Compare commits

...
Author SHA1 Message Date
feder-cr e99f9cdbeb tests: a process that reads no seccomp filter while it starts is read again before it is judged
Firefox pre-launches content processes and a child installs its filter only after its
own start-up, so a process sampled during start-up reads Seccomp 0 (run 43523960399:
the newest tab process). A pid that does not read 2 is now read again for up to 10 s;
none is dropped, and one that is still 0 fails with the same message. Two unit tests
hold it (a late filter is accepted, a process that stays unfiltered is not);
unit.udp min_tests 236 -> 238.
2026-11-14 01:10:30 +01:00
feder-cr 1f4fa986c1 tests: say why the push page asks again (silent start-up, lost Push:Registration, same in stock Playwright), with file:line and the bounded wait 2026-11-13 21:53:17 +01:00
feder-cr 9daa1166a2 Revert "tests: revert the retry of getSubscription and the longer wait (a page that retries hides a request that is never answered); keep the stage diagnostics"
This reverts commit fbd376c4c4.
2026-11-13 21:53:04 +01:00
feder-cr fbd376c4c4 tests: revert the retry of getSubscription and the longer wait (a page that retries hides a request that is never answered); keep the stage diagnostics 2026-11-13 21:49:47 +01:00
feder-cr f7a80ebb8c tests: the push page asks for its subscription again until the parent's push service answers
The parent process listens for the push requests of a content process only once its
PushServiceParent exists, which a first-window idle task creates (BrowserGlue
PushService.ensureReady); a request sent earlier is dropped, not queued. The page
of the push case now repeats getSubscription every 2 s (up to 15 times) and the
message says how many asks it took. The assertion is unchanged.
2026-11-13 21:43:58 +01:00
feder-cr 8c90267877 tests: the first browser run of the two context suites, test errors fixed
wrapper.e2e.context.sink: every probe by name behind SOCKS5 (and the TURN names of
the window and two-context cases) never connected, because the lab answers every
name with the address of this host, an RFC 1918 one on a runner, and the engine's
DoH client drops such an answer unless network.trr.allow-rfc1918 is true. The lab
now declares it. turns: by IP is refused by the browser itself ("TLS requires
FQDN, not IP address"), so that case shows no CONNECT and keeps every egress
assertion. The firefox-64 expectations of the three *.local probes were stale
(green in the run).

wrapper.e2e.context.egress: the push case waits for the page to leave pending
(30 s) and says the step it reached (registering, registered, ready,
subscription-read). The direct DoH connection of closing-context_only is an
engine behaviour and its assertion is unchanged.

unit.udp min_tests 233 -> 236 (three new unit tests of the lab).
2026-11-13 21:20:22 +01:00
feder-cr 902f636f77 tests: a session without a proxy declares the DoH provider and builtin-excluded-domains = localhost
The core declares network.trr.builtin-excluded-domains = "localhost" (core #261: behind a proxy a *.local name goes to DoH
through the proxy, not to the host's resolver). The unit test pinned the old set of two keys and was red in the engine
candidate 43471799366, which runs the core of main.
2026-11-13 19:24:48 +01:00
feder-cr d63b0d71bf tests: two contexts alive at once resolve their TURN names each through its own proxy and DoH
Two contexts of one browser, each with its own proxy and its own FakeDoh (a
zone that does not know the other's name), each with a PeerConnection kept
open whose TURN server over TCP has a different name. The port of a CONNECT
(one witness per context, same address) says which context it came from.
Each name must reach only the DoH of its own context through its own proxy,
none the machine's resolver, no CONNECT the other proxy, nothing a witness
direct. Behind SOCKS5 red on firefox-63 and green on firefox-64; behind an
HTTP proxy green on both.
2026-11-13 18:06:06 +01:00
feder-cr c8e7863a2d tests: a PeerConnection of a torn-down window leaves only through the proxy of its context (B3)
A PeerConnection built from the window of a detached iframe or of a closed
popup had no proxy config on the engine firefox-63: direct UDP and TCP from
the host, ICE server names looked up in the default context. Four cases (both
windows, behind SOCKS5 and behind an HTTP proxy) build one with a STUN and a
TURN-over-TCP server by name and judge it with the sinks of the suite; two
controls build the same PeerConnection from an attached iframe. A dead window
that refuses the constructor or never gathers passes the egress assertions and
says so (printed, recorded as dead_window_outcome).

Expected red on firefox-63, green on firefox-64.
2026-11-13 16:59:43 +01:00
feder-cr 474f0f2565 tests: nothing of a context leaves but through its proxy (witness, engine log and nonce as the sink)
A context with a proxy and a session with none, one probe per road a page can
start: fetch, WebSocket, stun, turn over UDP, turn and turns over TCP, each by
name, by IP and by a .local name, behind SOCKS5 and behind an HTTP proxy. The
sink is a witness at an address of this host (no proxy forwards to it), the
watcher, the engine's own resolver log and the resolver trap where it runs.
The Windows second sink is one function that raises until it is written.

Taken unchanged from the minimal-engine port: the page work of the proxied
context and the TURN-by-name reproducer (its engine gate removed: red on
firefox-63, as it is).
2026-11-13 15:59:49 +01:00
9 changed files with 1345 additions and 3 deletions

No files matched your search

+3 -1
View File
@@ -4,8 +4,10 @@
{"id": "wrapper.e2e.udp.sandbox", "giro": "G2", "os": ["linux"], "min_tests": 13, "exact": true, "tests": ["tests/test_the_socket_process_is_sandboxed_e2e.py", "tests/test_webrtc_realness.py::test_the_gather_is_real_without_a_proxy", "tests/test_webrtc_realness.py::test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay", "tests/test_ice_names_by_the_context_proxy_e2e.py::test_a_gateway_without_udp_resolves_the_ice_name_then_ends_in_701"], "marker": "e2e", "needs_root": false, "note": "The browser WITH its sandbox, run by a normal user, as on any Linux that allows user namespaces. On the Ubuntu 24.04 runner AppArmor refuses them to a user, so every other non-root suite runs a browser WITHOUT the sandbox of its socket and content processes; the gate turns the restriction off for this leg (sysctl kernel.apparmor_restrict_unprivileged_userns=0) and the first test fails unless the socket and a tab process have a seccomp filter (Seccomp: 2). The three situations of the UDP line: A (a proxy that carries UDP: the srflx born through the relay), B (no proxy: the gather is real), C (a proxy with no UDP: the ICE server name goes by DoH through the proxy and the gather ends in 701). No root and no resolver trap needed.", "linux_only": "It reads the seccomp filter of the socket and tab processes in /proc. The Windows twin reads the sandbox token of the same processes (integrity level, restrictions) and needs a measurement of the retail Firefox's tokens first; until then Linux only."},
{"id": "wrapper.e2e.web", "giro": "G2", "os": ["linux", "windows"], "min_tests": 27, "exact": true, "tests": ["tests/test_networkidle_through_a_served_browser_with_routes_e2e.py", "tests/test_http3_through_the_proxy_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The networkidle e2e with routes and the HTTP/3 e2e, split from wrapper.e2e.udp (about 260 s of 500 on Linux; the whole suite did not fit the 15 minutes of Windows)."},
{"id": "wrapper.e2e.doh", "giro": "G2", "os": ["linux", "windows"], "min_tests": 19, "exact": true, "tests": ["tests/test_the_hosts_file_of_the_host_is_never_read_e2e.py", "tests/test_resolver_race_e2e.py", "tests/test_doh_under_stress_e2e.py", "tests/test_context_proxy_only_resolves_by_doh_e2e.py", "tests/test_doh_through_the_proxy_e2e.py", "tests/test_ice_names_by_the_context_proxy_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Linux needs root: the resolver trap of the file (ResolverTrap) points /etc/resolv.conf at a counting resolver on port 53. Su Windows il resolver trap non gira: l'asserzione sul resolver di sistema è l'unica omessa. Run it without xdist (port 53 is one per host). On the Linux leg the gate exports INVPW_REQUIRE_TRAP=1: a trap that cannot run or bind port 53 is a failure, not a skipped assertion."},
{"id": "wrapper.e2e.context.egress", "giro": "G2", "os": ["linux", "windows"], "min_tests": 14, "exact": true, "tests": ["tests/test_nothing_leaves_but_the_proxy_e2e.py", "tests/test_a_turn_name_over_tcp_goes_through_the_proxy_of_the_context_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Taken from the minimal-engine port (branch tests/minimal-port) unchanged but for the removed engine gate: 12 = 6 kinds of page work (hints, image/fetch/WebSocket/EventSource, WebRTC STUN and TURN-udp by name, geolocation, a service worker with push, a page still loading when its context closes) x 2 schemes (no proxy at launch and a gateway on the context; a launch gateway and a different one on the context), and 2 = the TURN server named over TCP in those two schemes. EXPECTED RED on the published firefox-63: the 2 TURN-by-name cases (the lookup of the TCP socket takes user context 0; fixed by commits ac0214bff4 and 058edd6cc6 of firefox-64). The 12 have not run on any engine yet. Like wrapper.e2e.doh: the Linux leg runs as root for the resolver trap (INVPW_REQUIRE_TRAP=1); on Windows the DoH log and the gateway's CONNECTs are the sink."},
{"id": "wrapper.e2e.context.sink", "giro": "G2", "os": ["linux"], "min_tests": 31, "exact": true, "tests": ["tests/test_nothing_of_a_context_leaves_but_through_its_proxy_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "The behavioural half of the class gate 'nothing of a context leaves but through its proxy', with a witness at an address of this host (no root, no address on lo) and the engine's own resolver log as the native-lookup sink. 31 = 19 probes (fetch, WebSocket, stun, turn over UDP, turn and turns over TCP, each by name, by IP and by a .local name, behind SOCKS5 and behind an HTTP proxy where the road differs) + 3 controls (the same probe by IP with no proxy IS heard by the witness) + 1 control of the native sink. + 4 PeerConnections built from a torn-down window (a detached iframe, a closed popup; behind SOCKS5 and behind HTTP; defect B3: EXPECTED RED on firefox-63, green on firefox-64) + 2 controls of them (the same PeerConnection from an attached iframe, green on both). + 2 cases of two contexts alive at once (each with its own proxy and DoH, a TURN server over TCP by a different name in each; behind SOCKS5 EXPECTED RED on firefox-63 like turn_tcp-name-socks5, behind HTTP green on both). EXPECTED RED on firefox-63: turn_tcp-name-socks5, turns_tcp-name-socks5 (user context 0, fixed in firefox-64) and the three .local cases fetch-local-socks5, stun-local-socks5, stun-local-http (audit B4, also red on firefox-64 until decided). The Linux leg runs as root so the resolver trap is a second sink.", "linux_only": "The Windows sink of native lookups is not proven yet: _egress_sink.native_lookup_names reads the engine's log everywhere, but its second sink on Windows (the DNS-Client event log, _windows_dns_client_lookups) is step 3 of the class gate and raises until written, and the socket-process log under the Windows sandbox is to be shown on a runner. The suite gets its Windows leg when that is done."},
{"id": "wrapper.e2e.realness", "giro": "G2", "os": ["linux", "windows"], "min_tests": 32, "exact": true, "tests": ["tests/test_realness_behind_a_declared_exit_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "The realness check without a real proxy: six declared exits, the values a page reads, and the roads. Linux runs as root without xdist like the DoH suite (the resolver trap); on Windows the trap does not exist and the assertion on the system resolver is the only one omitted."},
{"id": "wrapper.unit.udp", "giro": "G1", "os": ["linux", "windows"], "min_tests": 222, "exact": true, "tests": ["tests/test_a_served_launch_cannot_turn_the_launch_counter_off.py", "tests/test_the_witness_picks_a_port_both_sockets_bind.py", "tests/test_preload_newtab_reaches_the_core_only_when_asked.py", "tests/test_the_resolver_trap_counts_its_own_users.py", "tests/test_the_doh_e2e_launch_on_a_virtual_display.py", "tests/test_the_realness_helpers.py", "tests/test_the_h3_line_helpers.py", "tests/test_the_fake_doh_delays_and_refuses.py", "tests/test_the_host_address_helper.py", "tests/test_the_udp_chain_helper.py", "tests/test_the_fake_doh_answers.py", "tests/test_doh_session_prefs_unit.py", "tests/test_the_leak_watcher_sees_a_direct_connection.py", "tests/test_the_http_proxy_helper_asks_for_credentials.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_the_network_declaration_reaches_the_engine.py", "tests/test_the_resolver_trap_is_required_by_the_gate.py", "tests/test_the_exit_of_a_context_is_discovered_through_its_own_gateway.py", "tests/test_the_witness_hears_a_direct_send.py"], "marker": "unit", "needs_root": false, "note": "92 = 6+32+21+7+8+3+9+6. The leak watcher file defines exactly one of its two resolver-trap tests per host (7 everywhere), so no test is skipped. `exact`: min_tests is raised by hand when a test is added."},
{"id": "wrapper.unit.udp", "giro": "G1", "os": ["linux", "windows"], "min_tests": 238, "exact": true, "tests": ["tests/test_a_served_launch_cannot_turn_the_launch_counter_off.py", "tests/test_the_witness_picks_a_port_both_sockets_bind.py", "tests/test_preload_newtab_reaches_the_core_only_when_asked.py", "tests/test_the_resolver_trap_counts_its_own_users.py", "tests/test_the_doh_e2e_launch_on_a_virtual_display.py", "tests/test_the_realness_helpers.py", "tests/test_the_h3_line_helpers.py", "tests/test_the_fake_doh_delays_and_refuses.py", "tests/test_the_host_address_helper.py", "tests/test_the_udp_chain_helper.py", "tests/test_the_fake_doh_answers.py", "tests/test_doh_session_prefs_unit.py", "tests/test_the_leak_watcher_sees_a_direct_connection.py", "tests/test_the_http_proxy_helper_asks_for_credentials.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_the_network_declaration_reaches_the_engine.py", "tests/test_the_resolver_trap_is_required_by_the_gate.py", "tests/test_the_exit_of_a_context_is_discovered_through_its_own_gateway.py", "tests/test_the_witness_hears_a_direct_send.py", "tests/test_the_egress_sink_helpers.py"], "marker": "unit", "needs_root": false, "note": "92 = 6+32+21+7+8+3+9+6. The leak watcher file defines exactly one of its two resolver-trap tests per host (7 everywhere), so no test is skipped. `exact`: min_tests is raised by hand when a test is added. The sink of the egress gate (tests/test_the_egress_sink_helpers.py, 16): the engine's log and the witness read on known inputs, and a blind or Windows-without-its-second-sink input that must not answer 'nothing'."},
{"id": "wrapper.e2e.page", "giro": "G2", "os": ["linux", "windows"], "min_tests": 115, "exact": true, "tests": ["tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_popup_of_a_link_reaches_the_client_e2e.py", "tests/test_popup_destinations_e2e.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_route_superseded_e2e.py"], "marker": "e2e", "needs_root": false, "note": "114 = 100 + the 14 of test_a_page_that_moves_on_e2e.py (a navigation the page overtook with location.replace ends; the engine fix 860ef8a6d9 is proved by it). 100 counted at the collection; was 96 = 10+32+16+34+4 before the popup tests of 6200bc2). A page is handed over when the engine says Page.ready; a popup reaches the client (link, noopener, window.open; own site and another; with and without a route; in-process and over launch_server) as Playwright's does; a superseded route. Needs the candidate binary, and the stock Playwright client of the dev extra."},
{"id": "wrapper.unit.page", "giro": "G1", "os": ["linux", "windows"], "min_tests": 72, "exact": true, "tests": ["tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_page_number_follows_the_call.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_the_hand_over_of_a_popup_holds_under_concurrency.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py"], "marker": "unit", "needs_root": false, "note": "72 = 44 + 3+9+5+1+10 of the popup hand-over (24 counted at the collection before; was 20 = 3+8+1+8 before 6200bc2). The page dispatcher's wait for Page.ready and what it hands over; the drive gate goes through the core (the engine waits for the session's road)."}
]
+157
View File
@@ -0,0 +1,157 @@
"""The sink of "nothing of a context leaves but through its proxy": what a test reads to know that a request went AROUND the proxy (no pytest in here).
A context with a proxy and a session with none: the default context is then the machine's own network, so "everything that leaves" cannot be
judged (the browser's own background resolves and connects there, and may). What a test judges is what ITS probe made the browser do: every
name of a probe carries a nonce (``fetch-name-3fa91c.test``) and every address a probe uses is the one of a WITNESS no proxy of the test
forwards to (the gateways refuse a CONNECT past loopback and relay no datagram), so whatever arrives at the witness arrived direct. The sink
has four parts, each of which a test proves is not blind:
* the WITNESS (``_witness.Witness``) at an address of this host: a TCP connection or a datagram that reaches it came from the browser, direct;
* the WATCHER (``_leaks.Watcher``): a connection of a browser process to that address, seen in ``/proc`` or the connection table;
* the NATIVE LOOKUPS of the probe's names: ``native_lookup_names`` is the ONE function a test calls. On Linux it is the engine's own log
(``nsHostResolver.cpp`` writes ``DNS resolve task - Calling getaddrinfo for host [<name>]`` before every native lookup) and, where the
resolver trap runs (root), the trap's questions. On Windows it is the engine's log too, and ``_windows_dns_client_lookups`` is the place
of a second sink that needs no privilege of the test (the DNS-Client event log): until it is written it raises, it never answers "nothing";
* the LOOKUPS IN USER CONTEXT 0: the same log says in which context each name was asked (``Resolving host [<name>]<^userContextId=N>``): a
probe name asked with no ``userContextId`` is a lookup that lost the context of its page, whichever road it then took.
The log is the engine's, not a hook of the test: ``MOZ_LOG=sync,nsHostResolver:5`` and ``MOZ_LOG_FILE=<dir>/moz-%PID.log`` give one file per
process (``moz-<pid>.log`` and ``moz-<pid>.log.child-<n>``), as ``test_the_hosts_file_of_the_host_is_never_read_e2e.py`` reads it.
"""
from __future__ import annotations
import glob
import os
import re
import secrets
import sys
from typing import Callable, Dict, Iterable, List, Optional, Sequence
MOZ_LOG = "sync,nsHostResolver:5"
LOG_FILE_NAME = "moz-%PID.log"
_NATIVE = re.compile(r"Calling getaddrinfo for host \[([^\]]+)\]")
_RESOLVING = re.compile(r"Resolving host \[([^\]]+)\]<([^>]*)>")
_STARTED = "nsHostResolver::Init"
def new_nonce() -> str:
"""Six hex digits: unique in a run, and a legal label."""
return secrets.token_hex(3)
def log_files(directory) -> List[str]:
return sorted(glob.glob(os.path.join(str(directory), "moz-*.log*")))
def _lines(directory) -> Iterable[str]:
for path in log_files(directory):
with open(path, "rb") as handle:
for raw in handle:
yield raw.decode("utf-8", "replace")
def engine_log_native_lookups(directory, nonce: Optional[str] = None) -> List[str]:
"""The names the engine looked up with the machine's resolver (``getaddrinfo``), in the order it did, only those with ``nonce`` when given."""
out = []
for line in _lines(directory):
found = _NATIVE.search(line)
if found and (nonce is None or nonce in found.group(1)):
out.append(found.group(1))
return out
def engine_log_context_zero_lookups(directory, nonce: Optional[str] = None) -> List[str]:
"""The names asked of the resolver in a request with NO user context (user context 0: the suffix has no ``userContextId``)."""
out = []
for line in _lines(directory):
found = _RESOLVING.search(line)
if found and "userContextId" not in found.group(2) and (nonce is None or nonce in found.group(1)):
out.append(found.group(1))
return out
def engine_log_is_alive(directory) -> bool:
"""The control of the log sink: some process logged the start of its resolver. A log with no such line says nothing."""
return any(_STARTED in line for line in _lines(directory))
def _windows_dns_client_lookups(nonce: str) -> List[str]:
"""The names the Windows DNS client was asked for, from ``Microsoft-Windows-DNS-Client/Operational`` (events 3006 and 3008, enabled with
``wevtutil sl <log> /e:true``, which the hosted runner may do), by this browser's processes, with ``nonce``. NOT WRITTEN YET (step 3 of the
class gate): the engine's own log is the sink of Windows until then, and a second sink that raises is better than one that answers nothing."""
raise NotImplementedError("the Windows DNS-Client sink of the egress gate is step 3: read the event log of the browser's processes here")
def native_lookup_names(directory, nonce: str, trap=None, platform: Optional[str] = None,
windows_sink: Callable[[str], List[str]] = _windows_dns_client_lookups) -> List[str]:
"""Every name with ``nonce`` that the machine's resolver was asked for by the browser: the ONE function every test calls.
``trap`` is a ``_leaks.ResolverTrap`` (Linux, root) or None. ``platform`` and ``windows_sink`` are for the unit test of this function."""
platform = platform or sys.platform
names = set(engine_log_native_lookups(directory, nonce))
if trap is not None and platform.startswith("linux"):
names |= {n for n in trap.names() if nonce in n}
if platform == "win32":
names |= set(windows_sink(nonce))
return sorted(names)
class EgressSink:
"""What a probe of one case left behind, and the verdicts the test makes of it.
``witness`` is the ``_witness.Witness`` of the case, ``watcher`` the ``_leaks.Watcher`` (stopped), ``directory`` the folder of the engine's
log, ``nonce`` the one of the probe's names, ``trap`` the resolver trap or None."""
def __init__(self, witness, watcher, directory, nonce: str, trap=None, native: Callable[..., List[str]] = native_lookup_names):
self.witness, self.watcher, self.directory, self.nonce, self.trap = witness, watcher, directory, nonce, trap
self._native = native
def arrivals(self) -> Dict[str, list]:
"""Everything the witness heard: nothing is forwarded to it by any proxy of the tests, so each one is a send around the proxy."""
return self.witness.heard()
def direct_connections(self) -> list:
return [c for c in self.watcher.direct if c.remote.rsplit(":", 1)[0] == self.witness.address]
def native_lookups(self) -> List[str]:
return self._native(self.directory, self.nonce, self.trap)
def context_zero_lookups(self) -> List[str]:
return engine_log_context_zero_lookups(self.directory, self.nonce)
def blind_problems(self) -> List[str]:
"""The reasons this sink cannot be trusted: a green over a sink that sees nothing proves nothing."""
out = []
if not self.watcher.watched_pids:
out.append("the watcher never saw a browser process (it saw: %s)" % self.watcher.process_names)
if not log_files(self.directory):
out.append("the engine wrote no log in %s: the native-lookup sink is blind (MOZ_LOG / MOZ_LOG_FILE did not reach it)" % self.directory)
elif not engine_log_is_alive(self.directory):
out.append("no process of the browser logged the start of its resolver (%r): the native-lookup sink is blind" % _STARTED)
return out
def leak_problems(self) -> List[str]:
"""The sentences of every leak the sink saw, empty when the probe stayed home."""
out = []
heard = self.arrivals()
if heard["tcp"] or heard["udp"]:
out.append("the witness at %s was reached direct: %d TCP connection(s) from %s, %d datagram(s) from %s"
% (self.witness.address, len(heard["tcp"]), sorted({h[0] for h in heard["tcp"]}), len(heard["udp"]),
sorted({h[0] for h in heard["udp"]})))
seen = self.direct_connections()
if seen:
out.append("the watcher saw the browser connect to %s without the proxy: %s"
% (self.witness.address, "; ".join("%s %s -> %s %s" % (c.process, c.protocol, c.remote, c.status) for c in seen)))
native = self.native_lookups()
if native:
out.append("the machine's resolver was asked for %s (a lookup of a proxied context took the native road)" % native)
zero = self.context_zero_lookups()
if zero:
out.append("%s was looked up in user context 0, not in the context of its page" % sorted(set(zero)))
return out
def named_connects(gateway_connects: Sequence, is_address: Callable[[str], bool], allowed_names: Sequence[str] = ()) -> List[tuple]:
"""The CONNECTs of a SOCKS5 gateway that carry a NAME (the browser must resolve and connect by address), except ``allowed_names``."""
return [(h, p) for h, p in gateway_connects if not is_address(h) and h not in allowed_names]
+137
View File
@@ -0,0 +1,137 @@
"""The page work of the "nothing leaves but the proxy" e2e: the names, the pages and the server (no pytest in here).
A page can make a browser do much more than load a document: hints (``dns-prefetch``, ``preconnect``, ``prefetch``, ``preload``), an
image, a ``fetch``, a WebSocket, an EventSource, a WebRTC gather with a STUN and a TURN server, a geolocation request, a service worker
with push, and a page still loading when its context is closed. Each of them is tried in a context of its own behind a SOCKS5 gateway,
and what the test asks is where the browser went: no question to the resolver of the machine, no direct connection, every name asked
to the DoH THROUGH the gateway of the context, every CONNECT by an ADDRESS.
The names are the zone of a ``FakeDoh``. The pages are served from 127.0.0.1 and reached by a name (``<case>-site.test``) that points
there. Every name the page work uses points at a DOCUMENTATION address (RFC 5737, 198.51.100.0/24), never at loopback, for two reasons:
a connection a browser opens straight to it is seen by the leak watcher (a loopback one never is), and the gateway of the tests refuses
a CONNECT to a non-loopback address and lists it, which is how a test sees that the browser CONNECTed by the address the DoH gave.
"""
from __future__ import annotations
import http.server
import threading
from typing import Dict, List, Optional
from _servers import LocalServer
#: The zone of the page work: name -> the documentation address a lookup of it answers.
ROUTABLE: Dict[str, str] = {
"prefetch-a.test": "198.51.100.21", "preconnect-b.test": "198.51.100.22", "prefetch-c.test": "198.51.100.23",
"preload-d.test": "198.51.100.24",
"img-e.test": "198.51.100.25", "fetch-f.test": "198.51.100.26", "ws-g.test": "198.51.100.27", "es-h.test": "198.51.100.28",
"stun-i.test": "198.51.100.29", "turn-j.test": "198.51.100.30",
}
#: The pages' own names: they point at the local server. ``push`` is served by its address (a service worker needs a secure
#: context, and ``.test`` is not one; 127.0.0.1 is).
SITES: Dict[str, str] = {"hints-site.test": "127.0.0.1", "subresources-site.test": "127.0.0.1", "webrtc-site.test": "127.0.0.1",
"geolocation-site.test": "127.0.0.1", "closing-site.test": "127.0.0.1"}
ZONE: Dict[str, str] = {**SITES, **ROUTABLE}
#: What each case's page does. ``%`` is not used: the names are written out, the page of a case is a constant.
CASES: Dict[str, str] = {
"hints": '<link rel=dns-prefetch href="//prefetch-a.test"><link rel=preconnect href="http://preconnect-b.test">'
'<link rel=prefetch href="http://prefetch-c.test/x"><link rel=preload as=image href="http://preload-d.test/i.png">',
"subresources": '<img src="http://img-e.test/i.png"><script>fetch("http://fetch-f.test/x").catch(() => {});'
'try { new WebSocket("ws://ws-g.test/s").onerror = () => {}; } catch (e) {}'
'try { new EventSource("http://es-h.test/s").onerror = function () { this.close(); }; } catch (e) {}</script>',
"webrtc": '<script>(async () => { const pc = new RTCPeerConnection({iceServers: [{urls: "stun:stun-i.test:3478"},'
'{urls: "turn:turn-j.test:3478", username: "u", credential: "p"}]});'
'pc.createDataChannel("d"); await pc.setLocalDescription(await pc.createOffer()); })().catch(() => {});</script>',
"geolocation": '<script>try { navigator.geolocation.getCurrentPosition(() => {}, () => {}, {timeout: 4000}); } catch (e) {}</script>',
# a page still loading when its context is closed: requests made between the close and the death of its processes. These names
# are in no zone: the DoH answers NXDOMAIN, and what is asked is where the question goes.
"closing": '<script>let n = 0; setInterval(() => { for (let k = 0; k < 3; k++) fetch("http://late-" + (n++) + ".test/x")'
'.catch(() => {}); }, 5);</script>',
# `__pushStage` says how far the page got (registering, registered, ready, subscription-read): a page that stays `pending` names the step it
# is stuck in.
"push": '<script>window.__push = "pending"; window.__pushStage = "start"; (async () => { if (!navigator.serviceWorker) { window.__push = "no-service-worker"; return; }'
'window.__pushStage = "registering"; const r = await navigator.serviceWorker.register("/sw.js"); window.__pushStage = "registered";'
'await navigator.serviceWorker.ready; window.__pushStage = "ready";'
# WHY THE PAGE ASKS AGAIN (run 43501478312: Linux, both schemes, stage `ready`, `pending` for 30 s; Windows passes). The launch has `-silent`
# (invisible_core/juggler/connection.py:1245), which means NO window at start-up (browser/components/BrowserContentHandler.sys.mjs:626,
# preventDefault) and Juggler declares the browser started at once (juggler/components/Juggler.js:86-88) instead of waiting for
# `browser-idle-startup-tasks-finished` (Juggler.js:93). The first window is made by the first new page; only then does
# `sessionstore-windows-restored` (browser/components/sessionstore/SessionStore.sys.mjs:1865) schedule BrowserGlue's idle tasks
# (browser/components/BrowserGlue.sys.mjs:828-885), among them `PushService.ensureReady` (BrowserGlue.sys.mjs:984-1000), which is the first
# thing that creates the parent's PushServiceParent. Its message listeners are registered in the constructor (dom/push/PushComponents.sys.mjs:49-52),
# so a `Push:Registration` sent by the content process before that (PushComponents.sys.mjs:425-430) is lost, not queued: `getSubscription()` never
# settles. This is Mozilla/Juggler behaviour, not ours: stock Playwright 1.61 also starts a non-persistent Firefox with `-silent` (driver
# coreBundle.js, defaultArgs: `if (isPersistent) firefoxArguments.push("about:blank"); else firefoxArguments.push("-silent");`). A page
# that asks early is a property of this lab, so the page asks again every 2 s as a page would, bounded: 15 asks, 30 s, then it stays
# `pending` and the test fails with the stage. How long the push service takes to exist is UNMEASURED (the only runs are the red ones, where
# it had not existed 30 s after the page was loaded; no run has a number for a green Linux leg).
'let sub; for (let i = 1; i <= 15 && sub === undefined; i++) { window.__pushTries = i; sub = await Promise.race([r.pushManager.getSubscription(),'
' new Promise(res => setTimeout(() => res(undefined), 2000))]); }'
'if (sub === undefined) return; window.__push = "sub:" + JSON.stringify(sub); window.__pushStage = "subscription-read";'
'await r.pushManager.subscribe({userVisibleOnly: true, applicationServerKey: new Uint8Array(65).fill(4)});'
'})().catch(e => { window.__push = String(window.__push).startsWith("sub:") ? window.__push : "error:" + e.name; });</script>',
}
#: The names the DoH must be asked for, by case, when the work is done (a hint is speculative: the browser may skip it, so none is demanded).
ASKED: Dict[str, List[str]] = {
"hints": [], "subresources": ["img-e.test", "fetch-f.test", "ws-g.test", "es-h.test"], "webrtc": ["stun-i.test", "turn-j.test"],
"geolocation": [], "closing": ["late-0.test"], "push": [],
}
#: How long the page is left to work before the context is closed, in seconds: a case that does little is closed sooner.
SETTLE_SECONDS: Dict[str, float] = {"hints": 6.0, "subresources": 6.0, "webrtc": 6.0, "geolocation": 6.0, "closing": 1.5, "push": 6.0}
SW = b"self.addEventListener('push', () => {});"
def site_name(case: str) -> Optional[str]:
"""The name a case's page is reached by, or None for the one reached by its address."""
name = "%s-site.test" % case
return name if name in SITES else None
def is_documentation_address(address: str) -> bool:
"""True for an address of 198.51.100.0/24 (TEST-NET-2)."""
return address.startswith("198.51.100.")
class CaseSite:
"""A local HTTP server: ``/<case>`` answers the page of that case, ``/sw.js`` a service worker with a push listener."""
def __init__(self):
outer = self
self.hits: List[tuple] = []
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self): # noqa: N802
path = self.path.split("?", 1)[0]
outer.hits.append((self.headers.get("Host", ""), path))
if path == "/sw.js":
body, kind = SW, "application/javascript"
elif path.lstrip("/") in CASES:
body, kind = ("<!doctype html><meta charset=utf-8><title>%s</title>%s" % (path.lstrip("/"), CASES[path.lstrip("/")])
).encode(), "text/html; charset=utf-8"
else:
body, kind = b"", "text/plain"
self.send_response(200)
self.send_header("Content-Type", kind)
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, case: str) -> str:
name = site_name(case)
return "http://%s:%d/%s" % (name or "127.0.0.1", self.port, case)
def close(self) -> None:
self._server.shutdown()
self._server.server_close()
@@ -0,0 +1,116 @@
"""E2E: a TURN server given by NAME, over TCP, in a context with a proxy, is resolved by the DoH through THAT proxy.
EXPECTED RED ON THE PUBLISHED ENGINE firefox-63, GREEN ON firefox-64 (the engine fix is commit ac0214bff4 with 058edd6cc6). The test is not gated and
not skipped: it runs on every engine, so the candidate of firefox-64 (this branch runs there as ``wrapper_ref``) is red when the fix is missing, and
firefox-63 is red because it does not have it.
The defect. A page asks for ``turn:<name>:3478?transport=tcp``. The TCP socket that talks to the TURN server (``WebrtcTCPSocket``) did not
carry the origin attributes of its PeerConnection, so its name lookup was made in the DEFAULT user context. In a session with no proxy at
launch and a proxy on the context (the scheme of ``test_context_proxy_only_resolves_by_doh_e2e.py``) the default context resolves natively:
the lookup went to the system resolver (a question for a name of a proxied page, and the DoH never saw it); with a proxy at launch AND a
different one on the context, the DoH request left by the proxy of the LAUNCH, the wrong exit. The STUN and the TURN-over-UDP names do not
have the defect (``test_ice_names_by_the_context_proxy_e2e.py``), and the TURN over TCP by an IP does not resolve at all
(``test_webrtc_realness.py::test_the_turn_over_tcp_of_a_context_goes_through_the_proxy_of_that_context``): no test of the main line made the
browser resolve a TURN name over TCP, so nothing showed it. Found by the minimal engine's matrix of page work behind a proxy.
What the page does and what is read (two schemes, as in ``test_nothing_leaves_but_the_proxy_e2e.py``):
* ``context_only``: no launch proxy, a context with a SOCKS5 gateway. The name must reach the DoH by that gateway, the resolver of the
machine must be asked nothing for it (the trap, Linux root), and the gateway must be handed the ADDRESS the DoH answered (198.51.100.7,
a documentation address nothing routes: the gateway refuses it and lists it);
* ``launch_and_context``: a launch gateway and a different one for the context. The name must reach the DoH by the gateway of the CONTEXT
and by no other, and nothing at all may go direct or ask the resolver.
Red on the defect: the DoH is never asked for the name (the lookup took the native road, or the default context's DoH request failed its
handshake by design), and on Linux the trap heard the name.
"""
from __future__ import annotations
import pytest
# The fixtures and the helpers of the DoH e2e (imported, not copied). `doh`, `gateway`, `pages`, `trap` and `watcher` are in conftest.py.
from test_doh_through_the_proxy_e2e import ( # noqa: F401 (the hermetic session is autouse and imported by name)
DOH_ADDRESSES, ZONE, _assert_every_connection_went_through_the_gateway, _direct_to_the_doh, _hermetic_session, _is_address, _launch,
_page_in, _why)
import _doh_servers as ds
from _doh_servers import DOH_HOST, QTYPE_A, FakeDoh
pytestmark = [pytest.mark.e2e]
#: A documentation address of its own (not the STUN one, 198.51.100.5, nor the core's measurement one, 198.51.100.6).
TURN_NUMBER = "198.51.100.7"
TURN_NAME = "turn-a.test"
TURN_PORT = 3478
TURN_ZONE = {**ZONE, TURN_NAME: TURN_NUMBER}
#: How long the page waits for the ICE agent to try the server, in milliseconds.
WAIT_MS = 6000
#: How long to wait for the DoH to be asked and for the gateway to be handed the address, in seconds.
ASKED_SECONDS = 25
_PROBE_JS = """async ([url, waitMs]) => {
const errors = [], found = [];
const pc = new RTCPeerConnection({iceServers: [{urls: url, username: 'u', credential: 'p'}]});
pc.createDataChannel('d');
pc.onicecandidateerror = (e) => errors.push(e.errorCode);
pc.onicecandidate = (e) => { if (e.candidate) found.push(e.candidate.candidate); };
await pc.setLocalDescription(await pc.createOffer());
await new Promise((resolve) => setTimeout(resolve, waitMs));
pc.close();
return {errors, candidates: found.length};
}"""
@pytest.fixture
def doh():
"""The FakeDoh with the TURN name pointing at a documentation address (overrides the one of conftest.py)."""
import h2 # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
server = FakeDoh(TURN_ZONE)
yield server
server.close()
@pytest.mark.parametrize("scheme", ["context_only", "launch_and_context"])
def test_a_turn_server_named_over_tcp_is_resolved_by_the_doh_through_the_proxy_of_the_context(
scheme, firefox_binary, doh, pages, gateway, trap, watcher):
"""EXPECTED RED on the published firefox-63 (the defect), green with the engine fix of firefox-64."""
gw_context = gateway("gw-context")
gw_launch = gateway("gw-launch") if scheme == "launch_and_context" else None
gateways = [g for g in (gw_context, gw_launch) if g is not None]
with _launch(firefox_binary, gw_launch.proxy if gw_launch else None) as browser:
context, page = _page_in(browser, proxy=gw_context.proxy)
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
result = page.evaluate(_PROBE_JS, ["turn:%s:%d?transport=tcp" % (TURN_NAME, TURN_PORT), WAIT_MS])
asked = ds.wait_until(lambda: doh.queries_for(TURN_NAME, QTYPE_A), ASKED_SECONDS)
handed = ds.wait_until(lambda: (TURN_NUMBER, TURN_PORT) in gw_context.connects, ASKED_SECONDS)
context.close()
watcher.stop()
why = _why(doh, *gateways) + "\n the page: %s" % (result,)
assert asked, (
"the DoH was never asked for the TURN name %s over TCP: the lookup of the socket took the user context of no proxy (the "
"system resolver, or the default context's DoH request)" % TURN_NAME + why)
assert doh.vias_of(TURN_NAME, QTYPE_A) == {gw_context.name}, (
"%s (A) was not asked by the gateway of the context only: %s" % (TURN_NAME, sorted(doh.vias_of(TURN_NAME, QTYPE_A))) + why)
assert handed, "the gateway of the context was never handed the address %s:%d the DoH answered" % (TURN_NUMBER, TURN_PORT) + why
for gw in gateways:
named = [h for h, _p in gw.connects if not _is_address(h) and h != DOH_HOST]
assert named == [], "%s was sent a NAME in a CONNECT: %s" % (gw.name, named) + why
if gw_launch is not None:
assert (TURN_NUMBER, TURN_PORT) not in gw_launch.connects, "the TURN address was handed to the gateway of the LAUNCH" + why
assert [q for q in doh.queries if q.via == gw_launch.name and q.name == TURN_NAME] == [], (
"the name of the TURN server left by the gateway of the LAUNCH, not by the one of the context" + why)
_assert_every_connection_went_through_the_gateway(doh, *gateways)
assert watcher.watched_pids, "the watcher never saw a browser process (it saw: %s)" % watcher.process_names
assert _direct_to_the_doh(watcher) == [], (
"the browser reached a DoH (%s) or a DNS server (port 53) without the proxy: %s" % (", ".join(DOH_ADDRESSES), watcher.describe()))
assert [c for c in watcher.direct if c.remote.rsplit(":", 1)[0] == TURN_NUMBER] == [], (
"the browser connected straight to the TURN server, around the proxy: %s" % watcher.describe())
if gw_launch is not None:
assert watcher.direct == [], "the browser connected past the gateways, with every context proxied: %s" % watcher.describe()
if trap is not None:
assert not trap.asked(TURN_NAME), "the browser asked the resolver of the machine for the TURN name: %s" % trap.describe()
if gw_launch is not None:
assert trap.queries == [], "the browser asked the resolver of the machine, with every context proxied: %s" % trap.describe()
+2 -1
View File
@@ -86,7 +86,8 @@ def test_the_bootstrap_address_is_a_public_address_and_not_the_proxy(compose):
def test_a_session_without_a_proxy_declares_the_provider_and_no_state(compose):
prefs = compose(None)
assert sorted(k for k in prefs if k.startswith("network.trr.")) == ["network.trr.bootstrapAddr", "network.trr.uri"]
assert sorted(k for k in prefs if k.startswith("network.trr.")) == ["network.trr.bootstrapAddr", "network.trr.builtin-excluded-domains", "network.trr.uri"]
assert prefs["network.trr.builtin-excluded-domains"] == "localhost", "only localhost stays off DoH: a *.local name behind a proxy is not read from the host"
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"
@@ -0,0 +1,156 @@
"""E2E: nothing a PAGE makes the browser do leaves except through the proxy of its context.
Why it is a file of its own. The DoH e2e (``test_doh_through_the_proxy_e2e.py``, ``test_context_proxy_only_resolves_by_doh_e2e.py``) prove the
road of the names a page NAVIGATES to and of one STUN name. A page does much more than that, and each kind of work is its own road inside the
browser, written by its own code (the preconnect and prefetch hints, the image loader, the WebSocket and EventSource channels, the ICE
resolver and its sockets, the geolocation provider, the service worker and the push service, a request still in flight when its context
dies). A real-sites run found the main process asking the machine's resolver for names of pages loaded behind a SOCKS proxy and opening a
few TLS connections straight to sites: nothing in the navigations of the DoH e2e could have shown it.
Each kind of page work is tried in a context of its own, on the scheme that shows a leak (``test_context_proxy_only_resolves_by_doh_e2e.py``):
* ``context_only``: NO proxy at launch, a context with a SOCKS5 gateway of its own. The default context is the machine's own network, so a
lookup that takes the wrong user context takes the system resolver and the page's name never reaches the DoH;
* ``launch_and_context``: a launch gateway AND a different gateway for the context. The default context is proxied too, so nothing at all
may go direct or ask the resolver, and a name of the page must reach the DoH by the gateway of the CONTEXT, never by the one of the launch
(a lookup with the default user context would leave by the wrong exit).
What each case proves (the page work is in ``_page_work.py``; every name points at a documentation address, never at loopback):
* no question to the resolver of the machine for a ``.test`` name (the resolver trap, where it runs: Linux, root; with a launch gateway no
question at all);
* no direct connection: the watcher sees none to a DoH address, to port 53 or to a documentation address (with a launch gateway, none at all);
* every name the page work needs is asked of the DoH, and only by the gateway of the context;
* every CONNECT a gateway got carries an ADDRESS, never a name;
* the work was done (the page opened, and the names the case must have asked were asked): a leak test that measures nothing is not green.
The TURN server given by NAME over TCP is not here: it is the reproducer of an engine defect and has its own file
(``test_a_turn_name_over_tcp_goes_through_the_proxy_of_the_context_e2e.py``).
Hermetic like the DoH e2e it borrows from: its fixtures, FakeDoh, gateway, watcher and trap are imported, not copied.
"""
from __future__ import annotations
import time
import pytest
# The fixtures and the helpers of the DoH e2e (imported, not copied): the hermetic session (autouse), the launch, the page in a context,
# and the accounting of the end of a test. `doh`, `gateway`, `trap` and `watcher` are in conftest.py.
from test_doh_through_the_proxy_e2e import ( # noqa: F401 (the hermetic session is autouse and imported by name)
DOH_ADDRESSES, _assert_every_connection_went_through_the_gateway, _direct_to_the_doh, _hermetic_session, _is_address, _launch,
_page_in, _why)
import _doh_servers as ds
from _doh_servers import DOH_HOST, QTYPE_A, FakeDoh
from _page_work import ASKED, CASES, SETTLE_SECONDS, ZONE, CaseSite, is_documentation_address, site_name
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
SCHEMES = ["context_only", "launch_and_context"]
#: How long to wait for a name the case must have asked to reach the DoH, in seconds.
ASKED_SECONDS = 25
#: How long the page of the `push` case may take to register its service worker and read its subscription, in seconds.
PUSH_SECONDS = 40
#: After the context of the `closing` case is closed, the browser lives on this long: the requests of the page's last moments are made now.
AFTER_CLOSE_SECONDS = 4
@pytest.fixture
def doh():
"""The FakeDoh with the names of the page work (overrides the one of conftest.py)."""
import h2 # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
server = FakeDoh(ZONE)
yield server
server.close()
@pytest.fixture
def site():
server = CaseSite()
yield server
server.close()
def _direct_to_a_documentation_address(watcher):
"""The direct connections the watcher saw to the addresses the page work's names answer (loopback is never seen as direct)."""
return [c for c in watcher.direct if is_documentation_address(c.remote.rsplit(":", 1)[0])]
@pytest.mark.parametrize("scheme", SCHEMES)
@pytest.mark.parametrize("case", list(CASES))
def test_a_kind_of_page_work_leaves_only_through_the_proxy_of_its_context(case, scheme, firefox_binary, doh, site, gateway, trap,
watcher):
gw_context = gateway("gw-context")
gw_launch = gateway("gw-launch") if scheme == "launch_and_context" else None
gateways = [g for g in (gw_context, gw_launch) if g is not None]
asked_names = ASKED[case] + ([site_name(case)] if site_name(case) else [])
opened = None
waited = {}
with _launch(firefox_binary, gw_launch.proxy if gw_launch else None) as browser:
context, page = _page_in(browser, proxy=gw_context.proxy) # a proxy of its own: the only one in `context_only`
try:
page.goto(site.url(case), wait_until="load", timeout=30000)
opened = True
except Exception as exc: # noqa: BLE001 - said below with everything the sides saw
opened = "%s: %s" % (type(exc).__name__, str(exc)[:160])
for name in asked_names:
waited[name] = ds.wait_until(lambda n=name: doh.queries_for(n, QTYPE_A), ASKED_SECONDS)
page.wait_for_timeout(int(SETTLE_SECONDS[case] * 1000))
if case == "push":
# A service worker starts a process: wait for the page to leave `pending` (a fixed settle is a guess), and say the step it reached.
try:
page.wait_for_function("() => window.__push !== 'pending'", timeout=PUSH_SECONDS * 1000)
except Exception: # noqa: BLE001 - the state is read and said below
pass
pushed = page.evaluate("() => window.__push")
push_stage = page.evaluate("() => window.__pushStage + ' after ' + window.__pushTries + ' ask(s)'")
context.close() # for `closing`: the page is still working
if case == "closing":
time.sleep(AFTER_CLOSE_SECONDS)
watcher.stop()
why = _why(doh, *gateways) + "\n the page: opened=%r" % (opened,)
assert opened is True, "the page of the case %r did not open through the gateway of its context: %s" % (case, opened) + why
if case == "push":
assert pushed.startswith("sub:"), (
"the page could not register its service worker and read its subscription: %r (last step reached: %s)" % (pushed, push_stage) + why)
# The work was done: the names it needs reached the DoH, by the gateway of the context and by no other road.
for name in asked_names:
assert waited[name], "the DoH was never asked for %s (the work of the case %r was not done, or its name took another road)" % (
name, case) + why
assert doh.vias_of(name, QTYPE_A) == {gw_context.name}, (
"%s (A) was not asked by the gateway of the context only: %s" % (name, sorted(doh.vias_of(name, QTYPE_A))) + why)
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without a proxy" + why
if gw_launch is not None:
asked_by_launch = [q.name for q in doh.queries if q.via == gw_launch.name and q.name in ZONE]
assert asked_by_launch == [], (
"a name of the page work left by the gateway of the LAUNCH, not by the one of the context: %s" % (asked_by_launch,) + why)
# Every CONNECT is an address: the browser resolves with the DoH and connects to what it answered.
for gw in gateways:
named = [h for h, _p in gw.connects if not _is_address(h) and h != DOH_HOST]
assert named == [], "%s was sent a NAME in a CONNECT: %s (the browser must resolve with the DoH)" % (gw.name, named) + why
_assert_every_connection_went_through_the_gateway(doh, *gateways)
# Nothing direct.
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 _direct_to_the_doh(watcher) == [], (
"the browser reached a DoH (%s) or a DNS server (port 53) without the proxy: %s" % (", ".join(DOH_ADDRESSES), watcher.describe()))
assert _direct_to_a_documentation_address(watcher) == [], (
"the browser connected straight to an address a name of the page work answers: %s" % watcher.describe())
if gw_launch is not None:
assert watcher.direct == [], "the browser connected past the gateways, with every context proxied: %s" % watcher.describe()
# Nothing asked of the resolver of the machine.
if trap is not None:
if gw_launch is not None:
assert trap.queries == [], "the browser asked the resolver of the machine, with every context proxied: %s" % trap.describe()
else:
asked = [name for name in trap.names() if name.endswith(".test")]
assert asked == [], (
"the browser asked the resolver of the machine for a name of the page work (the lookup took the user context of no "
"proxy): %s" % asked + "; " + trap.describe())
@@ -0,0 +1,562 @@
"""E2E: nothing a context's page makes the browser do arrives at a server except through the proxy of that context (the behavioural half of the
class gate; the static half is the ledger of birth points in the series).
The class. A page can make the browser open a socket, send a datagram or ask a name through code that was written for the browser, not for the
page: an ICE agent, an OCSP fetch, a DNS prefetch. Each such road picks its proxy and its resolver from the user context of its request, and a
request made with the default attributes or the system principal leaves OUTSIDE the proxy of the context it came from. Two were found one at a
time (the TCP socket of a TURN server's name, the OCSP request); this file holds the class, one probe per road.
The lab, with nothing but this host:
* the session has NO proxy (the default context is the machine's own network) and ONE context has a proxy of its own: the only proxy there is;
* a WITNESS (``_witness.Witness``) stands at an address of this host (``this_host_address``: no root, no address added to ``lo``, so the lab is
the same on every host). No proxy of the test forwards to it: the SOCKS5 gateways refuse a CONNECT past loopback and relay no datagram, the HTTP
proxy answers 403. So whatever the witness hears came from the browser, direct;
* every name a probe uses is ``<case>-<nonce>.test`` (or ``.local``) and the FakeDoh answers it with the witness's address: a name that is looked
up by the DoH through the proxy leads to a CONNECT to the witness's address AT THE GATEWAY, listed there; a name looked up any other way is
seen by the sink (``_egress_sink.py``): the engine's own log (``getaddrinfo`` calls, and the user context of each lookup) on every system, the
resolver trap too where it runs (Linux, root);
* a probe is one mechanism of a page: ``fetch``, ``WebSocket``, ``stun:`` and ``turn:`` over UDP, ``turn:`` and ``turns:`` over TCP, each by NAME,
by IP, and (``.local``) by a name the engine excludes from the DoH; behind SOCKS5 and behind an HTTP proxy where the road differs.
What each case asserts (``_egress_sink.EgressSink``): the witness heard nothing, the watcher saw no connection to it, no name of the probe was
looked up natively, none was looked up in user context 0, and the work WAS done (the DoH asked the name by the gateway of the context only, and
the gateway or the proxy was handed the target). The controls make the green mean something: the same probe by IP with NO proxy IS heard by the
witness, and a name looked up natively IS seen by the native sink.
Expected, case by case, on the published engine firefox-63 and on firefox-64 (the tree with the TURN-by-name fix): ``EXPECTED``, below. Nothing
here is skipped or marked as an expected failure: a case that is red on firefox-63 is red there, and says which road it is.
The window of a torn-down document (defect B3). A PeerConnection built from ``W.RTCPeerConnection``, where ``W`` is the window of an iframe that
was removed or of a popup that was closed, had NO proxy config on the engine firefox-63: its sockets were plain (direct UDP and TCP from the host)
and its ICE server names were resolved in the default context. ``WINDOW_CASES`` makes that window two ways (a detached iframe, a closed popup) behind
SOCKS5 and behind an HTTP proxy and builds the PeerConnection with a STUN and a TURN-over-TCP server named by name; ``CONTROL_CASES`` builds the
same PeerConnection from an ATTACHED iframe of the same page (proof that the lab sees the PeerConnection of a sub-window at all). A dead window may
refuse to build a PeerConnection, or build one that never gathers: that passes the egress assertions (nothing left) but is never hidden, the test
prints which one happened (``DEAD-WINDOW`` line) and records it as the property ``dead_window_outcome``. ``EXPECTED_WINDOW`` says what each case does
on firefox-63 (red: the direct UDP/TCP is heard by the witness, the names are looked up natively or in user context 0) and on firefox-64 (green).
Two contexts alive at once. Two contexts of ONE browser, each with its OWN proxy and its OWN FakeDoh (a different zone: the name of the other context is
unknown to it), each with a PeerConnection whose TURN server is given by a DIFFERENT name over TCP (the name of A at the port of witness A, the name of
B at the port of witness B, both witnesses at the address of this host: the PORT of a CONNECT says which context's TURN it was). Each name must reach
only the DoH of its own context through its own proxy, no name the machine's resolver, each TURN CONNECT only the proxy of its context, and nothing the
witnesses direct. Behind SOCKS5 it is RED on firefox-63 (the TURN names are resolved by the machine, as ``turn_tcp-name-socks5``) and green on
firefox-64; behind an HTTP proxy the name goes to the proxy in the CONNECT and the case is green on both (as ``turn_tcp-name-http``). ``EXPECTED_TWO``.
The Windows sink is ``_egress_sink.native_lookup_names``; it needs no change here.
"""
from __future__ import annotations
import dataclasses
import os
from typing import Callable, Dict, Optional
import pytest
from invisible_playwright import InvisiblePlaywright
# The fixtures and the helpers of the DoH e2e (imported, not copied): the hermetic session (autouse) and the page in a context. `gateway`, `pages`,
# `trap` and `watcher` are in conftest.py.
from test_doh_through_the_proxy_e2e import ( # noqa: F401 (the hermetic session is autouse and imported by name)
PREFS, ZONE, _hermetic_session, _is_address, _page_in, _why)
import _doh_servers as ds
from _doh_servers import QTYPE_A, FakeDoh
from _egress_sink import (LOG_FILE_NAME, MOZ_LOG, EgressSink, named_connects, native_lookup_names, new_nonce)
from _host_address import this_host_address
from _http_proxy import HttpProxy
from _witness import Witness
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
#: How long the page waits for the browser to try the target, in milliseconds (the ICE agent retransmits STUN and TURN at 0, 0.1, 0.3, 0.7 s...).
WAIT_MS = {"fetch": 2500, "websocket": 2500, "stun": 5000, "turn_udp": 5000, "turn_tcp": 5000, "turns_tcp": 5000}
#: How long to wait, in seconds, for the proxy or the DoH to have been handed what the probe asked for.
EVIDENCE_SECONDS = 20
#: The lab's own prefs, on top of the DoH provider of ``PREFS``. Every name of a probe is answered with the address of THIS host (the witness), and on
#: a LAN or a runner that is an RFC 1918 address: the engine's DoH client DROPS such an answer unless ``network.trr.allow-rfc1918`` is true
#: (TRR.cpp / DNSPacket.cpp: ``aAllowRFC1918 || !addr.IsIPAddrLocal()``), so the name would resolve to nothing and the probe would never connect
#: (the first run on a runner, 10.1.0.150: the DoH was asked, the gateway never got a CONNECT). The lab declares it; no egress assertion depends on it.
LAB_PREFS = {"network.trr.allow-rfc1918": True, "media.peerconnection.ice.obfuscate_host_addresses": True}
@dataclasses.dataclass(frozen=True)
class Case:
kind: str # fetch | websocket | stun | turn_udp | turn_tcp | turns_tcp
by: str # name | ip | local
proxy: str # socks5 | http
@property
def id(self) -> str:
return "%s-%s-%s" % (self.kind, self.by, self.proxy)
@property
def tcp(self) -> bool:
return self.kind not in ("stun", "turn_udp")
@property
def refused_by_the_browser(self) -> bool:
"""``turns:`` by an IP: the browser never tries it (nricectx.cpp, ``ToNicerTurnStruct``: "TLS requires FQDN, not IP address"), on every
proxy and none: no connection is made to prove a road. The case keeps every egress assertion (witness, watcher, native lookup)."""
return self.kind == "turns_tcp" and self.by == "ip"
CASES = [
Case("fetch", "name", "socks5"), Case("fetch", "ip", "socks5"), Case("fetch", "local", "socks5"), Case("fetch", "local", "http"),
Case("websocket", "name", "socks5"), Case("websocket", "ip", "socks5"),
Case("stun", "name", "socks5"), Case("stun", "ip", "socks5"), Case("stun", "local", "socks5"), Case("stun", "local", "http"),
Case("turn_udp", "name", "socks5"), Case("turn_udp", "ip", "socks5"),
Case("turn_tcp", "name", "socks5"), Case("turn_tcp", "name", "http"), Case("turn_tcp", "ip", "socks5"), Case("turn_tcp", "ip", "http"),
Case("turns_tcp", "name", "socks5"), Case("turns_tcp", "name", "http"), Case("turns_tcp", "ip", "socks5"),
]
BY_ID = {c.id: c for c in CASES}
@dataclasses.dataclass(frozen=True)
class WindowCase:
window: str # iframe (detached) | popup (closed) | attached (control: an iframe still in its page)
proxy: str # socks5 | http
@property
def id(self) -> str:
return "%s-%s" % (self.window, self.proxy)
@property
def dead(self) -> bool:
return self.window != "attached"
WINDOW_CASES = [WindowCase(w, p) for w in ("iframe", "popup") for p in ("socks5", "http")]
CONTROL_CASES = [WindowCase("attached", p) for p in ("socks5", "http")]
#: The two ICE servers of a window case, by name: the STUN server over UDP and the TURN server over TCP.
ICE_KINDS = ("stun", "turn")
#: How long the page waits for the gathering to end, in milliseconds (the witness answers nothing: the ICE agent retries until this ends).
GATHER_MS = 6000
#: How long the page waits for a closed popup to say ``closed``, in milliseconds.
CLOSED_MS = 5000
#: What each case is expected to do, by engine. "green" is the contract; "RED" names the road that leaves the proxy. Held by
#: test_the_egress_sink_helpers.py (every id is a case, and a RED has its reason).
EXPECTED: Dict[str, Dict[str, str]] = {
"firefox-63": {
"turn_tcp-name-socks5": "RED: the name of the TURN server is looked up in user context 0 (WebrtcTCPSocket, native or the DoH of the wrong context)",
"turns_tcp-name-socks5": "RED: same road as turn_tcp-name-socks5 (the TLS socket is made by the same code)",
"fetch-local-socks5": "RED: *.local is excluded from the DoH (all.js network.trr.builtin-excluded-domains) and looked up natively (audit B4)",
"stun-local-socks5": "RED: the ICE resolver asks the machine's resolver for *.local (audit B4)",
"stun-local-http": "RED: same, the ICE resolver always resolves the name itself (audit B4)",
},
# B4 is closed on this engine (the core declares ``network.trr.builtin-excluded-domains`` = localhost: a ``*.local`` name goes to the DoH through
# the proxy): the three ``*-local`` probes are green (run 43488527832: the DoH is asked, no native lookup).
"firefox-64": {},
}
#: The same for the window cases (``WindowCase.id``). On firefox-64 (fix of B3) every case is green, so it has no row. The controls are green everywhere.
EXPECTED_WINDOW: Dict[str, Dict[str, str]] = {
"firefox-63": {c.id: "RED: the PeerConnection of a torn-down window has no proxy config: its UDP and TCP sockets are direct (the witness hears "
"them) and its ICE server names are looked up in the default context (B3)" for c in WINDOW_CASES},
"firefox-64": {},
}
#: Two contexts alive at once, each with its own proxy and its own DoH, a TURN server by a different name in each (``test_two_contexts_...``).
EXPECTED_TWO: Dict[str, Dict[str, str]] = {
"firefox-63": {"socks5": "RED: the TURN name is looked up in user context 0 (same road as turn_tcp-name-socks5): the machine's resolver is asked, no DoH "
"of either context hears it, and no CONNECT of the TURN reaches either gateway"},
"firefox-64": {},
}
_FETCH_JS = """async ([host, port, waitMs]) => {
fetch('http://' + host + ':' + port + '/f', {mode: 'no-cors'}).catch(() => {});
await new Promise((resolve) => setTimeout(resolve, waitMs));
}"""
_WEBSOCKET_JS = """async ([host, port, waitMs]) => {
try { const ws = new WebSocket('ws://' + host + ':' + port + '/s'); ws.onerror = () => {}; } catch (e) {}
await new Promise((resolve) => setTimeout(resolve, waitMs));
}"""
def _ice_js(url_expression):
return """async ([host, port, waitMs]) => {
const pc = new RTCPeerConnection({iceServers: [{urls: [%s], username: 'u', credential: 'p'}]});
pc.createDataChannel('d');
await pc.setLocalDescription(await pc.createOffer());
await new Promise((resolve) => setTimeout(resolve, waitMs));
pc.close();
}""" % url_expression
PROBE_JS = {
"fetch": _FETCH_JS,
"websocket": _WEBSOCKET_JS,
"stun": _ice_js("'stun:' + host + ':' + port"),
"turn_udp": _ice_js("'turn:' + host + ':' + port + '?transport=udp'"),
"turn_tcp": _ice_js("'turn:' + host + ':' + port + '?transport=tcp'"),
"turns_tcp": _ice_js("'turns:' + host + ':' + port + '?transport=tcp'"),
}
#: A PeerConnection with a TURN server over TCP by name that STAYS OPEN (two contexts must each hold one at the same time): it returns when the offer is set.
_TURN_KEPT_JS = """async ([host, port]) => {
const pc = new RTCPeerConnection({iceServers: [{urls: ['turn:' + host + ':' + port + '?transport=tcp'], username: 'u', credential: 'p'}]});
window.__pc = pc;
pc.createDataChannel('d');
await pc.setLocalDescription(await pc.createOffer());
}"""
#: Step 1 of the popup variant: a button whose handler opens the popup and closes it at once. It is CLICKED (a real click holds the user gesture; a
#: ``window.open`` from an ``evaluate`` has none and the popup blocker answers null, which would test the blocker).
_POPUP_BUTTON_JS = """() => {
const b = document.createElement('button');
b.id = 'open-dead'; b.textContent = 'open';
b.onclick = () => { window.__popup = window.open('about:blank'); if (window.__popup) window.__popup.close(); };
document.body.append(b);
}"""
#: Steps 1 and 2 of a window case: the window (an iframe that is removed, a popup that was closed, or an iframe that stays), the PeerConnection
#: built from ITS ``RTCPeerConnection`` with a STUN and a TURN-over-TCP server by name, the offer, and the wait for the end of the gathering. It
#: returns what happened, so the test can say it: ``made`` (the window exists), ``closed`` (it is dead), ``constructed`` (the constructor did not
#: throw), ``error``, ``state`` (``iceGatheringState`` at the end), ``started`` (the gathering ran).
_WINDOW_ICE_JS = """async ([how, stunHost, turnHost, port, gatherMs, closedMs]) => {
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const out = {window: how, made: false, closed: null, constructed: false, error: null, state: null, started: false};
let W = null;
if (how === 'popup') {
W = window.__popup || null;
out.made = !!W;
const t0 = Date.now();
while (W && !W.closed && Date.now() - t0 < closedMs) await sleep(50);
out.closed = !!W && W.closed === true;
} else {
const f = document.createElement('iframe');
document.body.append(f);
W = f.contentWindow;
out.made = !!W;
if (how === 'iframe') { f.remove(); out.closed = f.contentWindow === null; }
}
if (!out.made || (how !== 'attached' && !out.closed)) return out;
let pc = null;
try {
pc = new W.RTCPeerConnection({iceServers: [
{urls: 'stun:' + stunHost + ':' + port},
{urls: 'turn:' + turnHost + ':' + port + '?transport=tcp', username: 'u', credential: 'p'}]});
out.constructed = true;
pc.createDataChannel('x');
await pc.setLocalDescription(await pc.createOffer());
} catch (e) { out.error = String(e && e.name ? e.name + ': ' + e.message : e); }
if (pc) {
try {
const t0 = Date.now();
while (pc.iceGatheringState !== 'complete' && Date.now() - t0 < gatherMs) await sleep(100);
out.state = pc.iceGatheringState;
out.started = out.state !== 'new';
pc.close();
} catch (e) { out.error = (out.error ? out.error + '; ' : '') + String(e && e.name ? e.name + ': ' + e.message : e); }
}
return out;
}"""
class Lab:
"""The witness, the nonce, and the names of the cases (every one answered with the witness's address)."""
def __init__(self, witness: Witness, nonce: str):
self.witness, self.nonce = witness, nonce
def host_of(self, case: Case) -> str:
if case.by == "ip":
return self.witness.address
return "%s-%s-%s.%s" % (case.kind, case.by, self.nonce, "local" if case.by == "local" else "test")
def ice_host(self, case: WindowCase, kind: str) -> str:
"""The name of the STUN (``kind="stun"``) or TURN server of a window case."""
return "%s-%s-%s.test" % (kind, case.window, self.nonce)
@property
def zone(self) -> Dict[str, str]:
names = {self.host_of(c): self.witness.address for c in CASES if c.by != "ip"}
names.update({self.ice_host(c, k): self.witness.address for c in WINDOW_CASES + CONTROL_CASES for k in ICE_KINDS})
return names
# ------------------------------------------------------------------------------------------------------- fixtures
@pytest.fixture
def lab():
address = this_host_address() # before any server starts: it skips, never leaves one listening
witness = Witness(address)
try:
yield Lab(witness, new_nonce())
finally:
witness.close()
@pytest.fixture
def doh(lab):
"""The FakeDoh with the names of the cases (overrides the one of conftest.py)."""
import h2 # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
server = FakeDoh({**ZONE, **lab.zone})
yield server
server.close()
@pytest.fixture
def engine_log(tmp_path, monkeypatch):
"""The engine logs its resolver, one file per process, in a folder of the test (the environment reaches the browser through the launch)."""
directory = tmp_path / "moz"
directory.mkdir()
monkeypatch.setenv("MOZ_LOG", MOZ_LOG)
monkeypatch.setenv("MOZ_LOG_FILE", str(directory / LOG_FILE_NAME))
return directory
def _launch(binary, proxy=None):
"""The session of the lab: NO proxy unless given (the default context is the machine's own network), the DoH provider of the FakeDoh."""
return InvisiblePlaywright(seed=42, binary_path=binary, proxy=proxy, headless=True,
extra_prefs={**PREFS, **LAB_PREFS})
def _the_proxy_of(case: Case, doh, gateway):
if case.proxy == "http":
return HttpProxy("http1", doh)
return gateway("gw-context")
def _was_handed(case: Case, proxy, host: str, port: int) -> bool:
"""The road was the proxy's: a SOCKS5 gateway lists every CONNECT it got (even the ones it refuses), the HTTP proxy every request."""
if case.proxy == "http":
return any(s.host == host and s.port == port for s in proxy.seen)
# SOCKS5: the browser resolved the name and connects by ADDRESS.
return (host, port) in proxy.connects
def _the_work_was_done(case: Case, lab: Lab, doh, proxy) -> Optional[Callable[[], bool]]:
"""What shows that the probe reached the road it was meant to try, or None when only the control can show it (a UDP probe by IP), or when
the browser refuses the probe itself (``Case.refused_by_the_browser``)."""
host, port = lab.host_of(case), lab.witness.port
if case.refused_by_the_browser:
return None
if case.proxy == "http":
if case.tcp:
return lambda: _was_handed(case, proxy, host, port)
return None
if case.by == "ip":
return (lambda: _was_handed(case, proxy, host, port)) if case.tcp else None
if case.tcp:
return lambda: (lab.witness.address, port) in proxy.connects
return lambda: bool(doh.queries_for(host, QTYPE_A))
# ----------------------------------------------------------------------------------------------------------- tests
@pytest.mark.parametrize("case", CASES, ids=[c.id for c in CASES])
def test_a_probe_of_a_context_leaves_only_through_its_proxy(case, firefox_binary, lab, doh, pages, gateway, trap, watcher, engine_log):
proxy = _the_proxy_of(case, doh, gateway)
host, port = lab.host_of(case), lab.witness.port
with _launch(firefox_binary) as browser:
context, page = _page_in(browser, proxy=proxy.proxy)
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
page.evaluate(PROBE_JS[case.kind], [host, port, WAIT_MS[case.kind]])
done = _the_work_was_done(case, lab, doh, proxy)
reached = ds.wait_until(done, EVIDENCE_SECONDS) if done else None
context.close()
watcher.stop()
sink = EgressSink(lab.witness, watcher, engine_log, lab.nonce, trap)
why = _why(doh, proxy) + "\n case %s: target %s:%d, witness at %s" % (case.id, host, port, lab.witness.address)
assert sink.blind_problems() == [], "the sink cannot be trusted: %s" % sink.blind_problems() + why
assert sink.leak_problems() == [], "; ".join(sink.leak_problems()) + why
# The work was done, by the road it was meant to take.
if reached is not None:
assert reached, "the proxy was never handed %s:%d (the probe did not run, or it took another road)" % (host, port) + why
if case.proxy == "socks5":
named = named_connects(proxy.connects, _is_address, allowed_names=[ds.DOH_HOST])
assert named == [], "the gateway was sent a NAME in a CONNECT: %s (the browser must resolve with the DoH and connect by address)" % named + why
if case.by != "ip":
assert doh.vias_of(host, QTYPE_A) == {proxy.name}, (
"%s was not asked of the DoH by the gateway of the context only: %s" % (host, sorted(doh.vias_of(host, QTYPE_A))) + why)
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without the proxy" + why
@pytest.mark.parametrize("kind", ["fetch", "stun", "turn_tcp"])
def test_the_same_probe_with_no_proxy_is_heard_by_the_witness(kind, firefox_binary, lab, watcher, engine_log):
"""The control of the witness: with no proxy at all the probe by IP reaches it. Without this a silent witness proves nothing."""
case = Case(kind, "ip", "socks5")
with _launch(firefox_binary) as browser:
page = browser.new_context(ignore_https_errors=True).new_page()
page.goto("about:blank")
page.evaluate(PROBE_JS[kind], [lab.witness.address, lab.witness.port, WAIT_MS[kind]])
reached = ds.wait_until(lambda: lab.witness.heard()["tcp" if case.tcp else "udp"], EVIDENCE_SECONDS)
watcher.stop()
assert reached, "no proxy, and the %s probe by IP did not reach the witness at %s: %s" % (kind, lab.witness.target, lab.witness.heard())
def test_the_native_sink_hears_a_native_lookup(firefox_binary, lab, trap, watcher, engine_log):
"""The control of the native sink: a context with NO proxy looks a name up with the machine's resolver (nothing answers, the page fails), and
``native_lookup_names`` says so. Without this an empty answer proves nothing, on Linux (the log, and the trap as root) and on Windows."""
name = "native-control-%s.test" % lab.nonce
with _launch(firefox_binary) as browser:
page = browser.new_context().new_page()
try:
page.goto("http://%s:%d/" % (name, lab.witness.port), timeout=15000)
except Exception: # noqa: BLE001 - the name has no address: the lookup is what the test is about
pass
heard = ds.wait_until(lambda: native_lookup_names(engine_log, lab.nonce, trap), EVIDENCE_SECONDS)
watcher.stop()
assert heard and name in native_lookup_names(engine_log, lab.nonce, trap), (
"a context with no proxy looked %s up natively and the sink did not hear it: %s; log files: %s"
% (name, native_lookup_names(engine_log, lab.nonce, trap), sorted(os.listdir(str(engine_log)))))
# ------------------------------------------------------------------------------------- the window of a torn-down document (B3)
def _run_window_case(case: WindowCase, firefox_binary, lab: Lab, doh, pages, gateway, watcher):
"""The page of a proxied context makes the window, builds the PeerConnection from it and waits. Returns (proxy, outcome, reached), where
``reached`` is None when no road shows that the probe ran (a window that did not gather)."""
proxy = HttpProxy("http1", doh) if case.proxy == "http" else gateway("gw-context")
stun_host, turn_host, port = lab.ice_host(case, "stun"), lab.ice_host(case, "turn"), lab.witness.port
reached = None
with _launch(firefox_binary) as browser:
context, page = _page_in(browser, proxy=proxy.proxy)
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
if case.window == "popup":
page.evaluate(_POPUP_BUTTON_JS)
page.click("#open-dead", timeout=10000)
outcome = page.evaluate(_WINDOW_ICE_JS, [case.window, stun_host, turn_host, port, GATHER_MS, CLOSED_MS])
if outcome["started"]:
def done() -> bool:
# the TURN server over TCP was handed to the proxy, and the STUN name was asked of the DoH (SOCKS5: by the gateway of the context)
if case.proxy == "http":
return _was_handed(case, proxy, turn_host, port)
return (lab.witness.address, port) in proxy.connects and bool(doh.queries_for(stun_host, QTYPE_A))
reached = ds.wait_until(done, EVIDENCE_SECONDS)
context.close()
watcher.stop()
return proxy, outcome, reached
def _what_the_window_did(outcome: dict) -> str:
"""The sentence that says which of the three things happened in the window (never hidden: printed, recorded, and part of every message)."""
if outcome["started"]:
return "gathered (iceGatheringState=%s)" % outcome["state"]
if not outcome["constructed"]:
return "constructor-threw (%s)" % outcome["error"]
return "no-gathering (constructed, iceGatheringState=%s, error=%s)" % (outcome["state"], outcome["error"])
def _check_window_case(case: WindowCase, outcome: dict, proxy, reached, lab: Lab, doh, trap, watcher, engine_log, record_property):
stun_host, turn_host, port = lab.ice_host(case, "stun"), lab.ice_host(case, "turn"), lab.witness.port
said = _what_the_window_did(outcome)
print("DEAD-WINDOW %s: %s" % (case.id, said))
record_property("dead_window_outcome", said)
why = (_why(doh, proxy) + "\n case %s: STUN %s, TURN %s, port %d, witness at %s\n the window: %s"
% (case.id, stun_host, turn_host, port, lab.witness.address, said))
assert outcome["made"], "the lab could not make the window (a popup blocked, or an iframe with no window): %s" % outcome + why
if case.dead:
assert outcome["closed"], "the window is not dead (the popup never said closed, or the iframe still has a window): %s" % outcome + why
sink = EgressSink(lab.witness, watcher, engine_log, lab.nonce, trap)
assert sink.blind_problems() == [], "the sink cannot be trusted: %s" % sink.blind_problems() + why
assert sink.leak_problems() == [], "; ".join(sink.leak_problems()) + why
if not case.dead:
# The control: the PeerConnection of a sub-window that is still attached gathers, by the road of the context (the sibling cases' green).
assert outcome["started"], "the control PeerConnection of an attached iframe never gathered: the lab does not see a sub-window: %s" % outcome + why
if outcome["started"]:
assert reached, "the proxy was never handed %s:%d, or the DoH never asked %s (the work did not take the road of the context)" % (turn_host, port, stun_host) + why
if case.proxy == "socks5":
named = named_connects(proxy.connects, _is_address, allowed_names=[ds.DOH_HOST])
assert named == [], "the gateway was sent a NAME in a CONNECT: %s (the browser must resolve with the DoH and connect by address)" % named + why
for host in (stun_host, turn_host):
assert doh.vias_of(host, QTYPE_A) == {proxy.name}, (
"%s was not asked of the DoH by the gateway of the context only: %s" % (host, sorted(doh.vias_of(host, QTYPE_A))) + why)
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without the proxy" + why
@pytest.mark.parametrize("case", WINDOW_CASES, ids=[c.id for c in WINDOW_CASES])
def test_a_peerconnection_of_a_torn_down_window_leaves_only_through_the_proxy(
case, firefox_binary, lab, doh, pages, gateway, trap, watcher, engine_log, record_property):
"""B3. RED on firefox-63 (the PeerConnection of a torn-down window has no proxy config: direct sockets, names looked up in the default
context), GREEN on firefox-64. A window that refuses the PeerConnection, or one that never gathers, passes the egress assertions and says so."""
proxy, outcome, reached = _run_window_case(case, firefox_binary, lab, doh, pages, gateway, watcher)
_check_window_case(case, outcome, proxy, reached, lab, doh, trap, watcher, engine_log, record_property)
@pytest.mark.parametrize("case", CONTROL_CASES, ids=[c.id for c in CONTROL_CASES])
def test_the_same_peerconnection_of_an_attached_iframe_leaves_only_through_the_proxy(
case, firefox_binary, lab, doh, pages, gateway, trap, watcher, engine_log, record_property):
"""The control of the test above: the same PeerConnection built from an iframe that is still in its page gathers and goes through the proxy of
the context (green on firefox-63 and on firefox-64): the lab sees the PeerConnection of a sub-window."""
proxy, outcome, reached = _run_window_case(case, firefox_binary, lab, doh, pages, gateway, watcher)
_check_window_case(case, outcome, proxy, reached, lab, doh, trap, watcher, engine_log, record_property)
# ------------------------------------------------------------------------------------- two contexts alive at once, a TURN name each
@pytest.mark.parametrize("scheme", ["socks5", "http"])
def test_two_contexts_each_resolve_their_turn_name_through_their_own_proxy(
scheme, firefox_binary, lab, doh, pages, gateway, trap, watcher, engine_log):
"""Context A (proxy A, DoH A, TURN ``turn-ctx-a-<nonce>.test`` at witness A's port) and context B (proxy B, DoH B, TURN ``turn-ctx-b-...`` at
witness B's port), alive together in one browser, each with a PeerConnection kept open. Each name is asked only of the DoH of its own context
through its own proxy (SOCKS5), each TURN CONNECT goes through the proxy of its context and never through the other, no name reaches the
machine's resolver, nothing reaches either witness direct. RED on firefox-63 behind SOCKS5, green on firefox-64 (see ``EXPECTED_TWO``)."""
import h2 # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
address = lab.witness.address
witness_b = Witness(address) # the same address, another port: the port of a CONNECT says which context it came from
try:
name_a, name_b = ("turn-ctx-%s-%s.test" % (tag, lab.nonce) for tag in ("a", "b"))
port_a, port_b = lab.witness.port, witness_b.port
doh.names[name_a] = address # DoH A knows its own name only ...
doh_b = FakeDoh({**ZONE, name_b: address}) # ... and DoH B its own (and its own certificate)
try:
if scheme == "http":
proxy_a, proxy_b = HttpProxy("http-a", doh), HttpProxy("http-b", doh_b)
else:
from _doh_servers import DohGateway
proxy_a, proxy_b = gateway("gw-a"), DohGateway("gw-b", doh_b)
try:
def handed(proxy, name, port):
if scheme == "http":
return any(x.host == name and x.port == port for x in proxy.seen)
return (address, port) in proxy.connects
with _launch(firefox_binary) as browser:
context_a, page_a = _page_in(browser, proxy=proxy_a.proxy)
context_b, page_b = _page_in(browser, proxy=proxy_b.proxy)
page_a.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
page_b.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
page_a.evaluate(_TURN_KEPT_JS, [name_a, port_a])
page_b.evaluate(_TURN_KEPT_JS, [name_b, port_b]) # both contexts, and both PeerConnections, alive now
reached_a = ds.wait_until(lambda: handed(proxy_a, name_a, port_a), EVIDENCE_SECONDS)
reached_b = ds.wait_until(lambda: handed(proxy_b, name_b, port_b), EVIDENCE_SECONDS)
context_a.close()
context_b.close()
watcher.stop()
sink = EgressSink(lab.witness, watcher, engine_log, lab.nonce, trap) # the witness of A; the watcher and the log see both names
why = (_why(doh, proxy_a) + "\n --- context B ---" + _why(doh_b, proxy_b)
+ "\n scheme %s: A is %s:%d, B is %s:%d, witnesses at %s" % (scheme, name_a, port_a, name_b, port_b, address))
assert sink.blind_problems() == [], "the sink cannot be trusted: %s" % sink.blind_problems() + why
assert sink.leak_problems() == [], "; ".join(sink.leak_problems()) + why
assert witness_b.heard() == {"tcp": [], "udp": []}, "the witness of context B was reached direct: %s" % witness_b.heard() + why
# each TURN went through the proxy of its context, and only that one
assert reached_a, "the proxy of context A was never handed the TURN %s:%d" % (name_a, port_a) + why
assert reached_b, "the proxy of context B was never handed the TURN %s:%d" % (name_b, port_b) + why
assert not handed(proxy_b, name_a, port_a), "the TURN of context A went through the proxy of context B" + why
assert not handed(proxy_a, name_b, port_b), "the TURN of context B went through the proxy of context A" + why
if scheme == "socks5":
for proxy in (proxy_a, proxy_b):
named = named_connects(proxy.connects, _is_address, allowed_names=[ds.DOH_HOST])
assert named == [], "%s was sent a NAME in a CONNECT: %s (resolve with the DoH, connect by address)" % (proxy.name, named) + why
# each name was asked of the DoH of its own context, by the gateway of that context, and of no other
assert doh.vias_of(name_a, QTYPE_A) == {proxy_a.name}, "%s: %s" % (name_a, sorted(doh.vias_of(name_a, QTYPE_A))) + why
assert doh_b.vias_of(name_b, QTYPE_A) == {proxy_b.name}, "%s: %s" % (name_b, sorted(doh_b.vias_of(name_b, QTYPE_A))) + why
assert not doh.queries_for(name_b), "the name of context B was asked of the DoH of context A" + why
assert not doh_b.queries_for(name_a), "the name of context A was asked of the DoH of context B" + why
for server in (doh, doh_b):
assert "direct" not in {q.via for q in server.queries}, "something reached a DoH without the proxy" + why
finally:
proxy_b.close() # the proxy of A is closed by the `gateway` fixture (SOCKS5) or here (HTTP)
if scheme == "http":
proxy_a.close()
finally:
doh_b.close()
finally:
witness_b.close()
+194
View File
@@ -0,0 +1,194 @@
"""The sink of the "nothing of a context leaves but through its proxy" e2e, held to what it says with no browser.
``_egress_sink.py`` reads the engine's own log and the witness, and answers four questions: did the browser connect or send direct, did it ask the
machine's resolver, did it ask in user context 0, and can the answer be trusted. Here each one is shown on a known input that makes it say yes, and
on a known-bad input that must NOT pass: a sink that answers "nothing" because it cannot see is the failure this file exists for.
Known-bad inputs: a log with no resolver start (blind), a Windows host whose second sink is not written (raises, never answers empty), a witness that
heard a datagram (a leak), a probe name asked with no user context.
"""
from __future__ import annotations
import pytest
import _egress_sink as sink_mod
import test_nothing_of_a_context_leaves_but_through_its_proxy_e2e as e2e
pytestmark = pytest.mark.unit
NONCE = "3fa91c"
LOG = """\
[Parent 100: Socket Thread]: D/nsHostResolver nsHostResolver::Init
[Parent 100: Socket Thread]: D/nsHostResolver Resolving host [turn-name-3fa91c.test]<^userContextId=6> type 0. [this=0x1]
[Parent 100: Socket Thread]: D/nsHostResolver Resolving host [turn-name-3fa91c.test]<> type 0. [this=0x1]
[Parent 100: Socket Thread]: D/nsHostResolver Resolving host [elsewhere.test]<> type 0. [this=0x1]
[Parent 100: DNS Resolver #1]: D/nsHostResolver DNS resolve task - Calling getaddrinfo for host [fetch-local-3fa91c.local].
[Parent 100: DNS Resolver #2]: D/nsHostResolver DNS resolve task - Calling getaddrinfo for host [detectportal.firefox.com].
"""
def _log(tmp_path, text=LOG, name="moz-100.log"):
(tmp_path / name).write_text(text, encoding="utf-8")
return tmp_path
def _on_linux(directory, nonce, trap):
"""The native sink as a Linux host answers it, whatever host the unit test runs on (a Windows one raises, by design: see below)."""
return sink_mod.native_lookup_names(directory, nonce, trap, platform="linux")
class _Watcher:
def __init__(self, pids=(1,), direct=()):
self.watched_pids, self.process_names, self.direct = set(pids), ["firefox"], list(direct)
class _Witness:
address = "192.0.2.77"
port = 40000
def __init__(self, tcp=(), udp=()):
self._heard = {"tcp": list(tcp), "udp": list(udp)}
def heard(self):
return self._heard
class _Trap:
def __init__(self, names):
self._names = names
def names(self):
return list(self._names)
def test_the_log_gives_the_native_lookups_of_the_probe_and_no_other(tmp_path):
directory = _log(tmp_path)
assert sink_mod.engine_log_native_lookups(directory, NONCE) == ["fetch-local-3fa91c.local"]
assert sorted(sink_mod.engine_log_native_lookups(directory)) == ["detectportal.firefox.com", "fetch-local-3fa91c.local"]
def test_the_log_gives_the_lookups_made_in_user_context_zero(tmp_path):
directory = _log(tmp_path)
assert sink_mod.engine_log_context_zero_lookups(directory, NONCE) == ["turn-name-3fa91c.test"]
# A first-party domain is not a user context: the suffix says no userContextId, so it is context 0.
other = _log(tmp_path, "Resolving host [x-3fa91c.test]<^firstPartyDomain=a.b> type 0.\n", "moz-101.log.child-1")
assert "x-3fa91c.test" in sink_mod.engine_log_context_zero_lookups(other, NONCE)
def test_a_log_with_no_resolver_start_is_not_alive(tmp_path):
empty = tmp_path / "none"
empty.mkdir()
assert sink_mod.engine_log_is_alive(empty) is False
assert sink_mod.engine_log_is_alive(_log(tmp_path)) is True
def test_native_lookup_names_adds_the_trap_on_linux_and_ignores_it_elsewhere(tmp_path):
directory = _log(tmp_path)
trap = _Trap(["fetch-local-3fa91c.local", "turn-name-3fa91c.test", "other.test"])
assert sink_mod.native_lookup_names(directory, NONCE, trap, platform="linux") == ["fetch-local-3fa91c.local", "turn-name-3fa91c.test"]
assert sink_mod.native_lookup_names(directory, NONCE, trap, platform="darwin") == ["fetch-local-3fa91c.local"]
def test_native_lookup_names_on_windows_asks_the_second_sink_and_its_absence_is_loud(tmp_path):
directory = _log(tmp_path)
got = sink_mod.native_lookup_names(directory, NONCE, None, platform="win32", windows_sink=lambda nonce: ["from-the-event-log-3fa91c.test"])
assert got == ["fetch-local-3fa91c.local", "from-the-event-log-3fa91c.test"]
with pytest.raises(NotImplementedError): # the known-bad input: a Windows host whose second sink is not written never answers "nothing"
sink_mod.native_lookup_names(directory, NONCE, None, platform="win32")
def test_a_clean_probe_has_no_leak_and_a_trusted_sink(tmp_path):
directory = _log(tmp_path, "nsHostResolver::Init\nResolving host [page-a.test]<^userContextId=6> type 0.\n")
sink = sink_mod.EgressSink(_Witness(), _Watcher(), directory, NONCE, native=_on_linux)
assert sink.blind_problems() == []
assert sink.leak_problems() == []
def test_every_way_to_leave_is_a_leak_sentence(tmp_path):
directory = _log(tmp_path)
connection = type("C", (), {"process": "firefox", "protocol": "tcp", "remote": "192.0.2.77:40000", "status": "SYN_SENT"})()
sink = sink_mod.EgressSink(_Witness(tcp=[("192.0.2.77", 5)], udp=[("192.0.2.77", 6, 20)]), _Watcher(direct=[connection]), directory, NONCE, native=_on_linux)
said = " | ".join(sink.leak_problems())
assert "reached direct" in said and "1 TCP" in said and "1 datagram" in said
assert "watcher saw the browser connect" in said
assert "fetch-local-3fa91c.local" in said and "user context 0" in said and "turn-name-3fa91c.test" in said
def test_a_connection_to_another_address_is_not_a_leak_of_the_probe(tmp_path):
directory = _log(tmp_path, "nsHostResolver::Init\n")
elsewhere = type("C", (), {"process": "firefox", "protocol": "tcp", "remote": "203.0.113.9:443", "status": "ESTABLISHED"})()
sink = sink_mod.EgressSink(_Witness(), _Watcher(direct=[elsewhere]), directory, NONCE, native=_on_linux)
assert sink.leak_problems() == []
def test_a_sink_that_sees_nothing_says_it_is_blind(tmp_path):
empty = tmp_path / "none"
empty.mkdir()
blind = sink_mod.EgressSink(_Witness(), _Watcher(pids=()), empty, NONCE).blind_problems()
assert any("watcher never saw a browser" in p for p in blind) and any("wrote no log" in p for p in blind)
no_start = sink_mod.EgressSink(_Witness(), _Watcher(), _log(tmp_path, "Resolving host [a.test]<> type 0.\n"), NONCE).blind_problems()
assert any("start of its resolver" in p for p in no_start)
def test_the_cases_are_unique_and_every_expectation_names_a_case_and_a_road():
ids = [c.id for c in e2e.CASES]
assert len(ids) == len(set(ids))
assert {c.kind for c in e2e.CASES} <= set(e2e.PROBE_JS) and {c.kind for c in e2e.CASES} <= set(e2e.WAIT_MS)
for engine, rows in e2e.EXPECTED.items():
for case_id, what in rows.items():
assert case_id in e2e.BY_ID, (engine, case_id)
assert what.startswith("RED") and len(what) > 20, (engine, case_id, what)
def test_the_names_of_the_cases_are_all_in_the_zone_with_the_address_of_the_witness():
lab = e2e.Lab(_Witness(), NONCE)
zone = lab.zone
assert all(address == _Witness.address for address in zone.values())
for case in e2e.CASES:
host = lab.host_of(case)
assert (host in zone) == (case.by != "ip"), case.id
if case.by == "ip":
assert host == _Witness.address
else:
assert host.endswith(".local" if case.by == "local" else ".test") and NONCE in host
def test_the_lab_lets_the_doh_answer_with_the_private_address_of_this_host():
"""The names of a probe are answered with the address of THIS host, an RFC 1918 one on a LAN or a runner (10.1.0.150): the engine's DoH client
drops such an answer unless ``network.trr.allow-rfc1918`` is true. Without it every probe by name resolves to nothing and never connects."""
assert e2e.LAB_PREFS.get("network.trr.allow-rfc1918") is True
def test_only_a_probe_the_browser_refuses_has_no_road_to_show():
"""``turns:`` by IP is refused by the browser itself ("TLS requires FQDN"): it can show no CONNECT. Every other TCP probe by a SOCKS5 gateway or an
HTTP proxy names the road it must have taken."""
lab = e2e.Lab(_Witness(), NONCE)
refused = [c.id for c in e2e.CASES if c.refused_by_the_browser]
assert refused == ["turns_tcp-ip-socks5"]
for case in e2e.CASES:
done = e2e._the_work_was_done(case, lab, doh=None, proxy=None)
if case.tcp and not case.refused_by_the_browser:
assert done is not None, case.id
def test_the_push_page_says_the_step_it_reached():
import _page_work as pw
page = pw.CASES["push"]
for stage in ("registering", "registered", "ready", "subscription-read"):
assert '__pushStage = "%s"' % stage in page, stage
# the request of a content process before the parent's PushServiceParent exists is dropped: the page asks again
assert "__pushTries" in page and "Promise.race" in page
def test_a_process_that_reads_no_filter_while_it_starts_is_read_again_and_one_that_stays_unfiltered_is_not_dropped(monkeypatch):
import test_the_socket_process_is_sandboxed_e2e as sandbox
reads = {4090: iter(["0", "0", "2"])}
monkeypatch.setattr(sandbox, "_seccomp", lambda pid: "2" if pid != 4090 else next(reads[4090]))
assert sandbox._settled_seccomp([3905, 4090], seconds=5) == {3905: "2", 4090: "2"}
monkeypatch.setattr(sandbox, "_seccomp", lambda pid: "0" if pid == 4090 else "2")
assert sandbox._settled_seccomp([3905, 4090], seconds=0.6) == {3905: "2", 4090: "0"}
def test_the_filter_wait_of_the_sandbox_test_is_bounded():
import test_the_socket_process_is_sandboxed_e2e as sandbox
assert 0 < sandbox.STARTUP_SECONDS <= 15
@@ -65,6 +65,23 @@ def _children_of(binary: str):
return found
#: How long a process that reads ``Seccomp: 0`` is read again, in seconds, before it is judged unsandboxed. A child turns its filter on only after its own
#: start-up, and Firefox pre-launches content processes, so a process sampled while it starts legitimately reads 0 (run 43523960399: the newest tab
#: process, pid 4090 of [3905, 4002, 4005, 4090], read 0 and the same suite was green on the candidates before). A process that is still 0 after this
#: long has finished starting and runs without a filter: that is the failure the test is for.
STARTUP_SECONDS = 10
def _settled_seccomp(pids, seconds: float = STARTUP_SECONDS) -> dict:
"""``{pid: Seccomp}`` of every pid, where a pid that does not read ``2`` is read again until it does or ``seconds`` have passed. No pid is dropped."""
say = {pid: _seccomp(pid) for pid in pids}
deadline = time.monotonic() + seconds
while time.monotonic() < deadline and any(s != "2" for s in say.values()):
time.sleep(0.25)
say = {pid: (s if s == "2" else _seccomp(pid)) for pid, s in say.items()}
return say
def _kernel_says() -> str:
out = []
for name in ("kernel.apparmor_restrict_unprivileged_userns", "kernel.unprivileged_userns_clone", "user.max_user_namespaces"):
@@ -95,7 +112,7 @@ def test_the_socket_process_and_a_tab_process_have_a_seccomp_filter(firefox_bina
if sockets and tabs:
break
time.sleep(0.5)
say = {pid: _seccomp(pid) for pid in sockets + tabs}
say = _settled_seccomp(sockets + tabs)
known = "socket %s, tab %s; %s" % (sockets, tabs, _kernel_says())
assert sockets, "the browser has no socket process after a PeerConnection (%s)" % known
assert tabs, "the browser has no tab process (%s)" % known