#!/usr/bin/env python3 """Local test server for tests/smoke/net-*.txt (S007). Offline: listens on 127.0.0.1 only. Port 8766 speaks plain HTTP and HTTPS on the same socket (it looks at the first byte), with a throwaway self-signed certificate for *.nacre.test. Port 8767 speaks plain HTTP only (an HTTPS upgrade to it fails). /dns-query DNS over HTTPS stub (RFC 8484 GET): *.nacre.test, *.other.test, accounts.google.com -> 127.0.0.1, other name NXDOMAIN, so secure DNS pointed here never reaches a public resolver /auth HTTP Basic sign-in (smoke / letmein), title "Auth ok" or "Auth needed" (S048) / "Net test" page with links to the downloads below; /echo shows the query string in the title /ads.html page with a listed script and image and elements the cosmetic rules hide /ads/* the "ads" (count as hits when they get through) /list.txt filter list for the ad blocker (a custom list URL) /big.bin 4 MiB sent slowly (about 7 s), with Range support for pause/resume /file.zip small file (a download by its URL) /attachment small file with Content-Disposition: attachment (a download by its headers); /report the same file at a path that gives no hint /add, /jsonrpc, /flashgot stubs for AB Download Manager, aria2 and JDownloader 2 /setcookie?name=N[&domain=D][&ss=lax|none] sets cookie N=1 (Path=/, SameSite=None; Secure, so https only, or the ss= variant; Domain=D if given); /cookies shows the Cookie header in the title; /pixel is a 1x1 GIF; /tp?tag=T is a page with a cross-site iframe and picture (https://cdn.other.test:8766) and a same-site picture (https://img.nacre.test:8766), titled "TP T done" when loaded /login?user=U signs in: a persistent cookie session=nacre-test-session-U (Max-Age a day, HttpOnly); /whoami is titled "Signed in as U" or "Signed out" (S025 restart smoke; the value stays out of history) /jstp?tag=T page with a cross-site frame (/jscookie) that writes and reads document.cookie and reports what it read as /note?tag=T&seen=... (S024) /reset empties the "reqs" list of /log /log JSON: every request path, DNS name asked, Range header and download manager call; "reqs" has each GET's host, path, Cookie, DNT, Sec-GPC, Save-Data, Accept-Language and User-Agent headers Runs until killed. Usage: python3 tests/smoke/net/server.py & """ import json import os import re import socket import ssl import subprocess import tempfile import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import parse_qs, urlsplit BIG = 4 * 1024 * 1024 log = {"paths": [], "dns": [], "ranges": [], "dlm": [], "tls": 0, "reqs": []} lock = threading.Lock() def record(key, value): with lock: log[key].append(value) def make_cert(): folder = tempfile.mkdtemp(prefix="nacre-net-") cert, key = os.path.join(folder, "cert.pem"), os.path.join(folder, "key.pem") subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "2", "-subj", "/CN=nacre.test", "-addext", "subjectAltName=DNS:*.nacre.test,DNS:nacre.test,DNS:*.other.test", "-keyout", key, "-out", cert], check=True, capture_output=True) context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.load_cert_chain(cert, key) return context def dns_answer(query): """Answer a wire-format DNS query: A 127.0.0.1 for *.nacre.test, empty for AAAA, NXDOMAIN otherwise.""" pos, labels = 12, [] while query[pos]: labels.append(query[pos + 1:pos + 1 + query[pos]].decode("ascii", "replace")) pos += 1 + query[pos] qtype = int.from_bytes(query[pos + 1:pos + 3], "big") question = query[12:pos + 5] name = ".".join(labels).lower() record("dns", name) # accounts.google.com too, so the Google sign-in user agent quirk can be checked offline (S050). ours = name == "nacre.test" or name.endswith(".nacre.test") or name.endswith(".other.test") or name == "accounts.google.com" flags = b"\x81\x80" if ours else b"\x81\x83" answers = b"" if ours and qtype == 1: answers = b"\xc0\x0c\x00\x01\x00\x01\x00\x00\x01\x2c\x00\x04" + bytes([127, 0, 0, 1]) count = 1 if answers else 0 return query[:2] + flags + b"\x00\x01" + count.to_bytes(2, "big") + b"\x00\x00\x00\x00" + question + answers ADS_PAGE = b"""Ads

Content stays

site-specific ad (cosmetic rule for nacre.test)
generic ad (generic cosmetic rule)
""" FILTER_LIST = b"""! Title: Nacre network smoke test list (S007) ! Served by tests/smoke/net/server.py; every rule names something only the test pages use. /ads/banner.js /ads/pixel.gif nacre.test,127.0.0.1##.nacre-ad ###nacre-generic-ad """ TP_PAGE = """TP TAG

Third-party test TAG """ # document.cookie in a cross-site frame (S024): the frame on 127.0.0.1:8767 writes a cookie from script, reads # document.cookie and reports what it saw as /note?tag=T&seen=... (recorded in the request log). JSTP_PAGE = """JSTP TAG """ JSCOOKIE_PAGE = """JS cookie """ GIF = bytes.fromhex("47494638396101000100800000ffffff00000021f90401000000002c00000000010001000002024401003b") class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def do_GET(self): url = urlsplit(self.path) path = url.path record("paths", self.path) if path != "/log": record("reqs", {"host": self.headers.get("Host", ""), "path": self.path, "cookie": self.headers.get("Cookie"), "dnt": self.headers.get("DNT"), "gpc": self.headers.get("Sec-GPC"), "savedata": self.headers.get("Save-Data"), "lang": self.headers.get("Accept-Language"), "ua": self.headers.get("User-Agent")}) if path == "/dns-query": import base64 wire = parse_qs(url.query).get("dns", [""])[0] query = base64.urlsafe_b64decode(wire + "=" * (-len(wire) % 4)) return self.reply(dns_answer(query), "application/dns-message") if path == "/reset": with lock: log["reqs"].clear() return self.reply(b"Reset", "text/html") if path == "/log": with lock: return self.reply(json.dumps(log).encode(), "application/json") if path == "/": scheme = "https" if isinstance(self.connection, ssl.SSLSocket) else "http" links = '

zip attachment report' return self.reply(f"Net test {scheme}

Net test over {scheme}{links}".encode(), "text/html") if path == "/auth": import base64 if self.headers.get("Authorization") == "Basic " + base64.b64encode(b"smoke:letmein").decode(): return self.reply(b"Auth ok

Signed in", "text/html") return self.reply(b"Auth needed

No", "text/html", {"WWW-Authenticate": 'Basic realm="smoke"'}, 401) if path == "/echo": return self.reply(f"Echo {url.query}

{url.query}".encode(), "text/html") if path == "/setcookie": query = parse_qs(url.query) name = query.get("name", ["c"])[0] # SameSite=None; Secure: a cookie without SameSite is Lax in WebKit (and Chromium) and never goes to a # cross-site frame or picture, so the third-party switch would have nothing to block; None needs Secure. extra = {"lax": "", "none": "; SameSite=None"}.get(query.get("ss", [""])[0], "; SameSite=None; Secure") cookie = f"{name}=1; Path=/{extra}" + (f"; Domain={query['domain'][0]}" if "domain" in query else "") return self.reply(f"Set {name}

Set {name}".encode(), "text/html", {"Set-Cookie": cookie}) if path == "/login": user = parse_qs(url.query).get("user", ["u"])[0] cookie = f"session=nacre-test-session-{user}; Path=/; Max-Age=86400; HttpOnly" return self.reply(f"Signed in {user}".encode(), "text/html", {"Set-Cookie": cookie}) if path == "/whoami": signed_in = re.search(r"(?:^|; )session=nacre-test-session-(\w+)", self.headers.get("Cookie", "")) title = f"Signed in as {signed_in.group(1)}" if signed_in else "Signed out" return self.reply(f"{title}".encode(), "text/html") if path == "/cookies": return self.reply(f"Cookies {self.headers.get('Cookie', '')}".encode(), "text/html") if path == "/pixel": return self.reply(GIF, "image/gif") if path == "/tp": tag = parse_qs(url.query).get("tag", ["x"])[0] return self.reply(TP_PAGE.replace("TAG", tag).encode(), "text/html") if path in ("/jstp", "/jscookie"): tag = parse_qs(url.query).get("tag", ["x"])[0] return self.reply((JSTP_PAGE if path == "/jstp" else JSCOOKIE_PAGE).replace("TAG", tag).encode(), "text/html") if path == "/note": return self.reply(GIF, "image/gif") if path == "/ads.html": return self.reply(ADS_PAGE, "text/html") if path == "/ads/banner.js": return self.reply(b"window.adScript = true;", "text/javascript") if path == "/ads/pixel.gif": return self.reply(GIF, "image/gif") if path == "/list.txt": return self.reply(FILTER_LIST, "text/plain") if path == "/file.zip": return self.reply(b"PK\x05\x06" + b"\x00" * 18, "application/zip") if path in ("/attachment", "/report"): return self.reply(b"attachment body\n", "application/octet-stream", {"Content-Disposition": 'attachment; filename="report.txt"'}) if path == "/big.bin": return self.big() self.reply(b"not found", "text/plain", status=404) def do_HEAD(self): url = urlsplit(self.path) record("paths", "HEAD " + self.path) if url.path in ("/attachment", "/report"): self.send_response(200) self.send_header("Content-Type", "application/octet-stream") self.send_header("Content-Disposition", 'attachment; filename="report.txt"') self.send_header("Content-Length", "16") self.end_headers() else: self.send_response(200) self.send_header("Content-Type", "text/html") self.send_header("Content-Length", "0") self.end_headers() def do_POST(self): length = int(self.headers.get("Content-Length") or 0) body = self.rfile.read(length).decode("utf-8", "replace") path = urlsplit(self.path).path record("paths", "POST " + self.path) if path == "/jsonrpc": call = json.loads(body) record("dlm", {"manager": "aria2", "method": call.get("method"), "params": call.get("params")}) result = {"version": "1.37.0"} if call.get("method") == "aria2.getVersion" else "2089b05ecca3d829" return self.reply(json.dumps({"id": call.get("id"), "jsonrpc": "2.0", "result": result}).encode(), "application/json") if path == "/add": record("dlm", {"manager": "abdm", "body": json.loads(body)}) return self.reply(b"OK", "text/plain") if path in ("/flashgot", "/flash/add"): record("dlm", {"manager": "jdownloader", "path": path, "form": parse_qs(body)}) return self.reply(b"success\r\n", "text/plain") self.reply(b"not found", "text/plain", status=404) def big(self): start = 0 wanted = self.headers.get("Range") if wanted: record("ranges", wanted) start = int(wanted.split("=")[1].split("-")[0]) self.send_response(206 if start else 200) self.send_header("Content-Type", "application/octet-stream") self.send_header("Accept-Ranges", "bytes") self.send_header("Content-Length", str(BIG - start)) if start: self.send_header("Content-Range", f"bytes {start}-{BIG - 1}/{BIG}") self.end_headers() chunk = 64 * 1024 sent = start try: while sent < BIG: # Byte i of the file is i % 251, so a resumed file can be checked end to end. n = min(chunk, BIG - sent) self.wfile.write(bytes((sent + i) % 251 for i in range(n))) sent += n time.sleep(0.11) except (BrokenPipeError, ConnectionResetError, ssl.SSLError): pass def reply(self, body, kind, headers=None, status=200): self.send_response(status) self.send_header("Content-Type", kind) self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", "no-store") for name, value in (headers or {}).items(): self.send_header(name, value) self.end_headers() self.wfile.write(body) def log_message(self, *args): pass class Sniffing(ThreadingHTTPServer): """Plain HTTP and TLS on one port: a TLS connection starts with a handshake record (0x16).""" daemon_threads = True tls = None def finish_request(self, request, client_address): if self.tls is not None: request.settimeout(10) try: first = request.recv(1, socket.MSG_PEEK) except OSError: return if first == b"\x16": with lock: log["tls"] += 1 try: request = self.tls.wrap_socket(request, server_side=True) except (ssl.SSLError, OSError): return # the browser refused the certificate request.settimeout(None) super().finish_request(request, client_address) both = Sniffing(("127.0.0.1", 8766), Handler) both.tls = make_cert() plain = Sniffing(("127.0.0.1", 8767), Handler) threading.Thread(target=plain.serve_forever, daemon=True).start() both.serve_forever()