Course contentsShow
← Linux
Lesson 1185 of 1,81910. Network Administration and Kernel StacksFree lesson

Socket-Level BPF Hooks

Attach BPF logic directly to sockets for application-specific processing.

In this lesson, you will learn how to attach BPF logic directly to specific application sockets to perform granular packet processing without the overhead of global network filters.

Why Hook at the Socket?

So far, we have looked at filtering at the XDP or Traffic Control (TC) layers. While powerful, those hooks see every packet hitting the network interface. When you need to enforce logic specific to a single application—such as a custom protocol parser or per-connection authentication—processing every global packet is inefficient.

Socket-level BPF hooks allow you to attach programs directly to a struct sock. By attaching here, the BPF program only executes when packets are associated with that specific socket file descriptor. This moves the logic from the "global ingress" path into the "application context," providing a massive performance boost for localized tasks.

The Mechanism

You typically use the BPF_PROG_TYPE_SOCKET_FILTER type. When you attach a program to a socket, the kernel runs your BPF code for every packet received by that socket. Your program can inspect the packet data, perform math, or make decisions (like dropping the packet or allowing it) by returning a value:

SEC("socket_filter")
int my_socket_filter(struct __sk_buff *skb) {
    // Only accept packets if they meet our criteria
    if (skb->len < 64) 
        return 0; // Drop small packets
    
    return -1; // Allow the packet to reach the application
}

Practical Application

Imagine a high-performance database service. Instead of filtering all traffic at the TC layer and trying to identify which packets belong to the database, you attach a BPF filter directly to the database’s listening socket. If the BPF program detects an unauthorized command pattern within the packet payload, it drops the packet instantly. Because the filter is bound to the socket, you don’t need to worry about cross-talk from other services running on the same host. This isolation simplifies your logic and ensures your firewalling rules stay relevant to the specific data being processed by the application.

Key Takeaway: Socket-level BPF hooks provide a dedicated execution path for individual applications, enabling high-performance, per-connection traffic inspection without needing to parse global network traffic.