Skip to content
5 changes: 3 additions & 2 deletions src/sql_jsc/mysql/JSMySQLConnection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1049,8 +1049,9 @@ impl<const SSL: bool> SocketHandler<SSL> {
// `_ref` has not yet dropped, so `*p` is still live; `ParentRef`
// yields a fresh `&JSMySQLConnection` per access (R-2: every
// callee is `&self`).
// reset the connection timeout after we're done processing the data
p.reset_connection_timeout();
if p.connection.get().status == my_sql_connection::Status::Connected {
p.reset_connection_timeout();
}
p.update_reference_type();
p.register_auto_flusher();
}
Expand Down
17 changes: 15 additions & 2 deletions src/sql_jsc/mysql/MySQLConnection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@

auth_plugin: Option<AuthMethod>,
_auth_state: AuthState,
auth_switch_count: u8,

auth_data: Vec<u8>,
// PERF: database/user/password/options could be sub-slices into options_buf
Expand Down Expand Up @@ -108,6 +109,7 @@
status_flags: StatusFlags::default(),
auth_plugin: None,
_auth_state: AuthState::Pending,
auth_switch_count: 0,
auth_data: Vec::new(),
database: Box::default(),
user: Box::default(),
Expand Down Expand Up @@ -900,15 +902,26 @@
};
auth_switch.decode_internal(reader)?;

// Update auth plugin and data
let auth_method = AuthMethod::from_string(auth_switch.plugin_name.slice())
.ok_or(AnyMySQLError::UnsupportedAuthPlugin)?;

// Bound a hostile server's auth ping-pong.
if self.auth_switch_count >= 2 || self.auth_plugin == Some(auth_method) {

Check failure on line 909 in src/sql_jsc/mysql/MySQLConnection.rs

View check run for this annotation

Claude / Claude Code Review

Same-plugin AuthSwitchRequest rejection may break real MySQL-compatible servers

The `|| self.auth_plugin == Some(auth_method)` clause rejects the *first* AuthSwitchRequest whenever it names the plugin the server advertised in HandshakeV10 — but real MySQL-compatible endpoints (Azure Database for MySQL, ProxySQL, some MariaDB configs) do exactly this to deliver a fresh nonce, and libmysqlclient/mysql2/go-sql-driver all honour it. The `auth_switch_count >= 2` cap alone already fully bounds the ping-pong (an attacker just alternates two plugin names anyway), so this clause add
Comment thread
robobun marked this conversation as resolved.
Resolved
bun_core::scoped_log!(
MySQLConnection,
"rejecting AuthSwitchRequest (count={}, plugin={:?})",
self.auth_switch_count,
auth_method
);
return Err(AnyMySQLError::UnexpectedPacket);
}
self.auth_switch_count += 1;

Check warning on line 918 in src/sql_jsc/mysql/MySQLConnection.rs

View check run for this annotation

Claude / Claude Code Review

auth_switch_count does not cover the sibling MORE_DATA/CONTINUE_AUTH arm

The new `auth_switch_count` cap only guards the `AUTH_SWITCH` (0xFE) arm; the sibling `MORE_DATA` (0x01) → `CachingSha2Password` `CONTINUE_AUTH` branch in the same match — and the `AuthenticationAwaitingPk` ↔ `Authenticating` cycle it drives via `handle_handshake_decode_public_key` — still answers every server packet with no counter or state guard. The `on_data` change in this PR now bounds that loop by `connectionTimeout`, so the unbounded DoS is closed, but for consistency the count (or a dedi
Comment thread
claude[bot] marked this conversation as resolved.
Resolved

let auth_data = auth_switch.plugin_data.slice();
self.auth_plugin = Some(auth_method);
self.auth_data.clear();
self.auth_data.extend_from_slice(auth_data);

// Send new auth response
self.send_auth_switch_response(auth_method, auth_data)?;
}

Expand Down
1 change: 1 addition & 0 deletions src/sql_jsc/postgres/AuthenticationState.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub enum AuthenticationState {
Ok,
Sasl(SASL),
Md5,
ClearText,
}

impl AuthenticationState {
Expand Down
34 changes: 28 additions & 6 deletions src/sql_jsc/postgres/PostgresSQLConnection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -971,7 +971,9 @@ impl PostgresSQLConnection {
self.ref_();
self.update_flags(|f| f.insert(ConnectionFlags::IS_PROCESSING_DATA));

self.disable_connection_timeout();
if self.status.get() == Status::Connected {
self.disable_connection_timeout();
}

let event_loop = self.event_loop();
event_loop.enter();
Expand Down Expand Up @@ -1060,8 +1062,9 @@ impl PostgresSQLConnection {
}
self.update_flags(|f| f.remove(ConnectionFlags::IS_PROCESSING_DATA));

// reset the connection timeout after we're done processing the data
self.reset_connection_timeout();
if self.status.get() == Status::Connected {
self.reset_connection_timeout();
}
// SAFETY: `self` is a live Box-allocated connection; this releases one ref.
unsafe { Self::deref(self.as_ctx_ptr()) };
}
Expand Down Expand Up @@ -2647,13 +2650,16 @@ impl PostgresSQLConnection {

match &auth {
protocol::Authentication::SASL => {
// libpq: "duplicate SASL authentication request".
if !matches!(
self.authentication_state.get(),
AuthenticationState::Sasl(_)
AuthenticationState::Pending
) {
self.authentication_state
.set(AuthenticationState::Sasl(Default::default()));
debug!("duplicate AuthenticationSASL");
return Err(AnyPostgresError::UnexpectedMessage);
}
self.authentication_state
.set(AuthenticationState::Sasl(Default::default()));

let mut mechanism_buf = [0u8; 128];
// `sasl` borrow ends before `self.writer()`/`self.flush_data()`
Expand Down Expand Up @@ -2872,17 +2878,33 @@ impl PostgresSQLConnection {
}

protocol::Authentication::ClearTextPassword => {
if !matches!(
self.authentication_state.get(),
AuthenticationState::Pending
) {
debug!("duplicate AuthenticationCleartextPassword");
return Err(AnyPostgresError::UnexpectedMessage);
}
debug!("ClearTextPassword");
let response = protocol::PasswordMessage {
// password is a valid slice into options_buf.
password: Data::Temporary(self.password),
};

self.authentication_state
.set(AuthenticationState::ClearText);
response.write_internal(&mut self.writer())?;
self.flush_data();
}

protocol::Authentication::MD5Password { salt } => {
if !matches!(
self.authentication_state.get(),
AuthenticationState::Pending
) {
debug!("duplicate AuthenticationMD5Password");
return Err(AnyPostgresError::UnexpectedMessage);
}
debug!("MD5Password");
// Format is: md5 + md5(md5(password + username) + salt)
let mut first_hash_buf: [u8; 16] = Default::default();
Expand Down
209 changes: 209 additions & 0 deletions test/js/sql/postgres-duplicate-auth-request.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
// Fault-injection test: requires a server that refuses / drops / sends malformed
// frames, which a healthy container will not do on demand. DO NOT COPY THIS
// PATTERN — anything a real server can produce belongs in describeWithContainer.
// All wire-protocol bytes come from test/js/sql/wire-frames.ts; do not inline
// Buffer.alloc frame construction here.
//
// A server (or MITM) that answers the client's password / SASLInitialResponse
// with another Authentication{SASL,CleartextPassword,MD5Password} request
// drove the client into an unbounded authentication loop at 100% CPU, and
// connectionTimeout never fired because every arriving packet reset the
// connect-phase timer. libpq rejects a second AuthenticationSASL with
// "duplicate SASL authentication request".
import { SQL } from "bun";
import { expect, test } from "bun:test";
import {
listeningServer,
pgAuthenticationCleartextPassword,
pgAuthenticationMD5Password,
pgAuthenticationOk,
pgAuthenticationSASL,
pgReadyForQuery,
} from "./wire-frames";

/**
* Answer the startup packet with `first`, then answer every subsequent client
* message (PasswordMessage / SASLInitialResponse, type 'p') with `second`, up
* to `limit` times. Resolves to the error the client surfaced and the number
* of 'p' responses observed.
*/
async function duplicateAuthRequest(first: Buffer, second: Buffer, limit: number) {
let responses = 0;
const sockets = new Set<import("node:net").Socket>();
const { port, server } = await listeningServer(socket => {
sockets.add(socket);
let buf = Buffer.alloc(0);
let sawStartup = false;
socket.on("error", () => {});
socket.on("close", () => sockets.delete(socket));
socket.on("data", chunk => {
buf = Buffer.concat([buf, chunk]);
for (;;) {
if (!sawStartup) {
// StartupMessage: Int32(len) Int32(protocol) ...; no leading type byte.
if (buf.length < 4) return;
const len = buf.readInt32BE(0);
if (buf.length < len) return;
sawStartup = true;
buf = buf.subarray(len);
socket.write(first);
continue;
}
if (buf.length < 5) return;
const len = buf.readInt32BE(1);
if (buf.length < 1 + len) return;
const type = String.fromCharCode(buf[0]);
buf = buf.subarray(1 + len);
if (type !== "p") continue;
responses++;
if (responses >= limit) {
socket.destroy();
return;
}
socket.write(second);
}
});
});

const db = new SQL({
url: `postgres://u:pw@127.0.0.1:${port}/db?sslmode=disable`,
max: 1,
connectionTimeout: 30,
});
let err: any;
try {
await db.connect();
err = new Error("expected connect() to reject");
} catch (e) {
err = e;
} finally {
await db.close({ timeout: 0 });
for (const s of sockets) s.destroy();
await new Promise<void>(r => server.close(() => r()));
}
return { err, responses };
}

const methods = [
{ name: "AuthenticationSASL", frame: pgAuthenticationSASL() },
{ name: "AuthenticationCleartextPassword", frame: pgAuthenticationCleartextPassword() },
{ name: "AuthenticationMD5Password", frame: pgAuthenticationMD5Password() },
];

test.each(methods)("postgres: duplicate $name is rejected, not answered again", async ({ frame }) => {
const { err, responses } = await duplicateAuthRequest(frame, frame, 50);
// The client must answer the first request (responses == 1) and then error
// on the duplicate without answering it. Before the fix `responses` hit the
// limit in a few milliseconds.
expect({ code: err.code, responses }).toEqual({
code: "ERR_POSTGRES_UNEXPECTED_MESSAGE",
responses: 1,
});
});

// Mixed sequences: a second authentication-start message of any kind after
// a first of a different kind is equally a protocol violation.
const mixed = [
{ name: "SASL after CleartextPassword", first: pgAuthenticationCleartextPassword(), second: pgAuthenticationSASL() },
{ name: "CleartextPassword after SASL", first: pgAuthenticationSASL(), second: pgAuthenticationCleartextPassword() },
{ name: "MD5Password after SASL", first: pgAuthenticationSASL(), second: pgAuthenticationMD5Password() },
];

test.each(mixed)("postgres: $name is rejected", async ({ first, second }) => {
const { err, responses } = await duplicateAuthRequest(first, second, 50);
expect({ code: err.code, responses }).toEqual({
code: "ERR_POSTGRES_UNEXPECTED_MESSAGE",
responses: 1,
});
});

// Boundary: the normal single-request flow for each method still connects.
async function singleRequestConnects(request: Buffer) {
const { port, server } = await listeningServer(socket => {
let sawStartup = false;
socket.on("error", () => {});
socket.on("data", () => {
if (!sawStartup) {
sawStartup = true;
socket.write(request);
return;
}
socket.write(Buffer.concat([pgAuthenticationOk(), pgReadyForQuery()]));
});
});
const db = new SQL({
url: `postgres://u:pw@127.0.0.1:${port}/db?sslmode=disable`,
max: 1,
connectionTimeout: 30,
});
try {
await expect(db.connect()).resolves.toBeDefined();
} finally {
await db.close({ timeout: 0 });
await new Promise<void>(r => server.close(() => r()));
}
}

test("postgres: a single AuthenticationCleartextPassword still connects", async () => {
await singleRequestConnects(pgAuthenticationCleartextPassword());
});

test("postgres: a single AuthenticationMD5Password still connects", async () => {
await singleRequestConnects(pgAuthenticationMD5Password());
});

test("postgres: connectionTimeout bounds the whole handshake, not per packet", async () => {
// Server that answers the startup packet with AuthenticationCleartextPassword,
// then trickles the next response one byte at a time, each well under
// connectionTimeout, never completing a message. Before the fix each byte
// re-armed the connect timer so the client waited indefinitely; now it fails
// once the overall deadline passes.
const sockets = new Set<import("node:net").Socket>();
const { port, server } = await listeningServer(socket => {
sockets.add(socket);
let phase = 0;
let id: ReturnType<typeof setInterval> | undefined;
socket.on("error", () => {});
socket.on("close", () => {
if (id) clearInterval(id);
sockets.delete(socket);
});
socket.on("data", () => {
if (phase === 0) {
phase = 1;
socket.write(pgAuthenticationCleartextPassword());
} else if (phase === 1) {
phase = 2;
// Announce an Authentication ('R') message with a huge body so the
// client buffers indefinitely awaiting bytes that never complete.
const header = Buffer.alloc(5);
header.write("R", 0);
header.writeInt32BE(1 << 20, 1);
socket.write(header);
Comment thread
robobun marked this conversation as resolved.
Resolved
id = setInterval(() => {
if (!socket.destroyed) socket.write(Buffer.from([0]));
}, 200);
}
});
});

const t0 = performance.now();
const db = new SQL({
url: `postgres://u:pw@127.0.0.1:${port}/db?sslmode=disable`,
max: 1,
connectionTimeout: 1,
});
try {
const err = await db.connect().then(
() => ({ code: "UNEXPECTED_SUCCESS" }),
(e: any) => ({ code: e?.code ?? String(e) }),
);
const elapsed = performance.now() - t0;
expect(err).toEqual({ code: "ERR_POSTGRES_CONNECTION_TIMEOUT" });
expect(elapsed).toBeLessThan(8000);
} finally {
await db.close({ timeout: 0 });
for (const s of sockets) s.destroy();
await new Promise<void>(r => server.close(() => r()));
}
});
Loading
Loading