-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinux_forensics.py
More file actions
1642 lines (1426 loc) · 62.6 KB
/
Copy pathlinux_forensics.py
File metadata and controls
1642 lines (1426 loc) · 62.6 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
# -*- coding: utf-8 -*-
"""
linux_forensics.py - DFIR LINUX SNIPER v2.0
Corrélateur Réseau / Processus / Système de fichiers pour live forensics Linux.
Contraintes de conception (inchangées) :
* Aucune dépendance externe (stdlib uniquement, Python >= 3.6).
* Exécution intégralement en mémoire : aucune écriture disque, aucun appel
réseau, aucun signal envoyé, aucun module chargé.
* Lecture seule stricte : O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_NOATIME.
* Comportement dégradé mais utile en utilisateur standard, complet en root.
* Confirmation explicite de l'analyste après affichage d'un avertissement.
Sortie : indicateurs pondérés + SHA256 de chaque artefact retenu, pour
pivot CTI (VirusTotal / MISP / OpenCTI / MalwareBazaar).
Changelog v2.0
--------------
Correctifs de bugs :
* Filtrage loopback IPv6 inopérant (comparaison sur une chaîne contenant
le port) et sessions loopback ESTABLISHED remontées à tort.
* Conversion hexadécimale des adresses codée en dur pour little-endian.
* Écrasement d'entrées de socket sur l'inode 0 (TIME_WAIT / orphelins).
* Fuite de descripteur si os.fdopen() échouait après os.open().
* Blocage possible sur FIFO/device faute de contrôle S_ISREG.
* Comparaison de CapEff à une constante de 16 zéros (dépend du noyau).
* `break` inopérant sur la boucle externe lors du parsing d'environ.
* `f"{COULEUR}=" * 70` répétait la séquence ANSI 70 fois.
* input() sur stdin non interactif levait EOFError non gérée.
* PID 1 arbitrairement exclu de l'analyse.
Durcissement :
* O_NOFOLLOW systématique (anti-symlink), lectures bornées, budget global
de fichiers, non-franchissement des points de montage, anti-ReDoS.
* Neutralisation des séquences ANSI présentes dans les noms de fichiers
et les cmdline (anti-injection dans le terminal de l'analyste).
Détection ajoutée :
* Binaire supprimé ou memfd toujours en exécution, usurpation de nom de
thread noyau, ptrace actif, élévation RUID/EUID.
* Processus cachés (getdents filtré), LKM masqué, kernel tainted,
sockets sans propriétaire, /etc/ld.so.preload.
* Chasse fichiers dans les répertoires de prédilection des implants avec
SHA256, analyse de contenu des scripts déposés et des tâches planifiées.
"""
import argparse
import errno
import hashlib
import ipaddress
import os
import re
import stat
import sys
import time
VERSION = "2.0"
# ==========================================================================
# CONFIGURATION & IoC
# ==========================================================================
# --- Limites de sûreté (anti-DoS sur soi-même) ---
MAX_PROC_READ = 512 * 1024 # octets lus par pseudo-fichier /proc
HASH_CHUNK = 1024 * 1024 # taille de bloc pour le SHA256
DEFAULT_MAX_HASH_SIZE = 128 * 1024 * 1024
DEFAULT_MAX_DEPTH = 6
DEFAULT_MAX_FILES_PER_ROOT = 8000
GLOBAL_FILE_BUDGET = 60000
REGEX_PROBE_LIMIT = 64 * 1024 # borne les moteurs regex (anti-ReDoS sur fichier gonflé)
MAX_PID_BRUTEFORCE = 131072
# --- Seuils de scoring (réduction des faux positifs) ---
SEV_CRITICAL = 70
SEV_HIGH = 50
SEV_MEDIUM = 30
# --- Patterns de ligne de commande (regex ciblées, pas de mots-clés nus) ---
CMD_PATTERNS = [
(re.compile(r'/dev/(tcp|udp)/[0-9a-z]', re.I),
"Reverse shell natif bash (/dev/tcp)", 70),
(re.compile(r'\b(nc|ncat|netcat)(\.\w+)?\b[^;|&]{0,120}?\s-\w*e\w*(\s|$)'),
"Netcat avec exécution de commande (-e/-c)", 65),
(re.compile(r'\b(curl|wget)\b[^;|&]{0,160}\|\s*(ba|z|k|da)?sh\b'),
"Téléchargement redirigé vers un interpréteur (dropper)", 70),
(re.compile(r'\b(curl|wget)\b[^;|&]{0,160}\s-O\s*/(tmp|dev/shm|var/tmp)/'),
"Téléchargement vers un répertoire monde-inscriptible", 55),
(re.compile(r'\bpython[0-9.]*\s+-c\b.{0,300}?(socket\.socket|pty\.spawn|os\.dup2|'
r'SOCK_STREAM|connect\()', re.S),
"One-liner Python établissant un socket / relais de tty", 60),
(re.compile(r'\bpython[0-9.]*\s+-c\b.{0,300}?(subprocess|os\.system|os\.popen|'
r'exec\(|eval\()', re.S),
"One-liner Python exécutant des commandes (LotL, à corréler)", 25),
(re.compile(r'\bperl\s+-e\b.{0,300}?(socket|exec|system)', re.S),
"One-liner Perl orienté shell/socket", 60),
(re.compile(r'\bruby\s+-r?socket\b'), "One-liner Ruby socket", 55),
(re.compile(r'\bphp\s+-r\b.{0,300}?(fsockopen|exec|system)', re.S),
"One-liner PHP orienté shell/socket", 60),
(re.compile(r'\bsocat\b[^;|&]{0,160}(exec|system):', re.I),
"Socat avec exécution de commande", 65),
(re.compile(r'\bbase64\s+(-d|--decode)\b[^;|&]{0,120}\|\s*(ba|z|k|da)?sh\b'),
"Payload base64 décodé puis exécuté", 70),
(re.compile(r'\b(bash|sh|zsh|ksh)\s+-[a-z]*i\b'),
"Shell interactif lancé en ligne de commande", 30),
(re.compile(r'\bhistory\s+-c\b|\bunset\s+HISTFILE\b|HISTFILE=/dev/null|HISTSIZE=0'),
"Anti-forensic : neutralisation de l'historique shell", 55),
(re.compile(r'\bchattr\s+[+-]i\b'),
"Anti-forensic : verrouillage d'attribut immuable", 45),
(re.compile(r'ld\.so\.preload'),
"Manipulation de /etc/ld.so.preload (hooking userland)", 60),
(re.compile(r'\binsmod\b|\bmodprobe\s+\./|/proc/self/mem\b'),
"Manipulation noyau / mémoire du processus courant", 55),
(re.compile(r'memfd_create|/memfd:'),
"Exécution depuis un fichier anonyme en mémoire (memfd)", 65),
(re.compile(r'\b(xmrig|minerd|cpuminer|kdevtmpfsi|kinsing|tsunami|dota3?|'
r'watchdogs|sysrv|xmr-stak|nanominer|teamtnt)\b', re.I),
"Nom associé à un malware/cryptominer Linux connu", 85),
(re.compile(r'--donate-level|stratum\+tcp://|pool\.(minexmr|supportxmr|nanopool)', re.I),
"Configuration de pool de minage", 85),
(re.compile(r'\b(chmod|chown)\s+[+7]?[0-7]{0,4}s?\s+/(tmp|dev/shm|var/tmp)/'),
"Modification de permissions dans un répertoire temporaire", 35),
]
# --- Variables d'environnement à haut risque ---
ENV_CRITICAL = ('LD_PRELOAD', 'LD_AUDIT')
ENV_WATCH = ('LD_LIBRARY_PATH', 'PROMPT_COMMAND', 'BASH_ENV', 'ENV', 'PYTHONSTARTUP')
# Chemins tolérés pour LD_PRELOAD/LD_AUDIT (intégrations légitimes connues)
ENV_ALLOW_SUBSTR = (
'libsnapd-glib', '/snap/', 'nvidia', 'libgtk3-nocsd', 'libfakeroot',
'libjemalloc', 'libtcmalloc', 'libnss_', 'libpam', '/usr/lib/apt/',
'libSegFault', 'libjvm', 'libasan', 'libtsan', 'libeatmydata',
)
# --- Répertoires d'exécution atypiques ---
EXEC_RED_ZONES = (
'/tmp/', '/var/tmp/', '/dev/shm/', '/run/shm/', '/dev/mqueue/',
'/var/spool/', '/var/lock/', '/var/run/', '/run/user/',
)
EXEC_TRUSTED_PREFIX = (
'/usr/bin/', '/usr/sbin/', '/usr/lib/', '/usr/libexec/', '/usr/share/',
'/bin/', '/sbin/', '/lib/', '/lib64/', '/opt/', '/snap/',
'/usr/local/bin/', '/usr/local/sbin/', '/usr/local/lib/', '/usr/local/libexec/',
)
# --- Capacités Linux réellement dangereuses pour un processus non-root ---
DANGEROUS_CAPS = {
1: 'CAP_DAC_OVERRIDE', 2: 'CAP_DAC_READ_SEARCH', 4: 'CAP_FOWNER',
6: 'CAP_SETGID', 7: 'CAP_SETUID', 8: 'CAP_SETPCAP',
16: 'CAP_SYS_MODULE', 17: 'CAP_SYS_RAWIO', 18: 'CAP_SYS_CHROOT',
19: 'CAP_SYS_PTRACE', 21: 'CAP_SYS_ADMIN', 22: 'CAP_SYS_BOOT',
38: 'CAP_PERFMON', 39: 'CAP_BPF',
}
# --- Noms de threads noyau usurpés par les rootkits userland ---
KTHREAD_LIKE = re.compile(
r'^\[?(kworker|ksoftirqd|kthreadd|migration|rcu_|watchdog|kswapd|'
r'kcompactd|khugepaged|kdevtmpfs|kaudit|kintegrity|jbd2|ext4-|'
r'irq/|scsi_|md|xfs)', re.I)
# --- Fichiers de persistance systématiquement empreintés ---
PERSISTENCE_FILES = (
'/etc/ld.so.preload', '/etc/rc.local', '/etc/crontab',
'/etc/hosts.deny', '/etc/sudoers',
)
PERSISTENCE_DIRS = (
'/etc/cron.d', '/etc/cron.hourly', '/etc/cron.daily',
'/etc/cron.weekly', '/etc/cron.monthly', '/etc/profile.d',
'/etc/update-motd.d', '/var/spool/cron', '/var/spool/cron/crontabs',
)
# Deux niveaux : le niveau faible (curl/wget seuls) est omniprésent dans les
# scripts légitimes de distribution (update-motd, apt, certbot...).
PERSISTENCE_STRONG = re.compile(
r'/dev/tcp/|\b(nc|ncat|netcat)\b[^\n]{0,80}\s-\w*e|'
r'base64\s+(-d|--decode)[^\n]{0,80}\|\s*(ba)?sh|'
r'(curl|wget)[^\n]{0,120}\|\s*(ba)?sh|'
r'\b(chattr\s+[+-]i|history\s+-c|HISTFILE=/dev/null)\b|'
r'(/tmp/|/dev/shm/|/var/tmp/)[\w.\-]*\s*(&|;|$)', re.I | re.M)
PERSISTENCE_WEAK = re.compile(
r'\b(curl|wget)\b|\bbase64\b|\bpython[0-9.]*\s+-c\b|\bperl\s+-e\b', re.I)
# --- Magies de fichiers ---
MAGIC_ELF = b'\x7fELF'
MAGIC_SCRIPT = b'#!'
# ==========================================================================
# PRÉSENTATION TERMINAL
# ==========================================================================
class Palette(object):
"""Codes ANSI, neutralisés si la sortie n'est pas un TTY (--no-color)."""
def __init__(self, enabled=True):
self.enabled = enabled
def __call__(self, text, code):
if not self.enabled:
return text
return '\033[%sm%s\033[0m' % (code, text)
def red(self, t):
return self(t, '91')
def green(self, t):
return self(t, '92')
def yellow(self, t):
return self(t, '93')
def cyan(self, t):
return self(t, '96')
def grey(self, t):
return self(t, '90')
def bold(self, t):
return self(t, '1')
C = Palette(False) # remplacé dans main()
def out(msg=''):
try:
sys.stdout.write(msg + '\n')
except (BrokenPipeError, ValueError):
raise SystemExit(0)
def severity_label(score):
if score >= SEV_CRITICAL:
return 'CRITIQUE', C.red
if score >= SEV_HIGH:
return 'ELEVE', C.red
if score >= SEV_MEDIUM:
return 'MOYEN', C.yellow
return 'INFO', C.cyan
# ==========================================================================
# MOTEUR I/O SÉCURISÉ (lecture seule, non bloquant, anti-symlink)
# ==========================================================================
O_NOATIME = getattr(os, 'O_NOATIME', 0o1000000)
O_CLOEXEC = getattr(os, 'O_CLOEXEC', 0)
_STATS = {
'noatime_ok': 0,
'noatime_fallback': 0,
'read_denied': 0,
'hashed': 0,
'hash_bytes': 0,
}
def open_ro(path, nofollow=True):
"""Ouvre un fichier en lecture seule sans jamais suivre de lien symbolique
et sans jamais bloquer (FIFO / device). Retourne un fd ou None."""
flags = os.O_RDONLY | os.O_NONBLOCK | O_CLOEXEC
if nofollow:
flags |= os.O_NOFOLLOW
try:
fd = os.open(path, flags | O_NOATIME)
_STATS['noatime_ok'] += 1
return fd
except OSError as exc:
# O_NOATIME exige d'être propriétaire du fichier ou CAP_FOWNER.
if exc.errno in (errno.EPERM, errno.EACCES, errno.EINVAL, errno.EROFS):
try:
fd = os.open(path, flags)
_STATS['noatime_fallback'] += 1
return fd
except OSError:
_STATS['read_denied'] += 1
return None
_STATS['read_denied'] += 1
return None
def read_bytes(path, limit=MAX_PROC_READ, nofollow=True, require_regular=False):
"""Lecture bornée et non bloquante. Ne lève jamais."""
fd = open_ro(path, nofollow=nofollow)
if fd is None:
return None
try:
try:
st = os.fstat(fd)
except OSError:
return None
if require_regular and not stat.S_ISREG(st.st_mode):
return None
buf = bytearray()
while len(buf) < limit:
try:
chunk = os.read(fd, min(65536, limit - len(buf)))
except (BlockingIOError, InterruptedError):
break
except OSError:
break
if not chunk:
break
buf += chunk
return bytes(buf)
finally:
try:
os.close(fd)
except OSError:
pass
def read_text(path, limit=MAX_PROC_READ, nofollow=True):
data = read_bytes(path, limit=limit, nofollow=nofollow)
if data is None:
return None
return data.decode('utf-8', 'replace')
def sanitize(text, maxlen=None):
"""Neutralise les caractères de contrôle (protection du terminal contre
l'injection de séquences ANSI par un nom de fichier ou une cmdline)."""
if not text:
return ''
clean = re.sub(r'[\x00-\x1f\x7f-\x9f]', ' ', text)
clean = re.sub(r'\s{2,}', ' ', clean).strip()
if maxlen and len(clean) > maxlen:
clean = clean[:maxlen] + '...'
return clean
def readlink(path):
try:
return os.readlink(path)
except OSError:
return None
def sha256_fd(fd, size_hint, max_size):
"""Empreinte un descripteur déjà ouvert et validé. Retourne (hash, magic)."""
if size_hint is not None and size_hint > max_size:
return 'NON-CALCULE (taille > limite)', b''
h = hashlib.sha256()
magic = b''
total = 0
while True:
try:
chunk = os.read(fd, HASH_CHUNK)
except (BlockingIOError, InterruptedError):
break
except OSError:
return None, magic
if not chunk:
break
if not magic:
magic = chunk[:8]
total += len(chunk)
if total > max_size:
return 'NON-CALCULE (taille > limite)', magic
h.update(chunk)
_STATS['hashed'] += 1
_STATS['hash_bytes'] += total
return h.hexdigest(), magic
def sha256_path(path, max_size, nofollow=True):
"""SHA256 d'un fichier régulier. Ne suit pas les symlinks, ne bloque pas
sur un FIFO ou un device."""
fd = open_ro(path, nofollow=nofollow)
if fd is None:
return None, b''
try:
try:
st = os.fstat(fd)
except OSError:
return None, b''
if not stat.S_ISREG(st.st_mode):
return None, b''
return sha256_fd(fd, st.st_size, max_size)
finally:
try:
os.close(fd)
except OSError:
pass
def file_kind(magic):
if magic.startswith(MAGIC_ELF):
return 'ELF'
if magic.startswith(MAGIC_SCRIPT):
return 'SCRIPT'
if magic[:2] in (b'\x1f\x8b',) or magic[:4] in (b'PK\x03\x04', b'\xfd7zXZ'):
return 'ARCHIVE'
return 'DATA'
def fmt_time(epoch):
try:
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(epoch))
except (ValueError, OSError):
return '?'
def fmt_size(n):
for unit in ('o', 'Ko', 'Mo', 'Go'):
if n < 1024:
return '%d%s' % (n, unit)
n //= 1024
return '%dTo' % n
# ==========================================================================
# COLLECTE DES RÉSULTATS
# ==========================================================================
class Report(object):
def __init__(self):
self.findings = []
self.iocs = [] # (sha256, path, contexte)
self._seen_hash = set()
def add(self, score, category, title, details, hashes=None):
self.findings.append({
'score': score, 'category': category, 'title': title,
'details': details, 'hashes': hashes or [],
})
def add_ioc(self, digest, path, context):
if not digest or not re.fullmatch(r'[0-9a-f]{64}', digest):
return
key = (digest, path)
if key in self._seen_hash:
return
self._seen_hash.add(key)
self.iocs.append((digest, path, context))
def sorted_findings(self, min_score):
keep = [f for f in self.findings if f['score'] >= min_score]
return sorted(keep, key=lambda f: -f['score'])
REPORT = Report()
# ==========================================================================
# RÉSOLUTION RÉSEAU
# ==========================================================================
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',
}
TCP_TARGET_STATES = ('01', '02', '0A') # ESTABLISHED, SYN_SENT, LISTEN
def _hex_to_addr(hex_addr):
"""Convertit une adresse hexadécimale du noyau (ordre hôte) en objet
ipaddress. Gère explicitement l'endianness de la machine."""
raw = bytes(bytearray.fromhex(hex_addr))
if len(raw) == 4:
if sys.byteorder == 'little':
raw = raw[::-1]
return ipaddress.IPv4Address(raw)
if len(raw) == 16:
if sys.byteorder == 'little':
raw = b''.join(raw[i:i + 4][::-1] for i in range(0, 16, 4))
return ipaddress.IPv6Address(raw)
raise ValueError('longueur d adresse inattendue')
def parse_hex_endpoint(token):
"""'0100007F:1F90' -> (IPv4Address, 8080). Retourne (None, None) si KO."""
try:
hex_addr, hex_port = token.split(':')
return _hex_to_addr(hex_addr), int(hex_port, 16)
except (ValueError, ipaddress.AddressValueError):
return None, None
def addr_repr(addr, port):
if addr is None:
return '?:?'
if addr.version == 6:
return '[%s]:%d' % (addr.compressed, port)
return '%s:%d' % (addr.compressed, port)
def is_unspecified(addr):
return addr is not None and int(addr) == 0
def parse_socket_table(path, proto):
"""Parse une table /proc/net/{tcp,tcp6,udp,udp6}. Retourne {inode: info}."""
content = read_text(path)
if not content:
return {}
result = {}
for line in content.splitlines()[1:]:
parts = line.split()
if len(parts) < 10:
continue
local_tok, remote_tok, state, uid, inode = (
parts[1], parts[2], parts[3].upper(), parts[7], parts[9])
if inode == '0':
continue # sockets orphelins / TIME_WAIT
if proto.startswith('tcp') and state not in TCP_TARGET_STATES:
continue
laddr, lport = parse_hex_endpoint(local_tok)
raddr, rport = parse_hex_endpoint(remote_tok)
if laddr is None:
continue
# Filtrage du trafic strictement local (corrige le bug de la v1 :
# les sessions établies 127.0.0.1 <-> 127.0.0.1 passaient au travers).
loop_local = laddr.is_loopback
loop_remote = raddr is not None and (raddr.is_loopback or is_unspecified(raddr))
if loop_local and loop_remote:
continue
remote_public = bool(raddr is not None and not is_unspecified(raddr)
and not raddr.is_private and not raddr.is_loopback
and not raddr.is_link_local and not raddr.is_multicast)
listening_public = bool(state == '0A' and not laddr.is_loopback)
result[inode] = {
'proto': proto,
'state': TCP_STATES.get(state, 'UDP' if proto.startswith('udp') else state),
'local': addr_repr(laddr, lport),
'remote': addr_repr(raddr, rport) if raddr is not None else '-',
'remote_public': remote_public,
'remote_ip': raddr.compressed if raddr is not None else None,
'listening_public': listening_public,
'uid': uid,
}
return result
def collect_sockets(netns_pids, is_root):
"""Agrège les tables de sockets du namespace courant et, en root, de tous
les namespaces réseau distincts trouvés (détection de C2 conteneurisé)."""
tables = {}
namespaces = {'host': ''}
if is_root:
namespaces.update(netns_pids)
for ns_id, pid in namespaces.items():
base = '/proc/net' if not pid else '/proc/%s/net' % pid
for proto in ('tcp', 'tcp6', 'udp', 'udp6'):
path = '%s/%s' % (base, proto)
if not os.path.exists(path):
continue
for inode, info in parse_socket_table(path, proto).items():
info['netns'] = ns_id
tables.setdefault(inode, info)
return tables
def process_socket_inodes(pid):
"""Inodes de socket détenus par un PID (via /proc/<pid>/fd)."""
inodes = set()
fd_dir = '/proc/%s/fd' % pid
try:
with os.scandir(fd_dir) as entries:
for entry in entries:
link = readlink(entry.path)
if link and link.startswith('socket:['):
inodes.add(link[8:-1])
except OSError:
pass
return inodes
# ==========================================================================
# INSPECTION DES PROCESSUS
# ==========================================================================
PF_KTHREAD = 0x00200000
def parse_proc_stat(pid):
"""Parse /proc/<pid>/stat en gérant les comm contenant espaces/parenthèses."""
raw = read_text('/proc/%s/stat' % pid, limit=8192)
if not raw:
return None
close = raw.rfind(')')
open_ = raw.find('(')
if close == -1 or open_ == -1 or close < open_:
return None
comm = raw[open_ + 1:close]
fields = raw[close + 1:].split()
if len(fields) < 20:
return None
try:
return {
'comm': comm,
'state': fields[0],
'ppid': fields[1],
'flags': int(fields[6]),
'starttime': fields[19],
}
except (ValueError, IndexError):
return None
def parse_proc_status(pid):
raw = read_text('/proc/%s/status' % pid, limit=32768)
if not raw:
return {}
info = {}
for line in raw.splitlines():
if ':' not in line:
continue
key, _, value = line.partition(':')
info[key.strip()] = value.strip()
return info
def caps_to_names(cap_hex):
try:
mask = int(cap_hex, 16)
except (ValueError, TypeError):
return []
return [name for bit, name in DANGEROUS_CAPS.items() if mask & (1 << bit)]
def path_is_hidden(path):
return any(part.startswith('.') and part not in ('.', '..')
for part in path.split('/') if part)
def analyse_process(pid, sockets, init_netns, args, is_root):
"""Analyse un PID et retourne un dict de constat si le score est retenu."""
proc_dir = '/proc/%s' % pid
st = parse_proc_stat(pid)
if st is None:
return None
# Les threads noyau n'ont ni exe ni cmdline : on les exclut du scoring
# métier, sauf s'ils détiennent un socket (cas rootkit LKM).
is_kthread = bool(st['flags'] & PF_KTHREAD)
score = 0
reasons = []
hashes = []
# --- Contexte réseau ---
net_ctx = []
public_egress = False
public_listen = False
for inode in process_socket_inodes(pid):
info = sockets.get(inode)
if not info:
continue
net_ctx.append('%s %s %s -> %s' % (
info['proto'].upper(), info['state'], info['local'], info['remote']))
public_egress |= info['remote_public']
public_listen |= info['listening_public']
if is_kthread and net_ctx:
score += 60
reasons.append(('Thread noyau détenant un socket réseau (rootkit LKM ?)', 60))
elif is_kthread:
return None
# --- Binaire exécuté ---
exe_raw = readlink('%s/exe' % proc_dir)
exe = exe_raw or ''
exe_deleted = exe.endswith(' (deleted)')
exe_clean = exe[:-10] if exe_deleted else exe
if exe_deleted:
score += 65
reasons.append(('Binaire supprimé du disque mais toujours en exécution : %s'
% sanitize(exe_clean, 160), 65))
if exe_clean.startswith('/memfd:') or exe_clean.startswith('memfd:'):
score += 75
reasons.append(('Exécution depuis un fichier anonyme en mémoire (memfd) : %s'
% sanitize(exe_clean, 120), 75))
elif exe_clean:
in_red = any(exe_clean.startswith(z) for z in EXEC_RED_ZONES)
trusted = any(exe_clean.startswith(p) for p in EXEC_TRUSTED_PREFIX)
if in_red:
score += 55
reasons.append(('Exécution depuis une zone monde-inscriptible : %s'
% sanitize(exe_clean, 160), 55))
elif path_is_hidden(exe_clean) and not trusted:
score += 45
reasons.append(('Exécution depuis un répertoire caché : %s'
% sanitize(exe_clean, 160), 45))
# --- Usurpation d'identité de thread noyau ---
comm = sanitize(st['comm'], 64)
if exe_clean and not is_kthread and KTHREAD_LIKE.match(comm):
score += 60
reasons.append(('Nom de processus usurpant un thread noyau (%s) alors '
'qu\'un binaire est mappé : %s'
% (comm, sanitize(exe_clean, 120)), 60))
# --- Ligne de commande ---
cmdline_raw = read_bytes('%s/cmdline' % proc_dir, limit=16384)
cmdline = ''
if cmdline_raw:
cmdline = sanitize(cmdline_raw.decode('utf-8', 'replace').replace('\x00', ' '), 400)
probe = cmdline.replace('"', '').replace("'", '').replace('\\', '')
for pattern, label, weight in CMD_PATTERNS:
if pattern.search(probe):
score += weight
reasons.append(('%s : %s' % (label, cmdline[:180]), weight))
# --- Répertoire courant ---
cwd = readlink('%s/cwd' % proc_dir) or ''
if cwd.endswith(' (deleted)'):
score += 20
reasons.append(('Répertoire de travail supprimé : %s' % sanitize(cwd, 120), 20))
elif any(cwd.startswith(z) for z in ('/tmp/', '/dev/shm/', '/var/tmp/')) and net_ctx:
score += 20
reasons.append(('Processus réseau travaillant depuis %s' % sanitize(cwd, 120), 20))
# --- Statut : uid, capacités, ptrace ---
status = parse_proc_status(pid)
uid_field = status.get('Uid', '').split()
ruid = uid_field[0] if uid_field else '?'
euid = uid_field[1] if len(uid_field) > 1 else ruid
if ruid != '?' and euid != '?' and ruid != euid and euid == '0':
score += 35
reasons.append(('Élévation de privilèges effective (RUID=%s -> EUID=0)'
% ruid, 35))
if euid not in ('0', '?'):
dangerous = caps_to_names(status.get('CapEff', '0'))
if dangerous:
weight = 45 if any(c in ('CAP_SYS_MODULE', 'CAP_SYS_ADMIN',
'CAP_SYS_PTRACE', 'CAP_BPF') for c in dangerous) else 25
score += weight
reasons.append(('Capacités noyau anormales pour un non-root : %s'
% ', '.join(dangerous), weight))
tracer = status.get('TracerPid', '0')
if tracer not in ('0', ''):
score += 30
reasons.append(('Processus tracé par le PID %s (injection / debug actif)'
% tracer, 30))
# --- Namespace réseau (informatif : conteneurs légitimes très fréquents) ---
pid_netns = readlink('%s/ns/net' % proc_dir)
isolated = bool(init_netns and pid_netns and pid_netns != init_netns)
if isolated and net_ctx:
score += 10
reasons.append(('Namespace réseau isolé (conteneur) : %s' % pid_netns, 10))
# --- Environnement (LD_PRELOAD & co) ---
environ_raw = read_bytes('%s/environ' % proc_dir, limit=65536)
if environ_raw:
seen_env = set()
for var in environ_raw.decode('utf-8', 'replace').split('\x00'):
if '=' not in var:
continue
name, _, value = var.partition('=')
name = name.strip()
if name in seen_env:
continue
if name in ENV_CRITICAL and value.strip():
seen_env.add(name)
if any(sub in value for sub in ENV_ALLOW_SUBSTR):
continue
risky = any(value.startswith(z) or z in value for z in EXEC_RED_ZONES) \
or path_is_hidden(value) or '/home/' in value
weight = 70 if risky else 40
score += weight
reasons.append(('Injection de bibliothèque via %s=%s'
% (name, sanitize(value, 160)), weight))
for lib in re.split(r'[:\s]+', value):
if lib and os.path.isabs(lib):
digest, _magic = sha256_path(lib, args.max_file_size)
if digest:
hashes.append((digest, lib, 'bibliothèque préchargée'))
elif name in ENV_WATCH and value.strip():
probe = value.replace('"', '').replace("'", '')
for pattern, label, weight in CMD_PATTERNS:
if pattern.search(probe):
seen_env.add(name)
score += min(weight, 50)
reasons.append(('Contenu suspect dans %s : %s'
% (name, sanitize(value, 160)), min(weight, 50)))
break
# --- Pondération contextuelle réseau ---
if score > 0 and net_ctx:
if public_egress:
score += 20
reasons.append(('Communication sortante vers une IP publique '
'(canal C2 potentiel)', 20))
if public_listen:
score += 15
reasons.append(('Socket en écoute exposé hors loopback (backdoor ?)', 15))
if score < SEV_MEDIUM:
return None
# --- Empreinte du binaire pour pivot CTI ---
# /proc/<pid>/exe reste lisible même si le binaire a été supprimé : c'est
# souvent la seule copie récupérable de l'implant.
if exe_raw and not exe_clean.startswith(('/memfd:', 'memfd:')):
digest, magic = sha256_path('%s/exe' % proc_dir, args.max_file_size,
nofollow=False)
if digest:
hashes.append((digest, exe_clean or ('/proc/%s/exe' % pid),
'binaire du PID %s (%s)' % (pid, file_kind(magic))))
return {
'pid': pid,
'comm': comm,
'uid': ruid,
'ppid': st['ppid'],
'exe': sanitize(exe or 'introuvable', 200),
'cmdline': cmdline or '(vide)',
'net': net_ctx,
'score': score,
'reasons': reasons,
'hashes': hashes,
'netns': pid_netns,
}
def enumerate_pids():
pids = []
try:
with os.scandir('/proc') as entries:
for entry in entries:
if entry.name.isdigit():
pids.append(entry.name)
except OSError:
pass
return pids
def map_network_namespaces(pids):
"""{ns_id: pid_representatif} — nécessite root pour les autres utilisateurs."""
mapping = {}
for pid in pids:
ns = readlink('/proc/%s/ns/net' % pid)
if ns and ns not in mapping:
mapping[ns] = pid
return mapping
def module_processes(args, is_root):
out(C.cyan('[*] Étape 1/4 — Cartographie des namespaces et des sockets actifs'))
pids = enumerate_pids()
netns_map = map_network_namespaces(pids)
init_netns = readlink('/proc/1/ns/net')
sockets = collect_sockets(netns_map, is_root)
out(C.grey(' %d processus visibles, %d namespace(s) réseau, %d socket(s) pertinents'
% (len(pids), len(netns_map) or 1, len(sockets))))
out(C.cyan('[*] Étape 2/4 — Corrélation PID <-> socket et scoring comportemental'))
hits = []
for pid in pids:
try:
result = analyse_process(pid, sockets, init_netns, args, is_root)
except OSError:
continue # le processus a disparu pendant l'analyse
if result:
hits.append(result)
hits.sort(key=lambda h: -h['score'])
for hit in hits:
label, painter = severity_label(hit['score'])
title = ('[%s] PID %s (%s) — score %d'
% (label, hit['pid'], hit['comm'], hit['score']))
details = [
'PPID : %s UID : %s' % (hit['ppid'], hit['uid']),
'Binaire : %s' % hit['exe'],
'Cmdline : %s' % hit['cmdline'],
]
if hit['net']:
for conn in hit['net'][:8]:
details.append('Connexion : %s' % conn)
else:
details.append('Connexion : aucune socket active')
for reason, weight in hit['reasons']:
details.append('Motif (+%-3d): %s' % (weight, reason))
for digest, path, ctx in hit['hashes']:
details.append('SHA256 : %s (%s)' % (digest, ctx))
REPORT.add_ioc(digest, path, ctx)
REPORT.add(hit['score'], 'PROCESSUS', title, details)
out(C.grey(' %d processus retenus au-dessus du seuil de bruit' % len(hits)))
return pids, sockets
# ==========================================================================
# DÉTECTION DE ROOTKITS / DISSIMULATION
# ==========================================================================
def collect_all_tids(pids):
tids = set(pids)
for pid in pids:
try:
with os.scandir('/proc/%s/task' % pid) as entries:
for entry in entries:
if entry.name.isdigit():
tids.add(entry.name)
except OSError:
continue
return tids
def detect_hidden_pids(pids):
"""Un PID accessible par stat() mais absent du listing de /proc trahit un
rootkit qui filtre getdents(). Double passe pour éliminer les processus
créés pendant le scan (source majeure de faux positifs)."""
known = collect_all_tids(pids)
raw = read_text('/proc/sys/kernel/pid_max', limit=64)
try:
pid_max = int((raw or '32768').strip())
except ValueError:
pid_max = 32768
limit = min(pid_max, MAX_PID_BRUTEFORCE)
candidates = []
for pid in range(1, limit + 1):
spid = str(pid)
if spid in known:
continue
try:
os.stat('/proc/%s' % spid)
except OSError:
continue
candidates.append(spid)
if not candidates:
return [], limit
# Seconde passe : le processus est-il toujours invisible ET toujours vivant ?
known2 = collect_all_tids(enumerate_pids())
confirmed = []
for spid in candidates:
if spid in known2:
continue
try:
os.stat('/proc/%s' % spid)
except OSError:
continue
confirmed.append(spid)
return confirmed, limit
def detect_module_mismatch():
"""Compare /proc/modules et /sys/module : un LKM masquant son entrée dans
/proc/modules reste souvent visible dans sysfs."""
proc_mods = set()
content = read_text('/proc/modules', limit=1024 * 1024)
if content is None:
return None
for line in content.splitlines():
parts = line.split()
if parts:
proc_mods.add(parts[0])
sys_mods = set()
try:
with os.scandir('/sys/module') as entries:
for entry in entries:
if entry.is_dir(follow_symlinks=False):
# Un module chargé possède un répertoire 'initstate'.
if os.path.exists('/sys/module/%s/initstate' % entry.name):
sys_mods.add(entry.name)
except OSError:
return None
return proc_mods, sys_mods
def detect_partial_proc_view():
"""Un /proc partiel (conteneur, namespace PID tiers) produit des sockets
sans propriétaire apparent : il faut le savoir avant de crier au rootkit."""
hints = []
if os.path.exists('/.dockerenv'):
hints.append('/.dockerenv présent')
cgroup = read_text('/proc/1/cgroup', limit=65536) or ''
if re.search(r'docker|kubepods|containerd|lxc|libpod|garden', cgroup, re.I):
hints.append('cgroup de PID 1 de type conteneur')
init_pidns = readlink('/proc/1/ns/pid')
self_pidns = readlink('/proc/self/ns/pid')
if init_pidns and self_pidns and init_pidns != self_pidns:
hints.append('namespace PID distinct de celui de PID 1')
comm = read_text('/proc/1/comm', limit=256) or ''
if comm.strip() not in ('systemd', 'init', 'upstart', 'openrc-init', 'runit', ''):
hints.append('PID 1 atypique (%s)' % sanitize(comm, 32))
return hints
def module_rootkit(pids, sockets, is_root):
out(C.cyan('[*] Étape 3/4 — Recherche d\'indicateurs de dissimulation (rootkit)'))
# 1. Processus cachés
hidden, scanned = detect_hidden_pids(pids)
if hidden:
details = ['Plage inspectée : PID 1 à %d' % scanned]
for spid in hidden[:20]: