Upgrade to Pro — share decks privately, control downloads, hide ads and more …

RubyでXDPプログラミング

Yukimitsu Izawa
January 18, 2025
3

 RubyでXDPプログラミング

北陸三県.rb Lightning Talks in Kanazawa (2025/01/18) での発表資料。
RubyでBCC経由でXDPプログラミングをするまでの紹介。

Yukimitsu Izawa

January 18, 2025
Tweet

Transcript

  1. ࣗݾ঺հ w :PV5VCFS ‣ .Z0VUEPPS-JGF IUUQTLBOB[BXBDBNQ  w ത࢜ ৘ใՊֶ

     ‣ ΠϯλʔωοτΛ࢖ͬͨૄ݁߹෼ࢄγεςϜͷݚڀΛ͍ͯ͠·͢ w גࣜձࣾΫϧ΢Οοτऔక໾$00݉๺཮ࢧࣾ௕ w $PEFGPS,BOB[BXBཧࣄ w ిࢠ޻࡞φΠϑ੍࡞ϨβʔΫϥϑτͳͲɺ΋ͷΛ࡞Δͷ͕झຯͰ͢
  2. 9%1ͷ࢓૊Έ /*$ 5$1*14UBDL 9%1FOWJSPONFOU 9%1ॲཧ 9%1@%301 9%1@1"44 9%1@59 /*$%SJWFS w

    /*$ͷυϥΠό಺Ͱ࣮ߦ w ύέοτ౸ணຖʹ)PPL͞ΕΔ w ύέοτͷॲ۰ΛܾΊΔ ‣ 9%1@1"44*14UBDLʹ্͛Δ ‣ 9%1@%301ࣺͯΔ ‣ 9%1@59ड৴ͨ͠/*$͔ΒૹΔ ‣ 9%1@3&%*3&$5ผͷ/*$͔ΒૹΔ
  3. 1 require 'rbbcc' 2 include RbBCC 3 4 5 print

    "loading..." 6 STDOUT.flush 7 8 b = BCC.new(text: <<BPF) 9 10 #include <uapi/linux/bpf.h> 11 #include <linux/ip.h> 12 #include <linux/icmp.h> 13 14 15 int xdp_drop_icmp(struct xdp_md *ctx) { 16 void* data_end = (void*)(long)ctx->data_end; 17 void* data = (void*)(long)ctx->data; 18 struct ethhdr *eth = data; 19 u32 protocol; 20 u16 sequence; 21 u64 nh_off = sizeof(*eth); 22 23 // for validator 24 if (data + nh_off > data_end) 25 return XDP_PASS; 26 27 if (eth->h_proto == htons(ETH_P_IP)) { 28 struct iphdr *iph = data + nh_off; 29 29 30 // for validator 31 if ((void*)&iph[1] > data_end) 32 return XDP_PASS; 33 34 protocol = iph->protocol; 35 if (protocol == 1) { /* ICMP */ 36 struct icmphdr *icmph = data + nh_off + iph->ihl * 4; 37 38 // for validator 39 if ((void*)&icmph[1] > data_end) 40 return XDP_PASS; 41 42 if (icmph->type == 8) { /* ECHO REQUEST */ 43 if (icmph->un.echo.sequence > 0 && 44 icmph->un.echo.sequence % 3 == 0) { 45 return XDP_PASS; 46 } 47 else return XDP_DROP; 48 } 49 } 50 } 51 return XDP_PASS; 52 } 53 BPF 54 55 fn = b.load_func("xdp_drop_icmp", BPF::XDP) 56 puts "done." 57 58 b.attach_xdp("eth0", "xdp_drop_icmp") 59 sleep(20) 60 b.remove_xdp("eth0") αϯϓϧϓϩάϥϜYEQ@JDNQSC