diff --git a/nixos/snowglobe.nix b/nixos/snowglobe.nix index 840364077639983737ca16e47df9492fa8a97945..c1a50953d2eed09ffc8caf67d8ae75084fa08fa8 100644 --- a/nixos/snowglobe.nix +++ b/nixos/snowglobe.nix @@ -40,7 +40,8 @@ in startAt = "*:0/5"; serviceConfig = { Type = "oneshot"; DynamicUser = true; }; script = '' - ${pkgs.miniupnpc}/bin/upnpc -u http://${config.networking.defaultGateway.address}:1900/whaoc/rootDesc.xml -e "Snow Globe XMPP" -r \ + description="$(${pkgs.python3}/bin/python3 ${./upnp-discover.py} ${lib.escapeShellArg config.networking.defaultGateway.address})" + exec ${pkgs.miniupnpc}/bin/upnpc -u "$description" -e "Snow Globe XMPP" -r \ ${lib.concatMapStringsSep " " (port: "${toString port} TCP") xmppTCPPorts} \ ${lib.concatMapStringsSep " " (port: "${toString port} UDP") (xmppUDPPorts ++ lib.range xmppNetwork.relay_first xmppNetwork.relay_last)} ''; diff --git a/nixos/upnp-discover.py b/nixos/upnp-discover.py new file mode 100644 index 0000000000000000000000000000000000000000..4f19e39d5ae98ff13e29b952b048a1cd88181e6b --- /dev/null +++ b/nixos/upnp-discover.py @@ -0,0 +1,71 @@ +import ipaddress +import socket +import sys +import time +from urllib.parse import urlsplit + + +def description_location(packet, sender, gateway): + if sender != (gateway, 1900) or len(packet) > 8192: + return None + try: + header, _ = packet.decode("ascii").split("\r\n\r\n", 1) + status, *lines = header.split("\r\n") + if status != "HTTP/1.1 200 OK": + return None + headers = {} + for line in lines: + name, value = line.split(":", 1) + if not name or any(not (c.isalnum() or c in "!#$%&'*+-.^_`|~") for c in name): + return None + name = name.lower() + if name in headers: + return None + headers[name] = value.strip(" \t") + if headers.get("st") != "upnp:rootdevice": + return None + location = headers["location"] + if any(ord(c) <= 32 or ord(c) >= 127 for c in location): + return None + url = urlsplit(location) + if (url.scheme != "http" or url.hostname != gateway or url.port == 0 + or url.username is not None or url.password is not None + or url.fragment or not url.path.startswith("/")): + return None + return location + except (ValueError, KeyError): + return None + + +def discover(gateway, timeout=3.0): + gateway = str(ipaddress.IPv4Address(gateway)) + request = ( + 'M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\n' + 'MAN: "ssdp:discover"\r\nMX: 1\r\nST: upnp:rootdevice\r\n\r\n' + ).encode("ascii") + deadline = time.monotonic() + timeout + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as udp: + udp.settimeout(timeout) + udp.sendto(request, (gateway, 1900)) + for _ in range(64): + remaining = deadline - time.monotonic() + if remaining <= 0: + break + udp.settimeout(remaining) + try: + packet, sender = udp.recvfrom(8193) + except socket.timeout: + break + location = description_location(packet, sender, gateway) + if location is not None: + return location + raise TimeoutError(f"No valid UPnP description from {gateway}:1900") + + +if __name__ == "__main__": + if len(sys.argv) != 2: + sys.exit("Usage: upnp-discover.py GATEWAY_IPV4") + try: + print(discover(sys.argv[1])) + except (OSError, ValueError) as error: + sys.exit(str(error)) diff --git a/tools/upnp-discover-test.py b/tools/upnp-discover-test.py new file mode 100644 index 0000000000000000000000000000000000000000..dcc2d5b297c20df3a43d62f1151894542cdecffc --- /dev/null +++ b/tools/upnp-discover-test.py @@ -0,0 +1,127 @@ +import importlib.util +from pathlib import Path +import socket +import threading +import time +import unittest + + +spec = importlib.util.spec_from_file_location( + "upnp_discover", Path(__file__).resolve().parents[1] / "nixos/upnp-discover.py" +) +upnp = importlib.util.module_from_spec(spec) +spec.loader.exec_module(upnp) +GATEWAY = "127.0.0.1" +LOCATION = "http://127.0.0.1:1900/random-after-reboot/rootDesc.xml" +RESPONSE = ( + f"HTTP/1.1 200 OK\r\nST: upnp:rootdevice\r\nLOCATION: {LOCATION}\r\n\r\n" +).encode("ascii") + + +class DiscoveryTests(unittest.TestCase): + def test_gateway_extension_headers(self): + packet = ( + "HTTP/1.1 200 OK\r\nCACHE-CONTROL: max-age=120\r\nST: upnp:rootdevice\r\n" + "USN: uuid:00000000-0000-0000-0000-000000000001::upnp:rootdevice\r\nEXT:\r\n" + "SERVER: TP-LINK/TP-LINK UPnP/1.1 MiniUPnPd/1.8\r\n" + f"LOCATION: {LOCATION}\r\n" + 'OPT: "http://schemas.upnp.org/upnp/1/0/"; ns=01\r\n01-NLS: 1\r\n' + "BOOTID.UPNP.ORG: 1\r\nCONFIGID.UPNP.ORG: 1337\r\n\r\n" + ).encode("ascii") + self.assertEqual(upnp.description_location(packet, (GATEWAY, 1900), GATEWAY), LOCATION) + + def test_response_validation(self): + self.assertEqual(upnp.description_location(RESPONSE, (GATEWAY, 1900), GATEWAY), LOCATION) + alternate_port = RESPONSE.replace(b":1900/random", b":8080/random") + self.assertEqual( + upnp.description_location(alternate_port, (GATEWAY, 1900), GATEWAY), + LOCATION.replace(":1900/", ":8080/"), + ) + invalid = [ + RESPONSE.replace(b"127.0.0.1:1900", b"example.net:1900"), + RESPONSE.replace(b"127.0.0.1:1900", b"127.0.0.2:1900"), + RESPONSE.replace(b":1900/", b":0/"), + RESPONSE.replace(b":1900/", b":65536/"), + RESPONSE.replace(b":1900/", b":not-a-port/"), + RESPONSE.replace(b"http://", b"https://"), + RESPONSE.replace(b"http://", b"http://user@"), + RESPONSE.replace(b"rootDesc.xml", b"rootDesc.xml#fragment"), + RESPONSE.replace(b"rootDesc.xml", b"root\tDesc.xml"), + RESPONSE.replace(b"200 OK", b"404 Not Found"), + RESPONSE.replace(b"upnp:rootdevice", b"ssdp:all"), + RESPONSE.replace(b"LOCATION:", b"MISSING:"), + RESPONSE.replace(b"LOCATION:", b"BAD NAME:"), + RESPONSE.replace(b"LOCATION:", b"BAD/NAME:"), + RESPONSE.replace(b"\r\n\r\n", b"\r\nLOCATION: http://evil/\r\n\r\n"), + RESPONSE.replace(b"\r\n\r\n", b"\r\n folded\r\n\r\n"), + RESPONSE.replace(b"\r\n\r\n", b"\r\n"), + b"404", + b"\xff" + RESPONSE, + RESPONSE + b"x" * 8192, + ] + for packet in invalid: + with self.subTest(packet=packet[:100]): + self.assertIsNone(upnp.description_location(packet, (GATEWAY, 1900), GATEWAY)) + self.assertIsNone(upnp.description_location(RESPONSE, ("127.0.0.2", 1900), GATEWAY)) + self.assertIsNone(upnp.description_location(RESPONSE, (GATEWAY, 1901), GATEWAY)) + + def test_real_udp_ignores_invalid_then_accepts_gateway(self): + errors = [] + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as gateway: + gateway.bind((GATEWAY, 1900)) + gateway.settimeout(1) + + def respond(): + try: + request, sender = gateway.recvfrom(8192) + self.assertIn(b"M-SEARCH * HTTP/1.1\r\n", request) + self.assertIn(b"ST: upnp:rootdevice\r\n\r\n", request) + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as rogue: + rogue.sendto(RESPONSE, sender) + gateway.sendto(RESPONSE.replace(b"127.0.0.1:1900", b"evil:1900"), sender) + gateway.sendto(b"HTTP/1.1 200 OK\r\n\r\n", sender) + gateway.sendto(RESPONSE, sender) + except BaseException as error: + errors.append(error) + + thread = threading.Thread(target=respond) + thread.start() + try: + self.assertEqual(upnp.discover(GATEWAY, timeout=0.5), LOCATION) + finally: + thread.join(timeout=2) + self.assertFalse(thread.is_alive()) + self.assertEqual(errors, []) + + def test_timeout_is_bounded(self): + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as gateway: + gateway.bind((GATEWAY, 1900)) + started = time.monotonic() + with self.assertRaises(TimeoutError): + upnp.discover(GATEWAY, timeout=0.05) + self.assertLess(time.monotonic() - started, 0.5) + + def test_invalid_response_flood_is_bounded(self): + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as gateway: + gateway.bind((GATEWAY, 1900)) + gateway.settimeout(1) + + def flood(): + _, sender = gateway.recvfrom(8192) + for _ in range(128): + gateway.sendto(b"invalid", sender) + + thread = threading.Thread(target=flood) + thread.start() + started = time.monotonic() + try: + with self.assertRaises(TimeoutError): + upnp.discover(GATEWAY, timeout=0.5) + finally: + thread.join(timeout=2) + self.assertFalse(thread.is_alive()) + self.assertLess(time.monotonic() - started, 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/xmpp.md b/tools/xmpp.md index f96f7e61bba761ad4bbbe2c61fbc3d0eb5cec2df..5841fd7fedc6a719e50d2c98697590fa1f618840 100644 --- a/tools/xmpp.md +++ b/tools/xmpp.md @@ -25,9 +25,11 @@ provisions client, direct-TLS client, and federation SRV records pointing at `xmpp.paperclover.net`; the website keeps its existing apex address. Router forwarding must send the TCP listeners, UDP TURN listeners, and UDP relay range to Snow Globe. `xmpp-nat.service` refreshes UPnP mappings on startup and every five -minutes, using the Archer AX3000's description URL at the configured gateway. -The description is fetched directly; multicast SSDP discovery failed on this -host. Production activation uses the normal described-main deployment: +minutes, discovering the current description URL with a bounded unicast SSDP +request to the configured gateway on port 1900. Replies and HTTP description +hosts must match that gateway; discovery failure fails the refresh. Multicast +SSDP discovery does not work on this host. Production activation uses the normal +described-main deployment: ```sh SNOWGLOBE_DEPLOY_HOST=root@10.0.0.1 SNOWGLOBE_DEPLOY_PORT=22 python3 tools/deploy.py prod