-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparanoya.py
executable file
·1946 lines (1719 loc) · 67.8 KB
/
paranoya.py
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 python
"""
paranoya
https://github.com/c0m4r/paranoya
paranoya: Simple IOC and YARA Scanner for Linux®
Copyright (c) 2015-2023 Florian Roth
Copyright (c) 2023-2024 c0m4r
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Linux® is the registered trademark of Linus Torvalds
in the U.S. and other countries.
"""
import argparse
import codecs
import datetime
import ipaddress
import os
import platform
import re
import socket
import stat
import sys
import threading
import traceback
from bisect import bisect_left
from collections import Counter
from multiprocessing import Process
from signal import signal, SIGPIPE, SIG_DFL, SIGTERM, SIGINT
from subprocess import Popen, PIPE, run
from types import FrameType
from typing import Optional
# paranoya modules
from lib.paranoya_args import parser
from lib.paranoya_logger import ParanoyaLogger, get_syslog_timestamp
from lib.paranoya_helpers import (
paranoya_generate_hashes,
paranoya_get_excluded_mountpoints,
paranoya_print_progress,
paranoya_transform_os,
paranoya_replace_env_vars,
paranoya_get_file_type,
paranoya_remove_non_ascii_drop,
paranoya_get_age_string,
)
from lib.paranoya_constants import (
EVIL_EXTENSIONS,
SCRIPT_EXTENSIONS,
SCRIPT_TYPES,
HASH_WHITELIST,
)
from lib.paranoya_venv import venv_check
# venv before loading custom modules
venv_check(__file__)
# Custom modules
try:
import psutil
import yara
import progressbar
except Exception as e:
print(e)
sys.exit(0)
signal(SIGPIPE, SIG_DFL)
def ioc_contains(sorted_list, value):
"""
returns true if sorted_list contains value
"""
index = bisect_left(sorted_list, value)
return index != len(sorted_list) and sorted_list[index] == value
class Paranoya:
"""
paranoya
"""
# Signatures
yara_rules: list[yara.Rules] = []
filename_iocs: list[dict] = []
hashes_md5: dict = {}
hashes_sha1: dict = {}
hashes_sha256: dict = {}
hashes_scores: dict = {}
false_hashes: dict = {}
c2_server: dict = {}
# Yara rule directories
yara_rule_directories: list = []
# Excludes (list of regex that match within the whole path) (user-defined via excludes.cfg)
full_excludes: list = []
# Platform specific excludes (match the beginning of the full path) (not user-defined)
start_excludes: set = set()
# Excludes hash (md5, sha1 and sha256)
excludes_hash: list = []
# File type magics
filetype_magics: dict = {}
max_filetype_magics = 0
bar_iter = 0
bar_iter_max = 10000
def __init__(self, intense_mode: bool) -> None:
"""
init
"""
# Scan Mode
self.intense_mode = intense_mode
# Get application path
self.app_path = get_application_path()
# Check if signature database is present
sig_dir = os.path.join(self.app_path, "signature-base")
if not os.path.exists(sig_dir) or os.listdir(sig_dir) == []:
logger.log(
"NOTICE",
"Init",
"The 'signature-base' subdirectory doesn't exist or is empty. "
"Trying to retrieve the signature database automatically.",
)
update_paranoya(sigs_only=True)
# Excludes
self.initialize_excludes(
os.path.join(self.app_path, "config/excludes.cfg".replace("/", os.sep))
)
# Static excludes
if not args.force:
linux_path_skips_start = set(
[
"/proc",
"/dev",
"/sys/kernel/debug",
"/sys/kernel/slab",
"/sys/devices",
"/usr/src/linux",
]
)
if args.alldrives:
self.start_excludes = linux_path_skips_start
else:
self.start_excludes = (
linux_path_skips_start
| set(["/media", "/volumes"])
| set(paranoya_get_excluded_mountpoints())
)
# Set IOC path
self.ioc_path = os.path.join(
self.app_path, "signature-base/iocs/".replace("/", os.sep)
)
# Yara rule directories
self.yara_rule_directories.append(
os.path.join(self.app_path, args.custom.replace("/", os.sep))
)
self.yara_rule_directories.append(
os.path.join(self.app_path, "signature-base/iocs/yara".replace("/", os.sep))
)
self.yara_rule_directories.append(
os.path.join(self.app_path, "signature-base/3rdparty".replace("/", os.sep))
)
# Read IOCs -------------------------------------------------------
# File Name IOCs (all files in iocs that contain 'filename')
self.initialize_filename_iocs(self.ioc_path)
logger.log(
"INFO",
"Init",
f"File Name Characteristics initialized with {len(self.filename_iocs)} regex patterns",
)
# C2 based IOCs (all files in iocs that contain 'c2')
self.initialize_c2_iocs(self.ioc_path)
logger.log(
"INFO",
"Init",
f"C2 server indicators initialized with {len(self.c2_server.keys())} elements",
)
# Hash based IOCs (all files in iocs that contain 'hash')
self.initialize_hash_iocs(self.ioc_path)
logger.log(
"INFO",
"Init",
f"Malicious MD5 Hashes initialized with {len(self.hashes_md5.keys())} hashes",
)
logger.log(
"INFO",
"Init",
f"Malicious SHA1 Hashes initialized with {len(self.hashes_sha1.keys())} hashes",
)
logger.log(
"INFO",
"Init",
f"Malicious SHA256 Hashes initialized with {len(self.hashes_sha256.keys())} hashes",
)
# Hash based False Positives (all files in iocs that contain 'hash' and 'falsepositive')
self.initialize_hash_iocs(self.ioc_path, false_positive=True)
logger.log(
"INFO",
"Init",
f"False Positive Hashes initialized with {len(self.false_hashes.keys())} hashes",
)
# Compile Yara Rules
self.initialize_yara_rules()
# Initialize File Type Magic signatures
self.initialize_filetype_magics(
os.path.join(
self.app_path,
"signature-base/misc/file-type-signatures.txt".replace("/", os.sep),
)
)
def file_list_gen(self, path):
"""
file list gen
"""
matches = []
flg_iter = 0
logger.log("INFO", "Init", "Processing files to scan, this might take a while.")
for root, _, filenames in os.walk(path, followlinks=args.followlinks):
for filename in filenames:
matches.append(os.path.join(root, filename))
flg_iter += 1
if flg_iter > self.bar_iter_max:
logger.log(
"INFO",
"Init",
"File list too large, progress will be unavailable",
)
return matches
logger.log("INFO", "Init", "Processing done")
return matches
def scan_path(self, path):
"""
scan path
"""
if os.path.isfile(path):
root = ""
directories = ""
files = [path]
# Disable progress bar for single file scan
args.progress = False
paranoya.scan_path_files(root, directories, files)
return
if args.progress and not args.silent and not args.noindicator:
files_all = self.file_list_gen(path)
files_all_len = len(files_all)
# Check if path exists
if not os.path.exists(path):
logger.log("ERROR", "FileScan", f"None Existing Scanning Path {path} ... ")
return
# Startup
logger.log("INFO", "FileScan", f"Scanning Path {path} ... ")
# Platform specific excludes
for skip in self.start_excludes:
if path.startswith(skip):
logger.log(
"INFO",
"FileScan",
f"Skipping {skip} directory [fixed excludes]"
" (try using --force or --alldrives)",
)
return
if args.progress and not args.silent and not args.noindicator:
if files_all_len <= self.bar_iter_max:
progress_bar = progressbar.ProgressBar(
max_value=files_all_len, redirect_stdout=True
)
else:
progress_bar = progressbar.ProgressBar(
max_value=progressbar.UnknownLength, redirect_stdout=True
)
else:
progress_bar = None
for root, directories, files in os.walk(
path, onerror=walk_error, followlinks=args.followlinks
):
# Skip paths that start with ..
new_directories = []
for dirname in directories:
skip_it = False
# Generate a complete path for comparisons
complete_path = os.path.join(root, dirname).lower() + os.sep
# Platform specific excludes
for skip in self.start_excludes:
if complete_path.startswith(skip):
logger.log(
"INFO",
"FileScan",
f"Skipping {skip} directory [fixed excludes] "
"(try using --force or --alldrives)",
)
skip_it = True
if not skip_it:
new_directories.append(dirname)
directories[:] = new_directories
if args.multicore:
proc = Process(
target=paranoya.scan_path_files,
args=(
root,
directories,
files,
progress_bar,
),
)
proc.start()
else:
paranoya.scan_path_files(root, directories, files, progress_bar)
def perform_intense_check(
self,
file_path,
file_type,
file_name_cleaned,
file_path_cleaned,
extension,
reasons,
total_score,
):
"""
Perform intense check
"""
# Hash Check -------------------------------------------------------
# Do the check
file_data = self.get_file_data(file_path)
# First bytes
first_bytes_string = "%s / %s" % (
file_data[:20].hex(),
paranoya_remove_non_ascii_drop(file_data[:20]),
)
# Hash Eval
match_type = None
match_desc = None
match_hash = None
md5 = 0
sha1 = 0
sha256 = 0
md5, sha1, sha256 = paranoya_generate_hashes(file_data)
md5_num = int(md5, 16)
sha1_num = int(sha1, 16)
sha256_num = int(sha256, 16)
# False Positive Hash
if (
md5_num in self.false_hashes.keys()
or sha1_num in self.false_hashes.keys()
or sha256_num in self.false_hashes.keys()
):
return False, None, None, None, None, None
# Skip exclude hash
if (
md5 in self.excludes_hash
or sha1 in self.excludes_hash
or sha256 in self.excludes_hash
):
logger.log(
"DEBUG",
"FileScan",
f"Skipping element {file_path} excluded by hash",
)
return False, None, None, None, None, None
# Malware Hash
match_score = 100
match_level = "Malware"
if ioc_contains(self.hashes_md5_list, md5_num):
match_type = "MD5"
match_desc = self.hashes_md5[md5_num]
match_hash = md5
match_score = self.hashes_scores[md5_num]
if ioc_contains(self.hashes_sha1_list, sha1_num):
match_type = "SHA1"
match_desc = self.hashes_sha1[sha1_num]
match_hash = sha1
match_score = self.hashes_scores[sha1_num]
if ioc_contains(self.hashes_sha256_list, sha256_num):
match_type = "SHA256"
match_desc = self.hashes_sha256[sha256_num]
match_hash = sha256
match_score = self.hashes_scores[sha256_num]
# If score is low change the description
if match_score < 80:
match_level = "Suspicious"
# Hash string
hash_string = f"MD5: {md5} SHA1: {sha1} SHA256: {sha256}"
if match_type:
reasons.append(
f"{match_level} Hash TYPE: {match_type} HASH: {match_hash}"
f" SUBSCORE: {match_score} DESC: {match_desc}"
)
total_score += match_score
# Script Anomalies Check
if args.scriptanalysis:
if extension in SCRIPT_EXTENSIONS or type in SCRIPT_TYPES:
logger.log(
"DEBUG",
"FileScan",
f"Performing character analysis on file {file_path} ... ",
)
message, score = self.script_stats_analysis(file_data)
if message:
reasons.append("%s SCORE: %s" % (message, score))
total_score += score
# Yara Check -------------------------------------------------------
# Memory Dump Scan
if file_type == "MDMP":
logger.log(
"INFO",
"FileScan",
"Scanning memory dump file %s" % file_name_cleaned.decode("utf-8"),
)
# Scan the read data
try:
for (
score,
rule,
description,
reference,
matched_strings,
author,
) in self.scan_data(
file_data=file_data,
file_type=file_type,
file_name=file_name_cleaned,
file_path=file_path_cleaned,
extension=extension,
md5=md5, # legacy rule support
):
# Message
message = (
f"Yara Rule MATCH: {rule} SUBSCORE: {score} "
f"DESCRIPTION: {description} REF: {reference} AUTHOR: {author}"
)
# Matches
if len(matched_strings) > 0:
message += " MATCHES: %s" % ", ".join(matched_strings)
total_score += score
reasons.append(message)
return (
True,
file_data,
total_score,
first_bytes_string,
hash_string,
reasons,
)
except Exception:
if logger.debug:
traceback.print_exc()
logger.log(
"ERROR",
"FileScan",
f"Cannot YARA scan file: {file_path_cleaned}",
)
def scan_path_files(self, root, directories, files, progress_bar=None):
"""
scan path files
"""
# Counter
c = 0
# Loop through files
for filename in files:
try:
if args.progress and not args.silent and not args.noindicator:
self.bar_iter += 1
progress_bar.update(self.bar_iter)
# Findings
reasons = []
# Total Score
total_score = 0
# Get the file and path
file_path = os.path.join(root, filename)
fpath = os.path.split(file_path)[0]
# Clean the values for YARA matching
# > due to errors when Unicode characters are passed to the match function as
# external variables
file_path_cleaned = fpath.encode("ascii", errors="replace")
file_name_cleaned = filename.encode("ascii", errors="replace")
# Get Extension
extension = os.path.splitext(file_path)[1].lower()
# Skip marker
skip_it = False
# User defined excludes
for skip in self.full_excludes:
if skip.search(file_path):
logger.log("DEBUG", "FileScan", f"Skipping element {file_path}")
skip_it = True
# File mode
try:
mode = os.stat(file_path).st_mode
if (
stat.S_ISCHR(mode)
or stat.S_ISBLK(mode)
or stat.S_ISFIFO(mode)
or stat.S_ISLNK(mode)
or stat.S_ISSOCK(mode)
):
continue
except Exception:
logger.log(
"DEBUG",
"FileScan",
f"Skipping element {file_path} does not exist or is a broken symlink",
)
continue
# Skip
if skip_it:
continue
# Counter
c += 1
if not args.noindicator:
paranoya_print_progress(c)
# Skip program directory
if self.app_path.lower() in file_path.lower() and not args.force:
logger.log(
"NOTICE",
"FileScan",
f"Skipping file in program directory: {file_path_cleaned}",
)
continue
file_size = os.stat(file_path).st_size
# print file_size
# File Name Checks -------------------------------------------------
for fioc in self.filename_iocs:
match = fioc["regex"].search(file_path)
if match:
# Check for False Positive
if fioc["regex_fp"]:
match_fp = fioc["regex_fp"].search(file_path)
if match_fp:
continue
# Create Reason
reasons.append(
"File Name IOC matched PATTERN: %s SUBSCORE: %s DESC: %s"
% (
fioc["regex"].pattern,
fioc["score"],
fioc["description"],
)
)
total_score += int(fioc["score"])
# Access check (also used for magic header detection)
first_bytes_string = b"-"
hash_string = ""
# Evaluate Type
file_type = paranoya_get_file_type(
file_path, self.filetype_magics, self.max_filetype_magics, logger
)
# Fast Scan Mode - non intense
do_intense_check = True
if (
not self.intense_mode
and file_type == "UNKNOWN"
and extension not in EVIL_EXTENSIONS
):
if args.printall:
logger.log(
"INFO",
"FileScan",
f"Skipping file due to fast scan mode: {file_name_cleaned}",
)
do_intense_check = False
# Set file_data to an empty value
file_data = ""
print_filesize_info = False
# Evaluations -------------------------------------------------------
# Evaluate size
file_size_limit = int(args.s) * 1024
if file_size > file_size_limit:
# Print files
do_intense_check = False
print_filesize_info = True
# Some file types will force intense check
if file_type == "MDMP":
do_intense_check = True
print_filesize_info = False
# Intense Check switch
if do_intense_check and args.printall:
logger.log(
"INFO",
"FileScan",
f"Scanning {file_name_cleaned} TYPE: {file_type} SIZE: {file_size}",
)
elif args.printall:
logger.log(
"INFO",
"FileScan",
f"Checking {file_name_cleaned} TYPE: {file_type} SIZE: {file_size}",
)
if print_filesize_info and args.printall:
logger.log(
"INFO",
"FileScan",
f"Skipping file due to file size: {file_name_cleaned}"
f" TYPE: {file_type} SIZE: {file_size}"
f" CURRENT SIZE LIMIT(kilobytes): {file_size_limit}",
)
if do_intense_check:
(
proceed,
file_data,
total_score,
first_bytes_string,
hash_string,
reasons,
) = self.perform_intense_check(
file_path,
file_type,
file_name_cleaned,
file_path_cleaned,
extension,
reasons,
total_score,
)
if not proceed:
continue
# Info Line -----------------------------------------------------------------------
file_info = (
f"FILE: {file_path} SCORE: {total_score}"
f" TYPE: {file_type} SIZE: {file_size}"
f" FIRST_BYTES: {first_bytes_string} {hash_string}"
f" {paranoya_get_age_string(file_path)} "
)
# Now print the total result
if total_score >= args.a:
message_type = "ALERT"
threading.current_thread().message = "ALERT"
elif total_score >= args.w:
message_type = "WARNING"
threading.current_thread().message = "WARNING"
elif total_score >= args.n:
message_type = "NOTICE"
threading.current_thread().message = "NOTICE"
if total_score < args.n:
continue
# Reasons to message body
message_body = file_info
for i, r in enumerate(reasons):
if i < 2 or args.allreasons:
message_body += f"REASON_{i + 1}: {r}"
logger.log(message_type, "FileScan", message_body)
except Exception:
if logger.debug:
traceback.print_exc()
sys.exit(1)
def yara_externals(
self,
dummy,
file_name=b"-",
file_path=b"-",
extension=b"-",
file_type="-",
md5="-",
):
"""
yara externals
"""
if dummy is True:
return {
"filename": "dummy",
"filepath": "dummy",
"extension": "dummy",
"filetype": "dummy",
"md5": "dummy",
"owner": "dummy",
}
else:
return {
"filename": file_name,
"filepath": file_path,
"extension": extension,
"filetype": file_type,
"md5": md5,
"owner": "dummy",
}
def scan_data(
self,
file_data,
file_type="-",
file_name=b"-",
file_path=b"-",
extension=b"-",
md5="-",
):
"""
scan data
"""
# Scan with yara
try:
for rules in self.yara_rules:
# Yara Rule Match
externals = self.yara_externals(
False,
file_name.decode("utf-8"),
file_path.decode("utf-8"),
extension,
file_type,
md5,
)
matches = rules.match(
data=file_data,
externals=externals,
)
# If matched
if matches:
for match in matches:
score = 70
description = "not set"
reference = "-"
author = "-"
# Built-in rules have meta fields (cannot be expected from custom rules)
if hasattr(match, "meta"):
if "description" in match.meta:
description = match.meta["description"]
if "cluster" in match.meta:
description = "IceWater Cluster {0}".format(
match.meta["cluster"]
)
if "reference" in match.meta:
reference = match.meta["reference"]
if "viz_url" in match.meta:
reference = match.meta["viz_url"]
if "author" in match.meta:
author = match.meta["author"]
# If a score is given
if "score" in match.meta:
score = int(match.meta["score"])
# Matching strings
matched_strings = []
if hasattr(match, "strings"):
# Get matching strings
matched_strings = self.get_string_matches(match.strings)
yield score, match.rule, description, reference, matched_strings, author
except Exception:
if logger.debug:
traceback.print_exc()
def get_string_matches(self, strings):
"""
get string matches
"""
try:
matching_strings = []
for string in strings:
# Limit string
string_value = str(string.instances[0]).replace("'", "\\")
if len(string_value) > 140:
string_value = string_value[:140] + " ... (truncated)"
matching_strings.append(f"{string.identifier}: '{string_value}'")
return matching_strings
except Exception:
traceback.print_exc()
def scan_processes_linux(self) -> None:
"""
scan processes linux
"""
processes = psutil.pids()
for process in processes:
# Gather Process Information -------------------------------------
pid = process
try:
name = psutil.Process(process).name()
except psutil.NoSuchProcess:
logger.log(
"DEBUG",
"ProcessScan",
f"Skipping Process PID: {str(pid)} as it just exited and no longer exists",
)
continue
owner = psutil.Process(process).username()
status = psutil.Process(process).status()
try:
cmd = " ".join(psutil.Process(process).cmdline())
except (psutil.NoSuchProcess, psutil.ZombieProcess):
logger.log(
"WARNING",
"ProcessScan",
f"Process PID: {str(pid)} NAME: {name} STATUS: {status}",
)
continue
path = psutil.Process(process).cwd()
bin = psutil.Process(process).exe()
tty = psutil.Process(process).terminal()
process_info = (
f"PID: {str(pid)} NAME: {name} OWNER: {owner} STATUS: {status}"
f" BIN: {bin} CMD: {cmd.strip()} PATH: {path} TTY: {tty}"
)
# Print info -------------------------------------------------------
logger.log("INFO", "ProcessScan", f"Process {process_info}")
# Process Masquerading Detection -----------------------------------
if re.search(r"\[", cmd):
maps = f"/proc/{str(pid)}/maps"
maps = run(["/bin/cat", maps], encoding="utf-8", stdout=PIPE)
if maps.stdout.strip():
logger.log(
"WARNING",
"ProcessScan",
f"Potential Process Masquerading PID: {str(pid)}"
f" CMD: {cmd} Check /proc/{str(pid)}/maps",
)
# File Name Checks -------------------------------------------------
for fioc in self.filename_iocs:
match = fioc["regex"].search(cmd)
if match:
if int(fioc["score"]) > 70:
logger.log(
"ALERT",
"ProcessScan",
"File Name IOC matched PATTERN: %s DESC: %s MATCH: %s"
% (fioc["regex"].pattern, fioc["description"], cmd),
)
elif int(fioc["score"]) > 40:
logger.log(
"WARNING",
"ProcessScan",
"File Name Suspicious IOC matched PATTERN: %s DESC: %s MATCH: %s"
% (fioc["regex"].pattern, fioc["description"], cmd),
)
# Process connections ----------------------------------------------
if not args.nolisten:
connections = psutil.Process(pid).net_connections()
conn_count = 0
conn_limit = 20
for pconn in connections:
conn_count += 1
if conn_count > conn_limit:
logger.log(
"NOTICE",
"ProcessScan",
f"Process PID: {str(pid)} NAME: {name} More connections detected."
f" Showing only {conn_limit}",
)
break
ip = pconn.laddr.ip
status = pconn.status
ext = pconn.raddr
if ext:
ext_ip = pconn.raddr.ip
ext_port = pconn.raddr.port
logger.log(
"NOTICE",
"ProcessScan",
f"Process PID: {str(pid)} NAME: {name}"
f" CONNECTION: {ip} <=> {ext_ip} {ext_port} ({status})",
)
else:
logger.log(
"NOTICE",
"ProcessScan",
f"Process PID: {str(pid)} NAME: {name} CONNECTION: {ip} ({status})",
)
def check_process_connections(self, process):
"""
check process connections
"""
try:
# Limits
max_connections = 20
# Counter
connection_count = 0
# Pid from process
pid = process.ProcessId
name = process.Name
# Get psutil info about the process
try:
p = psutil.Process(pid)
except Exception:
if logger.debug:
traceback.print_exc()
return
# print "Checking connections of %s" % process.Name
for x in p.connections():
# Evaluate a usable command line to check
try:
command = process.CommandLine
except Exception:
command = p.cmdline()
if x.status == "LISTEN":
connection_count += 1
logger.log(
"NOTICE",
"ProcessScan",
"Listening process PID: %s NAME: %s COMMAND: %s IP: %s PORT: %s"
% (str(pid), name, command, str(x.laddr[0]), str(x.laddr[1])),
)
if str(x.laddr[1]) == "0":
logger.log(
"WARNING",
"ProcessScan",
"Listening on Port 0 PID: %s NAME: %s COMMAND: %s IP: %s PORT: %s"
% (
str(pid),
name,