Add tcpfilter example
This commit is contained in:
parent
066d9972cc
commit
6e8387a0a4
5 changed files with 58 additions and 2 deletions
16
tcpfilter/default.nix
Normal file
16
tcpfilter/default.nix
Normal file
|
@ -0,0 +1,16 @@
|
|||
{clangStdenv, libbpf, ...}: clangStdenv.mkDerivation {
|
||||
name = "tcpfilter";
|
||||
src = ./.;
|
||||
hardeningDisable = [ "stackprotector" "zerocallusedregs" ];
|
||||
dontFixup = true;
|
||||
buildInputs = [ libbpf ];
|
||||
|
||||
buildPhase = ''
|
||||
clang -O2 -target bpf -g -c tcpfilter.c -o tcpfilter.o
|
||||
'';
|
||||
|
||||
installPhase = ''
|
||||
mkdir $out
|
||||
cp tcpfilter.o $out
|
||||
'';
|
||||
}
|
33
tcpfilter/tcpfilter.c
Normal file
33
tcpfilter/tcpfilter.c
Normal file
|
@ -0,0 +1,33 @@
|
|||
#include <linux/bpf.h>
|
||||
#include <linux/if_ether.h>
|
||||
#include <linux/ip.h>
|
||||
#include <linux/tcp.h>
|
||||
#include <linux/in.h>
|
||||
#include <bpf/bpf_helpers.h>
|
||||
#include <bpf/bpf_endian.h>
|
||||
|
||||
SEC("xdp")
|
||||
int isTCP( struct xdp_md *ctx ) {
|
||||
void *data_end = (void *)(long) ctx->data_end;
|
||||
void *data_begin = (void *)(long) ctx->data;
|
||||
struct ethhdr* eth = data_begin;
|
||||
|
||||
// Check packet's size
|
||||
if(eth + 1 > data_end)
|
||||
return XDP_PASS;
|
||||
|
||||
// Check if Ethernet frame has IPv4 packet
|
||||
if (eth->h_proto == bpf_htons( ETH_P_IP )) {
|
||||
struct iphdr *ipv4 = (struct iphdr *)( ((void*)eth) + ETH_HLEN );
|
||||
|
||||
if(ipv4 + 1 > data_end)
|
||||
return XDP_PASS;
|
||||
|
||||
// Check if IPv4 packet contains a TCP segment
|
||||
if (ipv4->protocol == IPPROTO_TCP)
|
||||
return XDP_PASS;
|
||||
}
|
||||
return XDP_DROP;
|
||||
}
|
||||
|
||||
char LICENSE[] SEC("license") = "GPL";
|
Loading…
Add table
Add a link
Reference in a new issue