[PATCH net] tls: fix use-after-free in tls_sw_sendmsg() cork error path

Sechang Lim posted 1 patch 2 days, 7 hours ago
net/tls/tls_sw.c | 1 +
1 file changed, 1 insertion(+)
[PATCH net] tls: fix use-after-free in tls_sw_sendmsg() cork error path
Posted by Sechang Lim 2 days, 7 hours ago
tls_sw_sendmsg_locked() caches a pointer into the open record:

	rec    = ctx->open_rec;
	msg_pl = &rec->msg_plaintext;

and keeps using msg_pl after bpf_exec_tx_verdict(). When an attached
SK_MSG bpf program calls bpf_msg_apply_bytes(), tls_push_record() splits the
open record: the original record is encrypted, queued and freed by
tls_tx_records(), while ctx->open_rec is replaced by the split remainder.
If the bpf program also sets cork_bytes, bpf_exec_tx_verdict() then returns
-ENOSPC, and the error path dereferences the now-dangling msg_pl:

	else if (ctx->open_rec && ret == -ENOSPC) {
		if (msg_pl->cork_bytes) {	/* use-after-free */

  BUG: KASAN: slab-use-after-free in tls_sw_sendmsg+0x118d/0x16f0
  Read of size 4 at addr ffff88810a36f2ac by task syz.0.17/2056
  CPU: 1 UID: 0 PID: 2056 Comm: syz.0.17 Not tainted 7.1.0-rc6 #2
  Call Trace:
   tls_sw_sendmsg+0x118d/0x16f0
   __sock_sendmsg+0xe4/0x130
   __sys_sendto+0x2fe/0x3f0
   __x64_sys_sendto+0x7b/0x90
   do_syscall_64+0x14c/0x480
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

  Allocated by task 2056:
   tls_get_rec+0x7a/0x3d0
   tls_sw_sendmsg+0x3cd/0x16f0
   __sock_sendmsg+0xe4/0x130
   __sys_sendto+0x2fe/0x3f0

  Freed by task 2056:
   kfree+0x163/0x560
   tls_tx_records+0x2d6/0x380
   bpf_exec_tx_verdict+0x3de/0xd50
   tls_sw_sendmsg+0x10e9/0x16f0
   __sock_sendmsg+0xe4/0x130
   __sys_sendto+0x2fe/0x3f0

ctx->open_rec already points at the live record on this path, so re-fetch
msg_pl from it before use.

Fixes: 54a3ecaeeeae ("bpf: fix ktls panic with sockmap")
Signed-off-by: Sechang Lim <rhkrqnwk98@gmail.com>
---
 net/tls/tls_sw.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/net/tls/tls_sw.c b/net/tls/tls_sw.c
index 964ebc268ee4..39dee66cc99b 100644
--- a/net/tls/tls_sw.c
+++ b/net/tls/tls_sw.c
@@ -1165,6 +1165,7 @@ static int tls_sw_sendmsg_locked(struct sock *sk, struct msghdr *msg,
 				else if (ret == -ENOMEM)
 					goto wait_for_memory;
 				else if (ctx->open_rec && ret == -ENOSPC) {
+					msg_pl = &ctx->open_rec->msg_plaintext;
 					if (msg_pl->cork_bytes) {
 						ret = 0;
 						goto send_end;
-- 
2.43.0