1#!/usr/bin/env python3
2"""Check loopback forwarding against a disposable HTTP server in the live VM."""
3
4import hashlib
5from importlib import import_module
6from pathlib import Path
7import shlex
8import socket
9import subprocess
10import sys
11import time
12import urllib.error
13import urllib.request
14
15
16vm = import_module("mac-agent-vm")
17
18
19def main():
20 payload = b"forwarding fixture\n" * 40000
21 code = '''from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
22import sys, threading
23class Handler(BaseHTTPRequestHandler):
24 def do_GET(self):
25 body = b"forwarding fixture\\n" * 40000
26 self.send_response(200)
27 self.send_header("Content-Length", str(len(body)))
28 self.end_headers()
29 self.wfile.write(body)
30 def log_message(self, *args): pass
31server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
32threading.Thread(target=server.serve_forever, daemon=True).start()
33print(server.server_port, flush=True)
34sys.stdin.buffer.read()
35server.shutdown()
36server.server_close()
37'''
38 ip = vm.tart("ip", vm.NAME, capture_output=True, text=True, timeout=5).stdout.strip()
39 server = subprocess.Popen([*vm.ssh_args(), "admin@" + ip, "python3 -u -c " + shlex.quote(code)],
40 stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
41 tunnel = None
42 try:
43 port = int(server.stdout.readline())
44 with socket.socket() as available:
45 available.bind(("127.0.0.1", 0))
46 local_port = available.getsockname()[1]
47 command = [sys.executable, str(Path(__file__).with_name("mac-agent-vm.py")),
48 "forward", str(port), "--local-port", str(local_port)]
49 tunnel = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
50 url = f"http://127.0.0.1:{local_port}/fixture"
51 opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
52 deadline = time.monotonic() + 15
53 while True:
54 if tunnel.poll() is not None:
55 raise AssertionError(tunnel.communicate()[1])
56 try:
57 with opener.open(url, timeout=2) as response:
58 actual = response.read()
59 break
60 except urllib.error.URLError:
61 if time.monotonic() >= deadline:
62 raise
63 time.sleep(0.05)
64 assert hashlib.sha256(actual).digest() == hashlib.sha256(payload).digest()
65 collision = subprocess.run(command, capture_output=True, text=True, timeout=15)
66 assert collision.returncode != 0, "A second tunnel silently reused an occupied port."
67 with opener.open(url, timeout=2) as response:
68 assert response.read() == payload, "Port collision disturbed the first tunnel."
69 tunnel.terminate()
70 tunnel.communicate(timeout=5)
71 try:
72 opener.open(url, timeout=2)
73 except urllib.error.URLError:
74 pass
75 else:
76 raise AssertionError("The tunnel listener survived its process.")
77 print(f"Forwarded {len(payload)} bytes intact; collision preserved the live tunnel; shutdown closed its listener.")
78 finally:
79 if tunnel is not None and tunnel.poll() is None:
80 tunnel.terminate()
81 tunnel.communicate(timeout=5)
82 server.stdin.close()
83 server.wait(timeout=10)
84 server.stdout.close()
85
86
87if __name__ == "__main__":
88 main()