From: Alexei Starovoitov sk_clone() sets sk_refcnt of the new socket some lines behind bpf_sk_storage_clone(). But the elements which that function copies are linked to their maps at once, and an element leads to its owner: the iterator over a sk_storage map hands the owner to its program. bpf_sk_storage_get() with BPF_SK_STORAGE_GET_F_CREATE and bpf_sk_storage_delete() rely on refcount_inc_not_zero() to tell whether they may touch the socket. sk_refcnt is in the part of struct sock which sock_copy() leaves out, and sk_prot_alloc() does not clear a clone unless init_on_alloc is on. It is zero in an object which has been a socket before, and anything in one which has not. If it is not zero, a helper gets a reference which refcount_set() wipes out, and the helper's sock_put() then drops one of the two references of the new socket, which is freed too early: IPv4: Attempt to release TCP socket in state 1 BUG: KASAN: slab-use-after-free in __raw_spin_lock_init+0x47/0x90 In the meantime the helper changes a storage which bpf_sk_storage_clone() fills without taking its lock. Nothing else can find the clone at this point. Say that it is not alive yet, before the first element is linked. Sockets whose parent has no storage are left alone. Fixes: a50a85e40c59 ("bpf: Expose bpf_sk_storage_* to iterator programs") Suggested-by: Josef Bacik Signed-off-by: Alexei Starovoitov --- net/core/bpf_sk_storage.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/net/core/bpf_sk_storage.c b/net/core/bpf_sk_storage.c index 1d295a8769fa..b5349bec5695 100644 --- a/net/core/bpf_sk_storage.c +++ b/net/core/bpf_sk_storage.c @@ -164,6 +164,13 @@ int bpf_sk_storage_clone(const struct sock *sk, struct sock *newsk) if (!sk_storage || hlist_empty(&sk_storage->list)) goto out; + /* + * The maps lead to newsk as soon as an element is linked, but + * sk_clone() sets sk_refcnt only later. Until then it holds whatever + * the slab object held before: no reference can be had yet. + */ + refcount_set(&newsk->sk_refcnt, 0); + hlist_for_each_entry_rcu(selem, &sk_storage->list, snode) { struct bpf_local_storage_elem *copy_selem; struct bpf_local_storage_map *smap; -- 2.55.0