Commit 85b8ac01 authored by Lorenz Bauer's avatar Lorenz Bauer Committed by Daniel Borkmann

bpf, sockmap: Check update requirements after locking

It's currently possible to insert sockets in unexpected states into
a sockmap, due to a TOCTTOU when updating the map from a syscall.
sock_map_update_elem checks that sk->sk_state == TCP_ESTABLISHED,
locks the socket and then calls sock_map_update_common. At this
point, the socket may have transitioned into another state, and
the earlier assumptions don't hold anymore. Crucially, it's
conceivable (though very unlikely) that a socket has become unhashed.
This breaks the sockmap's assumption that it will get a callback
via sk->sk_prot->unhash.

Fix this by checking the (fixed) sk_type and sk_protocol without the
lock, followed by a locked check of sk_state.

Unfortunately it's not possible to push the check down into
sock_(map|hash)_update_common, since BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB
run before the socket has transitioned from TCP_SYN_RECV into
TCP_ESTABLISHED.

Fixes: 604326b4 ("bpf, sockmap: convert to generic sk_msg interface")
Signed-off-by: default avatarLorenz Bauer <lmb@cloudflare.com>
Signed-off-by: default avatarDaniel Borkmann <daniel@iogearbox.net>
Reviewed-by: default avatarJakub Sitnicki <jakub@cloudflare.com>
Link: https://lore.kernel.org/bpf/20200207103713.28175-1-lmb@cloudflare.com
parent b9e42724
...@@ -416,13 +416,15 @@ static int sock_map_update_elem(struct bpf_map *map, void *key, ...@@ -416,13 +416,15 @@ static int sock_map_update_elem(struct bpf_map *map, void *key,
ret = -EINVAL; ret = -EINVAL;
goto out; goto out;
} }
if (!sock_map_sk_is_suitable(sk) || if (!sock_map_sk_is_suitable(sk)) {
sk->sk_state != TCP_ESTABLISHED) {
ret = -EOPNOTSUPP; ret = -EOPNOTSUPP;
goto out; goto out;
} }
sock_map_sk_acquire(sk); sock_map_sk_acquire(sk);
if (sk->sk_state != TCP_ESTABLISHED)
ret = -EOPNOTSUPP;
else
ret = sock_map_update_common(map, idx, sk, flags); ret = sock_map_update_common(map, idx, sk, flags);
sock_map_sk_release(sk); sock_map_sk_release(sk);
out: out:
...@@ -739,13 +741,15 @@ static int sock_hash_update_elem(struct bpf_map *map, void *key, ...@@ -739,13 +741,15 @@ static int sock_hash_update_elem(struct bpf_map *map, void *key,
ret = -EINVAL; ret = -EINVAL;
goto out; goto out;
} }
if (!sock_map_sk_is_suitable(sk) || if (!sock_map_sk_is_suitable(sk)) {
sk->sk_state != TCP_ESTABLISHED) {
ret = -EOPNOTSUPP; ret = -EOPNOTSUPP;
goto out; goto out;
} }
sock_map_sk_acquire(sk); sock_map_sk_acquire(sk);
if (sk->sk_state != TCP_ESTABLISHED)
ret = -EOPNOTSUPP;
else
ret = sock_hash_update_common(map, key, sk, flags); ret = sock_hash_update_common(map, key, sk, flags);
sock_map_sk_release(sk); sock_map_sk_release(sk);
out: out:
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment