// SPDX-License-Identifier: GPL-2.0-or-later
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#define SSH_PORT 22
#define MAX_CONN_ATTEMPTS 3
#define RATE_LIMIT_INTERVAL 30 // seconds
#define MAX_ACTIVE_CONNECTIONS 3
#define SSH_VERSION_STRING "SSH-2.0-"
#define SSH_VERSION_STRING_LEN 8
struct bpf_map_def SEC("maps") conn_states = {
.type = BPF_MAP_TYPE_HASH,
.key_size = sizeof(__u64), // Combined src IP and src port
.value_size = sizeof(__u8),
.max_entries = 1024,
};
struct conn_attempt {
__u32 count;
__u64 last_time;
};
struct bpf_map_def SEC("maps") rate_limit_map = {
.type = BPF_MAP_TYPE_HASH,
.key_size = sizeof(__u32), // Source IP
.value_size = sizeof(struct conn_attempt),
.max_entries = 1024,
};
struct bpf_map_def SEC("maps") active_conns = {
.type = BPF_MAP_TYPE_HASH,
.key_size = sizeof(__u32), // Source IP
.value_size = sizeof(__u32),
.max_entries = 1024,
};
struct bpf_map_def SEC("maps") xdp_stats_map = {
.type = BPF_MAP_TYPE_PERCPU_ARRAY,
.key_size = sizeof(__u32),
.value_size = sizeof(__u64),
.max_entries = 1,
};
static __always_inline int parse_ethhdr(struct xdp_md *ctx, void **data, void **data_end, struct ethhdr **ethhdr) {
*ethhdr = *data;
if ((void *)(*ethhdr + 1) > *data_end)
return -1;
return (*ethhdr)->h_proto; // Return Ethernet protocol
}
static __always_inline int parse_iphdr(void **data, void **data_end, struct iphdr **iphdr) {
*iphdr = *data;
if ((void *)(*iphdr + 1) > *data_end)
return -1;
if ((*iphdr)->ihl < 5)
return -1;
if ((void *)(*iphdr + (*iphdr)->ihl) > *data_end)
return -1;
return (*iphdr)->protocol; // Return IP protocol
}
static __always_inline int parse_tcphdr(void **data, void **data_end, struct tcphdr **tcphdr) {
*tcphdr = *data;
if ((void *)(*tcphdr + 1) > *data_end)
return -1;
if ((void *)(*tcphdr + (*tcphdr)->doff) > *data_end)
return -1;
return 0;
}
static __always_inline int validate_ssh_protocol(void *data, void *data_end, struct tcphdr *tcph) {
void *app_data = (void *)(tcph + 1);
if (app_data >= data_end)
return -1;
// Check for SSH version string in the payload
int payload_len = data_end - app_data;
if (payload_len < SSH_VERSION_STRING_LEN)
return -1;
char ssh_version[SSH_VERSION_STRING_LEN];
if (bpf_probe_read_kernel(&ssh_version, SSH_VERSION_STRING_LEN, app_data) < 0)
return -1;
for (int i = 0; i < SSH_VERSION_STRING_LEN; i++) {
if (ssh_version[i] != SSH_VERSION_STRING[i])
return -1;
}
return 0;
}
SEC("xdp")
int xdp_ssh_filter(struct xdp_md *ctx) {
void *data = (void *)(long)ctx->data;
void *data_end = (void *)(long)ctx->data_end;
struct ethhdr *eth;
int eth_proto = parse_ethhdr(ctx, &data, &data_end, ð);
if (eth_proto == -1 || eth_proto != bpf_htons(ETH_P_IP))
goto drop_packet;
data += sizeof(struct ethhdr);
struct iphdr *ip;
int ip_proto = parse_iphdr(&data, &data_end, &ip);
if (ip_proto == -1 || ip_proto != IPPROTO_TCP)
goto drop_packet;
data += ip->ihl * 4;
struct tcphdr *tcp;
if (parse_tcphdr(&data, &data_end, &tcp) < 0)
goto drop_packet;
__u16 dport = bpf_ntohs(tcp->dest);
__u16 sport = bpf_ntohs(tcp->source);
// Only allow packets destined for port 22
if (dport != SSH_PORT)
goto drop_packet;
__u32 src_ip = ip->saddr;
__u64 current_time = bpf_ktime_get_ns();
// Rate limiting per IP address
struct conn_attempt *attempt;
attempt = bpf_map_lookup_elem(&rate_limit_map, &src_ip);
if (attempt) {
if ((current_time - attempt->last_time) / 1000000000ULL <= RATE_LIMIT_INTERVAL) {
if (attempt->count >= MAX_CONN_ATTEMPTS)
goto drop_packet;
else
attempt->count++;
} else {
attempt->count = 1;
attempt->last_time = current_time;
}
} else {
struct conn_attempt new_attempt = {};
new_attempt.count = 1;
new_attempt.last_time = current_time;
bpf_map_update_elem(&rate_limit_map, &src_ip, &new_attempt, BPF_ANY);
}
// Limit active SSH connections per IP
__u32 *active_conn = bpf_map_lookup_elem(&active_conns, &src_ip);
if (active_conn) {
if (*active_conn >= MAX_ACTIVE_CONNECTIONS)
goto drop_packet;
} else {
__u32 init_conn = 0;
bpf_map_update_elem(&active_conns, &src_ip, &init_conn, BPF_ANY);
}
// Stateful connection tracking
__u64 flow_key = ((__u64)src_ip << 32) | (__u64)sport;
__u8 *state = bpf_map_lookup_elem(&conn_states, &flow_key);
if (tcp->syn && !tcp->ack) {
// New connection attempt
__u8 conn_state = 1; // SYN sent
bpf_map_update_elem(&conn_states, &flow_key, &conn_state, BPF_ANY);
} else if (tcp->syn && tcp->ack) {
// SYN-ACK received
if (state && *state == 1) {
*state = 2; // SYN-ACK received
} else {
goto drop_packet;
}
} else if (tcp->ack) {
if (state && (*state == 1 || *state == 2)) {
*state = 3; // Established
// Increment active connections
__u32 *active_conn = bpf_map_lookup_elem(&active_conns, &src_ip);
if (active_conn)
(*active_conn)++;
} else if (!state) {
goto drop_packet;
}
} else if (tcp->fin || tcp->rst) {
// Connection closing
if (state) {
bpf_map_delete_elem(&conn_states, &flow_key);
// Decrement active connections
__u32 *active_conn = bpf_map_lookup_elem(&active_conns, &src_ip);
if (active_conn && *active_conn > 0)
(*active_conn)--;
}
} else {
// Invalid TCP flags
goto drop_packet;
}
// Deep packet inspection for SSH protocol validation
if (validate_ssh_protocol(data, data_end, tcp) < 0)
goto drop_packet;
// Allow packet
return XDP_PASS;
drop_packet:
// Track XDP_DROP actions
__u32 key = 0;
__u64 *value = bpf_map_lookup_elem(&xdp_stats_map, &key);
if (value)
(*value)++;
return XDP_DROP;
}
char _license[] SEC("license") = "GPL";
Explanation:
This eBPF XDP program implements the required functionality step by step:
-
Port 22 Restriction: It checks if the destination port of the TCP packet is port 22 (SSH).
-
Automatic Stateful Packet Inspection:
- It uses a hash map
conn_states to track the state of each connection based on a flow key combining source IP and source port.
- It monitors SYN, SYN-ACK, ACK packets to enforce correct TCP handshake sequences.
- It updates or deletes the connection state accordingly.
-
Dropping Invalid and Non-SSH Packets:
- If packets don't conform to the expected TCP flags sequence, they are dropped.
- If the packet is invalid or malformed (e.g., headers extend beyond the packet data), it is dropped.
-
Full SSH Protocol Validation:
- The
validate_ssh_protocol function checks the application payload for the SSH version string.
- It reads the beginning of the payload to ensure it matches "SSH-2.0-".
-
Deep Packet Inspection for SSH Protocol Validation:
- By examining the payload after the TCP header, it performs DPI to validate the SSH handshake process.
-
SSH Connection Rate Limiting:
- The
rate_limit_map tracks the number of connection attempts per IP.
- It allows up to 3 connection attempts per 30 seconds per IP address.
-
Limiting Active SSH Connections:
- The
active_conns map keeps count of active connections per IP.
- It limits the number of active SSH connections to 3 per IP address.
-
Tracking and Logging XDP Drops:
- The
xdp_stats_map tracks the number of packets that are dropped using XDP_DROP.
- This allows for monitoring and logging drop statistics.
Security and Efficiency Considerations:
Deployment Notes:
- This program should be compiled using
clang with eBPF targets and loaded into the kernel using tools like ip or tc.
- Ensure that the system supports eBPF and XDP, and has the necessary headers and permissions.
- The maps can be pinned to the BPF filesystem for user-space interaction if needed.
Limitations:
-
Simplified SSH Validation: The SSH protocol is complex. This code only checks for the SSH version string in the initial payload. Full protocol validation would require more extensive parsing, which may not be feasible in XDP.
-
State Table Size: The maps have a fixed size (max_entries), which limits the number of concurrent connections it can track. Adjust as needed for your environment.
-
Per-IP Limitations: The rate limiting and active connection tracking are done per source IP, which may not work as intended if clients are behind NAT.
Conclusion:
This eBPF XDP program incorporates all your specified requirements, emphasizing security and efficiency. It leverages eBPF features to provide high-performance packet processing directly in the kernel, filtering and monitoring SSH traffic effectively.