AtlatestRepositorysigil-nat
1
// PCP RFC 6887 sections 7/11/14; NAT-PMP RFC 6886 sections 3.2–3.4.2
// Pure codecs: no sockets, implicit requests, wildcard mappings or crypto.3
import { isIP } from 'node:net';5
function check(value, message) { if (!value) throw new Error(message); }6
function integer(value, maximum, label, minimum = 0) {7
check(Number.isInteger(value) && value >= minimum && value <= maximum, `Invalid ${label}`);8
}9
export function ipv4Bytes(address) {10
check(isIP(address) === 4, 'Expected an IPv4 address');11
return Buffer.from(address.split('.').map(Number));12
}13
export function mappedAddress(address) {14
const bytes = Buffer.alloc(16);15
bytes[10] = 255; bytes[11] = 255; ipv4Bytes(address).copy(bytes, 12);16
return bytes;17
}18
function readAddress(bytes) {19
if (bytes.subarray(0, 10).every(octet => octet === 0) && bytes[10] === 255 && bytes[11] === 255)20
return [...bytes.subarray(12)].join('.');21
return Array.from({ length: 8 }, (_, index) => bytes.readUInt16BE(index * 2).toString(16)).join(':');22
}23
function mappingFields({ protocol = 17, internalPort, externalPort = 0, lifetime }) {24
check(protocol === 17 || protocol === 6, 'Only a single UDP/TCP mapping is supported');25
integer(internalPort, 65535, 'internal port', 1);26
integer(externalPort, 65535, 'external port');27
integer(lifetime, 7200, 'bounded mapping lifetime');28
}29
export function pcpAnnounce(clientAddress) {30
const packet = Buffer.alloc(24);31
packet[0] = 2; mappedAddress(clientAddress).copy(packet, 8);32
return packet;33
}34
export function pcpMap({ clientAddress, nonce, protocol = 17, internalPort,35
externalPort = 0, externalAddress = '0.0.0.0', lifetime }) {36
mappingFields({ protocol, internalPort, externalPort, lifetime });37
check(Buffer.isBuffer(nonce) && nonce.length === 12, 'PCP requires an owned 96-bit mapping nonce');38
const packet = Buffer.alloc(60);39
packet[0] = 2; packet[1] = 1; packet.writeUInt32BE(lifetime, 4);40
mappedAddress(clientAddress).copy(packet, 8); nonce.copy(packet, 24);41
packet[36] = protocol; packet.writeUInt16BE(internalPort, 40); packet.writeUInt16BE(externalPort, 42);42
mappedAddress(externalAddress).copy(packet, 44);43
return packet;44
}45
function pcpOptions(bytes, start) {46
const options = [];47
for (let offset = start; offset < bytes.length;) {48
check(offset + 4 <= bytes.length, 'Truncated PCP option header');49
const size = bytes.readUInt16BE(offset + 2);50
const end = offset + 4 + size;51
const padded = end + ((4 - size % 4) % 4);52
check(padded <= bytes.length, 'Truncated PCP option/padding');53
options.push({ code: bytes[offset], bytes: Buffer.from(bytes.subarray(offset + 4, end)) });54
check(options.length <= 64, 'PCP option work budget');55
offset = padded;56
}57
return options;58
}59
export function decodePcp(bytes, expectedOpcode, expectedMap) {60
check(Buffer.isBuffer(bytes) && bytes.length >= 24 && bytes.length <= 1100, 'Invalid PCP response size');61
check(bytes[0] === 2 && (bytes[1] & 128) !== 0 && (bytes[1] & 127) === expectedOpcode,62
'PCP version/direction/opcode mismatch');63
const response = { protocol: 'pcp', opcode: expectedOpcode, result: bytes[3],64
lifetime: bytes.readUInt32BE(4), epoch: bytes.readUInt32BE(8) };65
// Reserved bits are ignored on reception as required by RFC 6887.66
if (response.result !== 0) return response;67
if (expectedOpcode === 0) {68
response.options = pcpOptions(bytes, 24);69
return response;70
}71
check(expectedOpcode === 1 && bytes.length >= 60, 'Truncated/unsupported PCP MAP response');72
Object.assign(response, { nonce: Buffer.from(bytes.subarray(24, 36)), transport: bytes[36],73
internalPort: bytes.readUInt16BE(40), externalPort: bytes.readUInt16BE(42),74
externalAddress: readAddress(bytes.subarray(44, 60)), options: pcpOptions(bytes, 60) });75
if (expectedMap) {76
check(response.nonce.equals(expectedMap.nonce) && response.transport === expectedMap.protocol &&77
response.internalPort === expectedMap.internalPort, 'Unmatched PCP mapping response');78
}79
return response;80
}81
export function natPmpAddress() { return Buffer.from([0, 0]); }82
export function natPmpMap({ protocol = 17, internalPort, externalPort = 0, lifetime }) {83
mappingFields({ protocol, internalPort, externalPort, lifetime });84
check(lifetime !== 0 || externalPort === 0, 'NAT-PMP delete requires external port zero');85
const packet = Buffer.alloc(12);86
packet[1] = protocol === 17 ? 1 : 2;87
packet.writeUInt16BE(internalPort, 4); packet.writeUInt16BE(externalPort, 6); packet.writeUInt32BE(lifetime, 8);88
return packet;89
}90
export function decodeNatPmp(bytes, opcode, internalPort) {91
check(Buffer.isBuffer(bytes) && bytes.length >= 8 && bytes.length <= 16, 'Invalid NAT-PMP response size');92
check(bytes[0] === 0 && bytes[1] === 128 + opcode && [0, 1, 2].includes(opcode),93
'NAT-PMP version/direction/opcode mismatch');94
const response = { protocol: 'nat-pmp', opcode, result: bytes.readUInt16BE(2), epoch: bytes.readUInt32BE(4) };95
if (response.result !== 0) return response;96
check(bytes.length === (opcode === 0 ? 12 : 16), 'Truncated/extra NAT-PMP response bytes');97
if (opcode === 0) response.externalAddress = [...bytes.subarray(8, 12)].join('.');98
else {99
Object.assign(response, { internalPort: bytes.readUInt16BE(8), externalPort: bytes.readUInt16BE(10),100
lifetime: bytes.readUInt32BE(12) });101
if (internalPort !== undefined) check(response.internalPort === internalPort, 'Unmatched NAT-PMP mapping response');102
}103
return response;104
}