From 130cf40d8c935ff10dd8ca15b7202bfe8661b4c4 Mon Sep 17 00:00:00 2001 From: Lsong Date: Mon, 16 Nov 2026 16:32:55 +0800 Subject: [PATCH 1/2] fix(dns): correctly encode long TXT and mixed IPv4/IPv6 RDATA (#134) --- packet.js | 74 +++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 47 insertions(+), 27 deletions(-) diff --git a/packet.js b/packet.js index e1ef1e1..5d94099 100644 --- a/packet.js +++ b/packet.js @@ -36,7 +36,22 @@ const toIPv6 = buffer => { }; const fromIPv6 = address => { + if (!net.isIPv6(address)) { + throw new Error(`invalid IPv6 address ${JSON.stringify(address)}`); + } const digits = address.split(':'); + // RFC 4291 §2.2: an IPv4 dotted-quad tail represents two 16-bit groups. + // Expand it before calculating how many groups "::" must fill. + const ipv4 = digits[digits.length - 1]; + if (net.isIPv4(ipv4)) { + const octets = ipv4.split('.').map(Number); + digits.splice( + digits.length - 1, + 1, + ((octets[0] << 8) | octets[1]).toString(16), + ((octets[2] << 8) | octets[3]).toString(16), + ); + } // Leading/trailing "::" produces an empty leading/trailing element that is // not a zero group of its own; drop it so only the interior "" marks the run. if (digits[0] === '') { @@ -659,6 +674,11 @@ Packet.Resource.encode = function (resource, writer) { } } const rdlen = (writer.bitLength() - rdataBitStart) / 8; + if (rdlen > 0xffff) { + throw new Error( + `${Packet.typeName(resource.type)} encode: RDATA length ${rdlen} exceeds 65535 octets`, + ); + } writer.patch(rdlenBitPos, rdlen, 16); return writer.toBuffer(); }; @@ -1030,12 +1050,28 @@ Packet.Resource.SPF = Packet.Resource.TXT = { return characterString; }); - // write each string to output (RDLENGTH is back-filled by Resource.encode) + // RFC 1035 §3.3: each character-string has a one-octet length (max 255). + // Preserve explicit array boundaries; split only oversized entries. characterStringBuffers.forEach(function (buffer) { - writer.write(buffer.length, 8); // text length - buffer.forEach(function (c) { - writer.write(c, 8); - }); + if (buffer.length === 0) { + writer.write(0, 8); + return; + } + for (let start = 0; start < buffer.length; ) { + let end = Math.min(start + 255, buffer.length); + if (end < buffer.length) { + // Do not split within a UTF-8 sequence: TXT.decode converts each + // character-string to a separate JS string. + let safeEnd = end; + while (safeEnd > start && (buffer[safeEnd] & 0xc0) === 0x80) { + safeEnd--; + } + if (safeEnd > start) end = safeEnd; + } + writer.write(end - start, 8); + for (let i = start; i < end; i++) writer.write(buffer[i], 8); + start = end; + } }); }, }; @@ -1294,29 +1330,13 @@ Packet.Resource.EDNS.ECS.encode = function (record, writer) { } }; -// Expand a (possibly compressed) IPv6 text address into a 16-byte array. +// Share the AAAA IPv6 parser with ECS so dotted-quad tails are expanded +// consistently before truncating to the ECS source prefix length. function expandIPv6ToBytes(address) { - let head, tail; - const idx = address.indexOf('::'); - if (idx === -1) { - head = address.split(':'); - tail = []; - } else { - head = address.slice(0, idx).split(':').filter(Boolean); - tail = address - .slice(idx + 2) - .split(':') - .filter(Boolean); - } - const missing = 8 - head.length - tail.length; - const groups = [...head, ...new Array(missing).fill('0'), ...tail]; - const out = new Array(16).fill(0); - for (let g = 0; g < 8; g++) { - const n = parseInt(groups[g], 16) || 0; - out[g * 2] = (n >> 8) & 0xff; - out[g * 2 + 1] = n & 0xff; - } - return out; + return fromIPv6(address).flatMap(group => { + const value = parseInt(group, 16); + return [value >>> 8, value & 0xff]; + }); } // RFC 8914 §3 — EXTRA-TEXT should stay short. It shares the response with the From 2c2372ad15eefaacc4340e4f2eb4b910ea5970bc Mon Sep 17 00:00:00 2001 From: Lsong Date: Mon, 16 Nov 2026 16:33:39 +0800 Subject: [PATCH 2/2] test(dns): cover TXT boundaries and IPv4-mapped AAAA/ECS (#134) --- test/issue-134.test.js | 140 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 test/issue-134.test.js diff --git a/test/issue-134.test.js b/test/issue-134.test.js new file mode 100644 index 0000000..7bfb803 --- /dev/null +++ b/test/issue-134.test.js @@ -0,0 +1,140 @@ +const assert = require('node:assert/strict'); +const test = require('node:test'); +const { Packet } = require('..'); + +function roundTrip(...answers) { + const packet = new Packet(); + packet.header.qr = 1; + packet.questions.push({ + name: 'example.com', + type: answers[0].type, + class: Packet.CLASS.IN, + }); + packet.answers = answers.map(answer => ({ + name: 'example.com', + class: Packet.CLASS.IN, + ttl: 300, + ...answer, + })); + const parsed = Packet.parse(packet.toBuffer()); + assert.equal(parsed.errors.length, 0); + assert.equal(parsed.answers.length, answers.length); + return parsed.answers; +} + +test('TXT and SPF split strings longer than 255 octets', () => { + for (const type of [Packet.TYPE.TXT, Packet.TYPE.SPF]) { + for (const size of [0, 1, 254, 255, 256, 510, 511, 1024]) { + const data = 'x'.repeat(size); + const [answer] = roundTrip({ type, data }); + const expected = + size === 0 + ? [''] + : Array.from({ length: Math.ceil(size / 255) }, (_, index) => + data.slice(index * 255, (index + 1) * 255), + ); + assert.deepEqual(answer.data, expected, `type=${type}, size=${size}`); + } + } +}); + +test('TXT splitting preserves UTF-8 characters and explicit boundaries', () => { + // The first emoji straddles the 255-octet boundary. + const utf8 = 'a'.repeat(254) + '💡' + 'é'.repeat(130); + const [answer] = roundTrip({ + type: Packet.TYPE.TXT, + data: ['first', utf8, Buffer.from('z'.repeat(256)), '', 'last'], + }); + assert.equal(answer.data[0], 'first'); + assert.equal(answer.data.at(-2), ''); + assert.equal(answer.data.at(-1), 'last'); + assert.equal(answer.data.slice(1, -4).join(''), utf8); + assert.deepEqual(answer.data.slice(-4, -2), ['z'.repeat(255), 'z']); + assert.ok(answer.data.every(s => Buffer.byteLength(s, 'utf8') <= 255)); +}); + +test('oversized TXT does not misalign the following resource record', () => { + const [txt, address] = roundTrip( + { type: Packet.TYPE.TXT, data: 'k'.repeat(600) }, + { type: Packet.TYPE.A, address: '192.0.2.10' }, + ); + assert.equal(txt.data.join(''), 'k'.repeat(600)); + assert.equal(address.address, '192.0.2.10'); +}); + +test('TXT RDATA beyond 65535 octets fails instead of truncating RDLENGTH', () => { + const packet = new Packet(); + packet.answers.push({ + name: 'example.com', + type: Packet.TYPE.TXT, + class: Packet.CLASS.IN, + ttl: 60, + data: 'x'.repeat(65280), // 256 chunks of 255 plus 256 length octets + }); + assert.throws(() => packet.toBuffer(), /RDATA length 65536 exceeds 65535/); +}); + +test('AAAA encodes mixed IPv6/IPv4 text as exactly 16 octets', () => { + const cases = [ + ['::ffff:192.0.2.1', '::ffff:c000:201', '00000000000000000000ffffc0000201'], + ['0:0:0:0:0:ffff:192.0.2.1', '::ffff:c000:201', '00000000000000000000ffffc0000201'], + ['2001:db8::192.0.2.1', '2001:db8::c000:201', '20010db80000000000000000c0000201'], + ['::192.0.2.1', '::c000:201', '000000000000000000000000c0000201'], + ]; + for (const [input, expectedText, expectedHex] of cases) { + const packet = new Packet(); + packet.answers.push({ + name: 'example.com', + type: Packet.TYPE.AAAA, + class: Packet.CLASS.IN, + ttl: 60, + address: input, + }); + const wire = packet.toBuffer(); + assert.equal(wire.subarray(-16).toString('hex'), expectedHex, input); + const parsed = Packet.parse(wire); + assert.equal(parsed.errors.length, 0, input); + assert.equal(parsed.answers[0].address, expectedText, input); + assert.equal(Packet.fromIPv6(input).length, 8, input); + } +}); + +test('EDNS ECS shares AAAA mixed IPv6 parsing for /128 and /96', () => { + const expected = Buffer.from('00000000000000000000ffffc0000201', 'hex'); + for (const address of [ + '::ffff:192.0.2.1', + '0:0:0:0:0:ffff:192.0.2.1', + ]) { + for (const bits of [96, 128]) { + const opt = new Packet.Resource.EDNS([{ + ednsCode: Packet.EDNS_OPTION_CODE.ECS, + family: 2, + sourcePrefixLength: bits, + scopePrefixLength: 0, + ip: address, + }]); + const wire = Packet.Resource.encode(opt); + const octets = bits / 8; + assert.deepEqual(wire.subarray(-octets), expected.subarray(0, octets)); + const parsed = Packet.Resource.decode(wire); + assert.equal(parsed.rdata[0].family, 2); + assert.equal(parsed.rdata[0].sourcePrefixLength, bits); + if (bits === 128) { + assert.equal(parsed.rdata[0].ip, '0:0:0:0:0:ffff:c000:201'); + } + } + } +}); + +test('fromIPv6 and ECS reject malformed mixed IPv6 addresses', () => { + const invalid = '::ffff:999.2.3.4'; + assert.throws(() => Packet.fromIPv6(invalid), /invalid IPv6 address/); + const opt = new Packet.Resource.EDNS([{ + ednsCode: Packet.EDNS_OPTION_CODE.ECS, + family: 2, + sourcePrefixLength: 128, + scopePrefixLength: 0, + ip: invalid, + }]); + assert.throws(() => Packet.Resource.encode(opt), /invalid IPv6 address/); +});