Skip to content

Commit 8705d89

Browse files
authored
tls: normalize the hostname for server identity checks (#42977)
### Problem - `tls.checkServerIdentity("foo。bar.example.com", cert)` accepts a certificate for `*.example.com`. IDNA maps U+3002, U+FF0E and U+FF61 to ".", so a resolver looks up `foo.bar.example.com`, two labels deep. Node fixed this as CVE-2026-48618. - The cause: a label split on ASCII "." only, in `splitHost` (`src/js/node/tls.ts:352`) and the native `match_hostname` (`src/boringssl/lib.rs:302`). Canary accepts it in `tls.connect`, `https.request`, `fetch` (`tls.serverName`) and `Bun.connect`. - Only a raw `host` or `servername` string reaches it. A URL host is already ASCII. ### Fix - Port nodejs/node 1efb4ff51a and its follow-up 1d87a24050: `checkServerIdentity` matches DNS names on `url.domainToASCII(hostname)`. IP literals and the error text keep the hostname as typed, because `domainToASCII("::1")` is `""`. `domainToASCII` moves to `internal/url`, as in Node. - `check_x509_server_identity` runs the same conversion when the host has a non-ASCII byte. A host that does not convert matches nothing. ASCII hosts are unchanged. - One deliberate difference from Node: `*` does not match an empty label. The conversion turns `。example.com` into `.example.com`, which Node accepts for `*.example.com`. - Verified: `test/js/web/fetch/fetch.tls.wildcard.test.ts` (23 of 100 fail on canary) and the vendored `test-tls-check-server-identity.js`, synced to Node v26.8.2. Self-reviewed: 3 concerns raised, 1 addressed, 2 kept with the reason in Notes. ### Background - `checkServerIdentity` compares the host with each DNS name in the certificate, label by label. A left-most `*` stands for exactly one label. - IDNA (UTS #46) maps a Unicode domain name to ASCII. `url.domainToASCII` applies it. - Bun has two matchers with Node's rules: the JS one in `node:tls`, and a Rust port that every native TLS client calls. <details><summary>Notes</summary> **Repro** ```js const tls = require("tls"); const err = tls.checkServerIdentity("foo\u3002bar.example.com", { subjectaltname: "DNS:*.example.com", subject: {} }); console.log(err ? "REJECTED: " + err.reason : "ACCEPTED"); ``` | runtime | output | | --- | --- | | Node v26.3.0 | `ACCEPTED` | | Bun canary 1.4.3 (09bb546, c6b7fcb) | `ACCEPTED` | | Node v26.6.0, v26.8.2 | `REJECTED: Host: foo。bar.example.com. is not in the cert's altnames: DNS:*.example.com` | | this branch | same as Node v26.8.2 | The CVE fix shipped in Node v26.5.0. That release stopped matching IPv6 hosts against IP SANs (nodejs/node#64144). v26.6.0 fixed it with 1d87a24050. This PR ports both, so `::1` keeps matching `IP Address:0:0:0:0:0:0:0:1`. **End to end, server certificate `DNS:*.example.com`, client dials 127.0.0.1** | entry point | `foo。bar.example.com` on canary | on this branch | | --- | --- | --- | | `tls.connect({ servername })` | authorized | `ERR_TLS_CERT_ALTNAME_INVALID` | | `https.request({ servername })` | 200 | `ERR_TLS_CERT_ALTNAME_INVALID` | | `fetch(url, { tls: { serverName } })` | 200 | `ERR_TLS_CERT_ALTNAME_INVALID` | | `Bun.connect({ tls: { serverName } })` | authorized | `ERR_TLS_CERT_ALTNAME_INVALID` | U+FF0E and U+FF61 give the same results. `bar.example.com` and `bücher.example.com` stay accepted on all four. **Comparison with Node on a 28-row table** (full stops in SAN and CN paths, trailing ideographic full stop, U-labels, IPv4 and IPv6 hosts, hosts that `domainToASCII` rejects). This branch gives the same verdict, `reason` and `host` as Node v26.6.0 on all 28 rows, and as Node v26.8.2 on 27. The other row is `xn--a.example.com` against `DNS:xn--a.example.com`: Node v26.7.0 moved to ada 4.0.0, where `domainToASCII` no longer rejects an invalid punycode label. Bun's `url.domainToASCII` still returns `""` for it, as ada 3.4.4 does, so the host matches nothing. That difference belongs to `node:url`. **Empty first label** `domainToASCII("。example.com")` is `.example.com`. Node's `check()` lets `*` match the empty first label, so Node accepts that host for `*.example.com`: | host against `DNS:*.example.com` | Node v26.3.0 | Node v26.8.2 | Bun canary | this branch | | --- | --- | --- | --- | --- | | `.example.com` | accepted | accepted | accepted | rejected | | `。example.com` | rejected | accepted | rejected | rejected | A plain port would make Bun newly accept `。example.com`. A name with an empty label is not a name below `*.example.com` (OpenSSL's `wildcard_match` also needs one character), and glibc does not resolve `.localhost`. So both matchers reject an empty first label. This is the one place where `check()` differs from Node, and the tests mark the rows. **Reach** - On Linux, Bun's resolver returns `ENOTFOUND` for a host with one of these full stops, so a raw `host` does not dial. The check is reached through `servername`, a custom `lookup`, a proxy agent that connects first, or a direct call to `tls.checkServerIdentity`. - On Windows, the resolver already maps the full stop: on canary a8e4e90, `dns.lookup("127。0。0。1")` returns `127.0.0.1` and `net.connect({ host: "127。0。0。1", port })` connects to 127.0.0.1. There a raw `host` is enough. - #35590 adds the IDNA mapping to `dns.lookup` on every platform. **Native matcher** - Every native caller goes through `check_x509_server_identity`: fetch and its HTTPS proxy tunnel, `Bun.connect`, WebSocket, Postgres, MySQL, Valkey. The conversion is in that one function. - `Bun__domainToASCII` wraps the same `parseDomainAsHost` that backs `url.domainToASCII`. It can run off the JS thread. The HTTP thread already calls `WTF::URL` for redirects (`bun_url::href_from_string`). - The conversion only runs for a host with a non-ASCII byte. `tls.checkServerIdentity` converts every host, as Node does. So the two matchers differ on an ASCII host that is not a valid URL host. Example: `a b.example.com` against `*.example.com` is rejected by `tls.checkServerIdentity` and still accepted by the native matcher. No resolver maps an ASCII name, so the label split is correct there. The conversion also rejects ASCII hosts that work today, for example `db.1` (a numeric last label must parse as IPv4), so the native ASCII path stays as it is. - A host is an IP address only as typed, as in Node. `127.0.0.1` converts to `127.0.0.1` and is still matched as a DNS name. One test pins this for both matchers. - The native mismatch reason printed the host through the escaping that is meant for certificate names. `Bun.connect` showed `Host: "foo\u00e3\^@\^Bbar.example.com".` for a UTF-8 host. It now prints the host as typed, as Node does. The `Bun.connect` tests assert the full message. - `X509Certificate#checkHost`, the HTTP/3 client and `node:quic` use OpenSSL rules (`X509_check_host`), where `*` only spans letters, digits and "-". They already reject these hosts. The test table records `checkHost` as `undefined` for each new row. **Tests** - `fetch.tls.wildcard.test.ts`: `tls.connect` and `Bun.connect` end to end for the three code points, new rows in the `checkServerIdentity == fetch` table, and a table for `tls.checkServerIdentity` (SAN, CN fallback, error text, `err.host`, trailing U+3002, U-label against an A-label SAN, IPv6 host, empty first label). Canary a8e4e90: 77 pass, 23 fail. With the fix: 100 pass. - `test/js/node/test/parallel/test-tls-check-server-identity.js` is byte-identical to Node v26.8.2. It fails on canary at the U+3002 row. - Also ran with the debug build: `test/js/node/tls/`, `test/js/node/url/`, `fetch.tls.test.ts`, `fetch.tls.ipv6.test.ts`, `node-https-checkServerIdentity.test.ts`, `valkey-tls-verify.test.ts`, `test/js/bun/net/socket.test.ts`, `test/internal/source-lints/`, and the 262 vendored `test-tls-*`, `test-https-*`, `test-x509-*` files. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 0 · 7 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 23 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/web/fetch/fetch.tls.wildcard.test.ts bun test v1.4.3 (c6b7fcb) test/js/web/fetch/fetch.tls.wildcard.test.ts: (pass) TLS wildcard hostname verification > should reject multi-label wildcard match (sub.foo.example.com vs *.example.com) [645.61ms] (pass) TLS wildcard hostname verification > should accept valid single-label wildcard match (foo.example.com vs *.example.com) [392.23ms] (pass) TLS wildcard hostname verification > should reject bare domain for wildcard cert (example.com vs *.example.com) [386.83ms] (pass) TLS wildcard hostname verification > should accept exact match for wildcard labels (bar.example.com vs *.example.com) [404.48ms] (pass) TLS wildcard hostname verification > should reject deeply nested subdomain (a.b.c.example.com vs *.example.com) [393.09ms] 327 | servername, 328 | }); 329 | socket.on("secureConnect", () => resolve({ authorized: socket.authorized })); 330 | socket.on("error", resolve); 331 | try { 332 | expect(await promise).toMatchObject({ ... (truncated) release without fix: 7 FAILED bun test v1.4.3-canary.1 (dd5e81d) test/js/web/fetch/fetch.tls.wildcard.test.ts: (pass) TLS certificate name matching: fetch() / checkServerIdentity / checkHost agree > checkServerIdentity == fetch > "a.b.wild.test" [7.83ms] (pass) TLS certificate name matching: fetch() / checkServerIdentity / checkHost agree > checkServerIdentity == fetch > "wild.test" [7.43ms] (pass) TLS certificate name matching: fetch() / checkServerIdentity / checkHost agree > checkServerIdentity == fetch > "foo.wild.test" [12.93ms] (pass) TLS certificate name matching: fetch() / checkServerIdentity / checkHost agree > checkServerIdentity == fetch > "FOO.WILD.TEST" [12.26ms] (pass) TLS wildcard hostname verification > should reject multi-label wildcard match (sub.foo.example.com vs *.example.com) [37.15ms] (pass) TLS wildcard hostname verification > should accept valid single-label wildcard match (foo.example.com vs *.example.com) [29.23ms] (pass) TLS wildcard hostname verification > should reject bare domain for wildcard cert (example.com vs *.example.com) [28.23ms] (pass) TLS certificate name matching: fetch() / checkServerIdentity / checkHost agree > checkServerIdentity == fetch > "foo.wi ... (truncated) ``` </details> <details><summary>passes on PR (with fix)</summary> ```console ASAN with fix: all passed $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/web/fetch/fetch.tls.wildcard.test.ts bun test v1.4.3 (c6b7fcb) test/js/web/fetch/fetch.tls.wildcard.test.ts: (pass) TLS wildcard hostname verification > should reject multi-label wildcard match (sub.foo.example.com vs *.example.com) [643.60ms] (pass) TLS wildcard hostname verification > should accept valid single-label wildcard match (foo.example.com vs *.example.com) [380.95ms] (pass) TLS wildcard hostname verification > should reject bare domain for wildcard cert (example.com vs *.example.com) [373.22ms] (pass) TLS wildcard hostname verification > should accept exact match for wildcard labels (bar.example.com vs *.example.com) [391.15ms] (pass) TLS wildcard hostname verification > should reject deeply nested subdomain (a.b.c.example.com vs *.example.com) [381.85ms] (pass) TLS wildcard hostname verification > should accept case-insensitive wildcard match (FOO.EXAMPLE.COM vs *.example.com) [257.09ms] (pass) TLS wildcard hostname verification > should accept mixed-case wildcard match (FoO.ExAmPlE.cOm vs *.example.com) [246.58m ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 576ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/126] gen cpp.rs (cppbind) [2/126] gen JS modules (bundle-modules) Preprocess modules (6548ms) Bundle modules (44ms) Postprocesss modules (19ms) Bundle Functions (402ms) Generate Code (23ms) [7.04s] Bundled "src/js" for production 2600 kb 197 internal modules 13 native modules 50 internal functions across 16 files [2/9] cargo bun_runtime → libbun_runtime.a �[1m�[33mwarning�[0m�[1m: binary `bun_shim_impl` should have a kebab-case name�[0m �[1m�[94m|�[0m �[1m�[94m 1�[0m �[1m�[94m|�[0m /workspace/bun/build/release/rust-target/.../bun_shim_impl �[1m�[94m|�[0m �[1m�[33m^^^^^^^^^^^^^�[0m �[1m�[94m|�[0m �[1m�[94m= �[0m�[1mnote�[0m: `cargo::non_kebab_case_bins` is set to `warn` by default �[1m�[96mhelp�[0m: to change the binary name to `bun-shim-impl`, convert `bin.name` �[1m�[94m--> �[0msrc/install/windows-shim/Cargo.toml:41:8 �[1m�[94m|�[0m �[1m�[94m41�[0m �[91m- �[0mname = �[91m"bun_shim_impl"�[0m �[1m�[94m41�[0m �[92m+ �[0mname = �[92m" ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/boringssl/lib.rs | 38 +++++- src/js/internal/url.ts | 5 + src/js/node/tls.ts | 14 +- src/js/node/url.ts | 3 +- src/jsc/bindings/NodeURL.cpp | 9 ++ .../parallel/test-tls-check-server-identity.js | 30 +++++ test/js/web/fetch/fetch.tls.wildcard.test.ts | 149 ++++++++++++++++++++- 7 files changed, 241 insertions(+), 7 deletions(-) ``` </details> **gate history** · 2 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/boringssl/lib.rs 6 6 25 src/js/internal/url.ts 1 1 24 src/js/node/tls.ts 4 4 26 src/js/node/url.ts 1 1 24 src/jsc/bindings/NodeURL.cpp 2 2 24 …js/node/test/parallel/test-tls-check-server-identity.js 0 0 32 test/js/web/fetch/fetch.tls.wildcard.test.ts 4 7 24 ``` </details> <!-- robobun:evidence:end -->
1 parent ebfad4c commit 8705d89

7 files changed

Lines changed: 241 additions & 7 deletions

File tree

‎src/boringssl/lib.rs‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,10 @@ fn match_hostname(pattern: &[u8], hostname: &[u8], opts: MatchOpts) -> bool {
400400
&hostname[..end]
401401
};
402402

403+
// Node lets `*` match the empty label of ".example.com", the IDNA form of "。example.com".
404+
if host_first.is_empty() {
405+
return false;
406+
}
403407
if prefix.len() + suffix.len() > host_first.len() {
404408
return false;
405409
}
@@ -434,9 +438,27 @@ fn match_dns_name(pattern: &[u8], hostname: &[u8]) -> bool {
434438
match_hostname(pattern, hostname, MatchOpts::TLS_CHECK)
435439
}
436440

441+
unsafe extern "C" {
442+
/// `url.domainToASCII` in NodeURL.cpp. `Tag::Dead` when `domain` is not a valid host.
443+
safe fn Bun__domainToASCII(domain: &bun_core::String) -> bun_core::String;
444+
}
445+
437446
pub fn check_x509_server_identity(x509: &mut boring::X509, hostname: &[u8]) -> bool {
447+
// As in Node.js, a host is an IP address only as typed, not after the IDNA mapping.
448+
let host_is_ip = bun_core::ip_address::is_ip_address(unfqdn(hostname));
449+
let ascii_hostname;
450+
// CVE-2026-48618: IDNA maps "。" to ".", so a non-ASCII host is matched on `domainToASCII(host)`.
451+
let hostname = if strings::first_non_ascii(hostname).is_some() {
452+
let ascii = Bun__domainToASCII(&bun_core::String::borrow_utf8(hostname));
453+
if ascii.is_dead() {
454+
return false;
455+
}
456+
ascii_hostname = ascii.to_owned_slice();
457+
&ascii_hostname[..]
458+
} else {
459+
hostname
460+
};
438461
let hostname = unfqdn(hostname);
439-
let host_is_ip = bun_core::ip_address::is_ip_address(hostname);
440462
let mut has_dns_san = false;
441463

442464
match x509.subject_alt_names() {
@@ -651,6 +673,18 @@ impl core::fmt::Display for NameBytes<'_> {
651673
}
652674
}
653675

676+
/// The host as typed, as Node.js prints it. Invalid UTF-8 takes the `NameBytes` escaping.
677+
struct HostName<'a>(&'a [u8]);
678+
679+
impl core::fmt::Display for HostName<'_> {
680+
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
681+
match core::str::from_utf8(self.0) {
682+
Ok(host) => f.write_str(host),
683+
Err(_) => NameBytes(self.0).fmt(f),
684+
}
685+
}
686+
}
687+
654688
/// Node's `subjectaltname` rendering of an IP entry: dotted IPv4, or IPv6 as
655689
/// uncompressed lowercase-hex groups (`0:0:0:0:0:0:0:1`).
656690
struct AltNameIp<'a>(&'a [u8]);
@@ -740,7 +774,7 @@ pub fn write_server_identity_mismatch_reason(
740774
) -> core::fmt::Result {
741775
const NO_DNS: &str = "Cert does not contain a DNS name";
742776
let hostname = unfqdn(hostname);
743-
let host = NameBytes(hostname);
777+
let host = HostName(hostname);
744778
let host_is_ip = bun_core::ip_address::is_ip_address(hostname);
745779

746780
let Some(x509) = ssl_ptr.peer_leaf_certificate() else {

‎src/js/internal/url.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
const [domainToASCII, domainToUnicode, idnaToASCII] = $cpp("NodeURL.cpp", "Bun::createNodeURLBinding");
2+
13
function urlToHttpOptions(url) {
24
const options = {
35
...url,
@@ -23,5 +25,8 @@ function urlToHttpOptions(url) {
2325
}
2426

2527
export default {
28+
domainToASCII,
29+
domainToUnicode,
30+
idnaToASCII,
2631
urlToHttpOptions,
2732
};

‎src/js/node/tls.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ const Duplex = require("internal/streams/duplex");
55
const EventEmitter = require("node:events");
66
const addServerName = $newRustFunction("Listener.rs", "jsAddServerName", 3);
77
const { throwNotImplemented } = require("internal/shared");
8+
const { domainToASCII } = require("internal/url");
89
const {
910
throwOnInvalidTLSArray,
1011
tlsStringToProtocolVersion,
@@ -396,6 +397,9 @@ function check(hostParts, pattern, wildcards) {
396397

397398
const { 0: prefix, 1: suffix } = patternSubdomainParts;
398399

400+
// Node lets "*" match the empty label of ".example.com", the IDNA form of "。example.com".
401+
if (hostSubdomain === "") return false;
402+
399403
if (prefix.length + suffix.length > hostSubdomain.length) return false;
400404

401405
if (!StringPrototypeStartsWith.$call(hostSubdomain, prefix)) return false;
@@ -450,6 +454,12 @@ function checkServerIdentity(hostname, cert) {
450454
const ips = [];
451455

452456
hostname = "" + hostname;
457+
// CVE-2026-48618, https://github.com/nodejs/node/commit/1efb4ff51a: IDNA maps "。" to ".".
458+
const hostnameASCII = domainToASCII(hostname);
459+
460+
// Remove trailing dots for error messages and matching.
461+
hostname = unfqdn(hostname);
462+
const hostnameASCIIWithoutFQDN = unfqdn(hostnameASCII);
453463

454464
if (altNames) {
455465
const splitAltNames = StringPrototypeIncludes.$call(altNames, '"')
@@ -467,14 +477,14 @@ function checkServerIdentity(hostname, cert) {
467477
let valid = false;
468478
let reason = "Unknown reason";
469479

470-
hostname = unfqdn(hostname); // Remove trailing dot for error messages.
480+
// https://github.com/nodejs/node/commit/1d87a24050: domainToASCII("::1") is "", so IP hosts stay as typed.
471481
if (net.isIP(hostname)) {
472482
valid = ArrayPrototypeIncludes.$call(ips, canonicalizeIP(hostname));
473483
if (!valid) reason = `IP: ${hostname} is not in the cert's list: ` + ArrayPrototypeJoin.$call(ips, ", ");
474484
} else {
475485
const hasDnsNames = dnsNames.length > 0;
476486
if (hasDnsNames || subject?.CN) {
477-
const hostParts = splitHost(hostname);
487+
const hostParts = splitHost(hostnameASCIIWithoutFQDN);
478488
const wildcard = pattern => check(hostParts, pattern, true);
479489

480490
if (hasDnsNames) {

‎src/js/node/url.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,7 @@
2626
"use strict";
2727

2828
const { URL, URLSearchParams, URLPattern } = globalThis;
29-
const [domainToASCII, domainToUnicode, idnaToASCII] = $cpp("NodeURL.cpp", "Bun::createNodeURLBinding");
30-
const { urlToHttpOptions } = require("internal/url");
29+
const { domainToASCII, domainToUnicode, idnaToASCII, urlToHttpOptions } = require("internal/url");
3130
const { validateString, validateObject } = require("internal/validators");
3231
const ObjectSetPrototypeOf = Object.setPrototypeOf;
3332

‎src/jsc/bindings/NodeURL.cpp‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,15 @@ static String parseDomainAsHost(const String& domain)
157157
return parsedHost;
158158
}
159159

160+
// url.domainToASCII for src/boringssl/lib.rs, on any thread. Dead when the host does not parse.
161+
extern "C" BunString Bun__domainToASCII(const BunString* domain)
162+
{
163+
auto host = parseDomainAsHost(domain->toWTFString());
164+
if (host.isNull())
165+
return { BunStringTag::Dead };
166+
return Bun::toStringRef(host);
167+
}
168+
160169
JSC_DEFINE_HOST_FUNCTION(jsDomainToASCII, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
161170
{
162171
auto& vm = JSC::getVM(globalObject);

‎test/js/node/test/parallel/test-tls-check-server-identity.js‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,27 @@ const tests = [
100100
cert: { subject: { CN: '8.8.8.8' }, subjectaltname: 'IP Address:8.8.8.8' }
101101
},
102102

103+
// An "IP Address:" SAN also matches an IPv6 host. Regression test for the
104+
// IDNA-normalization change: domainToASCII('::1') === '' (an IPv6 literal is
105+
// not a domain), which made the normalized host skip IPv6 IP-SAN matching.
106+
{
107+
host: '::1',
108+
cert: { subject: {}, subjectaltname: 'IP Address:::1' }
109+
},
110+
111+
// IPv6 hosts and SANs are matched canonically.
112+
{
113+
host: '2001:db8::1',
114+
cert: { subject: {}, subjectaltname: 'IP Address:2001:DB8:0:0:0:0:0:1' }
115+
},
116+
117+
// A non-matching IPv6 "IP Address:" SAN is rejected.
118+
{
119+
host: '::1',
120+
cert: { subject: {}, subjectaltname: 'IP Address:::2' },
121+
error: 'IP: ::1 is not in the cert\'s list: ::2'
122+
},
123+
103124
// But not when it's a CIDR.
104125
{
105126
host: '8.8.8.8',
@@ -381,6 +402,15 @@ const tests = [
381402
error: 'Host: localhost. is not in the cert\'s altnames: ' +
382403
'DNS:a.com'
383404
},
405+
{
406+
host: 'foo。bar.example.com',
407+
cert: {
408+
subjectaltname: 'DNS:*.example.com',
409+
subject: {}
410+
},
411+
error: 'Host: foo。bar.example.com. is not in the cert\'s altnames: ' +
412+
'DNS:*.example.com'
413+
},
384414
// IDNA
385415
{
386416
host: 'xn--bcher-kva.example.com',

‎test/js/web/fetch/fetch.tls.wildcard.test.ts‎

Lines changed: 148 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -300,14 +300,100 @@ describe.concurrent("TLS wildcard hostname verification", () => {
300300
expect(result.success).toBe(true);
301301
expect(result.error).toBeUndefined();
302302
});
303+
304+
// UTS #46 maps these three code points to ".", so a resolver that applies
305+
// IDNA looks up "foo.bar.example.com", two labels below example.com
306+
// (Node.js CVE-2026-48618).
307+
const unicodeFullStops = [
308+
["U+3002", "foo\u3002bar.example.com"],
309+
["U+FF0E", "foo\uff0ebar.example.com"],
310+
["U+FF61", "foo\uff61bar.example.com"],
311+
];
312+
313+
it.each(unicodeFullStops)("tls.connect should reject a %s full stop in servername", async (_name, servername) => {
314+
using server = Bun.serve({
315+
port: 0,
316+
tls: wildcardExampleComTls,
317+
fetch() {
318+
return new Response("Hello");
319+
},
320+
});
321+
322+
const { promise, resolve } = Promise.withResolvers<unknown>();
323+
const socket = tls.connect({
324+
host: "127.0.0.1",
325+
port: server.port,
326+
ca: wildcardExampleComTls.cert,
327+
servername,
328+
});
329+
socket.on("secureConnect", () => resolve({ authorized: socket.authorized }));
330+
socket.on("error", resolve);
331+
try {
332+
expect(await promise).toMatchObject({
333+
code: "ERR_TLS_CERT_ALTNAME_INVALID",
334+
host: servername,
335+
message:
336+
"Hostname/IP does not match certificate's altnames: " +
337+
`Host: ${servername}. is not in the cert's altnames: DNS:*.example.com`,
338+
});
339+
} finally {
340+
socket.destroy();
341+
}
342+
});
343+
344+
it.each(unicodeFullStops)("Bun.connect should reject a %s full stop in tls.serverName", async (_name, serverName) => {
345+
using server = Bun.serve({
346+
port: 0,
347+
tls: wildcardExampleComTls,
348+
fetch() {
349+
return new Response("Hello");
350+
},
351+
});
352+
353+
const { promise, resolve, reject } = Promise.withResolvers<unknown>();
354+
const socket = await Bun.connect({
355+
hostname: "127.0.0.1",
356+
port: server.port,
357+
tls: { ca: wildcardExampleComTls.cert, serverName },
358+
socket: {
359+
handshake(s, success) {
360+
const error = s.getAuthorizationError();
361+
resolve({ success, authorized: s.authorized, code: error?.code, message: error?.message });
362+
},
363+
data() {},
364+
error(_s, err) {
365+
reject(err);
366+
},
367+
connectError(_s, err) {
368+
reject(err);
369+
},
370+
close() {
371+
reject(new Error("closed before the handshake callback"));
372+
},
373+
},
374+
});
375+
try {
376+
expect(await promise).toEqual({
377+
success: false,
378+
authorized: false,
379+
code: "ERR_TLS_CERT_ALTNAME_INVALID",
380+
message:
381+
"Hostname/IP does not match certificate's altnames: " +
382+
`Host: ${serverName}. is not in the cert's altnames: DNS:*.example.com`,
383+
});
384+
} finally {
385+
socket.end();
386+
}
387+
});
303388
});
304389

305390
// Bun exposes three certificate-name matchers that must agree with Node.js:
306391
// - tls.checkServerIdentity() -> JS port of Node lib/tls.js check()
307392
// - fetch() / WebSocket / Bun.connect / SQL -> native Rust port of check()
308393
// - X509Certificate#checkHost -> native port of OpenSSL X509_check_host
309394
// The first two share semantics; checkHost follows OpenSSL where Node does.
310-
// Every expected value below was taken from Node.js v26.3.0.
395+
// Every expected value below was taken from Node.js v26.3.0, unless a comment
396+
// names a later version.
311397
describe("TLS certificate name matching: fetch() / checkServerIdentity / checkHost agree", () => {
312398
// Minimal DER encoder sufficient to build a self-signed EC certificate with
313399
// an arbitrary subjectAltName. Real CAs don't issue partial-wildcard SANs,
@@ -421,6 +507,25 @@ describe("TLS certificate name matching: fetch() / checkServerIdentity / checkHo
421507
["ww.mid.test", true, undefined],
422508
["abc.mid.test", false, undefined],
423509
["cn-not-in-san.test", false, undefined],
510+
// UTS #46 maps U+3002, U+FF0E and U+FF61 to ".". Both matchers match a
511+
// non-ASCII host on url.domainToASCII(host) (Node.js CVE-2026-48618, values
512+
// from v26.8.2). checkHost hands the raw host to OpenSSL, where "*" only
513+
// spans LDH bytes. An ASCII host reaches the native matcher as typed, so
514+
// the two differ on one that is not a valid URL host ("a b.wild.test").
515+
["foo\u3002bar.wild.test", false, undefined],
516+
["foo\uff0ebar.wild.test", false, undefined],
517+
["foo\uff61bar.wild.test", false, undefined],
518+
["foo\u3002wild.test", true, undefined],
519+
["exact\u3002test", true, undefined],
520+
["exact.test\u3002", true, undefined],
521+
["b\u00fccher.wild.test", true, undefined],
522+
["\uff46oo.partial.test", true, undefined],
523+
// Node's check() lets "*" match the empty first label of ".wild.test", and
524+
// domainToASCII turns "\u3002wild.test" into that host. Both Bun matchers
525+
// reject an empty label. checkHost reads a leading "." as OpenSSL's
526+
// subdomain form.
527+
[".wild.test", false, "*.wild.test"],
528+
["\u3002wild.test", false, undefined],
424529
];
425530

426531
describe.concurrent("checkServerIdentity == fetch", () => {
@@ -437,6 +542,48 @@ describe("TLS certificate name matching: fetch() / checkServerIdentity / checkHo
437542
});
438543
});
439544

545+
// tls.checkServerIdentity matches DNS names on url.domainToASCII(host) and
546+
// reports the host as typed. IP hosts skip domainToASCII, which returns ""
547+
// for "::1". Every expected value was taken from Node.js v26.8.2, except the
548+
// two hosts with an empty first label: Node lets "*" match it, Bun does not.
549+
describe("checkServerIdentity matches on domainToASCII(host)", () => {
550+
const wildcardSan = { subjectaltname: "DNS:*.example.com", subject: {} };
551+
const notInAltnames = (host: string) => `Host: ${host}. is not in the cert's altnames: DNS:*.example.com`;
552+
it.each([
553+
["foo\u3002bar.example.com", wildcardSan, notInAltnames("foo\u3002bar.example.com")],
554+
["foo\uff0ebar.example.com", wildcardSan, notInAltnames("foo\uff0ebar.example.com")],
555+
["foo\uff61bar.example.com", wildcardSan, notInAltnames("foo\uff61bar.example.com")],
556+
["a b.example.com", wildcardSan, notInAltnames("a b.example.com")],
557+
[".example.com", wildcardSan, notInAltnames(".example.com")],
558+
["\u3002example.com", wildcardSan, notInAltnames("\u3002example.com")],
559+
[
560+
"foo\u3002bar.example.com",
561+
{ subject: { CN: "*.example.com" } },
562+
"Host: foo\u3002bar.example.com. is not cert's CN: *.example.com",
563+
],
564+
["foo\u3002bar.example.com", { subjectaltname: "DNS:*.bar.example.com", subject: {} }, undefined],
565+
["foo\u3002bar.example.com\u3002", { subjectaltname: "DNS:foo.bar.example.com", subject: {} }, undefined],
566+
["b\u00fccher.example.com", { subjectaltname: "DNS:xn--bcher-kva.example.com", subject: {} }, undefined],
567+
["::1", { subjectaltname: "IP Address:0:0:0:0:0:0:0:1", subject: {} }, undefined],
568+
])("%j vs %j", (host, cert, reason) => {
569+
const err = tls.checkServerIdentity(host, cert as tls.PeerCertificate) as any;
570+
expect(err === undefined ? undefined : { code: err.code, reason: err.reason, host: err.host }).toEqual(
571+
reason === undefined ? undefined : { code: "ERR_TLS_CERT_ALTNAME_INVALID", reason, host },
572+
);
573+
});
574+
575+
// A host is an IP address only as typed. domainToASCII maps this one to
576+
// "127.0.0.1", and Node still matches it as a DNS name.
577+
it("a host that maps to an IPv4 literal does not match an IP SAN", async () => {
578+
const m = makeCert("x", [["ip", "127.0.0.1"]]);
579+
const host = "\uff11\uff12\uff17.0.0.1";
580+
expect({ csi: csi(m.x509, host), fetch: await fetchOk(m, host) }).toEqual({
581+
csi: false,
582+
fetch: { ok: false, code: "ERR_TLS_CERT_ALTNAME_INVALID" },
583+
});
584+
});
585+
});
586+
440587
// Rejections Node's check() applies to the pattern that the native matcher
441588
// must not relax. The checkHost column is Node/OpenSSL's verdict; where that
442589
// falls through to equal_nocase (a..b.test) it matches even though Node's

0 commit comments

Comments
 (0)