load_elf__block_a_port.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // SPDX-License-Identifier: (APACHE-2.0 OR MIT)
  2. // Copyright 2016 6WIND S.A. <[email protected]>
  3. // Block TCP packets on source or destination port 0x9999.
  4. #include <linux/ip.h>
  5. #include <linux/in.h>
  6. #include <linux/tcp.h>
  7. #include <linux/bpf.h>
  8. #define ETH_ALEN 6
  9. #define ETH_P_IP 0x0008 /* htons(0x0800) */
  10. #define TCP_HDR_LEN 20
  11. #define BLOCKED_TCP_PORT 0x9999
  12. struct eth_hdr {
  13. unsigned char h_dest[ETH_ALEN];
  14. unsigned char h_source[ETH_ALEN];
  15. unsigned short h_proto;
  16. };
  17. #define SEC(NAME) __attribute__((section(NAME), used))
  18. SEC(".classifier")
  19. int handle_ingress(struct __sk_buff *skb)
  20. {
  21. void *data = (void *)(long)skb->data;
  22. void *data_end = (void *)(long)skb->data_end;
  23. struct eth_hdr *eth = data;
  24. struct iphdr *iph = data + sizeof(*eth);
  25. struct tcphdr *tcp = data + sizeof(*eth) + sizeof(*iph);
  26. /* single length check */
  27. if (data + sizeof(*eth) + sizeof(*iph) + sizeof(*tcp) > data_end)
  28. return 0;
  29. if (eth->h_proto != ETH_P_IP)
  30. return 0;
  31. if (iph->protocol != IPPROTO_TCP)
  32. return 0;
  33. if (tcp->source == BLOCKED_TCP_PORT || tcp->dest == BLOCKED_TCP_PORT)
  34. return -1;
  35. return 0;
  36. }