├── xdp-security-group ├── .gitignore ├── server │ ├── .gitignore │ ├── go.mod │ ├── Makefile │ └── main.go ├── Makefile ├── README.md └── sg.bpf.c ├── tc-bandwidth-limit ├── .gitignore ├── bpf │ ├── x86 │ │ └── vmlinux.h │ ├── .gitignore │ ├── bandwidthlimit.bpf.c │ ├── bandwidthlimit.cc │ └── Makefile ├── Makefile └── README.md ├── tc-traffic-stat ├── .gitignore ├── bpf │ ├── x86 │ │ └── vmlinux.h │ ├── .gitignore │ ├── trafficstat.bpf.c │ ├── trafficstat.cc │ └── Makefile ├── pcap │ ├── .gitignore │ ├── Makefile │ └── main.cpp ├── default.conf ├── Makefile └── README.md ├── .gitignore ├── modify-arguments-on-the-fly ├── tracee │ ├── .gitignore │ ├── go.mod │ ├── Makefile │ └── main.go ├── tracer │ ├── .gitignore │ ├── go.mod │ ├── Makefile │ ├── go.sum │ └── main.go └── README.md ├── trace-tcpreset-and-tcpretransmit └── tracer │ ├── .gitignore │ ├── doc.go │ ├── go.mod │ ├── Makefile │ ├── go.sum │ ├── view.py │ └── main.go ├── uretprobe-with-golang-the-wrong-way ├── tracee │ ├── .gitignore │ ├── go.mod │ ├── Makefile │ └── main.go └── tracer │ ├── .gitignore │ ├── go.mod │ ├── Makefile │ ├── go.sum │ └── main.go ├── README.md ├── .gitmodules ├── xdp-helloworld ├── drop.c ├── README.md └── Makefile └── LICENSE /xdp-security-group/.gitignore: -------------------------------------------------------------------------------- 1 | *.o 2 | -------------------------------------------------------------------------------- /tc-bandwidth-limit/.gitignore: -------------------------------------------------------------------------------- 1 | testfile 2 | -------------------------------------------------------------------------------- /tc-traffic-stat/.gitignore: -------------------------------------------------------------------------------- 1 | testfile 2 | -------------------------------------------------------------------------------- /tc-traffic-stat/bpf/x86/vmlinux.h: -------------------------------------------------------------------------------- 1 | vmlinux_505.h -------------------------------------------------------------------------------- /tc-traffic-stat/pcap/.gitignore: -------------------------------------------------------------------------------- 1 | /pcap-stat 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | bak 2 | 3 | *.o 4 | bpf_helpers.h 5 | -------------------------------------------------------------------------------- /tc-bandwidth-limit/bpf/x86/vmlinux.h: -------------------------------------------------------------------------------- 1 | vmlinux_505.h -------------------------------------------------------------------------------- /xdp-security-group/server/.gitignore: -------------------------------------------------------------------------------- 1 | /testserver 2 | -------------------------------------------------------------------------------- /modify-arguments-on-the-fly/tracee/.gitignore: -------------------------------------------------------------------------------- 1 | tracee 2 | -------------------------------------------------------------------------------- /modify-arguments-on-the-fly/tracer/.gitignore: -------------------------------------------------------------------------------- 1 | tracer 2 | -------------------------------------------------------------------------------- /tc-bandwidth-limit/bpf/.gitignore: -------------------------------------------------------------------------------- 1 | /trafficstat 2 | /.output 3 | -------------------------------------------------------------------------------- /tc-traffic-stat/bpf/.gitignore: -------------------------------------------------------------------------------- 1 | /trafficstat 2 | /.output 3 | -------------------------------------------------------------------------------- /trace-tcpreset-and-tcpretransmit/tracer/.gitignore: -------------------------------------------------------------------------------- 1 | tracer 2 | -------------------------------------------------------------------------------- /uretprobe-with-golang-the-wrong-way/tracee/.gitignore: -------------------------------------------------------------------------------- 1 | tracee 2 | -------------------------------------------------------------------------------- /uretprobe-with-golang-the-wrong-way/tracer/.gitignore: -------------------------------------------------------------------------------- 1 | tracer 2 | -------------------------------------------------------------------------------- /xdp-security-group/server/go.mod: -------------------------------------------------------------------------------- 1 | module chenhengqi.com/testserver 2 | 3 | go 1.15 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BPF Examples 2 | 3 | A collection of BPF examples illustrate how to exploit the magic power of BPF in real world. 4 | -------------------------------------------------------------------------------- /modify-arguments-on-the-fly/tracee/go.mod: -------------------------------------------------------------------------------- 1 | module chenhengqi.com/bpf-examples/change-arguments-on-the-fly/tracee 2 | 3 | go 1.15 4 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "tc-traffic-stat/bpf/libbpf"] 2 | path = tc-traffic-stat/bpf/libbpf 3 | url = https://github.com/libbpf/libbpf.git 4 | -------------------------------------------------------------------------------- /uretprobe-with-golang-the-wrong-way/tracee/go.mod: -------------------------------------------------------------------------------- 1 | module chenhengqi.com/bpf-examples/uretprobe-with-golang-the-wrong-way/tracee 2 | 3 | go 1.15 4 | -------------------------------------------------------------------------------- /modify-arguments-on-the-fly/README.md: -------------------------------------------------------------------------------- 1 | # Modify arguments on the fly 2 | 3 | See the blog post [here](https://cloud.tencent.com/developer/article/1790913). 4 | -------------------------------------------------------------------------------- /xdp-security-group/server/Makefile: -------------------------------------------------------------------------------- 1 | APP=testserver 2 | 3 | build: 4 | go build -o $(APP) 5 | 6 | run: 7 | ./$(APP) 8 | 9 | clean: 10 | rm -f $(APP) 11 | -------------------------------------------------------------------------------- /uretprobe-with-golang-the-wrong-way/tracee/Makefile: -------------------------------------------------------------------------------- 1 | APP=tracee 2 | 3 | build: 4 | go build -o $(APP) 5 | 6 | run: 7 | ./$(APP) 'hello world!' 8 | 9 | clean: 10 | rm -f $(APP) 11 | -------------------------------------------------------------------------------- /modify-arguments-on-the-fly/tracee/Makefile: -------------------------------------------------------------------------------- 1 | APP=tracee 2 | 3 | build: 4 | go build -gcflags='-l' -o $(APP) 5 | 6 | run: 7 | ./$(APP) 'hello world!' 8 | 9 | clean: 10 | rm -f $(APP) 11 | -------------------------------------------------------------------------------- /tc-traffic-stat/pcap/Makefile: -------------------------------------------------------------------------------- 1 | APP=pcap-stat 2 | 3 | build: 4 | g++ -Wall -std=c++17 -o $(APP) main.cpp -lpcap -lpthread 5 | 6 | run: 7 | sudo ./$(APP) 8 | 9 | clean: 10 | rm -f $(APP) 11 | -------------------------------------------------------------------------------- /modify-arguments-on-the-fly/tracer/go.mod: -------------------------------------------------------------------------------- 1 | module chenhengqi.com/bpf-examples/change-arguments-on-the-fly/tracer 2 | 3 | go 1.15 4 | 5 | require github.com/iovisor/gobpf v0.0.0-20210217075126-686d1e527d5f 6 | -------------------------------------------------------------------------------- /trace-tcpreset-and-tcpretransmit/tracer/doc.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // http://www.brendangregg.com/blog/2018-03-22/tcp-tracepoints.html 4 | // http://www.brendangregg.com/blog/2018-05-31/linux-tcpdrop.html 5 | -------------------------------------------------------------------------------- /trace-tcpreset-and-tcpretransmit/tracer/go.mod: -------------------------------------------------------------------------------- 1 | module chenhengqi.com/bpf-examples/log-tcpretransmit-tcpreset/tracer 2 | 3 | go 1.15 4 | 5 | require github.com/iovisor/gobpf v0.0.0-20210217075126-686d1e527d5f 6 | -------------------------------------------------------------------------------- /trace-tcpreset-and-tcpretransmit/tracer/Makefile: -------------------------------------------------------------------------------- 1 | APP=tracer 2 | 3 | build: 4 | go build -o $(APP) 5 | 6 | run: 7 | sudo ./$(APP) 8 | 9 | view: 10 | sudo python3 view.py 11 | 12 | clean: 13 | rm -f $(APP) 14 | -------------------------------------------------------------------------------- /uretprobe-with-golang-the-wrong-way/tracer/go.mod: -------------------------------------------------------------------------------- 1 | module chenhengqi.com/bpf-examples/uretprobe-with-golang-the-wrong-way/tracer 2 | 3 | go 1.15 4 | 5 | require github.com/iovisor/gobpf v0.0.0-20210217075126-686d1e527d5f 6 | -------------------------------------------------------------------------------- /tc-traffic-stat/default.conf: -------------------------------------------------------------------------------- 1 | server { 2 | listen 80; 3 | listen [::]:80; 4 | server_name localhost; 5 | 6 | location /downloads/ { 7 | alias /home/data/; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /modify-arguments-on-the-fly/tracer/Makefile: -------------------------------------------------------------------------------- 1 | APP=tracer 2 | ROOT=$(realpath ..) 3 | 4 | build: 5 | go build -o $(APP) 6 | 7 | run: 8 | sudo ./$(APP) $(ROOT)/tracee/tracee 'main.greet' 9 | 10 | clean: 11 | rm -f $(APP) 12 | -------------------------------------------------------------------------------- /uretprobe-with-golang-the-wrong-way/tracer/Makefile: -------------------------------------------------------------------------------- 1 | APP=tracer 2 | ROOT=$(realpath ..) 3 | 4 | build: 5 | go build -o $(APP) 6 | 7 | run: 8 | sudo ./$(APP) $(ROOT)/tracee/tracee 'main.foobar' 9 | 10 | clean: 11 | rm -f $(APP) 12 | -------------------------------------------------------------------------------- /modify-arguments-on-the-fly/tracer/go.sum: -------------------------------------------------------------------------------- 1 | github.com/iovisor/gobpf v0.0.0-20210217075126-686d1e527d5f h1:9TIWcvGZKltp/4xKSDrjwZYCshG5VYtUmz7ZygqYtgA= 2 | github.com/iovisor/gobpf v0.0.0-20210217075126-686d1e527d5f/go.mod h1:WSY9Jj5RhdgC3ci1QaacvbFdQ8cbrEjrpiZbLHLt2s4= 3 | -------------------------------------------------------------------------------- /trace-tcpreset-and-tcpretransmit/tracer/go.sum: -------------------------------------------------------------------------------- 1 | github.com/iovisor/gobpf v0.0.0-20210217075126-686d1e527d5f h1:9TIWcvGZKltp/4xKSDrjwZYCshG5VYtUmz7ZygqYtgA= 2 | github.com/iovisor/gobpf v0.0.0-20210217075126-686d1e527d5f/go.mod h1:WSY9Jj5RhdgC3ci1QaacvbFdQ8cbrEjrpiZbLHLt2s4= 3 | -------------------------------------------------------------------------------- /uretprobe-with-golang-the-wrong-way/tracer/go.sum: -------------------------------------------------------------------------------- 1 | github.com/iovisor/gobpf v0.0.0-20210217075126-686d1e527d5f h1:9TIWcvGZKltp/4xKSDrjwZYCshG5VYtUmz7ZygqYtgA= 2 | github.com/iovisor/gobpf v0.0.0-20210217075126-686d1e527d5f/go.mod h1:WSY9Jj5RhdgC3ci1QaacvbFdQ8cbrEjrpiZbLHLt2s4= 3 | -------------------------------------------------------------------------------- /modify-arguments-on-the-fly/tracee/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "time" 7 | ) 8 | 9 | //go:noinline 10 | func greet(s string) { 11 | fmt.Println(s) 12 | } 13 | 14 | func main() { 15 | for { 16 | greet(os.Args[1]) 17 | time.Sleep(time.Second) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /xdp-helloworld/drop.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "bpf_helpers.h" 3 | 4 | #define SEC(NAME) __attribute__((section(NAME), used)) 5 | 6 | SEC("xdp") 7 | int xdp_drop(struct xdp_md *ctx) { 8 | bpf_printk("xdp_drop get called\n"); 9 | return XDP_DROP; 10 | } 11 | 12 | char __license[] SEC("license") = "GPL"; 13 | -------------------------------------------------------------------------------- /tc-traffic-stat/bpf/trafficstat.bpf.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int ifindex = 0; 6 | __u64 traffic = 0; 7 | 8 | SEC("tp_btf/netif_receive_skb") 9 | int BPF_PROG(netif_receive_skb, struct sk_buff *skb) 10 | { 11 | if (skb->dev->ifindex == ifindex) { 12 | traffic += skb->data_len; 13 | } 14 | return 0; 15 | } 16 | 17 | char LICENSE[] SEC("license") = "GPL"; 18 | -------------------------------------------------------------------------------- /tc-bandwidth-limit/bpf/bandwidthlimit.bpf.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int ifindex = 0; 6 | __u64 traffic = 0; 7 | 8 | SEC("tp_btf/netif_receive_skb") 9 | int BPF_PROG(netif_receive_skb, struct sk_buff *skb) 10 | { 11 | if (skb->dev->ifindex == ifindex) { 12 | traffic += skb->data_len; 13 | } 14 | return 0; 15 | } 16 | 17 | char LICENSE[] SEC("license") = "GPL"; 18 | -------------------------------------------------------------------------------- /xdp-security-group/Makefile: -------------------------------------------------------------------------------- 1 | ROOT_DIR=$(realpath ..) 2 | LIBBPF_HEADERS_DIR=$(ROOT_DIR)/tc-traffic-stat/bpf/libbpf/src 3 | 4 | DEV_NAME=eth0 5 | OBJ=sg.bpf.o 6 | 7 | build: 8 | clang -I$(LIBBPF_HEADERS_DIR) -Wall -g -O2 -target bpf -c sg.bpf.c -o $(OBJ) 9 | 10 | load: 11 | sudo ip link set dev $(DEV_NAME) xdpgeneric obj $(OBJ) sec xdp verbose 12 | 13 | unload: 14 | sudo ip link set dev $(DEV_NAME) xdpgeneric off 15 | 16 | dump: 17 | llvm-objdump-10 -S --no-show-raw-insn $(OBJ) 18 | 19 | clean: 20 | rm -f $(OBJ) 21 | -------------------------------------------------------------------------------- /xdp-security-group/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io" 5 | "log" 6 | "net" 7 | ) 8 | 9 | func serve(c net.Conn) { 10 | defer c.Close() 11 | 12 | log.Printf("client connected: %s\n", c.RemoteAddr().String()) 13 | io.Copy(c, c) 14 | log.Printf("client closed: %s\n", c.RemoteAddr().String()) 15 | } 16 | 17 | func main() { 18 | lis, err := net.Listen("tcp", ":12160") 19 | if err != nil { 20 | panic(err) 21 | } 22 | 23 | for { 24 | conn, err := lis.Accept() 25 | if err != nil { 26 | panic(err) 27 | } 28 | go serve(conn) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /tc-traffic-stat/Makefile: -------------------------------------------------------------------------------- 1 | init: 2 | # 512MB = 4KB * 128K 3 | dd if=/dev/zero of=/tmp/testfile bs=4096 count=131072 4 | 5 | run: 6 | sudo docker run -d --rm \ 7 | -p 10086:80 \ 8 | -v /tmp/testfile:/home/data/testfile \ 9 | -v $(PWD)/default.conf:/etc/nginx/conf.d/default.conf \ 10 | --name my-nginx \ 11 | --network my-tc-net \ 12 | nginx:alpine 13 | 14 | kill: 15 | sudo docker kill my-nginx 16 | 17 | exec: 18 | sudo docker exec -it my-nginx /bin/sh 19 | 20 | download: 21 | curl http://localhost:10086/downloads/testfile --output testfile 22 | 23 | clean: 24 | rm -f testfile 25 | -------------------------------------------------------------------------------- /tc-bandwidth-limit/Makefile: -------------------------------------------------------------------------------- 1 | init: 2 | # 512MB = 4KB * 128K 3 | dd if=/dev/zero of=/tmp/testfile bs=4096 count=131072 4 | 5 | run: 6 | sudo docker run -d --rm \ 7 | -p 10086:80 \ 8 | -v /tmp/testfile:/home/data/testfile \ 9 | -v $(PWD)/default.conf:/etc/nginx/conf.d/default.conf \ 10 | --name my-nginx \ 11 | --network my-tc-net \ 12 | nginx:alpine 13 | 14 | kill: 15 | sudo docker kill my-nginx 16 | 17 | exec: 18 | sudo docker exec -it my-nginx /bin/sh 19 | 20 | download: 21 | curl http://localhost:10086/downloads/testfile --output testfile 22 | 23 | clean: 24 | rm -f testfile 25 | -------------------------------------------------------------------------------- /uretprobe-with-golang-the-wrong-way/tracee/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "time" 7 | ) 8 | 9 | //go:noinline 10 | func foobar() (int, string, int) { 11 | var x [10]int 12 | foo(x) 13 | return 0xbeef, os.Args[1], 0xfaac 14 | } 15 | 16 | //go:noinline 17 | func foo(x [10]int) { 18 | var y [100]int 19 | bar(y) 20 | } 21 | 22 | //go:noinline 23 | func bar(y [100]int) { 24 | var z [1000]int 25 | buz(z) 26 | } 27 | 28 | //go:noinline 29 | func buz(z [1000]int) { 30 | 31 | } 32 | 33 | func main() { 34 | for { 35 | a, b, c := foobar() 36 | fmt.Printf("%x %s %x\n", a, b, c) 37 | time.Sleep(time.Second) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /xdp-helloworld/README.md: -------------------------------------------------------------------------------- 1 | # Steps 2 | 3 | ## Create a new network device 4 | 5 | ``` 6 | $ sudo docker network create my-xdp-net 7 | ``` 8 | 9 | ## Run a container using the network created 10 | 11 | ``` 12 | $ sudo docker run -d --rm -p 10086:80 --name my-nginx --network my-xdp-net nginx:alpine 13 | ``` 14 | 15 | ## Test connnectivity 16 | 17 | ``` 18 | $ curl http://localhost:10086 19 | ``` 20 | 21 | ## Load XDP program 22 | 23 | ``` 24 | $ sudo ip link set dev br-5cee99d90a59 xdp obj drop.o sec xdp verbose 25 | ``` 26 | 27 | ## Test connnectivity again 28 | 29 | ``` 30 | $ curl http://localhost:10086 31 | ``` 32 | 33 | ## Unload XDP program 34 | 35 | ``` 36 | $ sudo ip link set dev br-5cee99d90a59 xdp off 37 | ``` 38 | 39 | ## Test connnectivity again 40 | 41 | ``` 42 | $ curl http://localhost:10086 43 | ``` 44 | -------------------------------------------------------------------------------- /xdp-helloworld/Makefile: -------------------------------------------------------------------------------- 1 | BPF_HELPERS_URL=https://raw.githubusercontent.com/torvalds/linux/v5.4/tools/testing/selftests/bpf/bpf_helpers.h 2 | BPF_HELPERS=bpf_helpers.h 3 | DEV_NAME=br-$(shell sudo docker network inspect my-xdp-net -f '{{.Id}}' | cut -c1-12) 4 | 5 | build: download 6 | clang -Wall -target bpf -O2 -g -c drop.c -o drop.o 7 | 8 | load: 9 | sudo ip link set dev $(DEV_NAME) xdp obj drop.o sec xdp verbose 10 | 11 | unload: 12 | sudo ip link set dev $(DEV_NAME) xdp off 13 | 14 | download: 15 | if [ ! -f $(BPF_HELPERS) ]; then curl $(BPF_HELPERS_URL) --output $(BPF_HELPERS); fi 16 | 17 | debug: 18 | clang -Wall -target bpf -g -c drop.c -o debug-drop.o 19 | llvm-objdump-11 -S --no-show-raw-insn debug-drop.o 20 | clang -Wall -target bpf -O2 -g -c drop.c -o debug-drop-O2.o 21 | llvm-objdump-11 -S --no-show-raw-insn debug-drop-O2.o 22 | 23 | clean: 24 | rm -f *.o 25 | -------------------------------------------------------------------------------- /xdp-security-group/README.md: -------------------------------------------------------------------------------- 1 | # Implement your own security group 2 | 3 | ## Run a simple TCP echo server 4 | 5 | ``` 6 | $ cd server 7 | $ make 8 | $ make run 9 | ``` 10 | 11 | ## Interact with the server using netcat 12 | 13 | run `netcat` from another host 14 | ``` 15 | $ nc $(SERVER_IP) 12160 16 | hello world 17 | hello world 18 | ``` 19 | 20 | ## Apply our own security policy 21 | 22 | build BPF program and attach to `eth0` 23 | ``` 24 | $ sudo ip link set dev eth0 xdpgeneric obj sg.bpf.o sec xdp verbose 25 | ``` 26 | 27 | ## Now client should fail to send echo request to the server 28 | 29 | ``` 30 | $ nc $(SERVER_IP) 12160 31 | hello world 32 | hello world 33 | ... 34 | ping 35 | ``` 36 | 37 | ## Interact with the server using netcat from port 10216 38 | 39 | run `netcat` again, this time we specify client port 40 | ``` 41 | $ nc $(SERVER_IP) 12160 -p 10216 42 | hello world 43 | hello world 44 | ``` 45 | 46 | it works 47 | -------------------------------------------------------------------------------- /modify-arguments-on-the-fly/tracer/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/iovisor/gobpf/bcc" 7 | ) 8 | 9 | const bpfProgram = ` 10 | #include 11 | 12 | int hack(struct pt_regs *ctx) { 13 | char text[] = "You are hacked!"; 14 | // read string address 15 | u64 addr = 0; 16 | u64* sp = (u64*)ctx->sp; 17 | bpf_probe_read(&addr, sizeof(addr), sp + 1); 18 | // overwrite string content 19 | bpf_probe_write_user((u64*)addr, text, sizeof(text)); 20 | return 0; 21 | } 22 | ` 23 | 24 | const ( 25 | bpfFuncName = "hack" 26 | ) 27 | 28 | func main() { 29 | bpfModule := bcc.NewModule(bpfProgram, []string{}) 30 | uprobeFD, err := bpfModule.LoadUprobe(bpfFuncName) 31 | if err != nil { 32 | panic(err) 33 | } 34 | 35 | hackedBinary := os.Args[1] 36 | hackedFuncName := os.Args[2] 37 | err = bpfModule.AttachUprobe(hackedBinary, hackedFuncName, uprobeFD, -1) 38 | if err != nil { 39 | panic(err) 40 | } 41 | 42 | select {} 43 | } 44 | -------------------------------------------------------------------------------- /tc-traffic-stat/bpf/trafficstat.cc: -------------------------------------------------------------------------------- 1 | #include "trafficstat.skel.h" 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | 8 | const int ifindex = 7; 9 | 10 | int main() { 11 | auto obj = trafficstat_bpf__open(); 12 | if (!obj) { 13 | fprintf(stderr, "failed to open BPF object\n"); 14 | return -1; 15 | } 16 | 17 | obj->bss->ifindex = ifindex; 18 | 19 | auto err = trafficstat_bpf__load(obj); 20 | if (err) { 21 | fprintf(stderr, "failed to load BPF object: %d\n", err); 22 | trafficstat_bpf__destroy(obj); 23 | return -1; 24 | } 25 | 26 | err = trafficstat_bpf__attach(obj); 27 | if (err) { 28 | fprintf(stderr, "failed to attach BPF object: %d\n", err); 29 | trafficstat_bpf__destroy(obj); 30 | return -1; 31 | } 32 | 33 | while (true) { 34 | std::this_thread::sleep_for(std::chrono::seconds(10)); 35 | printf("traffic in bytes: %lld\n", obj->bss->traffic); 36 | } 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /tc-bandwidth-limit/bpf/bandwidthlimit.cc: -------------------------------------------------------------------------------- 1 | #include "bandwidthlimit.skel.h" 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | 8 | const int ifindex = 7; 9 | 10 | int main() { 11 | auto obj = bandwidthlimit_bpf__open(); 12 | if (!obj) { 13 | fprintf(stderr, "failed to open BPF object\n"); 14 | return -1; 15 | } 16 | 17 | obj->bss->ifindex = ifindex; 18 | 19 | auto err = bandwidthlimit_bpf__load(obj); 20 | if (err) { 21 | fprintf(stderr, "failed to load BPF object: %d\n", err); 22 | bandwidthlimit_bpf__destroy(obj); 23 | return -1; 24 | } 25 | 26 | err = bandwidthlimit_bpf__attach(obj); 27 | if (err) { 28 | fprintf(stderr, "failed to attach BPF object: %d\n", err); 29 | bandwidthlimit_bpf__destroy(obj); 30 | return -1; 31 | } 32 | 33 | while (true) { 34 | std::this_thread::sleep_for(std::chrono::seconds(10)); 35 | printf("traffic in bytes: %lld\n", obj->bss->traffic); 36 | } 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /tc-bandwidth-limit/README.md: -------------------------------------------------------------------------------- 1 | # Network Traffic Stat 2 | 3 | ## Create a new network device 4 | 5 | ``` 6 | $ sudo docker network create my-tc-net 7 | ``` 8 | 9 | ## Create a file for download 10 | 11 | ``` 12 | $ dd if=/dev/zero of=/tmp/testfile bs=4096 count=131072 13 | ``` 14 | 15 | ## Run a nginx server that serves file download 16 | 17 | ``` 18 | $ sudo docker run -d --rm \ 19 | -p 10086:80 \ 20 | -v /tmp/testfile:/home/data/testfile \ 21 | -v $(PWD)/default.conf:/etc/nginx/conf.d/default.conf \ 22 | --name my-nginx \ 23 | --network my-tc-net \ 24 | nginx:alpine 25 | ``` 26 | 27 | ## Download file and stat network traffic using libpcap 28 | 29 | On a terminal: 30 | ``` 31 | $ sudo ./pcap-stat 32 | ``` 33 | 34 | On another terminal: 35 | ``` 36 | $ curl http://localhost:10086/downloads/testfile --output testfile 37 | ``` 38 | 39 | ## Download file and stat network traffic using BPF 40 | 41 | On a terminal: 42 | ``` 43 | $ sudo ./bpf-stat 44 | ``` 45 | 46 | On another terminal: 47 | ``` 48 | $ curl http://localhost:10086/downloads/testfile --output testfile 49 | ``` 50 | -------------------------------------------------------------------------------- /tc-traffic-stat/README.md: -------------------------------------------------------------------------------- 1 | # Network Traffic Stat 2 | 3 | ## Create a new network device 4 | 5 | ``` 6 | $ sudo docker network create my-tc-net 7 | ``` 8 | 9 | ## Create a file for download 10 | 11 | ``` 12 | $ dd if=/dev/zero of=/tmp/testfile bs=4096 count=131072 13 | ``` 14 | 15 | ## Run a nginx server that serves file download 16 | 17 | ``` 18 | $ sudo docker run -d --rm \ 19 | -p 10086:80 \ 20 | -v /tmp/testfile:/home/data/testfile \ 21 | -v $(PWD)/default.conf:/etc/nginx/conf.d/default.conf \ 22 | --name my-nginx \ 23 | --network my-tc-net \ 24 | nginx:alpine 25 | ``` 26 | 27 | ## Download file and stat network traffic using libpcap 28 | 29 | On a terminal: 30 | ``` 31 | $ sudo ./pcap-stat 32 | ``` 33 | 34 | On another terminal: 35 | ``` 36 | $ curl http://localhost:10086/downloads/testfile --output testfile 37 | ``` 38 | 39 | ## Download file and stat network traffic using BPF 40 | 41 | On a terminal: 42 | ``` 43 | $ sudo ./bpf-stat 44 | ``` 45 | 46 | On another terminal: 47 | ``` 48 | $ curl http://localhost:10086/downloads/testfile --output testfile 49 | ``` 50 | -------------------------------------------------------------------------------- /uretprobe-with-golang-the-wrong-way/tracer/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/iovisor/gobpf/bcc" 7 | ) 8 | 9 | const bpfProgram = ` 10 | #include 11 | 12 | const int MAX_LEN = 0xFF; 13 | 14 | int hack(struct pt_regs *ctx) { 15 | u64* sp = (u64*)ctx->sp; 16 | 17 | u64 a = 0; 18 | bpf_probe_read(&a, sizeof(a), sp + 0); 19 | 20 | char b[MAX_LEN] = {0}; 21 | u64 addr = 0; 22 | bpf_probe_read(&addr, sizeof(addr), sp + 1); 23 | u64 size = 0; 24 | bpf_probe_read(&size, sizeof(size), sp + 2); 25 | bpf_probe_read_str(&b, ((size & MAX_LEN) + 1) & MAX_LEN, (u64*)addr); 26 | 27 | u64 c = 0; 28 | bpf_probe_read(&c, sizeof(c), sp + 3); 29 | 30 | bpf_trace_printk("I got it: %x %s %x\n", a, b, c); 31 | return 0; 32 | } 33 | ` 34 | 35 | const ( 36 | bpfFuncName = "hack" 37 | ) 38 | 39 | func main() { 40 | bpfModule := bcc.NewModule(bpfProgram, []string{}) 41 | uprobeFD, err := bpfModule.LoadUprobe(bpfFuncName) 42 | if err != nil { 43 | panic(err) 44 | } 45 | 46 | hackedBinary := os.Args[1] 47 | hackedFuncName := os.Args[2] 48 | err = bpfModule.AttachUretprobe(hackedBinary, hackedFuncName, uprobeFD, -1) 49 | if err != nil { 50 | panic(err) 51 | } 52 | 53 | select {} 54 | } 55 | -------------------------------------------------------------------------------- /xdp-security-group/sg.bpf.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include "bpf_helpers.h" 8 | #include "bpf_endian.h" 9 | 10 | static int is_secure_source(void *data_begin, void *data_end) 11 | { 12 | struct ethhdr *eth_header = data_begin; 13 | 14 | // ignore 15 | if ((void *)(eth_header + 1) > data_end) { 16 | return 1; 17 | } 18 | 19 | // ignore 20 | if (eth_header->h_proto != bpf_htons(ETH_P_IP)) { 21 | return 1; 22 | } 23 | 24 | struct iphdr *ip_header = (struct iphdr *)(eth_header + 1); 25 | 26 | // ignore 27 | if ((void *)(ip_header + 1) > data_end) { 28 | return 1; 29 | } 30 | 31 | // ignore 32 | if (ip_header->protocol != IPPROTO_TCP) { 33 | return 1; 34 | } 35 | 36 | struct tcphdr *tcp_header = (struct tcphdr *)(ip_header + 1); 37 | 38 | // ignore 39 | if ((void *)(tcp_header + 1) > data_end) { 40 | return 1; 41 | } 42 | 43 | if (tcp_header->dest == bpf_htons(12160)) { 44 | if (tcp_header->source != bpf_htons(10216)) { 45 | return 0; // reject 46 | } else { 47 | return 1; // accept 48 | } 49 | } else { 50 | return 1; 51 | } 52 | } 53 | 54 | SEC("xdp") 55 | int xdp_secure_policy(struct xdp_md *ctx) 56 | { 57 | void *data = (void *)(__u64)ctx->data; 58 | void *data_end = (void *)(__u64)ctx->data_end; 59 | if (is_secure_source(data, data_end)) { 60 | return XDP_PASS; 61 | } else { 62 | return XDP_DROP; 63 | } 64 | } 65 | 66 | char __license[] SEC("license") = "GPL"; 67 | -------------------------------------------------------------------------------- /trace-tcpreset-and-tcpretransmit/tracer/view.py: -------------------------------------------------------------------------------- 1 | # encoding: utf8 2 | 3 | """ 4 | Read Trace Logs 5 | ~~~~~~~~~~~~~~~ 6 | 7 | This script is used to view trace logs. 8 | """ 9 | 10 | import datetime 11 | import re 12 | import socket 13 | import subprocess 14 | import sys 15 | import time 16 | 17 | # TCP states 18 | # https://elixir.bootlin.com/linux/latest/source/include/net/tcp_states.h 19 | TCP_STATE = { 20 | 1: 'TCP_ESTABLISHED', 21 | 2: 'TCP_SYN_SENT', 22 | 3: 'TCP_SYN_RECV', 23 | 4: 'TCP_FIN_WAIT1', 24 | 5: 'TCP_FIN_WAIT2', 25 | 6: 'TCP_TIME_WAIT', 26 | 7: 'TCP_CLOSE', 27 | 8: 'TCP_CLOSE_WAIT', 28 | 9: 'TCP_LAST_ACK', 29 | 10: 'TCP_LISTEN', 30 | 11: 'TCP_CLOSING', 31 | 12: 'TCP_NEW_SYN_RECV', 32 | } 33 | 34 | log_path = '/sys/kernel/debug/tracing/trace' 35 | if len(sys.argv) > 1: 36 | log_path = sys.argv[1] 37 | 38 | status, output = subprocess.getstatusoutput('cat /proc/uptime|cut -f 1 -d" "') 39 | if status != 0: 40 | sys.exit(-1) 41 | 42 | base_time = time.time() - float(output) 43 | 44 | with open(log_path, 'r') as file: 45 | for line in file: 46 | match = re.findall(r'(\d+\.\d+):.*:.*(tcp_\S+) port=(\d+) dst=(\d+) state=(\d+)', line) 47 | if not match or len(match[0]) != 5: 48 | continue 49 | 50 | matches = match[0] 51 | 52 | # Boot time 53 | boot_time = matches[0] 54 | 55 | # Tracepoint 56 | tracepoint = matches[1] 57 | 58 | # Datetime 59 | t = base_time + float(boot_time) 60 | dt = datetime.datetime.fromtimestamp(t).strftime('%Y-%m-%d %H:%M:%S.%f') 61 | 62 | # Port, in network byteorder 63 | raw_port = matches[2] 64 | port = int.from_bytes(int(raw_port).to_bytes(2, 'big'), 'little') 65 | 66 | # IP, in network byteorder? 67 | raw_ip = matches[3] 68 | ip = socket.inet_ntop(socket.AF_INET, int(raw_ip).to_bytes(4, 'little')) 69 | 70 | # TCP State 71 | state = int(matches[4]) 72 | tcp_state = TCP_STATE[state] if 1 <= state <= 12 else 'INVALID' 73 | 74 | print('{} {}\t{}\t{:16}\t{:5}\t{:16}'.format(boot_time, dt, tracepoint, ip, port, tcp_state)) 75 | -------------------------------------------------------------------------------- /tc-traffic-stat/bpf/Makefile: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) 2 | OUTPUT := .output 3 | CLANG ?= clang 4 | LLVM_STRIP ?= llvm-strip 5 | BPFTOOL ?= bpftool 6 | LIBBPF_SRC := $(abspath ./libbpf/src) 7 | LIBBPF_OBJ := $(abspath $(OUTPUT)/libbpf.a) 8 | INCLUDES := -I$(OUTPUT) 9 | CFLAGS := -g -O2 -Wall 10 | INSTALL ?= install 11 | prefix ?= /usr/local 12 | ARCH := $(shell uname -m | sed 's/x86_64/x86/' | sed 's/aarch64/arm64/' | sed 's/ppc64le/powerpc/') 13 | 14 | ifeq ($(wildcard $(ARCH)/),) 15 | $(error Architecture $(ARCH) is not supported yet. Please open an issue) 16 | endif 17 | 18 | APPS = trafficstat 19 | 20 | .PHONY: all 21 | all: $(APPS) 22 | 23 | ifeq ($(V),1) 24 | Q = 25 | msg = 26 | else 27 | Q = @ 28 | msg = @printf ' %-8s %s%s\n' "$(1)" "$(notdir $(2))" "$(if $(3), $(3))"; 29 | MAKEFLAGS += --no-print-directory 30 | endif 31 | 32 | .PHONY: clean 33 | clean: 34 | $(call msg,CLEAN) 35 | $(Q)rm -rf $(OUTPUT) $(APPS) 36 | 37 | $(OUTPUT) $(OUTPUT)/libbpf: 38 | $(call msg,MKDIR,$@) 39 | $(Q)mkdir -p $@ 40 | 41 | $(APPS): %: $(OUTPUT)/%.o $(LIBBPF_OBJ) | $(OUTPUT) 42 | $(call msg,BINARY,$@) 43 | $(Q)$(CXX) $(CFLAGS) $^ -lelf -lz -o $@ 44 | 45 | $(patsubst %,$(OUTPUT)/%.o,$(APPS)): %.o: %.skel.h 46 | 47 | $(OUTPUT)/%.o: %.cc $(wildcard %.h) | $(OUTPUT) 48 | $(call msg,CC,$@) 49 | $(Q)$(CXX) $(CFLAGS) $(INCLUDES) -c $(filter %.cc,$^) -o $@ 50 | 51 | $(OUTPUT)/%.skel.h: $(OUTPUT)/%.bpf.o | $(OUTPUT) 52 | $(call msg,GEN-SKEL,$@) 53 | $(Q)$(BPFTOOL) gen skeleton $< > $@ 54 | 55 | $(OUTPUT)/%.bpf.o: %.bpf.c $(LIBBPF_OBJ) $(wildcard %.h) $(ARCH)/vmlinux.h | $(OUTPUT) 56 | $(call msg,BPF,$@) 57 | $(Q)$(CLANG) -g -O2 -target bpf -D__TARGET_ARCH_$(ARCH) \ 58 | -I$(ARCH)/ $(INCLUDES) -c $(filter %.c,$^) -o $@ && \ 59 | $(LLVM_STRIP) -g $@ 60 | 61 | # Build libbpf.a 62 | $(LIBBPF_OBJ): $(wildcard $(LIBBPF_SRC)/*.[ch]) | $(OUTPUT)/libbpf 63 | $(call msg,LIB,$@) 64 | $(Q)$(MAKE) -C $(LIBBPF_SRC) BUILD_STATIC_ONLY=1 \ 65 | OBJDIR=$(dir $@)/libbpf DESTDIR=$(dir $@) \ 66 | INCLUDEDIR= LIBDIR= UAPIDIR= \ 67 | install 68 | 69 | install: $(APPS) 70 | $(call msg, INSTALL libbpf-tools) 71 | $(Q)$(INSTALL) -m 0755 -d $(DESTDIR)$(prefix)/bin 72 | $(Q)$(INSTALL) $(APPS) $(DESTDIR)$(prefix)/bin 73 | 74 | run: 75 | sudo ./trafficstat 76 | 77 | # delete failed targets 78 | .DELETE_ON_ERROR: 79 | # keep intermediate (.skel.h, .bpf.o, etc) targets 80 | .SECONDARY: 81 | -------------------------------------------------------------------------------- /trace-tcpreset-and-tcpretransmit/tracer/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/iovisor/gobpf/bcc" 7 | ) 8 | 9 | const bpfProgram = ` 10 | #include 11 | #include 12 | 13 | int log_tcp_retransmit(struct pt_regs *ctx, struct sock *sk) { 14 | u16 port = sk->__sk_common.skc_dport; 15 | u32 daddr = sk->__sk_common.skc_daddr; 16 | u8 state = sk->__sk_common.skc_state; 17 | bpf_trace_printk("tcp_retransmit port=%d dst=%d state=%d\n", port, daddr, state); 18 | return 0; 19 | } 20 | 21 | int log_tcp_reset(struct pt_regs *ctx, struct sock *sk) { 22 | u16 port = sk->__sk_common.skc_dport; 23 | u32 daddr = sk->__sk_common.skc_daddr; 24 | u8 state = sk->__sk_common.skc_state; 25 | bpf_trace_printk("tcp_reset port=%d dst=%d state=%d\n", port, daddr, state); 26 | return 0; 27 | } 28 | 29 | int log_tcp_drop(struct pt_regs *ctx, struct sock *sk) { 30 | u16 port = sk->__sk_common.skc_dport; 31 | u32 daddr = sk->__sk_common.skc_daddr; 32 | u8 state = sk->__sk_common.skc_state; 33 | bpf_trace_printk("tcp_drop port=%d dst=%d state=%d\n", port, daddr, state); 34 | return 0; 35 | } 36 | ` 37 | 38 | const ( 39 | funcNameTCPRetransmit = "log_tcp_retransmit" 40 | funcNameTCPReset = "log_tcp_reset" 41 | funcNameTCPDrop = "log_tcp_drop" 42 | eventNameTCPRetransmit = "tcp_retransmit_skb" 43 | eventNameTCPReset = "tcp_reset" 44 | eventNameTCPDrop = "tcp_drop" 45 | maxActive = 0 46 | ) 47 | 48 | func main() { 49 | bpfModule := bcc.NewModule(bpfProgram, []string{}) 50 | defer bpfModule.Close() 51 | 52 | // TCP Retransmission 53 | uprobeFD, err := bpfModule.LoadKprobe(funcNameTCPRetransmit) 54 | if err != nil { 55 | panic(err) 56 | } 57 | err = bpfModule.AttachKprobe(eventNameTCPRetransmit, uprobeFD, maxActive) 58 | if err != nil { 59 | panic(err) 60 | } 61 | 62 | // TCP Reset 63 | uprobeFD, err = bpfModule.LoadKprobe(funcNameTCPReset) 64 | if err != nil { 65 | panic(err) 66 | } 67 | err = bpfModule.AttachKprobe(eventNameTCPReset, uprobeFD, maxActive) 68 | if err != nil { 69 | panic(err) 70 | } 71 | 72 | // TCP Drop 73 | uprobeFD, err = bpfModule.LoadKprobe(funcNameTCPDrop) 74 | if err != nil { 75 | panic(err) 76 | } 77 | err = bpfModule.AttachKprobe(eventNameTCPDrop, uprobeFD, maxActive) 78 | if err != nil { 79 | panic(err) 80 | } 81 | 82 | fmt.Println("attached!") 83 | select {} 84 | } 85 | -------------------------------------------------------------------------------- /tc-bandwidth-limit/bpf/Makefile: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) 2 | OUTPUT := .output 3 | CLANG ?= clang 4 | LLVM_STRIP ?= llvm-strip 5 | BPFTOOL ?= bpftool 6 | LIBBPF_SRC := $(abspath ../../tc-traffic-stat/bpf/libbpf/src) 7 | LIBBPF_OBJ := $(abspath $(OUTPUT)/libbpf.a) 8 | INCLUDES := -I$(OUTPUT) 9 | CFLAGS := -g -O2 -Wall 10 | INSTALL ?= install 11 | prefix ?= /usr/local 12 | ARCH := $(shell uname -m | sed 's/x86_64/x86/' | sed 's/aarch64/arm64/' | sed 's/ppc64le/powerpc/') 13 | 14 | ifeq ($(wildcard $(ARCH)/),) 15 | $(error Architecture $(ARCH) is not supported yet. Please open an issue) 16 | endif 17 | 18 | APPS = bandwidthlimit 19 | 20 | .PHONY: all 21 | all: $(APPS) 22 | 23 | ifeq ($(V),1) 24 | Q = 25 | msg = 26 | else 27 | Q = @ 28 | msg = @printf ' %-8s %s%s\n' "$(1)" "$(notdir $(2))" "$(if $(3), $(3))"; 29 | MAKEFLAGS += --no-print-directory 30 | endif 31 | 32 | .PHONY: clean 33 | clean: 34 | $(call msg,CLEAN) 35 | $(Q)rm -rf $(OUTPUT) $(APPS) 36 | 37 | $(OUTPUT) $(OUTPUT)/libbpf: 38 | $(call msg,MKDIR,$@) 39 | $(Q)mkdir -p $@ 40 | 41 | $(APPS): %: $(OUTPUT)/%.o $(LIBBPF_OBJ) | $(OUTPUT) 42 | $(call msg,BINARY,$@) 43 | $(Q)$(CXX) $(CFLAGS) $^ -lelf -lz -o $@ 44 | 45 | $(patsubst %,$(OUTPUT)/%.o,$(APPS)): %.o: %.skel.h 46 | 47 | $(OUTPUT)/%.o: %.cc $(wildcard %.h) | $(OUTPUT) 48 | $(call msg,CC,$@) 49 | $(Q)$(CXX) $(CFLAGS) $(INCLUDES) -c $(filter %.cc,$^) -o $@ 50 | 51 | $(OUTPUT)/%.skel.h: $(OUTPUT)/%.bpf.o | $(OUTPUT) 52 | $(call msg,GEN-SKEL,$@) 53 | $(Q)$(BPFTOOL) gen skeleton $< > $@ 54 | 55 | $(OUTPUT)/%.bpf.o: %.bpf.c $(LIBBPF_OBJ) $(wildcard %.h) $(ARCH)/vmlinux.h | $(OUTPUT) 56 | $(call msg,BPF,$@) 57 | $(Q)$(CLANG) -g -O2 -target bpf -D__TARGET_ARCH_$(ARCH) \ 58 | -I$(ARCH)/ $(INCLUDES) -c $(filter %.c,$^) -o $@ && \ 59 | $(LLVM_STRIP) -g $@ 60 | 61 | # Build libbpf.a 62 | $(LIBBPF_OBJ): $(wildcard $(LIBBPF_SRC)/*.[ch]) | $(OUTPUT)/libbpf 63 | $(call msg,LIB,$@) 64 | $(Q)$(MAKE) -C $(LIBBPF_SRC) BUILD_STATIC_ONLY=1 \ 65 | OBJDIR=$(dir $@)/libbpf DESTDIR=$(dir $@) \ 66 | INCLUDEDIR= LIBDIR= UAPIDIR= \ 67 | install 68 | 69 | install: $(APPS) 70 | $(call msg, INSTALL libbpf-tools) 71 | $(Q)$(INSTALL) -m 0755 -d $(DESTDIR)$(prefix)/bin 72 | $(Q)$(INSTALL) $(APPS) $(DESTDIR)$(prefix)/bin 73 | 74 | run: 75 | sudo ./trafficstat 76 | 77 | # delete failed targets 78 | .DELETE_ON_ERROR: 79 | # keep intermediate (.skel.h, .bpf.o, etc) targets 80 | .SECONDARY: 81 | -------------------------------------------------------------------------------- /tc-traffic-stat/pcap/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #define ETHERNET_HEADER_LEN 14 11 | #define MIN_IP_HEADER_LEN 20 12 | #define IP_HL(ip) (((ip)->ihl) & 0x0f) 13 | 14 | const char* dev = "br-7e20abc6df31"; 15 | const char* filter_expr = "src net 172.20.0.0/16"; 16 | 17 | int64_t traffic = 0; 18 | 19 | // Reference: 20 | // https://www.tcpdump.org/manpages/ 21 | // https://tools.ietf.org/html/rfc791 22 | void traffic_stat() { 23 | // find the IPv4 network number and netmask for a device 24 | bpf_u_int32 net = 0; 25 | bpf_u_int32 mask = 0; 26 | char errbuf[PCAP_ERRBUF_SIZE] = {0}; 27 | int ret = pcap_lookupnet(dev, &net, &mask, errbuf); 28 | if (ret == PCAP_ERROR) { 29 | fprintf(stderr, "pcap_lookupnet failed: %s\n", errbuf); 30 | exit(EXIT_FAILURE); 31 | } 32 | 33 | // open a device for capturing 34 | int promisc = 1; 35 | int timeout = 1000; // in milliseconds 36 | const int SNAP_LEN = 64; 37 | auto handle = pcap_open_live(dev, SNAP_LEN, promisc, timeout, errbuf); 38 | if (!handle) { 39 | fprintf(stderr, "pcap_open_live failed: %s\n", errbuf); 40 | exit(EXIT_FAILURE); 41 | } 42 | 43 | // compile a filter expression 44 | struct bpf_program fp; 45 | int optimize = 1; 46 | ret = pcap_compile(handle, &fp, filter_expr, optimize, net); 47 | if (ret == PCAP_ERROR) { 48 | fprintf(stderr, "pcap_compile failed: %s\n", pcap_geterr(handle)); 49 | exit(EXIT_FAILURE); 50 | } 51 | 52 | // set the filter 53 | ret = pcap_setfilter(handle, &fp); 54 | if (ret == PCAP_ERROR) { 55 | fprintf(stderr, "pcap_setfilter failed: %s\n", pcap_geterr(handle)); 56 | exit(EXIT_FAILURE); 57 | } 58 | 59 | // process packets from a live capture 60 | int packet_count = -1; // -1 means infinity 61 | pcap_loop(handle, packet_count, [](u_char* args, const struct pcap_pkthdr* header, const u_char* bytes) { 62 | 63 | auto ip_header = reinterpret_cast(const_cast(bytes) + ETHERNET_HEADER_LEN); 64 | const int ip_header_len = IP_HL(ip_header) * 4; 65 | if (ip_header_len < MIN_IP_HEADER_LEN) { 66 | return; 67 | } 68 | 69 | auto len = ntohs(ip_header->tot_len); 70 | if (len <= 0) { 71 | return; 72 | } 73 | 74 | auto traffic = reinterpret_cast(args); 75 | *traffic += len; 76 | 77 | }, reinterpret_cast(&traffic)); 78 | 79 | // free a BPF program 80 | pcap_freecode(&fp); 81 | // close the capture device 82 | pcap_close(handle); 83 | } 84 | 85 | int main() { 86 | auto task = std::async(std::launch::async, traffic_stat); 87 | while (true) { 88 | std::this_thread::sleep_for(std::chrono::seconds(10)); 89 | printf("traffic in bytes: %ld\n", traffic); 90 | } 91 | task.wait(); 92 | return 0; 93 | } 94 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------