Skip to contentSkip to conversation

bpf: Fix out-of-bounds read of sk_protocol in bpf_sock_destroy()

PATCH Superseded Jiayuan Chen 3 participants 6 messages Sep 3

Subsystems (6)

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

PATCH 1/2 bpf: Fix out-of-bounds read of sk_protocol in bpf_sock_destroy()

sk_protocol lives in struct sock, not in struct sock_common. A timewait or request sock handed to bpf_sock_destroy() by the tcp iterator is neither, so reading sk->sk_protocol runs past the object:

==================================================================

BUG: KASAN: slab-out-of-bounds in bpf_sock_destroy+0xc7/0xe0
Read of size 2 at addr ffff8881047d11b4 by task test_progs/428

Tainted: [W]=WARN
Call Trace:
 <TASK>
 dump_stack_lvl+0x91/0xf0
 print_report+0xd1/0x630
 kasan_report+0xf3/0x130
 __asan_report_load2_noabort+0x14/0x30
 bpf_sock_destroy+0xc7/0xe0
 bpf_prog_c3dd61f9d9cd9f37_iter_tcp6_timewait+0x9f/0xb7
 bpf_iter_run_prog+0x538/0xde0
 bpf_iter_tcp_seq_show+0x26b/0x4b0
 bpf_seq_read+0x424/0x1210
 vfs_read+0x197/0xe40
 ksys_read+0x119/0x240
 __x64_sys_read+0x72/0xc0
 x64_sys_call+0x647/0x27e0
 do_syscall_64+0xe5/0x610
 entry_SYSCALL_64_after_hwframe+0x76/0x7e

Only check sk_protocol on full socks. tcp_abort() already knows how to deal with TIME_WAIT and NEW_SYN_RECV socks. Also fix the comment, it never matched the code.

Fixes 4ddbcb886268 ("bpf: Add bpf_sock_destroy kfunc")
---
 net/core/filter.c | 12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)
net/core/filter.c +8 -4
index 61940e753552..1bbb72138ac6 100644
@@ -12912,8 +12912,8 @@ __bpf_kfunc_start_defs();
  * @sock: Pointer to socket to be destroyed
  *
  * Return:
- * On error, may return EPROTONOSUPPORT, EINVAL.
- * EPROTONOSUPPORT if protocol specific destroy handler is not supported.
+ * On error, may return EOPNOTSUPP, EINVAL.
+ * EOPNOTSUPP if protocol specific destroy handler is not supported.
  * 0 otherwise
  */
 __bpf_kfunc int bpf_sock_destroy(struct sock_common *sock)
@@ -12925,8 +12925,12 @@ __bpf_kfunc int bpf_sock_destroy(struct sock_common *sock)
 	 * Supporting protocols will need to acquire sock lock in the BPF context
 	 * prior to invoking this kfunc.
 	 */
-	if (!sk->sk_prot->diag_destroy || (sk->sk_protocol != IPPROTO_TCP &&
-					   sk->sk_protocol != IPPROTO_UDP))
+	if (!sk->sk_prot->diag_destroy)
+		return -EOPNOTSUPP;
+
+	if (sk_fullsock(sk) &&
+	    sk->sk_protocol != IPPROTO_TCP &&
+	    sk->sk_protocol != IPPROTO_UDP)
 		return -EOPNOTSUPP;
 
 	return sk->sk_prot->diag_destroy(sk, ECONNABORTED);
Signature · 1 line
2.43.0
#1 lore raw

PATCH 2/2 selftests/bpf: Test bpf_sock_destroy() on a TIME_WAIT sock

Add a tcp_timewait subtest. The client shuts down first and the server closes after it, so the client sock ends up in TIME_WAIT. A tcp iterator then finds the timewait sock by the cookie it inherited from the client sock and destroys it. Iterate once more to make sure it is gone.

Without the previous fix bpf_sock_destroy() reads past the timewait sock and KASAN complains.

./test_progs -a sock_destroy

  #444/1   sock_destroy/tcp_client:OK
  #444/2   sock_destroy/tcp_server:OK
  #444/3   sock_destroy/tcp_timewait:OK
  #444/4   sock_destroy/udp_client:OK
  #444/5   sock_destroy/udp_server:OK
  #444/6   sock_destroy/trace_tcp_destroy_sock:OK
  #444     sock_destroy:OK

Summary: 1/6 PASSED, 0 SKIPPED, 0/0 FAILED

---
 .../selftests/bpf/prog_tests/sock_destroy.c   | 62 ++++++++++++++++++-
 .../selftests/bpf/progs/sock_destroy_prog.c   | 30 +++++++++
 2 files changed, 91 insertions(+), 1 deletion(-)
tools/testing/selftests/bpf/prog_tests/sock_destroy.c +61 -1
index 9c11938fe597..6ccc7cda410b 100644
@@ -110,6 +110,65 @@ static void test_tcp_server(struct sock_destroy_prog *skel)
 		close(serv);
 }
 
+static void test_tcp_timewait(struct sock_destroy_prog *skel)
+{
+	int serv = -1, clien = -1, accept_serv = -1, n;
+	struct timeval tv = {};
+	char buf[1];
+
+	serv = start_server(AF_INET6, SOCK_STREAM, NULL, 0, 0);
+	if (!ASSERT_GE(serv, 0, "start_server"))
+		goto cleanup;
+
+	clien = connect_to_fd(serv, 0);
+	if (!ASSERT_GE(clien, 0, "connect_to_fd"))
+		goto cleanup;
+
+	accept_serv = accept(serv, NULL, NULL);
+	if (!ASSERT_GE(accept_serv, 0, "serv accept"))
+		goto cleanup;
+
+	/* Active close from the client, then close the server side. Once
+	 * recv() sees EOF the server FIN has been processed and the client
+	 * sock is in TIME_WAIT. Block without timeout so a loaded CI box
+	 * can't race us.
+	 */
+	if (!ASSERT_OK(setsockopt(clien, SOL_SOCKET, SO_RCVTIMEO, &tv,
+				  sizeof(tv)), "clear rcvtimeo"))
+		goto cleanup;
+	if (!ASSERT_OK(shutdown(clien, SHUT_WR), "client shutdown"))
+		goto cleanup;
+
+	close(accept_serv);
+	accept_serv = -1;
+
+	/* block until return EOF */
+	n = recv(clien, buf, sizeof(buf), 0);
+	if (!ASSERT_EQ(n, 0, "client recv EOF"))
+		goto cleanup;
+
+	/* Run iterator program that destroys the timewait client sock. */
+	skel->bss->tw_found = 0;
+	start_iter_sockets(skel->progs.iter_tcp6_timewait);
+	if (!ASSERT_EQ(skel->bss->tw_found, 1, "timewait sock found"))
+		goto cleanup;
+
+	ASSERT_OK(skel->bss->tw_destroy_err, "destroy timewait sock");
+
+	/* The destroyed timewait sock must be gone. */
+	skel->bss->tw_found = 0;
+	start_iter_sockets(skel->progs.iter_tcp6_timewait);
+	ASSERT_EQ(skel->bss->tw_found, 0, "timewait sock destroyed");
+
+cleanup:
+	if (clien != -1)
+		close(clien);
+	if (accept_serv != -1)
+		close(accept_serv);
+	if (serv != -1)
+		close(serv);
+}
+
 static void test_udp_client(struct sock_destroy_prog *skel)
 {
 	int serv = -1, clien = -1, n = 0;
@@ -204,11 +263,12 @@ void test_sock_destroy(void)
 		test_tcp_client(skel);
 	if (test__start_subtest("tcp_server"))
 		test_tcp_server(skel);
+	if (test__start_subtest("tcp_timewait"))
+		test_tcp_timewait(skel);
 	if (test__start_subtest("udp_client"))
 		test_udp_client(skel);
 	if (test__start_subtest("udp_server"))
 		test_udp_server(skel);
-
 	RUN_TESTS(sock_destroy_prog_fail);
 
 cleanup:
tools/testing/selftests/bpf/progs/sock_destroy_prog.c +30 -0
index 9e0bf7a54cec..0a8887543218 100644
@@ -7,6 +7,8 @@
 #include "bpf_tracing_net.h"
 
 __be16 serv_port = 0;
+int tw_found = 0;
+int tw_destroy_err = 0;
 
 int bpf_sock_destroy(struct sock_common *sk) __ksym;
 
@@ -100,6 +102,34 @@ int iter_tcp6_server(struct bpf_iter__tcp *ctx)
 	return 0;
 }
 
+SEC("iter/tcp")
+int iter_tcp6_timewait(struct bpf_iter__tcp *ctx)
+{
+	struct sock_common *sk_common = ctx->sk_common;
+	__u64 *val;
+	int key = 0;
+
+	if (!sk_common)
+		return 0;
+
+	if (sk_common->skc_family != AF_INET6)
+		return 0;
+
+	if (!bpf_skc_to_tcp_timewait_sock(sk_common))
+		return 0;
+
+	val = bpf_map_lookup_elem(&tcp_conn_sockets, &key);
+	if (!val)
+		return 0;
+	/* The timewait sock inherits the cookie of the closed client sock. */
+	if (bpf_get_socket_cookie(sk_common) != *val)
+		return 0;
+
+	tw_found++;
+	tw_destroy_err = bpf_sock_destroy(sk_common);
+
+	return 0;
+}
 
 SEC("iter/udp")
 int iter_udp6_client(struct bpf_iter__udp *ctx)
Signature · 1 line
2.43.0
#2 lore raw

Re: [PATCH bpf 2/2] selftests/bpf: Test bpf_sock_destroy() on a TIME_WAIT sock

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] The test creates a simultaneous close race condition that will cause it to randomly fail by…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] The test creates a simultaneous close race condition that will cause it to randomly fail by observing the socket in TCP_CLOSING state instead of TCP_TIME_WAIT.
- [Low] The multi-line comment uses the incorrect style for the BPF subsystem.
--

commit c91152edb079a3ce44e0f45e8d080efb432c5870

Author: Jiayuan Chen <[email protected]>
Date:   Thu Sep 3 12:52:49 2026 +0000

selftests/bpf: Test bpf_sock_destroy() on a TIME_WAIT sock

This commit adds a tcp_timewait subtest to verify that bpf_sock_destroy() correctly handles TIME_WAIT sockets. A tcp iterator finds the timewait socket by its inherited cookie and destroys it.

Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/sock_destroy.c +0 -0
index 9c11938fe597d..6ccc7cda410bf 100644

[ ... ]

Quoted 1 line
tools/testing/selftests/bpf/prog_tests/sock_destroy.c +0 -0
@@ -110,6 +110,65 @@ static void test_tcp_server(struct sock_destroy_prog *skel)

[ ... ]

tools/testing/selftests/bpf/prog_tests/sock_destroy.c static void test_tcp_server(struct sock_destroy_prog *skel) · line 135

Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/sock_destroy.c +5 -0
+	/* Active close from the client, then close the server side. Once
+	 * recv() sees EOF the server FIN has been processed and the client
+	 * sock is in TIME_WAIT. Block without timeout so a loaded CI box
+	 * can't race us.
+	 */

[Severity: Low]
Does this multi-line comment follow the BPF subsystem coding style? The guidelines prefer placing the opening /* on its own line before starting the comment text.

tools/testing/selftests/bpf/prog_tests/sock_destroy.c static void test_tcp_server(struct sock_destroy_prog *skel) · line 146

Quoted 11 lines
tools/testing/selftests/bpf/prog_tests/sock_destroy.c +11 -0
+	if (!ASSERT_OK(setsockopt(clien, SOL_SOCKET, SO_RCVTIMEO, &tv,
+				  sizeof(tv)), "clear rcvtimeo"))
+		goto cleanup;
+	if (!ASSERT_OK(shutdown(clien, SHUT_WR), "client shutdown"))
+		goto cleanup;
+
+	close(accept_serv);
+	accept_serv = -1;
+
+	/* block until return EOF */
+	n = recv(clien, buf, sizeof(buf), 0);

[Severity: Medium]
Could this sequence create a simultaneous close race condition that leads to random test failures?

If shutdown(clien, SHUT_WR) sends a FIN, and the test immediately calls close(accept_serv) on the server without waiting for the client's FIN to be processed, the server might send its FIN before receiving the client's FIN.

If these FINs cross (simultaneous close), the client will receive the server's FIN, enter the TCP_CLOSING state, and wake up the blocking recv() call. The subsequent BPF iterator would then run while the socket is still in TCP_CLOSING rather than TCP_TIME_WAIT.

Because the socket is in TCP_CLOSING, bpf_skc_to_tcp_timewait_sock() will return NULL, causing the iterator to miss the socket and the assertion ASSERT_EQ(skel->bss->tw_found, 1) to fail.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#3 lore raw

Re: [PATCH bpf 2/2] selftests/bpf: Test bpf_sock_destroy() on a TIME_WAIT sock

Quoted 51 lines · 在 9/3/26 9:07 PM, [email protected] 写道:

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] The test creates a simultaneous close race condition that will cause it to randomly fail by observing the socket in TCP_CLOSING state instead of TCP_TIME_WAIT.
- [Low] The multi-line comment uses the incorrect style for the BPF subsystem.
--

commit c91152edb079a3ce44e0f45e8d080efb432c5870

Author: Jiayuan Chen <[email protected]>
Date:   Thu Sep 3 12:52:49 2026 +0000

selftests/bpf: Test bpf_sock_destroy() on a TIME_WAIT sock

This commit adds a tcp_timewait subtest to verify that bpf_sock_destroy() correctly handles TIME_WAIT sockets. A tcp iterator finds the timewait socket by its inherited cookie and destroys it.

Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/sock_destroy.c +0 -0
index 9c11938fe597d..6ccc7cda410bf 100644

[ ... ]

Quoted 1 line
tools/testing/selftests/bpf/prog_tests/sock_destroy.c +0 -0
@@ -110,6 +110,65 @@ static void test_tcp_server(struct sock_destroy_prog *skel)

[ ... ]

tools/testing/selftests/bpf/prog_tests/sock_destroy.c static void test_tcp_server(struct sock_destroy_prog *skel) · line 135

Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/sock_destroy.c +5 -0
+	/* Active close from the client, then close the server side. Once
+	 * recv() sees EOF the server FIN has been processed and the client
+	 * sock is in TIME_WAIT. Block without timeout so a loaded CI box
+	 * can't race us.
+	 */

[Severity: Low]
Does this multi-line comment follow the BPF subsystem coding style? The guidelines prefer placing the opening /* on its own line before starting the comment text.

tools/testing/selftests/bpf/prog_tests/sock_destroy.c static void test_tcp_server(struct sock_destroy_prog *skel) · line 146

Quoted 11 lines
tools/testing/selftests/bpf/prog_tests/sock_destroy.c +11 -0
+	if (!ASSERT_OK(setsockopt(clien, SOL_SOCKET, SO_RCVTIMEO, &tv,
+				  sizeof(tv)), "clear rcvtimeo"))
+		goto cleanup;
+	if (!ASSERT_OK(shutdown(clien, SHUT_WR), "client shutdown"))
+		goto cleanup;
+
+	close(accept_serv);
+	accept_serv = -1;
+
+	/* block until return EOF */
+	n = recv(clien, buf, sizeof(buf), 0);

[Severity: Medium]
Could this sequence create a simultaneous close race condition that leads to random test failures?

If shutdown(clien, SHUT_WR) sends a FIN, and the test immediately calls close(accept_serv) on the server without waiting for the client's FIN to be processed, the server might send its FIN before receiving the client's FIN.

Quoted 8 lines

If these FINs cross (simultaneous close), the client will receive the server's FIN, enter the TCP_CLOSING state, and wake up the blocking recv() call. The subsequent BPF iterator would then run while the socket is still in TCP_CLOSING rather than TCP_TIME_WAIT.

Because the socket is in TCP_CLOSING, bpf_skc_to_tcp_timewait_sock() will return NULL, causing the iterator to miss the socket and the assertion ASSERT_EQ(skel->bss->tw_found, 1) to fail.

Right, I think I can just recv(accept_serv) to make sure client's FIN

has been processed by server before closing it, so the two FINs won't cross

#4 lore raw
In reply to Jiayuan Chen
The EPROTONOSUPPORT -> EOPNOTSUPP correction is right, but the rewritten error list is incomplete. tcp_abort() returns -ENOENT when the socket is already closed (net/ipv4/tcp.c, around the sk_state…

net/core/filter.c __bpf_kfunc_start_defs(); · line 12917

Quoted 13 lines
net/core/filter.c +2 -2
index 61940e7535523..1bbb72138ac64 100644
@@ -12912,8 +12912,8 @@ __bpf_kfunc_start_defs();
  * @sock: Pointer to socket to be destroyed
  *
  * Return:
- * On error, may return EPROTONOSUPPORT, EINVAL.
- * EPROTONOSUPPORT if protocol specific destroy handler is not supported.
+ * On error, may return EOPNOTSUPP, EINVAL.
+ * EOPNOTSUPP if protocol specific destroy handler is not supported.
  * 0 otherwise

The EPROTONOSUPPORT -> EOPNOTSUPP correction is right, but the rewritten error list is incomplete. tcp_abort() returns -ENOENT when the socket is already closed (net/ipv4/tcp.c, around the sk_state == TCP_CLOSE check):

    /* Avoid closing the same socket twice. */
    if (sk->sk_state == TCP_CLOSE) {
        if (!has_current_bpf_ctx())
            release_sock(sk);
        return -ENOENT;
    }

That error propagates through sk->sk_prot->diag_destroy(sk, ECONNABORTED) and is reachable from a BPF iterator (destroying a sock the iterator already destroyed, or one closed concurrently). In contrast, EINVAL is only reachable through the narrower tcp_abort_override() path for MPTCP listener subflows.

Should ENOENT be added to the list?

Quoted 5 lines
net/core/filter.c +0 -1
@@ -12925,8 +12925,12 @@ __bpf_kfunc int bpf_sock_destroy(struct sock_common *sock)
 	 * Supporting protocols will need to acquire sock lock in the BPF context
 	 * prior to invoking this kfunc.
 	 */
-	if (!sk->sk_prot->diag_destroy || (sk->sk_protocol != IPPROTO_TCP &&

net/core/filter.c __bpf_kfunc int bpf_sock_destroy(struct sock_common *sock) · line 12936

Quoted 10 lines
net/core/filter.c +6 -1
-					   sk->sk_protocol != IPPROTO_UDP))
+	if (!sk->sk_prot->diag_destroy)
+		return -EOPNOTSUPP;
+
+	if (sk_fullsock(sk) &&
+	    sk->sk_protocol != IPPROTO_TCP &&
+	    sk->sk_protocol != IPPROTO_UDP)
 		return -EOPNOTSUPP;
 
 	return sk->sk_prot->diag_destroy(sk, ECONNABORTED);

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/33760037892

#5 lore raw
Quoted 24 lines · on 9/3/26 10:01 PM, [email protected] wrote:

net/core/filter.c __bpf_kfunc_start_defs(); · line 12917

Quoted 13 lines
net/core/filter.c +2 -2
index 61940e7535523..1bbb72138ac64 100644
@@ -12912,8 +12912,8 @@ __bpf_kfunc_start_defs();
   * @sock: Pointer to socket to be destroyed
   *
   * Return:
- * On error, may return EPROTONOSUPPORT, EINVAL.
- * EPROTONOSUPPORT if protocol specific destroy handler is not supported.
+ * On error, may return EOPNOTSUPP, EINVAL.
+ * EOPNOTSUPP if protocol specific destroy handler is not supported.
   * 0 otherwise

The EPROTONOSUPPORT -> EOPNOTSUPP correction is right, but the rewritten error list is incomplete. tcp_abort() returns -ENOENT when the socket is already closed (net/ipv4/tcp.c, around the sk_state == TCP_CLOSE check):

     /* Avoid closing the same socket twice. */
     if (sk->sk_state == TCP_CLOSE) {
         if (!has_current_bpf_ctx())
             release_sock(sk);
         return -ENOENT;
     }
Quoted 7 lines

That error propagates through sk->sk_prot->diag_destroy(sk, ECONNABORTED) and is reachable from a BPF iterator (destroying a sock the iterator already destroyed, or one closed concurrently). In contrast, EINVAL is only reachable through the narrower tcp_abort_override() path for MPTCP listener subflows.

Should ENOENT be added to the list?

I'd like to describe it as "others" since diag_destroy may change it's return value.