parse_simple.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /* Copyright (c) 2016 Facebook
  2. *
  3. * This program is free software; you can redistribute it and/or
  4. * modify it under the terms of version 2 of the GNU General Public
  5. * License as published by the Free Software Foundation.
  6. */
  7. #include <linux/ip.h>
  8. #include <linux/ipv6.h>
  9. #include <linux/in.h>
  10. #include <linux/tcp.h>
  11. #include <linux/udp.h>
  12. #include <uapi/linux/bpf.h>
  13. #include <net/ip.h>
  14. #include "bpf_helpers.h"
  15. #define DEFAULT_PKTGEN_UDP_PORT 9
  16. /* copy of 'struct ethhdr' without __packed */
  17. struct eth_hdr {
  18. unsigned char h_dest[ETH_ALEN];
  19. unsigned char h_source[ETH_ALEN];
  20. unsigned short h_proto;
  21. };
  22. SEC("simple")
  23. int handle_ingress(struct __sk_buff *skb)
  24. {
  25. void *data = (void *)(long)skb->data;
  26. struct eth_hdr *eth = data;
  27. struct iphdr *iph = data + sizeof(*eth);
  28. struct udphdr *udp = data + sizeof(*eth) + sizeof(*iph);
  29. void *data_end = (void *)(long)skb->data_end;
  30. /* single length check */
  31. if (data + sizeof(*eth) + sizeof(*iph) + sizeof(*udp) > data_end)
  32. return 0;
  33. if (eth->h_proto != htons(ETH_P_IP))
  34. return 0;
  35. if (iph->protocol != IPPROTO_UDP || iph->ihl != 5)
  36. return 0;
  37. if (ip_is_fragment(iph))
  38. return 0;
  39. if (udp->dest == htons(DEFAULT_PKTGEN_UDP_PORT))
  40. return TC_ACT_SHOT;
  41. return 0;
  42. }
  43. char _license[] SEC("license") = "GPL";