This repository has been archived by the owner on Oct 10, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathace
executable file
·3572 lines (2877 loc) · 142 KB
/
ace
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
import argparse
import atexit
import collections
import datetime
import fnmatch
import getpass
import io
import json
import logging
import os
import os.path
import pwd
import re
import shutil
import signal
import smtplib
import socket
import sqlite3
import sys
import tempfile
import time
import trace
import traceback
import unittest
import uuid
parser = argparse.ArgumentParser(description="Simple Alert Queue")
parser.add_argument('--saq-home', required=False, dest='saq_home', default=None,
help="Sets the SAQ_HOME environment variable.")
parser.add_argument('-L', '--logging-config-path', required=False, dest='logging_config_path', default=None,
help="Path to the logging configuration file.")
parser.add_argument('-c', '--config-path', required=False, dest='config_paths', action='append', default=[],
help="ACE configuration files. $SAQ_HOME/etc/saq.default.ini is always loaded, additional override default settings.")
#parser.add_argument('--single-threaded', required=False, dest='single_threaded', default=False, action='store_true',
#help="Force execution to take place in a single process and a single thread. Useful for manual debugging.")
parser.add_argument('--log-level', required=False, dest='log_level', default=None,
help="Change the root log level.")
parser.add_argument('-u', '--user-name', required=False, dest='user_name', default=None,
help="The user name of the ACE user executing the command. This information is required for some commands.")
parser.add_argument('--start', required=False, dest='start', default=False, action='store_true',
help="Start the specified service. Blocks keyboard unless --daemon (-d) is used.")
parser.add_argument('--stop', required=False, dest='stop', default=False, action='store_true',
help="Stop the specified service. Only applies to services started with --daemon (-d).")
parser.add_argument('-d', '--daemon', required=False, dest='daemon', default=False, action='store_true',
help="Run this process as a daemon in the background.")
parser.add_argument('-k', '--kill-daemon', required=False, dest='kill_daemon', default=False, action='store_true',
help="Kill the currently processing process.")
parser.add_argument('--force-alerts', required=False, dest='force_alerts', default=False, action='store_true',
help="Force all analysis to always generate an alert.")
parser.add_argument('--relative-dir', required=False, dest='relative_dir', default=None,
help="Assume all storage paths are relative to the given directory. Defaults to current work directory.")
parser.add_argument('-p', '--provide-decryption-password', required=False, action='store_true', dest='provide_decryption_password', default=False,
help="Prompt for the decryption password so that encrypted archive files can be automatically analyzed.")
parser.add_argument('--trace', required=False, action='store_true', dest='trace', default=False,
help="Enable execution tracing (debugging option).")
parser.add_argument('-D', required=False, action='store_true', dest='debug_on_error', default=False,
help="Break into pdb if an unhanled exception is thrown or an assertion fails.")
subparsers = parser.add_subparsers(dest='cmd')
# utility functions
def disable_proxy():
for proxy_setting in [ 'http_proxy', 'https_proxy', 'ftp_proxy' ]:
if proxy_setting in os.environ:
logging.warning("removing proxy setting {0}".format(proxy_setting))
del os.environ[proxy_setting]
def recurse_analysis(analysis, level=0, current_tree=[]):
"""Used to generate a textual display of the analysis results."""
if not analysis:
return
if analysis in current_tree:
return
current_tree.append(analysis)
if level > 0 and len(analysis.observables) == 0 and len(analysis.tags) == 0 and analysis.summary is None:
return
display = '{}{}{}'.format('\t' * level,
'<' + '!' * len(analysis.detections) + '> ' if analysis.detections else '',
analysis.summary if analysis.summary is not None else str(analysis))
if analysis.tags:
display += ' [ {} ] '.format(', '.join([x.name for x in analysis.tags]))
print(display)
for observable in analysis.observables:
display = '{} * {}{}:{}'.format('\t' * level,
'<' + '!' * len(observable.detections) + '> ' if observable.detections else '',
observable.type,
observable.value)
if observable.time is not None:
display += ' @ {0}'.format(observable.time)
if observable.directives:
display += ' {{ {} }} '.format(', '.join([x for x in observable.directives]))
if observable.tags:
display += ' [ {} ] '.format(', '.join([x.name for x in observable.tags]))
print(display)
for observable_analysis in observable.all_analysis:
recurse_analysis(observable_analysis, level + 1, current_tree)
def display_analysis(root):
recurse_analysis(root)
#observables = set(root.all_observables)
#if observables:
#print("{} OBSERVATIONS".format(len(observables)))
#for observable in observables:
#print("* {} - {}".format(observable.type, observable.value))
tags = set(root.all_tags)
if tags:
print("{} TAGS".format(len(tags)))
for tag in tags:
print('* {}'.format(tag))
detections = root.all_detection_points
if detections:
print("{} DETECTIONS FOUND (marked with <!> above)".format(len(detections)))
for detection in detections:
print('* {}'.format(detection))
def kill_daemon(daemon_name):
import psutil
daemon_pid_path = os.path.join(saq.DATA_DIR, 'var', 'daemon', daemon_name)
if not os.path.exists(daemon_pid_path):
logging.warning("daemon file {} does not exist (process not running?)".format(daemon_pid_path))
sys.exit(1)
deamon_pid = None
try:
with open(daemon_pid_path, 'r') as fp:
daemon_pid = int(fp.read())
except Exception as e:
logging.error("cannot read PID from {}: {}".format(daemon_pid_path, e))
sys.exit(1)
try:
parent = psutil.Process(daemon_pid)
logging.info("sending SIGTERM to {}".format(parent.pid))
# this should gracefully allow the system to come to a stop
parent.terminate()
try:
parent.wait(timeout=60)
logging.info("system shut down")
except Exception as e:
logging.error("unable to terminate process {}: {}".format(parent.pid, e))
# but if it doesn't work then we walk the tree kill all processes
for child in parent.children(recursive=True):
try:
child.kill()
logging.info("killed child process {}".format(child.pid))
except Exception as e:
logging.error("unable to kill child process {}: {}".format(child, e))
try:
parent.kill()
except Exception as e:
logging.error("unable to kill process {}: {}".format(parent.pid, e))
except Exception as e:
logging.error("unable to stop process {}: {}".format(parent, e))
try:
os.remove(daemon_pid_path)
except Exception as e:
logging.error("unable to delete PID file {}: {}".format(daemon_pid_path, e))
sys.exit(1)
sys.exit(0)
def daemonize(daemon_name):
# are we already running?
daemon_dir = os.path.join(saq.DATA_DIR, 'var', 'daemon')
if not os.path.exists(daemon_dir):
try:
os.makedirs(daemon_dir)
except Exception as e:
logging.error("unable to create {}: {}".format(daemon_dir, str(e)))
sys.exit(1)
daemon_pid_path = os.path.join(saq.DATA_DIR, 'var', 'daemon', daemon_name)
if os.path.exists(daemon_pid_path):
pid = None
with open(daemon_pid_path, 'r') as fp:
pid = int(fp.read())
if pid > 0:
try:
os.kill(pid, 0)
except OSError:
logging.warning("deamon PID file {} exists, but the process is not running. Proceeding to start engine.")
else:
import psutil
process = psutil.Process(pid)
logging.error("deamon PID file {} exists and '{}' is running with the contained PID={}: use command with -k to kill existing daemon".format(daemon_pid_path, process.name(), pid))
sys.exit(1)
pid = None
# http://code.activestate.com/recipes/278731-creating-a-daemon-the-python-way/
try:
pid = os.fork()
#print("got pid {}".format(pid))
except OSError as e:
logging.fatal("{} ({})".format(e.strerror, e.errno))
sys.exit(1)
if pid == 0:
os.setsid()
try:
pid = os.fork()
#print("got pid {}".format(pid))
except OSError as e:
logging.fatal("{} ({})".format(e.strerror, e.errno))
sys.exit(1)
if pid > 0:
# write the pid to a file
with open(daemon_pid_path, 'w') as fp:
fp.write(str(pid))
print("started background process {}".format(pid))
#print("pid {} exiting...".format(os.getpid()))
os._exit(0)
else:
#print("pid {} exiting...".format(os.getpid()))
os._exit(0)
import resource
maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
if (maxfd == resource.RLIM_INFINITY):
maxfd = MAXFD
for fd in range(0, maxfd):
try:
os.close(fd)
except OSError: # ERROR, fd wasn't open to begin with (ignored)
pass
if (hasattr(os, "devnull")):
REDIRECT_TO = os.devnull
else:
REDIRECT_TO = "/dev/null"
os.open(REDIRECT_TO, os.O_RDWR)
os.dup2(0, 1)
os.dup2(0, 2)
# ============================================================================
# export observables
#
# XXX not sure we need this anymore
def export_observables(args):
"""Exports observables, mappings and some alert context into a sqlite database."""
from saq.database import get_db_connection
if os.path.exists(args.output_file):
try:
os.remove(args.output_file)
except Exception as e:
logging.error("unable to delete {}: {}".format(args.output_file, e))
sys.exit(1)
output_db = sqlite3.connect(args.output_file)
output_c = output_db.cursor()
output_c.execute("""CREATE TABLE observables ( type text NOT NULL, value text NOT NULL)""")
output_c.execute("""CREATE UNIQUE INDEX i_type_value ON observables( type, value )""")
output_c.execute("""CREATE INDEX i_value ON observables( value )""")
i = 0
skip = 0
with get_db_connection() as input_db:
input_c = input_db.cursor()
input_c.execute("""SELECT type, value FROM observables""")
for _type, _value in input_c:
try:
_value = _value.decode('utf-8')
except UnicodeDecodeError as e:
skip += 1
continue
output_c.execute("""INSERT INTO observables ( type, value ) VALUES ( ?, ? )""", (_type, _value))
i += 1
output_db.commit()
output_db.close()
logging.info("exported {} observables (skipped {})".format(i, skip))
sys.exit(0)
export_observables_parser = subparsers.add_parser('export-observables',
help="Exports observables into a sqlite database.")
export_observables_parser.add_argument('output_file',
help="Path to the sqlite database to create. Existing files are overwritten.")
export_observables_parser.set_defaults(func=export_observables)
# ============================================================================
# ssdeep compilation
#
# XXX get rid of this garbage
def compile_ssdeep(args):
"""Compile the etc/ssdeep.json CRITS export into a usable ssdeep hash file."""
import saq
json_path = os.path.join(saq.SAQ_HOME, args.input)
output_path = os.path.join(saq.SAQ_HOME, args.output)
temp_output_path = '{}.tmp'.format(output_path)
count = 0
duplicate_check = set()
if not os.path.exists(json_path):
logging.error("missing {}".format(json_path))
sys.exit(1)
try:
with open(temp_output_path, 'w') as temp_fp:
temp_fp.write('ssdeep,1.1--blocksize:hash:hash,filename\n')
with open(json_path, 'r') as fp:
root = json.load(fp)
for _object in root['objects']:
if _object['ssdeep'] in duplicate_check:
logging.warning("detected duplicate ssdeep hash {}".format(_object['ssdeep']))
continue
duplicate_check.add(_object['ssdeep'])
temp_fp.write('{},{}\n'.format(_object['ssdeep'], _object['id']))
count += 1
except Exception as e:
logging.error("unable to create {}: {}".format(temp_output_path), str(e))
sys.exit(1)
# now move it over for usage
try:
logging.debug("moving {0} to {1}".format(temp_output_path, output_path))
shutil.move(temp_output_path, output_path)
except Exception as e:
logging.error("unable to move {0} to {1}: {2}".format(temp_output_path, output_path, str(e)))
sys.exit(1)
logging.info("processed {0} entries".format(count))
sys.exit(0)
compile_ssdeep_parser = subparsers.add_parser('compile-ssdeep',
help="Compiles ssdeep signatures exported from CRITS.")
compile_ssdeep_parser.add_argument('-i', '--input', required=False, default='etc/ssdeep.json', dest='input',
help="The CRITS export of the ssdeep hashses in JSON format.")
compile_ssdeep_parser.add_argument('-o', '--output', required=False, default='etc/ssdeep_hashes', dest='output',
help="The ssdeep hash file generated by the script.")
compile_ssdeep_parser.set_defaults(func=compile_ssdeep)
# ============================================================================
# command line correlation
#
def correlate(args):
# initialize command line engine
from saq import CONFIG
from saq.analysis import RootAnalysis
from saq.constants import F_FILE, F_SUSPECT_FILE, VALID_OBSERVABLE_TYPES, event_time_format, \
EVENT_GLOBAL_TAG_ADDED, \
EVENT_GLOBAL_ANALYSIS_ADDED, \
EVENT_GLOBAL_OBSERVABLE_ADDED, \
ANALYSIS_MODE_CLI, ANALYSIS_MODE_CORRELATION
from saq.engine import Engine
from saq.error import report_exception
from saq.process_server import initialize_process_server
from saq.util import parse_event_time
initialize_process_server()
engine = Engine(single_threaded_mode=args.single_threaded)
engine.set_local()
engine.disable_alerting()
def _cleanup():
nonlocal engine
from saq.database import get_db_connection
with get_db_connection() as db:
c = db.cursor()
c.execute("DELETE FROM workload WHERE exclusive_uuid = %s", (engine.exclusive_uuid,))
c.execute("DELETE FROM delayed_analysis WHERE exclusive_uuid = %s", (engine.exclusive_uuid,))
c.execute("DELETE FROM nodes WHERE id = %s", (saq.SAQ_NODE_ID,))
db.commit()
# when all is said and done we want to make sure we don't leave any work entries behind in the database
atexit.register(_cleanup)
# these might not make sense any more
#def _tag_added_event(source, event_type, tag):
#logging.info("tagged {} with {}".format(source, tag.name))
#def _observable_added_event(source, event_type, observable):
#logging.info("observed {} in {}".format(observable, source))
#def _analysis_added_event(source, event_type, analysis):
#logging.info("analyzed {} with {}".format(source, analysis))
#root.add_event_listener(EVENT_GLOBAL_TAG_ADDED, _tag_added_event)
#root.add_event_listener(EVENT_GLOBAL_OBSERVABLE_ADDED, _observable_added_event)
#root.add_event_listener(EVENT_GLOBAL_ANALYSIS_ADDED, _analysis_added_event)
if len(args.targets) % 2 != 0:
logging.error("odd number of arguments (you need pairs of type and value)")
sys.exit(1)
targets = args.targets
# did we specify targets from stdin?
if args.from_stdin:
for o_value in sys.stdin:
# the type of observables coming in on stdin is also specified on the command line
targets.append(args.stdin_type)
targets.append(o_value.strip())
reference_time = None
if args.reference_time is not None:
reference_time = parse_event_time(args.reference_time)
if os.path.exists(args.storage_dir) and not args.load:
# if the output directory is the default directory then just delete it
# this has been what I've wanted to happen 100% of the time
if args.storage_dir == 'ace.out':
try:
logging.warning("deleting existing output directory ace.out")
shutil.rmtree('ace.out')
except Exception as e:
logging.error("unable to delete existing output directory ace.out: {}".format(e))
sys.exit(1)
else:
logging.error("output directory {} already exists".format(args.storage_dir))
sys.exit(1)
roots = []
root = RootAnalysis()
# create a RootAnalysis to pass to the engine for analysis
root.storage_dir = args.storage_dir
if os.path.exists(args.storage_dir):
logging.warning("storage directory {} already exists".format(args.storage_dir))
else:
# create the output directory
try:
root.initialize_storage()
except Exception as e:
logging.error("unable to create output directory {}: {}".format(args.storage_dir, e))
sys.exit(1)
if args.load:
root.load()
# we override whatever previous analysis mode it had
root.analysis_mode = ANALYSIS_MODE_CLI if args.analysis_mode is None else args.analysis_mode
else:
# set all of the properties individually
# XXX only require company_id in RootAnalysis
if args.company_name:
root.company_name = args.company_name
root.tool = 'ACE - Command Line Analysis'
root.tool_instance = socket.gethostname()
root.alert_type = args.alert_type
root.analysis_mode = ANALYSIS_MODE_CLI if args.analysis_mode is None else args.analysis_mode
root.description = args.description if args.description else 'Command Line Correlation'
root.event_time = datetime.datetime.now() if reference_time is None else reference_time
if args.load_details:
with open(args.load_details, 'r') as fp:
root.details = json.load(fp)
else:
root.details = {
'local_user': pwd.getpwuid(os.getuid())[0],
'local_user_uid': os.getuid(),
'comment': args.comment
}
# create the list of observables to add to the alert for analysis
index = 0
while index < len(args.targets):
o_type = args.targets[index]
o_value = args.targets[index + 1]
if o_type not in VALID_OBSERVABLE_TYPES:
logging.error("invalid observable type {0}".format(o_type))
sys.exit(1)
# the root analysis we're currently working on (defaults to the main alert)
current_root = root
# are we creating a separate alert for each observable?
if args.split:
current_root = RootAnalysis()
subdir = os.path.join(root.storage_dir, current_root.uuid[0:3])
if not os.path.exists(subdir):
try:
os.mkdir(subdir)
except Exception as e:
logging.error("unable to create directory {}: {}".format(subdir, e))
sys.exit(1)
current_root.storage_dir = os.path.join(subdir, current_root.uuid)
try:
current_root.initialize_storage()
except Exception as e:
logging.error("unable to create directory {}: {}".format(subdir, e))
# XXX not sure we need this any more
# we'll make a little symlink if we can to help analysts know which directory is what
# it's ok if this fails
try:
os.symlink(os.path.join(current_root.uuid[0:3], current_root.uuid), os.path.join(root.storage_dir, str(o_value)))
except Exception as e:
logging.warning("unable to create symlink: {}".format(e))
current_root.tool = root.tool
current_root.tool_instance = root.tool_instance
current_root.alert_type = root.alert_type
current_root.analysis_mode = root.analysis_mode
current_root.description = "{} - {}:{}".format(root.description, o_type, o_value)
current_root.event_time = root.event_time
current_root.details = root.details
# if this is a file then we need to copy it over to the storage directory
if o_type == F_FILE:
dest_path = os.path.join(current_root.storage_dir, os.path.basename(o_value))
try:
logging.debug("copying {} to {}".format(o_value, dest_path))
shutil.copy(o_value, dest_path)
except Exception as e:
logging.error("unable to copy {} to {} for analysis: {}".format(o_value, dest_path, e))
sys.exit(1)
o_value = os.path.basename(o_value)
observable = current_root.add_observable(o_type, o_value, reference_time)
for directive in args.directives:
observable.add_directive(directive)
index += 2
if args.split:
current_root.save()
current_root.schedule(exclusive_uuid=exclusive_uuid)
roots.append(current_root)
# if we are not splitting up the alerts then we just have one alert to look at
if not args.split:
root.save()
root.schedule(exclusive_uuid=engine.exclusive_uuid)
roots.append(root)
# allow the user to control what analysis modules run
if args.disable_all:
logging.warning("disabling all analysis modules...")
for section in saq.CONFIG.sections():
if not section.startswith('analysis_module_'):
continue
saq.CONFIG[section]['enabled'] = 'no'
if args.disabled_modules:
for section in saq.CONFIG.sections():
if not section.startswith('analysis_module_'):
continue
for name_pattern in args.disabled_modules:
if name_pattern in section[len('analysis_module_'):]:
logging.warning("disabling {}".format(section))
saq.CONFIG[section]['enabled'] = 'no'
# enable by group
if args.enable_module_group:
for module_group in args.enable_module_group:
group_section = 'module_group_{}'.format(module_group)
if group_section not in saq.CONFIG:
logging.error("module group {} does not exist".format(module_group))
sys.exit(1)
for module_name in saq.CONFIG[group_section].keys():
logging.info("enabling {} by group {}".format(module_name, module_group))
engine.enable_module(module_name, ANALYSIS_MODE_CLI)
#saq.CONFIG[module_name]['enabled'] = 'yes'
#saq.CONFIG['engine_cli_correlation']['module_groups'] = ','.join(args.enable_module_group)
if args.enabled_modules:
for name_pattern in args.enabled_modules:
for section in saq.CONFIG.sections():
if fnmatch.fnmatch(section[len('analysis_module_'):], name_pattern):
#if name_pattern in section[len('analysis_module_'):]:
logging.info("enabling {}".format(section))
engine.enable_module(section, ANALYSIS_MODE_CLI)
#saq.CONFIG[section]['enabled'] = 'yes'
#saq.CONFIG['engine_cli_correlation'][section] = 'yes'
try:
if not args.single_threaded:
engine.controlled_stop()
engine.start()
engine.wait()
except KeyboardInterrupt:
logging.warning("user interrupted correlation")
engine.stop()
engine.wait()
for root in roots:
# display the results
root = RootAnalysis(storage_dir=root.storage_dir)
root.load()
display_analysis(root)
if args.alert:
if root.whitelisted:
logging.info("{} was whitelisted".format(root))
continue
if saq.FORCED_ALERTS or root.has_detections():
from ace_api import upload
try:
logging.info("uploading {}".format(root))
# need to switch the mode to correlation
root.analysis_mode = ANALYSIS_MODE_CORRELATION
root.save()
remote_host = None # if left as None then the api call defaults it to ace_api.default_node
if args.remote_host is not None:
remote_host = args.remote_host
if args.remote_port is not None:
remote_host = '{}:{}'.format(remote_host, args.remote_port)
result = upload(root.uuid, root.storage_dir, remote_host=remote_host, ssl_verification=args.ssl_ca_path)
except Exception as e:
logging.error("unable to upload {}: {}".format(root, e))
sys.exit(0)
# analyze-files
correlate_parser = subparsers.add_parser('correlate',
help="Analyze one or more observables or alerts.")
correlate_parser.add_argument('--single-threaded', required=False, dest='single_threaded', default=False, action='store_true',
help="Force execution to take place in a single process and a single thread. Useful for manual debugging.")
correlate_parser.add_argument('-D', '--disable-module', required=False, dest='disabled_modules', nargs='*',
help="Zero or more module names (substring match) to disable.")
correlate_parser.add_argument('--disable-all', required=False, dest='disable_all', default=False, action='store_true',
help="Disable all analysis modules (use -E switch to enable specific modules.")
correlate_parser.add_argument('-E', '--enable-module', required=False, dest='enabled_modules', nargs='*',
help="Zero or more module names (substring match) to enable.")
correlate_parser.add_argument('-G', '--enable-module-group', required=False, dest='enable_module_group', nargs='+',
help="One or more module group names to enable.")
correlate_parser.add_argument('-m', '--analysis-mode', required=False, dest='analysis_mode',
help="The analysis mode to use for this analysis. Defaults to cli")
correlate_parser.add_argument('-d', '--storage-dir', required=False, dest='storage_dir', default='ace.out',
help="Specify an output directory. Defaults to ace.out.")
correlate_parser.add_argument('-t', '--reference-time', required=False, dest='reference_time', default=None,
help="Specify a datetime in YYYY-MM-DD HH:MM:SS format that observables (of a temporal type) should be referenced from.")
correlate_parser.add_argument('--description', required=False, dest='description', default="ACE Manual Correlation",
help="Supply a description. This will be displayed as part of the alert if this correlation is later imported as an alert.")
correlate_parser.add_argument('--comment', required=False, dest='comment', default=None,
help="Optional generic comment to add to the details of the alert.")
correlate_parser.add_argument('--add-directive', required=False, dest='directives', action='append', default=[],
help="Adds the given directive to all observables specified. This option can be used multiple times.")
correlate_parser.add_argument('--alert-type', required=False, dest='alert_type', default='cli_analysis',
help="Optionally set the alert type. Some analysis is only performed for alerts of a certain type.")
correlate_parser.add_argument('--company-name', required=False, dest='company_name', default=None,
help="Optionally assign ownership of this analysis to a company.")
correlate_parser.add_argument('--alert', required=False, dest='alert', action='store_true', default=False,
help="Insert the correlation as an alert if it contains a detection point.")
correlate_parser.add_argument('--remote-host', required=False, dest='remote_host', default=None,
help="Specify the remote host of the ACE system (defaults to the engine_ace configuration values).")
correlate_parser.add_argument('--remote-port', required=False, dest='remote_port', default=None, type=int,
help="Specify the remote port of the ACE system (defaults to the engine_ace configuration values).")
#correlate_parser.add_argument('--ssl-root-cert', required=False, dest='ssl_root_cert', default=None,
#help="Specify the path to the SSL cert for the ACE system (defaults to the engine_ace configuration values).")
#correlate_parser.add_argument('--ssl-key', required=False, dest='ssl_key', default=None,
#help="Specify the path to the SSL key for the ACE system (defaults to the engine_ace configuration values).")
correlate_parser.add_argument('--ssl-ca-path', required=False, dest='ssl_ca_path', default=None,
help="Specify the path to the CA cert for the ACE system (defaults to the engine_ace configuration values).")
#correlate_parser.add_argument('--ssl-hostname', required=False, dest='ssl_hostname', default=None,
#help="Specify the ssl hostname of the ACE system (defaults to the engine_ace configuration values).")
correlate_parser.add_argument('--split', required=False, dest='split', action='store_true', default=False,
help="Split the observables up into individual analysis.")
correlate_parser.add_argument('--from-stdin', required=False, dest='from_stdin', action='store_true', default=False,
help="Read observables from stanard input. Defaults to treating them as file-type observables.")
correlate_parser.add_argument('--stdin-type', required=False, dest='stdin_type', default='file',
help="Specify the observable type when reading observables from stdin. Defaults to file.")
#correlate_parser.add_argument('--skip-analysis', required=False, dest='skip_analysis', action='store_true', default=False,
#help="Skip analyzing the alert. Useful if you just want to send a bunch of stuff to ACE for analysis.")
correlate_parser.add_argument('--load', required=False, dest='load', action='store_true', default=False,
help="Instead of creating a new analysis, load the existing analysis stored at --storage-dir.")
correlate_parser.add_argument('--load-details', required=False, dest='load_details', default=None,
help="Load the given JSON file as the details of the alert.")
correlate_parser.add_argument('targets', nargs="*",
help="One or more pairs of indicator types and values.")
correlate_parser.set_defaults(func=correlate)
# ============================================================================
# correlation engine
#
def correlation_engine(args):
from saq.engine import Engine
from saq.error import report_exception
from saq.process_server import initialize_process_server
daemon_name = 'correlation-engine'
disable_proxy()
if args.stop:
kill_daemon(daemon_name)
sys.exit(0)
elif args.start:
if args.daemon:
logging.info("starting daemon {}".format(daemon_name))
daemonize(daemon_name)
initialize_process_server()
ace_engine = None
# add the capability for a graceful shutdown
def handle_signal(signum, frame):
ace_engine.stop()
signal.signal(signal.SIGTERM, handle_signal)
signal.signal(signal.SIGINT, handle_signal)
try:
ace_engine = Engine()
ace_engine.start()
ace_engine.wait()
except Exception as e:
logging.error("uncaught exception: {}".format(e))
report_exception()
else:
logging.error("You must specify either --start or --stop for this service.")
sys.exit(1)
sys.exit(0)
correlation_engine_parser = subparsers.add_parser('correlation-engine',
help="Start/Stop the ACE correlation analysis engine.")
correlation_engine_parser.set_defaults(func=correlation_engine)
# ============================================================================
# Remediation System
#
def remediation_system(args):
from saq.remediation import initialize_remediation_system_manager, start_remediation_system_manager, stop_remediation_system_manager, wait_remediation_system_manager
daemon_name = 'remediation-system'
if args.stop:
kill_daemon(daemon_name)
sys.exit(0)
elif args.start:
if args.daemon:
logging.info(f"starting daemon {daemon_name}")
daemonize(daemon_name)
try:
initialize_remediation_system_manager()
def handle_signal(signum, frame):
stop_remediation_system_manager(wait=False)
signal.signal(signal.SIGTERM, handle_signal)
signal.signal(signal.SIGINT, handle_signal)
start_remediation_system_manager()
wait_remediation_system_manager()
except KeyboardInterrupt:
stop_remediation_system_manager()
except Exception as e:
logging.error(f"uncaught exception {e}")
sys.exit(1)
sys.exit(0)
else:
logging.error("You must specify either --start or --stop for this service.")
sys.exit(1)
remediation_system_parser = subparsers.add_parser('remediation-system',
help="Starts/stops the remediation system, responsible for implementing remediation requests in the background.")
remediation_system_parser.set_defaults(func=remediation_system)
# ============================================================================
# Message Dispatch System
#
def message_system(args):
from saq.messaging import initialize_message_system, start_message_system, stop_message_system, wait_message_system
daemon_name = 'message-dispatch-system'
if args.stop:
kill_daemon(daemon_name)
sys.exit(0)
elif args.start:
if args.daemon:
logging.info(f"starting daemon {daemon_name}")
daemonize(daemon_name)
try:
initialize_message_system()
def handle_signal(signum, frame):
stop_message_system(wait=False)
signal.signal(signal.SIGTERM, handle_signal)
signal.signal(signal.SIGINT, handle_signal)
start_message_system()
wait_message_system()
except KeyboardInterrupt:
stop_message_system()
except Exception as e:
logging.error(f"uncaught exception {e}")
sys.exit(1)
sys.exit(0)
else:
logging.error("You must specify either --start or --stop for this service.")
sys.exit(1)
message_system_parser = subparsers.add_parser('message-system',
help="Starts/stops the message dispatch system, responsible for dispatching messages to other systems.")
message_system_parser.set_defaults(func=message_system)
# ============================================================================
# start GUI (non-apache version)
#
def start_gui(args):
import saq
from app import create_app, db
from app.models import User
from flask_script import Manager, Shell
app = create_app()
# add the "do" template command
app.jinja_env.add_extension('jinja2.ext.do')
if args.print_uri_paths:
for rule in app.url_map.iter_rules():
print(rule)
sys.exit(0)
app.run(saq.CONFIG.get('gui', 'listen_address'), debug=True, port=saq.CONFIG.getint('gui', 'listen_port'),
ssl_context=(saq.CONFIG.get('gui', 'ssl_cert'), saq.CONFIG.get('gui', 'ssl_key')),
use_reloader=True)
# start-gui
start_gui_parser = subparsers.add_parser('start-gui',
help="Start the SAQ GUI.")
start_gui_parser.add_argument('args', nargs=argparse.REMAINDER,
help="Parameters to pass to the GUI command shell.")
start_gui_parser.add_argument('--print-uri-paths', default=False, action='store_true',
help="Print all of the availble URL paths and exit, without starting the GUI.")
start_gui_parser.set_defaults(func=start_gui)
# ============================================================================
# start API (non-apache version)
#
def start_api(args):
import saq
from api import create_app
app = create_app(testing=True)
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware
from flask import Flask, url_for
app.config['DEBUG'] = True
app.config['APPLICATION_ROOT'] = '/api'
application = DispatcherMiddleware(Flask('dummy_app'), {
app.config['APPLICATION_ROOT']: app,
})
if args.print_uri_paths:
for rule in app.url_map.iter_rules():
print(rule)
sys.exit(0)
run_simple(saq.CONFIG.get('api', 'listen_address'), saq.CONFIG.getint('api', 'listen_port'), application,
ssl_context=(saq.CONFIG.get('api', 'ssl_cert'), saq.CONFIG.get('api', 'ssl_key')),
use_reloader=False)
# start-gui
start_api_parser = subparsers.add_parser('start-api',
help="Start the ACE API server in DEBUG mode.")
start_api_parser.add_argument('args', nargs=argparse.REMAINDER,
help="Parameters to pass to the API command shell.")
start_api_parser.add_argument('--print-uri-paths', default=False, action='store_true',
help="Print all of the availble URL paths and exit, without starting the API.")
start_api_parser.set_defaults(func=start_api)
# ============================================================================
# start/stop the primary ACE engine
#
def ace(args):
from saq.engine import Engine
from saq.error import report_exception
from saq.process_server import initialize_process_server
daemon_name = 'ace'
disable_proxy()
if args.stop:
kill_daemon(daemon_name)
sys.exit(0)
elif args.start:
if args.daemon:
logging.info("starting daemon {}".format(daemon_name))
daemonize(daemon_name)
initialize_process_server()
try:
engine = Engine()
engine.start()
engine.wait()
except KeyboardInterrupt as e:
logging.info("caught user interrupt")
try:
engine.stop()
engine.wait()
except Exception as e:
logging.error("uncaught exception: {}".format(e))
except Exception as e:
logging.error("uncaught exception: {}".format(e))
report_exception()
else:
logging.error("You must specify either --start or --stop for this service.")
sys.exit(1)
sys.exit(0)
# ace-engine
ace_engine_parser = subparsers.add_parser('ace-engine',
help="Start/Stop the Analysis Correlation Engine")
ace_engine_parser.set_defaults(func=ace)
# ============================================================================
# start/stop the carbon black binary collector
#
def cb_binary_collector(args):
from saq.collectors.cb_binaries import CarbonBlackBinaryCollector
from saq.error import report_exception
daemon_name = 'cb_binary'
disable_proxy()
if args.stop:
kill_daemon(daemon_name)
sys.exit(0)
elif args.start:
if args.daemon:
logging.info("starting daemon {}".format(daemon_name))
daemonize(daemon_name)
try: