4
0

load_elf__block_a_port.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright 2016 6WIND S.A. <quentin.monnet@6wind.com>
  2. //
  3. // Licensed under the Apache License, Version 2.0
  4. // <http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
  5. // <http://opensource.org/licenses/MIT>, at your option. This file may not be
  6. // copied, modified, or distributed except according to those terms.
  7. // Block TCP packets on source or destination port 0x9999.
  8. #include <linux/ip.h>
  9. #include <linux/in.h>
  10. #include <linux/tcp.h>
  11. #include <linux/bpf.h>
  12. #define ETH_ALEN 6
  13. #define ETH_P_IP 0x0008 /* htons(0x0800) */
  14. #define TCP_HDR_LEN 20
  15. #define BLOCKED_TCP_PORT 0x9999
  16. struct eth_hdr {
  17. unsigned char h_dest[ETH_ALEN];
  18. unsigned char h_source[ETH_ALEN];
  19. unsigned short h_proto;
  20. };
  21. #define SEC(NAME) __attribute__((section(NAME), used))
  22. SEC(".classifier")
  23. int handle_ingress(struct __sk_buff *skb)
  24. {
  25. void *data = (void *)(long)skb->data;
  26. void *data_end = (void *)(long)skb->data_end;
  27. struct eth_hdr *eth = data;
  28. struct iphdr *iph = data + sizeof(*eth);
  29. struct tcphdr *tcp = data + sizeof(*eth) + sizeof(*iph);
  30. /* single length check */
  31. if (data + sizeof(*eth) + sizeof(*iph) + sizeof(*tcp) > data_end)
  32. return 0;
  33. if (eth->h_proto != ETH_P_IP)
  34. return 0;
  35. if (iph->protocol != IPPROTO_TCP)
  36. return 0;
  37. if (tcp->source == BLOCKED_TCP_PORT || tcp->dest == BLOCKED_TCP_PORT)
  38. return -1;
  39. return 0;
  40. }