4
0

block_a_port.c 1023 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. #include <linux/ip.h>
  2. #include <linux/in.h>
  3. #include <linux/tcp.h>
  4. #include <linux/bpf.h>
  5. #define ETH_ALEN 6
  6. #define ETH_P_IP 0x0008 /* htons(0x0800) */
  7. #define TCP_HDR_LEN 20
  8. #define BLOCKED_TCP_PORT 0x9999
  9. struct eth_hdr {
  10. unsigned char h_dest[ETH_ALEN];
  11. unsigned char h_source[ETH_ALEN];
  12. unsigned short h_proto;
  13. };
  14. #define SEC(NAME) __attribute__((section(NAME), used))
  15. SEC(".classifier")
  16. int handle_ingress(struct __sk_buff *skb)
  17. {
  18. void *data = (void *)(long)skb->data;
  19. void *data_end = (void *)(long)skb->data_end;
  20. struct eth_hdr *eth = data;
  21. struct iphdr *iph = data + sizeof(*eth);
  22. struct tcphdr *tcp = data + sizeof(*eth) + sizeof(*iph);
  23. /* single length check */
  24. if (data + sizeof(*eth) + sizeof(*iph) + sizeof(*tcp) > data_end)
  25. return 0;
  26. if (eth->h_proto != ETH_P_IP)
  27. return 0;
  28. if (iph->protocol != IPPROTO_TCP)
  29. return 0;
  30. if (tcp->source == BLOCKED_TCP_PORT || tcp->dest == BLOCKED_TCP_PORT)
  31. return -1;
  32. return 0;
  33. }