-
Notifications
You must be signed in to change notification settings - Fork 5k
sql: detach the stored socket in on_close/on_connect_error #32861
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
robobun
wants to merge
4
commits into
main
Choose a base branch
from
farm/d0f6b155/sql-detach-socket-on-close
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+182
−0
Open
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
b40d131
sql: detach the stored socket in on_close/on_connect_error
robobun 59d4ce9
ci: retrigger
robobun b8a8ce0
test: address review feedback on sql-connection-socket-uaf
robobun 384bf5a
test: drop redundant per-test timeout and relax stderr assertion
robobun File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,165 @@ | ||
| // 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. | ||
| // | ||
| // PostgresSQLConnection/MySQLConnection kept the raw us_socket_t* in | ||
| // self.socket after usockets dispatched on_close/on_connect_error. usockets | ||
| // frees closed sockets at the end of the same tick, so any later read of | ||
| // self.socket.is_closed() (connection.ref()/.unref()/.close(), or the | ||
| // connectionTimeout timer) was a heap-use-after-free. Valkey already | ||
| // detaches its stored socket in the same callbacks; Postgres and MySQL now | ||
| // do too. | ||
| // | ||
| // The fixture captures the native connection by shadowing the query | ||
| // handle's .run(connection, query), lets the server drop the socket, yields | ||
| // past us_internal_free_closed_sockets, then touches the native connection | ||
| // through a method that reads the stored socket pointer. | ||
|
|
||
| import { expect, test } from "bun:test"; | ||
| import { bunEnv, bunExe, isASAN, isDebug, tempDir } from "harness"; | ||
| import path from "node:path"; | ||
|
|
||
| const wireFrames = path.join(import.meta.dir, "wire-frames.ts"); | ||
|
|
||
| const drivers = [ | ||
| { | ||
| name: "postgres", | ||
| // .ref() calls update_has_pending_activity() which reads | ||
| // self.socket.is_closed() when the connection is in a terminal state. | ||
| touch: "nativeConnection.ref(); nativeConnection.unref();", | ||
| server: /* js */ ` | ||
| import { pgAuthenticationOk, pgReadyForQuery } from ${JSON.stringify(wireFrames)}; | ||
| export const url = port => \`postgres://postgres@127.0.0.1:\${port}/db\`; | ||
| export function onSocket(socket) { | ||
| socket.once("data", () => { | ||
| socket.write(Buffer.concat([pgAuthenticationOk(), pgReadyForQuery()])); | ||
| }); | ||
| socket.on("error", () => {}); | ||
| }`, | ||
| }, | ||
| { | ||
| name: "mysql", | ||
| // .close() on a failed connection calls clean_queue_and_close() which | ||
| // calls self.socket.close() and so reads the freed is_closed flag. | ||
| touch: "nativeConnection.close();", | ||
| server: /* js */ ` | ||
| import { mysqlHandshakeV10, mysqlOkPacket } from ${JSON.stringify(wireFrames)}; | ||
| export const url = port => \`mysql://root@127.0.0.1:\${port}/db\`; | ||
| export function onSocket(socket) { | ||
| let buffered = Buffer.alloc(0), authed = false; | ||
| socket.write(mysqlHandshakeV10()); | ||
| socket.on("data", chunk => { | ||
| buffered = Buffer.concat([buffered, chunk]); | ||
| while (buffered.length >= 4) { | ||
| const len = buffered[0] | (buffered[1] << 8) | (buffered[2] << 16); | ||
| if (buffered.length < 4 + len) break; | ||
| const seq = buffered[3]; | ||
| buffered = buffered.subarray(4 + len); | ||
| if (!authed) { authed = true; socket.write(mysqlOkPacket(seq + 1)); } | ||
| // never respond to queries, so they stay in the native request queue | ||
| } | ||
| }); | ||
| socket.on("error", () => {}); | ||
| }`, | ||
| }, | ||
| ] as const; | ||
|
|
||
| // The failure is a 1-byte heap-use-after-free; it is only observable under | ||
| // ASAN (debug builds enable ASAN). | ||
| for (const { name, touch, server } of drivers) { | ||
| test.skipIf(!isDebug && !isASAN)( | ||
| `${name}: touching the native connection after the socket is freed does not read freed memory`, | ||
| async () => { | ||
| using dir = tempDir(`sql-conn-socket-uaf-${name}`, { | ||
| "server.ts": server, | ||
| "fixture.ts": /* js */ ` | ||
| import net from "node:net"; | ||
| import { SQL } from "bun"; | ||
| import { onSocket, url } from "./server.ts"; | ||
|
|
||
| let socketRef; | ||
| const server = net.createServer(socket => { | ||
| socketRef = socket; | ||
| onSocket(socket); | ||
| }); | ||
| server.listen(0, "127.0.0.1"); | ||
| await new Promise(r => server.on("listening", r)); | ||
|
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
| const { port } = server.address(); | ||
|
|
||
| const sql = new SQL({ url: url(port), max: 1, connectionTimeout: 30 }); | ||
|
|
||
| // Capture the native connection by shadowing the query handle's | ||
| // .run(connection, query) — the pool hands it the native handle. | ||
| let nativeConnection; | ||
| let runCount = 0; | ||
| const q = sql\`select 1\`; | ||
| q.values(); // force lazy creation of the native query handle | ||
| const handleSym = Object.getOwnPropertySymbols(q).find(s => s.description === "handle"); | ||
| const handle = q[handleSym]; | ||
| const protoRun = Object.getPrototypeOf(handle).run; | ||
| Object.defineProperty(handle, "run", { | ||
| configurable: true, | ||
| writable: true, | ||
| value(connection, query) { | ||
| nativeConnection = connection; | ||
| runCount++; | ||
| return protoRun.call(this, connection, query); | ||
| }, | ||
| }); | ||
| const settled = q.catch(err => err?.code ?? String(err)); | ||
|
|
||
| // Wait for the connection to establish and the query to enqueue. | ||
| while (runCount === 0) await new Promise(r => setImmediate(r)); | ||
|
|
||
| // Replace the pool's JS onclose so it does not pre-emptively drop | ||
| // our reference; we want the native connection to outlive the | ||
| // socket by at least one tick. | ||
| nativeConnection.onclose = () => {}; | ||
|
|
||
| // Server drops the socket -> native on_close -> status=Failed. The | ||
| // us_socket_t goes onto closed_head and is freed at the end of the | ||
| // current usockets tick. | ||
| socketRef.destroy(); | ||
|
|
||
| // Yield past us_internal_free_closed_sockets. | ||
| for (let i = 0; i < 5; i++) await new Promise(r => setImmediate(r)); | ||
|
|
||
| // Without the fix this reads s->flags.is_closed on a freed | ||
| // us_socket_t and ASAN aborts with heap-use-after-free. | ||
| ${touch} | ||
|
|
||
| await settled; | ||
| // A second round of touches after the promise machinery has | ||
| // settled covers the re-entrant path the timer originally hit. | ||
| ${touch} | ||
|
|
||
| console.log("ok"); | ||
| process.exit(0); | ||
| `, | ||
| }); | ||
|
|
||
| await using proc = Bun.spawn({ | ||
| cmd: [bunExe(), "fixture.ts"], | ||
| env: { | ||
| ...bunEnv, | ||
| // symbolize=0: the full symbolized report under debug+ASAN can | ||
| // take tens of seconds; we only need to see the crash, not the | ||
| // stack. | ||
| ASAN_OPTIONS: "allow_user_segv_handler=1:disable_coredump=1:symbolize=0", | ||
| BUN_ENABLE_CRASH_REPORTING: "0", | ||
| }, | ||
| cwd: String(dir), | ||
| stdout: "pipe", | ||
| stderr: "pipe", | ||
| timeout: 20_000, | ||
| }); | ||
|
|
||
| const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); | ||
|
|
||
| expect({ stdout, stderr, exitCode }).toEqual({ stdout: "ok\n", stderr: "", exitCode: 0 }); | ||
| }, | ||
| 30_000, | ||
| ); | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.