diff --git a/packages/bun-types/sql.d.ts b/packages/bun-types/sql.d.ts index b6d524b0cbba..78912a5e68c3 100644 --- a/packages/bun-types/sql.d.ts +++ b/packages/bun-types/sql.d.ts @@ -385,7 +385,9 @@ declare module "bun" { * the connection is not protected by TLS. Disabled by default because a * network attacker can substitute their own key and recover the * plaintext password. Enable only for trusted local connections, or use - * TLS instead. + * TLS instead. Not needed over TLS or a Unix socket (`path`): like other + * MySQL clients, Bun treats those as secure and sends the password + * directly instead of requesting the key. * @default false */ allowPublicKeyRetrieval?: boolean | undefined; diff --git a/src/sql_jsc/mysql/JSMySQLConnection.rs b/src/sql_jsc/mysql/JSMySQLConnection.rs index bae2128d7a08..0d93a3b7b87a 100644 --- a/src/sql_jsc/mysql/JSMySQLConnection.rs +++ b/src/sql_jsc/mysql/JSMySQLConnection.rs @@ -500,6 +500,7 @@ impl JSMySQLConnection { // MySQL doesn't support unnamed prepared statements let _ = use_unnamed_prepared_statements; let allow_public_key_retrieval = callframe.argument(15).to_boolean(); + let unix_socket = !path.is_empty(); // Ownership transferred into `ptr.connection`; disarm the errdefer so the // connect-fail `ptr.deref()` is the sole cleanup path from here on. @@ -523,6 +524,7 @@ impl JSMySQLConnection { secure, args.ssl_mode, allow_public_key_retrieval, + unix_socket, )), auto_flusher: JsCell::new(AutoFlusher::default()), idle_timeout_interval_ms: u32::try_from(idle_timeout).expect("int cast"), @@ -547,7 +549,7 @@ impl JSMySQLConnection { // MySQL always opens plain TCP first; STARTTLS adopts into the TLS // group after the SSLRequest exchange. let group = vm.mysql_socket_group::(); - let result = if !path.is_empty() { + let result = if unix_socket { SocketTCP::connect_unix_group( group, uws::DispatchKind::Mysql, diff --git a/src/sql_jsc/mysql/MySQLConnection.rs b/src/sql_jsc/mysql/MySQLConnection.rs index 5a2b6d656c8b..36cf04aaca79 100644 --- a/src/sql_jsc/mysql/MySQLConnection.rs +++ b/src/sql_jsc/mysql/MySQLConnection.rs @@ -90,6 +90,7 @@ pub struct MySQLConnection { tls_status: TLSStatus, ssl_mode: SSLMode, allow_public_key_retrieval: bool, + unix_socket: bool, flags: ConnectionFlags, } @@ -124,6 +125,7 @@ impl Default for MySQLConnection { tls_status: TLSStatus::None, ssl_mode: SSLMode::Disable, allow_public_key_retrieval: false, + unix_socket: false, flags: ConnectionFlags::default(), } } @@ -144,6 +146,7 @@ impl MySQLConnection { secure: Option<*mut SslCtx>, ssl_mode: SSLMode, allow_public_key_retrieval: bool, + unix_socket: bool, ) -> Self { Self { database, @@ -158,6 +161,7 @@ impl MySQLConnection { secure, ssl_mode, allow_public_key_retrieval, + unix_socket, tls_status: if ssl_mode != SSLMode::Disable { TLSStatus::Pending } else { @@ -769,6 +773,15 @@ impl MySQLConnection { } } + /// Transports over which caching_sha2_password full authentication sends the + /// password itself rather than going through the RSA public-key exchange. The + /// public-key gate defends against an on-path attacker, who does not exist on a + /// unix socket; libmysqlclient, mysql2 (`ssl || socketPath`) and go-sql-driver + /// (`Net == "unix"`) draw the same line. + fn is_secure_transport(&self) -> bool { + self.tls_status == TLSStatus::SslOk || self.unix_socket + } + pub(crate) fn handle_auth( &mut self, reader: NewReader, @@ -835,7 +848,7 @@ impl MySQLConnection { } self.full_auth_requested = true; - if self.tls_status != TLSStatus::SslOk { + if !self.is_secure_transport() { // Over plain TCP, an on-path attacker can answer the // public-key request with their own key and recover the // password. Match mysql2 / Connector/J: refuse unless the @@ -860,9 +873,8 @@ impl MySQLConnection { } else { bun_core::scoped_log!( MySQLConnection, - "sending password TLS enabled" + "secure transport, sending password as is" ); - // SSL mode is enabled, send password as is let mut packet = self.writer().start(self.sequence_id)?; self.writer().write_z(&self.password)?; packet.end()?; diff --git a/test/js/sql/sql-mysql.auth.test.ts b/test/js/sql/sql-mysql.auth.test.ts index 097e265a40b9..b5b23170992e 100644 --- a/test/js/sql/sql-mysql.auth.test.ts +++ b/test/js/sql/sql-mysql.auth.test.ts @@ -1,13 +1,19 @@ import { SQL } from "bun"; -import { expect, test } from "bun:test"; -import { describeWithContainer } from "harness"; +import { describe, expect, test } from "bun:test"; +import { describeWithContainer, tempDir } from "harness"; import { createHash } from "node:crypto"; +import type { Server, Socket } from "node:net"; import { listeningServer, + listeningUnixServer, MYSQL_FAST_AUTH_SUCCESS, MYSQL_MOCK_AUTH_DATA_PART_1, MYSQL_MOCK_AUTH_DATA_PART_2, + MYSQL_PERFORM_FULL_AUTHENTICATION, + MYSQL_REQUEST_PUBLIC_KEY, mysqlAuthMoreData, + mysqlAuthSwitchRequest, + mysqlErrPacket, mysqlHandshakeV10, mysqlOkPacket, mysqlParseHandshakeResponse41, @@ -218,3 +224,141 @@ test("caching_sha2_password scramble hashes the double-SHA256 before the nonce", server.close(); } }); + +// perform_full_authentication (AuthMoreData 0x04) asks the client for the password itself, and +// what the client may put on the wire depends on the transport. libmysqlclient, mysql2 +// (`config.ssl || config.socketPath`) and go-sql-driver (`Net == "unix"`) treat a unix socket +// like TLS and send the NUL-terminated password; only plain TCP has to fetch the server's RSA +// key first, which is what allowPublicKeyRetrieval gates. +// https://dev.mysql.com/doc/dev/mysql-server/latest/page_caching_sha2_authentication_exchanges.html +describe("caching_sha2_password full authentication", () => { + const password = "bunbun"; + const CLEARTEXT_PASSWORD = Buffer.concat([Buffer.from(password), Buffer.from([0])]).toString("hex"); + const PUBLIC_KEY_REQUEST = Buffer.from([MYSQL_REQUEST_PUBLIC_KEY]).toString("hex"); + + type Exchange = { + transport: "unix" | "tcp"; + allowPublicKeyRetrieval?: boolean; + /** Reach caching_sha2_password through an AuthSwitchRequest instead of the greeting. */ + viaAuthSwitch?: boolean; + }; + + /** + * Scripted server: answers the client's scramble (or AuthSwitchResponse) with + * perform_full_authentication and reports the one packet the client sends back, or `[]` + * if it sends none. The password is accepted with OK; anything else gets the + * ER_ACCESS_DENIED_ERROR a real server would answer with. + */ + function fullAuthServer(opts: Exchange, sockets: Set) { + const afterFullAuth = Promise.withResolvers(); + const onSocket = (socket: Socket) => { + sockets.add(socket); + let buffered = Buffer.alloc(0); + let phase: "handshake-response" | "auth-switch-response" | "full-auth" | "done" = "handshake-response"; + socket.write( + mysqlHandshakeV10({ authPlugin: opts.viaAuthSwitch ? "mysql_native_password" : "caching_sha2_password" }), + ); + socket.on("error", () => {}); + socket.on("close", () => { + sockets.delete(socket); + afterFullAuth.resolve([]); + }); + socket.on("data", chunk => { + buffered = mysqlReadPackets(Buffer.concat([buffered, chunk]), (seq, payload) => { + switch (phase) { + case "handshake-response": + if (opts.viaAuthSwitch) { + phase = "auth-switch-response"; + socket.write(mysqlAuthSwitchRequest(seq + 1, "caching_sha2_password", Buffer.alloc(20, 0x63))); + return; + } + phase = "full-auth"; + socket.write(mysqlAuthMoreData(seq + 1, Buffer.from([MYSQL_PERFORM_FULL_AUTHENTICATION]))); + return; + case "auth-switch-response": + phase = "full-auth"; + socket.write(mysqlAuthMoreData(seq + 1, Buffer.from([MYSQL_PERFORM_FULL_AUTHENTICATION]))); + return; + case "full-auth": { + phase = "done"; + const sent = payload.toString("hex"); + socket.write(sent === CLEARTEXT_PASSWORD ? mysqlOkPacket(seq + 1) : mysqlErrPacket(seq + 1)); + afterFullAuth.resolve([sent]); + return; + } + case "done": + // COM_QUIT from the close() below. + return; + } + }); + }); + }; + return { onSocket, afterFullAuth: afterFullAuth.promise }; + } + + async function fullAuthExchange(opts: Exchange) { + using dir = tempDir("mysql-full-auth", {}); + const sockets = new Set(); + const { onSocket, afterFullAuth } = fullAuthServer(opts, sockets); + let server: Server; + let endpoint: { path: string } | { hostname: string; port: number }; + if (opts.transport === "unix") { + const unix = await listeningUnixServer(String(dir), onSocket); + server = unix.server; + endpoint = { path: unix.path }; + } else { + const tcp = await listeningServer(onSocket); + server = tcp.server; + endpoint = { hostname: "127.0.0.1", port: tcp.port }; + } + + const db = new SQL({ + adapter: "mysql", + ...endpoint, + username: "u", + password, + database: "d", + tls: false, + max: 1, + allowPublicKeyRetrieval: opts.allowPublicKeyRetrieval, + }); + let outcome: string | { code: string }; + try { + outcome = await db.connect().then( + () => "connected", + (e: { code?: string }) => ({ code: e?.code ?? String(e) }), + ); + } finally { + await db.close({ timeout: 0 }); + // Settles afterFullAuth (with []) if the client neither answered nor hung up. + for (const socket of sockets) socket.destroy(); + await new Promise(resolve => server.close(() => resolve())); + } + return { outcome, afterFullAuth: await afterFullAuth }; + } + + test.each<{ name: string } & Exchange>([ + { name: "with the default options", transport: "unix" }, + { name: "even with allowPublicKeyRetrieval", transport: "unix", allowPublicKeyRetrieval: true }, + { name: "after an AuthSwitchRequest", transport: "unix", viaAuthSwitch: true }, + ])("over a unix socket the password is sent as is $name", async opts => { + expect(await fullAuthExchange(opts)).toEqual({ + outcome: "connected", + afterFullAuth: [CLEARTEXT_PASSWORD], + }); + }); + + test("over TCP nothing is sent unless allowPublicKeyRetrieval is set", async () => { + expect(await fullAuthExchange({ transport: "tcp" })).toEqual({ + outcome: { code: "ERR_MYSQL_PUBLIC_KEY_RETRIEVAL_NOT_ALLOWED" }, + afterFullAuth: [], + }); + }); + + test("over TCP with allowPublicKeyRetrieval the public key is requested, never the password", async () => { + expect(await fullAuthExchange({ transport: "tcp", allowPublicKeyRetrieval: true })).toEqual({ + outcome: { code: "ERR_MYSQL_SERVER_ERROR" }, + afterFullAuth: [PUBLIC_KEY_REQUEST], + }); + }); +}); diff --git a/test/js/sql/wire-frames.ts b/test/js/sql/wire-frames.ts index 3903b1c7364f..a6987039b65d 100644 --- a/test/js/sql/wire-frames.ts +++ b/test/js/sql/wire-frames.ts @@ -5,6 +5,7 @@ // Buffer.alloc / writeInt32BE sequences. import net from "node:net"; +import { join } from "node:path"; // --------------------------------------------------------------------------- // Server helpers shared by every fault-injection test. @@ -19,6 +20,17 @@ export async function listeningServer( return { port: (server.address() as net.AddressInfo).port, server }; } +/** Start a server on a unix domain socket inside `dir` (a `tempDir` the caller owns); connect to it with the SQL `path` option. */ +export async function listeningUnixServer( + dir: string, + onSocket: (socket: net.Socket) => void, +): Promise<{ path: string; server: net.Server }> { + const server = net.createServer(onSocket); + const path = join(dir, "db.sock"); + await new Promise(resolve => server.listen(path, resolve)); + return { path, server }; +} + /** Reserve and immediately release a port so connecting to it is refused. */ export async function closedPort(): Promise { const server = net.createServer(); @@ -356,15 +368,36 @@ export function mysqlOkPacket(seq: number, header: 0x00 | 0xfe = 0x00): Buffer { return mysqlRawPacket(seq, Buffer.from([header, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00])); } +// MySQL Protocol::ERR_Packet, page_protocol_basic_err_packet.html (CLIENT_PROTOCOL_41 form): +// Int<1>(0xff) Int<2>(error_code) String<1>('#') String<5>(sql_state) String(error_message) +// Defaults to ER_ACCESS_DENIED_ERROR, the rejection a server sends when authentication fails. +export function mysqlErrPacket(seq: number, opts: { code?: number; sqlState?: string; message?: string } = {}): Buffer { + const code = Buffer.alloc(2); + code.writeUInt16LE(opts.code ?? 1045, 0); + return mysqlRawPacket( + seq, + Buffer.concat([ + Buffer.from([0xff]), + code, + Buffer.from(`#${opts.sqlState ?? "28000"}`), + Buffer.from(opts.message ?? "Access denied", "utf-8"), + ]), + ); +} + // MySQL Protocol::AuthMoreData — page_protocol_connection_phase_packets_protocol_auth_more_data.html: // Int<1>(0x01) String(plugin-specific payload) export function mysqlAuthMoreData(seq: number, data: Buffer): Buffer { return mysqlRawPacket(seq, Buffer.concat([Buffer.from([0x01]), data])); } -// caching_sha2_password fast_auth_success marker carried in an AuthMoreData payload — -// page_caching_sha2_authentication_exchanges.html (its sibling, 0x04, is perform_full_authentication). +// caching_sha2_password single-byte AuthMoreData payloads, page_caching_sha2_authentication_exchanges.html: +// the server answers the scramble with fast_auth_success or perform_full_authentication; a client asked for +// full authentication sends request_public_key over plain TCP, and the NUL-terminated password over TLS or +// a unix socket. +export const MYSQL_REQUEST_PUBLIC_KEY = 0x02; export const MYSQL_FAST_AUTH_SUCCESS = 0x03; +export const MYSQL_PERFORM_FULL_AUTHENTICATION = 0x04; // MySQL Protocol::AuthSwitchRequest — page_protocol_connection_phase_packets_protocol_auth_switch_request.html: // Int<1>(0xfe) NulString(plugin_name) String(plugin_provided_data)