forked from stratosphereips/StratosphereLinuxIPS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slips.py
executable file
·1956 lines (1701 loc) · 75.1 KB
/
slips.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 python3
# Stratosphere Linux IPS. A machine-learning Intrusion Detection System
# Copyright (C) 2021 Sebastian Garcia
# 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 2
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from slips_files.common.abstracts import Module
from slips_files.common.slips_utils import utils
from slips_files.core.database.database import __database__
from slips_files.common.config_parser import ConfigParser
from exclusiveprocess import Lock, CannotAcquireLock
import threading
import signal
import sys
import redis
import os
import time
import shutil
import psutil
import socket
import warnings
import json
import pkgutil
import inspect
import modules
import importlib
import errno
import subprocess
import re
from datetime import datetime
from collections import OrderedDict
from distutils.dir_util import copy_tree
from daemon import Daemon
from multiprocessing import Queue
version = '1.0.2'
# Ignore warnings on CPU from tensorflow
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# Ignore warnings in general
warnings.filterwarnings('ignore')
# ---------------------
class Main:
def __init__(self, testing=False):
self.name = 'Main'
self.alerts_default_path = 'output/'
self.mode = 'interactive'
self.running_logfile = 'running_slips_info.txt'
# slips picks a redis port from the following range
self.start_port = 32768
self.end_port = 32850
self.conf = ConfigParser()
self.args = self.conf.get_args()
# in testing mode we manually set the following params
if not testing:
self.pid = os.getpid()
self.check_given_flags()
if not self.args.stopdaemon:
# Check the type of input
self.input_type, self.input_information, self.line_type = self.check_input_type()
# If we need zeek (bro), test if we can run it.
self.check_zeek_or_bro()
self.prepare_output_dir()
# this is the zeek dir slips will be using
self.prepare_zeek_output_dir()
self.twid_width = self.conf.get_tw_width()
def prepare_zeek_output_dir(self):
from pathlib import Path
without_ext = Path(self.input_information).stem
# do we store the zeek dir inside the output dir?
store_zeek_files_in_the_output_dir = self.conf.store_zeek_files_in_the_output_dir()
if store_zeek_files_in_the_output_dir:
self.zeek_folder = os.path.join(self.args.output, 'zeek_files')
else:
self.zeek_folder = f'zeek_files_{without_ext}/'
def get_host_ip(self):
"""
Recognize the IP address of the machine
"""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('1.1.1.1', 80))
ipaddr_check = s.getsockname()[0]
s.close()
except (socket.error):
# not connected to the internet
return None
return ipaddr_check
def get_pid_using_port(self, port):
"""
Returns the PID of the process using the given port or False if no process is using it
"""
port = int(port)
for conn in psutil.net_connections():
if conn.laddr.port == port:
return psutil.Process(conn.pid).pid #.name()
return None
def check_if_webinterface_started(self):
if not hasattr(self, 'webinterface_return_value'):
return
# now that the web interface had enough time to start,
# check if it successfully started or not
if self.webinterface_return_value.empty():
# to make sure this function is only executed once
delattr(self, 'webinterface_return_value')
return
if self.webinterface_return_value.get() != True:
# to make sure this function is only executed once
delattr(self, 'webinterface_return_value')
return
self.print(f"Slips {self.green('web interface')} running on "
f"http://localhost:55000/")
delattr(self, 'webinterface_return_value')
def start_webinterface(self):
"""
Starts the web interface shell script if -w is given
"""
def detach_child():
"""
Detach the web interface from the parent process group(slips.py), the child(web interface)
will no longer receive signals and should be manually killed in shutdown_gracefully()
"""
os.setpgrp()
def run_webinterface():
# starting the wbeinterface using the shell script results in slips not being able to
# get the PID of the python proc started by the .sh scrip
command = ['python3', 'webinterface/app.py']
webinterface = subprocess.Popen(
command,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
stdin=subprocess.DEVNULL,
preexec_fn=detach_child
)
# self.webinterface_pid = webinterface.pid
__database__.store_process_PID('Web Interface', webinterface.pid)
# we'll assume that it started, and if not, the return value will immidiately change and this thread will
# print an error
self.webinterface_return_value.put(True)
# waits for process to terminate, so if no errors occur
# we will never get the return value of this thread
error = webinterface.communicate()[1]
if error:
# pop the True we just added
self.webinterface_return_value.get()
# set false as the return value of this thread
self.webinterface_return_value.put(False)
pid = self.get_pid_using_port(55000)
self.print (f"Web interface error:\n"
f"{error.strip().decode()}\n"
f"Port 55000 is used by PID {pid}")
# if theres's an error, this will be set to false, and the error will be printed
# otherwise we assume that the inetrface started
# self.webinterface_started = True
self.webinterface_return_value = Queue()
self.webinterface_thread = threading.Thread(
target=run_webinterface,
daemon=True,
)
self.webinterface_thread.start()
# we'll be checking the return value of this thread later
def store_host_ip(self):
"""
Store the host IP address if input type is interface
"""
running_on_interface = '-i' in sys.argv or __database__.is_growing_zeek_dir()
if not running_on_interface:
return
hostIP = self.get_host_ip()
while True:
try:
__database__.set_host_ip(hostIP)
break
except redis.exceptions.DataError:
self.print(
'Not Connected to the internet. Reconnecting in 10s.'
)
time.sleep(10)
hostIP = self.get_host_ip()
return hostIP
def create_folder_for_logs(self):
"""
Create a dir for logs if logs are enabled
"""
logs_folder = utils.convert_format(datetime.now(), '%Y-%m-%d--%H-%M-%S')
# place the logs dir inside the output dir
logs_folder = os.path.join(self.args.output, f'detailed_logs_{logs_folder}')
try:
os.makedirs(logs_folder)
except OSError as e:
if e.errno != errno.EEXIST:
# doesn't exist and can't create
return False
return logs_folder
def check_redis_database(
self, redis_host='localhost', redis_port=6379
) -> bool:
"""
Check if we have redis-server running (this is the cache db it should always be running)
"""
tries = 0
while True:
try:
r = redis.StrictRedis(
host=redis_host,
port=redis_port,
db=1,
charset='utf-8',
decode_responses=True,
)
r.ping()
return True
except Exception as ex:
# only try to open redi-server once.
if tries == 2:
print(f'[Main] Problem starting redis cache database. \n{ex}\nStopping')
self.terminate_slips()
return False
print('[Main] Starting redis cache database..')
os.system(
f'redis-server redis.conf --daemonize yes > /dev/null 2>&1'
)
# give the server time to start
time.sleep(1)
tries += 1
def get_random_redis_port(self):
"""
Keeps trying to connect to random generated ports until we're connected.
returns the used port
"""
# generate a random unused port
for port in range(self.start_port, self.end_port+1):
# check if 1. we can connect
# 2.server is not being used by another instance of slips
# note: using r.keys() blocks the server
try:
connected = __database__.connect_to_redis_server(port)
if connected:
server_used = len(list(__database__.r.keys())) < 2
if server_used:
# if the db managed to connect to this random port, then this is
# the port we'll be using
return port
except redis.exceptions.ConnectionError:
# Connection refused to this port
continue
else:
# there's no usable port in this range
print(f"All ports from {self.start_port} to {self.end_port} are used. "
"Unable to start slips.\n")
return False
def clear_redis_cache_database(
self, redis_host='localhost', redis_port=6379
) -> bool:
"""
Clear cache database
"""
rcache = redis.StrictRedis(
host=redis_host,
port=redis_port,
db=1,
charset='utf-8',
decode_responses=True,
)
rcache.flushdb()
return True
def check_zeek_or_bro(self):
"""
Check if we have zeek or bro
"""
self.zeek_bro = None
if self.input_type not in ('pcap', 'interface'):
return False
if shutil.which('zeek'):
self.zeek_bro = 'zeek'
elif shutil.which('bro'):
self.zeek_bro = 'bro'
else:
print('Error. No zeek or bro binary found.')
self.terminate_slips()
return False
return self.zeek_bro
def terminate_slips(self):
"""
Shutdown slips, is called when stopping slips before
starting all modules. for example using -cb
"""
if self.mode == 'daemonized':
self.daemon.stop()
sys.exit(0)
def get_modules(self, to_ignore):
"""
Get modules from the 'modules' folder.
"""
# This plugins import will automatically load the modules and put them in
# the __modules__ variable
plugins = {}
failed_to_load_modules = 0
# Walk recursively through all modules and packages found on the . folder.
# __path__ is the current path of this python program
for loader, module_name, ispkg in pkgutil.walk_packages(
modules.__path__, f'{modules.__name__}.'
):
if any(module_name.__contains__(mod) for mod in to_ignore):
continue
# If current item is a package, skip.
if ispkg:
continue
# to avoid loading everything in the dir,
# only load modules that have the same name as the dir name
dir_name = module_name.split('.')[1]
file_name = module_name.split('.')[2]
if dir_name != file_name:
continue
# Try to import the module, otherwise skip.
try:
# "level specifies whether to use absolute or relative imports. The default is -1 which
# indicates both absolute and relative imports will be attempted. 0 means only perform
# absolute imports. Positive values for level indicate the number of parent
# directories to search relative to the directory of the module calling __import__()."
module = importlib.import_module(module_name)
except ImportError as e:
print(
'Something wrong happened while importing the module {0}: {1}'.format(
module_name, e
)
)
failed_to_load_modules += 1
continue
# Walk through all members of currently imported modules.
for member_name, member_object in inspect.getmembers(module):
# Check if current member is a class.
if inspect.isclass(member_object) and (issubclass(
member_object, Module
) and member_object is not Module):
plugins[member_object.name] = dict(
obj=member_object,
description=member_object.description,
)
# Change the order of the blocking module(load it first)
# so it can receive msgs sent from other modules
if 'Blocking' in plugins:
plugins = OrderedDict(plugins)
# last=False to move to the beginning of the dict
plugins.move_to_end('Blocking', last=False)
return plugins, failed_to_load_modules
def load_modules(self):
to_ignore = self.conf.get_disabled_modules(self.input_type)
# Import all the modules
modules_to_call = self.get_modules(to_ignore)[0]
for module_name in modules_to_call:
if module_name in to_ignore:
continue
module_class = modules_to_call[module_name]['obj']
if 'P2P Trust' == module_name:
module = module_class(
self.outputqueue,
self.redis_port,
output_dir=self.args.output
)
else:
module = module_class(
self.outputqueue,
self.redis_port
)
module.start()
__database__.store_process_PID(
module_name, int(module.pid)
)
description = modules_to_call[module_name]['description']
self.print(
f'\t\tStarting the module {self.green(module_name)} '
f'({description}) '
f'[PID {self.green(module.pid)}]', 1, 0
)
# give outputprocess time to print all the started modules
time.sleep(0.5)
print('-' * 27)
self.print(f"Disabled Modules: {to_ignore}", 1, 0)
def setup_detailed_logs(self, LogsProcess):
"""
Detailed logs are the ones created by logsProcess
"""
do_logs = self.conf.create_log_files()
# if -l is provided or create_log_files is yes then we will create log files
if self.args.createlogfiles or do_logs:
# Create a folder for logs
logs_dir = self.create_folder_for_logs()
# Create the logsfile thread if by parameter we were told,
# or if it is specified in the configuration
self.logsProcessQueue = Queue()
logs_process = LogsProcess(
self.logsProcessQueue,
self.outputqueue,
self.args.verbose,
self.args.debug,
logs_dir,
self.redis_port
)
logs_process.start()
self.print(
f'Started {self.green("Logs Process")} '
f'[PID {self.green(logs_process.pid)}]', 1, 0
)
__database__.store_process_PID(
'Logs', int(logs_process.pid)
)
else:
# If self.args.nologfiles is False, then we don't want log files,
# independently of what the conf says.
logs_dir = False
def start_gui_process(self):
# Get the type of output from the parameters
# Several combinations of outputs should be able to be used
if self.args.gui:
# Create the curses thread
guiProcessQueue = Queue()
guiProcess = GuiProcess(
guiProcessQueue, self.outputqueue, self.args.verbose,
self.args.debug
)
__database__.store_process_PID(
'GUI',
int(guiProcess.pid)
)
guiProcess.start()
self.print('quiet')
def close_all_ports(self):
"""
Closes all the redis ports in logfile and in slips supported range of ports
"""
if not hasattr(self, 'open_servers_PIDs'):
self.get_open_redis_servers()
# close all ports in logfile
for pid in self.open_servers_PIDs:
self.flush_redis_server(pid=pid)
self.kill_redis_server(pid)
# closes all the ports in slips supported range of ports
slips_supported_range = [port for port in range(self.start_port, self.end_port + 1)]
slips_supported_range.append(6379)
for port in slips_supported_range:
pid = self.get_pid_of_redis_server(port)
if pid:
self.flush_redis_server(pid=pid)
self.kill_redis_server(pid)
# print(f"Successfully closed all redis servers on ports {self.start_port} to {self.end_port}")
print(f"Successfully closed all open redis servers")
try:
os.remove(self.running_logfile)
except FileNotFoundError:
pass
self.terminate_slips()
return
def get_pid_of_redis_server(self, port: int) -> str:
"""
Gets the pid of the redis server running on this port
Returns str(port) or false if there's no redis-server running on this port
"""
cmd = 'ps aux | grep redis-server'
cmd_output = os.popen(cmd).read()
for line in cmd_output.splitlines():
if str(port) in line:
pid = line.split()[1]
return pid
return False
def update_local_TI_files(self):
from modules.update_manager.update_file_manager import UpdateFileManager
try:
# only one instance of slips should be able to update ports and orgs at a time
# so this function will only be allowed to run from 1 slips instance.
with Lock(name="slips_ports_and_orgs"):
update_manager = UpdateFileManager(self.outputqueue, self.redis_port)
update_manager.update_ports_info()
update_manager.update_org_files()
except CannotAcquireLock:
# another instance of slips is updating ports and orgs
return
def add_metadata(self):
"""
Create a metadata dir output/metadata/ that has a copy of slips.conf, whitelist.conf, current commit and date
"""
if not self.enable_metadata:
return
metadata_dir = os.path.join(self.args.output, 'metadata')
try:
os.mkdir(metadata_dir)
except FileExistsError:
# if the file exists it will be overwritten
pass
# Add a copy of slips.conf
config_file = self.args.config or 'config/slips.conf'
shutil.copy(config_file, metadata_dir)
# Add a copy of whitelist.conf
whitelist = self.conf.whitelist_path()
shutil.copy(whitelist, metadata_dir)
branch_info = utils.get_branch_info()
commit, branch = None, None
if branch_info != False:
# it's false when we're in docker because there's no .git/ there
commit, branch = branch_info[0], branch_info[1]
now = datetime.now()
now = utils.convert_format(now, utils.alerts_format)
self.info_path = os.path.join(metadata_dir, 'info.txt')
with open(self.info_path, 'w') as f:
f.write(f'Slips version: {version}\n'
f'File: {self.input_information}\n'
f'Branch: {branch}\n'
f'Commit: {commit}\n'
f'Slips start date: {now}\n'
)
print(f'[Main] Metadata added to {metadata_dir}')
return self.info_path
def kill(self, module_name, INT=False):
sig = signal.SIGINT if INT else signal.SIGKILL
try:
pid = int(self.PIDs[module_name])
os.kill(pid, sig)
except (KeyError, ProcessLookupError):
# process hasn't started yet
pass
def kill_all(self, PIDs):
for module in PIDs:
if module not in self.PIDs:
# modules the are last to kill aren't always started and there in self.PIDs
# ignore them
continue
self.kill(module)
self.print_stopped_module(module)
def stop_core_processes(self):
self.kill('Input')
if self.mode == 'daemonized':
# when using -D, we kill the processes because
# the queues are not there yet to send stop msgs
for process in (
'ProfilerProcess',
'logsProcess',
'OutputProcess'
):
self.kill(process, INT=True)
else:
# Send manual stops to the processes using queues
stop_msg = 'stop_process'
self.profilerProcessQueue.put(stop_msg)
self.outputqueue.put(stop_msg)
if hasattr(self, 'logsProcessQueue'):
self.logsProcessQueue.put(stop_msg)
def save_the_db(self):
# save the db to the output dir of this analysis
# backups_dir = os.path.join(os.getcwd(), 'redis_backups/')
# try:
# os.mkdir(backups_dir)
# except FileExistsError:
# pass
backups_dir = self.args.output
# The name of the interface/pcap/nfdump/binetflow used is in self.input_information
# if the input is a zeek dir, remove the / at the end
if self.input_information.endswith('/'):
self.input_information = self.input_information[:-1]
# We need to separate it from the path
self.input_information = os.path.basename(self.input_information)
# Remove the extension from the filename
try:
self.input_information = self.input_information[
: self.input_information.index('.')
]
except ValueError:
# it's a zeek dir
pass
# Give the exact path to save(), this is where our saved .rdb backup will be
rdb_filepath = os.path.join(backups_dir, self.input_information)
__database__.save(rdb_filepath)
# info will be lost only if you're out of space and redis can't write to dump.rdb, otherwise you're fine
print(
'[Main] [Warning] stop-writes-on-bgsave-error is set to no, information may be lost in the redis backup file.'
)
def was_running_zeek(self) -> bool:
"""returns true if zeek wa sused in this run """
return __database__.get_input_type() in ('pcap', 'interface') or __database__.is_growing_zeek_dir()
def store_zeek_dir_copy(self):
store_a_copy_of_zeek_files = self.conf.store_a_copy_of_zeek_files()
was_running_zeek = self.was_running_zeek()
if store_a_copy_of_zeek_files and was_running_zeek:
# this is where the copy will be stored
dest_zeek_dir = os.path.join(self.args.output, 'zeek_files')
copy_tree(self.zeek_folder, dest_zeek_dir)
print(
f'[Main] Stored a copy of zeek files to {dest_zeek_dir}'
)
def delete_zeek_files(self):
delete = self.conf.delete_zeek_files()
if delete:
shutil.rmtree(self.zeek_folder)
def green(self, txt):
"""
returns the text in green
"""
GREEN_s = '\033[1;32;40m'
GREEN_e = '\033[00m'
return f'{GREEN_s}{txt}{GREEN_e}'
def print_stopped_module(self, module):
self.PIDs.pop(module, None)
# all text printed in green should be wrapped in the following
modules_left = len(list(self.PIDs.keys()))
# to vertically align them when printing
module += ' ' * (20 - len(module))
print(
f'\t{self.green(module)} \tStopped. '
f'{self.green(modules_left)} left.'
)
def get_already_stopped_modules(self):
already_stopped_modules = []
for module, pid in self.PIDs.items():
try:
# signal 0 is used to check if the pid exists
os.kill(int(pid), 0)
except ProcessLookupError:
# pid doesn't exist because module already stopped
# to be able to remove it's pid from the dict
already_stopped_modules.append(module)
return already_stopped_modules
def warn_about_pending_modules(self, finished_modules):
# exclude the module that are already stopped from the pending modules
pending_modules = [
module
for module in list(self.PIDs.keys())
if module not in finished_modules
]
if not len(pending_modules):
return
print(
f'\n[Main] The following modules are busy working on your data.'
f'\n\n{pending_modules}\n\n'
'You can wait for them to finish, or you can '
'press CTRL-C again to force-kill.\n'
)
return True
def set_analysis_end_date(self):
"""
Add the analysis end date to the metadata file and
the db for the web inerface to display
"""
self.enable_metadata = self.conf.enable_metadata()
end_date = utils.convert_format(datetime.now(), utils.alerts_format)
__database__.set_input_metadata({'analysis_end': end_date})
if self.enable_metadata:
# add slips end date in the metadata dir
try:
with open(self.info_path, 'a') as f:
f.write(f'Slips end date: {end_date}\n')
except (NameError, AttributeError):
pass
return end_date
def should_kill_all_modules(self, function_start_time, wait_for_modules_to_finish) -> bool:
"""
checks if x minutes has passed since the start of the function
:param wait_for_modules_to_finish: time in mins to wait before force killing all modules
defined by wait_for_modules_to_finish in slips.conf
"""
now = datetime.now()
diff = utils.get_time_diff(function_start_time, now, return_type='minutes')
return True if diff >= wait_for_modules_to_finish else False
def shutdown_gracefully(self):
"""
Wait for all modules to confirm that they're done processing
or kill them after 15 mins
"""
# 15 mins from this time, all modules should be killed
function_start_time = datetime.now()
try:
if not self.args.stopdaemon:
print('\n' + '-' * 27)
print('Stopping Slips')
wait_for_modules_to_finish = self.conf.wait_for_modules_to_finish()
# close all tws
__database__.check_TW_to_close(close_all=True)
# set analysis end date
end_date = self.set_analysis_end_date()
start_time = __database__.get_slips_start_time()
analysis_time = utils.get_time_diff(start_time, end_date, return_type='minutes')
print(f'[Main] Analysis finished in {analysis_time:.2f} minutes')
# Stop the modules that are subscribed to channels
__database__.publish_stop()
finished_modules = []
# get dict of PIDs spawned by slips
self.PIDs = __database__.get_PIDs()
# we don't want to kill this process
self.PIDs.pop('slips.py', None)
if self.mode == 'daemonized':
profilesLen = __database__.getProfilesLen()
self.daemon.print(f'Total analyzed IPs: {profilesLen}.')
modules_to_be_killed_last = {
'EvidenceProcess',
'Blocking',
'Exporting Alerts',
}
self.stop_core_processes()
# only print that modules are still running once
warning_printed = False
# timeout variable so we don't loop forever
# give slips enough time to close all modules - make sure
# all modules aren't considered 'busy' when slips stops
max_loops = 430
# loop until all loaded modules are finished
# in the case of -S, slips doesn't even start the modules,
# so they don't publish in finished_modules. we don't need to wait for them we have to kill them
if not self.args.stopdaemon:
# modules_to_be_killed_last are ignored when they publish a msg in finished modules channel,
# we will kill them aletr, so we shouldn't be looping and waiting for them to get outta the loop
slips_processes = len(list(self.PIDs.keys())) - len(modules_to_be_killed_last)
try:
while (
len(finished_modules) < slips_processes and max_loops != 0
):
# print(f"Modules not finished yet {set(loaded_modules) - set(finished_modules)}")
try:
message = self.c1.get_message(timeout=0.00000001)
except NameError:
continue
if message and message['data'] in ('stop_process', 'stop_slips'):
continue
if utils.is_msg_intended_for(message, 'finished_modules'):
# all modules must reply with their names in this channel after
# receiving the stop_process msg
# to confirm that all processing is done and we can safely exit now
module_name = message['data']
if module_name in modules_to_be_killed_last:
# we should kill these modules the very last, or else we'll miss evidence generated
# right before slips stops
continue
if module_name not in finished_modules:
finished_modules.append(module_name)
self.kill(module_name)
self.print_stopped_module(module_name)
# some modules publish in finished_modules channel before slips.py starts listening,
# but they finished gracefully.
# remove already stopped modules from PIDs dict
for module in self.get_already_stopped_modules():
finished_modules.append(module)
self.print_stopped_module(module)
max_loops -= 1
# after reaching the max_loops and before killing the modules that aren't finished,
# make sure we're not processing
# the logical flow is self.pids should be empty by now as all modules
# are closed, the only ones left are the ones we want to kill last
if len(self.PIDs) > len(modules_to_be_killed_last) and max_loops < 2:
if not warning_printed and self.warn_about_pending_modules(finished_modules):
if 'Update Manager' not in finished_modules:
print(
f"[Main] Update Manager may take several minutes "
f"to finish updating 45+ TI files."
)
warning_printed = True
# -t flag is only used in integration tests,
# so we don't care about the modules finishing their job when testing
# instead, kill them
if self.args.testing:
break
# delay killing unstopped modules until all of them
# are done processing
max_loops += 1
# checks if 15 minutes has passed since the start of the function
if self.should_kill_all_modules(function_start_time, wait_for_modules_to_finish):
print(f"Killing modules that took more than "
f"{wait_for_modules_to_finish} mins to finish.")
break
except KeyboardInterrupt:
# either the user wants to kill the remaining modules (pressed ctrl +c again)
# or slips was stuck looping for too long that the os sent an automatic sigint to kill slips
# pass to kill the remaining modules
pass
# modules that aren't subscribed to any channel will always be killed and not stopped
# comes here if the user pressed ctrl+c again
self.kill_all(self.PIDs.copy())
self.kill_all(modules_to_be_killed_last)
# save redis database if '-s' is specified
if self.args.save:
self.save_the_db()
# if store_a_copy_of_zeek_files is set to yes in slips.conf,
# copy the whole zeek_files dir to the output dir
self.store_zeek_dir_copy()
# if delete_zeek_files is set to yes in slips.conf,
# delete zeek_files/ dir
self.delete_zeek_files()
if self.mode == 'daemonized':
# if slips finished normally without stopping the daemon with -S
# then we need to delete the pidfile
self.daemon.delete_pidfile()
os._exit(-1)
except KeyboardInterrupt:
return False
def get_open_redis_servers(self) -> dict:
"""
Returns the dict of PIDs and ports of the redis servers started by slips
"""
self.open_servers_PIDs = {}
try:
with open(self.running_logfile, 'r') as f:
for line in f.read().splitlines():
# skip comments
if (
line.startswith('#')
or line.startswith('Date')
or len(line) < 3
):
continue
line = line.split(',')
pid, port = line[3], line[2]
self.open_servers_PIDs[pid] = port
return self.open_servers_PIDs
except FileNotFoundError:
# print(f"Error: {self.running_logfile} is not found. Can't kill open servers. Stopping.")
return {}
def print_open_redis_servers(self):
"""
Returns a dict {counter: (used_port,pid) }
"""
open_servers = {}
to_print = f"Choose which one to kill [0,1,2 etc..]\n" \
f"[0] Close all Redis servers\n"
there_are_ports_to_print = False
try:
with open(self.running_logfile, 'r') as f:
line_number = 0
for line in f.read().splitlines():
# skip comments
if (
line.startswith('#')
or line.startswith('Date')
or len(line) < 3
):
continue
line_number += 1
line = line.split(',')
file, port, pid = line[1], line[2], line[3]
there_are_ports_to_print = True
to_print += f"[{line_number}] {file} - port {port}\n"
open_servers[line_number] = (port, pid)
except FileNotFoundError:
print(f"{self.running_logfile} is not found. Can't get open redis servers. Stopping.")
return False
if there_are_ports_to_print:
print(to_print)
else:
print(f"No open redis servers in {self.running_logfile}")
return open_servers
def get_port_of_redis_server(self, pid: str):
"""
returns the port of the redis running on this pid
"""
cmd = 'ps aux | grep redis-server'
cmd_output = os.popen(cmd).read()
for line in cmd_output.splitlines():
if str(pid) in line:
port = line.split(':')[-1]
return port
return False
def flush_redis_server(self, pid: str='', port: str=''):
"""
Flush the redis server on this pid, only 1 param should be given, pid or port
:param pid: can be False if port is given
Gets the pid of the port is not given
"""
if not port and not pid:
return False
# sometimes the redis port is given, no need to get it manually