hackerbyhobby
safebrowsing debugging
d5030c9 unverified
raw
history blame
2.6 kB
import requests
import json
import os
SAFE_BROWSING_API_KEY = os.getenv("GOOGLE_SAFE_BROWSING_API_KEY")
SAFE_BROWSING_URL = "https://safebrowsing.googleapis.com/v4/threatMatches:find"
def check_urls_with_google_safebrowsing(urls):
"""
Debug-enabled version:
- Prints payload and raw response to help troubleshoot Safe Browsing issues.
Returns a dict {url: bool is_malicious}.
"""
result = {}
if not SAFE_BROWSING_API_KEY:
print("No GOOGLE_SAFE_BROWSING_API_KEY found. Returning all URLs as safe.")
for u in urls:
result[u] = False
return result
# Build threatEntries for each URL
threat_entries = [{"url": u} for u in urls]
payload = {
"client": {
"clientId": "my-smishing-detector",
"clientVersion": "1.0"
},
"threatInfo": {
"threatTypes": [
"MALWARE",
"SOCIAL_ENGINEERING",
"UNWANTED_SOFTWARE",
"POTENTIALLY_HARMFUL_APPLICATION"
],
"platformTypes": ["ANY_PLATFORM"],
"threatEntryTypes": ["URL"],
"threatEntries": threat_entries
}
}
print("---- Safe Browsing Debug ----")
print("REQUEST Payload (JSON):")
print(json.dumps(payload, indent=2))
print("REQUEST Endpoint:", SAFE_BROWSING_URL, "Key:", SAFE_BROWSING_API_KEY)
print("URLs being checked:", urls)
try:
resp = requests.post(
SAFE_BROWSING_URL,
params={"key": SAFE_BROWSING_API_KEY},
json=payload,
timeout=10
)
print("RESPONSE Status Code:", resp.status_code)
try:
data = resp.json()
print("RESPONSE JSON:")
print(json.dumps(data, indent=2))
except Exception as parse_error:
print("Error parsing response as JSON:", parse_error)
data = {}
# If "matches" is present, some URL is flagged
malicious_urls = set()
if "matches" in data:
for match in data["matches"]:
threat_url = match.get("threat", {}).get("url")
if threat_url:
malicious_urls.add(threat_url)
for u in urls:
result[u] = (u in malicious_urls)
except Exception as e:
print(f"Error contacting Safe Browsing API: {e}")
# default: everything safe if error
for u in urls:
result[u] = False
print("RESULTS (url -> malicious):", result)
print("---- End Debug ----\n")
return result