Commit86ef4e52Recorded18 Oct 2026Repositorysigil-nat
Add owned NAT probe reflectors and outbound measurement client
Message
Measure port behaviour without refreshing idle data sockets and keep failed controls inconclusive. Support the single-host two-port run with a base-Perl reflector, bounded state and process lifetimes, private receipts, and explicit unmeasured address dependence. Add actual loopback UDP and Perl interoperability checks.
Changed
README.md | 33 +++++++++++++++++++++++++++++++++
scripts/nat-probe.mjs | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++
scripts/phantom-nat-probe-check.sh | 7 +++++--
tools/nat/nat-probe-analysis.mjs | 29 +++++++++++++++++++++++++++--
tools/nat/nat-probe-reflector.mjs | 123 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
tools/nat/nat-probe-socket.mjs | 87 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
tools/nat/nat-probe-wire.mjs | 7 +++++++
tools/nat/nat-probe.mjs | 117 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
tools/nat/reflectors/nat-probe.pl | 106 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
tools/nat/test-nat-probe-perl.mjs | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
tools/nat/test-nat-probe-runtime.mjs | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
tools/nat/test-nat-probe.mjs | 13 ++++++++++++-
12 files changed, 722 insertions(+), 5 deletions(-)Diff
README.mdmodified
@@ -20,3 +20,36 @@ The protocol codec sources are RFC 6887 and RFC 6886. UPnP service actions and
20
lease semantics follow the [WANIPConnection:1 service template](https://upnp.org/specs/gw/UPnP-gw-WANIPConnection-v1-Service.pdf), 21
including `GetSpecificPortMappingEntry`, `AddPortMapping`, 22
`DeletePortMapping`, and `GetExternalIPAddress`.+23
+24
`tools/nat/nat-probe.mjs` measures the current combined IPv4 path using owned,+25
run-specific reflectors. Its private fixed-size protocol is not STUN wire.+26
The client checks reachability once per reflector port before measuring,+27
uses fresh source ports for filtering before contacting alternates, compares+28
full observed address/port tuples and checks the primary tuple again. Idle+29
samples use separate receive-only data sockets and a control socket; the+30
measured socket sends only its initial lookup. Missing send acknowledgements+31
or positive controls remain inconclusive. A missing idle reply is reported+32
as not observed, not proof of expiration.+33
+34
For a single-host run, `tools/nat/reflectors/nat-probe.pl` uses only+35
base Perl modules and two ephemeral high ports on one exact IPv4 interface.+36
Its private owned config contains four lines: bind IPv4, 64-hex run token,+37
lifetime milliseconds (at most 900000), and absolute receipt path. It latches+38
the first valid token holder's source IP, responds only to that client, and+39
can deliver idle probes only to tuples it previously observed. Packet/state+40
budgets and expiry bound the listener. Its private receipt records its PID+41
and ports; the `.done` receipt records shutdown. Stop only that admitted PID.+42
No package installation or firewall change is part of this helper.+43
+44
`scripts/nat-probe.mjs PRIVATE_CONFIG.json` runs the client on the+45
default-route source. The config names schema 1, expectedHost,+46
localAddress, tokenHex, a new absolute runDirectory, optional mappingSamples+47
(3..5), and reflectors.a1/a2 with the same public address and different ports.+48
This wrapper rejects a VPN/private reflector address and uses the+49
15/30/60/120-second idle plan. The library also supports two distinct-address+50
reflectors with explicit configuration. A single-host result explicitly leaves+51
address dependence unmeasured. Public summaries contain only classifications,+52
counts and timings; observed addresses stay in private details receipts.+53
+54
Validate with `node --test tools/nat/test-*.mjs`. Tests include real loopback UDP and the actual Perl reflector; these+55
are apparatus checks, not observations about an outside NAT.scripts/nat-probe.mjsadded
@@ -0,0 +1,51 @@
+1
// Bounded client for a public reflector controlled by the caller.+2
import { readFileSync, lstatSync, mkdirSync, writeFileSync } from 'node:fs';+3
import { hostname } from 'node:os';+4
import { isIP } from 'node:net';+5
import { isAbsolute, resolve, join } from 'node:path';+6
import { gatewayRoute } from '../tools/nat/discovery.mjs';+7
import { runNatProbe } from '../tools/nat/nat-probe.mjs';+8
+9
const configPath = resolve(process.argv[2] ?? '');+10
const file = lstatSync(configPath);+11
if (!file.isFile() || file.uid !== process.getuid() ||+12
file.size > 16384 || (file.mode & 0o077) !== 0)+13
throw new Error('NAT probe requires a private owned config');+14
const config = JSON.parse(readFileSync(configPath, 'utf8'));+15
if (config.schema !== 1 || config.expectedHost !== hostname() ||+16
!/^[0-9a-f]{64}$/.test(config.tokenHex ?? '') || !isAbsolute(config.runDirectory ?? ''))+17
throw new Error('Invalid NAT probe host/schema/token/run directory');+18
const address = config.reflectors?.a1?.address;+19
const parts = isIP(address) === 4 ? address.split('.').map(Number) : [];+20
if (parts.length !== 4 || parts[0] === 0 || parts[0] === 10 || parts[0] === 127 || parts[0] >= 224 ||+21
(parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127) ||+22
(parts[0] === 169 && parts[1] === 254) || (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) ||+23
(parts[0] === 192 && parts[1] === 168) || config.reflectors.b !== undefined)+24
throw new Error('Expected one public IPv4 reflector');+25
const route = gatewayRoute();+26
if (config.localAddress !== route.localAddress) throw new Error('Probe source must match the owned default-route interface');+27
mkdirSync(config.runDirectory, { mode: 0o700 });+28
const abort = new AbortController();+29
const stop = () => abort.abort(new Error('NAT probe interrupted'));+30
process.once('SIGTERM', stop); process.once('SIGINT', stop);+31
const state = { processId: process.pid, startedAt: new Date().toISOString() };+32
writeFileSync(join(config.runDirectory, 'starting.json'), JSON.stringify(state) + '\n', { mode: 0o600 });+33
try {+34
const result = await runNatProbe({ localAddress: route.localAddress, reflectors: config.reflectors,+35
token: Buffer.from(config.tokenHex, 'hex'), mappingSamples: config.mappingSamples ?? 3,+36
signal: abort.signal });+37
writeFileSync(join(config.runDirectory, 'details.json'), JSON.stringify(result.details, null, 2) + '\n', { mode: 0o600 });+38
state.summary = result.summary;+39
state.completed = true;+40
console.log(JSON.stringify(result.summary));+41
} catch (error) {+42
state.completed = false;+43
state.errorCode = error.code ?? 'PROBE_FAILED';+44
state.controls = error.controls;+45
console.log(`RESULT nat-probe=${state.errorCode} completed=false`);+46
process.exitCode = 1;+47
} finally {+48
process.off('SIGTERM', stop); process.off('SIGINT', stop);+49
state.endedAt = new Date().toISOString();+50
writeFileSync(join(config.runDirectory, 'result.json'), JSON.stringify(state, null, 2) + '\n', { mode: 0o600 });+51
}scripts/phantom-nat-probe-check.shmodified
@@ -8,6 +8,9 @@ record_result() {
8
printf 'RESULT nat-probe-check rc=%s\n' "$job_rc" | tee -a "$result_path" 9
} 10
trap record_result EXIT−11
printf 'RESULT operation=offline-probe-fixtures no-network\n' | tee "$result_path"−12
timeout --foreground 30 node --test tools/nat/test-nat-probe.mjs 2>&1 | tee build/nat-probe/tests.log+11
printf 'RESULT operation=probe-fixtures-plus-real-loopback-UDP no-outside-network\n' | tee "$result_path"+12
command -v perl > build/nat-probe/perl-path.txt+13
perl -c tools/nat/reflectors/nat-probe.pl 2>&1 | tee build/nat-probe/perl-syntax.log+14
node --check scripts/nat-probe.mjs+15
timeout --foreground 30 node --test tools/nat/test-nat-probe.mjs tools/nat/test-nat-probe-runtime.mjs tools/nat/test-nat-probe-perl.mjs 2>&1 | tee build/nat-probe/tests.log 16
printf 'RESULT nat-probe-fixtures=PASS\n' | tee -a "$result_path"tools/nat/nat-probe-analysis.mjsmodified
@@ -45,15 +45,40 @@ function counts(values) {
45
return result; 46
} 47
export function summarizeNatProbe({ mapping, filtering, lifetime }) {+48
validateSamples(mapping, filtering);+49
const compared = mapping.filter(sample => usableObservation(sample.a1));+50
return { mapping: counts(mapping.map(classifyProbeMapping)),+51
filtering: counts(filtering.map(classifyProbeFiltering)),+52
portPreservation: { compared: compared.length,+53
preserved: compared.filter(sample => sample.a1.observed.port === sample.localPort).length },+54
lifetime: summarizeProbeLifetime(lifetime),+55
scope: 'observed-combined-IPv4-path', protocol: 'private-RFC-style-not-STUN' };+56
}+57
function validateSamples(mapping, filtering) { 58
if (!Array.isArray(mapping) || mapping.length < 3 || mapping.length > 5 || 59
!Array.isArray(filtering) || filtering.length < 1 || filtering.length > 5) 60
throw new Error('Probe needs 3..5 mapping samples and 1..5 filtering samples'); 61
if (mapping.some(sample => !Number.isInteger(sample.localPort) || sample.localPort < 1024 || sample.localPort > 65535) || 62
new Set(mapping.map(sample => sample.localPort)).size !== mapping.length) 63
throw new Error('Mapping samples must use different local source ports');+64
}+65
export function summarizeSingleHostNatProbe({ mapping, filtering, lifetime }) {+66
validateSamples(mapping, filtering);+67
const mappingClass = sample => {+68
if (![sample.a1, sample.a2, sample.repeatedA1].every(usableObservation) ||+69
!sameEndpoint(sample.a1.observed, sample.repeatedA1.observed)) return 'inconclusive';+70
return sameEndpoint(sample.a1.observed, sample.a2.observed)+71
? 'port-independent-for-tested-address' : 'port-dependent-for-tested-address';+72
};+73
const filteringClass = sample => {+74
if (![sample.controls?.primary, sample.controls?.alternatePort, sample.controls?.recoveredPrimary].every(value => value === true) ||+75
sample.alternatePort?.sent !== true || sample.alternatePort?.ackMatched !== true ||+76
typeof sample.alternatePort?.received !== 'boolean') return 'inconclusive';+77
return sample.alternatePort.received ? 'alternate-port-allowed' : 'alternate-port-not-observed';+78
}; 79
const compared = mapping.filter(sample => usableObservation(sample.a1));−55
return { mapping: counts(mapping.map(classifyProbeMapping)),−56
filtering: counts(filtering.map(classifyProbeFiltering)),+80
return { mapping: counts(mapping.map(mappingClass)), filtering: counts(filtering.map(filteringClass)),+81
addressDependence: 'unmeasured-single-reflector-IP', 82
portPreservation: { compared: compared.length, 83
preserved: compared.filter(sample => sample.a1.observed.port === sample.localPort).length }, 84
lifetime: summarizeProbeLifetime(lifetime),tools/nat/nat-probe-reflector.mjsadded
@@ -0,0 +1,123 @@
+1
// Owned, short-lived measurement reflectors. No unauthenticated UDP replies.+2
import { createSocket } from 'node:dgram';+3
import { once } from 'node:events';+4
import { isIP } from 'node:net';+5
import { closeUdpSocket } from './socket-cleanup.mjs';+6
import { decodeProbeMessage, encodeProbeMessage, probeEndpoint, sameEndpoint,+7
probeOperations as op } from './nat-probe-wire.mjs';+8
+9
export async function openNatProbeReflector({ role, bindAddress, ports, token,+10
clientAddresses, peer, lifetimeMs = 180000 }) {+11
if (!['a', 'b'].includes(role) || isIP(bindAddress) !== 4 || bindAddress === '0.0.0.0' ||+12
!Array.isArray(ports) || ports.length !== (role === 'a' ? 2 : 1) ||+13
ports.some(port => !Number.isInteger(port) || port < 0 || port > 65535) ||+14
!Buffer.isBuffer(token) || token.length !== 32 || !Array.isArray(clientAddresses) ||+15
clientAddresses.length < 1 || clientAddresses.length > 4 || clientAddresses.some(address => isIP(address) !== 4) ||+16
!Number.isInteger(lifetimeMs) || lifetimeMs < 1 || lifetimeMs > 240000)+17
throw new Error('Invalid bounded NAT reflector configuration');+18
const sockets = [];+19
const entries = new Map();+20
const pending = new Map();+21
const forwarded = new Set();+22
const errors = [];+23
const counts = { received: 0, accepted: 0, sent: 0, discarded: 0 };+24
let remotePeer = peer ? probeEndpoint(peer) : undefined;+25
let closing;+26
let timer;+27
let resolveClosed;+28
const closed = new Promise(done => { resolveClosed = done; });+29
const close = () => {+30
if (closing) return closing;+31
clearTimeout(timer);+32
closing = (async () => {+33
const results = await Promise.allSettled(sockets.map(closeUdpSocket));+34
for (const result of results) if (result.status === 'rejected') errors.push(result.reason.code ?? 'close-error');+35
entries.clear(); pending.clear(); forwarded.clear();+36
resolveClosed();+37
})();+38
return closing;+39
};+40
const send = async (index, destination, operation, transaction, endpoint) => {+41
if (closing || counts.sent >= 256) throw new Error('Reflector stopped or outbound budget exhausted');+42
probeEndpoint(destination);+43
counts.sent += 1;+44
const packet = encodeProbeMessage({ token, transaction, operation, endpoint });+45
await new Promise((done, reject) => sockets[index].send(packet, destination.port, destination.address,+46
error => error ? reject(error) : done()));+47
};+48
const handle = async (index, bytes, source) => {+49
counts.received += 1;+50
if (counts.received > 512) { await close(); return; }+51
let message;+52
try { message = decodeProbeMessage(bytes, token); }+53
catch { counts.discarded += 1; return; }+54
const sender = { address: source.address, port: source.port };+55
const id = message.transaction.toString('hex');+56
const fromClient = clientAddresses.includes(sender.address) && sender.port >= 1024;+57
const fromPeer = sameEndpoint(sender, remotePeer);+58
// Forwarding can only come from the single admitted peer reflector, to an+59
// admitted client's address. It never accepts an arbitrary external target.+60
if (role === 'b' && index === 0 && fromPeer && message.operation === op.forward) {+61
if (!message.endpoint || !clientAddresses.includes(message.endpoint.address) ||+62
message.endpoint.port < 1024 || forwarded.has(id) || forwarded.size >= 64) return;+63
forwarded.add(id);+64
counts.accepted += 1;+65
await send(0, message.endpoint, op.probe, message.transaction);+66
await send(0, sender, op.sent, message.transaction);+67
return;+68
}+69
if (role === 'a' && index === 0 && fromPeer && message.operation === op.sent) {+70
const destination = pending.get(id);+71
if (!destination || message.endpoint) return;+72
pending.delete(id);+73
await send(0, destination, op.sent, message.transaction);+74
return;+75
}+76
if (!fromClient || message.endpoint) { counts.discarded += 1; return; }+77
counts.accepted += 1;+78
if (message.operation === op.lookup) {+79
const previous = entries.get(id);+80
if (previous && !sameEndpoint(previous.sender, sender)) return;+81
if (!previous && entries.size >= 64) return;+82
entries.set(id, previous ?? { sender, delivered: false });+83
await send(index, sender, op.observed, message.transaction, sender);+84
} else if (role === 'a' && index === 0 && message.operation === op.alternatePort) {+85
await send(1, sender, op.probe, message.transaction);+86
await send(0, sender, op.sent, message.transaction);+87
} else if (role === 'a' && index === 0 && message.operation === op.alternateAddress && remotePeer) {+88
if (pending.has(id) || pending.size >= 32) return;+89
pending.set(id, sender);+90
await send(0, remotePeer, op.forward, message.transaction, sender);+91
} else if (role === 'a' && index === 0 && message.operation === op.deliverStored) {+92
const stored = entries.get(id);+93
if (!stored || stored.delivered) return;+94
stored.delivered = true;+95
// The destination was observed by lookup, never supplied by this request.+96
await send(0, stored.sender, op.probe, message.transaction);+97
await send(0, sender, op.sent, message.transaction);+98
}+99
};+100
try {+101
for (let index = 0; index < ports.length; index += 1) {+102
const socket = createSocket('udp4');+103
sockets.push(socket);+104
socket.on('error', error => { errors.push(error.code ?? 'socket-error'); void close(); });+105
socket.on('message', (bytes, source) => {+106
void handle(index, bytes, source).catch(error => {+107
errors.push(error.code ?? 'send-error');+108
void close();+109
});+110
});+111
socket.bind(ports[index], bindAddress);+112
await once(socket, 'listening');+113
if (closing) throw new Error('Reflector stopped during binding');+114
}+115
const endpoints = sockets.map(socket => ({ address: bindAddress, port: socket.address().port }));+116
timer = setTimeout(() => { void close(); }, lifetimeMs);+117
return { endpoints, counts, errors, close, closed,+118
setPeer(endpoint) {+119
if (remotePeer) throw new Error('Reflector peer is already fixed');+120
remotePeer = probeEndpoint(endpoint);+121
} };+122
} catch (error) { await close(); throw error; }+123
}tools/nat/nat-probe-socket.mjsadded
@@ -0,0 +1,87 @@
+1
import { createSocket } from 'node:dgram';+2
import { randomBytes } from 'node:crypto';+3
import { once } from 'node:events';+4
import { isIP } from 'node:net';+5
import { closeUdpSocket } from './socket-cleanup.mjs';+6
import { decodeProbeMessage, encodeProbeMessage, sameEndpoint, probeEndpoint,+7
probeOperations as op } from './nat-probe-wire.mjs';+8
+9
export async function openNatProbeSocket({ localAddress, token, usedPorts = new Set(), signal }) {+10
if (isIP(localAddress) !== 4 || !Buffer.isBuffer(token) || token.length !== 32)+11
throw new Error('Invalid NAT probe socket configuration');+12
for (let attempt = 0; attempt < 8; attempt += 1) {+13
signal?.throwIfAborted();+14
const port = 49152 + randomBytes(2).readUInt16BE(0) % 16384;+15
if (usedPorts.has(port)) continue;+16
const socket = createSocket('udp4');+17
const watchers = new Map();+18
const counts = { outbound: 0, received: 0, ignored: 0 };+19
let fault;+20
let closing;+21
const stopWatchers = () => { for (const watcher of [...watchers.values()]) watcher.finish(); };+22
const close = () => {+23
if (closing) return closing;+24
stopWatchers();+25
signal?.removeEventListener('abort', aborted);+26
closing = closeUdpSocket(socket);+27
return closing;+28
};+29
const aborted = () => { fault = signal.reason; void close(); };+30
socket.on('error', error => { fault = error; stopWatchers(); });+31
socket.on('message', (bytes, source) => {+32
counts.received += 1;+33
if (counts.received > 128) { fault = new Error('Probe receive budget'); void close(); return; }+34
let message;+35
try { message = decodeProbeMessage(bytes, token); }+36
catch { counts.ignored += 1; return; }+37
const watcher = watchers.get(message.transaction.toString('hex'));+38
const expected = watcher?.expected[message.operation];+39
if (!watcher || !sameEndpoint(expected, source) ||+40
(message.operation === op.observed ? !message.endpoint : Boolean(message.endpoint))) {+41
counts.ignored += 1; return;+42
}+43
watcher.messages[message.operation] = message;+44
if (watcher.required.every(operation => watcher.messages[operation])) watcher.finish();+45
});+46
try {+47
socket.bind(port, localAddress);+48
await once(socket, 'listening');+49
} catch (error) {+50
await close();+51
if (error.code === 'EADDRINUSE') continue;+52
throw error;+53
}+54
usedPorts.add(port);+55
signal?.addEventListener('abort', aborted, { once: true });+56
if (signal?.aborted) { aborted(); await close(); signal.throwIfAborted(); }+57
return { port, counts, close,+58
watch({ transaction, expected, required, timeoutMs }) {+59
signal?.throwIfAborted();+60
if (closing || fault || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 5000)+61
throw new Error('Probe watch unavailable or invalid deadline');+62
const id = transaction.toString('hex');+63
if (watchers.has(id) || watchers.size >= 8) throw new Error('Duplicate/excessive probe waiter');+64
let done;+65
const result = new Promise(resolve => { done = resolve; });+66
const watcher = { expected, required, messages: {}, timer: undefined,+67
finish() {+68
if (!watchers.delete(id)) return;+69
clearTimeout(watcher.timer);+70
done({ messages: watcher.messages, failed: Boolean(fault || closing) });+71
} };+72
watchers.set(id, watcher);+73
watcher.timer = setTimeout(watcher.finish, timeoutMs);+74
return result;+75
},+76
async send(operation, destination, transaction) {+77
signal?.throwIfAborted();+78
if (closing || fault || counts.outbound >= 32) throw new Error('Probe socket stopped or packet budget exceeded');+79
probeEndpoint(destination);+80
const packet = encodeProbeMessage({ token, transaction, operation });+81
counts.outbound += 1;+82
await new Promise((done, reject) => socket.send(packet, destination.port, destination.address,+83
error => error ? reject(error) : done()));+84
} };+85
}+86
throw new Error('No unused random source port in bounded allocation attempts');+87
}tools/nat/nat-probe-wire.mjsmodified
@@ -52,8 +52,15 @@ export function sameEndpoint(first, second) {
52
return Boolean(first && second && first.address === second.address && first.port === second.port); 53
} 54
export function validateProbeReflectors({ a1, a2, b }) {+55
validateSingleHostReflectors({ a1, a2 }); 56
for (const endpoint of [a1, a2, b]) probeEndpoint(endpoint); 57
if (a1.address !== a2.address || a1.port === a2.port || a1.address === b.address) 58
throw new Error('Probe needs two different IPv4 addresses and two ports on A'); 59
return { a1: { ...a1 }, a2: { ...a2 }, b: { ...b } }; 60
}+61
export function validateSingleHostReflectors({ a1, a2 }) {+62
for (const endpoint of [a1, a2]) probeEndpoint(endpoint);+63
if (a1.address !== a2.address || a1.port === a2.port)+64
throw new Error('Single-host probe needs two ports on A with one IPv4 address and different port numbers');+65
return { a1: { ...a1 }, a2: { ...a2 } };+66
}tools/nat/nat-probe.mjsadded
@@ -0,0 +1,117 @@
+1
// Outbound-only RFC-style observations over the private probe wire protocol.+2
import { randomBytes } from 'node:crypto';+3
import { performance } from 'node:perf_hooks';+4
import { setTimeout as delay } from 'node:timers/promises';+5
import { openNatProbeSocket } from './nat-probe-socket.mjs';+6
import { validateProbeReflectors, validateSingleHostReflectors, probeOperations as op } from './nat-probe-wire.mjs';+7
import { summarizeNatProbe, summarizeSingleHostNatProbe } from './nat-probe-analysis.mjs';+8
+9
async function lookup(channel, destination, timeoutMs, transaction = randomBytes(12)) {+10
const result = channel.watch({ transaction, expected: { [op.observed]: destination },+11
required: [op.observed], timeoutMs });+12
await channel.send(op.lookup, destination, transaction);+13
const response = await result;+14
return { sent: true, matched: !response.failed && Boolean(response.messages[op.observed]),+15
observed: response.messages[op.observed]?.endpoint, transaction };+16
}+17
async function alternate(channel, primary, expectedProbe, operation, timeoutMs) {+18
const transaction = randomBytes(12);+19
const result = channel.watch({ transaction,+20
expected: { [op.sent]: primary, [op.probe]: expectedProbe }, required: [op.sent, op.probe], timeoutMs });+21
await channel.send(operation, primary, transaction);+22
const response = await result;+23
return { sent: true, ackMatched: !response.failed && Boolean(response.messages[op.sent]),+24
received: !response.failed && Boolean(response.messages[op.probe]) };+25
}+26
export async function runNatProbe({ localAddress, reflectors, token, mappingSamples = 3,+27
idleMs = [15000, 30000, 60000, 120000], timeoutMs = 1500, deadlineMs = 180000, signal }) {+28
const singleHost = reflectors?.b === undefined;+29
const topology = singleHost ? validateSingleHostReflectors(reflectors) : validateProbeReflectors(reflectors);+30
if (!Number.isInteger(mappingSamples) || mappingSamples < 3 || mappingSamples > 5 ||+31
!Array.isArray(idleMs) || idleMs.length < 1 || idleMs.length > 4 ||+32
new Set(idleMs).size !== idleMs.length || idleMs.some(value => !Number.isInteger(value) || value < 1 || value > 120000) ||+33
!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 5000 ||+34
!Number.isInteger(deadlineMs) || deadlineMs < 1 || deadlineMs > 240000)+35
throw new Error('Invalid bounded NAT probe plan');+36
const abort = new AbortController();+37
const cancel = () => abort.abort(signal.reason);+38
signal?.addEventListener('abort', cancel, { once: true });+39
if (signal?.aborted) cancel();+40
const deadline = setTimeout(() => abort.abort(new Error('NAT probe overall deadline')), deadlineMs);+41
const channels = [];+42
const usedPorts = new Set();+43
const started = performance.now();+44
const open = async () => {+45
abort.signal.throwIfAborted();+46
const channel = await openNatProbeSocket({ localAddress, token, usedPorts, signal: abort.signal });+47
channels.push(channel);+48
return channel;+49
};+50
try {+51
const control = await open();+52
const positive = {+53
primary: (await lookup(control, topology.a1, timeoutMs)).matched,+54
alternatePort: (await lookup(control, topology.a2, timeoutMs)).matched,+55
};+56
if (!singleHost) positive.alternateAddress = (await lookup(control, topology.b, timeoutMs)).matched;+57
if (!Object.values(positive).every(Boolean)) {+58
const error = new Error('NAT probe reflector connectivity precondition failed');+59
error.code = 'PROBE_SETUP_FAILED';+60
error.controls = positive;+61
throw error;+62
}+63
const mapping = [], filtering = [];+64
for (let index = 0; index < mappingSamples; index += 1) {+65
const data = await open();+66
const a1 = await lookup(data, topology.a1, timeoutMs);+67
// This source port has contacted A1 only. Control-socket preflights cannot+68
// establish permissions for this separate measured source port.+69
const alternateAddress = singleHost ? undefined+70
: await alternate(data, topology.a1, topology.b, op.alternateAddress, timeoutMs);+71
const alternatePort = await alternate(data, topology.a1, topology.a2, op.alternatePort, timeoutMs);+72
const recoveredPrimary = (await lookup(data, topology.a1, timeoutMs)).matched;+73
filtering.push({ localPort: data.port, controls: { ...positive, primary: a1.matched, recoveredPrimary },+74
alternateAddress, alternatePort, outboundDestinationsBeforeFiltering: ['a1'] });+75
const a2 = await lookup(data, topology.a2, timeoutMs);+76
const b = singleHost ? undefined : await lookup(data, topology.b, timeoutMs);+77
const repeatedA1 = await lookup(data, topology.a1, timeoutMs);+78
mapping.push({ localPort: data.port, a1, a2, b, repeatedA1 });+79
}+80
// Start with distinct data sockets, kept open throughout. Each sends one+81
// lookup, then stays receive-only; probes are requested via control instead.+82
const idlePlans = [];+83
for (const requestedIdleMs of idleMs) {+84
const data = await open();+85
const initial = await lookup(data, topology.a1, timeoutMs);+86
idlePlans.push({ data, initial, requestedIdleMs, idleStart: performance.now() });+87
}+88
const lifetime = await Promise.all(idlePlans.map(async ({ data, initial, requestedIdleMs, idleStart }) => {+89
await delay(Math.max(0, requestedIdleMs - (performance.now() - idleStart)), undefined, { signal: abort.signal });+90
// A lookup on the measured socket here would reset its NAT mapping.+91
const delivered = data.watch({ transaction: initial.transaction,+92
expected: { [op.probe]: topology.a1 }, required: [op.probe], timeoutMs });+93
const acknowledged = control.watch({ transaction: initial.transaction,+94
expected: { [op.sent]: topology.a1 }, required: [op.sent], timeoutMs });+95
const idleAtRequestMs = performance.now() - idleStart;+96
await control.send(op.deliverStored, topology.a1, initial.transaction);+97
const [response, ack] = await Promise.all([delivered, acknowledged]);+98
const controlHealthy = (await lookup(control, topology.a1, timeoutMs)).matched;+99
return { localPort: data.port, idleMs: requestedIdleMs, actualIdleAtRequestMs: idleAtRequestMs,+100
outboundPackets: data.counts.outbound, established: initial.matched,+101
probeSent: !ack.failed && Boolean(ack.messages[op.sent]),+102
ackMatched: !ack.failed && Boolean(ack.messages[op.sent]),+103
controlHealthy, received: !response.failed && Boolean(response.messages[op.probe]) };+104
}));+105
abort.signal.throwIfAborted();+106
const summary = (singleHost ? summarizeSingleHostNatProbe : summarizeNatProbe)({ mapping, filtering, lifetime });+107
summary.durationMs = Number((performance.now() - started).toFixed(3));+108
summary.packetCounts = channels.reduce((total, channel) => ({ outbound: total.outbound + channel.counts.outbound,+109
received: total.received + channel.counts.received }), { outbound: 0, received: 0 });+110
return { summary, details: { reflectors: topology, localAddress, mapping, filtering, lifetime,+111
sourcePorts: channels.map(channel => channel.port) } };+112
} finally {+113
clearTimeout(deadline);+114
signal?.removeEventListener('abort', cancel);+115
await Promise.all(channels.map(channel => channel.close()));+116
}+117
}tools/nat/reflectors/nat-probe.pladded
@@ -0,0 +1,106 @@
+1
#!/usr/bin/perl+2
# Base-Perl two-port reflector. Private fixed-size protocol; not a STUN server.+3
use strict;+4
use warnings;+5
use IO::Socket::INET;+6
use IO::Select;+7
use Socket qw(sockaddr_in inet_aton inet_ntoa);+8
use Time::HiRes qw(time);+9
use Fcntl qw(O_WRONLY O_CREAT O_EXCL);+10
+11
my $config_path = shift @ARGV or die "Private config path required\n";+12
my @info = stat($config_path);+13
die "Config must be private and owned\n" unless @info && $info[4] == $< && ($info[2] & 077) == 0 && $info[7] <= 8192;+14
open(my $config, '<', $config_path) or die "Cannot read private config\n";+15
my @lines = <$config>;+16
close($config);+17
chomp(@lines);+18
my ($bind, $token_hex, $lifetime_ms, $state_path) = @lines;+19
die "Invalid bounded reflector config\n" unless @lines == 4 &&+20
defined($bind) && $bind =~ /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/ &&+21
defined($token_hex) && $token_hex =~ /^[0-9a-f]{64}$/ &&+22
defined($lifetime_ms) && $lifetime_ms =~ /^[0-9]+$/ && $lifetime_ms >= 1 && $lifetime_ms <= 900000 &&+23
defined($state_path) && $state_path =~ m{^/} && $state_path !~ /[\x00-\x1f]/;+24
my @octets = split(/\./, $bind);+25
die "Bind must name an exact unicast IPv4 interface\n" if grep { $_ > 255 } @octets;+26
die "Bind must name an exact unicast IPv4 interface\n" if $octets[0] == 0 || $octets[0] >= 224;+27
my $token = pack('H*', $token_hex);+28
my @sockets;+29
for (1..2) {+30
my $socket = IO::Socket::INET->new(LocalAddr => $bind, LocalPort => 0, Proto => 'udp')+31
or die "Cannot bind owned UDP socket\n";+32
die "Kernel selected a low UDP port\n" if $socket->sockport < 1024;+33
push @sockets, $socket;+34
}+35
my @ports = map { $_->sockport } @sockets;+36
my $selector = IO::Select->new(@sockets);+37
my $running = 1;+38
$SIG{TERM} = sub { $running = 0; };+39
$SIG{INT} = sub { $running = 0; };+40
$SIG{ALRM} = sub { $running = 0; };+41
alarm(int(($lifetime_ms + 999) / 1000));+42
my $end = time() + $lifetime_ms / 1000;+43
my ($received, $accepted, $sent, $errors) = (0, 0, 0, 0);+44
my %entries;+45
my $client_address;+46
sub record_file {+47
my ($path, $json) = @_;+48
sysopen(my $file, $path, O_WRONLY | O_CREAT | O_EXCL, 0600) or die "Cannot create private reflector receipt\n";+49
print {$file} $json, "\n";+50
close($file) or die "Cannot finish private reflector receipt\n";+51
}+52
sub send_packet {+53
my ($socket, $target, $transaction, $operation, $address, $port) = @_;+54
return 0 unless $running && $sent < 256;+55
my $bytes = pack('a4a32a12Ca4na9', 'SNP1', $token, $transaction, $operation,+56
defined($address) ? $address : "\0" x 4, defined($port) ? $port : 0, "\0" x 9);+57
my $written = $socket->send($bytes, 0, $target);+58
if (!defined($written) || $written != 64) { $errors++; return 0; }+59
$sent++;+60
return 1;+61
}+62
record_file($state_path, '{"pid":' . $$ . ',"address":"' . $bind . '","ports":[' . join(',', @ports) . '],"ready":true}');+63
$| = 1;+64
print "RESULT reflector-ready sockets=2 lifetimeMs=$lifetime_ms\n";+65
while ($running && time() < $end && $received < 512 && $sent < 256) {+66
for my $socket ($selector->can_read(0.1)) {+67
my $bytes = '';+68
my $source = $socket->recv($bytes, 65);+69
$received++;+70
next unless defined($source) && length($bytes) == 64;+71
my ($magic, $supplied_token, $transaction, $operation, $target_address, $target_port, $reserved) =+72
unpack('a4a32a12Ca4na9', $bytes);+73
next unless $magic eq 'SNP1' && $supplied_token eq $token && $reserved eq "\0" x 9 &&+74
$target_address eq "\0" x 4 && $target_port == 0;+75
my ($source_port, $source_address) = sockaddr_in($source);+76
next if $source_port < 1024;+77
# Only the first valid run-token holder's observed IP is admitted. Tokens+78
# stay in private config/receipts and are never returned to another IP.+79
$client_address = $source_address unless defined($client_address);+80
next unless $client_address eq $source_address;+81
$accepted++;+82
my $id = unpack('H*', $transaction);+83
if ($operation == 1) {+84
next if exists($entries{$id}) && $entries{$id}->{source} ne $source;+85
next if !exists($entries{$id}) && scalar(keys(%entries)) >= 64;+86
$entries{$id} //= { source => $source, delivered => 0 };+87
send_packet($socket, $source, $transaction, 2, $source_address, $source_port);+88
} elsif ($socket == $sockets[0] && $operation == 3) {+89
if (send_packet($sockets[1], $source, $transaction, 6, undef, undef)) {+90
send_packet($sockets[0], $source, $transaction, 7, undef, undef);+91
}+92
} elsif ($socket == $sockets[0] && $operation == 8) {+93
my $entry = $entries{$id};+94
next unless $entry && !$entry->{delivered};+95
$entry->{delivered} = 1;+96
if (send_packet($sockets[0], $entry->{source}, $transaction, 6, undef, undef)) {+97
send_packet($sockets[0], $source, $transaction, 7, undef, undef);+98
}+99
}+100
}+101
}+102
alarm(0);+103
for my $socket (@sockets) { close($socket); }+104
record_file($state_path . '.done', '{"stopped":true,"received":' . $received . ',"accepted":' . $accepted . ',"sent":' . $sent . ',"errors":' . $errors . '}');+105
print "RESULT reflector-stopped sockets=2 received=$received sent=$sent errors=$errors\n";+106
exit($errors ? 1 : 0);tools/nat/test-nat-probe-perl.mjsadded
@@ -0,0 +1,63 @@
+1
import assert from 'node:assert/strict';+2
import { test } from 'node:test';+3
import { spawn } from 'node:child_process';+4
import { randomBytes } from 'node:crypto';+5
import { mkdirSync, mkdtempSync, writeFileSync, readFileSync, existsSync } from 'node:fs';+6
import { resolve, join } from 'node:path';+7
import { setTimeout as delay } from 'node:timers/promises';+8
import { runNatProbe } from './nat-probe.mjs';+9
import { openNatProbeSocket } from './nat-probe-socket.mjs';+10
import { probeOperations as op } from './nat-probe-wire.mjs';+11
+12
+13
test('base Perl reflector interoperates over real UDP and single-host results leave IP dependence unmeasured', async t => {+14
mkdirSync('build/nat-probe', { recursive: true });+15
const directory = mkdtempSync(resolve('build/nat-probe/perl-'));+16
const token = randomBytes(32);+17
const statePath = join(directory, 'state.json');+18
const config = join(directory, 'config.txt');+19
writeFileSync(config, ['127.0.0.1', token.toString('hex'), '3000', statePath, ''].join('\n'), { mode: 0o600 });+20
const child = spawn('perl', ['tools/nat/reflectors/nat-probe.pl', config], { stdio: ['ignore', 'pipe', 'pipe'] });+21
let ended = false, code;+22
let output = '', errors = '';+23
child.stdout.on('data', bytes => { if (output.length < 4096) output += bytes; });+24
child.stderr.on('data', bytes => { if (errors.length < 4096) errors += bytes; });+25
const closed = new Promise(done => {+26
child.once('error', error => { errors += error.code; });+27
child.once('close', value => { ended = true; code = value; done(); });+28
});+29
t.after(async () => {+30
if (!ended) child.kill('SIGTERM'); // Exact admitted child PID.+31
if (!await Promise.race([closed.then(() => true), delay(2000).then(() => false)])) child.kill('SIGKILL');+32
await closed;+33
writeFileSync(join(directory, 'stdout.log'), output, { mode: 0o600 });+34
writeFileSync(join(directory, 'stderr.log'), errors, { mode: 0o600 });+35
assert.equal(code, 0, 'Perl reflector must complete owned shutdown');+36
assert.equal(JSON.parse(readFileSync(statePath + '.done')).stopped, true);+37
});+38
const readyDeadline = performance.now() + 2000;+39
while (!existsSync(statePath)) {+40
if (ended || performance.now() > readyDeadline) throw new Error('Perl reflector setup failed: ' + errors);+41
await delay(10);+42
}+43
const state = JSON.parse(readFileSync(statePath));+44
assert.equal(state.pid, child.pid);+45
const foreign = await openNatProbeSocket({ localAddress: '127.0.0.4', token: Buffer.alloc(32) });+46
const transaction = randomBytes(12);+47
const invalid = foreign.watch({ transaction, expected: { [op.observed]: { address: state.address, port: state.ports[0] } },+48
required: [op.observed], timeoutMs: 40 });+49
await foreign.send(op.lookup, { address: state.address, port: state.ports[0] }, transaction);+50
assert.equal((await invalid).messages[op.observed], undefined);+51
await foreign.close();+52
const result = await runNatProbe({ localAddress: '127.0.0.3', token,+53
reflectors: { a1: { address: state.address, port: state.ports[0] },+54
a2: { address: state.address, port: state.ports[1] } },+55
idleMs: [20, 40, 80, 120], timeoutMs: 250, deadlineMs: 2500 });+56
assert.deepEqual(result.summary.mapping, { 'port-independent-for-tested-address': 3 });+57
assert.deepEqual(result.summary.filtering, { 'alternate-port-allowed': 3 });+58
assert.equal(result.summary.addressDependence, 'unmeasured-single-reflector-IP');+59
assert.equal(result.summary.lifetime.lowerBoundSeconds, 0.12);+60
assert.ok(result.details.lifetime.every(sample => sample.outboundPackets === 1 && sample.received));+61
assert.doesNotMatch(JSON.stringify(result.summary), /127\.0\.0/);+62
assert.equal(errors, '');+63
});tools/nat/test-nat-probe-runtime.mjsadded
@@ -0,0 +1,91 @@
+1
import assert from 'node:assert/strict';+2
import { test } from 'node:test';+3
import { randomBytes } from 'node:crypto';+4
import { createSocket } from 'node:dgram';+5
import { once } from 'node:events';+6
import { openNatProbeReflector } from './nat-probe-reflector.mjs';+7
import { openNatProbeSocket } from './nat-probe-socket.mjs';+8
import { runNatProbe } from './nat-probe.mjs';+9
import { closeUdpSocket } from './socket-cleanup.mjs';+10
import { encodeProbeMessage, probeOperations as op } from './nat-probe-wire.mjs';+11
+12
async function reflectors(t, { lifetimeMs = 5000, wrongPeer = false } = {}) {+13
const token = randomBytes(32);+14
const a = await openNatProbeReflector({ role: 'a', bindAddress: '127.0.0.1', ports: [0, 0], token,+15
clientAddresses: ['127.0.0.3'], lifetimeMs });+16
t.after(() => a.close());+17
const b = await openNatProbeReflector({ role: 'b', bindAddress: '127.0.0.2', ports: [0], token,+18
clientAddresses: ['127.0.0.3'], peer: wrongPeer ? a.endpoints[1] : a.endpoints[0], lifetimeMs });+19
t.after(() => b.close());+20
a.setPeer(b.endpoints[0]);+21
return { a, b, token, topology: { a1: a.endpoints[0], a2: a.endpoints[1], b: b.endpoints[0] } };+22
}+23
+24
test('real UDP client measures all mapping/filtering channels and isolated idle sockets', async t => {+25
const hosts = await reflectors(t);+26
const result = await runNatProbe({ localAddress: '127.0.0.3', token: hosts.token,+27
reflectors: hosts.topology, idleMs: [20, 40, 80, 120], timeoutMs: 250, deadlineMs: 4000 });+28
assert.deepEqual(result.summary.mapping, { 'endpoint-independent': 3 });+29
assert.deepEqual(result.summary.filtering, { 'endpoint-independent': 3 });+30
assert.equal(result.summary.portPreservation.preserved, 3);+31
assert.equal(result.summary.lifetime.trials.length, 4);+32
assert.equal(result.summary.lifetime.lowerBoundSeconds, 0.12);+33
assert.equal(result.summary.lifetime.inconclusiveCount, 0);+34
assert.ok(result.details.lifetime.every(sample => sample.outboundPackets === 1 && sample.received && sample.ackMatched));+35
assert.ok(result.details.filtering.every(sample =>+36
JSON.stringify(sample.outboundDestinationsBeforeFiltering) === '["a1"]'));+37
assert.equal(new Set(result.details.sourcePorts).size, 8);+38
assert.ok(result.summary.packetCounts.outbound > 0);+39
assert.doesNotMatch(JSON.stringify(result.summary), /127\.0\.0/);+40
assert.equal(hosts.a.errors.length, 0);+41
assert.equal(hosts.b.errors.length, 0);+42
await hosts.a.close(); await hosts.b.close();+43
assert.ok(hosts.a.counts.sent > 0 && hosts.b.counts.sent > 0);+44
});+45
+46
test('missing alternate-host forwarding acknowledgement stays inconclusive', async t => {+47
const hosts = await reflectors(t, { wrongPeer: true });+48
const result = await runNatProbe({ localAddress: '127.0.0.3', token: hosts.token,+49
reflectors: hosts.topology, idleMs: [20], timeoutMs: 40, deadlineMs: 4000 });+50
// Direct connectivity to B succeeds; B rejects only the unadmitted forwarder.+51
assert.deepEqual(result.summary.mapping, { 'endpoint-independent': 3 });+52
assert.deepEqual(result.summary.filtering, { inconclusive: 3 });+53
assert.ok(result.details.filtering.every(sample => !sample.alternateAddress.ackMatched));+54
});+55
+56
test('foreign run tokens receive no reply; the correct token remains a positive control', async t => {+57
const hosts = await reflectors(t);+58
const socket = createSocket('udp4');+59
t.after(() => closeUdpSocket(socket));+60
socket.bind(0, '127.0.0.3');+61
await once(socket, 'listening');+62
let replies = 0;+63
socket.on('message', () => { replies += 1; });+64
const packet = encodeProbeMessage({ token: Buffer.alloc(32), transaction: Buffer.alloc(12), operation: op.lookup });+65
await new Promise((done, reject) => socket.send(packet, hosts.topology.a1.port, hosts.topology.a1.address,+66
error => error ? reject(error) : done()));+67
await new Promise(done => setTimeout(done, 30));+68
assert.equal(replies, 0);+69
const channel = await openNatProbeSocket({ localAddress: '127.0.0.3', token: hosts.token });+70
t.after(() => channel.close());+71
const transaction = randomBytes(12);+72
const response = channel.watch({ transaction, expected: { [op.observed]: hosts.topology.a1 },+73
required: [op.observed], timeoutMs: 250 });+74
await channel.send(op.lookup, hosts.topology.a1, transaction);+75
assert.ok((await response).messages[op.observed]);+76
});+77
+78
test('overall deadline aborts idle waits and closes client sockets', async t => {+79
const hosts = await reflectors(t);+80
await assert.rejects(runNatProbe({ localAddress: '127.0.0.3', token: hosts.token,+81
reflectors: hosts.topology, idleMs: [1000], timeoutMs: 100, deadlineMs: 100 }), /abort|deadline/i);+82
assert.equal(hosts.a.errors.length, 0);+83
});+84
+85
test('reflectors expire automatically and repeated close is safe', async t => {+86
const hosts = await reflectors(t, { lifetimeMs: 100 });+87
await Promise.all([hosts.a.closed, hosts.b.closed]);+88
await Promise.all([hosts.a.close(), hosts.a.close(), hosts.b.close()]);+89
assert.equal(hosts.a.errors.length, 0);+90
assert.equal(hosts.b.errors.length, 0);+91
});tools/nat/test-nat-probe.mjsmodified
@@ -3,7 +3,7 @@ import { test } from 'node:test';
3
import { encodeProbeMessage, decodeProbeMessage, validateProbeReflectors, 4
probeOperations as op } from './nat-probe-wire.mjs'; 5
import { classifyProbeMapping, classifyProbeFiltering, summarizeProbeLifetime,−6
summarizeNatProbe } from './nat-probe-analysis.mjs';+6
summarizeNatProbe, summarizeSingleHostNatProbe } from './nat-probe-analysis.mjs'; 7
8
const token = Buffer.alloc(32, 0x11), transaction = Buffer.alloc(12, 0x22); 9
const observed = port => ({ sent: true, matched: true, observed: { address: '198.51.100.1', port } });@@ -90,3 +90,14 @@ test('public summary exposes counts/classifications/timings without addresses or
90
assert.throws(() => summarizeNatProbe({ mapping: [baseline(), baseline(), baseline()], 91
filtering: [{ controls, alternateAddress: filter(true) }], lifetime: [] }), /different local/); 92
});+93
+94
test('single-host evidence never invents an address-dependence classification', () => {+95
const summary = summarizeSingleHostNatProbe({ mapping: [baseline(45000),+96
{ ...baseline(45010), a2: observed(50000) }, baseline(45020)],+97
filtering: [{ controls, alternatePort: filter(true) },+98
{ controls, alternatePort: filter(false) },+99
{ controls, alternatePort: { ...filter(false), ackMatched: false } }], lifetime: [] });+100
assert.deepEqual(summary.mapping, { 'port-independent-for-tested-address': 2, 'port-dependent-for-tested-address': 1 });+101
assert.deepEqual(summary.filtering, { 'alternate-port-allowed': 1, 'alternate-port-not-observed': 1, inconclusive: 1 });+102
assert.equal(summary.addressDependence, 'unmeasured-single-reflector-IP');+103
});