forked from fireeye/HXTool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhxtool_api.py
executable file
·3578 lines (2964 loc) · 148 KB
/
hxtool_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import random
import csv
from io import BytesIO
from io import StringIO
from collections import deque, defaultdict
import zipfile
try:
from flask import Flask, request, Response, session, redirect, render_template, send_file, g, url_for, abort, Blueprint, current_app as app
except ImportError:
print("hxtool requires the 'Flask' module, please install it.")
exit(1)
import hxtool_logging
from hxtool_vars import HXTOOL_API_VERSION, default_encoding
from hx_lib import *
from hxtool_util import *
from hxtool_data_models import *
from hxtool_scheduler import *
from hxtool_scheduler_task import *
from hxtool_task_modules import *
from hx_openioc import openioc_to_hxioc
ht_api = Blueprint('ht_api', __name__, template_folder='templates')
logger = hxtool_logging.getLogger(__name__)
###################################
# Common User interface endpoints #
###################################
@ht_api.route('/api/v{0}/hostsets/list'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_hostsets_list(hx_api_object):
(ret, response_code, response_data) = hx_api_object.restListHostsets()
if ret:
response_data['data']['entries'].append({
"_id": 9,
"name": "All hosts",
"type": "hidden",
"url": "/hx/api/v3/host_sets/9"
})
(r, rcode) = create_api_response(ret, response_code, response_data)
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/getHealth'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def getHealth(hx_api_object):
myHealth = {}
(ret, response_code, response_data) = hx_api_object.restGetControllerVersion()
if ret:
myHealth['status'] = "OK"
myHealth['version'] = response_data['data']
return(app.response_class(response=json.dumps(myHealth), status=200, mimetype='application/json'))
else:
myHealth['status'] = "FAIL"
return(app.response_class(response=json.dumps(myHealth), status=200, mimetype='application/json'))
@ht_api.route('/api/v{0}/version/get'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_version_get(hx_api_object):
(ret, response_code, response_data) = hx_api_object.restGetControllerVersion()
(r, rcode) = create_api_response(ret, response_code, response_data)
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
#################
# Audit Manager #
#################
@ht_api.route('/api/v{0}/auditmanager/getaudits'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_auditmanager_getaudits(hx_api_object):
r = hxtool_global.hxtool_db.auditGetCollections()
# Grab all bulk acqs so we can use their data to enrich the table
bulk_acqs = {}
(ret, response_code, response_data) = hx_api_object.restListBulkAcquisitions()
if ret:
for entry in response_data['data']['entries']:
bulk_acqs[entry['_id']] = entry
response = {}
mydata = []
for res in r:
row = {}
res_data = eval(res['_id'])
for key, value in res_data.items():
row[key] = value
row['count'] = res['count']
row['action'] = res_data['bulk_acquisition_id']
if res_data['bulk_acquisition_id'] in bulk_acqs.keys():
row['created'] = bulk_acqs[res_data['bulk_acquisition_id']]['create_time']
row['state'] = bulk_acqs[res_data['bulk_acquisition_id']]['state']
row['name'] = bulk_acqs[res_data['bulk_acquisition_id']]['comment']
row['hostset'] = bulk_acqs[res_data['bulk_acquisition_id']]['host_set']['name']
else:
row['created'] = ""
row['state'] = ""
row['name'] = ""
row['hostset'] = ""
mydata.append(row)
response['columns'] = []
for column in list(set().union(*(d.keys() for d in mydata))):
response['columns'].append({ "data": column, "title": column })
response['data'] = mydata
return(app.response_class(response=json.dumps(response), status=200, mimetype='application/json'))
else:
return(app.response_class(response=json.dumps("Unable to list bulk acquisitions"), status=404, mimetype='application/json'))
@ht_api.route('/api/v{0}/auditmanager/remove'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_auditmanager_remove(hx_api_object):
rcode = 200
rmessage = "Audit action remove"
try:
r = hxtool_global.hxtool_db.auditRemove(request.args.get('id'))
except:
rcode = 404
rmessage = "Audit action remove failed"
return(app.response_class(response=json.dumps(rmessage), status=rcode, mimetype='application/json'))
#################
# Audit viewer #
#################
@ht_api.route('/api/v{0}/auditviewer/query'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_auditviewer_query(hx_api_object):
mstr = hxtool_global.hxtool_db.queryParse(request.args.get('q'))
if mstr['type'] == "find":
try:
if 'sort' in mstr.keys():
r = hxtool_global.hxtool_db.auditQuery(mstr['query'], mstr['sort'])
else:
r = hxtool_global.hxtool_db.auditQuery(mstr['query'])
except:
return(app.response_class(response=json.dumps(r), status=404, mimetype='application/json'))
response = {}
mydata = []
for res in r:
row = {
"hostname": res['hostname'],
"generator": res['generator'],
"hx_host": res['hx_host'],
"bulk_acquisition_id": res['bulk_acquisition_id']
}
for key in res[res['generator_item_name']].keys():
row[res['generator_item_name'] + "/" + key] = res[res['generator_item_name']][key]
mydata.append(row)
response['columns'] = []
for column in list(set().union(*(d.keys() for d in mydata))):
response['columns'].append({ "data": column, "title": column })
mynewdata = []
for myrecord in mydata:
for mykey in list(set().union(*(d.keys() for d in mydata))):
if mykey not in myrecord.keys():
myrecord[mykey] = ""
mynewdata.append(myrecord)
response['data'] = mynewdata
if mstr['type'] == "aggregate":
try:
r = hxtool_global.hxtool_db.auditQueryAggregate(mstr['query'])
except:
return(app.response_class(response=json.dumps(r), status=404, mimetype='application/json'))
response = {}
mydata = []
for res in r:
row = {}
res_data = eval(res['_id'])
for key, value in res_data.items():
row[key] = value
row['count'] = res['count']
mydata.append(row)
response['columns'] = []
for column in list(set().union(*(d.keys() for d in mydata))):
response['columns'].append({ "data": column, "title": column })
response['data'] = mydata
return(app.response_class(response=json.dumps(response), status=200, mimetype='application/json'))
################
# Acquisitions #
################
@ht_api.route('/api/v{0}/acquisition/remove'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_acquisition_remove(hx_api_object):
(ret, response_code, response_data) = hx_api_object.restDeleteFile(request.args.get('url'))
(r, rcode) = create_api_response(ret, response_code, response_data)
app.logger.info(format_activity_log(msg="acquisition", action="remove", host=request.args.get('url'), user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/acquisition/get'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_acquisition_get(hx_api_object):
(ret, response_code, response_data) = hx_api_object.restGetUrl(request.args.get('url'))
(r, rcode) = create_api_response(ret, response_code, response_data)
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/acquisition/download'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_acquisition_download(hx_api_object):
if request.args.get('id'):
if request.args.get('content') == "json":
(ret, response_code, response_data) = hx_api_object.restDownloadFile(request.args.get('id'), accept = "application/json")
else:
(ret, response_code, response_data) = hx_api_object.restDownloadFile(request.args.get('id'))
if ret:
flask_response = Response(iter_chunk(response_data))
flask_response.headers['Content-Type'] = response_data.headers['Content-Type']
flask_response.headers['Content-Disposition'] = response_data.headers['Content-Disposition']
app.logger.info(format_activity_log(msg="acquisition", action="download", host=request.args.get('id'), user=session['ht_user'], controller=session['hx_ip']))
return flask_response
else:
(r, rcode) = create_api_response(ret, response_code, response_data)
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
else:
abort(404)
@ht_api.route('/api/v{0}/acquisition/new'.format(HXTOOL_API_VERSION), methods=['GET', 'POST'])
@valid_session_required
def hxtool_api_acquisition_new(hx_api_object):
if request.method == 'POST':
fc = request.files['script']
myscript = fc.read()
myAgentID = request.form.get('id')
myScriptName = request.form.get('scriptname')
do_skip_base64 = False
elif request.method == 'GET':
myscript = hxtool_global.hxtool_db.scriptGet(request.args.get('scriptid'))['script']
do_skip_base64 = True
myAgentID = request.args.get('id')
myScriptName = request.args.get('scriptname')
(ret, response_code, response_data) = hx_api_object.restNewAcquisition(myAgentID, myScriptName, myscript, skip_base64=do_skip_base64)
(r, rcode) = create_api_response(ret, response_code, response_data)
app.logger.info(format_activity_log(msg="acquisition", action="new", host=request.args.get('id'), user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/acquisition/file'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_acquisition_file(hx_api_object):
if request.args.get('type') == "api":
mode = True
if request.args.get('type') == "raw":
mode = False
if 'filepath' in request.args:
if '\\' in request.args.get('filepath'):
fileName = request.args.get('filepath').rsplit("\\", 1)[1]
filePath = request.args.get('filepath').rsplit("\\", 1)[0]
elif '/' in request.args.get('filepath'):
fileName = request.args.get('filepath').rsplit("/", 1)[1]
filePath = request.args.get('filepath').rsplit("/", 1)[0]
elif 'path' in request.args:
filePath = request.args.get('path')
fileName = request.args.get('filename')
(ret, response_code, response_data) = hx_api_object.restAcquireFile(request.args.get('id'), filePath, fileName, mode)
(r, rcode) = create_api_response(ret, response_code, response_data)
app.logger.info(format_activity_log(msg="file acquisition", action="new", host=request.args.get('id'), user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/acquisition/triage'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_acquisition_triage(hx_api_object):
if request.args.get('type') == "standard":
(ret, response_code, response_data) = hx_api_object.restAcquireTriage(request.args.get('id'))
elif request.args.get('type') in ["1", "2", "4", "8"]:
mytime = datetime.datetime.now() - datetime.timedelta(hours = int(request.args.get('type')))
(ret, response_code, response_data) = hx_api_object.restAcquireTriage(request.args.get('id'), mytime.strftime('%Y-%m-%d %H:%M:%S'))
elif request.args.get('type') == "timestamp":
(ret, response_code, response_data) = hx_api_object.restAcquireTriage(request.args.get('id'), request.args.get('timestamp'))
(r, rcode) = create_api_response(ret, response_code, response_data)
app.logger.info(format_activity_log(msg="triage acquisition", action="new", host=request.args.get('id'), user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
#####################
# Enterprise Search #
#####################
# Stop
@ht_api.route('/api/v{0}/enterprise_search/stop'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_enterprise_search_stop(hx_api_object):
(ret, response_code, response_data) = hx_api_object.restCancelJob('searches', request.args.get('id'))
(r, rcode) = create_api_response(ret, response_code, response_data)
app.logger.info(format_activity_log(msg="enterprise search", action="stop", id=request.args.get('id'), user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
# Remove
@ht_api.route('/api/v{0}/enterprise_search/remove'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_enterprise_search_remove(hx_api_object):
(ret, response_code, response_data) = hx_api_object.restDeleteJob('searches', request.args.get('id'))
(r, rcode) = create_api_response(ret, response_code, response_data)
app.logger.info(format_activity_log(msg="enterprise search", action="remove", id=request.args.get('id'), user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
# New search from openioc store
@ht_api.route('/api/v{0}/enterprise_search/new/db'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_enterprise_search_new_db(hx_api_object):
if 'sweephostset' not in request.args or request.args['sweephostset'] == "false":
return(app.response_class(response=json.dumps("Please select a host set."), status=400, mimetype='application/json'))
ioc_script = hxtool_global.hxtool_db.oiocGet(request.args.get('ioc'))
ignore_unsupported_items = True
if 'esskipterms' in request.args.keys():
if request.args.get('esskipterms') == "false":
ignore_unsupported_items = False
else:
ignore_unsupported_items = True
mydisplayname = "N/A"
if 'displayname' in request.args.keys():
mydisplayname = request.args.get("displayname")
(start_time, schedule) = parse_schedule(request.args)
enterprise_search_task = hxtool_scheduler_task(session['ht_profileid'], "Enterprise Search Task", start_time = start_time)
if schedule:
enterprise_search_task.set_schedule(**schedule)
# IOC conditions can be in "event only" or "eventItem" format. The IOC content shipped via DTI
# and available in the Endpoint Supplementary IOCs on the Market use the "event only" format.
# Other IOCs may be in "eventItem" format, depending on how they are created using OpenIOC
# editor. Most importantly, the HX Enterprise Search API expects "eventItem" format. This
# regex adds the necessary "eventItem" prefix to any IOC conditions in "event only" format.
# For example, this regex converts:
# <Context document="processEvent" search="processEvent/process" type="event" />
# to:
# <Context document="eventItem" search="eventItem/processEvent/process" type="event" />
# This will not convert conditions such as:
# <Context document="FileItem" search="FileItem/FullPath" type="endpoint" />
event_item_script = re.sub(
'<Context\s+document="(?!eventItem).+"\s+search="(?!eventItem/)(?P<search>.+Event.+)"\s+type="(?!mir).+"\s+/>',
'<Context document="eventItem" search="eventItem/\g<search>" type="event" />',
HXAPI.b64(ioc_script['ioc'], True).decode('utf-8'),
flags=re.IGNORECASE)
enterprise_search_task.add_step(enterprise_search_task_module, kwargs = {
'script' : HXAPI.b64(event_item_script),
'hostset_id' : request.args.get('sweephostset'),
'ignore_unsupported_items' : ignore_unsupported_items,
'skip_base64': True,
'displayname': mydisplayname
})
hxtool_global.hxtool_scheduler.add(enterprise_search_task)
app.logger.info(format_activity_log(msg="enterprise search", action="new", user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps("OK"), status=200, mimetype='application/json'))
# New search from file
@ht_api.route('/api/v{0}/enterprise_search/new/file'.format(HXTOOL_API_VERSION), methods=['POST'])
@valid_session_required
def hxtool_api_enterprise_search_new_file(hx_api_object):
if 'sweephostset' not in request.form or request.form['sweephostset'] == "false":
return(app.response_class(response=json.dumps("Please select a host set."), status=400, mimetype='application/json'))
fc = request.files['ioc']
ioc_script = fc.read()
ignore_unsupported_items = True
if 'esskipterms' in request.form.keys():
if request.form.get('esskipterms') == "false":
ignore_unsupported_items = False
else:
ignore_unsupported_items = True
mydisplayname = "N/A"
if 'displayname' in request.form.keys():
mydisplayname = request.form.get("displayname")
(start_time, schedule) = parse_schedule(request.form)
enterprise_search_task = hxtool_scheduler_task(session['ht_profileid'], "Enterprise Search Task", start_time = start_time)
if schedule:
enterprise_search_task.set_schedule(**schedule)
# see comment in hxtool_api_enterprise_search_new_db above
event_item_script = re.sub(
'<Context\s+document="(?!eventItem).+"\s+search="(?!eventItem/)(?P<search>.+Event.+)"\s+type="(?!mir).+"\s+/>',
'<Context document="eventItem" search="eventItem/\g<search>" type="event" />',
ioc_script.decode('utf-8'),
flags=re.IGNORECASE)
enterprise_search_task.add_step(enterprise_search_task_module, kwargs = {
'script' : HXAPI.b64(event_item_script),
'hostset_id' : request.form.get('sweephostset'),
'ignore_unsupported_items' : ignore_unsupported_items,
'skip_base64': True,
'displayname': mydisplayname
})
hxtool_global.hxtool_scheduler.add(enterprise_search_task)
app.logger.info(format_activity_log(msg="enterprise search", action="new", user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps("OK"), status=200, mimetype='application/json'))
#########
# Hosts #
#########
@ht_api.route('/api/v{0}/hosts/config'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_hosts_config(hx_api_object):
(ret, response_code, response_data) = hx_api_object.restGetUrl("/hx/api/v3/hosts/" + request.args.get('id') + "/configuration/actual.json")
(r, rcode) = create_api_response(response_data = response_data)
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/hosts/get'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_hosts_get(hx_api_object):
(ret, response_code, response_data) = hx_api_object.restGetHostSummary(request.args.get('id'))
(r, rcode) = create_api_response(response_data = response_data)
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/hosts/sysinfo'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_hosts_sysinfo(hx_api_object):
(ret, response_code, response_data) = hx_api_object.restGetHostSysinfo(request.args.get('id'))
(r, rcode) = create_api_response(response_data = response_data)
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/hosts/contain'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_hosts_contain(hx_api_object):
(ret, response_code, response_data) = hx_api_object.restRequestContainment(request.args.get('id'))
(r, rcode) = create_api_response(response_data = response_data)
app.logger.info(format_activity_log(msg="host action", action="containment request", id=request.args.get('id'), user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/hosts/uncontain'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_hosts_uncontain(hx_api_object):
(ret, response_code, response_data) = hx_api_object.restRemoveContainment(request.args.get('id'))
(r, rcode) = create_api_response(response_data = response_data)
app.logger.info(format_activity_log(msg="host action", action="uncontain", id=request.args.get('id'), user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/hosts/contain/approve'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_hosts_contain_approve(hx_api_object):
(ret, response_code, response_data) = hx_api_object.restApproveContainment(request.args.get('id'))
(r, rcode) = create_api_response(response_data = response_data)
app.logger.info(format_activity_log(msg="host action", action="containment approval", id=request.args.get('id'), user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/hosts/remove'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_hosts_remove(hx_api_object):
(ret, response_code, response_data) = hx_api_object.restDeleteHostByID(request.args.get('id'))
(r, rcode) = create_api_response(response_data = response_data)
app.logger.info(format_activity_log(msg="host action", action="remove", id=request.args.get('id'), user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
###################
# Manage OpenIOCs #
###################
@ht_api.route('/api/v{0}/openioc/view'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_openioc_view(hx_api_object):
storedioc = hxtool_global.hxtool_db.oiocGet(request.args.get('id'))
(r, rcode) = create_api_response(response_data = json.dumps(storedioc))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/openioc/remove'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_openioc_remove(hx_api_object):
hxtool_global.hxtool_db.oiocDelete(request.args.get('id'))
(r, rcode) = create_api_response()
app.logger.info(format_activity_log(msg="openioc action", action="remove", id=request.args.get('id'), user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/openioc/upload'.format(HXTOOL_API_VERSION), methods=['POST'])
@valid_session_required
def hxtool_api_openioc_upload(hx_api_object):
fc = request.files['myioc']
rawioc = fc.read()
hxtool_global.hxtool_db.oiocCreate(request.form['iocname'], HXAPI.b64(rawioc), session['ht_user'])
(r, rcode) = create_api_response(ret=True)
app.logger.info(format_activity_log(msg="openioc action", action="new", name=request.form['iocname'], user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/openioc/download'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_openioc_download(hx_api_object):
myiocData = hxtool_global.hxtool_db.oiocGet(request.args.get('id'))
buffer = BytesIO()
buffer.write(json.dumps(HXAPI.b64(myiocData['ioc'], decode=True, decode_string=True)).encode(default_encoding))
buffer.seek(0)
app.logger.info(format_activity_log(msg="openioc action", action="download", name=myiocData['iocname'], user=session['ht_user'], controller=session['hx_ip']))
return send_file(buffer, attachment_filename=myiocData['iocname'] + ".ioc", as_attachment=True)
##########
# Alerts #
##########
@ht_api.route('/api/v{0}/alerts/remove'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_alerts_remove(hx_api_object):
(ret, response_code, response_data) = hx_api_object.restDeleteJob('alerts', request.args.get('id'))
(r, rcode) = create_api_response(ret, response_code, response_data)
app.logger.info(format_activity_log(msg="alert action", action="remove", id=request.args.get('id'), user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/alerts/get'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_alerts_get(hx_api_object):
(ret, response_code, response_data) = hx_api_object.restGetAlertID(request.args.get('id'))
# Workaround for matching condition which isn't a part of the response
if response_data.get('data', None) is not None and response_data['data']['source'] == "IOC":
# Handle missing indicator object when multiple IOCs hit. ENDPT-52003
if response_data['data'].get('indicator', None) is None:
(cret, cresponse_code, cresponse_data) = hx_api_object.restGetIndicatorFromCondition(response_data['data']['condition']['_id'])
if cret and len(cresponse_data['data']['entries']) > 0:
tlist = [ _['name'] for _ in cresponse_data['data']['entries'] ]
response_data['data'].update({
'indicator' : {
'display_name' : "; ".join(tlist)
}})
(cret, cresponse_code, cresponse_data) = hx_api_object.restGetConditionDetails(response_data['data']['condition']['_id'])
if ret:
response_data['data']['condition']['tests'] = cresponse_data['data']['tests']
(r, rcode) = create_api_response(ret, response_code, response_data)
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
else:
(r, rcode) = create_api_response(ret, response_code, response_data)
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
#####################
# Alert Annotations #
#####################
@ht_api.route('/api/v{0}/annotation/add'.format(HXTOOL_API_VERSION), methods=['POST'])
@valid_session_required
def hxtool_api_annotation_add(hx_api_object):
hxtool_global.hxtool_db.alertCreate(session['ht_profileid'], request.form['id'])
hxtool_global.hxtool_db.alertAddAnnotation(session['ht_profileid'], request.form['id'], request.form['text'], request.form['state'], session['ht_user'])
app.logger.info(format_activity_log(msg="annotation action", action="new", id=request.form['id'], user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps("OK"), status=200, mimetype='application/json'))
@ht_api.route('/api/v{0}/annotation/alert/view'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_annotation_alert_view(hx_api_object):
alertAnnotations = hxtool_global.hxtool_db.alertGet(session['ht_profileid'], request.args.get('id'))
return(app.response_class(response=json.dumps(alertAnnotations), status=200, mimetype='application/json'))
#############
# Scheduler #
#############
@ht_api.route('/api/v{0}/scheduler/remove'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_scheduler_remove(hx_api_object):
key_to_delete = request.args.get('id')
hxtool_global.hxtool_scheduler.remove(key_to_delete, delete_children=True)
app.logger.info(format_activity_log(msg="scheduler action", action="remove", id=key_to_delete, user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps("OK"), status=200, mimetype='application/json'))
@ht_api.route('/api/v{0}/scheduler_health'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def scheduler_health(hx_api_object):
return(app.response_class(response=json.dumps(hxtool_global.hxtool_scheduler.status()), status=200, mimetype='application/json'))
@ht_api.route('/api/v{0}/scheduler_tasks'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def scheduler_tasks(hx_api_object):
mytasks = {}
mytasks['data'] = []
for task in hxtool_global.hxtool_scheduler.tasks():
if not task['parent_id']:
taskstates = {}
for subtask in hxtool_global.hxtool_scheduler.tasks():
if subtask['parent_id'] == task['task_id']:
if not task_states.description.get(subtask['state'], "Unknown") in taskstates.keys():
taskstates[task_states.description.get(subtask['state'], "Unknown")] = 1
else:
taskstates[task_states.description.get(subtask['state'], "Unknown")] += 1
mytasks['data'].append({
"DT_RowId": task['task_id'],
"profile": task['profile_id'],
"profile_name": task['profile_name'],
"child_states": json.dumps(taskstates),
"name": task['name'],
"enabled": task['enabled'],
"last_run": str(task['last_run']),
"next_run": str(task['next_run']),
"immutable": task['immutable'],
"state": task_states.description.get(task['state'], "Unknown"),
"action": task['task_id']
})
return(app.response_class(response=json.dumps(mytasks), status=200, mimetype='application/json'))
################
# Task profile #
################
@ht_api.route('/api/v{0}/taskprofile/remove'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_taskprofile_remove(hx_api_object):
hxtool_global.hxtool_db.taskProfileDelete(request.args.get('id'))
(r, rcode) = create_api_response(ret=True)
app.logger.info(format_activity_log(msg="task profile action", action="remove", id=request.args.get('id'), user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/taskprofile/new'.format(HXTOOL_API_VERSION), methods=['POST'])
@valid_session_required
def hxtool_api_taskprofile_new(hx_api_object):
mydata = request.get_json(silent=True)
hxtool_global.hxtool_db.taskProfileAdd(mydata['name'], session['ht_user'], mydata['params'])
(r, rcode) = create_api_response(ret=True)
app.logger.info(format_activity_log(msg="task profile action", action="new", name=mydata['name'], user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
###############
# Host Groups #
###############
@ht_api.route('/api/v{0}/hostgroups'.format(HXTOOL_API_VERSION), methods=['POST'])
@valid_session_required
def hxtool_api_hostgroup_add(hx_api_object):
hostgroup_data = request.json
hxtool_global.hxtool_db.hostGroupAdd(session['profile_id'], hostgroup_data['name'], session['ht_user'], hostgroup_data['agent_ids'])
(r, rcode) = create_api_response(ret=True)
logger.info(format_activity_log(msg="host group action", action="new", name=hostgroup_data['name'], user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/hostgroups/<uuid:hostgroup_id>'.format(HXTOOL_API_VERSION), methods=['GET', 'DELETE'])
@valid_session_required
def hxtool_api_hostgroup_id(hx_api_object, hostgroup_id):
hostgroup_id = str(hostgroup_id)
if request.method == 'GET':
hostgroup = hxtool_global.hxtool_db.hostGroupGet(hostgroup_id)
if hostgroup:
(r, rcode) = create_api_response(ret=True, response_code=200, response_data=hostgroup)
else:
(r, rcode) = create_api_response(ret=False, response_code=404)
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
elif request.method == 'DELETE':
hxtool_global.hxtool_db.hostGroupRemove(hostgroup_id)
(r, rcode) = create_api_response(ret=True)
logger.info(format_activity_log(msg="host group action", action="remove", hostgroup_id=hostgroup_id, user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
####################
# Bulk Acquisition #
####################
# Remove
@ht_api.route('/api/v{0}/acquisition/bulk/remove'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_acquisition_bulk_remove(hx_api_object):
(ret, response_code, response_data) = hx_api_object.restDeleteJob('acqs/bulk', request.args.get('id'))
(r, rcode) = create_api_response(ret, response_code, response_data)
app.logger.info(format_activity_log(msg="bulk acquisition action", action="remove", id=request.args.get('id'), user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
# Stop
@ht_api.route('/api/v{0}/acquisition/bulk/stop'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_acquisition_bulk_stop(hx_api_object):
(ret, response_code, response_data) = hx_api_object.restCancelJob('acqs/bulk', request.args.get('id'))
(r, rcode) = create_api_response(ret, response_code, response_data)
app.logger.info(format_activity_log(msg="bulk acquisition action", action="stop", id=request.args.get('id'), user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
# Stop download
@ht_api.route('/api/v{0}/acquisition/bulk/stopdownload'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_acquisition_bulk_stopdownload(hx_api_object):
ret = hxtool_global.hxtool_db.bulkDownloadUpdate(request.args.get('id'), stopped = True)
app.logger.info(format_activity_log(msg="bulk acquisition action", action="stop download", id=request.args.get('id'), user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps("OK"), status=200, mimetype='application/json'))
# Download
@ht_api.route('/api/v{0}/acquisition/bulk/download'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_acquisition_bulk_download(hx_api_object):
hostset_id = -1
(ret, response_code, response_data) = hx_api_object.restGetBulkDetails(request.args.get('id'))
if ret:
if 'host_set' in response_data['data']:
hostset_id = int(response_data['data']['host_set']['_id'])
(ret, response_code, response_data) = hx_api_object.restListBulkHosts(request.args.get('id'))
if ret and response_data and len(response_data['data']['entries']) > 0:
bulk_download_eid = hxtool_global.hxtool_db.bulkDownloadCreate(session['ht_profileid'], hostset_id = hostset_id, task_profile = None)
bulk_acquisition_hosts = {}
task_list = []
for host in response_data['data']['entries']:
bulk_acquisition_hosts[host['host']['_id']] = {'downloaded' : False, 'hostname' : host['host']['hostname']}
bulk_acquisition_download_task = hxtool_scheduler_task(session['ht_profileid'], 'Bulk Acquisition Download: {}'.format(host['host']['hostname']))
bulk_acquisition_download_task.add_step(bulk_download_task_module, kwargs = {
'bulk_download_eid' : bulk_download_eid,
'agent_id' : host['host']['_id'],
'host_name' : host['host']['hostname']
})
# This works around a nasty race condition where the task would start before the download job was added to the database
task_list.append(bulk_acquisition_download_task)
hxtool_global.hxtool_db.bulkDownloadUpdate(bulk_download_eid, hosts = bulk_acquisition_hosts, bulk_acquisition_id = int(request.args.get('id')))
hxtool_global.hxtool_scheduler.add_list(task_list)
app.logger.info(format_activity_log(msg="bulk acquisition action", action="download", id=request.args.get('id'), hostset=hostset_id, user=session['ht_user'], controller=session['hx_ip']))
else:
app.logger.warn(format_activity_log(msg="bulk acquisition action", action="download", error="No host entries were returned for bulk acquisition", id=request.args.get('id'), user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps("OK"), status=200, mimetype='application/json'))
# New bulk acquisiton from scriptstore
@ht_api.route('/api/v{0}/acquisition/bulk/new/db'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_acquisition_bulk_new_db(hx_api_object):
if 'bulkhostset' not in request.args or request.args['bulkhostset'] == "false":
return(app.response_class(response=json.dumps("Please select a host set."), status=400, mimetype='application/json'))
(start_time, schedule) = parse_schedule(request.args)
should_download = False
bulk_acquisition_script = hxtool_global.hxtool_db.scriptGet(request.args.get('bulkscript'))['script']
skip_base64 = True
task_profile = None
if request.args.get('taskprocessor') != "false":
task_profile = request.args.get('taskprocessor', None)
should_download = True
submit_bulk_job(bulk_acquisition_script,
hostset_id = int(request.args.get('bulkhostset')),
start_time = start_time,
schedule = schedule,
task_profile = task_profile,
download = should_download,
skip_base64 = skip_base64,
comment=request.args.get('displayname'))
app.logger.info(format_activity_log(msg="bulk acquisition action", action="new", user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps("OK"), status=200, mimetype='application/json'))
# New bulk acquisition from file
@ht_api.route('/api/v{0}/acquisition/bulk/new/file'.format(HXTOOL_API_VERSION), methods=['POST'])
@valid_session_required
def hxtool_api_acquisition_bulk_new_file(hx_api_object):
if 'bulkhostset' not in request.form or request.form['bulkhostset'] == "false":
return(app.response_class(response=json.dumps("Please select a host set."), status=400, mimetype='application/json'))
(start_time, schedule) = parse_schedule(request.form)
bulk_acquisition_script = None
skip_base64 = False
should_download = False
f = request.files['bulkscript']
bulk_acquisition_script = f.read()
task_profile = None
if request.form['taskprocessor'] != "false":
task_profile = request.form.get('taskprocessor', None)
should_download = True
submit_bulk_job(HXAPI.compat_str(bulk_acquisition_script),
hostset_id = int(request.form['bulkhostset']),
start_time = start_time,
schedule = schedule,
task_profile = task_profile,
download = should_download,
skip_base64 = skip_base64,
comment=request.form['displayname'])
app.logger.info(format_activity_log(msg="bulk acquisition action", action="new", user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps("OK"), status=200, mimetype='application/json'))
###########
# Scripts #
###########
@ht_api.route('/api/v{0}/scripts/remove'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_scripts_remove(hx_api_object):
hxtool_global.hxtool_db.scriptDelete(request.args.get('id'))
(r, rcode) = create_api_response(ret=True)
app.logger.info(format_activity_log(msg="script action", action="remove", id=request.args.get('id'), user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/scripts/upload'.format(HXTOOL_API_VERSION), methods=['POST'])
@valid_session_required
def hxtool_api_scripts_upload(hx_api_object):
fc = request.files['myscript']
rawscript = fc.read()
hxtool_global.hxtool_db.scriptCreate(request.form['scriptname'], HXAPI.b64(rawscript), session['ht_user'])
(r, rcode) = create_api_response(ret=True)
app.logger.info(format_activity_log(msg="script action", action="new", name=request.form['scriptname'], user=session['ht_user'], controller=session['hx_ip']))
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/scripts/builder'.format(HXTOOL_API_VERSION), methods=['POST'])
@valid_session_required
def hxtool_api_scripts_builder(hx_api_object):
mydata = request.get_json(silent=True)
hxtool_global.hxtool_db.scriptCreate(mydata['scriptName'], HXAPI.b64(json.dumps(mydata['script'], indent=4).encode()), session['ht_user'])
app.logger.info(format_activity_log(msg="new scriptbuilder acquisiton script", name=mydata['scriptName'], user=session['ht_user'], controller=session['hx_ip']))
(r, rcode) = create_api_response(ret=True)
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/scripts/download'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_scripts_download(hx_api_object):
myscriptData = hxtool_global.hxtool_db.scriptGet(request.args.get('id'))
buffer = BytesIO()
buffer.write(HXAPI.b64(myscriptData['script'], decode=True, decode_string=True).encode(default_encoding))
buffer.seek(0)
app.logger.info(format_activity_log(msg="script action", action="download", id=request.args.get('id'), user=session['ht_user'], controller=session['hx_ip']))
return send_file(buffer, attachment_filename=myscriptData['scriptname'] + ".json", as_attachment=True)
########################
# IOC Streaming API #
########################
@ht_api.route('/api/v{0}/streaming_indicator_category/get_edit_policies'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_streaming_indicator_category_get_edit_policies(hx_api_object):
# streaming indicators don't have categories, so make them up for our own purposes. We just need one of each type.
r = {
'api_success':True,
'api_response_code':200,
'api_response': json.dumps({
"1": "read_only",
"2": "full",
"3": "edit_delete",
"4": "delete"
})
}
return(app.response_class(response=json.dumps(r), status=200, mimetype='application/json'))
@ht_api.route('/api/v{0}/datatable_streaming_indicators'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def datatable_streaming_indicators(hx_api_object):
mydata = {}
mydata['data'] = []
mySort = 'updated_at:desc' #sort most recent updates to the top
myFilter = '{"operator":"eq","field":"deleted","arg":["false"]}' # show only active indicators
(ret, response_code, response_data) = hx_api_object.restListStreamingIndicators(sort_term=mySort, filter_term=myFilter)
if ret:
for indicator in response_data['data']['entries']:
mydata['data'].append(indicator_dict_from_indicator(indicator=indicator, hx_api_object=hx_api_object))
return(app.response_class(response=json.dumps(mydata), status=200, mimetype='application/json'))
@ht_api.route('/api/v{0}/streaming_indicators/get/conditions'.format(HXTOOL_API_VERSION), methods=['GET'])
@valid_session_required
def hxtool_api_streaming_indicators_get_conditions(hx_api_object):
uuid = request.args.get('uuid')
(ret, response_code, condition_class_conditions) = hx_api_object.restListConditionsForStreamingIndicator(indicator_id=uuid)
myconditions = { "conditions": condition_class_conditions }
(r, rcode) = create_api_response(ret, response_code, myconditions)
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/streaming_indicators/enable'.format(HXTOOL_API_VERSION), methods=['POST'])
@valid_session_required
def hxtool_api_streaming_indicators_enable(hx_api_object):
mydata = json.loads(request.form.get('data'))
uuid = mydata['id']
is_enabled = mydata['is_enabled']
(ret, response_code, resp_data) = hx_api_object.restEnableStreamingIndicator(ioc_id=uuid, is_enabled=is_enabled)
(r, rcode) = create_api_response(ret, response_code, resp_data)
return(app.response_class(response=json.dumps(r), status=rcode, mimetype='application/json'))
@ht_api.route('/api/v{0}/streaming_indicators/newOrUpdate'.format(HXTOOL_API_VERSION), methods=['POST'])
@valid_session_required
def hxtool_api_streaming_indicators_newOrUpdate(hx_api_object):
mydata = json.loads(request.form.get('rule'))
'''
Keys within mydata:
'name' - the name of the rule
'description' - the description of the rule
'platform' - the platform assigned to the rule, or 'all'
'originalname' - the original name of the rule
'originalcategory' - the original category of the rule
'iocuri' - the fully qualified uri of the rule, for example:'/hx/api/plugins/ioc-streaming/v1/indicators/e3d70699-4d46-4b3c-8a5b-8d46ef1e22a2'
The uri will be empty if this is a new rule.
'xxx_condition' - The condition to attach. If there are more than one, they will appear in sequence. A condition is not required
'xxx' will be the UUID of the condition. If the condition is a new one, then 'xxx' with be 'undefined'
Each condition is an array of Tests
Keys with Tests:
'case' - boolean to make the comparison case sensitive
'data' - the data to test for within the comparison
'field' - the field for the comparions
'group' - the groupd for the field, for example:'fileWriteEvent'
'negate' - boolean to reverse the sense of the test
'operator' - the comparison operator
'type' - the data type of the field, for example:'text'
'''
mydata['category'] = '' # no value, for now
orig_uri = mydata.get('iocuri') # if None this is a new indicator
if mydata['platform'] == "all":
chosenplatform = ['win', 'osx', 'linux']
else:
chosenplatform = [mydata['platform']]
# Our approach is to simply create a new indicator with conditions (even if this is an update). For an update, we will delete the old condition.
# We do this so that we can roll-back to the original in the case that there is a problem with the update.
# create the new indicator. If this is an update, the orginal will be removed below.
(ret, response_code, response_data) = hx_api_object.restAddStreamingIndicator(
ioc_category=mydata['category'],
display_name=mydata['name'],
create_text=session['ht_user'],
platforms=chosenplatform,
description=mydata['description'])
if ret:
new_ioc_id = response_data['id']
#create each condition for the new indicator
for key, value in mydata.items():
if "_condition" in key:
(form_iocguid, ioctype) = key.split("_")
mytests = {"tests": []}
for test in value: # value is an array of tests
mytests['tests'].append({
"token": test['group'] + "/" + test['field'],
"operator": test['operator'],
"type": test['type'],
"value": test['data'],
"preservecase" : test['case'],
"negate" : test['negate']
})