Sure! Below is the complete eBPF XDP script that implements the advanced SSH packet inspection and filtering as per your instructions. I've included the Makefile you'll use to compile the script, and I've provided detailed instructions on how to run it on an Ubuntu 22.04 machine.
eBPF XDP Script: xdp_ssh_filter.c
// xdp_ssh_filter.c
#include <linux/bpf.h>
#include <linux/pkt_cls.h>
#include "bpf_helpers.h"
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#define SEC(NAME) __attribute__((section(NAME), used))
// Map to track connection attempts per IP for rate limiting
struct bpf_map_def SEC("maps") connection_attempts = {
.type = BPF_MAP_TYPE_HASH,
.key_size = sizeof(__u32), // IP address
.value_size = sizeof(__u64), // Timestamp and count
.max_entries = 1024,
};
// Map to track active connections per IP
struct bpf_map_def SEC("maps") active_connections = {
.type = BPF_MAP_TYPE_HASH,
.key_size = sizeof(__u32), // IP address
.value_size = sizeof(__u32), // Connection count
.max_entries = 1024,
};
// Map to count XDP_DROP actions
struct bpf_map_def SEC("maps") xdp_drop_counter = {
.type = BPF_MAP_TYPE_ARRAY,
.key_size = sizeof(__u32),
.value_size = sizeof(__u64),
.max_entries = 1,
};
// Helper function to convert network byte order to host byte order
static __always_inline __u16 ntohs(__u16 x) {
return __builtin_bswap16(x);
}
SEC("xdp")
int xdp_ssh_filter_prog(struct xdp_md *ctx)
{
// Parsing packet headers
void *data_end = (void *)(long)ctx->data_end;
void *data = (void *)(long)ctx->data;
// Ethernet header
struct ethhdr *eth = data;
if ((void *)(eth + 1) > data_end)
return XDP_DROP;
// Only IPv4 packets
if (ntohs(eth->h_proto) != ETH_P_IP)
return XDP_PASS;
// IP header
struct iphdr *ip = data + sizeof(struct ethhdr);
if ((void *)(ip + 1) > data_end)
return XDP_DROP;
// Only TCP packets
if (ip->protocol != IPPROTO_TCP)
return XDP_PASS;
// IP header length
__u32 ip_header_length = ip->ihl * 4;
// TCP header
struct tcphdr *tcp = (void *)ip + ip_header_length;
if ((void *)(tcp + 1) > data_end)
return XDP_DROP;
// Only packets destined to port 22 (SSH)
if (ntohs(tcp->dest) != 22)
return XDP_DROP;
// Source IP address
__u32 src_ip = ip->saddr;
// Current time in nanoseconds
__u64 current_time = bpf_ktime_get_ns();
// Implement rate limiting (3 connections per 30 seconds per IP)
if (tcp->syn && !tcp->ack) {
// New connection attempt
__u64 *attempt_value = bpf_map_lookup_elem(&connection_attempts, &src_ip);
__u64 attempt_time_count = 0;
if (attempt_value) {
__u64 last_time = *attempt_value >> 32;
__u32 count = *attempt_value & 0xFFFFFFFF;
if ((current_time - last_time) < 30 * 1e9) {
// Within 30 seconds window
if (count >= 3) {
// Exceeded connection attempts
// Increment XDP_DROP counter
__u32 index = 0;
__u64 *drop_count = bpf_map_lookup_elem(&xdp_drop_counter, &index);
if (drop_count)
__sync_fetch_and_add(drop_count, 1);
else {
__u64 init_val = 1;
bpf_map_update_elem(&xdp_drop_counter, &index, &init_val, BPF_ANY);
}
return XDP_DROP;
} else {
// Increment attempt count
count++;
attempt_time_count = (last_time << 32) | count;
}
} else {
// Reset attempt count
attempt_time_count = (current_time << 32) | 1;
}
} else {
// First attempt
attempt_time_count = (current_time << 32) | 1;
}
bpf_map_update_elem(&connection_attempts, &src_ip, &attempt_time_count, BPF_ANY);
}
// Enforce a cap on active SSH sessions (3 per IP)
if (tcp->syn && tcp->ack) {
// Connection established
__u32 *conn_count = bpf_map_lookup_elem(&active_connections, &src_ip);
__u32 new_conn_count = 1;
if (conn_count) {
if (*conn_count >= 3) {
// Exceeded active connections
// Increment XDP_DROP counter
__u32 index = 0;
__u64 *drop_count = bpf_map_lookup_elem(&xdp_drop_counter, &index);
if (drop_count)
__sync_fetch_and_add(drop_count, 1);
else {
__u64 init_val = 1;
bpf_map_update_elem(&xdp_drop_counter, &index, &init_val, BPF_ANY);
}
return XDP_DROP;
} else {
new_conn_count = *conn_count + 1;
}
}
bpf_map_update_elem(&active_connections, &src_ip, &new_conn_count, BPF_ANY);
}
if (tcp->fin || tcp->rst) {
// Connection closing
__u32 *conn_count = bpf_map_lookup_elem(&active_connections, &src_ip);
if (conn_count && *conn_count > 0) {
__u32 new_conn_count = *conn_count - 1;
bpf_map_update_elem(&active_connections, &src_ip, &new_conn_count, BPF_ANY);
}
}
// Drop invalid or non-SSH packets
// Basic SSH protocol validation (checking for "SSH-" in payload)
__u32 tcp_header_length = tcp->doff * 4;
void *tcp_payload = (void *)tcp + tcp_header_length;
if (tcp_payload >= data_end)
return XDP_DROP;
__u32 payload_size = data_end - tcp_payload;
if (payload_size > 4) {
char ssh_magic[4];
bpf_probe_read_kernel(ssh_magic, 4, tcp_payload);
if (!(ssh_magic[0] == 'S' && ssh_magic[1] == 'S' && ssh_magic[2] == 'H' && ssh_magic[3] == '-')) {
// Not SSH traffic
// Increment XDP_DROP counter
__u32 index = 0;
__u64 *drop_count = bpf_map_lookup_elem(&xdp_drop_counter, &index);
if (drop_count)
__sync_fetch_and_add(drop_count, 1);
else {
__u64 init_val = 1;
bpf_map_update_elem(&xdp_drop_counter, &index, &init_val, BPF_ANY);
}
return XDP_DROP;
}
}
return XDP_PASS;
}
char _license[] SEC("license") = "GPL";
Makefile
# Makefile
BPF_CLANG ?= clang
BPF_CFLAGS ?= -O2 -g -Wall \
-target bpf \
-I/usr/include/x86_64-linux-gnu
ALL_BIN := xdp_ssh_filter_kern.o
.PHONY: all clean
all: $(ALL_BIN)
%.o: %.c
$(BPF_CLANG) $(BPF_CFLAGS) -c $< -o $@
clean:
rm -f $(ALL_BIN)
Instructions to Run the Script on Ubuntu 22.04
Prerequisites
-
Update System Packages
sudo apt update
sudo apt upgrade -y
-
Install Required Packages
Install the necessary tools and headers for eBPF and XDP development:
sudo apt install -y clang llvm libbpf-dev libelf-dev linux-headers-$(uname -r) build-essential bpftool iproute2 net-tools
Compile the eBPF XDP Program
-
Save the eBPF Program
Create a file named xdp_ssh_filter.c and paste the eBPF XDP script code into it.
nano xdp_ssh_filter.c
Paste the code and save the file.
-
Create the Makefile
Create a file named Makefile in the same directory and paste the provided Makefile content.
nano Makefile
Paste the code and save the file.
-
Compile the eBPF Program
Run the following command to compile the eBPF program:
make
This will generate the object file xdp_ssh_filter_kern.o.
Attach the XDP Program to the Network Interface
-
Identify Your Network Interface
Use the ip link or ifconfig command to list your network interfaces:
ip link show
Identify the network interface you want to attach the XDP program to (e.g., eth0).
-
Attach the XDP Program
Use ip command to attach the XDP program:
sudo ip link set dev eth0 xdp obj xdp_ssh_filter_kern.o sec xdp
Replace eth0 with your network interface name.
Verify that the XDP Program is Loaded
Check if the XDP program is attached to the interface:
sudo ip -details link show dev eth0
You should see an xdp section indicating that the program is attached.
Monitoring XDP_DROP Actions
To track and log XDP_DROP actions, you'll use bpftool to read from the xdp_drop_counter map.
-
Find the Map ID
List all BPF maps:
sudo bpftool map
Look for the map named xdp_drop_counter and note its id.
-
Create a Monitoring Script
Create a script monitor_xdp_drop.sh to print the drop count every second:
nano monitor_xdp_drop.sh
Paste the following content:
#!/bin/bash
MAP_ID=$(sudo bpftool map | grep xdp_drop_counter | awk '{print $1}' | cut -d':' -f1)
while true; do
DROP_COUNT=$(sudo bpftool map dump id $MAP_ID | grep 'value' | awk '{print $2}')
echo "XDP_DROP count: $DROP_COUNT"
sleep 1
done
Make the script executable:
chmod +x monitor_xdp_drop.sh
-
Run the Monitoring Script
./monitor_xdp_drop.sh
This will print the XDP_DROP count every second.
Testing the Script
To test the script:
- Try connecting via SSH from different IP addresses and observe the behavior.
- Exceed the rate limit or active connection limit and observe that connections are dropped.
- Monitor the
XDP_DROP counter to see drops being recorded.
Detaching the XDP Program
When you want to remove the XDP program:
sudo ip link set dev eth0 xdp off
Important Notes
- Root Privileges Required: Running and attaching eBPF XDP programs requires root access.
- Networking Impact: Be careful when attaching XDP programs as misconfigurations can disrupt network traffic.
- Testing Environment: It's recommended to test this script in a controlled environment before deploying to production.
- Kernel Support: Ensure your kernel supports eBPF and XDP (Ubuntu 22.04's default kernel supports this).
Explanation of the Script
1. Port 22 Restriction
- The script checks if the TCP destination port is 22, which is the default SSH port.
- If the port is not 22, the packet is dropped (
return XDP_DROP).
2. Automatic Stateful Packet Inspection
- The script inspects TCP flags (
SYN, ACK, FIN, RST) to track connection states.
- It differentiates between new connection attempts, established connections, and connection terminations.
3. Dropping Invalid and Non-SSH Packets
- The script checks for malformed packets by validating header sizes and ensuring payloads are within packet boundaries.
- It performs a basic check on the TCP payload to see if it starts with
SSH-, indicating legitimate SSH traffic.
- Non-SSH packets are dropped.
4. Full SSH Protocol Validation
- Due to eBPF limitations, full SSH protocol validation cannot be performed.
- However, the script validates the initial SSH version exchange by checking the payload for the
SSH- string.
5. Deep Packet Inspection for SSH Protocol Validation
- The script attempts to read the first few bytes of the TCP payload to verify the SSH protocol initiation.
- Full deep packet inspection is limited in eBPF/XDP due to constraints like no loops and limited stack size.
6. SSH Connection Rate Limiting
- Uses a hash map (
connection_attempts) to track the number of connection attempts per IP within a 30-second window.
- If an IP exceeds 3 connection attempts within 30 seconds, further attempts are dropped.
7. Limiting Active SSH Connections
- Uses a hash map (
active_connections) to keep track of the number of active SSH sessions per IP.
- Limits the number of concurrent SSH connections to 3 per IP address.
8. Tracking and Logging XDP Drops
- Implements a counter (
xdp_drop_counter) to keep track of how many times XDP_DROP is invoked.
- The counter is stored in a BPF map and can be read using
bpftool or the provided monitoring script.
Additional Considerations
- Performance: The script is designed to be efficient and minimize performance impact on the system.
- Security: By dropping non-SSH traffic and enforcing strict connection limits, the script enhances the security of the SSH service.
- eBPF Limitations: eBPF programs have constraints (e.g., no loops, limited stack size). The script is crafted to work within these limitations.
Conclusion
The provided eBPF XDP script fulfills your requirements to the extent possible within the capabilities of eBPF. It includes advanced packet inspection, rate limiting, active connection limiting, and logging mechanisms.
By following the instructions, you should be able to compile and run the script on your Ubuntu 22.04 machine. Always ensure to test in a safe environment and monitor the effects on your network traffic when deploying such low-level networking scripts.