#!/usr/bin/env python3 """AWEIGH IPv4 UDP NAT behavior test (RFC 5780, Python standard library).""" import argparse import ipaddress import secrets import socket import struct import time from collections import namedtuple SERVER = "stunserver2025.stunprotocol.org" PORT = 3478 MAGIC = 0x2112A442 HEADER = struct.Struct("!HHI12s") Binding = namedtuple("Binding", "mapped other") EIM, ADM, APDM = "eim", "adm", "apdm" EIF, ADF, APDF = "eif", "adf", "apdf" TEXT = { "en": { "mapping": "Mapping", "filtering": "Filtering", "type": "Traditional type", "endpoint": "Public UDP endpoint", "unknown": "Undetermined", "eim": "Endpoint-independent", "adm": "Address-dependent", "apdm": "Address and port-dependent", "eif": "Endpoint-independent", "adf": "Address-dependent", "apdf": "Address and port-dependent (inferred)", "full": "Full cone NAT", "restricted": "Restricted cone NAT", "port": "Port-restricted cone NAT", "symmetric": "Symmetric NAT", "open": "Open Internet (no NAT observed)", "firewall": "UDP filtering detected (no NAT observed)", "timeout": "The initial STUN request timed out. UDP connectivity could not be confirmed.", "incomplete": "Some required STUN replies were unavailable. The incomplete result is left undetermined.", "unreachable": "Unable to reach the IPv4 STUN service from this device.", "scope": "This result applies to the current IPv4 UDP path. Local or network firewall behavior can affect it.", }, "zh": { "mapping": "映射行为", "filtering": "过滤行为", "type": "传统 NAT 类型", "endpoint": "UDP 公网端点", "unknown": "无法判定", "eim": "端点无关", "adm": "依赖目标地址", "apdm": "依赖目标地址和端口", "eif": "端点无关", "adf": "依赖来源地址", "apdf": "依赖来源地址和端口(推断)", "full": "全锥型 NAT", "restricted": "受限锥型 NAT", "port": "端口受限锥型 NAT", "symmetric": "对称型 NAT", "open": "开放互联网(未观测到 NAT)", "firewall": "检测到 UDP 入站过滤(未观测到 NAT)", "timeout": "首次 STUN 请求超时,无法确认 UDP 连通性。", "incomplete": "部分必要的 STUN 回包缺失,相关行为暂无法判定。", "unreachable": "当前设备无法访问 IPv4 STUN 服务。", "scope": "结果仅反映当前 IPv4 UDP 路径,可能受设备或网络防火墙影响。", }, } def ipv4_endpoint(value, xor=False): if len(value) != 8 or value[:2] != b"\x00\x01": return None port, address = struct.unpack_from("!HI", value, 2) if xor: port ^= MAGIC >> 16 address ^= MAGIC ip = ipaddress.IPv4Address(address) if not port or not ip.is_global or ip.is_multicast or ip.is_reserved: return None return str(ip), port def binding_response(packet, transaction): if len(packet) < HEADER.size: return None kind, length, magic, received = HEADER.unpack_from(packet) if kind != 0x0101 or magic != MAGIC or received != transaction or length % 4 or len(packet) != HEADER.size + length: return None mapped = other = None offset = HEADER.size while offset < len(packet): attribute, size = struct.unpack_from("!HH", packet, offset) start = offset + 4 offset = start + ((size + 3) & ~3) if offset > len(packet): return None if attribute == 0x0020: mapped = ipv4_endpoint(packet[start:start + size], xor=True) elif attribute == 0x802C: other = ipv4_endpoint(packet[start:start + size]) return Binding(mapped, other) if mapped else None def probe(sock, target, change=0, reply_from=None): transaction = secrets.token_bytes(12) attribute = struct.pack("!HHI", 0x0003, 4, change) if change else b"" packet = HEADER.pack(0x0001, len(attribute), MAGIC, transaction) + attribute expected = reply_from or target for wait in (0.5, 1.0, 2.0): sock.sendto(packet, target) deadline = time.monotonic() + wait while time.monotonic() < deadline: sock.settimeout(max(0.001, deadline - time.monotonic())) try: reply, source = sock.recvfrom(2048) except (TimeoutError, ConnectionResetError): break if source == expected: result = binding_response(reply, transaction) if result: return result return None def discover(sock, server, first): local = sock.getsockname() translated = first.mapped != local mapping = None if translated else EIM other = first.other if not other or other[0] == server[0] or other[1] == server[1] or other[1] < 1024: return translated, mapping, None # Filtering must run before direct probes prime the alternate destinations. alternate_port = (server[0], other[1]) filtering = None if probe(sock, server, change=6, reply_from=other): filtering = EIF elif probe(sock, server, change=2, reply_from=alternate_port): filtering = ADF if translated: second = probe(sock, (other[0], server[1])) if second and second.mapped == first.mapped: mapping = EIM elif second: third = probe(sock, other) if third: mapping = ADM if second.mapped == third.mapped else APDM # A negative filtering result is usable only if ordinary replies from both # alternate endpoints and the original endpoint still arrive. if filtering is None and probe(sock, other) and probe(sock, alternate_port) and probe(sock, server): filtering = APDF return translated, mapping, filtering def traditional_type(translated, mapping, filtering): if not translated: return "open" if filtering == EIF else ("firewall" if filtering else "unknown") if mapping in (ADM, APDM): return "symmetric" if mapping == EIM: return {EIF: "full", ADF: "restricted", APDF: "port"}.get(filtering, "unknown") return "unknown" def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--lang", choices=("en", "zh"), default="en") text = TEXT[parser.parse_args().lang] print(f"AWEIGH | IPv4 UDP | {SERVER}:{PORT}", flush=True) try: server = (socket.gethostbyname(SERVER), PORT) with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as route: route.connect(server) local_ip = route.getsockname()[0] with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: sock.bind((local_ip, 0)) first = probe(sock, server) if not first: print(text["timeout"]) return 1 print(f"{text['endpoint']}: {first.mapped[0]}:{first.mapped[1]}", flush=True) translated, mapping, filtering = discover(sock, server, first) except OSError: print(text["unreachable"]) return 1 print(f"{text['mapping']}: {text[mapping or 'unknown']}") print(f"{text['filtering']}: {text[filtering or 'unknown']}") print(f"{text['type']}: {text[traditional_type(translated, mapping, filtering)]}") if not mapping or not filtering: print(text["incomplete"]) print(text["scope"]) return int(not mapping or not filtering) if __name__ == "__main__": raise SystemExit(main())