Repository navigation
sql(mysql,postgres): reject duplicate auth requests; make connectionTimeout an absolute handshake deadline - #36308
Conversation
…onTimeout an absolute handshake deadline A malicious or MITM'd server that answers every client auth packet with another AuthSwitchRequest (mysql) or AuthenticationSASL/MD5/Cleartext (postgres) drove the client into an unbounded auth loop at 100% CPU, pre-auth, with no application-visible signal. connectionTimeout never fired because on_data re-armed the connect-phase timer on every inbound packet, so any server that trickles bytes held the client indefinitely. MySQL: track whether an AuthSwitchRequest has already been honoured and reject a second one with ERR_MYSQL_UNEXPECTED_PACKET (mysql2 and libmysqlclient refuse a second switch). on_data now leaves the connect-phase timer running until the auth OK transitions the connection to Connected. Postgres: AuthenticationSASL / AuthenticationCleartextPassword / AuthenticationMD5Password each start an authentication exchange and are now only accepted while authentication_state is Pending; any later arrival is rejected with ERR_POSTGRES_UNEXPECTED_MESSAGE (libpq: "duplicate SASL authentication request"). on_data now leaves the connect-phase timer running until ReadyForQuery transitions the connection to Connected.
WalkthroughChangesThe MySQL and PostgreSQL SQL clients now bound authentication protocol exchanges, reject duplicate authentication requests, and preserve connection deadlines across partial handshakes. New fault-injection tests cover invalid loops, valid authentication, and trickled handshake timeouts. SQL protocol authentication hardening
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Status: ready for review; diff is green, CI flaky on unrelated lanes. Reproduced with the script in the report: stock bun answers 40 AuthSwitchRequests over ~8s with MySQL: Postgres half folds in #33671 which was conflicting with main. Fail-before / pass-after on both new test files (11 bug cases fail on stock bun, 4 happy-path boundaries pass on both). Verification cells: endless-AuthSwitch rejects in ~200ms, 500ms/byte trickle times out at ~2.1s with CI: both new |
|
Found 1 issue this PR may fix:
🤖 Generated with Claude Code |
|
This PR may be a duplicate of:
🤖 Generated with Claude Code |
…urrent plugin Replaces the boolean one-switch cap with an auth_switch_count and an explicit same-plugin check: reject when count >= 2 or when the requested plugin equals the plugin already in use (the signature of the ping-pong attack; mysql2 errors on a repeated auth switch).
There was a problem hiding this comment.
Additional findings (outside current diff — PR may have been updated during review):
-
🔴
src/sql_jsc/mysql/MySQLConnection.rs:899-908— Theauth_switchedguard boundsPacketType::AUTH_SWITCH, but the siblingPacketType::MORE_DATAarm in the samehandle_authmatch still lets a hostile server drive an unbounded caching_sha2 ping-pong: over TLS eachCONTINUE_AUTH(0x04) elicits another plaintext-password write with no state change, and over plain TCP withallowPublicKeyRetrieval: trueit oscillatesAuthenticationAwaitingPk↔Authenticating. The absolute-deadline timer only bounds this whenconnectionTimeout > 0;connectionTimeout: 0is an explicitly supported value that disables the timer (src/js/internal/sql/shared.ts:730), leaving the loop structurally unbounded — the same class this PR targets. A per-handshake flag on theCONTINUE_AUTH/ public-key branches mirroringauth_switchedwould close it (REVIEW.md: "fix the whole class — parallel switch arms").Extended reasoning...
What the bug is
This PR adds
auth_switched: boolto structurally boundPacketType::AUTH_SWITCH— a second AuthSwitchRequest is now rejected withUnexpectedPacket. However, the immediately adjacentPacketType::MORE_DATAarm in the samehandle_authmatch (MySQLConnection.rs:807–880, specifically theFastAuthStatus::CONTINUE_AUTHbranch at :828) has no equivalent per-handshake state, so a hostile/MITM server can still drive an unbounded auth ping-pong through the caching_sha2_password continuation path — the exact loop shape this PR fixes for AUTH_SWITCH.Step-by-step proof (TLS path — the common production configuration)
- Server greets with
caching_sha2_password; client sends HandshakeResponse41.status = Authenticating,auth_plugin = Some(CachingSha2Password),tls_status = SslOk. - Server sends MORE_DATA (0x01) with body
[0x04]→FastAuthStatus::CONTINUE_AUTH. handle_authMORE_DATA arm, CONTINUE_AUTH branch: sincetls_status == SslOk, the client writes the plaintext password packet (writer().write_z(&self.password)) and callsflush_data(). No field onselfchanges — status staysAuthenticating,auth_pluginstaysCachingSha2Password, no counter advances.- Server replies with another MORE_DATA
[0x04]. Step 3 repeats. Forever.
The plain-TCP variant (with
allowPublicKeyRetrieval: true) alternates: CONTINUE_AUTH →set_status(AuthenticationAwaitingPk)+ send PublicKeyRequest → next MORE_DATA hitshandle_handshake_decode_public_keywhich explicitly doesset_status(Authenticating)+ sends encrypted password → server sends CONTINUE_AUTH again → back to step 1. Also unbounded.Why the PR's other fix does not fully cover this
The
on_datachange makesconnectionTimeoutan absolute deadline, which bounds the loop to ~30 s at the default. ButconnectionTimeout: 0is an explicitly supported value:src/js/internal/sql/shared.ts:1997only rejects< 0;0is accepted.src/js/internal/sql/shared.ts:730documents "an explicit connectionTimeout of 0 disables the connect timer".- In
JSMySQLConnection.rs,get_timeout_interval()returnsconnection_timeout_msduring handshake, andreset_connection_timeout()returns early wheninterval == 0, so no timer is ever armed.
With
connectionTimeout: 0the MORE_DATA loop is structurally unbounded — the identical failure mode ("unbounded authentication loop at 100% CPU, pre-auth") that this PR's description names as the defect. Even at the 30 s default, that is 30 s of tight-loop CPU + repeated password transmission on every connection attempt, pre-auth — the AUTH_SWITCH arm was not left in that state, it got a structural bound.Why this belongs in this PR
REVIEW.md, Correctness: the bug class, not the bug: "Fix the whole class in the same PR … grep for every sibling site sharing the pattern: parallel switch arms".
MORE_DATAis a literal sibling match arm ofAUTH_SWITCHin the same function, with the same threat model (hostile/MITM server driving auth ping-pong) and the same fix shape. The PR description frames the defect generically as "unbounded authentication loop" and cites mysql2/libmysqlclient as the reference; leaving one of the two server-driven auth-request arms unguarded means the class is only half-fixed.How to fix
Mirror
auth_switchedwith a per-handshake flag on the CONTINUE_AUTH path — e.g. afull_auth_sent: bool(or a small round counter) set when the client writes the plaintext-password / encrypted-password / public-key-request response, and checked at the top of the CONTINUE_AUTH branch to returnAnyMySQLError::UnexpectedPacketon repeat. One flag covers both the TLS andAuthenticationAwaitingPkvariants. - Server greets with
…nd per handshake The MORE_DATA/CONTINUE_AUTH arm (the sibling of AUTH_SWITCH in handle_auth) had the same unbounded loop: over TLS each 0x04 elicited another plaintext password write with no state change, and over plain TCP with allowPublicKeyRetrieval it oscillated AwaitingPk <-> Authenticating.
|
Good catch on the |
Azure Database for MySQL, ProxySQL and similar front-ends answer the HandshakeResponse with an AuthSwitchRequest naming the plugin the greeting already advertised, carrying a fresh nonce; libmysqlclient, mysql2 and go-sql-driver/mysql all honour it. Gate the same-plugin rejection on auth_switch_count > 0 so only a second switch back to a plugin already tried is refused.
There was a problem hiding this comment.
Both earlier blocking findings are addressed: the first-AuthSwitch-to-greeting-plugin regression is now gated on auth_switch_count > 0 (cd5b298), and the caching_sha2 CONTINUE_AUTH sibling arm is bounded by full_auth_requested (c68f8ae). I also traced the connect→idle timer handoff under the new Connected-gated reset in on_data for both adapters — the transition still re-arms the idle timer once the OK/ReadyForQuery packet lands. Deferring to a human given this is pre-auth protocol handling and changes connection-timeout semantics.
Extended reasoning...
My two prior inline findings on this PR are resolved and the remaining inline comment is a test-style nit. Beyond that I verified the timer semantics change does not strand the connection without a timer: on the packet that transitions status to Connected, MySQL's deferred block runs after read_and_process_data clears IS_PROCESSING_DATA with status already Connected, and Postgres clears the flag at on_data:1063 before the gated reset_connection_timeout() at 1065-1067 — so the idle timer is armed on both paths. Not auto-approving because this is security-sensitive pre-auth handling across two adapters plus a behavioural change to what connectionTimeout measures.
There was a problem hiding this comment.
The three earlier findings (Azure/ProxySQL same-plugin first switch, the unguarded CONTINUE_AUTH sibling arm, and the inlined pgRaw frame) are all addressed in the current diff, and I found nothing new. Deferring to a human because this is auth-protocol state-machine code across both adapters and it changes what connectionTimeout means (per-packet → absolute handshake deadline).
What was reviewed
- Traced the Postgres
Pending-only guard againstSASLContinue/SASLFinal/Ok— those arms usesasl_state_mut()/separate variants, so the SCRAM continuation flow is unaffected. - Checked the timer gating on both sides:
reset_connection_timeout()removes-then-reinserts, so the handshake→Connected transition insideon_datacorrectly re-arms as the idle timer;on_connection_timeoutalready early-returns onIS_PROCESSING_DATA. - Walked the
auth_switch_count/auth_pluginguard through the greeting→switch→switch sequences; the same-plugin clause now only trips on the second switch, andfull_auth_requestedbounds the PK-retrieval loop.
Extended reasoning...
Overview
Bounds the pre-auth handshake against hostile/MITM servers in both SQL adapters: MySQL gains auth_switch_count (cap 2, plus a same-plugin check gated on count > 0) and full_auth_requested for the caching_sha2 CONTINUE_AUTH arm; Postgres now only accepts AuthenticationSASL/ClearTextPassword/MD5Password while authentication_state == Pending (new ClearText variant records that a password was sent). Both adapters' on_data stop resetting the connect-phase timer per packet, making connectionTimeout an absolute connect→ready deadline. Two new fault-injection test files cover the loop cases, the happy-path boundaries, and the trickle-timeout, plus two new frame builders in wire-frames.ts.
Security risks
This is the security fix — it closes a pre-auth CPU-spin / stall DoS. The residual risk is over-tightening: rejecting a sequence a real server legitimately sends. My earlier round caught exactly that (the same-plugin first-switch rejection would have broken Azure MySQL / ProxySQL); the fix in cd5b298 gates it on count > 0 and adds a happy-path test for the fresh-nonce pattern. I re-walked the remaining rejection paths and each corresponds to a sequence libmysqlclient/mysql2/libpq also refuse. full_auth_requested is not reset on an intervening AUTH_SWITCH, so a caching_sha2 → CONTINUE_AUTH → switch-away → switch-back-to-caching_sha2 → CONTINUE_AUTH sequence would be rejected, but I could not find any real server that does this and the count cap would terminate it one packet later anyway.
Level of scrutiny
High — this is authentication protocol state-machine logic, and the connectionTimeout change is a user-visible semantic shift (previously any handshake activity kept the connection alive; now it's a hard deadline). A maintainer should confirm they want the timeout semantics change and glance at the two rejection guards.
Other factors
This has already been through two rounds of my review with fixes landed for each finding; the bug-hunt system found nothing on the current head. Tests are thorough (fail-before/pass-after evidence in the PR body covers 11 bug cases + 4 boundary cases across debug-ASAN and release). CI is green on the touched files; the one red lane is an unrelated worker_threads SIGABRT also failing on main. #33671 is superseded by this PR.
There was a problem hiding this comment.
No issues found this round — the earlier findings (Azure/ProxySQL first-switch compat, the CONTINUE_AUTH sibling arm, and the pgRaw helper) are all addressed. Deferring to a maintainer because this changes the user-visible connectionTimeout semantics on both adapters (per-packet inactivity → absolute connect→ready deadline) alongside the auth-state-machine guards, and that behaviour shift is worth a human sign-off.
What was reviewed:
- Traced the Postgres
on_datatimer bracket: connect-phase timer now stays armed through auth; on theReadyForQuery→Connectedtransition the exit-sidereset_connection_timeout()still runs and swaps to the idle timer; theConnected→Failedmid-on_datapath leaves the timer cancelled, same net effect as before. - Verified the MD5 arm's pre-existing
authentication_state.set(Md5)makes the newPending-only guard effective there; SASLContinue/SASLFinal are separate arms and unaffected. - Checked
full_auth_requestedis set before both the plain-TCP public-key-request branch and the TLS cleartext-password branch, so both loop shapes are bounded. - Confirmed the
auth_switch_count > 0 && same-pluginclause admits the first same-plugin switch (Azure fresh-nonce) and only rejects a repeat.
Extended reasoning...
Overview
The PR hardens the MySQL and Postgres SQL clients against a hostile-server pre-auth DoS: (1) a per-handshake counter/flag rejects repeated AuthSwitchRequest / CONTINUE_AUTH (MySQL) and repeated Authentication{SASL,CleartextPassword,MD5Password} (Postgres) with ERR_*_UNEXPECTED_*; (2) on_data on both adapters now leaves the connect-phase timer running until the connection reaches Connected, so connectionTimeout is an absolute connect→ready deadline instead of a per-packet inactivity window. Two new fault-injection test files exercise the duplicate-request rejections, the happy-path boundaries, and the trickle-timeout, plus two new frame builders in wire-frames.ts.
Security risks
The change is itself a security hardening (bounds a pre-auth CPU spin and an indefinite hang). The risk surface is regression: over-tight guards could reject legitimate server sequences. That already happened once in review (the same-plugin first-switch clause broke Azure MySQL / ProxySQL) and was fixed by gating on auth_switch_count > 0. I re-checked the Postgres SASL flow — SASLContinue/SASLFinal are separate match arms so the multi-roundtrip SCRAM exchange is unaffected by the new Pending-only gate on AuthenticationSASL.
Level of scrutiny
High. This is auth-path protocol state on two adapters, and it changes the user-observable contract of connectionTimeout. A legitimately slow server (cold-start container, congested link) that previously survived because each packet reset the timer will now hit ERR_*_CONNECTION_TIMEOUT at the absolute deadline. That is almost certainly the right behaviour (matches libpq / mysql2), but it is a behaviour change a maintainer should confirm — in particular whether any docs / release notes need to mention it.
Other factors
- All three of my prior inline findings are resolved and the fixes look right on re-read.
- Test coverage is good: fail-before/pass-after on 11 bug cases, 4 boundary happy paths, both adapters, the mixed-method Postgres matrix, and the caching_sha2 public-key loop.
- The Postgres SASL arm's guard was flipped from "lazy-init if not already Sasl" to "reject if not Pending" — I confirmed nothing else sets
authentication_stateback toPendingafter the first request, so this can't false-positive on the legitimate single-request path. - The MySQL timer gate is in the
scopeguard::defer!, so it runs afterread_and_process_datahas clearedIS_PROCESSING_DATA;reset_connection_timeout()'s ownis_processing_data()early-return therefore doesn't interfere.
Problem
A hostile or MITM'd server that answers every client auth packet with another AuthSwitchRequest (MySQL 0xFE) or AuthenticationSASL / MD5Password / CleartextPassword (Postgres
R) drives Bun into an unbounded authentication loop at 100% CPU, pre-auth, with no application-visible signal.connectionTimeoutnever fires becauseon_datare-arms the connect-phase timer on every inbound packet, so any server that dribbles bytes (e.g. one greeting byte per 1.5s) holds the client indefinitely.mysql2 / libmysqlclient refuse a second auth-switch; libpq rejects a second AuthenticationSASL with
duplicate SASL authentication request.Cause
Two independent defects, shared between the adapters:
MySQLConnection::handle_authhonoured everyPacketType::AUTH_SWITCHwith no per-handshake state. The PostgresAuthentication::SASL/ClearTextPassword/MD5Passwordarms likewise accepted a fresh request in every authentication state.JSMySQLConnection::on_dataandPostgresSQLConnection::on_databracketed processing with areset_connection_timeout()(mysql) /disable_connection_timeout()+reset_connection_timeout()(postgres), turning the connect deadline into a per-packet inactivity timer.Fix
MySQL: record that an AuthSwitchRequest has been honoured and reject a second one with
ERR_MYSQL_UNEXPECTED_PACKET.on_datanow leaves the connect-phase timer running until the auth OK transitions the connection toConnected, at which point it is re-armed as the idle timer.Postgres:
AuthenticationSASL,AuthenticationCleartextPasswordandAuthenticationMD5Passwordare only accepted whileauthentication_stateisPending; any later arrival is rejected withERR_POSTGRES_UNEXPECTED_MESSAGE. A newAuthenticationState::ClearTextrecords that a cleartext password was sent.on_datanow leaves the connect-phase timer running untilReadyForQuerytransitions the connection toConnected.Verification
New scripted wire-server tests:
test/js/sql/sql-mysql-duplicate-auth-switch.test.ts: a second AuthSwitchRequest is rejected after exactly one response; the one-switch happy path still connects; a server that trickles the greeting one byte per 200ms fails at the 1sconnectionTimeout.test/js/sql/postgres-duplicate-auth-request.test.ts: duplicate and mixed-method auth requests are rejected after exactly one response; the single-request cleartext and MD5 happy paths still connect; a server that trickles bytes during auth fails at the 1sconnectionTimeout.Existing
wire-frames.test.ts,sql-mysql-auth-short-nonce.test.ts,sql-connect-error-reporting.test.ts,postgres-frame-boundary.test.ts,postgres-invalid-message-length.test.ts, and the scripted cases insql-mysql.auth.test.tspass unchanged.Closes #33671 (postgres half, now folded in and rebased).
[review] gate passed · iteration 4 · 7 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 5 passed · 1 rejected · iteration 4
evidence per changed file