blob: 7c2cea1264b5103e502f7f6ca89e5739ec5a32a6 [file] [log] [blame]
Alexey Ivanovcc01a9c2019-01-16 09:50:46 -08001#!/usr/bin/python
Alexei Starovoitovbdf07732016-01-14 10:09:20 -08002# @lint-avoid-python-3-compatibility-imports
Brendan Greggf06d3b42015-10-15 17:21:32 -07003#
Alexei Starovoitovbdf07732016-01-14 10:09:20 -08004# tcpconnect Trace TCP connect()s.
5# For Linux, uses BCC, eBPF. Embedded C.
Brendan Greggf06d3b42015-10-15 17:21:32 -07006#
Xiaozhou Liu9518a5b2019-08-02 01:13:53 +08007# USAGE: tcpconnect [-h] [-c] [-t] [-p PID] [-P PORT [PORT ...]]
Brendan Greggf06d3b42015-10-15 17:21:32 -07008#
9# All connection attempts are traced, even if they ultimately fail.
10#
Brendan Gregg24825522016-02-14 16:32:29 -080011# This uses dynamic tracing of kernel functions, and will need to be updated
12# to match kernel changes.
13#
Brendan Greggf06d3b42015-10-15 17:21:32 -070014# Copyright (c) 2015 Brendan Gregg.
15# Licensed under the Apache License, Version 2.0 (the "License")
16#
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080017# 25-Sep-2015 Brendan Gregg Created this.
Brendan Gregg24825522016-02-14 16:32:29 -080018# 14-Feb-2016 " " Switch to bpf_perf_output.
Takuma Kumeb181a8e2019-01-10 05:49:59 +090019# 09-Jan-2019 Takuma Kume Support filtering by UID
Xiaozhou Liu9518a5b2019-08-02 01:13:53 +080020# 30-Jul-2019 Xiaozhou Liu Count connects.
Brendan Greggf06d3b42015-10-15 17:21:32 -070021
22from __future__ import print_function
23from bcc import BPF
Alban Crequy32ab8582020-03-22 16:06:44 +010024from bcc.containers import filter_by_containers
japrocaed9b1e2019-01-04 20:21:46 +030025from bcc.utils import printb
Brendan Greggf06d3b42015-10-15 17:21:32 -070026import argparse
chantra52938052016-09-10 09:44:50 -070027from socket import inet_ntop, ntohs, AF_INET, AF_INET6
Mark Drayton11de2982016-06-26 21:14:44 +010028from struct import pack
Xiaozhou Liu9518a5b2019-08-02 01:13:53 +080029from time import sleep
Brendan Greggf06d3b42015-10-15 17:21:32 -070030
31# arguments
32examples = """examples:
33 ./tcpconnect # trace all TCP connect()s
34 ./tcpconnect -t # include timestamps
35 ./tcpconnect -p 181 # only trace PID 181
chantra52938052016-09-10 09:44:50 -070036 ./tcpconnect -P 80 # only trace port 80
37 ./tcpconnect -P 80,81 # only trace port 80 and 81
Takuma Kumeb181a8e2019-01-10 05:49:59 +090038 ./tcpconnect -U # include UID
39 ./tcpconnect -u 1000 # only trace UID 1000
Xiaozhou Liu9518a5b2019-08-02 01:13:53 +080040 ./tcpconnect -c # count connects per src ip and dest ip/port
Alban Crequy32ab8582020-03-22 16:06:44 +010041 ./tcpconnect --cgroupmap mappath # only trace cgroups in this BPF map
42 ./tcpconnect --mntnsmap mappath # only trace mount namespaces in the map
Brendan Greggf06d3b42015-10-15 17:21:32 -070043"""
44parser = argparse.ArgumentParser(
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080045 description="Trace TCP connects",
46 formatter_class=argparse.RawDescriptionHelpFormatter,
47 epilog=examples)
Brendan Greggf06d3b42015-10-15 17:21:32 -070048parser.add_argument("-t", "--timestamp", action="store_true",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080049 help="include timestamp on output")
Brendan Greggf06d3b42015-10-15 17:21:32 -070050parser.add_argument("-p", "--pid",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080051 help="trace this PID only")
chantra52938052016-09-10 09:44:50 -070052parser.add_argument("-P", "--port",
53 help="comma-separated list of destination ports to trace.")
Takuma Kumeb181a8e2019-01-10 05:49:59 +090054parser.add_argument("-U", "--print-uid", action="store_true",
55 help="include UID on output")
56parser.add_argument("-u", "--uid",
57 help="trace this UID only")
Xiaozhou Liu9518a5b2019-08-02 01:13:53 +080058parser.add_argument("-c", "--count", action="store_true",
59 help="count connects per src ip and dest ip/port")
Alban Crequy1ce868f2020-02-19 17:07:41 +010060parser.add_argument("--cgroupmap",
61 help="trace cgroups in this BPF map only")
Alban Crequy32ab8582020-03-22 16:06:44 +010062parser.add_argument("--mntnsmap",
63 help="trace mount namespaces in this BPF map only")
Nathan Scottcf0792f2018-02-02 16:56:50 +110064parser.add_argument("--ebpf", action="store_true",
65 help=argparse.SUPPRESS)
Brendan Greggf06d3b42015-10-15 17:21:32 -070066args = parser.parse_args()
67debug = 0
68
69# define BPF program
70bpf_text = """
71#include <uapi/linux/ptrace.h>
72#include <net/sock.h>
73#include <bcc/proto.h>
74
75BPF_HASH(currsock, u32, struct sock *);
76
Brendan Gregg24825522016-02-14 16:32:29 -080077// separate data structs for ipv4 and ipv6
78struct ipv4_data_t {
Brendan Gregg24825522016-02-14 16:32:29 -080079 u64 ts_us;
Joe Yin36ce1122018-08-17 06:04:00 +080080 u32 pid;
Takuma Kumeb181a8e2019-01-10 05:49:59 +090081 u32 uid;
Joe Yin36ce1122018-08-17 06:04:00 +080082 u32 saddr;
83 u32 daddr;
Mark Drayton11de2982016-06-26 21:14:44 +010084 u64 ip;
Joe Yin36ce1122018-08-17 06:04:00 +080085 u16 dport;
Brendan Gregg24825522016-02-14 16:32:29 -080086 char task[TASK_COMM_LEN];
87};
88BPF_PERF_OUTPUT(ipv4_events);
89
90struct ipv6_data_t {
Brendan Gregg24825522016-02-14 16:32:29 -080091 u64 ts_us;
Joe Yin36ce1122018-08-17 06:04:00 +080092 u32 pid;
Takuma Kumeb181a8e2019-01-10 05:49:59 +090093 u32 uid;
Mark Drayton11de2982016-06-26 21:14:44 +010094 unsigned __int128 saddr;
95 unsigned __int128 daddr;
Brendan Gregg24825522016-02-14 16:32:29 -080096 u64 ip;
Joe Yin36ce1122018-08-17 06:04:00 +080097 u16 dport;
Brendan Gregg24825522016-02-14 16:32:29 -080098 char task[TASK_COMM_LEN];
99};
100BPF_PERF_OUTPUT(ipv6_events);
101
Xiaozhou Liu9518a5b2019-08-02 01:13:53 +0800102// separate flow keys per address family
103struct ipv4_flow_key_t {
104 u32 saddr;
105 u32 daddr;
106 u16 dport;
107};
108BPF_HASH(ipv4_count, struct ipv4_flow_key_t);
109
110struct ipv6_flow_key_t {
111 unsigned __int128 saddr;
112 unsigned __int128 daddr;
113 u16 dport;
114};
115BPF_HASH(ipv6_count, struct ipv6_flow_key_t);
116
Brendan Greggf06d3b42015-10-15 17:21:32 -0700117int trace_connect_entry(struct pt_regs *ctx, struct sock *sk)
118{
Alban Crequy32ab8582020-03-22 16:06:44 +0100119 if (container_should_be_filtered()) {
120 return 0;
Alban Crequy1ce868f2020-02-19 17:07:41 +0100121 }
Alban Crequy1ce868f2020-02-19 17:07:41 +0100122
Brendan Gregg8cd3efd2019-04-07 12:32:53 -0700123 u64 pid_tgid = bpf_get_current_pid_tgid();
124 u32 pid = pid_tgid >> 32;
125 u32 tid = pid_tgid;
chantra52938052016-09-10 09:44:50 -0700126 FILTER_PID
Brendan Greggf06d3b42015-10-15 17:21:32 -0700127
Takuma Kumeb181a8e2019-01-10 05:49:59 +0900128 u32 uid = bpf_get_current_uid_gid();
129 FILTER_UID
130
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800131 // stash the sock ptr for lookup on return
Brendan Gregg8cd3efd2019-04-07 12:32:53 -0700132 currsock.update(&tid, &sk);
Brendan Greggf06d3b42015-10-15 17:21:32 -0700133
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800134 return 0;
Brendan Greggf06d3b42015-10-15 17:21:32 -0700135};
136
137static int trace_connect_return(struct pt_regs *ctx, short ipver)
138{
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530139 int ret = PT_REGS_RC(ctx);
Brendan Gregg8cd3efd2019-04-07 12:32:53 -0700140 u64 pid_tgid = bpf_get_current_pid_tgid();
141 u32 pid = pid_tgid >> 32;
142 u32 tid = pid_tgid;
Brendan Greggf06d3b42015-10-15 17:21:32 -0700143
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800144 struct sock **skpp;
Brendan Gregg8cd3efd2019-04-07 12:32:53 -0700145 skpp = currsock.lookup(&tid);
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800146 if (skpp == 0) {
147 return 0; // missed entry
148 }
Brendan Greggf06d3b42015-10-15 17:21:32 -0700149
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800150 if (ret != 0) {
151 // failed to send SYNC packet, may not have populated
152 // socket __sk_common.{skc_rcv_saddr, ...}
Brendan Gregg8cd3efd2019-04-07 12:32:53 -0700153 currsock.delete(&tid);
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800154 return 0;
155 }
Brendan Greggf06d3b42015-10-15 17:21:32 -0700156
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800157 // pull in details
158 struct sock *skp = *skpp;
Paul Chaignoneae0acf2017-08-05 23:04:41 +0200159 u16 dport = skp->__sk_common.skc_dport;
Brendan Greggf06d3b42015-10-15 17:21:32 -0700160
chantra52938052016-09-10 09:44:50 -0700161 FILTER_PORT
162
Brendan Gregg24825522016-02-14 16:32:29 -0800163 if (ipver == 4) {
Xiaozhou Liu9518a5b2019-08-02 01:13:53 +0800164 IPV4_CODE
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800165 } else /* 6 */ {
Xiaozhou Liu9518a5b2019-08-02 01:13:53 +0800166 IPV6_CODE
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800167 }
Brendan Greggf06d3b42015-10-15 17:21:32 -0700168
Brendan Gregg8cd3efd2019-04-07 12:32:53 -0700169 currsock.delete(&tid);
Brendan Greggf06d3b42015-10-15 17:21:32 -0700170
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800171 return 0;
Brendan Greggf06d3b42015-10-15 17:21:32 -0700172}
173
174int trace_connect_v4_return(struct pt_regs *ctx)
175{
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800176 return trace_connect_return(ctx, 4);
Brendan Greggf06d3b42015-10-15 17:21:32 -0700177}
178
179int trace_connect_v6_return(struct pt_regs *ctx)
180{
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800181 return trace_connect_return(ctx, 6);
Brendan Greggf06d3b42015-10-15 17:21:32 -0700182}
183"""
184
Xiaozhou Liu9518a5b2019-08-02 01:13:53 +0800185struct_init = { 'ipv4':
186 { 'count' :
187 """
188 struct ipv4_flow_key_t flow_key = {};
189 flow_key.saddr = skp->__sk_common.skc_rcv_saddr;
190 flow_key.daddr = skp->__sk_common.skc_daddr;
191 flow_key.dport = ntohs(dport);
192 ipv4_count.increment(flow_key);""",
193 'trace' :
194 """
195 struct ipv4_data_t data4 = {.pid = pid, .ip = ipver};
196 data4.uid = bpf_get_current_uid_gid();
197 data4.ts_us = bpf_ktime_get_ns() / 1000;
198 data4.saddr = skp->__sk_common.skc_rcv_saddr;
199 data4.daddr = skp->__sk_common.skc_daddr;
200 data4.dport = ntohs(dport);
201 bpf_get_current_comm(&data4.task, sizeof(data4.task));
202 ipv4_events.perf_submit(ctx, &data4, sizeof(data4));"""
203 },
204 'ipv6':
205 { 'count' :
206 """
207 struct ipv6_flow_key_t flow_key = {};
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500208 bpf_probe_read_kernel(&flow_key.saddr, sizeof(flow_key.saddr),
Xiaozhou Liu9518a5b2019-08-02 01:13:53 +0800209 skp->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32);
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500210 bpf_probe_read_kernel(&flow_key.daddr, sizeof(flow_key.daddr),
Xiaozhou Liu9518a5b2019-08-02 01:13:53 +0800211 skp->__sk_common.skc_v6_daddr.in6_u.u6_addr32);
212 flow_key.dport = ntohs(dport);
213 ipv6_count.increment(flow_key);""",
214 'trace' :
215 """
216 struct ipv6_data_t data6 = {.pid = pid, .ip = ipver};
217 data6.uid = bpf_get_current_uid_gid();
218 data6.ts_us = bpf_ktime_get_ns() / 1000;
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500219 bpf_probe_read_kernel(&data6.saddr, sizeof(data6.saddr),
Xiaozhou Liu9518a5b2019-08-02 01:13:53 +0800220 skp->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32);
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500221 bpf_probe_read_kernel(&data6.daddr, sizeof(data6.daddr),
Xiaozhou Liu9518a5b2019-08-02 01:13:53 +0800222 skp->__sk_common.skc_v6_daddr.in6_u.u6_addr32);
223 data6.dport = ntohs(dport);
224 bpf_get_current_comm(&data6.task, sizeof(data6.task));
225 ipv6_events.perf_submit(ctx, &data6, sizeof(data6));"""
226 }
227 }
228
Brendan Greggf06d3b42015-10-15 17:21:32 -0700229# code substitutions
Xiaozhou Liu9518a5b2019-08-02 01:13:53 +0800230if args.count:
231 bpf_text = bpf_text.replace("IPV4_CODE", struct_init['ipv4']['count'])
232 bpf_text = bpf_text.replace("IPV6_CODE", struct_init['ipv6']['count'])
233else:
234 bpf_text = bpf_text.replace("IPV4_CODE", struct_init['ipv4']['trace'])
235 bpf_text = bpf_text.replace("IPV6_CODE", struct_init['ipv6']['trace'])
236
Brendan Greggf06d3b42015-10-15 17:21:32 -0700237if args.pid:
chantra52938052016-09-10 09:44:50 -0700238 bpf_text = bpf_text.replace('FILTER_PID',
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800239 'if (pid != %s) { return 0; }' % args.pid)
chantra52938052016-09-10 09:44:50 -0700240if args.port:
241 dports = [int(dport) for dport in args.port.split(',')]
242 dports_if = ' && '.join(['dport != %d' % ntohs(dport) for dport in dports])
243 bpf_text = bpf_text.replace('FILTER_PORT',
Mauricio Vásquez884799f2020-10-07 20:11:25 -0500244 'if (%s) { currsock.delete(&tid); return 0; }' % dports_if)
Takuma Kumeb181a8e2019-01-10 05:49:59 +0900245if args.uid:
246 bpf_text = bpf_text.replace('FILTER_UID',
247 'if (uid != %s) { return 0; }' % args.uid)
Alban Crequy32ab8582020-03-22 16:06:44 +0100248bpf_text = filter_by_containers(args) + bpf_text
chantra52938052016-09-10 09:44:50 -0700249
250bpf_text = bpf_text.replace('FILTER_PID', '')
251bpf_text = bpf_text.replace('FILTER_PORT', '')
Takuma Kumeb181a8e2019-01-10 05:49:59 +0900252bpf_text = bpf_text.replace('FILTER_UID', '')
chantra52938052016-09-10 09:44:50 -0700253
Nathan Scottcf0792f2018-02-02 16:56:50 +1100254if debug or args.ebpf:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800255 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100256 if args.ebpf:
257 exit()
Brendan Greggf06d3b42015-10-15 17:21:32 -0700258
Brendan Gregg24825522016-02-14 16:32:29 -0800259# process event
260def print_ipv4_event(cpu, data, size):
Xiaozhou Liu31563032019-02-14 14:33:58 +0800261 event = b["ipv4_events"].event(data)
Mark Drayton11de2982016-06-26 21:14:44 +0100262 global start_ts
Brendan Gregg24825522016-02-14 16:32:29 -0800263 if args.timestamp:
264 if start_ts == 0:
265 start_ts = event.ts_us
Gary Lin6c793312019-04-18 15:17:56 +0800266 printb(b"%-9.3f" % ((float(event.ts_us) - start_ts) / 1000000), nl="")
Takuma Kumeb181a8e2019-01-10 05:49:59 +0900267 if args.print_uid:
Gary Lin6c793312019-04-18 15:17:56 +0800268 printb(b"%-6d" % event.uid, nl="")
japrocaed9b1e2019-01-04 20:21:46 +0300269 printb(b"%-6d %-12.12s %-2d %-16s %-16s %-4d" % (event.pid,
Yonghong Songebe19512019-01-10 14:54:16 -0800270 event.task, event.ip,
271 inet_ntop(AF_INET, pack("I", event.saddr)).encode(),
272 inet_ntop(AF_INET, pack("I", event.daddr)).encode(), event.dport))
Brendan Gregg9e0b0872016-03-28 12:11:45 -0700273
Brendan Gregg24825522016-02-14 16:32:29 -0800274def print_ipv6_event(cpu, data, size):
Xiaozhou Liu31563032019-02-14 14:33:58 +0800275 event = b["ipv6_events"].event(data)
Mark Drayton11de2982016-06-26 21:14:44 +0100276 global start_ts
Brendan Gregg24825522016-02-14 16:32:29 -0800277 if args.timestamp:
278 if start_ts == 0:
279 start_ts = event.ts_us
Gary Lin6c793312019-04-18 15:17:56 +0800280 printb(b"%-9.3f" % ((float(event.ts_us) - start_ts) / 1000000), nl="")
Takuma Kumeb181a8e2019-01-10 05:49:59 +0900281 if args.print_uid:
Gary Lin6c793312019-04-18 15:17:56 +0800282 printb(b"%-6d" % event.uid, nl="")
japrocaed9b1e2019-01-04 20:21:46 +0300283 printb(b"%-6d %-12.12s %-2d %-16s %-16s %-4d" % (event.pid,
Yonghong Songebe19512019-01-10 14:54:16 -0800284 event.task, event.ip,
285 inet_ntop(AF_INET6, event.saddr).encode(), inet_ntop(AF_INET6, event.daddr).encode(),
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200286 event.dport))
Brendan Gregg24825522016-02-14 16:32:29 -0800287
Xiaozhou Liu9518a5b2019-08-02 01:13:53 +0800288def depict_cnt(counts_tab, l3prot='ipv4'):
289 for k, v in sorted(counts_tab.items(), key=lambda counts: counts[1].value, reverse=True):
290 depict_key = ""
291 if l3prot == 'ipv4':
292 depict_key = "%-25s %-25s %-20s" % ((inet_ntop(AF_INET, pack('I', k.saddr))),
293 inet_ntop(AF_INET, pack('I', k.daddr)), k.dport)
294 else:
295 depict_key = "%-25s %-25s %-20s" % ((inet_ntop(AF_INET6, k.saddr)),
296 inet_ntop(AF_INET6, k.daddr), k.dport)
297
298 print ("%s %-10d" % (depict_key, v.value))
299
Brendan Greggf06d3b42015-10-15 17:21:32 -0700300# initialize BPF
301b = BPF(text=bpf_text)
302b.attach_kprobe(event="tcp_v4_connect", fn_name="trace_connect_entry")
303b.attach_kprobe(event="tcp_v6_connect", fn_name="trace_connect_entry")
304b.attach_kretprobe(event="tcp_v4_connect", fn_name="trace_connect_v4_return")
305b.attach_kretprobe(event="tcp_v6_connect", fn_name="trace_connect_v6_return")
306
Xiaozhou Liu9518a5b2019-08-02 01:13:53 +0800307print("Tracing connect ... Hit Ctrl-C to end")
308if args.count:
Jerome Marchand51671272018-12-19 01:57:24 +0100309 try:
Xiaozhou Liu9518a5b2019-08-02 01:13:53 +0800310 while 1:
311 sleep(99999999)
Jerome Marchand51671272018-12-19 01:57:24 +0100312 except KeyboardInterrupt:
Xiaozhou Liu9518a5b2019-08-02 01:13:53 +0800313 pass
314
315 # header
316 print("\n%-25s %-25s %-20s %-10s" % (
317 "LADDR", "RADDR", "RPORT", "CONNECTS"))
318 depict_cnt(b["ipv4_count"])
319 depict_cnt(b["ipv6_count"], l3prot='ipv6')
320# read events
321else:
322 # header
323 if args.timestamp:
324 print("%-9s" % ("TIME(s)"), end="")
325 if args.print_uid:
326 print("%-6s" % ("UID"), end="")
327 print("%-6s %-12s %-2s %-16s %-16s %-4s" % ("PID", "COMM", "IP", "SADDR",
328 "DADDR", "DPORT"))
329
330 start_ts = 0
331
332 # read events
333 b["ipv4_events"].open_perf_buffer(print_ipv4_event)
334 b["ipv6_events"].open_perf_buffer(print_ipv6_event)
335 while 1:
336 try:
337 b.perf_buffer_poll()
338 except KeyboardInterrupt:
339 exit()