Skip to content

tls: a server name that is not a hostname matches no certificate name - #43873

Merged
Jarred-Sumner merged 5 commits into
mainfrom
robobun/aedaaf2c/tls-hostname-fail-closed
Sep 25, 2026
Merged

Jarred-Sumner merged 5 commits into
mainfrom
robobun/aedaaf2c/tls-hostname-fail-closed

Conversation

@robobun

@robobun robobun commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • tls.checkServerIdentity("localhost/.evil.test", cert) accepts a certificate for *.evil.test, and so do tls.connect, fetch and Bun.connect. An application that validates the name with a URL parser sees localhost.
  • Both matchers compare an ASCII host as typed (src/js/node/tls.ts:488, src/boringssl/lib.rs:446), so * covers any first label, also localhost/. Every Bun release and Node v26.3.0 do this.

Fix

  • In both matchers, a DNS host with a character outside letters, digits, -, _ and . matches nothing. The rule runs after the IDNA step. It supersedes "an ASCII host is matched as typed" from tls: match a server identity on the IDNA mapping alone, not on a URL host parse #43040.
  • IP hosts: the native matcher takes only the strict form of net.isIP (127.1 matched the IP SAN 127.1.0.0). tls.checkServerIdentity no longer matches ::1%lo against a malformed IP SAN.
  • Verified: test/js/web/fetch/fetch.tls.wildcard.test.ts (35 of 183 fail on main, with a sweep of the 62 excluded ASCII bytes). Self-reviewed: 13 concerns, 4 changes made, 3 follow-ups (Notes).

Background

Downsides

  • Node v26.8.2 rejects 43 of the 62 bytes (/, ?, #, space, @). Only Bun rejects the other 19, a literal * host, and an exact name like exact!name.test against the same SAN. A test that expects Node's result fails.
  • Cost: 425 bytes less text in the release binary. tls.checkServerIdentity for a plain hostname: 2,476 ns per call, main 2,494, noise floor 0.9%. Native: one more host scan per handshake.
Notes

Repro (no network)

const tls = require("tls");
const cert = { subjectaltname: "DNS:*.evil.test", subject: {} };
for (const host of ["localhost/.evil.test", "localhost?.evil.test", "localhost#.evil.test", "localhost\\.evil.test", "db:5432/.evil.test"])
  console.log(JSON.stringify(host).padEnd(26), tls.checkServerIdentity(host, cert) ? "rejected" : "ACCEPTED");
build result
Bun 1.4.2, Node v26.3.0 ACCEPTED
main with #42977 and without #43040 (6d504dd) rejected
main 2838e1b ACCEPTED
this branch, Node v26.8.2 rejected

End to end. The server has one certificate, DNS:*.evil.test. The client dials 127.0.0.1 with localhost/.evil.test as servername / tls.serverName.

entry point Bun 1.4.2 main 6d504dd (before #43040) main with #43040 this branch
tls.connect authorized rejected authorized rejected
fetch authorized authorized authorized rejected

The native matcher never had the URL host parse for an ASCII name, so fetch and Bun.connect accept the name in every build before this one.

Reach. Only a raw host or servername string gets there. It takes an application that validates the name with a URL parser (it sees localhost, or another single-label name that it trusts) and passes the raw string as servername, and an attacker who receives the connection with a *.evil.test certificate. It is the mirror image of the case that #43040 closed (evil.test/.example.com against a raw-string suffix check). One reading of the name is not enough: a name with two readings must not match.

The rule

  • The set is letters, digits, -, _ and .. An underscore is in it because such names exist (foo_bar.example.com under *.example.com keeps working). db.1, xn--a.example.com, a trailing dot and an IP literal keep working. A literal * in the host no longer matches a wildcard.
  • It runs on the name the matcher compares: as typed for an ASCII host, and the UTS Bun v0.0.41 #46 form for a host with a non-ASCII code point. So a mapped delimiter (localhost/.evil.test) is rejected, and bücher.example.com still matches xn--bcher-kva.example.com.
  • JS: an empty label list never matches in check(). Rust: host_is_dns_name gates the SAN loop and the CN fallback in check_x509_server_identity, the one function every native client calls. X509Certificate#checkHost keeps OpenSSL's rules, where * already covers only letters, digits and -.
  • The error text does not change: Host: localhost/.evil.test. is not in the cert's altnames: DNS:*.evil.test.

IP shorthand. check_x509_server_identity asked ares_inet_pton whether the host is an IP address. That function is inet_net_pton underneath: it reads 127.1 as 127.1.0.0 and 10 as 10.0.0.0, and it takes hex, zero-padded octets and a trailing /bits. A resolver reads 127.1 as 127.0.0.1, so such a name has two readings too. With a certificate that has the IP SANs 127.0.0.1, 127.1.0.0, 10.0.0.0, 1.2.3.4 and 1.2.3.0, fetch accepted 127.1, 10, 0x7f000001, 127.000.000.001, 1.2.3, 1.2.3.4/8 and 127.0.0.1/32 on Bun 1.4.2 and on main, and tls.checkServerIdentity rejected each of them. The native matcher now uses ip_address::parse_strict, and both reject them. net.isIP was already strict.

Zone ids. net.isIP takes an IPv6 address with a zone (::1%lo), and canonicalizeIP() returns undefined for it. It also returns undefined for a malformed iPAddress SAN, which the certificate prints as IP Address:<invalid>. tls.checkServerIdentity then found undefined in the list and accepted: with a certificate that has a 5-byte iPAddress SAN, Bun 1.4.2 and main accept ::1%lo and fe80::1%eth0, and Node and the native matcher reject them. The IP branch now needs a canonical form of the host. Both matchers reject a host with a zone, as before for a well-formed SAN. Node strips the zone and accepts ::1%lo for the IP SAN ::1. That is a follow-up, because both matchers need it.

Node and prior art. Of the 62 ASCII bytes outside the set (NUL aside), Node v26.3.0 accepts all 62 in the label under *, as Bun 1.4.2 does. Node v26.8.2 rejects 43, because its url.domainToASCII step fails on them. It accepts the other 19: tab, CR and LF, which the URL parse drops, and !"$&'()*+,;=`{}~, which are URL host characters. Of the 21 hosts that the tests pin as rejected, v26.8.2 rejects 18 with the same code, reason and host. It accepts *.wild.test, *.example.com and exact!name.test, and the tests mark those rows as Bun only. rustls and mozilla::pkix (Firefox) refuse a reference name that is not a DNS name in the same way, and both allow the underscore. Go limits wildcard matches to valid hostnames and keeps an exact match.

Differential run. 3,682 pairs of a host and a certificate through tls.checkServerIdentity and fetch (tls.serverName). main: 656 accepted, of which 401 have an ASCII character outside the set (for example foo\r.wild.test under *.wild.test). This branch: 178 accepted, 0 with such a character. The one difference between the matchers in that run is the empty serverName, which means "not set". The run is a script outside the tree. In the tree, the test file now sweeps all 62 bytes through both matchers on one server, and a grid of IP shorthand, zone ids and a malformed iPAddress SAN.

Cost. Release builds of main 2838e1b with and without this diff. size: text 80,659,886 to 80,659,461 bytes (-425, the strict parse replaces two ares_inet_pton calls with their 512-byte buffers), data and bss unchanged, file 80,827,936 bytes in both. The first commit alone was +87 bytes. CPU per call from process.cpuUsage() for tls.checkServerIdentity("foo.example.com", cert), 2e6 calls, 11 interleaved rounds of main, this diff, main again: 2,494, 2,476 and 2,516 ns. The JS matcher adds one regex test per DNS-name check. The native matcher adds one pass over the host bytes per handshake, and it parses the host once with core::net where it called ares_inet_pton up to twice. perf, valgrind and bloaty are not on this machine, so there is no instruction count.

Self-review. It asked for four changes, and all are in: the guard in the JS IP branch, test comments that name the rows only Bun rejects, this description (it supersedes the rule of #43040 and splits the rejected names by Node's verdict), and the in-tree sweep in place of the script. Follow-ups, not in this PR: tls.checkServerIdentity can call the Rust matcher, so that one implementation is left. bun_core::ip_address::is_ip_address still uses ares_inet_pton at its other call sites, which only decide whether to send SNI. bun_boringssl is not in the crates that CI runs under Miri.

Tests

  • fetch.tls.wildcard.test.ts: tls.connect and Bun.connect end to end for localhost/.example.com and the U+FF0F form, 12 rows in the checkServerIdentity == fetch table (9 rejected, and foo_bar, foo-bar, xn--a accepted), and 13 rows for tls.checkServerIdentity with the error text (SAN, CN fallback, an exact odd name, a literal *, and foo_bar and a trailing dot accepted). The rows for a b and user@foo from tls: match a server identity on the IDNA mapping alone, not on a URL host parse #43040 now expect a rejection. Three rows for the native CN fallback (a certificate with the CN *.cn.a.test and no SAN, one of them localhost/.cn.a.test through fetch), and 8 rows for IP shorthand through both matchers. One test sweeps the 62 bytes through both matchers, and 3 rows cover zone ids with a malformed iPAddress SAN. main 8d36bff: 148 pass, 35 fail. This branch: 183 pass.
  • Also ran with the debug build: test-tls-check-server-identity.js, node-tls-connect-hostname-verification.test.ts, node-https-checkServerIdentity.test.ts, fetch.tls.test.ts, fetch.tls.ipv6.test.ts, valkey-tls-verify.test.ts, node-tls-cert.test.ts, node-tls-connect.test.ts, tls-sql.test.ts. All pass.

Both matchers compared an ASCII host as typed. The "*" of a wildcard
then covers a first label that holds a URL delimiter:
"localhost/.evil.test" passed for a certificate of "*.evil.test", and a
URL parser reads that name as the host "localhost".

For a DNS-name match, a host with a character outside letters, digits,
"-", "_" and "." (after the IDNA step) now matches nothing, in
tls.checkServerIdentity and in the native matcher.
@robobun

robobun commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: the fix is pushed and the PR is ready for review.

How to reproduce the bug on a build without this change:

const tls = require("tls");
const cert = { subjectaltname: "DNS:*.evil.test", subject: {} };
for (const host of ["localhost/.evil.test", "localhost#.evil.test", "db:5432/.evil.test"])
  console.log(JSON.stringify(host), tls.checkServerIdentity(host, cert) ? "rejected" : "ACCEPTED");
  • Bun 1.4.2, main 2838e1b and Node v26.3.0 print ACCEPTED for each host.
  • This branch and Node v26.8.2 print rejected.

For the native matcher, dial a server whose only certificate is DNS:*.evil.test with fetch(url, { tls: { ca, serverName: "localhost/.evil.test" } }) or Bun.connect. Every build before this one connects. This branch fails with ERR_TLS_CERT_ALTNAME_INVALID.

The native matcher also took IP shorthand for an IP address: with a certificate that has the IP SAN 127.1.0.0, fetch with serverName: "127.1" connects on every build before this one, and tls.checkServerIdentity("127.1", cert) rejects. This branch rejects in both.

tls.checkServerIdentity("::1%lo", { subjectaltname: "IP Address:<invalid>", subject: {} }) accepts on every build before this one (canonicalizeIP() returns undefined for both sides). This branch and Node reject.

test/js/web/fetch/fetch.tls.wildcard.test.ts fails 35 of its 183 tests with the src/ of main 8d36bff. bun bd test passes all 183 with the fix.

CI: the diff is green. Builds #120169 (8c3bdcd) and #120180 (f994cab, the complete diff) passed on every lane. After main was merged into the branch, two tests that this PR does not touch failed, one in each build:

  • #120229: test/cli/inspect/inspect.test.ts, a segmentation fault on Windows 2019 x64. It did not happen again in the next build.
  • #120234: test/js/bun/util/filesink.test.ts on darwin aarch64 (ENOTCONN where the test expects EPIPE). The same test was flaky on debian aarch64 in #120229. The other 179 jobs passed.

Both are reported as breaks on main.

@coderabbitai

coderabbitai Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: oven-sh/bun/.coderabbit.yaml

Review profile: ASSERTIVE

Plan: Essentials

Run ID: db971cd6-f919-4391-92a5-e9218d506842

📥 Commits

Reviewing files that changed from the base of the PR and between f994cab and 7634e7b.

📒 Files selected for processing (1)
  • src/boringssl/lib.rs

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.


Walkthrough

TLS hostname checks now restrict DNS SAN and common-name matching to non-IP hosts with permitted ASCII characters. IP classification uses strict parsing. Tests cover rejected hostname inputs, accepted underscore and hyphen labels, and strict IPv4 matching.

Changes

TLS hostname validation

Layer / File(s) Summary
Hostname classification and matching
src/boringssl/lib.rs, src/js/node/tls.ts
BoringSSL requires valid non-IP hostnames for DNS SAN and common-name matching and uses strict IP parsing for host classification. JavaScript creates DNS labels only when the normalized hostname contains permitted characters.
Hostname validation tests
test/js/web/fetch/fetch.tls.wildcard.test.ts
Tests cover invalid hostname characters, underscore and hyphen labels, wildcard common-name matching, and IP SAN matching for strict IPv4 notation only.

Suggested reviewers: jarred-sumner

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 70229

This change tightens TLS certificate-name matching for invalid hostname characters and noncanonical IP forms. No concrete current-head issue was established in the inspected identity paths, so no actionable merge risk remains beyond normal checks.

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: invalid server names no longer match certificate names during TLS verification.
Description check ✅ Passed The description provides a detailed explanation of the problem, fix, scope, trade-offs, and verification results. It does not use the exact template headings, but it includes the required information …

Comment @coderabbitai help to get the list of available commands.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Beyond the inline findings, I also checked two things and ruled them out: the new is_hostname in src/boringssl/lib.rs uses .iter().all(...) with a predicate body (is_ascii_alphanumeric() || matches!(...)), which the byte-search source lint in test/internal/source-lints/byte-search.test.ts only flags for the b != b'x' shape, so it does not trip; and the JS check in src/js/node/tls.ts:489 goes through the module-load-captured RegExpPrototypeExec with $call, matching the file's existing tamper-resistant pattern.

Extended reasoning...

The change tightens TLS certificate hostname matching in both the Rust native matcher and the node:tls JS matcher, plus test updates; it is a security-sensitive path (certificate identity verification for tls.connect, fetch, Bun.connect). Inline findings were posted, so a human look is already signalled; this note only records the two extra checks (source lint applicability and primordial-safe regex call) that were examined and found not to be issues.

Comment thread src/js/node/tls.ts Resolved
Comment thread src/boringssl/lib.rs Resolved
Comment thread src/boringssl/lib.rs Resolved
@robobun

robobun commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 8:18 AM PT - Sep 24th, 2026

✅ @robobun, your commit 2723321d8564e3e128b1cdfb263cadc961f98187 passed in Build #120315! 🎉


🧪   To try this PR locally:

bunx bun-pr 43873

That installs a local version of the PR into your bun-43873 executable, so you can run:

bun-43873 --bun

check_x509_server_identity asked ares_inet_pton, which also reads
"127.1" (as 127.1.0.0), "10", hex, zero-padded octets and "1.2.3.4/8".
fetch and Bun.connect then matched such a name against IP SANs, while
tls.checkServerIdentity treated it as a DNS name, and a resolver reads
"127.1" as 127.0.0.1. The host is now an IP address only in the strict
form.

Tests: the native CN fallback with a URL delimiter in the label, and the
IP shorthand rows through both matchers.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I re-reviewed after f994cab and found no new bugs; because this changes what every TLS client in Bun accepts as a server name, and deliberately diverges from Node for exact names containing non-hostname characters, a human look is still worthwhile.

What was reviewed:

  • The second commit addresses the two points from the earlier pass: parse_strict now classifies IP hosts in both check_x509_server_identity and write_server_identity_mismatch_reason (matching net.isIP for 127.1, 10, hex, zero-padded, /bits), and the new cnRows entries go through fetchOk, so the native CN-fallback gate is now exercised end to end.
  • Checked the two matchers agree on the input classes I could enumerate: plain/underscore/hyphen labels, trailing dot, xn-- names, IPv4 and IPv6 literals, IP shorthand, and every URL delimiter row; a zoned IPv6 literal (fe80::1%eth0) is classified as IP only by the JS side but is rejected by both, so the verdict is the same.
  • The remaining is_ip_address callers (http, websocket, proxy tunnel, DevServer) only decide whether to send SNI, not certificate matching, so they are outside this fix's class.
Extended reasoning...

The change tightens TLS server-identity matching in src/boringssl/lib.rs (native matcher used by fetch, Bun.connect, postgres, valkey, WebSocket) and src/js/node/tls.ts (tls.checkServerIdentity), adding an is_hostname byte-class gate on DNS-name matching and the CN fallback, and switching IP classification to strict parsing; the test file adds rejected-servername, IP-shorthand and CN-fallback rows and flips two prior expectations with a stated reason. This is security-sensitive certificate validation reachable by every TLS client. No new defects were found this run, and the prior run's inline findings on IP classification and CN-fallback coverage are addressed by f994cab, but the PR knowingly rejects exact-name matches such as DNS:exact!name.test that Node accepts, which is a product decision a maintainer should weigh rather than an automated approval.

Jarred-Sumner and others added 3 commits September 23, 2026 23:32
net.isIP takes an IPv6 address with a zone ("::1%lo"), and
canonicalizeIP() returns undefined for it. It also returns undefined for
a malformed iPAddress SAN, so tls.checkServerIdentity compared undefined
with undefined and accepted the certificate. The native matcher rejects
such a host.

Tests: every ASCII byte outside the hostname set under a wildcard,
through both matchers on one server. Zone-id hosts against a certificate
with a 5-byte iPAddress SAN. The comments name the rows that only Bun
rejects.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

The follow-up commits cover what I raised on the earlier pushes: both native gates in check_x509_server_identity and the mismatch-reason writer now classify the host with parse_strict, so 127.1 / 1.2.3.4/8 get the same verdict from fetch and tls.checkServerIdentity, and the CN-fallback table now drives localhost/.cn.a.test through the native matcher with a SAN-less wildcard CN. Beyond the inline note, I also checked that the new is_hostname byte predicate and the JS regex agree on the same character set after the IDNA step, and that * / ! / a trailing dot / xn-- labels land on the intended side in both matchers.

Extended reasoning...

The diff touches the two TLS server-identity matchers (src/boringssl/lib.rs native path used by fetch, Bun.connect and the DB clients, and src/js/node/tls.ts checkServerIdentity) plus the wildcard test file, so it is certificate-validation security code with a stated, commented divergence from Node.js. The latest commits address the matcher-disagreement and untested-CN-gate points from prior rounds, and the remaining inline finding is a pre-existing Node compat gap for zone-id IPv6 hosts rather than something this PR introduces. A human should still weigh the deliberate rejection of exact-match names containing non-hostname bytes, which is a behavior change for node:tls users.

Comment thread src/js/node/tls.ts Resolved
@Jarred-Sumner
Jarred-Sumner merged commit 262530d into main Sep 25, 2026
10 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the robobun/aedaaf2c/tls-hostname-fail-closed branch September 25, 2026 21:44
Jarred-Sumner pushed a commit that referenced this pull request Sep 25, 2026
…st names (#43979)

Follow-up to #43873, found by code reading. Supersedes #39931.

### Problem
- `bun_core::ip_address` parses with c-ares `ares_inet_pton`, which is
`inet_net_pton`. It also takes `127.1`, `0x7f000001`, zero-padded octets
and a trailing `/bits`.
- `Bun.connect` and `Bun.udpSocket` dial `::` for `::1/64`. On Windows
they dial 127.1.0.0 for `127.1`, and elsewhere 127.0.0.1 for `127.0.0.1
db.example`.
- fetch, `Bun.connect`, `RedisClient` and `Bun.SQL` verify `0x7f000001`
against a certificate for 127.0.0.1. fetch sends no SNI for `127.1`.

### Fix
- `is_ip_address`, `is_ipv6_address`, the IPv6 arm of `to_ip_address`
and its IPv4 arm on Windows use the `core::net` parser.
- Elsewhere the IPv4 arm keeps `inet_aton` and takes a host only when
`inet_aton` read it all. The dev server Host check accepts that
shorthand too.
- Verified on Linux: 75 new test rows in 8 files, 58 fail on main. On
Windows: 68 of the rows.
- Self-reviewed: 12 concerns raised, 11 addressed. The tarball case has
no test.

### Background
- SNI is the host name in the first TLS message. RFC 6066 forbids an IP
literal there.
- Weighed: the strict parse at each call site. It leaves a lenient
`is_ip_address` for the callers that #42766 and #42054 add.

### Downsides
- Breaking: a host in hex, zero-padded or `/bits` form no longer matches
an IP address in a certificate, only the same text.
- Breaking: `Bun.connect` answers `ENOTFOUND` for `"127.0.0.1\n"` and
any host with text after whitespace. On Windows also for `0x7f000001`
and `127.0.0.1/32`.
- Cost: release `.text` -1,024 bytes. Instructions per call fall, with
two exceptions: IPv4 shorthand at the dev server (`127.1`: 471 to 1,391)
and `::1/64` in `to_ip_address` (520 to 538).

<details><summary>Notes</summary>

**What changes, by caller**

| Function | Callers | A host in shorthand before | Now |
| --- | --- | --- | --- |
| `is_ip_address` | SNI in `src/http/lib.rs`, `ProxyTunnel.rs`,
`WebSocketUpgradeClient.rs`, `WebSocketProxyTunnel.rs` | no SNI | SNI as
typed, as `tls.connect` |
| | certificate check, `src/boringssl/lib.rs` (file not touched) |
`0x7f000001` matched IP:127.0.0.1 | a name: matches a dNSName or CN with
that text only |
| | `bun install` DNS prefetch, `src/url/lib.rs` | a registry host
arrives canonical | the same. A host that the URL parser rejects
(`08.1.1.1`) is now prefetched |
| `is_ip_address` and `to_ip_address` | dev server Host check,
`src/runtime/bake/DevServer.rs` (the one call site that changes) |
allowed | what the resolver reads stays allowed (`127.1`), the rest is
refused (`[::1/64]`) |
| `to_ip_address`, IPv6 arm | `Bun.connect`, `Bun.listen`,
`Bun.udpSocket`, `is_valid_hostname`, `strip_ipv6_brackets` (20 call
sites) | `::1/64` was the address `::` | not an address: `ENOTFOUND`,
`Invalid address`, brackets stay |
| `to_ip_address`, IPv4 arm on Windows | the same callers | `127.1` was
127.1.0.0, `127.0.0.1/32` was an address | not an address, as for the
Windows resolver |
| `to_ip_address`, IPv4 arm elsewhere | the same callers | `127.0.0.1
db.example` was 127.0.0.1, because `inet_aton` stops at whitespace or a
NUL | not an address. `127.1` stays 127.0.0.1 |
| `is_ipv6_address` | `normalize_dns_name`, brackets of a displayed URL
| `::1/64` was IPv6 | not reached: `is_valid_hostname` rejects it first
|

Shorthand gets to the TLS callers from `tls.serverName`, a proxy in
`HTTP_PROXY` or `HTTPS_PROXY`, a tarball URL and a `wss+unix:` URL host.
A `fetch` or `wss:` URL host, the `proxy` option and a registry URL go
through the URL parser first, which writes `127.1` as `127.0.0.1`.

`is_ipv6_address` and `to_ip_address` must change together. `do_lookup`
(`src/runtime/dns_jsc/dns.rs`) asks `is_valid_hostname` first, and that
asks `to_ip_address`. With a strict `is_ipv6_address` alone, `::1/64`
would stay on the c-ares backend, and c-ares reads it as a literal.

**Breaking changes, measured.** Linux rows: release builds of one tree
that differ only in the two source files. Windows rows: a debug build of
this branch against the canary of main (29d9638), on Windows Server
2019 x64.

| Case | main | this branch |
| --- | --- | --- |
| fetch, `ca` set, `tls.serverName` `0x7f000001`, `127.000.000.001`,
`127.0.0.1/32`, `127.0.0.1/8`, `::1/128` | verified |
`ERR_TLS_CERT_ALTNAME_INVALID` |
| `Bun.connect`, `socket.upgradeTLS`, `RedisClient`
(`rediss://0x7f000001`), `Bun.SQL` `sslmode=verify-full` | verified |
`ERR_TLS_CERT_ALTNAME_INVALID` |
| `HTTP_PROXY=https://0x7f000001:PORT` | verified, no SNI |
`ERR_TLS_CERT_ALTNAME_INVALID`, SNI `0x7f000001`. On Windows `ENOTFOUND`
|
| `bun install` of `https://0x7f000001:PORT/pkg.tgz` with `--cafile` |
installs | `ERR_TLS_CERT_ALTNAME_INVALID downloading tarball` |
| host `127.1` against a certificate with `DNS:127.1`, or `CN=127.1` and
no dNSName | rejected | verified |
| `127.1`, `10` against IP:127.0.0.1 | rejected | rejected |
| `Bun.connect` to `::1/64`, `::1/0`, `2001:db8::1/0`, `[::1/64]` |
connects to `::1` | `ENOTFOUND` |
| `Bun.udpSocket` `send()` to `::1/64`, `2001:db8::1/0` | delivered to
`::1` | throws `Invalid address` |
| Windows: `Bun.connect` to `127.1` | connects, the server sees
127.1.0.0 | `ENOTFOUND` |
| Windows: `Bun.connect` to `0x7f000001`, `127.000.000.001`,
`127.0.0.1/32` | connects to 127.0.0.1 | `ENOTFOUND` |
| Windows: `Bun.connect` to `1.2.3.4/8` | dials 1.2.3.4 | `ENOTFOUND` |
| Windows: `dns.lookup` of each of these, in Bun and in Node.js v26.3.0
| `ENOTFOUND` | `ENOTFOUND` |
| Linux: `Bun.connect` to `127.1`, `0x7f000001`, `2130706433` | connects
to 127.0.0.1 | the same |
| Linux: `Bun.connect` to `127.0.0.1 db.allowed.example`,
`"127.0.0.1\n"`, and the 7 other host names of #39931 | connects to
127.0.0.1 (`"12\t7.0.0.1"`: dials 0.0.0.12) | `ENOTFOUND`, with no
lookup |
| Linux: `Bun.udpSocket` `send()` to `127.0.0.1 rebound.example`, or to
`127.0.0.1` and a NUL and more text | delivered to 127.0.0.1 | throws
`Invalid address` |

**The dev server Host check**

| `Host` header | main | this branch |
| --- | --- | --- |
| `127.0.0.1`, `[::1]`, `localhost` | 200 | 200 |
| `127.1:PORT`, `0x7f000001`, `127.000.000.001` (raw, wget 1.25.0,
Python 3.13.5 urllib) | 200 | 200. On Windows 403, where no resolver
reads them |
| `[::1/64]`, `[::ffff:127.1]`, `1.2.3.4/8`, `08.1.1.1` | 200 | 403 |
| `2130706433`, `0.0.0.0x1` (`inet_aton` reads them, c-ares did not) |
403 | 200 |
| `127.0.0.1 rebound-host.example` (`inet_aton` stops at the space) |
403 | 403 |
| `rebound-host.example` | 403 | 403 |

An earlier commit of this branch made the check strict, which answered
403 to wget and Python at `http://127.1:PORT`. That stopped no DNS
rebinding request: a URL parser writes a dotted quad or rejects the
host, so a browser cannot send these forms. The check now takes an IP
literal, or a host that starts with a digit and that `to_ip_address`
reads as IPv4. Over 25,792 `Host` values, 1,924 go from allowed to
refused and 539 from refused to allowed. Each of the 539 has a number as
its last label, so none is a DNS name. #40946 reports that the check
cannot be configured, and #40733 adds `development.allowedHosts`.

**Measurements.** Release builds on Linux, one tree, the two source
files from main against this branch.
- Size (`size -A`, `nm -S`): `.text` 58,301,116 to 58,300,092 bytes.
File size 80,995,912 bytes in both. `HTTPClient::on_open::<true>` 1,684
to 1,474 bytes, `check_x509_server_identity` 1,481 to 1,336,
`parse_strict` 447 to 303, `to_ip_address` 477 to 724,
`is_allowed_host_header` 579 to 468.
- Instructions per call (`gdb` `stepi` from entry to return, callees
included, 3 equal runs per input):

| Input | `is_allowed_host_header` | `to_ip_address` |
| --- | --- | --- |
| `registry.npmjs.org` | 596 to 548 | 367 to 345 |
| `localhost` / `example.com` | 592 to 533 (`example.com`) | 386 to 352
/ 441 to 409 |
| `127.0.0.1` | 617 to 445 | 1,436 to 1,113 |
| `::1` (`[::1]` as a Host) | 1,055 to 959 | 424 to 366 |
| a 51-byte name | 792 to 465 | 435 to 177 |
| a 253-byte name | 724 to 524 | 347 to 216 |
| `127.1` | 471 to 1,391 | 1,048 to 813 |
| `0x7f000001` | 722 to 1,269 | |
| `::1/64` (verdict changes) | | 520 to 538 |

- Variants that I measured and dropped: `parse_strict` inlined by LLVM
(`.text` +1,024 bytes against main), `parse_strict` for the IPv6 arm too
(`to_ip_address("localhost")` 386 to 404), the Host check with
`to_ip_address` for every host (`registry.npmjs.org` 596 to 895), and a
check of the bytes in the Host check in place of the change in
`to_ip_address`.
- Stack (`objdump`): `is_allowed_host_header` `sub $0x228,%rsp` to `sub
$0x18,%rsp`, `on_open::<true>` `0x278` to `0x68`. Calls into c-ares per
check 2 to 0. No allocator call before or after.
- Classification by `is_ip_address`, through SNI on the real binaries:
141 server names, 19 go from address to name, 0 go the other way. The
result equals `net.isIP` without a zone on every name.
- SNI over fetch, a CONNECT tunnel and `wss+unix:`: 28 of 28 shorthand
cells change and equal `tls.connect`. 0 of 8 literal cells change.
- DNS prefetch calls per `bun install` (`gdb` breakpoint count):
`localhost` 1 to 1, `127.1` 0 to 0, `127.0.0.1` 0 to 0, `08.1.1.1` 0 to
1.
- `bun run rust:check-all`: 12 of 12 targets, 0 errors.
- Not measured: instructions per TLS handshake. `perf`, `valgrind` and
`strace` are not on this machine.

**Tests.** On Linux with `src/` from main each of the 8 files fails, and
only new rows fail in them (58). With this branch they pass:
`fetch.tls.test.ts` 56, `fetch.tls.wildcard.test.ts` 158,
`proxy.test.ts` 96, `websocket-unix.test.ts` 8,
`test/bake/dev/esm.test.ts` 18, `socket-dns-error.test.ts` 29,
`udp_socket.test.ts` 230, `tls-reject-before-client-cert.test.ts` 121.
On Windows with this branch the same files pass
(`websocket-unix.test.ts` is skipped there), and on the canary of main
10 of the 12 UDP rows fail. The 7 rows for #39931 came after the Windows
run. No new row needs a resolver: a row that expects `ENOTFOUND` has a
byte that `is_valid_hostname` refuses, and the rows for `/bits` and for
the Windows shorthand are UDP rows, where `send()` throws at once. Same
failure set on both Linux builds for `resolve-dns.test.ts`,
`node-dns.test.js`, `socket.test.ts`, `serve.test.ts` and
`node-dgram.test.js` (they need the network or a user that is not root).
The tarball case has no test: the download uses the HTTP client path
that the fetch rows pin.

**Other open PRs**
- #43873 changes the two call sites in `src/boringssl/lib.rs` to
`parse_strict`. After this PR that gives the same answer. Its hostname
rule and its change in `tls.ts` are still needed: 9 of its 11 IP rows
pass on this branch alone, and the other 2 are zone rows. Its
certificate grid and the one here cover the same names.
- #39931 makes `to_ip_address` refuse whitespace in the whole host. This
PR has that change for IPv4, because the dev server Host check asks
`to_ip_address` and must refuse `127.0.0.1 rebound-host.example`. The
check here runs after `inet_aton` succeeds, so a host name does not pay
for it. The nine host names of its test are rows of
`socket-dns-error.test.ts` here. One difference: #39931 also refuses
whitespace in a `%zone`. This PR leaves the zone as it is on main,
because `node:dgram` takes any zone text: `setMulticastInterface("::%lo
junk")` succeeds in Node.js v26.3.0 and on main, and throws `EINVAL`
with a check of the zone in `to_ip_address`.
- #37013 adds a NUL check to the three function bodies. The strict parse
rejects a NUL, and the `inet_aton` arm now does too, so those three
hunks are covered for a host with no `%zone`. Its other hunks are still
needed.
- #42766 and #42054 call `is_ip_address` for an SNI decision and get the
strict answer with no change.

**Not in this PR**
- The direct callers of `ares_inet_pton`: `net.SocketAddress` and
`net.BlockList` (`SocketAddress.rs`), `dns.setServers` (`dns.rs`),
`node_cluster_binding.rs`, `c_ares.rs`, and `canonicalize_ip` in
`src/boringssl/lib.rs`. `new net.SocketAddress({ address: "::1/64" })`
succeeds, and Node.js throws `ERR_INVALID_ADDRESS`. #28792 lists that as
a breaking change, and #36185 covers the `dns` ones.
- The TLS clients that set SNI and never ask: `Bun.connect` and
`upgradeTLS` (`socket_body.rs`, `tls_socket_functions.rs`), `Bun.SQL`,
HTTP/3 and `node:quic`. They send `127.0.0.1` as SNI. #20727 was this
defect in `tls.connect`.
- A zone: fetch sends the SNI `fe80::1%eth0`, and `net.isIP` says 6 for
it. `Bun.connect` dials `::1` for `::1%eth0 junk` with scope 0, as libuv
does for a zone that names no interface. Node.js `net.connect` answers
`EAI_ADDRFAMILY` for it, because `net.isIP` says 0. That check belongs
to the caller, not to `to_ip_address`, which `node:dgram` shares.

</details>

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 1 · platform-specific test(s) that do not
run on this machine, deferring to CI, which covers all platforms:
test/js/web/websocket/websocket-unix.test.ts,
test/js/web/fetch/fetch.tls.test.ts, test/js/bun/udp/udp_socket.test.ts,
test/js/bun/net/tls-reject-before-client-cert.test.ts,
test/js/bun/net/socket-dns-error.test.ts,
test/js/bun/http/proxy.test.ts, test/bake/dev/esm.test.ts

<!-- robobun:evidence:end -->

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Jarred-Sumner pushed a commit that referenced this pull request Sep 25, 2026
… IP host (#42766)

### Problem

- `new Bun.SQL("postgres://u@[::1]:5432/db?sslmode=verify-full")`
rejects a certificate that has `IP:::1` with
`ERR_TLS_CERT_ALTNAME_INVALID`. `mysql://` does the same.
- `parseOptions` copies `URL.hostname`, brackets kept, into
`tls.serverName` (`src/js/internal/sql/shared.ts:2159`). Both adapters
check the certificate against that text, and `"[::1]"` is not an IP
address.
- Both adapters send an IP literal as SNI (`127.0.0.1`). RFC 6066
section 3 forbids that.

### Fix

- `SSLConfig::server_name_bytes()` (`src/sql_jsc/jsc.rs`) returns the
name through `bun_core::ip_address::strip_ipv6_brackets`. The identity
checks of both adapters read the name there.
- New `SSLConfig::sni()` returns no name for an IP literal, bracketed or
not. Both `adopt_tls` sites use it. libpq and fetch send none either.
- Verified: `test/js/sql/sql-tls-ip-literal-host.test.ts` (new, 8
cases). 6 fail on main 0d73249, all pass here.

### Background

- `sslmode=verify-full` checks that the certificate names the host. An
IP host matches only an IP SAN entry, and only as a bare address
(`check_x509_server_identity`, `src/boringssl/lib.rs:452`).
- SNI is the host name a TLS client sends in its first message.
`adopt_tls` sets it.
- Considered a strip in `parseOptions` (the first version). That was a
second copy of `strip_ipv6_brackets`, which fetch, RedisClient and
Bun.connect use, and it changed `sql.options`.

### Downsides

- Bun.SQL sends no SNI for an IP-literal name. A TLS proxy that routes
on such a value loses it.
- A zone-scoped address (`hostname: "::1%lo"`) still fails
`verify-full`, and without brackets it still goes out as SNI:
`is_ip_address` accepts no `%zone`.
- Cost per TLS connection: one `is_ip_address` call (at most 45 bytes,
no allocation) and a bracket check at each name read.

<details><summary>Notes</summary>

- History of this PR. The first version removed the brackets in
`parseOptions` (JS). Main then gained
`bun_core::ip_address::strip_ipv6_brackets` and moved every other client
to it. A review noted that the JS helper disagreed with it (`[db]` lost
its brackets too). aa4d699 moves the fix to the two native accessors
and restores `parseOptions` to its state on main. So this PR no longer
touches `src/js/internal/sql/shared.ts`, and it does not conflict with
#42054 or #41761, which edit that block.
- `sql.options.tls.serverName` and `sql.options.hostname` keep the
brackets, as on main. Only the native reads see the bare address.
- When this PR opened (canary 09bb546), Bun.SQL also accepted a
certificate whose only SAN is `DNS:[::1]`, and a hostname mismatch gave
an `Error` with an empty `code` and `message`. Main changed both since:
#43873 makes a name that is not a hostname match no certificate name,
and #43694 rejects the mismatch inside the handshake with
`ERR_TLS_CERT_ALTNAME_INVALID`. This PR changes neither.
- Probed on the debug build with a mock TLS server on 127.0.0.1 and an
explicit `tls.serverName`. `"[::1]"` and `"::1"` under `verify-full`:
connects, no SNI. `"[db]"` under `verify-full`:
`ERR_TLS_CERT_ALTNAME_INVALID`, as on main. `"[fe80::1%lo]"` under
`require`: no SNI. `"fe80::1%lo"` and `"127.1"` under `require`: sent as
SNI, because `is_ip_address` takes neither as an IP literal (#43979).
`"localhost"`: sent as SNI.
- Observed on main 0d73249: peer SNI `127.0.0.1` for host
`127.0.0.1`. With this change: none.
- The cases that dial `[::1]` gate on `isIPv6()` (Buildkite Linux has no
IPv6 loopback). The other cases run on every lane. One of them dials
127.0.0.1 with `tls.serverName: "[::1]"`, so every lane checks a
bracketed name against the `IP:::1` entry.
- Two gaps in the same `parseOptions` block are on main and stay out of
this PR: `tls.servername` (the Node spelling) is ignored, which #42054
owns, and `tls: true` without an sslmode derives no `serverName`, which
#26369 tracks. A `BunFile` given as `tls` with an explicit sslmode loses
the file there, which #41761 owns.
- Same bug class as #30668, which #30674 fixed for fetch and WebSocket.
The dial path already removes the brackets
(`src/uws_sys/socket.rs:791`).
- Other suites run on the merged debug build (main 601af5a):
`postgres-pgsslmode-env`, `sql-mysql-tls-plaintext-injection`, all of
`adapter-env-var-precedence`, and
`test/js/bun/net/tls-reject-before-client-cert.test.ts` (121 pass, 9
skip). I ran the new file 40 times on the earlier head: 320 of 320 cases
pass. The container TLS suites (`tls-sql`, `local-sql`) need Docker and
run in CI.

</details>

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 0 · platform-specific test(s) that do not
run on this machine, deferring to CI, which covers all platforms:
test/js/sql/adapter-env-var-precedence.test.ts

<!-- robobun:evidence:end -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants