• Joe Stringer's avatar
    bpf: Add helper to retrieve socket in BPF · 6acc9b43
    Joe Stringer authored
    This patch adds new BPF helper functions, bpf_sk_lookup_tcp() and
    bpf_sk_lookup_udp() which allows BPF programs to find out if there is a
    socket listening on this host, and returns a socket pointer which the
    BPF program can then access to determine, for instance, whether to
    forward or drop traffic. bpf_sk_lookup_xxx() may take a reference on the
    socket, so when a BPF program makes use of this function, it must
    subsequently pass the returned pointer into the newly added sk_release()
    to return the reference.
    
    By way of example, the following pseudocode would filter inbound
    connections at XDP if there is no corresponding service listening for
    the traffic:
    
      struct bpf_sock_tuple tuple;
      struct bpf_sock_ops *sk;
    
      populate_tuple(ctx, &tuple); // Extract the 5tuple from the packet
      sk = bpf_sk_lookup_tcp(ctx, &tuple, sizeof tuple, netns, 0);
      if (!sk) {
        // Couldn't find a socket listening for this traffic. Drop.
        return TC_ACT_SHOT;
      }
      bpf_sk_release(sk, 0);
      return TC_ACT_OK;
    Signed-off-by: default avatarJoe Stringer <joe@wand.net.nz>
    Acked-by: default avatarAlexei Starovoitov <ast@kernel.org>
    Signed-off-by: default avatarDaniel Borkmann <daniel@iogearbox.net>
    6acc9b43
bpf_helpers.h 13.4 KB