This repository has been archived by the owner on Mar 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
ace
executable file
·4543 lines (3678 loc) · 191 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
# PYTHON_ARGCOMPLETE_OK
import argcomplete
import argparse
import atexit
import collections
import datetime
import fnmatch
import getpass
import importlib
import io
import json
import logging
import operator
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="Analysis Correlation Engine")
parser.add_argument('--saq-home', required=False, dest='saq_home', default=None,
help="Sets the base directory of ACE.")
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.
This option can be specified multiple times and each file is loaded in order.""")
#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. Read README.CRYPTO for details.")
parser.add_argument('-P', '--set-decryption-password', dest='set_decryption_password', default=None,
help="Provide the decryption password on the command line. Not secure at all. Don't do it.")
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.debug("removing proxy setting {}".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)
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))
# ============================================================================
# hunting utilities
#
def execute_hunt(args):
import ace_api
import pytz
from saq.constants import event_time_format_tz
from saq.collectors.hunter import HunterCollector
from saq.collectors.query_hunter import QueryHunt
collector = HunterCollector()
collector.load_hunt_managers()
hunt_type, hunt_name = args.hunt.split(':', 1)
if hunt_type not in collector.hunt_managers:
logging.error(f"invalid hunt type {hunt_type}")
sys.exit(1)
collector.hunt_managers[hunt_type].load_hunts_from_config()
hunts = collector.hunt_managers[hunt_type].get_hunts(lambda hunt: hunt_name in hunt.ini_path)
if hunts is None:
logging.error(f"unknown hunt {hunt_name} for type {hunt_type}")
sys.exit(1)
hunt = hunts[0]
if len(hunts) > 1:
logging.warning(f"got {len(hunts)} hunts matching '{hunt_name}' for type {hunt_type}")
for _hunt in hunts:
_ini_name = os.path.basename(_hunt.ini_path).split('.', 1)[0]
logging.warning(f" -> {_hunt.name} @ {_hunt.ini_path} - {_ini_name}")
if hunt_name == _ini_name:
hunt = _hunt
logging.warning(f"going with {hunt.name} @ {hunt.ini_path}...")
# set the Hunt to manual so we don't record the execution timestamps
hunt.manual_hunt = True
exec_kwargs = {}
if isinstance(hunt, QueryHunt):
start_time = datetime.datetime.strptime(args.start_time, '%m/%d/%Y:%H:%M:%S')
end_time = datetime.datetime.strptime(args.end_time, '%m/%d/%Y:%H:%M:%S')
if args.timezone is not None:
start_time = pytz.timezone(args.timezone).localize(start_time)
end_time = pytz.timezone(args.timezone).localize(end_time)
else:
start_time = pytz.utc.localize(start_time)
end_time = pytz.utc.localize(end_time)
exec_kwargs['start_time'] = start_time
exec_kwargs['end_time'] = end_time
hunt.query_result_file = args.query_result_file
if args.json_dir is not None:
os.makedirs(args.json_dir, exist_ok=True)
json_dir_index = 0
for submission in hunt.execute(**exec_kwargs):
print(submission.description)
if args.details:
for o in submission.observables:
output = f"\t(*) {o['type']} - {o['value']}"
if 'time' in o:
output += " - {}".format(o['time'].strftime(event_time_format_tz))
if 'tags' in o:
output += " tags [{}]".format(','.join(o['tags']))
if 'directives' in o:
output += " direc [{}]".format(','.join(o['directives']))
# TODO the other stuff
print(output)
for t in submission.tags:
print(f"\t(+) {t}")
if args.events:
print("BEGIN EVENTS")
for event in submission.details:
print(event)
print("END EVENTS")
if args.json_dir is not None:
buffer = []
for event in submission.details:
buffer.append(event)
target_json_file = os.path.join(args.json_dir, '{}.json'.format(str(json_dir_index)))
with open(target_json_file, 'w') as fp:
json.dump(buffer, fp)
with open(os.path.join(args.json_dir, 'manifest'), 'a') as fp:
fp.write(f'{json_dir_index} = {submission.description}\n')
json_dir_index += 1
if args.submit_alerts is not None:
result = ace_api.submit(
submission.description,
remote_host=args.submit_alerts,
ssl_verification=saq.CONFIG['SSL']['ca_chain_path'],
analysis_mode=submission.analysis_mode,
tool=submission.tool,
tool_instance=submission.tool_instance,
type=submission.type,
event_time=submission.event_time,
details=submission.details,
observables=submission.observables,
tags=submission.tags,
queue=submission.queue,
instructions=submission.instructions,
files=[])
hunt_parser = subparsers.add_parser('hunt')
hunt_sp = hunt_parser.add_subparsers(dest='hunt_cmd')
execute_hunt_parser = hunt_sp.add_parser('execute',
help="Execute a hunt with the given parameters.")
execute_hunt_parser.add_argument('hunt',
help="The name of the hunt to execute in the format type:name where type is the hunt type.")
execute_hunt_parser.add_argument('-s', '--start-time', required=False, default=None,
help="Optional start time. Time spec absolute format is MM/DD/YYYY:HH:MM:SS")
execute_hunt_parser.add_argument('-e', '--end-time', required=False, default=None,
help="Optional end time. Time spec absolute format is MM/DD/YYYY:HH:MM:SS")
execute_hunt_parser.add_argument('-z', '--timezone', required=False, default=None,
help="Optional time zone for start time and end time. Defaults to local time zone.")
execute_hunt_parser.add_argument('-v', '--events', required=False, default=False, action='store_true',
help="Output the events instead of the submissions.")
execute_hunt_parser.add_argument('--json-dir', required=False, default=None,
help="Store the events as JSON files in the given directory, one per submission created.")
execute_hunt_parser.add_argument('-d', '--details', required=False, default=False, action='store_true',
help="Include the details of the submissions in the output.")
execute_hunt_parser.add_argument('--submit-alerts', required=False, default=None,
help="Submit as alerts to the given host[:port]")
execute_hunt_parser.add_argument('--query-result-file', required=False, default=None,
help="Valid only for query hunts. Save the raw query results to the given file.")
execute_hunt_parser.set_defaults(func=execute_hunt)
def verify_hunt(args):
from saq.collectors.hunter import HunterCollector
from saq.collectors.query_hunter import QueryHunt
collector = HunterCollector()
collector.load_hunt_managers()
failed = False
for hunt_type, manager in collector.hunt_managers.items():
manager.load_hunts_from_config()
if manager.failed_ini_files:
sys.stderr.write(f"ERROR: unable to load {len(manager.failed_ini_files)} {hunt_type} hunts\n")
failed = True
if failed:
sys.exit(1)
print("hunt syntax verified")
sys.exit(0)
verify_hunt_parser = hunt_sp.add_parser('verify',
help="Verifies that all configured hunts are able to load.")
verify_hunt_parser.set_defaults(func=verify_hunt)
def list_hunts(args):
from saq.collectors.hunter import HunterCollector
from saq.collectors.query_hunter import QueryHunt
collector = HunterCollector()
collector.load_hunt_managers()
for hunt_type, manager in sorted(collector.hunt_managers.items()):
manager.load_hunts_from_config()
for hunt in sorted(sorted(manager.hunts, key=operator.attrgetter('name')),
key=operator.attrgetter('enabled'), reverse=True):
ini_file = os.path.splitext(os.path.basename(hunt.ini_path))[0]
status = "E" if hunt.enabled else "D"
print(f"{status} {hunt_type}:{ini_file} - {hunt.name}")
sys.exit(0)
list_hunts_parser = hunt_sp.add_parser('list',
help="""List the available hunts.
The format of the output is
E|D type:name - description
E: enabled
D: disabled""")
list_hunts_parser.set_defaults(func=list_hunts)
def list_hunt_types(args):
from saq.collectors.hunter import HunterCollector
from saq.collectors.query_hunter import QueryHunt
collector = HunterCollector()
collector.load_hunt_managers()
for hunt_type in collector.hunt_managers.keys():
print(hunt_type)
sys.exit(0)
list_hunt_types_parser = hunt_sp.add_parser('list-types',
help="List the available hunting types.")
list_hunt_types_parser.set_defaults(func=list_hunt_types)
# ============================================================================
# persistence data
#
persistence_parser = subparsers.add_parser('persistence', aliases=['per'])
persistence_sp = persistence_parser.add_subparsers(dest='persistence_cmd')
def list_persistence(args):
from saq.database import Persistence, PersistenceSource
source_query = saq.db.query(PersistenceSource)
if args.source:
source_query = source_query.filter(PersistenceSource.name.like('%{}%'.format(args.source)))
for source in source_query.order_by(PersistenceSource.name):
if args.keys or args.name:
query = saq.db.query(Persistence).filter(Persistence.source_id == source.id)
if args.name:
query = query.filter(Persistence.uuid.like(f'%{args.name}%'))
if not args.temporal:
query = query.filter(Persistence.permanent == 1)
for persistence in query.order_by(Persistence.uuid):
print(f"{source.name} {persistence.uuid}")
else:
print(source.name)
sys.exit(0)
list_persistence_parser = persistence_sp.add_parser('list',
help="List all persistence sources.")
list_persistence_parser.add_argument('-k', '--keys', action='store_true', default=False,
help="Also display permanent keys. Use --search to narrow down results.")
list_persistence_parser.add_argument('-s', '--source',
help="Search for keys from the given source.")
list_persistence_parser.add_argument('-n', '--name',
help="Search for key names matching the given pattern.")
list_persistence_parser.add_argument('-t', '--temporal', action='store_true', default=False,
help="Also display temporal (non-permanent) keys.")
list_persistence_parser.set_defaults(func=list_persistence)
def clear_persistence(args):
import dateparser
from saq.database import Persistence, PersistenceSource, and_
source = saq.db.query(PersistenceSource).filter(PersistenceSource.name == args.source).first()
if source is None:
logging.error(f"unknown persistence source {args.source}")
sys.exit(1)
if args.all:
result = saq.db.execute(Persistence.__table__.delete().where(Persistence.source_id == source.id))
logging.info(f"persistence group {args.source} cleared {result.rowcount} items")
if not args.dry_run:
saq.db.commit()
sys.exit(0)
elif args.older_than:
target_date = dateparser.parse(args.older_than)
result = saq.db.execute(Persistence.__table__.delete().where(and_(Persistence.source_id == source.id,
Persistence.permanent == 0,
Persistence.last_update < target_date)))
logging.info(f"persistence group {args.source} cleared {result.rowcount} items")
if not args.dry_run:
saq.db.commit()
sys.exit(0)
for key in args.keys:
result = saq.db.execute(Persistence.__table__.delete().where(and_(Persistence.source_id == source.id,
Persistence.uuid == key)))
logging.info(f"persistence group {args.source} key {key} cleared {result.rowcount} items")
if not args.dry_run:
saq.db.commit()
sys.exit(0)
clear_persistence_parser = persistence_sp.add_parser('clear',
help="Clears persistence data for the given source.")
clear_persistence_parser.add_argument('source',
help="The name of the source to clear.")
clear_persistence_parser.add_argument('keys', nargs="*",
help="One or more keys to clear.")
clear_persistence_parser.add_argument('--all', action='store_true', default=False,
help="Clear all persistence data for this source.")
clear_persistence_parser.add_argument('--older-than',
help="Clear all non-permanent persistence data that is older than a given time.")
clear_persistence_parser.add_argument('--dry-run', action='store_true', default=False,
help="Do no commit the changes, only report how many would be cleared out.")
clear_persistence_parser.set_defaults(func=clear_persistence)
# ============================================================================
# microsoft api utilities
#
msapi_parser = subparsers.add_parser('msapi',
help="Interface with Microsoft API integrations.")
msapi_sp = msapi_parser.add_subparsers(dest='msapi_cmd')
graph_parser = msapi_sp.add_parser('graph',
help="MS Graph API utilites")
graph_sp = graph_parser.add_subparsers(dest='graph_cmd')
def export_azure_devices(args):
from saq.graph_api import get_api, execute_and_get_all, execute_request
api = get_api(args.account_name)
if not api:
logging.error(f"no graph api instance loaded for {args.account_name}")
return False
api.initialize()
headers = {'ConsistencyLevel': 'eventual'}
if args.device_count:
headers['Accept'] = 'text/plain'
url = api.build_url(f'v1.0/devices/$count')
results = execute_request(api, url, headers=headers)
print(f"{results} total devices")
return
# get all devices by default
url = api.build_url('v1.0/devices?$top=500')
if args.device_name:
url = api.build_url(f'v1.0/devices?$search="displayName:{args.device_name}"')
results = execute_and_get_all(api, url, headers=headers)
if not results:
return None
if args.stdout or args.device_name:
print(json.dumps(results, indent=2))
return
with open(args.output_file, 'w') as fp:
fp.write(json.dumps(results))
if os.path.exists(args.output_file):
print(f" + wrote: {args.output_file}")
return
export_azure_devices_parser = graph_sp.add_parser('get-devices',
help="Getting and exporting azure devices. WARNING: default is to export all devices to json file.")
export_azure_devices_parser.add_argument(
'--account-name', default='default',
help="The company name of a configured Azure tenant."
)
export_azure_devices_parser.add_argument(
'-d', '--device_name', default=None,
help="Query Azure AD for this device name."
)
export_azure_devices_parser.add_argument(
'-c', '--device_count', action='store_true',
help="Query Azure AD and return a count of devices."
)
export_azure_devices_parser.add_argument(
'-o', '--output_file', default='azure_device_export.json',
help="The name of the file to write results to. Default=azure_device_export.json"
)
export_azure_devices_parser.add_argument(
'--stdout', action='store_true', default=False,
help="Print JSON output to console."
)
export_azure_devices_parser.set_defaults(func=export_azure_devices)
def list_graph_resources(args):
from saq.collectors import graph_collections
grc = graph_collections.GraphResourceCollector()
grc.load_resources()
for r in grc.resources:
print(r)
sys.exit(0)
validate_resource_parser = graph_sp.add_parser('list-resources',
help="Validate graph resource configurations.")
validate_resource_parser.set_defaults(func=list_graph_resources)
def print_collection_accounts(args):
from saq.collectors import graph_collections
grc = graph_collections.GraphResourceCollector()
grc.load_collection_accounts()
for account, value in grc.collection_accounts.items():
print(f"\t{account}: {value}")
sys.exit(0)
print_collection_account_parser = graph_sp.add_parser('print-collection-accounts',
help="print configured collection accounts")
print_collection_account_parser.set_defaults(func=print_collection_accounts)
def get_resource(args):
from saq.graph_api import GraphAPI
from saq.collectors import graph_collections
grc = graph_collections.GraphResourceCollector()
grc.load_resources()
if args.resource not in [r.name for r in grc.resources]:
logging.error(f"no configured resource by the name {args.resource}")
sys.exit(1)
resource = [r for r in grc.resources if r.name == args.resource][0]
logging.info(f"loaded the {resource.name} resource")
if not resource.ready:
print("Supply required arguments:")
for arg in resource.args['required']:
value = input(f"Set {arg}: ")
resource.set_argument(arg, value)
print("Change optional arugments, if you want:")
for arg in resource.args['optional']:
default = resource.args['optional'][arg]
value = input(f"Set {arg} [{default}]: ") or default
resource.set_argument(arg, value)
if not grc.build_graph_api_client_map():
logging.error("failed to get a graph api client.")
sys.exit(1)
graph_api_client = grc.graph_api_clients[resource.graph_account_name]
graph_api_client.initialize()
results = grc.execute_resource(graph_api_client, resource)
# NOTE, not handeling pagination here
if results:
print(json.dumps(results, indent=2, sort_keys=True))
sys.exit(0)
graph_resource_parser = graph_sp.add_parser('get',
help="get a configured resource")
graph_resource_parser.add_argument('resource', action='store',
help="the name of a configured resource")
graph_resource_parser.set_defaults(func=get_resource)
# ============================================================================
# configuration settings
#
def enable_integration(args):
import saq.integration
saq.integration.enable_integration(args.integration)
sys.exit(0)
def disable_integration(args):
import saq.integration
saq.integration.disable_integration(args.integration)
sys.exit(0)
def list_integrations(args):
import saq.integration
saq.integration.list_integrations()
sys.exit(0)
integration_parser = subparsers.add_parser('integration')
integration_sp = integration_parser.add_subparsers(dest='integration_cmd')
enable_integration_parser = integration_sp.add_parser('enable',
help="Enables the given integration.")
enable_integration_parser.add_argument('integration',
help="The integration to enable. Use ace integration list to get the list of available integrations.")
enable_integration_parser.set_defaults(func=enable_integration)
list_integration_parser = integration_sp.add_parser('list',
help="List the available integrations and show enabled/disabled status.")
list_integration_parser.set_defaults(func=list_integrations)
disable_integration_parser = integration_sp.add_parser('disable',
help="Disables the given integration.")
disable_integration_parser.add_argument('integration',
help="The integration to disable. Use ace integration list to get the list of available integrations.")
disable_integration_parser.set_defaults(func=disable_integration)
# ============================================================================
# service control/start/stop
#
service_parser = subparsers.add_parser('service',
help="Service management commands. See ace service --help for details.")
service_sp = service_parser.add_subparsers(dest='service_cmd')
def start_service(args):
import saq.service
# get the list of the services to start
if args.all:
service_names = saq.service.get_all_service_names()
else:
service_names = args.services
# replace any dashes with underscores to make it easier to type
service_names = [_.replace('-', '_') for _ in service_names]
# you can only debug one service at a time
if args.debug and len(service_names) > 1:
logging.error("you can only debug one service at a time")
sys.exit(1)
# if no option is specified then the default is to execute in the background
if not args.daemon and not args.foreground and not args.debug:
args.daemon = True
# check service depedencies and reorder startup
# first iterate over all the dependencies
# if any are listed that are not running yet AND are not in our list to start
# then we bail on startup
dependencies = set() # of service names
for service_name in service_names:
for dep_service_name in saq.service.get_service_dependencies(service_name):
dependencies.add(dep_service_name)
if saq.service.get_service_status(dep_service_name) != saq.service.SERVICE_STATUS_RUNNING:
if dep_service_name not in service_names:
if args.no_deps:
print(f"NOPE: service {service_name} depends on {dep_service_name} and you're not starting it")
sys.exit(1)
service_names.extend(list(dependencies))
targets = []
for service_name in service_names:
targets.append((service_name, saq.service.get_service_dependencies(service_name)))
# https://stackoverflow.com/a/11564323
def topological_sort(source):
"""perform topo sort on elements.
:arg source: list of ``(name, [list of dependancies])`` pairs
:returns: list of names, with dependancies listed first
"""
pending = [(name, set(deps)) for name, deps in source] # copy deps so we can modify set in-place
emitted = []
while pending:
next_pending = []
next_emitted = []
for entry in pending:
name, deps = entry
deps.difference_update(emitted) # remove deps we emitted last pass
if deps: # still has deps? recheck during next pass
next_pending.append(entry)
else: # no more deps? time to emit
yield name
emitted.append(name) # <-- not required, but helps preserve original ordering
next_emitted.append(name) # remember what we emitted for difference_update() in next pass
if not next_emitted: # all entries have unmet deps, one of two things is wrong...
raise ValueError("cyclic or missing dependancy detected: %r" % (next_pending,))
pending = next_pending
emitted = next_emitted
# go ahead and install signal handlers to stop the services we're about to start up
services = [] # of ACEService objects
# at this point we have the list of services we want to start
for service_name in list(topological_sort(targets)): # in the order they need to be started
try:
if saq.service.get_service_status(service_name) == saq.service.SERVICE_STATUS_RUNNING:
continue
service = saq.service.get_service_class(service_name)()
service.start_service(daemon=args.daemon, debug=args.debug, threaded=args.foreground)
services.append(service)
except Exception as e:
logging.error(f"unable to load service {service_name}: {e}")
traceback.print_exc()
sys.exit(1)
# if we're running in daemon mode then we're done here
if args.daemon:
sys.exit(0)
for service in services:
service.wait_service()
sys.exit(0)
start_service_parser = service_sp.add_parser('start',
help="Start ACE services.")
start_service_parser.add_argument('--debug', action='store_true', default=False,
help="Starts the service in debug mode.")
start_service_parser.add_argument('-d', '--daemon', '--background', action='store_true', default=False,
help="Starts the service and then executes in the background, tracking the PID. "
"This is the default if no other option is specified." )
start_service_parser.add_argument('--foreground', action='store_true', default=False,
help="Starts the service and then executes in the foreground, tracking the PID.")
start_service_parser.add_argument('--all', action='store_true', default=False,
help="Starts all enabled services.")
start_service_parser.add_argument('--no-deps', action='store_true', default=False,
help="Do NOT automatically start service dependencies.")
start_service_parser.add_argument('services', nargs="*",
help="The names of the services to start. Use ace service list to get a list of names.")
start_service_parser.set_defaults(func=start_service)
def _stop_service(args):
import saq.service
# get the list of the services to start
if args.all:
service_names = saq.service.get_all_service_names()
else:
service_names = args.services
for service_name in service_names:
service_status = saq.service.get_service_status(service_name)
if service_status is None:
logging.error(f"unknown service {service_name}")
elif service_status == saq.service.SERVICE_STATUS_RUNNING:
logging.info(f"stopping service {service_name}")
saq.service.stop_service(service_name)
else:
if not args.all:
logging.info(f"service {service_name} status already ({service_status})")
def stop_service(args):
_stop_service(args)
sys.exit(0)
stop_service_parser = service_sp.add_parser('stop',
help="Stops the services.")
stop_service_parser.add_argument('--all', action='store_true', default=False,
help="Stops all running services.")
stop_service_parser.add_argument('services', nargs="*",
help="The names of the service to stop. Use ace service list to get a list of names.")
stop_service_parser.set_defaults(func=stop_service)
def restart_service(args):
_stop_service(args)
start_service(args)
restart_service_parser = service_sp.add_parser('restart',
help="Restart ACE services.")
restart_service_parser.add_argument('--debug', action='store_true', default=False,
help="Starts the service in debug mode.")
restart_service_parser.add_argument('-d', '--daemon', '--background', action='store_true', default=False,
help="Starts the service and then executes in the background, tracking the PID. "
"This is the default if no other option is specified." )
restart_service_parser.add_argument('--foreground', action='store_true', default=False,
help="Starts the service and then executes in the foreground, tracking the PID.")
restart_service_parser.add_argument('--all', action='store_true', default=False,
help="Restarts all enabled services.")
restart_service_parser.add_argument('--no-deps', action='store_true', default=False,
help="Do NOT automatically start service dependencies.")
restart_service_parser.add_argument('services', nargs="*",
help="The names of the services to restart. Use ace service list to get a list of names.")
restart_service_parser.set_defaults(func=restart_service)
def status_service(args):
from saq.service import get_all_service_names, get_service_config, get_service_status
print("{:<30}{:<15}{}".format('SERVICE', 'STATUS', 'DESCRIPTION'))
for service_name in get_all_service_names():
service_config = get_service_config(service_name)
print("{:<30}{:<15}{}".format(service_name,
get_service_status(service_name),
service_config.get('description', fallback='?')))
status_service_parser = service_sp.add_parser('status',
help="Lists the available services and their status.")
status_service_parser.set_defaults(func=status_service)
# ============================================================================
# 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: