Last active
April 18, 2019 10:15
-
-
Save pandax381/d91e662ce50a4bd3b56bf1d48836b085 to your computer and use it in GitHub Desktop.
Trace reuse TCP connection in TIME_WAIT state
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
from __future__ import print_function | |
from bcc import BPF | |
from socket import inet_ntop, ntohs, AF_INET, AF_INET6 | |
from struct import pack | |
b = BPF(text=""" | |
#include <uapi/linux/ptrace.h> | |
#include <net/sock.h> | |
#include <bcc/proto.h> | |
BPF_HASH(currsock, u32, struct sock *); | |
struct data_t { | |
u64 ts; | |
u32 pid; | |
u32 saddr; | |
u32 daddr; | |
u16 sport; | |
u16 dport; | |
}; | |
BPF_PERF_OUTPUT(events); | |
int trace_tcp_twsk_unique(struct pt_regs *ctx, struct sock *sk, struct sock *sktw, void *twp) | |
{ | |
u32 pid = bpf_get_current_pid_tgid(); | |
currsock.update(&pid, &sktw); | |
return 0; | |
} | |
int trace_tcp_twsk_unique_return(struct pt_regs *ctx) | |
{ | |
int ret = PT_REGS_RC(ctx); | |
struct sock **skpp; | |
u32 pid = bpf_get_current_pid_tgid(); | |
skpp = currsock.lookup(&pid); | |
if (!skpp) { | |
return 0; | |
} | |
if (ret == 0) { | |
currsock.delete(&pid); | |
return 0; | |
} | |
struct sock *skp = *skpp; | |
struct data_t data = {}; | |
data.ts = bpf_ktime_get_ns(); | |
data.pid = pid; | |
data.saddr = skp->sk_rcv_saddr; | |
data.daddr = skp->sk_daddr; | |
data.sport = skp->sk_num; | |
data.dport = skp->sk_dport; | |
events.perf_submit(ctx, &data, sizeof(data)); | |
return 0; | |
} | |
""") | |
b.attach_kprobe(event="tcp_twsk_unique", fn_name="trace_tcp_twsk_unique") | |
b.attach_kretprobe(event="tcp_twsk_unique", fn_name="trace_tcp_twsk_unique_return") | |
print("%-18s %-5s %21s > %-21s" % ("TIME(s)", "PID", "SRC(addr:port)", "DST(addr:port)")) | |
start = 0 | |
def print_event(cpu, data, size): | |
global start | |
event = b["events"].event(data) | |
if start == 0: | |
start = event.ts | |
time_s = (float(event.ts - start)) / 1000000000 | |
print("%-18.9f %-5d %21s > %-21s" % (time_s, event.pid, "%15s:%-5d" % (inet_ntop(AF_INET, pack('I', event.saddr)), ntohs(event.sport)), "%s:%d" % (inet_ntop(AF_INET, pack('I', event.daddr)), ntohs(event.dport)))) | |
b["events"].open_perf_buffer(print_event) | |
while 1: | |
try: | |
b.perf_buffer_poll() | |
except KeyboardInterrupt: | |
exit() |
Author
pandax381
commented
Apr 17, 2019
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment