Skip to content

AI powered OSINT engine to discover and map 840+ social media identities across the web

fix: SSRF guard on avatar fetching, header size limit, non-finite durations

arxhr0078f8d05724e1b
diff --git a/src/aliens_eye/core/config.py b/src/aliens_eye/core/config.py
index 368304f..8718a21 100644
--- a/src/aliens_eye/core/config.py
+++ b/src/aliens_eye/core/config.py
@@ -32,6 +32,11 @@ def _supported_encodings() -> str:
return ", ".join(encodings)
+# aiohttp defaults to 8190 bytes per header line. Real sites exceed that -- trakt
+# ships a very large Link header of asset preloads -- and the request then fails
+# with "Got more than 8190 bytes when reading" rather than returning a page.
+MAX_HEADER_SIZE = 65536
+
DEFAULT_HEADERS = {
"User-Agent": DEFAULT_USER_AGENT,
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
diff --git a/src/aliens_eye/core/correlate.py b/src/aliens_eye/core/correlate.py
index c344490..7027bb1 100644
--- a/src/aliens_eye/core/correlate.py
+++ b/src/aliens_eye/core/correlate.py
@@ -12,9 +12,11 @@ correlation still runs on name/bio/link signals alone.
from __future__ import annotations
import asyncio
+import ipaddress
import re
from dataclasses import dataclass, field
from typing import Any
+from urllib.parse import urlparse
import aiohttp
@@ -153,11 +155,56 @@ 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 favicon
+ link, 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.
+ """
+ parsed = urlparse(url)
+ if parsed.scheme.lower() not in ALLOWED_AVATAR_SCHEMES:
+ return False
+ host = parsed.hostname
+ if not host:
+ return False
+ if allow_private:
+ return True
+ try:
+ infos = await asyncio.get_event_loop().getaddrinfo(host, None)
+ except (OSError, UnicodeError):
+ return False
+ 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
+
+
async def _download_and_hash(
- session: aiohttp.ClientSession, profile: Profile, timeout: float
+ session: aiohttp.ClientSession,
+ profile: Profile,
+ timeout: float,
+ allow_private: bool = False,
) -> None:
if not profile.avatar:
return
+ if not await is_fetchable_avatar(profile.avatar, allow_private):
+ return
try:
async with session.get(profile.avatar, timeout=aiohttp.ClientTimeout(total=timeout)) as resp:
if resp.status != 200:
@@ -168,7 +215,12 @@ async def _download_and_hash(
profile.avatar_hash = _dhash(data)
-async def hash_avatars(profiles: list[Profile], proxy: str | None = None, timeout: float = 10.0) -> None:
+async def hash_avatars(
+ profiles: list[Profile],
+ proxy: str | None = None,
+ timeout: float = 10.0,
+ allow_private: bool = False,
+) -> None:
"""Download and dhash every profile avatar in place. No-op without Pillow."""
if not pillow_available():
return
@@ -183,7 +235,7 @@ async def hash_avatars(profiles: list[Profile], proxy: str | None = None, timeou
async def worker(p: Profile) -> None:
async with sem:
- await _download_and_hash(session, p, timeout)
+ await _download_and_hash(session, p, timeout, allow_private)
await asyncio.gather(*(worker(p) for p in targets))
@@ -280,11 +332,19 @@ def cluster_profiles(profiles: list[Profile]) -> list[dict[str, Any]]:
async def correlate_report(
- report: dict[str, Any], proxy: str | None = None, timeout: float = 10.0
+ report: dict[str, Any],
+ proxy: str | None = None,
+ timeout: float = 10.0,
+ allow_private_avatars: bool = False,
) -> dict[str, Any]:
- """Full correlation pass over a report dict. Returns a ``correlation`` block."""
+ """Full correlation pass over a report dict. Returns a ``correlation`` block.
+
+ ``allow_private_avatars`` lifts the guard that stops scraped avatar URLs
+ resolving to private or loopback addresses; only set it when scanning a
+ network you own.
+ """
profiles = profiles_from_report(report)
- await hash_avatars(profiles, proxy=proxy, timeout=timeout)
+ await hash_avatars(profiles, proxy=proxy, timeout=timeout, allow_private=allow_private_avatars)
clusters = cluster_profiles(profiles)
return {
"avatar_hashing": pillow_available(),
diff --git a/src/aliens_eye/core/scanner.py b/src/aliens_eye/core/scanner.py
index c900a99..6e9ef31 100644
--- a/src/aliens_eye/core/scanner.py
+++ b/src/aliens_eye/core/scanner.py
@@ -13,7 +13,7 @@ from aliens_eye.utils.console import ScanView, get_console
from .analyzer import FeatureExtractor
from .browser import BrowserFallback
-from .config import DEFAULT_HEADERS, ScannerConfig
+from .config import DEFAULT_HEADERS, MAX_HEADER_SIZE, ScannerConfig
from .detector import Detector
from .fingerprints import FingerprintStore, build_fingerprint
from .http import fetch_url
@@ -129,6 +129,26 @@ def build_connector(config: ScannerConfig, limit: int) -> aiohttp.BaseConnector:
return aiohttp.TCPConnector(limit=limit)
+def build_session(
+ config: ScannerConfig,
+ limit: int,
+ headers: dict[str, str] | None = None,
+) -> aiohttp.ClientSession:
+ """Session for fetching site pages, with the header-size limit raised.
+
+ aiohttp caps a single header line at 8190 bytes, which some real sites
+ exceed; the request then fails outright instead of returning the page. Every
+ path that fetches profile pages should build its session here so the limit,
+ the headers and the proxy connector stay consistent.
+ """
+ return aiohttp.ClientSession(
+ headers=DEFAULT_HEADERS if headers is None else headers,
+ connector=build_connector(config, limit),
+ max_line_size=MAX_HEADER_SIZE,
+ max_field_size=MAX_HEADER_SIZE,
+ )
+
+
class UsernameScanner:
"""Coordinates async scanning across all platforms."""
@@ -216,12 +236,9 @@ class UsernameScanner:
view = ScanView(self.console)
view.start(username, len(pending))
- connector = build_connector(self.config, conn_limit)
start_time = time.monotonic()
try:
- async with aiohttp.ClientSession(
- headers=DEFAULT_HEADERS, connector=connector
- ) as session:
+ async with build_session(self.config, conn_limit) as session:
workers = [
asyncio.create_task(
self._worker(queue, username, session, rate_limiter, results, view)
diff --git a/src/aliens_eye/core/watch.py b/src/aliens_eye/core/watch.py
index e82b971..2f03efa 100644
--- a/src/aliens_eye/core/watch.py
+++ b/src/aliens_eye/core/watch.py
@@ -8,6 +8,7 @@ cycle (seeded from the most recent report on disk, if any).
from __future__ import annotations
import asyncio
+import math
from pathlib import Path
from typing import Any
@@ -34,8 +35,11 @@ def parse_duration(value: str) -> float:
number = text
factor = 1.0
seconds = float(number) * factor
- if seconds <= 0:
- raise ValueError(f"duration must be positive: {value!r}")
+ # NaN defeats every ordering comparison, so `seconds <= 0` alone lets it
+ # through and the watch loop ends up in asyncio.sleep(nan). Infinity passes
+ # the same check and sleeps forever.
+ if not math.isfinite(seconds) or seconds <= 0:
+ raise ValueError(f"duration must be a positive, finite number: {value!r}")
return seconds
diff --git a/src/aliens_eye/corpus/record.py b/src/aliens_eye/corpus/record.py
index d8461c2..16fefc9 100644
--- a/src/aliens_eye/corpus/record.py
+++ b/src/aliens_eye/corpus/record.py
@@ -18,10 +18,10 @@ from typing import Any
import aiohttp
from aliens_eye import __version__
-from aliens_eye.core.config import DEFAULT_HEADERS, ScannerConfig
+from aliens_eye.core.config import ScannerConfig
from aliens_eye.core.http import FetchResult, fetch_url
from aliens_eye.core.rate_limit import DomainRateLimiter
-from aliens_eye.core.scanner import build_connector, format_site_url
+from aliens_eye.core.scanner import build_session, format_site_url
from .store import CorpusRecord, CorpusStore
@@ -222,9 +222,8 @@ async def record_corpus(
conn_limit = max(1, min(concurrency, len(jobs) or 1))
semaphore = asyncio.Semaphore(conn_limit)
- connector = build_connector(config, conn_limit)
- async with aiohttp.ClientSession(headers=DEFAULT_HEADERS, connector=connector) as session:
+ async with build_session(config, conn_limit) as session:
async def run(url: str) -> None:
async with semaphore:
diff --git a/src/aliens_eye/ml/collect.py b/src/aliens_eye/ml/collect.py
index dde6bec..fddddc3 100644
--- a/src/aliens_eye/ml/collect.py
+++ b/src/aliens_eye/ml/collect.py
@@ -28,12 +28,12 @@ from typing import Any
import aiohttp
from aliens_eye.core.analyzer import FeatureExtractor
-from aliens_eye.core.config import DEFAULT_HEADERS, ScannerConfig
+from aliens_eye.core.config import ScannerConfig
from aliens_eye.core.detector import Detector
from aliens_eye.core.features import FEATURE_SCHEMA, vectorize_features
from aliens_eye.core.http import fetch_url
from aliens_eye.core.rate_limit import DomainRateLimiter
-from aliens_eye.core.scanner import format_site_url
+from aliens_eye.core.scanner import build_session, format_site_url
TRAIN_SPLIT_RESOURCE = "selfcheck.json"
HOLDOUT_SPLIT_RESOURCE = "eval_holdout.json"
@@ -197,8 +197,7 @@ async def collect_dataset(
semaphore = asyncio.Semaphore(concurrency)
rows: list[list[float]] = []
- connector = aiohttp.TCPConnector(limit=concurrency)
- async with aiohttp.ClientSession(headers=DEFAULT_HEADERS, connector=connector) as session:
+ async with build_session(config, concurrency) as session:
async def run_job(job: tuple[str, str, str, int]) -> None:
site, template, username, label = job
diff --git a/src/aliens_eye/selfcheck.py b/src/aliens_eye/selfcheck.py
index 2ca17d6..101d05d 100644
--- a/src/aliens_eye/selfcheck.py
+++ b/src/aliens_eye/selfcheck.py
@@ -19,17 +19,16 @@ import string
from pathlib import Path
from typing import Any
-import aiohttp
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from aliens_eye.core.analyzer import FeatureExtractor
-from aliens_eye.core.config import DEFAULT_HEADERS, ScannerConfig
+from aliens_eye.core.config import ScannerConfig
from aliens_eye.core.detector import Detector
from aliens_eye.core.http import fetch_url
from aliens_eye.core.rate_limit import DomainRateLimiter
-from aliens_eye.core.scanner import format_site_url
+from aliens_eye.core.scanner import build_session, format_site_url
from aliens_eye.utils.console import get_console
@@ -120,8 +119,7 @@ async def run_selfcheck(
rows: list[dict] = []
semaphore = asyncio.Semaphore(min(10, len(jobs)))
- connector = aiohttp.TCPConnector(limit=10)
- async with aiohttp.ClientSession(headers=DEFAULT_HEADERS, connector=connector) as session:
+ async with build_session(config, 10) as session:
fetch_result = fetch
diff --git a/tests/test_new_features.py b/tests/test_new_features.py
index b31b99a..df07296 100644
--- a/tests/test_new_features.py
+++ b/tests/test_new_features.py
@@ -3,6 +3,8 @@ domains, checkpoint, graph export, dataset append, and selfcheck metrics."""
import json
+import pytest
+
from aliens_eye.core import report as report_mod
from aliens_eye.core.checkpoint import Checkpoint
from aliens_eye.core.correlate import (
@@ -259,3 +261,97 @@ def test_metrics_math():
assert m["recall"] == 0.8
assert round(m["f1"], 2) == 0.8
assert m["false_positive_rate"] == 0.2
+
+
+# --- parse_duration: non-finite input -------------------------------------
+
+
+def test_parse_duration_rejects_nan():
+ """NaN defeats `<= 0`, so it reached asyncio.sleep(nan) in the watch loop."""
+ from aliens_eye.core.watch import parse_duration
+
+ for value in ("nan", "NaN", "-nan"):
+ with pytest.raises(ValueError, match="finite"):
+ parse_duration(value)
+
+
+def test_parse_duration_rejects_infinity():
+ from aliens_eye.core.watch import parse_duration
+
+ for value in ("inf", "-inf", "infinity"):
+ with pytest.raises(ValueError):
+ parse_duration(value)
+
+
+def test_parse_duration_still_accepts_normal_values():
+ from aliens_eye.core.watch import parse_duration
+
+ assert parse_duration("6h") == 21600.0
+ assert parse_duration("90") == 90.0
+ assert parse_duration("1.5m") == 90.0
+
+
+# --- avatar fetch: SSRF guard ---------------------------------------------
+
+
+def _fetchable(url, allow_private=False):
+ import asyncio
+
+ from aliens_eye.core.correlate import is_fetchable_avatar
+
+ return asyncio.run(is_fetchable_avatar(url, allow_private))
+
+
+def test_avatar_fetch_rejects_loopback_and_private_hosts():
+ """Avatar URLs come from the target's own page, so they are attacker-chosen.
+
+ Fetching them unchecked aims requests from the analyst's machine wherever
+ the target likes: cloud metadata, intranet hosts, services on loopback.
+ """
+ for url in (
+ "http://127.0.0.1:8080/admin",
+ "http://localhost/",
+ "http://169.254.169.254/latest/meta-data/",
+ "http://10.0.0.5/",
+ "http://192.168.1.1/",
+ "http://[::1]/",
+ ):
+ assert _fetchable(url) is False, url
+
+
+def test_avatar_fetch_rejects_non_http_schemes():
+ for url in ("file:///etc/passwd", "ftp://example.com/x.png", "gopher://x/", "data:image/png;base64,AAAA"):
+ assert _fetchable(url) is False, url
+
+
+def test_avatar_fetch_rejects_malformed_urls():
+ for url in ("", "http://", "notaurl", "https:///nohost"):
+ assert _fetchable(url) is False, url
+
+
+def test_avatar_fetch_allows_a_public_address():
+ # 8.8.8.8 is a literal public address, so this needs no DNS lookup.
+ assert _fetchable("https://8.8.8.8/avatar.png") is True
+
+
+def test_allow_private_opt_out_skips_the_check():
+ """Deliberate lab scanning must still be possible."""
+ 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."""
+ import asyncio
+
+ from 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")
+
+ 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))
+ assert profile.avatar_hash is None