Skip to content

Instantly share code, notes, and snippets.

@kyontan
Created December 27, 2020 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyontan/cd92f23631caf3b37bc552836bbd61f3 to your computer and use it in GitHub Desktop.
Save kyontan/cd92f23631caf3b37bc552836bbd61f3 to your computer and use it in GitHub Desktop.
pyroute2 + SRv6 example
#include <linux/bpf.h>
int pass(struct __sk_buff *skb) {
return BPF_OK; // packet continues
// return BPF_DROP; // packet drops
}
from bcc import BPF
from pyroute2 import IPRoute
from time import sleep
import sys, signal
b = BPF(src_file="bpf.c")
fn = b.load_func("pass", 19)
# 19 means BPF_PROG_TYPE_LWT_SEG6LOCAL
# https://github.com/torvalds/linux/blob/3cb12d27ff655e57e8efe3486dca2a22f4e30578/include/uapi/linux/bpf.h#L190
ipr = IPRoute()
idx = ipr.link_lookup(ifname="eth0")[0] # interface to attach
sid = 'fd00::1/128'
encap = {'type':'seg6local', 'action':'End.BPF', 'bpf':{'fd':fn.fd, 'name':fn.name}}
ipr.route("add", dst=sid, oif=idx, encap=encap)
print(f"Attached func {fn.name} to {sid}")
def remove_rt(sig, fr):
ipr.route("del", dst=sid, oif=idx)
print(f"Detached func {fn.name} from {sid}")
sys.exit(0)
signal.signal(signal.SIGTERM, remove_rt)
signal.signal(signal.SIGINT, remove_rt)
while True:
sleep(0.01)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment