parse_simple.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. #define KBUILD_MODNAME "foo"
  8. #include <linux/ip.h>
  9. #include <linux/ipv6.h>
  10. #include <linux/in.h>
  11. #include <linux/tcp.h>
  12. #include <linux/udp.h>
  13. #include <uapi/linux/bpf.h>
  14. #include <net/ip.h>
  15. #include <bpf/bpf_helpers.h>
  16. #define DEFAULT_PKTGEN_UDP_PORT 9
  17. /* copy of 'struct ethhdr' without __packed */
  18. struct eth_hdr {
  19. unsigned char h_dest[ETH_ALEN];
  20. unsigned char h_source[ETH_ALEN];
  21. unsigned short h_proto;
  22. };
  23. SEC("simple")
  24. int handle_ingress(struct __sk_buff *skb)
  25. {
  26. void *data = (void *)(long)skb->data;
  27. struct eth_hdr *eth = data;
  28. struct iphdr *iph = data + sizeof(*eth);
  29. struct udphdr *udp = data + sizeof(*eth) + sizeof(*iph);
  30. void *data_end = (void *)(long)skb->data_end;
  31. /* single length check */
  32. if (data + sizeof(*eth) + sizeof(*iph) + sizeof(*udp) > data_end)
  33. return 0;
  34. if (eth->h_proto != htons(ETH_P_IP))
  35. return 0;
  36. if (iph->protocol != IPPROTO_UDP || iph->ihl != 5)
  37. return 0;
  38. if (ip_is_fragment(iph))
  39. return 0;
  40. if (udp->dest == htons(DEFAULT_PKTGEN_UDP_PORT))
  41. return TC_ACT_SHOT;
  42. return 0;
  43. }
  44. char _license[] SEC("license") = "GPL";