daily pastebin goal
9%
SHARE
TWEET

ebpf.c

teknoraver Feb 13th, 2018 73 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdint.h>
  2. #include <arpa/inet.h>
  3. #include <linux/bpf.h>
  4. #include <linux/if_ether.h>
  5. #include <linux/ip.h>
  6. #include <linux/icmp.h>
  7.  
  8. /*
  9.  * ntohs() triggers the following LLVM error:
  10.  * couldn't allocate output register for constraint 'r' at line 2147805127
  11.  */
  12. #ifdef ntohs
  13. #undef ntohs
  14. #endif
  15. #define ntohs(x) __constant_ntohs(x)
  16.  
  17. #define SEC(NAME) __attribute__((section(NAME), used))
  18.  
  19. static inline void csum_replace2(uint16_t *sum, uint16_t old, uint16_t new)
  20. {
  21.     uint16_t csum = ~*sum;
  22.  
  23.     csum += ~old;
  24.     csum += csum < (uint16_t)~old;
  25.  
  26.     csum += new;
  27.     csum += csum < (uint16_t)new;
  28.  
  29.     *sum = ~csum;
  30. }
  31.  
  32. SEC("prog")
  33. int xdp_main(struct xdp_md *ctx)
  34. {
  35.     void *data_end = (void *)(uintptr_t)ctx->data_end;
  36.     void *data = (void *)(uintptr_t)ctx->data;
  37.  
  38.     struct ethhdr *eth = data;
  39.     struct iphdr *iph = (struct iphdr *)(eth + 1);
  40.     struct icmphdr *icmph = (struct icmphdr *)(iph + 1);
  41.  
  42.     /* sanity check needed by the eBPF verifier */
  43.     if (eth + 1 > data_end)
  44.         return XDP_DROP;
  45.  
  46.     if (eth->h_proto != ntohs(ETH_P_IP))
  47.         return XDP_PASS;
  48.  
  49.     /* sanity check needed by the eBPF verifier */
  50.     if (iph + 1 > data_end)
  51.         return XDP_DROP;
  52.  
  53.     if (iph->protocol != IPPROTO_ICMP)
  54.         return XDP_PASS;
  55.  
  56.     /* sanity check needed by the eBPF verifier */
  57.     if (icmph + 1 > data_end)
  58.         return XDP_DROP;
  59.  
  60.     if (icmph->type == ICMP_ECHOREPLY) {
  61.         // if (bpf_ktime_get_ns() & 1)
  62.  
  63.         /* drop odd packets */
  64.         if (!(icmph->un.echo.sequence & ntohs(1)))
  65.             return XDP_DROP;
  66.  
  67.         /* lower the TTL and recalculate the checksum */
  68.         uint16_t *ttlproto = (uint16_t *)&iph->ttl;
  69.         uint16_t old_ttlproto = *ttlproto;
  70.         iph->ttl /= 3;
  71.  
  72.         csum_replace2(&iph->check, old_ttlproto, *ttlproto);
  73.     }
  74.  
  75.     return XDP_PASS;
  76. }
  77.  
  78. char _license[] SEC("license") = "GPL";
RAW Paste Data
Top