Skip to contentSkip to conversation

bpf, sockmap: Fix af_unix null-ptr-deref in proto update

PATCH Applied Michal Luczaj 4 participants 12 messages Apr 14 – Apr 16

Subsystems (8)
lore
Share & tools
lore
#0 lore raw

v4 cover bpf, sockmap: Fix af_unix null-ptr-deref in proto update

Updating sockmap/sockhash using a unix sock races unix_stream_connect():
when sock_map_sk_state_allowed() passes (sk_state == TCP_ESTABLISHED), unix_peer(sk) in unix_stream_bpf_update_proto() may still return NULL.

---
Changes in v4:
- Circle back to v1 approach
- More details in commit messages [Martin]
- Make unix iter take the state lock [Kaniyuki]
- Link to v3: https://lore.kernel.org/r/20260306-unix-proto-update-null-ptr-deref-v3-0-2f0c7410c523@rbox.co

Changes in v3:
- Drop sparse annotations [Martin]
- Keep lock_sock() along the unix_state_lock() [Kaniyuki]
- Unify BPF iter af_unix locking [Kaniyuki, Martin]
- Link to v2: https://lore.kernel.org/r/20260207-unix-proto-update-null-ptr-deref-v2-0-9f091330e7cd@rbox.co

Changes in v2:
- Instead of probing for unix peer, make sockmap take the right lock [Martin]
- Annotate data races [Kaniyuki, Martin]
- Extend bpf unix iter selftest to attempt a deadlock
- Link to v1: https://lore.kernel.org/r/20260129-unix-proto-update-null-ptr-deref-v1-1-e1daeb7012fd@rbox.co

To: John Fastabend <[email protected]>
To: Jakub Sitnicki <[email protected]>
To: Eric Dumazet <[email protected]>
To: Kuniyuki Iwashima <[email protected]>
To: Paolo Abeni <[email protected]>
To: Willem de Bruijn <[email protected]>
To: "David S. Miller" <[email protected]>
To: Jakub Kicinski <[email protected]>
To: Simon Horman <[email protected]>
To: Yonghong Song <[email protected]>
To: Andrii Nakryiko <[email protected]>
To: Eduard Zingerman <[email protected]>
To: Alexei Starovoitov <[email protected]>
To: Daniel Borkmann <[email protected]>
To: Martin KaFai Lau <[email protected]>
To: Song Liu <[email protected]>
To: Yonghong Song <[email protected]>
To: KP Singh <[email protected]>
To: Stanislav Fomichev <[email protected]>
To: Hao Luo <[email protected]>
To: Jiri Olsa <[email protected]>
To: Shuah Khan <[email protected]>
To: Cong Wang <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]

---
Michal Luczaj (5):
bpf, sockmap: Annotate af_unix sock::sk_state data-races bpf, sockmap: Fix af_unix iter deadlock selftests/bpf: Extend bpf_iter_unix to attempt deadlocking bpf, sockmap: Fix af_unix null-ptr-deref in proto update bpf, sockmap: Take state lock for af_unix iter

 net/core/sock_map.c                               |  4 ++--
 net/unix/af_unix.c                                |  9 +++++----
 net/unix/unix_bpf.c                               |  3 +++
 tools/testing/selftests/bpf/progs/bpf_iter_unix.c | 10 ++++++++++
 4 files changed, 20 insertions(+), 6 deletions(-)

---
base-commit: 0f00132132937ca01a99feaf8985109a9087c9ff
change-id: 20260129-unix-proto-update-null-ptr-deref-6a2733bcbbf8

Best regards,

Signature · 1 line
Michal Luczaj <[email protected]>
#1 lore raw

PATCH v4 1/5 bpf, sockmap: Annotate af_unix sock::sk_state data-races

sock_map_sk_state_allowed() and sock_map_redirect_allowed() read af_unix socket sk_state locklessly.

Use READ_ONCE(). Note that for sock_map_redirect_allowed() change affects not only af_unix, but all non-TCP sockets (UDP, af_vsock).

---
 net/core/sock_map.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
net/core/sock_map.c +2 -2
index b0e96337a269..02a68be3002a 100644
@@ -530,7 +530,7 @@ static bool sock_map_redirect_allowed(const struct sock *sk)
 	if (sk_is_tcp(sk))
 		return sk->sk_state != TCP_LISTEN;
 	else
-		return sk->sk_state == TCP_ESTABLISHED;
+		return READ_ONCE(sk->sk_state) == TCP_ESTABLISHED;
 }
 
 static bool sock_map_sk_is_suitable(const struct sock *sk)
@@ -543,7 +543,7 @@ static bool sock_map_sk_state_allowed(const struct sock *sk)
 	if (sk_is_tcp(sk))
 		return (1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_LISTEN);
 	if (sk_is_stream_unix(sk))
-		return (1 << sk->sk_state) & TCPF_ESTABLISHED;
+		return (1 << READ_ONCE(sk->sk_state)) & TCPF_ESTABLISHED;
 	if (sk_is_vsock(sk) &&
 	    (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET))
 		return (1 << sk->sk_state) & TCPF_ESTABLISHED;
Signature · 1 line
2.53.0
#2 lore raw

PATCH v4 2/5 bpf, sockmap: Fix af_unix iter deadlock

In reply to Michal Luczaj

bpf_iter_unix_seq_show() may deadlock when lock_sock_fast() takes the fast path and the iter prog attempts to update a sockmap. Which ends up spinning at sock_map_update_elem()'s bh_lock_sock():

WARNING: possible recursive locking detected
test_progs/1393 is trying to acquire lock:
ffff88811ec25f58 (slock-AF_UNIX){+...}-{3:3}, at: sock_map_update_elem+0xdb/0x1f0

but task is already holding lock:
ffff88811ec25f58 (slock-AF_UNIX){+...}-{3:3}, at: __lock_sock_fast+0x37/0xe0

other info that might help us debug this:

 Possible unsafe locking scenario:
       CPU0
       ----

lock(slock-AF_UNIX);
lock(slock-AF_UNIX);

*** DEADLOCK ***

May be due to missing lock nesting notation

4 locks held by test_progs/1393:
#0: ffff88814b59c790 (&p->lock){+.+.}-{4:4}, at: bpf_seq_read+0x59/0x10d0 #1: ffff88811ec25fd8 (sk_lock-AF_UNIX){+.+.}-{0:0}, at: bpf_seq_read+0x42c/0x10d0 #2: ffff88811ec25f58 (slock-AF_UNIX){+...}-{3:3}, at: __lock_sock_fast+0x37/0xe0 #3: ffffffff85a6a7c0 (rcu_read_lock){....}-{1:3}, at: bpf_iter_run_prog+0x51d/0xb00

Call Trace:
 dump_stack_lvl+0x5d/0x80
 print_deadlock_bug.cold+0xc0/0xce
 __lock_acquire+0x130f/0x2590
 lock_acquire+0x14e/0x2b0
 _raw_spin_lock+0x30/0x40
 sock_map_update_elem+0xdb/0x1f0
 bpf_prog_2d0075e5d9b721cd_dump_unix+0x55/0x4f4
 bpf_iter_run_prog+0x5b9/0xb00
 bpf_iter_unix_seq_show+0x1f7/0x2e0
 bpf_seq_read+0x42c/0x10d0
 vfs_read+0x171/0xb20
 ksys_read+0xff/0x200
 do_syscall_64+0x6b/0x3a0
 entry_SYSCALL_64_after_hwframe+0x76/0x7e
Fixes 2c860a43dd77 ("bpf: af_unix: Implement BPF iterator for UNIX domain socket.")
---
 net/unix/af_unix.c | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)
net/unix/af_unix.c +3 -4
index b23c33df8b46..590a30d3b2f7 100644
@@ -3731,15 +3731,14 @@ static int bpf_iter_unix_seq_show(struct seq_file *seq, void *v)
 	struct bpf_prog *prog;
 	struct sock *sk = v;
 	uid_t uid;
-	bool slow;
 	int ret;
 
 	if (v == SEQ_START_TOKEN)
 		return 0;
 
-	slow = lock_sock_fast(sk);
+	lock_sock(sk);
 
-	if (unlikely(sk_unhashed(sk))) {
+	if (unlikely(sock_flag(sk, SOCK_DEAD))) {
 		ret = SEQ_SKIP;
 		goto unlock;
 	}
@@ -3749,7 +3748,7 @@ static int bpf_iter_unix_seq_show(struct seq_file *seq, void *v)
 	prog = bpf_iter_get_info(&meta, false);
 	ret = unix_prog_seq_show(prog, &meta, v, uid);
 unlock:
-	unlock_sock_fast(sk, slow);
+	release_sock(sk);
 	return ret;
 }
 
Signature · 1 line
2.53.0
#3 lore raw

PATCH v4 3/5 selftests/bpf: Extend bpf_iter_unix to attempt deadlocking

In reply to Michal Luczaj

Updating a sockmap from a unix iterator prog may lead to a deadlock. Piggyback on the original selftest.

---
 tools/testing/selftests/bpf/progs/bpf_iter_unix.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
tools/testing/selftests/bpf/progs/bpf_iter_unix.c +10 -0
index fea275df9e22..a2652c8c3616 100644
@@ -7,6 +7,13 @@
 
 char _license[] SEC("license") = "GPL";
 
+SEC(".maps") struct {
+	__uint(type, BPF_MAP_TYPE_SOCKMAP);
+	__uint(max_entries, 1);
+	__type(key, __u32);
+	__type(value, __u64);
+} sockmap;
+
 static long sock_i_ino(const struct sock *sk)
 {
 	const struct socket *sk_socket = sk->sk_socket;
@@ -76,5 +83,8 @@ int dump_unix(struct bpf_iter__unix *ctx)
 
 	BPF_SEQ_PRINTF(seq, "\n");
 
+	/* Test for deadlock. */
+	bpf_map_update_elem(&sockmap, &(int){0}, sk, 0);
+
 	return 0;
 }
Signature · 1 line
2.53.0
#5 lore raw

PATCH v4 4/5 bpf, sockmap: Fix af_unix null-ptr-deref in proto update

In reply to Michal Luczaj

unix_stream_connect() sets sk_state (WRITE_ONCE(sk->sk_state, TCP_ESTABLISHED)) _before_ it assigns a peer (unix_peer(sk) = newsk). sk_state == TCP_ESTABLISHED makes sock_map_sk_state_allowed() believe that socket is properly set up, which would include having a defined peer. IOW, there's a window when unix_stream_bpf_update_proto() can be called on socket which still has unix_peer(sk) == NULL.

         CPU0 bpf                            CPU1 connect
         --------                            ------------

                                WRITE_ONCE(sk->sk_state, TCP_ESTABLISHED)

sock_map_sk_state_allowed(sk)
...
sk_pair = unix_peer(sk)
sock_hold(sk_pair)
sock_hold(newsk) smp_mb__after_atomic() unix_peer(sk) = newsk

BUG: kernel NULL pointer dereference, address: 0000000000000080
RIP: 0010:unix_stream_bpf_update_proto+0xa0/0x1b0
Call Trace:
  sock_map_link+0x564/0x8b0
  sock_map_update_common+0x6e/0x340
  sock_map_update_elem_sys+0x17d/0x240
  __sys_bpf+0x26db/0x3250
  __x64_sys_bpf+0x21/0x30
  do_syscall_64+0x6b/0x3a0
  entry_SYSCALL_64_after_hwframe+0x76/0x7e

Initial idea was to move peer assignment _before_ the sk_state update[1], but that involved an additional memory barrier, and changing the hot path was rejected.
Then a NULL check during proto update in unix_stream_bpf_update_proto() was considered[2], but the follow-up discussion[3] focused on the root cause, i.e. sockmap update taking a wrong lock. Or, more specifically, missing unix_state_lock()[4].
In the end it was concluded that teaching sockmap about the af_unix locking would be unnecessarily complex[5].
Complexity aside, since BPF_PROG_TYPE_SCHED_CLS and BPF_PROG_TYPE_SCHED_ACT are allowed to update sockmaps, sock_map_update_elem() taking the unix lock, as it is currently implemented in unix_state_lock():
spin_lock(&unix_sk(s)->lock), would be problematic. unix_state_lock() taken in a process context, followed by a softirq-context TC BPF program attempting to take the same spinlock -- deadlock[6].
This way we circled back to the peer check idea[2].

[1]: https://lore.kernel.org/netdev/[email protected]/
[2]: https://lore.kernel.org/netdev/[email protected]/
[3]: https://lore.kernel.org/netdev/[email protected]/
[4]: https://lore.kernel.org/netdev/CAAVpQUA+8GL_j63CaKb8hbxoL21izD58yr1NvhOhU=j+35+3og@mail.gmail.com/
[5]: https://lore.kernel.org/bpf/CAAVpQUAHijOMext28Gi10dSLuMzGYh+jK61Ujn+fZ-wvcODR2A@mail.gmail.com/
[6]: https://lore.kernel.org/bpf/[email protected]/

Summary of scenarios where af_unix/stream connect() may race a sockmap update:

1. connect() vs. bpf(BPF_MAP_UPDATE_ELEM), i.e. sock_map_update_elem_sys()

Implemented NULL check is sufficient. Once assigned, socket peer won't be released until socket fd is released. And that's not an issue because sock_map_update_elem_sys() bumps fd refcnf.

2. connect() vs BPF program doing update

Update restricted per verifier.c:may_update_sockmap() to

BPF_PROG_TYPE_TRACING/BPF_TRACE_ITER BPF_PROG_TYPE_SOCK_OPS (bpf_sock_map_update() only) BPF_PROG_TYPE_SOCKET_FILTER BPF_PROG_TYPE_SCHED_CLS BPF_PROG_TYPE_SCHED_ACT
BPF_PROG_TYPE_XDP BPF_PROG_TYPE_SK_REUSEPORT BPF_PROG_TYPE_FLOW_DISSECTOR BPF_PROG_TYPE_SK_LOOKUP

Plus one more race to consider:

            CPU0 bpf                            CPU1 connect
            --------                            ------------

                                   WRITE_ONCE(sk->sk_state, TCP_ESTABLISHED)
   sock_map_sk_state_allowed(sk)
                                   sock_hold(newsk)
                                   smp_mb__after_atomic()
                                   unix_peer(sk) = newsk
   sk_pair = unix_peer(sk)
   if (unlikely(!sk_pair))
      return -EINVAL;

                                                 CPU1 close
                                                 ----------

                                   skpair = unix_peer(sk);
                                   unix_peer(sk) = NULL;
                                   sock_put(skpair)

// use after free?
sock_hold(sk_pair)

2.1 BPF program invoking helper function bpf_sock_map_update() ->
BPF_CALL_4(bpf_sock_map_update(), ...)

Helper limited to BPF_PROG_TYPE_SOCK_OPS. Nevertheless, a unix sock might be accessible via bpf_map_lookup_elem(). Which implies sk already having psock, which in turn implies sk already having sk_pair. Since sk_psock_destroy() is queued as RCU work, sk_pair won't go away while BPF executes the update.

2.2 BPF program invoking helper function bpf_map_update_elem() ->

       sock_map_update_elem()

       2.2.1 Unix sock accessible to BPF prog only via sockmap lookup in
             BPF_PROG_TYPE_SOCKET_FILTER, BPF_PROG_TYPE_SCHED_CLS,
             BPF_PROG_TYPE_SCHED_ACT, BPF_PROG_TYPE_XDP,
             BPF_PROG_TYPE_SK_REUSEPORT, BPF_PROG_TYPE_FLOW_DISSECTOR,
             BPF_PROG_TYPE_SK_LOOKUP.

             Pretty much the same as case 2.1.

       2.2.2 Unix sock accessible to BPF program directly:
             BPF_PROG_TYPE_TRACING, narrowed down to BPF_TRACE_ITER.

             Sockmap iterator (sock_map_seq_ops) is safe: unix sock
             residing in a sockmap means that the sock already went through
             the proto update step.

             Unix sock iterator (bpf_iter_unix_seq_ops), on the other hand,
             gives access to socks that may still be unconnected. Which
             means iterator prog can race sockmap/proto update against
             connect().

             BUG: KASAN: null-ptr-deref in unix_stream_bpf_update_proto+0x253/0x4d0
             Write of size 4 at addr 0000000000000080 by task test_progs/3140
             Call Trace:
              dump_stack_lvl+0x5d/0x80
              kasan_report+0xe4/0x1c0
              kasan_check_range+0x125/0x200
              unix_stream_bpf_update_proto+0x253/0x4d0
              sock_map_link+0x71c/0xec0
              sock_map_update_common+0xbc/0x600
              sock_map_update_elem+0x19a/0x1f0
              bpf_prog_bbbf56096cdd4f01_selective_dump_unix+0x20c/0x217
              bpf_iter_run_prog+0x21e/0xae0
              bpf_iter_unix_seq_show+0x1e0/0x2a0
              bpf_seq_read+0x42c/0x10d0
              vfs_read+0x171/0xb20
              ksys_read+0xff/0x200
              do_syscall_64+0xf7/0x5e0
              entry_SYSCALL_64_after_hwframe+0x76/0x7e

             While the introduced NULL check prevents null-ptr-deref in the
             BPF program path as well, it is insufficient to guard against
             a poorly timed close() leading to a use-after-free. This will
             be addressed in a subsequent patch.
---
 net/unix/unix_bpf.c | 3 +++
 1 file changed, 3 insertions(+)
net/unix/unix_bpf.c +3 -0
index e0d30d6d22ac..57f3124c9d8d 100644
@@ -185,6 +185,9 @@ int unix_stream_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool r
 	 */
 	if (!psock->sk_pair) {
 		sk_pair = unix_peer(sk);
+		if (unlikely(!sk_pair))
+			return -EINVAL;
+
 		sock_hold(sk_pair);
 		psock->sk_pair = sk_pair;
 	}
Signature · 1 line
2.53.0
maintainer Reviewed-by on v4 4/5
#6 lore raw
Quoted 157 lines · Michal Luczaj

unix_stream_connect() sets sk_state (WRITE_ONCE(sk->sk_state, TCP_ESTABLISHED)) _before_ it assigns a peer (unix_peer(sk) = newsk). sk_state == TCP_ESTABLISHED makes sock_map_sk_state_allowed() believe that socket is properly set up, which would include having a defined peer. IOW, there's a window when unix_stream_bpf_update_proto() can be called on socket which still has unix_peer(sk) == NULL.

         CPU0 bpf                            CPU1 connect
         --------                            ------------

                                WRITE_ONCE(sk->sk_state, TCP_ESTABLISHED)

sock_map_sk_state_allowed(sk)
...
sk_pair = unix_peer(sk)
sock_hold(sk_pair)
sock_hold(newsk) smp_mb__after_atomic() unix_peer(sk) = newsk

BUG: kernel NULL pointer dereference, address: 0000000000000080
RIP: 0010:unix_stream_bpf_update_proto+0xa0/0x1b0
Call Trace:
  sock_map_link+0x564/0x8b0
  sock_map_update_common+0x6e/0x340
  sock_map_update_elem_sys+0x17d/0x240
  __sys_bpf+0x26db/0x3250
  __x64_sys_bpf+0x21/0x30
  do_syscall_64+0x6b/0x3a0
  entry_SYSCALL_64_after_hwframe+0x76/0x7e

Initial idea was to move peer assignment _before_ the sk_state update[1], but that involved an additional memory barrier, and changing the hot path was rejected.
Then a NULL check during proto update in unix_stream_bpf_update_proto() was considered[2], but the follow-up discussion[3] focused on the root cause, i.e. sockmap update taking a wrong lock. Or, more specifically, missing unix_state_lock()[4].
In the end it was concluded that teaching sockmap about the af_unix locking would be unnecessarily complex[5].
Complexity aside, since BPF_PROG_TYPE_SCHED_CLS and BPF_PROG_TYPE_SCHED_ACT are allowed to update sockmaps, sock_map_update_elem() taking the unix lock, as it is currently implemented in unix_state_lock():
spin_lock(&unix_sk(s)->lock), would be problematic. unix_state_lock() taken in a process context, followed by a softirq-context TC BPF program attempting to take the same spinlock -- deadlock[6].
This way we circled back to the peer check idea[2].

[1]: https://lore.kernel.org/netdev/[email protected]/
[2]: https://lore.kernel.org/netdev/[email protected]/
[3]: https://lore.kernel.org/netdev/[email protected]/
[4]: https://lore.kernel.org/netdev/CAAVpQUA+8GL_j63CaKb8hbxoL21izD58yr1NvhOhU=j+35+3og@mail.gmail.com/
[5]: https://lore.kernel.org/bpf/CAAVpQUAHijOMext28Gi10dSLuMzGYh+jK61Ujn+fZ-wvcODR2A@mail.gmail.com/
[6]: https://lore.kernel.org/bpf/[email protected]/

Summary of scenarios where af_unix/stream connect() may race a sockmap update:

1. connect() vs. bpf(BPF_MAP_UPDATE_ELEM), i.e. sock_map_update_elem_sys()

Implemented NULL check is sufficient. Once assigned, socket peer won't be released until socket fd is released. And that's not an issue because sock_map_update_elem_sys() bumps fd refcnf.

2. connect() vs BPF program doing update

Update restricted per verifier.c:may_update_sockmap() to

BPF_PROG_TYPE_TRACING/BPF_TRACE_ITER BPF_PROG_TYPE_SOCK_OPS (bpf_sock_map_update() only) BPF_PROG_TYPE_SOCKET_FILTER BPF_PROG_TYPE_SCHED_CLS BPF_PROG_TYPE_SCHED_ACT
BPF_PROG_TYPE_XDP BPF_PROG_TYPE_SK_REUSEPORT BPF_PROG_TYPE_FLOW_DISSECTOR BPF_PROG_TYPE_SK_LOOKUP

   Plus one more race to consider:

            CPU0 bpf                            CPU1 connect
            --------                            ------------

                                   WRITE_ONCE(sk->sk_state, TCP_ESTABLISHED)
   sock_map_sk_state_allowed(sk)
                                   sock_hold(newsk)
                                   smp_mb__after_atomic()
                                   unix_peer(sk) = newsk
   sk_pair = unix_peer(sk)
   if (unlikely(!sk_pair))
      return -EINVAL;

                                                 CPU1 close
                                                 ----------

                                   skpair = unix_peer(sk);
                                   unix_peer(sk) = NULL;
                                   sock_put(skpair)
   // use after free?
   sock_hold(sk_pair)

   2.1 BPF program invoking helper function bpf_sock_map_update() ->
       BPF_CALL_4(bpf_sock_map_update(), ...)

       Helper limited to BPF_PROG_TYPE_SOCK_OPS. Nevertheless, a unix sock
       might be accessible via bpf_map_lookup_elem(). Which implies sk
       already having psock, which in turn implies sk already having
       sk_pair. Since sk_psock_destroy() is queued as RCU work, sk_pair
       won't go away while BPF executes the update.

   2.2 BPF program invoking helper function bpf_map_update_elem() ->
       sock_map_update_elem()

       2.2.1 Unix sock accessible to BPF prog only via sockmap lookup in
             BPF_PROG_TYPE_SOCKET_FILTER, BPF_PROG_TYPE_SCHED_CLS,
             BPF_PROG_TYPE_SCHED_ACT, BPF_PROG_TYPE_XDP,
             BPF_PROG_TYPE_SK_REUSEPORT, BPF_PROG_TYPE_FLOW_DISSECTOR,
             BPF_PROG_TYPE_SK_LOOKUP.

             Pretty much the same as case 2.1.

       2.2.2 Unix sock accessible to BPF program directly:
             BPF_PROG_TYPE_TRACING, narrowed down to BPF_TRACE_ITER.

             Sockmap iterator (sock_map_seq_ops) is safe: unix sock
             residing in a sockmap means that the sock already went through
             the proto update step.

             Unix sock iterator (bpf_iter_unix_seq_ops), on the other hand,
             gives access to socks that may still be unconnected. Which
             means iterator prog can race sockmap/proto update against
             connect().

             BUG: KASAN: null-ptr-deref in unix_stream_bpf_update_proto+0x253/0x4d0
             Write of size 4 at addr 0000000000000080 by task test_progs/3140
             Call Trace:
              dump_stack_lvl+0x5d/0x80
              kasan_report+0xe4/0x1c0
              kasan_check_range+0x125/0x200
              unix_stream_bpf_update_proto+0x253/0x4d0
              sock_map_link+0x71c/0xec0
              sock_map_update_common+0xbc/0x600
              sock_map_update_elem+0x19a/0x1f0
              bpf_prog_bbbf56096cdd4f01_selective_dump_unix+0x20c/0x217
              bpf_iter_run_prog+0x21e/0xae0
              bpf_iter_unix_seq_show+0x1e0/0x2a0
              bpf_seq_read+0x42c/0x10d0
              vfs_read+0x171/0xb20
              ksys_read+0xff/0x200
              do_syscall_64+0xf7/0x5e0
              entry_SYSCALL_64_after_hwframe+0x76/0x7e

             While the introduced NULL check prevents null-ptr-deref in the
             BPF program path as well, it is insufficient to guard against
             a poorly timed close() leading to a use-after-free. This will
             be addressed in a subsequent patch.
Quoted 7 lines
#7 lore raw

PATCH v4 5/5 bpf, sockmap: Take state lock for af_unix iter

In reply to Michal Luczaj

When a BPF iterator program updates a sockmap, there is a race condition in unix_stream_bpf_update_proto() where the peer pointer can become stale[1] during a state transition TCP_ESTABLISHED -> TCP_CLOSE.

CPU0 bpf CPU1 close
-------- ----------
// unix_stream_bpf_update_proto()
sk_pair = unix_peer(sk)
if (unlikely(!sk_pair))

   return -EINVAL;
                                     // unix_release_sock()
                                     skpair = unix_peer(sk);
                                     unix_peer(sk) = NULL;
                                     sock_put(skpair)

sock_hold(sk_pair) // UaF

More practically, this fix guarantees that the iterator program is consistently provided with a unix socket that remains stable during iterator execution.

[1]:

BUG: KASAN: slab-use-after-free in unix_stream_bpf_update_proto+0x155/0x490
Write of size 4 at addr ffff8881178c9a00 by task test_progs/2231
Call Trace:
 dump_stack_lvl+0x5d/0x80
 print_report+0x170/0x4f3
 kasan_report+0xe4/0x1c0
 kasan_check_range+0x125/0x200
 unix_stream_bpf_update_proto+0x155/0x490
 sock_map_link+0x71c/0xec0
 sock_map_update_common+0xbc/0x600
 sock_map_update_elem+0x19a/0x1f0
 bpf_prog_bbbf56096cdd4f01_selective_dump_unix+0x20c/0x217
 bpf_iter_run_prog+0x21e/0xae0
 bpf_iter_unix_seq_show+0x1e0/0x2a0
 bpf_seq_read+0x42c/0x10d0
 vfs_read+0x171/0xb20
 ksys_read+0xff/0x200
 do_syscall_64+0xf7/0x5e0
 entry_SYSCALL_64_after_hwframe+0x76/0x7e

Allocated by task 2236:
 kasan_save_stack+0x30/0x50
 kasan_save_track+0x14/0x30
 __kasan_slab_alloc+0x63/0x80
 kmem_cache_alloc_noprof+0x1d5/0x680
 sk_prot_alloc+0x59/0x210
 sk_alloc+0x34/0x470
 unix_create1+0x86/0x8a0
 unix_stream_connect+0x318/0x15b0
 __sys_connect+0xfd/0x130
 __x64_sys_connect+0x72/0xd0
 do_syscall_64+0xf7/0x5e0
 entry_SYSCALL_64_after_hwframe+0x76/0x7e

Freed by task 2236:
 kasan_save_stack+0x30/0x50
 kasan_save_track+0x14/0x30
 kasan_save_free_info+0x3b/0x70
 __kasan_slab_free+0x47/0x70
 kmem_cache_free+0x11c/0x590
 __sk_destruct+0x432/0x6e0
 unix_release_sock+0x9b3/0xf60
 unix_release+0x8a/0xf0
 __sock_release+0xb0/0x270
 sock_close+0x18/0x20
 __fput+0x36e/0xac0
 fput_close_sync+0xe5/0x1a0
 __x64_sys_close+0x7d/0xd0
 do_syscall_64+0xf7/0x5e0
 entry_SYSCALL_64_after_hwframe+0x76/0x7e
Fixes 2c860a43dd77 ("bpf: af_unix: Implement BPF iterator for UNIX domain socket.")
---
 net/unix/af_unix.c | 2 ++
 1 file changed, 2 insertions(+)
net/unix/af_unix.c +2 -0
index 590a30d3b2f7..15b48cc6e9b0 100644
@@ -3737,6 +3737,7 @@ static int bpf_iter_unix_seq_show(struct seq_file *seq, void *v)
 		return 0;
 
 	lock_sock(sk);
+	unix_state_lock(sk);
 
 	if (unlikely(sock_flag(sk, SOCK_DEAD))) {
 		ret = SEQ_SKIP;
@@ -3748,6 +3749,7 @@ static int bpf_iter_unix_seq_show(struct seq_file *seq, void *v)
 	prog = bpf_iter_get_info(&meta, false);
 	ret = unix_prog_seq_show(prog, &meta, v, uid);
 unlock:
+	unix_state_unlock(sk);
 	release_sock(sk);
 	return ret;
 }
Signature · 1 line
2.53.0
#8 lore raw

Re: [PATCH bpf v4 5/5] bpf, sockmap: Take state lock for af_unix iter

Sashiko AI review found 2 potential issue(s): - [High] Incomplete fix for Use-After-Free (UAF) in unix_stream_bpf_update_proto(). - [High] Spinlock held during BPF program execution leads to context…

Sashiko AI review found 2 potential issue(s):
- [High] Incomplete fix for Use-After-Free (UAF) in unix_stream_bpf_update_proto().
- [High] Spinlock held during BPF program execution leads to context violations and deadlock risks. --

commit 059f81e7a85c481f9c7f6dd1d0ab36e935134ac8
Author: Michal Luczaj <[email protected]>

bpf, sockmap: Take state lock for af_unix iter

This commit attempts to fix a use-after-free race condition in unix_stream_bpf_update_proto() by acquiring the unix_state_lock() inside the bpf_iter_unix_seq_show() callback.

Quoted 9 lines
net/unix/af_unix.c +1 -0
index 590a30d3b2f70..15b48cc6e9b0c 100644
@@ -3737,6 +3737,7 @@ static int bpf_iter_unix_seq_show(struct seq_file *seq, void *v)
 		return 0;
 
 	lock_sock(sk);
+	unix_state_lock(sk);

[ ... ]

net/unix/af_unix.c static int bpf_iter_unix_seq_show(struct seq_file *seq, void *v) · line 3750

Quoted 3 lines
net/unix/af_unix.c +0 -0
@@ -3748,6 +3749,7 @@ static int bpf_iter_unix_seq_show(struct seq_file *seq, void *v)
 	prog = bpf_iter_get_info(&meta, false);
 	ret = unix_prog_seq_show(prog, &meta, v, uid);

Does holding a spinlock during bpf program execution introduce sleep-in-atomic or lock inversion issues?

If the bpf iterator program is loaded with BPF_F_SLEEPABLE, bpf_iter_run_prog() explicitly calls might_fault(). Calling might_fault() while holding a spinlock (which disables preemption) triggers a sleep in atomic context bug.

Also, could this introduce a lock inversion risk? The bpf programs can interact with maps or other sockets, acquiring locks like map->lock or bh_lock_sock. Taking unix_state_lock before these locks might create an unnatural lock hierarchy, potentially leading to deadlocks if other kernel paths acquire these locks in the standard order.

Additionally, does this fully resolve the use-after-free in unix_stream_bpf_update_proto()?

Since unix_stream_bpf_update_proto() is the underlying callback used whenever an af_unix socket is inserted into a sockmap, can it be reached independently of this iterator?

For example, could it be reached via the bpf(BPF_MAP_UPDATE_ELEM) syscall, or when a bpf program updates the map using a different af_unix socket than the one being iterated? In those cases, unix_state_lock(sk) would not be held, leaving the use-after-free unresolved.

Should the lock be acquired directly inside unix_stream_bpf_update_proto() instead?

Quoted 5 lines
net/unix/af_unix.c +1 -0
 unlock:
+	unix_state_unlock(sk);
 	release_sock(sk);
 	return ret;
 }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/20260414-unix-proto-update-null-ptr-deref-v4-0-2af6fe97918e@rbox.co?part=5
#9 lore raw

Re: [PATCH bpf v4 5/5] bpf, sockmap: Take state lock for af_unix iter

Quoted 15 lines · On 4/14/26 23:30, [email protected] wrote:
Quoted 5 lines
net/unix/af_unix.c +1 -0
@@ -3737,6 +3737,7 @@ static int bpf_iter_unix_seq_show(struct seq_file *seq, void *v)
 		return 0;
 
 	lock_sock(sk);
+	unix_state_lock(sk);

[ ... ]

net/unix/af_unix.c static int bpf_iter_unix_seq_show(struct seq_file *seq, void *v) · line 3750

Quoted 3 lines
net/unix/af_unix.c +0 -0
@@ -3748,6 +3749,7 @@ static int bpf_iter_unix_seq_show(struct seq_file *seq, void *v)
 	prog = bpf_iter_get_info(&meta, false);
 	ret = unix_prog_seq_show(prog, &meta, v, uid);

Does holding a spinlock during bpf program execution introduce sleep-in-atomic or lock inversion issues?

Quoted 4 lines

If the bpf iterator program is loaded with BPF_F_SLEEPABLE, bpf_iter_run_prog() explicitly calls might_fault(). Calling might_fault() while holding a spinlock (which disables preemption) triggers a sleep in atomic context bug.

See bpf_iter_link_attach(): BPF_F_SLEEPABLE is only allowed for resched-able iterators (BPF_ITER_RESCHED). This excludes unix iter.

Quoted 5 lines

Also, could this introduce a lock inversion risk? The bpf programs can interact with maps or other sockets, acquiring locks like map->lock or bh_lock_sock. Taking unix_state_lock before these locks might create an unnatural lock hierarchy, potentially leading to deadlocks if other kernel paths acquire these locks in the standard order.

Nothing I can think of. Any specific lock inversion scenario to consider?

Quoted 11 lines

Additionally, does this fully resolve the use-after-free in unix_stream_bpf_update_proto()?

Since unix_stream_bpf_update_proto() is the underlying callback used whenever an af_unix socket is inserted into a sockmap, can it be reached independently of this iterator?

For example, could it be reached via the bpf(BPF_MAP_UPDATE_ELEM) syscall, or when a bpf program updates the map using a different af_unix socket than the one being iterated? In those cases, unix_state_lock(sk) would not be held, leaving the use-after-free unresolved.

No, I don't think it can race the bpf() syscall. Both bpf_iter_unix_seq_show() (see patch 2/5) and sock_map_update_elem_sys() take the lock_sock. The latter via sock_map_sk_acquire().

Yes, bpf updating sockmap using a different unix sock than the one being iterated is possible:
a) iter prog accessing another sock (e.g. peer) by pointer chasing. To my understanding that's something the bpf validator is expected to reject[1].
b) iter prog looking up another sock in a sockmap. That sounds like a (safe) scenario 2.2.1 described in patch 4/5 commit message.

And yes, as pointed out by Martin[2], there's still the issue of sock_map_update_elem() missing sock_owned_by_user() check.

[1]:
https://lore.kernel.org/bpf/CAADnVQK_93g_KkNFYXSr8ZvA1fYh4hoFRJCJFPS-zs4ox0HhAA@mail.gmail.com/
[2]:
https://lore.kernel.org/bpf/[email protected]/

Quoted 2 lines

Should the lock be acquired directly inside unix_stream_bpf_update_proto() instead?

unix_stream_bpf_update_proto() is called in both process (e.g. syscall) and softirq (e.g. TC prog) contexts. Taking spinlock there would lead to context violation.

maintainer Reviewed-by on v4 5/5
#10 lore raw

Re: [PATCH bpf v4 5/5] bpf, sockmap: Take state lock for af_unix iter

In reply to Michal Luczaj
Quoted 73 lines · Michal Luczaj

When a BPF iterator program updates a sockmap, there is a race condition in unix_stream_bpf_update_proto() where the peer pointer can become stale[1] during a state transition TCP_ESTABLISHED -> TCP_CLOSE.

CPU0 bpf CPU1 close
-------- ----------
// unix_stream_bpf_update_proto()
sk_pair = unix_peer(sk)
if (unlikely(!sk_pair))

   return -EINVAL;
                                     // unix_release_sock()
                                     skpair = unix_peer(sk);
                                     unix_peer(sk) = NULL;
                                     sock_put(skpair)

sock_hold(sk_pair) // UaF

More practically, this fix guarantees that the iterator program is consistently provided with a unix socket that remains stable during iterator execution.

[1]:

BUG: KASAN: slab-use-after-free in unix_stream_bpf_update_proto+0x155/0x490
Write of size 4 at addr ffff8881178c9a00 by task test_progs/2231
Call Trace:
 dump_stack_lvl+0x5d/0x80
 print_report+0x170/0x4f3
 kasan_report+0xe4/0x1c0
 kasan_check_range+0x125/0x200
 unix_stream_bpf_update_proto+0x155/0x490
 sock_map_link+0x71c/0xec0
 sock_map_update_common+0xbc/0x600
 sock_map_update_elem+0x19a/0x1f0
 bpf_prog_bbbf56096cdd4f01_selective_dump_unix+0x20c/0x217
 bpf_iter_run_prog+0x21e/0xae0
 bpf_iter_unix_seq_show+0x1e0/0x2a0
 bpf_seq_read+0x42c/0x10d0
 vfs_read+0x171/0xb20
 ksys_read+0xff/0x200
 do_syscall_64+0xf7/0x5e0
 entry_SYSCALL_64_after_hwframe+0x76/0x7e

Allocated by task 2236:
 kasan_save_stack+0x30/0x50
 kasan_save_track+0x14/0x30
 __kasan_slab_alloc+0x63/0x80
 kmem_cache_alloc_noprof+0x1d5/0x680
 sk_prot_alloc+0x59/0x210
 sk_alloc+0x34/0x470
 unix_create1+0x86/0x8a0
 unix_stream_connect+0x318/0x15b0
 __sys_connect+0xfd/0x130
 __x64_sys_connect+0x72/0xd0
 do_syscall_64+0xf7/0x5e0
 entry_SYSCALL_64_after_hwframe+0x76/0x7e

Freed by task 2236:
 kasan_save_stack+0x30/0x50
 kasan_save_track+0x14/0x30
 kasan_save_free_info+0x3b/0x70
 __kasan_slab_free+0x47/0x70
 kmem_cache_free+0x11c/0x590
 __sk_destruct+0x432/0x6e0
 unix_release_sock+0x9b3/0xf60
 unix_release+0x8a/0xf0
 __sock_release+0xb0/0x270
 sock_close+0x18/0x20
 __fput+0x36e/0xac0
 fput_close_sync+0xe5/0x1a0
 __x64_sys_close+0x7d/0xd0
 do_syscall_64+0xf7/0x5e0
 entry_SYSCALL_64_after_hwframe+0x76/0x7e
Quoted 3 lines
Fixes 2c860a43dd77 ("bpf: af_unix: Implement BPF iterator for UNIX domain socket.")

Thanks for the fixes, Michal !

#11 lore raw
In reply to Michal Luczaj
This series was applied to bpf/bpf.git (master) by Martin KaFai Lau <[email protected]>:

Hello:

This series was applied to bpf/bpf.git (master)
by Martin KaFai Lau <[email protected]>:

Quoted 5 lines · On Tue, 14 Apr 2026 16:13:14 +0200 you wrote:

Updating sockmap/sockhash using a unix sock races unix_stream_connect():
when sock_map_sk_state_allowed() passes (sk_state == TCP_ESTABLISHED), unix_peer(sk) in unix_stream_bpf_update_proto() may still return NULL.

Quoted 8 lines

---
Changes in v4:
- Circle back to v1 approach
- More details in commit messages [Martin]
- Make unix iter take the state lock [Kaniyuki]
- Link to v3: https://lore.kernel.org/r/20260306-unix-proto-update-null-ptr-deref-v3-0-2f0c7410c523@rbox.co

[...]

Here is the summary with links:
- [bpf,v4,1/5] bpf, sockmap: Annotate af_unix sock::sk_state data-races

    https://git.kernel.org/bpf/bpf/c/a25566084e39
  - [bpf,v4,2/5] bpf, sockmap: Fix af_unix iter deadlock
    https://git.kernel.org/bpf/bpf/c/4d328dd69538
  - [bpf,v4,3/5] selftests/bpf: Extend bpf_iter_unix to attempt deadlocking
    https://git.kernel.org/bpf/bpf/c/997b8483d44c
  - [bpf,v4,4/5] bpf, sockmap: Fix af_unix null-ptr-deref in proto update
    https://git.kernel.org/bpf/bpf/c/dca38b7734d2
  - [bpf,v4,5/5] bpf, sockmap: Take state lock for af_unix iter
    https://git.kernel.org/bpf/bpf/c/64c2f93fc325

You are awesome, thank you!

Signature · 2 lines
Deet-doot-dot, I am a bot.
https://korg.docs.kernel.org/patchwork/pwbot.html