这会儿不是工作日,这会儿是周六。
systemtap就是一个kprobe的DSL,本质上完成的是同一类工作,kprobe用起来比较麻烦,还要自己编写编译内核模块,相比而言,stap就方便很多。
既然kprobe可以修改内核结构体的内容,那么也就可以修改网络数据包咯,前面的文章描述了如何迷惑程序员的抓包行为,本文展示一下如何实现一个NAT端口转换逻辑,代码如下:
1#!/usr/bin/stap -g 2 3%{ 4#include <linux/tcp.h> 5#include <linux/ip.h> 6%} 7 8// 将来源于100.100.100.2的访问端口12345的流转换到访问22 9function port_transform(skb:long, type:long) 10%{ 11 struct sk_buff *skb2 = (struct sk_buff *)STAP_ARG_skb; 12 struct iphdr *iph; 13 struct tcphdr *th; 14 15 iph = ip_hdr(skb2); 16 if (iph->protocol != IPPROTO_TCP) 17 return; 18 th = (struct tcphdr *)((unsigned char *)iph + (iph->ihl * 4)); 19 if (STAP_ARG_type == 0 && iph->saddr == 0x02646464 && ntohs(th->dest) == 12345) { 20 __be16 dest = th->dest; 21 th->dest = htons(22); 22 inet_proto_csum_replace2(&th->check, skb2, dest, htons(22), 0); 23 } 24 if (STAP_ARG_type == 1 && iph->daddr == 0x02646464 && ntohs(th->source) == 22) { 25 __be16 source = th->source; 26 th->source = htons(12345); 27 inet_proto_csum_replace2(&th->check, skb2, source, htons(12345), 0); 28 } 29%} 30 31probe kernel.function("ip_rcv_finish") 32{ 33 port_transform($skb, 0); 34} 35 36probe kernel.function("ip_output") 37{ 38 port_transform($skb, 1); 39}
为了让代码保持短,我硬编码了规则:
- 将来自100.100.100.2的访问TCP端口12345的包转换为访问TCP端口22的包。
在100.100.100.2这台机器上测试一下telnet 100.100.100.1 12345显然是通的。
我这个脚本意义在于可以在正式开发之前先搞POC,除此之外就没有别的意义了,没人会在生产环境拿kprobe跑业务流量,诸如int 3,单步指令会影响性能balabalabala…
浙江温州皮鞋湿,下雨进水不会胖。