Repository navigation
Expand file tree
/
Copy pathprocsnap.py
More file actions
executable file
·5064 lines (4738 loc) · 258 KB
/
Copy pathprocsnap.py
File metadata and controls
executable file
·5064 lines (4738 loc) · 258 KB
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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
procsnap - periodic process + network snapshotter for Linux hosts.
Reads /proc directly (no ps/netstat/ss dependency), records a delta event
stream to JSONL so long runs stay small, and ships with an analysis side.
Collect:
sudo ./procsnap.py collect --interval 10 --out /var/log/procsnap
sudo ./procsnap.py collect --interval 5 --stdout # live to terminal
Analyse:
./procsnap.py report /var/log/procsnap
./procsnap.py timeline /var/log/procsnap --since 2h
./procsnap.py procs /var/log/procsnap --grep curl
./procsnap.py conns /var/log/procsnap --remote 1.2.3.4
./procsnap.py sqlite /var/log/procsnap -o snap.db
Service:
sudo ./procsnap.py install-service --interval 10
"""
from __future__ import annotations
import argparse
import array
import base64
import difflib
import fcntl
import glob
import gzip
import hashlib
import json
import os
import pwd
import re
import shlex
import shutil
import signal
import socket
import sqlite3
import stat
import struct
import sys
import time
import zlib
from collections import Counter, defaultdict
from datetime import datetime
VERSION = "2.0.1"
HZ = os.sysconf("SC_CLK_TCK")
PAGE_KB = os.sysconf("SC_PAGE_SIZE") // 1024
TCP_STATES = {
"01": "ESTABLISHED", "02": "SYN_SENT", "03": "SYN_RECV", "04": "FIN_WAIT1",
"05": "FIN_WAIT2", "06": "TIME_WAIT", "07": "CLOSE", "08": "CLOSE_WAIT",
"09": "LAST_ACK", "0A": "LISTEN", "0B": "CLOSING", "0C": "NEW_SYN_RECV",
}
SUSPECT_DIRS = ("/tmp/", "/dev/shm/", "/var/tmp/", "/run/shm/", "/home/")
# Command-line patterns that are rarely legitimate. Shared by the collector,
# the triage engine (cron, systemd, shell init, history) and the HTML report.
SUSPECT_CMD = re.compile(
r"(curl|wget)\b[^|;]*\|\s*(ba|da|z)?sh\b|base64\s+(-d|--decode)|/dev/(tcp|udp)/|"
r"\bnc(at)?\b[^|;]*\s-[a-z]*e\s|\bmkfifo\b[^;]*\bnc\b|socat\b[^;]*\bexec:|"
r"\b(ba)?sh\s+-i\s*[<>]&|chmod\s+(\+x|[0-7]?7[0-7][0-7])\s+/(tmp|dev/shm|var/tmp)/|"
r"openssl\s+s_client\b[^;]*-connect|xmrig|kinsing|kdevtmpfsi|stratum\+tcp|"
r"\bhistory\s+-c\b|unset\s+HISTFILE|HISTFILE=/dev/null|chattr\s+\+i\s",
re.I,
)
# Inline interpreter one-liners: common in admin tooling, so context only.
SUSPECT_INLINE = re.compile(r"\b(python[0-9.]*\s+-c|perl\s+-e|php\s+-r|ruby\s+-e)\s", re.I)
_UID_CACHE: dict[int, str] = {}
# --------------------------------------------------------------------------
# helpers
# --------------------------------------------------------------------------
def uname(uid: int) -> str:
if uid not in _UID_CACHE:
try:
_UID_CACHE[uid] = pwd.getpwuid(uid).pw_name
except KeyError:
_UID_CACHE[uid] = str(uid)
return _UID_CACHE[uid]
def boot_time() -> float:
try:
with open("/proc/stat") as fh:
for line in fh:
if line.startswith("btime"):
return float(line.split()[1])
except OSError:
pass
with open("/proc/uptime") as fh:
return time.time() - float(fh.read().split()[0])
def iso(ts: float) -> str:
return datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")
def readlink(path: str) -> str | None:
try:
return os.readlink(path)
except OSError:
return None
def exe_sha256(pid: int, cache: dict, cap: int = 512 << 20, cached_only: bool = False) -> str | None:
"""SHA-256 of a process's executable, read through /proc/<pid>/exe.
Works for deleted and memfd binaries too. Cached per (device, inode, size,
mtime) so each distinct binary is hashed once, however many processes run it.
"""
path = f"/proc/{pid}/exe"
try:
st = os.stat(path)
except OSError:
return None
if not stat.S_ISREG(st.st_mode) or st.st_size > cap:
return None
key = (st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns)
if key not in cache and cached_only:
return None
if key not in cache:
try:
h = hashlib.sha256()
with open(path, "rb") as fh:
for b in iter(lambda: fh.read(1 << 20), b""):
h.update(b)
cache[key] = h.hexdigest()
except OSError:
cache[key] = None
return cache[key]
class ChunkHasher:
"""Resumable SHA-256 of one queued executable at a time, in 1 MB steps.
A job is (pid, start, comm, exe, (dev, ino, size, mtime_ns)) captured when the
process was first seen. The file is opened through /proc/<pid>/exe and checked
against that identity, so a recycled PID can never lend another binary's hash.
Once open, the descriptor keeps the file readable even if the process exits or
the binary is deleted.
"""
def __init__(self, cache):
self.cache = cache
self.job = self.fh = self.h = None
def busy(self):
return self.job is not None
def start(self, job):
self.job, ident = job, job[4]
if ident in self.cache: # same binary already hashed
self.fh, self.h = None, None
return
try:
self.fh = open(f"/proc/{job[0]}/exe", "rb")
st = os.fstat(self.fh.fileno())
if (st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns) != ident:
raise OSError("pid reused or binary replaced")
if st.st_size > 512 << 20:
raise OSError("too large")
self.h = hashlib.sha256()
except OSError: # gone, recycled, replaced, too big
self.close()
self.h = None
def step(self, deadline):
"""Hash until done or until `deadline`. -> (job, sha) when finished, else None."""
job = self.job
if self.fh is None: # cached, gone, or refused
self.job = None
return job, self.cache.get(job[4])
while time.time() < deadline:
b = self.fh.read(1 << 20)
if not b:
sha = self.h.hexdigest()
self.cache[job[4]] = sha
self.close()
self.job = None
return job, sha
self.h.update(b)
return None
def close(self):
if self.fh:
try:
self.fh.close()
except OSError:
pass
self.fh = None
def hex_ip(h: str) -> str:
"""/proc/net/* stores addresses as little-endian hex words."""
try:
if len(h) == 8:
return socket.inet_ntop(socket.AF_INET, struct.pack("<I", int(h, 16)))
if len(h) == 32:
raw = b"".join(struct.pack("<I", int(h[i:i + 8], 16)) for i in range(0, 32, 8))
ip = socket.inet_ntop(socket.AF_INET6, raw)
return ip[7:] if ip.startswith("::ffff:") else ip
except (ValueError, OSError):
pass
return h
def is_private(ip) -> bool:
ip = str(ip or "")
if ip.startswith(("10.", "127.", "192.168.", "169.254.", "::1", "fe80:", "fc", "fd")):
return True
if ip.startswith("172."):
try:
return 16 <= int(ip.split(".")[1]) <= 31
except (ValueError, IndexError):
return False
return ip in ("0.0.0.0", "::", "")
def duration(spec: str) -> float:
"""Accept 10, 10s, 5m, 1h, 90ms-style intervals -> seconds (float)."""
spec = str(spec).strip().lower()
m = re.fullmatch(r"(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?", spec)
if not m:
raise argparse.ArgumentTypeError(
f"bad duration {spec!r} - use e.g. 10, 30s, 10m, 1h")
val = float(m.group(1))
mult = {"ms": 0.001, "s": 1, "m": 60, "h": 3600, "d": 86400}[m.group(2) or "s"]
secs = val * mult
if secs < 0.05:
raise argparse.ArgumentTypeError(f"interval {spec!r} is too small (min 50ms)")
return secs
def human_dur(secs: float) -> str:
if secs >= 3600 and secs % 3600 == 0:
return f"{int(secs // 3600)}h"
if secs >= 60 and secs % 60 == 0:
return f"{int(secs // 60)}m"
return f"{secs:g}s"
def human_span(secs) -> str:
"""3725 -> '1h 02m', 93784 -> '1d 2h 03m'"""
if secs is None:
return ""
secs = max(0, int(secs))
d, r = divmod(secs, 86400)
h, r = divmod(r, 3600)
m, s = divmod(r, 60)
if d:
return f"{d}d {h}h {m:02d}m"
if h:
return f"{h}h {m:02d}m"
return f"{m}m {s:02d}s"
def parse_since(spec: str) -> float:
m = re.fullmatch(r"(\d+)\s*([smhd])", spec.strip(), re.I)
if m:
mult = {"s": 1, "m": 60, "h": 3600, "d": 86400}[m.group(2).lower()]
return time.time() - int(m.group(1)) * mult
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
try:
return datetime.strptime(spec, fmt).timestamp()
except ValueError:
continue
raise SystemExit(f"cannot parse --since {spec!r} (use 30m / 2h / 7d / 'YYYY-MM-DD HH:MM')")
# --------------------------------------------------------------------------
# collection
# --------------------------------------------------------------------------
def scan_procs(bt: float, want_fds: bool = True):
"""Return (procs_by_key, socket_inode -> pid)."""
procs: dict[tuple[int, int], dict] = {}
inode2pid: dict[str, int] = {}
for entry in os.scandir("/proc"):
if not entry.name.isdigit():
continue
pid = int(entry.name)
base = "/proc/" + entry.name
try:
with open(base + "/stat", "rb") as fh:
raw = fh.read().decode("utf-8", "replace")
uid = os.stat(base).st_uid
except OSError:
continue
close = raw.rfind(")")
if close < 0:
continue
comm = raw[raw.find("(") + 1:close]
f = raw[close + 2:].split()
if len(f) < 22:
continue
try:
ppid = int(f[1])
sid = int(f[3])
tty_nr = int(f[4])
cpu_ticks = int(f[11]) + int(f[12])
nthreads = int(f[17])
starttime = int(f[19])
rss_kb = int(f[21]) * PAGE_KB
except (ValueError, IndexError):
continue
try:
with open(base + "/cmdline", "rb") as fh:
cmdline = fh.read().decode("utf-8", "replace").replace("\0", " ").strip()
except OSError:
cmdline = ""
kthread = not cmdline
exe = readlink(base + "/exe")
deleted = bool(exe and exe.endswith(" (deleted)"))
if deleted:
exe = exe[: -len(" (deleted)")]
cg = ""
try:
with open(base + "/cgroup") as fh:
cg = fh.readline().strip().rsplit("/", 1)[-1][:64]
except OSError:
pass
rec = {
"pid": pid,
"ppid": ppid,
"uid": uid,
"user": uname(uid),
"comm": comm,
"cmdline": cmdline or f"[{comm}]",
"exe": exe,
"exe_deleted": deleted,
"cwd": readlink(base + "/cwd"),
"sid": sid,
"tty": tty_nr,
"nthreads": nthreads,
"rss_kb": rss_kb,
"cpu_s": round(cpu_ticks / HZ, 2),
"cgroup": cg,
"kthread": kthread,
"start": round(bt + starttime / HZ, 2),
}
procs[(pid, starttime)] = rec
if want_fds and not kthread:
try:
with os.scandir(base + "/fd") as it:
for fd in it:
tgt = readlink(fd.path)
if tgt and tgt.startswith("socket:["):
inode2pid[tgt[8:-1]] = pid
except OSError:
pass
return procs, inode2pid
def scan_sockets(inode2pid, procs_by_pid, include_timewait=False):
"""Return (listen_dict, conn_dict) keyed for delta comparison."""
listen: dict[tuple, dict] = {}
conns: dict[tuple, dict] = {}
sources = (
("tcp", "/proc/net/tcp"), ("tcp", "/proc/net/tcp6"),
("udp", "/proc/net/udp"), ("udp", "/proc/net/udp6"),
)
for proto, path in sources:
try:
with open(path) as fh:
lines = fh.read().splitlines()[1:]
except OSError:
continue
for line in lines:
f = line.split()
if len(f) < 10:
continue
try:
lip_h, lport_h = f[1].split(":")
rip_h, rport_h = f[2].split(":")
lport, rport = int(lport_h, 16), int(rport_h, 16)
except ValueError:
continue
if proto == "tcp":
state = TCP_STATES.get(f[3].upper(), f[3])
else:
state = "BOUND" if rport == 0 else "ACTIVE"
if state == "TIME_WAIT" and not include_timewait:
continue
inode = f[9]
pid = inode2pid.get(inode)
p = procs_by_pid.get(pid, {})
lip, rip = hex_ip(lip_h), hex_ip(rip_h)
base = {
"proto": proto,
"laddr": lip, "lport": lport,
"state": state,
"pid": pid,
"comm": p.get("comm"),
"cmdline": p.get("cmdline"),
"exe": p.get("exe"),
"user": p.get("user") or uname(int(f[7])),
}
if rport == 0 or state == "LISTEN":
listen[(proto, lip, lport)] = base
else:
base["raddr"], base["rport"] = rip, rport
conns[(proto, lip, lport, rip, rport)] = base
return listen, conns
class Writer:
"""Day-rotating JSONL writer (optionally gzipped)."""
def __init__(self, outdir=None, gz=False, to_stdout=False, retain_days=0):
self.outdir = outdir
self.gz = gz
self.to_stdout = to_stdout
self.retain_days = retain_days
self.day = None
self.fh = None
if outdir:
os.makedirs(outdir, exist_ok=True)
def _roll(self):
day = time.strftime("%Y%m%d")
if day == self.day and self.fh:
return
if self.fh:
self.fh.close()
self.day = day
ext = ".jsonl.gz" if self.gz else ".jsonl"
path = os.path.join(self.outdir, f"procsnap-{day}{ext}")
self.fh = gzip.open(path, "at") if self.gz else open(path, "a", buffering=1)
self._prune()
def _prune(self):
if not self.retain_days:
return
cutoff = time.time() - self.retain_days * 86400
for p in glob.glob(os.path.join(self.outdir, "procsnap-*.jsonl*")):
try:
if os.path.getmtime(p) < cutoff:
os.remove(p)
except OSError:
pass
def emit(self, ev: dict):
line = json.dumps(ev, separators=(",", ":"), default=str)
if self.to_stdout:
print(line, flush=True)
if self.outdir:
self._roll()
self.fh.write(line + "\n")
def close(self):
if self.fh:
self.fh.close()
def cmd_collect(a):
if os.geteuid() != 0:
print("[!] not root - cmdline/exe/socket-to-PID will be missing for other users' "
"processes", file=sys.stderr)
bt = boot_time()
w = Writer(None if a.stdout and not a.out else a.out, a.gzip, a.stdout, a.retain_days)
running = True
def stop(_sig, _frm):
nonlocal running
running = False
signal.signal(signal.SIGINT, stop)
signal.signal(signal.SIGTERM, stop)
if not a.stdout:
where = a.out or "stdout"
stop_hint = f"stops after {a.count} snapshots" if a.count else "runs until Ctrl+C / kill"
print(f"[procsnap] every {human_dur(a.interval)} -> {where} ({stop_hint}, pid {os.getpid()})",
file=sys.stderr)
w.emit({
"ts": round(time.time(), 3), "ev": "collector_start", "version": VERSION,
"host": socket.gethostname(), "kernel": os.uname().release,
"boot": round(bt, 2), "interval": a.interval,
"interval_h": human_dur(a.interval), "root": os.geteuid() == 0,
"net": not a.no_net,
})
prev_procs: dict = {}
prev_listen: dict = {}
prev_conns: dict = {}
first_seen: dict = {}
peak_rss: dict = {}
hcache: dict = {}
hqueue: list = []
hasher = ChunkHasher(hcache)
n = 0
while running:
t0 = time.time()
procs, inode2pid = scan_procs(bt, want_fds=not a.no_net)
if a.no_kthreads:
procs = {k: v for k, v in procs.items() if not v["kthread"]}
by_pid = {v["pid"]: v for v in procs.values()}
if a.no_net:
listen, conns = {}, {}
else:
listen, conns = scan_sockets(inode2pid, by_pid, a.include_timewait)
if a.no_loopback:
conns = {k: v for k, v in conns.items()
if not (v["laddr"].startswith("127.") or v["laddr"] in ("::1",))}
ts = round(time.time(), 3)
# --- process deltas -------------------------------------------------
for key, rec in procs.items():
peak_rss[key] = max(peak_rss.get(key, 0), rec["rss_kb"])
if key not in prev_procs:
first_seen[key] = ts
ev = dict(rec)
ev.update(ts=ts, ev="proc_start", baseline=(n == 0))
if not a.no_hash and not rec["kthread"]:
# never hash inside the snapshot: a cold cache (first snapshot, big
# binaries) took ~16 s and left the collector blind. Known binaries
# are tagged now; the rest are hashed in the idle time below and
# reported as an exe_hash event.
known = exe_sha256(rec["pid"], hcache, cached_only=True)
if known:
ev["sha256"] = known
else:
try: # remember WHICH file, not just the pid
xs = os.stat(f"/proc/{rec['pid']}/exe")
job = (rec["pid"], rec["start"], rec["comm"], rec["exe"],
(xs.st_dev, xs.st_ino, xs.st_size, xs.st_mtime_ns))
# processes born after snapshot 1 are the interesting ones:
# they go ahead of the cold-start backlog
hqueue.insert(0, job) if n else hqueue.append(job)
except OSError:
pass
par = by_pid.get(rec["ppid"])
if par:
ev["pcomm"] = par["comm"]
ev["pcmdline"] = par["cmdline"]
w.emit(ev)
elif rec["exe_deleted"] and not prev_procs[key]["exe_deleted"]:
# binary removed while running: the classic "delete myself after
# start" move. Without this event a process first seen before the
# deletion would never be flagged.
w.emit({"ts": ts, "ev": "exe_deleted", "pid": rec["pid"], "ppid": rec["ppid"],
"user": rec["user"], "comm": rec["comm"], "cmdline": rec["cmdline"],
"exe": rec["exe"], "exe_deleted": True, "start": rec["start"]})
for key, rec in prev_procs.items():
if key not in procs:
w.emit({
"ts": ts, "ev": "proc_exit", "pid": rec["pid"], "ppid": rec["ppid"],
"user": rec["user"], "comm": rec["comm"], "cmdline": rec["cmdline"],
"exe": rec["exe"], "start": rec["start"],
"lifetime_s": round(ts - rec["start"], 2),
"cpu_s": rec["cpu_s"], "rss_kb_peak": peak_rss.pop(key, rec["rss_kb"]),
})
first_seen.pop(key, None)
# --- socket deltas --------------------------------------------------
for key, rec in listen.items():
if key not in prev_listen:
first_seen[("L",) + key] = ts
w.emit({**rec, "ts": ts, "ev": "listen_open", "baseline": n == 0})
for key, rec in prev_listen.items():
if key not in listen:
st = first_seen.pop(("L",) + key, None)
w.emit({**rec, "ts": ts, "ev": "listen_close",
"duration_s": round(ts - st, 1) if st else None})
lports = {(k[0], k[2]) for k in listen}
for key, rec in conns.items():
if key not in prev_conns:
first_seen[("C",) + key] = ts
w.emit({**rec, "ts": ts, "ev": "conn_open", "baseline": n == 0,
"dir": "inbound" if (rec["proto"], rec["lport"]) in lports
else "outbound"})
for key, rec in prev_conns.items():
if key not in conns:
st = first_seen.pop(("C",) + key, None)
w.emit({**rec, "ts": ts, "ev": "conn_close",
"duration_s": round(ts - st, 1) if st else None})
# --- periodic full inventory (resync point) -------------------------
if a.full_every and n % a.full_every == 0:
w.emit({
"ts": ts, "ev": "inventory",
"procs": sorted(procs.values(), key=lambda r: r["pid"]),
"listen": list(listen.values()),
"conns": list(conns.values()),
})
w.emit({
"ts": ts, "ev": "heartbeat", "n": n,
"nproc": len(procs), "nlisten": len(listen), "nconn": len(conns),
"scan_ms": round((time.time() - t0) * 1000, 1),
})
prev_procs, prev_listen, prev_conns = procs, listen, conns
n += 1
if a.count and n >= a.count:
break
deadline = t0 + a.interval
while running and time.time() < deadline:
# idle-time hashing in 1 MB steps: a 500 MB binary is spread over as many
# idle windows as it needs and never delays the next snapshot
if hasher.busy() or hqueue:
if not hasher.busy():
hasher.start(hqueue.pop(0))
done = hasher.step(deadline - 0.02)
if done:
job, sha = done
if sha:
w.emit({"ts": round(time.time(), 3), "ev": "exe_hash", "pid": job[0],
"start": job[1], "comm": job[2], "exe": job[3], "sha256": sha})
continue
time.sleep(min(0.25, max(0.0, deadline - time.time())))
hasher.close()
w.emit({"ts": round(time.time(), 3), "ev": "collector_stop", "snapshots": n})
w.close()
# --------------------------------------------------------------------------
# analysis
# --------------------------------------------------------------------------
def load(path, since=None, until=None):
files = []
if os.path.isdir(path):
files = sorted(glob.glob(os.path.join(path, "procsnap-*.jsonl*")))
elif os.path.isfile(path):
files = [path]
if not files:
raise SystemExit(f"no procsnap logs found at {path}")
for fp in files:
opener = gzip.open if fp.endswith(".gz") else open
try:
with opener(fp, "rt", errors="replace") as fh:
for line in fh:
line = line.strip()
if not line:
continue
try:
ev = json.loads(line)
except json.JSONDecodeError:
continue
if not isinstance(ev, dict): # crafted/corrupt line
continue
ts = ev.get("ts", 0)
if not isinstance(ts, (int, float)):
continue
if since and ts < since:
continue
if until and ts > until:
continue
yield ev
except (EOFError, zlib.error, gzip.BadGzipFile) as e:
# a .gz still being written (or cut by kill -9) ends mid-member:
# keep everything read so far instead of crashing the analysis.
print(f"[!] {fp}: truncated ({e.__class__.__name__}) - using the part before the cut",
file=sys.stderr)
# Severity tiers. HIGH = act on it. LOW = context only, expect benign hits.
SEVERITY = {
"exe-deleted": "high",
"exe-in-world-writable": "high",
"suspicious-cmdline": "high",
"comm-exe-mismatch": "low",
"listen-all-ifaces-highport": "low",
"inline-interpreter": "low",
}
_SCRIPT_EXT = (".sh", ".py", ".pl", ".rb", ".php", ".js", ".bash")
# comm values the kernel or a multi-call binary legitimately reports under a
# different exe name.
_COMM_ALIAS = {
"sh": {"dash", "bash", "busybox"},
"systemd-udevd": {"udevadm"},
"systemd": {"systemd-executor"},
}
def _strip_ver(name: str) -> str:
"""python3.12 -> python, ruby2.7 -> ruby"""
return re.sub(r"[-_.0-9]+$", "", name)
def comm_exe_mismatch(comm: str | None, exe: str | None) -> bool:
"""True only when comm and exe genuinely disagree.
The naive basename(exe) != comm test is ~90% false positives: interpreters
carry version suffixes, scripts report their own filename, the kernel
truncates comm at 15 chars, and multi-call binaries are exec'd under
an alias.
"""
if not comm or not exe:
return False
if comm.startswith("("): # (sd-pam) and friends
return False
if len(comm) >= 15: # kernel-truncated, can't compare
return False
if comm.endswith(_SCRIPT_EXT): # script name as comm
return False
base = os.path.basename(exe)
if not base or not re.search(r"[A-Za-z]", base): # versioned filename, e.g. 2.1.241
return False
if base.startswith(comm) or comm.startswith(base): # truncation / version suffix
return False
if _strip_ver(base) == _strip_ver(comm):
return False
if base in _COMM_ALIAS.get(comm, ()):
return False
return True
def suspicious(ev) -> list[str]:
tags = []
exe = ev.get("exe") or ""
cmd = ev.get("cmdline") or ""
if exe.startswith(SUSPECT_DIRS):
tags.append("exe-in-world-writable")
if ev.get("exe_deleted"):
tags.append("exe-deleted")
if SUSPECT_CMD.search(cmd):
tags.append("suspicious-cmdline")
elif SUSPECT_INLINE.search(cmd + " "):
tags.append("inline-interpreter")
if comm_exe_mismatch(ev.get("comm"), exe):
tags.append("comm-exe-mismatch")
if ev.get("ev") == "listen_open" and ev.get("laddr") in ("0.0.0.0", "::") \
and (ev.get("lport") or 0) > 1024:
tags.append("listen-all-ifaces-highport")
return tags
# --------------------------------------------------------------------------
# point-in-time state reconstruction (snapshot browsing + diffing)
# --------------------------------------------------------------------------
def snapshot_points(path, since=None):
"""Every heartbeat is one snapshot. Returns [(n, ts)] in order."""
pts = []
for ev in load(path, since):
if ev.get("ev") == "heartbeat":
pts.append((len(pts) + 1, ev["ts"]))
return pts
def resolve_at(pts, spec):
"""'#3' -> 3rd snapshot; 'first'/'last'; a clock time; or an epoch/ISO time."""
if not pts:
raise SystemExit("no snapshots in this log")
spec = str(spec).strip()
if spec in ("first", "0"):
return pts[0]
if spec == "last":
return pts[-1]
if spec.startswith("#"):
i = int(spec[1:])
if not 1 <= i <= len(pts):
raise SystemExit(f"snapshot {spec} out of range (1..{len(pts)})")
return pts[i - 1]
if re.fullmatch(r"\d{1,2}:\d{2}(:\d{2})?", spec):
day = datetime.fromtimestamp(pts[0][1]).strftime("%Y-%m-%d")
fmt = "%Y-%m-%d %H:%M:%S" if spec.count(":") == 2 else "%Y-%m-%d %H:%M"
want = datetime.strptime(f"{day} {spec}", fmt).timestamp()
else:
try:
want = float(spec)
except ValueError:
want = parse_since(spec)
# nearest snapshot at or before the requested time
best = pts[0]
for n, ts in pts:
if ts <= want + 0.001:
best = (n, ts)
else:
break
return best
def reconstruct(path, at):
"""Replay the delta stream up to `at` and return the exact state then."""
procs, listen, conns = {}, {}, {}
for ev in load(path):
ts = ev.get("ts", 0)
if ts > at + 0.001:
break
k = ev.get("ev")
if k == "collector_start":
# a new collector session restarts the delta chain from a fresh
# baseline: anything carried over from the previous session is stale.
# This is what makes cron-driven `once` logs reconstruct correctly,
# and what stops a reboot from leaving dead processes "alive".
procs.clear(); listen.clear(); conns.clear()
elif k == "proc_start":
procs[(ev.get("pid"), ev.get("start"))] = ev
elif k == "proc_exit":
procs.pop((ev.get("pid"), ev.get("start")), None)
elif k == "exe_deleted":
p = procs.get((ev.get("pid"), ev.get("start")))
if p:
procs[(ev.get("pid"), ev.get("start"))] = dict(p, exe_deleted=True)
elif k == "listen_open":
listen[(ev.get("proto"), ev.get("laddr"), ev.get("lport"))] = ev
elif k == "listen_close":
listen.pop((ev.get("proto"), ev.get("laddr"), ev.get("lport")), None)
elif k == "conn_open":
conns[(ev.get("proto"), ev.get("laddr"), ev.get("lport"),
ev.get("raddr"), ev.get("rport"))] = ev
elif k == "conn_close":
conns.pop((ev.get("proto"), ev.get("laddr"), ev.get("lport"),
ev.get("raddr"), ev.get("rport")), None)
return procs, listen, conns
def _proc_line(ev, by_pid):
pid = f"{ev.get('pid'):>7} " if by_pid else ""
return f"{pid}{ev.get('user','?'):<12} {ev.get('cmdline','?')}"
def _listen_line(ev, by_pid):
pid = f"{ev.get('pid') or '-':>7} " if by_pid else ""
return (f"{pid}{ev.get('proto','?'):<5} "
f"{str(ev.get('laddr'))+':'+str(ev.get('lport')):<26} "
f"{ev.get('comm') or '?'}")
def _conn_line(ev, by_pid):
pid = f"{ev.get('pid') or '-':>7} " if by_pid else ""
return (f"{pid}{ev.get('proto','?'):<5} "
f"{str(ev.get('laddr'))+':'+str(ev.get('lport')):<24}-> "
f"{str(ev.get('raddr'))+':'+str(ev.get('rport')):<24} "
f"{ev.get('state','') :<12} {ev.get('comm') or '?'}")
SECTIONS = (("PROCESSES", 0, _proc_line),
("LISTENERS", 1, _listen_line),
("CONNECTIONS", 2, _conn_line))
def state_lines(state, by_pid, no_kthreads=False):
"""dict section -> {line: event}"""
out = {}
for name, idx, fmt in SECTIONS:
d = {}
for ev in state[idx].values():
if no_kthreads and ev.get("kthread"):
continue
d[fmt(ev, by_pid)] = ev
out[name] = d
return out
def cmd_snapshots(a):
pts = snapshot_points(a.path, parse_since(a.since) if a.since else None)
print(f"{len(pts)} snapshots in {a.path}")
step = max(1, len(pts) // a.limit) if a.limit and len(pts) > a.limit else 1
for n, ts in pts[::step]:
print(f" #{n:<6} {iso(ts)} {ts}")
if step > 1:
print(f" (showing 1 in {step} - raise --limit, or --limit 0, for all)")
def cmd_show(a):
pts = snapshot_points(a.path)
n, ts = resolve_at(pts, a.at)
state = reconstruct(a.path, ts)
lines = state_lines(state, a.pid, a.no_kthreads)
print(f"\033[1msnapshot #{n}\033[0m {iso(ts)} ({a.path})")
for name, _, _ in SECTIONS:
d = lines[name]
print(f"\n\033[1m{name}\033[0m ({len(d)})\n" + "-" * (len(name) + 8))
for line in sorted(d):
print(" " + line)
def cmd_diff(a):
pts = snapshot_points(a.path)
picks = [resolve_at(pts, x) for x in a.at]
if len(picks) < 2:
raise SystemExit("need at least two --at values to diff")
states = [state_lines(reconstruct(a.path, ts), a.pid, a.no_kthreads)
for _, ts in picks]
print(f"\033[1mcomparing {len(picks)} snapshots\033[0m ({a.path})")
for i, (n, ts) in enumerate(picks):
print(f" S{i+1} = snapshot #{n} {iso(ts)}")
changed = 0
for name, _, _ in SECTIONS:
sets = [set(st[name]) for st in states]
union = set().union(*sets)
common = set.intersection(*sets)
diffs = sorted(union - common)
print(f"\n\033[1m{name}\033[0m "
f"{len(common)} identical, \033[33m{len(diffs)} differing\033[0m\n"
+ "-" * (len(name) + 30))
if not diffs:
print(" (no change)")
continue
changed += len(diffs)
if len(picks) == 2:
for line in diffs:
sign = "\033[32m+\033[0m" if line in sets[1] else "\033[31m-\033[0m"
print(f" {sign} {line}")
if a.verbose:
ev = states[1][name].get(line) or states[0][name].get(line)
if ev and ev.get("exe"):
print(f" exe={ev['exe']}"
+ (" \033[31m[DELETED]\033[0m"
if ev.get("exe_deleted") else ""))
else:
hdr = "".join(f" S{i+1}" for i in range(len(picks)))
print(f" {hdr} entity")
for line in diffs:
mark = "".join(" X" if line in s else " ." for s in sets)
print(f" {mark} {line}")
print(f"\n{changed} differing line(s) across "
f"{len(SECTIONS)} sections.\n")
def cmd_report(a):
since = parse_since(a.since) if a.since else None
starts = exits = 0
hb = None
hosts, sessions = set(), 0
proc_agg = Counter()
user_agg = Counter()
parent_agg = Counter()
listeners = {}
remotes = Counter()
rports = Counter()
ext_conns = Counter()
flags = defaultdict(list)
t_min = t_max = None
for ev in load(a.path, since):
ts = ev.get("ts", 0)
t_min = ts if t_min is None else min(t_min, ts)
t_max = ts if t_max is None else max(t_max, ts)
k = ev.get("ev")
if k == "collector_start":
hosts.add(ev.get("host", "?"))
sessions += 1
elif k == "heartbeat":
hb = ev
elif k == "proc_start":
starts += 1
proc_agg[ev.get("cmdline", "?")[:160]] += 1
user_agg[ev.get("user", "?")] += 1
if ev.get("pcomm"):
parent_agg[f"{ev['pcomm']} -> {ev.get('comm')}"] += 1
for t in suspicious(ev):
flags[t].append(ev)
elif k == "proc_exit":
exits += 1
elif k == "exe_deleted":
for t in suspicious(ev):
flags[t].append(ev)
elif k == "listen_open":
listeners[(ev["proto"], ev["laddr"], ev["lport"])] = ev
for t in suspicious(ev):
flags[t].append(ev)
elif k == "conn_open":
r = ev.get("raddr", "")
remotes[r] += 1
rports[f"{ev.get('proto')}/{ev.get('rport')}"] += 1
if not is_private(r):
ext_conns[(ev.get("comm") or "?", r, ev.get("rport"))] += 1
def hdr(t):
print(f"\n\033[1m{t}\033[0m\n" + "-" * len(t))