AI powered OSINT engine to discover and map 840+ social media identities across the web
Python aiartificial-intelligencedebainhackhackerhackinghackingtoolsinformationinformation-gatheringlinuxlinux-desktoposintpythonpython-scriptpython3social-mediasocialmediahackingtermuxtermux-tool
feat: profile URL matching and guarded page fetch; close redirect bypass (2.6.0)
arxhr0073e2410e3cf06
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 633cfee..86b8749 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,30 @@# Changelog+## 2.6.0 (2026-10-07)++### Security+- **The address check on scraped URLs could be bypassed with a redirect.** Since 2.4.0,+ avatar URLs taken from scanned pages were only fetched if they pointed at a public+ address. The check covered the URL itself, and the HTTP client then followed redirects+ unchecked, so a public URL answering `302 Location: http://127.0.0.1/...` was still+ followed. This affected `--correlate` and `--format pdf`. Redirects are now followed one+ hop at a time with every hop validated, and `--correlate` pins the connection to the+ address that was checked, which also closes a DNS-rebinding race.++### Added+- `aliens_eye.api.match_profile_url(url)`: which site and username a profile link belongs+ to, for any site in the catalogue. `https://www.instagram.com/_someone_/` gives+ `("instagram", "_someone_")`; a repository, a navigation page or an unknown host gives+ nothing.+- `aliens_eye.api.fetch_page(url)`: fetch one page whose address came from somewhere you do+ not control, with the checks above.+- `aliens_eye.api.profile_url(site, username)`.++### Changed+- `--recurse-depth` now understands profile links for every site in the catalogue. It used+ to recognise 19 hard-coded domains and take the first path segment, which missed+ `linkedin.com/in/<user>` and `<user>.tumblr.com` and misread `github.com/<user>/<repo>`.+## 2.5.1 (2026-10-07)### Fixeddiff --git a/README.md b/README.mdindex ef57f7c..40e5c7d 100644--- a/README.md+++ b/README.md@@ -229,6 +229,16 @@ async def main():asyncio.run(main())```+It can also read a profile link back into a site and username, and fetch a page+whose address came from somewhere you don't control:++```python+api.match_profile_url("https://www.instagram.com/_someone_/")+# [ProfileMatch(site='instagram', username='_someone_')]++page = await api.fetch_page("https://example.com/") # public http(s) addresses only+```+Everything outside `aliens_eye.api` is internal and may change between minor releases.## Configurationdiff --git a/pyproject.toml b/pyproject.tomlindex cb226eb..ec42374 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "aliens-eye"-version = "2.5.1"+version = "2.6.0"description = "AI-powered OSINT username scanner across 800+ social media and web platforms"readme = "README.md"requires-python = ">=3.10"diff --git a/src/aliens_eye/__init__.py b/src/aliens_eye/__init__.pyindex 26bc7e4..68abe08 100644--- a/src/aliens_eye/__init__.py+++ b/src/aliens_eye/__init__.py@@ -1,3 +1,3 @@"""Aliens Eye - AI-powered OSINT username scanner."""-__version__ = "2.5.1"+__version__ = "2.6.0"diff --git a/src/aliens_eye/api.py b/src/aliens_eye/api.pyindex 3d7626f..5e2a163 100644--- a/src/aliens_eye/api.py+++ b/src/aliens_eye/api.py@@ -18,7 +18,19 @@ from collections.abc import Awaitable, Callablefrom pathlib import Pathfrom typing import Any-__all__ = ["LEVELS", "ResultHook", "correlate", "load_sites", "scan"]+__all__ = [+ "LEVELS",+ "ProfileMatch",+ "ResultHook",+ "correlate",+ "fetch_page",+ "load_sites",+ "match_profile_url",+ "profile_url",+ "scan",+]++from aliens_eye.core.urlmatch import ProfileMatchLEVELS = ("basic", "intermediate", "advanced")@@ -148,3 +160,74 @@ async def correlate(allow_private_avatars=allow_private_avatars,include_profiles=True,)+++def match_profile_url(url: str, sites: dict[str, str] | None = None) -> list[ProfileMatch]:+ """Which catalogue profiles a URL could be, most specific first.++ ``match_profile_url("https://www.instagram.com/_arx_/")`` gives+ ``[ProfileMatch(site="instagram", username="_arx_")]``. A URL that is not a+ profile on a known site -- a repository, a navigation page, an unknown host+ -- gives ``[]``.+ """+ from aliens_eye.core.urlmatch import matcher_for++ return matcher_for(sites if sites is not None else load_sites()).match(url)+++def profile_url(site: str, username: str, sites: dict[str, str] | None = None) -> str:+ """The profile URL for ``username`` on ``site``. Raises KeyError for an unknown site."""+ from aliens_eye.core.scanner import format_site_url++ catalogue = sites if sites is not None else load_sites()+ return format_site_url(site, catalogue[site], username)+++async def fetch_page(+ url: str,+ *,+ proxy: str | None = None,+ timeout: float = 20.0,+ max_bytes: int = 1_000_000,+ allow_private: bool = False,+) -> dict[str, Any]:+ """Fetch one page whose address came from somewhere you do not control.++ For reading a profile or personal site to see what it links to. Only http(s)+ is fetched, and only from public addresses: the URL and every redirect hop+ are validated, and the connection itself is pinned to a public address, so a+ link cannot steer the request at an internal service. ``allow_private`` lifts+ that for a network you own. Through a ``proxy`` the proxy does the resolving,+ and the pinning does not apply.++ Never raises for a bad or unreachable URL: returns ``{"url", "final_url",+ "status", "html", "error"}`` with ``error`` set and ``html`` empty. A refusal+ says why: "host does not resolve", "host resolves to a non-public address" or+ "not an http(s) address".+ """+ from aliens_eye.core import netguard+ from aliens_eye.core.config import ScannerConfig+ from aliens_eye.core.scanner import build_session++ result: dict[str, Any] = {"url": url, "final_url": url, "status": 0, "html": "", "error": None}+ http_proxy = proxy if proxy and proxy.lower().startswith(("http://", "https://")) else None+ resolver = None if (allow_private or proxy) else netguard.PublicOnlyResolver()+ try:+ async with build_session(ScannerConfig(proxy=proxy), 2, resolver=resolver) as session:+ response = await netguard.guarded_get(+ session, url, timeout=timeout, max_bytes=max_bytes,+ allow_private=allow_private, proxy=http_proxy,+ )+ except netguard.GuardError as exc:+ result["error"] = str(exc)+ return result+ except Exception as exc: # noqa: BLE001 - reported to the caller, never raised+ result["error"] = f"{type(exc).__name__}: {exc}"[:200]+ return result+ result["final_url"] = response.final_url+ result["status"] = response.status+ try:+ result["html"] = response.body.decode(response.charset or "utf-8", errors="ignore")+ except LookupError: # a charset name Python does not know+ result["html"] = response.body.decode("utf-8", errors="ignore")+ return resultdiff --git a/src/aliens_eye/core/correlate.py b/src/aliens_eye/core/correlate.pyindex 6749dc0..fe5e830 100644--- a/src/aliens_eye/core/correlate.py+++ b/src/aliens_eye/core/correlate.py@@ -12,17 +12,14 @@ correlation still runs on name/bio/link signals alone.from __future__ import annotationsimport asyncio-import ipaddressimport re-import socketfrom dataclasses import dataclass, fieldfrom typing import Any-from urllib.parse import urlparseimport aiohttp+from . import netguardfrom .config import DEFAULT_HEADERS, ScannerConfig-from .http import read_cappedfrom .scanner import build_connector_URL_RE = re.compile(r"https?://[^\s\"'<>)]+", re.IGNORECASE)@@ -157,75 +154,21 @@ def pillow_available() -> bool:return False-ALLOWED_AVATAR_SCHEMES = {"http", "https"}--async def is_fetchable_avatar(url: str, allow_private: bool = False) -> bool:"""Whether an avatar URL is safe for this process to fetch.Avatar URLs are scraped from the target page (og:image, JSON-LD, a faviconlink, or a per-site CSS selector), so they are chosen by whoever controls- that page. Fetching them unchecked turns a scan into a request generator- aimed wherever the target likes -- cloud metadata endpoints, an intranet- host, a service bound to loopback on the analyst's own machine.-- Investigators run this against hostile targets by definition, so the address- is resolved and rejected unless every answer is a public one. ``allow_private``- exists for scanning a lab network on purpose.+ that page. See ``core.netguard`` for what is checked and why; note that this+ answers for the URL itself, and a fetch must still validate every redirect+ hop, which :func:`_download_and_hash` does through ``guarded_get``."""- host = _fetchable_host(url)- if host is None:- return False- if allow_private:- return True- try:- infos = await asyncio.get_event_loop().getaddrinfo(host, None)- except (OSError, UnicodeError):- return False- return _all_public(infos)+ return await netguard.is_public_url(url, allow_private)def avatar_url_allowed(url: str, allow_private: bool = False) -> bool:- """Blocking twin of :func:`is_fetchable_avatar`, for synchronous callers.-- The PDF exporter downloads the same scraped avatar URLs with urllib, which- also speaks ``file://`` -- so without this check a hostile og:image could- point a report at a local file as easily as at an intranet host.- """- host = _fetchable_host(url)- if host is None:- return False- if allow_private:- return True- try:- infos = socket.getaddrinfo(host, None)- except (OSError, UnicodeError):- return False- return _all_public(infos)---def _fetchable_host(url: str) -> str | None:- try:- parsed = urlparse(url)- except ValueError:- return None- if parsed.scheme.lower() not in ALLOWED_AVATAR_SCHEMES:- return None- return parsed.hostname or None---def _all_public(infos) -> bool:- """True only if every resolved address is a public one."""- if not infos:- return False- for info in infos:- try:- address = ipaddress.ip_address(info[4][0])- except ValueError:- return False- if not address.is_global or address.is_private or address.is_loopback:- return False- return True+ """Blocking twin of :func:`is_fetchable_avatar`, for synchronous callers."""+ return netguard.is_public_url_sync(url, allow_private)async def _download_and_hash(@@ -236,18 +179,18 @@ async def _download_and_hash() -> None:if not profile.avatar:return- if not await is_fetchable_avatar(profile.avatar, allow_private):- returntry:- async with session.get(profile.avatar, timeout=aiohttp.ClientTimeout(total=timeout)) as resp:- if resp.status != 200:- return- # read_capped, not content.read(n): a single read returns whatever has- # arrived, so the image was hashed from a random-length prefix.- data = await read_capped(resp, 2_000_000) # cap at 2 MB- except Exception:+ # guarded_get validates the URL and every redirect hop: a public avatar+ # URL that answers 302 to an internal address must not be followed.+ response = await netguard.guarded_get(+ session, profile.avatar, timeout=timeout, max_bytes=2_000_000,+ allow_private=allow_private,+ )+ except Exception: # noqa: BLE001 - avatar hashing is best-effort+ return+ if response.status != 200:return- profile.avatar_hash = _dhash(data)+ profile.avatar_hash = _dhash(response.body)async def hash_avatars(@@ -264,7 +207,9 @@ async def hash_avatars(returnlimit = min(20, len(targets))- connector = build_connector(ScannerConfig(proxy=proxy), limit)+ # The resolver pins the check to the address actually connected to.+ resolver = None if allow_private else netguard.PublicOnlyResolver()+ connector = build_connector(ScannerConfig(proxy=proxy), limit, resolver)sem = asyncio.Semaphore(limit)async with aiohttp.ClientSession(headers=DEFAULT_HEADERS, connector=connector) as session:diff --git a/src/aliens_eye/core/expand.py b/src/aliens_eye/core/expand.pyindex 9ec7034..76f9b4e 100644--- a/src/aliens_eye/core/expand.py+++ b/src/aliens_eye/core/expand.py@@ -1,54 +1,39 @@"""Recursive expansion: mine linked usernames out of found profiles.Given scan results, pull candidate usernames from each Found/Maybe profile's bio-(``@handle`` mentions) and external links that follow a known ``domain/<user>``-shape (github.com/<user>, twitter.com/<user>, ...). These feed another scan hop.+(``@handle`` mentions) and external links that are profile URLs on any site in+the catalogue. These feed another scan hop."""from __future__ import annotationsimport re+from functools import lru_cachefrom typing import Any-from urllib.parse import urlparse_HANDLE_RE = re.compile(r"@([A-Za-z0-9_.]{2,30})")_URL_RE = re.compile(r"https?://[^\s\"'<>)]+", re.IGNORECASE)-# Domains where the first path segment is the username.-_USER_PATH_DOMAINS = {- "github.com", "gitlab.com", "twitter.com", "x.com", "instagram.com",- "t.me", "telegram.me", "medium.com", "dev.to", "reddit.com",- "tiktok.com", "youtube.com", "twitch.tv", "keybase.io", "about.me",- "codepen.io", "replit.com", "soundcloud.com", "pinterest.com",-}+@lru_cache(maxsize=1)+def _catalogue() -> tuple[tuple[str, str], ...]:+ from .scanner import load_sites_data-# Path segments that are never usernames.-_PATH_STOPWORDS = {- "in", "u", "user", "users", "profile", "channel", "c", "watch", "p",- "about", "home", "login", "signup", "help", "settings", "explore",-}+ return tuple(sorted(load_sites_data().items()))def _username_from_url(url: str) -> str | None:- try:- parsed = urlparse(url)- except ValueError:- return None- host = parsed.netloc.lower()- if host.startswith("www."):- host = host[4:]- if host not in _USER_PATH_DOMAINS:- return None- segments = [s for s in parsed.path.split("/") if s]- if not segments:- return None- candidate = segments[0].lstrip("@")- if candidate.lower() in _PATH_STOPWORDS:- candidate = segments[1] if len(segments) > 1 else ""- candidate = candidate.strip()- if len(candidate) < 2 or "." in candidate and not candidate.replace(".", "").isalnum():- return None- return candidate if candidate else None+ """The username a profile link points at, for any site in the catalogue.++ This used to recognise 19 hard-coded domains by taking the first path+ segment. It now reverse-matches the link against every catalogue template+ (see ``core.urlmatch``), so ``linkedin.com/in/<user>`` or+ ``<user>.tumblr.com`` are understood and ``github.com/<user>/<repo>`` is+ correctly not taken for a profile.+ """+ from .urlmatch import matcher_for++ matches = matcher_for(dict(_catalogue())).match(url)+ return matches[0].username if matches else Nonedef candidate_usernames_from_results(diff --git a/src/aliens_eye/core/netguard.py b/src/aliens_eye/core/netguard.pynew file mode 100644index 0000000..b0dd50f--- /dev/null+++ b/src/aliens_eye/core/netguard.py@@ -0,0 +1,234 @@+"""Fetching URLs that someone else chose, without being steered somewhere private.++Avatar URLs, and the links a profile page points at, come from the scanned page,+so whoever controls that page chooses them. Fetched unchecked they turn a scan+into a request generator aimed wherever the target likes: a cloud metadata+endpoint, an intranet host, a service on the analyst's own loopback.++Three things are needed, and checking the first host alone gives none of them:++* **Scheme**: http and https only. urllib also opens ``file://``.+* **Every redirect hop**: a public URL can answer ``302 Location: http://127.0.0.1/``.+ The 2.4 and 2.5 guards validated only the URL they were handed and then let the+ HTTP client follow redirects on its own. Redirects are followed manually here,+ and each hop is validated before it is requested.+* **The address actually connected to**: resolving a name to check it, then+ letting the client resolve it again to connect, leaves a gap a hostile DNS+ server can use (answer public first, private second). :class:`PublicOnlyResolver`+ does the filtering inside the connector, so the checked address is the one used.++None of this applies through a proxy: the proxy resolves and connects, not us.+"""++from __future__ import annotations++import asyncio+import ipaddress+import socket+import urllib.error+import urllib.request+from dataclasses import dataclass+from urllib.parse import urljoin, urlparse++import aiohttp+from aiohttp.abc import AbstractResolver+from aiohttp.resolver import DefaultResolver++ALLOWED_SCHEMES = {"http", "https"}+MAX_REDIRECTS = 5+_REDIRECT_STATUSES = {301, 302, 303, 307, 308}+++class GuardError(Exception):+ """A URL, or a hop it redirected to, is not one this process may fetch."""+++def fetchable_host(url: str) -> str | None:+ """The host of an http(s) URL, or None if the URL may not be fetched at all."""+ try:+ parsed = urlparse(url)+ except ValueError:+ return None+ if parsed.scheme.lower() not in ALLOWED_SCHEMES:+ return None+ return parsed.hostname or None+++def is_public_ip(address: str) -> bool:+ try:+ ip = ipaddress.ip_address(address)+ except ValueError:+ return False+ return ip.is_global and not ip.is_private and not ip.is_loopback+++def all_public(infos) -> bool:+ """True only if getaddrinfo returned something and every answer is public."""+ return bool(infos) and all(is_public_ip(info[4][0]) for info in infos)+++async def host_is_public(host: str) -> bool:+ try:+ infos = await asyncio.get_running_loop().getaddrinfo(host, None)+ except (OSError, UnicodeError):+ return False+ return all_public(infos)+++def host_is_public_sync(host: str) -> bool:+ try:+ infos = socket.getaddrinfo(host, None)+ except (OSError, UnicodeError):+ return False+ return all_public(infos)+++async def is_public_url(url: str, allow_private: bool = False) -> bool:+ host = fetchable_host(url)+ if host is None:+ return False+ return True if allow_private else await host_is_public(host)+++def is_public_url_sync(url: str, allow_private: bool = False) -> bool:+ host = fetchable_host(url)+ if host is None:+ return False+ return True if allow_private else host_is_public_sync(host)+++async def refusal_reason(url: str) -> str:+ """Why :func:`is_public_url` said no, for an error a person can act on.++ "Does not resolve" and "resolves somewhere private" call for different+ responses: the first is usually a dead domain or a blocked lookup, the+ second is the guard doing its job.+ """+ host = fetchable_host(url)+ if host is None:+ return "not an http(s) address"+ try:+ infos = await asyncio.get_running_loop().getaddrinfo(host, None)+ except (OSError, UnicodeError):+ return "host does not resolve"+ return "host resolves to a non-public address" if not all_public(infos) else "refused"+++class PublicOnlyResolver(AbstractResolver):+ """A resolver that refuses names with any non-public address.++ Installed on the connector, so the addresses it approves are the ones the+ connection is made to; there is no second lookup to race.+ """++ def __init__(self, inner: AbstractResolver | None = None) -> None:+ self._inner = inner or DefaultResolver()++ async def resolve(self, host: str, port: int = 0, family: int = socket.AF_INET):+ results = await self._inner.resolve(host, port, family)+ if not results or not all(is_public_ip(r["host"]) for r in results):+ raise OSError(f"{host} does not resolve to a public address")+ return results++ async def close(self) -> None:+ await self._inner.close()+++@dataclass+class GuardedResponse:+ url: str+ final_url: str+ status: int+ headers: dict[str, str]+ body: bytes+ charset: str | None+ redirects: int+++async def guarded_get(+ session: aiohttp.ClientSession,+ url: str,+ *,+ timeout: float = 15.0,+ max_bytes: int = 2_000_000,+ allow_private: bool = False,+ proxy: str | None = None,+) -> GuardedResponse:+ """GET ``url``, validating it and every redirect hop. Raises :class:`GuardError`."""+ from .http import read_capped++ current = url+ for hop in range(MAX_REDIRECTS + 1):+ if not await is_public_url(current, allow_private):+ raise GuardError(f"{await refusal_reason(current)}: {current}")+ async with session.get(+ current,+ timeout=aiohttp.ClientTimeout(total=timeout),+ allow_redirects=False,+ proxy=proxy,+ ) as response:+ if response.status in _REDIRECT_STATUSES:+ location = response.headers.get("Location")+ if not location:+ raise GuardError(f"redirect without a Location from {current!r}")+ current = urljoin(current, location)+ continue+ body = await read_capped(response, max_bytes)+ return GuardedResponse(+ url=url,+ final_url=current,+ status=response.status,+ headers=dict(response.headers),+ body=body,+ charset=response.charset,+ redirects=hop,+ )+ raise GuardError(f"too many redirects from {url!r}")+++class _GuardedRedirects(urllib.request.HTTPRedirectHandler):+ max_redirections = MAX_REDIRECTS++ def __init__(self, allow_private: bool) -> None:+ self._allow_private = allow_private++ def redirect_request(self, req, fp, code, msg, headers, newurl):+ if not is_public_url_sync(newurl, self._allow_private):+ raise urllib.error.URLError(f"refusing redirect to {newurl!r}")+ return super().redirect_request(req, fp, code, msg, headers, newurl)+++def guarded_urlopen_bytes(+ url: str,+ *,+ timeout: float = 6.0,+ max_bytes: int = 2_000_000,+ allow_private: bool = False,+ user_agent: str = "Mozilla/5.0 aliens-eye",+) -> bytes | None:+ """Blocking fetch for synchronous callers; None on any refusal or failure.++ The opener is built with http and https handlers only, so no redirect can+ reach ``file://`` or ``ftp://`` even in principle. It validates each hop but,+ unlike :func:`guarded_get` behind a :class:`PublicOnlyResolver`, it resolves+ names twice, so a DNS-rebinding race is not closed on this path.+ """+ if not is_public_url_sync(url, allow_private):+ return None+ opener = urllib.request.OpenerDirector()+ for handler in (+ urllib.request.HTTPHandler(),+ urllib.request.HTTPSHandler(),+ _GuardedRedirects(allow_private),+ urllib.request.HTTPDefaultErrorHandler(),+ urllib.request.HTTPErrorProcessor(),+ ):+ opener.add_handler(handler)+ try:+ request = urllib.request.Request(url, headers={"User-Agent": user_agent})+ with opener.open(request, timeout=timeout) as response:+ if response.status != 200:+ return None+ return response.read(max_bytes)+ except Exception: # noqa: BLE001 - a best-effort image fetch never fails a report+ return Nonediff --git a/src/aliens_eye/core/pdf_report.py b/src/aliens_eye/core/pdf_report.pyindex 9676d6d..45d2502 100644--- a/src/aliens_eye/core/pdf_report.py+++ b/src/aliens_eye/core/pdf_report.py@@ -8,7 +8,6 @@ is not installed; the exporter catches that and prints an install hint.from __future__ import annotationsimport io-import urllib.requestfrom pathlib import Pathfrom typing import Any@@ -30,20 +29,13 @@ _MAX_AVATARS = 40def _fetch_avatar(url: str, timeout: float = 6.0) -> io.BytesIO | None:# Avatar URLs are scraped from the target's page, so the target chooses- # them. urllib also accepts file://, so the guard matters doubly here.- from aliens_eye.core.correlate import avatar_url_allowed+ # them. The guarded opener speaks http(s) only and validates every redirect.+ from aliens_eye.core.netguard import guarded_urlopen_bytes- if not url or not avatar_url_allowed(url):- return None- try:- req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 aliens-eye"})- with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310 - user-provided profile URL- if resp.status != 200:- return None- data = resp.read(2_000_000)- return io.BytesIO(data)- except Exception:+ if not url:return None+ data = guarded_urlopen_bytes(url, timeout=timeout)+ return io.BytesIO(data) if data is not None else Nonedef write_pdf(path: str | Path, results_data: dict[str, Any]) -> None:diff --git a/src/aliens_eye/core/scanner.py b/src/aliens_eye/core/scanner.pyindex 4acc501..a821913 100644--- a/src/aliens_eye/core/scanner.py+++ b/src/aliens_eye/core/scanner.py@@ -154,12 +154,21 @@ def _looks_like_bot_wall(signals: dict[str, Any]) -> bool:return any(keyword in haystack for keyword in _BOT_WALL_KEYWORDS)-def build_connector(config: ScannerConfig, limit: int) -> aiohttp.BaseConnector:- """TCP connector, or a SOCKS proxy connector when a socks:// proxy is set."""+def build_connector(+ config: ScannerConfig, limit: int, resolver=None+) -> aiohttp.BaseConnector:+ """TCP connector, or a SOCKS proxy connector when a socks:// proxy is set.++ ``resolver`` is for fetches of URLs taken from scanned pages; see+ ``core.netguard.PublicOnlyResolver``. It has no effect through a SOCKS+ proxy, where the proxy does the resolving.+ """if config.proxy and config.proxy.lower().startswith(("socks4://", "socks5://")):from aiohttp_socks import ProxyConnectorreturn ProxyConnector.from_url(config.proxy, limit=limit)+ if resolver is not None:+ return aiohttp.TCPConnector(limit=limit, resolver=resolver)return aiohttp.TCPConnector(limit=limit)@@ -167,6 +176,7 @@ def build_session(config: ScannerConfig,limit: int,headers: dict[str, str] | None = None,+ resolver=None,) -> aiohttp.ClientSession:"""Session for fetching site pages, with the header-size limit raised.@@ -177,7 +187,7 @@ def build_session("""return aiohttp.ClientSession(headers=DEFAULT_HEADERS if headers is None else headers,- connector=build_connector(config, limit),+ connector=build_connector(config, limit, resolver),max_line_size=MAX_HEADER_SIZE,max_field_size=MAX_HEADER_SIZE,)diff --git a/src/aliens_eye/core/urlmatch.py b/src/aliens_eye/core/urlmatch.pynew file mode 100644index 0000000..92039f1--- /dev/null+++ b/src/aliens_eye/core/urlmatch.py@@ -0,0 +1,207 @@+"""Reverse lookup: which site and username does a profile URL belong to?++The catalogue maps ``site -> url template``. Scanning fills a username into every+template; this goes the other way, so a link found on a page ("instagram.com/_arx_")+can be turned back into ``("instagram", "_arx_")``.++Templates come in three shapes, all handled:++* path ``https://github.com/{}``, ``https://lor.example/people/{}/profile``+* subdomain ``https://{}.tumblr.com``+* query ``https://forum.example/member.php?username={}``++A match must fit the whole template. ``github.com/arx/some-repo`` is not the+profile ``github.com/{}``, and ``github.com/features`` is site navigation, not a+user called "features": words that are page names, and the fixed first segment of+any sibling template on the same host (``sponsors`` in ``github.com/sponsors/{}``),+are never accepted as usernames.+"""++from __future__ import annotations++import re+from functools import lru_cache+from typing import NamedTuple+from urllib.parse import parse_qsl, unquote, urlparse++PLACEHOLDER = "{}"+_TOKEN = "\x00user\x00"++#: Hosts that serve the same profiles as a catalogue host.+HOST_ALIASES = {+ "x.com": "twitter.com",+ "mobile.twitter.com": "twitter.com",+ "mobile.x.com": "twitter.com",+ "telegram.me": "t.me",+ "m.facebook.com": "facebook.com",+ "fb.com": "facebook.com",+ "old.reddit.com": "reddit.com",+ "new.reddit.com": "reddit.com",+ "m.youtube.com": "youtube.com",+ "threads.com": "threads.net",+}++#: Path segments and subdomains that are pages or services, never usernames.+RESERVED = frozenset({+ "about", "account", "accounts", "admin", "api", "app", "apps", "blog", "careers",+ "categories", "collections", "contact", "docs", "download", "events", "explore",+ "features", "feed", "hashtag", "help", "home", "i", "in", "intent", "jobs", "join",+ "legal", "login", "logout", "m", "marketplace", "messages", "mobile", "new", "news",+ "notifications", "orgs", "p", "policies", "policy", "press", "pricing", "privacy",+ "profile", "register", "results", "search", "security", "settings", "share",+ "sharer", "shop", "signin", "sign-in", "signup", "sign-up", "status", "store",+ "support", "tag", "tags", "terms", "topics", "tos", "trending", "u", "c", "user",+ "users", "channel", "watch", "www", "static", "cdn", "assets", "images", "img",+})++_FILE_SUFFIXES = (+ ".html", ".htm", ".php", ".asp", ".aspx", ".png", ".jpg", ".jpeg", ".gif", ".svg",+ ".webp", ".ico", ".pdf", ".xml", ".json", ".js", ".css", ".txt", ".zip", ".rss",+)+++class ProfileMatch(NamedTuple):+ site: str+ username: str+++def _norm_host(host: str) -> str:+ host = (host or "").lower().rstrip(".")+ if host.startswith("www."):+ host = host[4:]+ return HOST_ALIASES.get(host, host)+++def _valid_username(raw: str, reserved: frozenset[str] | set[str]) -> str | None:+ username = unquote(raw or "").strip().lstrip("@")+ if not 2 <= len(username) <= 64 or any(ch.isspace() for ch in username):+ return None+ lowered = username.lower()+ if lowered in RESERVED or lowered in reserved or lowered.endswith(_FILE_SUFFIXES):+ return None+ return username+++class _Rule(NamedTuple):+ site: str+ weight: int # literal characters matched; higher is more specific+ path_re: re.Pattern | None # captures the username (path shape)+ host_re: re.Pattern | None # captures the username (subdomain shape)+ path: str | None # exact path (query shape; subdomain shape with a path)+ query_key: str | None # query parameter holding the username+ query_fixed: tuple[tuple[str, str], ...]+++class ProfileUrlMatcher:+ """Compiled reverse index over a site catalogue."""++ def __init__(self, sites: dict[str, str]) -> None:+ self._by_host: dict[str, list[_Rule]] = {}+ self._by_suffix: dict[str, list[_Rule]] = {}+ self._reserved: dict[str, set[str]] = {}+ for site, template in sorted(sites.items()):+ self._add(site, template)+ for rules in (*self._by_host.values(), *self._by_suffix.values()):+ rules.sort(key=lambda r: (-r.weight, r.site))++ def _add(self, site: str, template: str) -> None:+ if not isinstance(template, str) or template.count(PLACEHOLDER) != 1:+ return # two-placeholder templates (pinterest boards) name no single user+ try:+ parsed = urlparse(template.replace(PLACEHOLDER, _TOKEN))+ except ValueError:+ return+ host = (parsed.hostname or "").lower()+ if not host:+ return+ path = parsed.path.rstrip("/")++ if _TOKEN in host:+ prefix, _, suffix = host.partition(_TOKEN)+ suffix = _norm_host(suffix.lstrip("."))+ if prefix or not suffix or _TOKEN in path:+ return+ self._by_suffix.setdefault(suffix, []).append(_Rule(+ site, len(suffix) + len(path),+ None, re.compile(r"^(?P<u>[^.]+)\." + re.escape(suffix) + "$"),+ path or None, None, (),+ ))+ return++ host = _norm_host(host)+ if _TOKEN in path:+ literal = path.replace(_TOKEN, "")+ pattern = re.escape(path).replace(re.escape(_TOKEN), r"(?P<u>[^/?#]+)")+ self._by_host.setdefault(host, []).append(_Rule(+ site, len(literal), re.compile("^" + pattern + "$", re.IGNORECASE),+ None, None, None, (),+ ))+ first = path.strip("/").split("/", 1)[0]+ if first and _TOKEN not in first:+ self._reserved.setdefault(host, set()).add(first.lstrip("@").lower())+ return++ pairs = parse_qsl(parsed.query, keep_blank_values=True)+ keys = [k for k, v in pairs if v == _TOKEN]+ if len(keys) != 1:+ return+ fixed = tuple((k, v) for k, v in pairs if v != _TOKEN)+ self._by_host.setdefault(host, []).append(_Rule(+ site, len(path) + len(keys[0]), None, None, path.lower(), keys[0], fixed,+ ))++ def match(self, url: str) -> list[ProfileMatch]:+ """Every catalogue profile this URL could be, most specific first."""+ try:+ parsed = urlparse((url or "").strip())+ except ValueError:+ return []+ if parsed.scheme.lower() not in {"http", "https"} or not parsed.hostname:+ return []+ host = _norm_host(parsed.hostname)+ path = parsed.path.rstrip("/")+ reserved = self._reserved.get(host, set())+ found: list[tuple[int, ProfileMatch]] = []++ for rule in self._by_host.get(host, ()):+ raw = None+ if rule.path_re is not None:+ hit = rule.path_re.match(path)+ raw = hit.group("u") if hit else None+ elif rule.query_key is not None and path.lower() == rule.path:+ query = dict(parse_qsl(parsed.query, keep_blank_values=True))+ if all(query.get(k) == v for k, v in rule.query_fixed):+ raw = query.get(rule.query_key)+ username = _valid_username(raw, reserved) if raw else None+ if username:+ found.append((rule.weight, ProfileMatch(rule.site, username)))++ labels = host.split(".")+ for i in range(1, len(labels) - 1):+ suffix = ".".join(labels[i:])+ for rule in self._by_suffix.get(suffix, ()):+ hit = rule.host_re.match(host)+ if not hit or (rule.path is not None and path.lower() != rule.path.lower()):+ continue+ username = _valid_username(hit.group("u"), frozenset())+ if username:+ found.append((rule.weight, ProfileMatch(rule.site, username)))++ found.sort(key=lambda item: (-item[0], item[1].site))+ seen: set[ProfileMatch] = set()+ ordered = []+ for _, match in found:+ if match not in seen:+ seen.add(match)+ ordered.append(match)+ return ordered+++@lru_cache(maxsize=4)+def _cached(items: tuple[tuple[str, str], ...]) -> ProfileUrlMatcher:+ return ProfileUrlMatcher(dict(items))+++def matcher_for(sites: dict[str, str]) -> ProfileUrlMatcher:+ """A matcher for this catalogue, compiled once and reused."""+ return _cached(tuple(sorted(sites.items())))diff --git a/tests/test_netguard.py b/tests/test_netguard.pynew file mode 100644index 0000000..56f4617--- /dev/null+++ b/tests/test_netguard.py@@ -0,0 +1,173 @@+"""Fetching attacker-chosen URLs: every hop and the connected address are checked."""++import socket+import urllib.error+import urllib.request++import aiohttp+import pytest+from aiohttp import web+from aiohttp.test_utils import TestServer++from aliens_eye.core import netguard+++async def redirector():+ """One loopback server. Reached as ``localhost`` it plays the public site;+ reached as ``127.0.0.1`` it plays the internal service a redirect aims at."""+ hits = {"secret": 0}+ app = web.Application()++ async def to_internal(request):+ raise web.HTTPFound(f"http://127.0.0.1:{request.url.port}/secret")++ async def to_public(request):+ raise web.HTTPFound("/ok")++ async def loop(request):+ raise web.HTTPFound("/loop")++ async def secret(request):+ hits["secret"] += 1+ return web.Response(text="internal data")++ async def ok(request):+ return web.Response(text="fine")++ app.router.add_get("/to-internal", to_internal)+ app.router.add_get("/to-public", to_public)+ app.router.add_get("/loop", loop)+ app.router.add_get("/secret", secret)+ app.router.add_get("/ok", ok)+ server = TestServer(app, host="127.0.0.1")+ await server.start_server()+ server.hits = hits+ yield server+ await server.close()+++def only_localhost_is_public(monkeypatch):+ async def fake(host):+ return host == "localhost"++ monkeypatch.setattr(netguard, "host_is_public", fake)+++def ipv4_session():+ return aiohttp.ClientSession(connector=aiohttp.TCPConnector(family=socket.AF_INET))+++async def test_redirect_to_an_internal_address_is_not_followed(redirector, only_localhost_is_public):+ """Regression: the guard checked the first URL, then the client followed 302s."""+ async with ipv4_session() as session:+ with pytest.raises(netguard.GuardError):+ await netguard.guarded_get(session, f"http://localhost:{redirector.port}/to-internal")+ assert redirector.hits["secret"] == 0+++async def test_redirect_to_a_public_address_is_followed(redirector, only_localhost_is_public):+ async with ipv4_session() as session:+ response = await netguard.guarded_get(session, f"http://localhost:{redirector.port}/to-public")+ assert response.body == b"fine"+ assert response.redirects == 1+ assert response.final_url.endswith("/ok")+++async def test_redirect_loops_are_cut_off(redirector, only_localhost_is_public):+ async with ipv4_session() as session:+ with pytest.raises(netguard.GuardError, match="too many redirects"):+ await netguard.guarded_get(session, f"http://localhost:{redirector.port}/loop")+++async def test_first_hop_is_checked_too(redirector, only_localhost_is_public):+ async with ipv4_session() as session:+ with pytest.raises(netguard.GuardError):+ await netguard.guarded_get(session, f"http://127.0.0.1:{redirector.port}/secret")+ assert redirector.hits["secret"] == 0+++async def test_allow_private_lifts_the_check(redirector):+ async with ipv4_session() as session:+ response = await netguard.guarded_get(+ session, f"http://127.0.0.1:{redirector.port}/secret", allow_private=True+ )+ assert response.body == b"internal data"++[email protected]("url", ["file:///etc/passwd", "ftp://example.com/x", "gopher://x/", "", "http://"])+async def test_non_http_urls_are_never_fetchable(url):+ assert await netguard.is_public_url(url) is False+ assert await netguard.is_public_url(url, allow_private=True) is False+ assert netguard.is_public_url_sync(url, allow_private=True) is False++[email protected]("address,public", [+ ("8.8.8.8", True),+ ("127.0.0.1", False),+ ("10.1.2.3", False),+ ("192.168.0.1", False),+ ("169.254.169.254", False),+ ("::1", False),+ ("fe80::1", False),+ ("not-an-ip", False),+])+def test_is_public_ip(address, public):+ assert netguard.is_public_ip(address) is public+++class FakeResolver:+ def __init__(self, hosts):+ self.hosts = hosts++ async def resolve(self, host, port=0, family=socket.AF_INET):+ return [{"hostname": host, "host": h, "port": port, "family": family, "proto": 0, "flags": 0}+ for h in self.hosts]++ async def close(self):+ pass+++async def test_resolver_passes_public_answers():+ resolver = netguard.PublicOnlyResolver(FakeResolver(["8.8.8.8", "1.1.1.1"]))+ assert [r["host"] for r in await resolver.resolve("example.com")] == ["8.8.8.8", "1.1.1.1"]++[email protected]("answers", [["127.0.0.1"], ["8.8.8.8", "10.0.0.1"], []])+async def test_resolver_refuses_any_private_answer(answers):+ """One private answer among public ones is how DNS rebinding gets in."""+ resolver = netguard.PublicOnlyResolver(FakeResolver(answers))+ with pytest.raises(OSError):+ await resolver.resolve("evil.example")+++def test_sync_opener_refuses_private_redirects():+ handler = netguard._GuardedRedirects(allow_private=False)+ request = urllib.request.Request("https://8.8.8.8/a.png")+ with pytest.raises(urllib.error.URLError):+ handler.redirect_request(request, None, 302, "Found", {}, "http://127.0.0.1/secret")+ with pytest.raises(urllib.error.URLError):+ handler.redirect_request(request, None, 302, "Found", {}, "file:///etc/passwd")+++def test_sync_fetch_refuses_before_opening(monkeypatch):+ opened = []+ monkeypatch.setattr(urllib.request.OpenerDirector, "open",+ lambda self, req, *a, **k: opened.append(req))+ for url in ("file:///etc/passwd", "http://127.0.0.1/x", "http://169.254.169.254/"):+ assert netguard.guarded_urlopen_bytes(url) is None+ assert opened == []++[email protected]("url,reason", [+ ("http://127.0.0.1/x", "non-public"),+ ("http://no-such-host.invalid/", "does not resolve"),+ ("file:///etc/passwd", "not an http(s) address"),+])+async def test_refusals_say_why(url, reason):+ """A dead domain and a blocked private address need different responses."""+ assert reason in await netguard.refusal_reason(url)+ async with aiohttp.ClientSession() as session:+ with pytest.raises(netguard.GuardError, match=reason.replace("(", r"\(").replace(")", r"\)")):+ await netguard.guarded_get(session, url)diff --git a/tests/test_new_features.py b/tests/test_new_features.pyindex ca8dc1a..130716d 100644--- a/tests/test_new_features.py+++ b/tests/test_new_features.py@@ -339,21 +339,31 @@ def test_allow_private_opt_out_skips_the_check():assert _fetchable("http://127.0.0.1/x.png", allow_private=True) is True-def test_blocked_avatar_is_never_downloaded(monkeypatch):- """The guard must run before any request is issued."""+def test_blocked_avatar_is_never_downloaded():+ """The guard must run before any request is issued.++ The session records calls rather than raising: the download swallows+ exceptions by design, so a session that raised could never fail this test.+ """import asynciofrom aliens_eye.core.correlate import Profile, _download_and_hash- class ExplodingSession:- def get(self, *a, **k):- raise AssertionError("a blocked avatar URL was fetched anyway")+ class RecordingSession:+ def __init__(self):+ self.calls = []+ def get(self, url, **kwargs):+ self.calls.append(url)+ raise RuntimeError("no network in this test")++ session = RecordingSession()profile = Profile(variation="u", site="s", url="https://s/u", name="", bio="", status="Found",avatar="http://169.254.169.254/latest/meta-data/",)- asyncio.run(_download_and_hash(ExplodingSession(), profile, timeout=1.0))+ asyncio.run(_download_and_hash(session, profile, timeout=1.0))+ assert session.calls == []assert profile.avatar_hash is None@@ -434,15 +444,15 @@ def test_sync_avatar_guard_allows_public():def test_pdf_avatar_fetch_never_opens_a_blocked_url(monkeypatch):- """urllib speaks file://; a hostile og:image must never reach urlopen."""+ """A hostile og:image must never reach the network or the filesystem."""import urllib.requestpytest.importorskip("reportlab") # CI installs the [pdf] extra so this runs therefrom aliens_eye.core import pdf_report- def explode(*a, **k):- raise AssertionError("urlopen was called for a blocked avatar URL")-- monkeypatch.setattr(urllib.request, "urlopen", explode)+ opened = []+ monkeypatch.setattr(urllib.request.OpenerDirector, "open",+ lambda self, req, *a, **k: opened.append(req.full_url))for url in ("file:///etc/passwd", "http://127.0.0.1/admin", "http://10.0.0.1/x"):assert pdf_report._fetch_avatar(url) is None+ assert opened == []diff --git a/tests/test_urlmatch.py b/tests/test_urlmatch.pynew file mode 100644index 0000000..a101385--- /dev/null+++ b/tests/test_urlmatch.py@@ -0,0 +1,181 @@+"""Reverse URL matching, and the guarded page fetch built for following links."""++import socket++import aiohttp+import pytest+from aiohttp import web+from aiohttp.test_utils import TestServer++from aliens_eye import api+from aliens_eye.core import netguard+from aliens_eye.core.expand import _username_from_url+from aliens_eye.core.urlmatch import ProfileUrlMatcher++SITES = {+ "github": "https://github.com/{}",+ "github.sponsors": "https://github.com/sponsors/{}",+ "reddit": "https://www.reddit.com/user/{}",+ "medium": "https://medium.com/@{}",+ "tumblr": "https://{}.tumblr.com",+ "forum": "https://forum.example/member.php?mode=view&username={}",+ "lor": "https://www.linux.example/people/{}/profile",+ "twitter": "https://twitter.com/{}",+ "boards": "https://www.pinterest.com/{}/{}",+}+++def matcher():+ return ProfileUrlMatcher(SITES)+++def first(matcher, url):+ matches = matcher.match(url)+ return tuple(matches[0]) if matches else None++[email protected]("url,expected", [+ ("https://github.com/arx", ("github", "arx")),+ ("http://www.GitHub.com/arx/", ("github", "arx")), # scheme, www, case, slash+ ("https://github.com/arx?tab=repositories#x", ("github", "arx")), # query and fragment ignored+ ("https://www.reddit.com/user/spez", ("reddit", "spez")),+ ("https://old.reddit.com/user/spez", ("reddit", "spez")), # host alias+ ("https://medium.com/@someone", ("medium", "someone")),+ ("https://arx.tumblr.com", ("tumblr", "arx")),+ ("https://arx.tumblr.com/post/1", ("tumblr", "arx")),+ ("https://forum.example/member.php?username=zed&mode=view", ("forum", "zed")),+ ("https://www.linux.example/people/maxcom/profile", ("lor", "maxcom")),+ ("https://x.com/arx", ("twitter", "arx")), # x.com is twitter+ ("https://twitter.com/@arx", ("twitter", "arx")), # leading @ dropped+])+def test_profile_urls_are_recognised(matcher, url, expected):+ assert first(matcher, url) == expected++[email protected]("url", [+ "https://github.com/arx/some-repo", # a repository, not a profile+ "https://github.com/sponsors", # fixed segment of a sibling template+ "https://github.com/features", # site navigation+ "https://github.com/login",+ "https://github.com/",+ "https://twitter.com/intent/tweet?text=hi",+ "https://www.tumblr.com", # no username subdomain+ "https://www.tumblr.com/explore",+ "https://api.tumblr.com", # service subdomain+ "https://forum.example/member.php?username=zed", # fixed param missing+ "https://forum.example/other.php?mode=view&username=zed", # wrong path+ "https://www.linux.example/people/maxcom", # template suffix missing+ "https://github.com/logo.png", # a file+ "https://github.com/a", # too short to scan+ "https://unknown.example/arx",+ "javascript:alert(1)",+ "file:///etc/passwd",+ "not a url",+ "",+])+def test_non_profile_urls_do_not_match(matcher, url):+ assert matcher.match(url) == []+++def test_most_specific_template_wins(matcher):+ assert first(matcher, "https://github.com/sponsors/arx") == ("github.sponsors", "arx")+++def test_two_placeholder_templates_are_skipped(matcher):+ assert all(m.site != "boards" for m in matcher.match("https://www.pinterest.com/arx/board"))+++def test_username_case_is_preserved(matcher):+ assert first(matcher, "https://github.com/ArxHR") == ("github", "ArxHR")+++def test_percent_encoded_usernames_are_decoded(matcher):+ assert first(matcher, "https://github.com/%E5%9D%A6%E9%80%94") == ("github", "坦途")+++def test_api_matches_against_the_real_catalogue():+ assert tuple(api.match_profile_url("https://www.instagram.com/_arx_/")[0]) == ("instagram", "_arx_")+ assert tuple(api.match_profile_url("https://www.linkedin.com/in/some-one")[0]) == ("linkedin", "some-one")+ assert api.match_profile_url("https://github.com/arx/repo") == []+++def test_profile_url_round_trips_through_the_matcher():+ url = api.profile_url("github", "arx")+ assert tuple(api.match_profile_url(url)[0]) == ("github", "arx")+ with pytest.raises(KeyError):+ api.profile_url("no-such-site", "arx")+++def test_expand_understands_any_catalogue_site():+ """It used to know 19 hard-coded domains and take the first path segment."""+ assert _username_from_url("https://www.linkedin.com/in/some-one") == "some-one"+ assert _username_from_url("https://twitter.com/charlie") == "charlie"+ assert _username_from_url("https://github.com/arx/repo") is None+++# --- fetch_page ----------------------------------------------------------------+++async def page_server():+ hits = {"secret": 0}+ app = web.Application()++ async def page(request):+ return web.Response(text="<html><a rel='me' href='https://github.com/arx'>gh</a></html>",+ content_type="text/html")++ async def to_internal(request):+ raise web.HTTPFound(f"http://127.0.0.1:{request.url.port}/secret")++ async def secret(request):+ hits["secret"] += 1+ return web.Response(text="internal")++ app.router.add_get("/page", page)+ app.router.add_get("/to-internal", to_internal)+ app.router.add_get("/secret", secret)+ server = TestServer(app, host="127.0.0.1")+ await server.start_server()+ server.hits = hits+ yield server+ await server.close()+++async def test_fetch_page_returns_html(page_server):+ result = await api.fetch_page(f"http://127.0.0.1:{page_server.port}/page", allow_private=True)+ assert result["status"] == 200+ assert result["error"] is None+ assert "rel='me'" in result["html"]+++async def test_fetch_page_refuses_private_addresses_by_default(page_server):+ result = await api.fetch_page(f"http://127.0.0.1:{page_server.port}/secret")+ assert result["error"]+ assert result["html"] == ""+ assert page_server.hits["secret"] == 0+++async def test_fetch_page_does_not_follow_a_redirect_inward(page_server, monkeypatch):+ async def only_localhost(host):+ return host == "localhost"++ monkeypatch.setattr(netguard, "host_is_public", only_localhost)+ # Plain IPv4 connector: the public-only resolver would (rightly) refuse the+ # test server itself. The per-hop check is what is under test here.+ monkeypatch.setattr(+ "aliens_eye.core.scanner.build_session",+ lambda config, limit, headers=None, resolver=None: aiohttp.ClientSession(+ connector=aiohttp.TCPConnector(family=socket.AF_INET)+ ),+ )+ result = await api.fetch_page(f"http://localhost:{page_server.port}/to-internal")+ assert result["error"]+ assert page_server.hits["secret"] == 0++[email protected]("url", ["file:///etc/passwd", "javascript:alert(1)", "", "ftp://x/y"])+async def test_fetch_page_never_raises_on_bad_urls(url):+ result = await api.fetch_page(url)+ assert result["error"] and result["html"] == ""