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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/bun-usockets/src/context.c
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,9 @@ struct us_socket_t *us_socket_adopt(struct us_socket_t *s, struct us_socket_grou
us_internal_socket_group_link_connecting_socket(group, c);
}
}
if (old_group != group && new_s->ssl) {
us_internal_ssl_socket_left_group(new_s);
}
new_s->group = group;
new_s->kind = kind;
new_s->timeout = 255;
Expand Down
724 changes: 258 additions & 466 deletions packages/bun-usockets/src/crypto/openssl.c

Large diffs are not rendered by default.

24 changes: 21 additions & 3 deletions packages/bun-usockets/src/internal/internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,12 @@ extern struct us_connecting_socket_t *us_dispatch_connecting_error(struct us_con
extern void us_dispatch_handshake(us_socket_r s, int success, struct us_bun_verify_error_t err);
extern void us_dispatch_session(us_socket_r s, const unsigned char *data, int length);
extern void us_dispatch_keylog(us_socket_r s, const unsigned char *data, int length);
struct ssl_session_st;
/* Runs inside SSL_read/SSL_do_handshake: must not run JS. Returns 1 to get us_dispatch_session later. */
extern int us_dispatch_new_session(us_socket_r s, struct ssl_session_st *session);
/* 1 when the owner accepts the name on the server's certificate, or does not check it natively. */
extern int us_dispatch_server_identity(us_socket_r s, struct ssl_st *ssl);
extern struct ssl_ctx_st *us_dispatch_socket_server_name(us_socket_r s, const char *hostname, int *abort_handshake);
extern struct us_socket_t *us_dispatch_ssl_raw_tap(us_socket_r s, char *data, int length);
#ifdef __cplusplus
}
Expand Down Expand Up @@ -235,6 +241,7 @@ void us_internal_ssl_attach(us_socket_r s, struct ssl_ctx_st *ssl_ctx, int is_cl
/* SSL_free(s->ssl); s->ssl = NULL. Idempotent. */
void us_internal_ssl_detach(us_socket_r s);
void us_internal_ssl_socket_relocated(us_loop_r loop, us_socket_r old_s, us_socket_r new_s);
void us_internal_ssl_socket_left_group(us_socket_r s);

/* TLS-layer event hooks. loop.c calls these instead of us_dispatch_* when
* s->ssl != NULL; they decrypt/encrypt and re-dispatch the plaintext. */
Expand Down Expand Up @@ -293,8 +300,7 @@ struct us_socket_t {
unsigned char kind;
/* SSL state. These 6 bits live in the pad-to-pointer gap before `group`, so
* they cost nothing on epoll/kqueue (poll=4 + 4×u8 + 1 byte bits = 9, padded
* to 16 anyway for the pointer). Per-socket reneg counters and SNI userdata
* hang off SSL ex_data, allocated on first use only. */
* to 16 anyway for the pointer). */
unsigned char ssl_handshake_state : 2;
unsigned char ssl_write_wants_read : 1;
/* us_internal_ssl_write refused application data because the handshake was
Expand Down Expand Up @@ -326,12 +332,24 @@ struct us_socket_t {
* the driver's epilogue via ssl_pending_detach. */
unsigned char ssl_in_use : 1;
unsigned char ssl_pending_detach : 1;
/* Client with rejectUnauthorized on: a failed chain fails the handshake before the Certificate flight. */
unsigned char ssl_inline_reject : 1;
/* The verify callback saw an error in this handshake. */
unsigned char ssl_verify_failed : 1;
/* The owner refused the server's name before the client certificate went out. */
unsigned char ssl_identity_rejected : 1;
/* US_SNI_*: an async SNICallback has the handshake suspended. */
unsigned char ssl_sni_pending : 2;
/* Server-side socket adopted into TLS with its own SNICallback. */
unsigned char ssl_sni_resolver : 1;
/* This socket has entries in the loop's ssl_pending_events. */
unsigned char ssl_has_pending_events : 1;
/* Peer FIN was dispatched as on_end on a half-open socket; readable interest is never re-added and on_end never re-fires. */
unsigned char read_eof : 1;
/* The close code passed to the deferred close (e.g. a reset requested from
* inside a handshake callback must still RST, not FIN, when it is finally
* performed). */
unsigned char ssl_pending_close_code;
unsigned char ssl_pending_close_code : 2;
/* Consecutive send() failures with an errno that is neither
* would-block/transient nor a known peer-gone error (see
* us_socket_write_check_error). Reset by any send that makes progress.
Expand Down
35 changes: 5 additions & 30 deletions packages/bun-usockets/src/libusockets.h
Original file line number Diff line number Diff line change
Expand Up @@ -437,11 +437,8 @@ void us_ssl_ctx_set_sni_policy(struct ssl_ctx_st *ctx, int request_cert,
int us_socket_server_name_reject_unauthorized(us_socket_r s);
int us_ssl_ctx_reject_unauthorized(struct ssl_ctx_st *ctx);
/* Socket-level SNI resolver, for a server-side socket adopted into TLS with no
* listen socket behind it. Same contract as the listener resolver: an owned
* SSL_CTX ref or NULL; *abort_handshake 1 = drop silently, 2 = suspend. */
typedef struct ssl_ctx_st *(*us_socket_server_name_cb)(struct us_socket_t *socket,
const char *hostname, int *abort_handshake);
void us_socket_on_server_name(us_socket_r s, us_socket_server_name_cb cb);
* listen socket behind it: us_dispatch_socket_server_name then resolves. */
void us_socket_on_server_name(us_socket_r s);

/* ── Connect ──────────────────────────────────────────────────────────────
* Returns either us_socket_t* (fast path, *is_connecting=1) or
Expand Down Expand Up @@ -561,31 +558,9 @@ long us_ssl_ctx_live_count(void);
/* Appends the certificates in the PEM `content` to `ctx`'s trust store;
* returns 0 when nothing could be added. */
int us_ssl_ctx_add_ca_cert(struct ssl_ctx_st *ctx, const char *content);
/* TLS-over-duplex / named-pipe SSL owners (no us_socket_t): opt an SSL into
* the parked new-session/keylog queues, then drain them with the pop calls
* after each SSL_read/SSL_do_handshake stack unwinds. Pop returns the entry
* length (0 = queue empty); entries are capped at 64 KB (sessions) and
* 4 KB+1 (keylog lines). */
void us_ssl_enable_pending_events(struct ssl_st *ssl);
int us_ssl_pop_pending_session(struct ssl_st *ssl, unsigned char *out, int out_cap);
int us_ssl_pop_pending_keylog(struct ssl_st *ssl, unsigned char *out, int out_cap);
/* The same owners as clients whose rejectUnauthorized policy is on.
* set_inline_reject installs the verify recorder before the handshake starts.
* tripped() is read after each SSL_do_handshake of the initial handshake: 1
* means the server's chain failed, so the owner drops its queued output (the
* flight that carries the client certificate) and fails the handshake. */
void us_internal_ssl_set_inline_reject(struct ssl_st *ssl);
int us_internal_ssl_inline_reject_tripped(struct ssl_st *ssl);
/* The resumable session most recently delivered via the new-session callback,
* or NULL if none. Borrowed; valid until the next NewSessionTicket or SSL_free. */
struct ssl_session_st *us_ssl_get_new_session(struct ssl_st *ssl);
/* Per-SSL session sink: each resumable session reaching the new-session
* callback is SSL_SESSION_up_ref'd and handed to on_new_session (which takes
* ownership of that reference). on_free(owner) runs once on SSL_free. */
void us_ssl_set_session_sink(struct ssl_st *ssl, void *owner,
void (*on_new_session)(void *, struct ssl_session_st *),
void (*on_free)(void *));
void *us_ssl_get_session_sink_owner(struct ssl_st *ssl);
/* Owner data for us_dispatch_new_session. `on_free(sink)` runs once, on SSL_free. */
void us_socket_set_session_sink(us_socket_r s, void *sink, void (*on_free)(void *));
void *us_socket_session_sink(us_socket_r s);

/* Public interfaces for loops */

Expand Down
13 changes: 13 additions & 0 deletions src/boringssl/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -816,6 +816,19 @@ pub fn check_server_identity(ssl_ptr: &mut boring::SSL, hostname: &[u8]) -> bool
.is_some_and(|x509| check_x509_server_identity(x509, hostname))
}

/// Node.js's `ERR_TLS_CERT_ALTNAME_INVALID` message for the peer's leaf certificate and `hostname`.
pub fn server_identity_mismatch_message(ssl_ptr: &mut boring::SSL, hostname: &[u8]) -> String {
let mut message = String::from("Hostname/IP does not match certificate's altnames: ");
// Infallible: the writer is a `String`.
let _ = write_server_identity_mismatch_reason(ssl_ptr, hostname, &mut message);
message
}

/// [`check_server_identity`] for the check inside the handshake: `None` or an empty `host` is no check there.
pub fn server_identity_ok(ssl: &mut boring::SSL, host: Option<&[u8]>) -> bool {
host.is_none_or(|host| host.is_empty() || check_server_identity(ssl, host))
}

#[cfg(test)]
mod tests {
use super::{NameBytes, is_safe_alt_name};
Expand Down
14 changes: 11 additions & 3 deletions src/http/HTTPContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1317,6 +1317,13 @@ impl<const SSL: bool> Drop for HTTPContext<SSL> {
pub struct Handler<const SSL: bool>;

impl<const SSL: bool> Handler<SSL> {
/// `us_dispatch_server_identity`: only a client that is in its handshake has a name to match.
pub fn server_identity_ok(ptr: *mut c_void, ssl: &mut bun_boringssl_sys::SSL) -> bool {
HTTPContext::<SSL>::get_tagged(ptr)
.client_mut()
.is_none_or(|client| client.server_identity_ok(ssl))
}

pub fn on_open(ptr: *mut c_void, socket: HTTPSocket<SSL>) {
let active = HTTPContext::<SSL>::get_tagged(ptr);
if let Some(client) = active.client_mut() {
Expand Down Expand Up @@ -1380,9 +1387,10 @@ impl<const SSL: bool> Handler<SSL> {
// Peer chain + hostname verified: let the session sink
// flush its pending TLS 1.2 ticket (parked before this
// dispatch) and cache later TLS 1.3 tickets directly.
// SAFETY: `ssl` is the live handle for this socket on the
// HTTP thread.
unsafe { crate::session_cache::arm(ssl) };
if let Some(raw) = socket.socket.get() {
// SAFETY: `raw` is this live socket, on the HTTP thread.
unsafe { crate::session_cache::arm(raw) };
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}

Expand Down
9 changes: 9 additions & 0 deletions src/http/ProxyTunnel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,14 @@ fn progress_update_for_proxy_socket(ctx: *mut HTTPClient, proxy: NonNull<ProxyTu
}
}

/// The inner connection's form of `HTTPClient::server_identity_ok`.
fn server_identity(ctx: *mut HTTPClient, ssl: &mut bun_boringssl::c::SSL) -> bool {
// SAFETY: `ctx` is the live client that drives this tunnel's handshake.
let client = unsafe { &*ctx };
let native = client.target_verification() == PeerVerification::Native;
bun_boringssl::server_identity_ok(ssl, native.then(|| crate::get_tls_hostname(client, false)))
}

// ─── ProxyTunnel methods ─────────────────────────────────────────────────────

impl ProxyTunnel {
Expand Down Expand Up @@ -599,6 +607,7 @@ impl ProxyTunnel {
// opting out keeps its SSL off the parked queues entirely.
on_session: None,
on_keylog: None,
server_identity: Some(server_identity),
ctx: this.as_erased_ptr().as_ptr(),
},
) {
Expand Down
2 changes: 0 additions & 2 deletions src/http/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,8 +246,6 @@ pub enum CertError {
SUITE_B_LOS_NOT_ALLOWED,
#[error("SUITE_B_CANNOT_SIGN_P_384_WITH_P_256")]
SUITE_B_CANNOT_SIGN_P_384_WITH_P_256,
#[error("HOSTNAME_MISMATCH")]
HOSTNAME_MISMATCH,
#[error("EMAIL_MISMATCH")]
EMAIL_MISMATCH,
#[error("IP_ADDRESS_MISMATCH")]
Expand Down
21 changes: 19 additions & 2 deletions src/http/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1538,7 +1538,10 @@ pub(crate) fn get_cert_error_from_no(error_no: i32) -> crate::Error {
59 => CertError::SUITE_B_INVALID_SIGNATURE_ALGORITHM,
60 => CertError::SUITE_B_LOS_NOT_ALLOWED,
61 => CertError::SUITE_B_CANNOT_SIGN_P_384_WITH_P_256,
62 => CertError::HOSTNAME_MISMATCH,
// The verdict of the in-handshake server identity check.
uws::us_bun_verify_error_t::HOSTNAME_MISMATCH => {
return crate::Error::ERR_TLS_CERT_ALTNAME_INVALID;
}
63 => CertError::EMAIL_MISMATCH,
64 => CertError::IP_ADDRESS_MISMATCH,
65 => CertError::INVALID_CALL,
Expand Down Expand Up @@ -1671,6 +1674,15 @@ impl<'a> HTTPClient<'a> {
}
}

/// Whether the outer socket's peer carries the name `check_server_identity` matches after the handshake.
pub(crate) fn server_identity_ok(&self, ssl: &mut boringssl::c::SSL) -> bool {
let native = self.socket_verification() == PeerVerification::Native;
boringssl::server_identity_ok(
ssl,
native.then(|| get_tls_hostname(self, self.http_proxy.is_some())),
)
}

/// `PooledSocket::verification` to record when releasing the outer socket.
fn pooled_socket_verification(&self) -> PeerVerification {
self.flags
Expand Down Expand Up @@ -1878,7 +1890,11 @@ impl<'a> HTTPClient<'a> {
socket.set_inline_reject();
}

if crate::session_cache::eligible(self) {
if let Some(raw_socket) = socket
.socket
.get()
.filter(|_| crate::session_cache::eligible(self))
{
let want_tunnel = self.http_proxy.is_some() && self.url.is_https();
// SAFETY: `ssl_ptr` is live and pre-handshake (guarded by
// `SSL_is_init_finished == 0` above); `get_ssl_ctx` returns
Expand All @@ -1887,6 +1903,7 @@ impl<'a> HTTPClient<'a> {
// every SSL attached to their socket group.
unsafe {
crate::session_cache::install(
raw_socket,
ssl_ptr,
self.get_ssl_ctx::<true>(),
self.connected_url.hostname,
Expand Down
43 changes: 21 additions & 22 deletions src/http/session_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,7 @@ impl SessionCache {
}
}

/// Per-`SSL` sink. Box-allocated; the ex_data slot on the `SSL` holds the raw
/// pointer and its free callback reclaims the Box on `SSL_free`.
/// Per-`SSL` sink. Box-allocated; uSockets holds the raw pointer and frees the Box on `SSL_free`.
pub(crate) struct SessionSink {
ctx: *const crate::HttpsContext,
hostname: Box<[u8]>,
Expand All @@ -133,15 +132,18 @@ impl Drop for SessionSink {
}
}

extern "C" fn sink_on_new_session(owner: *mut c_void, session: *mut SSL_SESSION) {
/// `us_dispatch_new_session` for an HTTP client socket. Runs inside `SSL_read`/`SSL_do_handshake`.
pub fn on_new_session(socket: &mut bun_uws::us_socket_t, session: *mut SSL_SESSION) {
let Some(session) = NonNull::new(session) else {
return;
};
// SAFETY: `socket` is live for this call.
let owner = unsafe { us_socket_session_sink(socket) };
let Some(owner) = NonNull::new(owner.cast::<SessionSink>()) else {
// SAFETY: +1 reference received from C with no consumer.
unsafe { SSL_SESSION_free(session.as_ptr()) };
return;
};
// SAFETY: `session` is live for this call; the sink takes its own reference.
unsafe { SSL_SESSION_up_ref(session.as_ptr()) };
// SAFETY: `owner` is the Box interior installed by [`install`]. Runs on
// the HTTP thread inside `SSL_read`/`SSL_do_handshake`; nothing else
// holds a borrow of the sink during that call.
Expand Down Expand Up @@ -170,19 +172,19 @@ extern "C" fn sink_on_free(owner: *mut c_void) {
if owner.is_null() {
return;
}
// SAFETY: `owner` is the `heap::into_raw` from [`install`]; the ex_data
// SAFETY: `owner` is the `heap::into_raw` from [`install`]; uSockets'
// free callback fires exactly once on `SSL_free`.
unsafe { bun_core::heap::destroy(owner.cast::<SessionSink>()) };
}

unsafe extern "C" {
fn us_ssl_set_session_sink(
ssl: *mut SSL,
owner: *mut c_void,
on_new_session: Option<extern "C" fn(*mut c_void, *mut SSL_SESSION)>,
fn us_socket_set_session_sink(
s: *mut bun_uws::us_socket_t,
sink: *mut c_void,
on_free: Option<extern "C" fn(*mut c_void)>,
);
fn us_ssl_get_session_sink_owner(ssl: *mut SSL) -> *mut c_void;
fn us_socket_session_sink(s: *mut bun_uws::us_socket_t) -> *mut c_void;
fn SSL_SESSION_up_ref(session: *mut SSL_SESSION) -> core::ffi::c_int;
}

/// Whether this TLS client should read/write the cache. Lax verification and
Expand All @@ -199,8 +201,9 @@ pub(crate) fn eligible(client: &crate::HTTPClient<'_>) -> bool {
/// Offer any cached session for this key and install an unarmed sink.
///
/// # Safety
/// `ssl` must be a live pre-handshake `SSL*`; `ctx` must outlive `ssl`.
/// `socket` must be live and `ssl` its pre-handshake `SSL*`; `ctx` must outlive `ssl`.
pub(crate) unsafe fn install(
socket: *mut bun_uws::us_socket_t,
ssl: *mut SSL,
ctx: *const crate::HttpsContext,
hostname: &[u8],
Expand Down Expand Up @@ -229,12 +232,11 @@ pub(crate) unsafe fn install(
armed: false,
pending: None,
});
// SAFETY: `ssl` is live; Box ownership moves to the ex_data slot.
// SAFETY: `socket` is live; Box ownership moves to uSockets.
unsafe {
us_ssl_set_session_sink(
ssl,
us_socket_set_session_sink(
socket,
bun_core::heap::into_raw(sink).cast::<c_void>(),
Some(sink_on_new_session),
Some(sink_on_free),
);
}
Expand All @@ -243,13 +245,10 @@ pub(crate) unsafe fn install(
/// Flush the parked TLS 1.2 session and admit later TLS 1.3 tickets.
///
/// # Safety
/// `ssl` must be a live `SSL*` on the HTTP thread.
pub(crate) unsafe fn arm(ssl: *mut SSL) {
if ssl.is_null() {
return;
}
/// `socket` must be a live socket on the HTTP thread.
pub(crate) unsafe fn arm(socket: *mut bun_uws::us_socket_t) {
// SAFETY: caller contract.
let owner = unsafe { us_ssl_get_session_sink_owner(ssl) };
let owner = unsafe { us_socket_session_sink(socket) };
let Some(mut owner) = NonNull::new(owner.cast::<SessionSink>()) else {
return;
};
Expand Down
9 changes: 9 additions & 0 deletions src/http_jsc/websocket_client/WebSocketProxyTunnel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ impl WebSocketProxyTunnel {
// SSL off the parked session/keylog queues entirely.
on_session: None,
on_keylog: None,
server_identity: Some(Self::server_identity),
},
)
.map_err(|_| crate::Error::InvalidOptions)?;
Expand Down Expand Up @@ -241,6 +242,14 @@ impl WebSocketProxyTunnel {
}

/// SSLWrapper callback: Called before TLS handshake starts
fn server_identity(this: ThisPtr<Self>, ssl: &mut bun_boringssl::c::SSL) -> bool {
let hostname = this
.sni_hostname
.as_deref()
.filter(|_| this.reject_unauthorized);
bun_boringssl::server_identity_ok(ssl, hostname)
}

fn on_open(this: ThisPtr<Self>) {
let _guard = RefPtr::from_this(this);
bun_core::scoped_log!(WebSocketProxyTunnel, "onOpen");
Expand Down
Loading
Loading