Reuse hash table bucket entries if they're stale 32+ seconds
[flowspec-xdp] / xdp.c
1 #include <stdint.h>
2 #include <endian.h>
3 #include <linux/if_ether.h>
4 #include <linux/ip.h>
5 #include <linux/udp.h>
6 #include <linux/icmp.h>
7 #include <linux/icmpv6.h>
8 #include <arpa/inet.h>
9
10 #include "siphash.h"
11
12 /* IP flags. */
13 #define IP_CE           0x8000          /* Flag: "Congestion"           */
14 #define IP_DF           0x4000          /* Flag: "Don't Fragment"       */
15 #define IP_MF           0x2000          /* Flag: "More Fragments"       */
16 #define IP_OFFSET       0x1FFF          /* "Fragment Offset" part       */
17
18 #define IP_PROTO_TCP 6
19 #define IP_PROTO_UDP 17
20 #define IP_PROTO_ICMP 1
21 #define IP6_PROTO_ICMPV6 58
22 #define IP6_PROTO_FRAG 44
23
24 typedef __uint128_t uint128_t;
25
26 // Our own ipv6hdr that uses uint128_t
27 struct ip6hdr {
28 #if defined(__LITTLE_ENDIAN_BITFIELD)
29         __u8    priority:4,
30                 version:4;
31 #elif defined(__BIG_ENDIAN_BITFIELD)
32         __u8    version:4,
33                 priority:4;
34 #else
35 #error  "Please fix <asm/byteorder.h>"
36 #endif
37         __u8    flow_lbl[3];
38
39         __be16  payload_len;
40         __u8            nexthdr;
41         __u8            hop_limit;
42
43         uint128_t       saddr;
44         uint128_t       daddr;
45 } __attribute__((packed));
46
47 #define IP6_MF 1
48 #define IP6_FRAGOFF 0xfff8
49 struct ip6_fraghdr {
50         uint8_t nexthdr;
51         uint8_t _reserved;
52         uint16_t frag_off; // BE low 3 bits flags, last is "more frags"
53         uint32_t id;
54 } __attribute__((packed));
55
56 // Our own ethhdr with optional vlan tags
57 struct ethhdr_vlan {
58         unsigned char   h_dest[ETH_ALEN];       /* destination eth addr */
59         unsigned char   h_source[ETH_ALEN];     /* source ether addr    */
60         __be16          vlan_magic;             /* 0x8100 */
61         __be16          tci;            /* PCP (3 bits), DEI (1 bit), and VLAN (12 bits) */
62         __be16          h_proto;                /* packet type ID field */
63 } __attribute__((packed));
64
65 // Our own tcphdr without the flags blown up
66 struct tcphdr {
67         __be16  source;
68         __be16  dest;
69         __be32  seq;
70         __be32  ack_seq;
71         __u16   flags;
72         __be16  window;
73         __sum16 check;
74         __be16  urg_ptr;
75 } __attribute__((packed));
76
77 // Note that all operations on uint128s *stay* in Network byte order!
78
79 #if defined(__LITTLE_ENDIAN)
80 #define BIGEND32(v) (((((uint32_t)(v)) >> 3*8) & 0xff) | \
81                      ((((uint32_t)(v)) >> 1*8) & 0xff00) | \
82                      ((((uint32_t)(v)) << 1*8) & 0xff0000) | \
83                      ((((uint32_t)(v)) << 3*8) & 0xff000000))
84 #elif defined(__BIG_ENDIAN)
85 #define BIGEND32(v) ((uint32_t)(v))
86 #else
87 #error "Need endian info"
88 #endif
89
90 #if defined(__LITTLE_ENDIAN)
91 #define BIGEND128(a, b, c, d) ( \
92                 (((uint128_t)BIGEND32(d)) << 3*32) | \
93                 (((uint128_t)BIGEND32(c)) << 2*32) | \
94                 (((uint128_t)BIGEND32(b)) << 1*32) | \
95                 (((uint128_t)BIGEND32(a)) << 0*32))
96 #define HTON128(a) BIGEND128(a >> 3*32, a >> 2*32, a >> 1*32, a>> 0*32)
97 // Yes, somehow macro'ing this changes LLVM's view of htons...
98 #define BE16(a) (((((uint16_t)a) & 0xff00) >> 8) | ((((uint16_t)a) & 0xff) << 8))
99 #define BE128BEHIGH64(val) ((uint64_t)((uint128_t)(val)))
100
101 #elif defined(__BIG_ENDIAN)
102
103 #define BIGEND128(a, b, c, d) ((((uint128_t)(a)) << 3*32) | (((uint128_t)(b)) << 2*32) | (((uint128_t)(c)) << 1*32) | (((uint128_t)(d)) << 0*32))
104 #define HTON128(a) ((uint128_t)(a))
105 #define BE16(a) ((uint16_t)(a))
106 #define BE128BEHIGH64(val) ((uint64_t)(((uint128_t)(val)) >> 64))
107
108 #else
109 #error "Need endian info"
110 #endif
111
112 #define MASK4(pfxlen) BIGEND32(~((((uint32_t)1) << (32 - pfxlen)) - 1))
113 #define MASK6(pfxlen) HTON128(~((((uint128_t)1) << (128 - pfxlen)) - 1))
114 #define MASK6_OFFS(offs, pfxlen) HTON128((~((((uint128_t)1) << (128 - pfxlen)) - 1)) & ((((uint128_t)1) << (128 - offs)) - 1))
115
116 // PARSE is used as a preprocessor flag to indicate parsing fields
117 #define PARSE 42
118 #include "rules.h"
119
120 #define unlikely(a) __builtin_expect(a, 0)
121 #define likely(a) __builtin_expect(a, 1)
122
123 static const uint32_t PKT_LEN_DROP = 0;
124 static const uint32_t VLAN_DROP = 1;
125 static const uint32_t IHL_DROP = 2;
126 static const uint32_t V6FRAG_DROP = 3;
127 #define STATIC_RULE_CNT 4
128
129 #define DO_RETURN(reason, ret) {\
130                 if (ret == XDP_DROP) { INCREMENT_MATCH(reason); } \
131                 return ret; \
132         }
133
134 // It seems (based on drop counts) that data_end points to the last byte, not one-past-the-end.
135 // This feels strange, but some documentation suggests > here as well, so we stick with that.
136 #define CHECK_LEN(start, struc) \
137         if (unlikely((void*)(start) + sizeof(struct struc) > data_end)) DO_RETURN(PKT_LEN_DROP, XDP_DROP);
138
139 #ifdef TEST
140 // 64 bit version of xdp_md for testing
141 struct xdp_md {
142         __u64 data;
143         __u64 data_end;
144         __u64 data_meta;
145         /* Below access go through struct xdp_rxq_info */
146         __u64 ingress_ifindex; /* rxq->dev->ifindex */
147         __u64 rx_queue_index;  /* rxq->queue_index  */
148
149         __u64 egress_ifindex;  /* txq->dev->ifindex */
150 };
151 static const int XDP_PASS = 0;
152 static const int XDP_DROP = 1;
153
154 static long drop_cnt_map[RULECNT + STATIC_RULE_CNT];
155 #define INCREMENT_MATCH(reason) { drop_cnt_map[reason] += 1; drop_cnt_map[reason] += data_end - pktdata; }
156
157 #else /* TEST */
158 #include <linux/bpf.h>
159 #include <bpf/bpf_helpers.h>
160
161 struct match_counter {
162         uint64_t bytes;
163         uint64_t packets;
164 };
165 struct {
166         __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
167         __uint(max_entries, RULECNT + STATIC_RULE_CNT);
168         __u32 *key;
169         struct match_counter *value;
170 } drop_cnt_map SEC(".maps");
171
172 #define INCREMENT_MATCH(reason) { \
173         struct match_counter *value = bpf_map_lookup_elem(&drop_cnt_map, &reason); \
174         if (value) { \
175                 value->bytes += data_end - pktdata; \
176                 value->packets += 1; \
177         } \
178 }
179
180 // Rate limits are done in a static-sized leaky bucket with a decimal counter
181 // Bucket size is always exactly (1 << RATE_BUCKET_INTEGER_BITS)
182 #define RATE_BUCKET_DECIMAL_BITS 8
183 #define RATE_BUCKET_INTEGER_BITS 4
184
185 #define RATE_BUCKET_BITS (RATE_BUCKET_DECIMAL_BITS + RATE_BUCKET_INTEGER_BITS)
186 #define RATE_TIME_MASK ((1ULL << (64 - RATE_BUCKET_BITS)) - 1)
187
188 // Time going backwards 10ms+ or forward 32sec+ implies we should consider it
189 // an overflow, or at least stale enough that we should reset the entry.
190 #define RATE_MIN_TIME_OFFSET -10000000LL
191 #define RATE_MAX_TIME_OFFSET 32000000000LL
192
193 #ifdef RATE_CNT
194 struct ratelimit {
195         struct bpf_spin_lock lock;
196         uint64_t sent_time;
197 };
198 struct {
199         __uint(type, BPF_MAP_TYPE_ARRAY);
200         __uint(max_entries, RATE_CNT);
201         __u32 *key;
202         struct ratelimit *value;
203 } rate_map SEC(".maps");
204 #endif /* RATE_CNT */
205
206 // We implement a rather naive hashtable here instead of using a BPF map because
207 // (a) the BPF map hashtables are similarly naive (no rehashing, etc),
208 // (b) the BPF map LRU hashtables don't support locking.
209 //
210 // We first separate into a few top-level buckets with per-bucket locks, limiting
211 // us to 2^SRC_HASH_MAX_PARALLELISM parallel accessors.
212 //
213 // Then we build an array of MAX_ENTRIES/2**SRC_HASH_MAX_PARALLELISM_POW entries,
214 // which are split into buckets of size SRC_HASH_BUCKET_COUNT. An entry can appear
215 // in any of the SRC_HASH_BUCKET_COUNT buckets at it's hash value.
216 #define SRC_HASH_MAX_PARALLELISM_POW 9
217 #define SRC_HASH_MAX_PARALLELISM (1 << SRC_HASH_MAX_PARALLELISM_POW)
218 #define SRC_HASH_BUCKET_COUNT_POW 3
219 #define SRC_HASH_BUCKET_COUNT (1 << SRC_HASH_BUCKET_COUNT_POW)
220
221 #include "rand.h"
222
223 #define CREATE_PERSRC_LOOKUP(IPV, IP_TYPE) \
224 struct persrc_rate##IPV##_entry { \
225         uint64_t sent_time; \
226         IP_TYPE srcip; \
227 }; \
228  \
229 struct persrc_rate##IPV##_bucket { \
230         struct bpf_spin_lock lock; \
231         struct persrc_rate##IPV##_entry entries[]; \
232 }; \
233  \
234 struct persrc_rate##IPV##_ptr { \
235         struct persrc_rate##IPV##_entry *rate; \
236         struct bpf_spin_lock *lock; \
237 }; \
238  \
239 __attribute__((always_inline)) \
240 static inline struct persrc_rate##IPV##_ptr get_v##IPV##_persrc_ratelimit(IP_TYPE key, void *map, size_t map_limit, int64_t cur_time_masked) { \
241         struct persrc_rate##IPV##_ptr res = { .rate = NULL, .lock = NULL }; \
242         uint64_t hash = siphash(&key, sizeof(key), COMPILE_TIME_RAND); \
243  \
244         const uint32_t map_key = hash % SRC_HASH_MAX_PARALLELISM; \
245         struct persrc_rate##IPV##_bucket *buckets = bpf_map_lookup_elem(map, &map_key); \
246         if (!buckets) return res; \
247  \
248         hash >>= SRC_HASH_MAX_PARALLELISM_POW; \
249         map_limit >>= SRC_HASH_MAX_PARALLELISM_POW; \
250  \
251         struct persrc_rate##IPV##_entry *first_bucket = &buckets->entries[(hash % map_limit) & (~(SRC_HASH_BUCKET_COUNT - 1))]; \
252         bpf_spin_lock(&buckets->lock); \
253  \
254         int min_sent_idx = 0; \
255         uint64_t min_sent_time = UINT64_MAX; \
256         for (int i = 0; i < SRC_HASH_BUCKET_COUNT; i++) { \
257                 if (first_bucket[i].srcip == key) { \
258                         res.rate = &first_bucket[i]; \
259                         res.lock = &buckets->lock; \
260                         return res; \
261                 } \
262                 int64_t time_offset = ((int64_t)cur_time_masked) - (first_bucket[i].sent_time & RATE_TIME_MASK); \
263                 if (time_offset < RATE_MIN_TIME_OFFSET || time_offset > RATE_MAX_TIME_OFFSET) { \
264                         min_sent_idx = i; \
265                         break; \
266                 } \
267                 if ((first_bucket[i].sent_time & RATE_TIME_MASK) < min_sent_time) { \
268                         min_sent_time = first_bucket[i].sent_time & RATE_TIME_MASK; \
269                         min_sent_idx = i; \
270                 } \
271         } \
272         res.rate = &first_bucket[min_sent_idx]; \
273         res.rate->srcip = key; \
274         res.rate->sent_time = 0; \
275         res.lock = &buckets->lock; \
276         return res; \
277 }
278
279 CREATE_PERSRC_LOOKUP(6, uint128_t)
280 CREATE_PERSRC_LOOKUP(5, uint64_t) // IPv6 matching no more than a /64
281 CREATE_PERSRC_LOOKUP(4, uint32_t)
282
283 #define SRC_RATE_DEFINE(IPV, n, limit) \
284 struct persrc_rate##IPV##_bucket_##n { \
285         struct bpf_spin_lock lock; \
286         struct persrc_rate##IPV##_entry entries[limit / SRC_HASH_MAX_PARALLELISM]; \
287 }; \
288 struct { \
289         __uint(type, BPF_MAP_TYPE_ARRAY); \
290         __uint(max_entries, SRC_HASH_MAX_PARALLELISM); \
291         uint32_t *key; \
292         struct persrc_rate##IPV##_bucket_##n *value; \
293 } v##IPV##_src_rate_##n SEC(".maps");
294
295 #include "maps.h"
296
297 #ifndef HAVE_WRAPPER // Set this to call xdp_drop externally
298 SEC("xdp_drop")
299 #endif /* HAVE_WRAPPER */
300 #endif /* not TEST */
301 int xdp_drop_prog(struct xdp_md *ctx)
302 {
303         const void *const data_end = (void *)(size_t)ctx->data_end;
304
305         const void * pktdata;
306         unsigned short eth_proto;
307
308         {
309                 // DO_RETURN in CHECK_LEN relies on pktdata being set to calculate packet length.
310                 // That said, we don't want to overflow, so just set packet length to 0 here.
311                 pktdata = data_end;
312                 CHECK_LEN((size_t)ctx->data, ethhdr);
313                 const struct ethhdr *const eth = (void*)(size_t)ctx->data;
314                 pktdata = (const void *)(long)ctx->data + sizeof(struct ethhdr);
315
316 #if PARSE_8021Q == PARSE
317                 if (likely(eth->h_proto == BE16(ETH_P_8021Q))) {
318                         CHECK_LEN((size_t)ctx->data, ethhdr_vlan);
319                         const struct ethhdr_vlan *const eth_vlan = (void*)(size_t)ctx->data;
320                         pktdata = (const void *)(long)ctx->data + sizeof(struct ethhdr_vlan);
321 #ifdef REQ_8021Q
322                         if (unlikely((eth_vlan->tci & BE16(0xfff)) != BE16(REQ_8021Q)))
323                                 DO_RETURN(VLAN_DROP, XDP_DROP);
324 #endif
325                         eth_proto = eth_vlan->h_proto;
326 #else
327                 if (unlikely(eth->h_proto == BE16(ETH_P_8021Q))) {
328                         pktdata = (const void *)(long)ctx->data + sizeof(struct ethhdr_vlan);
329                         DO_RETURN(VLAN_DROP, PARSE_8021Q);
330 #endif
331                 } else {
332 #ifdef REQ_8021Q
333                         DO_RETURN(VLAN_DROP, XDP_DROP);
334 #else
335                         eth_proto = eth->h_proto;
336 #endif
337                 }
338         }
339
340         const void *l4hdr = NULL;
341         const struct tcphdr *tcp = NULL;
342         int32_t sport = -1, dport = -1; // Host Endian! Only valid with tcp || udp
343
344 #ifdef NEED_V4_PARSE
345         if (eth_proto == BE16(ETH_P_IP)) {
346                 CHECK_LEN(pktdata, iphdr);
347                 struct iphdr *ip = (struct iphdr*) pktdata;
348
349 #if PARSE_IHL == PARSE
350                 if (unlikely(ip->ihl < 5)) DO_RETURN(IHL_DROP, XDP_DROP);
351                 l4hdr = pktdata + ip->ihl * 4;
352 #else
353                 if (ip->ihl != 5) DO_RETURN(IHL_DROP, PARSE_IHL);
354                 l4hdr = pktdata + 5*4;
355 #endif
356
357                 const struct icmphdr *icmp = NULL;
358                 if ((ip->frag_off & BE16(IP_OFFSET)) == 0) {
359                         if (ip->protocol == IP_PROTO_TCP) {
360                                 CHECK_LEN(l4hdr, tcphdr);
361                                 tcp = (struct tcphdr*) l4hdr;
362                                 sport = BE16(tcp->source);
363                                 dport = BE16(tcp->dest);
364                         } else if (ip->protocol == IP_PROTO_UDP) {
365                                 CHECK_LEN(l4hdr, udphdr);
366                                 const struct udphdr *udp = (struct udphdr*) l4hdr;
367                                 sport = BE16(udp->source);
368                                 dport = BE16(udp->dest);
369                         } else if (ip->protocol == IP_PROTO_ICMP) {
370                                 CHECK_LEN(l4hdr, icmphdr);
371                                 icmp = (struct icmphdr*) l4hdr;
372                         }
373                 }
374
375                 RULES4
376         }
377 #endif
378 #ifdef NEED_V6_PARSE
379         if (eth_proto == BE16(ETH_P_IPV6)) {
380                 CHECK_LEN(pktdata, ip6hdr);
381                 struct ip6hdr *ip6 = (struct ip6hdr*) pktdata;
382
383                 l4hdr = pktdata + 40;
384
385                 uint8_t v6nexthdr = ip6->nexthdr;
386                 const struct ip6_fraghdr *frag6 = NULL;
387 #ifdef PARSE_V6_FRAG
388 #if PARSE_V6_FRAG == PARSE
389                 if (ip6->nexthdr == IP6_PROTO_FRAG) {
390                         CHECK_LEN(l4hdr, ip6_fraghdr);
391                         frag6 = (struct ip6_fraghdr*) l4hdr;
392                         l4hdr = l4hdr + sizeof(struct ip6_fraghdr);
393                         v6nexthdr = frag6->nexthdr;
394 #else
395                 if (unlikely(ip6->nexthdr == IP6_PROTO_FRAG)) {
396                         DO_RETURN(V6FRAG_DROP, PARSE_V6_FRAG);
397 #endif
398                 }
399 #endif
400                 // TODO: Handle more options?
401
402                 const struct icmp6hdr *icmpv6 = NULL;
403                 if (frag6 == NULL || (frag6->frag_off & BE16(IP6_FRAGOFF)) == 0) {
404                         if (v6nexthdr == IP_PROTO_TCP) {
405                                 CHECK_LEN(l4hdr, tcphdr);
406                                 tcp = (struct tcphdr*) l4hdr;
407                                 sport = BE16(tcp->source);
408                                 dport = BE16(tcp->dest);
409                         } else if (v6nexthdr == IP_PROTO_UDP) {
410                                 CHECK_LEN(l4hdr, udphdr);
411                                 const struct udphdr *udp = (struct udphdr*) l4hdr;
412                                 sport = BE16(udp->source);
413                                 dport = BE16(udp->dest);
414                         } else if (v6nexthdr == IP6_PROTO_ICMPV6) {
415                                 CHECK_LEN(l4hdr, icmp6hdr);
416                                 icmpv6 = (struct icmp6hdr*) l4hdr;
417                         }
418                 }
419
420                 RULES6
421         }
422 #endif
423
424         return XDP_PASS;
425 }
426
427 #ifdef TEST
428 #include <assert.h>
429 #include <string.h>
430
431 char d[] = TEST;
432 int main() {
433         struct xdp_md test = {
434                 .data = (uint64_t)d,
435                 // -1 because sizeof includes a trailing null in the "string"
436                 .data_end = (uint64_t)(d + sizeof(d) - 1),
437         };
438         assert(xdp_drop_prog(&test) == TEST_EXP);
439 }
440 #endif