forked from iovisor/bcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcptracer.py
executable file
·688 lines (572 loc) · 17.9 KB
/
tcptracer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
#!/usr/bin/env python
#
# tcpv4tracer Trace TCP connections.
# For Linux, uses BCC, eBPF. Embedded C.
#
# USAGE: tcpv4tracer [-h] [-v] [-p PID] [-N NETNS] [-4 | -6]
#
# You should generally try to avoid writing long scripts that measure multiple
# functions and walk multiple kernel structures, as they will be a burden to
# maintain as the kernel changes.
# The following code should be replaced, and simplified, when static TCP probes
# exist.
#
# Copyright 2017-2020 Kinvolk GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License")
from __future__ import print_function
from bcc import BPF
from bcc.containers import filter_by_containers
import argparse as ap
from socket import inet_ntop, AF_INET, AF_INET6
from struct import pack
parser = ap.ArgumentParser(description="Trace TCP connections",
formatter_class=ap.RawDescriptionHelpFormatter)
parser.add_argument("-t", "--timestamp", action="store_true",
help="include timestamp on output")
parser.add_argument("-p", "--pid", default=0, type=int,
help="trace this PID only")
parser.add_argument("-N", "--netns", default=0, type=int,
help="trace this Network Namespace only")
parser.add_argument("--cgroupmap",
help="trace cgroups in this BPF map only")
parser.add_argument("--mntnsmap",
help="trace mount namespaces in this BPF map only")
group = parser.add_mutually_exclusive_group()
group.add_argument("-4", "--ipv4", action="store_true",
help="trace IPv4 family only")
group.add_argument("-6", "--ipv6", action="store_true",
help="trace IPv6 family only")
parser.add_argument("-v", "--verbose", action="store_true",
help="include Network Namespace in the output")
parser.add_argument("--ebpf", action="store_true",
help=ap.SUPPRESS)
args = parser.parse_args()
bpf_text = """
#include <uapi/linux/ptrace.h>
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wtautological-compare"
#include <net/sock.h>
#pragma clang diagnostic pop
#include <net/inet_sock.h>
#include <net/net_namespace.h>
#include <bcc/proto.h>
#define TCP_EVENT_TYPE_CONNECT 1
#define TCP_EVENT_TYPE_ACCEPT 2
#define TCP_EVENT_TYPE_CLOSE 3
struct tcp_ipv4_event_t {
u64 ts_ns;
u32 type;
u32 pid;
char comm[TASK_COMM_LEN];
u8 ip;
u32 saddr;
u32 daddr;
u16 sport;
u16 dport;
u32 netns;
};
BPF_PERF_OUTPUT(tcp_ipv4_event);
struct tcp_ipv6_event_t {
u64 ts_ns;
u32 type;
u32 pid;
char comm[TASK_COMM_LEN];
unsigned __int128 saddr;
unsigned __int128 daddr;
u16 sport;
u16 dport;
u32 netns;
u8 ip;
};
BPF_PERF_OUTPUT(tcp_ipv6_event);
// tcp_set_state doesn't run in the context of the process that initiated the
// connection so we need to store a map TUPLE -> PID to send the right PID on
// the event
struct ipv4_tuple_t {
u32 saddr;
u32 daddr;
u16 sport;
u16 dport;
u32 netns;
};
struct ipv6_tuple_t {
unsigned __int128 saddr;
unsigned __int128 daddr;
u16 sport;
u16 dport;
u32 netns;
};
struct pid_comm_t {
u64 pid;
char comm[TASK_COMM_LEN];
};
BPF_HASH(tuplepid_ipv4, struct ipv4_tuple_t, struct pid_comm_t);
BPF_HASH(tuplepid_ipv6, struct ipv6_tuple_t, struct pid_comm_t);
BPF_HASH(connectsock, u64, struct sock *);
static int read_ipv4_tuple(struct ipv4_tuple_t *tuple, struct sock *skp)
{
u32 net_ns_inum = 0;
u32 saddr = skp->__sk_common.skc_rcv_saddr;
u32 daddr = skp->__sk_common.skc_daddr;
struct inet_sock *sockp = (struct inet_sock *)skp;
u16 sport = sockp->inet_sport;
u16 dport = skp->__sk_common.skc_dport;
#ifdef CONFIG_NET_NS
net_ns_inum = skp->__sk_common.skc_net.net->ns.inum;
#endif
##FILTER_NETNS##
tuple->saddr = saddr;
tuple->daddr = daddr;
tuple->sport = sport;
tuple->dport = dport;
tuple->netns = net_ns_inum;
// if addresses or ports are 0, ignore
if (saddr == 0 || daddr == 0 || sport == 0 || dport == 0) {
return 0;
}
return 1;
}
static int read_ipv6_tuple(struct ipv6_tuple_t *tuple, struct sock *skp)
{
u32 net_ns_inum = 0;
unsigned __int128 saddr = 0, daddr = 0;
struct inet_sock *sockp = (struct inet_sock *)skp;
u16 sport = sockp->inet_sport;
u16 dport = skp->__sk_common.skc_dport;
#ifdef CONFIG_NET_NS
net_ns_inum = skp->__sk_common.skc_net.net->ns.inum;
#endif
bpf_probe_read_kernel(&saddr, sizeof(saddr),
skp->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32);
bpf_probe_read_kernel(&daddr, sizeof(daddr),
skp->__sk_common.skc_v6_daddr.in6_u.u6_addr32);
##FILTER_NETNS##
tuple->saddr = saddr;
tuple->daddr = daddr;
tuple->sport = sport;
tuple->dport = dport;
tuple->netns = net_ns_inum;
// if addresses or ports are 0, ignore
if (saddr == 0 || daddr == 0 || sport == 0 || dport == 0) {
return 0;
}
return 1;
}
static bool check_family(struct sock *sk, u16 expected_family) {
u64 zero = 0;
u16 family = sk->__sk_common.skc_family;
return family == expected_family;
}
int trace_connect_v4_entry(struct pt_regs *ctx, struct sock *sk)
{
if (container_should_be_filtered()) {
return 0;
}
u64 pid = bpf_get_current_pid_tgid();
##FILTER_PID##
u16 family = sk->__sk_common.skc_family;
##FILTER_FAMILY##
// stash the sock ptr for lookup on return
connectsock.update(&pid, &sk);
return 0;
}
int trace_connect_v4_return(struct pt_regs *ctx)
{
int ret = PT_REGS_RC(ctx);
u64 pid = bpf_get_current_pid_tgid();
struct sock **skpp;
skpp = connectsock.lookup(&pid);
if (skpp == 0) {
return 0; // missed entry
}
connectsock.delete(&pid);
if (ret != 0) {
// failed to send SYNC packet, may not have populated
// socket __sk_common.{skc_rcv_saddr, ...}
return 0;
}
// pull in details
struct sock *skp = *skpp;
struct ipv4_tuple_t t = { };
if (!read_ipv4_tuple(&t, skp)) {
return 0;
}
struct pid_comm_t p = { };
p.pid = pid;
bpf_get_current_comm(&p.comm, sizeof(p.comm));
tuplepid_ipv4.update(&t, &p);
return 0;
}
int trace_connect_v6_entry(struct pt_regs *ctx, struct sock *sk)
{
if (container_should_be_filtered()) {
return 0;
}
u64 pid = bpf_get_current_pid_tgid();
##FILTER_PID##
u16 family = sk->__sk_common.skc_family;
##FILTER_FAMILY##
// stash the sock ptr for lookup on return
connectsock.update(&pid, &sk);
return 0;
}
int trace_connect_v6_return(struct pt_regs *ctx)
{
int ret = PT_REGS_RC(ctx);
u64 pid = bpf_get_current_pid_tgid();
struct sock **skpp;
skpp = connectsock.lookup(&pid);
if (skpp == 0) {
return 0; // missed entry
}
connectsock.delete(&pid);
if (ret != 0) {
// failed to send SYNC packet, may not have populated
// socket __sk_common.{skc_rcv_saddr, ...}
return 0;
}
// pull in details
struct sock *skp = *skpp;
struct ipv6_tuple_t t = { };
if (!read_ipv6_tuple(&t, skp)) {
return 0;
}
struct pid_comm_t p = { };
p.pid = pid;
bpf_get_current_comm(&p.comm, sizeof(p.comm));
tuplepid_ipv6.update(&t, &p);
return 0;
}
int trace_tcp_set_state_entry(struct pt_regs *ctx, struct sock *skp, int state)
{
if (state != TCP_ESTABLISHED && state != TCP_CLOSE) {
return 0;
}
u16 family = skp->__sk_common.skc_family;
##FILTER_FAMILY##
u8 ipver = 0;
if (check_family(skp, AF_INET)) {
ipver = 4;
struct ipv4_tuple_t t = { };
if (!read_ipv4_tuple(&t, skp)) {
return 0;
}
if (state == TCP_CLOSE) {
tuplepid_ipv4.delete(&t);
return 0;
}
struct pid_comm_t *p;
p = tuplepid_ipv4.lookup(&t);
if (p == 0) {
return 0; // missed entry
}
struct tcp_ipv4_event_t evt4 = { };
evt4.ts_ns = bpf_ktime_get_ns();
evt4.type = TCP_EVENT_TYPE_CONNECT;
evt4.pid = p->pid >> 32;
evt4.ip = ipver;
evt4.saddr = t.saddr;
evt4.daddr = t.daddr;
evt4.sport = ntohs(t.sport);
evt4.dport = ntohs(t.dport);
evt4.netns = t.netns;
int i;
for (i = 0; i < TASK_COMM_LEN; i++) {
evt4.comm[i] = p->comm[i];
}
tcp_ipv4_event.perf_submit(ctx, &evt4, sizeof(evt4));
tuplepid_ipv4.delete(&t);
} else if (check_family(skp, AF_INET6)) {
ipver = 6;
struct ipv6_tuple_t t = { };
if (!read_ipv6_tuple(&t, skp)) {
return 0;
}
if (state == TCP_CLOSE) {
tuplepid_ipv6.delete(&t);
return 0;
}
struct pid_comm_t *p;
p = tuplepid_ipv6.lookup(&t);
if (p == 0) {
return 0; // missed entry
}
struct tcp_ipv6_event_t evt6 = { };
evt6.ts_ns = bpf_ktime_get_ns();
evt6.type = TCP_EVENT_TYPE_CONNECT;
evt6.pid = p->pid >> 32;
evt6.ip = ipver;
evt6.saddr = t.saddr;
evt6.daddr = t.daddr;
evt6.sport = ntohs(t.sport);
evt6.dport = ntohs(t.dport);
evt6.netns = t.netns;
int i;
for (i = 0; i < TASK_COMM_LEN; i++) {
evt6.comm[i] = p->comm[i];
}
tcp_ipv6_event.perf_submit(ctx, &evt6, sizeof(evt6));
tuplepid_ipv6.delete(&t);
}
// else drop
return 0;
}
int trace_close_entry(struct pt_regs *ctx, struct sock *skp)
{
if (container_should_be_filtered()) {
return 0;
}
u64 pid = bpf_get_current_pid_tgid();
##FILTER_PID##
u16 family = skp->__sk_common.skc_family;
##FILTER_FAMILY##
u8 oldstate = skp->sk_state;
// Don't generate close events for connections that were never
// established in the first place.
if (oldstate == TCP_SYN_SENT ||
oldstate == TCP_SYN_RECV ||
oldstate == TCP_NEW_SYN_RECV)
return 0;
u8 ipver = 0;
if (check_family(skp, AF_INET)) {
ipver = 4;
struct ipv4_tuple_t t = { };
if (!read_ipv4_tuple(&t, skp)) {
return 0;
}
struct tcp_ipv4_event_t evt4 = { };
evt4.ts_ns = bpf_ktime_get_ns();
evt4.type = TCP_EVENT_TYPE_CLOSE;
evt4.pid = pid >> 32;
evt4.ip = ipver;
evt4.saddr = t.saddr;
evt4.daddr = t.daddr;
evt4.sport = ntohs(t.sport);
evt4.dport = ntohs(t.dport);
evt4.netns = t.netns;
bpf_get_current_comm(&evt4.comm, sizeof(evt4.comm));
tcp_ipv4_event.perf_submit(ctx, &evt4, sizeof(evt4));
} else if (check_family(skp, AF_INET6)) {
ipver = 6;
struct ipv6_tuple_t t = { };
if (!read_ipv6_tuple(&t, skp)) {
return 0;
}
struct tcp_ipv6_event_t evt6 = { };
evt6.ts_ns = bpf_ktime_get_ns();
evt6.type = TCP_EVENT_TYPE_CLOSE;
evt6.pid = pid >> 32;
evt6.ip = ipver;
evt6.saddr = t.saddr;
evt6.daddr = t.daddr;
evt6.sport = ntohs(t.sport);
evt6.dport = ntohs(t.dport);
evt6.netns = t.netns;
bpf_get_current_comm(&evt6.comm, sizeof(evt6.comm));
tcp_ipv6_event.perf_submit(ctx, &evt6, sizeof(evt6));
}
// else drop
return 0;
};
int trace_accept_return(struct pt_regs *ctx)
{
if (container_should_be_filtered()) {
return 0;
}
struct sock *newsk = (struct sock *)PT_REGS_RC(ctx);
u64 pid = bpf_get_current_pid_tgid();
##FILTER_PID##
if (newsk == NULL) {
return 0;
}
// pull in details
u16 lport = 0, dport = 0;
u32 net_ns_inum = 0;
u8 ipver = 0;
dport = newsk->__sk_common.skc_dport;
lport = newsk->__sk_common.skc_num;
// Get network namespace id, if kernel supports it
#ifdef CONFIG_NET_NS
net_ns_inum = newsk->__sk_common.skc_net.net->ns.inum;
#endif
##FILTER_NETNS##
u16 family = newsk->__sk_common.skc_family;
##FILTER_FAMILY##
if (check_family(newsk, AF_INET)) {
ipver = 4;
struct tcp_ipv4_event_t evt4 = { 0 };
evt4.ts_ns = bpf_ktime_get_ns();
evt4.type = TCP_EVENT_TYPE_ACCEPT;
evt4.netns = net_ns_inum;
evt4.pid = pid >> 32;
evt4.ip = ipver;
evt4.saddr = newsk->__sk_common.skc_rcv_saddr;
evt4.daddr = newsk->__sk_common.skc_daddr;
evt4.sport = lport;
evt4.dport = ntohs(dport);
bpf_get_current_comm(&evt4.comm, sizeof(evt4.comm));
// do not send event if IP address is 0.0.0.0 or port is 0
if (evt4.saddr != 0 && evt4.daddr != 0 &&
evt4.sport != 0 && evt4.dport != 0) {
tcp_ipv4_event.perf_submit(ctx, &evt4, sizeof(evt4));
}
} else if (check_family(newsk, AF_INET6)) {
ipver = 6;
struct tcp_ipv6_event_t evt6 = { 0 };
evt6.ts_ns = bpf_ktime_get_ns();
evt6.type = TCP_EVENT_TYPE_ACCEPT;
evt6.netns = net_ns_inum;
evt6.pid = pid >> 32;
evt6.ip = ipver;
bpf_probe_read_kernel(&evt6.saddr, sizeof(evt6.saddr),
newsk->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32);
bpf_probe_read_kernel(&evt6.daddr, sizeof(evt6.daddr),
newsk->__sk_common.skc_v6_daddr.in6_u.u6_addr32);
evt6.sport = lport;
evt6.dport = ntohs(dport);
bpf_get_current_comm(&evt6.comm, sizeof(evt6.comm));
// do not send event if IP address is 0.0.0.0 or port is 0
if (evt6.saddr != 0 && evt6.daddr != 0 &&
evt6.sport != 0 && evt6.dport != 0) {
tcp_ipv6_event.perf_submit(ctx, &evt6, sizeof(evt6));
}
}
// else drop
return 0;
}
"""
verbose_types = {"C": "connect", "A": "accept",
"X": "close", "U": "unknown"}
def print_ipv4_event(cpu, data, size):
event = b["tcp_ipv4_event"].event(data)
global start_ts
if args.timestamp:
if start_ts == 0:
start_ts = event.ts_ns
if args.verbose:
print("%-14d" % (event.ts_ns - start_ts), end="")
else:
print("%-9.3f" % ((event.ts_ns - start_ts) / 1000000000.0), end="")
if event.type == 1:
type_str = "C"
elif event.type == 2:
type_str = "A"
elif event.type == 3:
type_str = "X"
else:
type_str = "U"
if args.verbose:
print("%-12s " % (verbose_types[type_str]), end="")
else:
print("%-2s " % (type_str), end="")
print("%-6d %-16s %-2d %-16s %-16s %-6d %-6d" %
(event.pid, event.comm.decode('utf-8', 'replace'),
event.ip,
inet_ntop(AF_INET, pack("I", event.saddr)),
inet_ntop(AF_INET, pack("I", event.daddr)),
event.sport,
event.dport), end="")
if args.verbose and not args.netns:
print(" %-8d" % event.netns)
else:
print()
def print_ipv6_event(cpu, data, size):
event = b["tcp_ipv6_event"].event(data)
global start_ts
if args.timestamp:
if start_ts == 0:
start_ts = event.ts_ns
if args.verbose:
print("%-14d" % (event.ts_ns - start_ts), end="")
else:
print("%-9.3f" % ((event.ts_ns - start_ts) / 1000000000.0), end="")
if event.type == 1:
type_str = "C"
elif event.type == 2:
type_str = "A"
elif event.type == 3:
type_str = "X"
else:
type_str = "U"
if args.verbose:
print("%-12s " % (verbose_types[type_str]), end="")
else:
print("%-2s " % (type_str), end="")
print("%-6d %-16s %-2d %-16s %-16s %-6d %-6d" %
(event.pid, event.comm.decode('utf-8', 'replace'),
event.ip,
"[" + inet_ntop(AF_INET6, event.saddr) + "]",
"[" + inet_ntop(AF_INET6, event.daddr) + "]",
event.sport,
event.dport), end="")
if args.verbose and not args.netns:
print(" %-8d" % event.netns)
else:
print()
pid_filter = ""
netns_filter = ""
if args.pid:
pid_filter = 'if (pid >> 32 != %d) { return 0; }' % args.pid
if args.netns:
netns_filter = 'if (net_ns_inum != %d) { return 0; }' % args.netns
if args.ipv4:
bpf_text = bpf_text.replace('##FILTER_FAMILY##',
'if (family != AF_INET) { return 0; }')
elif args.ipv6:
bpf_text = bpf_text.replace('##FILTER_FAMILY##',
'if (family != AF_INET6) { return 0; }')
bpf_text = bpf_text.replace('##FILTER_FAMILY##', '')
bpf_text = bpf_text.replace('##FILTER_PID##', pid_filter)
bpf_text = bpf_text.replace('##FILTER_NETNS##', netns_filter)
bpf_text = filter_by_containers(args) + bpf_text
if args.ebpf:
print(bpf_text)
exit()
# initialize BPF
b = BPF(text=bpf_text)
if args.ipv4:
b.attach_kprobe(event="tcp_v4_connect", fn_name="trace_connect_v4_entry")
b.attach_kretprobe(event="tcp_v4_connect", fn_name="trace_connect_v4_return")
elif args.ipv6:
b.attach_kprobe(event="tcp_v6_connect", fn_name="trace_connect_v6_entry")
b.attach_kretprobe(event="tcp_v6_connect", fn_name="trace_connect_v6_return")
else:
b.attach_kprobe(event="tcp_v4_connect", fn_name="trace_connect_v4_entry")
b.attach_kretprobe(event="tcp_v4_connect", fn_name="trace_connect_v4_return")
b.attach_kprobe(event="tcp_v6_connect", fn_name="trace_connect_v6_entry")
b.attach_kretprobe(event="tcp_v6_connect", fn_name="trace_connect_v6_return")
b.attach_kprobe(event="tcp_set_state", fn_name="trace_tcp_set_state_entry")
b.attach_kprobe(event="tcp_close", fn_name="trace_close_entry")
b.attach_kretprobe(event="inet_csk_accept", fn_name="trace_accept_return")
print("Tracing TCP established connections. Ctrl-C to end.")
# header
if args.verbose:
if args.timestamp:
print("%-14s" % ("TIME(ns)"), end="")
print("%-12s %-6s %-16s %-2s %-16s %-16s %-6s %-7s" % ("TYPE",
"PID", "COMM", "IP", "SADDR", "DADDR", "SPORT", "DPORT"), end="")
if not args.netns:
print("%-8s" % "NETNS", end="")
print()
else:
if args.timestamp:
print("%-9s" % ("TIME(s)"), end="")
print("%-2s %-6s %-16s %-2s %-16s %-16s %-6s %-6s" %
("T", "PID", "COMM", "IP", "SADDR", "DADDR", "SPORT", "DPORT"))
start_ts = 0
def inet_ntoa(addr):
dq = ''
for i in range(0, 4):
dq = dq + str(addr & 0xff)
if (i != 3):
dq = dq + '.'
addr = addr >> 8
return dq
b["tcp_ipv4_event"].open_perf_buffer(print_ipv4_event)
b["tcp_ipv6_event"].open_perf_buffer(print_ipv6_event)
while True:
try:
b.perf_buffer_poll()
except KeyboardInterrupt:
exit()