forked from Neo23x0/Loki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loki.py
1521 lines (1254 loc) · 69 KB
/
loki.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
# -*- coding: utf-8 -*-
"""
Loki
Simple IOC Scanner
Detection is based on three detection methods:
1. File Name IOC
Applied to file names
2. Yara Check
Applied to files and processes
3. Hash Check
Compares known malicious hashes with th ones of the scanned files
Loki combines all IOCs from ReginScanner and SkeletonKeyScanner and is the
little brother of THOR our full-featured corporate APT Scanner
Florian Roth
BSK Consulting GmbH
DISCLAIMER - USE AT YOUR OWN RISK.
"""
import sys
import os
import argparse
import traceback
import yara # install 'yara-python' module not the outdated 'yara' module
import re
import stat
import psutil
import platform
import signal as signal_module
from sys import platform as _platform
from subprocess import Popen, PIPE
from collections import Counter
# LOKI Modules
from lib.lokilogger import *
# Private Rules Support
from lib.privrules import *
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
from lib.helpers import *
from lib.pesieve import PESieve
from lib.doublepulsar import DoublePulsar
# Platform
os_platform = ""
if _platform == "linux" or _platform == "linux2":
os_platform = "linux"
elif _platform == "darwin":
os_platform = "osx"
elif _platform == "win32":
os_platform = "windows"
# Win32 Imports
if os_platform == "windows":
try:
import wmi
import win32api
from win32com.shell import shell
except Exception, e:
print "Linux System - deactivating process memory check ..."
os_platform = "linux" # crazy guess
if os_platform == "":
print "Unable to determine platform - LOKI is lost."
sys.exit(1)
# Predefined Evil Extensions
EVIL_EXTENSIONS = [".vbs", ".ps", ".ps1", ".rar", ".tmp", ".bas", ".bat", ".chm", ".cmd", ".com", ".cpl",
".crt", ".dll", ".exe", ".hta", ".js", ".lnk", ".msc", ".ocx", ".pcd", ".pif", ".pot", ".pdf",
".reg", ".scr", ".sct", ".sys", ".url", ".vb", ".vbe", ".wsc", ".wsf", ".wsh", ".ct", ".t",
".input", ".war", ".jsp", ".php", ".asp", ".aspx", ".doc", ".docx", ".pdf", ".xls", ".xlsx", ".ppt",
".pptx", ".tmp", ".log", ".dump", ".pwd", ".w", ".txt", ".conf", ".cfg", ".conf", ".config", ".psd1",
".psm1", ".ps1xml", ".clixml", ".psc1", ".pssc", ".pl", ".www", ".rdp", ".jar", ".docm"]
SCRIPT_EXTENSIONS = [".asp", ".vbs", ".ps1", ".bas", ".bat", ".js", ".vb", ".vbe", ".vbs", ".wsc", ".wsf",
".wsh", ".jsp", ".php", ".asp", ".aspx", ".psd1", ".psm1", ".ps1xml", ".clixml", ".psc1",
".pssc"]
SCRIPT_TYPES = ["VBS", "PHP", "JSP", "ASP", "BATCH"]
class Loki(object):
# Signatures
yara_rules = []
filename_iocs = []
hashes_md5 = {}
hashes_sha1 = {}
hashes_sha256 = {}
false_hashes = {}
c2_server = {}
# Yara rule directories
yara_rule_directories = []
# Excludes (list of regex that match within the whole path) (user-defined via excluces.cfg)
fullExcludes = []
# Platform specific excludes (match the beginning of the full path) (not user-defined)
startExcludes = []
# File type magics
filetype_magics = {}
max_filetype_magics = 0
# Predefined paths to skip (Linux platform)
LINUX_PATH_SKIPS_START = set(["/proc", "/dev", "/media", "/sys/kernel/debug", "/sys/kernel/slab", "/sys/devices", "/usr/src/linux" ])
LINUX_PATH_SKIPS_END = set(["/initctl"])
def __init__(self, intense_mode):
# Scan Mode
self.intense_mode = intense_mode
# Get application path
self.app_path = get_application_path()
# PESieve
self.peSieve = PESieve(self.app_path, is64bit(), logger)
# 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.")
updateLoki(sigsOnly=True)
# Excludes
self.initialize_excludes(os.path.join(self.app_path, "./config/excludes.cfg"))
# Linux excludes from mtab
if os_platform == "linux":
self.startExcludes = self.LINUX_PATH_SKIPS_START | set(getExcludedMountpoints())
# OSX excludes like Linux until we get some field data
if os_platform == "osx":
self.startExcludes = self.LINUX_PATH_SKIPS_START
# Set IOC path
self.ioc_path = os.path.join(self.app_path, "./signature-base/iocs/")
# Yara rule directories
self.yara_rule_directories.append(os.path.join(self.app_path, "./signature-base/yara"))
self.yara_rule_directories.append(os.path.join(self.app_path, "./signature-base/iocs/yara"))
# Read IOCs -------------------------------------------------------
# File Name IOCs (all files in iocs that contain 'filename')
self.initialize_filename_iocs(self.ioc_path)
logger.log("INFO", "Init", "File Name Characteristics initialized with %s regex patterns" % len(self.filename_iocs))
# C2 based IOCs (all files in iocs that contain 'c2')
self.initialize_c2_iocs(self.ioc_path)
logger.log("INFO", "Init", "C2 server indicators initialized with %s elements" % len(self.c2_server.keys()))
# Hash based IOCs (all files in iocs that contain 'hash')
self.initialize_hash_iocs(self.ioc_path)
logger.log("INFO", "Init", "Malicious MD5 Hashes initialized with %s hashes" % len(self.hashes_md5.keys()))
logger.log("INFO", "Init", "Malicious SHA1 Hashes initialized with %s hashes" % len(self.hashes_sha1.keys()))
logger.log("INFO", "Init", "Malicious SHA256 Hashes initialized with %s hashes" % len(self.hashes_sha256.keys()))
# 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", "False Positive Hashes initialized with %s hashes" % len(self.false_hashes.keys()))
# 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'))
def scan_path(self, path):
# Startup
logger.log("INFO", "FileScan", "Scanning %s ... " % path)
# Counter
c = 0
for root, directories, files in os.walk(unicode(path), onerror=walk_error, followlinks=False):
# Skip paths that start with ..
newDirectories = []
for dir in directories:
skipIt = False
# Generate a complete path for comparisons
completePath = os.path.join(root, dir).lower() + os.sep
# Platform specific excludes
for skip in self.startExcludes:
if completePath.startswith(skip):
logger.log("INFO", "FileScan", "Skipping %s directory" % skip)
skipIt = True
if not skipIt:
newDirectories.append(dir)
directories[:] = newDirectories
# Loop through files
for filename in files:
try:
# Findings
reasons = []
# Total Score
total_score = 0
# Get the file and path
filePath = os.path.join(root,filename)
# Clean the values for YARA matching
# > due to errors when Unicode characters are passed to the match function as
# external variables
filePathCleaned = filePath.encode('ascii', errors='replace')
fileNameCleaned = filename.encode('ascii', errors='replace')
# Get Extension
extension = os.path.splitext(filePath)[1].lower()
# Skip marker
skipIt = False
# Unicode error test
#if 1 > 0:
# walk_error(OSError("[Error 3] No such file or directory"))
# User defined excludes
for skip in self.fullExcludes:
if skip.search(filePath):
logger.log("DEBUG", "FileScan", "Skipping element %s" % filePath)
skipIt = True
# Linux directory skip
if os_platform == "linux" or os_platform == "osx":
# Skip paths that end with ..
for skip in self.LINUX_PATH_SKIPS_END:
if filePath.endswith(skip):
if self.LINUX_PATH_SKIPS_END[skip] == 0:
logger.log("INFO", "FileScan", "Skipping %s element" % skip)
self.LINUX_PATH_SKIPS_END[skip] = 1
skipIt = True
# File mode
mode = os.stat(filePath).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
# Skip
if skipIt:
continue
# Counter
c += 1
if not args.noindicator:
printProgress(c)
# Skip program directory
# print appPath.lower() +" - "+ filePath.lower()
if self.app_path.lower() in filePath.lower():
logger.log("DEBUG", "FileScan", "Skipping file in program directory FILE: %s" % filePathCleaned)
continue
fileSize = os.stat(filePath).st_size
# print file_size
# File Name Checks -------------------------------------------------
for fioc in self.filename_iocs:
match = fioc['regex'].search(filePath)
if match:
# Check for False Positive
if fioc['regex_fp']:
match_fp = fioc['regex_fp'].search(filePath)
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)
firstBytes = ""
firstBytesString = "-"
hashString = ""
try:
with open(filePath, 'rb') as f:
firstBytes = f.read(4)
except Exception, e:
logger.log("DEBUG", "FileScan", "Cannot open file %s (access denied)" % filePathCleaned)
# Evaluate Type
fileType = get_file_type(filePath, self.filetype_magics, self.max_filetype_magics, logger)
# Fast Scan Mode - non intense
do_intense_check = True
if not self.intense_mode and fileType == "UNKNOWN" and extension not in EVIL_EXTENSIONS:
if args.printAll:
logger.log("INFO", "FileScan", "Skipping file due to fast scan mode: %s" % filePathCleaned)
do_intense_check = False
# Set fileData to an empty value
fileData = ""
# Evaluations -------------------------------------------------------
# Evaluate size
if fileSize > (args.s * 1024):
# Print files
do_intense_check = False
# Some file types will force intense check
if fileType == "MDMP":
do_intense_check = True
# Intense Check switch
if do_intense_check:
if args.printAll:
logger.log("INFO", "FileScan", "Scanning %s TYPE: %s SIZE: %s" % (filePathCleaned, fileType, fileSize))
else:
if args.printAll:
logger.log("INFO", "FileScan", "Checking %s TYPE: %s SIZE: %s" % (filePathCleaned, fileType, fileSize))
# Hash Check -------------------------------------------------------
# Do the check
if do_intense_check:
fileData = self.get_file_data(filePath)
# First bytes
firstBytesString = "%s / %s" % (fileData[:20].encode('hex'), removeNonAsciiDrop(fileData[:20]) )
# Hash Eval
matchType = None
matchDesc = None
matchHash = None
md5 = "-"
sha1 = "-"
sha256 = "-"
md5, sha1, sha256 = generateHashes(fileData)
# False Positive Hash
if md5 in self.false_hashes.keys() or sha1 in self.false_hashes.keys() or sha256 in self.false_hashes.keys():
continue
# Malware Hash
if md5 in self.hashes_md5.keys():
matchType = "MD5"
matchDesc = self.hashes_md5[md5]
matchHash = md5
elif sha1 in self.hashes_sha1.keys():
matchType = "SHA1"
matchDesc = self.hashes_sha1[sha1]
matchHash = sha1
elif sha256 in self.hashes_sha256.keys():
matchType = "SHA256"
matchDesc = self.hashes_sha256[sha256]
matchHash = sha256
# Hash string
hashString = "MD5: %s SHA1: %s SHA256: %s" % ( md5, sha1, sha256 )
if matchType:
reasons.append("Malware Hash TYPE: %s HASH: %s SUBSCORE: 100 DESC: %s" % (
matchType, matchHash, matchDesc))
total_score += 100
# Regin .EVT FS Check
if len(fileData) > 11 and args.reginfs:
# Check if file is Regin virtual .evt file system
self.scan_regin_fs(fileData, filePath)
# Script Anomalies Check
if args.scriptanalysis:
if extension in SCRIPT_EXTENSIONS or type in SCRIPT_TYPES:
logger.log("DEBUG", "FileScan", "Performing character analysis on file %s ... " % filePath)
message, score = self.script_stats_analysis(fileData)
if message:
reasons.append("%s SCORE: %s" % (message, score))
total_score += score
# Yara Check -------------------------------------------------------
# Memory Dump Scan
if fileType == "MDMP":
logger.log("INFO", "FileScan", "Scanning memory dump file %s" % filePathCleaned)
# Umcompressed SWF scan
if fileType == "ZWS" or fileType == "CWS":
logger.log("INFO", "FileScan", "Scanning decompressed SWF file %s" % filePathCleaned)
success, decompressedData = decompressSWFData(fileData)
if success:
fileData = decompressedData
# Scan the read data
try:
for (score, rule, description, reference, matched_strings) in \
self.scan_data(fileData=fileData,
fileType=fileType,
fileName=fileNameCleaned,
filePath=filePathCleaned,
extension=extension,
md5=md5 # legacy rule support
):
# Message
message = "Yara Rule MATCH: %s SUBSCORE: %s DESCRIPTION: %s REF: %s" % \
(rule, score, description, reference)
# Matches
if matched_strings:
message += " MATCHES: %s" % matched_strings
total_score += score
reasons.append(message)
except Exception, e:
logger.log("ERROR", "FileScan", "Cannot YARA scan file: %s" % filePathCleaned)
# Info Line -----------------------------------------------------------------------
fileInfo = "FILE: %s SCORE: %s TYPE: %s SIZE: %s FIRST_BYTES: %s %s %s " % (
filePath, total_score, fileType, fileSize, firstBytesString, hashString, getAgeString(filePath))
# Now print the total result
if total_score >= args.a:
message_type = "ALERT"
elif total_score >= args.w:
message_type = "WARNING"
elif total_score >= args.n:
message_type = "NOTICE"
if total_score < args.n:
continue
# Reasons to message body
message_body = fileInfo
for i, r in enumerate(reasons):
if i < 2 or args.allreasons:
message_body += "REASON_{0}: {1}".format(i+1, r.encode('ascii', errors='replace'))
logger.log(message_type, "FileScan", message_body)
except Exception, e:
if logger.debug:
traceback.print_exc()
sys.exit(1)
def scan_data(self, fileData, fileType="-", fileName="-", filePath="-", extension="-", md5="-"):
# Scan parameters
#print fileType, fileName, filePath, extension, md5
# Scan with yara
try:
for rules in self.yara_rules:
# Yara Rule Match
matches = rules.match(data=fileData,
externals={
'filename': fileName,
'filepath': filePath,
'extension': extension,
'filetype': fileType,
'md5': md5
})
# If matched
if matches:
for match in matches:
score = 70
description = "not set"
reference = "-"
# 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 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
except Exception, e:
if logger.debug:
traceback.print_exc()
def get_string_matches(self, strings):
try:
string_matches = []
matching_strings = ""
for string in strings:
# print string
extract = string[2]
if not extract in string_matches:
string_matches.append(extract)
string_num = 1
for string in string_matches:
matching_strings += " Str" + str(string_num) + ": " + removeNonAscii(removeBinaryZero(string))
string_num += 1
# Limit string
if len(matching_strings) > 140:
matching_strings = matching_strings[:140] + " ... (truncated)"
return matching_strings.lstrip(" ")
except:
traceback.print_exc()
def check_svchost_owner(self, owner):
## Locale setting
import ctypes
import locale
windll = ctypes.windll.kernel32
locale = locale.windows_locale[ windll.GetUserDefaultUILanguage() ]
if locale == 'fr_FR':
return (owner.upper().startswith("SERVICE LOCAL") or
owner.upper().startswith(u"SERVICE RÉSEAU") or
re.match(r"SERVICE R.SEAU", owner) or
owner == u"Système" or
owner.upper().startswith(u"AUTORITE NT\Système") or
re.match(r"AUTORITE NT\\Syst.me", owner))
elif locale == 'ru_RU':
return (owner.upper().startswith("NET") or
owner == u"система" or
owner.upper().startswith("LO"))
else:
return ( owner.upper().startswith("NT ") or owner.upper().startswith("NET") or
owner.upper().startswith("LO") or
owner.upper().startswith("SYSTEM"))
def scan_processes(self):
# WMI Handler
c = wmi.WMI()
processes = c.Win32_Process()
t_systemroot = os.environ['SYSTEMROOT']
# WinInit PID
wininit_pid = 0
# LSASS Counter
lsass_count = 0
# LOKI's processes
loki_pid = os.getpid()
loki_ppid = psutil.Process(os.getpid()).ppid() # safer way to do this - os.ppid() fails in some envs
for process in processes:
try:
# Gather Process Information --------------------------------------
pid = process.ProcessId
name = process.Name
cmd = process.CommandLine
if not cmd:
cmd = "N/A"
if not name:
name = "N/A"
path = "none"
parent_pid = process.ParentProcessId
priority = process.Priority
ws_size = process.VirtualSize
if process.ExecutablePath:
path = process.ExecutablePath
# Owner
try:
owner_raw = process.GetOwner()
owner = owner_raw[2]
except Exception, e:
owner = "unknown"
if not owner:
owner = "unknown"
except Exception, e:
logger.log("ALERT", "ProcessScan", "Error getting all process information. Did you run the scanner 'As Administrator'?")
continue
# Is parent to other processes - save PID
if name == "wininit.exe":
wininit_pid = pid
# Special Checks ------------------------------------------------------
# better executable path
if not "\\" in cmd and path != "none":
cmd = path
# Process Info
process_info = "PID: %s NAME: %s OWNER: %s CMD: %s PATH: %s" % (str(pid), name, owner, cmd, path)
# Skip some PIDs ------------------------------------------------------
if pid == 0 or pid == 4:
logger.log("INFO", "ProcessScan", "Skipping Process %s" % process_info)
continue
# Skip own process ----------------------------------------------------
if loki_pid == pid or loki_ppid == pid:
logger.log("INFO", "ProcessScan", "Skipping LOKI Process %s" % process_info)
continue
# Print info ----------------------------------------------------------
logger.log("INFO", "ProcessScan", "Scanning Process %s" % process_info)
# Skeleton Key Malware Process
if re.search(r'psexec .* [a-fA-F0-9]{32}', cmd, re.IGNORECASE):
logger.log("WARNING", "ProcessScan", "Process that looks liks SKELETON KEY psexec execution detected %s" % process_info)
# File Name Checks -------------------------------------------------
for fioc in self.filename_iocs:
match = fioc['regex'].search(cmd)
if match:
if fioc['score'] > 70:
logger.log("ALERT", "ProcessScan", "File Name IOC matched PATTERN: %s DESC: %s MATCH: %s" % (fioc['regex'].pattern, fioc['description'], cmd))
elif fioc['score'] > 40:
logger.log("WARNING", "ProcessScan", "File Name Suspicious IOC matched PATTERN: %s DESC: %s MATCH: %s" % (fioc['regex'].pattern, fioc['description'], cmd))
# Suspicious waitfor - possible backdoor https://twitter.com/subTee/status/872274262769500160
if name == "waitfor.exe":
logger.log("WARNING", "ProcessScan", "Suspicious waitfor.exe process https://twitter.com/subTee/status/872274262769500160 %s" % process_info)
# Yara rule match
# only on processes with a small working set size
if processExists(pid):
if int(ws_size) < ( 100 * 1048576 ): # 100 MB
try:
alerts = []
for rules in self.yara_rules:
# continue - fast switch
matches = rules.match(pid=pid)
if matches:
for match in matches:
# Preset memory_rule
memory_rule = 1
# Built-in rules have meta fields (cannot be expected from custom rules)
if hasattr(match, 'meta'):
# If a score is given
if 'memory' in match.meta:
memory_rule = int(match.meta['memory'])
# If rule is meant to be applied to process memory as well
if memory_rule == 1:
# print match.rule
alerts.append("Yara Rule MATCH: %s %s" % (match.rule, process_info))
if len(alerts) > 3:
logger.log("INFO", "ProcessScan", "Too many matches on process memory - most likely a false positive %s" % process_info)
elif len(alerts) > 0:
for alert in alerts:
logger.log("ALERT", "ProcessScan", alert)
except Exception, e:
if logger.debug:
traceback.print_exc()
logger.log("ERROR", "ProcessScan", "Error while process memory Yara check (maybe the process doesn't exist anymore or access denied) %s" % process_info)
else:
logger.log("DEBUG", "ProcessScan", "Skipped Yara memory check due to the process' big working set size (stability issues) PID: %s NAME: %s SIZE: %s" % ( pid, name, ws_size))
###############################################################
# PE-Sieve Checks
if processExists(pid) and self.peSieve.active:
# If PE-Sieve reports replaced processes
logger.log("DEBUG", "ProcessScan", "PE-Sieve scan of process PID: %s" % pid)
results = self.peSieve.scan(pid=pid)
if results["replaced"]:
logger.log("WARNING", "ProcessScan", "PE-Sieve reported replaced process %s REPLACED: %s" %
(process_info, str(results["replaced"])))
elif results["implanted"]:
logger.log("WARNING", "ProcessScan", "PE-Sieve reported implanted process %s IMPLANTED: %s" %
(process_info, str(results["implanted"])))
elif results["hooked"] or results["detached"]:
logger.log("NOTICE", "ProcessScan", "PE-Sieve reported hooked or detached process %s "
"HOOKED: %s SUSPICIOUS: %s" % (process_info, str(results["hooked"]),
str(results["detached"])))
else:
logger.log("INFO", "ProcessScan", "PE-Sieve reported no anomalies %s" % process_info)
###############################################################
# THOR Process Connection Checks
self.check_process_connections(process)
###############################################################
# THOR Process Anomaly Checks
# Source: Sysforensics http://goo.gl/P99QZQ
# Process: System
if name == "System" and not pid == 4:
logger.log("WARNING", "ProcessScan", "System process without PID=4 %s" % process_info)
# Process: smss.exe
if name == "smss.exe" and not parent_pid == 4:
logger.log("WARNING", "ProcessScan", "smss.exe parent PID is != 4 %s" % process_info)
if path != "none":
if name == "smss.exe" and not ( "system32" in path.lower() or "system32" in cmd.lower() ):
logger.log("WARNING", "ProcessScan", "smss.exe path is not System32 %s" % process_info)
if name == "smss.exe" and priority is not 11:
logger.log("WARNING", "ProcessScan", "smss.exe priority is not 11 %s" % process_info)
# Process: csrss.exe
if path != "none":
if name == "csrss.exe" and not ( "system32" in path.lower() or "system32" in cmd.lower() ):
logger.log("WARNING", "ProcessScan", "csrss.exe path is not System32 %s" % process_info)
if name == "csrss.exe" and priority is not 13:
logger.log("WARNING", "ProcessScan", "csrss.exe priority is not 13 %s" % process_info)
# Process: wininit.exe
if path != "none":
if name == "wininit.exe" and not ( "system32" in path.lower() or "system32" in cmd.lower() ):
logger.log("WARNING", "ProcessScan", "wininit.exe path is not System32 %s" % process_info)
if name == "wininit.exe" and priority is not 13:
logger.log("NOTICE", "ProcessScan", "wininit.exe priority is not 13 %s" % process_info)
# Is parent to other processes - save PID
if name == "wininit.exe":
wininit_pid = pid
# Process: services.exe
if path != "none":
if name == "services.exe" and not ( "system32" in path.lower() or "system32" in cmd.lower() ):
logger.log("WARNING", "ProcessScan", "services.exe path is not System32 %s" % process_info)
if name == "services.exe" and priority is not 9:
logger.log("WARNING", "ProcessScan", "services.exe priority is not 9 %s" % process_info)
if wininit_pid > 0:
if name == "services.exe" and not parent_pid == wininit_pid:
logger.log("WARNING", "ProcessScan", "services.exe parent PID is not the one of wininit.exe %s" % process_info)
# Process: lsass.exe
if path != "none":
if name == "lsass.exe" and not ( "system32" in path.lower() or "system32" in cmd.lower() ):
logger.log("WARNING", "ProcessScan", "lsass.exe path is not System32 %s" % process_info)
if name == "lsass.exe" and priority is not 9:
logger.log("WARNING", "ProcessScan", "lsass.exe priority is not 9 %s" % process_info)
if wininit_pid > 0:
if name == "lsass.exe" and not parent_pid == wininit_pid:
logger.log("WARNING", "ProcessScan", "lsass.exe parent PID is not the one of wininit.exe %s" % process_info)
# Only a single lsass process is valid - count occurrences
if name == "lsass.exe":
lsass_count += 1
if lsass_count > 1:
logger.log("WARNING", "ProcessScan", "lsass.exe count is higher than 1 %s" % process_info)
# Process: svchost.exe
if path is not "none":
if name == "svchost.exe" and not ( "system32" in path.lower() or "system32" in cmd.lower() ):
logger.log("WARNING", "ProcessScan", "svchost.exe path is not System32 %s" % process_info)
if name == "svchost.exe" and priority is not 8:
logger.log("NOTICE", "ProcessScan", "svchost.exe priority is not 8 %s" % process_info)
if name == "svchost.exe" and not ( self.check_svchost_owner(owner) or "UnistackSvcGroup" in cmd):
logger.log("WARNING", "ProcessScan", "svchost.exe process owner is suspicious %s" % process_info)
if name == "svchost.exe" and not " -k " in cmd and cmd != "N/A":
logger.log("WARNING", "ProcessScan", "svchost.exe process does not contain a -k in its command line %s" % process_info)
# Process: lsm.exe
if path != "none":
if name == "lsm.exe" and not ( "system32" in path.lower() or "system32" in cmd.lower() ):
logger.log("WARNING", "ProcessScan", "lsm.exe path is not System32 %s" % process_info)
if name == "lsm.exe" and priority is not 8:
logger.log("NOTICE", "ProcessScan", "lsm.exe priority is not 8 %s" % process_info)
if name == "lsm.exe" and not ( owner.startswith("NT ") or owner.startswith("LO") or owner.startswith("SYSTEM") or owner.startswith(u"система")):
logger.log(u"WARNING", "ProcessScan", "lsm.exe process owner is suspicious %s" % process_info)
if wininit_pid > 0:
if name == "lsm.exe" and not parent_pid == wininit_pid:
logger.log("WARNING", "ProcessScan", "lsm.exe parent PID is not the one of wininit.exe %s" % process_info)
# Process: winlogon.exe
if name == "winlogon.exe" and priority is not 13:
logger.log("WARNING", "ProcessScan", "winlogon.exe priority is not 13 %s" % process_info)
if re.search("(Windows 7|Windows Vista)", getPlatformFull()):
if name == "winlogon.exe" and parent_pid > 0:
for proc in processes:
if parent_pid == proc.ProcessId:
logger.log("WARNING", "ProcessScan", "winlogon.exe has a parent ID but should have none %s PARENTID: %s"
% (process_info, str(parent_pid)))
# Process: explorer.exe
if path != "none":
if name == "explorer.exe" and not t_systemroot.lower() in path.lower():
logger.log("WARNING", "ProcessScan", "explorer.exe path is not %%SYSTEMROOT%% %s" % process_info)
if name == "explorer.exe" and parent_pid > 0:
for proc in processes:
if parent_pid == proc.ProcessId:
logger.log("NOTICE", "ProcessScan", "explorer.exe has a parent ID but should have none %s" % process_info)
def check_process_connections(self, process):
try:
# Limits
MAXIMUM_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 as e:
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, command, str(x.laddr[0]), str(x.laddr[1]) ))
if x.status == 'ESTABLISHED':
# Lookup Remote IP
# Geo IP Lookup removed
# Check keyword in remote address
is_match, description = self.check_c2(str(x.raddr[0]))
if is_match:
logger.log("ALERT", "ProcessScan",
"Malware Domain/IP match in remote address PID: %s NAME: %s COMMAND: %s IP: %s PORT: %s DESC: %s" % (
str(pid), name, command, str(x.raddr[0]), str(x.raddr[1]), description))
# Full list
connection_count += 1
logger.log("NOTICE", "ProcessScan",
"Established connection PID: %s NAME: %s COMMAND: %s LIP: %s LPORT: %s RIP: %s RPORT: %s" % (
str(pid), name, command, str(x.laddr[0]), str(x.laddr[1]), str(x.raddr[0]), str(x.raddr[1]) ))
# Maximum connection output
if connection_count > MAXIMUM_CONNECTIONS:
logger.log("NOTICE", "ProcessScan", "Connection output threshold reached. Output truncated.")
return
except Exception, e:
if args.debug:
traceback.print_exc()
sys.exit(1)
logger.log("INFO", "ProcessScan",
"Process %s does not exist anymore or cannot be accessed" % str(pid))
def check_rootkit(self):
logger.log("INFO", "Rootkit", "Checking for Backdoors ...")
dp = DoublePulsar(ip="127.0.0.1", timeout=None, verbose=args.debug)
logger.log("INFO", "Rootkit", "Checking for Double Pulsar RDP Backdoor")
try:
dp_rdp_result, message = dp.check_ip_rdp()
if dp_rdp_result:
logger.log("ALERT", message)
else:
logger.log("INFO", "Rootkit", "Double Pulsar RDP check RESULT: %s" % message)
except Exception, e:
logger.log("INFO", "Rootkit", "Double Pulsar RDP check failed RESULT: Connection failure")
if args.debug:
traceback.print_exc()
logger.log("INFO", "Rootkit", "Checking for Double Pulsar SMB Backdoor")
try:
dp_smb_result, message = dp.check_ip_smb()
if dp_smb_result:
logger.log("ALERT", message)
else:
logger.log("INFO", "Rootkit", "Double Pulsar SMB check RESULT: %s" % message)
except Exception, e:
logger.log("INFO", "Rootkit", "Double Pulsar SMB check failed RESULT: Connection failure")
if args.debug:
traceback.print_exc()
def check_c2(self, remote_system):
# IP - exact match
if is_ip(remote_system):
for c2 in self.c2_server:
# if C2 definition is CIDR network
if is_cidr(c2):
if ip_in_net(remote_system, c2):
return True, self.c2_server[c2]
# if C2 is ip or else
if c2 == remote_system:
return True, self.c2_server[c2]
# Domain - remote system contains c2
# e.g. evildomain.com and dga1.evildomain.com
else:
for c2 in self.c2_server:
if c2 in remote_system:
return True, self.c2_server[c2]
return False,""
def initialize_c2_iocs(self, ioc_directory):
try:
for ioc_filename in os.listdir(ioc_directory):
try:
if 'c2' in ioc_filename:
with codecs.open(os.path.join(ioc_directory, ioc_filename), 'r', encoding='utf-8') as file:
lines = file.readlines()
for line in lines:
try:
# Comments and empty lines
if re.search(r'^#', line) or re.search(r'^[\s]*$', line):
continue
# Split the IOC line
row = line.split(';')
c2 = row[0]
comment = row[1].rstrip(" ").rstrip("\n")
# Check length
if len(c2) < 4:
logger.log("NOTICE", "Init",
"C2 server definition is suspiciously short - will not add %s" %c2)
continue
# Add to the LOKI iocs
self.c2_server[c2.lower()] = comment
except Exception,e:
logger.log("ERROR", "Init", "Cannot read line: %s" % line)
if logger.debug:
sys.exit(1)
except OSError, e:
logger.log("ERROR", "Init", "No such file or directory")
except Exception, e:
traceback.print_exc()
logger.log("ERROR", "Init", "Error reading Hash file: %s" % ioc_filename)
def initialize_filename_iocs(self, ioc_directory):
try:
for ioc_filename in os.listdir(ioc_directory):
if 'filename' in ioc_filename:
with codecs.open(os.path.join(ioc_directory, ioc_filename), 'r', encoding='utf-8') as file:
lines = file.readlines()
# Last Comment Line
last_comment = ""
for line in lines:
try:
# Empty
if re.search(r'^[\s]*$', line):
continue
# Comments
if re.search(r'^#', line):
last_comment = line.lstrip("#").lstrip(" ").rstrip("\n")
continue
# Elements with description
if ";" in line:
line = line.rstrip(" ").rstrip("\n\r")
row = line.split(';')
regex = row[0]
score = row[1]
if len(row) > 2:
regex_fp = row[2]
desc = last_comment
# Elements without description
else:
regex = line
# Replace environment variables
regex = replaceEnvVars(regex)
# OS specific transforms