Forwarded: [PATCH] bpf: Fix use-after-free in bpf_raw_tp_link_dealloc

syzbot posted 1 patch 1 month, 3 weeks ago
There is a newer version of this series
include/linux/bpf.h  | 1 +
kernel/bpf/syscall.c | 2 +-
2 files changed, 2 insertions(+), 1 deletion(-)
Forwarded: [PATCH] bpf: Fix use-after-free in bpf_raw_tp_link_dealloc
Posted by syzbot 1 month, 3 weeks ago
For archival purposes, forwarding an incoming command email to
linux-kernel@vger.kernel.org, syzkaller-bugs@googlegroups.com.

***

Subject: [PATCH] bpf: Fix use-after-free in bpf_raw_tp_link_dealloc
Author: kartikey406@gmail.com

#syz test: git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git master

When a BPF raw tracepoint link is released, bpf_raw_tp_link_release()
calls bpf_probe_unregister(), which internally calls
tracepoint_probe_unregister(). This function performs an RCU-deferred
swap of the tracepoint's funcs array via call_rcu(), so that existing
readers can finish observing the old array (which still references the
link) before it is replaced.

Concurrently, bpf_link_put_direct() schedules its own call_rcu() to
invoke bpf_raw_tp_link_dealloc(). Since both call_rcu() calls are
issued at roughly the same time, the dealloc grace period can complete
before the tracepoint's internal grace period. When this happens,
kfree(raw_tp) runs while RCU readers can still reach the link via the
old funcs array, causing a use-after-free in __bpf_trace_run() when it
dereferences link->link.prog.

Fix this by replacing kfree(raw_tp) with kfree_rcu(raw_tp, rcu),
adding an rcu_head field to struct bpf_raw_tp_link. This ensures a
third grace period elapses before the memory is freed, guaranteeing
that all readers which could have observed the old funcs array have
completed before the link is released.

Reported-by: syzbot+59701a78e84b0bccfe1b@syzkaller.appspotmail.com
Closes: https://syzkaller.appspot.com/bug?extid=59701a78e84b0bccfe1b
Signed-off-by: Deepanshu Kartikey <kartikey406@gmail.com>
---
 include/linux/bpf.h  | 1 +
 kernel/bpf/syscall.c | 2 +-
 2 files changed, 2 insertions(+), 1 deletion(-)

diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index cd9b96434904..673d19b360a7 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -1893,6 +1893,7 @@ struct bpf_raw_tp_link {
 	struct bpf_link link;
 	struct bpf_raw_event_map *btp;
 	u64 cookie;
+	struct rcu_head rcu;
 };
 
 struct bpf_link_primer {
diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c
index dd89bf809772..b9dfc36d8a77 100644
--- a/kernel/bpf/syscall.c
+++ b/kernel/bpf/syscall.c
@@ -3790,7 +3790,7 @@ static void bpf_raw_tp_link_dealloc(struct bpf_link *link)
 	struct bpf_raw_tp_link *raw_tp =
 		container_of(link, struct bpf_raw_tp_link, link);
 
-	kfree(raw_tp);
+	kfree_rcu(raw_tp, rcu);
 }
 
 static void bpf_raw_tp_link_show_fdinfo(const struct bpf_link *link,
-- 
2.43.0