test_pkt_access.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* Copyright (c) 2017 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 <stddef.h>
  8. #include <linux/bpf.h>
  9. #include <linux/if_ether.h>
  10. #include <linux/if_packet.h>
  11. #include <linux/ip.h>
  12. #include <linux/ipv6.h>
  13. #include <linux/in.h>
  14. #include <linux/tcp.h>
  15. #include <linux/pkt_cls.h>
  16. #include "bpf_helpers.h"
  17. #include "bpf_endian.h"
  18. #define barrier() __asm__ __volatile__("": : :"memory")
  19. int _version SEC("version") = 1;
  20. SEC("test1")
  21. int process(struct __sk_buff *skb)
  22. {
  23. void *data_end = (void *)(long)skb->data_end;
  24. void *data = (void *)(long)skb->data;
  25. struct ethhdr *eth = (struct ethhdr *)(data);
  26. struct tcphdr *tcp = NULL;
  27. __u8 proto = 255;
  28. __u64 ihl_len;
  29. if (eth + 1 > data_end)
  30. return TC_ACT_SHOT;
  31. if (eth->h_proto == bpf_htons(ETH_P_IP)) {
  32. struct iphdr *iph = (struct iphdr *)(eth + 1);
  33. if (iph + 1 > data_end)
  34. return TC_ACT_SHOT;
  35. ihl_len = iph->ihl * 4;
  36. proto = iph->protocol;
  37. tcp = (struct tcphdr *)((void *)(iph) + ihl_len);
  38. } else if (eth->h_proto == bpf_htons(ETH_P_IPV6)) {
  39. struct ipv6hdr *ip6h = (struct ipv6hdr *)(eth + 1);
  40. if (ip6h + 1 > data_end)
  41. return TC_ACT_SHOT;
  42. ihl_len = sizeof(*ip6h);
  43. proto = ip6h->nexthdr;
  44. tcp = (struct tcphdr *)((void *)(ip6h) + ihl_len);
  45. }
  46. if (tcp) {
  47. if (((void *)(tcp) + 20) > data_end || proto != 6)
  48. return TC_ACT_SHOT;
  49. barrier(); /* to force ordering of checks */
  50. if (((void *)(tcp) + 18) > data_end)
  51. return TC_ACT_SHOT;
  52. if (tcp->urg_ptr == 123)
  53. return TC_ACT_OK;
  54. }
  55. return TC_ACT_UNSPEC;
  56. }