Spaces:
Running
Running
Download app/intel.py from Reaper1909/wade-ips: direct link, hf CLI and curl.
- Browser
- Download file 10.7 kB
-
https://huggingface.co/spaces/Reaper1909/wade-ips/resolve/main/app/intel.py
- Command line
-
hf download hf://spaces/Reaper1909/wade-ips/app/intel.py
-
curl -L -o intel.py https://huggingface.co/spaces/Reaper1909/wade-ips/resolve/main/app/intel.py
10.7 kB
| """Threat-intelligence sources: OSINT feeds, domain age (WHOIS / TLS), VirusTotal, Tranco. | |
| Third-party libraries (httpx, python-whois) are imported lazily so this module, and the scoring | |
| engine built on it, can be unit-tested without them. | |
| """ | |
| from __future__ import annotations | |
| import asyncio | |
| import base64 | |
| import io | |
| import logging | |
| import socket | |
| import ssl | |
| import time | |
| import zipfile | |
| from datetime import datetime, timezone | |
| from . import netguard | |
| from .privacy import CleanURL, sanitize_url | |
| log = logging.getLogger("wade.intel") | |
| FEED_SOURCES = ( | |
| "https://urlhaus.abuse.ch/downloads/text_online/", | |
| "https://raw.githubusercontent.com/mitchellkrogza/Phishing.Database/master/phishing-links-ACTIVE.txt", | |
| ) | |
| MAX_FEED_ENTRIES = 1_000_000 | |
| # Seed allow-list carried over from the original prototype (domain -> approximate age in days). | |
| TRUSTED_AGES = { | |
| "google.com": 9500, "youtube.com": 6900, "wikipedia.org": 8700, "github.com": 5800, | |
| "microsoft.com": 11000, "huggingface.co": 1500, "stackoverflow.com": 7000, "amazon.com": 10500, | |
| "apple.com": 13000, "netflix.com": 9000, "linkedin.com": 7500, "whatsapp.com": 5000, | |
| "openai.com": 3000, "facebook.com": 7600, "instagram.com": 4500, "twitter.com": 6500, | |
| "x.com": 10000, "twitch.tv": 4000, "gmail.com": 9500, "outlook.com": 8000, "yahoo.com": 10000, | |
| "paruluniversity.ac.in": 5000, | |
| } | |
| TRANCO_FALLBACK = ["google.com", "youtube.com", "github.com", "paruluniversity.ac.in"] | |
| # --------------------------------------------------------------------------- feeds | |
| class ThreatFeeds: | |
| """In-memory index of known-bad URLs/hosts, normalised the same way as incoming requests.""" | |
| def __init__(self) -> None: | |
| self.urls: set[str] = set() | |
| self.hosts: set[str] = set() | |
| self.loaded_at: float | None = None | |
| def __len__(self) -> int: | |
| return len(self.urls) + len(self.hosts) | |
| def add_line(self, line: str) -> bool: | |
| line = line.strip() | |
| if not line or line.startswith("#"): | |
| return False | |
| try: | |
| clean = sanitize_url(line if "://" in line else "http://" + line) | |
| except ValueError: | |
| return False | |
| if clean.path == "/": | |
| self.hosts.add(clean.host) | |
| else: | |
| self.urls.add(clean.key) | |
| return True | |
| def contains(self, clean: CleanURL) -> bool: | |
| return clean.key in self.urls or clean.host in self.hosts | |
| async def refresh(self, client) -> int: | |
| new = ThreatFeeds() | |
| for src in FEED_SOURCES: | |
| try: | |
| r = await client.get(src, timeout=20) | |
| if r.status_code != 200: | |
| log.warning("feed returned %s", r.status_code, extra={"event": "feed_error"}) | |
| continue | |
| for line in r.text.splitlines(): | |
| if len(new) >= MAX_FEED_ENTRIES: | |
| break | |
| new.add_line(line) | |
| except Exception as exc: # network errors must not take the API down | |
| log.warning("feed fetch failed: %s", type(exc).__name__, extra={"event": "feed_error"}) | |
| if len(new): # keep the previous index if every feed failed | |
| self.urls, self.hosts, self.loaded_at = new.urls, new.hosts, time.time() | |
| return len(self) | |
| # --------------------------------------------------------------------------- domain age | |
| def _age_days(created: datetime) -> int: | |
| if created.tzinfo is None: | |
| created = created.replace(tzinfo=timezone.utc) | |
| return max(0, (datetime.now(timezone.utc) - created).days) | |
| def _whois_age(host: str) -> int | None: | |
| try: | |
| import whois # python-whois | |
| except ImportError: | |
| return None | |
| try: | |
| created = whois.whois(host).creation_date | |
| except Exception: | |
| return None | |
| if isinstance(created, list): | |
| created = created[0] if created else None | |
| if isinstance(created, datetime): | |
| return _age_days(created) | |
| return None | |
| def _tls_age(host: str) -> int | None: | |
| """Age of the certificate; only connects to vetted public IPs.""" | |
| try: | |
| addrs = netguard.resolve_public(host, 443) | |
| ctx = ssl.create_default_context() | |
| with socket.create_connection((addrs[0], 443), timeout=2.5) as sock: | |
| with ctx.wrap_socket(sock, server_hostname=host) as tls: | |
| not_before = tls.getpeercert()["notBefore"] | |
| return _age_days(datetime.fromtimestamp(ssl.cert_time_to_seconds(not_before), tz=timezone.utc)) | |
| except Exception: | |
| return None | |
| def domain_age_days(host: str) -> int: | |
| """Blocking. WHOIS creation date, falling back to TLS certificate issue date; -1 if unknown. | |
| Never probes IP literals or internal names (see netguard). | |
| """ | |
| try: | |
| netguard.check_hostname(host) | |
| import ipaddress | |
| try: | |
| ipaddress.ip_address(host) | |
| return -1 | |
| except ValueError: | |
| pass | |
| except netguard.UnsafeTarget: | |
| return -1 | |
| age = _whois_age(host) | |
| if age is None: | |
| age = _tls_age(host) | |
| return -1 if age is None else age | |
| # --------------------------------------------------------------------------- VirusTotal | |
| NO_VT = {"malicious": 0, "total": "N/A"} | |
| async def virustotal(client, api_key: str | None, clean: CleanURL) -> dict: | |
| if not api_key: | |
| return dict(NO_VT) | |
| url_id = base64.urlsafe_b64encode(clean.url.encode()).decode().strip("=") | |
| try: | |
| r = await client.get(f"https://www.virustotal.com/api/v3/urls/{url_id}", | |
| headers={"x-apikey": api_key}, timeout=6.0) | |
| if r.status_code == 200: | |
| stats = r.json()["data"]["attributes"]["last_analysis_stats"] | |
| return {"malicious": int(stats.get("malicious", 0)), "total": int(sum(stats.values()))} | |
| except Exception as exc: | |
| log.warning("virustotal lookup failed: %s", type(exc).__name__, extra={"event": "vt_error"}) | |
| return dict(NO_VT) | |
| # --------------------------------------------------------------------------- Google Safe Browsing | |
| async def safe_browsing(client, api_key: str | None, clean: CleanURL) -> dict: | |
| """Returns {"threat": "None" | MALWARE | SOCIAL_ENGINEERING | UNWANTED_SOFTWARE, "source": ...}. | |
| Only the sanitised URL (no query string / credentials) is sent to Google. | |
| """ | |
| if not api_key: | |
| return {"threat": "None", "source": "No Key"} | |
| payload = { | |
| "client": {"clientId": "wade-ips", "clientVersion": "7.1"}, | |
| "threatInfo": { | |
| "threatTypes": ["MALWARE", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE"], | |
| "platformTypes": ["ANY_PLATFORM"], | |
| "threatEntryTypes": ["URL"], | |
| "threatEntries": [{"url": clean.url}], | |
| }, | |
| } | |
| try: | |
| # key goes in a header, not the URL, so it can never leak into access logs | |
| r = await client.post("https://safebrowsing.googleapis.com/v4/threatMatches:find", | |
| headers={"x-goog-api-key": api_key}, json=payload, timeout=6.0) | |
| if r.status_code == 200: | |
| matches = r.json().get("matches") or [] | |
| if matches: | |
| return {"threat": str(matches[0].get("threatType", "UNKNOWN")), "source": "Google Safe Browsing"} | |
| except Exception as exc: | |
| log.warning("safe browsing lookup failed: %s", type(exc).__name__, extra={"event": "sb_error"}) | |
| return {"threat": "None", "source": "Google Safe Browsing"} | |
| # --------------------------------------------------------------------------- AbuseIPDB | |
| async def abuseipdb(client, api_key: str | None, host: str) -> dict: | |
| """Only queried when the host is a public IPv4 literal; domains return abuse_confidence 0.""" | |
| if not api_key: | |
| return {"abuse_confidence": 0, "source": "No Key"} | |
| import ipaddress | |
| try: | |
| ip = ipaddress.ip_address(host) | |
| except ValueError: | |
| return {"abuse_confidence": 0, "source": "Not an IP"} | |
| if ip.version != 4 or not netguard.is_public_ip(host): | |
| return {"abuse_confidence": 0, "source": "Not a public IPv4"} | |
| try: | |
| r = await client.get("https://api.abuseipdb.com/api/v2/check", headers={"Key": api_key}, | |
| params={"ipAddress": host, "maxAgeInDays": 30}, timeout=6.0) | |
| if r.status_code == 200: | |
| return {"abuse_confidence": int(r.json()["data"]["abuseConfidenceScore"]), "source": "AbuseIPDB"} | |
| except Exception as exc: | |
| log.warning("abuseipdb lookup failed: %s", type(exc).__name__, extra={"event": "abuse_error"}) | |
| return {"abuse_confidence": 0, "source": "AbuseIPDB"} | |
| # --------------------------------------------------------------------------- Tranco | |
| class TrancoList: | |
| def __init__(self, ttl: int = 86400, size: int = 10_000): | |
| self.ttl, self.size = ttl, size | |
| self.domains: list[str] = [] | |
| self.fetched_at = 0.0 | |
| self._set: frozenset[str] = frozenset() | |
| def contains(self, host: str) -> bool: | |
| """True if host or any parent domain is in the list ('a.b.google.com' -> 'google.com'). | |
| Label-boundary match: 'evilgoogle.com' does NOT match 'google.com'. | |
| """ | |
| labels = host.lower().rstrip(".").split(".") | |
| return any(".".join(labels[i:]) in self._set for i in range(len(labels) - 1)) | |
| def parse_zip(payload: bytes, size: int) -> list[str]: | |
| with zipfile.ZipFile(io.BytesIO(payload)) as z: | |
| with z.open(z.namelist()[0]) as f: | |
| out = [] | |
| for i, line in enumerate(f): | |
| if i >= size: | |
| break | |
| parts = line.decode("utf-8", "ignore").strip().split(",") | |
| if len(parts) == 2 and parts[1]: | |
| out.append(parts[1].lower()) | |
| return out | |
| async def get(self, client) -> list[str]: | |
| if self.domains and time.time() - self.fetched_at < self.ttl: | |
| return self.domains | |
| try: | |
| r = await client.get("https://tranco-list.eu/top-1m.csv.zip", timeout=30, follow_redirects=True) | |
| r.raise_for_status() | |
| domains = await asyncio.to_thread(self.parse_zip, r.content, self.size) | |
| if domains: | |
| self.domains = sorted(set(domains + ["paruluniversity.ac.in"])) | |
| self._set = frozenset(self.domains) | |
| self.fetched_at = time.time() | |
| except Exception as exc: | |
| log.warning("tranco refresh failed: %s", type(exc).__name__, extra={"event": "tranco_error"}) | |
| if not self.domains: | |
| self.domains = list(TRANCO_FALLBACK) | |
| self._set = frozenset(self.domains) | |
| return self.domains | |