Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8ebad6103 | ||
|
|
56b33a7740 |
No files matched your search
+1
-1
@@ -118,7 +118,7 @@ dependencies = [
|
||||
|
||||
[project.optional-dependencies]
|
||||
remote = ["websockets>=13"]
|
||||
dev = ["websockets>=13", "pytest>=7", "build>=1", "ruff>=0.6", "pytest-rerunfailures>=14", "pytest-timeout>=2", "pytest-xdist>=3", "playwright==1.61.0", "cryptography>=41"]
|
||||
dev = ["websockets>=13", "pytest>=7", "build>=1", "ruff>=0.6", "pytest-rerunfailures>=14", "pytest-timeout>=2", "pytest-xdist>=3", "playwright==1.61.0", "cryptography>=41", "h2>=4,<5"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
markers = [
|
||||
|
||||
@@ -713,7 +713,7 @@ def _launch_params(session: Any, *, virtual_display: bool, headless: bool,
|
||||
"""`InvisiblePlaywright.__enter__` up to the launch, as protocol params.
|
||||
|
||||
The same calls in the same order, so the served browser is the one the
|
||||
wrapper would have launched: geo (egress, timezone, locale, srflx), the
|
||||
wrapper would have launched: geo (egress, timezone, locale), the
|
||||
hidden display, the prefs, the proxy, the session token and the env."""
|
||||
from invisible_core import configure_proxy, prepare_session_geo
|
||||
from invisible_core import make_virtual_display
|
||||
@@ -725,7 +725,6 @@ def _launch_params(session: Any, *, virtual_display: bool, headless: bool,
|
||||
session._timezone = geo.timezone
|
||||
session._locale = geo.locale
|
||||
session._webrtc_egress_ip = geo.egress_ip
|
||||
session._srflx_declared = geo.srflx_to_declare()
|
||||
executable = resolve_executable(session._binary_path)
|
||||
pw_headless = bool(headless)
|
||||
if not headless and virtual_display:
|
||||
@@ -789,7 +788,7 @@ def launch_server(host: str = DEFAULT_HOST, port: int = 0, *,
|
||||
pin fingerprint fields forced (see docs/pinning.md).
|
||||
proxy `{"server", "username", "password"}`, fixed after the
|
||||
launch; the egress (exit IP -> timezone, locale
|
||||
"auto", srflx/WebRTC; the GeoIP database offline from
|
||||
"auto"; the GeoIP database offline from
|
||||
STEALTHFOX_GEOIP_MMDB) is measured here through it.
|
||||
headless True = true headless; False = headed.
|
||||
virtual_display with headless=False: a private virtual display (Xvfb
|
||||
|
||||
@@ -295,7 +295,7 @@ def session_for_launch(prefs: Dict, executable: str, proxy: Optional[Dict] = Non
|
||||
|
||||
`proxy` is the launch's own (`launch(proxy=...)`): the session is composed
|
||||
through it as `InvisiblePlaywright(proxy=...)` composes, so the egress it
|
||||
measures there is the address WebRTC declares (STEALTHFOX_WEBRTC_PUBLIC_IP),
|
||||
measures there (timezone, locale) and the network it declares are the proxy's,
|
||||
not this machine's. The engine is told the proxy by `op_launch`, as before.
|
||||
"""
|
||||
if COMPOSED_PREF in prefs:
|
||||
@@ -5351,8 +5351,8 @@ class BrowserTypeDispatcher(Dispatcher):
|
||||
# ⛔ THE PROXY IS SET BY THE CORE'S `launch`, before any page exists,
|
||||
# and a proxy the engine refuses closes the browser there: the driver
|
||||
# once accepted `proxy=` and dropped it, and a page went out on the
|
||||
# host address while the session's timezone, locale and WebRTC
|
||||
# candidate had been resolved THROUGH the proxy (2026-08-30). Until
|
||||
# host address while the session's timezone and locale
|
||||
# had been resolved THROUGH the proxy (2026-08-30). Until
|
||||
# 0.34.0 this method sent the command itself, as Selenium's and
|
||||
# Puppeteer's launch did, each with the same fixed 10 s.
|
||||
conn = juggler.launch(executable, profile,
|
||||
|
||||
@@ -86,11 +86,18 @@ def default_session(executable: Optional[str] = None,
|
||||
geo = session_geo(session._timezone, session._proxy, session._locale_requested)
|
||||
session._timezone, session._locale = geo.timezone, geo.locale
|
||||
prefs = session._build_prefs()
|
||||
env = build_env(srflx_declared=geo.srflx_to_declare(), profile=session._profile,
|
||||
env = build_env(network_declared=declared_network(session), profile=session._profile,
|
||||
executable=executable, base_env={})
|
||||
return prefs, env
|
||||
|
||||
|
||||
def declared_network(session: Any) -> str:
|
||||
"""The host network this session declares to the engine (the value of
|
||||
STEALTHFOX_WEBRTC_NETWORK), drawn from its seed, with or without a proxy."""
|
||||
from invisible_core import network_to_declare
|
||||
return network_to_declare(session.seed)
|
||||
|
||||
|
||||
def true_headless_requested(env: Optional[Dict[str, str]] = None) -> bool:
|
||||
return (env if env is not None else os.environ).get(TRUE_HEADLESS_ENV) == "1"
|
||||
|
||||
@@ -99,13 +106,9 @@ def true_headless_requested(env: Optional[Dict[str, str]] = None) -> bool:
|
||||
#: lives. It was duplicated here byte-for-byte - ten entries, including the
|
||||
def build_env(
|
||||
*,
|
||||
#: The address to DECLARE as srflx, or None to declare nothing and let the
|
||||
#: real one through. ⛔ This is NOT the egress IP: it is a DECISION the
|
||||
#: core makes in a single place, looking at the capabilities of the egress
|
||||
#: (`SessionGeo.srflx_to_declare`). The old name, `egress_ip`, said
|
||||
#: something else and made the rule look like "there's a proxy -> declare
|
||||
#: it", which is the wrong question.
|
||||
srflx_declared: Optional[str],
|
||||
#: The host network the engine reads (STEALTHFOX_WEBRTC_NETWORK), drawn from
|
||||
#: the session seed (`declared_network`); None declares nothing.
|
||||
network_declared: Optional[str],
|
||||
profile: Any = None,
|
||||
executable: Optional[str] = None,
|
||||
base_env: Optional[Dict[str, str]] = None,
|
||||
@@ -166,7 +169,7 @@ def build_env(
|
||||
f"(e.g. {missing[:3]}). Engine: {executable}. The metrics "
|
||||
f"would describe fonts that are not there.")
|
||||
manifest_path = cached_font_manifest_path(manifest)
|
||||
return build_launch_env({}, srflx_declared=srflx_declared,
|
||||
return build_launch_env({}, network_declared=network_declared,
|
||||
manifest_path=manifest_path, base_env=base_env,
|
||||
display_env=display_env)
|
||||
|
||||
@@ -279,16 +282,14 @@ class ProxyEgressDrifted(RuntimeError):
|
||||
This is not a condition the product can recover from, and it is deliberate
|
||||
that it is an error instead of a silent update.
|
||||
|
||||
The IP we declare to the engine for the WebRTC srflx candidate is
|
||||
discovered ONCE, at launch. If the egress changes afterwards, the page
|
||||
exits from one address and WebRTC announces another: it is exactly the
|
||||
comparison detectors make ("WebRTC IP doesn't match your Remote IP"), and
|
||||
no Firefox on a real connection produces it.
|
||||
The timezone and the locale are decided ONCE, at launch, from the egress
|
||||
country. If the egress moves afterwards, the page exits from one place
|
||||
while the timezone and the language still describe another: a mismatch no
|
||||
real connection produces.
|
||||
|
||||
Updating the value on the fly would be worse, not better: the site would
|
||||
see the WebRTC IP change before its own eyes mid-session, which is just as
|
||||
unnatural a signal. If the egress does not hold for the duration of the
|
||||
session, that proxy is not sticky and is not usable for this purpose.
|
||||
Updating them on the fly would be just as unnatural (the site would see
|
||||
them change mid-session). If the egress does not hold for the duration of
|
||||
the session, that proxy is not sticky and is not usable for this purpose.
|
||||
|
||||
Measured on 2026-08-25: the two providers tried both declare sessions
|
||||
sticky by TIME (60 minutes at most for one, a sliding timeout for the
|
||||
@@ -384,7 +385,7 @@ class CommonLaunch:
|
||||
`_cursor_engine`, `_extra_prefs`, `_headless`, `_humanize`,
|
||||
`_lifetime_guard`, `_locale` (the core's SessionLocale, None until
|
||||
`__enter__` decides it), `_profile`, `_session_token`, `_show_cursor`,
|
||||
`_srflx_declared`, `_timezone` and `_virtual_display` in their own
|
||||
`_network_declared`, `_timezone` and `_virtual_display` in their own
|
||||
`__init__`. They already did, identically, which is why this works at all.
|
||||
"""
|
||||
|
||||
@@ -449,7 +450,7 @@ class CommonLaunch:
|
||||
"""Env for the Firefox subprocess, then stamped with this session's token.
|
||||
|
||||
The body is `build_env`, shared with the async class - it was
|
||||
written twice, identically, and the WebRTC pair is a contract with the
|
||||
written twice, identically, and the WebRTC declaration is a contract with the
|
||||
binary, so two landing sites meant two chances to miss a change.
|
||||
|
||||
The token stamp stays here because it is the only genuinely per-session
|
||||
@@ -458,7 +459,7 @@ class CommonLaunch:
|
||||
"""
|
||||
vd = self._virtual_display
|
||||
return self._session_token.stamp(
|
||||
build_env(srflx_declared=self._srflx_declared,
|
||||
build_env(network_declared=self._network_declared,
|
||||
profile=self._profile,
|
||||
executable=resolve_executable(self._binary_path),
|
||||
display_env=vd.launch_env() if vd is not None else None))
|
||||
|
||||
@@ -88,13 +88,11 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
# otherwise. Nothing was red because no test enters this context manager.
|
||||
self._session_token = SessionToken()
|
||||
self._lifetime_guard = guard_for()
|
||||
# Proxy egress IP (WebRTC srflx override); discovered in __aenter__.
|
||||
# Proxy egress IP, discovered in __aenter__: the guard against drift
|
||||
# compares it with the egress now. None without a proxy.
|
||||
self._webrtc_egress_ip: Optional[str] = None
|
||||
#: The DECISION about the srflx, distinct from the fact above.
|
||||
#: Starts as None like it: `_build_env` can be called before
|
||||
#: the geo path has resolved, and in that case nothing is
|
||||
#: declared.
|
||||
self._srflx_declared: Optional[str] = None
|
||||
#: The host network the engine reads, drawn from the seed.
|
||||
self._network_declared: str = _session.declared_network(self)
|
||||
#: See the twin in `launcher.py`: starts at 0 because the first
|
||||
#: context must be able to check right away.
|
||||
self._ultimo_controllo_uscita: float = 0.0
|
||||
@@ -116,17 +114,6 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
self._timezone = _geo.timezone
|
||||
self._locale = _geo.locale
|
||||
self._webrtc_egress_ip = _geo.egress_ip
|
||||
# ⛔ TWO DIFFERENT THINGS, and they used to be a single field.
|
||||
# `_webrtc_egress_ip` is the FACT: where we exit from. It feeds
|
||||
# the guard against drift, which compares the current egress
|
||||
# against the one at launch.
|
||||
# `_srflx_declared` is the DECISION: what the engine must
|
||||
# announce. It is None when the egress has proven, consistent
|
||||
# UDP, because there the real srflx is already correct and
|
||||
# declaring one would add a candidate with no matching
|
||||
# allocation - the signal a detector running its own TURN reads.
|
||||
# The core takes it in a single spot.
|
||||
self._srflx_declared = _geo.srflx_to_declare()
|
||||
# binary_path= never reaches ensure_binary(), so the engine check lives
|
||||
# on the resolved executable rather than inside the fetcher.
|
||||
executable = resolve_executable(self._binary_path)
|
||||
@@ -191,7 +178,7 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
#: session gets rejected. One alone would be too strict - a timeout
|
||||
#: happens - but unlimited would be declared blindness: after three
|
||||
#: silent checks at 120 s each, that is six minutes in which nothing
|
||||
#: is confirming the address the engine announces on every page.
|
||||
#: is confirming that the timezone and the locale still match the egress.
|
||||
_MAX_USCITE_NON_MISURABILI = 3
|
||||
|
||||
async def _assert_uscita_invariata(self) -> None:
|
||||
@@ -210,19 +197,19 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
if outcome == _session.USCITA_DERIVATA:
|
||||
raise _session.ProxyEgressDrifted(
|
||||
"the proxy's egress IP changed during the session: "
|
||||
"at launch it was %s, now it is %s. The WebRTC srflx "
|
||||
"candidate still declares the first one, so from this "
|
||||
"moment the page exits from one address and WebRTC "
|
||||
"announces another - the disagreement detectors look "
|
||||
"for. This proxy does not hold the session sticky for "
|
||||
"at launch it was %s, now it is %s. The timezone and the "
|
||||
"locale still describe the first one, so from this moment "
|
||||
"the page exits from one place and they say another. "
|
||||
"This proxy does not hold the session sticky for "
|
||||
"the required duration: use one that guarantees it, or "
|
||||
"shorten the session."
|
||||
% (self._webrtc_egress_ip, current))
|
||||
if outcome == _session.USCITA_NON_MISURABILE:
|
||||
# This is NOT "holds", which is why there are three outcomes. A
|
||||
# probe that fails ONCE is the network; one that always fails is
|
||||
# blindness: from that moment the engine keeps declaring an
|
||||
# address on every page that nobody is confirming anymore. It is
|
||||
# blindness: from that moment the timezone and the locale stay
|
||||
# declared on every page with nobody confirming them against the
|
||||
# egress anymore. It is
|
||||
# counted, instead of ignored, and rejected only if it repeats.
|
||||
self._uscite_non_misurabili += 1
|
||||
if self._uscite_non_misurabili >= self._MAX_USCITE_NON_MISURABILI:
|
||||
@@ -230,8 +217,8 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
"the egress IP could not be verified for %d checks in "
|
||||
"a row. It is not drift - the probe did not respond at "
|
||||
"all - but it is not agreement either: from here on "
|
||||
"the engine would be declaring an address on every "
|
||||
"page that nobody confirms anymore. Check that the "
|
||||
"the timezone and the locale go unconfirmed on every "
|
||||
"page. Check that the "
|
||||
"proxy is reachable, then relaunch the session."
|
||||
% self._uscite_non_misurabili)
|
||||
return
|
||||
|
||||
@@ -235,14 +235,11 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
# before __enter__ has got anywhere - always finds them.
|
||||
self._session_token = SessionToken()
|
||||
self._lifetime_guard = guard_for()
|
||||
# Proxy egress IP, discovered at launch (see __enter__). Feeds the
|
||||
# WebRTC srflx override so the candidate matches the proxy IP, not the
|
||||
# real host IP. None when no proxy is set.
|
||||
# Proxy egress IP, discovered at launch (see __enter__): the guard
|
||||
# against drift compares it with the egress now. None without a proxy.
|
||||
self._webrtc_egress_ip: Optional[str] = None
|
||||
#: The DECISION about the srflx, distinct from the fact above.
|
||||
#: Starts at None like it: `_build_env` can be called before the
|
||||
#: geo path has resolved, and in that case nothing is declared.
|
||||
self._srflx_declared: Optional[str] = None
|
||||
#: The host network the engine reads, drawn from the seed.
|
||||
self._network_declared: str = _session.declared_network(self)
|
||||
#: When the egress was last rechecked. Starts at 0 rather than at
|
||||
#: `time.monotonic()`: the first context must be able to check
|
||||
#: right away, because time may already have passed between launch
|
||||
@@ -264,17 +261,6 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
self._timezone = _geo.timezone
|
||||
self._locale = _geo.locale
|
||||
self._webrtc_egress_ip = _geo.egress_ip
|
||||
# ⛔ TWO DIFFERENT THINGS, and before they were a single field.
|
||||
# `_webrtc_egress_ip` is the FACT: where we exit from. It serves the
|
||||
# guard against drift, which compares now's egress against the one
|
||||
# at launch.
|
||||
# `_srflx_declared` is the DECISION: what the engine must
|
||||
# announce. It is None when the egress has proven, consistent UDP,
|
||||
# because there the real srflx is already born correct and
|
||||
# declaring one would add a candidate with no matching
|
||||
# allocation - the signal a detector running its own TURN reads.
|
||||
# The core reads it in one place only.
|
||||
self._srflx_declared = _geo.srflx_to_declare()
|
||||
# binary_path= never reaches ensure_binary(), so the engine check lives
|
||||
# on the resolved executable rather than inside the fetcher.
|
||||
executable = resolve_executable(self._binary_path)
|
||||
@@ -409,20 +395,18 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
#: session gets refused. Just one would be too strict - a timeout
|
||||
#: happens - but unlimited would be declared blindness: after three
|
||||
#: silent checks at 120s each, that is six minutes in which nobody is
|
||||
#: confirming the address the engine announces on every page.
|
||||
#: confirming that the timezone and the locale still match the egress.
|
||||
_MAX_USCITE_NON_MISURABILI = 3
|
||||
|
||||
def _assert_uscita_invariata(self) -> None:
|
||||
"""Refuses if the egress IP has changed since launch.
|
||||
|
||||
A change mid-session cannot be recovered from: the IP we declare to
|
||||
the engine for the srflx was photographed at launch, so from that
|
||||
moment the page exits from one address and WebRTC announces
|
||||
another - the disagreement detectors look for. Updating it on the
|
||||
fly would not help: it would make the WebRTC IP change under the
|
||||
site's eyes, which is just as unnatural. If the egress does not
|
||||
hold for the session's duration, that proxy is not sticky and is
|
||||
not fit for this purpose.
|
||||
A change mid-session cannot be recovered from: the timezone and the locale were decided from the egress at launch, so
|
||||
from that moment the page exits from one place while they describe
|
||||
another. Updating them on the fly would not help: the site would see
|
||||
them change, which is just as unnatural. If the egress does not hold
|
||||
for the session's duration, that proxy is not sticky and is not fit
|
||||
for this purpose.
|
||||
"""
|
||||
if not self._proxy or not self._webrtc_egress_ip:
|
||||
return
|
||||
@@ -435,10 +419,9 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
if outcome == _session.USCITA_DERIVATA:
|
||||
raise _session.ProxyEgressDrifted(
|
||||
"the proxy's egress IP changed during the session: "
|
||||
"it was %s at launch, now it is %s. The WebRTC srflx "
|
||||
"candidate still declares the first one, so from this "
|
||||
"moment the page exits from one address and WebRTC "
|
||||
"announces another - the disagreement detectors look for. "
|
||||
"it was %s at launch, now it is %s. The timezone and the "
|
||||
"locale still describe the first one, so from this moment "
|
||||
"the page exits from one place and they say another. "
|
||||
"This proxy does not hold the session sticky for the "
|
||||
"required duration: use one that guarantees it, or "
|
||||
"shorten the session."
|
||||
@@ -446,18 +429,18 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
if outcome == _session.USCITA_NON_MISURABILE:
|
||||
# It is NOT "holding", and that is why there are three outcomes.
|
||||
# A probe that fails ONCE is the network; one that always fails
|
||||
# is blindness: from that moment the engine keeps declaring an
|
||||
# address on every page that nobody is confirming anymore. It
|
||||
# is counted, instead of ignored, and refused only if it
|
||||
# is blindness: from that moment the timezone and the locale
|
||||
# stay declared on every page with nobody confirming them against
|
||||
# the egress anymore. It is counted, instead of ignored, and refused only if it
|
||||
# repeats.
|
||||
self._uscite_non_misurabili += 1
|
||||
if self._uscite_non_misurabili >= self._MAX_USCITE_NON_MISURABILI:
|
||||
raise _session.ProxyEgressNonVerificabile(
|
||||
"the egress IP was not verifiable for %d checks in a "
|
||||
"row. It is not drift - the probe did not respond at "
|
||||
"all - but it is not parity either: from here on the "
|
||||
"engine would keep declaring an address on every page "
|
||||
"that nobody confirms anymore. Check that the proxy is "
|
||||
"all - but it is not parity either: from here on "
|
||||
"the timezone and the locale go unconfirmed on every "
|
||||
"page. Check that the proxy is "
|
||||
"reachable, then relaunch the session."
|
||||
% self._uscite_non_misurabili)
|
||||
return
|
||||
@@ -516,11 +499,9 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
# then on.
|
||||
#
|
||||
# Measured 2026-08-25 in a manual session: at launch the egress
|
||||
# was `82.40.95.144` and that is what landed in the srflx; nine
|
||||
# tabs later the page was exiting from `130.12.17.118`, and the
|
||||
# two showed up together on screen - `PUBLIC IP` against
|
||||
# `WEBRTC CLIENT SIDE IP OFFER`. The guard existed, it was
|
||||
# correct, and it was never asked.
|
||||
# was `203.0.113.10`, which the timezone was decided from; nine
|
||||
# tabs later the page was exiting from `203.0.113.20`. The guard
|
||||
# existed, it was correct, and it was never asked.
|
||||
#
|
||||
# The cost stays the same as before: `_assert_uscita_invariata`
|
||||
# limits itself to one check every `_INTERVALLO_CONTROLLO_USCITA_S`,
|
||||
|
||||
@@ -0,0 +1,583 @@
|
||||
"""A DNS-over-HTTPS server and a SOCKS5 gateway that carries the DoH road, for tests that need a real wire.
|
||||
|
||||
Hermetic: loopback only, no DNS, no internet. Nothing here knows about the product.
|
||||
|
||||
What a proxied session declares (core-19) is that every name the browser resolves goes to the DoH of Firefox
|
||||
(``network.trr.mode`` 3), at ``https://mozilla.cloudflare-dns.com/dns-query``, found with no DNS at the address
|
||||
``network.trr.bootstrapAddr`` (162.159.61.4), and that the DoH request is a channel like any other, so it leaves
|
||||
THROUGH the proxy of the context of the lookup. A test of that needs three things this file builds:
|
||||
|
||||
* :class:`FakeDoh` - the DoH server. RFC 8484 (POST ``application/dns-message`` and GET ``?dns=base64url``) over TLS
|
||||
with a certificate for ``mozilla.cloudflare-dns.com`` and ``127.0.0.1``, written by hand: the question is parsed from
|
||||
its labels and the answer is built byte by byte (header, the question copied, one A record, TTL 30). It answers
|
||||
HTTP/2 when the ``h2`` package is importable and ALPN selects it (Firefox's TRR speaks h2), HTTP/1.1 otherwise.
|
||||
Every query is recorded as ``(name, qtype, via)``.
|
||||
* :class:`DohGateway` - a SOCKS5 gateway (the ``Gateway`` of ``_socks_servers``) whose CONNECT to the DoH address
|
||||
(``162.159.61.4:443``, or ``mozilla.cloudflare-dns.com:443`` by name) is handed to the FakeDoh of the test, with the
|
||||
gateway's name as ``via``; every other CONNECT to a loopback address is relayed for real. It never resolves a name
|
||||
itself and never reaches a non-loopback address: a CONNECT that asks for one is refused and recorded, so a test run
|
||||
cannot leak anything and cannot be mistaken for leaking.
|
||||
* the DNS codec (:func:`parse_query`, :func:`build_response`), which the resolver trap of ``_leaks`` reuses.
|
||||
|
||||
``via`` answers "by which road did this query arrive": the name of the gateway that carried the CONNECT, or
|
||||
``"direct"`` for a client that connected to the FakeDoh's own port.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import datetime
|
||||
import ipaddress
|
||||
import socket
|
||||
import ssl
|
||||
import struct
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Callable, Dict, List, NamedTuple, Optional, Set, Tuple
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
from _socks_servers import EXIT, Gateway, WEB_NAME, WHOAMI4, WHOAMI6
|
||||
|
||||
try: # the HTTP/2 side needs it; a test that wants h2 says pytest.importorskip("h2")
|
||||
import h2.config
|
||||
import h2.connection
|
||||
import h2.events
|
||||
import h2.exceptions
|
||||
H2_AVAILABLE = True
|
||||
except ImportError: # pragma: no cover - depends on the environment
|
||||
H2_AVAILABLE = False
|
||||
|
||||
#: The host name of the DoH the session declares, and the address it is found at without DNS.
|
||||
DOH_HOST = "mozilla.cloudflare-dns.com"
|
||||
DOH_BOOTSTRAP = "162.159.61.4"
|
||||
DOH_PORT = 443
|
||||
DOH_PATH = "/dns-query"
|
||||
#: Every CONNECT target the gateways hand to the FakeDoh.
|
||||
DOH_TARGETS = frozenset({(DOH_BOOTSTRAP, DOH_PORT), (DOH_HOST, DOH_PORT)})
|
||||
|
||||
QTYPE_A, QTYPE_AAAA = 1, 28
|
||||
RCODE_OK, RCODE_NXDOMAIN, RCODE_REFUSED = 0, 3, 5
|
||||
DOH_TTL = 30
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------- DNS codec
|
||||
class Query(NamedTuple):
|
||||
ident: int
|
||||
flags: int
|
||||
name: str # lower case, no trailing dot
|
||||
qtype: int
|
||||
qclass: int
|
||||
question: bytes # the question section as it came, to be copied into the answer
|
||||
|
||||
|
||||
def parse_query(msg: bytes) -> Query:
|
||||
"""The first (and only) question of a DNS message. Raises ``ValueError`` on anything that is not one."""
|
||||
try:
|
||||
ident, flags, qdcount, _an, _ns, _ar = struct.unpack("!6H", msg[:12])
|
||||
if qdcount != 1:
|
||||
raise ValueError("expected one question, got %d" % qdcount)
|
||||
i, labels = 12, []
|
||||
while True:
|
||||
length = msg[i]
|
||||
i += 1
|
||||
if length == 0:
|
||||
break
|
||||
if length & 0xC0:
|
||||
raise ValueError("a compressed name in the question")
|
||||
labels.append(msg[i:i + length].decode("ascii"))
|
||||
i += length
|
||||
qtype, qclass = struct.unpack("!HH", msg[i:i + 4]) # struct.error when truncated
|
||||
i += 4
|
||||
except (IndexError, struct.error, UnicodeDecodeError) as exc:
|
||||
raise ValueError("not a DNS query: %s" % exc) from None
|
||||
return Query(ident, flags, ".".join(labels).lower(), qtype, qclass, msg[12:i])
|
||||
|
||||
|
||||
def build_response(query: Query, rcode: int = RCODE_OK, answers: Tuple[Tuple[int, bytes], ...] = ()) -> bytes:
|
||||
"""A response to ``query``: QR+RA, the RD bit copied, ``rcode``, the question copied, one record per
|
||||
``(type, rdata)`` with the name as a pointer to the question and TTL 30."""
|
||||
flags = 0x8000 | (query.flags & 0x0100) | 0x0080 | (rcode & 0xF)
|
||||
out = struct.pack("!6H", query.ident, flags, 1, len(answers), 0, 0) + query.question
|
||||
for rtype, rdata in answers:
|
||||
out += struct.pack("!HHHIH", 0xC00C, rtype, 1, DOH_TTL, len(rdata)) + rdata
|
||||
return out
|
||||
|
||||
|
||||
def encode_query(name: str, qtype: int = QTYPE_A, ident: int = 0) -> bytes:
|
||||
"""A query message (RD set), the way a client builds it."""
|
||||
labels = b"".join(bytes([len(p)]) + p.encode("ascii") for p in name.rstrip(".").split(".") if p)
|
||||
return struct.pack("!6H", ident, 0x0100, 1, 0, 0, 0) + labels + b"\x00" + struct.pack("!HH", qtype, 1)
|
||||
|
||||
|
||||
def answer_for(names: Dict[str, str], query: Query) -> bytes:
|
||||
"""The response a zone made of ``names`` (name -> address) gives: A for an IPv4 value, AAAA for an IPv6 one,
|
||||
NOERROR with no answer for any other type of a known name, NXDOMAIN for an unknown name."""
|
||||
value = names.get(query.name)
|
||||
if value is None:
|
||||
return build_response(query, RCODE_NXDOMAIN)
|
||||
address = ipaddress.ip_address(value)
|
||||
if query.qtype == QTYPE_A and address.version == 4:
|
||||
return build_response(query, RCODE_OK, ((QTYPE_A, address.packed),))
|
||||
if query.qtype == QTYPE_AAAA and address.version == 6:
|
||||
return build_response(query, RCODE_OK, ((QTYPE_AAAA, address.packed),))
|
||||
return build_response(query, RCODE_OK)
|
||||
|
||||
|
||||
def wait_until(predicate: Callable[[], object], timeout: float, step: float = 0.05) -> bool:
|
||||
"""True as soon as ``predicate()`` is truthy, False after ``timeout`` seconds."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
if predicate():
|
||||
return True
|
||||
if time.monotonic() >= deadline:
|
||||
return False
|
||||
time.sleep(step)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------------ certificate
|
||||
def make_certificate(directory: Path, dns_names: Tuple[str, ...] = (DOH_HOST,),
|
||||
ip_addresses: Tuple[str, ...] = ("127.0.0.1",)) -> Tuple[Path, Path]:
|
||||
"""A self-signed certificate (EC P-256, 30 days) whose SAN covers ``dns_names`` and ``ip_addresses``.
|
||||
Returns (certificate path, key path), both PEM."""
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.x509.oid import NameOID
|
||||
|
||||
key = ec.generate_private_key(ec.SECP256R1())
|
||||
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, dns_names[0] if dns_names else ip_addresses[0])])
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
san = [x509.DNSName(n) for n in dns_names] + [x509.IPAddress(ipaddress.ip_address(a)) for a in ip_addresses]
|
||||
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key())
|
||||
.serial_number(x509.random_serial_number()).not_valid_before(now - datetime.timedelta(days=1))
|
||||
.not_valid_after(now + datetime.timedelta(days=30))
|
||||
.add_extension(x509.SubjectAlternativeName(san), critical=False)
|
||||
.sign(key, hashes.SHA256()))
|
||||
cert_path, key_path = directory / "doh-cert.pem", directory / "doh-key.pem"
|
||||
cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
|
||||
key_path.write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
|
||||
serialization.NoEncryption()))
|
||||
return cert_path, key_path
|
||||
|
||||
|
||||
_REASONS = {200: "OK", 400: "Bad Request", 404: "Not Found", 405: "Method Not Allowed",
|
||||
415: "Unsupported Media Type"}
|
||||
|
||||
|
||||
class DohQuery(NamedTuple):
|
||||
name: str
|
||||
qtype: int
|
||||
via: str
|
||||
|
||||
|
||||
class FakeDoh:
|
||||
"""A DoH server on 127.0.0.1 (its own port, ``via`` ``"direct"``) that also serves any socket a gateway hands it.
|
||||
|
||||
``names`` maps a name to the address it resolves to; it can be changed while the server runs. ``h2=False`` makes
|
||||
it offer HTTP/1.1 only (the way to test that a client falls back), ``h2=True`` is the default when the ``h2``
|
||||
package is importable.
|
||||
"""
|
||||
|
||||
def __init__(self, names: Optional[Dict[str, str]] = None, *, h2: Optional[bool] = None):
|
||||
self.names: Dict[str, str] = {k.lower(): v for k, v in (names or {}).items()}
|
||||
self.offers_h2 = H2_AVAILABLE if h2 is None else (h2 and H2_AVAILABLE)
|
||||
#: Every query, in order.
|
||||
self.queries: List[DohQuery] = []
|
||||
#: Every TLS connection served: (via, negotiated protocol).
|
||||
self.connections: List[Tuple[str, str]] = []
|
||||
#: The TLS handshakes that did not complete (a client that refused the certificate): (via, error).
|
||||
self.tls_failures: List[Tuple[str, str]] = []
|
||||
#: Every HTTP request that was not a well-formed DoH query: (via, method, target, status).
|
||||
self.bad_requests: List[Tuple[str, str, str, int]] = []
|
||||
self._lock = threading.Lock()
|
||||
self._open: List[Tuple[str, ssl.SSLSocket]] = []
|
||||
self._dir = tempfile.TemporaryDirectory()
|
||||
self.certificate_path, self._key_path = make_certificate(Path(self._dir.name))
|
||||
self._context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
self._context.load_cert_chain(str(self.certificate_path), str(self._key_path))
|
||||
self._context.set_alpn_protocols(["h2", "http/1.1"] if self.offers_h2 else ["http/1.1"])
|
||||
self._listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
self._listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
self._listener.bind(("127.0.0.1", 0))
|
||||
self._listener.listen(32)
|
||||
self.port: int = self._listener.getsockname()[1]
|
||||
self._closed = False
|
||||
threading.Thread(target=self._accept, daemon=True).start()
|
||||
|
||||
# --- what a test reads ------------------------------------------------------------------------------------
|
||||
def queries_for(self, name: str, qtype: Optional[int] = None) -> List[DohQuery]:
|
||||
name = name.lower().rstrip(".")
|
||||
with self._lock:
|
||||
return [q for q in self.queries if q.name == name and (qtype is None or q.qtype == qtype)]
|
||||
|
||||
def vias_of(self, name: str, qtype: Optional[int] = None) -> Set[str]:
|
||||
"""The set of roads (gateway names) a name was asked by."""
|
||||
return {q.via for q in self.queries_for(name, qtype)}
|
||||
|
||||
def seen_names(self) -> List[str]:
|
||||
with self._lock:
|
||||
return sorted({q.name for q in self.queries})
|
||||
|
||||
def alpn_of(self, via: str) -> Set[str]:
|
||||
with self._lock:
|
||||
return {proto for v, proto in self.connections if v == via}
|
||||
|
||||
# --- serving ----------------------------------------------------------------------------------------------
|
||||
def _accept(self) -> None:
|
||||
while not self._closed:
|
||||
try:
|
||||
conn, _ = self._listener.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self.serve, args=(conn, "direct"), daemon=True).start()
|
||||
|
||||
def serve(self, sock: socket.socket, via: str) -> None:
|
||||
"""Serve one connection (TLS first) that arrived by ``via``. Blocks until it ends, and closes ``sock``."""
|
||||
try:
|
||||
sock.settimeout(60)
|
||||
tls = self._context.wrap_socket(sock, server_side=True)
|
||||
except (ssl.SSLError, OSError) as exc:
|
||||
with self._lock:
|
||||
self.tls_failures.append((via, "%s: %s" % (type(exc).__name__, exc)))
|
||||
try:
|
||||
sock.close()
|
||||
except OSError:
|
||||
pass
|
||||
return
|
||||
protocol = tls.selected_alpn_protocol() or "http/1.1"
|
||||
with self._lock:
|
||||
self.connections.append((via, protocol))
|
||||
self._open.append((via, tls))
|
||||
try:
|
||||
if protocol == "h2":
|
||||
self._serve_h2(tls, via)
|
||||
else:
|
||||
self._serve_h1(tls, via)
|
||||
except (OSError, ssl.SSLError, ValueError, KeyError):
|
||||
pass
|
||||
except Exception as exc: # noqa: BLE001 - an h2 protocol error ends the connection like a reset
|
||||
if not (H2_AVAILABLE and isinstance(exc, h2.exceptions.H2Error)):
|
||||
raise
|
||||
finally:
|
||||
with self._lock:
|
||||
self._open = [(v, s) for v, s in self._open if s is not tls]
|
||||
try:
|
||||
tls.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def drop(self, via: Optional[str] = None) -> int:
|
||||
"""Close every open connection that arrived by ``via`` (all of them when None). Returns how many."""
|
||||
with self._lock:
|
||||
victims = [s for v, s in self._open if via is None or v == via]
|
||||
for s in victims:
|
||||
for action in (lambda: s.shutdown(socket.SHUT_RDWR), s.close):
|
||||
try:
|
||||
action()
|
||||
except OSError:
|
||||
pass
|
||||
return len(victims)
|
||||
|
||||
def _answer(self, via: str, method: str, target: str, content_type: str,
|
||||
body: bytes) -> Tuple[int, bytes, str]:
|
||||
"""(status, body, content type) of one HTTP request, recording the DNS query it carries."""
|
||||
def bad(status: int) -> Tuple[int, bytes, str]:
|
||||
with self._lock:
|
||||
self.bad_requests.append((via, method, target, status))
|
||||
return status, b"", "text/plain"
|
||||
|
||||
split = urlsplit(target)
|
||||
if split.path != DOH_PATH:
|
||||
return bad(404)
|
||||
if method == "POST":
|
||||
if content_type.split(";")[0].strip().lower() != "application/dns-message":
|
||||
return bad(415)
|
||||
message = body
|
||||
elif method == "GET":
|
||||
values = parse_qs(split.query).get("dns")
|
||||
if not values:
|
||||
return bad(400)
|
||||
try:
|
||||
message = base64.urlsafe_b64decode(values[0] + "=" * (-len(values[0]) % 4))
|
||||
except ValueError:
|
||||
return bad(400)
|
||||
else:
|
||||
return bad(405)
|
||||
try:
|
||||
query = parse_query(message)
|
||||
except ValueError:
|
||||
return bad(400)
|
||||
with self._lock:
|
||||
self.queries.append(DohQuery(query.name, query.qtype, via))
|
||||
names = dict(self.names)
|
||||
return 200, answer_for(names, query), "application/dns-message"
|
||||
|
||||
def _serve_h1(self, tls: ssl.SSLSocket, via: str) -> None:
|
||||
buffer = b""
|
||||
while True:
|
||||
while b"\r\n\r\n" not in buffer:
|
||||
chunk = tls.recv(65536)
|
||||
if not chunk:
|
||||
return
|
||||
buffer += chunk
|
||||
head, _, buffer = buffer.partition(b"\r\n\r\n")
|
||||
lines = head.decode("latin-1").split("\r\n")
|
||||
method, target, _version = lines[0].split(" ", 2)
|
||||
headers = {}
|
||||
for line in lines[1:]:
|
||||
key, _, value = line.partition(":")
|
||||
headers[key.strip().lower()] = value.strip()
|
||||
length = int(headers.get("content-length", "0"))
|
||||
while len(buffer) < length:
|
||||
chunk = tls.recv(65536)
|
||||
if not chunk:
|
||||
return
|
||||
buffer += chunk
|
||||
body, buffer = buffer[:length], buffer[length:]
|
||||
status, payload, content_type = self._answer(via, method, target, headers.get("content-type", ""), body)
|
||||
close = headers.get("connection", "").lower() == "close"
|
||||
tls.sendall(("HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %d\r\nCache-Control: max-age=%d\r\n"
|
||||
"%s\r\n" % (status, _REASONS.get(status, "Status"), content_type, len(payload), DOH_TTL,
|
||||
"Connection: close\r\n" if close else "")).encode("latin-1") + payload)
|
||||
if close:
|
||||
return
|
||||
|
||||
def _serve_h2(self, tls: ssl.SSLSocket, via: str) -> None:
|
||||
connection = h2.connection.H2Connection(
|
||||
config=h2.config.H2Configuration(client_side=False, header_encoding="utf-8"))
|
||||
connection.initiate_connection()
|
||||
tls.sendall(connection.data_to_send())
|
||||
streams: Dict[int, dict] = {}
|
||||
while True:
|
||||
data = tls.recv(65536)
|
||||
if not data:
|
||||
return
|
||||
for event in connection.receive_data(data):
|
||||
if isinstance(event, h2.events.RequestReceived):
|
||||
streams[event.stream_id] = {"headers": dict(event.headers), "body": b""}
|
||||
elif isinstance(event, h2.events.DataReceived):
|
||||
streams[event.stream_id]["body"] += event.data
|
||||
connection.acknowledge_received_data(event.flow_controlled_length, event.stream_id)
|
||||
elif isinstance(event, h2.events.StreamEnded):
|
||||
request = streams.pop(event.stream_id)
|
||||
headers = request["headers"]
|
||||
status, payload, content_type = self._answer(
|
||||
via, headers.get(":method", ""), headers.get(":path", ""),
|
||||
headers.get("content-type", ""), request["body"])
|
||||
connection.send_headers(event.stream_id, [
|
||||
(":status", str(status)), ("content-type", content_type),
|
||||
("content-length", str(len(payload))), ("cache-control", "max-age=%d" % DOH_TTL)])
|
||||
connection.send_data(event.stream_id, payload, end_stream=True)
|
||||
elif isinstance(event, h2.events.StreamReset):
|
||||
streams.pop(event.stream_id, None)
|
||||
elif isinstance(event, h2.events.ConnectionTerminated):
|
||||
return
|
||||
pending = connection.data_to_send()
|
||||
if pending:
|
||||
tls.sendall(pending)
|
||||
|
||||
def close(self) -> None:
|
||||
self._closed = True
|
||||
try:
|
||||
self._listener.close()
|
||||
except OSError:
|
||||
pass
|
||||
self.drop()
|
||||
try:
|
||||
self._dir.cleanup()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def __enter__(self) -> "FakeDoh":
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self.close()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------- relaying
|
||||
def pump(source: socket.socket, sink: socket.socket) -> None:
|
||||
"""Copy bytes from ``source`` to ``sink`` until either ends, then shut both."""
|
||||
try:
|
||||
while True:
|
||||
data = source.recv(65536)
|
||||
if not data:
|
||||
break
|
||||
sink.sendall(data)
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
for s in (source, sink):
|
||||
try:
|
||||
s.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def relay(a: socket.socket, b: socket.socket) -> None:
|
||||
"""Carry bytes both ways between two connected sockets until one ends. Blocks."""
|
||||
a.settimeout(None)
|
||||
b.settimeout(None)
|
||||
thread = threading.Thread(target=pump, args=(b, a), daemon=True)
|
||||
thread.start()
|
||||
pump(a, b)
|
||||
thread.join(timeout=2)
|
||||
|
||||
|
||||
def is_loopback(host: str) -> bool:
|
||||
"""True for a loopback ADDRESS. A name is never loopback here: nothing in these helpers resolves a name."""
|
||||
try:
|
||||
return ipaddress.ip_address(host).is_loopback
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
class DohGateway(Gateway):
|
||||
"""A SOCKS5 gateway of ``_socks_servers`` that carries the DoH road to a :class:`FakeDoh`.
|
||||
|
||||
* CONNECT to ``DOH_TARGETS`` is served by ``doh`` with ``via=name``;
|
||||
* CONNECT to a loopback address is relayed for real (the pages and the echo servers of a test);
|
||||
* the egress endpoints of the base class (``api.ipify.org:80``) keep working;
|
||||
* any other CONNECT is refused (reply 2 "not allowed", for an address; 4 "host unreachable", for a name) and
|
||||
listed in :attr:`refused`: the gateway never resolves a name and never reaches past the loopback.
|
||||
|
||||
:attr:`connects` (inherited) lists EVERY CONNECT target in order, so ``("page-a.test", 80)`` in it means the
|
||||
browser sent a name where it should have sent an address. :attr:`credentials_seen` lists every
|
||||
username/password offered, ``first_connection_delay`` holds the first accepted connection that many seconds
|
||||
before it is answered (a gateway that is slow to say hello), and :meth:`kill` makes the gateway dead: the port
|
||||
refuses, and every open tunnel is closed.
|
||||
"""
|
||||
|
||||
def __init__(self, name: str, doh: FakeDoh, *, user: Optional[str] = None, password: Optional[str] = None,
|
||||
first_connection_delay: float = 0.0):
|
||||
# State first: the base constructor starts the accept thread.
|
||||
self.name = name
|
||||
self.doh = doh
|
||||
self.first_connection_delay = first_connection_delay
|
||||
#: Every (username, password) a client offered.
|
||||
self.credentials_seen: List[Tuple[str, str]] = []
|
||||
#: Every CONNECT that was refused: (host, port).
|
||||
self.refused: List[Tuple[str, int]] = []
|
||||
#: How many connections were accepted, and the monotonic time of each.
|
||||
self.accepted_at: List[float] = []
|
||||
self.killed = False
|
||||
self._live: List[socket.socket] = []
|
||||
self._live_lock = threading.Lock()
|
||||
super().__init__(udp="refuse", tcp_exit=EXIT, udp_exit=EXIT, user=user, password=password)
|
||||
|
||||
# --- accepting, and the slow first hello ---------------------------------------------------------------------
|
||||
def _handle(self, c: socket.socket) -> None:
|
||||
with self._live_lock:
|
||||
self.accepted_at.append(time.monotonic())
|
||||
first = len(self.accepted_at) == 1
|
||||
self._live.append(c)
|
||||
if first and self.first_connection_delay:
|
||||
time.sleep(self.first_connection_delay)
|
||||
super()._handle(c)
|
||||
|
||||
def _greet(self, c: socket.socket) -> bool:
|
||||
"""The base negotiation, recording the credentials a client sent."""
|
||||
ver, n = _recv_exact(c, 2)
|
||||
methods = _recv_exact(c, n)
|
||||
if ver != 5:
|
||||
return False
|
||||
if self.user is not None:
|
||||
if 2 not in methods:
|
||||
self._send(c, b"\x05\xff")
|
||||
return False
|
||||
self._send(c, b"\x05\x02")
|
||||
_recv_exact(c, 1)
|
||||
offered = (_recv_exact(c, _recv_exact(c, 1)[0]).decode("utf-8", "replace"),
|
||||
_recv_exact(c, _recv_exact(c, 1)[0]).decode("utf-8", "replace"))
|
||||
self.credentials_seen.append(offered)
|
||||
ok = offered == (self.user, self.password)
|
||||
self._send(c, b"\x01" + (b"\x00" if ok else b"\x01"))
|
||||
return ok
|
||||
self._send(c, b"\x05\x00" if 0 in methods else b"\x05\x02")
|
||||
if 0 not in methods: # a client that only offers user/password: accept any
|
||||
_recv_exact(c, 1)
|
||||
offered = (_recv_exact(c, _recv_exact(c, 1)[0]).decode("utf-8", "replace"),
|
||||
_recv_exact(c, _recv_exact(c, 1)[0]).decode("utf-8", "replace"))
|
||||
self.credentials_seen.append(offered)
|
||||
self._send(c, b"\x01\x00")
|
||||
return True
|
||||
|
||||
# --- CONNECT ---------------------------------------------------------------------------------------------------
|
||||
def _connect(self, c: socket.socket, host: str, port: int) -> None:
|
||||
if (host, port) in DOH_TARGETS:
|
||||
self.connects.append((host, port))
|
||||
self._send(c, self._reply(0))
|
||||
self.doh.serve(c, self.name)
|
||||
return
|
||||
if (host, port) in (WHOAMI4, WHOAMI6, (WEB_NAME, 80)):
|
||||
super()._connect(c, host, port)
|
||||
return
|
||||
if not is_loopback(host):
|
||||
self.connects.append((host, port))
|
||||
self.refused.append((host, port))
|
||||
self._send(c, self._reply(2 if _is_address(host) else 4))
|
||||
return
|
||||
self.connects.append((host, port))
|
||||
try:
|
||||
upstream = socket.create_connection((host, port), timeout=10)
|
||||
except OSError:
|
||||
self._send(c, self._reply(5))
|
||||
return
|
||||
with self._live_lock:
|
||||
self._live.append(upstream)
|
||||
self._send(c, self._reply(0))
|
||||
try:
|
||||
relay(c, upstream)
|
||||
finally:
|
||||
upstream.close()
|
||||
|
||||
# --- the DoH road, by CONNECT target --------------------------------------------------------------------------
|
||||
def doh_connects(self) -> List[Tuple[str, int]]:
|
||||
return [t for t in self.connects if t in DOH_TARGETS]
|
||||
|
||||
def kill(self) -> None:
|
||||
"""Dead proxy: the port refuses new connections and every tunnel that was open is closed."""
|
||||
self.killed = True
|
||||
# shutdown() first: on Linux, close() alone leaves a listening socket open (and accepting) while another
|
||||
# thread is blocked in accept() on it, so the "dead" proxy would still take connections.
|
||||
try:
|
||||
self._listener.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:
|
||||
pass
|
||||
self.close()
|
||||
self.doh.drop(self.name)
|
||||
with self._live_lock:
|
||||
sockets, self._live = self._live, []
|
||||
for s in sockets:
|
||||
for action in (lambda: s.shutdown(socket.SHUT_RDWR), s.close):
|
||||
try:
|
||||
action()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _is_address(host: str) -> bool:
|
||||
try:
|
||||
ipaddress.ip_address(host)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def _recv_exact(s: socket.socket, n: int) -> bytes:
|
||||
data = b""
|
||||
while len(data) < n:
|
||||
chunk = s.recv(n - len(data))
|
||||
if not chunk:
|
||||
raise ConnectionError("closed")
|
||||
data += chunk
|
||||
return data
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DOH_BOOTSTRAP", "DOH_HOST", "DOH_PATH", "DOH_PORT", "DOH_TARGETS", "DOH_TTL", "H2_AVAILABLE", "QTYPE_A",
|
||||
"QTYPE_AAAA", "RCODE_NXDOMAIN", "RCODE_OK", "RCODE_REFUSED", "DohGateway", "DohQuery", "FakeDoh", "Query",
|
||||
"answer_for", "build_response", "encode_query", "is_loopback", "make_certificate", "parse_query", "pump",
|
||||
"relay", "wait_until",
|
||||
]
|
||||
@@ -0,0 +1,158 @@
|
||||
"""A local HTTPS server that speaks HTTP/3 as well, reached by its address.
|
||||
|
||||
The same port answers TCP (TLS, HTTP/1.1, with an `Alt-Svc: h3` header) and UDP (QUIC, HTTP/3, aioquic), with a self-signed
|
||||
certificate for the address it is given. It records, for every QUIC connection, the address the packets came from: a
|
||||
connection that comes from anywhere but the relay of a gateway on this host (127.0.0.1) did not go through the proxy.
|
||||
|
||||
Needs `aioquic` (pip install aioquic); a test that wants it imports it with `pytest.importorskip`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import datetime
|
||||
import http.server
|
||||
import ipaddress
|
||||
import socket
|
||||
import ssl
|
||||
import tempfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
|
||||
def _certificate(address: str, directory: Path):
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.x509.oid import NameOID
|
||||
|
||||
key = ec.generate_private_key(ec.SECP256R1())
|
||||
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, address)])
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key())
|
||||
.serial_number(x509.random_serial_number()).not_valid_before(now - datetime.timedelta(days=1))
|
||||
.not_valid_after(now + datetime.timedelta(days=30))
|
||||
.add_extension(x509.SubjectAlternativeName([x509.IPAddress(ipaddress.ip_address(address))]), critical=False)
|
||||
.sign(key, hashes.SHA256()))
|
||||
cert_path, key_path = directory / "cert.pem", directory / "key.pem"
|
||||
cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
|
||||
key_path.write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
|
||||
serialization.NoEncryption()))
|
||||
return cert_path, key_path
|
||||
|
||||
|
||||
class H3Server:
|
||||
"""TCP+TLS and QUIC on one port of `address`."""
|
||||
|
||||
def __init__(self, address: str):
|
||||
from aioquic.asyncio import serve
|
||||
from aioquic.asyncio.protocol import QuicConnectionProtocol
|
||||
from aioquic.h3.connection import H3_ALPN, H3Connection
|
||||
from aioquic.h3.events import HeadersReceived
|
||||
from aioquic.quic.configuration import QuicConfiguration
|
||||
from aioquic.quic.events import ProtocolNegotiated
|
||||
|
||||
self.address = address
|
||||
#: The address each QUIC connection came from.
|
||||
self.quic_peers: List[str] = []
|
||||
#: The paths of the requests that were answered over HTTP/3, and over TCP.
|
||||
self.h3_requests: List[str] = []
|
||||
self.tcp_requests: List[str] = []
|
||||
self._dir = tempfile.TemporaryDirectory()
|
||||
cert, key = _certificate(address, Path(self._dir.name))
|
||||
|
||||
server = self
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
timeout = 5
|
||||
|
||||
def do_GET(self):
|
||||
server.tcp_requests.append(self.path)
|
||||
body = b"tcp ok"
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/plain")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Alt-Svc", 'h3=":%d"; ma=3600' % server.port)
|
||||
self.send_header("Access-Control-Allow-Origin", "*")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
# One port for both: the TCP port first, then the same number for UDP.
|
||||
for _ in range(50):
|
||||
tcp = http.server.ThreadingHTTPServer((address, 0), Handler)
|
||||
port = tcp.server_address[1]
|
||||
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
probe.bind((address, port))
|
||||
probe.close()
|
||||
break
|
||||
except OSError:
|
||||
probe.close()
|
||||
tcp.server_close()
|
||||
else:
|
||||
raise RuntimeError("no port free for both TCP and UDP")
|
||||
self.port = port
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.load_cert_chain(str(cert), str(key))
|
||||
context.set_alpn_protocols(["http/1.1"])
|
||||
tcp.socket = context.wrap_socket(tcp.socket, server_side=True)
|
||||
tcp.daemon_threads = True
|
||||
self._tcp = tcp
|
||||
threading.Thread(target=tcp.serve_forever, daemon=True).start()
|
||||
|
||||
class Protocol(QuicConnectionProtocol):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self._http = None
|
||||
|
||||
def quic_event_received(self, event):
|
||||
if isinstance(event, ProtocolNegotiated):
|
||||
self._http = H3Connection(self._quic)
|
||||
server.quic_peers.append(self._quic._network_paths[0].addr[0])
|
||||
if self._http is not None:
|
||||
for http_event in self._http.handle_event(event):
|
||||
if isinstance(http_event, HeadersReceived):
|
||||
headers = dict(http_event.headers)
|
||||
server.h3_requests.append(headers.get(b":path", b"").decode())
|
||||
self._http.send_headers(http_event.stream_id, [
|
||||
(b":status", b"200"), (b"content-type", b"text/plain"),
|
||||
(b"access-control-allow-origin", b"*")])
|
||||
self._http.send_data(http_event.stream_id, b"h3 ok", end_stream=True)
|
||||
self.transmit()
|
||||
|
||||
configuration = QuicConfiguration(is_client=False, alpn_protocols=H3_ALPN)
|
||||
configuration.load_cert_chain(str(cert), str(key))
|
||||
self._loop = asyncio.new_event_loop()
|
||||
started = threading.Event()
|
||||
|
||||
def run():
|
||||
asyncio.set_event_loop(self._loop)
|
||||
self._quic = self._loop.run_until_complete(
|
||||
serve(address, port, configuration=configuration, create_protocol=Protocol))
|
||||
started.set()
|
||||
self._loop.run_forever()
|
||||
|
||||
threading.Thread(target=run, daemon=True).start()
|
||||
if not started.wait(10):
|
||||
raise RuntimeError("the QUIC server did not start")
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
return "https://%s:%d/" % (self.address, self.port)
|
||||
|
||||
def close(self) -> None:
|
||||
self._tcp.shutdown()
|
||||
self._tcp.server_close()
|
||||
self._quic.close()
|
||||
self._loop.call_soon_threadsafe(self._loop.stop)
|
||||
self._dir.cleanup()
|
||||
|
||||
def __enter__(self) -> "H3Server":
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self.close()
|
||||
@@ -0,0 +1,234 @@
|
||||
"""An HTTP proxy on 127.0.0.1 that asks for credentials, and carries the DoH road to a :class:`FakeDoh`.
|
||||
|
||||
The counterpart of :class:`_doh_servers.DohGateway` for the ``http`` scheme:
|
||||
|
||||
* a request without a valid ``Proxy-Authorization: Basic`` gets ``407`` with ``Proxy-Authenticate: Basic`` (the
|
||||
connection is closed, as many real proxies do); the right credentials get through;
|
||||
* ``CONNECT`` to the DoH address (``162.159.61.4:443`` or ``mozilla.cloudflare-dns.com:443``) is answered ``200``
|
||||
and handed to the FakeDoh with ``via=name``; ``CONNECT`` to a loopback address is relayed for real; any other
|
||||
CONNECT is refused (``403``) and recorded;
|
||||
* a plain ``GET http://host:port/path`` (the form a browser sends to an HTTP proxy for an ``http`` page: the NAME
|
||||
travels to the proxy, the proxy is the one that resolves it) is forwarded for real to a loopback address. The
|
||||
proxy "resolves" the name with the zone of the FakeDoh (``doh.names``) and never asks any other resolver; a name
|
||||
that is not in the zone answers ``502``. That is the exit's own resolution, and it is why a page behind an HTTP
|
||||
proxy does NOT make the browser ask DoH for its name: something else must (an ICE server name does);
|
||||
* every request is recorded in :attr:`seen` with the ``Proxy-Authorization`` header it carried and the status given.
|
||||
|
||||
Hermetic: nothing leaves the loopback and no name is resolved by the operating system.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import socket
|
||||
import threading
|
||||
from typing import Dict, List, NamedTuple, Optional, Tuple
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from _doh_servers import DOH_TARGETS, FakeDoh, is_loopback, relay
|
||||
|
||||
_REASONS = {200: "Connection Established", 403: "Forbidden", 405: "Method Not Allowed",
|
||||
407: "Proxy Authentication Required", 502: "Bad Gateway"}
|
||||
|
||||
|
||||
def basic(user: str, password: str) -> str:
|
||||
"""The ``Proxy-Authorization`` value of Basic credentials (UTF-8, RFC 7617)."""
|
||||
return "Basic " + base64.b64encode(("%s:%s" % (user, password)).encode("utf-8")).decode("ascii")
|
||||
|
||||
|
||||
class Seen(NamedTuple):
|
||||
method: str
|
||||
host: str
|
||||
port: int
|
||||
#: The Proxy-Authorization header as it came, None when the request had none.
|
||||
authorization: Optional[str]
|
||||
status: int
|
||||
|
||||
|
||||
class HttpProxy:
|
||||
"""See the module docstring. ``user=None`` means no authentication is asked."""
|
||||
|
||||
def __init__(self, name: str, doh: FakeDoh, *, user: Optional[str] = None, password: Optional[str] = None):
|
||||
self.name = name
|
||||
self.doh = doh
|
||||
self.user, self.password = user, password
|
||||
#: Every request, in order.
|
||||
self.seen: List[Seen] = []
|
||||
self._lock = threading.Lock()
|
||||
self._listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
self._listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
self._listener.bind(("127.0.0.1", 0))
|
||||
self._listener.listen(32)
|
||||
self.port: int = self._listener.getsockname()[1]
|
||||
self._closed = False
|
||||
threading.Thread(target=self._accept, daemon=True).start()
|
||||
|
||||
# --- what the test hands to the product ---------------------------------------------------------------------
|
||||
@property
|
||||
def server(self) -> str:
|
||||
return "http://127.0.0.1:%d" % self.port
|
||||
|
||||
@property
|
||||
def proxy(self) -> dict:
|
||||
"""The endpoint dict the core takes: ``{"server": ..., [username, password]}``."""
|
||||
out = {"server": self.server}
|
||||
if self.user is not None:
|
||||
out.update(username=self.user, password=self.password)
|
||||
return out
|
||||
|
||||
@property
|
||||
def expected_authorization(self) -> Optional[str]:
|
||||
return basic(self.user, self.password) if self.user is not None else None
|
||||
|
||||
# --- what the test reads ------------------------------------------------------------------------------------
|
||||
@property
|
||||
def connects(self) -> List[Tuple[str, int]]:
|
||||
"""The targets of the CONNECTs that were accepted, in order."""
|
||||
with self._lock:
|
||||
return [(s.host, s.port) for s in self.seen if s.method == "CONNECT" and s.status == 200]
|
||||
|
||||
@property
|
||||
def refused_for_credentials(self) -> List[Seen]:
|
||||
with self._lock:
|
||||
return [s for s in self.seen if s.status == 407]
|
||||
|
||||
def authorizations_for(self, host: str, port: int) -> List[Optional[str]]:
|
||||
"""The Proxy-Authorization of every CONNECT to ``host:port`` (the DoH address, for instance)."""
|
||||
with self._lock:
|
||||
return [s.authorization for s in self.seen if s.method == "CONNECT" and (s.host, s.port) == (host, port)]
|
||||
|
||||
def doh_authorizations(self) -> List[Optional[str]]:
|
||||
with self._lock:
|
||||
return [s.authorization for s in self.seen if s.method == "CONNECT" and (s.host, s.port) in DOH_TARGETS]
|
||||
|
||||
def doh_connects(self) -> List[Tuple[str, int]]:
|
||||
return [t for t in self.connects if t in DOH_TARGETS]
|
||||
|
||||
# --- serving ------------------------------------------------------------------------------------------------
|
||||
def close(self) -> None:
|
||||
self._closed = True
|
||||
try:
|
||||
self._listener.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def __enter__(self) -> "HttpProxy":
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self.close()
|
||||
|
||||
def _accept(self) -> None:
|
||||
while not self._closed:
|
||||
try:
|
||||
conn, _ = self._listener.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self._handle, args=(conn,), daemon=True).start()
|
||||
|
||||
@staticmethod
|
||||
def _answer(conn: socket.socket, status: int, extra: str = "") -> None:
|
||||
conn.sendall(("HTTP/1.1 %d %s\r\n%sContent-Length: 0\r\n%s\r\n" % (
|
||||
status, _REASONS.get(status, "Status"), extra,
|
||||
"Connection: close\r\n" if status != 200 else "")).encode("latin-1"))
|
||||
|
||||
def _record(self, method: str, host: str, port: int, authorization: Optional[str], status: int) -> None:
|
||||
with self._lock:
|
||||
self.seen.append(Seen(method, host, port, authorization, status))
|
||||
|
||||
def _handle(self, conn: socket.socket) -> None:
|
||||
try:
|
||||
conn.settimeout(30)
|
||||
data = b""
|
||||
while b"\r\n\r\n" not in data:
|
||||
chunk = conn.recv(65536)
|
||||
if not chunk:
|
||||
return
|
||||
data += chunk
|
||||
head, _, rest = data.partition(b"\r\n\r\n")
|
||||
lines = head.decode("latin-1").split("\r\n")
|
||||
method, target, _version = lines[0].split(" ", 2)
|
||||
headers: Dict[str, str] = {}
|
||||
for line in lines[1:]:
|
||||
key, _, value = line.partition(":")
|
||||
headers[key.strip().lower()] = value.strip()
|
||||
authorization = headers.get("proxy-authorization")
|
||||
if method == "CONNECT":
|
||||
host, _, port_text = target.rpartition(":")
|
||||
host, port = host.strip("[]"), int(port_text)
|
||||
else:
|
||||
split = urlsplit(target)
|
||||
host, port = split.hostname or "", split.port or 80
|
||||
if self.user is not None and authorization != self.expected_authorization:
|
||||
self._record(method, host, port, authorization, 407)
|
||||
self._answer(conn, 407, 'Proxy-Authenticate: Basic realm="invisible"\r\n')
|
||||
return
|
||||
if method == "CONNECT":
|
||||
self._connect(conn, host, port, authorization)
|
||||
elif method == "GET":
|
||||
self._forward(conn, host, port, authorization, split, headers, rest)
|
||||
else:
|
||||
self._record(method, host, port, authorization, 405)
|
||||
self._answer(conn, 405)
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
conn.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _connect(self, conn: socket.socket, host: str, port: int, authorization: Optional[str]) -> None:
|
||||
if (host, port) in DOH_TARGETS:
|
||||
self._record("CONNECT", host, port, authorization, 200)
|
||||
self._answer(conn, 200)
|
||||
self.doh.serve(conn, self.name)
|
||||
return
|
||||
if not is_loopback(host):
|
||||
self._record("CONNECT", host, port, authorization, 403)
|
||||
self._answer(conn, 403)
|
||||
return
|
||||
try:
|
||||
upstream = socket.create_connection((host, port), timeout=10)
|
||||
except OSError:
|
||||
self._record("CONNECT", host, port, authorization, 502)
|
||||
self._answer(conn, 502)
|
||||
return
|
||||
self._record("CONNECT", host, port, authorization, 200)
|
||||
self._answer(conn, 200)
|
||||
try:
|
||||
relay(conn, upstream)
|
||||
finally:
|
||||
upstream.close()
|
||||
|
||||
def _forward(self, conn: socket.socket, host: str, port: int, authorization: Optional[str], split,
|
||||
headers: Dict[str, str], rest: bytes) -> None:
|
||||
"""A plain GET, in the absolute form: resolved by the zone of the FakeDoh, then fetched for real."""
|
||||
address = host if is_loopback(host) else self.doh.names.get(host.lower(), "")
|
||||
if not address or not is_loopback(address):
|
||||
self._record("GET", host, port, authorization, 502)
|
||||
self._answer(conn, 502)
|
||||
return
|
||||
try:
|
||||
upstream = socket.create_connection((address, port), timeout=10)
|
||||
except OSError:
|
||||
self._record("GET", host, port, authorization, 502)
|
||||
self._answer(conn, 502)
|
||||
return
|
||||
self._record("GET", host, port, authorization, 200)
|
||||
try:
|
||||
path = (split.path or "/") + ("?" + split.query if split.query else "")
|
||||
passed = "".join("%s: %s\r\n" % (k, v) for k, v in headers.items()
|
||||
if not k.startswith("proxy-") and k not in ("connection", "keep-alive"))
|
||||
upstream.sendall(("GET %s HTTP/1.1\r\n%sConnection: close\r\n\r\n" % (path, passed)).encode("latin-1"))
|
||||
conn.settimeout(None)
|
||||
upstream.settimeout(None)
|
||||
while True:
|
||||
data = upstream.recv(65536)
|
||||
if not data:
|
||||
break
|
||||
conn.sendall(data)
|
||||
finally:
|
||||
upstream.close()
|
||||
|
||||
|
||||
__all__ = ["HttpProxy", "Seen", "basic"]
|
||||
+340
@@ -0,0 +1,340 @@
|
||||
"""Two traps for what a browser does that it should not: a connection that does not go through the gateway, and a
|
||||
question put to the resolver of the machine.
|
||||
|
||||
* :class:`Watcher` samples, from before a launch until it is stopped, the network connections of every process that
|
||||
is a DESCENDANT of this test process and whose executable name contains a given word (``firefox`` by default).
|
||||
An inet connection - TCP in any state, SYN_SENT included, or a connected UDP socket - whose remote address is not
|
||||
loopback is a DIRECT connection: the browser did not go through the proxy (the proxy of a test is on 127.0.0.1).
|
||||
It also lists the names of every descendant it saw, which is how a test shows that no helper process
|
||||
(crash reporter, updater...) was ever started. Descendants of THIS process only, so parallel workers do not see
|
||||
each other's browsers.
|
||||
* :class:`ResolverTrap` listens on 127.0.0.1:53 (UDP and TCP, and ::1 when it can) and points ``/etc/resolv.conf``
|
||||
at it for as long as it runs, restoring the file byte for byte at the end, so every question that reaches the
|
||||
resolver of the machine is counted as ``(name, qtype)``. It needs Linux, root and a writable resolv.conf:
|
||||
``ResolverTrap.available`` says so and ``ResolverTrap.reason`` says why not. The trap answers from ``answers``
|
||||
(name -> IPv4) and REFUSES everything else at once, so nothing waits for it. Anything on the machine that resolves
|
||||
a name while it runs is counted too, the test process included: a test must not resolve names itself.
|
||||
|
||||
``ResolverTrap(port=0, rewrite_resolv_conf=False)`` is the same trap on a free port with no file touched, for the
|
||||
unit tests of the trap itself and for a client that is told where to ask.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import os
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Dict, Iterable, List, NamedTuple, Optional, Set, Tuple
|
||||
|
||||
from _doh_servers import RCODE_REFUSED, DohQuery, answer_for, build_response, parse_query
|
||||
|
||||
RESOLV_CONF = Path("/etc/resolv.conf")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------- Watcher
|
||||
class DirectConnection(NamedTuple):
|
||||
pid: int
|
||||
process: str # the name of the process
|
||||
protocol: str # "tcp" or "udp"
|
||||
local: str
|
||||
remote: str # "ip:port"
|
||||
status: str
|
||||
|
||||
|
||||
def _is_loopback(ip: str) -> bool:
|
||||
try:
|
||||
address = ipaddress.ip_address(ip.split("%")[0])
|
||||
except ValueError:
|
||||
return False
|
||||
if address.version == 6 and address.ipv4_mapped is not None:
|
||||
address = address.ipv4_mapped
|
||||
return address.is_loopback
|
||||
|
||||
|
||||
def _connections_of(process) -> list:
|
||||
getter = getattr(process, "net_connections", None) or process.connections
|
||||
return getter(kind="inet")
|
||||
|
||||
|
||||
class Watcher:
|
||||
"""Samples every ``interval`` seconds. Use as a context manager, or ``start()`` and ``stop()``.
|
||||
|
||||
``match`` is a word (or several) searched, case-insensitively, in the name of a process: only the connections of
|
||||
the descendants whose name contains one of them are judged. Every descendant, matching or not, is listed in
|
||||
:attr:`process_names`.
|
||||
"""
|
||||
|
||||
def __init__(self, *, interval: float = 0.02, match: Iterable[str] | str = "firefox", root_pid: Optional[int] = None):
|
||||
self.interval = interval
|
||||
self.match = tuple(m.lower() for m in ([match] if isinstance(match, str) else match))
|
||||
self.root_pid = root_pid if root_pid is not None else os.getpid()
|
||||
#: Every direct connection seen, once per (pid, remote, status).
|
||||
self.direct: List[DirectConnection] = []
|
||||
#: Names of the descendants seen, in the order they were first seen (one entry per name).
|
||||
self.process_names: List[str] = []
|
||||
#: pids of the matching descendants seen.
|
||||
self.watched_pids: Set[int] = set()
|
||||
self.samples = 0
|
||||
self._seen_keys: Set[tuple] = set()
|
||||
self._stop = threading.Event()
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
|
||||
# --- control -------------------------------------------------------------------------------------------------
|
||||
def start(self) -> "Watcher":
|
||||
if self._thread is None:
|
||||
self._thread = threading.Thread(target=self._run, daemon=True, name="leak-watcher")
|
||||
self._thread.start()
|
||||
return self
|
||||
|
||||
def stop(self) -> "Watcher":
|
||||
self._stop.set()
|
||||
if self._thread is not None:
|
||||
self._thread.join(timeout=5)
|
||||
self._thread = None
|
||||
return self
|
||||
|
||||
def __enter__(self) -> "Watcher":
|
||||
return self.start()
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self.stop()
|
||||
|
||||
# --- what a test asks ----------------------------------------------------------------------------------------
|
||||
def describe(self) -> str:
|
||||
return "; ".join("%s(pid %d) %s %s -> %s %s" % (c.process, c.pid, c.protocol, c.local, c.remote, c.status)
|
||||
for c in self.direct) or "nothing"
|
||||
|
||||
def helpers_seen(self, forbidden: Iterable[str]) -> List[str]:
|
||||
"""The process names whose stem (the name without its extension) contains one of ``forbidden``."""
|
||||
words = [w.lower() for w in forbidden]
|
||||
return [n for n in self.process_names if any(w in os.path.splitext(n)[0].lower() for w in words)]
|
||||
|
||||
# --- the sampling --------------------------------------------------------------------------------------------
|
||||
def _run(self) -> None:
|
||||
import psutil
|
||||
|
||||
root = None
|
||||
while not self._stop.is_set():
|
||||
started = time.monotonic()
|
||||
try:
|
||||
root = root or psutil.Process(self.root_pid)
|
||||
children = root.children(recursive=True)
|
||||
except psutil.Error:
|
||||
children = []
|
||||
for child in children:
|
||||
try:
|
||||
name = child.name()
|
||||
except psutil.Error:
|
||||
continue
|
||||
if name not in self.process_names:
|
||||
self.process_names.append(name)
|
||||
if not any(m in name.lower() for m in self.match):
|
||||
continue
|
||||
self.watched_pids.add(child.pid)
|
||||
try:
|
||||
connections = _connections_of(child)
|
||||
except (psutil.Error, OSError):
|
||||
continue
|
||||
for c in connections:
|
||||
if not c.raddr or _is_loopback(c.raddr.ip):
|
||||
continue
|
||||
protocol = "udp" if c.type == socket.SOCK_DGRAM else "tcp"
|
||||
key = (child.pid, protocol, c.raddr.ip, c.raddr.port, c.status)
|
||||
if key in self._seen_keys:
|
||||
continue
|
||||
self._seen_keys.add(key)
|
||||
self.direct.append(DirectConnection(
|
||||
child.pid, name, protocol, "%s:%s" % (c.laddr.ip, c.laddr.port) if c.laddr else "",
|
||||
"%s:%s" % (c.raddr.ip, c.raddr.port), c.status))
|
||||
self.samples += 1
|
||||
self._stop.wait(max(0.0, self.interval - (time.monotonic() - started)))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------- ResolverTrap
|
||||
def _trap_capability() -> Tuple[bool, str]:
|
||||
if not sys.platform.startswith("linux"):
|
||||
return False, "the resolver trap needs Linux (it points /etc/resolv.conf at itself)"
|
||||
if os.geteuid() != 0:
|
||||
return False, "the resolver trap needs root (port 53 and /etc/resolv.conf)"
|
||||
if not os.access(RESOLV_CONF, os.W_OK):
|
||||
return False, "/etc/resolv.conf is not writable"
|
||||
return True, ""
|
||||
|
||||
|
||||
class ResolverTrap:
|
||||
"""A resolver on loopback that counts what it is asked. See the module docstring."""
|
||||
|
||||
available, reason = _trap_capability()
|
||||
|
||||
def __init__(self, answers: Optional[Dict[str, str]] = None, *, port: int = 53,
|
||||
rewrite_resolv_conf: bool = True):
|
||||
self.answers = {k.lower(): v for k, v in (answers or {}).items()}
|
||||
self.port = port
|
||||
self.rewrite_resolv_conf = rewrite_resolv_conf
|
||||
#: Every question: (name, qtype, "udp"|"tcp").
|
||||
self.queries: List[DohQuery] = []
|
||||
self._lock = threading.Lock()
|
||||
self._sockets: List[socket.socket] = []
|
||||
self._original: Optional[bytes] = None
|
||||
self._running = False
|
||||
|
||||
# --- what a test reads ---------------------------------------------------------------------------------------
|
||||
def names(self) -> List[str]:
|
||||
with self._lock:
|
||||
return sorted({q.name for q in self.queries})
|
||||
|
||||
def asked(self, name: str, qtype: Optional[int] = None) -> List[DohQuery]:
|
||||
name = name.lower().rstrip(".")
|
||||
with self._lock:
|
||||
return [q for q in self.queries if q.name == name and (qtype is None or q.qtype == qtype)]
|
||||
|
||||
def describe(self) -> str:
|
||||
with self._lock:
|
||||
return ", ".join("%s/%d (%s)" % q for q in self.queries) or "nothing"
|
||||
|
||||
# --- control -------------------------------------------------------------------------------------------------
|
||||
def __enter__(self) -> "ResolverTrap":
|
||||
if self.rewrite_resolv_conf and not self.available:
|
||||
raise RuntimeError(self.reason)
|
||||
try:
|
||||
self._bind()
|
||||
if self.rewrite_resolv_conf:
|
||||
self._original = RESOLV_CONF.read_bytes()
|
||||
# In place, not by rename: in a container the file is often a bind mount.
|
||||
with open(RESOLV_CONF, "wb") as f:
|
||||
f.write(b"nameserver 127.0.0.1\noptions timeout:1 attempts:1\n")
|
||||
except BaseException:
|
||||
self._restore()
|
||||
raise
|
||||
self._running = True
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self._running = False
|
||||
self._restore()
|
||||
|
||||
def _restore(self) -> None:
|
||||
if self._original is not None:
|
||||
with open(RESOLV_CONF, "wb") as f:
|
||||
f.write(self._original)
|
||||
self._original = None
|
||||
for s in self._sockets:
|
||||
try:
|
||||
s.close()
|
||||
except OSError:
|
||||
pass
|
||||
self._sockets = []
|
||||
|
||||
def _bind(self) -> None:
|
||||
"""UDP and TCP on 127.0.0.1 (required) and on ::1 (when it can): the same port for all of them."""
|
||||
discarded: List[socket.socket] = [] # closed at the end, so a failed attempt's port is not handed out again
|
||||
made: List[socket.socket] = []
|
||||
try:
|
||||
for attempt in range(200):
|
||||
made = self._bind_once(discarded)
|
||||
if made:
|
||||
break
|
||||
if self.port != 0:
|
||||
break
|
||||
if not made:
|
||||
raise OSError("the resolver trap found no port it could bind for TCP and UDP")
|
||||
finally:
|
||||
for s in discarded:
|
||||
s.close()
|
||||
self._sockets += made
|
||||
for s in made:
|
||||
target = self._serve_udp if s.type == socket.SOCK_DGRAM else self._serve_tcp
|
||||
threading.Thread(target=target, args=(s,), daemon=True).start()
|
||||
|
||||
def _bind_once(self, discarded: List[socket.socket]) -> List[socket.socket]:
|
||||
"""One attempt: the sockets bound, or [] after putting what it opened in ``discarded``."""
|
||||
made: List[socket.socket] = []
|
||||
port = self.port
|
||||
for family, host, required in ((socket.AF_INET, "127.0.0.1", True), (socket.AF_INET6, "::1", False)):
|
||||
pair: List[socket.socket] = [] # this family's TCP and UDP, kept or dropped together
|
||||
try:
|
||||
# TCP first: Windows keeps big excluded ranges and hands out ephemeral ports in sequence, so a
|
||||
# UDP-first pick can land in a range TCP may not bind, again and again.
|
||||
tcp = socket.socket(family, socket.SOCK_STREAM)
|
||||
pair.append(tcp)
|
||||
if sys.platform != "win32": # on Windows SO_REUSEADDR is "share the port": it breaks bind
|
||||
tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
tcp.bind((host, port))
|
||||
if port == 0:
|
||||
port = tcp.getsockname()[1]
|
||||
tcp.listen(16)
|
||||
udp = socket.socket(family, socket.SOCK_DGRAM)
|
||||
pair.append(udp)
|
||||
udp.bind((host, port))
|
||||
except OSError:
|
||||
discarded += pair
|
||||
if required:
|
||||
discarded += made
|
||||
return []
|
||||
continue
|
||||
made += pair
|
||||
self.port = port
|
||||
return made
|
||||
|
||||
# --- answering -----------------------------------------------------------------------------------------------
|
||||
def _respond(self, message: bytes, protocol: str) -> Optional[bytes]:
|
||||
try:
|
||||
query = parse_query(message)
|
||||
except ValueError:
|
||||
return None
|
||||
with self._lock:
|
||||
self.queries.append(DohQuery(query.name, query.qtype, protocol))
|
||||
if query.name in self.answers:
|
||||
return answer_for(self.answers, query)
|
||||
return build_response(query, RCODE_REFUSED)
|
||||
|
||||
def _serve_udp(self, sock: socket.socket) -> None:
|
||||
while True:
|
||||
try:
|
||||
data, peer = sock.recvfrom(4096)
|
||||
except OSError:
|
||||
return
|
||||
response = self._respond(data, "udp")
|
||||
if response is not None:
|
||||
try:
|
||||
sock.sendto(response, peer)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _serve_tcp(self, listener: socket.socket) -> None:
|
||||
while True:
|
||||
try:
|
||||
conn, _ = listener.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self._tcp_conversation, args=(conn,), daemon=True).start()
|
||||
|
||||
def _tcp_conversation(self, conn: socket.socket) -> None:
|
||||
try:
|
||||
conn.settimeout(5)
|
||||
while True:
|
||||
head = conn.recv(2)
|
||||
if len(head) < 2:
|
||||
return
|
||||
size = struct.unpack("!H", head)[0]
|
||||
message = b""
|
||||
while len(message) < size:
|
||||
chunk = conn.recv(size - len(message))
|
||||
if not chunk:
|
||||
return
|
||||
message += chunk
|
||||
response = self._respond(message, "tcp")
|
||||
if response is None:
|
||||
return
|
||||
conn.sendall(struct.pack("!H", len(response)) + response)
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
__all__ = ["DirectConnection", "ResolverTrap", "Watcher"]
|
||||
@@ -0,0 +1,443 @@
|
||||
"""Three local SOCKS5 gateways on 127.0.0.1, for tests that need a real wire.
|
||||
|
||||
Reusable: nothing here knows about the core. A test (or the wrapper's system
|
||||
test) starts one with ``with coherent() as gw:`` and points the product at
|
||||
``gw.server`` (``socks5://127.0.0.1:<port>``), with ``gw.credentials`` when the
|
||||
gateway asks for a user and password.
|
||||
|
||||
The three gateways are the three things a real one can be:
|
||||
|
||||
* :func:`coherent` - TCP CONNECT works, UDP ASSOCIATE is granted, and the relay
|
||||
carries a STUN binding request to a fake STUN server that answers with the
|
||||
SAME address the TCP side reports as the exit. This is the gateway whose UDP
|
||||
can be trusted.
|
||||
* :func:`tcp_only` - TCP CONNECT works, UDP ASSOCIATE is refused with reply code
|
||||
7 ("command not supported"), the way a residential gateway does.
|
||||
* :func:`mismatched` - UDP ASSOCIATE is granted and STUN answers, but with an
|
||||
address DIFFERENT from the TCP exit: the disagreement a detector looks for.
|
||||
|
||||
Everything is on loopback, so the "exit address" is made observable and
|
||||
controllable instead of real: the TCP exit is what the gateway's fake "what is
|
||||
my address" endpoint (``api.ipify.org:80``, the one the product asks) answers,
|
||||
and the UDP exit is what the fake STUN server puts in its XOR-MAPPED-ADDRESS.
|
||||
Both are chosen by the test (``tcp_exit`` and ``udp_exit`` arguments).
|
||||
|
||||
Any other CONNECT is really forwarded, and any other UDP datagram is really
|
||||
forwarded to its destination and the reply wrapped back, so a page, or an echo
|
||||
server on 127.0.0.1, can be reached through the gateway and the test can
|
||||
observe which road its bytes took (:attr:`Gateway.connects`,
|
||||
:attr:`Gateway.datagrams`).
|
||||
|
||||
This is the ONE SOCKS5 gateway of the test suite. A road that needs more than the three above (a TURN server, a resolver,
|
||||
a page, by NAME: ``tests/_turn_chain.py``) subclasses :class:`Gateway` and overrides the small hooks (:meth:`Gateway._route`,
|
||||
:meth:`Gateway._target`, :attr:`Gateway.whoami_names`) instead of re-implementing the greeting, the authentication, the
|
||||
ASSOCIATE, the relay or the round trip.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import socket
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
#: The name the product's STUN probe sends through the relay. The relay maps it
|
||||
#: to the fake STUN server; every other destination is forwarded for real.
|
||||
STUN_NAME = "stun.l.google.com"
|
||||
STUN_PORT = 19302
|
||||
#: The same STUN server by NUMBER. A page cannot resolve a name behind the session (the engine forbids local
|
||||
#: resolution), so the wrapper's system test hands the page this address; like the name it is a documentation
|
||||
#: address (RFC 5737, TEST-NET-2), unroutable: the only road to it is the relay, which maps it to the fake STUN
|
||||
#: server. (A copy of invisible_core's tests/_socks_servers.py with this one addition.)
|
||||
STUN_NUMBER = "198.51.100.5"
|
||||
#: A page the gateway serves itself, for a test that loads one through the proxy (a name nothing else resolves).
|
||||
WEB_NAME = "page.test"
|
||||
#: The echo endpoints the product asks for its TCP exit.
|
||||
WHOAMI4 = ("api.ipify.org", 80)
|
||||
WHOAMI6 = ("api6.ipify.org", 80)
|
||||
|
||||
_MAGIC = b"\x21\x12\xa4\x42"
|
||||
|
||||
|
||||
def _recv_exact(s: socket.socket, n: int) -> bytes:
|
||||
data = b""
|
||||
while len(data) < n:
|
||||
chunk = s.recv(n - len(data))
|
||||
if not chunk:
|
||||
raise ConnectionError("closed")
|
||||
data += chunk
|
||||
return data
|
||||
|
||||
|
||||
class FakeStun:
|
||||
"""A UDP STUN server that answers every binding request with ``mapped_ip``."""
|
||||
|
||||
def __init__(self, mapped_ip: str, mapped_port: int = 40000):
|
||||
self.mapped_ip = mapped_ip
|
||||
self.mapped_port = mapped_port
|
||||
self.requests = 0
|
||||
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
self._sock.bind(("127.0.0.1", 0))
|
||||
self.address: Tuple[str, int] = self._sock.getsockname()
|
||||
self._thread = threading.Thread(target=self._serve, daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def _serve(self) -> None:
|
||||
while True:
|
||||
try:
|
||||
data, peer = self._sock.recvfrom(2048)
|
||||
except OSError:
|
||||
return
|
||||
if len(data) < 20 or data[0:2] != b"\x00\x01":
|
||||
continue
|
||||
self.requests += 1
|
||||
txid = data[8:20]
|
||||
xport = struct.pack("!H", self.mapped_port ^ 0x2112)
|
||||
xaddr = bytes(a ^ b for a, b in zip(socket.inet_aton(self.mapped_ip), _MAGIC))
|
||||
attr = struct.pack("!HH", 0x0020, 8) + b"\x00\x01" + xport + xaddr
|
||||
resp = b"\x01\x01" + struct.pack("!H", len(attr)) + _MAGIC + txid + attr
|
||||
try:
|
||||
self._sock.sendto(resp, peer)
|
||||
except OSError:
|
||||
return
|
||||
|
||||
def close(self) -> None:
|
||||
self._sock.close()
|
||||
|
||||
|
||||
class Gateway:
|
||||
"""A SOCKS5 server. ``udp`` is ``"relay"`` or ``"refuse"`` (reply code 7)."""
|
||||
|
||||
def __init__(self, *, udp: str, tcp_exit: str, udp_exit: str,
|
||||
user: Optional[str] = None, password: Optional[str] = None,
|
||||
relay_host: str = "127.0.0.1", rtt_ms: int = 0,
|
||||
exit_host: str = "127.0.0.1", tcp_data_delay: bool = False):
|
||||
assert udp in ("relay", "refuse")
|
||||
self.udp = udp
|
||||
#: The round trip to this gateway, in seconds: every answer on the control connection waits for it, and each
|
||||
#: datagram the relay carries waits half of it each way. A real gateway is not on loopback.
|
||||
self.rtt = rtt_ms / 1000.0
|
||||
#: The address of the UDP relay, the BND.ADDR of the association. A real gateway's is a routable address; the
|
||||
#: loopback default only suits a client whose UDP socket is not bound to an interface (an engine's ICE
|
||||
#: sockets are, and Windows does not send from an interface address to loopback).
|
||||
self.relay_host = relay_host
|
||||
#: The local address the relay's datagrams leave from (the source a server behind the gateway sees). Another
|
||||
#: loopback address makes a client that sent direct (from 127.0.0.1) tell apart from one that used the relay.
|
||||
self.exit_host = exit_host
|
||||
#: Whether each chunk of a forwarded TCP stream also waits half the round trip (a far gateway), as the datagrams do.
|
||||
self.tcp_data_delay = tcp_data_delay
|
||||
self.tcp_exit = tcp_exit
|
||||
self.user, self.password = user, password
|
||||
self.stun = FakeStun(udp_exit)
|
||||
#: Every CONNECT, as (host, port), in order.
|
||||
self.connects: List[Tuple[str, int]] = []
|
||||
#: Every UDP ASSOCIATE request, answered or refused.
|
||||
self.associates = 0
|
||||
#: When the gateway started: the origin of the times below.
|
||||
self.t0 = time.monotonic()
|
||||
#: Every UDP ASSOCIATE that was granted, as [start, end] seconds from t0; end is None until it was answered.
|
||||
self.associations: List[List[Optional[float]]] = []
|
||||
#: Every datagram the relay carried out, as (host as sent, port, address type, seconds from t0).
|
||||
self.datagram_log: List[Tuple[str, int, int, float]] = []
|
||||
#: Every datagram the relay carried out, as (host, port, payload).
|
||||
self.datagrams: List[Tuple[str, int, bytes]] = []
|
||||
self._listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
self._listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
self._listener.bind(("127.0.0.1", 0))
|
||||
self._listener.listen(32)
|
||||
self.port: int = self._listener.getsockname()[1]
|
||||
self._closed = False
|
||||
threading.Thread(target=self._accept, daemon=True).start()
|
||||
|
||||
# --- what the test hands to the product ---------------------------------
|
||||
@property
|
||||
def server(self) -> str:
|
||||
return "socks5://127.0.0.1:%d" % self.port
|
||||
|
||||
@property
|
||||
def credentials(self) -> dict:
|
||||
return ({"username": self.user, "password": self.password}
|
||||
if self.user is not None else {})
|
||||
|
||||
@property
|
||||
def proxy(self) -> dict:
|
||||
"""The endpoint dict the core takes: ``{"server": ..., [credentials]}``."""
|
||||
return dict({"server": self.server}, **self.credentials)
|
||||
|
||||
def close(self) -> None:
|
||||
self._closed = True
|
||||
for s in (self._listener,):
|
||||
try:
|
||||
s.close()
|
||||
except OSError:
|
||||
pass
|
||||
self.stun.close()
|
||||
|
||||
def __enter__(self) -> "Gateway":
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self.close()
|
||||
|
||||
# --- the TCP side --------------------------------------------------------
|
||||
def _send(self, c: socket.socket, data: bytes) -> None:
|
||||
if self.rtt:
|
||||
time.sleep(self.rtt)
|
||||
c.sendall(data)
|
||||
|
||||
def _accept(self) -> None:
|
||||
while not self._closed:
|
||||
try:
|
||||
conn, _ = self._listener.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self._handle, args=(conn,), daemon=True).start()
|
||||
|
||||
def _greet(self, c: socket.socket) -> bool:
|
||||
ver, n = _recv_exact(c, 2)
|
||||
methods = _recv_exact(c, n)
|
||||
if ver != 5:
|
||||
return False
|
||||
if self.user is not None:
|
||||
if 2 not in methods:
|
||||
self._send(c, b"\x05\xff")
|
||||
return False
|
||||
self._send(c, b"\x05\x02")
|
||||
_recv_exact(c, 1)
|
||||
u = _recv_exact(c, _recv_exact(c, 1)[0]).decode()
|
||||
p = _recv_exact(c, _recv_exact(c, 1)[0]).decode()
|
||||
ok = (u, p) == (self.user, self.password)
|
||||
self._send(c, b"\x01" + (b"\x00" if ok else b"\x01"))
|
||||
return ok
|
||||
self._send(c, b"\x05\x00" if 0 in methods else b"\x05\x02")
|
||||
if 0 not in methods: # a client that only offers user/password: accept any
|
||||
_recv_exact(c, 1)
|
||||
_recv_exact(c, _recv_exact(c, 1)[0])
|
||||
_recv_exact(c, _recv_exact(c, 1)[0])
|
||||
self._send(c, b"\x01\x00")
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _read_address(c: socket.socket) -> Tuple[str, int]:
|
||||
atyp = _recv_exact(c, 1)[0]
|
||||
if atyp == 1:
|
||||
host = socket.inet_ntoa(_recv_exact(c, 4))
|
||||
elif atyp == 3:
|
||||
host = _recv_exact(c, _recv_exact(c, 1)[0]).decode()
|
||||
else:
|
||||
host = socket.inet_ntop(socket.AF_INET6, _recv_exact(c, 16))
|
||||
return host, struct.unpack("!H", _recv_exact(c, 2))[0]
|
||||
|
||||
@staticmethod
|
||||
def _reply(rep: int, host: str = "0.0.0.0", port: int = 0) -> bytes:
|
||||
return b"\x05" + bytes([rep]) + b"\x00\x01" + socket.inet_aton(host) + struct.pack("!H", port)
|
||||
|
||||
def _handle(self, c: socket.socket) -> None:
|
||||
try:
|
||||
c.settimeout(30)
|
||||
if not self._greet(c):
|
||||
return
|
||||
ver, cmd, _rsv = _recv_exact(c, 3)
|
||||
host, port = self._read_address(c)
|
||||
if cmd == 1:
|
||||
self._connect(c, host, port)
|
||||
elif cmd == 3:
|
||||
self._associate(c)
|
||||
else:
|
||||
self._send(c, self._reply(7))
|
||||
except (OSError, ConnectionError):
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
c.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
#: The names the product asks "what is my address" of (on port 80); each is answered with ``tcp_exit``.
|
||||
whoami_names: Tuple[str, ...] = (WHOAMI4[0],)
|
||||
|
||||
def _target(self, host: str, port: int) -> Tuple[str, int]:
|
||||
"""Where a CONNECT that is not a special one really goes. A subclass maps a name to a local server."""
|
||||
return host, port
|
||||
|
||||
def _connect(self, c: socket.socket, host: str, port: int) -> None:
|
||||
self.connects.append((host, port))
|
||||
if host.lower() in self.whoami_names and port == WHOAMI4[1]:
|
||||
self._send(c, self._reply(0))
|
||||
_ = c.recv(4096)
|
||||
body = self.tcp_exit.encode()
|
||||
self._send(c, b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: %d\r\n"
|
||||
b"Connection: close\r\n\r\n%s" % (len(body), body))
|
||||
return
|
||||
if (host, port) == WHOAMI6:
|
||||
self._send(c, self._reply(4)) # no IPv6 exit
|
||||
return
|
||||
if (host, port) == (WEB_NAME, 80): # a page that only the gateway can reach
|
||||
self._send(c, self._reply(0))
|
||||
_ = c.recv(4096)
|
||||
body = b"<html><body>behind the gateway</body></html>"
|
||||
self._send(c, b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: %d\r\n"
|
||||
b"Connection: close\r\n\r\n%s" % (len(body), body))
|
||||
return
|
||||
try:
|
||||
up = socket.create_connection(self._target(host, port), timeout=10)
|
||||
except OSError:
|
||||
self._send(c, self._reply(5))
|
||||
return
|
||||
self._send(c, self._reply(0))
|
||||
c.settimeout(None)
|
||||
up.settimeout(None)
|
||||
|
||||
def pump(a: socket.socket, b: socket.socket) -> None:
|
||||
try:
|
||||
while True:
|
||||
d = a.recv(65536)
|
||||
if not d:
|
||||
break
|
||||
if self.tcp_data_delay and self.rtt:
|
||||
time.sleep(self.rtt / 2)
|
||||
b.sendall(d)
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
for s in (a, b):
|
||||
try:
|
||||
s.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
t = threading.Thread(target=pump, args=(up, c), daemon=True)
|
||||
t.start()
|
||||
pump(c, up)
|
||||
t.join(timeout=2)
|
||||
up.close()
|
||||
|
||||
# --- the UDP side --------------------------------------------------------
|
||||
def _later(self, fn) -> None:
|
||||
"""Run ``fn`` after half the round trip (at once on loopback), ignoring a socket that is already closed."""
|
||||
def run() -> None:
|
||||
try:
|
||||
fn()
|
||||
except OSError:
|
||||
pass
|
||||
threading.Timer(self.rtt / 2, run).start() if self.rtt else run()
|
||||
|
||||
def _deliver(self, relay: socket.socket, to: Tuple[str, int], host: str, port: int, payload: bytes) -> None:
|
||||
"""Wrap ``payload`` as coming from ``host``:``port`` (an IPv4 literal) and send it back to the client."""
|
||||
data = b"\x00\x00\x00\x01" + socket.inet_aton(host) + struct.pack("!H", port) + payload
|
||||
self._later(lambda: relay.sendto(data, to))
|
||||
|
||||
def _route(self, host: str, dport: int, atyp: int, payload: bytes, out_port: int,
|
||||
answer) -> Optional[Tuple[Tuple[str, int], Optional[Tuple[str, int]]]]:
|
||||
"""Where one datagram of the client goes: ``(target, reported_as)``, or None when it is dropped.
|
||||
|
||||
``target`` is the real address the datagram is sent to from the exit socket (``out_port`` is that socket's port);
|
||||
``reported_as`` is the address the client is told the reply came from (None: the real source). A subclass may also
|
||||
answer by itself with ``answer(host, port, data)``. By default the fake STUN server, by name or by number, is
|
||||
mapped and everything else is forwarded for real."""
|
||||
if (host, dport) in ((STUN_NAME, STUN_PORT), (STUN_NUMBER, STUN_PORT)):
|
||||
# A real server answers from the address it was asked at; the fake STUN server is mapped, so its reply is
|
||||
# reported as from the asked address (only when that was a literal: a name has no address to report).
|
||||
return self.stun.address, ((host, dport) if atyp == 1 else None)
|
||||
return (host, dport), None
|
||||
|
||||
def _associate(self, c: socket.socket) -> None:
|
||||
self.associates += 1
|
||||
if self.udp == "refuse":
|
||||
self._send(c, self._reply(7))
|
||||
return
|
||||
record: List[Optional[float]] = [time.monotonic() - self.t0, None]
|
||||
self.associations.append(record)
|
||||
relay = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
relay.bind((self.relay_host, 0))
|
||||
out = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
out.bind((self.exit_host, 0))
|
||||
client: List[Optional[Tuple[str, int]]] = [None]
|
||||
#: Where a mapped destination really is -> the address the client is told it answered from.
|
||||
asked_at: dict = {}
|
||||
self._send(c, self._reply(0, self.relay_host, relay.getsockname()[1]))
|
||||
record[1] = time.monotonic() - self.t0
|
||||
|
||||
def answer(host: str, port: int, data: bytes) -> None:
|
||||
self._deliver(relay, client[0], host, port, data)
|
||||
|
||||
def inbound() -> None: # client -> world
|
||||
while True:
|
||||
try:
|
||||
d, peer = relay.recvfrom(65536)
|
||||
except OSError:
|
||||
return
|
||||
if len(d) < 10 or d[2] != 0:
|
||||
continue
|
||||
client[0] = peer
|
||||
atyp, i = d[3], 4
|
||||
if atyp == 1:
|
||||
host, i = socket.inet_ntoa(d[i:i + 4]), i + 4
|
||||
elif atyp == 3:
|
||||
n = d[i]
|
||||
host, i = d[i + 1:i + 1 + n].decode(), i + 1 + n
|
||||
else:
|
||||
host, i = socket.inet_ntop(socket.AF_INET6, d[i:i + 16]), i + 16
|
||||
dport = struct.unpack("!H", d[i:i + 2])[0]
|
||||
payload = d[i + 2:]
|
||||
self.datagrams.append((host, dport, payload))
|
||||
self.datagram_log.append((host, dport, atyp, time.monotonic() - self.t0))
|
||||
routed = self._route(host, dport, atyp, payload, out.getsockname()[1], answer)
|
||||
if routed is None:
|
||||
continue
|
||||
target, reported = routed
|
||||
if reported is not None:
|
||||
asked_at[target] = reported
|
||||
self._later(lambda p=payload, t=target: out.sendto(p, t))
|
||||
|
||||
def outbound() -> None: # world -> client
|
||||
while True:
|
||||
try:
|
||||
d, src = out.recvfrom(65536)
|
||||
except OSError:
|
||||
return
|
||||
if client[0] is None:
|
||||
continue
|
||||
host, port = asked_at.get(src, src)
|
||||
self._deliver(relay, client[0], host, port, d)
|
||||
|
||||
threading.Thread(target=inbound, daemon=True).start()
|
||||
threading.Thread(target=outbound, daemon=True).start()
|
||||
try: # the association lives as long as the control connection
|
||||
c.settimeout(None)
|
||||
while c.recv(1024):
|
||||
pass
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
relay.close()
|
||||
out.close()
|
||||
|
||||
|
||||
#: Documentation addresses (RFC 5737): never a real host, so nothing in a test
|
||||
#: can be mistaken for the machine's own address.
|
||||
EXIT = "203.0.113.7"
|
||||
OTHER_EXIT = "198.51.100.4"
|
||||
|
||||
|
||||
def coherent(*, exit_ip: str = EXIT, user: Optional[str] = None,
|
||||
password: Optional[str] = None, relay_host: str = "127.0.0.1", rtt_ms: int = 0) -> Gateway:
|
||||
"""TCP and UDP both work, and both leave from ``exit_ip``."""
|
||||
return Gateway(udp="relay", tcp_exit=exit_ip, udp_exit=exit_ip,
|
||||
user=user, password=password, relay_host=relay_host, rtt_ms=rtt_ms)
|
||||
|
||||
|
||||
def tcp_only(*, exit_ip: str = EXIT, user: Optional[str] = None,
|
||||
password: Optional[str] = None) -> Gateway:
|
||||
"""TCP works; UDP ASSOCIATE is refused with reply code 7."""
|
||||
return Gateway(udp="refuse", tcp_exit=exit_ip, udp_exit=exit_ip,
|
||||
user=user, password=password)
|
||||
|
||||
|
||||
def mismatched(*, tcp_exit: str = EXIT, udp_exit: str = OTHER_EXIT,
|
||||
user: Optional[str] = None, password: Optional[str] = None) -> Gateway:
|
||||
"""UDP is granted and STUN answers, with an address that is not the TCP exit."""
|
||||
assert udp_exit != tcp_exit
|
||||
return Gateway(udp="relay", tcp_exit=tcp_exit, udp_exit=udp_exit,
|
||||
user=user, password=password)
|
||||
@@ -0,0 +1,345 @@
|
||||
"""A whole, hermetic road for a page that asks for a TURN allocation BY NAME behind a SOCKS5 gateway that carries UDP.
|
||||
|
||||
Nothing here is a real server of anybody: everything is on loopback, and the only way to anything is the gateway.
|
||||
|
||||
* :class:`TurnServer` - a TURN server (RFC 5766, the part a browser uses): Allocate answered 401 with a realm and a nonce, then
|
||||
answered with the relayed and the mapped address under a long-term credential, checked and signed (MESSAGE-INTEGRITY), so
|
||||
the browser's ICE agent accepts it as it accepts a real one. It records the SOURCE it saw for every datagram: that is the
|
||||
address a real TURN server would report as the browser's, and the one the verdict compares with.
|
||||
* :class:`DnsServer` - answers an A query for the TURN name and for the page's name; the only resolver of the world.
|
||||
* :class:`Chain` - the SOCKS5 gateway of ``_socks_servers.Gateway`` (greeting, ASSOCIATE, relay and the round trip of a gateway
|
||||
that is far away, ``rtt_ms``, are all there, not here), told where this world's names and datagrams go: TCP CONNECT to the
|
||||
page's name goes to the page server; a datagram to the TURN's documentation address goes to the TURN server, a datagram to
|
||||
port 53 goes to the DNS server, a datagram to the TURN NAME (SOCKS5 address type 3: the gateway resolves it) goes to the TURN
|
||||
server, and a STUN binding request to anything else is answered with the exit. Datagrams leave from ``EXIT_HOST`` (another
|
||||
loopback address), so the TURN server sees a source that is not the browser's own: if it sees the browser's, the road was
|
||||
not the gateway's.
|
||||
* :class:`Page` - the page and the verdict, with the shape of a leak test's logic: a tick of 2 seconds after the page starts that
|
||||
marks TIMEOUT, cleared only after a POST made when a server-reflexive candidate arrives; the server compares the address
|
||||
of that candidate with the source the TURN saw.
|
||||
|
||||
The names and the addresses are RFC 2606 / RFC 5737: nothing in a test can be mistaken for a real host.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import socket
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
from _socks_servers import Gateway
|
||||
|
||||
TURN_NAME = "turn.relay-only.test"
|
||||
PAGE_NAME = "page.relay-only.test"
|
||||
#: RFC 5737 TEST-NET-2: unroutable, so the only road to it is the gateway, which maps it to the TURN server.
|
||||
TURN_IP = "198.51.100.7"
|
||||
TURN_PORT = 3478
|
||||
RELAYED = ("198.51.100.7", 50000)
|
||||
#: Where the gateway's datagrams come from. A browser that sends direct comes from 127.0.0.1.
|
||||
EXIT_HOST = "127.0.0.2"
|
||||
MAGIC = 0x2112A442
|
||||
PASSWORD = "qwerty"
|
||||
REALM = "hermetic"
|
||||
NONCE = "6e6f6e6365"
|
||||
|
||||
|
||||
def this_host_address() -> str:
|
||||
"""The address of this host that a socket bound to an interface can send from: the relay's BND.ADDR (a loopback relay
|
||||
only suits a client whose UDP socket is not bound to an interface, and an engine's ICE sockets are)."""
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
s.connect(("192.0.2.1", 9))
|
||||
return s.getsockname()[0]
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
|
||||
# ── STUN / TURN wire ───────────────────────────────────────────────────────────
|
||||
|
||||
def _attrs(data: bytes) -> Dict[int, bytes]:
|
||||
out: Dict[int, bytes] = {}
|
||||
i = 20
|
||||
while i + 4 <= len(data):
|
||||
t, n = struct.unpack("!HH", data[i:i + 4])
|
||||
out[t] = data[i + 4:i + 4 + n]
|
||||
i += 4 + ((n + 3) & ~3)
|
||||
return out
|
||||
|
||||
|
||||
def _attr(t: int, v: bytes) -> bytes:
|
||||
return struct.pack("!HH", t, len(v)) + v + b"\x00" * (-len(v) % 4)
|
||||
|
||||
|
||||
def _xor_addr(ip: str, port: int) -> bytes:
|
||||
xp = port ^ (MAGIC >> 16)
|
||||
xa = struct.unpack("!I", socket.inet_aton(ip))[0] ^ MAGIC
|
||||
return b"\x00\x01" + struct.pack("!HI", xp, xa)
|
||||
|
||||
|
||||
def _message(mtype: int, tid: bytes, attrs: bytes, key: Optional[bytes] = None) -> bytes:
|
||||
if key is None:
|
||||
return struct.pack("!HHI", mtype, len(attrs), MAGIC) + tid + attrs
|
||||
head = struct.pack("!HHI", mtype, len(attrs) + 24, MAGIC) + tid
|
||||
mac = hmac.new(key, head + attrs, hashlib.sha1).digest()
|
||||
return head + attrs + _attr(0x0008, mac)
|
||||
|
||||
|
||||
class TurnServer:
|
||||
"""UDP TURN server on 127.0.0.1. ``seen`` is every datagram as (source ip, source port, STUN type), in order;
|
||||
``allocations`` the successful Allocates as (source ip, source port, username, time)."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
self.sock.bind(("127.0.0.1", 0))
|
||||
self.address: Tuple[str, int] = self.sock.getsockname()
|
||||
self.seen: List[Tuple[str, int, int]] = []
|
||||
self.allocations: List[Tuple[str, int, str, float]] = []
|
||||
self._closed = False
|
||||
threading.Thread(target=self._serve, daemon=True).start()
|
||||
|
||||
def close(self) -> None:
|
||||
self._closed = True
|
||||
self.sock.close()
|
||||
|
||||
def _serve(self) -> None:
|
||||
while not self._closed:
|
||||
try:
|
||||
data, src = self.sock.recvfrom(65536)
|
||||
except OSError:
|
||||
return
|
||||
if len(data) < 20 or struct.unpack("!I", data[4:8])[0] != MAGIC:
|
||||
continue
|
||||
mtype, tid = struct.unpack("!H", data[:2])[0], data[8:20]
|
||||
self.seen.append((src[0], src[1], mtype))
|
||||
attrs = _attrs(data)
|
||||
if mtype == 0x0003: # Allocate
|
||||
if 0x0008 not in attrs or 0x0006 not in attrs: # no credentials: 401 with a realm and a nonce
|
||||
err = _attr(0x0009, b"\x00\x00\x04\x01Unauthorized") + _attr(0x0014, REALM.encode()) + _attr(0x0015, NONCE.encode())
|
||||
self.sock.sendto(_message(0x0113, tid, err), src)
|
||||
continue
|
||||
user = attrs[0x0006].decode(errors="replace")
|
||||
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode()).digest()
|
||||
body = (_attr(0x0016, _xor_addr(*RELAYED)) + _attr(0x0020, _xor_addr(src[0], src[1])) +
|
||||
_attr(0x000D, struct.pack("!I", 600)))
|
||||
self.allocations.append((src[0], src[1], user, time.monotonic()))
|
||||
self.sock.sendto(_message(0x0103, tid, body, key), src)
|
||||
elif mtype in (0x0004, 0x0008, 0x0009): # Refresh, CreatePermission, ChannelBind
|
||||
user = attrs.get(0x0006, b"").decode(errors="replace")
|
||||
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode()).digest()
|
||||
body = _attr(0x000D, struct.pack("!I", 600)) if mtype == 0x0004 else b""
|
||||
self.sock.sendto(_message(mtype | 0x0100, tid, body, key), src)
|
||||
|
||||
|
||||
class DnsServer:
|
||||
"""A resolver that knows two names. ``queries`` is every name asked, in order."""
|
||||
|
||||
def __init__(self, names: Dict[str, str]) -> None:
|
||||
self.names = {k.lower(): v for k, v in names.items()}
|
||||
self.queries: List[str] = []
|
||||
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
self.sock.bind(("127.0.0.1", 0))
|
||||
self.address: Tuple[str, int] = self.sock.getsockname()
|
||||
threading.Thread(target=self._serve, daemon=True).start()
|
||||
|
||||
def close(self) -> None:
|
||||
self.sock.close()
|
||||
|
||||
def answer(self, q: bytes) -> Optional[bytes]:
|
||||
if len(q) < 12:
|
||||
return None
|
||||
i, labels = 12, []
|
||||
while i < len(q) and q[i]:
|
||||
labels.append(q[i + 1:i + 1 + q[i]].decode(errors="replace"))
|
||||
i += 1 + q[i]
|
||||
name = ".".join(labels).lower()
|
||||
qtype = struct.unpack("!H", q[i + 1:i + 3])[0]
|
||||
self.queries.append(name)
|
||||
question = q[12:i + 5]
|
||||
ip = self.names.get(name)
|
||||
if ip is None:
|
||||
return q[:2] + b"\x81\x83" + q[4:6] + b"\x00\x00\x00\x00\x00\x00" + question
|
||||
if qtype != 1: # AAAA and the rest: the name exists, nothing of that type
|
||||
return q[:2] + b"\x81\x80" + q[4:6] + b"\x00\x00\x00\x00\x00\x00" + question
|
||||
return (q[:2] + b"\x81\x80" + q[4:6] + b"\x00\x01\x00\x00\x00\x00" + question +
|
||||
b"\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\x3c\x00\x04" + socket.inet_aton(ip))
|
||||
|
||||
def _serve(self) -> None:
|
||||
while True:
|
||||
try:
|
||||
q, src = self.sock.recvfrom(4096)
|
||||
except OSError:
|
||||
return
|
||||
r = self.answer(q)
|
||||
if r:
|
||||
self.sock.sendto(r, src)
|
||||
|
||||
|
||||
# ── the gateway ────────────────────────────────────────────────────────────────
|
||||
|
||||
def _literal(host: str) -> str:
|
||||
"""``host`` when it is an IPv4 literal; else the TURN address (a datagram sent by name is answered as from there)."""
|
||||
try:
|
||||
socket.inet_aton(host)
|
||||
return host
|
||||
except OSError:
|
||||
return TURN_IP
|
||||
|
||||
|
||||
class Chain(Gateway):
|
||||
"""The SOCKS5 gateway, with the TURN server, the resolver and the page behind it. A context manager."""
|
||||
|
||||
#: What the product asks "what is my address" of: answered with the exit.
|
||||
whoami_names = ("api.ipify.org", "ifconfig.me", "icanhazip.com")
|
||||
|
||||
def __init__(self, *, rtt_ms: int = 130, relay_host: Optional[str] = None) -> None:
|
||||
self.turn = TurnServer()
|
||||
self.dns = DnsServer({TURN_NAME: TURN_IP, PAGE_NAME: "127.0.0.1"})
|
||||
self.page = Page(self)
|
||||
super().__init__(udp="relay", tcp_exit=EXIT_HOST, udp_exit=EXIT_HOST,
|
||||
relay_host=relay_host or this_host_address(), rtt_ms=rtt_ms,
|
||||
exit_host=EXIT_HOST, tcp_data_delay=True)
|
||||
|
||||
def close(self) -> None:
|
||||
super().close()
|
||||
self.turn.close()
|
||||
self.dns.close()
|
||||
self.page.close()
|
||||
|
||||
def _target(self, host: str, port: int) -> Tuple[str, int]:
|
||||
return ("127.0.0.1", self.page.port) if host.lower() == PAGE_NAME else (host, port)
|
||||
|
||||
def _route(self, host, dport, atyp, payload, out_port, answer):
|
||||
is_turn = (host == TURN_IP or host.lower() == TURN_NAME) and dport == TURN_PORT
|
||||
if is_turn:
|
||||
target = self.turn.address
|
||||
elif dport == 53:
|
||||
target = self.dns.address
|
||||
elif len(payload) >= 20 and payload[:2] == b"\x00\x01" and struct.unpack("!I", payload[4:8])[0] == MAGIC:
|
||||
# a STUN binding request to anyone else: answered by the gateway, with the exit as the mapped address
|
||||
answer(_literal(host), dport, _message(0x0101, payload[8:20], _attr(0x0020, _xor_addr(EXIT_HOST, out_port))))
|
||||
return None
|
||||
else:
|
||||
return None
|
||||
return target, (_literal(TURN_IP if is_turn else host), dport)
|
||||
|
||||
# --- what a failed test says ----------------------------------------------
|
||||
def explain(self, result: dict) -> str:
|
||||
"""The road, as the three servers and the page saw it, and the sentence that says where it stopped."""
|
||||
turn_heard = [s for s in self.turn.seen]
|
||||
names_asked = [h for h, _p, a, _t in self.datagram_log if a == 3]
|
||||
dns_asked = self.dns.queries
|
||||
lines = ["", "THE ROAD, as the servers saw it:"]
|
||||
lines.append(" gateway: %d UDP ASSOCIATE (start -> answered, seconds): %s" % (
|
||||
len(self.associations), ", ".join("%.2f->%s" % (a, "%.2f" % b if b is not None else "-") for a, b in self.associations) or "none"))
|
||||
lines.append(" gateway: datagrams carried out: %d (to the TURN address/name: %d, DNS queries through it: %d, names sent by the relay-resolves road: %d)" % (
|
||||
len(self.datagram_log), sum(1 for h, p, _a, _t in self.datagram_log if p == TURN_PORT),
|
||||
len(dns_asked), len(names_asked)))
|
||||
lines.append(" TURN server heard %d datagram(s) %s; allocations: %s" % (
|
||||
len(turn_heard), [("%s:%d" % (s[0], s[1]), hex(s[2])) for s in turn_heard][:6],
|
||||
[("%s:%d" % (a[0], a[1])) for a in self.turn.allocations]))
|
||||
lines.append(" page verdicts: %s" % (self.page.verdicts or "none: no server-reflexive candidate came before the tick, or the POST did not finish"))
|
||||
lines.append(" page: %s" % json.dumps({k: result.get(k) for k in ("status", "timeline", "errors", "srflx", "candidates")}, default=str)[:900])
|
||||
if not turn_heard:
|
||||
if not dns_asked and not names_asked:
|
||||
why = ("the browser never tried to reach the TURN server: its name %r was not resolved through the relay "
|
||||
"(no DNS query reached the resolver and no datagram carried the name), so no allocation was ever asked for; "
|
||||
"the only server-reflexive candidate the page can have is one the engine made up" % TURN_NAME)
|
||||
else:
|
||||
why = "the name was asked (%s) but no datagram reached the TURN server: the answer did not come back, or came after the tick" % (dns_asked or names_asked)
|
||||
elif not self.turn.allocations:
|
||||
why = "the TURN server heard the browser but no Allocate was answered with credentials: the 401 round trip did not finish"
|
||||
elif result.get("status") == "TIMEOUT":
|
||||
ends = [e for _s, e in self.associations if e is not None]
|
||||
why = ("the allocation succeeded but too late for the tick of 2000 ms: the association handshakes alone ended at %s s"
|
||||
% ", ".join("%.2f" % e for e in ends))
|
||||
else:
|
||||
why = "the srflx of the page is not the address the TURN server saw (%s)" % [("%s:%d" % (a[0], a[1])) for a in self.turn.allocations]
|
||||
lines.append("WHY: " + why)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ── the page and the verdict ───────────────────────────────────────────────────
|
||||
|
||||
PAGE_HTML = """<!doctype html><meta charset=utf-8><title>relay-only</title><script>
|
||||
const t0 = performance.now(), mark = (k) => (window.__result.timeline[k] = Math.round(performance.now() - t0));
|
||||
window.__result = {status: 'PENDING', timeline: {}, errors: [], candidates: [], srflx: null};
|
||||
let status = 'PENDING';
|
||||
const finish = (s) => { status = s; window.__result.status = s; window.__done = true; };
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
mark('dom');
|
||||
// the tick of a leak test: 2 seconds after the page starts. It is cleared only after the POST made on a srflx.
|
||||
const tick = setInterval(() => { if (status === 'PENDING') { mark('tick'); finish('TIMEOUT'); } clearInterval(tick); }, 2000);
|
||||
const pc = new RTCPeerConnection({iceServers: [{urls: ['turn:%(turn)s:%(port)d?transport=udp'], username: 'challenge-' + Date.now(), credential: '%(password)s'}]});
|
||||
pc.createDataChannel('x');
|
||||
mark('pc');
|
||||
pc.onicegatheringstatechange = () => mark('gathering_' + pc.iceGatheringState);
|
||||
pc.onicecandidateerror = (e) => window.__result.errors.push([e.errorCode, e.url]);
|
||||
pc.onicecandidate = async (e) => {
|
||||
if (!e.candidate) return;
|
||||
window.__result.candidates.push(e.candidate.candidate);
|
||||
if (e.candidate.candidate.indexOf(' typ srflx ') < 0 || status !== 'PENDING') return;
|
||||
mark('srflx');
|
||||
window.__result.srflx = e.candidate.candidate;
|
||||
const r = await fetch('/verdict', {method: 'POST', body: JSON.stringify({srflx: e.candidate.candidate})});
|
||||
mark('posted');
|
||||
if (status !== 'PENDING') return;
|
||||
clearInterval(tick);
|
||||
finish((await r.json()).ok ? 'DONE' : 'REFUSED');
|
||||
};
|
||||
pc.createOffer().then((o) => pc.setLocalDescription(o));
|
||||
});
|
||||
</script>"""
|
||||
|
||||
|
||||
class Page:
|
||||
"""The page server (the browser reaches it by NAME, through the gateway) and the verdict."""
|
||||
|
||||
def __init__(self, chain: "Chain") -> None:
|
||||
outer = self
|
||||
self.verdicts: List[dict] = []
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
timeout = 5
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
body = (PAGE_HTML % {"turn": TURN_NAME, "port": TURN_PORT, "password": PASSWORD}).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_POST(self):
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
cand = json.loads(self.rfile.read(n) or b"{}").get("srflx", "")
|
||||
parts = cand.split()
|
||||
ip, port = (parts[4], int(parts[5])) if len(parts) > 5 else ("", 0)
|
||||
seen = [(a[0], a[1]) for a in chain.turn.allocations]
|
||||
ok = bool(seen) and (ip, port) in seen and ip == EXIT_HOST
|
||||
outer.verdicts.append({"srflx": "%s:%d" % (ip, port), "seen_by_the_turn": ["%s:%d" % s for s in seen], "ok": ok})
|
||||
body = json.dumps({"ok": ok}).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
self.httpd.daemon_threads = True
|
||||
self.port: int = self.httpd.server_address[1]
|
||||
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
return "http://%s:%d/" % (PAGE_NAME, self.port)
|
||||
|
||||
def close(self) -> None:
|
||||
self.httpd.shutdown()
|
||||
@@ -39,8 +39,7 @@ def display(monkeypatch):
|
||||
vd = RecordingDisplay()
|
||||
geo = types.SimpleNamespace(timezone="Europe/Rome",
|
||||
locale=SessionLocale.of("it-IT"),
|
||||
egress_ip=None,
|
||||
srflx_to_declare=lambda: None)
|
||||
egress_ip=None)
|
||||
|
||||
def refuse(**_kw):
|
||||
raise FontManifestMismatch("the engine does not carry these faces")
|
||||
|
||||
@@ -91,12 +91,13 @@ def test_every_context_of_a_served_browser_is_the_session(firefox_binary):
|
||||
assert "Windows NT" in agent and platform == "Win32", seen[0]
|
||||
|
||||
|
||||
def test_a_bare_launch_behind_a_proxy_declares_the_egress_as_its_srflx(firefox_binary, monkeypatch):
|
||||
"""Behind a proxy a page must read, as WebRTC's server-reflexive candidate, the address the session
|
||||
leaves from (STEALTHFOX_WEBRTC_PUBLIC_IP, which the session's environment carries), not none and not
|
||||
this machine's. A bare launch got no session environment, so a page behind the proxy saw no srflx of
|
||||
the egress. The proxy is the local TCP-only SOCKS5 of test_webrtc_realness.py; the egress the session
|
||||
measures through it is answered with a TEST-NET address (RFC 5737), as in those tests."""
|
||||
def test_a_bare_launch_behind_a_proxy_is_composed_through_it(firefox_binary, monkeypatch):
|
||||
"""A bare launch behind a proxy gets a session composed THROUGH that proxy (the egress, the timezone and
|
||||
the locale measured there, the network declared from the seed), and the page's WebRTC gather still
|
||||
completes with mDNS hosts. The declaration (STEALTHFOX_WEBRTC_NETWORK) is read by the new engine only;
|
||||
its value is asserted without a browser in test_the_network_declaration_reaches_the_engine.py. The
|
||||
proxy is the local TCP-only SOCKS5 of test_webrtc_realness.py; the egress the session measures through
|
||||
it is answered with a TEST-NET address (RFC 5737), as in those tests."""
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import threading
|
||||
|
||||
@@ -104,16 +105,15 @@ def test_a_bare_launch_behind_a_proxy_declares_the_egress_as_its_srflx(firefox_b
|
||||
from invisible_core._geo import SessionGeo
|
||||
from invisible_playwright import _session
|
||||
from invisible_playwright._pw.sync_api import sync_playwright
|
||||
from test_webrtc_realness import _PROBE_JS, _Socks5TcpOnly, candidates, srflx_candidates
|
||||
from test_webrtc_realness import _PROBE_JS, _Socks5TcpOnly, candidates, host_is_mdns
|
||||
|
||||
egress = "203.0.113.7"
|
||||
for name in ("STEALTHFOX_WEBRTC_PUBLIC_IP", "STEALTHFOX_WEBRTC_DISABLE_IPV6"):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
monkeypatch.delenv("STEALTHFOX_WEBRTC_NETWORK", raising=False)
|
||||
measured = []
|
||||
|
||||
def through_the_proxy(timezone, proxy, locale):
|
||||
measured.append(proxy)
|
||||
return SessionGeo("America/New_York", egress, srflx_suppressed=False,
|
||||
return SessionGeo("America/New_York", egress,
|
||||
locale=decide_session_locale("en-US"))
|
||||
|
||||
monkeypatch.setattr(_session, "session_geo", through_the_proxy, raising=False) # absent before the fix
|
||||
@@ -146,7 +146,7 @@ def test_a_bare_launch_behind_a_proxy_declares_the_egress_as_its_srflx(firefox_b
|
||||
finally:
|
||||
socks.close()
|
||||
httpd.shutdown()
|
||||
srflx = [c for c in srflx_candidates(candidates(res["candidates"])) if c["address"] == egress]
|
||||
assert srflx, "behind the proxy the page reads no srflx of the egress %s: %s" % (egress, res["candidates"])
|
||||
cands = candidates(res["candidates"])
|
||||
assert cands and host_is_mdns(cands), "behind the proxy the gather is blocked or leaks a host: %s" % res["candidates"]
|
||||
assert measured and measured[0] and measured[0].get("server", "").startswith("socks5://"), (
|
||||
"the session was not composed through the launch's proxy: %r" % measured)
|
||||
@@ -0,0 +1,196 @@
|
||||
"""The host network a page sees is the one the session DECLARES, not the one of the machine (red until it is declared).
|
||||
|
||||
Design: ``invisible_WebRTC/notes/declared-interfaces-design.md`` and ``declared-interfaces-proofs.md`` (the private study
|
||||
repository). Behind a
|
||||
proxy the engine must not read the host's interfaces: the core declares one adapter in ``STEALTHFOX_WEBRTC_NETWORK``,
|
||||
``v4=<private address>;v6=<0|1>;p6=<the exit's /64 prefix, empty without IPv6>`` (the IPv6 host is that prefix and a
|
||||
temporary identifier; v6=1 without a prefix is no IPv6), and the engine answers the reads of the host (the interface list,
|
||||
the default route, the address and port a bound socket reports) from it (nr_stealth_network.h). A page
|
||||
then sees what retail Firefox on Windows shows on a machine with that adapter, whatever the machine under the browser has:
|
||||
|
||||
* no IPv6: ONE host name (udp + tcp), ranked 127 (the only address);
|
||||
* IPv6: TWO host names, the IPv6 one ranked 127 above the IPv4 one at 126 (``nrinterfaceprioritizer.cpp:82-85``);
|
||||
* the host ports are those of a Windows machine, chosen by our code: 49152-65535, a consecutive pair per connection
|
||||
(IPv4 N, IPv6 N+1), drawn at random by our code for each connection (not by the kernel, not from the seed: two visits
|
||||
with the same seed must not share ports), the same distribution on every host;
|
||||
* two connections on one page connect to each other in the time retail takes.
|
||||
|
||||
Reference shape (retail 159, measured 2026-11-11, ``captures/retail/firefox-159.0-win/direct-dualstack-stun-candidates``):
|
||||
host udp 2122252543 (IPv6) and 2122187007 (IPv4), host tcp 2105524479 and 2105458943, one name per address.
|
||||
|
||||
Red on an engine without the declared network (before webrtc/declared-interfaces b9bdb3c3ad + 6ca7a8c104): it gathered
|
||||
every filtered address of the OS and let the kernel hand out the ports, so these failed on every machine with more than
|
||||
one interface or a port range that is not Windows's, the IPv6 case everywhere, and the loopback test was slower than
|
||||
retail and died with no usable interface. Hermetic: a local TCP-only SOCKS5 proxy and a local page, no external network.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import statistics
|
||||
|
||||
import pytest
|
||||
|
||||
from test_webrtc_realness import (_FAKE_EGRESS, _e2e_binary, _launch, candidates, decode_priority, host_candidates,
|
||||
is_mdns, local_https_page, socks5_tcp_only) # noqa: F401 (fixtures)
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
NETWORK_ENV = "STEALTHFOX_WEBRTC_NETWORK"
|
||||
# retail 159 on Windows. The interface rank is the position in the prioritizer's sort, starting at 127
|
||||
# (nrinterfaceprioritizer.cpp:183-189), so an IPv4-only machine ranks its one host 127, and with IPv6 the IPv6 host
|
||||
# takes 127 and the IPv4 host 126.
|
||||
UDP_127, UDP_126, TCP_127, TCP_126 = 2122252543, 2122187007, 2105524479, 2105458943
|
||||
# The two shapes of the declared adapter: without IPv6, and with the exit's /64 prefix.
|
||||
V4_ONLY = "v4=192.168.31.7;v6=0;p6="
|
||||
DUAL = "v4=192.168.31.7;v6=1;p6=2a01:e0a:1f2:3450::/64"
|
||||
|
||||
_GATHER_JS = r"""async () => {
|
||||
const pc = new RTCPeerConnection({iceServers: []});
|
||||
pc.createDataChannel('');
|
||||
const cands = [];
|
||||
pc.addEventListener('icecandidate', e => { if (e.candidate && e.candidate.candidate) cands.push(e.candidate.candidate); });
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
await new Promise(r => setTimeout(r, 2500));
|
||||
try { pc.close(); } catch (e) {}
|
||||
return cands;
|
||||
}"""
|
||||
|
||||
# Two connections on one page, connected to each other in script (the loopback test many demos use).
|
||||
_LOOPBACK_JS = r"""async () => {
|
||||
const t0 = performance.now();
|
||||
const pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();
|
||||
pc1.onicecandidate = e => { if (e.candidate) pc2.addIceCandidate(e.candidate).catch(() => {}); };
|
||||
pc2.onicecandidate = e => { if (e.candidate) pc1.addIceCandidate(e.candidate).catch(() => {}); };
|
||||
const dc = pc1.createDataChannel('x');
|
||||
let opened = null, echoed = false;
|
||||
dc.onopen = () => { opened = Math.round(performance.now() - t0); dc.send('ping'); };
|
||||
pc2.ondatachannel = ev => { ev.channel.onmessage = m => ev.channel.send('pong:' + m.data); };
|
||||
dc.onmessage = m => { echoed = (m.data === 'pong:ping'); };
|
||||
await pc1.setLocalDescription(await pc1.createOffer());
|
||||
await pc2.setRemoteDescription(pc1.localDescription);
|
||||
await pc2.setLocalDescription(await pc2.createAnswer());
|
||||
await pc1.setRemoteDescription(pc2.localDescription);
|
||||
const deadline = performance.now() + 8000;
|
||||
while (performance.now() < deadline && !(opened !== null && echoed)) await new Promise(r => setTimeout(r, 5));
|
||||
pc1.close(); pc2.close();
|
||||
return {opened, echoed};
|
||||
}"""
|
||||
|
||||
# Retail 159 on Windows, 12 cold launches (``captures/mdns-loopback/retail-159-win-12``): 37-52 ms in ten of twelve, two
|
||||
# slow ones at about 110, median 41.5. Without mDNS retail takes about 20 ms (``retail-159-win-nomdns``): the other 20 ms are
|
||||
# the multicast round trip of the responder. The engine makes that round trip too, on the loopback (the responder joins and
|
||||
# speaks on 127.0.0.1; a name of ours answers with the loopback of its family), so the window is the retail one: 30-55 ms on
|
||||
# the MEDIAN of five cold launches. It keeps out "dead" (no usable interface), "slower than retail" and "faster than retail"
|
||||
# (an answer that skips the round trip).
|
||||
RETAIL_MEDIAN_WINDOW_MS = (30, 55)
|
||||
|
||||
|
||||
def _session(declaration, socks, page_url, monkeypatch, seed, script):
|
||||
"""One proxied launch with the declaration in the environment; runs ``script`` on the page and returns the result."""
|
||||
binary = _e2e_binary()
|
||||
if not binary:
|
||||
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
|
||||
monkeypatch.setenv("STEALTHFOX_WEBRTC_PUBLIC_IP", _FAKE_EGRESS)
|
||||
monkeypatch.delenv("STEALTHFOX_WEBRTC_DISABLE_IPV6", raising=False) # the declaration replaces it
|
||||
monkeypatch.setenv(NETWORK_ENV, declaration)
|
||||
prefs = {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": ""}
|
||||
proxy = {"server": "socks5://127.0.0.1:%d" % socks.port}
|
||||
with _launch(binary_path=binary, proxy=proxy, extra_prefs=prefs, seed=seed) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto(page_url, wait_until="domcontentloaded", timeout=60000)
|
||||
return script(page)
|
||||
|
||||
|
||||
def _host_shape(declaration, socks, page_url, monkeypatch, seed=42):
|
||||
return host_candidates(candidates(
|
||||
_session(declaration, socks, page_url, monkeypatch, seed, lambda page: page.evaluate(_GATHER_JS))))
|
||||
|
||||
|
||||
def _by_protocol(hosts):
|
||||
return {proto: sorted((c["priority"] for c in hosts if c["proto"] == proto), reverse=True)
|
||||
for proto in ("UDP", "TCP")}
|
||||
|
||||
|
||||
def _udp_ports_by_rank(hosts):
|
||||
return {decode_priority(c["priority"])["iface_pref"]: c["port"] for c in hosts if c["proto"] == "UDP"}
|
||||
|
||||
|
||||
def test_without_a_declared_ipv6_the_page_sees_one_host_name(local_https_page, socks5_tcp_only, monkeypatch):
|
||||
"""One adapter, no IPv6: a udp and a tcp host candidate on ONE mDNS name, ranked 127 as the only address.
|
||||
|
||||
The shape is a function of the declaration alone, so this must hold on every machine: run it on a host with three
|
||||
IPv4 adapters (the engine gathers all three today), in a container with two interfaces (``docker network connect``
|
||||
before ``docker start``), and in a container with one."""
|
||||
hosts = _host_shape(V4_ONLY, socks5_tcp_only, local_https_page, monkeypatch)
|
||||
assert all(is_mdns(c["address"]) for c in hosts), [c["address"] for c in hosts]
|
||||
assert len({c["address"] for c in hosts}) == 1, "host names: %r" % sorted({c["address"] for c in hosts})
|
||||
assert _by_protocol(hosts) == {"UDP": [UDP_127], "TCP": [TCP_127]}, _by_protocol(hosts)
|
||||
|
||||
|
||||
def test_a_declared_ipv6_gives_two_host_names_ranked_127_and_126(local_https_page, socks5_tcp_only, monkeypatch):
|
||||
"""One adapter with IPv6: two names; the IPv6 host ranks one above the IPv4 one, as on the retail capture."""
|
||||
hosts = _host_shape(DUAL, socks5_tcp_only, local_https_page, monkeypatch)
|
||||
assert all(is_mdns(c["address"]) for c in hosts), [c["address"] for c in hosts]
|
||||
assert len({c["address"] for c in hosts}) == 2, "host names: %r" % sorted({c["address"] for c in hosts})
|
||||
assert _by_protocol(hosts) == {"UDP": [UDP_127, UDP_126], "TCP": [TCP_127, TCP_126]}, _by_protocol(hosts)
|
||||
assert [decode_priority(p)["iface_pref"] for p in _by_protocol(hosts)["UDP"]] == [127, 126]
|
||||
|
||||
|
||||
def test_ipv6_without_the_exit_prefix_is_no_ipv6(local_https_page, socks5_tcp_only, monkeypatch):
|
||||
"""v6=1 with an empty prefix: the exit gave the core no /64, so the machine has no IPv6 address, and no fallback
|
||||
invents one. One host name, as without IPv6."""
|
||||
hosts = _host_shape("v4=192.168.31.7;v6=1;p6=", socks5_tcp_only, local_https_page, monkeypatch)
|
||||
assert _by_protocol(hosts) == {"UDP": [UDP_127], "TCP": [TCP_127]}, hosts
|
||||
|
||||
|
||||
def test_the_host_ports_are_those_of_a_windows_machine(local_https_page, socks5_tcp_only, monkeypatch):
|
||||
"""Retail on Windows (6 of 6 runs, ``captures/retail/firefox-159.0-win/direct-dualstack-srflx-ports``): the UDP host
|
||||
ports are in the dynamic range 49152-65535 and, on one connection, the IPv4 port and the IPv6 port are consecutive
|
||||
(N, N+1). A page reads them. Linux hands out 32768-60999 at random, so on a Linux host this is red today."""
|
||||
hosts = _host_shape(DUAL, socks5_tcp_only, local_https_page, monkeypatch)
|
||||
by_rank = _udp_ports_by_rank(hosts)
|
||||
assert sorted(by_rank) == [126, 127], by_rank
|
||||
assert all(49152 <= port <= 65535 for port in by_rank.values()), by_rank
|
||||
assert by_rank[127] == by_rank[126] + 1, "IPv4 port %d, IPv6 port %d" % (by_rank[126], by_rank[127])
|
||||
|
||||
|
||||
def test_the_host_port_is_in_the_windows_range_without_ipv6_too(local_https_page, socks5_tcp_only, monkeypatch):
|
||||
"""The one-address case of the range check. On a Linux host it can pass by luck (a kernel port in 49152-60999 falls
|
||||
in the range); the same-seed test above is the one that cannot."""
|
||||
hosts = _host_shape(V4_ONLY, socks5_tcp_only, local_https_page, monkeypatch)
|
||||
by_rank = _udp_ports_by_rank(hosts)
|
||||
assert list(by_rank) == [127] and 49152 <= by_rank[127] <= 65535, by_rank
|
||||
|
||||
|
||||
def _ports_of_two_connections(declaration, socks, page_url, monkeypatch, seed):
|
||||
def script(page):
|
||||
first = host_candidates(candidates(page.evaluate(_GATHER_JS)))
|
||||
second = host_candidates(candidates(page.evaluate(_GATHER_JS)))
|
||||
return first, second
|
||||
|
||||
first, second = _session(declaration, socks, page_url, monkeypatch, seed, script)
|
||||
return (sorted(c["port"] for c in first if c["proto"] == "UDP"),
|
||||
sorted(c["port"] for c in second if c["proto"] == "UDP"))
|
||||
|
||||
|
||||
def test_two_connections_on_one_page_get_their_own_port_pair(local_https_page, socks5_tcp_only, monkeypatch):
|
||||
"""Retail (``captures/retail/firefox-159.0-win/two-pc-port-sequence``, 6 of 6): each connection gets its own pair,
|
||||
consecutive (N, N+1) in the range, and the second pair is unrelated to the first (not increasing)."""
|
||||
first, second = _ports_of_two_connections(DUAL, socks5_tcp_only, local_https_page, monkeypatch, 42)
|
||||
for pair in (first, second):
|
||||
assert len(pair) == 2 and pair[1] == pair[0] + 1 and 49152 <= pair[0] and pair[1] <= 65535, (first, second)
|
||||
assert first != second, (first, second)
|
||||
|
||||
|
||||
def test_two_connections_on_one_page_connect_in_the_time_of_retail(local_https_page, socks5_tcp_only, monkeypatch):
|
||||
"""The names the browser registered for itself must resolve although the declared address is not the host's, and in
|
||||
the time retail takes: not slower (a responder that cannot hear itself, or an OS list that is empty, kills the test),
|
||||
not faster (an answer that skips the round trip). Five cold launches, median in the retail window."""
|
||||
times = []
|
||||
for n in range(5):
|
||||
res = _session(V4_ONLY, socks5_tcp_only, local_https_page, monkeypatch, 100 + n,
|
||||
lambda page: page.evaluate(_LOOPBACK_JS))
|
||||
assert res["echoed"] and res["opened"] is not None, "run %d: the data channel did not open: %r" % (n, res)
|
||||
times.append(res["opened"])
|
||||
low, high = RETAIL_MEDIAN_WINDOW_MS
|
||||
median = statistics.median(times)
|
||||
assert low <= median <= high, "median %s ms of %r, retail window %d-%d ms" % (median, sorted(times), low, high)
|
||||
@@ -0,0 +1,105 @@
|
||||
"""A proxied session declares Firefox's DoH in mode 3 through the proxy; a session without a proxy declares no DoH.
|
||||
|
||||
The contract (core-19): with a proxy, every name the browser resolves goes to DoH, and a DoH request is a channel like
|
||||
any other, so it leaves through the proxy of the context of the lookup. What the core writes to make that so:
|
||||
|
||||
network.trr.mode = 3 no fallback to the resolver of the machine
|
||||
network.trr.uri = https://mozilla.cloudflare-dns.com/dns-query
|
||||
network.trr.bootstrapAddr = <an IP> the DoH host is found with no DNS at all
|
||||
network.trr.exclude-etc-hosts = False the hosts file of the machine answers nothing
|
||||
network.trr.excluded-domains = <proxy> ONLY when the proxy is given by NAME: the one name the system resolver
|
||||
answers (DoH needs the proxy); an address needs no lookup
|
||||
network.proxy.allow_bypass = False no channel falls back to direct when the proxy stumbles
|
||||
network.parental_controls_cached_state = False declared off, as retail without the service
|
||||
|
||||
Two doors are checked, because the e2e launches through the second: the core's composer, and the wrapper's own path
|
||||
(`InvisiblePlaywright._build_prefs` and the core's proxy step, what a launch composes). Nothing here starts a browser or the network (the
|
||||
suite's autouse fixture answers the egress lookup).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_core import decide_session_locale
|
||||
from invisible_core._fpforge import generate_profile
|
||||
from invisible_core.prefs import compose_session_prefs
|
||||
|
||||
from invisible_playwright import _session
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
URI = "https://mozilla.cloudflare-dns.com/dns-query"
|
||||
NAMED = {"server": "socks5://gw.example.test:1080"}
|
||||
BY_ADDRESS = {"server": "socks5://203.0.113.9:1080"}
|
||||
HTTP_WITH_CREDENTIALS = {"server": "http://gw.example.test:3128", "username": "u", "password": "p"}
|
||||
HTTP_BY_V6_ADDRESS = {"server": "http://[2001:db8::1]:3128"}
|
||||
|
||||
|
||||
def _core(proxy):
|
||||
return compose_session_prefs(generate_profile(seed=42), locale=decide_session_locale("en-US"),
|
||||
timezone="America/New_York", proxy=proxy).prefs
|
||||
|
||||
|
||||
def _wrapper(proxy):
|
||||
"""What the launcher composes: the session's prefs (`_build_prefs`), then the core's proxy step
|
||||
(`configure_proxy`) on them, exactly as `launcher.__enter__` and `remote.op_launch` do."""
|
||||
from invisible_core import configure_proxy
|
||||
from invisible_playwright.launcher import InvisiblePlaywright
|
||||
|
||||
session = InvisiblePlaywright(seed=42, binary_path="firefox.exe", humanize=False, proxy=proxy or None)
|
||||
geo = _session.session_geo(session._timezone, session._proxy, session._locale_requested)
|
||||
session._timezone, session._locale = geo.timezone, geo.locale
|
||||
prefs = session._build_prefs()
|
||||
configure_proxy(session._proxy, prefs)
|
||||
return prefs
|
||||
|
||||
|
||||
@pytest.fixture(params=[_core, _wrapper], ids=["core", "wrapper"])
|
||||
def compose(request):
|
||||
return request.param
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proxy", [NAMED, BY_ADDRESS, HTTP_WITH_CREDENTIALS, HTTP_BY_V6_ADDRESS],
|
||||
ids=["socks-name", "socks-ip", "http-name", "http-ipv6"])
|
||||
def test_a_proxied_session_declares_doh_in_mode_3(compose, proxy):
|
||||
prefs = compose(proxy)
|
||||
assert prefs["network.trr.mode"] == 3
|
||||
assert prefs["network.trr.uri"] == URI
|
||||
ipaddress.ip_address(prefs["network.trr.bootstrapAddr"]) # raises unless it is an IP literal
|
||||
assert prefs["network.trr.exclude-etc-hosts"] is False
|
||||
assert prefs["network.proxy.allow_bypass"] is False
|
||||
assert prefs["network.parental_controls_cached_state"] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proxy, host", [(NAMED, "gw.example.test"), (HTTP_WITH_CREDENTIALS, "gw.example.test")])
|
||||
def test_a_proxy_named_by_a_name_is_the_one_name_the_system_resolver_answers(compose, proxy, host):
|
||||
assert compose(proxy)["network.trr.excluded-domains"] == host
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proxy", [BY_ADDRESS, HTTP_BY_V6_ADDRESS], ids=["ipv4", "ipv6"])
|
||||
def test_a_proxy_given_by_an_address_excludes_nothing(compose, proxy):
|
||||
assert "network.trr.excluded-domains" not in compose(proxy)
|
||||
|
||||
|
||||
def test_the_bootstrap_address_is_a_public_address_and_not_the_proxy(compose):
|
||||
bootstrap = ipaddress.ip_address(compose(BY_ADDRESS)["network.trr.bootstrapAddr"])
|
||||
assert bootstrap.is_global and str(bootstrap) != "203.0.113.9"
|
||||
|
||||
|
||||
def test_a_session_without_a_proxy_declares_no_doh(compose):
|
||||
prefs = compose(None)
|
||||
assert [k for k in prefs if k.startswith("network.trr.")] == []
|
||||
assert prefs.get("network.proxy.allow_bypass") is not False, "no proxy, no closed fallback"
|
||||
assert prefs["network.parental_controls_cached_state"] is False, "declared off with or without a proxy"
|
||||
|
||||
|
||||
def test_the_doh_prefs_are_the_same_for_the_same_proxy_whatever_the_seed():
|
||||
"""Nothing about the DoH is drawn from the seed: two sessions behind the same proxy declare the same DoH."""
|
||||
def trr(seed):
|
||||
prefs = compose_session_prefs(generate_profile(seed=seed), locale=decide_session_locale("en-US"),
|
||||
timezone="America/New_York", proxy=NAMED).prefs
|
||||
return {k: v for k, v in prefs.items() if k.startswith("network.trr.")}
|
||||
|
||||
assert trr(1) == trr(2) == trr(970411)
|
||||
@@ -0,0 +1,432 @@
|
||||
"""E2E: behind a proxy every name is resolved by Firefox's DoH THROUGH the proxy, and nothing leaves the host.
|
||||
|
||||
WRITTEN AGAINST THE CONTRACT, BEFORE THE ENGINE THAT KEEPS IT EXISTS. No binary in this tree has the behaviour yet, so
|
||||
these tests cannot go green here; what is proven now is that the tools they stand on are right
|
||||
(`test_the_fake_doh_answers.py`, `test_the_http_proxy_helper_asks_for_credentials.py`,
|
||||
`test_the_leak_watcher_sees_a_direct_connection.py`) and that the session declares what the contract starts from
|
||||
(`test_doh_session_prefs_unit.py`). Run against an engine that keeps the contract, they are the proof; run against one
|
||||
that does not, each of them fails on the thing it names.
|
||||
|
||||
The contract (core-19 and motore-18): a PROXIED session declares TRR mode 3 (`network.trr.uri` the DoH of Mozilla,
|
||||
`network.trr.bootstrapAddr` an address so the DoH host is found with no DNS, `network.proxy.allow_bypass` false).
|
||||
Every name the browser resolves - page hosts, ICE server names, HTTP/3 hosts - goes to that DoH; a DoH request is a
|
||||
channel like any other, so it leaves THROUGH the session proxy (a SOCKS5 CONNECT or an HTTP CONNECT to
|
||||
162.159.61.4:443), by the proxy of the context of the lookup; the browser then connects to the resolved ADDRESS (SOCKS5
|
||||
by address, never by name). The session proxy is the first command on the pipe, and every proxied channel waits for
|
||||
it: nothing goes DIRECT. No UDP/53 and no direct TCP leave the browser, and no helper process (crash reporter, default
|
||||
browser agent, maintenance service, updater, pingsender) is started.
|
||||
|
||||
How each test sees it, with nothing but loopback:
|
||||
|
||||
* `FakeDoh` answers the names (`page-a.test`...) and records every query with the gateway it arrived by (`via`);
|
||||
* `DohGateway` / `HttpProxy` are the proxies; a CONNECT to the DoH address is handed to the FakeDoh, every other one to
|
||||
a loopback address is relayed, and every CONNECT is recorded (a CONNECT that carries a NAME is a defect to find);
|
||||
* `Watcher` samples the connections of every browser process from before the launch: one to a non-loopback address is
|
||||
a direct connection;
|
||||
* `ResolverTrap` (Linux, root) points /etc/resolv.conf at a counting resolver: one question is a leak to the resolver
|
||||
of the machine. Where it cannot run, its assertions are skipped, not the test.
|
||||
|
||||
Pages are served by a local HTTP server on 127.0.0.1 and reached by NAMES only the FakeDoh can resolve. The browser must
|
||||
accept the FakeDoh certificate: the pages are opened in contexts made with `ignore_https_errors=True`, which the engine
|
||||
implements per user context (`Browser.setIgnoreHTTPSErrors` -> `nsICertOverrideService`, keyed by the origin attributes
|
||||
of the TLS socket), and a DoH request of a lookup carries the user context of that lookup
|
||||
(`StealthApplyTRRContextToChannel`). So the lookups of THESE contexts accept the certificate; a lookup of the default
|
||||
context (user context 0: the browser's own background resolutions) cannot be made to, and mode 3 does not need it. This
|
||||
is why a test says "a context with no proxy of its own" where the brief says "the default context".
|
||||
|
||||
Assumptions that could not be verified without the engine, each one the first place to look if a test fails for no
|
||||
visible reason: (1) the TRR channel of a lookup in a context honours `ignore_https_errors` of that context; (2) the
|
||||
ICE resolver's lookup carries the origin attributes of its document; (3) Firefox's TRR accepts HTTP/1.1 as well as h2
|
||||
(the FakeDoh offers both; `doh.alpn_of(...)` says which one was used); (4) the DoH and page connections reach a SOCKS
|
||||
gateway as ADDRESSES; (5) behind an HTTP proxy an `http` page's name goes to the proxy inside the request (it is the
|
||||
proxy that resolves it), so the DoH is triggered there by an ICE server name, which the browser always resolves itself.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import http.server
|
||||
import ipaddress
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_core import SessionGeo, decide_session_locale
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
import _doh_servers as ds
|
||||
from _doh_servers import DOH_BOOTSTRAP, DOH_HOST, DOH_PORT, QTYPE_A, DohGateway, FakeDoh
|
||||
from _http_proxy import HttpProxy, basic
|
||||
from _leaks import ResolverTrap, Watcher
|
||||
from _servers import LocalServer
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
#: The zone of the FakeDoh: every name a test uses, all pointing at the loopback where the page server is.
|
||||
ZONE = {"page-a.test": "127.0.0.1", "page-b.test": "127.0.0.1", "page-c.test": "127.0.0.1",
|
||||
"stun-a.test": "127.0.0.1"}
|
||||
#: Loopback targets go through the proxy too (as in test_proxy_socks_auth_e2e.py), so the road of a page is observable.
|
||||
PREFS = {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": ""}
|
||||
#: The helper processes of Firefox that a session behind a proxy must never start (match on the executable's stem).
|
||||
HELPERS = ("crashreporter", "default-browser-agent", "maintenanceservice", "updater", "pingsender")
|
||||
GEO = SessionGeo("America/New_York", "203.0.113.7", latitude=40.7128, longitude=-74.0060,
|
||||
locale=decide_session_locale("en-US"))
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------------- fixtures
|
||||
@pytest.fixture(autouse=True)
|
||||
def _hermetic_session(monkeypatch):
|
||||
"""No egress lookup on the internet, and no egress drift check through the proxy.
|
||||
|
||||
A launch asks "who am I" through the proxy (api.ipify.org by NAME, resolved by the TEST process: a question to the
|
||||
resolver trap and a connection past the loopback), and re-asks at every new context. This test is about the
|
||||
BROWSER's roads, so the answer is declared: the same facts (timezone, locale, position, an exit address) the
|
||||
lookup would have returned.
|
||||
"""
|
||||
monkeypatch.setattr("invisible_playwright.launcher.prepare_session_geo", lambda tz, proxy, locale: GEO)
|
||||
monkeypatch.setattr(InvisiblePlaywright, "_assert_uscita_invariata", lambda self: None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def doh():
|
||||
pytest.importorskip("h2", reason="Firefox's TRR speaks h2: the FakeDoh serves it with the h2 package "
|
||||
"(pip install h2); without it only HTTP/1.1 would be exercised")
|
||||
server = FakeDoh(ZONE)
|
||||
yield server
|
||||
server.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def gateway(doh):
|
||||
made = []
|
||||
|
||||
def make(name, **kwargs):
|
||||
gw = DohGateway(name, doh, **kwargs)
|
||||
made.append(gw)
|
||||
return gw
|
||||
|
||||
yield make
|
||||
for gw in made:
|
||||
gw.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def trap():
|
||||
"""The resolver trap, counting every question the machine's resolver is asked; None where it cannot run."""
|
||||
if not ResolverTrap.available:
|
||||
yield None
|
||||
return
|
||||
resolver = ResolverTrap()
|
||||
try:
|
||||
resolver.__enter__()
|
||||
except OSError: # port 53 taken (another worker holds the trap)
|
||||
yield None
|
||||
return
|
||||
try:
|
||||
yield resolver
|
||||
finally:
|
||||
resolver.__exit__(None, None, None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def watcher(firefox_binary):
|
||||
"""Started BEFORE the test body, so before any launch; stopped by the test or here."""
|
||||
w = Watcher(match=("firefox", Path(firefox_binary).stem.lower())).start()
|
||||
yield w
|
||||
w.stop()
|
||||
|
||||
|
||||
class Pages:
|
||||
"""A local HTTP server: every path answers a page that says which Host it was asked for."""
|
||||
|
||||
def __init__(self):
|
||||
outer = self
|
||||
self.hits = []
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self): # noqa: N802
|
||||
host = self.headers.get("Host", "")
|
||||
outer.hits.append((host, self.path))
|
||||
body = ("<!doctype html><title>page</title><body>HOST=%s</body>" % host).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
self._server = LocalServer(("127.0.0.1", 0), Handler)
|
||||
self.port = self._server.server_address[1]
|
||||
threading.Thread(target=self._server.serve_forever, daemon=True).start()
|
||||
|
||||
def url(self, name):
|
||||
return "http://%s:%d/" % (name, self.port)
|
||||
|
||||
def close(self):
|
||||
self._server.shutdown()
|
||||
self._server.server_close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pages():
|
||||
server = Pages()
|
||||
yield server
|
||||
server.close()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------- helpers
|
||||
def _launch(binary, proxy, **kwargs):
|
||||
return InvisiblePlaywright(seed=42, binary_path=binary, proxy=proxy, extra_prefs=dict(PREFS), **kwargs)
|
||||
|
||||
|
||||
def _page_in(browser, proxy=None):
|
||||
"""A page in a new context, with its own proxy when given and the FakeDoh's certificate accepted."""
|
||||
options = {"ignore_https_errors": True}
|
||||
if proxy is not None:
|
||||
options["proxy"] = proxy
|
||||
context = browser.new_context(**options)
|
||||
return context, context.new_page()
|
||||
|
||||
|
||||
def _text(page):
|
||||
return page.evaluate("() => document.body.innerText")
|
||||
|
||||
|
||||
def _why(doh, *proxies):
|
||||
"""What every side saw, for the message of a failed assertion."""
|
||||
lines = ["FakeDoh queries: %s" % [tuple(q) for q in doh.queries],
|
||||
"FakeDoh connections (via, protocol): %s" % doh.connections,
|
||||
"FakeDoh TLS failures: %s" % doh.tls_failures]
|
||||
for p in proxies:
|
||||
lines.append("%s CONNECTs: %s" % (p.name, p.connects))
|
||||
if getattr(p, "refused", None):
|
||||
lines.append("%s refused: %s" % (p.name, p.refused))
|
||||
return "\n " + "\n ".join(lines)
|
||||
|
||||
|
||||
def _is_address(host):
|
||||
try:
|
||||
ipaddress.ip_address(host)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def _assert_stayed_home(watcher, trap=None):
|
||||
"""Nothing went past the gateway (no direct connection) and nothing asked the machine's resolver."""
|
||||
assert watcher.watched_pids, ("the watcher never saw a browser process (it saw: %s): a watcher that cannot see "
|
||||
"proves nothing" % watcher.process_names)
|
||||
assert watcher.direct == [], "the browser connected past the gateway: %s" % watcher.describe()
|
||||
if trap is not None:
|
||||
assert trap.queries == [], "the browser asked the resolver of the machine: %s" % trap.describe()
|
||||
|
||||
|
||||
def _create_a_peer_connection_for(page, name):
|
||||
"""An RTCPeerConnection whose ICE server is `stun:<name>:3478`, gathering started: the browser resolves the name."""
|
||||
page.evaluate("""(name) => {
|
||||
const pc = new RTCPeerConnection({iceServers: [{urls: 'stun:' + name + ':3478'}]});
|
||||
window.__pc = pc;
|
||||
pc.createDataChannel('probe');
|
||||
pc.createOffer().then(offer => pc.setLocalDescription(offer));
|
||||
}""", name)
|
||||
|
||||
|
||||
# ============================================================================================================ tests
|
||||
def test_names_resolve_through_doh_by_the_proxy(firefox_binary, doh, pages, gateway, trap, watcher):
|
||||
"""A page name is asked to the DoH, by the proxy, and the page is then reached by ADDRESS."""
|
||||
gw1 = gateway("gw1")
|
||||
with _launch(firefox_binary, gw1.proxy) as browser:
|
||||
context, page = _page_in(browser)
|
||||
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
|
||||
text = _text(page)
|
||||
context.close()
|
||||
watcher.stop()
|
||||
|
||||
assert "HOST=page-a.test:%d" % pages.port in text, "the page did not load through the proxy: %r" % text
|
||||
why = _why(doh, gw1)
|
||||
assert doh.vias_of("page-a.test", QTYPE_A) == {"gw1"}, "page-a.test (A) was not asked by gw1 only" + why
|
||||
assert (DOH_BOOTSTRAP, DOH_PORT) in gw1.connects, "no DoH CONNECT to the bootstrap address" + why
|
||||
assert not [h for h, _p in gw1.connects if h == "page-a.test"], (
|
||||
"the browser sent the NAME page-a.test to the proxy instead of resolving it" + why)
|
||||
assert [h for h, _p in gw1.connects if not _is_address(h) and h != DOH_HOST] == [], (
|
||||
"a CONNECT carried a name: the browser must resolve with the DoH and connect by address" + why)
|
||||
assert ("127.0.0.1", pages.port) in gw1.connects, "the page was not reached by address through gw1" + why
|
||||
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without the proxy" + why
|
||||
_assert_stayed_home(watcher, trap)
|
||||
|
||||
|
||||
def test_an_ice_server_name_resolves_the_same_way(firefox_binary, doh, pages, gateway, trap, watcher):
|
||||
"""A name chosen by the PAGE (a STUN server in iceServers) is resolved by the DoH through the proxy too."""
|
||||
gw1 = gateway("gw1")
|
||||
with _launch(firefox_binary, gw1.proxy) as browser:
|
||||
context, page = _page_in(browser)
|
||||
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
|
||||
_create_a_peer_connection_for(page, "stun-a.test")
|
||||
asked = ds.wait_until(lambda: doh.queries_for("stun-a.test"), 30)
|
||||
page.evaluate("() => window.__pc.close()")
|
||||
context.close()
|
||||
watcher.stop()
|
||||
|
||||
why = _why(doh, gw1)
|
||||
assert asked, "the browser never asked the DoH for the ICE server name" + why
|
||||
assert doh.vias_of("stun-a.test") == {"gw1"}, "stun-a.test was not asked by gw1 only" + why
|
||||
_assert_stayed_home(watcher, trap)
|
||||
|
||||
|
||||
def test_two_contexts_two_doh_exits(firefox_binary, doh, pages, gateway, trap, watcher):
|
||||
"""Each context resolves by ITS proxy: the browser's for a context with none, its own for context B, each with
|
||||
the credentials of that gateway."""
|
||||
gw1 = gateway("gw1", user="gw1-user", password="gw1-pass")
|
||||
gw2 = gateway("gw2", user="gw2-user", password="gw2-pass")
|
||||
with _launch(firefox_binary, gw1.proxy) as browser:
|
||||
context_a, page_a = _page_in(browser) # no proxy of its own: the browser's, gw1
|
||||
context_b, page_b = _page_in(browser, proxy=gw2.proxy) # its own: gw2
|
||||
page_a.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
|
||||
page_b.goto(pages.url("page-b.test"), wait_until="load", timeout=30000)
|
||||
text_a, text_b = _text(page_a), _text(page_b)
|
||||
context_a.close()
|
||||
context_b.close()
|
||||
watcher.stop()
|
||||
|
||||
why = _why(doh, gw1, gw2)
|
||||
assert "HOST=page-a.test" in text_a and "HOST=page-b.test" in text_b, (text_a, text_b)
|
||||
assert doh.vias_of("page-a.test", QTYPE_A) == {"gw1"}, "page-a.test must be resolved by gw1 only" + why
|
||||
assert doh.vias_of("page-b.test", QTYPE_A) == {"gw2"}, "page-b.test must be resolved by gw2 only" + why
|
||||
assert gw1.doh_connects() and gw2.doh_connects(), "each gateway must have carried a DoH CONNECT" + why
|
||||
assert ("127.0.0.1", pages.port) in gw1.connects and ("127.0.0.1", pages.port) in gw2.connects, (
|
||||
"each page must be reached by address through the gateway of its context" + why)
|
||||
assert gw1.credentials_seen and set(gw1.credentials_seen) == {("gw1-user", "gw1-pass")}, (
|
||||
"gw1 saw: %s" % gw1.credentials_seen)
|
||||
assert gw2.credentials_seen and set(gw2.credentials_seen) == {("gw2-user", "gw2-pass")}, (
|
||||
"gw2 saw: %s" % gw2.credentials_seen)
|
||||
_assert_stayed_home(watcher, trap)
|
||||
|
||||
|
||||
def test_an_authenticated_http_proxy_resolves(firefox_binary, doh, pages, trap, watcher):
|
||||
"""An http proxy with credentials: the DoH CONNECT carries the PREEMPTIVE `Proxy-Authorization: Basic`, so it
|
||||
never needs a 407 round trip, and the page loads.
|
||||
|
||||
Behind an HTTP proxy an `http` page's NAME goes to the proxy (which resolves it), so the browser's own DoH is
|
||||
triggered here by an ICE server name, which the browser always resolves itself.
|
||||
"""
|
||||
user, password = "ferd_http_user", "pw-é42"
|
||||
proxy = HttpProxy("http1", doh, user=user, password=password)
|
||||
try:
|
||||
with _launch(firefox_binary, proxy.proxy) as browser:
|
||||
context, page = _page_in(browser)
|
||||
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
|
||||
text = _text(page)
|
||||
_create_a_peer_connection_for(page, "stun-a.test")
|
||||
asked = ds.wait_until(lambda: doh.queries_for("stun-a.test"), 30)
|
||||
page.evaluate("() => window.__pc.close()")
|
||||
context.close()
|
||||
watcher.stop()
|
||||
|
||||
expected = "Basic " + base64.b64encode(("%s:%s" % (user, password)).encode("utf-8")).decode("ascii")
|
||||
assert expected == basic(user, password)
|
||||
why = _why(doh, proxy)
|
||||
assert "HOST=page-a.test:%d" % pages.port in text, "the page did not load through the proxy: %r" % text
|
||||
assert asked and doh.vias_of("stun-a.test") == {"http1"}, "the DoH was not reached through the proxy" + why
|
||||
authorizations = proxy.doh_authorizations()
|
||||
assert authorizations, "no DoH CONNECT reached the proxy" + why
|
||||
assert set(authorizations) == {expected}, (
|
||||
"every DoH CONNECT must carry the preemptive Basic header %r, saw %r" % (expected, authorizations) + why)
|
||||
assert [s for s in proxy.refused_for_credentials if (s.host, s.port) in ds.DOH_TARGETS] == [], (
|
||||
"the DoH CONNECT needed a 407 round trip: the header was not preemptive" + why)
|
||||
_assert_stayed_home(watcher, trap)
|
||||
finally:
|
||||
proxy.close()
|
||||
|
||||
|
||||
def test_nothing_leaves_the_host_between_launch_and_the_first_command(firefox_binary, doh, pages, gateway, trap,
|
||||
watcher):
|
||||
"""The watcher runs from before the launch to the first navigation, against a gateway that is slow to say hello
|
||||
(its first accepted connection is answered a second late): the session proxy is the first command on the pipe and
|
||||
every proxied channel is held until then, so nothing may leave meanwhile."""
|
||||
gw1 = gateway("gw1", first_connection_delay=1.0)
|
||||
with _launch(firefox_binary, gw1.proxy) as browser:
|
||||
context, page = _page_in(browser)
|
||||
page.goto(pages.url("page-a.test"), wait_until="load", timeout=45000)
|
||||
text = _text(page)
|
||||
context.close()
|
||||
watcher.stop()
|
||||
|
||||
why = _why(doh, gw1)
|
||||
assert "HOST=page-a.test" in text
|
||||
assert gw1.accepted_at, "the browser never connected to the gateway" + why
|
||||
_assert_stayed_home(watcher, trap)
|
||||
|
||||
|
||||
def test_no_helper_process_starts(firefox_binary, doh, pages, gateway, trap, watcher):
|
||||
"""No crash reporter client, default browser agent, maintenance service, updater or pingsender is started,
|
||||
through the first five seconds of the session and its teardown (pingsender is the one that starts at exit)."""
|
||||
gw1 = gateway("gw1")
|
||||
with _launch(firefox_binary, gw1.proxy) as browser:
|
||||
context, page = _page_in(browser)
|
||||
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
|
||||
time.sleep(5)
|
||||
context.close()
|
||||
time.sleep(1) # the processes of the exit
|
||||
watcher.stop()
|
||||
|
||||
assert watcher.watched_pids, "the watcher never saw a browser process: %s" % watcher.process_names
|
||||
started = watcher.helpers_seen(HELPERS)
|
||||
assert started == [], "helper processes were started: %s (all processes seen: %s)" % (
|
||||
started, watcher.process_names)
|
||||
|
||||
|
||||
def test_a_dead_proxy_does_not_fall_back(firefox_binary, doh, pages, gateway, trap, watcher):
|
||||
"""When the proxy dies, a navigation fails: it does not go direct and does not reach the resolver of the machine.
|
||||
|
||||
`page-c.test` is not cached anywhere and the FakeDoh would answer it if it were reached.
|
||||
"""
|
||||
gw1 = gateway("gw1")
|
||||
with _launch(firefox_binary, gw1.proxy) as browser:
|
||||
context, page = _page_in(browser)
|
||||
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
|
||||
gw1.kill()
|
||||
with pytest.raises(Exception) as failed:
|
||||
page.goto(pages.url("page-c.test"), wait_until="load", timeout=20000)
|
||||
context.close()
|
||||
watcher.stop()
|
||||
|
||||
why = _why(doh, gw1)
|
||||
assert pages.hits and all(host.startswith("page-a.test") for host, _p in pages.hits), (
|
||||
"the dead proxy still served a page: %s" % pages.hits + why)
|
||||
assert doh.queries_for("page-c.test") == [], "page-c.test was resolved after the proxy died" + why
|
||||
assert gw1.killed and failed.value is not None
|
||||
_assert_stayed_home(watcher, trap)
|
||||
|
||||
|
||||
def test_a_session_without_a_proxy_resolves_with_the_system_resolver(firefox_binary, pages, watcher):
|
||||
"""The negative control: with no proxy the exit is the machine's own network and retail resolves with the system
|
||||
resolver (mode 0). No `network.trr.*` pref is declared, and the resolver trap sees the question."""
|
||||
if not ResolverTrap.available:
|
||||
pytest.skip(ResolverTrap.reason)
|
||||
zone = {"page-d.test": "127.0.0.1"}
|
||||
session = InvisiblePlaywright(seed=42, binary_path=firefox_binary, proxy=None)
|
||||
session._timezone, session._locale = GEO.timezone, GEO.locale
|
||||
declared = [k for k in session._build_prefs() if k.startswith("network.trr.")]
|
||||
assert declared == [], "a session without a proxy declared TRR prefs: %s" % declared
|
||||
|
||||
try:
|
||||
trap = ResolverTrap(zone)
|
||||
trap.__enter__()
|
||||
except OSError:
|
||||
pytest.skip("port 53 is taken (another worker holds the resolver trap)")
|
||||
try:
|
||||
with session as browser:
|
||||
context = browser.new_context()
|
||||
page = context.new_page()
|
||||
page.goto(pages.url("page-d.test"), wait_until="load", timeout=30000)
|
||||
text = _text(page)
|
||||
context.close()
|
||||
finally:
|
||||
trap.__exit__(None, None, None)
|
||||
watcher.stop()
|
||||
|
||||
assert "HOST=page-d.test:%d" % pages.port in text, "the page did not load through the system resolver: %r" % text
|
||||
assert trap.asked("page-d.test"), "the system resolver was never asked for page-d.test: %s" % trap.describe()
|
||||
@@ -0,0 +1,90 @@
|
||||
"""HTTP/3 behind a SOCKS5 proxy: the page reads `nextHopProtocol`, and a retail Firefox with no proxy uses h3.
|
||||
|
||||
⛔ THE KNOWN-BAD INPUT: the engine refuses HTTP/3 whenever a proxy is in use (AltSvcCache::UpdateAltServiceMapping, the
|
||||
attempt of DnsAndConnectSocket, HttpBaseChannel), so a page behind a SOCKS5 gateway that relays UDP read `h2` where the
|
||||
same Firefox with no proxy reads `h3`. With a gateway that relays UDP the QUIC connection goes through the ASSOCIATE of the
|
||||
proxy (the server sees the relay, never this host); with one that does not, the QUIC handshake never completes and Firefox
|
||||
falls back to h2 by itself, and nothing UDP leaves this host direct.
|
||||
|
||||
The server is local, reached by its address (an address of this host that is not loopback: a loopback destination goes
|
||||
direct whatever the proxy), with a self-signed certificate (the context ignores certificate errors).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import socket
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
|
||||
def _binary():
|
||||
cand = os.environ.get("STEALTHFOX_E2E_BINARY") or os.environ.get("INVPW_BINARY_PATH")
|
||||
if not cand or not os.path.exists(cand):
|
||||
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
|
||||
return cand
|
||||
|
||||
|
||||
def _address_of_this_host() -> str:
|
||||
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
probe.connect(("192.0.2.1", 9))
|
||||
return probe.getsockname()[0]
|
||||
finally:
|
||||
probe.close()
|
||||
|
||||
|
||||
_FETCH = """async (url) => {
|
||||
const seen = [];
|
||||
for (let i = 0; i < 12; i++) {
|
||||
const r = await fetch(url + '?n=' + i, {cache: 'no-store', mode: 'no-cors'});
|
||||
await r.arrayBuffer();
|
||||
const entry = performance.getEntriesByType('resource').filter(e => e.name.includes('?n=' + i)).pop();
|
||||
seen.push(entry ? entry.nextHopProtocol : '?');
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
}
|
||||
return seen;
|
||||
}"""
|
||||
|
||||
|
||||
def _protocols_behind(gateway, server, monkeypatch):
|
||||
from invisible_core import _geo
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", lambda *_a, **_k: gateway.tcp_exit)
|
||||
with InvisiblePlaywright(headless=True, binary_path=_binary(), timezone="America/New_York",
|
||||
proxy=gateway.proxy) as browser:
|
||||
context = browser.new_context(ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
page.goto(server.url, wait_until="load", timeout=60000) # the answer that carries Alt-Svc: h3
|
||||
page.wait_for_timeout(1500)
|
||||
return page.evaluate(_FETCH, server.url)
|
||||
|
||||
|
||||
def test_a_page_behind_a_gateway_that_relays_udp_reads_h3_and_the_quic_goes_by_the_relay(monkeypatch):
|
||||
pytest.importorskip("aioquic")
|
||||
from _h3_server import H3Server
|
||||
from _socks_servers import coherent
|
||||
|
||||
host = _address_of_this_host()
|
||||
with H3Server(host) as server, coherent(user="alice", password="s3cret", relay_host=host) as gateway:
|
||||
protocols = _protocols_behind(gateway, server, monkeypatch)
|
||||
carried = [(h, p) for h, p, _data in gateway.datagrams if (h, p) == (host, server.port)]
|
||||
assert "h3" in protocols, f"nextHopProtocol of 12 fetches behind a gateway that relays UDP: {protocols}"
|
||||
assert carried, "the QUIC datagrams did not go by the relay of the gateway"
|
||||
assert server.quic_peers and set(server.quic_peers) == {"127.0.0.1"}, (
|
||||
f"the QUIC server saw {server.quic_peers}: only the relay of the gateway (127.0.0.1) may reach it")
|
||||
|
||||
|
||||
def test_a_page_behind_a_gateway_without_udp_falls_back_to_h2_and_nothing_goes_direct(monkeypatch):
|
||||
pytest.importorskip("aioquic")
|
||||
from _h3_server import H3Server
|
||||
from _socks_servers import tcp_only
|
||||
|
||||
host = _address_of_this_host()
|
||||
with H3Server(host) as server, tcp_only(user="alice", password="s3cret") as gateway:
|
||||
protocols = _protocols_behind(gateway, server, monkeypatch)
|
||||
assert "?" not in protocols and "h3" not in protocols, (
|
||||
f"behind a gateway that carries no UDP every fetch is h2 (or http/1.1), never h3: {protocols}")
|
||||
assert not server.quic_peers, f"a QUIC connection reached the server direct, around the proxy: {server.quic_peers}"
|
||||
@@ -56,7 +56,6 @@ _REQUIRED_PREFS_KEYS = (
|
||||
"intl.accept_languages",
|
||||
"intl.locale.requested",
|
||||
"zoom.stealth.fpp.hw_seed",
|
||||
"zoom.stealth.webrtc.host_ip",
|
||||
"zoom.stealth.webgl.renderer",
|
||||
"zoom.stealth.webgl.vendor",
|
||||
"webgl.msaa-samples",
|
||||
@@ -120,7 +119,9 @@ def test_socks5_proxy_mutates_prefs_then_pipeline_still_valid():
|
||||
"network.proxy.socks_username", "network.proxy.socks_password",
|
||||
"network.proxy.http", "network.proxy.ssl"):
|
||||
assert name not in prefs, name
|
||||
assert prefs["zoom.stealth.dns.no_local_resolution"] is True
|
||||
# Names are resolved by Firefox's own DoH, through the session proxy: no gate of ours, a declared DoH (mode 3).
|
||||
assert "zoom.stealth.dns.no_local_resolution" not in prefs
|
||||
assert prefs["network.trr.mode"] == 3
|
||||
|
||||
# Profile-derived keys must still be present after proxy mutation.
|
||||
#
|
||||
@@ -359,7 +360,9 @@ def test_linux_xvfb_workarounds_with_socks_proxy(monkeypatch):
|
||||
# The proxy layer no longer writes any endpoint, and what it does write - the
|
||||
# leak-channel prefs - does not trample the Linux prefs above.
|
||||
assert "network.proxy.type" not in prefs
|
||||
assert prefs["zoom.stealth.dns.no_local_resolution"] is True
|
||||
# Names are resolved by Firefox's own DoH, through the session proxy: no gate of ours, a declared DoH (mode 3).
|
||||
assert "zoom.stealth.dns.no_local_resolution" not in prefs
|
||||
assert prefs["network.trr.mode"] == 3
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -1085,6 +1085,10 @@ def test_the_launch_handler_hands_the_named_environment_to_the_engine(monkeypatc
|
||||
assert env.pop("TEMP") == tmp and env.pop("TMPDIR") == tmp
|
||||
from invisible_playwright import _session
|
||||
_, session_env = _session.default_session("x")
|
||||
# The network is drawn from the seed of each session, and each unmarked
|
||||
# launch is a new session: it is there.
|
||||
assert env.pop("STEALTHFOX_WEBRTC_NETWORK").startswith("v4=")
|
||||
session_env.pop("STEALTHFOX_WEBRTC_NETWORK")
|
||||
assert env == dict(session_env, DISPLAY=":123")
|
||||
assert "WAYLAND_DISPLAY" not in env
|
||||
finally:
|
||||
|
||||
@@ -180,45 +180,23 @@ def test_default_context_with_no_language_asked_is_en_us():
|
||||
assert ip._default_context_kwargs()["locale"] == "en-US"
|
||||
|
||||
|
||||
# ── InvisiblePlaywright._build_env - WebRTC egress auto-derive ─────────
|
||||
# Locks the 2026-06-10 fix: behind a proxy the launcher feeds the discovered
|
||||
# egress IP to nICEr (srflx override) + drops IPv6. Without it, a proxied
|
||||
# session's WebRTC silently fell back to leaking/blocking. Runs in tests.yml.
|
||||
# ── InvisiblePlaywright._build_env - the declared network ─────────────
|
||||
# The session declares its host network (drawn from the seed) in one variable,
|
||||
# with or without a proxy. Runs in tests.yml.
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_build_env_injects_webrtc_egress_when_discovered():
|
||||
ip = InvisiblePlaywright(seed=42)
|
||||
# ⛔ TWO FIELDS, and this test only exercised one. `_webrtc_egress_ip`
|
||||
# is the FACT (where we exit from, read by the guard against drift);
|
||||
# `_srflx_declared` is the DECISION that ends up in the env. Since
|
||||
# 2026-08-25 they do not coincide: when the exit has proven, consistent
|
||||
# UDP the decision is None and nothing gets declared.
|
||||
ip._webrtc_egress_ip = "203.0.113.9" # what __enter__ resolves behind a proxy
|
||||
ip._srflx_declared = "203.0.113.9" # and here the decision coincides with the fact
|
||||
env = ip._build_env({})
|
||||
assert env["STEALTHFOX_WEBRTC_PUBLIC_IP"] == "203.0.113.9"
|
||||
assert env["STEALTHFOX_WEBRTC_DISABLE_IPV6"] == "1"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_build_env_no_webrtc_keys_without_proxy(monkeypatch):
|
||||
monkeypatch.delenv("STEALTHFOX_WEBRTC_PUBLIC_IP", raising=False)
|
||||
ip = InvisiblePlaywright(seed=42)
|
||||
ip._webrtc_egress_ip = None # no proxy → real STUN already truthful
|
||||
env = ip._build_env({})
|
||||
assert "STEALTHFOX_WEBRTC_PUBLIC_IP" not in env
|
||||
assert "STEALTHFOX_WEBRTC_DISABLE_IPV6" not in env
|
||||
def test_build_env_carries_the_declared_network():
|
||||
from invisible_core import network_to_declare
|
||||
env = InvisiblePlaywright(seed=42)._build_env({})
|
||||
assert env["STEALTHFOX_WEBRTC_NETWORK"] == network_to_declare(42)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_build_env_caller_env_override_wins(monkeypatch):
|
||||
monkeypatch.setenv("STEALTHFOX_WEBRTC_PUBLIC_IP", "198.51.100.5")
|
||||
ip = InvisiblePlaywright(seed=42)
|
||||
ip._webrtc_egress_ip = "203.0.113.9" # auto-discovered
|
||||
env = ip._build_env({})
|
||||
assert env["STEALTHFOX_WEBRTC_PUBLIC_IP"] == "198.51.100.5" # caller wins
|
||||
assert env["STEALTHFOX_WEBRTC_DISABLE_IPV6"] == "1"
|
||||
monkeypatch.setenv("STEALTHFOX_WEBRTC_NETWORK", "v4=198.51.100.5;v6=1")
|
||||
env = InvisiblePlaywright(seed=42)._build_env({})
|
||||
assert env["STEALTHFOX_WEBRTC_NETWORK"] == "v4=198.51.100.5;v6=1" # caller wins
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -232,7 +210,7 @@ def test_build_env_drops_the_variables_the_display_names_absent():
|
||||
``None`` value and, worse, keep ``WAYLAND_DISPLAY``."""
|
||||
from invisible_playwright._session import build_env
|
||||
base = {"PATH": "/usr/bin", "WAYLAND_DISPLAY": "wayland-0", "DISPLAY": ":0"}
|
||||
env = build_env(srflx_declared=None, base_env=base,
|
||||
env = build_env(network_declared=None, base_env=base,
|
||||
display_env={"DISPLAY": ":123", "GDK_BACKEND": "x11",
|
||||
"WAYLAND_DISPLAY": None, "PULSE_SERVER": None})
|
||||
assert env["DISPLAY"] == ":123"
|
||||
|
||||
@@ -38,16 +38,41 @@ def test_the_gate_is_importable_from_the_pinned_core():
|
||||
assert hasattr(release, "resolve_project_identity")
|
||||
|
||||
|
||||
def _own_distribution_name() -> str:
|
||||
"""The name this project declares in ITS pyproject, read here independently of the gate."""
|
||||
import tomllib
|
||||
|
||||
with (_REPO / "pyproject.toml").open("rb") as fh:
|
||||
return tomllib.load(fh)["project"]["name"]
|
||||
|
||||
|
||||
def test_the_gate_recognises_THIS_project_and_not_the_core():
|
||||
"""One gate, several projects: the identity comes from our pyproject.
|
||||
Reading the core's would gate the wrong package and pass every time."""
|
||||
Reading the core's would gate the wrong package and pass every time.
|
||||
|
||||
The name is compared with what OUR pyproject declares, not with the name of the folder the checkout sits in:
|
||||
a worktree (``wrapper-p6``, ``wt/foo``) is the same project, and the folder name is nothing the gate reads."""
|
||||
from invisible_core.release import resolve_project_identity
|
||||
|
||||
dist, pkg = resolve_project_identity(_REPO)
|
||||
assert dist.replace("-", "_") == _REPO.name
|
||||
assert dist == _own_distribution_name()
|
||||
assert dist.replace("-", "_") != "invisible_core", "the gate read the core's identity"
|
||||
assert (_REPO / "src" / pkg).is_dir()
|
||||
|
||||
|
||||
def test_the_identity_does_not_depend_on_the_name_of_the_folder(tmp_path):
|
||||
"""The same project under another folder name (what any worktree is) resolves to the same identity."""
|
||||
import shutil
|
||||
|
||||
from invisible_core.release import resolve_project_identity
|
||||
|
||||
moved = tmp_path / "some-worktree-with-another-name"
|
||||
moved.mkdir()
|
||||
shutil.copy(_REPO / "pyproject.toml", moved / "pyproject.toml")
|
||||
assert resolve_project_identity(moved) == resolve_project_identity(_REPO)
|
||||
assert moved.name != _own_distribution_name().replace("-", "_")
|
||||
|
||||
|
||||
@pytest.mark.skipif(not _HOOK.exists(), reason="not a source checkout")
|
||||
def test_the_pre_push_hook_gates_release_tags():
|
||||
"""Driven, not read.
|
||||
|
||||
@@ -74,9 +74,9 @@ _LEAKS = ("PYTHONPATH", "PYTHONHOME", "VIRTUAL_ENV",
|
||||
"INVISIBLE_DOWNLOAD_DEADLINE", "STEALTHFOX_GITHUB_TOKEN", "GITHUB_TOKEN",
|
||||
"INVISIBLE_SEAL_FILE", "INVISIBLE_CORE_PIN", "INVISIBLE_CORE_AUTOFIX",
|
||||
"INVISIBLE_CORE_AUTOFIX_TIMEOUT", "UV", "STEALTHFOX_GEOIP_MMDB",
|
||||
"STEALTHFOX_FONT_MANIFEST", "STEALTHFOX_WEBRTC_PUBLIC_IP",
|
||||
"STEALTHFOX_FONT_MANIFEST", "STEALTHFOX_WEBRTC_NETWORK",
|
||||
"INVPW_CURSOR_TIMER", "INVISIBLE_CORE_AUTOFIX_ATTEMPTED",
|
||||
"INVPW_SESSION_TOKEN", "INVPW_DESKTOP", "STEALTHFOX_WEBRTC_DISABLE_IPV6")
|
||||
"INVPW_SESSION_TOKEN", "INVPW_DESKTOP")
|
||||
|
||||
|
||||
def _clean_env(base=None):
|
||||
|
||||
@@ -0,0 +1,435 @@
|
||||
"""The helpers of the DoH e2e (`_doh_servers.py`) do what the e2e relies on, tested with plain Python clients.
|
||||
|
||||
The e2e tests of `test_doh_through_the_proxy_e2e.py` are written against a contract no engine in this tree has yet, so
|
||||
what can be proven now is that the TOOLS are right: the DNS codec, the DoH server over HTTP/1.1 and over h2, and the
|
||||
SOCKS5 gateway that hands a CONNECT to the DoH address to the DoH server, tagged with its own name. A helper that
|
||||
answers wrongly would turn the e2e red or green for no reason, and nobody would know which.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import socket
|
||||
import ssl
|
||||
import struct
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
import _doh_servers as ds
|
||||
from _doh_servers import (DOH_BOOTSTRAP, DOH_HOST, DOH_PATH, DohGateway, FakeDoh, QTYPE_A, QTYPE_AAAA,
|
||||
encode_query, parse_query)
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
NAMES = {"page-a.test": "127.0.0.1", "other.test": "127.0.0.2"}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ a tiny parser, independent of the server's
|
||||
def read_response(message: bytes):
|
||||
"""(id, flags, rcode, question name, [(type, ttl, rdata)]) read the way a client reads it."""
|
||||
ident, flags, qd, an, ns, ar = struct.unpack("!6H", message[:12])
|
||||
assert (qd, ns, ar) == (1, 0, 0), (qd, ns, ar)
|
||||
i, labels = 12, []
|
||||
while message[i]:
|
||||
labels.append(message[i + 1:i + 1 + message[i]].decode())
|
||||
i += 1 + message[i]
|
||||
i += 1 + 4 # the root label, QTYPE, QCLASS
|
||||
answers = []
|
||||
for _ in range(an):
|
||||
assert message[i:i + 2] == b"\xc0\x0c", "the owner name is a pointer to the question"
|
||||
rtype, rclass, ttl, rdlength = struct.unpack("!HHIH", message[i + 2:i + 12])
|
||||
assert rclass == 1
|
||||
answers.append((rtype, ttl, message[i + 12:i + 12 + rdlength]))
|
||||
i += 12 + rdlength
|
||||
assert i == len(message), "no trailing bytes"
|
||||
return ident, flags, flags & 0xF, ".".join(labels), answers
|
||||
|
||||
|
||||
def _tls(host_port, *, alpn):
|
||||
context = ssl.create_default_context()
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
context.set_alpn_protocols(alpn)
|
||||
raw = socket.create_connection(host_port, timeout=10)
|
||||
return context.wrap_socket(raw, server_hostname=DOH_HOST)
|
||||
|
||||
|
||||
def _h1_request(tls, method, target, body=b"", content_type=None, close=False):
|
||||
head = "%s %s HTTP/1.1\r\nHost: %s\r\nAccept: application/dns-message\r\n" % (method, target, DOH_HOST)
|
||||
if content_type:
|
||||
head += "Content-Type: %s\r\n" % content_type
|
||||
if method == "POST":
|
||||
head += "Content-Length: %d\r\n" % len(body)
|
||||
if close:
|
||||
head += "Connection: close\r\n"
|
||||
tls.sendall(head.encode() + b"\r\n" + body)
|
||||
data = b""
|
||||
while b"\r\n\r\n" not in data:
|
||||
chunk = tls.recv(65536)
|
||||
assert chunk, "the server closed without answering"
|
||||
data += chunk
|
||||
header, _, rest = data.partition(b"\r\n\r\n")
|
||||
lines = header.decode().split("\r\n")
|
||||
status = int(lines[0].split()[1])
|
||||
headers = {k.strip().lower(): v.strip() for k, _, v in (l.partition(":") for l in lines[1:])}
|
||||
length = int(headers["content-length"])
|
||||
while len(rest) < length:
|
||||
rest += tls.recv(65536)
|
||||
return status, headers, rest
|
||||
|
||||
|
||||
def _get_target(message):
|
||||
return "%s?dns=%s" % (DOH_PATH, base64.urlsafe_b64encode(message).rstrip(b"=").decode())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def doh():
|
||||
with FakeDoh(NAMES) as server:
|
||||
yield server
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def doh_h1_only():
|
||||
with FakeDoh(NAMES, h2=False) as server:
|
||||
yield server
|
||||
|
||||
|
||||
# -------------------------------------------------------------------------------------------------- the codec
|
||||
def test_a_query_is_parsed_from_its_labels():
|
||||
q = parse_query(encode_query("Page-A.test.", QTYPE_AAAA, ident=7))
|
||||
assert (q.ident, q.name, q.qtype, q.qclass) == (7, "page-a.test", QTYPE_AAAA, 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("junk", [b"", b"\x00" * 5, b"\x00" * 12, encode_query("a.test")[:-2],
|
||||
encode_query("a.test")[:12] + b"\xc0\x0c" + b"\x00\x01\x00\x01"])
|
||||
def test_a_message_that_is_not_a_query_is_refused(junk):
|
||||
with pytest.raises(ValueError):
|
||||
parse_query(junk)
|
||||
|
||||
|
||||
def test_the_response_codec_round_trips_through_the_independent_parser():
|
||||
q = parse_query(encode_query("page-a.test", QTYPE_A, ident=9))
|
||||
ident, flags, rcode, name, answers = read_response(ds.answer_for(NAMES, q))
|
||||
assert (ident, rcode, name) == (9, 0, "page-a.test")
|
||||
assert flags & 0x8000 and flags & 0x0100, "QR set, RD copied"
|
||||
assert answers == [(QTYPE_A, ds.DOH_TTL, socket.inet_aton("127.0.0.1"))]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------- HTTP/1.1, POST and GET
|
||||
@pytest.mark.parametrize("how", ["POST", "GET"])
|
||||
def test_an_a_query_for_a_known_name_is_answered_over_http1(doh_h1_only, how):
|
||||
tls = _tls(("127.0.0.1", doh_h1_only.port), alpn=["http/1.1"])
|
||||
try:
|
||||
message = encode_query("page-a.test", QTYPE_A, ident=0)
|
||||
if how == "POST":
|
||||
status, headers, body = _h1_request(tls, "POST", DOH_PATH, message, "application/dns-message")
|
||||
else:
|
||||
status, headers, body = _h1_request(tls, "GET", _get_target(message))
|
||||
assert status == 200 and headers["content-type"] == "application/dns-message"
|
||||
_ident, _flags, rcode, name, answers = read_response(body)
|
||||
assert (rcode, name) == (0, "page-a.test")
|
||||
assert answers == [(QTYPE_A, 30, bytes([127, 0, 0, 1]))]
|
||||
finally:
|
||||
tls.close()
|
||||
assert [(q.name, q.qtype, q.via) for q in doh_h1_only.queries] == [("page-a.test", QTYPE_A, "direct")]
|
||||
assert doh_h1_only.alpn_of("direct") == {"http/1.1"}
|
||||
|
||||
|
||||
def test_an_unknown_name_is_nxdomain_over_http1(doh_h1_only):
|
||||
tls = _tls(("127.0.0.1", doh_h1_only.port), alpn=["http/1.1"])
|
||||
try:
|
||||
status, _h, body = _h1_request(tls, "POST", DOH_PATH, encode_query("nobody.test"), "application/dns-message")
|
||||
finally:
|
||||
tls.close()
|
||||
assert status == 200, "a name that does not exist is a DNS answer, not an HTTP error"
|
||||
_i, _f, rcode, name, answers = read_response(body)
|
||||
assert (rcode, name, answers) == (3, "nobody.test", [])
|
||||
assert doh_h1_only.queries_for("nobody.test"), "the miss is recorded too"
|
||||
|
||||
|
||||
def test_an_aaaa_query_for_a_known_name_is_empty_noerror_over_http1(doh_h1_only):
|
||||
tls = _tls(("127.0.0.1", doh_h1_only.port), alpn=["http/1.1"])
|
||||
try:
|
||||
_s, _h, body = _h1_request(tls, "POST", DOH_PATH, encode_query("page-a.test", QTYPE_AAAA),
|
||||
"application/dns-message")
|
||||
finally:
|
||||
tls.close()
|
||||
_i, _f, rcode, _n, answers = read_response(body)
|
||||
assert (rcode, answers) == (0, [])
|
||||
|
||||
|
||||
def test_http1_keeps_the_connection_for_the_next_query(doh_h1_only):
|
||||
tls = _tls(("127.0.0.1", doh_h1_only.port), alpn=["http/1.1"])
|
||||
try:
|
||||
for name in ("page-a.test", "other.test"):
|
||||
status, _h, body = _h1_request(tls, "POST", DOH_PATH, encode_query(name), "application/dns-message")
|
||||
assert status == 200 and read_response(body)[4]
|
||||
finally:
|
||||
tls.close()
|
||||
assert len(doh_h1_only.connections) == 1 and len(doh_h1_only.queries) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("request_, status", [
|
||||
(("POST", DOH_PATH, b"junk", "application/dns-message"), 400),
|
||||
(("POST", DOH_PATH, b"", "text/plain"), 415),
|
||||
(("GET", DOH_PATH, b"", None), 400),
|
||||
(("GET", "/elsewhere", b"", None), 404),
|
||||
(("PUT", DOH_PATH, b"", None), 405),
|
||||
])
|
||||
def test_what_is_not_a_doh_query_is_an_http_error_and_not_a_query(doh_h1_only, request_, status):
|
||||
method, target, body, content_type = request_
|
||||
tls = _tls(("127.0.0.1", doh_h1_only.port), alpn=["http/1.1"])
|
||||
try:
|
||||
got, _h, _b = _h1_request(tls, method, target, body, content_type, close=True)
|
||||
finally:
|
||||
tls.close()
|
||||
assert got == status
|
||||
assert doh_h1_only.queries == []
|
||||
assert doh_h1_only.bad_requests[-1][3] == status
|
||||
|
||||
|
||||
def test_the_certificate_covers_the_doh_host_and_loopback(doh):
|
||||
"""A client that VERIFIES (trusting the certificate file) accepts both names the DoH may be reached by."""
|
||||
for server_name in (DOH_HOST, "127.0.0.1"):
|
||||
context = ssl.create_default_context(cafile=str(doh.certificate_path))
|
||||
raw = socket.create_connection(("127.0.0.1", doh.port), timeout=10)
|
||||
tls = context.wrap_socket(raw, server_hostname=server_name)
|
||||
tls.close()
|
||||
context = ssl.create_default_context(cafile=str(doh.certificate_path))
|
||||
raw = socket.create_connection(("127.0.0.1", doh.port), timeout=10)
|
||||
with pytest.raises(ssl.SSLCertVerificationError):
|
||||
context.wrap_socket(raw, server_hostname="some-other-host.test")
|
||||
raw.close()
|
||||
|
||||
|
||||
def test_a_client_that_refuses_the_certificate_is_listed_as_a_tls_failure(doh):
|
||||
context = ssl.create_default_context() # verifies, and does not trust the self-signed certificate
|
||||
raw = socket.create_connection(("127.0.0.1", doh.port), timeout=10)
|
||||
with pytest.raises(ssl.SSLError):
|
||||
context.wrap_socket(raw, server_hostname=DOH_HOST)
|
||||
raw.close()
|
||||
assert ds.wait_until(lambda: doh.tls_failures, 5), "the failed handshake is recorded"
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------------- h2
|
||||
def _h2_query(doh, method, message, raw=None):
|
||||
"""One DoH query over h2, on `raw` (a connected socket, e.g. a tunnel) or straight to the server."""
|
||||
h2_config = pytest.importorskip("h2.config")
|
||||
h2_connection = pytest.importorskip("h2.connection")
|
||||
h2_events = pytest.importorskip("h2.events")
|
||||
if raw is None:
|
||||
tls = _tls(("127.0.0.1", doh.port), alpn=["h2", "http/1.1"])
|
||||
else:
|
||||
context = ssl.create_default_context()
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
context.set_alpn_protocols(["h2", "http/1.1"])
|
||||
tls = context.wrap_socket(raw, server_hostname=DOH_HOST)
|
||||
assert tls.selected_alpn_protocol() == "h2"
|
||||
conn = h2_connection.H2Connection(config=h2_config.H2Configuration(client_side=True, header_encoding="utf-8"))
|
||||
conn.initiate_connection()
|
||||
headers = [(":method", method), (":scheme", "https"), (":authority", DOH_HOST),
|
||||
(":path", DOH_PATH if method == "POST" else _get_target(message)), ("accept", "application/dns-message")]
|
||||
if method == "POST":
|
||||
headers += [("content-type", "application/dns-message"), ("content-length", str(len(message)))]
|
||||
conn.send_headers(1, headers)
|
||||
conn.send_data(1, message, end_stream=True)
|
||||
else:
|
||||
conn.send_headers(1, headers, end_stream=True)
|
||||
tls.sendall(conn.data_to_send())
|
||||
status, body, ended = None, b"", False
|
||||
while not ended:
|
||||
data = tls.recv(65536)
|
||||
assert data, "the server closed without answering"
|
||||
for event in conn.receive_data(data):
|
||||
if isinstance(event, h2_events.ResponseReceived):
|
||||
status = dict(event.headers)[":status"]
|
||||
elif isinstance(event, h2_events.DataReceived):
|
||||
body += event.data
|
||||
conn.acknowledge_received_data(event.flow_controlled_length, event.stream_id)
|
||||
elif isinstance(event, h2_events.StreamEnded):
|
||||
ended = True
|
||||
tls.sendall(conn.data_to_send())
|
||||
tls.close()
|
||||
return status, body
|
||||
|
||||
|
||||
@pytest.mark.parametrize("how", ["POST", "GET"])
|
||||
def test_an_a_query_is_answered_over_h2(doh, how):
|
||||
status, body = _h2_query(doh, how, encode_query("page-a.test", QTYPE_A))
|
||||
assert status == "200"
|
||||
_i, _f, rcode, name, answers = read_response(body)
|
||||
assert (rcode, name, answers) == (0, "page-a.test", [(QTYPE_A, 30, bytes([127, 0, 0, 1]))])
|
||||
assert doh.alpn_of("direct") == {"h2"}
|
||||
|
||||
|
||||
def test_a_miss_and_an_aaaa_are_answered_over_h2(doh):
|
||||
_s, body = _h2_query(doh, "POST", encode_query("nobody.test"))
|
||||
assert read_response(body)[2:] == (3, "nobody.test", [])
|
||||
_s, body = _h2_query(doh, "GET", encode_query("page-a.test", QTYPE_AAAA))
|
||||
assert (read_response(body)[2], read_response(body)[4]) == (0, [])
|
||||
assert [(q.name, q.qtype) for q in doh.queries] == [("nobody.test", 1), ("page-a.test", QTYPE_AAAA)]
|
||||
|
||||
|
||||
def test_a_server_that_does_not_offer_h2_selects_http1_for_a_client_that_asks_for_both(doh_h1_only):
|
||||
tls = _tls(("127.0.0.1", doh_h1_only.port), alpn=["h2", "http/1.1"])
|
||||
try:
|
||||
assert tls.selected_alpn_protocol() == "http/1.1"
|
||||
finally:
|
||||
tls.close()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------- the gateway (H2)
|
||||
def _socks_connect(gateway_port, host, port, *, credentials=None, by_name=False):
|
||||
"""A plain SOCKS5 client: returns (socket, reply code)."""
|
||||
s = socket.create_connection(("127.0.0.1", gateway_port), timeout=10)
|
||||
if credentials:
|
||||
s.sendall(b"\x05\x01\x02")
|
||||
assert s.recv(2) == b"\x05\x02"
|
||||
u, p = (c.encode() for c in credentials)
|
||||
s.sendall(b"\x01" + bytes([len(u)]) + u + bytes([len(p)]) + p)
|
||||
assert s.recv(2) == b"\x01\x00"
|
||||
else:
|
||||
s.sendall(b"\x05\x01\x00")
|
||||
assert s.recv(2) == b"\x05\x00"
|
||||
if by_name:
|
||||
target = b"\x03" + bytes([len(host)]) + host.encode()
|
||||
else:
|
||||
target = b"\x01" + socket.inet_aton(host)
|
||||
s.sendall(b"\x05\x01\x00" + target + struct.pack("!H", port))
|
||||
reply = b""
|
||||
while len(reply) < 10:
|
||||
chunk = s.recv(10 - len(reply))
|
||||
if not chunk:
|
||||
break
|
||||
reply += chunk
|
||||
return s, (reply[1] if len(reply) > 1 else None)
|
||||
|
||||
|
||||
def _query_through(sock, name, qtype=QTYPE_A):
|
||||
context = ssl.create_default_context()
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
context.set_alpn_protocols(["http/1.1"])
|
||||
tls = context.wrap_socket(sock, server_hostname=DOH_HOST)
|
||||
try:
|
||||
status, _h, body = _h1_request(tls, "POST", DOH_PATH, encode_query(name, qtype), "application/dns-message",
|
||||
close=True)
|
||||
finally:
|
||||
tls.close()
|
||||
return status, body
|
||||
|
||||
|
||||
@pytest.mark.parametrize("by_name", [False, True])
|
||||
def test_a_connect_to_the_doh_address_reaches_the_doh_and_is_tagged_with_the_gateway(doh, by_name):
|
||||
with DohGateway("gw1", doh) as gw:
|
||||
target = DOH_HOST if by_name else DOH_BOOTSTRAP
|
||||
s, code = _socks_connect(gw.port, target, 443, by_name=by_name)
|
||||
assert code == 0
|
||||
status, body = _query_through(s, "page-a.test")
|
||||
assert status == 200 and read_response(body)[4][0][0] == QTYPE_A
|
||||
assert gw.connects == [(target, 443)]
|
||||
assert gw.doh_connects() == [(target, 443)]
|
||||
assert [(q.name, q.qtype, q.via) for q in doh.queries] == [("page-a.test", QTYPE_A, "gw1")]
|
||||
assert doh.vias_of("page-a.test") == {"gw1"}
|
||||
|
||||
|
||||
def test_two_gateways_tag_their_own_queries(doh):
|
||||
with DohGateway("gw1", doh) as one, DohGateway("gw2", doh) as two:
|
||||
for gateway, name in ((one, "page-a.test"), (two, "other.test")):
|
||||
s, code = _socks_connect(gateway.port, DOH_BOOTSTRAP, 443)
|
||||
assert code == 0
|
||||
assert _query_through(s, name)[0] == 200
|
||||
assert doh.vias_of("page-a.test") == {"gw1"}
|
||||
assert doh.vias_of("other.test") == {"gw2"}
|
||||
|
||||
|
||||
def test_the_doh_road_works_over_h2_through_the_gateway(doh):
|
||||
pytest.importorskip("h2")
|
||||
with DohGateway("gw1", doh) as gw:
|
||||
s, code = _socks_connect(gw.port, DOH_BOOTSTRAP, 443)
|
||||
assert code == 0
|
||||
status, body = _h2_query(doh, "POST", encode_query("page-a.test"), raw=s)
|
||||
assert status == "200" and read_response(body)[4]
|
||||
assert doh.alpn_of("gw1") == {"h2"}
|
||||
assert doh.vias_of("page-a.test") == {"gw1"}
|
||||
|
||||
|
||||
def test_a_gateway_with_credentials_records_what_it_was_offered_and_serves_only_the_right_ones(doh):
|
||||
with DohGateway("gw1", doh, user="alice", password="pw-1") as gw:
|
||||
try:
|
||||
_socks_connect(gw.port, DOH_BOOTSTRAP, 443, credentials=("alice", "bad"))
|
||||
except AssertionError:
|
||||
pass # the refusal of the auth reply is what the client helper asserts on
|
||||
s, code = _socks_connect(gw.port, DOH_BOOTSTRAP, 443, credentials=("alice", "pw-1"))
|
||||
assert code == 0
|
||||
assert _query_through(s, "page-a.test")[0] == 200
|
||||
assert gw.credentials_seen == [("alice", "bad"), ("alice", "pw-1")]
|
||||
assert doh.vias_of("page-a.test") == {"gw1"}
|
||||
|
||||
|
||||
def test_a_connect_to_a_loopback_address_is_relayed_for_real_and_recorded(doh):
|
||||
echo = socket.socket()
|
||||
echo.bind(("127.0.0.1", 0))
|
||||
echo.listen(1)
|
||||
|
||||
def serve():
|
||||
c, _ = echo.accept()
|
||||
c.sendall(c.recv(100).upper())
|
||||
c.close()
|
||||
|
||||
threading.Thread(target=serve, daemon=True).start()
|
||||
with DohGateway("gw1", doh) as gw:
|
||||
s, code = _socks_connect(gw.port, "127.0.0.1", echo.getsockname()[1])
|
||||
assert code == 0
|
||||
s.sendall(b"ping")
|
||||
assert s.recv(10) == b"PING"
|
||||
s.close()
|
||||
assert gw.connects == [("127.0.0.1", echo.getsockname()[1])]
|
||||
echo.close()
|
||||
assert doh.queries == []
|
||||
|
||||
|
||||
def test_a_connect_that_would_leave_the_loopback_is_refused_and_never_resolved(doh):
|
||||
with DohGateway("gw1", doh) as gw:
|
||||
s, code = _socks_connect(gw.port, "198.51.100.77", 80)
|
||||
assert code == 2
|
||||
s.close()
|
||||
s, code = _socks_connect(gw.port, "page-a.test", 80, by_name=True)
|
||||
assert code == 4, "a name is refused, not looked up"
|
||||
s.close()
|
||||
assert gw.refused == [("198.51.100.77", 80), ("page-a.test", 80)]
|
||||
assert ("page-a.test", 80) in gw.connects, "a CONNECT by name is visible to a test that forbids it"
|
||||
|
||||
|
||||
def test_the_first_connection_can_be_answered_late(doh):
|
||||
import time
|
||||
with DohGateway("gw1", doh, first_connection_delay=0.6) as gw:
|
||||
started = time.monotonic()
|
||||
s, code = _socks_connect(gw.port, DOH_BOOTSTRAP, 443)
|
||||
assert code == 0 and time.monotonic() - started >= 0.55
|
||||
s.close()
|
||||
started = time.monotonic()
|
||||
s, code = _socks_connect(gw.port, DOH_BOOTSTRAP, 443)
|
||||
assert code == 0 and time.monotonic() - started < 0.5, "only the first one is late"
|
||||
s.close()
|
||||
|
||||
|
||||
def test_a_killed_gateway_refuses_and_drops_its_open_tunnels(doh):
|
||||
gw = DohGateway("gw1", doh)
|
||||
port = gw.port
|
||||
s, code = _socks_connect(port, DOH_BOOTSTRAP, 443)
|
||||
assert code == 0
|
||||
context = ssl.create_default_context()
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
context.set_alpn_protocols(["http/1.1"])
|
||||
tls = context.wrap_socket(s, server_hostname=DOH_HOST)
|
||||
assert _h1_request(tls, "POST", DOH_PATH, encode_query("page-a.test"), "application/dns-message")[0] == 200
|
||||
gw.kill()
|
||||
with pytest.raises((OSError, AssertionError)):
|
||||
_h1_request(tls, "POST", DOH_PATH, encode_query("other.test"), "application/dns-message")
|
||||
tls.close()
|
||||
with pytest.raises(OSError):
|
||||
socket.create_connection(("127.0.0.1", port), timeout=2)
|
||||
assert gw.killed and doh.vias_of("other.test") == set()
|
||||
@@ -0,0 +1,179 @@
|
||||
"""The HTTP proxy of the DoH e2e (`_http_proxy.py`) refuses without credentials, serves with them, and records headers.
|
||||
|
||||
Tested with raw sockets and `http.client`: the e2e asserts on what this proxy recorded (the preemptive
|
||||
`Proxy-Authorization` of the DoH CONNECT), so what it records has to be what the wire carried.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import http.client
|
||||
import socket
|
||||
import ssl
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from _doh_servers import DOH_BOOTSTRAP, DOH_HOST, DOH_PATH, FakeDoh, QTYPE_A, encode_query, wait_until
|
||||
from _http_proxy import HttpProxy, basic
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
USER, PASSWORD = "ferd:user", "pässword" # a colon in the name and a non-ASCII password: UTF-8, as RFC 7617 says
|
||||
NAMES = {"page-a.test": "127.0.0.1"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def doh():
|
||||
with FakeDoh(NAMES) as server:
|
||||
yield server
|
||||
|
||||
|
||||
def _connect_raw(proxy, target, authorization=None):
|
||||
"""CONNECT on a raw socket: (socket, status line, headers)."""
|
||||
s = socket.create_connection(("127.0.0.1", proxy.port), timeout=10)
|
||||
head = "CONNECT %s HTTP/1.1\r\nHost: %s\r\n" % (target, target)
|
||||
if authorization:
|
||||
head += "Proxy-Authorization: %s\r\n" % authorization
|
||||
s.sendall((head + "\r\n").encode())
|
||||
data = b""
|
||||
while b"\r\n\r\n" not in data:
|
||||
chunk = s.recv(4096)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
lines = data.split(b"\r\n\r\n")[0].decode().split("\r\n")
|
||||
headers = {k.strip().lower(): v.strip() for k, _, v in (l.partition(":") for l in lines[1:])}
|
||||
return s, lines[0], headers
|
||||
|
||||
|
||||
def test_basic_is_base64_of_utf8_user_colon_password():
|
||||
assert basic(USER, PASSWORD) == "Basic " + base64.b64encode("ferd:user:pässword".encode("utf-8")).decode()
|
||||
|
||||
|
||||
def test_a_connect_without_credentials_gets_407_with_a_basic_challenge(doh):
|
||||
with HttpProxy("http1", doh, user=USER, password=PASSWORD) as proxy:
|
||||
s, status, headers = _connect_raw(proxy, "%s:443" % DOH_BOOTSTRAP)
|
||||
s.close()
|
||||
assert status.split()[1] == "407"
|
||||
assert headers["proxy-authenticate"].lower().startswith("basic")
|
||||
assert proxy.connects == []
|
||||
assert [(r.method, r.authorization, r.status) for r in proxy.refused_for_credentials] == [("CONNECT", None, 407)]
|
||||
|
||||
|
||||
def test_a_connect_with_the_wrong_credentials_gets_407_and_the_header_is_recorded(doh):
|
||||
with HttpProxy("http1", doh, user=USER, password=PASSWORD) as proxy:
|
||||
wrong = basic(USER, "not-it")
|
||||
s, status, _h = _connect_raw(proxy, "%s:443" % DOH_BOOTSTRAP, wrong)
|
||||
s.close()
|
||||
assert status.split()[1] == "407"
|
||||
assert proxy.authorizations_for(DOH_BOOTSTRAP, 443) == [wrong]
|
||||
|
||||
|
||||
def test_a_connect_with_the_right_credentials_is_accepted_and_the_header_is_recorded(doh):
|
||||
with HttpProxy("http1", doh, user=USER, password=PASSWORD) as proxy:
|
||||
s, status, _h = _connect_raw(proxy, "%s:443" % DOH_BOOTSTRAP, basic(USER, PASSWORD))
|
||||
assert status.split()[1] == "200"
|
||||
context = ssl.create_default_context()
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
context.set_alpn_protocols(["http/1.1"])
|
||||
tls = context.wrap_socket(s, server_hostname=DOH_HOST)
|
||||
message = encode_query("page-a.test", QTYPE_A)
|
||||
tls.sendall(("POST %s HTTP/1.1\r\nHost: %s\r\nContent-Type: application/dns-message\r\n"
|
||||
"Content-Length: %d\r\nConnection: close\r\n\r\n" % (DOH_PATH, DOH_HOST, len(message))).encode()
|
||||
+ message)
|
||||
reply = b""
|
||||
while True:
|
||||
chunk = tls.recv(65536)
|
||||
if not chunk:
|
||||
break
|
||||
reply += chunk
|
||||
tls.close()
|
||||
assert reply.startswith(b"HTTP/1.1 200")
|
||||
assert proxy.doh_authorizations() == [basic(USER, PASSWORD)]
|
||||
assert proxy.doh_connects() == [(DOH_BOOTSTRAP, 443)]
|
||||
assert doh.vias_of("page-a.test") == {"http1"}
|
||||
|
||||
|
||||
def test_a_proxy_without_credentials_asks_for_none(doh):
|
||||
with HttpProxy("http1", doh) as proxy:
|
||||
s, status, _h = _connect_raw(proxy, "%s:443" % DOH_HOST)
|
||||
s.close()
|
||||
assert status.split()[1] == "200"
|
||||
assert proxy.doh_authorizations() == [None]
|
||||
assert proxy.proxy == {"server": proxy.server}
|
||||
|
||||
|
||||
def test_the_endpoint_dict_carries_the_credentials(doh):
|
||||
with HttpProxy("http1", doh, user=USER, password=PASSWORD) as proxy:
|
||||
assert proxy.proxy == {"server": "http://127.0.0.1:%d" % proxy.port, "username": USER, "password": PASSWORD}
|
||||
|
||||
|
||||
def test_a_connect_to_loopback_is_relayed_and_one_that_would_leave_it_is_refused(doh):
|
||||
listener = socket.socket()
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
listener.listen(1)
|
||||
|
||||
def serve():
|
||||
c, _ = listener.accept()
|
||||
c.sendall(b"hello")
|
||||
c.close()
|
||||
|
||||
threading.Thread(target=serve, daemon=True).start()
|
||||
with HttpProxy("http1", doh) as proxy:
|
||||
s, status, _h = _connect_raw(proxy, "127.0.0.1:%d" % listener.getsockname()[1])
|
||||
assert status.split()[1] == "200"
|
||||
assert s.recv(10) == b"hello"
|
||||
s.close()
|
||||
s, status, _h = _connect_raw(proxy, "198.51.100.77:443")
|
||||
s.close()
|
||||
assert status.split()[1] == "403"
|
||||
s, status, _h = _connect_raw(proxy, "page-a.test:443")
|
||||
s.close()
|
||||
assert status.split()[1] == "403", "a name is refused, not resolved"
|
||||
assert wait_until(lambda: len(proxy.seen) == 3, 5)
|
||||
listener.close()
|
||||
|
||||
|
||||
def test_a_plain_get_in_the_absolute_form_is_forwarded_by_the_zone_of_the_doh(doh):
|
||||
"""The form a browser sends to an HTTP proxy for an http page: the name travels to the proxy, which resolves it."""
|
||||
import http.server
|
||||
|
||||
class Page(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self): # noqa: N802
|
||||
body = ("host=%s path=%s via=%s" % (self.headers["Host"], self.path,
|
||||
self.headers.get("Proxy-Authorization"))).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
server = http.server.HTTPServer(("127.0.0.1", 0), Page)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
port = server.server_address[1]
|
||||
try:
|
||||
with HttpProxy("http1", doh, user=USER, password=PASSWORD) as proxy:
|
||||
conn = http.client.HTTPConnection("127.0.0.1", proxy.port, timeout=10)
|
||||
conn.request("GET", "http://page-a.test:%d/x?y=1" % port, headers={"Host": "page-a.test:%d" % port})
|
||||
assert conn.getresponse().status == 407
|
||||
conn.close()
|
||||
conn = http.client.HTTPConnection("127.0.0.1", proxy.port, timeout=10)
|
||||
conn.request("GET", "http://page-a.test:%d/x?y=1" % port,
|
||||
headers={"Host": "page-a.test:%d" % port, "Proxy-Authorization": basic(USER, PASSWORD)})
|
||||
response = conn.getresponse()
|
||||
body = response.read().decode()
|
||||
conn.close()
|
||||
assert response.status == 200
|
||||
assert body == "host=page-a.test:%d path=/x?y=1 via=None" % port, "the proxy's header is not passed on"
|
||||
conn = http.client.HTTPConnection("127.0.0.1", proxy.port, timeout=10)
|
||||
conn.request("GET", "http://not-in-the-zone.test:%d/" % port,
|
||||
headers={"Proxy-Authorization": basic(USER, PASSWORD)})
|
||||
assert conn.getresponse().status == 502
|
||||
conn.close()
|
||||
assert [s.status for s in proxy.seen] == [407, 200, 502]
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
@@ -0,0 +1,175 @@
|
||||
"""The traps of the DoH e2e (`_leaks.py`): the connection watcher and the resolver trap, tested on what they promise.
|
||||
|
||||
A trap that cannot see is worse than none: the e2e asserts "nothing left the host", and an empty Watcher reads the
|
||||
same whether nothing left or the Watcher was blind. So the Watcher is shown a connection that does leave (a connect in
|
||||
flight to a blackholed documentation address, from a child process) and shown that it ignores loopback. The resolver
|
||||
trap is shown on a free port without touching any file; the rewrite of /etc/resolv.conf is tested only where it can
|
||||
run (Linux, root).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import errno
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
import _doh_servers as ds
|
||||
from _leaks import ResolverTrap, Watcher
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
#: RFC 5737 TEST-NET-3: never routed, so a SYN to it stays in flight (or is refused at once on a host with no route).
|
||||
BLACKHOLE = ("203.0.113.1", 9)
|
||||
|
||||
_IN_FLIGHT = {errno.EINPROGRESS, errno.EWOULDBLOCK, getattr(errno, "WSAEWOULDBLOCK", errno.EWOULDBLOCK), 10035}
|
||||
|
||||
CHILD_SYN = """
|
||||
import errno, socket, sys, time
|
||||
s = socket.socket()
|
||||
s.setblocking(False)
|
||||
code = s.connect_ex(("%s", %d))
|
||||
print("in-flight" if code in (%s) else "failed:%%d" %% code, flush=True)
|
||||
time.sleep(float(sys.argv[1]))
|
||||
""" % (BLACKHOLE[0], BLACKHOLE[1], ", ".join(str(c) for c in sorted(_IN_FLIGHT)))
|
||||
|
||||
|
||||
def _child(code, *args):
|
||||
return subprocess.Popen([sys.executable, "-c", code, *map(str, args)], stdout=subprocess.PIPE, text=True)
|
||||
|
||||
|
||||
def test_the_watcher_flags_a_connection_in_flight_to_a_non_loopback_address():
|
||||
with Watcher(match="python") as watcher:
|
||||
child = _child(CHILD_SYN, 4)
|
||||
try:
|
||||
state = child.stdout.readline().strip()
|
||||
if state != "in-flight":
|
||||
pytest.skip("this host refuses a connect to %s:%d at once (%s): a SYN_SENT cannot be observed here"
|
||||
% (BLACKHOLE + (state,)))
|
||||
seen = ds.wait_until(lambda: any(c.remote == "%s:%d" % BLACKHOLE for c in watcher.direct), 3)
|
||||
finally:
|
||||
child.kill()
|
||||
child.wait()
|
||||
if not seen and sys.platform != "win32" and not watcher.watched_pids:
|
||||
pytest.skip("the child process was never listed as a descendant")
|
||||
assert seen, "a connect in flight to %s:%d was not reported; the watcher saw: %s (processes: %s)" % (
|
||||
BLACKHOLE + (watcher.describe(), watcher.process_names))
|
||||
first = [c for c in watcher.direct if c.remote == "%s:%d" % BLACKHOLE][0]
|
||||
assert first.protocol == "tcp" and first.pid in watcher.watched_pids
|
||||
|
||||
|
||||
def test_the_watcher_ignores_loopback_connections_tcp_and_udp():
|
||||
listener = socket.socket()
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
listener.listen(4)
|
||||
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
udp.bind(("127.0.0.1", 0))
|
||||
code = """
|
||||
import socket, sys, time
|
||||
s = socket.create_connection(("127.0.0.1", %d))
|
||||
u = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
u.connect(("127.0.0.1", %d))
|
||||
print("up", flush=True)
|
||||
time.sleep(1.5)
|
||||
""" % (listener.getsockname()[1], udp.getsockname()[1])
|
||||
with Watcher(match="python") as watcher:
|
||||
child = _child(code)
|
||||
try:
|
||||
assert child.stdout.readline().strip() == "up"
|
||||
time.sleep(0.8)
|
||||
finally:
|
||||
child.kill()
|
||||
child.wait()
|
||||
listener.close()
|
||||
udp.close()
|
||||
assert watcher.direct == [], watcher.describe()
|
||||
assert watcher.samples > 5
|
||||
|
||||
|
||||
def test_the_watcher_lists_the_names_of_the_descendants():
|
||||
with Watcher(match="no-such-process-name") as watcher:
|
||||
child = _child("import time; print('x', flush=True); time.sleep(2)")
|
||||
try:
|
||||
child.stdout.readline()
|
||||
assert ds.wait_until(lambda: watcher.process_names, 3)
|
||||
finally:
|
||||
child.kill()
|
||||
child.wait()
|
||||
assert any("python" in n.lower() for n in watcher.process_names), watcher.process_names
|
||||
assert watcher.direct == [] and not watcher.watched_pids, "an unmatched name is listed but not judged"
|
||||
|
||||
|
||||
def test_helpers_are_matched_on_the_stem_case_insensitively():
|
||||
watcher = Watcher()
|
||||
watcher.process_names[:] = ["firefox.exe", "CrashReporter.exe", "default-browser-agent.exe", "updater",
|
||||
"python3", "Updater.EXE", "pingsender"]
|
||||
assert watcher.helpers_seen(["crashreporter", "default-browser-agent", "maintenanceservice", "updater",
|
||||
"pingsender"]) == ["CrashReporter.exe", "default-browser-agent.exe", "updater",
|
||||
"Updater.EXE", "pingsender"]
|
||||
assert watcher.helpers_seen(["exe"]) == [], "the extension is not part of the stem"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- the resolver trap
|
||||
def _udp_ask(port, name, qtype=ds.QTYPE_A):
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
s.settimeout(5)
|
||||
s.sendto(ds.encode_query(name, qtype, ident=77), ("127.0.0.1", port))
|
||||
data, _ = s.recvfrom(4096)
|
||||
s.close()
|
||||
return data
|
||||
|
||||
|
||||
def _tcp_ask(port, name):
|
||||
import struct
|
||||
s = socket.create_connection(("127.0.0.1", port), timeout=5)
|
||||
message = ds.encode_query(name, ds.QTYPE_A, ident=78)
|
||||
s.sendall(struct.pack("!H", len(message)) + message)
|
||||
size = struct.unpack("!H", s.recv(2))[0]
|
||||
data = b""
|
||||
while len(data) < size:
|
||||
data += s.recv(size - len(data))
|
||||
s.close()
|
||||
return data
|
||||
|
||||
|
||||
def test_the_trap_counts_a_query_it_is_sent_and_refuses_what_it_cannot_answer():
|
||||
with ResolverTrap(port=0, rewrite_resolv_conf=False) as trap:
|
||||
assert trap.port > 0
|
||||
refused = _udp_ask(trap.port, "leak.test")
|
||||
assert refused[0:2] == b"\x00\x4d" and refused[3] & 0xF == ds.RCODE_REFUSED
|
||||
_tcp_ask(trap.port, "leak-tcp.test")
|
||||
assert ds.wait_until(lambda: len(trap.queries) == 2, 3)
|
||||
assert [(q.name, q.qtype, q.via) for q in trap.queries] == [
|
||||
("leak.test", ds.QTYPE_A, "udp"), ("leak-tcp.test", ds.QTYPE_A, "tcp")]
|
||||
assert trap.asked("LEAK.test.") and trap.names() == ["leak-tcp.test", "leak.test"]
|
||||
|
||||
|
||||
def test_the_trap_answers_the_names_it_is_given_over_udp_and_tcp():
|
||||
with ResolverTrap({"page-d.test": "127.0.0.1"}, port=0, rewrite_resolv_conf=False) as trap:
|
||||
for data in (_udp_ask(trap.port, "page-d.test"), _tcp_ask(trap.port, "page-d.test")):
|
||||
assert data[3] & 0xF == 0 and data[6:8] == b"\x00\x01", "NOERROR with one answer"
|
||||
assert data.endswith(socket.inet_aton("127.0.0.1"))
|
||||
aaaa = _udp_ask(trap.port, "page-d.test", ds.QTYPE_AAAA)
|
||||
assert aaaa[3] & 0xF == 0 and aaaa[6:8] == b"\x00\x00", "empty NOERROR for AAAA"
|
||||
|
||||
|
||||
def test_a_trap_that_cannot_rewrite_resolv_conf_says_why_and_does_not_start():
|
||||
if ResolverTrap.available:
|
||||
pytest.skip("this host can run the trap")
|
||||
assert ResolverTrap.reason
|
||||
with pytest.raises(RuntimeError):
|
||||
ResolverTrap().__enter__()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not ResolverTrap.available, reason=ResolverTrap.reason or "the resolver trap is available")
|
||||
def test_the_trap_points_resolv_conf_at_itself_and_restores_it_byte_for_byte():
|
||||
from pathlib import Path
|
||||
original = Path("/etc/resolv.conf").read_bytes()
|
||||
with ResolverTrap({"page-d.test": "127.0.0.1"}) as trap:
|
||||
assert b"nameserver 127.0.0.1" in Path("/etc/resolv.conf").read_bytes()
|
||||
assert socket.gethostbyname("page-d.test") == "127.0.0.1"
|
||||
assert trap.asked("page-d.test")
|
||||
assert Path("/etc/resolv.conf").read_bytes() == original
|
||||
@@ -0,0 +1,70 @@
|
||||
"""The session declares the host network to the engine from its seed.
|
||||
|
||||
One variable, STEALTHFOX_WEBRTC_NETWORK, drawn by the core from the session seed
|
||||
and written with or without a proxy. Nothing here launches a browser.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
|
||||
import pytest
|
||||
from invisible_core import network_to_declare
|
||||
|
||||
from invisible_playwright._session import build_env
|
||||
|
||||
NETWORK = "STEALTHFOX_WEBRTC_NETWORK"
|
||||
SRC = pathlib.Path(__file__).resolve().parent.parent / "src" / "invisible_playwright"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("seed", [1, 42, 123456])
|
||||
def test_build_env_carries_the_seed_declaration(seed):
|
||||
env = build_env(network_declared=network_to_declare(seed), base_env={})
|
||||
assert env[NETWORK] == network_to_declare(seed)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("proxy", [None, {"server": "socks5://127.0.0.1:1"}])
|
||||
def test_a_session_declares_its_seed_network_with_or_without_a_proxy(proxy):
|
||||
from invisible_playwright.launcher import InvisiblePlaywright
|
||||
ip = InvisiblePlaywright(seed=42, proxy=proxy)
|
||||
assert ip._build_env({})[NETWORK] == network_to_declare(42)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("proxy", [None, {"server": "socks5://127.0.0.1:1"}])
|
||||
def test_the_server_default_session_declares_the_network_of_its_seed(monkeypatch, proxy):
|
||||
"""`default_session` (what a launch naming no session gets) declares the
|
||||
network of ITS seed, with or without a proxy."""
|
||||
from invisible_core import decide_session_locale
|
||||
from invisible_core._geo import SessionGeo
|
||||
from invisible_playwright import _session
|
||||
from invisible_playwright.launcher import InvisiblePlaywright
|
||||
|
||||
seeds = []
|
||||
real_init = InvisiblePlaywright.__init__
|
||||
|
||||
def spy(self, *a, **k):
|
||||
real_init(self, *a, **k)
|
||||
seeds.append(self.seed)
|
||||
|
||||
monkeypatch.setattr(InvisiblePlaywright, "__init__", spy)
|
||||
monkeypatch.setattr(_session, "session_geo", lambda tz, px, loc: SessionGeo(
|
||||
"America/New_York", None, locale=decide_session_locale("en-US")))
|
||||
_prefs, env = _session.default_session(None, proxy)
|
||||
assert env[NETWORK] == network_to_declare(seeds[0])
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_library_adds_no_other_webrtc_variable():
|
||||
env = build_env(network_declared=network_to_declare(42), base_env={})
|
||||
assert "STEALTHFOX_WEBRTC_PUBLIC_IP" not in env
|
||||
assert "STEALTHFOX_WEBRTC_DISABLE_IPV6" not in env
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_no_source_file_spells_the_removed_names():
|
||||
removed = ("srflx_declared", "srflx_to_declare", "WEBRTC_PUBLIC_IP", "WEBRTC_DISABLE_IPV6")
|
||||
hits = [(p.name, w) for p in SRC.rglob("*.py")
|
||||
for w in removed if w in p.read_text(encoding="utf-8")]
|
||||
assert not hits, hits
|
||||
@@ -0,0 +1,84 @@
|
||||
"""The hermetic road of test_the_whole_udp_chain_by_name_e2e is itself a working road: a plain client walks it by hand
|
||||
(no browser): SOCKS5 UDP ASSOCIATE, the name asked of the resolver through the relay, an Allocate answered 401 then, with
|
||||
the credentials, with an answer signed as a real TURN server signs it, and the source the TURN server saw is the gateway's
|
||||
exit and not the client. If this helper were wrong, the e2e could never go green; this says it can."""
|
||||
import hashlib
|
||||
import hmac
|
||||
import socket
|
||||
import struct
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
import _turn_chain as c
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
def _socks_associate(chain):
|
||||
t = socket.create_connection(("127.0.0.1", chain.port), timeout=5)
|
||||
t.sendall(b"\x05\x01\x00")
|
||||
assert t.recv(2) == b"\x05\x00"
|
||||
t.sendall(b"\x05\x03\x00\x01\x00\x00\x00\x00\x00\x00")
|
||||
rep = t.recv(10)
|
||||
assert rep[1] == 0
|
||||
return t, (socket.inet_ntoa(rep[4:8]), struct.unpack("!H", rep[8:10])[0])
|
||||
|
||||
|
||||
def _via(relay_sock, relay, host_ip, port, payload):
|
||||
relay_sock.sendto(b"\x00\x00\x00\x01" + socket.inet_aton(host_ip) + struct.pack("!H", port) + payload, relay)
|
||||
data, _ = relay_sock.recvfrom(65536)
|
||||
return data[10:]
|
||||
|
||||
|
||||
def _dns_query(name):
|
||||
q = b"\x12\x34\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00"
|
||||
for label in name.split("."):
|
||||
q += bytes([len(label)]) + label.encode()
|
||||
return q + b"\x00\x00\x01\x00\x01"
|
||||
|
||||
|
||||
def test_a_client_walks_the_whole_road_and_the_turn_server_sees_the_gateways_exit():
|
||||
with c.Chain(rtt_ms=20, relay_host="127.0.0.1") as chain:
|
||||
t, relay = _socks_associate(chain)
|
||||
u = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
u.settimeout(5)
|
||||
# the name, asked of "a resolver on the Internet" through the relay: it is the world's only resolver
|
||||
answer = _via(u, relay, "192.0.2.53", 53, _dns_query(c.TURN_NAME))
|
||||
assert socket.inet_ntoa(answer[-4:]) == c.TURN_IP
|
||||
# an Allocate without credentials: 401 with a realm and a nonce
|
||||
tid = b"\x01" * 12
|
||||
alloc = struct.pack("!HHI", 0x0003, 8, c.MAGIC) + tid + struct.pack("!HH", 0x0019, 4) + b"\x11\x00\x00\x00"
|
||||
r1 = _via(u, relay, c.TURN_IP, c.TURN_PORT, alloc)
|
||||
assert struct.unpack("!H", r1[:2])[0] == 0x0113
|
||||
attrs = c._attrs(r1)
|
||||
assert attrs[0x0014] == c.REALM.encode() and attrs[0x0015] == c.NONCE.encode()
|
||||
# with the credentials: a success signed with the long-term key
|
||||
user = b"challenge-1"
|
||||
key = hashlib.md5(b"challenge-1:" + c.REALM.encode() + b":" + c.PASSWORD.encode()).digest()
|
||||
body = (c._attr(0x0019, b"\x11\x00\x00\x00") + c._attr(0x0006, user) + c._attr(0x0014, c.REALM.encode()) +
|
||||
c._attr(0x0015, c.NONCE.encode()))
|
||||
req = c._message(0x0003, b"\x02" * 12, body, key)
|
||||
r2 = _via(u, relay, c.TURN_IP, c.TURN_PORT, req)
|
||||
assert struct.unpack("!H", r2[:2])[0] == 0x0103
|
||||
# the signature of the answer is the one a client with the same credentials computes
|
||||
mi_at = r2.index(struct.pack("!HH", 0x0008, 20))
|
||||
head = struct.pack("!H", 0x0103) + struct.pack("!H", mi_at - 20 + 24) + r2[4:20]
|
||||
assert hmac.new(key, head + r2[20:mi_at], hashlib.sha1).digest() == r2[mi_at + 4:mi_at + 24]
|
||||
mapped = c._attrs(r2)[0x0020]
|
||||
port = struct.unpack("!H", mapped[2:4])[0] ^ (c.MAGIC >> 16)
|
||||
ip = socket.inet_ntoa(struct.pack("!I", struct.unpack("!I", mapped[4:8])[0] ^ c.MAGIC))
|
||||
# the XOR-MAPPED-ADDRESS is the source the TURN server saw: the gateway's exit, not this client
|
||||
assert ip == c.EXIT_HOST and (ip, port) in [(a[0], a[1]) for a in chain.turn.allocations]
|
||||
assert {s[0] for s in chain.turn.seen} == {c.EXIT_HOST}
|
||||
t.close()
|
||||
|
||||
|
||||
def test_every_step_of_the_gateway_costs_its_round_trip():
|
||||
with c.Chain(rtt_ms=130, relay_host="127.0.0.1") as chain:
|
||||
began = time.monotonic()
|
||||
t, _relay = _socks_associate(chain)
|
||||
took = time.monotonic() - began
|
||||
t.close()
|
||||
assert 0.25 <= took < 1.5, took # the greeting and the request each wait one round trip
|
||||
assert chain.associations and chain.associations[0][1] is not None
|
||||
@@ -0,0 +1,58 @@
|
||||
"""The whole chain a leak test walks, by NAME, behind a SOCKS5 gateway that carries UDP, all on loopback (hermetic).
|
||||
|
||||
A page asks for a TURN allocation at a server written as a NAME (`turn:turn.relay-only.test:3478`), as the real leak-test pages
|
||||
do: no STUN, so a server-reflexive candidate can only be born from a successful allocation. Its logic is the logic of such a page:
|
||||
a tick of 2 seconds from the start of the page that marks TIMEOUT, cleared only after a POST made when the srflx arrives; the
|
||||
server compares the address of that srflx with the source the TURN server saw for the allocation.
|
||||
|
||||
The only road to anything is a gateway at 130 ms of round trip (every step of its control connection, every datagram):
|
||||
the TURN server is at an unroutable documentation address that only the gateway maps to it, the name is known only to a resolver
|
||||
that only the gateway reaches (the gateway also resolves a name sent to it as SOCKS5 address type 3), and the gateway's
|
||||
datagrams leave from 127.0.0.2 so that a TURN server hearing 127.0.0.1 proves the browser went around the gateway.
|
||||
|
||||
What the product must do, to be what a retail Firefox is with no proxy at all (the same candidates, in the same time):
|
||||
* the name of the ICE server is resolved at the exit, with no local resolution;
|
||||
* the UDP to the TURN server leaves through the gateway's relay;
|
||||
* and all of it, with the handshakes of the associations the browser needs, fits in the tick of the page.
|
||||
|
||||
It fails today, and says WHY (the explanation lists what each server saw): the engine refuses to resolve a name that is not a literal
|
||||
behind a proxy, so the browser never reaches the TURN server, and the handshakes of its associations are serial (each costs
|
||||
round trips of the gateway before a socket is usable).
|
||||
"""
|
||||
import pytest
|
||||
|
||||
import _turn_chain as chain_mod
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
EXIT = "203.0.113.7" # what the product's own probe of the egress is told: RFC 5737 TEST-NET-3
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def gateway(monkeypatch):
|
||||
# The probes of the core that ask for the egress go nowhere: the world has no network but the gateway.
|
||||
for module, name in (("invisible_core._geo", "discover_egress_ip"),):
|
||||
try:
|
||||
mod = __import__(module, fromlist=[name])
|
||||
monkeypatch.setattr(mod, name, lambda *a, **k: EXIT, raising=False)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
with chain_mod.Chain(rtt_ms=130) as chain:
|
||||
yield chain
|
||||
|
||||
|
||||
def test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick(gateway, firefox_binary, engine_at_least):
|
||||
engine_at_least("firefox-62")
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(headless=True, binary_path=firefox_binary, timezone="America/New_York", locale="en-US",
|
||||
proxy=gateway.proxy) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto(gateway.page.url, wait_until="domcontentloaded", timeout=60000)
|
||||
try:
|
||||
page.wait_for_function("window.__done === true", timeout=9000)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
result = page.evaluate("window.__result")
|
||||
ok = result.get("status") == "DONE" and gateway.page.verdicts and gateway.page.verdicts[-1]["ok"]
|
||||
assert ok, "the page did not get a server-reflexive candidate that the TURN server saw, before its tick of 2 s:" + gateway.explain(result)
|
||||
@@ -68,9 +68,9 @@ _LEAKS = ("PYTHONPATH", "PYTHONHOME", "VIRTUAL_ENV",
|
||||
"INVISIBLE_DOWNLOAD_DEADLINE", "STEALTHFOX_GITHUB_TOKEN", "GITHUB_TOKEN",
|
||||
"INVISIBLE_SEAL_FILE", "INVISIBLE_CORE_PIN", "INVISIBLE_CORE_AUTOFIX",
|
||||
"INVISIBLE_CORE_AUTOFIX_TIMEOUT", "UV", "STEALTHFOX_GEOIP_MMDB",
|
||||
"STEALTHFOX_FONT_MANIFEST", "STEALTHFOX_WEBRTC_PUBLIC_IP",
|
||||
"STEALTHFOX_FONT_MANIFEST", "STEALTHFOX_WEBRTC_NETWORK",
|
||||
"INVPW_CURSOR_TIMER", "INVISIBLE_CORE_AUTOFIX_ATTEMPTED",
|
||||
"INVPW_SESSION_TOKEN", "INVPW_DESKTOP", "STEALTHFOX_WEBRTC_DISABLE_IPV6")
|
||||
"INVPW_SESSION_TOKEN", "INVPW_DESKTOP")
|
||||
|
||||
|
||||
def _clean_env(base=None):
|
||||
|
||||
+291
-80
@@ -4,15 +4,13 @@ Two layers, both runnable on GitHub CI:
|
||||
|
||||
* **unit** (`@pytest.mark.unit`) - pure SDP/candidate assertions against golden
|
||||
samples. No browser, no proxy, no network. These lock in every rule we found
|
||||
on 2026-06-06: host must be mDNS ``.local``; the synthetic srflx must carry the
|
||||
egress IP with a GENUINE nICEr priority (never ``local_pref == 0xFFFF``) and a
|
||||
on 2026-06-06: host must be mDNS ``.local``; an srflx must carry a
|
||||
GENUINE nICEr priority (never ``local_pref == 0xFFFF``) and a
|
||||
stable, distinct foundation; CreepJS's resolver must return the egress, and a
|
||||
host-only SDP must read as "blocked". They run in the standard ``tests.yml``.
|
||||
|
||||
* **e2e** (`@pytest.mark.e2e`) - launch the patched binary and verify the live
|
||||
ICE gather. "Being behind a proxy" is faked WITHOUT any external proxy provider:
|
||||
- the egress IP is injected via ``STEALTHFOX_WEBRTC_PUBLIC_IP`` (RFC 5737
|
||||
TEST-NET, so it never collides with a real IP);
|
||||
- the "behind a TCP-only SOCKS proxy" condition is reproduced by a tiny
|
||||
in-process SOCKS5 server that relays TCP CONNECT but refuses UDP ASSOCIATE
|
||||
(exactly a residential TCP-only proxy → WebRTC's default-route UDP probe
|
||||
@@ -240,27 +238,14 @@ def test_shipped_webrtc_baseline_is_the_validated_config():
|
||||
# without a proxy the pref did.
|
||||
assert "zoom.stealth.webrtc.disable_ipv6" not in prefs
|
||||
assert "media.peerconnection.ice.disableIPv6" not in prefs
|
||||
# The single source is the environment, and it turns on ONLY behind a proxy.
|
||||
#
|
||||
# Measured on 2026-08-25 against the installed retail Firefox, same
|
||||
# connection (dual-stack, no VPN): retail emits 6 candidates - host UDP x2
|
||||
# and host TCP x2 obfuscated mDNS, plus srflx v4 and **srflx v6 with the
|
||||
# real global address IN THE CLEAR** (mDNS only covers the hosts). We
|
||||
# emitted 3, because we always filtered IPv6: we looked like an IPv4-only
|
||||
# machine where the reference is dual-stack.
|
||||
#
|
||||
# Behind an IPv4 proxy the filter is genuinely useful (that IPv6 would be a
|
||||
# leak and an inconsistency with the HTTP IP); without a proxy it protects
|
||||
# nothing and only costs realism.
|
||||
# The single source is the environment (STEALTHFOX_WEBRTC_NETWORK, drawn from
|
||||
# the seed), declared with or without a proxy.
|
||||
from invisible_core import network_to_declare
|
||||
from invisible_core.launch import build_launch_env
|
||||
from invisible_playwright._session import build_env
|
||||
for build_fn in (lambda **k: build_launch_env({}, **k), build_env):
|
||||
env_with = build_fn(srflx_declared="203.0.113.77", base_env={})
|
||||
assert env_with["STEALTHFOX_WEBRTC_DISABLE_IPV6"] == "1"
|
||||
assert env_with["STEALTHFOX_WEBRTC_PUBLIC_IP"] == "203.0.113.77"
|
||||
env_without = build_fn(srflx_declared=None, base_env={})
|
||||
assert "STEALTHFOX_WEBRTC_DISABLE_IPV6" not in env_without
|
||||
assert "STEALTHFOX_WEBRTC_PUBLIC_IP" not in env_without
|
||||
env = build_fn(network_declared=network_to_declare(42), base_env={})
|
||||
assert env["STEALTHFOX_WEBRTC_NETWORK"] == network_to_declare(42)
|
||||
# peerconnection stays ON (a disabled WebRTC is itself a tell).
|
||||
assert prefs["media.peerconnection.enabled"] is True
|
||||
|
||||
@@ -459,14 +444,13 @@ def _launch(**extra):
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_srflx_is_real_and_resolvable(local_https_page):
|
||||
"""No proxy needed: the egress is faked via the env. Asserts the live srflx
|
||||
is genuine (Fix A/B) and that CreepJS's resolver returns it (not blocked)."""
|
||||
def test_the_gather_is_real_without_a_proxy(local_https_page):
|
||||
"""No proxy: the engine keeps the real network. The gather completes, the
|
||||
host is mDNS, and an srflx, when one is born, is genuine (Fix A/B) and
|
||||
resolvable by the resolver of a studied system (not blocked)."""
|
||||
binary = _e2e_binary()
|
||||
if not binary:
|
||||
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
|
||||
os.environ["STEALTHFOX_WEBRTC_PUBLIC_IP"] = _FAKE_EGRESS
|
||||
os.environ["STEALTHFOX_WEBRTC_DISABLE_IPV6"] = "1"
|
||||
with _launch(binary_path=binary) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto(local_https_page, wait_until="domcontentloaded", timeout=60000)
|
||||
@@ -474,97 +458,324 @@ def test_srflx_is_real_and_resolvable(local_https_page):
|
||||
cands = candidates(res["candidates"])
|
||||
assert cands, "ICE produced ZERO candidates (blocked)"
|
||||
assert host_is_mdns(cands), [c["address"] for c in host_candidates(cands)]
|
||||
srflx = [c for c in srflx_candidates(cands) if c["address"] == _FAKE_EGRESS]
|
||||
assert srflx, f"no synthetic srflx with {_FAKE_EGRESS}: {res['candidates']}"
|
||||
ok, reasons = srflx_realness(srflx[0], expected_ip=_FAKE_EGRESS)
|
||||
assert ok, reasons
|
||||
srflx = srflx_candidates(cands)
|
||||
for c in srflx:
|
||||
ok, reasons = srflx_realness(c, expected_ip=c["address"])
|
||||
assert ok, reasons
|
||||
# Two srflx for the same base must share ONE stable foundation (Fix B).
|
||||
assert len({c["foundation"] for c in srflx}) == 1
|
||||
assert creep_get_ipaddress(res["sdp"]) == _FAKE_EGRESS
|
||||
assert len({c["foundation"] for c in srflx}) <= 1
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_not_blocked_behind_tcp_only_socks(socks5_tcp_only):
|
||||
"""Fix C sentinel: behind a TCP-only SOCKS proxy on a remote origin, ICE
|
||||
must still complete (host .local + synthetic srflx), not return zero
|
||||
candidates. Without Fix C this page is fully 'blocked'."""
|
||||
"""Behind a TCP-only SOCKS proxy on a remote origin, ICE must still complete
|
||||
(host .local candidates), not return zero candidates: a fully blocked
|
||||
WebRTC is itself a tell. The session declares its network from the seed
|
||||
(STEALTHFOX_WEBRTC_NETWORK); that variable is read by the new engine only."""
|
||||
binary = _e2e_binary()
|
||||
if not binary:
|
||||
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
|
||||
os.environ["STEALTHFOX_WEBRTC_PUBLIC_IP"] = _FAKE_EGRESS
|
||||
os.environ["STEALTHFOX_WEBRTC_DISABLE_IPV6"] = "1"
|
||||
proxy = {"server": f"socks5://127.0.0.1:{socks5_tcp_only.port}"}
|
||||
try:
|
||||
with _launch(binary_path=binary, proxy=proxy) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
# remote origin loaded THROUGH the local SOCKS proxy (not localhost,
|
||||
# so no proxy-bypass) → WebRTC proxy config active → Fix C path.
|
||||
# so no proxy-bypass) -> WebRTC proxy config active.
|
||||
page.goto("https://example.com/", wait_until="domcontentloaded", timeout=70000)
|
||||
res = page.evaluate(_PROBE_JS)
|
||||
except Exception as exc: # network/proxy unavailable in this environment
|
||||
pytest.skip(f"proxy/network path unavailable: {exc!r}")
|
||||
cands = candidates(res["candidates"])
|
||||
# Hard regression check: ZERO candidates means WebRTC is fully blocked behind
|
||||
# the SOCKS proxy - that's the Fix C regression this sentinel exists to catch.
|
||||
assert cands, "behind SOCKS the gather returned ZERO candidates - Fix C regressed (blocked)"
|
||||
assert cands, "behind SOCKS the gather returned ZERO candidates (blocked)"
|
||||
assert host_is_mdns(cands)
|
||||
# A missing synthetic srflx used to be a skip, blamed on "a datacenter CI
|
||||
# box". That was wrong, and the skip hid a real defect on every Linux run:
|
||||
# behind a SOCKS proxy with remote DNS the document channel reports
|
||||
# 0.0.0.0 as the server address, and Firefox hands that wildcard to nICEr's
|
||||
# default-route probe. Windows refuses a UDP connect() to 0.0.0.0, so Fix C
|
||||
# fires and the synthetic srflx is born; Linux accepts it and answers
|
||||
# 127.0.0.1, so Fix C never fired, no srflx was born, and real sites saw
|
||||
# WebRTC as blocked. firefox-35 rejects a wildcard target in nICEr itself,
|
||||
# so Linux takes the Windows path. From that engine on, a missing srflx is
|
||||
# the defect this sentinel exists for, on every platform, and it FAILS.
|
||||
# Only an engine older than firefox-35 still skips, naming the known defect.
|
||||
srflx = [c for c in srflx_candidates(cands) if c["address"] == _FAKE_EGRESS]
|
||||
if not srflx:
|
||||
revision = _engine_revision()
|
||||
if revision is not None and revision < 35:
|
||||
pytest.skip(f"engine firefox-{revision} predates the nICEr wildcard "
|
||||
"fix: behind SOCKS on Linux no synthetic srflx is born "
|
||||
"(known defect B236, fixed in firefox-35)")
|
||||
pytest.fail("behind SOCKS the gather has no synthetic srflx with "
|
||||
f"{_FAKE_EGRESS} on engine {_engine_tag()}: real sites see "
|
||||
f"WebRTC as blocked (B236). Candidates: {res['candidates']}")
|
||||
assert creep_get_ipaddress(res["sdp"]) == _FAKE_EGRESS
|
||||
|
||||
|
||||
def _engine_tag() -> str:
|
||||
"""The release tag of the engine just launched. The launch refuses a binary
|
||||
the active seal does not describe (`verify_engine`), so after a launch the
|
||||
active seal's tag IS the binary's revision."""
|
||||
from invisible_core.seal import active_seal
|
||||
return active_seal().tag
|
||||
# The gather the next tests read: one STUN server, by number, and everything the engine says about it.
|
||||
_RELAY_PROBE_JS = r"""async (stun) => {
|
||||
const t0 = performance.now();
|
||||
const pc = new RTCPeerConnection({iceServers: [{urls: [stun]}]});
|
||||
pc.createDataChannel('');
|
||||
const cands = [], errors = [], at = {};
|
||||
pc.addEventListener('icecandidate', e => {
|
||||
if (e.candidate && e.candidate.candidate) {
|
||||
cands.push(e.candidate.candidate);
|
||||
const typ = (e.candidate.candidate.match(/ typ (\w+)/) || [])[1];
|
||||
if (typ && !(typ in at)) at[typ] = Math.round(performance.now() - t0);
|
||||
}
|
||||
});
|
||||
pc.addEventListener('icecandidateerror', e => { errors.push({code: e.errorCode, text: e.errorText, url: e.url}); at.error = Math.round(performance.now() - t0); });
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
await new Promise(resolve => {
|
||||
const timer = setTimeout(resolve, 25000);
|
||||
pc.addEventListener('icegatheringstatechange', () => {
|
||||
if (pc.iceGatheringState === 'complete') { at.complete = Math.round(performance.now() - t0); clearTimeout(timer); resolve(); }
|
||||
});
|
||||
});
|
||||
const sdp = (pc.localDescription && pc.localDescription.sdp) || '';
|
||||
try { pc.close(); } catch (e) {}
|
||||
return {candidates: cands, errors, sdp, at_ms: at};
|
||||
}"""
|
||||
|
||||
|
||||
def _address_of_this_host() -> str:
|
||||
"""The IPv4 address the host sends from (a routable one, as a real gateway's relay is). No packet is sent."""
|
||||
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
probe.connect(("192.0.2.1", 9))
|
||||
return probe.getsockname()[0]
|
||||
finally:
|
||||
probe.close()
|
||||
|
||||
|
||||
_ICE_PREFS = [
|
||||
{}, # the engine's default: ICE in the socket process
|
||||
{"media.peerconnection.mtransport_process": False}, # ICE in the process of the page
|
||||
]
|
||||
_ICE_IDS = ["ice_in_the_socket_process", "ice_in_the_content_process"]
|
||||
|
||||
|
||||
def _gather_behind_a_coherent_gateway(monkeypatch, credentials, ice_prefs, rtt_ms, page_first_ms=None):
|
||||
"""Launch the default engine behind a local gateway with coherent UDP, `rtt_ms` away, gather with a STUN server only
|
||||
its relay reaches, and say whether the page's request took the relay and what the gather looked like."""
|
||||
binary = _e2e_binary()
|
||||
if not binary:
|
||||
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
|
||||
from invisible_core import _geo
|
||||
|
||||
from _socks_servers import STUN_NUMBER, STUN_PORT, coherent
|
||||
stun = f"stun:{STUN_NUMBER}:{STUN_PORT}"
|
||||
user, password = credentials or (None, None)
|
||||
# The relay sits on the address of this host, as a real gateway's does: the engine's ICE sockets are bound to an
|
||||
# interface address, and on Windows such a socket cannot send to a relay on loopback.
|
||||
with coherent(user=user, password=password, relay_host=_address_of_this_host(), rtt_ms=rtt_ms) as gateway:
|
||||
exit_ip = gateway.tcp_exit
|
||||
# The session asks the gateway for its TCP exit over HTTPS, which no local gateway can answer as itself: the
|
||||
# answer is the gateway's. The UDP probe that follows is NOT replaced: it runs through the relay, for real.
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", lambda *_a, **_k: exit_ip)
|
||||
extra_prefs = {"media.peerconnection.ice.obfuscate_host_addresses": True, **ice_prefs}
|
||||
with _launch(binary_path=binary, proxy=gateway.proxy, extra_prefs=extra_prefs) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
if page_first_ms is None:
|
||||
page.goto("about:blank")
|
||||
else:
|
||||
# A page that is loaded through the gateway, and a while later asks for WebRTC.
|
||||
page.goto("http://page.test/")
|
||||
page.wait_for_timeout(page_first_ms)
|
||||
res = page.evaluate(_RELAY_PROBE_JS, stun)
|
||||
carried = [(host, port) for host, port, _payload in gateway.datagrams]
|
||||
stun_requests = gateway.stun.requests
|
||||
associates = gateway.associates
|
||||
srflx = [c for c in srflx_candidates(candidates(res["candidates"])) if c["address"] == exit_ip]
|
||||
verdict = (f"srflx with the gateway's exit {exit_ip}: {srflx}; candidates: {res['candidates']}; "
|
||||
f"ICE errors: {res['errors']}; gather timings (ms from the offer): {res['at_ms']}; "
|
||||
f"datagrams the relay carried: {carried}; STUN requests the server answered: {stun_requests}; "
|
||||
f"UDP ASSOCIATEs the gateway saw: {associates}; round trip to the gateway: {rtt_ms} ms")
|
||||
return bool(srflx) and (STUN_NUMBER, STUN_PORT) in carried, verdict, res["at_ms"]
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.parametrize("credentials", [None, ("alice", "s3cret"), ("user~tcp-windows-65535", "not-a-real-password")],
|
||||
ids=["no_auth", "user_and_password", "user_with_a_tilde"])
|
||||
@pytest.mark.parametrize("ice_prefs", _ICE_PREFS, ids=_ICE_IDS)
|
||||
def test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay(monkeypatch, credentials, ice_prefs):
|
||||
"""The default engine, a SOCKS5 gateway that relays UDP and whose UDP exit is its TCP exit: the page's STUN request
|
||||
goes THROUGH the relay and the srflx it gets is the gateway's exit.
|
||||
|
||||
The two places ICE can run are both held: in the socket process (the engine's default, `media.peerconnection.
|
||||
mtransport_process`; the sockets are NrSocket's) and in the process of the page (UDPSocketParent's sockets), each
|
||||
with a gateway that wants no credentials and with one that does. A request that does not take the relay ends in
|
||||
an ICE error 701 and no srflx; the failure message says what the gateway saw.
|
||||
|
||||
The gateway is local (tests/_socks_servers.py): the TCP exit and the UDP exit it reports are documentation addresses,
|
||||
and the STUN server the page is given is a documentation address too, so the only road to it is the relay. The page
|
||||
reaches the proxy by the session the Juggler holds, as every page does; nothing here sets a pref of the engine."""
|
||||
took_the_relay, verdict, _timings = _gather_behind_a_coherent_gateway(monkeypatch, credentials, ice_prefs, rtt_ms=0)
|
||||
assert took_the_relay, "the page's STUN request did not take the relay. " + verdict
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_a_host_with_ipv6_addresses_gathers_through_an_ipv4_relay(monkeypatch):
|
||||
"""The ICE sockets are opened with the family of the host candidate they carry (NrSocket::create, PR_OpenUDPSocket
|
||||
with the address's family): an IPv6 host gets AF_INET6 sockets next to its AF_INET ones, while the relay of the
|
||||
gateway is IPv4. With the host addresses in the clear, the IPv4 STUN server must still be answered through the relay."""
|
||||
took_the_relay, verdict, _timings = _gather_behind_a_coherent_gateway(
|
||||
monkeypatch, ("alice", "s3cret"), {"media.peerconnection.ice.obfuscate_host_addresses": False}, 0)
|
||||
print("[families] " + verdict)
|
||||
assert took_the_relay, "the page's STUN request did not take the relay. " + verdict
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.parametrize("rtt_ms", [80, 150, 250])
|
||||
@pytest.mark.parametrize("ice_prefs", _ICE_PREFS, ids=_ICE_IDS)
|
||||
def test_a_gateway_that_is_far_away_still_gives_the_page_a_srflx_born_through_its_relay(monkeypatch, ice_prefs, rtt_ms):
|
||||
"""The same gather with a gateway that is not on loopback: every answer on the control connection waits `rtt_ms`
|
||||
and the relay adds half of it each way. The layer opens one association per ICE socket, one after the other, each
|
||||
with a connect, a greeting, an authentication and the ASSOCIATE; a gather must not be over before they are done."""
|
||||
took_the_relay, verdict, _timings = _gather_behind_a_coherent_gateway(
|
||||
monkeypatch, ("alice", "s3cret"), ice_prefs, rtt_ms)
|
||||
print(f"[gather] rtt {rtt_ms} ms, {_ICE_IDS[_ICE_PREFS.index(ice_prefs)]}: {_timings}")
|
||||
assert took_the_relay, "the page's STUN request did not take the relay. " + verdict
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.parametrize("ice_prefs", _ICE_PREFS, ids=_ICE_IDS)
|
||||
def test_the_first_candidate_of_a_gather_does_not_wait_for_a_gateway_that_is_far_away(monkeypatch, ice_prefs):
|
||||
"""⛔ THE KNOWN-BAD INPUT: a gateway 250 ms away. The layer made its associations one after the other on the thread of
|
||||
the ICE sockets, a connect, a greeting, an authentication and the ASSOCIATE each, so the first candidate of the page
|
||||
came out after about twelve round trips (host candidate at 2.3 s on Linux and 3.0 s on Windows, against well under a
|
||||
second next to the gateway), and a page that times `icecandidate` reads it. A candidate does not wait for the proxy:
|
||||
the host candidate of the far gather comes within a round trip and a quarter of a second of the near one, and the
|
||||
srflx within the handshake (four round trips) and a STUN request (one) of its host candidate."""
|
||||
rtt_ms = 250
|
||||
near_ok, near_verdict, near = _gather_behind_a_coherent_gateway(monkeypatch, ("alice", "s3cret"), ice_prefs, 0)
|
||||
far_ok, far_verdict, far = _gather_behind_a_coherent_gateway(monkeypatch, ("alice", "s3cret"), ice_prefs, rtt_ms)
|
||||
print(f"[first candidate] near {near}, {rtt_ms} ms away {far}")
|
||||
assert near_ok, near_verdict
|
||||
assert far_ok, far_verdict
|
||||
assert far["host"] - near["host"] <= rtt_ms + 250, (
|
||||
f"the first candidate waited for the gateway: host candidate at {far['host']} ms behind a gateway {rtt_ms} ms away, "
|
||||
f"{near['host']} ms next to it. {far_verdict}")
|
||||
assert far["srflx"] - far["host"] <= 5 * rtt_ms + 250, (
|
||||
f"the srflx came {far['srflx'] - far['host']} ms after the host candidate. {far_verdict}")
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server(monkeypatch):
|
||||
"""⛔ THE KNOWN-BAD INPUT: a gateway 250 ms away, a page loaded through it, and two seconds later the page asks for
|
||||
WebRTC. Next to a gateway the srflx comes at once; behind this one it may come later by the road itself, the round
|
||||
trip of the relay to the STUN server and back, and by nothing else: the connect, the greeting, the authentication and
|
||||
the ASSOCIATE of each socket (about 0.56 s against the real driver) are made before the page asks, when the proxy
|
||||
of the context is first used, not after. A target without the proxy has no such cost to show."""
|
||||
rtt_ms = 250
|
||||
near_ok, near_verdict, near = _gather_behind_a_coherent_gateway(
|
||||
monkeypatch, ("alice", "s3cret"), {}, 0, page_first_ms=2000)
|
||||
far_ok, far_verdict, far = _gather_behind_a_coherent_gateway(
|
||||
monkeypatch, ("alice", "s3cret"), {}, rtt_ms, page_first_ms=2500)
|
||||
print(f"[page first] near {near}, {rtt_ms} ms away {far}")
|
||||
assert near_ok, near_verdict
|
||||
assert far_ok, far_verdict
|
||||
assert far["host"] - near["host"] <= 100, f"the host candidate waited: {far_verdict}"
|
||||
assert far["srflx"] - near["srflx"] <= rtt_ms + 250, (
|
||||
f"the srflx came {far['srflx']} ms after the offer behind a gateway {rtt_ms} ms away, {near['srflx']} ms next to "
|
||||
f"it: more than the road to the server ({rtt_ms} ms). {far_verdict}")
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_two_contexts_with_two_proxies_each_gets_the_srflx_of_its_own(monkeypatch):
|
||||
"""⛔ THE KNOWN-BAD INPUT: a session whose proxy is one gateway and a context whose proxy is another. The proxy a
|
||||
page's traffic takes is the one of its context, UDP included: the srflx of each context is the exit of its own
|
||||
gateway. (The engine took one proxy for the whole session and handed over nothing when two differed.)"""
|
||||
binary = _e2e_binary()
|
||||
if not binary:
|
||||
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
|
||||
from invisible_core import _geo
|
||||
|
||||
from _socks_servers import STUN_NUMBER, STUN_PORT, coherent
|
||||
stun = f"stun:{STUN_NUMBER}:{STUN_PORT}"
|
||||
host = _address_of_this_host()
|
||||
with coherent(exit_ip="203.0.113.7", user="alice", password="s3cret", relay_host=host) as first, coherent(exit_ip="198.51.100.77", user="bob", password="hunter2", relay_host=host) as second:
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", lambda *_a, **_k: first.tcp_exit)
|
||||
extra_prefs = {"media.peerconnection.ice.obfuscate_host_addresses": True}
|
||||
with _launch(binary_path=binary, proxy=first.proxy, extra_prefs=extra_prefs) as browser:
|
||||
of_the_session = browser.new_context().new_page()
|
||||
of_its_own = browser.new_context(proxy=second.proxy).new_page()
|
||||
res_session = of_the_session.evaluate(_RELAY_PROBE_JS, stun)
|
||||
res_own = of_its_own.evaluate(_RELAY_PROBE_JS, stun)
|
||||
|
||||
def exits(res):
|
||||
return sorted(c["address"] for c in srflx_candidates(candidates(res["candidates"])))
|
||||
|
||||
assert exits(res_session) == [first.tcp_exit], f"the context of the session: {res_session}"
|
||||
assert exits(res_own) == [second.tcp_exit], f"the context with a proxy of its own: {res_own}"
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_the_turn_over_tcp_of_a_context_goes_through_the_proxy_of_that_context(monkeypatch):
|
||||
"""⛔ THE KNOWN-BAD INPUT: the proxy lookup of the TCP socket of a TURN server was made with a channel of the system
|
||||
principal, so the filter of the session answered for context 0 and a SOCKS5 proxy of the context was not the one the
|
||||
TURN connection took. The page below sits in a context with a proxy of its own and asks for a TURN server over TCP:
|
||||
the CONNECT must reach the gateway of that context and not the one of the session."""
|
||||
binary = _e2e_binary()
|
||||
if not binary:
|
||||
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
|
||||
from invisible_core import _geo
|
||||
|
||||
from _socks_servers import coherent
|
||||
host = _address_of_this_host()
|
||||
turn_host, turn_port = "198.51.100.9", 3478
|
||||
with coherent(exit_ip="203.0.113.7", user="alice", password="s3cret", relay_host=host) as session, coherent(exit_ip="198.51.100.77", user="bob", password="hunter2", relay_host=host) as context:
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", lambda *_a, **_k: session.tcp_exit)
|
||||
extra_prefs = {"media.peerconnection.ice.obfuscate_host_addresses": True}
|
||||
with _launch(binary_path=binary, proxy=session.proxy, extra_prefs=extra_prefs) as browser:
|
||||
page = browser.new_context(proxy=context.proxy).new_page()
|
||||
page.goto("about:blank")
|
||||
page.evaluate("""async (turn) => {
|
||||
const pc = new RTCPeerConnection({iceServers: [{urls: [turn], username: 'u', credential: 'p'}]});
|
||||
pc.createDataChannel('');
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
await new Promise(r => setTimeout(r, 6000));
|
||||
pc.close();
|
||||
}""", f"turn:{turn_host}:{turn_port}?transport=tcp")
|
||||
in_context = [c for c in context.connects if c == (turn_host, turn_port)]
|
||||
in_session = [c for c in session.connects if c == (turn_host, turn_port)]
|
||||
assert in_context and not in_session, (
|
||||
f"the TURN connection of the context: by the gateway of the context {context.connects}, "
|
||||
f"by the gateway of the session {session.connects}")
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_a_proxy_that_does_not_relay_udp_gives_no_srflx_at_all(monkeypatch):
|
||||
"""⛔ THE KNOWN-BAD INPUT: a gateway that refuses UDP ASSOCIATE. The target is a retail Windows at home on a network
|
||||
that blocks UDP: the host candidates are there, the UDP datagrams leave nowhere and nothing answers (no error, no
|
||||
direct send), so the STUN request retransmits and ends in 701 in nICEr's own time, and the page gets no srflx: the
|
||||
session does not invent one (a candidate with the exit of TCP and no allocation behind it, raddr 0.0.0.0, is a value
|
||||
no browser makes). The time of that 701 on a retail with UDP blocked is still to be measured."""
|
||||
binary = _e2e_binary()
|
||||
if not binary:
|
||||
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
|
||||
from invisible_core import _geo
|
||||
|
||||
from _socks_servers import STUN_NUMBER, STUN_PORT, tcp_only
|
||||
stun = f"stun:{STUN_NUMBER}:{STUN_PORT}"
|
||||
with tcp_only(user="alice", password="s3cret") as gateway:
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", lambda *_a, **_k: gateway.tcp_exit)
|
||||
extra_prefs = {"media.peerconnection.ice.obfuscate_host_addresses": True}
|
||||
with _launch(binary_path=binary, proxy=gateway.proxy, extra_prefs=extra_prefs) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto("about:blank")
|
||||
res = page.evaluate(_RELAY_PROBE_JS, stun)
|
||||
typ = [c["typ"] for c in candidates(res["candidates"])]
|
||||
assert "srflx" not in typ and "relay" not in typ, f"a candidate that nothing allocated: {res['candidates']}"
|
||||
assert "host" in typ, f"no host candidate at all: {res['candidates']}"
|
||||
assert [e["code"] for e in res["errors"]] == [701], f"a network that blocks UDP ends the STUN request in 701: {res['errors']}"
|
||||
# The shape of a retail Firefox on a network that drops UDP (notes/retail-udp-blocked-reference.md): udp and tcp host
|
||||
# candidates, and the 701 of the UDP request at nICEr's own time, 11.1-11.3 s, together with the end of the gather: never
|
||||
# an immediate error, never a candidate that nothing allocated.
|
||||
protocols = sorted({c["proto"].upper() for c in candidates(res["candidates"]) if c["typ"] == "host"})
|
||||
assert protocols == ["TCP", "UDP"], f"host candidates of a retail on a network that drops UDP: {res['candidates']}"
|
||||
assert 10_000 <= res["at_ms"]["error"] <= 13_000, (
|
||||
f"the 701 of the UDP request came at {res['at_ms']['error']} ms; nICEr's time on a network that drops UDP is 11.1-11.3 s")
|
||||
|
||||
|
||||
def _engine_revision():
|
||||
"""N for a `firefox-N` tag (a local seal may append to it, as in
|
||||
`firefox-34-prfix`), or None when the tag says no revision. None never
|
||||
buys a skip: an engine that cannot say it is old is judged as a new one."""
|
||||
m = re.match(r"firefox-(\d+)", _engine_tag())
|
||||
return int(m.group(1)) if m else None
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
# The egress IP must not change MID-SESSION.
|
||||
#
|
||||
# Measured on 2026-08-25 on browserleaks, behind a residential proxy: the
|
||||
# page exited from 216.131.76.63 while the WebRTC srflx candidate announced
|
||||
# page exited from 203.0.113.30 while a second reading of the exit said
|
||||
# 216.131.76.64, and the site says so plainly ("WebRTC IP doesn't match your
|
||||
# Remote IP"). It was not a regression in the binary - interleaved A/B between
|
||||
# the release binary and the new one: 4 runs out of 4 consistent on both.
|
||||
#
|
||||
# The cause is that the IP declared to the engine is photographed ONCE, at
|
||||
# launch, and residential proxies do not promise to keep it: the docs of the
|
||||
# The cause is that the egress behind the timezone and the locale is photographed
|
||||
# ONCE, at launch, and residential proxies do not promise to keep it: the docs of the
|
||||
# two providers tried declare TIME-based sticky sessions (60 minutes max for
|
||||
# one; a sliding timeout for the other, which also expires early if the peer
|
||||
# disconnects). On a long session the drift is a certainty, not a risk - which
|
||||
# is why short probes never saw it.
|
||||
#
|
||||
# Owner's decision, 2026-08-25: it is not updated on the fly. A WebRTC IP that
|
||||
# Owner's decision, 2026-08-25: it is not updated on the fly. A timezone that
|
||||
# changes in front of the site's own eyes is as unnatural as the mismatch
|
||||
# itself. A proxy that does not hold the session is not fit for purpose, and
|
||||
# the product must SAY SO instead of carrying on.
|
||||
|
||||
Reference in new issue
Block a user