Repository navigation
Expand file tree
/
Copy pathwebtop.py
More file actions
executable file
·4425 lines (4170 loc) · 269 KB
/
Copy pathwebtop.py
File metadata and controls
executable file
·4425 lines (4170 loc) · 269 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
"""
webtop - htop-style live view of WHO is using your web server right now,
WHAT they request, and WHAT the web server does because of it.
* live request feed (tails nginx / Apache / LiteSpeed access logs)
* per-client view: req/min, POSTs, 4xx/5xx, open connections ("LIVE")
* in-flight requests from Apache mod_status (when available)
* inbound sessions + OUTBOUND connections made from web-server context
* every process the web server spawns (netlink exec events, /proc fallback),
attributed back to the client IP / URL that caused it
* detections: webshell access patterns, web-spawned shells, reverse shells
(shell with stdin/stdout on a TCP socket), netcat/socat sessions, payloads
Pure stdlib, reads /proc directly (same approach as ProcSnap, so it can be
merged in later as `procsnap.py webtop`). Run as root for full visibility.
sudo ./webtop.py # interactive TUI
sudo ./webtop.py -l /var/log/nginx/site_access.log
sudo ./webtop.py --stream alerts # plain-text alert feed (no TUI)
sudo ./webtop.py --once --duration 5 # JSON snapshot (for ProcSnap / scripts)
sudo ./webtop.py --alert-log /var/log/webtop.jsonl
"""
from __future__ import annotations
import argparse
import ctypes
import glob
import html
import itertools
import json
import os
import pwd
import queue
import re
import signal
import socket
import struct
import sys
import threading
import time
import urllib.parse
import urllib.request
from collections import Counter, deque
from datetime import datetime
VERSION = "0.3.0"
HZ = os.sysconf("SC_CLK_TCK")
UA_SELF = f"webtop/{VERSION} (local status poller)"
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",
}
DEFAULT_LOGS = [
"/var/log/nginx/access.log", "/var/log/nginx/*access*.log",
"/var/log/apache2/access.log", "/var/log/apache2/*access*.log",
"/var/log/httpd/access_log", "/var/log/httpd/*access_log",
"/usr/local/apache/logs/access_log", # cPanel
"/usr/local/apache/domlogs/*", # cPanel per-domain
"/etc/apache2/logs/domlogs/*", # cPanel (newer)
"/usr/local/lsws/logs/access.log", # LiteSpeed / OLS
"/var/log/lighttpd/access.log", "/var/log/caddy/access.log",
]
DEFAULT_PORTS = {80, 443, 8080, 8443, 8000, 8888}
STDOUT_TARGETS = ("/dev/stdout", "/proc/self/fd/1", "/dev/stderr", "/proc/self/fd/2")
# Processes that ARE the web server (comm, versions stripped by regex).
WEB_RE = re.compile(
r"^(nginx|apache2?|httpd(-\S*)?|lshttpd|litespeed|openlitespeed|lsphp\d*|"
r"php-fpm[\d.]*|php-cgi[\d.]*|php\d*-cgi|caddy|lighttpd|hhvm|unitd|"
r"gunicorn|uwsgi|uvicorn|passenger\S*|tomcat\S*|httpd\.worker)$", re.I)
SHELLS = {"sh", "bash", "dash", "zsh", "ksh", "csh", "tcsh", "fish", "ash", "busybox", "rbash"}
INTERP = {"python", "perl", "ruby", "php", "lua", "node", "tclsh", "expect", "pwsh", "awk", "gawk"}
NETTOOLS = {"nc", "ncat", "netcat", "socat", "telnet", "curl", "wget", "ssh", "openssl", "nmap",
"ftp", "tftp", "scp", "rsync", "nping", "sshpass"}
RECON = {"id", "whoami", "uname", "hostname", "ifconfig", "ip", "netstat", "ss", "ps", "w", "who",
"last", "cat", "ls", "find", "crontab", "chmod", "base64", "xxd", "dd", "env", "sudo",
"su", "pkexec", "getent", "lsb_release", "mount", "df", "useradd", "passwd", "history"}
# Normal children of web stacks (php mail(), image tools, ...). Not alerted.
ALLOW_CHILD = {"sendmail", "postdrop", "exim", "exim4", "ssmtp", "msmtp", "postfix", "convert",
"magick", "identify", "gs", "rotatelogs", "logger", "cronolog", "suexec",
"lsphp", "php-fpm", "cagefs_enter", "lve_suwrapper", "ffmpeg", "pdftotext",
"wkhtmltopdf", "gzip", "git"}
COMMON_OUT_PORTS = {53, 80, 443, 25, 465, 587, 3306, 5432, 6379, 11211, 9200, 27017, 9000, 389, 636}
STATIC_EXT = re.compile(r"\.(css|js|mjs|map|png|jpe?g|gif|svg|ico|webp|avif|woff2?|ttf|eot|otf|"
r"mp4|webm|mp3|pdf|txt|xml|json)$", re.I)
SEV_ORDER = {"CRIT": 4, "HIGH": 3, "MED": 2, "LOW": 1, "INFO": 0}
# --------------------------------------------------------------------- request rules
_DEC = urllib.parse.unquote_plus
R_WEBSHELL_NAME = re.compile(
r"/(c99|r57|r00t|wso\d*|b374k|alfa\w*|indoxploit|marijuana|priv8|webshell|backdoor|"
r"shell\d*|cmd|sh3ll|bypass|symlink|leafmailer|uploader|up|x{1,3}|tmp\d*|"
r"[a-f0-9]{16,})\.(php\d?|phtml|phar|jsp|aspx?)$", re.I)
R_EXEC_IN_UPLOADS = re.compile(
r"/(wp-content/uploads|uploads?|images?|img|files|media|cache|tmp|temp|static|assets|"
r"wp-includes/(css|images|fonts|js))/[^?]*\.(php\d?|phtml|phar|pht|inc)\b", re.I)
R_CMD_PARAM = re.compile(r"[?&](cmd|exec|command|execute|shell|system|passthru|run|cmdline|ip|c|e)=([^&]*)", re.I)
R_CMD_VALUE = re.compile(
r"^\s*(id|whoami|uname|ls|dir|cat|pwd|wget|curl|bash|sh|nc|ncat|python3?|perl|php|"
r"echo|ps|netstat|ifconfig|ip\s+a|chmod|rm|base64|busybox)\b|[;|`]|\$\(|/bin/", re.I)
R_PAYLOAD = [
("HIGH", "php-code-in-url", re.compile(r"(base64_decode|eval\s*\(|assert\s*\(|system\s*\(|passthru|"
r"shell_exec|proc_open|popen\s*\(|pcntl_exec|<\?php|"
r"call_user_func|preg_replace.*/e)", re.I)),
("HIGH", "os-cmd-injection", re.compile(r"(/bin/(ba)?sh|\bnc\s+-|bash\s+-i|/dev/tcp/|mkfifo|"
r"wget\s+http|curl\s+http|\|\s*sh\b|;\s*(id|uname|whoami)\b)", re.I)),
("HIGH", "log4shell", re.compile(r"\$\{(jndi|\$\{|lower:|upper:|env:)", re.I)),
("MED", "php-wrapper", re.compile(r"(php://(input|filter)|data://|expect://|phar://|zip://)", re.I)),
("MED", "path-traversal", re.compile(r"(\.\./\.\./|\.\.%2f|/etc/(passwd|shadow)|/proc/self/environ|"
r"win\.ini|boot\.ini)", re.I)),
("MED", "sqli", re.compile(r"(union(\s|\+|/\*.*\*/)+select|\bor\b\s+1=1|sleep\(\d|benchmark\(|"
r"information_schema|extractvalue\(|updatexml\()", re.I)),
("LOW", "sensitive-file", re.compile(r"/(\.env|\.git/|\.svn/|wp-config\.php\.(bak|old|save|swp)|"
r"\.htpasswd|id_rsa|\.aws/credentials|phpinfo\.php)", re.I)),
]
R_SCANNER_UA = re.compile(r"(sqlmap|nikto|nuclei|gobuster|dirbuster|dirb|ffuf|feroxbuster|wpscan|"
r"masscan|zgrab|acunetix|nessus|openvas|nmap|hydra|wfuzz|whatweb|"
r"jaeles|httpx|interactsh|commix)", re.I)
R_TOOL_UA = re.compile(r"^(curl|wget|python-requests|python-urllib|go-http-client|libwww-perl|"
r"java/|okhttp|php/|ruby|axios|node-fetch|powershell|-$)", re.I)
KNOWN_POST = re.compile(r"/(wp-login\.php|xmlrpc\.php|wp-admin/admin-ajax\.php|wp-cron\.php|"
r"index\.php|wp-json/|graphql|api/)", re.I)
LOGIN_URL = re.compile(r"/(wp-login\.php|xmlrpc\.php|administrator/index\.php|user/login|login|"
r"admin/login|signin)", re.I)
# ======================================================================= helpers
_UID = {}
def uname(uid):
if uid not in _UID:
try:
_UID[uid] = pwd.getpwuid(uid).pw_name
except KeyError:
_UID[uid] = str(uid)
return _UID[uid]
def boot_time():
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 readlink(p):
try:
return os.readlink(p)
except OSError:
return None
def hex_ip(h):
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 norm_comm(c):
"""python3.12 -> python, php8.3 -> php, php-fpm8.3 -> php-fpm"""
c = (c or "").lower()
c = re.sub(r"[\d.]+$", "", c)
return c.rstrip("-") or c
def ago(secs):
secs = max(0, int(secs))
if secs < 60:
return f"{secs}s"
if secs < 3600:
return f"{secs // 60}m{secs % 60:02d}s"
if secs < 86400:
return f"{secs // 3600}h{secs % 3600 // 60:02d}m"
return f"{secs // 86400}d{secs % 86400 // 3600}h"
def hms(ts):
return datetime.fromtimestamp(ts).strftime("%H:%M:%S")
def human_bytes(n):
for u in ("", "K", "M", "G"):
if n < 1024:
return f"{n:.0f}{u}"
n /= 1024
return f"{n:.0f}T"
def read_proc(pid, bt):
"""Minimal fast process record (used by exec monitor and detail view)."""
base = f"/proc/{pid}"
try:
with open(base + "/stat", "rb") as fh:
raw = fh.read().decode("utf-8", "replace")
uid = os.stat(base).st_uid
except OSError:
return None
close = raw.rfind(")")
comm = raw[raw.find("(") + 1:close]
f = raw[close + 2:].split()
try:
ppid, start = int(f[1]), int(f[19])
except (ValueError, IndexError):
return None
try:
with open(base + "/cmdline", "rb") as fh:
cmd = fh.read().decode("utf-8", "replace").replace("\0", " ").strip()
except OSError:
cmd = ""
exe = readlink(base + "/exe") or ""
return {"pid": pid, "ppid": ppid, "uid": uid, "user": uname(uid), "comm": comm,
"cmdline": cmd or f"[{comm}]", "exe": exe, "cwd": readlink(base + "/cwd") or "",
"start": bt + start / HZ, "startticks": start}
def read_environ(pid, keys=("REMOTE_ADDR", "REQUEST_URI", "SCRIPT_FILENAME", "HTTP_HOST",
"REQUEST_METHOD", "HTTP_X_FORWARDED_FOR", "HTTP_USER_AGENT")):
try:
with open(f"/proc/{pid}/environ", "rb") as fh:
raw = fh.read().decode("utf-8", "replace").split("\0")
except OSError:
return {}
out = {}
for kv in raw:
k, _, v = kv.partition("=")
if k in keys:
out[k] = v
return out
FD_SCAN_COMMS = SHELLS | INTERP | NETTOOLS | {"java", "node", "dotnet", "beam.smp", "ruby", "deno", "bun"}
def scan_procs(bt, full_fds=False):
"""pid -> record incl. socket inodes and std fds; inode -> [pids sharing it].
fds (the expensive part) are read only for web servers + their descendants and
shells / interpreters / network tools, unless full_fds."""
procs, inode2pid = {}, {}
for e in os.scandir("/proc"):
if not e.name.isdigit():
continue
pid = int(e.name)
base = "/proc/" + e.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(")")
comm = raw[raw.find("(") + 1:close]
f = raw[close + 2:].split()
try:
pstate, ppid, start = f[0], int(f[1]), int(f[19])
except (ValueError, IndexError):
continue
try:
with open(base + "/cmdline", "rb") as fh:
cmd = fh.read().decode("utf-8", "replace").replace("\0", " ").strip()
except OSError:
cmd = ""
if not cmd and ppid in (0, 2): # kernel thread
continue
procs[pid] = {"pid": pid, "ppid": ppid, "uid": uid, "user": uname(uid), "comm": comm,
"cmdline": cmd or f"[{comm}]", "exe": "", "start": bt + start / HZ,
"startticks": start, "socks": set(), "std": [None, None, None], "state": pstate}
if full_fds:
want = set(procs)
else:
children = {}
for p in procs.values():
children.setdefault(p["ppid"], []).append(p["pid"])
want = set()
stack = [pid for pid, p in procs.items() if WEB_RE.match(p["comm"])]
while stack: # web servers + all descendants
x = stack.pop()
if x not in want:
want.add(x)
stack.extend(children.get(x, []))
want |= {pid for pid, p in procs.items() if norm_comm(p["comm"]) in FD_SCAN_COMMS}
for pid in want:
p = procs[pid]
base = f"/proc/{pid}"
try:
with os.scandir(base + "/fd") as it:
for fd in it:
t = readlink(fd.path)
if not t:
continue
if fd.name in ("0", "1", "2"):
p["std"][int(fd.name)] = t
if t.startswith("socket:["):
ino = t[8:-1]
p["socks"].add(ino)
inode2pid.setdefault(ino, []).append(pid)
except OSError:
pass
p["exe"] = readlink(base + "/exe") or ""
return procs, inode2pid
def netns_roots(procs=None):
"""One /proc/<pid>/net dir per network namespace (host + every container)."""
seen, roots = set(), []
me = readlink("/proc/self/ns/net")
if me:
seen.add(me)
roots.append(("host", "/proc/net"))
for pid in (procs if procs is not None else [int(x) for x in os.listdir("/proc") if x.isdigit()]):
ns = readlink(f"/proc/{pid}/ns/net")
if ns and ns not in seen:
seen.add(ns)
roots.append((ns, f"/proc/{pid}/net"))
return roots
def scan_tcp(procs=None):
"""Return (listen: [(ip,port,inode)], conns: [dict]) across all network namespaces.
Socket inodes are global, so the inode -> pid map still works for containers."""
listen, conns = [], []
paths = [(ns, d + "/" + f) for ns, d in netns_roots(procs) for f in ("tcp", "tcp6")]
for ns, path in paths:
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:
lh, lp = f[1].split(":")
rh, rp = f[2].split(":")
lport, rport = int(lp, 16), int(rp, 16)
except ValueError:
continue
st = TCP_STATES.get(f[3].upper(), f[3])
if st == "LISTEN":
listen.append((hex_ip(lh), lport, f[9]))
elif st not in ("TIME_WAIT", "CLOSE"):
conns.append({"lip": hex_ip(lh), "lport": lport, "rip": hex_ip(rh), "rport": rport,
"state": st, "inode": f[9], "uid": int(f[7]),
"netns": "host" if ns == "host" else ns[5:-1]})
return listen, conns
def client_ips_of(pid, ports):
"""Remote IPs of established inbound web-port connections held by pid (its own netns)."""
inos = set()
try:
with os.scandir(f"/proc/{pid}/fd") as it:
for fd in it:
t = readlink(fd.path)
if t and t.startswith("socket:["):
inos.add(t[8:-1])
except OSError:
return []
ips = []
for f in ("tcp", "tcp6"):
try:
with open(f"/proc/{pid}/net/{f}") as fh:
for line in fh.read().splitlines()[1:]:
x = line.split()
if len(x) > 9 and x[9] in inos and x[3] == "01" and int(x[1].split(":")[1], 16) in ports:
ip = hex_ip(x[2].split(":")[0])
if ip not in ips:
ips.append(ip)
except (OSError, ValueError, IndexError):
pass
return ips
# =================================================================== log tailing
LOG_RE = re.compile(
r'^(?:(?P<vhost>\S+:\d+) )?(?P<ip>\S+) \S+ (?P<user>\S+) \[(?P<time>[^\]]+)\] '
r'"(?P<req>[^"\\]*(?:\\.[^"\\]*)*)" (?P<status>\d{3}|-) (?P<size>\S+)'
r'(?: "(?P<ref>[^"\\]*(?:\\.[^"\\]*)*)" "(?P<ua>[^"\\]*(?:\\.[^"\\]*)*)")?(?P<rest>.*)$')
_TCACHE = {}
def parse_time(s):
t = _TCACHE.get(s)
if t is None:
try:
t = datetime.strptime(s, "%d/%b/%Y:%H:%M:%S %z").timestamp()
except ValueError:
t = time.time()
if len(_TCACHE) > 4096:
_TCACHE.clear()
_TCACHE[s] = t
return t
def parse_line(line, trust_xff=False):
if line.startswith('{"log":'): # docker json-file log driver
try:
line = json.loads(line)["log"].rstrip("\n")
except (ValueError, KeyError, TypeError):
return None
m = LOG_RE.match(line)
if not m:
return None
req = m["req"].split(" ")
if len(req) >= 2:
method, url = req[0], " ".join(req[1:-1]) if len(req) > 2 else req[1]
proto = req[-1] if len(req) > 2 else ""
else:
method, url, proto = "-", m["req"], ""
ip = m["ip"]
xff = ""
rest = (m["rest"] or "").strip()
if rest:
q = re.findall(r'"([^"]*)"', rest)
for v in q:
if re.match(r"^[0-9a-fA-F:.]+(,\s*[0-9a-fA-F:.]+)*$", v):
xff = v
break
if trust_xff and xff:
ip = xff.split(",")[0].strip()
size = m["size"]
return {"ts": parse_time(m["time"]), "ip": ip, "vhost": (m["vhost"] or ""), "method": method,
"url": url, "proto": proto, "status": int(m["status"]) if m["status"].isdigit() else 0,
"size": int(size) if size.isdigit() else 0, "ref": m["ref"] or "", "ua": m["ua"] or "",
"user": m["user"], "xff": xff, "peer": m["ip"], "flags": [], "sev": None}
def site_from_log(path):
"""cPanel domlogs/example.com(-ssl_log), nginx example.com.access.log -> example.com"""
b = os.path.basename(path or "")
for suf in ("-ssl_log", ".access.log", "-access.log", "_access.log", ".access_log", "-access_log", ".log"):
if b.endswith(suf):
b = b[: -len(suf)]
break
if "." in b and re.match(r"^[A-Za-z0-9][A-Za-z0-9.-]*\.[A-Za-z]{2,}$", b):
return b
return ""
class LogTail:
def __init__(self, path, backfill=200, from_start=False, err=None):
self.path, self.fh, self.ino, self.buf = path, None, None, b""
self.ok, self.err, self.lines = False, "", 0
if err: # a source we could not even list (e.g. folder, no permission)
self.err, self._pending = err, []
return
self._open(backfill, from_start)
def _open(self, backfill, from_start=False):
try:
self.fh = open(self.path, "rb")
st = os.fstat(self.fh.fileno())
self.ino = st.st_ino
self.ok = True
if from_start: # file created while we run: all of it is new
self._pending = []
elif backfill and st.st_size:
pos = max(0, st.st_size - backfill * 400)
self.fh.seek(pos)
data = self.fh.read()
lines = data.split(b"\n")
if pos:
lines = lines[1:]
self._pending = [x.decode("utf-8", "replace") for x in lines if x][-backfill:]
else:
self.fh.seek(0, 2)
self._pending = []
except OSError as e:
self.ok, self.err, self._pending = False, str(e), []
def read(self):
out, self._pending = self._pending, []
if not self.fh:
return out
try:
st = os.stat(self.path)
if st.st_ino != self.ino or st.st_size < self.fh.tell(): # rotated / truncated
self.fh.close()
self.fh = open(self.path, "rb")
self.ino = os.fstat(self.fh.fileno()).st_ino
self.buf = b""
except OSError:
return out
data = self.fh.read(4 << 20)
if data:
data = self.buf + data
parts = data.split(b"\n")
self.buf = parts.pop()
out.extend(p.decode("utf-8", "replace") for p in parts if p)
self.lines += len(out)
return out
# ============================================================ netlink exec monitor
def header_warnings(e, short=False):
"""Problems a user must see first: (long text for stderr / dashboard, short text for the TUI header)."""
w = []
if os.geteuid() != 0:
w.append(("NOT ROOT: run with sudo", "NOT ROOT: run with sudo"))
bad = [t for t in e.tails if not t.ok]
why = lambda t: t.err.split(": '")[0].split(": /")[0][:70] # "[Errno 2] No such file..." w/o the path
if not any(t.ok for t in e.tails):
if getattr(e, "stdout_logs", None):
w.append(("NO LOG FILE: this server logs to stdout (container) - run WebTop on the host",
"NO LOG FILE: logs go to stdout, run on host"))
elif bad:
name = os.path.basename(bad[0].path.rstrip("/")) or bad[0].path
w.append((f"NO LOG: {bad[0].path}: {why(bad[0])}", f"NO LOG: {name} (h: details)"))
else:
w.append(("NO ACCESS LOG FOUND: name it with -l FILE|FOLDER", "NO ACCESS LOG: use -l"))
elif bad:
w.append((f"{len(bad)} log(s) unreadable: {bad[0].path} ({why(bad[0])})", f"{len(bad)} log(s) unreadable"))
if e.a.trust_xff and e.lines_seen >= 30 and not e.xff_seen:
w.append(("--trust-xff but no X-Forwarded-For in the log", "no XFF in log"))
if "no db" in e.geo.status():
w.append(("geo: no .mmdb found (see README, Recipe E)", "geo: no .mmdb"))
return [x[1] if short else x[0] for x in w]
def web_bind_problem(bind):
"""None if [HOST:]PORT can be bound, else a short human explanation."""
host, _, port = bind.rpartition(":")
host = (host or "127.0.0.1").strip("[]")
try:
port_n = int(port)
except ValueError:
return f"'{port}' is not a port number (use e.g. --web 8800 or --web 127.0.0.1:8800)"
try:
fam = socket.AF_INET6 if ":" in host else socket.AF_INET
with socket.socket(fam, socket.SOCK_STREAM) as sk:
sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sk.bind((host, port_n))
except OSError as e:
if e.errno == 98:
return (f"port {port_n} is already in use (another webtop or service?). "
f"Pick another one: --web {port_n + 1}")
if e.errno == 13:
return f"no permission to use port {port_n} (ports below 1024 need root): try --web 8800"
if e.errno == 99:
return f"{host} is not an address of this machine"
return e.strerror or str(e)
return None
def exec_poll_reason(err):
"""Short, readable reason why the netlink exec monitor is not available."""
if "111" in err or "refused" in err.lower():
return "(container)"
if "Errno 1]" in err or "ermission" in err:
return "(netlink needs root)"
return f"({err[:30]})" if err else ""
HARD_HOW = ("socket", "env", "fpm-uri", "lsphp-script", "xff")
class ExecMonitor(threading.Thread):
"""Linux proc connector (cn_proc): real-time fork/exec events, so even
1-millisecond `sh -c id` spawned by a webshell is caught."""
def __init__(self, bt, is_web_pid, web_ports=lambda: DEFAULT_PORTS, fpm_lookup=None):
super().__init__(daemon=True, name="execmon")
self.bt, self.is_web_pid, self.web_ports, self.fpm_lookup = bt, is_web_pid, web_ports, fpm_lookup
self.q = queue.Queue(maxsize=20000)
self.fork_parent = {}
self.spawned = {} # pid -> ts of web-spawned processes we emitted
self.ok, self.err, self.events = False, "", 0
try:
self.sock = socket.socket(socket.AF_NETLINK, socket.SOCK_DGRAM, 11) # NETLINK_CONNECTOR
self.sock.bind((0, 1)) # CN_IDX_PROC
port = self.sock.getsockname()[0]
op = struct.pack("=I", 1) # MCAST_LISTEN
cn = struct.pack("=IIIIHH", 1, 1, 0, 0, len(op), 0) + op
self.sock.send(struct.pack("=IHHII", 16 + len(cn), 3, 0, 0, port) + cn)
self.ok = True
except (OSError, AttributeError) as e:
self.err = str(e)
self.work = queue.Queue(maxsize=50000)
if self.ok:
try: # bigger receive buffer for exec storms
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4 << 20)
except OSError:
pass
threading.Thread(target=self._worker, daemon=True, name="execwork").start()
def run(self):
while self.ok:
try:
data = self.sock.recv(65536)
except OSError as e:
self.ok, self.err = False, str(e)
return
off = 0
while off + 52 <= len(data):
nlen = struct.unpack_from("=I", data, off)[0]
if nlen < 52:
break
what = struct.unpack_from("=I", data, off + 36)[0]
if what == 0x1: # FORK
_pp, ptgid, cpid, ctgid = struct.unpack_from("=IIII", data, off + 52)
if cpid == ctgid:
self.fork_parent[ctgid] = ptgid
if len(self.fork_parent) > 100000:
for k in list(self.fork_parent)[:50000]:
self.fork_parent.pop(k, None)
elif what == 0x2: # EXEC
_pid, tgid = struct.unpack_from("=II", data, off + 52)
self.events += 1
# stage 1 (here, microseconds): grab cmdline/ppid/uid before a 1 ms command is gone;
# stage 2 (worker thread): ancestry, env, sockets, mod_status / php-fpm lookups
try:
self.work.put_nowait((tgid, self._quick(tgid), time.time()))
except queue.Full:
pass
off += (nlen + 3) & ~3
def _quick(self, pid):
out = {}
try:
with open(f"/proc/{pid}/cmdline", "rb") as fh:
out["cmdline"] = fh.read().decode("utf-8", "replace").replace("\0", " ").strip()
with open(f"/proc/{pid}/stat", "rb") as fh:
raw = fh.read().decode("utf-8", "replace")
close = raw.rfind(")")
out["comm"] = raw[raw.find("(") + 1:close]
f = raw[close + 2:].split()
out["ppid"], out["startticks"] = int(f[1]), int(f[19])
out["uid"] = os.stat(f"/proc/{pid}").st_uid
except (OSError, ValueError, IndexError):
pass
return out
def _worker(self):
while True:
pid, quick, ts = self.work.get()
try:
self._on_exec(pid, quick, ts)
except Exception: # noqa: BLE001 - never let one odd process kill the monitor
pass
def _on_exec(self, pid, quick=None, ts=None):
now = ts or time.time()
quick = quick or {}
rec = read_proc(pid, self.bt)
if rec is not None and quick.get("startticks") not in (None, rec["startticks"]):
rec = None # pid already reused
if rec is not None and not rec["cmdline"].strip("[]") or (rec is not None and rec["cmdline"] == f"[{rec['comm']}]"):
if quick.get("cmdline"):
rec["cmdline"] = quick["cmdline"]
if rec is None and quick.get("comm") and quick.get("ppid"):
uid = quick.get("uid", -1) # gone already, but stage 1 saw it
rec = {"pid": pid, "ppid": quick["ppid"], "uid": uid, "user": uname(uid) if uid >= 0 else "?",
"comm": quick["comm"], "cmdline": quick.get("cmdline") or f"{quick['comm']} (exited before capture)",
"exe": "", "cwd": "", "start": self.bt + quick["startticks"] / HZ, "startticks": quick["startticks"]}
if rec is not None and rec["cmdline"] == f"[{rec['comm']}]":
rec["cmdline"] = f"{rec['comm']} (exited before capture)"
if rec is None: # exited before we could look (e.g. 1 ms `id`)
chain, p = [], self.fork_parent.get(pid)
for _ in range(10):
if not p:
return
pr = read_proc(p, self.bt) or {"pid": p, "ppid": self.fork_parent.get(p), "comm": "?",
"user": "?", "cmdline": "?"}
chain.append(pr)
if p in self.spawned or self.is_web_pid(p) or WEB_RE.match(pr["comm"]):
break
p = pr.get("ppid")
else:
return
self._put({"ts": now, "pid": pid, "ppid": chain[0]["pid"], "comm": "?", "cmdline":
"(exited before capture)", "user": chain[0].get("user"), "exe": "", "cwd": "",
"start": now, "chain": chain, "env": {}, "src": "netlink", "client_ips": []})
return
if WEB_RE.match(rec["comm"]):
return
chain, p, seen = [], rec["ppid"], 0
web = False
while p > 1 and seen < 40:
pr = read_proc(p, self.bt)
if pr is None:
q = self.fork_parent.get(p) # parent already gone: use fork map
if p in self.spawned and q:
chain.append({"pid": p, "ppid": q, "comm": "?", "user": "?", "cmdline": "?"})
p, seen = q, seen + 1
continue
break
chain.append(pr)
if WEB_RE.match(pr["comm"]) or self.is_web_pid(p):
web = True
break
p, seen = pr["ppid"], seen + 1
if not web:
return
self.spawned[pid] = now
if len(self.spawned) > 20000:
cut = now - 600
self.spawned = {k: v for k, v in self.spawned.items() if v > cut}
env = read_environ(pid)
if not env:
for c in chain:
env = read_environ(c["pid"])
if env:
break
# grab the worker's client socket NOW - a 1 ms `id` request is gone by the next tick
ips = client_ips_of(chain[-1]["pid"], self.web_ports()) if chain else []
fpm = None
if chain and self.fpm_lookup and re.match(r"^(apache2?|httpd)", chain[-1]["comm"]):
try:
fpm = self.fpm_lookup(chain[-1]["pid"], None, apache=True) # mod_status: worker -> request
except Exception: # noqa: BLE001
fpm = None
if chain and self.fpm_lookup and chain[-1]["comm"].startswith("php-fpm"):
try:
fpm = self.fpm_lookup(chain[-1]["pid"], chain[-1]["ppid"]) # what is this worker serving NOW
except Exception: # noqa: BLE001 - attribution is best effort
fpm = None
script = None
for c in chain:
m = LSPHP_SCRIPT.match(c.get("cmdline") or "")
if m:
script = m[1]
break
rec.update({"ts": now, "chain": chain, "env": env, "src": "netlink", "client_ips": ips, "fpm": fpm,
"script": script})
self._put(rec)
def _put(self, ev):
try:
self.q.put_nowait(ev)
except queue.Full:
pass
# ============================================================ apache mod_status
class ConnSampler(threading.Thread):
"""Reads only /proc/<netns>/net/tcp* every `interval` s (cheap) so connections that
open and close between two refreshes are still seen."""
def __init__(self, eng, interval=0.2):
super().__init__(daemon=True, name="connsampler")
self.e, self.interval = eng, interval
self.seen, self.lock = {}, threading.Lock()
def run(self):
while True:
now = time.time()
ports = self.e.web_listen_ports
for ns, d in list(self.e.netns_paths):
for f in ("tcp", "tcp6"):
try:
with open(f"{d}/{f}") as fh:
lines = fh.read().splitlines()[1:]
except OSError:
continue
for line in lines:
x = line.split()
if len(x) < 10 or x[3] != "01":
continue
try:
lh, lp = x[1].split(":")
rh, rp = x[2].split(":")
lport = int(lp, 16)
except ValueError:
continue
if lport not in ports:
continue
key = (hex_ip(lh), lport, hex_ip(rh), int(rp, 16))
with self.lock:
v = self.seen.get(key)
if v:
v[1] = now
else:
self.seen[key] = [now, now]
with self.lock:
if len(self.seen) > 5000 or int(now) % 10 == 0:
cut = now - 120
self.seen = {k: v for k, v in self.seen.items() if v[1] > cut}
time.sleep(self.interval)
def snapshot(self):
with self.lock:
return dict(self.seen)
# ======================================================= upload / webshell-drop watcher
SCRIPT_FILE = re.compile(r"(\.(php\d?|phtml|phar|pht|phps|inc|shtml?|jsp|jspx|asp|aspx|ashx|cgi|pl|py|sh)$|"
r"\.php\d?\.[A-Za-z0-9]{1,5}$|^\.htaccess$|^\.user\.ini$|^php\.ini$)", re.I)
UPLOAD_DIR = re.compile(r"/(wp-content/uploads|uploads?|upload_files|images?|img|files|media|cache|tmp|temp|"
r"static|assets|attachments|userfiles|avatars?|wp-includes/(css|images|fonts|js))(/|$)", re.I)
SKIP_DIRS = {".git", ".svn", ".hg", "node_modules", ".cache", "__pycache__", ".well-known"}
# (severity, rule-name, regex) applied to the first 1 MB of a new file
FILE_SIGS = [
("CRIT", "eval-of-decoded-payload", re.compile(
r"(eval|assert)\s*\(\s*(@?\s*)(base64_decode|gzinflate|gzuncompress|gzdecode|str_rot13|strrev|"
r"rawurldecode|hex2bin|convert_uudecode)\s*\(", re.I)),
("CRIT", "exec-of-request-input", re.compile(
r"(eval|assert|system|exec|shell_exec|passthru|popen|proc_open|pcntl_exec)\s*\(\s*@?\s*"
r"(stripslashes\s*\(\s*)?\$_(GET|POST|REQUEST|COOKIE|SERVER|FILES)", re.I)),
("CRIT", "variable-function-from-input", re.compile(r"\$_(GET|POST|REQUEST|COOKIE)\s*\[[^\]]{1,40}\]\s*\(", re.I)),
("CRIT", "php-reverse-shell", re.compile(r"fsockopen\s*\([\s\S]{0,2000}?(proc_open|shell_exec|exec|/bin/(ba)?sh)", re.I)),
("CRIT", "known-webshell-family", re.compile(
r"(c99shell|r57shell|WSO\s*[0-9.]+|b374k|FilesMan|IndoXploit|Alfa\s?Team|AnonymousFox|"
r"marijuana\s?shell|leafmailer|P\.A\.S\.|webadmin\.php|0byt3m1n1|Sh3ll)", re.I)),
("HIGH", "preg-replace-e", re.compile(r"preg_replace\s*\(\s*['\"][^'\"]{0,200}/e['\"]", re.I)),
("HIGH", "create-function-input", re.compile(r"create_function\s*\([\s\S]{0,300}\$_(GET|POST|REQUEST|COOKIE)", re.I)),
("HIGH", "file-uploader", re.compile(r"move_uploaded_file\s*\(\s*\$_FILES", re.I)),
("HIGH", "obfuscated-blob", re.compile(r"[A-Za-z0-9+/=]{3000,}")),
("HIGH", "handler-override", re.compile(
r"((AddHandler|AddType|SetHandler|ForceType)\s+[^\n]*(php|x-httpd|cgi-script))|"
r"(auto_(prepend|append)_file)", re.I)),
("MED", "exec-functions", re.compile(r"\b(shell_exec|passthru|proc_open|pcntl_exec)\s*\(", re.I)),
]
def scan_content(path, limit=1 << 20):
try:
with open(path, "rb") as fh:
data = fh.read(limit).decode("latin-1")
except OSError:
return []
return [(sev, name) for sev, name, rx in FILE_SIGS if rx.search(data)]
def _conf_files(prefix=""):
pats = ["/etc/apache2/apache2.conf", "/etc/apache2/sites-enabled/*", "/etc/apache2/conf-enabled/*",
"/etc/httpd/conf/httpd.conf", "/etc/httpd/conf.d/*.conf", "/usr/local/apache/conf/httpd.conf",
"/etc/apache2/conf/httpd.conf", "/etc/apache2/conf.d/*.conf", "/etc/apache2/conf.d/userdata/*/*/*/*.conf",
"/etc/nginx/nginx.conf", "/etc/nginx/sites-enabled/*", "/etc/nginx/conf.d/*.conf",
"/usr/local/lsws/conf/httpd_config.conf", "/usr/local/lsws/conf/vhosts/*/vhconf.conf",
"/etc/lighttpd/lighttpd.conf", "/etc/caddy/Caddyfile"]
out = []
for p in pats:
out.extend(glob.glob(prefix + p))
return out
DOCROOT_RE = re.compile(r"^\s*(?:DocumentRoot|docRoot|root|server\.document-root\s*=|Alias\s+\S+)\s+\"?([^\"\s;]+)",
re.I | re.M)
def find_docroots(extra=(), container_pids=()):
"""[(path_to_watch, url_base, label)] for host + containers (via /proc/<pid>/root)."""
found = []
prefixes = [("", "host")] + [(f"/proc/{pid}/root", f"container:{pid}") for pid in container_pids]
for prefix, label in prefixes:
for cf in _conf_files(prefix):
try:
with open(cf, errors="replace") as fh:
txt = fh.read(1 << 20)
except OSError:
continue
for m in DOCROOT_RE.finditer(txt):
d = m[1].rstrip("/")
if "$" in d:
vh = os.path.basename(os.path.dirname(cf))
d = d.replace("$VH_ROOT", f"/usr/local/lsws/{vh}").replace("$SERVER_ROOT", "/usr/local/lsws")
if d.startswith("/") and "$" not in d:
found.append((prefix + d, label))
for g in ("/home/*/public_html", "/home/*/www", "/var/www/vhosts/*/httpdocs", "/var/www/html", "/var/www/*/public"):
for d in glob.glob(prefix + g):
found.append((d, label))
for d in extra:
found.append((os.path.abspath(d), "--watch"))
out, seen = [], set()
for d, label in found:
try:
if not os.path.isdir(d):
continue
# never realpath() /proc/<pid>/root/... - it would resolve to the HOST path
key = os.path.normpath(d) if d.startswith("/proc/") else os.path.realpath(d)
except OSError:
continue
if key in seen:
continue
seen.add(key)
out.append((d, label))
# drop roots nested inside another root (one recursive watch covers them)
out.sort(key=lambda x: len(x[0]))
final = []
for d, label in out:
if not any(d == f or d.startswith(f.rstrip("/") + "/") for f, _ in final):
final.append((d, label))
return final
class FileWatcher(threading.Thread):
"""Recursive inotify watcher (ctypes, no dependencies)."""
IN_MODIFY, IN_ATTRIB, IN_CLOSE_WRITE, IN_MOVED_TO, IN_CREATE = 0x2, 0x4, 0x8, 0x80, 0x100
IN_DELETE_SELF, IN_Q_OVERFLOW, IN_IGNORED, IN_ISDIR = 0x400, 0x4000, 0x8000, 0x40000000
def __init__(self, cap=20000):
super().__init__(daemon=True, name="filewatch")
self.q = queue.Queue(maxsize=20000)
self.wd, self.roots, self.lock = {}, {}, threading.Lock()
self.ok, self.err, self.capped, self.events, self.overflows = False, "", False, 0, 0
try:
with open("/proc/sys/fs/inotify/max_user_watches") as fh:
cap = min(cap, int(int(fh.read()) * 0.8))
except (OSError, ValueError):
pass
self.cap = cap
try:
self.libc = ctypes.CDLL(None, use_errno=True)
self.fd = self.libc.inotify_init1(os.O_CLOEXEC)
if self.fd < 0:
raise OSError(ctypes.get_errno(), "inotify_init1 failed")
self.ok = True
except (OSError, AttributeError) as e:
self.err = str(e)
def _add(self, d):
if len(self.wd) >= self.cap:
self.capped = True
return False
mask = self.IN_CLOSE_WRITE | self.IN_MOVED_TO | self.IN_CREATE | self.IN_ATTRIB | self.IN_DELETE_SELF
w = self.libc.inotify_add_watch(self.fd, os.fsencode(d), mask)
if w >= 0:
self.wd[w] = d
return True
return False
def add_tree(self, top, emit_existing=False):
n = 0
for dp, dns, fns in os.walk(top):
dns[:] = [x for x in dns if x not in SKIP_DIRS and not os.path.islink(os.path.join(dp, x))]
with self.lock:
if not self._add(dp):
if self.capped:
return n
continue
n += 1
if emit_existing: # dir created while we were not watching it yet
for f in fns:
if SCRIPT_FILE.search(f):
self._put(os.path.join(dp, f), "created")
return n
def add_root(self, path, label, url_base="/"):
if path in self.roots or not self.ok:
return 0
self.roots[path] = {"label": label, "url": url_base, "dirs": 0}
n = self.add_tree(path)
self.roots[path]["dirs"] = n
return n
def root_of(self, path):
best = None
for r in self.roots:
if path == r or path.startswith(r.rstrip("/") + "/"):
if best is None or len(r) > len(best):
best = r
return best
def _put(self, path, kind):
self.events += 1
try:
self.q.put_nowait({"ts": time.time(), "path": path, "kind": kind})
except queue.Full:
pass
def run(self):
hdr = struct.calcsize("iIII")
while self.ok:
try:
buf = os.read(self.fd, 1 << 16)
except OSError as e:
self.ok, self.err = False, str(e)
return
off = 0
while off + hdr <= len(buf):
w, mask, _cookie, ln = struct.unpack_from("iIII", buf, off)
name = buf[off + hdr:off + hdr + ln].split(b"\0", 1)[0].decode("utf-8", "replace")
off += hdr + ln
if mask & self.IN_Q_OVERFLOW:
self.overflows += 1
continue
d = self.wd.get(w)
if d is None:
continue