Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 67 additions & 2 deletions packages/bun-usockets/src/crypto/openssl.c
Original file line number Diff line number Diff line change
Expand Up @@ -1206,9 +1206,12 @@ static int us_x509_verify_chain_cb(X509_STORE_CTX *ctx, void *arg) {
return us_x509_verify_chain(ctx);
}

static int us_ssl_reverify_client_session(const SSL_CLIENT_HELLO *client_hello);

/* For node:quic, which builds its own SSL_CTX. */
void us_ssl_ctx_reject_blocked_keys(SSL_CTX *ctx) {
SSL_CTX_set_cert_verify_callback(ctx, us_x509_verify_chain_cb, NULL);
SSL_CTX_set_dos_protection_cb(ctx, us_ssl_reverify_client_session);
}

/* A self-issued leaf that may not sign certificates is its own anchor when the store holds that very certificate (#44365). */
Expand Down Expand Up @@ -1966,13 +1969,75 @@ const char *us_X509_error_code(long err) {
return code;
}

static long us_internal_verify_peer_certificate(const SSL *ssl, long def) {
static int us_x509_session_chain_error(X509_STORE *store, X509_VERIFY_PARAM *param,
STACK_OF(X509) *chain, int purpose, int allow_untrusted) {
int error = X509_V_ERR_UNSPECIFIED;
X509_STORE_CTX *ctx = X509_STORE_CTX_new();
if (ctx && X509_STORE_CTX_init(ctx, store, sk_X509_value(chain, 0), chain) == 1 &&
X509_STORE_CTX_set_default(ctx, purpose == X509_PURPOSE_SSL_CLIENT ? "ssl_client" : "ssl_server") == 1 &&
X509_VERIFY_PARAM_set1(X509_STORE_CTX_get0_param(ctx), param) == 1) {
int ok = us_x509_verify_cert(ctx, purpose);
error = allow_untrusted ? us_x509_store_ctx_blocked_key_error(ctx) : X509_STORE_CTX_get_error(ctx);
if (!allow_untrusted && !ok && error == X509_V_OK) error = X509_V_ERR_UNSPECIFIED;
}
X509_STORE_CTX_free(ctx);
return error;
}

/* BoringSSL restores a session's old verify_result without running our cert callback.
* Rebuild its verified chain so newly blocked keys (including omitted anchors) cannot
* regain trust, while unused peer certificates retain the full-handshake policy. */
long us_ssl_verify_result(SSL *ssl) {
long result = SSL_get_verify_result(ssl);
if (!SSL_session_reused(ssl)) return result;
STACK_OF(X509) *chain = SSL_get_peer_full_cert_chain(ssl);
if (!chain || sk_X509_num(chain) == 0) return result;
ERR_set_mark();
int error = us_x509_session_chain_error(SSL_CTX_get_cert_store(SSL_get_SSL_CTX(ssl)),
SSL_get0_param(ssl), chain, SSL_is_server(ssl) ? X509_PURPOSE_SSL_CLIENT : X509_PURPOSE_SSL_SERVER, 0);
ERR_pop_to_mark();
return error == X509_V_OK ? result : error;
}

/* This hook runs after ticket decryption, before the server derives early-data keys. */
static int us_ssl_reverify_client_session(const SSL_CLIENT_HELLO *client_hello) {
SSL *ssl = client_hello->ssl;
if (!SSL_session_reused(ssl) || !(SSL_get_verify_mode(ssl) & SSL_VERIFY_PEER)) return 1;
STACK_OF(X509) *chain = SSL_get_peer_full_cert_chain(ssl);
return chain && sk_X509_num(chain) != 0 && us_ssl_verify_result(ssl) == X509_V_OK;
}

/* QUIC must admit the stored chain before releasing 0-RTT keys, not after its handshake. */
int us_ssl_ctx_session_is_trusted(SSL_CTX *ctx, const unsigned char *der, size_t length, int allow_untrusted) {
ERR_set_mark();
int trusted = 0;
SSL_SESSION *session = SSL_SESSION_from_bytes(der, length, ctx);
STACK_OF(X509) *chain = sk_X509_new_null();
const STACK_OF(CRYPTO_BUFFER) *certs = session ? SSL_SESSION_get0_peer_certificates(session) : NULL;
if (!chain || !certs || sk_CRYPTO_BUFFER_num(certs) == 0) goto cleanup;
for (size_t i = 0; i < sk_CRYPTO_BUFFER_num(certs); i++) {
X509 *cert = X509_parse_from_buffer(sk_CRYPTO_BUFFER_value(certs, i));
if (!cert || !sk_X509_push(chain, cert)) {
X509_free(cert);
goto cleanup;
}
}
trusted = us_x509_session_chain_error(SSL_CTX_get_cert_store(ctx), SSL_CTX_get0_param(ctx),
chain, X509_PURPOSE_SSL_SERVER, allow_untrusted) == X509_V_OK;
cleanup:
sk_X509_pop_free(chain, X509_free);
SSL_SESSION_free(session);
ERR_pop_to_mark();
return trusted;
}

static long us_internal_verify_peer_certificate(SSL *ssl, long def) {
if (!ssl) return def;
long err = def;
X509 *peer_cert = SSL_get_peer_certificate(ssl);
if (peer_cert) {
X509_free(peer_cert);
err = SSL_get_verify_result(ssl);
err = us_ssl_verify_result(ssl);
} else {
const SSL_CIPHER *curr_cipher = SSL_get_current_cipher(ssl);
if (curr_cipher && SSL_CIPHER_get_auth_nid(curr_cipher) == NID_auth_psk) {
Expand Down
1 change: 1 addition & 0 deletions packages/bun-usockets/src/quic.c
Original file line number Diff line number Diff line change
Expand Up @@ -1409,6 +1409,7 @@ us_quic_socket_context_t *us_create_quic_client_context(
* this path, and set_cert_store takes the getter's up-ref. */
SSL_CTX_set_cert_store(ssl, us_get_shared_default_ca_store(us_default_use_system_ca()));
SSL_CTX_set_custom_verify(ssl, SSL_VERIFY_PEER, us_quic_client_verify);
SSL_CTX_set_reverify_on_resume(ssl, 1);
if (!us_ssl_ctx_set_verify_signature_algorithms(ssl)) { SSL_CTX_free(ssl); return NULL; }

us_quic_socket_context_t *ctx = (us_quic_socket_context_t *)
Expand Down
6 changes: 6 additions & 0 deletions src/runtime/node/quic/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2394,6 +2394,12 @@ impl QuicEndpoint {
session_ticket
.as_array_buffer(global)
.map(|buf| buf.byte_slice().to_vec())
.filter(|blob| {
self.client_tls
.get()
.as_ref()
.is_some_and(|tls| tls.can_resume(blob, config.verify_hostname))
})
} else {
None
};
Expand Down
35 changes: 33 additions & 2 deletions src/runtime/node/quic/tls.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use core::ffi::c_int;
use core::ffi::{c_int, c_long};
use core::ptr::null_mut;

use bun_boringssl_sys as ssl;
Expand Down Expand Up @@ -538,6 +538,29 @@ impl TlsContext {
self.ctx.as_ptr()
}

pub(super) fn can_resume(&self, blob: &[u8], verify_hostname: bool) -> bool {
// lsquic's iquic_ssl_sess_to_resume_info: version tag, format version,
// DER length (all u32), DER, transport-parameter length and bytes.
const HEADER_LENGTH: usize = 12;
let Some(length) = blob.get(8..HEADER_LENGTH).and_then(|b| b.try_into().ok()) else {
return false;
};
let length = u32::from_be_bytes(length) as usize;
let Some(der) = blob.get(HEADER_LENGTH..).and_then(|b| b.get(..length)) else {
return false;
};
// processSessionOptions binds verifyHostname to verifyPeer != "manual".
// SAFETY: this context and the borrowed DER remain live during verification.
unsafe {
us_ssl_ctx_session_is_trusted(
self.raw(),
der.as_ptr(),
der.len(),
(!verify_hostname) as c_int,
) == 1
}
}

pub(super) fn alpn_cstr(config: &TlsConfig) -> Vec<u8> {
if config.alpn.len() < 2 {
return Vec::new();
Expand Down Expand Up @@ -578,6 +601,14 @@ unsafe extern "C" {
fn us_ssl_ctx_set_verify_signature_algorithms(ctx: *mut ssl::SSL_CTX) -> c_int;
/// openssl.c: the blocked public keys every other TLS context of Bun rejects in a peer's chain.
fn us_ssl_ctx_reject_blocked_keys(ctx: *mut ssl::SSL_CTX);
/// openssl.c: the current blocked-key policy also applies to resumed sessions.
fn us_ssl_verify_result(ssl: *mut ssl::SSL) -> c_long;
fn us_ssl_ctx_session_is_trusted(
ctx: *mut ssl::SSL_CTX,
der: *const u8,
length: usize,
allow_untrusted: c_int,
) -> c_int;
}

/// node's `X509_V_ERR_UNSPECIFIED`, reported when a peer sent no certificate
Expand Down Expand Up @@ -615,7 +646,7 @@ pub(super) fn validation_error(ssl: *mut ssl::SSL) -> Option<(&'static str, &'st
return None;
}
// SAFETY: as above.
let code = unsafe { ssl::SSL_get_verify_result(ssl) };
let code = unsafe { us_ssl_verify_result(ssl) };
if code == 0 {
return None;
}
Expand Down
113 changes: 113 additions & 0 deletions test/js/node/quic/quic-sni.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,119 @@ test("verifyPeer 'strict' and 'auto' refuse a certificate with a blocked public
}
});

test.each(
(["auto", "strict"] as const).flatMap(verifyPeer =>
(["blocked-key", "changed-ca", "changed-hostname", "blocked-client-key"] as const).map(policy => ({
verifyPeer,
policy,
})),
),
)("$verifyPeer checks $policy before sending saved-session early data", async ({ verifyPeer, policy }) => {
const fixtures = join(import.meta.dir, "..", "tls", "fixtures");
const cert = readFileSync(join(fixtures, "ed25519-cert.pem"));
const key = createPrivateKey(readFileSync(join(fixtures, "ed25519-key.pem")));
const clients: Awaited<ReturnType<typeof connect>>[] = [];
const servers: Awaited<ReturnType<typeof connect>>[] = [];
const receipts: Promise<{ body: string; early: boolean }>[] = [];
await using server = await listen(
session => {
servers.push(session);
ignoreErrors(session);
session.closed.catch(() => {});
session.onstream = stream => {
stream.closed.catch(() => {});
const receipt = (async () => {
const chunks: Uint8Array[] = [];
for await (const batch of stream) chunks.push(...batch);
const row = { body: Buffer.concat(chunks).toString(), early: stream.early };
stream.writer.endSync();
return row;
})();
receipt.catch(() => {});
receipts.push(receipt);
};
},
{
sni: { "*": { keys: [key], certs: [cert] } },
alpn: ["quic-test"],
...(policy === "blocked-client-key" ? { verifyClient: true, ca: [readKey("ca1-cert.pem")] } : {}),
},
);

async function request(
sessionTicket?: Buffer,
body?: string,
receiveTicket = false,
options: Partial<SessionOptions> = {},
) {
const ticket = Promise.withResolvers<Buffer>();
const session = await connect(server.address!, {
alpn: "quic-test",
servername: "localhost",
ca: [cert],
verifyPeer,
sessionTicket,
...(policy === "blocked-client-key" ? identity1 : {}),
onerror() {},
onsessionticket(value) {
ticket.resolve(value);
},
...options,
} as SessionOptions);
clients.push(session);
session.closed.catch(() => {});
const stream = body ? await session.createBidirectionalStream({ body: Buffer.from(body) }) : undefined;
stream?.closed.catch(() => {});
const outcome = await session.opened.then(
info => ({
opened: true,
earlyDataAttempted: info.earlyDataAttempted,
earlyDataAccepted: info.earlyDataAccepted,
}),
() => ({ opened: false }),
);
const saved = receiveTicket && outcome.opened ? await ticket.promise : undefined;
if (outcome.opened) {
if (stream)
for await (const _ of stream) {
}
await session.close();
} else await session.closed.catch(() => {});
return { outcome, ticket: saved };
}

try {
const first = await request(undefined, undefined, true);
expect(first.outcome.opened).toBe(true);
expect(first.ticket).toBeInstanceOf(Buffer);
const positive = await request(first.ticket, "legitimate early data");
expect(positive.outcome).toEqual({ opened: true, earlyDataAttempted: true, earlyDataAccepted: true });
expect(await Promise.all(receipts)).toEqual([{ body: "legitimate early data", early: true }]);
if (policy === "blocked-key" || policy === "blocked-client-key") {
addBlockedSPKIForTesting(
createHash("sha256")
.update(
new X509Certificate(policy === "blocked-client-key" ? cert1 : cert).publicKey.export({
type: "spki",
format: "der",
}),
)
.digest(),
);
}
const options =
policy === "changed-ca" ? { ca: [cert1] } : policy === "changed-hostname" ? { servername: "wrong.example" } : {};
const blocked = await request(first.ticket, "must never reach the untrusted peer", false, options);
expect(blocked.outcome).toEqual({ opened: false });
await Promise.all(servers.map(session => session.closed.catch(() => {})));
expect(await Promise.all(receipts)).toEqual([{ body: "legitimate early data", early: true }]);
} finally {
clearBlockedSPKIsForTesting();
for (const session of clients) session.destroy();
for (const session of servers) session.destroy();
}
});

test("connect() with the default verifyPeer refuses an unverifiable certificate before a pending stream reaches the server", async () => {
const script = `
import { createPrivateKey } from "node:crypto";
Expand Down
81 changes: 81 additions & 0 deletions test/js/node/tls/node-tls-internals.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { createHash, X509Certificate } from "node:crypto";
import { once } from "node:events";
import { readFileSync } from "node:fs";
import type { AddressInfo } from "node:net";
import { createConnection } from "node:net";
import { join } from "node:path";
import {
connect,
Expand Down Expand Up @@ -289,6 +290,86 @@ describe("blocked public keys", () => {
});
});

describe.each(["TLSv1.2", "TLSv1.3"] as const)("resumed %s sessions", version => {
async function sessionFrom(server: Server, options: ConnectionOptions) {
const { promise, resolve, reject } = Promise.withResolvers<Buffer>();
server.once("secureConnection", socket => socket.write("session fixture"));
const client = connect({
host: "127.0.0.1",
port: (server.address() as AddressInfo).port,
checkServerIdentity: () => undefined,
minVersion: version,
maxVersion: version,
...options,
});
clients.push(client);
client.once("session", resolve);
client.once("error", reject);
client.once("close", () => reject(new Error("closed before receiving a session")));
client.resume();
const session = await promise;
expect(authorization(client)).toEqual({ authorized: true, authorizationError: null });
return session;
}

async function resumedConnection(server: Server, options: ConnectionOptions) {
const result = await connectTo(server, { minVersion: version, maxVersion: version, ...options });
return { result, reused: clients.at(-1)!.isSessionReused() };
}

for (const wrapped of [false, true]) {
test(`a persisted session cannot restore a blocked intermediate${wrapped ? " through an existing socket" : ""}`, async () => {
const server = await listen({ key: leafKey, cert: leafChain, minVersion: version, maxVersion: version });
const session = await sessionFrom(server, { ca: rootCert });
const options = () => ({
ca: rootCert,
session,
...(wrapped
? { socket: createConnection({ host: "127.0.0.1", port: (server.address() as AddressInfo).port }) }
: {}),
});
expect(await resumedConnection(server, options())).toEqual({
result: { authorized: true, authorizationError: null },
reused: true,
});
addBlockedSPKIForTesting(intermediateSpkiHash);
expect((await resumedConnection(server, options())).result).toEqual({ error: "CERT_REVOKED" });
});
}

test("a blocked trust anchor is checked even when it was not sent by the peer", async () => {
const server = await listen({ key: leafKey, cert: leafChain, minVersion: version, maxVersion: version });
const session = await sessionFrom(server, { ca: rootCert });
addBlockedSPKIForTesting(spkiSha256(rootCert));
expect((await resumedConnection(server, { ca: rootCert, session })).result).toEqual({ error: "CERT_REVOKED" });
});

test("rejectUnauthorized: false reports a newly blocked resumed key", async () => {
const server = await listen({ key: leafKey, cert: leafChain, minVersion: version, maxVersion: version });
const session = await sessionFrom(server, { ca: rootCert });
addBlockedSPKIForTesting(intermediateSpkiHash);
expect(await resumedConnection(server, { ca: rootCert, session, rejectUnauthorized: false })).toEqual({
result: { authorized: false, authorizationError: "CERT_REVOKED" },
reused: true,
});
});

test("an unused blocked peer certificate does not invalidate a resumed verified chain", async () => {
const server = await listen({
key: leafKey,
cert: `${leafChain}\n${unrelatedCert}`,
minVersion: version,
maxVersion: version,
});
const session = await sessionFrom(server, { ca: rootCert });
addBlockedSPKIForTesting(unrelatedSpkiHash);
expect(await resumedConnection(server, { ca: rootCert, session })).toEqual({
result: { authorized: true, authorizationError: null },
reused: true,
});
});
});

describe("in the client's chain", () => {
const server = (rejectUnauthorized: boolean) =>
listen({ key: unaffectedKey, cert: unaffectedCert, ca: rootCert, requestCert: true, rejectUnauthorized });
Expand Down
Loading