AtlatestRepositorysigil-nat

sigil-nat / tree / tools / natupnp.mjs

1// Minimal HTTP/1.1 control point for a gateway already discovered by SSDP.
2// The peer, size, redirects, XML entities and work are deliberately bounded.
3import { connect } from 'node:net';
4import { isIP } from 'node:net';
5import { randomBytes } from 'node:crypto';
6
7const MAX_RESPONSE = 65536;
8const MAX_HEADER = 16384;
9
10function requireValue(value, message) {
11 if (!value) throw new Error(message);
14function safeXml(bytes) {
15 requireValue(Buffer.isBuffer(bytes) && bytes.length <= MAX_RESPONSE, 'UPnP XML exceeds size limit');
16 const xml = bytes.toString('utf8');
17 requireValue(!/<!\s*(?:DOCTYPE|ENTITY)/i.test(xml), 'UPnP XML DTD/entities are disabled');
18 return xml.replace(/<!--[\s\S]*?-->/g, '');
21function decodeXml(text) {
22 return text.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (_, entity) => {
23 const named = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
24 if (entity[0] !== '#') return named[entity.toLowerCase()];
25 const value = entity[1].toLowerCase() === 'x'
26 ? Number.parseInt(entity.slice(2), 16) : Number.parseInt(entity.slice(1), 10);
27 requireValue(Number.isInteger(value) && value > 0 && value <= 0x10ffff &&
28 !(value >= 0xd800 && value <= 0xdfff), 'Invalid XML character reference');
29 return String.fromCodePoint(value);
30 });
33function xmlTag(xml, name) {
34 const match = new RegExp(`<${name}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${name}\\s*>`, 'i').exec(xml);
35 return match ? decodeXml(match[1].trim()) : undefined;
38function controlUrl(value, base, gateway) {
39 const url = new URL(value, base);
40 requireValue(url.protocol === 'http:' && url.hostname === gateway &&
41 !url.username && !url.password && !url.hash, 'UPnP control URL escaped the HTTP gateway');
42 return url;
45function parseHttpResponse(bytes) {
46 const split = bytes.indexOf('\r\n\r\n');
47 requireValue(split >= 0 && split <= MAX_HEADER, 'Invalid/bounded UPnP HTTP headers');
48 const lines = bytes.subarray(0, split).toString('latin1').split('\r\n');
49 const status = /^HTTP\/1\.[01] ([0-9]{3})(?: .*)?$/.exec(lines.shift() ?? '');
50 requireValue(status, 'Invalid UPnP HTTP status line');
51 const headers = new Map();
52 for (const line of lines) {
53 const match = /^([A-Za-z0-9-]+):[ \t]*(.*)$/.exec(line);
54 requireValue(match && !headers.has(match[1].toLowerCase()), 'Malformed/duplicate UPnP HTTP header');
55 headers.set(match[1].toLowerCase(), match[2].trim());
56 }
57 const body = bytes.subarray(split + 4);
58 const transferEncoding = headers.get('transfer-encoding');
59 if (transferEncoding) {
60 requireValue(transferEncoding.toLowerCase() === 'chunked', 'Unsupported UPnP transfer encoding');
61 return { status: Number(status[1]), headers, body: decodeChunked(body) };
62 }
63 const length = headers.get('content-length');
64 if (length !== undefined) {
65 requireValue(/^\d+$/.test(length) && Number(length) <= MAX_RESPONSE && body.length >= Number(length),
66 'Invalid/truncated UPnP Content-Length');
67 requireValue(body.length === Number(length), 'Unexpected bytes after UPnP HTTP body');
68 }
69 return { status: Number(status[1]), headers, body };
72function decodeChunked(bytes) {
73 const chunks = [];
74 let offset = 0;
75 let total = 0;
76 while (true) {
77 const lineEnd = bytes.indexOf('\r\n', offset);
78 requireValue(lineEnd >= 0 && lineEnd - offset <= 32, 'Malformed UPnP chunk header');
79 const sizeText = bytes.subarray(offset, lineEnd).toString('ascii').split(';', 1)[0];
80 requireValue(/^[0-9a-f]{1,8}$/i.test(sizeText), 'Invalid UPnP chunk size');
81 const size = Number.parseInt(sizeText, 16);
82 offset = lineEnd + 2;
83 if (size === 0) {
84 requireValue(bytes.subarray(offset).equals(Buffer.from('\r\n')), 'Unexpected UPnP chunk trailers');
85 break;
86 }
87 total += size;
88 requireValue(total <= MAX_RESPONSE && offset + size + 2 <= bytes.length &&
89 bytes.subarray(offset + size, offset + size + 2).equals(Buffer.from('\r\n')),
90 'Truncated/oversized UPnP chunk');
91 chunks.push(bytes.subarray(offset, offset + size));
92 offset += size + 2;
93 }
94 return Buffer.concat(chunks, total);
97function requestHttp(url, { gateway, localAddress, method, headers = {}, body = Buffer.alloc(0) }) {
98 requireValue(isIP(gateway) === 4 && isIP(localAddress) === 4 && url.hostname === gateway &&
99 url.protocol === 'http:' && !url.username && !url.password, 'UPnP HTTP target must be the selected IPv4 gateway');
100 requireValue(body.length <= MAX_RESPONSE, 'UPnP request body exceeds limit');
101 const port = Number(url.port || 80);
102 requireValue(Number.isInteger(port) && port >= 1 && port <= 65535, 'Invalid UPnP HTTP port');
103 const path = `${url.pathname || '/'}${url.search}`;
104 const lines = [`${method} ${path} HTTP/1.1`, `Host: ${gateway}:${port}`,
105 'Connection: close', 'Accept: text/xml, application/xml'];
106 for (const [name, value] of Object.entries(headers)) {
107 requireValue(/^[A-Za-z0-9-]+$/.test(name) && !/[\r\n]/.test(value), 'Invalid UPnP request header');
108 lines.push(`${name}: ${value}`);
109 }
110 if (body.length) lines.push(`Content-Length: ${body.length}`);
111 const wire = Buffer.concat([Buffer.from(`${lines.join('\r\n')}\r\n\r\n`), body]);
112 return new Promise((resolve, reject) => {
113 const socket = connect({ host: gateway, port, localAddress });
114 const parts = [];
115 let length = 0;
116 let settled = false;
117 const deadline = setTimeout(() => finish(new Error('UPnP HTTP absolute deadline')), 3000);
118 const finish = (error, response) => {
119 if (settled) return;
120 settled = true;
121 clearTimeout(deadline);
122 socket.destroy();
123 if (error) reject(error); else resolve(response);
124 };
125 socket.setTimeout(3000, () => finish(new Error('UPnP HTTP request timed out')));
126 socket.on('error', error => finish(error));
127 socket.on('connect', () => socket.write(wire));
128 socket.on('data', chunk => {
129 length += chunk.length;
130 if (length > MAX_RESPONSE + MAX_HEADER) return finish(new Error('UPnP HTTP response exceeds limit'));
131 parts.push(chunk);
132 });
133 socket.on('end', () => {
134 try { finish(null, parseHttpResponse(Buffer.concat(parts, length))); }
135 catch (error) { finish(error); }
136 });
137 });
140export function parseIgdDescription(bytes, location, gateway) {
141 const xml = safeXml(bytes);
142 const rootUrl = xmlTag(xml, 'URLBase');
143 const base = rootUrl ? controlUrl(rootUrl, location, gateway) : location;
144 const services = [...xml.matchAll(/<service(?:\s[^>]*)?>([\s\S]*?)<\/service\s*>/gi)];
145 for (const [, serviceXml] of services) {
146 const serviceType = xmlTag(serviceXml, 'serviceType');
147 if (!/^urn:schemas-upnp-org:service:(?:WANIPConnection:[12]|WANPPPConnection:1)$/.test(serviceType ?? '')) continue;
148 const control = xmlTag(serviceXml, 'controlURL');
149 requireValue(control, 'IGD service has no control URL');
150 return { protocol: 'upnp-igd', serviceType, controlUrl: controlUrl(control, base, gateway).href };
151 }
152 throw new Error('IGD description has no supported WANIPConnection/WANPPPConnection service');
155export async function describeIgd(discovered, route) {
156 const location = new URL(discovered.location);
157 requireValue(location.protocol === 'http:' && location.hostname === route.gateway &&
158 !location.username && !location.password && !location.hash, 'IGD description URL must remain on the selected gateway');
159 const response = await requestHttp(location, { ...route, method: 'GET' });
160 requireValue(response.status === 200, `IGD description returned HTTP ${response.status}`);
161 return { ...parseIgdDescription(response.body, location, route.gateway), gateway: route.gateway,
162 localAddress: route.localAddress };
165function xmlEscape(value) {
166 return String(value).replace(/[&<>"']/g, character => ({
167 '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;',
168 })[character]);
171function parseActionResult(bytes, action) {
172 const xml = safeXml(bytes);
173 const fault = xmlTag(xml, 'errorCode');
174 if (fault) {
175 const error = new Error(`UPnP ${action} SOAP fault ${fault}`);
176 error.upnpCode = Number(fault);
177 throw error;
178 }
179 const body = new RegExp(`<[^>]*:?${action}Response(?:\\s[^>]*)?>([\\s\\S]*?)<\\/[^>]*:?${action}Response\\s*>`, 'i').exec(xml);
180 requireValue(body, `UPnP ${action} response element is missing`);
181 return body[1];
184export class UpnpIgdClient {
185 constructor(service, route) {
186 requireValue(service?.protocol === 'upnp-igd' &&
187 /^urn:schemas-upnp-org:service:(?:WANIPConnection:[12]|WANPPPConnection:1)$/.test(service.serviceType),
188 'Unsupported IGD service');
189 this.service = service;
190 this.route = route;
191 this.control = new URL(service.controlUrl);
192 }
193 async action(action, values = {}) {
194 const fields = Object.entries(values).map(([name, value]) => `<${name}>${xmlEscape(value)}</${name}>`).join('');
195 const body = Buffer.from(`<?xml version="1.0" encoding="utf-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:${action} xmlns:u="${this.service.serviceType}">${fields}</u:${action}></s:Body></s:Envelope>`);
196 const response = await requestHttp(this.control, { ...this.route, method: 'POST', body, headers: {
197 'Content-Type': 'text/xml; charset="utf-8"',
198 SOAPAction: `"${this.service.serviceType}#${action}"`,
199 } });
200 if (response.status !== 200) {
201 const faultCode = xmlTag(safeXml(response.body), 'errorCode');
202 const error = new Error(faultCode
203 ? `UPnP ${action} SOAP fault ${faultCode}`
204 : `UPnP ${action} returned HTTP ${response.status}`);
205 if (faultCode) error.upnpCode = Number(faultCode);
206 throw error;
207 }
208 return parseActionResult(response.body, action);
209 }
210 async getExternalAddress() {
211 const response = await this.action('GetExternalIPAddress');
212 const address = xmlTag(response, 'NewExternalIPAddress');
213 requireValue(isIP(address) === 4 && address !== '0.0.0.0', 'IGD returned no usable IPv4 external address');
214 return address;
215 }
216 async getMapping(externalPort, protocol = 'UDP') {
217 try {
218 const response = await this.action('GetSpecificPortMappingEntry', {
219 NewRemoteHost: '', NewExternalPort: externalPort, NewProtocol: protocol,
220 });
221 return {
222 internalPort: Number(xmlTag(response, 'NewInternalPort')),
223 internalClient: xmlTag(response, 'NewInternalClient'),
224 enabled: xmlTag(response, 'NewEnabled'),
225 description: xmlTag(response, 'NewPortMappingDescription'),
226 lifetime: Number(xmlTag(response, 'NewLeaseDuration')),
227 };
228 } catch (error) {
229 if (error.upnpCode === 714) return undefined;
230 throw error;
231 }
232 }
233 async addMapping({ internalPort, internalClient, externalPort, description, lifetime }) {
234 await this.action('AddPortMapping', {
235 NewRemoteHost: '', NewExternalPort: externalPort, NewProtocol: 'UDP',
236 NewInternalPort: internalPort, NewInternalClient: internalClient,
237 NewEnabled: 1, NewPortMappingDescription: description, NewLeaseDuration: lifetime,
238 });
239 }
240 async deleteMapping(externalPort) {
241 await this.action('DeletePortMapping', {
242 NewRemoteHost: '', NewExternalPort: externalPort, NewProtocol: 'UDP',
243 });
244 }
247export function upnpUdpCandidate(client, { internalPort, internalClient, externalAddress,
248 randomPort = () => 49152 + randomBytes(2).readUInt16BE(0) % 16384 }) {
249 const owner = `sigil-nat:${randomBytes(12).toString('hex')}`;
250 let ownedPort;
251 async function verifyOwned(port, requireBoundLease = true) {
252 const entry = await client.getMapping(port, 'UDP');
253 if (!entry) return undefined;
254 requireValue(entry.description === owner && entry.internalPort === internalPort &&
255 entry.internalClient === internalClient,
256 'UPnP port is occupied by a mapping this process does not own');
257 if (requireBoundLease)
258 requireValue(entry.enabled === '1' && Number.isInteger(entry.lifetime) && entry.lifetime >= 1 && entry.lifetime <= 1800,
259 'UPnP router granted an invalid or over-cap lease');
260 return entry;
261 }
262 return {
263 protocol: 'upnp-igd', identity: { internalPort, internalClient, owner },
264 async exchange(lifetime, previous) {
265 requireValue(Number.isInteger(lifetime) && lifetime >= 0 && lifetime <= 1800,
266 'UPnP lease must be within 30 minutes');
267 const port = previous?.externalPort ?? ownedPort ?? internalPort;
268 ownedPort = port;
269 if (lifetime === 0) {
270 const entry = await verifyOwned(port, false);
271 if (!entry) return { lifetime: 0, externalPort: port, absenceCode: 714 };
272 try { await client.deleteMapping(port); }
273 catch (error) {
274 // Lost delete replies are reconciled by the same 714 lookup below.
275 if (await client.getMapping(port, 'UDP')) throw error;
276 }
277 requireValue(!(await client.getMapping(port, 'UDP')), 'UPnP mapping still exists after deletion');
278 return { lifetime: 0, externalPort: port, externalAddress, absenceCode: 714 };
279 }
280 if (!previous) {
281 let free;
282 for (let attempts = 0; attempts < 8; attempts += 1) {
283 const candidate = attempts === 0 ? port : randomPort();
284 const entry = await client.getMapping(candidate, 'UDP');
285 if (!entry) { ownedPort = candidate; free = true; break; }
286 }
287 requireValue(free, 'No unoccupied external UDP port in bounded allocation attempts');
288 } else {
289 const existing = await verifyOwned(port);
290 requireValue(existing, 'Owned UPnP mapping disappeared before renewal');
291 }
292 try {
293 await client.addMapping({ internalPort, internalClient, externalPort: ownedPort,
294 description: owner, lifetime });
295 } catch (error) {
296 // A lost SOAP reply is resolved by reading the exact owner tuple.
297 const entry = await verifyOwned(ownedPort);
298 if (!entry) throw error;
299 }
300 const entry = await verifyOwned(ownedPort);
301 requireValue(entry && entry.lifetime > 0 && entry.lifetime <= lifetime,
302 'UPnP did not install a bounded leased mapping');
303 return { lifetime: entry.lifetime, externalPort: ownedPort, externalAddress };
304 },
305 };