bpf: fix use-after-free of bpf_link when priming half-fails
Subsystems (4)
PATCH v2 1/1 bpf: fix use-after-free of bpf_link when priming half-fails
If bpf_link_prime() succeeds to allocate new anon file, but then fails to allocate ID for it, link priming is considered to be failed and user is supposed ot be able to directly kfree() bpf_link, because it was never exposed to user-space.
But at that point file already keeps a pointer to bpf_link and will eventually call bpf_link_release(), so if bpf_link was kfree()'d by caller, that would lead to use-after-free.
Fix this by first allocating ID and only then allocating file. Adding ID to link_idr is ok, because link at that point still doesn't have its ID set, so no user-space process can create a new FD for it.
--- kernel/bpf/syscall.c | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-)
kernel/bpf/syscall.c +7 -6
@@ -2348,19 +2348,20 @@ int bpf_link_prime(struct bpf_link *link, struct bpf_link_primer *primer)if (fd <0 )return fd; - file =anon_inode_getfile ("bpf_link" , &bpf_link_fops, link,O_CLOEXEC ); -if (IS_ERR (file)) { -put_unused_fd (fd); -return PTR_ERR (file); - } id =bpf_link_alloc_id (link);if (id <0 ) {put_unused_fd (fd); -fput (file);return id; } + file =anon_inode_getfile ("bpf_link" , &bpf_link_fops, link,O_CLOEXEC ); +if (IS_ERR (file)) { +bpf_link_free_id (id); +put_unused_fd (fd); +return PTR_ERR (file); + } + primer->link = link; primer->file = file; primer->fd = fd;
Signature · 1 line
2.24.1
Quoted 5 lines · Andrii Nakryiko
If
bpf_link_prime()succeeds to allocate new anon file, but then fails to allocate ID for it, link priming is considered to be failed and user is supposed ot be able to directlykfree()bpf_link, because it was never exposed to user-space.
Quoted 7 lines
But at that point file already keeps a pointer to
bpf_linkand will eventually callbpf_link_release(), so ifbpf_linkwas kfree()'d by caller, that would lead to use-after-free.Fix this by first allocating ID and only then allocating file. Adding ID to
link_idris ok, because link at that point still doesn't have its ID set, so no user-space process can create a new FD for it.
Alexei Starovoitov
AppliedQuoted 7 lines · Martin KaFai Lau
Quoted 5 lines · Andrii Nakryiko
If
bpf_link_prime()succeeds to allocate new anon file, but then fails to allocate ID for it, link priming is considered to be failed and user is supposed ot be able to directlykfree()bpf_link, because it was never exposed to user-space.
Quoted 8 lines
Quoted 7 lines
But at that point file already keeps a pointer to
bpf_linkand will eventually callbpf_link_release(), so ifbpf_linkwas kfree()'d by caller, that would lead to use-after-free.Fix this by first allocating ID and only then allocating file. Adding ID to
link_idris ok, because link at that point still doesn't have its ID set, so no user-space process can create a new FD for it.Acked-by Martin KaFai Lau <[email protected]>
Applied. Thanks