1 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
2
3 /*
4 * Copyright (c) 2021 Hengqi Chen
5 *
6 * Based on bindsnoop(8) from BCC by Pavel Dubovitsky.
7 * 11-May-2021 Hengqi Chen Created this.
8 */
9 #include <argp.h>
10 #include <arpa/inet.h>
11 #include <errno.h>
12 #include <signal.h>
13 #include <string.h>
14 #include <sys/socket.h>
15 #include <time.h>
16 #include <unistd.h>
17 #include <fcntl.h>
18
19 #include <bpf/libbpf.h>
20 #include <bpf/bpf.h>
21 #include "bindsnoop.h"
22 #include "bindsnoop.skel.h"
23 #include "trace_helpers.h"
24 #include "btf_helpers.h"
25
26 #define PERF_BUFFER_PAGES 16
27 #define PERF_POLL_TIMEOUT_MS 100
28 #define warn(...) fprintf(stderr, __VA_ARGS__)
29
30 static struct env {
31 char *cgroupspath;
32 bool cg;
33 } env;
34
35 static volatile sig_atomic_t exiting = 0;
36
37 static bool emit_timestamp = false;
38 static pid_t target_pid = 0;
39 static bool ignore_errors = true;
40 static char *target_ports = NULL;
41 static bool verbose = false;
42
43 const char *argp_program_version = "bindsnoop 0.1";
44 const char *argp_program_bug_address =
45 "https://github.com/iovisor/bcc/tree/master/libbpf-tools";
46 const char argp_program_doc[] =
47 "Trace bind syscalls.\n"
48 "\n"
49 "USAGE: bindsnoop [-h] [-t] [-x] [-p PID] [-P ports] [-c CG]\n"
50 "\n"
51 "EXAMPLES:\n"
52 " bindsnoop # trace all bind syscall\n"
53 " bindsnoop -t # include timestamps\n"
54 " bindsnoop -x # include errors on output\n"
55 " bindsnoop -p 1216 # only trace PID 1216\n"
56 " bindsnoop -c CG # Trace process under cgroupsPath CG\n"
57 " bindsnoop -P 80,81 # only trace port 80 and 81\n"
58 "\n"
59 "Socket options are reported as:\n"
60 " SOL_IP IP_FREEBIND F....\n"
61 " SOL_IP IP_TRANSPARENT .T...\n"
62 " SOL_IP IP_BIND_ADDRESS_NO_PORT ..N..\n"
63 " SOL_SOCKET SO_REUSEADDR ...R.\n"
64 " SOL_SOCKET SO_REUSEPORT ....r\n";
65
66 static const struct argp_option opts[] = {
67 { "timestamp", 't', NULL, 0, "Include timestamp on output" },
68 { "cgroup", 'c', "/sys/fs/cgroup/unified", 0, "Trace process in cgroup path" },
69 { "failed", 'x', NULL, 0, "Include errors on output." },
70 { "pid", 'p', "PID", 0, "Process ID to trace" },
71 { "ports", 'P', "PORTS", 0, "Comma-separated list of ports to trace." },
72 { "verbose", 'v', NULL, 0, "Verbose debug output" },
73 { NULL, 'h', NULL, OPTION_HIDDEN, "Show the full help" },
74 {},
75 };
76
parse_arg(int key,char * arg,struct argp_state * state)77 static error_t parse_arg(int key, char *arg, struct argp_state *state)
78 {
79 long pid, port_num;
80 char *port;
81
82 switch (key) {
83 case 'p':
84 errno = 0;
85 pid = strtol(arg, NULL, 10);
86 if (errno || pid <= 0) {
87 warn("Invalid PID: %s\n", arg);
88 argp_usage(state);
89 }
90 target_pid = pid;
91 break;
92 case 'c':
93 env.cgroupspath = arg;
94 env.cg = true;
95 break;
96 case 'P':
97 if (!arg) {
98 warn("No ports specified\n");
99 argp_usage(state);
100 }
101 target_ports = strdup(arg);
102 port = strtok(arg, ",");
103 while (port) {
104 port_num = strtol(port, NULL, 10);
105 if (errno || port_num <= 0 || port_num > 65536) {
106 warn("Invalid ports: %s\n", arg);
107 argp_usage(state);
108 }
109 port = strtok(NULL, ",");
110 }
111 break;
112 case 'x':
113 ignore_errors = false;
114 break;
115 case 't':
116 emit_timestamp = true;
117 break;
118 case 'v':
119 verbose = true;
120 break;
121 case 'h':
122 argp_state_help(state, stderr, ARGP_HELP_STD_HELP);
123 break;
124 default:
125 return ARGP_ERR_UNKNOWN;
126 }
127 return 0;
128 }
129
libbpf_print_fn(enum libbpf_print_level level,const char * format,va_list args)130 static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
131 {
132 if (level == LIBBPF_DEBUG && !verbose)
133 return 0;
134 return vfprintf(stderr, format, args);
135 }
136
sig_int(int signo)137 static void sig_int(int signo)
138 {
139 exiting = 1;
140 }
141
handle_event(void * ctx,int cpu,void * data,__u32 data_sz)142 static void handle_event(void *ctx, int cpu, void *data, __u32 data_sz)
143 {
144 struct bind_event *e = data;
145 time_t t;
146 struct tm *tm;
147 char ts[32], addr[48];
148 char opts[] = {'F', 'T', 'N', 'R', 'r', '\0'};
149 const char *proto;
150 int i = 0;
151
152 if (emit_timestamp) {
153 time(&t);
154 tm = localtime(&t);
155 strftime(ts, sizeof(ts), "%H:%M:%S", tm);
156 printf("%8s ", ts);
157 }
158 if (e->proto == IPPROTO_TCP)
159 proto = "TCP";
160 else if (e->proto == IPPROTO_UDP)
161 proto = "UDP";
162 else
163 proto = "UNK";
164 while (opts[i]) {
165 if (!((1 << i) & e->opts)) {
166 opts[i] = '.';
167 }
168 i++;
169 }
170 if (e->ver == 4) {
171 inet_ntop(AF_INET, &e->addr, addr, sizeof(addr));
172 } else {
173 inet_ntop(AF_INET6, &e->addr, addr, sizeof(addr));
174 }
175 printf("%-7d %-16s %-3d %-5s %-5s %-4d %-5d %-48s\n",
176 e->pid, e->task, e->ret, proto, opts, e->bound_dev_if, e->port, addr);
177 }
178
handle_lost_events(void * ctx,int cpu,__u64 lost_cnt)179 static void handle_lost_events(void *ctx, int cpu, __u64 lost_cnt)
180 {
181 warn("lost %llu events on CPU #%d\n", lost_cnt, cpu);
182 }
183
main(int argc,char ** argv)184 int main(int argc, char **argv)
185 {
186 LIBBPF_OPTS(bpf_object_open_opts, open_opts);
187 static const struct argp argp = {
188 .options = opts,
189 .parser = parse_arg,
190 .doc = argp_program_doc,
191 };
192 struct perf_buffer *pb = NULL;
193 struct bindsnoop_bpf *obj;
194 int err, port_map_fd;
195 char *port;
196 short port_num;
197 int idx, cg_map_fd;
198 int cgfd = -1;
199
200 err = argp_parse(&argp, argc, argv, 0, NULL, NULL);
201 if (err)
202 return err;
203
204 libbpf_set_print(libbpf_print_fn);
205
206 err = ensure_core_btf(&open_opts);
207 if (err) {
208 fprintf(stderr, "failed to fetch necessary BTF for CO-RE: %s\n", strerror(-err));
209 return 1;
210 }
211
212 obj = bindsnoop_bpf__open_opts(&open_opts);
213 if (!obj) {
214 warn("failed to open BPF object\n");
215 return 1;
216 }
217
218 obj->rodata->filter_cg = env.cg;
219 obj->rodata->target_pid = target_pid;
220 obj->rodata->ignore_errors = ignore_errors;
221 obj->rodata->filter_by_port = target_ports != NULL;
222
223 err = bindsnoop_bpf__load(obj);
224 if (err) {
225 warn("failed to load BPF object: %d\n", err);
226 goto cleanup;
227 }
228
229 /* update cgroup path fd to map */
230 if (env.cg) {
231 idx = 0;
232 cg_map_fd = bpf_map__fd(obj->maps.cgroup_map);
233 cgfd = open(env.cgroupspath, O_RDONLY);
234 if (cgfd < 0) {
235 fprintf(stderr, "Failed opening Cgroup path: %s", env.cgroupspath);
236 goto cleanup;
237 }
238 if (bpf_map_update_elem(cg_map_fd, &idx, &cgfd, BPF_ANY)) {
239 fprintf(stderr, "Failed adding target cgroup to map");
240 goto cleanup;
241 }
242 }
243
244 if (target_ports) {
245 port_map_fd = bpf_map__fd(obj->maps.ports);
246 port = strtok(target_ports, ",");
247 while (port) {
248 port_num = strtol(port, NULL, 10);
249 bpf_map_update_elem(port_map_fd, &port_num, &port_num, BPF_ANY);
250 port = strtok(NULL, ",");
251 }
252 }
253
254 err = bindsnoop_bpf__attach(obj);
255 if (err) {
256 warn("failed to attach BPF programs: %d\n", err);
257 goto cleanup;
258 }
259
260 pb = perf_buffer__new(bpf_map__fd(obj->maps.events), PERF_BUFFER_PAGES,
261 handle_event, handle_lost_events, NULL, NULL);
262 if (!pb) {
263 err = -errno;
264 warn("failed to open perf buffer: %d\n", err);
265 goto cleanup;
266 }
267
268 if (signal(SIGINT, sig_int) == SIG_ERR) {
269 warn("can't set signal handler: %s\n", strerror(errno));
270 err = 1;
271 goto cleanup;
272 }
273
274 if (emit_timestamp)
275 printf("%-8s ", "TIME(s)");
276 printf("%-7s %-16s %-3s %-5s %-5s %-4s %-5s %-48s\n",
277 "PID", "COMM", "RET", "PROTO", "OPTS", "IF", "PORT", "ADDR");
278
279 while (!exiting) {
280 err = perf_buffer__poll(pb, PERF_POLL_TIMEOUT_MS);
281 if (err < 0 && err != -EINTR) {
282 warn("error polling perf buffer: %s\n", strerror(-err));
283 goto cleanup;
284 }
285 /* reset err to return 0 if exiting */
286 err = 0;
287 }
288
289 cleanup:
290 perf_buffer__free(pb);
291 bindsnoop_bpf__destroy(obj);
292 cleanup_core_btf(&open_opts);
293 if (cgfd > 0)
294 close(cgfd);
295
296 return err != 0;
297 }
298