Commitdb67eee5Recorded18 Oct 2026Repositorysigil-nat
Allow explicit ports for firewall-scoped NAT reflectors
Changed
README.md | 7 +++++--
tools/nat/reflectors/nat-probe.pl | 12 ++++++++----
tools/nat/test-nat-probe-perl.mjs | 114 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------------------------------------
3 files changed, 77 insertions(+), 56 deletions(-)Diff
README.mdmodified
@@ -32,9 +32,12 @@ 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.+35
base Perl modules and two high UDP 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+37
lifetime milliseconds (at most 900000), and absolute receipt path. Two optional+38
additional lines select distinct explicit ports (1024..65535); omit both for+39
kernel-selected ephemeral ports. An occupied explicit port fails without+40
fallback, so firewall-scoped runs never bind outside their admitted range. It latches 41
the first valid token holder's source IP, responds only to that client, and 42
can deliver idle probes only to tuples it previously observed. Packet/state 43
budgets and expiry bound the listener. Its private receipt records its PIDtools/nat/reflectors/nat-probe.plmodified
@@ -15,8 +15,8 @@ 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 &&+18
my ($bind, $token_hex, $lifetime_ms, $state_path, @requested_ports) = @lines;+19
die "Invalid bounded reflector config\n" unless (@lines == 4 || @lines == 6) && 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 &&@@ -24,10 +24,14 @@ die "Invalid bounded reflector config\n" unless @lines == 4 &&
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
die "Explicit ports must be distinct high UDP ports\n" if @requested_ports &&+28
(grep { !/^[0-9]+$/ || $_ < 1024 || $_ > 65535 } @requested_ports);+29
die "Explicit ports must be distinct high UDP ports\n" if @requested_ports && $requested_ports[0] == $requested_ports[1];+30
@requested_ports = (0, 0) unless @requested_ports; 31
my $token = pack('H*', $token_hex); 32
my @sockets;−29
for (1..2) {−30
my $socket = IO::Socket::INET->new(LocalAddr => $bind, LocalPort => 0, Proto => 'udp')+33
for my $port (@requested_ports) {+34
my $socket = IO::Socket::INET->new(LocalAddr => $bind, LocalPort => $port, Proto => 'udp') 35
or die "Cannot bind owned UDP socket\n"; 36
die "Kernel selected a low UDP port\n" if $socket->sockport < 1024; 37
push @sockets, $socket;tools/nat/test-nat-probe-perl.mjsmodified
@@ -10,54 +10,68 @@ 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(); });+13
for (const explicitPorts of [false, true]) {+14
test('base Perl reflector real UDP interoperability with ' + (explicitPorts ? 'explicit' : 'ephemeral') + ' ports', async t => {+15
mkdirSync('build/nat-probe', { recursive: true });+16
const directory = mkdtempSync(resolve('build/nat-probe/perl-'));+17
const token = randomBytes(32);+18
const statePath = join(directory, 'state.json');+19
const config = join(directory, 'config.txt');+20
const requestedPorts = [];+21
if (explicitPorts) {+22
const usedPorts = new Set();+23
const first = await openNatProbeSocket({ localAddress: '127.0.0.1', token, usedPorts });+24
t.after(() => first.close());+25
const second = await openNatProbeSocket({ localAddress: '127.0.0.1', token, usedPorts });+26
t.after(() => second.close());+27
requestedPorts.push(first.port, second.port);+28
await Promise.all([first.close(), second.close()]);+29
}+30
writeFileSync(config, ['127.0.0.1', token.toString('hex'), '3000', statePath,+31
...requestedPorts, ''].join('\n'), { mode: 0o600 });+32
const child = spawn('perl', ['tools/nat/reflectors/nat-probe.pl', config], { stdio: ['ignore', 'pipe', 'pipe'] });+33
let ended = false, code;+34
let output = '', errors = '';+35
child.stdout.on('data', bytes => { if (output.length < 4096) output += bytes; });+36
child.stderr.on('data', bytes => { if (errors.length < 4096) errors += bytes; });+37
const closed = new Promise(done => {+38
child.once('error', error => { errors += error.code; });+39
child.once('close', value => { ended = true; code = value; done(); });+40
});+41
t.after(async () => {+42
if (!ended) child.kill('SIGTERM'); // Exact admitted child PID.+43
if (!await Promise.race([closed.then(() => true), delay(2000).then(() => false)])) child.kill('SIGKILL');+44
await closed;+45
writeFileSync(join(directory, 'stdout.log'), output, { mode: 0o600 });+46
writeFileSync(join(directory, 'stderr.log'), errors, { mode: 0o600 });+47
assert.equal(code, 0, 'Perl reflector must complete owned shutdown');+48
assert.equal(JSON.parse(readFileSync(statePath + '.done')).stopped, true);+49
});+50
const readyDeadline = performance.now() + 2000;+51
while (!existsSync(statePath)) {+52
if (ended || performance.now() > readyDeadline) throw new Error('Perl reflector setup failed: ' + errors);+53
await delay(10);+54
}+55
const state = JSON.parse(readFileSync(statePath));+56
assert.equal(state.pid, child.pid);+57
if (explicitPorts) assert.deepEqual(state.ports, requestedPorts);+58
const foreign = await openNatProbeSocket({ localAddress: '127.0.0.4', token: Buffer.alloc(32) });+59
const transaction = randomBytes(12);+60
const invalid = foreign.watch({ transaction, expected: { [op.observed]: { address: state.address, port: state.ports[0] } },+61
required: [op.observed], timeoutMs: 40 });+62
await foreign.send(op.lookup, { address: state.address, port: state.ports[0] }, transaction);+63
assert.equal((await invalid).messages[op.observed], undefined);+64
await foreign.close();+65
const result = await runNatProbe({ localAddress: '127.0.0.3', token,+66
reflectors: { a1: { address: state.address, port: state.ports[0] },+67
a2: { address: state.address, port: state.ports[1] } },+68
idleMs: [20, 40, 80, 120], timeoutMs: 250, deadlineMs: 2500 });+69
assert.deepEqual(result.summary.mapping, { 'port-independent-for-tested-address': 3 });+70
assert.deepEqual(result.summary.filtering, { 'alternate-port-allowed': 3 });+71
assert.equal(result.summary.addressDependence, 'unmeasured-single-reflector-IP');+72
assert.equal(result.summary.lifetime.lowerBoundSeconds, 0.12);+73
assert.ok(result.details.lifetime.every(sample => sample.outboundPackets === 1 && sample.received));+74
assert.doesNotMatch(JSON.stringify(result.summary), /127\.0\.0/);+75
assert.equal(errors, ''); 76
});−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
});+77
}