Skip to content

Commit bf871bf

Browse files
lpincaarthurschreiberclaude
authored
fix: omit SNI for IP-based hostnames (#1728)
* fix: omit SNI for IP-based hostnames Refs: #1237 * fix: preserve server identity check when omitting SNI When a socket is passed to `tls.connect()` without a `host` option, the certificate identity check falls back to `options.servername || options.host || options.socket._host || 'localhost'`. Setting `servername` to an empty string for IP addresses therefore caused the server's certificate to be validated against `'localhost'` instead of the IP address, breaking connections to IP addresses that use `trustServerCertificate: false` with a certificate carrying matching `IP Address` SANs. Pass the target host explicitly so that certificate validation keeps using it while the SNI extension remains omitted for IP addresses. The IPv6 test is skipped on Node.js versions affected by nodejs/node#64144, where `tls.checkServerIdentity()` cannot match IPv6 addresses against `IP Address` SANs at all. Co-Authored-By: Claude Fable 5 <[email protected]> * test: align `servername` type widening with newer `@types/node` Recent `@types/node` versions declare the server-side `servername` getter on `TLSSocket` as `string | false | null`, which is incompatible with the `servername?: string` widening under `exactOptionalPropertyTypes`. Use the same union so the test compiles against both older and newer type definitions. Co-Authored-By: Claude Fable 5 <[email protected]> * test: drop `servername` type widening Now that the branch is on current `master`, whose lockfile pins `@types/node` 26, the server-side `servername` getter is declared on `TLSSocket` directly and the widening is no longer needed. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Arthur Schreiber <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]>
1 parent 41d46f8 commit bf871bf

4 files changed

Lines changed: 194 additions & 3 deletions

File tree

‎src/message-io.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import DuplexPair from 'native-duplexpair';
22

33
import { Duplex } from 'stream';
44
import * as tls from 'tls';
5-
import { Socket } from 'net';
5+
import { isIP, Socket } from 'net';
66
import { EventEmitter } from 'events';
77

88
import Debug from './debug';
@@ -73,7 +73,13 @@ class MessageIO extends EventEmitter {
7373
const securePair = this.securePair = {
7474
cleartext: tls.connect({
7575
socket: duplexpair.socket1 as Socket,
76-
servername: hostname,
76+
// The `host` is used to verify the server's certificate identity.
77+
// It is not used to establish a connection as a `socket` is
78+
// specified.
79+
host: hostname,
80+
// RFC 6066 does not allow IP addresses to be used as the server
81+
// name, so omit the SNI extension in that case.
82+
servername: isIP(hostname) ? '' : hostname,
7783
secureContext: secureContext,
7884
rejectUnauthorized: !trustServerCertificate
7985
}),

‎test/fixtures/loopback-ip.crt‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
-----BEGIN CERTIFICATE-----
2+
MIIDOzCCAiOgAwIBAgIUOagp5aI+GnvGz2kGV/dacO4z8+kwDQYJKoZIhvcNAQEL
3+
BQAwEzERMA8GA1UEAwwIbG9vcGJhY2swIBcNMjYwNzE3MTA1MTI5WhgPMjEyNjA2
4+
MjMxMDUxMjlaMBMxETAPBgNVBAMMCGxvb3BiYWNrMIIBIjANBgkqhkiG9w0BAQEF
5+
AAOCAQ8AMIIBCgKCAQEArSY7wJmq2PkFrf5/U9cAQmBhQiMhMKSav4may7JXEqyJ
6+
iS1esCDBk4kr0tdWAFX7od3l4Kmd21LfsqNCAdiJqsOpxc51CdyTp1gSAiesHOee
7+
b9t9fDvRu5vnRYWkAg3JHf4En09LGpnVMJ0fS9g9Jj5Oj+W+RTOnHZ5C5ZJgumhz
8+
TCv3UxfEoFA009hNHf0qYRGWJUG27Wcuo6AakPhJAaMhVQfi730AsIJkkHMSZWDa
9+
+CjhaNALLtNsyL9uUROtITZX/oX95ke8RCFB1oZ2Tq45MdWcj8OHY1t7c7tpOl/f
10+
tmbc3casio21iDiYe6FR29XE3+qNg6D04YdRE7VM/wIDAQABo4GEMIGBMB0GA1Ud
11+
DgQWBBThheYYWTAI/HjE2Oq6YLP/YdF55DAfBgNVHSMEGDAWgBThheYYWTAI/HjE
12+
2Oq6YLP/YdF55DAPBgNVHRMBAf8EBTADAQH/MCEGA1UdEQQaMBiHBH8AAAGHEAAA
13+
AAAAAAAAAAAAAAAAAAEwCwYDVR0PBAQDAgWgMA0GCSqGSIb3DQEBCwUAA4IBAQBu
14+
vUt7/fKxpuvhzScGfYcrDXHCVPBYG31PiqB3E95AWxSxE9pwAczVWiG8hm8ObhHy
15+
V2UD0D0oZhrrqfGfiIpdggvO7GZot6oZbBj9G9OrxDvjniKJ1ZFoDD+aMruA+Ulg
16+
6bm2fg1GRyYtON9zc+uTgDeCQxe3vuW59+z0r4+M4jdbA9DDjU1PGWkjbTspKUuA
17+
e1+Ceb5RWseBNCkS39oq5IX6av3CwboxEn35xAZGO4HZD9WIiMUbm3Zh7RU3ylrQ
18+
A9heYMjqxteiYQBXHK0A08CFLoXJAkPYtNRePVS99Hwn0tL4NCQCEDvDyDDkmFEr
19+
Il8meQR4AMX5EoAjl5D3
20+
-----END CERTIFICATE-----

‎test/fixtures/loopback-ip.key‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
-----BEGIN PRIVATE KEY-----
2+
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCtJjvAmarY+QWt
3+
/n9T1wBCYGFCIyEwpJq/iZrLslcSrImJLV6wIMGTiSvS11YAVfuh3eXgqZ3bUt+y
4+
o0IB2Imqw6nFznUJ3JOnWBICJ6wc555v2318O9G7m+dFhaQCDckd/gSfT0samdUw
5+
nR9L2D0mPk6P5b5FM6cdnkLlkmC6aHNMK/dTF8SgUDTT2E0d/SphEZYlQbbtZy6j
6+
oBqQ+EkBoyFVB+LvfQCwgmSQcxJlYNr4KOFo0Asu02zIv25RE60hNlf+hf3mR7xE
7+
IUHWhnZOrjkx1ZyPw4djW3tzu2k6X9+2ZtzdxqyKjbWIOJh7oVHb1cTf6o2DoPTh
8+
h1ETtUz/AgMBAAECggEAU2MYX7chyoCTNapdE7l1jIHyFPHqKAz94cSZYgQvXvTs
9+
/71z3orH7w+epVnDN0Ixf1DoRnwpY9jTlqp9PXpVQoIcnwDA6NDr4ynM8nC8uObr
10+
LJ+eHViJtzpr9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rK8jTJq6zjAqzAZR8s1+9/cH8XQuZ9mqw7fc5HS3D+b6Pon3c5zYAwAV
27+
4lmBEggRtnMfLaIewQABj4s=
28+
-----END PRIVATE KEY-----

‎test/unit/message-io-test.ts‎

Lines changed: 138 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { once } from 'events';
33
import { assert } from 'chai';
44
import { promisify } from 'util';
55
import DuplexPair from 'native-duplexpair';
6-
import { TLSSocket } from 'tls';
6+
import { checkServerIdentity, type PeerCertificate, TLSSocket } from 'tls';
77
import { readFileSync } from 'fs';
88
import { Duplex } from 'stream';
99

@@ -363,6 +363,30 @@ describe('MessageIO', function() {
363363
securePair.encrypted.destroy();
364364
});
365365

366+
/**
367+
* Forwards TLS handshake data between the given `MessageIO` and the
368+
* server side of the secure pair, unwrapping it from / wrapping it into
369+
* `PRELOGIN` messages.
370+
*/
371+
async function forwardTlsHandshake(io: MessageIO, rounds: number) {
372+
for (let i = 0; i < rounds; i++) {
373+
const message = await io.readMessage();
374+
for await (const chunk of message) {
375+
securePair.encrypted.write(chunk);
376+
}
377+
378+
await once(securePair.encrypted, 'readable');
379+
380+
const chunks = [];
381+
let chunk;
382+
while (chunk = securePair.encrypted.read()) {
383+
chunks.push(chunk);
384+
}
385+
386+
io.sendMessage(TYPE.PRELOGIN, Buffer.concat(chunks));
387+
}
388+
}
389+
366390
it('performs TLS negotiation', async function() {
367391
await Promise.all([
368392
// Client side
@@ -518,6 +542,119 @@ describe('MessageIO', function() {
518542
]);
519543
});
520544

545+
it('sends the hostname via the SNI extension', async function() {
546+
await Promise.all([
547+
// Client side
548+
(async () => {
549+
const io = new MessageIO(clientConnection, packetSize, debug);
550+
551+
await io.startTls({}, 'localhost', true);
552+
553+
assert(io.tlsNegotiationComplete);
554+
})(),
555+
556+
// Server side
557+
(async () => {
558+
const io = new MessageIO(serverConnection, packetSize, debug);
559+
560+
const onSecure = once(securePair.cleartext, 'secure');
561+
562+
await forwardTlsHandshake(io, 2);
563+
564+
await onSecure;
565+
566+
assert.strictEqual(securePair.cleartext.servername, 'localhost');
567+
})()
568+
]);
569+
});
570+
571+
describe('when connecting to an IP address', function() {
572+
beforeEach(function() {
573+
// Replace the server side of the secure pair with one that uses a
574+
// certificate that carries IP address SANs (and no DNS SANs).
575+
securePair.cleartext.destroy();
576+
securePair.encrypted.destroy();
577+
578+
const duplexpair = new DuplexPair();
579+
580+
securePair = {
581+
cleartext: new TLSSocket(duplexpair.socket1 as Socket, {
582+
key: readFileSync('./test/fixtures/loopback-ip.key'),
583+
cert: readFileSync('./test/fixtures/loopback-ip.crt'),
584+
isServer: true,
585+
ciphers: 'ECDHE-RSA-AES128-GCM-SHA256',
586+
// TDS 7.x only supports TLS versions up to TLS v1.2
587+
maxVersion: 'TLSv1.2'
588+
}),
589+
encrypted: duplexpair.socket2
590+
};
591+
});
592+
593+
it('omits the SNI extension and validates the certificate against the IPv4 address', async function() {
594+
await Promise.all([
595+
// Client side
596+
(async () => {
597+
const io = new MessageIO(clientConnection, packetSize, debug);
598+
599+
await io.startTls({
600+
ca: [readFileSync('./test/fixtures/loopback-ip.crt')]
601+
}, '127.0.0.1', false);
602+
603+
assert(io.tlsNegotiationComplete);
604+
})(),
605+
606+
// Server side
607+
(async () => {
608+
const io = new MessageIO(serverConnection, packetSize, debug);
609+
610+
const onSecure = once(securePair.cleartext, 'secure');
611+
612+
await forwardTlsHandshake(io, 2);
613+
614+
await onSecure;
615+
616+
assert.notOk(securePair.cleartext.servername);
617+
})()
618+
]);
619+
});
620+
621+
it('omits the SNI extension and validates the certificate against the IPv6 address', async function() {
622+
// Some Node.js versions are affected by an upstream regression that
623+
// prevents IPv6 addresses from being matched against `IP Address`
624+
// SANs. See https://github.com/nodejs/node/issues/64144
625+
const cert = { subject: { CN: 'dummy' }, subjectaltname: 'IP Address:0:0:0:0:0:0:0:1' };
626+
if (checkServerIdentity('::1', cert as PeerCertificate) !== undefined) {
627+
this.skip();
628+
}
629+
630+
await Promise.all([
631+
// Client side
632+
(async () => {
633+
const io = new MessageIO(clientConnection, packetSize, debug);
634+
635+
await io.startTls({
636+
ca: [readFileSync('./test/fixtures/loopback-ip.crt')]
637+
}, '::1', false);
638+
639+
assert(io.tlsNegotiationComplete);
640+
})(),
641+
642+
// Server side
643+
(async () => {
644+
const io = new MessageIO(serverConnection, packetSize, debug);
645+
646+
const onSecure = once(securePair.cleartext, 'secure');
647+
648+
await forwardTlsHandshake(io, 2);
649+
650+
await onSecure;
651+
652+
assert.notOk(securePair.cleartext.servername);
653+
})()
654+
]);
655+
});
656+
});
657+
521658
it('handles errors happening before TLS negotiation has sent any data', async function() {
522659
await Promise.all([
523660
// Client side

0 commit comments

Comments
 (0)