blob: ec5bb7b356975d6264da14db9d2b28cda2ba070d [file] [log] [blame]
Alexey Ivanovcc01a9c2019-01-16 09:50:46 -08001#!/usr/bin/python
Gerald Combsabdca972018-11-26 23:37:24 -07002# -*- coding: utf-8 -*-
Brendan Greggbbd9acd2018-03-20 18:35:12 -07003# @lint-avoid-python-3-compatibility-imports
4#
5# tcpstates Trace the TCP session state changes with durations.
6# For Linux, uses BCC, BPF. Embedded C.
7#
8# USAGE: tcpstates [-h] [-C] [-S] [interval [count]]
9#
10# This uses the sock:inet_sock_set_state tracepoint, added to Linux 4.16.
11# Linux 4.16 also adds more state transitions so that they can be traced.
12#
13# Copyright 2018 Netflix, Inc.
14# Licensed under the Apache License, Version 2.0 (the "License")
15#
16# 20-Mar-2018 Brendan Gregg Created this.
17
18from __future__ import print_function
19from bcc import BPF
20import argparse
21from socket import inet_ntop, AF_INET, AF_INET6
22from struct import pack
Gerald Combsabdca972018-11-26 23:37:24 -070023from time import strftime, time
24from os import getuid
Brendan Greggbbd9acd2018-03-20 18:35:12 -070025
26# arguments
27examples = """examples:
28 ./tcpstates # trace all TCP state changes
29 ./tcpstates -t # include timestamp column
30 ./tcpstates -T # include time column (HH:MM:SS)
Michael Prokopc14d02a2020-01-09 02:29:18 +010031 ./tcpstates -w # wider columns (fit IPv6)
Brendan Greggbbd9acd2018-03-20 18:35:12 -070032 ./tcpstates -stT # csv output, with times & timestamps
Gerald Combsabdca972018-11-26 23:37:24 -070033 ./tcpstates -Y # log events to the systemd journal
Brendan Greggbbd9acd2018-03-20 18:35:12 -070034 ./tcpstates -L 80 # only trace local port 80
35 ./tcpstates -L 80,81 # only trace local ports 80 and 81
36 ./tcpstates -D 80 # only trace remote port 80
37"""
38parser = argparse.ArgumentParser(
39 description="Trace TCP session state changes and durations",
40 formatter_class=argparse.RawDescriptionHelpFormatter,
41 epilog=examples)
42parser.add_argument("-T", "--time", action="store_true",
43 help="include time column on output (HH:MM:SS)")
44parser.add_argument("-t", "--timestamp", action="store_true",
45 help="include timestamp on output (seconds)")
46parser.add_argument("-w", "--wide", action="store_true",
47 help="wide column output (fits IPv6 addresses)")
48parser.add_argument("-s", "--csv", action="store_true",
49 help="comma separated values output")
50parser.add_argument("-L", "--localport",
51 help="comma-separated list of local ports to trace.")
52parser.add_argument("-D", "--remoteport",
53 help="comma-separated list of remote ports to trace.")
54parser.add_argument("--ebpf", action="store_true",
55 help=argparse.SUPPRESS)
Gerald Combsabdca972018-11-26 23:37:24 -070056parser.add_argument("-Y", "--journal", action="store_true",
57 help="log session state changes to the systemd journal")
Brendan Greggbbd9acd2018-03-20 18:35:12 -070058args = parser.parse_args()
59debug = 0
60
61# define BPF program
Daniel Poelzleithnerd0ec8a22020-03-12 12:31:39 +010062bpf_header = """
Brendan Greggbbd9acd2018-03-20 18:35:12 -070063#include <uapi/linux/ptrace.h>
Brendan Greggbbd9acd2018-03-20 18:35:12 -070064#include <linux/tcp.h>
65#include <net/sock.h>
66#include <bcc/proto.h>
67
68BPF_HASH(last, struct sock *, u64);
69
70// separate data structs for ipv4 and ipv6
71struct ipv4_data_t {
Brendan Greggbbd9acd2018-03-20 18:35:12 -070072 u64 ts_us;
73 u64 skaddr;
Joe Yin36ce1122018-08-17 06:04:00 +080074 u32 saddr;
75 u32 daddr;
Brendan Greggbbd9acd2018-03-20 18:35:12 -070076 u64 span_us;
Brendan Gregg2b23de62018-03-21 15:41:16 -070077 u32 pid;
78 u32 ports;
79 u32 oldstate;
80 u32 newstate;
Brendan Greggbbd9acd2018-03-20 18:35:12 -070081 char task[TASK_COMM_LEN];
82};
83BPF_PERF_OUTPUT(ipv4_events);
84
85struct ipv6_data_t {
86 u64 ts_us;
87 u64 skaddr;
Brendan Greggbbd9acd2018-03-20 18:35:12 -070088 unsigned __int128 saddr;
89 unsigned __int128 daddr;
Brendan Greggbbd9acd2018-03-20 18:35:12 -070090 u64 span_us;
Brendan Gregg2b23de62018-03-21 15:41:16 -070091 u32 pid;
92 u32 ports;
93 u32 oldstate;
94 u32 newstate;
Brendan Greggbbd9acd2018-03-20 18:35:12 -070095 char task[TASK_COMM_LEN];
96};
97BPF_PERF_OUTPUT(ipv6_events);
98
99struct id_t {
100 u32 pid;
101 char task[TASK_COMM_LEN];
102};
Daniel Poelzleithnerd0ec8a22020-03-12 12:31:39 +0100103"""
104bpf_text_tracepoint = """
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700105TRACEPOINT_PROBE(sock, inet_sock_set_state)
106{
107 if (args->protocol != IPPROTO_TCP)
108 return 0;
109
110 u32 pid = bpf_get_current_pid_tgid() >> 32;
111 // sk is used as a UUID
112 struct sock *sk = (struct sock *)args->skaddr;
113
114 // lport is either used in a filter here, or later
115 u16 lport = args->sport;
116 FILTER_LPORT
117
118 // dport is either used in a filter here, or later
119 u16 dport = args->dport;
120 FILTER_DPORT
121
122 // calculate delta
123 u64 *tsp, delta_us;
124 tsp = last.lookup(&sk);
125 if (tsp == 0)
126 delta_us = 0;
127 else
128 delta_us = (bpf_ktime_get_ns() - *tsp) / 1000;
129
130 if (args->family == AF_INET) {
131 struct ipv4_data_t data4 = {
132 .span_us = delta_us,
Marko Myllynenbfbf17e2018-09-11 21:49:58 +0300133 .oldstate = args->oldstate,
134 .newstate = args->newstate };
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700135 data4.skaddr = (u64)args->skaddr;
136 data4.ts_us = bpf_ktime_get_ns() / 1000;
Joe Yin36ce1122018-08-17 06:04:00 +0800137 __builtin_memcpy(&data4.saddr, args->saddr, sizeof(data4.saddr));
138 __builtin_memcpy(&data4.daddr, args->daddr, sizeof(data4.daddr));
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700139 // a workaround until data4 compiles with separate lport/dport
Xiaozhou Liu00213fc2019-06-17 23:28:16 +0800140 data4.ports = dport + ((0ULL + lport) << 16);
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700141 data4.pid = pid;
142
143 bpf_get_current_comm(&data4.task, sizeof(data4.task));
144 ipv4_events.perf_submit(args, &data4, sizeof(data4));
145
146 } else /* 6 */ {
147 struct ipv6_data_t data6 = {
148 .span_us = delta_us,
Marko Myllynenbfbf17e2018-09-11 21:49:58 +0300149 .oldstate = args->oldstate,
150 .newstate = args->newstate };
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700151 data6.skaddr = (u64)args->skaddr;
152 data6.ts_us = bpf_ktime_get_ns() / 1000;
Joe Yin36ce1122018-08-17 06:04:00 +0800153 __builtin_memcpy(&data6.saddr, args->saddr_v6, sizeof(data6.saddr));
154 __builtin_memcpy(&data6.daddr, args->daddr_v6, sizeof(data6.daddr));
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700155 // a workaround until data6 compiles with separate lport/dport
Xiaozhou Liu00213fc2019-06-17 23:28:16 +0800156 data6.ports = dport + ((0ULL + lport) << 16);
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700157 data6.pid = pid;
158 bpf_get_current_comm(&data6.task, sizeof(data6.task));
159 ipv6_events.perf_submit(args, &data6, sizeof(data6));
160 }
161
Jerome Marchand8bab4542021-03-05 14:58:06 +0100162 if (args->newstate == TCP_CLOSE) {
163 last.delete(&sk);
164 } else {
165 u64 ts = bpf_ktime_get_ns();
166 last.update(&sk, &ts);
167 }
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700168
169 return 0;
170}
171"""
172
Daniel Poelzleithnerd0ec8a22020-03-12 12:31:39 +0100173bpf_text_kprobe = """
174int kprobe__tcp_set_state(struct pt_regs *ctx, struct sock *sk, int state)
175{
Daniel Poelzleithnerd0ec8a22020-03-12 12:31:39 +0100176 u32 pid = bpf_get_current_pid_tgid() >> 32;
177 // sk is used as a UUID
178
179 // lport is either used in a filter here, or later
180 u16 lport = sk->__sk_common.skc_num;
181 FILTER_LPORT
182
183 // dport is either used in a filter here, or later
184 u16 dport = sk->__sk_common.skc_dport;
Rosen10dac5f2021-08-04 02:26:23 +0800185 dport = ntohs(dport);
Daniel Poelzleithnerd0ec8a22020-03-12 12:31:39 +0100186 FILTER_DPORT
187
188 // calculate delta
189 u64 *tsp, delta_us;
190 tsp = last.lookup(&sk);
191 if (tsp == 0)
192 delta_us = 0;
193 else
194 delta_us = (bpf_ktime_get_ns() - *tsp) / 1000;
195
196 u16 family = sk->__sk_common.skc_family;
197
198 if (family == AF_INET) {
199 struct ipv4_data_t data4 = {
200 .span_us = delta_us,
201 .oldstate = sk->__sk_common.skc_state,
202 .newstate = state };
203 data4.skaddr = (u64)sk;
204 data4.ts_us = bpf_ktime_get_ns() / 1000;
205 data4.saddr = sk->__sk_common.skc_rcv_saddr;
206 data4.daddr = sk->__sk_common.skc_daddr;
207 // a workaround until data4 compiles with separate lport/dport
208 data4.ports = dport + ((0ULL + lport) << 16);
209 data4.pid = pid;
210
211 bpf_get_current_comm(&data4.task, sizeof(data4.task));
212 ipv4_events.perf_submit(ctx, &data4, sizeof(data4));
213
214 } else /* 6 */ {
215 struct ipv6_data_t data6 = {
216 .span_us = delta_us,
217 .oldstate = sk->__sk_common.skc_state,
218 .newstate = state };
219 data6.skaddr = (u64)sk;
220 data6.ts_us = bpf_ktime_get_ns() / 1000;
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500221 bpf_probe_read_kernel(&data6.saddr, sizeof(data6.saddr),
Daniel Poelzleithnerd0ec8a22020-03-12 12:31:39 +0100222 sk->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32);
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500223 bpf_probe_read_kernel(&data6.daddr, sizeof(data6.daddr),
Daniel Poelzleithnerd0ec8a22020-03-12 12:31:39 +0100224 sk->__sk_common.skc_v6_daddr.in6_u.u6_addr32);
225 // a workaround until data6 compiles with separate lport/dport
226 data6.ports = dport + ((0ULL + lport) << 16);
227 data6.pid = pid;
228 bpf_get_current_comm(&data6.task, sizeof(data6.task));
229 ipv6_events.perf_submit(ctx, &data6, sizeof(data6));
230 }
231
Jerome Marchand8bab4542021-03-05 14:58:06 +0100232 if (state == TCP_CLOSE) {
233 last.delete(&sk);
234 } else {
235 u64 ts = bpf_ktime_get_ns();
236 last.update(&sk, &ts);
237 }
Daniel Poelzleithnerd0ec8a22020-03-12 12:31:39 +0100238
239 return 0;
240
241};
242"""
243
244bpf_text = bpf_header
245if (BPF.tracepoint_exists("sock", "inet_sock_set_state")):
246 bpf_text += bpf_text_tracepoint
247else:
248 bpf_text += bpf_text_kprobe
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700249
250# code substitutions
251if args.remoteport:
252 dports = [int(dport) for dport in args.remoteport.split(',')]
253 dports_if = ' && '.join(['dport != %d' % dport for dport in dports])
254 bpf_text = bpf_text.replace('FILTER_DPORT',
255 'if (%s) { last.delete(&sk); return 0; }' % dports_if)
256if args.localport:
257 lports = [int(lport) for lport in args.localport.split(',')]
258 lports_if = ' && '.join(['lport != %d' % lport for lport in lports])
259 bpf_text = bpf_text.replace('FILTER_LPORT',
260 'if (%s) { last.delete(&sk); return 0; }' % lports_if)
261bpf_text = bpf_text.replace('FILTER_DPORT', '')
262bpf_text = bpf_text.replace('FILTER_LPORT', '')
263
264if debug or args.ebpf:
265 print(bpf_text)
266 if args.ebpf:
267 exit()
268
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700269#
270# Setup output formats
271#
272# Don't change the default output (next 2 lines): this fits in 80 chars. I
273# know it doesn't have NS or UIDs etc. I know. If you really, really, really
274# need to add columns, columns that solve real actual problems, I'd start by
275# adding an extended mode (-x) to included those columns.
276#
277header_string = "%-16s %-5s %-10.10s %s%-15s %-5s %-15s %-5s %-11s -> %-11s %s"
278format_string = ("%-16x %-5d %-10.10s %s%-15s %-5d %-15s %-5d %-11s " +
279 "-> %-11s %.3f")
280if args.wide:
281 header_string = ("%-16s %-5s %-16.16s %-2s %-26s %-5s %-26s %-5s %-11s " +
282 "-> %-11s %s")
283 format_string = ("%-16x %-5d %-16.16s %-2s %-26s %-5s %-26s %-5d %-11s " +
284 "-> %-11s %.3f")
285if args.csv:
286 header_string = "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s"
287 format_string = "%x,%d,%s,%s,%s,%s,%s,%d,%s,%s,%.3f"
288
Gerald Combsabdca972018-11-26 23:37:24 -0700289if args.journal:
290 try:
291 from systemd import journal
292 except ImportError:
293 print("ERROR: Journal logging requires the systemd.journal module")
294 exit(1)
295
296
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700297def tcpstate2str(state):
298 # from include/net/tcp_states.h:
299 tcpstate = {
300 1: "ESTABLISHED",
301 2: "SYN_SENT",
302 3: "SYN_RECV",
303 4: "FIN_WAIT1",
304 5: "FIN_WAIT2",
305 6: "TIME_WAIT",
306 7: "CLOSE",
307 8: "CLOSE_WAIT",
308 9: "LAST_ACK",
309 10: "LISTEN",
310 11: "CLOSING",
311 12: "NEW_SYN_RECV",
312 }
313
314 if state in tcpstate:
315 return tcpstate[state]
316 else:
317 return str(state)
318
Gerald Combsabdca972018-11-26 23:37:24 -0700319def journal_fields(event, addr_family):
320 addr_pfx = 'IPV4'
321 if addr_family == AF_INET6:
322 addr_pfx = 'IPV6'
323
324 fields = {
325 # Standard fields described in systemd.journal-fields(7). journal.send
326 # will fill in CODE_LINE, CODE_FILE, and CODE_FUNC for us. If we're
327 # root and specify OBJECT_PID, systemd-journald will add other OBJECT_*
328 # fields for us.
329 'SYSLOG_IDENTIFIER': 'tcpstates',
330 'PRIORITY': 5,
331 '_SOURCE_REALTIME_TIMESTAMP': time() * 1000000,
332 'OBJECT_PID': str(event.pid),
333 'OBJECT_COMM': event.task.decode('utf-8', 'replace'),
334 # Custom fields, aka "stuff we sort of made up".
335 'OBJECT_' + addr_pfx + '_SOURCE_ADDRESS': inet_ntop(addr_family, pack("I", event.saddr)),
Xiaozhou Liu00213fc2019-06-17 23:28:16 +0800336 'OBJECT_TCP_SOURCE_PORT': str(event.ports >> 16),
Gerald Combsabdca972018-11-26 23:37:24 -0700337 'OBJECT_' + addr_pfx + '_DESTINATION_ADDRESS': inet_ntop(addr_family, pack("I", event.daddr)),
Xiaozhou Liu00213fc2019-06-17 23:28:16 +0800338 'OBJECT_TCP_DESTINATION_PORT': str(event.ports & 0xffff),
Gerald Combsabdca972018-11-26 23:37:24 -0700339 'OBJECT_TCP_OLD_STATE': tcpstate2str(event.oldstate),
340 'OBJECT_TCP_NEW_STATE': tcpstate2str(event.newstate),
341 'OBJECT_TCP_SPAN_TIME': str(event.span_us)
342 }
343
344 msg_format_string = (u"%(OBJECT_COMM)s " +
345 u"%(OBJECT_" + addr_pfx + "_SOURCE_ADDRESS)s " +
346 u"%(OBJECT_TCP_SOURCE_PORT)s → " +
347 u"%(OBJECT_" + addr_pfx + "_DESTINATION_ADDRESS)s " +
348 u"%(OBJECT_TCP_DESTINATION_PORT)s " +
349 u"%(OBJECT_TCP_OLD_STATE)s → %(OBJECT_TCP_NEW_STATE)s")
350 fields['MESSAGE'] = msg_format_string % (fields)
351
352 if getuid() == 0:
353 del fields['OBJECT_COMM'] # Handled by systemd-journald
354
355 return fields
356
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700357# process event
358def print_ipv4_event(cpu, data, size):
Xiaozhou Liu51d62d32019-02-15 13:03:05 +0800359 event = b["ipv4_events"].event(data)
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700360 global start_ts
361 if args.time:
362 if args.csv:
363 print("%s," % strftime("%H:%M:%S"), end="")
364 else:
365 print("%-8s " % strftime("%H:%M:%S"), end="")
366 if args.timestamp:
367 if start_ts == 0:
368 start_ts = event.ts_us
369 delta_s = (float(event.ts_us) - start_ts) / 1000000
370 if args.csv:
371 print("%.6f," % delta_s, end="")
372 else:
373 print("%-9.6f " % delta_s, end="")
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200374 print(format_string % (event.skaddr, event.pid, event.task.decode('utf-8', 'replace'),
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700375 "4" if args.wide or args.csv else "",
Xiaozhou Liu00213fc2019-06-17 23:28:16 +0800376 inet_ntop(AF_INET, pack("I", event.saddr)), event.ports >> 16,
377 inet_ntop(AF_INET, pack("I", event.daddr)), event.ports & 0xffff,
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700378 tcpstate2str(event.oldstate), tcpstate2str(event.newstate),
379 float(event.span_us) / 1000))
Gerald Combsabdca972018-11-26 23:37:24 -0700380 if args.journal:
381 journal.send(**journal_fields(event, AF_INET))
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700382
383def print_ipv6_event(cpu, data, size):
Xiaozhou Liu51d62d32019-02-15 13:03:05 +0800384 event = b["ipv6_events"].event(data)
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700385 global start_ts
386 if args.time:
387 if args.csv:
388 print("%s," % strftime("%H:%M:%S"), end="")
389 else:
390 print("%-8s " % strftime("%H:%M:%S"), end="")
391 if args.timestamp:
392 if start_ts == 0:
393 start_ts = event.ts_us
394 delta_s = (float(event.ts_us) - start_ts) / 1000000
395 if args.csv:
396 print("%.6f," % delta_s, end="")
397 else:
398 print("%-9.6f " % delta_s, end="")
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200399 print(format_string % (event.skaddr, event.pid, event.task.decode('utf-8', 'replace'),
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700400 "6" if args.wide or args.csv else "",
Xiaozhou Liu00213fc2019-06-17 23:28:16 +0800401 inet_ntop(AF_INET6, event.saddr), event.ports >> 16,
402 inet_ntop(AF_INET6, event.daddr), event.ports & 0xffff,
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700403 tcpstate2str(event.oldstate), tcpstate2str(event.newstate),
404 float(event.span_us) / 1000))
Gerald Combsabdca972018-11-26 23:37:24 -0700405 if args.journal:
406 journal.send(**journal_fields(event, AF_INET6))
Brendan Greggbbd9acd2018-03-20 18:35:12 -0700407
408# initialize BPF
409b = BPF(text=bpf_text)
410
411# header
412if args.time:
413 if args.csv:
414 print("%s," % ("TIME"), end="")
415 else:
416 print("%-8s " % ("TIME"), end="")
417if args.timestamp:
418 if args.csv:
419 print("%s," % ("TIME(s)"), end="")
420 else:
421 print("%-9s " % ("TIME(s)"), end="")
422print(header_string % ("SKADDR", "C-PID", "C-COMM",
423 "IP" if args.wide or args.csv else "",
424 "LADDR", "LPORT", "RADDR", "RPORT",
425 "OLDSTATE", "NEWSTATE", "MS"))
426
427start_ts = 0
428
429# read events
430b["ipv4_events"].open_perf_buffer(print_ipv4_event, page_cnt=64)
431b["ipv6_events"].open_perf_buffer(print_ipv6_event, page_cnt=64)
432while 1:
Jerome Marchand51671272018-12-19 01:57:24 +0100433 try:
434 b.perf_buffer_poll()
435 except KeyboardInterrupt:
436 exit()