Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
7 changes: 7 additions & 0 deletions src/boringssl_sys/boringssl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -925,6 +925,13 @@ unsafe extern "C" {
pub fn SSL_get_ex_data(ssl: *const SSL, idx: c_int) -> *mut c_void;
pub fn SSL_set_ex_data(ssl: *mut SSL, idx: c_int, data: *mut c_void) -> c_int;
pub fn SSL_set_tlsext_host_name(ssl: *mut SSL, name: *const c_char) -> c_int;
pub fn SSL_CTX_get_tlsext_ticket_keys(ctx: *mut SSL_CTX, out: *mut c_void, len: usize)
-> c_int;
pub fn SSL_CTX_set_tlsext_ticket_keys(
ctx: *mut SSL_CTX,
r#in: *const c_void,
len: usize,
) -> c_int;
pub fn SSL_set_alpn_protos(ssl: *mut SSL, protos: *const u8, protos_len: usize) -> c_int;
pub fn SSL_get0_alpn_selected(ssl: *const SSL, out_data: *mut *const u8, out_len: *mut c_uint);
pub fn SSL_set_options(ssl: *mut SSL, options: u32) -> u32;
Expand Down
7 changes: 7 additions & 0 deletions src/js/node/net.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ const newDetachedSocket = $newRustFunction("node_net_binding.rs", "newDetachedSo
const doConnect = $newRustFunction("node_net_binding.rs", "doConnect", 2);

const addServerName = $newRustFunction("Listener.rs", "jsAddServerName", 3);
const setTicketKeys = $newRustFunction("Listener.rs", "jsSetTicketKeys", 2);
const upgradeDuplexToTLS = $newRustFunction("runtime/socket/socket.rs", "jsUpgradeDuplexToTLS", 2);
// tls.connect({ socket }) upgrade: hostname policy stays with this JS layer.
const upgradeTLSDeferred = $newRustFunction("runtime/socket/socket.rs", "jsUpgradeTLSDeferred", 2);
Expand Down Expand Up @@ -3931,6 +3932,12 @@ Server.prototype[kRealListen] = function (
this._connectionKey = `${familyLast}:${addr.address}:${port}`;
}

if (tls) {
// Apply session-ticket keys to the freshly built SSL_CTX before any accept.
const ticketKeys = tls.ticketKeys;
if (ticketKeys !== undefined) setTicketKeys(this._handle, ticketKeys);
}

if (contexts) {
for (const [name, context] of contexts) {
// tls.ts stores the InternalSecureContext wrapper; the native side wants
Expand Down
60 changes: 53 additions & 7 deletions src/js/node/tls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ const net = require("node:net");
const Duplex = require("internal/streams/duplex");
const EventEmitter = require("node:events");
const addServerName = $newRustFunction("Listener.rs", "jsAddServerName", 3);
const { throwNotImplemented } = require("internal/shared");
const _getTicketKeys = $newRustFunction("Listener.rs", "jsGetTicketKeys", 1);
const _setTicketKeys = $newRustFunction("Listener.rs", "jsSetTicketKeys", 2);
const { throwNotImplemented, kInternalAssertionSuffix } = require("internal/shared");
const {
throwOnInvalidTLSArray,
tlsStringToProtocolVersion,
Expand All @@ -21,6 +23,8 @@ const {
validateFunction,
} = require("internal/validators");

let _randomBytes: ((size: number) => Buffer) | undefined;

const { Server: NetServer, Socket: NetSocket } = net;
const { kArmHandshakeTimeout, kSecureConnectDone, kVerifyError } = require("internal/net/symbols");

Expand Down Expand Up @@ -1135,7 +1139,8 @@ let CLIENT_RENEG_LIMIT = 3,
CLIENT_RENEG_WINDOW = 600;

function buildSharedCreds(server) {
return (server._sharedCreds = new InternalSecureContext(
const ticketKeys = server._ticketKeys;
const sc = (server._sharedCreds = new InternalSecureContext(
{
...server[ksharedCredsOptions],
pfx: undefined,
Expand All @@ -1155,8 +1160,12 @@ function buildSharedCreds(server) {
minVersion: server.minVersion,
maxVersion: server.maxVersion,
},
true,
// Per-server ticket keys must not land on a digest-cached shared SSL_CTX.
ticketKeys === undefined,
));
const { context } = sc;
if (ticketKeys !== undefined && context) _setTicketKeys(context, ticketKeys);
return sc;
}

function Server(options, secureConnectionListener): void {
Expand Down Expand Up @@ -1212,6 +1221,7 @@ function Server(options, secureConnectionListener): void {
this.servername = undefined;
this.ALPNProtocols = undefined;
this._sharedCreds = undefined;
this._ticketKeys = undefined;

let contexts: Map<string, typeof InternalSecureContext> | null = null;

Expand Down Expand Up @@ -1407,6 +1417,9 @@ function Server(options, secureConnectionListener): void {
serverTLSOptions == null || serverTLSOptions instanceof InternalSecureContext
? serverTLSOptions
: { ...serverTLSOptions };
// After _sharedCreds is assigned so the keys reach the new context.
const ticketKeys = options?.ticketKeys;
if (ticketKeys != null) this.setTicketKeys(ticketKeys);
};

// Lets net.ts's SNI dispatch recognize a raw native SecureContext handed to
Expand All @@ -1415,17 +1428,49 @@ function Server(options, secureConnectionListener): void {
Server.prototype[kNativeSecureContextCtor] = NativeSecureContext;

Server.prototype.getTicketKeys = function () {
throw Error("Not implented in Bun yet");
const { _handle } = this;
if (_handle) {
const keys = _getTicketKeys(_handle);
if (keys !== undefined) {
if (this._ticketKeys === undefined) {
// Pin so BoringSSL's default-key auto-rotation doesn't change later reads.
this._ticketKeys = Buffer.from(keys);
_setTicketKeys(_handle, keys);
if (this._sharedCreds && !(this[ksharedCredsOptions] instanceof InternalSecureContext)) {
this._sharedCreds = null;
}
}
Comment thread
robobun marked this conversation as resolved.
Resolved
return keys;
}
}
// Pre-listen: return the stored keys (generated lazily); applied at listen().
let stored = this._ticketKeys;
if (stored === undefined) {
stored = (_randomBytes ??= require("node:crypto").randomBytes)(48);
this._ticketKeys = stored;
if (this._sharedCreds && !(this[ksharedCredsOptions] instanceof InternalSecureContext)) {
this._sharedCreds = null;
}
}
return Buffer.from(stored);
};

Server.prototype.setTicketKeys = function (keys) {
Comment thread
robobun marked this conversation as resolved.
Resolved
if (!ArrayBuffer.isView(keys)) {
if (!isArrayBufferView(keys)) {
throw $ERR_INVALID_ARG_TYPE("buffer", ["Buffer", "TypedArray", "DataView"], keys);
}
if (keys.byteLength !== 48) {
throw $ERR_INVALID_ARG_VALUE("buffer", keys, "Session ticket keys must be a 48-byte buffer");
// Node checks length via internal/assert, so ERR_INTERNAL_ASSERTION (Error).
throw $ERR_INTERNAL_ASSERTION("Session ticket keys must be a 48-byte buffer" + kInternalAssertionSuffix);
}
Comment thread
robobun marked this conversation as resolved.
Resolved
// Copy so caller-side mutation cannot change what is applied at listen().
const copy = (this._ticketKeys = Buffer.from(new Uint8Array(keys.buffer, keys.byteOffset, keys.byteLength)));
const { _handle } = this;
if (_handle) _setTicketKeys(_handle, copy);
// Drop cached creds so the next injected socket rebuilds with the new keys.
if (this._sharedCreds && !(this[ksharedCredsOptions] instanceof InternalSecureContext)) {
this._sharedCreds = null;
}
throw Error("Not implented in Bun yet");
};

this[buntls] = function (port, host, isClient) {
Expand All @@ -1448,6 +1493,7 @@ function Server(options, secureConnectionListener): void {
clientRenegotiationLimit: CLIENT_RENEG_LIMIT,
clientRenegotiationWindow: CLIENT_RENEG_WINDOW,
contexts: contexts,
ticketKeys: this._ticketKeys,
// Translate minVersion/maxVersion/secureProtocol to the integer
// protocol range the native layer applies (secureProtocol wins, like
// Node's SecureContext::Init). When none are given the module-level
Expand Down
110 changes: 110 additions & 0 deletions src/runtime/socket/Listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1613,6 +1613,116 @@ pub(crate) fn js_add_server_name(global: &JSGlobalObject, frame: &CallFrame) ->
Err(global.throw(format_args!("Expected a Listener instance")))
}

const TICKET_KEY_SIZE: usize = 48;

impl Listener {
/// The `SSL_CTX*` backing accepted sockets; `None` before `listen()`.
fn ssl_ctx(&self) -> Option<NonNull<boring_sys::SSL_CTX>> {
if let Some(ctx) = self.secure_ctx.get() {
return Some(ctx);
}
#[cfg(windows)]
if let ListenerType::NamedPipe(np) = self.listener.get() {
// SAFETY: the parent Listener heap-allocated this context and
// outlives it until close_pipe_and_deinit.
return unsafe { np.as_ref() }.ctx;
}
None
}
}

fn get_ticket_keys_for_ctx(
global: &JSGlobalObject,
ctx: *mut boring_sys::SSL_CTX,
) -> JsResult<JSValue> {
let mut buf = [0u8; TICKET_KEY_SIZE];
// SAFETY: FFI — ctx is a live SSL_CTX; buf is 48 bytes, the size BoringSSL requires.
let ok = unsafe {
boring_sys::SSL_CTX_get_tlsext_ticket_keys(
ctx,
buf.as_mut_ptr().cast::<c_void>(),
TICKET_KEY_SIZE,
)
};
if ok != 1 {
return Err(global.throw(format_args!("Failed to get ticket keys")));
}
jsc::ArrayBuffer::create_buffer(global, &buf)
}

fn set_ticket_keys_for_ctx(
global: &JSGlobalObject,
ctx: *mut boring_sys::SSL_CTX,
keys: JSValue,
) -> JsResult<JSValue> {
let Some(buffer) = keys.as_array_buffer(global) else {
return Err(
global.throw_invalid_arguments(format_args!("keys must be a Buffer or TypedArray"))
);
};
let slice = buffer.byte_slice();
if slice.len() != TICKET_KEY_SIZE {
return Err(global.throw(format_args!("Session ticket keys must be exactly 48 bytes")));
}
// SAFETY: FFI — ctx is a live SSL_CTX; slice is exactly 48 bytes.
let ok = unsafe {
boring_sys::SSL_CTX_set_tlsext_ticket_keys(
ctx,
slice.as_ptr().cast::<c_void>(),
TICKET_KEY_SIZE,
)
};
if ok != 1 {
return Err(global.throw(format_args!("Failed to set ticket keys")));
}
Ok(JSValue::UNDEFINED)
}

/// Accepts a `Listener` or a `SecureContext` (`_sharedCreds.context`).
#[bun_jsc::host_fn]
pub(crate) fn js_get_ticket_keys(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSValue> {
jsc::mark_binding!();

let args = frame.arguments_as_array::<1>();
if let Some(this) = args[0].as_class_ref::<Listener>() {
if !this.ssl {
return Err(global.throw_invalid_arguments(format_args!("getTicketKeys requires TLS")));
}
let Some(ctx) = this.ssl_ctx() else {
return Ok(JSValue::UNDEFINED);
};
return get_ticket_keys_for_ctx(global, ctx.as_ptr());
}
if let Some(sc) = args[0].as_class_ref::<SecureContext>() {
return get_ticket_keys_for_ctx(global, sc.ctx);
}
Err(global.throw(format_args!(
"Expected a Listener or SecureContext instance"
)))
}

#[bun_jsc::host_fn]
pub(crate) fn js_set_ticket_keys(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSValue> {
jsc::mark_binding!();

let args = frame.arguments_as_array::<2>();
if let Some(this) = args[0].as_class_ref::<Listener>() {
if !this.ssl {
return Err(global.throw_invalid_arguments(format_args!("setTicketKeys requires TLS")));
}
let Some(ctx) = this.ssl_ctx() else {
return Ok(JSValue::UNDEFINED);
};
return set_ticket_keys_for_ctx(global, ctx.as_ptr(), args[1]);
}
if let Some(sc) = args[0].as_class_ref::<SecureContext>() {
return set_ticket_keys_for_ctx(global, sc.ctx, args[1]);
}
Err(global.throw(format_args!(
"Expected a Listener or SecureContext instance"
)))
}

#[cfg(windows)]
fn is_valid_pipe_name(pipe_name: &[u8]) -> bool {
// check for valid pipe names
Expand Down
Loading
Loading