-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnesnoop
executable file
·498 lines (423 loc) · 10.6 KB
/
nesnoop
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
#!/bin/sh
# vi: set ft=sh noet ts=8 sw=8 :: Vi/ViM
############################################################ IDENT(1)
#
# $Title: Script to snoop on Network End-point events under Linux $
# $Copyright: 2020-2023 Devin Teske. All rights reserved. $
# $FrauBSD: nesnoop/nesnoop 2023-08-28 18:16:37 -0700 freebsdfrau $
#
############################################################ DEFAULTS
DEFAULT_TIME_FMT="%Y %b %e %T"
############################################################ GLOBALS
VERSION='$Version: 0.6.2 $'
pgm="${0##*/}" # Program basename
#
# Global exit status
#
SUCCESS=0
FAILURE=1
#
# Command-line options
#
COLOR= # -c
DEBUG= # -d
RAW_OUTPUT= # -r
SILENT= # -s
TIME_FMT="$DEFAULT_TIME_FMT" # -t fmt
#
# Probes
# NB: Dependent on kernel version
# NB: export'd for awk(1) `ENVIRON' access
#
export KPROBE_TCP_CLOSE=kprobe:tcp_close
export KPROBE_TCP_CONNECT=kprobe:tcp_connect
export KPROBE_TCP_RECVMSG=kprobe:tcp_recvmsg
export KPROBE_TCP_SENDMSG=kprobe:tcp_sendmsg
export KRETPROBE_TCP_RECVMSG=kretprobe:tcp_recvmsg
export KRETPROBE_TCP_SENDMSG=kretprobe:tcp_sendmsg
#
# Miscellaneous
#
COMM=
CONDITION=
CONS=1
RAW_TIME_FMT='"%s"'
############################################################ FUNCTIONS
die()
{
local fmt="$1"
if [ "$fmt" ]; then
shift 1 # fmt
printf "%s: $fmt\n" "$pgm" "$@" >&2
fi
exit $FAILURE
}
info()
{
[ ! "$SILENT" ] || return
printf "${CONS:+\033[35m}INFO${CONS:+\033[39m} %s\n" "$*" >&2
}
warn()
{
[ ! "$SILENT" ] || return
printf "${CONS:+\033[31;1m}WARNING${CONS:+\033[39;22m} %s\n" "$*" >&2
}
usage()
{
local fmt="$1"
local optfmt="\t%-9s %s\n"
exec >&2
if [ "$fmt" ]; then
shift 1 # fmt
printf "%s: $fmt\n" "$pgm" "$@"
fi
printf "Usage: %s [OPTIONS] [comm]\n" "$pgm"
printf "Options:\n"
printf "$optfmt" "-c" "Always enable color."
printf "$optfmt" "-d" "Debug. Print script and exit."
printf "$optfmt" "-h" "Print this usage statement and exit."
printf "$optfmt" "-r" "Show unformatted raw output."
printf "$optfmt" "-s" "Silent. Hide informational messages/warnings."
printf "$optfmt" "-t fmt" "Time format. Default \`$DEFAULT_TIME_FMT'."
printf "$optfmt" "-v" "Print version information and exit."
die
}
run_bpftrace()
{
if [ "$DEBUG" ]; then
cat
return
fi
exec bpftrace -B none /dev/stdin
}
bpf_prog_id()
{
local __pid="$1" __prog="$2" __var_to_set="$3"
local __ls __out __res
[ "$__pid" -a "$__prog" ] || return ${FAILURE:-1}
__ls=$( ls -l /proc/$__pid/fd 2> /dev/null ) || return
__out=$( echo "$__ls" | awk -v pid=$__pid -v prog="$__prog" '
$NF == "anon_inode:bpf-prog" {
fd = $(NF-2)
fdinfo = sprintf("/proc/%d/fdinfo/%d", pid, fd)
id = ""
while (getline < fdinfo > 0) {
if ($1 != "prog_id:") continue
id = $2
break
}
close(fdinfo)
if (id == "") next
cmd = sprintf("bpftool prog show id %d", id)
if (cmd | getline <= 0 || $4 != prog) {
close(cmd)
next
}
print id
exit found = 1
}
END { exit found ? 0 : 3 }
' )
__res=$?
if [ "$__var_to_set" ]; then
eval $__var_to_set=\"\$__out\"
else
echo "$__out"
fi
return $__res
}
############################################################ MAIN
#
# Process command-line options
#
while getopts cdhrst:v flag; do
case "$flag" in
c) COLOR=1 ;;
d) DEBUG=1 ;;
r) RAW_OUTPUT=1 ;;
s) SILENT=1 ;;
t) TIME_FMT="$OPTARG" ;;
v) VERSION="${VERSION#*: }"
echo "${VERSION% $}"
exit $SUCCESS ;;
*) usage # NOTREACHED
esac
done
shift $(( $OPTIND - 1 ))
#
# Process command-line arguments
#
COMM="$1"
#
# Check command-line arguments
#
[ $# -le 1 ] || usage "Too many arguments" # NOTREACHED
#
# Process `-c' command-line option
#
[ "$COLOR" -o -t 1 ] || CONS= # stdout is not a tty
#
# Run script
#
{
exec 3<&1
#
# Generate conditions
#
if [ "$COMM" ]; then
COMM="\"$COMM\""
CONDITION="$CONDITION && comm == $COMM"
fi
CONDITION="${CONDITION# && }"
#
# Start background bpftrace
# NB: M-x package-install [RET] dtrace-script-mode [RET]
#
run_bpftrace <<EOF &
${DEBUG:+#!/usr/bin/bpftrace}
/* -*- mode: dtrace-script; tab-width: 4 -*- ;; Emacs
* vi: set ft=dtrace noet ts=4 sw=4 :: Vi/ViM
*/
////////////////////////////////////////////////// INCLUDES
#include <net/sock.h>
////////////////////////////////////////////////// ENDPOINT PROBES
/*
* connect(2)/close(2) probes
*/
$KPROBE_TCP_CONNECT
/comm != "sshd" && arg0 != 0${CONDITION:+ && $CONDITION}/
{
\$sk = (struct sock *)arg0;
\$dport = \$sk->__sk_common.skc_dport;
\$dport = (\$dport >> 8) | ((\$dport << 8) & 0xFF00);
${TIME_FMT:+time($RAW_TIME_FMT);
}printf("|connect|%d.%d|%s|%d|", uid, gid, comm, pid);
printf("%s|%d\n", ntop(\$sk->__sk_common.skc_daddr), \$dport);
@trace[tid] = 1;
}
$KPROBE_TCP_CLOSE
/@trace[tid] && arg0 != 0/
{
\$sk = (struct sock *)arg0;
\$dport = \$sk->__sk_common.skc_dport;
\$dport = (\$dport >> 8) | ((\$dport << 8) & 0xFF00);
${TIME_FMT:+time($RAW_TIME_FMT);
}printf("|close|%d.%d|%s|%d|", uid, gid, comm, pid);
printf("%s|%d\n", ntop(\$sk->__sk_common.skc_daddr), \$dport);
delete(@trace[tid]);
}
////////////////////////////////////////////////// SEND/RECV PROBES
/*
* send(2)/recv(2) [exit] probes
*/
$KPROBE_TCP_SENDMSG
/comm != "sshd" && arg1 != 0${CONDITION:+ && $CONDITION}/
{
@send_sk[tid] = arg1;
@send_size[tid] = arg3;
}
$KRETPROBE_TCP_SENDMSG
/@send_sk[tid]/
{
\$sk = (struct sock *)@send_sk[tid];
\$dport = \$sk->__sk_common.skc_dport;
\$dport = (\$dport >> 8) | ((\$dport << 8) & 0xFF00);
\$size = @send_size[tid];
${TIME_FMT:+time($RAW_TIME_FMT);
}printf("|sendmsg|%d.%d|%s|%d|", uid, gid, comm, pid);
printf("%s|%d|%d|%d\n", ntop(\$sk->__sk_common.skc_daddr), \$dport,
\$size, retval);
delete(@send_size[tid]);
delete(@send_sk[tid]);
}
$KPROBE_TCP_RECVMSG
/comm != "sshd" && arg1 != 0${CONDITION:+ && $CONDITION}/
{
@recv_sk[tid] = arg1;
@recv_len[tid] = arg3;
}
$KRETPROBE_TCP_RECVMSG
/@recv_sk[tid]/
{
\$sk = (struct sock *)@recv_sk[tid];
\$dport = \$sk->__sk_common.skc_dport;
\$dport = (\$dport >> 8) | ((\$dport << 8) & 0xFF00);
\$len = @recv_len[tid];
${TIME_FMT:+time($RAW_TIME_FMT);
}printf("|recvmsg|%d.%d|%s|%d|", uid, gid, comm, pid);
printf("%s|%d|%d|%d\n", ntop(\$sk->__sk_common.skc_daddr), \$dport,
\$len, retval);
delete(@recv_len[tid]);
delete(@recv_sk[tid]);
}
////////////////////////////////////////////////// END
END {
clear(@recv_len);
clear(@recv_sk);
clear(@send_size);
clear(@send_sk);
clear(@trace);
}
//////////////////////////////////////////////////////////////////////
// END
//////////////////////////////////////////////////////////////////////
EOF
pid=$!
prog_id=
#
# Identify child bpftrace
#
if [ ! "$DEBUG" ]; then
info "Waiting for bpftrace to initialize..."
while kill -0 $pid 2> /dev/null; do
bpf_prog_id $pid BEGIN prog_id
[ "$prog_id" ] || continue
break
sleep 1
done
if ! kill -0 $pid 2> /dev/null; then
wait $pid > /dev/null 2>&1 # Collect exit status
echo EXIT:$? # Send status to post-processor
exit
fi
fi
# BOOTSTRAP
#
# Bring bpftrace child back to foreground
#
wait $pid > /dev/null 2>&1 # Collect exit status
echo EXIT:$? # Send status to post-processor
} | awk -F'|' \
-v cons=${CONS:-0} \
-v debug=${DEBUG:-0} \
-v raw=${RAW_OUTPUT:-0} \
-v silent=${SILENT:-0} \
-v stderr=/dev/stderr \
-v timefmt="$TIME_FMT" \
'################################################# BEGIN
BEGIN {
NCF = 7 # Number of common fields
exit_status = 0 # SUCCESS
bold = "\033[1m"
nobold = "\033[22m"
red = "\033[31m"
green = "\033[32m"
yellow = "\033[33m"
blue = "\033[34m"
magenta = "\033[35m"
cyan = "\033[36m"
fgreset = "\033[39m"
srand() # Seed clock
tlim = srand() * 2 # limit time outliers
delete errno
cmd = "cpp -dM /usr/include/errno.h"
while (cmd | getline > 0) {
if (split($0, words, / +/) < 3) continue
if (words[1] != "#define") continue
macro = words[2]
if (substr(macro, 1, 1) != "E") continue
errno[words[3]] = macro
}
close(cmd)
}
################################################## FUNCTIONS
function fprint() { print; fflush() }
function eprint() { print > stderr; fflush(stderr) }
function info(str)
{
if (silent) return
printf "%sINFO%s %s\n",
cons ? magenta : "", cons ? fgreset : "", str > stderr
fflush(stderr)
}
function warn(str)
{
if (silent) return
printf "%sWARNING%s %s\n", cons ? yellow bold : "",
cons ? fgreset nobold : "", str > stderr
fflush(stderr)
}
function emit(color, str)
{
if (timefmt != "") {
if (time !~ /^[0-9]+$/ || time > tlim || time < 0)
return
printf "%s%s%s %s %s[%d]: %s\n",
cons ? color : "", strftime(timefmt, time),
cons ? fgreset : "", user, cmd, pid, str
} else {
printf "%s %s[%d]: %s\n", user, cmd, pid, str
}
fflush()
}
################################################## MAIN
sub(/^EXIT:/, "") { exit_status = $0; next }
debug { sub(/^\t/, ""); fprint(); next }
raw { fprint(); next }
/^Attaching [0-9]+ probes/ { eprint(); next }
# Base fields
{ time = $1 }
timefmt != "" {
if (time == "" || time < 0) next
}
{ call = $2 }
# Message passing
call == "info" || call == "warn" {
msg = $0
for (n = 1; n <= 2; n++)
sub(/^[^|]*\|/, "", msg)
if (call == "info") info(msg)
else if (call == "warn") warn(msg)
next
}
# Common fields
NF < NCF { next } # Malformed input
{
user = $3 # uid.gid
cmd = $4
sub(/ + [[:digit:]]+$/, "", cmd)
pid = $5
dest_addr = $6
dest_port = $7
if (dest_addr == "0.0.0.0" && dest_port == 0) next
# NB: Hide local socket activity events
}
call == "connect" {
emit(green, sprintf("connect([%s]:%u)", dest_addr, dest_port))
next
}
call == "close" {
emit(blue, sprintf("close([%s]:%u)", dest_addr, dest_port))
next
}
call == "sendmsg" {
if (NF < NCF + 2) next # Malformed input
size = $(NCF + 1)
ret = $(NCF + 2)
emit(red, sprintf("sendmsg([%s]:%u, size=%d) = %i %s",
dest_addr, dest_port, size, ret,
ret < 0 ? "<" errno[-1 * ret] ">" : ""))
next
}
call == "recvmsg" {
if (NF < NCF + 2) next # Malformed input
len = $(NCF + 1)
ret = $(NCF + 2)
emit(cyan, sprintf("recvmsg([%s]:%u, len=%d) = %i %s",
dest_addr, dest_port, len, ret,
ret < 0 ? "<" errno[-1 * ret] ">" : ""))
next
}
################################################## END
END { exit exit_status }
' # END-QUOTE
################################################################################
# END
################################################################################
# Local Variables:
# mode: sh
# tab-width: 8
# sh-basic-offset: 8
# indent-tabs-mode: t
# backward-delete-char-untabify-method: nil
# End: