servo-net hands its public cookie jar to Nacre instead of writing plain cookie_jar.json; store::cookies seals it in cookies.bin (XChaCha20-Poly1305) with a keyring-held key, saves on change and at exit, migrates the old plain jar. No keyring: cookies for the run only, Settings says so (D-019). Smokes with a throwaway GNOME Keyring (SMOKE_KEYRING=1). Co-Authored-By: Claude Opus 5.5 <[email protected]>
299 lines
14 KiB
Python
299 lines
14 KiB
Python
#!/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 -> 127.0.0.1, every other name NXDOMAIN, so
|
|
secure DNS pointed here never reaches a public resolver
|
|
/ "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] sets cookie N=1 (Path=/, 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
|
|
(127.0.0.1:8767) and a same-site picture (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 and Save-Data headers (S023)
|
|
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", "-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)
|
|
ours = name == "nacre.test" or name.endswith(".nacre.test")
|
|
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"""<!doctype html><meta charset=utf-8><title>Ads</title>
|
|
<style>div { height: 40px; margin: 4px; background: #c33; color: #fff; font: 16px sans-serif; }</style>
|
|
<p id=content>Content stays</p>
|
|
<div class="nacre-ad">site-specific ad (cosmetic rule for nacre.test)</div>
|
|
<div id="nacre-generic-ad">generic ad (generic cosmetic rule)</div>
|
|
<img id=pixel src="/ads/pixel.gif" width=10 height=10>
|
|
<script>window.adScript = false;</script>
|
|
<script src="/ads/banner.js"></script>
|
|
<script>
|
|
window.pixelLoaded = null;
|
|
let img = document.getElementById("pixel");
|
|
img.onload = () => { window.pixelLoaded = true; };
|
|
img.onerror = () => { window.pixelLoaded = false; };
|
|
if (img.complete) { window.pixelLoaded = img.naturalWidth > 0; }
|
|
</script>
|
|
"""
|
|
|
|
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 = """<!doctype html><meta charset=utf-8><title>TP TAG</title>
|
|
<p>Third-party test TAG
|
|
<iframe id=frame src="http://127.0.0.1:8767/setcookie?name=tpTAG&tag=TAG"></iframe>
|
|
<img id=cross src="http://127.0.0.1:8767/pixel?tag=TAG">
|
|
<img id=same src="http://img.nacre.test:8766/pixel?tag=TAG">
|
|
<script>
|
|
let left = 3;
|
|
const one = () => { if (--left === 0) document.title = "TP TAG done"; };
|
|
for (const e of [frame, cross, same]) { e.onload = one; e.onerror = one; }
|
|
</script>"""
|
|
|
|
# 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 = """<!doctype html><meta charset=utf-8><title>JSTP TAG</title>
|
|
<iframe id=frame src="http://127.0.0.1:8767/jscookie?tag=TAG"></iframe>
|
|
<script>frame.onload = () => setTimeout(() => { document.title = "JSTP TAG done"; }, 500);</script>"""
|
|
JSCOOKIE_PAGE = """<!doctype html><meta charset=utf-8><title>JS cookie</title>
|
|
<script>document.cookie = "jsTAG=1; Path=/";
|
|
new Image().src = "/note?tag=TAG&seen=" + encodeURIComponent(document.cookie);</script>"""
|
|
|
|
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")})
|
|
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"<!doctype html><title>Reset</title>", "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 = '<p><a id=zip href="/file.zip?link">zip</a> <a id=attachment href="/attachment?link">attachment</a> <a id=report href="/report">report</a>'
|
|
return self.reply(f"<!doctype html><title>Net test {scheme}</title><p>Net test over {scheme}{links}".encode(), "text/html")
|
|
if path == "/echo":
|
|
return self.reply(f"<!doctype html><title>Echo {url.query}</title><p>{url.query}".encode(), "text/html")
|
|
if path == "/setcookie":
|
|
query = parse_qs(url.query)
|
|
name = query.get("name", ["c"])[0]
|
|
cookie = f"{name}=1; Path=/" + (f"; Domain={query['domain'][0]}" if "domain" in query else "")
|
|
return self.reply(f"<!doctype html><title>Set {name}</title><p>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"<!doctype html><title>Signed in {user}</title>".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"<!doctype html><title>{title}</title>".encode(), "text/html")
|
|
if path == "/cookies":
|
|
return self.reply(f"<!doctype html><title>Cookies {self.headers.get('Cookie', '')}</title>".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()
|