Programmable Flow Protection (Beta)·续1
uint8_t status;
uint64_t expiry;
int ret = get_src_ip_status(&status, &expiry);
// Check if status has expired
int64_t now = timestamp();
if (ret == 0 && expiry > 0 && (uint64_t)now > expiry) {
// Status expired, treat as new connection
ret = -1;
}
```
6. Handle verified source IPs.
The Programmable Flow Protection platform will drop packets from blocklisted IPs before the program is invoked. There is no need to explicitly handle the blocklisted case.
If the source IP has been verified (passed a previous challenge), allow the packet through.
```c
if (ret == 0 && status == CF_EBPF_SRC_IP_STATUS_VERIFIED) {
return CF_EBPF_PASS;
}
```
7. Check if this is a challenge response from a challenged source IP.
If the source IP was previously challenged, check if the current packet contains a valid challenge response. If the response is correct, mark the source IP as verified. If the response is incorrect, blocklist the source IP immediately.
```c
if (ret == 0 && status == CF_EBPF_SRC_IP_STATUS_CHALLENGED) {
// Get the stored nonce from user data
uint64_t stored_nonce;
if (get_src_ip_data(&stored_nonce) != 0) {
return CF_EBPF_DROP;
}
// Parse the challenge response from the packet payload
struct challenge_packet *resp = (struct challenge_packet *)(udp_hdr + 1);
if ((uint8_t *)(resp + 1) > headers.data_end) {
return CF_EBPF_DROP;
}
// Verify the response: should be nonce XOR secret
uint64_t expected_response = stored_nonce ^ CHALLENGE_SECRET;
if (resp->response == expected_response) {
// Correct response - mark as verified
set_src_ip_status(CF_EBPF_SRC_IP_STATUS_VERIFIED, VERIFIED_EXPIRY_SECS);
set_src_ip_data(0); // Clear the nonce
return CF_EBPF_PASS;
}
// Wrong response - blocklist immediately
set_src_ip_status(CF_EBPF_SRC_IP_STATUS_BLOCKLISTED, 0);
return CF_EBPF_DROP;
}
```
8. Issue a new challenge for new source IPs.
Generate a random nonce, store it in the state table, create a challenge packet, and send it using `set_challenge`.
```c
// Generate a new challenge for this source IP
uint64_t nonce = rand();
// Store the nonce and mark as challenged
set_src_ip_status(CF_EBPF_SRC_IP_STATUS_CHALLENGED, CHALLENGE_EXPIRY_SECS);
set_src_ip_data(nonce);
// Build the challenge packet to send back
struct challenge_packet challenge;
challenge.nonce = nonce;
challenge.response = 0; // Client will fill this in
// Set the challenge packet buffer
set_challenge((uint8_t *)&challenge, sizeof(challenge));
// Drop the original packet until client responds to challenge
return CF_EBPF_DROP;
}
```
For reference, the example below is the complex program in its entirety:
```c
#define CF_EBPF_HELPER_V0
#include <cf_ebpf_defs.h>
#include <cf_ebpf_helper.h>
// Challenge-response protocol constants
#define CHALLENGE_SECRET 0xDEADBEEFCAFEBABEULL
#define CHALLENGE_EXPIRY_SECS 60
#define VERIFIED_EXPIRY_SECS 3600
// Challenge packet structure
struct challenge_packet {
uint64_t nonce;
uint64_t response;
};
uint64_t cf_ebpf_main(void *state)
{
struct cf_ebpf_generic_ctx *ctx = state;
struct cf_ebpf_parsed_headers headers;
struct cf_ebpf_packet_data *p;
if (parse_packet_data(ctx, &p, &headers) != 0) {
return CF_EBPF_DROP;
}
struct udphdr *udp_hdr = headers.udp;
// Check source IP status
uint8_t status;
uint64_t expiry;
int ret = get_src_ip_status(&status, &expiry);
// Check if status has expired
int64_t now = timestamp();
if (ret == 0 && expiry > 0 && (uint64_t)now > expiry) {
ret = -1; // Treat as new connection
}
// Handle verified source IPs - allow through
if (ret == 0 && status == CF_EBPF_SRC_IP_STATUS_VERIFIED) {
return CF_EBPF_PASS;
}
// Handle challenged source IPs - check for valid response
if (ret == 0 && status == CF_EBPF_SRC_IP_STATUS_CHALLENGED) {
uint64_t stored_nonce;
if (get_src_ip_data(&stored_nonce) != 0) {
return CF_EBPF_DROP;
}
// Parse challenge response from packet payload
struct challenge_packet *resp = (struct challenge_packet *)(udp_hdr + 1);
if ((uint8_t *)(resp + 1) > headers.data_end) {
return CF_EBPF_DROP;
}
// Check response using XOR
uint64_t expected_response = stored_nonce ^ CHALLENGE_SECRET;
if (resp->response == expected_response) {
// Correct response - mark as verified
set_src_ip_status(CF_EBPF_SRC_IP_STATUS_VERIFIED, VERIFIED_EXPIRY_SECS);
set_src_ip_data(0);
return CF_EBPF_PASS;
}
// Wrong response - blocklist immediately
set_src_ip_status(CF_EBPF_SRC_IP_STATUS_BLOCKLISTED, 0);
return CF_EBPF_DROP;
}
// New source IP - issue initial challenge
uint64_t nonce = rand();
set_src_ip_status(CF_EBPF_SRC_IP_STATUS_CHALLENGED, CHALLENGE_EXPIRY_SECS);
set_src_ip_data(nonce);
struct challenge_packet challenge;
challenge.nonce = nonce;
challenge.response = 0;
set_challenge((uint8_t *)&challenge, sizeof(challenge));
return CF_EBPF_DROP;
}
This program demonstrates several key concepts:
- State management: Using
get_src_ip_status,set_src_ip_status,get_src_ip_data, andset_src_ip_datato track the challenge state for each source IP. - Challenge emission: Using
set_challengeto send a challenge packet back to the client. - Cryptographic verification: Using a shared secret to verify that the client correctly responded to the challenge.
- Expiry handling: Using timestamps to expire stale state entries.
Write a complex program: rate limiting
The example program below implements a per-source-IP rate limiter using a fixed window algorithm. This is useful for mitigating volumetric DDoS attacks by limiting how many packets a single source IP can send within a time window.
The rate limiting mechanism works as follows:
When a packet arrives, the program retrieves the stored state for that source IP. The state contains a window start timestamp and a packet counter, packed into a single 64-bit value. If the current time is still within the window, the counter increments. If the counter exceeds the configured limit, the packet is dropped. When the window expires, the counter resets.
- Include the Cloudflare eBPF header files and define the helper version.
#include <cf_ebpf_defs.h>
#define CF_EBPF_HELPER_V0
#include <cf_ebpf_helper.h>
```
2. Define constants for the rate limit configuration.
`RATE_LIMIT` sets the maximum number of packets allowed per window. `WINDOW_SECONDS` defines the duration of each time window in seconds.
```c
#define RATE_LIMIT 100 // Maximum packets allowed per window
#define WINDOW_SECONDS 60 // Time window in seconds
```
3. Define macros to pack and unpack state data.
The source IP state table stores a single `u64` value per source IP. To track both a timestamp and a counter, pack them into this value: the timestamp in the upper 32 bits and the counter in the lower 32 bits.
```c
#define PACK_STATE(ts, count) (((uint64_t)(ts) << 32) | ((uint64_t)(count) & 0xFFFFFFFF))
#define UNPACK_TIMESTAMP(data) ((uint32_t)((data) >> 32))
#define UNPACK_COUNTER(data) ((uint32_t)((data) & 0xFFFFFFFF))
```
4. Define the entry function and get the current timestamp.
If the timestamp helper fails, allow the packet to avoid false positives.
```c
uint64_t cf_ebpf_main(void *state)
{
// Get current timestamp
int64_t now = timestamp();
if (now < 0) {
return CF_EBPF_PASS; // If timestamp fails, allow the packet
}
uint32_t now_secs = (uint32_t)now;
```
5. Retrieve the existing state for this source IP.
Use `get_src_ip_data` to look up whether this source IP has been seen before.
```c
// Try to get existing state for this source IP
uint64_t data;
int ret = get_src_ip_data(&data);
uint32_t window_start;
uint32_t counter;
```
6. Handle the case where this is a new source IP.
If no entry exists (return value is `-1`), this is the first packet from this source IP. Initialize the window to start now with a counter of 1.
```c
if (ret == -1) {
// No existing entry - first packet from this IP
// Initialize: window starts now, counter = 1
window_start = now_secs;
counter = 1;
}
```
7. Handle existing source IPs and check the time window.
If an entry exists, unpack the stored timestamp and counter. If the window has expired, reset both values. Otherwise, increment the counter and check if it exceeds the rate limit.
```c
} else if (ret != 0) {
// If there's other unknown error with getting src_ip_data, pass packet
return CF_EBPF_PASS;
} else {
// Entry exists - unpack the state
window_start = UNPACK_TIMESTAMP(data);
counter = UNPACK_COUNTER(data);
// Check if we're still in the same time window
if (now_secs - window_start >= WINDOW_SECONDS) {
// Window expired - reset counter and start new window
window_start = now_secs;
counter = 1;
} else {
// Still in same window - increment counter
counter++;
// Check if rate limit exceeded
if (counter > RATE_LIMIT) {
// Drop packet without updating state
return CF_EBPF_DROP;
}
}
}
```
8. Store the updated state and allow the packet.
Pack the window start timestamp and counter back into a single value and store it in the source IP state table.
```c
// Store updated state
uint64_t new_data = PACK_STATE(window_start, counter);
set_src_ip_data(new_data);
return CF_EBPF_PASS;
}
```
For reference, the example below is the rate limiting program in its entirety:
```c
#include <cf_ebpf_defs.h>
#define CF_EBPF_HELPER_V0
#include <cf_ebpf_helper.h>
// Rate limit configuration
// This program implements a fixed (not sliding) window ratelimit.
#define RATE_LIMIT 100 // Maximum packets allowed per window
#define WINDOW_SECONDS 60 // Time window in seconds
// The source IP table holds a mapping from source IP -> custom u64. We will make the custom u64 value in the
// table hold a timestamp and a counter to accomplish a ratelimit.
//
// NOTE: the source IP table is effectively a LRU cache. If it is full, old values will be evicted.
// Values are also garbage collected from the table every 1hr.
//
// The macros below pack the timestamp (upper 32 bits) and counter (lower 32 bits) into 64-bit data
// into a value that we can store into the source IP table.
#define PACK_STATE(ts, count) (((uint64_t)(ts) << 32) | ((uint64_t)(count) & 0xFFFFFFFF))
#define UNPACK_TIMESTAMP(data) ((uint32_t)((data) >> 32))
#define UNPACK_COUNTER(data) ((uint32_t)((data) & 0xFFFFFFFF))
uint64_t cf_ebpf_main(void *state)
{
// Get current timestamp
int64_t now = timestamp();
if (now < 0) {
return CF_EBPF_PASS; // If timestamp fails, allow the packet
}
uint32_t now_secs = (uint32_t)now;
// Try to get existing state for this source IP
uint64_t data;
int ret = get_src_ip_data(&data);
uint32_t window_start;
uint32_t counter;
if (ret == -1) {
// No existing entry - first packet from this IP
// Initialize: window starts now, counter = 1
window_start = now_secs;
counter = 1;
} else if (ret != 0) {
// If there's other unknown error with getting src_ip_data, pass packet
return CF_EBPF_PASS;
} else {
// Entry exists - unpack the state
window_start = UNPACK_TIMESTAMP(data);
counter = UNPACK_COUNTER(data);
// Check if we're still in the same time window
if (now_secs - window_start >= WINDOW_SECONDS) {
// Window expired - reset counter and start new window
window_start = now_secs;
counter = 1;
} else {
// Still in same window - increment counter
counter++;
// Check if rate limit exceeded
if (counter > RATE_LIMIT) {
// Drop packet without updating state
// Here is where the actual ratelimit occurs.
return CF_EBPF_DROP;
}
}
}
// Store updated state
uint64_t new_data = PACK_STATE(window_start, counter);
set_src_ip_data(new_data);
return CF_EBPF_PASS;
}
This program demonstrates several key concepts:
- Bit packing: Storing multiple values (timestamp and counter) in a single
u64using bit shifting. - Fixed window rate limiting: Tracking packet counts within discrete time windows and resetting when the window expires.
- Graceful error handling: Allowing packets through when helper functions fail to avoid false positives during edge cases.
- State table behavior: The source IP state table is an LRU cache. If it reaches capacity, old entries are evicted. Entries are also garbage collected after one hour of inactivity.
State
Each program has access to its own local state. State is local to each server and is not shared between datacenters.
State is tied to a specific program version. If you modify a rule's mode (disabled, monitoring, or enabled), the content of the state tables persists. However, if you move a rule to another program or program version, the state tables are cleared.
