diff mbox series

[bpf,1/2] bpf: sockmap, af_unix sockets need to hold ref for pair sock

Message ID 20231016190819.81307-2-john.fastabend@gmail.com (mailing list archive)
State Changes Requested
Delegated to: BPF
Headers show
Series sockmap fix for KASAN_VMALLOC and af_unix | expand

Checks

Context Check Description
netdev/series_format success Posting correctly formatted
netdev/tree_selection success Clearly marked for bpf
netdev/fixes_present success Fixes tag present in non-next series
netdev/header_inline success No static functions without inline keyword in header files
netdev/build_32bit success Errors and warnings before: 1440 this patch: 1440
netdev/cc_maintainers fail 3 blamed authors not CCed: andrii@kernel.org jiang.wang@bytedance.com cong.wang@bytedance.com; 9 maintainers not CCed: kuniyu@amazon.com pabeni@redhat.com edumazet@google.com andrii@kernel.org kuba@kernel.org jiang.wang@bytedance.com cong.wang@bytedance.com davem@davemloft.net dhowells@redhat.com
netdev/build_clang success Errors and warnings before: 1388 this patch: 1388
netdev/verify_signedoff success Signed-off-by tag matches author and committer
netdev/deprecated_api success None detected
netdev/check_selftest success No net selftest shell script
netdev/verify_fixes success Fixes tag looks correct
netdev/build_allmodconfig_warn success Errors and warnings before: 1467 this patch: 1467
netdev/checkpatch success total: 0 errors, 0 warnings, 0 checks, 64 lines checked
netdev/kdoc success Errors and warnings before: 0 this patch: 0
netdev/source_inline success Was 0 now: 0
bpf/vmtest-bpf-VM_Test-33 success Logs for x86_64-llvm-16 / veristat
bpf/vmtest-bpf-VM_Test-32 success Logs for x86_64-llvm-16 / test (test_verifier, false, 360) / test_verifier on x86_64 with llvm-16
bpf/vmtest-bpf-VM_Test-30 success Logs for x86_64-llvm-16 / test (test_progs_no_alu32_parallel, true, 30) / test_progs_no_alu32_parallel on x86_64 with llvm-16
bpf/vmtest-bpf-VM_Test-31 success Logs for x86_64-llvm-16 / test (test_progs_parallel, true, 30) / test_progs_parallel on x86_64 with llvm-16
bpf/vmtest-bpf-VM_Test-0 success Logs for Lint
bpf/vmtest-bpf-VM_Test-2 success Logs for Validate matrix.py
bpf/vmtest-bpf-VM_Test-1 success Logs for ShellCheck
bpf/vmtest-bpf-VM_Test-3 success Logs for aarch64-gcc / build / build for aarch64 with gcc
bpf/vmtest-bpf-VM_Test-8 success Logs for aarch64-gcc / veristat
bpf/vmtest-bpf-VM_Test-4 success Logs for aarch64-gcc / test (test_maps, false, 360) / test_maps on aarch64 with gcc
bpf/vmtest-bpf-VM_Test-7 success Logs for aarch64-gcc / test (test_verifier, false, 360) / test_verifier on aarch64 with gcc
bpf/vmtest-bpf-VM_Test-6 success Logs for aarch64-gcc / test (test_progs_no_alu32, false, 360) / test_progs_no_alu32 on aarch64 with gcc
bpf/vmtest-bpf-VM_Test-5 success Logs for aarch64-gcc / test (test_progs, false, 360) / test_progs on aarch64 with gcc
bpf/vmtest-bpf-VM_Test-9 success Logs for s390x-gcc / build / build for s390x with gcc
bpf/vmtest-bpf-VM_Test-19 success Logs for x86_64-gcc / test (test_progs_no_alu32, false, 360) / test_progs_no_alu32 on x86_64 with gcc
bpf/vmtest-bpf-VM_Test-14 success Logs for s390x-gcc / veristat
bpf/vmtest-bpf-VM_Test-16 success Logs for x86_64-gcc / build / build for x86_64 with gcc
bpf/vmtest-bpf-VM_Test-27 success Logs for x86_64-llvm-16 / test (test_progs_no_alu32, false, 360) / test_progs_no_alu32 on x86_64 with llvm-16
bpf/vmtest-bpf-VM_Test-24 success Logs for x86_64-llvm-16 / build / build for x86_64 with llvm-16
bpf/vmtest-bpf-VM_Test-17 success Logs for x86_64-gcc / test (test_maps, false, 360) / test_maps on x86_64 with gcc
bpf/vmtest-bpf-VM_Test-28 success Logs for x86_64-llvm-16 / test (test_verifier, false, 360) / test_verifier on x86_64 with llvm-16
bpf/vmtest-bpf-VM_Test-15 success Logs for set-matrix
bpf/vmtest-bpf-VM_Test-22 success Logs for x86_64-gcc / test (test_verifier, false, 360) / test_verifier on x86_64 with gcc
bpf/vmtest-bpf-VM_Test-20 success Logs for x86_64-gcc / test (test_progs_no_alu32_parallel, true, 30) / test_progs_no_alu32_parallel on x86_64 with gcc
bpf/vmtest-bpf-VM_Test-18 success Logs for x86_64-gcc / test (test_progs, false, 360) / test_progs on x86_64 with gcc
bpf/vmtest-bpf-VM_Test-26 success Logs for x86_64-llvm-16 / test (test_progs, false, 360) / test_progs on x86_64 with llvm-16
bpf/vmtest-bpf-VM_Test-25 success Logs for x86_64-llvm-16 / test (test_maps, false, 360) / test_maps on x86_64 with llvm-16
bpf/vmtest-bpf-VM_Test-23 success Logs for x86_64-gcc / veristat / veristat on x86_64 with gcc
bpf/vmtest-bpf-VM_Test-29 success Logs for x86_64-llvm-16 / veristat
bpf/vmtest-bpf-VM_Test-21 success Logs for x86_64-gcc / test (test_progs_parallel, true, 30) / test_progs_parallel on x86_64 with gcc
bpf/vmtest-bpf-VM_Test-13 success Logs for s390x-gcc / test (test_verifier, false, 360) / test_verifier on s390x with gcc
bpf/vmtest-bpf-VM_Test-12 success Logs for s390x-gcc / test (test_progs_no_alu32, false, 360) / test_progs_no_alu32 on s390x with gcc
bpf/vmtest-bpf-VM_Test-11 success Logs for s390x-gcc / test (test_progs, false, 360) / test_progs on s390x with gcc
bpf/vmtest-bpf-VM_Test-10 success Logs for s390x-gcc / test (test_maps, false, 360) / test_maps on s390x with gcc
bpf/vmtest-bpf-PR success PR summary

Commit Message

John Fastabend Oct. 16, 2023, 7:08 p.m. UTC
AF_UNIX sockets are a paired socket. So sending on one of the pairs
will lookup the paired socket as part of the send operation. It is
possible however to put just one of the pairs in a BPF map. This
currently increments the refcnt on the sock in the sockmap to
ensure it is not free'd by the stack before sockmap cleans up its
state and stops any skbs being sent/recv'd to that socket.

But we missed a case. If the peer socket is closed it will be
free'd by the stack. However, the paired socket can still be
referenced from BPF sockmap side because we hold a reference
there. Then if we are sending traffic through BPF sockmap to
that socket it will try to dereference the free'd pair in its
send logic creating a use after free.  And following splat,

   [59.900375] BUG: KASAN: slab-use-after-free in sk_wake_async+0x31/0x1b0
   [59.901211] Read of size 8 at addr ffff88811acbf060 by task kworker/1:2/954
   [...]
   [59.905468] Call Trace:
   [59.905787]  <TASK>
   [59.906066]  dump_stack_lvl+0x130/0x1d0
   [59.908877]  print_report+0x16f/0x740
   [59.910629]  kasan_report+0x118/0x160
   [59.912576]  sk_wake_async+0x31/0x1b0
   [59.913554]  sock_def_readable+0x156/0x2a0
   [59.914060]  unix_stream_sendmsg+0x3f9/0x12a0
   [59.916398]  sock_sendmsg+0x20e/0x250
   [59.916854]  skb_send_sock+0x236/0xac0
   [59.920527]  sk_psock_backlog+0x287/0xaa0

To fix let BPF sockmap hold a refcnt on both the socket in the
sockmap and its paired socket.  It wasn't obvious how to contain
the fix to bpf_unix logic. The primarily problem with keeping this
logic in bpf_unix was: In the sock close() we could handle the
deref by having a close handler. But, when we are destroying the
psock through a map delete operation we wouldn't have gotten any
signal thorugh the proto struct other than it being replaced.
If we do the deref from the proto replace its too early because
we need to deref the skpair after the backlog worker has been
stopped.

Given all this it seems best to just cache it at the end of the
psock and eat 8B for the af_unix and vsock users.

Fixes: 94531cfcbe79 ("af_unix: Add unix_stream_proto for sockmap")
Signed-off-by: John Fastabend <john.fastabend@gmail.com>
---
 include/linux/skmsg.h |  1 +
 include/net/af_unix.h |  1 +
 net/core/skmsg.c      |  2 ++
 net/unix/af_unix.c    |  2 --
 net/unix/unix_bpf.c   | 10 ++++++++++
 5 files changed, 14 insertions(+), 2 deletions(-)

Comments

Jakub Sitnicki Oct. 18, 2023, 10:40 a.m. UTC | #1
On Mon, Oct 16, 2023 at 12:08 PM -07, John Fastabend wrote:
> AF_UNIX sockets are a paired socket. So sending on one of the pairs
> will lookup the paired socket as part of the send operation. It is
> possible however to put just one of the pairs in a BPF map. This
> currently increments the refcnt on the sock in the sockmap to
> ensure it is not free'd by the stack before sockmap cleans up its
> state and stops any skbs being sent/recv'd to that socket.
>
> But we missed a case. If the peer socket is closed it will be
> free'd by the stack. However, the paired socket can still be
> referenced from BPF sockmap side because we hold a reference
> there. Then if we are sending traffic through BPF sockmap to
> that socket it will try to dereference the free'd pair in its
> send logic creating a use after free.  And following splat,
>
>    [59.900375] BUG: KASAN: slab-use-after-free in sk_wake_async+0x31/0x1b0
>    [59.901211] Read of size 8 at addr ffff88811acbf060 by task kworker/1:2/954
>    [...]
>    [59.905468] Call Trace:
>    [59.905787]  <TASK>
>    [59.906066]  dump_stack_lvl+0x130/0x1d0
>    [59.908877]  print_report+0x16f/0x740
>    [59.910629]  kasan_report+0x118/0x160
>    [59.912576]  sk_wake_async+0x31/0x1b0
>    [59.913554]  sock_def_readable+0x156/0x2a0
>    [59.914060]  unix_stream_sendmsg+0x3f9/0x12a0
>    [59.916398]  sock_sendmsg+0x20e/0x250
>    [59.916854]  skb_send_sock+0x236/0xac0
>    [59.920527]  sk_psock_backlog+0x287/0xaa0

Isn't the problem here that unix_stream_sendmsg doesn't grab a ref to
peer sock? Unlike unix_dgram_sendmsg which uses the unix_peer_get
helper.

>
> To fix let BPF sockmap hold a refcnt on both the socket in the
> sockmap and its paired socket.  It wasn't obvious how to contain
> the fix to bpf_unix logic. The primarily problem with keeping this
> logic in bpf_unix was: In the sock close() we could handle the
> deref by having a close handler. But, when we are destroying the
> psock through a map delete operation we wouldn't have gotten any
> signal thorugh the proto struct other than it being replaced.
> If we do the deref from the proto replace its too early because
> we need to deref the skpair after the backlog worker has been
> stopped.
>
> Given all this it seems best to just cache it at the end of the
> psock and eat 8B for the af_unix and vsock users.
>
> Fixes: 94531cfcbe79 ("af_unix: Add unix_stream_proto for sockmap")
> Signed-off-by: John Fastabend <john.fastabend@gmail.com>
> ---

[...]
John Fastabend Oct. 24, 2023, 9:39 p.m. UTC | #2
Jakub Sitnicki wrote:
> On Mon, Oct 16, 2023 at 12:08 PM -07, John Fastabend wrote:
> > AF_UNIX sockets are a paired socket. So sending on one of the pairs
> > will lookup the paired socket as part of the send operation. It is
> > possible however to put just one of the pairs in a BPF map. This
> > currently increments the refcnt on the sock in the sockmap to
> > ensure it is not free'd by the stack before sockmap cleans up its
> > state and stops any skbs being sent/recv'd to that socket.
> >
> > But we missed a case. If the peer socket is closed it will be
> > free'd by the stack. However, the paired socket can still be
> > referenced from BPF sockmap side because we hold a reference
> > there. Then if we are sending traffic through BPF sockmap to
> > that socket it will try to dereference the free'd pair in its
> > send logic creating a use after free.  And following splat,
> >
> >    [59.900375] BUG: KASAN: slab-use-after-free in sk_wake_async+0x31/0x1b0
> >    [59.901211] Read of size 8 at addr ffff88811acbf060 by task kworker/1:2/954
> >    [...]
> >    [59.905468] Call Trace:
> >    [59.905787]  <TASK>
> >    [59.906066]  dump_stack_lvl+0x130/0x1d0
> >    [59.908877]  print_report+0x16f/0x740
> >    [59.910629]  kasan_report+0x118/0x160
> >    [59.912576]  sk_wake_async+0x31/0x1b0
> >    [59.913554]  sock_def_readable+0x156/0x2a0
> >    [59.914060]  unix_stream_sendmsg+0x3f9/0x12a0
> >    [59.916398]  sock_sendmsg+0x20e/0x250
> >    [59.916854]  skb_send_sock+0x236/0xac0
> >    [59.920527]  sk_psock_backlog+0x287/0xaa0
> 
> Isn't the problem here that unix_stream_sendmsg doesn't grab a ref to
> peer sock? Unlike unix_dgram_sendmsg which uses the unix_peer_get
> helper.

It does by my read. In unix_stream_connect we have,

	sock_hold(sk);
	unix_peer(newsk)	= sk;
	newsk->sk_state		= TCP_ESTABLISHED;

where it assigns the peer sock. unix_dgram_connect() also calls
sock_hold() but through the path that does the socket lookup, such as
unix_find_other().

The problem I see is before the socket does the kfree on the
sock we need to be sure the backlog is canceled and the skb list
ingress_skb is purged. If we don't ensure this then the redirect
will 

My model is this,

         s1            c1
refcnt    1             1
connect   2             2
psock     3             3
send(s1) ...
close(s1) 2             1 <- close drops psock count also
close(c1) 0             0

The important bit here is the psock has a refcnt on the
underlying sock (psock->sk) and wont dec that until after
cancel_delayed_work_sync() completes. This ensures the
backlog wont try to sendmsg() on that sock after we free
it. We also check for SOCK_DEAD and abort to avoid sending
over a socket that has been marked DEAD.

So... After close(s1) the only thing keeping that sock
around is c1. Then we close(c1) that call path is

 unix_release
   close() 
   unix_release_sock()
     skpair = unix_peer(sk);
     ...
     sock_put(skpair);  <- trouble here

The release will call sock_put() on the pair socket and
dec it to 0 where it gets free'd through sk_free(). But
now the trouble is we haven't waited for cancel_delayed_work_sync()
on the c1 socket yet so backlog can still run. When it does
run it may try to send a pkg over socket s1. OK right up until
the sendmsg(s1, ...) does a peer lookup and derefs the peer
socket. The peer socket was free'd earlier so use after free. 

The question I had originally was this is odd, we are allowing
a sendmsg(s1) over a socket while its in unix_release(). We
used to take the sock lock from the backlog that was dropped
in the name of performance, but it creates these races.

Other fixes I considered. First adding sock lock back to
backlog. But that punishes the UDP and TCP cases that don't
have this problem. Set the SOCK_DEAD flag earlier or check
later but this just makes the race smaller doesn't really
eliminate it.

So this patch is what I came up with. 

> 
> >
> > To fix let BPF sockmap hold a refcnt on both the socket in the
> > sockmap and its paired socket.  It wasn't obvious how to contain
> > the fix to bpf_unix logic. The primarily problem with keeping this
> > logic in bpf_unix was: In the sock close() we could handle the
> > deref by having a close handler. But, when we are destroying the
> > psock through a map delete operation we wouldn't have gotten any
> > signal thorugh the proto struct other than it being replaced.
> > If we do the deref from the proto replace its too early because
> > we need to deref the skpair after the backlog worker has been
> > stopped.
> >
> > Given all this it seems best to just cache it at the end of the
> > psock and eat 8B for the af_unix and vsock users.
> >
> > Fixes: 94531cfcbe79 ("af_unix: Add unix_stream_proto for sockmap")
> > Signed-off-by: John Fastabend <john.fastabend@gmail.com>
> > ---
> 
> [...]
Jakub Sitnicki Oct. 27, 2023, 1:32 p.m. UTC | #3
On Tue, Oct 24, 2023 at 02:39 PM -07, John Fastabend wrote:
> Jakub Sitnicki wrote:
>> On Mon, Oct 16, 2023 at 12:08 PM -07, John Fastabend wrote:
>> > AF_UNIX sockets are a paired socket. So sending on one of the pairs
>> > will lookup the paired socket as part of the send operation. It is
>> > possible however to put just one of the pairs in a BPF map. This
>> > currently increments the refcnt on the sock in the sockmap to
>> > ensure it is not free'd by the stack before sockmap cleans up its
>> > state and stops any skbs being sent/recv'd to that socket.
>> >
>> > But we missed a case. If the peer socket is closed it will be
>> > free'd by the stack. However, the paired socket can still be
>> > referenced from BPF sockmap side because we hold a reference
>> > there. Then if we are sending traffic through BPF sockmap to
>> > that socket it will try to dereference the free'd pair in its
>> > send logic creating a use after free.  And following splat,
>> >
>> >    [59.900375] BUG: KASAN: slab-use-after-free in sk_wake_async+0x31/0x1b0
>> >    [59.901211] Read of size 8 at addr ffff88811acbf060 by task kworker/1:2/954
>> >    [...]
>> >    [59.905468] Call Trace:
>> >    [59.905787]  <TASK>
>> >    [59.906066]  dump_stack_lvl+0x130/0x1d0
>> >    [59.908877]  print_report+0x16f/0x740
>> >    [59.910629]  kasan_report+0x118/0x160
>> >    [59.912576]  sk_wake_async+0x31/0x1b0
>> >    [59.913554]  sock_def_readable+0x156/0x2a0
>> >    [59.914060]  unix_stream_sendmsg+0x3f9/0x12a0
>> >    [59.916398]  sock_sendmsg+0x20e/0x250
>> >    [59.916854]  skb_send_sock+0x236/0xac0
>> >    [59.920527]  sk_psock_backlog+0x287/0xaa0
>> 
>> Isn't the problem here that unix_stream_sendmsg doesn't grab a ref to
>> peer sock? Unlike unix_dgram_sendmsg which uses the unix_peer_get
>> helper.
>
> It does by my read. In unix_stream_connect we have,
>
> 	sock_hold(sk);
> 	unix_peer(newsk)	= sk;
> 	newsk->sk_state		= TCP_ESTABLISHED;
>
> where it assigns the peer sock. unix_dgram_connect() also calls
> sock_hold() but through the path that does the socket lookup, such as
> unix_find_other().
>
> The problem I see is before the socket does the kfree on the
> sock we need to be sure the backlog is canceled and the skb list
> ingress_skb is purged. If we don't ensure this then the redirect
> will 
>
> My model is this,
>
>          s1            c1
> refcnt    1             1
> connect   2             2
> psock     3             3
> send(s1) ...
> close(s1) 2             1 <- close drops psock count also
> close(c1) 0             0
>
> The important bit here is the psock has a refcnt on the
> underlying sock (psock->sk) and wont dec that until after
> cancel_delayed_work_sync() completes. This ensures the
> backlog wont try to sendmsg() on that sock after we free
> it. We also check for SOCK_DEAD and abort to avoid sending
> over a socket that has been marked DEAD.
>
> So... After close(s1) the only thing keeping that sock
> around is c1. Then we close(c1) that call path is
>
>  unix_release
>    close() 
>    unix_release_sock()
>      skpair = unix_peer(sk);
>      ...
>      sock_put(skpair);  <- trouble here
>
> The release will call sock_put() on the pair socket and
> dec it to 0 where it gets free'd through sk_free(). But
> now the trouble is we haven't waited for cancel_delayed_work_sync()
> on the c1 socket yet so backlog can still run. When it does
> run it may try to send a pkg over socket s1. OK right up until
> the sendmsg(s1, ...) does a peer lookup and derefs the peer
> socket. The peer socket was free'd earlier so use after free. 
>
> The question I had originally was this is odd, we are allowing
> a sendmsg(s1) over a socket while its in unix_release(). We
> used to take the sock lock from the backlog that was dropped
> in the name of performance, but it creates these races.
>
> Other fixes I considered. First adding sock lock back to
> backlog. But that punishes the UDP and TCP cases that don't
> have this problem. Set the SOCK_DEAD flag earlier or check
> later but this just makes the race smaller doesn't really
> eliminate it.
>
> So this patch is what I came up with. 

What I was getting at is that we could make it safe to call sendmsg on a
unix stream sock while its peer is being release. And not just for
sockmap. I expect io_uring might have the same problem. But I didn't
actually check yet.

For that we could keep a ref to peer for the duration of sendmsg call,
like unix dgram does. Then 'other' doesn't become a stale pointer before
we're done with it.

Bumping ref count on each sendmsg is not free, but maybe its
acceptable. Unix dgram sockets live with it.

With a patch like below, I'm no longer able to trigger an UAF splat.

WDYT?

---8<---

diff --git a/net/unix/af_unix.c b/net/unix/af_unix.c
index 3e8a04a13668..48cf19ea9294 100644
--- a/net/unix/af_unix.c
+++ b/net/unix/af_unix.c
@@ -2198,7 +2198,7 @@ static int unix_stream_sendmsg(struct socket *sock, struct msghdr *msg,
 		goto out_err;
 	} else {
 		err = -ENOTCONN;
-		other = unix_peer(sk);
+		other = unix_peer_get(sk);
 		if (!other)
 			goto out_err;
 	}
@@ -2282,6 +2282,7 @@ static int unix_stream_sendmsg(struct socket *sock, struct msghdr *msg,
 	}
 #endif
 
+	sock_put(other);
 	scm_destroy(&scm);
 
 	return sent;
@@ -2294,6 +2295,8 @@ static int unix_stream_sendmsg(struct socket *sock, struct msghdr *msg,
 		send_sig(SIGPIPE, current, 0);
 	err = -EPIPE;
 out_err:
+	if (other)
+		sock_put(other);
 	scm_destroy(&scm);
 	return sent ? : err;
 }
Kuniyuki Iwashima Oct. 27, 2023, 5:38 p.m. UTC | #4
From: Jakub Sitnicki <jakub@cloudflare.com>
Date: Fri, 27 Oct 2023 15:32:15 +0200
> On Tue, Oct 24, 2023 at 02:39 PM -07, John Fastabend wrote:
> > Jakub Sitnicki wrote:
> >> On Mon, Oct 16, 2023 at 12:08 PM -07, John Fastabend wrote:
> >> > AF_UNIX sockets are a paired socket. So sending on one of the pairs
> >> > will lookup the paired socket as part of the send operation. It is
> >> > possible however to put just one of the pairs in a BPF map. This
> >> > currently increments the refcnt on the sock in the sockmap to
> >> > ensure it is not free'd by the stack before sockmap cleans up its
> >> > state and stops any skbs being sent/recv'd to that socket.
> >> >
> >> > But we missed a case. If the peer socket is closed it will be
> >> > free'd by the stack. However, the paired socket can still be
> >> > referenced from BPF sockmap side because we hold a reference
> >> > there. Then if we are sending traffic through BPF sockmap to
> >> > that socket it will try to dereference the free'd pair in its
> >> > send logic creating a use after free.  And following splat,
> >> >
> >> >    [59.900375] BUG: KASAN: slab-use-after-free in sk_wake_async+0x31/0x1b0
> >> >    [59.901211] Read of size 8 at addr ffff88811acbf060 by task kworker/1:2/954
> >> >    [...]
> >> >    [59.905468] Call Trace:
> >> >    [59.905787]  <TASK>
> >> >    [59.906066]  dump_stack_lvl+0x130/0x1d0
> >> >    [59.908877]  print_report+0x16f/0x740
> >> >    [59.910629]  kasan_report+0x118/0x160
> >> >    [59.912576]  sk_wake_async+0x31/0x1b0
> >> >    [59.913554]  sock_def_readable+0x156/0x2a0
> >> >    [59.914060]  unix_stream_sendmsg+0x3f9/0x12a0
> >> >    [59.916398]  sock_sendmsg+0x20e/0x250
> >> >    [59.916854]  skb_send_sock+0x236/0xac0
> >> >    [59.920527]  sk_psock_backlog+0x287/0xaa0
> >> 
> >> Isn't the problem here that unix_stream_sendmsg doesn't grab a ref to
> >> peer sock? Unlike unix_dgram_sendmsg which uses the unix_peer_get
> >> helper.
> >
> > It does by my read. In unix_stream_connect we have,
> >
> > 	sock_hold(sk);
> > 	unix_peer(newsk)	= sk;
> > 	newsk->sk_state		= TCP_ESTABLISHED;
> >
> > where it assigns the peer sock. unix_dgram_connect() also calls
> > sock_hold() but through the path that does the socket lookup, such as
> > unix_find_other().
> >
> > The problem I see is before the socket does the kfree on the
> > sock we need to be sure the backlog is canceled and the skb list
> > ingress_skb is purged. If we don't ensure this then the redirect
> > will 
> >
> > My model is this,
> >
> >          s1            c1
> > refcnt    1             1
> > connect   2             2
> > psock     3             3
> > send(s1) ...
> > close(s1) 2             1 <- close drops psock count also
> > close(c1) 0             0
> >
> > The important bit here is the psock has a refcnt on the
> > underlying sock (psock->sk) and wont dec that until after
> > cancel_delayed_work_sync() completes. This ensures the
> > backlog wont try to sendmsg() on that sock after we free
> > it. We also check for SOCK_DEAD and abort to avoid sending
> > over a socket that has been marked DEAD.
> >
> > So... After close(s1) the only thing keeping that sock
> > around is c1. Then we close(c1) that call path is
> >
> >  unix_release
> >    close() 
> >    unix_release_sock()
> >      skpair = unix_peer(sk);
> >      ...
> >      sock_put(skpair);  <- trouble here
> >
> > The release will call sock_put() on the pair socket and
> > dec it to 0 where it gets free'd through sk_free(). But
> > now the trouble is we haven't waited for cancel_delayed_work_sync()
> > on the c1 socket yet so backlog can still run. When it does
> > run it may try to send a pkg over socket s1. OK right up until
> > the sendmsg(s1, ...) does a peer lookup and derefs the peer
> > socket. The peer socket was free'd earlier so use after free. 
> >
> > The question I had originally was this is odd, we are allowing
> > a sendmsg(s1) over a socket while its in unix_release(). We
> > used to take the sock lock from the backlog that was dropped
> > in the name of performance, but it creates these races.
> >
> > Other fixes I considered. First adding sock lock back to
> > backlog. But that punishes the UDP and TCP cases that don't
> > have this problem. Set the SOCK_DEAD flag earlier or check
> > later but this just makes the race smaller doesn't really
> > eliminate it.
> >
> > So this patch is what I came up with. 
> 
> What I was getting at is that we could make it safe to call sendmsg on a
> unix stream sock while its peer is being release. And not just for
> sockmap. I expect io_uring might have the same problem. But I didn't
> actually check yet.
> 
> For that we could keep a ref to peer for the duration of sendmsg call,
> like unix dgram does. Then 'other' doesn't become a stale pointer before
> we're done with it.
> 
> Bumping ref count on each sendmsg is not free, but maybe its
> acceptable. Unix dgram sockets live with it.

The reason why only dgram sk needs sock_hold() for each sendmsg() is
that dgram sk can send data without connect().  unix_peer_get() in
unix_dgram_sendmsg() is to reuse the same code when peer is not set.

unix_stream_sendmsg() already holds a necessary refcnt and need not
use sock_hold() there.

The user who touches a peer without lookup must hold refcnt beforehand.


> 
> With a patch like below, I'm no longer able to trigger an UAF splat.
> 
> WDYT?
> 
> ---8<---
> 
> diff --git a/net/unix/af_unix.c b/net/unix/af_unix.c
> index 3e8a04a13668..48cf19ea9294 100644
> --- a/net/unix/af_unix.c
> +++ b/net/unix/af_unix.c
> @@ -2198,7 +2198,7 @@ static int unix_stream_sendmsg(struct socket *sock, struct msghdr *msg,
>  		goto out_err;
>  	} else {
>  		err = -ENOTCONN;
> -		other = unix_peer(sk);
> +		other = unix_peer_get(sk);
>  		if (!other)
>  			goto out_err;
>  	}
> @@ -2282,6 +2282,7 @@ static int unix_stream_sendmsg(struct socket *sock, struct msghdr *msg,
>  	}
>  #endif
>  
> +	sock_put(other);
>  	scm_destroy(&scm);
>  
>  	return sent;
> @@ -2294,6 +2295,8 @@ static int unix_stream_sendmsg(struct socket *sock, struct msghdr *msg,
>  		send_sig(SIGPIPE, current, 0);
>  	err = -EPIPE;
>  out_err:
> +	if (other)
> +		sock_put(other);
>  	scm_destroy(&scm);
>  	return sent ? : err;
>  }
Jakub Sitnicki Oct. 28, 2023, 7:33 a.m. UTC | #5
On Fri, Oct 27, 2023 at 10:38 AM -07, Kuniyuki Iwashima wrote:
> From: Jakub Sitnicki <jakub@cloudflare.com>
> Date: Fri, 27 Oct 2023 15:32:15 +0200
>> On Tue, Oct 24, 2023 at 02:39 PM -07, John Fastabend wrote:
>> > Jakub Sitnicki wrote:
>> >> On Mon, Oct 16, 2023 at 12:08 PM -07, John Fastabend wrote:
>> >> > AF_UNIX sockets are a paired socket. So sending on one of the pairs
>> >> > will lookup the paired socket as part of the send operation. It is
>> >> > possible however to put just one of the pairs in a BPF map. This
>> >> > currently increments the refcnt on the sock in the sockmap to
>> >> > ensure it is not free'd by the stack before sockmap cleans up its
>> >> > state and stops any skbs being sent/recv'd to that socket.
>> >> >
>> >> > But we missed a case. If the peer socket is closed it will be
>> >> > free'd by the stack. However, the paired socket can still be
>> >> > referenced from BPF sockmap side because we hold a reference
>> >> > there. Then if we are sending traffic through BPF sockmap to
>> >> > that socket it will try to dereference the free'd pair in its
>> >> > send logic creating a use after free.  And following splat,
>> >> >
>> >> >    [59.900375] BUG: KASAN: slab-use-after-free in sk_wake_async+0x31/0x1b0
>> >> >    [59.901211] Read of size 8 at addr ffff88811acbf060 by task kworker/1:2/954
>> >> >    [...]
>> >> >    [59.905468] Call Trace:
>> >> >    [59.905787]  <TASK>
>> >> >    [59.906066]  dump_stack_lvl+0x130/0x1d0
>> >> >    [59.908877]  print_report+0x16f/0x740
>> >> >    [59.910629]  kasan_report+0x118/0x160
>> >> >    [59.912576]  sk_wake_async+0x31/0x1b0
>> >> >    [59.913554]  sock_def_readable+0x156/0x2a0
>> >> >    [59.914060]  unix_stream_sendmsg+0x3f9/0x12a0
>> >> >    [59.916398]  sock_sendmsg+0x20e/0x250
>> >> >    [59.916854]  skb_send_sock+0x236/0xac0
>> >> >    [59.920527]  sk_psock_backlog+0x287/0xaa0
>> >> 
>> >> Isn't the problem here that unix_stream_sendmsg doesn't grab a ref to
>> >> peer sock? Unlike unix_dgram_sendmsg which uses the unix_peer_get
>> >> helper.
>> >
>> > It does by my read. In unix_stream_connect we have,
>> >
>> > 	sock_hold(sk);
>> > 	unix_peer(newsk)	= sk;
>> > 	newsk->sk_state		= TCP_ESTABLISHED;
>> >
>> > where it assigns the peer sock. unix_dgram_connect() also calls
>> > sock_hold() but through the path that does the socket lookup, such as
>> > unix_find_other().
>> >
>> > The problem I see is before the socket does the kfree on the
>> > sock we need to be sure the backlog is canceled and the skb list
>> > ingress_skb is purged. If we don't ensure this then the redirect
>> > will 
>> >
>> > My model is this,
>> >
>> >          s1            c1
>> > refcnt    1             1
>> > connect   2             2
>> > psock     3             3
>> > send(s1) ...
>> > close(s1) 2             1 <- close drops psock count also
>> > close(c1) 0             0
>> >
>> > The important bit here is the psock has a refcnt on the
>> > underlying sock (psock->sk) and wont dec that until after
>> > cancel_delayed_work_sync() completes. This ensures the
>> > backlog wont try to sendmsg() on that sock after we free
>> > it. We also check for SOCK_DEAD and abort to avoid sending
>> > over a socket that has been marked DEAD.
>> >
>> > So... After close(s1) the only thing keeping that sock
>> > around is c1. Then we close(c1) that call path is
>> >
>> >  unix_release
>> >    close() 
>> >    unix_release_sock()
>> >      skpair = unix_peer(sk);
>> >      ...
>> >      sock_put(skpair);  <- trouble here
>> >
>> > The release will call sock_put() on the pair socket and
>> > dec it to 0 where it gets free'd through sk_free(). But
>> > now the trouble is we haven't waited for cancel_delayed_work_sync()
>> > on the c1 socket yet so backlog can still run. When it does
>> > run it may try to send a pkg over socket s1. OK right up until
>> > the sendmsg(s1, ...) does a peer lookup and derefs the peer
>> > socket. The peer socket was free'd earlier so use after free. 
>> >
>> > The question I had originally was this is odd, we are allowing
>> > a sendmsg(s1) over a socket while its in unix_release(). We
>> > used to take the sock lock from the backlog that was dropped
>> > in the name of performance, but it creates these races.
>> >
>> > Other fixes I considered. First adding sock lock back to
>> > backlog. But that punishes the UDP and TCP cases that don't
>> > have this problem. Set the SOCK_DEAD flag earlier or check
>> > later but this just makes the race smaller doesn't really
>> > eliminate it.
>> >
>> > So this patch is what I came up with. 
>> 
>> What I was getting at is that we could make it safe to call sendmsg on a
>> unix stream sock while its peer is being release. And not just for
>> sockmap. I expect io_uring might have the same problem. But I didn't
>> actually check yet.
>> 
>> For that we could keep a ref to peer for the duration of sendmsg call,
>> like unix dgram does. Then 'other' doesn't become a stale pointer before
>> we're done with it.
>> 
>> Bumping ref count on each sendmsg is not free, but maybe its
>> acceptable. Unix dgram sockets live with it.
>
> The reason why only dgram sk needs sock_hold() for each sendmsg() is
> that dgram sk can send data without connect().  unix_peer_get() in
> unix_dgram_sendmsg() is to reuse the same code when peer is not set.
>
> unix_stream_sendmsg() already holds a necessary refcnt and need not
> use sock_hold() there.
>
> The user who touches a peer without lookup must hold refcnt beforehand.

Right. And this ownership scheme works well for unix stream because, as
John nicely explained, we serialize close() and sendmsg() ops with sock
lock.

Here, however, we have a case of deferred work which holds a ref to sock
but does not grab the sock lock. While it is doing its thing, the sk
gets closed/released and we drop the skpair ref. And bam, UAF.

If it wasn't for the reference cycle between sk and skpair, we could
defer the skpari ref drop until sk_destruct callback. But we can't.

If grabbing a ref on skpair on each sendmsg turns out to be not a viable
option, I didn't run any benchmarks so can't say what's the penatly
like, the next best thing is RCU.

If we can protect the skpair pointer with RCU, the memory it points to
will stay valid until unix_stream_sendmsg is done with it. I have not
given this approach a shot, so there might be something in the way.

[...]
John Fastabend Nov. 4, 2023, 3:38 a.m. UTC | #6
Jakub Sitnicki wrote:
> On Fri, Oct 27, 2023 at 10:38 AM -07, Kuniyuki Iwashima wrote:
> > From: Jakub Sitnicki <jakub@cloudflare.com>
> > Date: Fri, 27 Oct 2023 15:32:15 +0200
> >> On Tue, Oct 24, 2023 at 02:39 PM -07, John Fastabend wrote:
> >> > Jakub Sitnicki wrote:
> >> >> On Mon, Oct 16, 2023 at 12:08 PM -07, John Fastabend wrote:
> >> >> > AF_UNIX sockets are a paired socket. So sending on one of the pairs
> >> >> > will lookup the paired socket as part of the send operation. It is
> >> >> > possible however to put just one of the pairs in a BPF map. This
> >> >> > currently increments the refcnt on the sock in the sockmap to
> >> >> > ensure it is not free'd by the stack before sockmap cleans up its
> >> >> > state and stops any skbs being sent/recv'd to that socket.
> >> >> >
> >> >> > But we missed a case. If the peer socket is closed it will be
> >> >> > free'd by the stack. However, the paired socket can still be
> >> >> > referenced from BPF sockmap side because we hold a reference
> >> >> > there. Then if we are sending traffic through BPF sockmap to
> >> >> > that socket it will try to dereference the free'd pair in its
> >> >> > send logic creating a use after free.  And following splat,
> >> >> >
> >> >> >    [59.900375] BUG: KASAN: slab-use-after-free in sk_wake_async+0x31/0x1b0
> >> >> >    [59.901211] Read of size 8 at addr ffff88811acbf060 by task kworker/1:2/954
> >> >> >    [...]
> >> >> >    [59.905468] Call Trace:
> >> >> >    [59.905787]  <TASK>
> >> >> >    [59.906066]  dump_stack_lvl+0x130/0x1d0
> >> >> >    [59.908877]  print_report+0x16f/0x740
> >> >> >    [59.910629]  kasan_report+0x118/0x160
> >> >> >    [59.912576]  sk_wake_async+0x31/0x1b0
> >> >> >    [59.913554]  sock_def_readable+0x156/0x2a0
> >> >> >    [59.914060]  unix_stream_sendmsg+0x3f9/0x12a0
> >> >> >    [59.916398]  sock_sendmsg+0x20e/0x250
> >> >> >    [59.916854]  skb_send_sock+0x236/0xac0
> >> >> >    [59.920527]  sk_psock_backlog+0x287/0xaa0
> >> >> 
> >> >> Isn't the problem here that unix_stream_sendmsg doesn't grab a ref to
> >> >> peer sock? Unlike unix_dgram_sendmsg which uses the unix_peer_get
> >> >> helper.
> >> >
> >> > It does by my read. In unix_stream_connect we have,
> >> >
> >> > 	sock_hold(sk);
> >> > 	unix_peer(newsk)	= sk;
> >> > 	newsk->sk_state		= TCP_ESTABLISHED;
> >> >
> >> > where it assigns the peer sock. unix_dgram_connect() also calls
> >> > sock_hold() but through the path that does the socket lookup, such as
> >> > unix_find_other().
> >> >
> >> > The problem I see is before the socket does the kfree on the
> >> > sock we need to be sure the backlog is canceled and the skb list
> >> > ingress_skb is purged. If we don't ensure this then the redirect
> >> > will 
> >> >
> >> > My model is this,
> >> >
> >> >          s1            c1
> >> > refcnt    1             1
> >> > connect   2             2
> >> > psock     3             3
> >> > send(s1) ...
> >> > close(s1) 2             1 <- close drops psock count also
> >> > close(c1) 0             0
> >> >
> >> > The important bit here is the psock has a refcnt on the
> >> > underlying sock (psock->sk) and wont dec that until after
> >> > cancel_delayed_work_sync() completes. This ensures the
> >> > backlog wont try to sendmsg() on that sock after we free
> >> > it. We also check for SOCK_DEAD and abort to avoid sending
> >> > over a socket that has been marked DEAD.
> >> >
> >> > So... After close(s1) the only thing keeping that sock
> >> > around is c1. Then we close(c1) that call path is
> >> >
> >> >  unix_release
> >> >    close() 
> >> >    unix_release_sock()
> >> >      skpair = unix_peer(sk);
> >> >      ...
> >> >      sock_put(skpair);  <- trouble here
> >> >
> >> > The release will call sock_put() on the pair socket and
> >> > dec it to 0 where it gets free'd through sk_free(). But
> >> > now the trouble is we haven't waited for cancel_delayed_work_sync()
> >> > on the c1 socket yet so backlog can still run. When it does
> >> > run it may try to send a pkg over socket s1. OK right up until
> >> > the sendmsg(s1, ...) does a peer lookup and derefs the peer
> >> > socket. The peer socket was free'd earlier so use after free. 
> >> >
> >> > The question I had originally was this is odd, we are allowing
> >> > a sendmsg(s1) over a socket while its in unix_release(). We
> >> > used to take the sock lock from the backlog that was dropped
> >> > in the name of performance, but it creates these races.
> >> >
> >> > Other fixes I considered. First adding sock lock back to
> >> > backlog. But that punishes the UDP and TCP cases that don't
> >> > have this problem. Set the SOCK_DEAD flag earlier or check
> >> > later but this just makes the race smaller doesn't really
> >> > eliminate it.
> >> >
> >> > So this patch is what I came up with. 
> >> 
> >> What I was getting at is that we could make it safe to call sendmsg on a
> >> unix stream sock while its peer is being release. And not just for
> >> sockmap. I expect io_uring might have the same problem. But I didn't
> >> actually check yet.
> >> 
> >> For that we could keep a ref to peer for the duration of sendmsg call,
> >> like unix dgram does. Then 'other' doesn't become a stale pointer before
> >> we're done with it.
> >> 
> >> Bumping ref count on each sendmsg is not free, but maybe its
> >> acceptable. Unix dgram sockets live with it.
> >
> > The reason why only dgram sk needs sock_hold() for each sendmsg() is
> > that dgram sk can send data without connect().  unix_peer_get() in
> > unix_dgram_sendmsg() is to reuse the same code when peer is not set.
> >
> > unix_stream_sendmsg() already holds a necessary refcnt and need not
> > use sock_hold() there.
> >
> > The user who touches a peer without lookup must hold refcnt beforehand.

Hi, we probably do need to get a fix for this. syzkaller hit it again
and anyways it likely will crash some real systems if folks try to use
it with enough systems.

> 
> Right. And this ownership scheme works well for unix stream because, as
> John nicely explained, we serialize close() and sendmsg() ops with sock
> lock.
> 
> Here, however, we have a case of deferred work which holds a ref to sock
> but does not grab the sock lock. While it is doing its thing, the sk
> gets closed/released and we drop the skpair ref. And bam, UAF.
> 
> If it wasn't for the reference cycle between sk and skpair, we could
> defer the skpari ref drop until sk_destruct callback. But we can't.
> 
> If grabbing a ref on skpair on each sendmsg turns out to be not a viable
> option, I didn't run any benchmarks so can't say what's the penatly
> like, the next best thing is RCU.

I think it really would be best to stay out of the presumably hotpath
here if we can.

I had considered marking the socket SOCK_RCU_FREE which should then
wait an rcu grace period. But then it wasn't clear to me that would
completely solve the race. The psock still needs to do the 
cancel_delayed_work_sync() and this is also done from the rcu call
back on the psock. Withtout the extra reference iirc the concern
was we would basically have two rcu callbacks running that have
an ordering requirement which I don't think is ensured.

> 
> If we can protect the skpair pointer with RCU, the memory it points to
> will stay valid until unix_stream_sendmsg is done with it. I have not
> given this approach a shot, so there might be something in the way.
> 
> [...]

Thanks,
John
Jakub Sitnicki Nov. 6, 2023, 10:15 a.m. UTC | #7
On Fri, Nov 03, 2023 at 08:38 PM -07, John Fastabend wrote:
> Jakub Sitnicki wrote:
>> On Fri, Oct 27, 2023 at 10:38 AM -07, Kuniyuki Iwashima wrote:
>> > From: Jakub Sitnicki <jakub@cloudflare.com>
>> > Date: Fri, 27 Oct 2023 15:32:15 +0200
>> >> On Tue, Oct 24, 2023 at 02:39 PM -07, John Fastabend wrote:
>> >> > Jakub Sitnicki wrote:
>> >> >> On Mon, Oct 16, 2023 at 12:08 PM -07, John Fastabend wrote:
>> >> >> > AF_UNIX sockets are a paired socket. So sending on one of the pairs
>> >> >> > will lookup the paired socket as part of the send operation. It is
>> >> >> > possible however to put just one of the pairs in a BPF map. This
>> >> >> > currently increments the refcnt on the sock in the sockmap to
>> >> >> > ensure it is not free'd by the stack before sockmap cleans up its
>> >> >> > state and stops any skbs being sent/recv'd to that socket.
>> >> >> >
>> >> >> > But we missed a case. If the peer socket is closed it will be
>> >> >> > free'd by the stack. However, the paired socket can still be
>> >> >> > referenced from BPF sockmap side because we hold a reference
>> >> >> > there. Then if we are sending traffic through BPF sockmap to
>> >> >> > that socket it will try to dereference the free'd pair in its
>> >> >> > send logic creating a use after free.  And following splat,
>> >> >> >
>> >> >> >    [59.900375] BUG: KASAN: slab-use-after-free in sk_wake_async+0x31/0x1b0
>> >> >> >    [59.901211] Read of size 8 at addr ffff88811acbf060 by task kworker/1:2/954
>> >> >> >    [...]
>> >> >> >    [59.905468] Call Trace:
>> >> >> >    [59.905787]  <TASK>
>> >> >> >    [59.906066]  dump_stack_lvl+0x130/0x1d0
>> >> >> >    [59.908877]  print_report+0x16f/0x740
>> >> >> >    [59.910629]  kasan_report+0x118/0x160
>> >> >> >    [59.912576]  sk_wake_async+0x31/0x1b0
>> >> >> >    [59.913554]  sock_def_readable+0x156/0x2a0
>> >> >> >    [59.914060]  unix_stream_sendmsg+0x3f9/0x12a0
>> >> >> >    [59.916398]  sock_sendmsg+0x20e/0x250
>> >> >> >    [59.916854]  skb_send_sock+0x236/0xac0
>> >> >> >    [59.920527]  sk_psock_backlog+0x287/0xaa0
>> >> >> 
>> >> >> Isn't the problem here that unix_stream_sendmsg doesn't grab a ref to
>> >> >> peer sock? Unlike unix_dgram_sendmsg which uses the unix_peer_get
>> >> >> helper.
>> >> >
>> >> > It does by my read. In unix_stream_connect we have,
>> >> >
>> >> > 	sock_hold(sk);
>> >> > 	unix_peer(newsk)	= sk;
>> >> > 	newsk->sk_state		= TCP_ESTABLISHED;
>> >> >
>> >> > where it assigns the peer sock. unix_dgram_connect() also calls
>> >> > sock_hold() but through the path that does the socket lookup, such as
>> >> > unix_find_other().
>> >> >
>> >> > The problem I see is before the socket does the kfree on the
>> >> > sock we need to be sure the backlog is canceled and the skb list
>> >> > ingress_skb is purged. If we don't ensure this then the redirect
>> >> > will 
>> >> >
>> >> > My model is this,
>> >> >
>> >> >          s1            c1
>> >> > refcnt    1             1
>> >> > connect   2             2
>> >> > psock     3             3
>> >> > send(s1) ...
>> >> > close(s1) 2             1 <- close drops psock count also
>> >> > close(c1) 0             0
>> >> >
>> >> > The important bit here is the psock has a refcnt on the
>> >> > underlying sock (psock->sk) and wont dec that until after
>> >> > cancel_delayed_work_sync() completes. This ensures the
>> >> > backlog wont try to sendmsg() on that sock after we free
>> >> > it. We also check for SOCK_DEAD and abort to avoid sending
>> >> > over a socket that has been marked DEAD.
>> >> >
>> >> > So... After close(s1) the only thing keeping that sock
>> >> > around is c1. Then we close(c1) that call path is
>> >> >
>> >> >  unix_release
>> >> >    close() 
>> >> >    unix_release_sock()
>> >> >      skpair = unix_peer(sk);
>> >> >      ...
>> >> >      sock_put(skpair);  <- trouble here
>> >> >
>> >> > The release will call sock_put() on the pair socket and
>> >> > dec it to 0 where it gets free'd through sk_free(). But
>> >> > now the trouble is we haven't waited for cancel_delayed_work_sync()
>> >> > on the c1 socket yet so backlog can still run. When it does
>> >> > run it may try to send a pkg over socket s1. OK right up until
>> >> > the sendmsg(s1, ...) does a peer lookup and derefs the peer
>> >> > socket. The peer socket was free'd earlier so use after free. 
>> >> >
>> >> > The question I had originally was this is odd, we are allowing
>> >> > a sendmsg(s1) over a socket while its in unix_release(). We
>> >> > used to take the sock lock from the backlog that was dropped
>> >> > in the name of performance, but it creates these races.
>> >> >
>> >> > Other fixes I considered. First adding sock lock back to
>> >> > backlog. But that punishes the UDP and TCP cases that don't
>> >> > have this problem. Set the SOCK_DEAD flag earlier or check
>> >> > later but this just makes the race smaller doesn't really
>> >> > eliminate it.
>> >> >
>> >> > So this patch is what I came up with. 
>> >> 
>> >> What I was getting at is that we could make it safe to call sendmsg on a
>> >> unix stream sock while its peer is being release. And not just for
>> >> sockmap. I expect io_uring might have the same problem. But I didn't
>> >> actually check yet.
>> >> 
>> >> For that we could keep a ref to peer for the duration of sendmsg call,
>> >> like unix dgram does. Then 'other' doesn't become a stale pointer before
>> >> we're done with it.
>> >> 
>> >> Bumping ref count on each sendmsg is not free, but maybe its
>> >> acceptable. Unix dgram sockets live with it.
>> >
>> > The reason why only dgram sk needs sock_hold() for each sendmsg() is
>> > that dgram sk can send data without connect().  unix_peer_get() in
>> > unix_dgram_sendmsg() is to reuse the same code when peer is not set.
>> >
>> > unix_stream_sendmsg() already holds a necessary refcnt and need not
>> > use sock_hold() there.
>> >
>> > The user who touches a peer without lookup must hold refcnt beforehand.
>
> Hi, we probably do need to get a fix for this. syzkaller hit it again
> and anyways it likely will crash some real systems if folks try to use
> it with enough systems.
>
>> 
>> Right. And this ownership scheme works well for unix stream because, as
>> John nicely explained, we serialize close() and sendmsg() ops with sock
>> lock.
>> 
>> Here, however, we have a case of deferred work which holds a ref to sock
>> but does not grab the sock lock. While it is doing its thing, the sk
>> gets closed/released and we drop the skpair ref. And bam, UAF.
>> 
>> If it wasn't for the reference cycle between sk and skpair, we could
>> defer the skpari ref drop until sk_destruct callback. But we can't.
>> 
>> If grabbing a ref on skpair on each sendmsg turns out to be not a viable
>> option, I didn't run any benchmarks so can't say what's the penatly
>> like, the next best thing is RCU.
>
> I think it really would be best to stay out of the presumably hotpath
> here if we can.
>
> I had considered marking the socket SOCK_RCU_FREE which should then
> wait an rcu grace period. But then it wasn't clear to me that would
> completely solve the race. The psock still needs to do the 
> cancel_delayed_work_sync() and this is also done from the rcu call
> back on the psock. Withtout the extra reference iirc the concern
> was we would basically have two rcu callbacks running that have
> an ordering requirement which I don't think is ensured.
>

I've checked io_uring and it keeps a ref to the related file for the
lifetime the I/O request. So I think we are good there and it's only
sockmap that is "bleeding".

I agree it would be best not to hamper unix_stream sendmsg performance.

At the same time, I think we can easily make the extra ref grab in
unix_stream_sendmsg optional, keeping the fast path fast (modulo 2x a
branch op).

I realize RCU would be a bigger, riskier overhaul. Perhaps not worth it,
if there are no benefits for "the regular" unix_stream users.

If we can avoid managing more state in psock, that would be my
preference. But I don't want to block any fixes that users are waiting
for.
Jakub Sitnicki Nov. 6, 2023, 12:35 p.m. UTC | #8
On Mon, Oct 16, 2023 at 12:08 PM -07, John Fastabend wrote:
> AF_UNIX sockets are a paired socket. So sending on one of the pairs
> will lookup the paired socket as part of the send operation. It is
> possible however to put just one of the pairs in a BPF map. This
> currently increments the refcnt on the sock in the sockmap to
> ensure it is not free'd by the stack before sockmap cleans up its
> state and stops any skbs being sent/recv'd to that socket.
>
> But we missed a case. If the peer socket is closed it will be
> free'd by the stack. However, the paired socket can still be
> referenced from BPF sockmap side because we hold a reference
> there. Then if we are sending traffic through BPF sockmap to
> that socket it will try to dereference the free'd pair in its
> send logic creating a use after free.  And following splat,
>
>    [59.900375] BUG: KASAN: slab-use-after-free in sk_wake_async+0x31/0x1b0
>    [59.901211] Read of size 8 at addr ffff88811acbf060 by task kworker/1:2/954
>    [...]
>    [59.905468] Call Trace:
>    [59.905787]  <TASK>
>    [59.906066]  dump_stack_lvl+0x130/0x1d0
>    [59.908877]  print_report+0x16f/0x740
>    [59.910629]  kasan_report+0x118/0x160
>    [59.912576]  sk_wake_async+0x31/0x1b0
>    [59.913554]  sock_def_readable+0x156/0x2a0
>    [59.914060]  unix_stream_sendmsg+0x3f9/0x12a0
>    [59.916398]  sock_sendmsg+0x20e/0x250
>    [59.916854]  skb_send_sock+0x236/0xac0
>    [59.920527]  sk_psock_backlog+0x287/0xaa0
>
> To fix let BPF sockmap hold a refcnt on both the socket in the
> sockmap and its paired socket.  It wasn't obvious how to contain
> the fix to bpf_unix logic. The primarily problem with keeping this
> logic in bpf_unix was: In the sock close() we could handle the
> deref by having a close handler. But, when we are destroying the
> psock through a map delete operation we wouldn't have gotten any
> signal thorugh the proto struct other than it being replaced.
> If we do the deref from the proto replace its too early because
> we need to deref the skpair after the backlog worker has been
> stopped.
>
> Given all this it seems best to just cache it at the end of the
> psock and eat 8B for the af_unix and vsock users.
>
> Fixes: 94531cfcbe79 ("af_unix: Add unix_stream_proto for sockmap")
> Signed-off-by: John Fastabend <john.fastabend@gmail.com>
> ---
>  include/linux/skmsg.h |  1 +
>  include/net/af_unix.h |  1 +
>  net/core/skmsg.c      |  2 ++
>  net/unix/af_unix.c    |  2 --
>  net/unix/unix_bpf.c   | 10 ++++++++++
>  5 files changed, 14 insertions(+), 2 deletions(-)
>

[...]

> diff --git a/net/unix/af_unix.c b/net/unix/af_unix.c
> index 3e8a04a13668..87dd723aacf9 100644
> --- a/net/unix/af_unix.c
> +++ b/net/unix/af_unix.c
> @@ -212,8 +212,6 @@ static inline bool unix_secdata_eq(struct scm_cookie *scm, struct sk_buff *skb)
>  }
>  #endif /* CONFIG_SECURITY_NETWORK */
>  
> -#define unix_peer(sk) (unix_sk(sk)->peer)
> -
>  static inline int unix_our_peer(struct sock *sk, struct sock *osk)
>  {
>  	return unix_peer(osk) == sk;
> diff --git a/net/unix/unix_bpf.c b/net/unix/unix_bpf.c
> index 2f9d8271c6ec..705eeed10be3 100644
> --- a/net/unix/unix_bpf.c
> +++ b/net/unix/unix_bpf.c
> @@ -143,6 +143,8 @@ static void unix_stream_bpf_check_needs_rebuild(struct proto *ops)
>  
>  int unix_dgram_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore)
>  {
> +	struct sock *skpair;
> +
>  	if (sk->sk_type != SOCK_DGRAM)
>  		return -EOPNOTSUPP;
>  
> @@ -152,6 +154,9 @@ int unix_dgram_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool re
>  		return 0;
>  	}
>  
> +	skpair = unix_peer(sk);
> +	sock_hold(skpair);
> +	psock->skpair = skpair;
>  	unix_dgram_bpf_check_needs_rebuild(psock->sk_proto);
>  	sock_replace_proto(sk, &unix_dgram_bpf_prot);
>  	return 0;

unix_dgram should not need this, since it grabs a ref on each sendmsg.

I'm not able to reproduce this bug for unix_dgram.

Have you seen any KASAN reports for unix_dgram from syzcaller?

> @@ -159,12 +164,17 @@ int unix_dgram_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool re
>  
>  int unix_stream_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore)
>  {
> +	struct sock *skpair = unix_peer(sk);
> +
>  	if (restore) {
>  		sk->sk_write_space = psock->saved_write_space;
>  		sock_replace_proto(sk, psock->sk_proto);
>  		return 0;
>  	}
>  
> +	skpair = unix_peer(sk);
> +	sock_hold(skpair);
> +	psock->skpair = skpair;
>  	unix_stream_bpf_check_needs_rebuild(psock->sk_proto);
>  	sock_replace_proto(sk, &unix_stream_bpf_prot);
>  	return 0;
Martin KaFai Lau Nov. 20, 2023, 9:13 p.m. UTC | #9
On 11/6/23 4:35 AM, Jakub Sitnicki wrote:
>> diff --git a/net/unix/unix_bpf.c b/net/unix/unix_bpf.c
>> index 2f9d8271c6ec..705eeed10be3 100644
>> --- a/net/unix/unix_bpf.c
>> +++ b/net/unix/unix_bpf.c
>> @@ -143,6 +143,8 @@ static void unix_stream_bpf_check_needs_rebuild(struct proto *ops)
>>   
>>   int unix_dgram_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore)
>>   {
>> +	struct sock *skpair;
>> +
>>   	if (sk->sk_type != SOCK_DGRAM)
>>   		return -EOPNOTSUPP;
>>   
>> @@ -152,6 +154,9 @@ int unix_dgram_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool re
>>   		return 0;
>>   	}
>>   
>> +	skpair = unix_peer(sk);
>> +	sock_hold(skpair);
>> +	psock->skpair = skpair;
>>   	unix_dgram_bpf_check_needs_rebuild(psock->sk_proto);
>>   	sock_replace_proto(sk, &unix_dgram_bpf_prot);
>>   	return 0;
> unix_dgram should not need this, since it grabs a ref on each sendmsg.

John, could you address this comment and respin v2?

The unix_inet_redir_to_connected() seems needing a fix in patch 2 also as 
pointed out by JakubS.

Thanks.

> 
> I'm not able to reproduce this bug for unix_dgram.
> 
> Have you seen any KASAN reports for unix_dgram from syzcaller?
John Fastabend Nov. 21, 2023, 8:40 p.m. UTC | #10
Martin KaFai Lau wrote:
> On 11/6/23 4:35 AM, Jakub Sitnicki wrote:
> >> diff --git a/net/unix/unix_bpf.c b/net/unix/unix_bpf.c
> >> index 2f9d8271c6ec..705eeed10be3 100644
> >> --- a/net/unix/unix_bpf.c
> >> +++ b/net/unix/unix_bpf.c
> >> @@ -143,6 +143,8 @@ static void unix_stream_bpf_check_needs_rebuild(struct proto *ops)
> >>   
> >>   int unix_dgram_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore)
> >>   {
> >> +	struct sock *skpair;
> >> +
> >>   	if (sk->sk_type != SOCK_DGRAM)
> >>   		return -EOPNOTSUPP;
> >>   
> >> @@ -152,6 +154,9 @@ int unix_dgram_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool re
> >>   		return 0;
> >>   	}
> >>   
> >> +	skpair = unix_peer(sk);
> >> +	sock_hold(skpair);
> >> +	psock->skpair = skpair;
> >>   	unix_dgram_bpf_check_needs_rebuild(psock->sk_proto);
> >>   	sock_replace_proto(sk, &unix_dgram_bpf_prot);
> >>   	return 0;
> > unix_dgram should not need this, since it grabs a ref on each sendmsg.
> 
> John, could you address this comment and respin v2?

Respinning now just letting some tests run for a bit and I'll kick it out.

Thanks.

> 
> The unix_inet_redir_to_connected() seems needing a fix in patch 2 also as 
> pointed out by JakubS.
> 
> Thanks.
> 
> > 
> > I'm not able to reproduce this bug for unix_dgram.
> > 
> > Have you seen any KASAN reports for unix_dgram from syzcaller?
John Fastabend Nov. 22, 2023, 7:26 p.m. UTC | #11
John Fastabend wrote:
> Martin KaFai Lau wrote:
> > On 11/6/23 4:35 AM, Jakub Sitnicki wrote:
> > >> diff --git a/net/unix/unix_bpf.c b/net/unix/unix_bpf.c
> > >> index 2f9d8271c6ec..705eeed10be3 100644
> > >> --- a/net/unix/unix_bpf.c
> > >> +++ b/net/unix/unix_bpf.c
> > >> @@ -143,6 +143,8 @@ static void unix_stream_bpf_check_needs_rebuild(struct proto *ops)
> > >>   
> > >>   int unix_dgram_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore)
> > >>   {
> > >> +	struct sock *skpair;
> > >> +
> > >>   	if (sk->sk_type != SOCK_DGRAM)
> > >>   		return -EOPNOTSUPP;
> > >>   
> > >> @@ -152,6 +154,9 @@ int unix_dgram_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool re
> > >>   		return 0;
> > >>   	}
> > >>   
> > >> +	skpair = unix_peer(sk);
> > >> +	sock_hold(skpair);
> > >> +	psock->skpair = skpair;
> > >>   	unix_dgram_bpf_check_needs_rebuild(psock->sk_proto);
> > >>   	sock_replace_proto(sk, &unix_dgram_bpf_prot);
> > >>   	return 0;
> > > unix_dgram should not need this, since it grabs a ref on each sendmsg.
> > 
> > John, could you address this comment and respin v2?
> 
> Respinning now just letting some tests run for a bit and I'll kick it out.


v2 on the list. Unfortunately the simple fix to the selftests to test STREAM
and DGRAM types caused a test failure. I look at it Monday unless someone
beats me to it.

> 
> Thanks.
> 
> > 
> > The unix_inet_redir_to_connected() seems needing a fix in patch 2 also as 
> > pointed out by JakubS.
> > 
> > Thanks.
> > 
> > > 
> > > I'm not able to reproduce this bug for unix_dgram.
> > > 
> > > Have you seen any KASAN reports for unix_dgram from syzcaller?
diff mbox series

Patch

diff --git a/include/linux/skmsg.h b/include/linux/skmsg.h
index c1637515a8a4..fbe628961cf8 100644
--- a/include/linux/skmsg.h
+++ b/include/linux/skmsg.h
@@ -106,6 +106,7 @@  struct sk_psock {
 	struct mutex			work_mutex;
 	struct sk_psock_work_state	work_state;
 	struct delayed_work		work;
+	struct sock			*skpair;
 	struct rcu_work			rwork;
 };
 
diff --git a/include/net/af_unix.h b/include/net/af_unix.h
index 824c258143a3..49c4640027d8 100644
--- a/include/net/af_unix.h
+++ b/include/net/af_unix.h
@@ -75,6 +75,7 @@  struct unix_sock {
 };
 
 #define unix_sk(ptr) container_of_const(ptr, struct unix_sock, sk)
+#define unix_peer(sk) (unix_sk(sk)->peer)
 
 #define peer_wait peer_wq.wait
 
diff --git a/net/core/skmsg.c b/net/core/skmsg.c
index 6c31eefbd777..6236164b9bce 100644
--- a/net/core/skmsg.c
+++ b/net/core/skmsg.c
@@ -826,6 +826,8 @@  static void sk_psock_destroy(struct work_struct *work)
 
 	if (psock->sk_redir)
 		sock_put(psock->sk_redir);
+	if (psock->skpair)
+		sock_put(psock->skpair);
 	sock_put(psock->sk);
 	kfree(psock);
 }
diff --git a/net/unix/af_unix.c b/net/unix/af_unix.c
index 3e8a04a13668..87dd723aacf9 100644
--- a/net/unix/af_unix.c
+++ b/net/unix/af_unix.c
@@ -212,8 +212,6 @@  static inline bool unix_secdata_eq(struct scm_cookie *scm, struct sk_buff *skb)
 }
 #endif /* CONFIG_SECURITY_NETWORK */
 
-#define unix_peer(sk) (unix_sk(sk)->peer)
-
 static inline int unix_our_peer(struct sock *sk, struct sock *osk)
 {
 	return unix_peer(osk) == sk;
diff --git a/net/unix/unix_bpf.c b/net/unix/unix_bpf.c
index 2f9d8271c6ec..705eeed10be3 100644
--- a/net/unix/unix_bpf.c
+++ b/net/unix/unix_bpf.c
@@ -143,6 +143,8 @@  static void unix_stream_bpf_check_needs_rebuild(struct proto *ops)
 
 int unix_dgram_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore)
 {
+	struct sock *skpair;
+
 	if (sk->sk_type != SOCK_DGRAM)
 		return -EOPNOTSUPP;
 
@@ -152,6 +154,9 @@  int unix_dgram_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool re
 		return 0;
 	}
 
+	skpair = unix_peer(sk);
+	sock_hold(skpair);
+	psock->skpair = skpair;
 	unix_dgram_bpf_check_needs_rebuild(psock->sk_proto);
 	sock_replace_proto(sk, &unix_dgram_bpf_prot);
 	return 0;
@@ -159,12 +164,17 @@  int unix_dgram_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool re
 
 int unix_stream_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore)
 {
+	struct sock *skpair = unix_peer(sk);
+
 	if (restore) {
 		sk->sk_write_space = psock->saved_write_space;
 		sock_replace_proto(sk, psock->sk_proto);
 		return 0;
 	}
 
+	skpair = unix_peer(sk);
+	sock_hold(skpair);
+	psock->skpair = skpair;
 	unix_stream_bpf_check_needs_rebuild(psock->sk_proto);
 	sock_replace_proto(sk, &unix_stream_bpf_prot);
 	return 0;