UDP Tunnel with eBPF
Here's a complete implementation of a UDP tunnel using eBPF that encapsulates packets with a custom header (0xDEADBEEF) on egress and decapsulates them on ingress.
Solution Overview
We'll create two eBPF programs:
- XDP program for ingress processing (decapsulation)
- Cilium-style socket filter for egress processing (encapsulation)
Implementation
1. eBPF Program (C code)
// udp_tunnel.bpf.c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/udp.h>
// Custom header structure
struct custom_hdr {
__be32 label; // 0xDEADBEEF
};
// Packet parsing helpers
static inline int parse_ipv4(void *data, u64 nh_off, void *data_end, struct iphdr **iph) {
*iph = data + nh_off;
if (*iph + 1 > data_end)
return -1;
if ((*iph)->version != 4)
return -1;
if ((*iph)->ihl < 5)
return -1;
nh_off += (*iph)->ihl * 4;
if (data + nh_off > data_end)
return -1;
return nh_off;
}
// XDP program for ingress (decapsulation)
SEC("xdp_ingress")
int xdp_ingress(struct xdp_md *ctx) {
void *data = (void *)(long)ctx->data;
void *data_end = (void *)(long)ctx->data_end;
struct ethhdr *eth = data;
if (eth + 1 > data_end)
return XDP_DROP;
if (eth->h_proto != bpf_htons(ETH_P_IP))
return XDP_PASS;
struct iphdr *ip;
int nh_off = sizeof(*eth);
nh_off = parse_ipv4(data, nh_off, data_end, &ip);
if (nh_off < 0)
return XDP_DROP;
if (ip->protocol != IPPROTO_UDP)
return XDP_PASS;
struct udphdr *udp = (void *)ip + (ip->ihl * 4);
if (udp + 1 > data_end)
return XDP_DROP;
// Check if it's our tunnel port (6996)
if (udp->dest != bpf_htons(6996))
return XDP_PASS;
// Check if we have enough space for our custom header
if ((void *)udp + sizeof(*udp) + sizeof(struct custom_hdr) > data_end)
return XDP_DROP;
// Verify custom header
struct custom_hdr *custom = (void *)udp + sizeof(*udp);
if (custom->label != bpf_htonl(0xDEADBEEF))
return XDP_DROP;
// Remove UDP header and custom header
void *inner_packet = (void *)custom + sizeof(*custom_hdr);
int inner_len = bpf_ntohs(udp->len) - sizeof(*udp) - sizeof(*custom_hdr);
// Adjust packet pointers
if (bpf_xdp_adjust_head(ctx, -(int)(sizeof(*eth) + sizeof(*ip) + sizeof(*udp) + sizeof(*custom_hdr))))
return XDP_DROP;
// Update packet data
data = (void *)(long)ctx->data;
data_end = (void *)(long)ctx->data_end;
// Copy inner packet to the beginning
if (bpf_xdp_load_bytes(ctx, inner_packet - data, data, inner_len))
return XDP_DROP;
// Adjust packet length
if (bpf_xdp_adjust_tail(ctx, -(int)(data_end - (data + inner_len))))
return XDP_DROP;
return XDP_TX;
}
// Socket filter for egress (encapsulation)
SEC("socket_filter_egress")
int socket_filter_egress(struct __sk_buff *skb) {
// Get packet data
void *data = (void *)(long)skb->data;
void *data_end = (void *)(long)skb->data_end;
// Check if we have enough space for encapsulation
if (data_end - data < sizeof(struct iphdr) + sizeof(struct udphdr) + sizeof(struct custom_hdr)) {
return 0; // Let it pass through normally
}
// Create new UDP header
struct udphdr udp = {
.source = bpf_htons(12345), // Random source port
.dest = bpf_htons(6996), // Our tunnel port
.len = bpf_htons((data_end - data) + sizeof(struct udphdr) + sizeof(struct custom_hdr)),
.check = 0, // Will be calculated by kernel
};
// Create custom header
struct custom_hdr custom = {
.label = bpf_htonl(0xDEADBEEF),
};
// Calculate new packet length
int new_len = data_end - data + sizeof(struct udphdr) + sizeof(struct custom_hdr);
// Check if we can expand the packet
if (skb->len + new_len > skb->len_max) {
return 0; // Let it pass through normally
}
// Move packet data to make room for new headers
if (bpf_skb_store_bytes(skb, sizeof(struct udphdr) + sizeof(struct custom_hdr),
data, data_end - data, 0))
return 0;
// Store UDP header
if (bpf_skb_store_bytes(skb, 0, &udp, sizeof(udp), 0))
return 0;
// Store custom header
if (bpf_skb_store_bytes(skb, sizeof(struct udphdr), &custom, sizeof(custom), 0))
return 0;
// Update packet length
skb->len = new_len;
return 0; // Let the packet continue processing
}
char _license[] SEC("license") = "GPL";
2. User-space Loader (Go)
// main.go
package main
import (
"log"
"os"
"os/signal"
"syscall"
"github.com/cilium/ebpf"
"github.com/cilium/ebpf/link"
"github.com/cilium/ebpf/rlimit"
)
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc clang -cflags "-O2 -g -Wall -Werror" udpTunnel udp_tunnel.bpf.c -- -I../../headers
func main() {
// Remove resource limits for kernels <5.11
if err := rlimit.RemoveMemlock(); err != nil {
log.Fatal("Removing memlock:", err)
}
// Load the compiled eBPF ELF and load it into the kernel
objs := udpTunnelObjects{}
if err := loadUdpTunnelObjects(&objs, nil); err != nil {
log.Fatal("Loading eBPF objects:", err)
}
defer objs.Close()
// Attach XDP program to ingress interface
iface := "eth0" // Change to your interface
xdp, err := link.AttachXDP(link.XDPOptions{
Program: objs.XdpIngress,
Interface: iface,
})
if err != nil {
log.Fatal("Attaching XDP:", err)
}
defer xdp.Close()
log.Printf("Attached XDP program to %s\n", iface)
// Attach socket filter to egress
// Note: This is a simplified approach. In production, you might want to use
// a more sophisticated method like Cilium's socket-based redirection.
_, err = link.AttachSocketFilter(link.SocketFilterOptions{
Program: objs.SocketFilterEgress,
})
if err != nil {
log.Fatal("Attaching socket filter:", err)
}
log.Println("Attached socket filter for egress")
// Wait for interrupt signal
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
<-sig
log.Println("Received signal, exiting...")
}
3. Makefile
# Makefile
all: generate load
generate:
go generate
load:
go run main.go
clean:
rm -f udp_tunnel.bpf.o udp_tunnel.bpf.h
How It Works
Egress (Encapsulation)
- The socket filter program intercepts outgoing packets
- It prepends a UDP header (port 6996) and custom header (0xDEADBEEF)
- The packet continues through the normal network stack
Ingress (Decapsulation)
- The XDP program intercepts incoming packets on the specified interface
- It checks for UDP packets with destination port 6996
- It verifies the custom header (0xDEADBEEF)
- It removes the UDP and custom headers, leaving the original packet
- The original packet continues through the network stack
Deployment
-
Install dependencies:
go get github.com/cilium/ebpf/cmd/bpf2go
go get github.com/cilium/ebpf
-
Build and run:
make
-
Test the tunnel:
- Send packets through the interface where XDP is attached
- Verify they get encapsulated on egress and decapsulated on ingress
Notes
-
This is a basic implementation. For production use, you should:
- Add more error handling
- Implement proper checksum calculation
- Add configuration options for the tunnel port and label
- Consider using BPF maps for stateful processing
-
The socket filter approach for egress is simplified. In a real-world scenario, you might want to use more sophisticated methods like Cilium's socket-based redirection.
-
You'll need root privileges to load eBPF programs and attach them to interfaces.
-
The interface name ("eth0") should be changed to match your system's network interface.