LIVE β€’ TECH, ENTERPRISE ERP & RETAIL AI JOURNAL
🌐id
βš–οΈIndependent Research • Verified Affiliate Transparency
Cloud VPS6 min read

Linux XDP eBPF & Go Controller Experiment on KVM VPS

Architectural exploration of packet filtering with eBPF XDP and Go controller on KVM VPS, evaluating generic vs native modes and virtio limits.

IP
By Iswan Putera β€’ November 23, 2026 09:07 WIB
Linux XDP eBPF & Go Controller Experiment on KVM VPS

When backend microservices handle high arrival rates of incoming network packets on Cloud VPS instances, traditional packet processing overhead inside the Linux kernel can become a notable bottleneck. Conventional layer-3 and layer-4 filtering with iptables or nftables requires the kernel to allocate an sk_buff (socket buffer) data structure for every incoming packet. Under intense packet bursts or SYN floods, memory allocations and context switches consume vital CPU cycles before packets ever reach application user space.

As an architectural pattern at the edge of the operating system, eXpress Data Path (XDP) powered by eBPF (Extended Berkeley Packet Filter) enables custom bytecode execution directly within the network driver tierβ€”filtering or dropping packets before full sk_buff allocation takes place.

Why Netfilter Incurs Overhead Under Saturated Packet Traffic

Standard Linux networking prioritizes rich stateful tracking and general-purpose flexibility. In standard packet ingestion:

  1. The Network Interface Card (NIC) receives an Ethernet frame and triggers a Hardware Interrupt (IRQ).
  2. The driver allocates an sk_buff in kernel memory to encapsulate the packet payload.
  3. The kernel triggers NET_RX_SOFTIRQ to feed the packet into the Netfilter subsystem.
  4. iptables / nftables evaluate rule sets sequentially across chains.
  5. If accepted, the packet transitions to the socket layer and triggers a context switch to user space.

This sequence incurs notable CPU cycles. When an instance receives hundreds of thousands of unsolicited packets per second, CPU cores spend significant capacity managing memory allocations for packets that are ultimately discarded.

By contrast, XDP introduces an execution hook inside the driver layer prior to sk_buff construction. The eBPF program receives an xdp_md context pointing directly to the DMA ring buffer. Decisions to pass (XDP_PASS) or drop (XDP_DROP) execute early with minimal memory footprint.

Table 1: Architectural Capacity Modeling on KVM VPS (Virtio-Net)

Estimates based on Architectural Capacity Modeling on KVM VPS (2-4 Dedicated vCPU, virtio-net driver, Linux kernel 6.x). Actual throughput depends on whether the hypervisor allows native driver XDP or falls back to generic XDP.

Architectural Dimension Netfilter (iptables) Netfilter (nftables) Linux eBPF XDP (Generic / VirtIO)
Execution Point Post sk_buff allocation Post sk_buff allocation Pre sk_buff (Native) / Early SKB (Generic)
Allocation Cost Full sk_buff structure Full sk_buff structure Zero/Minimal DMA buffer access
Rule Complexity Sequential O(N) Binary tree / Hash O(Log N) BPF Hash Map O(1)
Estimated Drop Capacity ~250,000–350,000 PPS ~450,000–600,000 PPS ~900,000–1,400,000 PPS (Generic mode)
Privilege Requirements CAP_NET_ADMIN CAP_NET_ADMIN CAP_BPF + CAP_NET_ADMIN (Root)
Protection Scope L3/L4 Stateful + NAT L3/L4 Stateful + NAT + Sets L2–L4 Stateless Filter & Rate Limiter
  • Execution Point β€” Netfilter (iptables): Post sk_buff allocation | Netfilter (nftables): Post sk_buff allocation | Linux eBPF XDP (Generic / VirtIO): Pre sk_buff (Native) / Early SKB (Generic)
  • Allocation Cost β€” Netfilter (iptables): Full sk_buff structure | Netfilter (nftables): Full sk_buff structure | Linux eBPF XDP (Generic / VirtIO): Zero/Minimal DMA buffer access
  • Rule Complexity β€” Netfilter (iptables): Sequential O(N) | Netfilter (nftables): Binary tree / Hash O(Log N) | Linux eBPF XDP (Generic / VirtIO): BPF Hash Map O(1)
  • Estimated Drop Capacity β€” Netfilter (iptables): ~250,000–350,000 PPS | Netfilter (nftables): ~450,000–600,000 PPS | Linux eBPF XDP (Generic / VirtIO): ~900,000–1,400,000 PPS (Generic mode)
  • Privilege Requirements β€” Netfilter (iptables): CAP_NET_ADMIN | Netfilter (nftables): CAP_NET_ADMIN | Linux eBPF XDP (Generic / VirtIO): CAP_BPF + CAP_NET_ADMIN (Root)
  • Protection Scope β€” Netfilter (iptables): L3/L4 Stateful + NAT | Netfilter (nftables): L3/L4 Stateful + NAT + Sets | Linux eBPF XDP (Generic / VirtIO): L2–L4 Stateless Filter & Rate Limiter

It is important to emphasize: XDP does not replace nftables. XDP serves as an early-stage stateless filter to shed raw packet floods, whereas nftables or reverse proxies such as Traefik v3 remain responsible for stateful connection tracking and layer-7 authorization.


System Environment & Toolchain Prerequisites

To compile eBPF C programs and manage them via a Go controller, ensure your environment provides the necessary toolchain. We recommend testing on modern distributions (Ubuntu 22.04/24.04 LTS or Debian 12) deployed on Hostinger KVM VPS infrastructure running Linux kernel 5.15+ or 6.x.

Installing Build Dependencies

Run the following command in your terminal to install Clang, LLVM, libbpf, and kernel development headers:

sudo apt update && sudo apt install -y \
  clang \
  llvm \
  libbpf-dev \
  linux-headers-$(uname -r) \
  build-essential \
  golang-go \
  pkg-config

Kernel C Snippet: eBPF XDP Filter (xdp_filter.c)

Below is the kernel C eBPF snippet implementing IP blacklisting via BPF Hash Map and token bucket rate-limiting.

[!IMPORTANT] SSH Port 22 Protection: Driver-level packet filtering must explicitly verify and allow TCP port 22 traffic before drop logic evaluates, preventing administrative lockouts on remote VPS instances.

// +build ignore
#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/in.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>

#define MAX_ENTRIES 65536
#define RATE_LIMIT_TOKENS 1000
#define REFILL_INTERVAL_NS 1000000000ULL // 1 second in nanoseconds

struct token_bucket {
    __u64 last_update;
    __u64 tokens;
};

// Map 1: IPv4 Blacklist (IP -> Status)
struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, MAX_ENTRIES);
    __type(key, __u32);
    __type(value, __u8);
} ip_blacklist SEC(".maps");

// Map 2: Rate Limit Bucket per IP
struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, MAX_ENTRIES);
    __type(key, __u32);
    __type(value, struct token_bucket);
} rate_limit_map SEC(".maps");

SEC("xdp")
int xdp_firewall_prog(struct xdp_md *ctx) {
    void *data_end = (void *)(long)ctx->data_end;
    void *data = (void *)(long)ctx->data;

    // 1. Layer 2 Ethernet Header Bounds Check
    struct ethhdr *eth = data;
    if ((void *)(eth + 1) > data_end)
        return XDP_PASS;

    if (eth->h_proto != bpf_htons(ETH_P_IP))
        return XDP_PASS;

    // 2. Layer 3 IPv4 Header Bounds Check
    struct iphdr *iph = (void *)(eth + 1);
    if ((void *)(iph + 1) > data_end)
        return XDP_PASS;

    // 3. SSH PORT 22 SAFEGUARD - Prevent Remote Lockout
    if (iph->protocol == IPPROTO_TCP) {
        struct tcphdr *tcph = (void *)iph + (iph->ihl * 4);
        if ((void *)(tcph + 1) <= data_end) {
            if (tcph->dest == bpf_htons(22) || tcph->source == bpf_htons(22)) {
                return XDP_PASS;
            }
        }
    }

    __u32 src_ip = iph->saddr;

    // 4. Evaluate IP Blacklist via BPF Map Lookup (O(1))
    __u8 *blocked = bpf_map_lookup_elem(&ip_blacklist, &src_ip);
    if (blocked && *blocked == 1) {
        return XDP_DROP;
    }

    // 5. Evaluate Token Bucket Rate Limiting
    __u64 now = bpf_ktime_get_ns();
    struct token_bucket *bucket = bpf_map_lookup_elem(&rate_limit_map, &src_ip);

    if (!bucket) {
        struct token_bucket new_bucket = {
            .last_update = now,
            .tokens = RATE_LIMIT_TOKENS - 1
        };
        bpf_map_update_elem(&rate_limit_map, &src_ip, &new_bucket, BPF_ANY);
        return XDP_PASS;
    }

    __u64 time_passed = now - bucket->last_update;
    if (time_passed > REFILL_INTERVAL_NS) {
        bucket->tokens = RATE_LIMIT_TOKENS;
        bucket->last_update = now;
    }

    if (bucket->tokens > 0) {
        bucket->tokens--;
        return XDP_PASS;
    }

    return XDP_DROP;
}

char _license[] SEC("license") = "GPL";

User-Space Controller Snippet: Go (cilium/ebpf)

To update filtering rules dynamically without restarting kernel programs, we utilize github.com/cilium/ebpf within a Go controller (main.go).

package main

import (
	"fmt"
	"net"
	"os"
	"os/signal"
	"syscall"

	"github.com/cilium/ebpf/link"
	"github.com/cilium/ebpf/rlimit"
)

//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -target bpf xdpFilter xdp_filter.c

func ipToUint32(ipStr string) (uint32, error) {
	ip := net.ParseIP(ipStr).To4()
	if ip == nil {
		return 0, fmt.Errorf("invalid IPv4 string: %s", ipStr)
	}
	return uint32(ip[0]) | uint32(ip[1])<<8 | uint32(ip[2])<<16 | uint32(ip[3])<<24, nil
}

func main() {
	// 1. Raise RLIMIT_MEMLOCK so eBPF maps can allocate memory
	if err := rlimit.RemoveMemlock(); err != nil {
		fmt.Printf("Failed to set rlimit memlock: %v\n", err)
		os.Exit(1)
	}

	// 2. Load compiled eBPF objects
	objs := xdpFilterObjects{}
	if err := loadXdpFilterObjects(&objs, nil); err != nil {
		fmt.Printf("Failed to load eBPF objects: %v\n", err)
		os.Exit(1)
	}
	defer objs.Close()

	// 3. Attach XDP program to network interface (e.g., eth0)
	ifaceName := "eth0"
	iface, err := net.InterfaceByName(ifaceName)
	if err != nil {
		fmt.Printf("Failed to resolve interface %s: %v\n", ifaceName, err)
		os.Exit(1)
	}

	// For virtualized VPS instances (VirtIO), use XDPGenericMode as reliable fallback
	l, err := link.AttachXDP(link.XDPOptions{
		Program:   objs.XdpFirewallProg,
		Interface: iface.Index,
		Flags:     link.XDPGenericMode,
	})
	if err != nil {
		fmt.Printf("Failed to attach XDP program: %v\n", err)
		os.Exit(1)
	}
	defer l.Close()

	fmt.Printf("Controller attached to %s in Generic Mode. Listening for signals...\n", ifaceName)

	// 4. Inject IP into BPF Blacklist Map dynamically
	targetIP := "198.51.100.45"
	ipVal, err := ipToUint32(targetIP)
	if err == nil {
		var flag uint8 = 1
		if err := objs.IpBlacklist.Put(ipVal, flag); err == nil {
			fmt.Printf("Successfully injected %s into kernel blacklist map.\n", targetIP)
		}
	}

	// Handle graceful termination
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
	<-sig

	fmt.Println("\nDetaching XDP program and exiting gracefully...")
}

Verification Commands & Recovery Runbook

1. Compilation and Execution

Execute the following commands in your Linux server terminal:

# Generate BPF Go bindings
go generate

# Build controller binary
go build -o ebpf-controller main.go

# Execute with root privileges
sudo ./ebpf-controller

2. Checking Interface Hook Status

Verify that the hook is attached to the interface:

ip link show dev eth0

Successful attachment displays the xdpgeneric or xdp flag:

2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 xdpgeneric qdisc fq_codel state UP ...
    prog/xdp id 42 name xdp_firewall_pr

3. Emergency Procedure: Detaching XDP

If unexpected connectivity loss occurs, immediately detach the XDP program:

# Detach XDP program from eth0
sudo ip link set dev eth0 xdp off

# If attached in generic mode
sudo ip link set dev eth0 xdpgeneric off

Technical Limitations & Production Considerations

Implementing eBPF XDP in Cloud VPS environments introduces specific constraints:

  • VirtIO Driver Mode (Generic vs Native): Cloud VPS providers typically virtualize network hardware via virtio_net. Native driver mode (XDPDriverMode) requires physical NIC driver hooks. In standard KVM instances, programs attach via XDPGenericMode. While generic mode executes after initial SKB allocation, it remains substantially faster than sequential Netfilter traversal.
  • Stateless Operations: XDP operates statelessly. For stateful connection tracking, complex L7 filtering, or TLS termination, pair XDP with reverse proxies and nftables.
  • Kernel Verifier Rigor: Packet pointers must be verified before dereferencing (data + offset > data_end). A single missing bounds check causes the Linux kernel verifier to reject program loading.

Deploying eBPF XDP at the ingress boundary provides a robust mechanism to shed raw packet surges, protecting core compute resources for application workloads.

Reliable KVM VPS infrastructure ensures a stable environment for these advanced kernel experiments.

Transparency: Some links in this article are affiliate links that support our independent technical research at no additional cost to you.


Primary Sources & Technical Documentation

IP

Iswan Putera

Principal Software Architect

Software Architect & Senior Systems Engineer with over a decade of hands-on expertise in distributed architectures, Linux private cloud deployments, and enterprise ERP implementations. Serves as Lead Technology Writer at Bijak Technology.

Share
Related Tags:#Cloud VPS#Linux#eBPF#Microservices#DevOps#Go#Hostinger