The code you've provided is an eBPF program intended to run in the XDP (eXpress Data Path) context. It aims to inspect incoming TCP packets on port 22 (SSH), maintain connection states, apply rate limiting, enforce active connection limits, and validate custom SSH protocol parameters. However, there are several issues in the code that will prevent it from functioning correctly. I'll walk you through the main problems and suggest how to address them.
1. Incorrect Use of Helper Functions in XDP Context
Issue: The code uses bpf_skb_load_bytes, which is not available in XDP programs. This helper function is intended for use with socket filters (e.g., TC programs), not XDP.
Solution: In XDP programs, you should directly access packet data using pointers derived from ctx->data and ctx->data_end. Here's how you can modify your code:
- Replace
bpf_skb_load_bytes with direct packet data access.
- Ensure that all pointers are within the bounds of
ctx->data and ctx->data_end to prevent illegal memory access, which would cause the eBPF verifier to reject the program.
Example:
static inline struct ethhdr *get_ethhdr(struct xdp_md *ctx)
{
void *data_end = (void *)(long)ctx->data_end;
void *data = (void *)(long)ctx->data;
struct ethhdr *eth = data;
if ((void *)(eth + 1) > data_end)
return NULL;
return eth;
}
static inline struct iphdr *get_iphdr(struct xdp_md *ctx)
{
struct ethhdr *eth = get_ethhdr(ctx);
if (!eth)
return NULL;
void *data_end = (void *)(long)ctx->data_end;
struct iphdr *ip = (void *)(eth + 1);
if ((void *)(ip + 1) > data_end)
return NULL;
return ip;
}
static inline struct tcphdr *get_tcphdr(struct xdp_md *ctx)
{
struct iphdr *ip = get_iphdr(ctx);
if (!ip)
return NULL;
if (ip->protocol != IPPROTO_TCP)
return NULL;
void *data_end = (void *)(long)ctx->data_end;
struct tcphdr *tcp = (void *)(ip + 1);
if ((void *)tcp + sizeof(struct tcphdr) > data_end)
return NULL;
return tcp;
}
2. Incorrect Extraction of TCP Flags
Issue: The function get_tcp_flags is attempting to retrieve TCP flags by performing a bitwise OR on individual flag fields (tcphdr.syn | tcphdr.ack | tcphdr.fin | ...), which doesn't yield the correct flags.
Solution: The TCP flags are stored within a specific field in the tcphdr struct. You should access the flags directly and return them appropriately.
Example:
static inline uint8_t get_tcp_flags(struct tcphdr *tcph)
{
return ((__u8 *)tcph)[13]; // Offset 13 bytes from the start of the TCP header
}
Alternatively, you can access the flags using bitfields if your environment supports it:
static inline uint8_t get_tcp_flags(struct tcphdr *tcph)
{
return *((uint8_t *)&tcph->ack_seq + 13 - 8); // Adjusting for the struct layout
}
But the direct byte access is generally safer in the eBPF context.
3. Multiple Redundant Lookups and Potential Null Pointer Dereference
Issue: In your code, after checking if state is NULL, you perform another lookup instead of initializing a new state. This redundancy doesn't fulfill the intended logic and could lead to a null pointer dereference.
Original Code:
struct conn_state *state = bpf_map_lookup_elem(&conn_state_map, &key);
if (!state) {
state = bpf_map_lookup_elem(&conn_state_map, &key);
if (!state) {
struct conn_state new_state = { .state = SYN_SENT };
bpf_map_update_elem(&conn_state_map, &key, &new_state, BPF_ANY);
}
}
Corrected Code:
struct conn_state *state = bpf_map_lookup_elem(&conn_state_map, &key);
if (!state) {
struct conn_state new_state = { .state = SYN_SENT };
bpf_map_update_elem(&conn_state_map, &key, &new_state, BPF_ANY);
state = &new_state; // Now use new_state
}
Remember that since eBPF programs can't persist local variables across invocations, you can't simply assign state = &new_state. Instead, you need to perform the lookup again after updating:
struct conn_state new_state = { .state = SYN_SENT };
bpf_map_update_elem(&conn_state_map, &key, &new_state, BPF_ANY);
state = bpf_map_lookup_elem(&conn_state_map, &key);
if (!state)
return XDP_ABORTED; // Should not happen
4. Incorrect Handling of Connection States and TCP Flags
Issue: The logic handling connection states and TCP flags doesn't align with the TCP state machine and may lead to unintended packet drops.
Solution: Revise the state machine logic to accurately reflect TCP connection states and respond appropriately to different TCP flag combinations.
Example Logic:
uint8_t flags = get_tcp_flags(tcph);
if (flags & TCP_SYN) {
if (!(flags & TCP_ACK)) {
// This is a SYN packet initiating a connection
// Update state to SYN_SENT
} else {
// This is a SYN-ACK packet
// Update state to SYN_RECV
}
} else if (flags & TCP_ACK) {
// This is an ACK packet
// Update state to ESTABLISHED
} else if (flags & TCP_FIN) {
// This is a FIN packet closing a connection
// Update state accordingly
}
5. Rate Limiting Logic
Issue: Your rate limiting logic increments conn_attempts for every packet, including retransmissions and non-SYN packets, which may not be an accurate reflection of connection attempts.
Solution: Only increment conn_attempts when a new connection attempt is detected (e.g., when a SYN packet without the ACK flag is received).
Example:
if (flags == TCP_SYN) {
uint32_t *conn_attempts = bpf_map_lookup_elem(&conn_attempts_map, &key.src_ip);
uint32_t attempts = conn_attempts ? *conn_attempts : 0;
attempts++;
bpf_map_update_elem(&conn_attempts_map, &key.src_ip, &attempts, BPF_ANY);
if (attempts > MAX_CONN_ATTEMPTS) {
// Trigger rate limiting action
}
}
6. Active Connections Tracking
Issue: Similar to the rate limiting logic, active connections should be tracked based on the establishment and teardown of connections, not on every packet.
Solution: Increment active_conns when a connection is established (e.g., upon receipt of an ACK for a SYN-ACK) and decrement it when the connection is closed (e.g., when a FIN is acknowledged).
Example:
if (state->state == ESTABLISHED && flags & TCP_FIN) {
// Decrement active connections
uint32_t *active_conns = bpf_map_lookup_elem(&active_conns_map, &key.src_ip);
if (active_conns && *active_conns > 0) {
(*active_conns)--;
bpf_map_update_elem(&active_conns_map, &key.src_ip, active_conns, BPF_ANY);
}
}
7. Parsing the SSH Payload
Issue: Directly parsing the SSH payload without proper bounds checking can lead to invalid memory access.
Solution: Before accessing the payload, ensure that the buffer is within the packet bounds. Use pointer arithmetic carefully, considering the sizes of the Ethernet, IP, and TCP headers.
Example:
static inline int parse_ssh_payload(struct xdp_md *ctx, struct cursor *c)
{
void *data_end = (void *)(long)ctx->data_end;
struct ssh_payload *payload = (struct ssh_payload *)c->pos;
if ((void *)(payload + 1) > data_end)
return -1;
// Validate SSH protocol version
if (memcmp(payload->protocol_version, SSH_PROTOCOL_VERSION, SSH_PROTOCOL_VERSION_LEN) != 0)
return -1;
// Additional parsing...
return 0;
}
8. Handling Non-SSH Traffic
Issue: The code drops all traffic that isn't on port 22. While this might be intentional, it's generally better to pass non-SSH traffic unless you have a specific reason to drop it.
Solution: Modify the initial port check to pass other traffic.
if (dst_port != 22) {
return XDP_PASS;
}
9. Map Definitions and Compatibility
Issue: The map definitions using struct bpf_map_def and SEC("maps") annotations are outdated. Modern eBPF tooling uses BPF skeletons and the libbpf library for map definitions.
Solution: Update map definitions to be compatible with the latest eBPF toolchain.
Example:
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 1024);
__type(key, struct conn_key);
__type(value, struct conn_state);
} conn_state_map SEC(".maps");
10. Licensing and ELF Sections
Issue: Ensure that the license is set correctly and that the ELF sections are appropriately named.
Solution: Make sure to include the correct license and section annotations.
char LICENSE[] SEC("license") = "GPL";
Summary of Recommendations
- Replace
bpf_skb_load_bytes with direct packet access methods suitable for XDP programs.
- Correct the extraction of TCP flags.
- Revise the connection state machine logic to accurately reflect TCP behavior.
- Update the rate limiting and active connection tracking to trigger on appropriate events.
- Ensure safe parsing of the SSH payload with proper bounds checking.
- Modify the handling of non-SSH traffic to pass it through unless there's a specific need to drop it.
- Update map definitions to conform with the latest eBPF standards.
- Confirm that all ELF sections and licenses are correctly specified for eBPF program compliance.
By addressing these issues, your eBPF XDP program should function as intended, enforcing SSH protocol validation, rate limiting, and connection limits effectively.
If you need further assistance implementing these changes or have additional questions, feel free to ask!