forked from fireeye/HXTool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hx_lib.py
executable file
·1464 lines (1070 loc) · 49.7 KB
/
hx_lib.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 -*-
##########################
### HX REST functions
### Henrik Olsson @FireEye
##########################
try:
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
except ImportError:
print("HXTool requires the 'requests' module, please install it.")
exit(1)
import urllib
import base64
import json
import logging
import datetime
import pickle
import shutil
class HXAPI:
HX_DEFAULT_PORT = 3000
HX_MIN_API_VERSION = 2
DEFAULT_LIMIT = 100000
def __init__(self, hx_host, hx_port = HX_DEFAULT_PORT, headers = None, cookies = None, proxies = None, disable_certificate_verification = True, logger_name = None, default_encoding = 'utf-8'):
if logger_name:
self.logger = logging.getLogger(logger_name)
else:
self.logger = logging.getLogger(__name__)
self.logger.debug('__init__ start.')
self.hx_host = hx_host
self.logger.debug('hx_host set to %s.', self.hx_host)
self.hx_port = hx_port
self.logger.debug('hx_port set to %s.', self.hx_port)
self._session = requests.Session()
if proxies:
if 'use_pac' in proxies and proxies['use_pac'] is True:
try:
from pypac import PACSession, get_pac
pac_url = proxies.get('pac_url', None)
self._session = PACSession(get_pac(pac_url))
except ImportError as e:
print(e)
self.logger.error("PAC support requested by configuration but pypac is not installed. Please install it if you'd like to use PAC files for proxy support")
elif 'https' in proxies:
self._session.proxies = proxies
self.logger.info("Proxy support enabled.")
if headers:
self.logger.debug('Appending additional headers passed to __init__')
self._session.headers.update(headers)
if cookies:
self.logger.debug('Appending additional cookies passed to __init__')
self._session.cookies.update(cookies)
if disable_certificate_verification:
self.logger.info('SSL/TLS certificate verification disabled.')
self._session.verify = False
self.suppress_requests_insecure_warning()
self.hx_user = None
self._hx_password = None
self.auto_renew_token = False
self.fe_token = None
self.api_version = self.HX_MIN_API_VERSION
self.hx_version = [0, 0, 0]
self.default_encoding = default_encoding
self.logger.debug('Encoding set to: %s.', self.default_encoding)
self.logger.debug('__init__ complete.')
###################
## Generic functions
###################
# Mmmm, base64 flavored pickles...
def serialize(self):
return HXAPI.b64(pickle.dumps(self, pickle.HIGHEST_PROTOCOL))
@staticmethod
def deserialize(base64_pickle):
return pickle.loads(HXAPI.b64(base64_pickle, True))
# Loggers don't pickle nicely
def __getstate__(self):
d = self.__dict__.copy()
if 'logger' in d.keys():
d['logger'] = d['logger'].name
return d
def __setstate__(self, d):
if 'logger' in d.keys():
d['logger'] = logging.getLogger(d['logger'])
self.__dict__.update(d)
if not self._session.verify:
self.suppress_requests_insecure_warning()
def suppress_requests_insecure_warning(self):
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
def build_request(self, url, method = 'GET', params = None, data = None, content_type = 'application/json', accept = 'application/json', auth = None):
full_url = "https://{0}:{1}{2}".format(self.hx_host, self.hx_port, url)
self.logger.debug('Creating request.')
request = requests.Request(method = method, url = full_url, params = params, data = data, auth = auth)
self.logger.debug('HTTP method set to: %s', request.method)
request.headers['Accept'] = accept
self.logger.debug('Accept header set to: %s', accept)
if method != 'GET' and method != 'DELETE':
request.headers['Content-Type'] = content_type
self.logger.debug('HTTP method is not GET or DELETE, Content-Type header set to: %s', content_type)
# Set the token here, this ensures the last_use_timestamp is properly updated on each request
api_token = self.get_token()
if api_token:
self.logger.debug("Setting X-FeApi-Token header")
self._session.headers['X-FeApi-Token'] = api_token['token']
pr = self._session.prepare_request(request)
self.logger.debug('Full URL is: %s', pr.url)
self.logger.debug('Request created, returning.')
return pr
def build_api_route(self, api_endpoint, min_api_version = None):
if not min_api_version:
min_api_version = self.api_version
return '/hx/api/v{0}/{1}'.format(min_api_version, api_endpoint)
def build_module_api_route(self, module_name, api_endpoint, min_api_version):
return '/hx/api/plugins/{0}/v{1}/{2}'.format(module_name, min_api_version, api_endpoint)
def handle_response(self, request, multiline_json = False, multiline_json_limit = DEFAULT_LIMIT, stream = False):
response = None
response_data = None
try:
self.logger.debug("Sending request, awaiting response")
response = self._session.send(request, stream = stream)
self.logger.debug("Have response.")
if not response.ok:
response.raise_for_status()
if not response.encoding:
response.encoding = self.default_encoding
# The HX API documentations states that the controller will include a new
# token in the response when the existing token is nearing expiration.
if 'X-FeApi-Token' in response.headers:
self.set_token(response.headers.get('X-FeApi-Token'))
content_type = response.headers.get('Content-Type', None)
if content_type is not None and 'Accept' in request.headers and not (request.headers['Accept'].lower() in content_type.lower()):
self.logger.info("Request Accept header '%s' does not match response Content-Type '%s'", request.headers['Accept'].lower(), content_type.lower())
if content_type is not None and 'json' in content_type.lower():
if multiline_json:
response_data = []
for l in response.iter_lines(chunk_size = 4096, decode_unicode = True):
if l.startswith('{'):
response_data.append(json.loads(l))
if len(response_data) >= multiline_json_limit:
break
else:
response_data = response.json()
else:
response_data = response.text
if response_data.startswith('{'):
self.logger.info("Possible JSON in response without corresponding Content-Type header.")
return(True, response.status_code, response_data, response.headers)
except (requests.exceptions.ChunkedEncodingError, requests.HTTPError, requests.ConnectionError) as e:
if hasattr(e, 'response') and e.response is not None:
# If we get a 401, invalidate the token forcing a re-login
if response.status_code == 401:
self.set_token(None)
response = e.response
# Check if error message is content type JSON
content_type = response.headers.get('Content-Type', None)
if content_type is not None and 'json' in content_type.lower():
response_data = response.json()
else:
response_data = response.text
return(False, response.status_code, response_data, response.headers)
return(False, None, e, None)
finally:
if response:
response.close()
def set_token(self, token):
self.logger.debug('set_token called')
timestamp = HXAPI.dt_to_str(datetime.datetime.utcnow())
if token:
self.fe_token = {'token' : token, 'grant_timestamp' : timestamp, 'last_use_timestamp' : timestamp}
# Removed the code setting the X-FeApi-Token header from here because the last_use_timestamp would never get updated
else:
self.fe_token = None
def get_token(self, update_last_use_timestamp = True):
self.logger.debug("get_token called, update_last_use_timestamp=%s", update_last_use_timestamp)
if not self.fe_token:
self.logger.debug("fe_token is empty.")
elif update_last_use_timestamp:
self.fe_token['last_use_timestamp'] = HXAPI.dt_to_str(datetime.datetime.utcnow())
return(self.fe_token)
def _set_version(self):
(ret, response_code, response_data) = self.restGetControllerVersion()
if ret:
version_string = response_data['data']['msoVersion']
self.hx_version = [int(v) for v in version_string.split('.')]
# TODO: this should be made into a dict
if self.hx_version[0] == 2:
self.api_version = 1
elif self.hx_version[0] == 3:
if self.hx_version[1] < 3:
self.api_version = 2
else:
self.api_version = 3
elif self.hx_version[0] >= 4:
self.api_version = 3
###################
## Generic URL Function
###################
def restGetUrl(self, url, method = 'GET', data = None, include_params=False, limit=DEFAULT_LIMIT, offset=0, share_mode=None, sort_term=None, search_term=None, filter_term={}, query_terms = {}):
params = {}
if include_params:
params = {
'limit' : limit,
'offset' : offset
}
if share_mode:
params['share_mode'] = share_mode
if search_term:
params['search'] = search_term
if sort_term:
params['sort'] = sort_term
params.update(filter_term)
params.update(query_terms)
request = self.build_request(url, method = method, params = params, data = data)
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
###################
## Authentication
###################
# Authenticate and return X-FeApi-Token
# A response code of 204 means that the
# authentication request was sucessful.
# A response code of 401 means that the
# authentication request failed.
# See page 47 in the API guide
def restLogin(self, hx_api_username, hx_api_password, auto_renew_token = False):
request = self.build_request(self.build_api_route('token', min_api_version = 1), auth = (hx_api_username, hx_api_password))
(ret, response_code, response_data, response_headers) = self.handle_response(request)
if ret and response_code == 204 and 'X-FeApi-Token' in response_headers:
self.logger.debug('Token granted.')
self.set_token(response_headers.get('X-FeApi-Token'))
self.hx_user = hx_api_username
self.auto_renew_token = auto_renew_token
if self.auto_renew_token:
self._hx_password = hx_api_password
self._set_version()
else:
ret = False
return(ret, response_code, response_data)
# Logout
# 204 = Success
# 304 = Failed due to missing API token
# See page 746 of the API guide
def restLogout(self):
request = self.build_request(self.build_api_route('token', min_api_version = 1), method = 'DELETE')
(ret, response_code, response_data, response_headers) = self.handle_response(request)
self.logger.debug('Setting token to None.')
self.set_token(None)
return(ret, response_code, response_data)
# Session expire after 15 minutes of inactivity
# or 2.5 hours, whichever comes first.
# See page 47 of the API guide
def restIsSessionValid(self):
is_valid = False
current_token = self.get_token(update_last_use_timestamp=False)
if current_token:
last_use_delta = (datetime.datetime.utcnow() - HXAPI.dt_from_str(current_token['grant_timestamp'])).seconds / 60
grant_time_delta = (datetime.datetime.utcnow() - HXAPI.dt_from_str(current_token['grant_timestamp'])).seconds / 60
self.logger.debug("Token last_use_timestamp is: {}, grant_timestamp is: {}, last_use_delta is: {}, grant_time_delta is: {}".format(current_token['last_use_timestamp'], current_token['grant_timestamp'], last_use_delta, grant_time_delta))
is_valid = (last_use_delta < 15 and grant_time_delta < 150)
if self.auto_renew_token and not is_valid:
self.logger.debug("Token has expired and auto_renew_token is set, renewing token.")
if current_token:
# Make sure we delete/logout the existing token so we don't leave stale ones on the controller
(ret, response_code, response_data) = self.restLogout()
(is_valid, response_code, response_data) = self.restLogin(self.hx_user, self._hx_password, self.auto_renew_token)
return is_valid
def restGetControllerVersion(self):
request = self.build_request(self.build_api_route('version', min_api_version = 1))
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
##################
# Module Support #
##################
def restListModules(self, limit=DEFAULT_LIMIT, offset=0, query_terms = {}):
params = {
'limit' : limit,
'offset' : offset
}
params.update(query_terms)
request = self.build_request('/hx/api/services/plugin', params=params)
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
## IOC Streaming
################
STREAMING_MODULE_NAME = 'ioc-streaming'
STREAMING_MODULE_API_VER = '1'
# List streaming indicators
def restListStreamingIndicators(self, limit=DEFAULT_LIMIT, offset=0, sort_term=None, filter_term={}, query_terms = {}):
params = {
'limit' : limit,
'offset' : offset
}
if sort_term:
params['sort'] = sort_term
if filter_term:
params['filter'] = filter_term
params.update(query_terms)
request = self.build_request(self.buildStreamingIndicatorURI(), params = params)
(ret, response_code, response_data, _) = self.handle_response(request)
return(ret, response_code, response_data)
# List conditions for a streaming indicator
def restListConditionsForStreamingIndicator(self, indicator_id):
request = self.build_request(self.buildStreamingIndicatorURI(indicator_id=indicator_id) + '/conditions')
(ret, response_code, response_data, _) = self.handle_response(request)
# filter out deleted conditions
not_deleted = list(filter(lambda x: x['deleted'] == False, response_data['data']['entries']))
response_data['data']['entries'] = not_deleted
return(ret, response_code, response_data)
# build the URI for the Indicators endpoint. Accommodate a specific indicator if provided
def buildStreamingIndicatorURI(self, api_endpoint='indicators', indicator_id=None):
uri = self.build_module_api_route(module_name=self.STREAMING_MODULE_NAME,
min_api_version=self.STREAMING_MODULE_API_VER,
api_endpoint=api_endpoint)
if indicator_id:
uri += '/{0}'.format(indicator_id)
return uri
# Add a new streaming indicator
def restAddStreamingIndicator(self, ioc_category, display_name, create_text=None, platforms=None, description=None, enabled=True):
data = {
'name' : display_name,
'enabled' : enabled
}
if create_text:
data['created_by'] = create_text
data['updated_by'] = create_text
if platforms:
data['platforms'] = platforms
if description:
data['description'] = description
body = {}
body['indicators'] = []
body['indicators'].append(data)
request = self.build_request(self.buildStreamingIndicatorURI(), method = 'POST', data = json.dumps(body))
(ret, response_code, response_data, _) = self.handle_response(request)
if ret:
response_data = response_data['data']['entries'][0]
return(ret, response_code, response_data)
# Enable/Disable a streaming indicator
def restEnableStreamingIndicator(self, ioc_id, is_enabled = True):
endpoint_suffix = '/enable' if is_enabled else '/disable'
request = self.build_request(self.buildStreamingIndicatorURI(indicator_id=ioc_id) + endpoint_suffix, method = 'POST')
(ret, response_code, response_data, _) = self.handle_response(request)
return(ret, response_code, response_data)
# Add a new streaming condition
def restAddStreamingCondition(self, ioc_category, ioc_id, condition_class, condition_data):
body = {}
body['conditions'] = []
body['conditions'].append(condition_data)
request = self.build_request(self.buildStreamingIndicatorURI(indicator_id=ioc_id) + '/conditions', method = 'POST', data = json.dumps(body))
(ret, response_code, response_data, _) = self.handle_response(request)
return(ret, response_code, response_data)
# Delete a streaming indicator by id
def restDeleteStreamingIndicator(self, indicator_category, ioc_id):
self.restDeleteAllConditionsFromStreamingIndicator(
indicator_category=indicator_category,
ioc_id=ioc_id)
request = self.build_request(self.buildStreamingIndicatorURI(indicator_id=ioc_id), method = 'DELETE')
(ret, response_code, response_data, _) = self.handle_response(request)
return(ret, response_code, response_data)
# Delete a condition from a streaming indicator by id
def restDeleteConditionFromStreamingIndicator(self, indicator_category, ioc_id, condition_id):
# detach the condition from the indicator
request = self.build_request(self.buildStreamingIndicatorURI(indicator_id=ioc_id) + '/conditions/{0}'.format(condition_id), method = 'DELETE')
(ret, response_code, response_data, _) = self.handle_response(request)
# delete the condition
if ret:
request = self.build_request(self.buildStreamingIndicatorURI(api_endpoint='conditions') + '/{0}'.format(condition_id), method = 'DELETE')
(ret, response_code, response_data, _) = self.handle_response(request)
return(ret, response_code, response_data)
# Delete all conditions from a streaming indicator by id
def restDeleteAllConditionsFromStreamingIndicator(self, indicator_category, ioc_id):
(ret, response_code, response_data) = self.restListConditionsForStreamingIndicator(indicator_id=ioc_id)
if ret:
myConditions = response_data['data']['entries']
for condition in myConditions:
condition_id = condition['id']
self.logger.debug('Deleting condition {0} from indicator {1}'.format(condition_id, ioc_id))
(ret_2, response_code, response_data) = self.restDeleteConditionFromStreamingIndicator('', ioc_id=ioc_id, condition_id=condition_id)
if not ret_2:
self.logger.error('Deleting condition {0} from indicator {1} yielded error [{2}] with reason [{3}]'.format(condition_id, ioc_id, response_code, response_data))
ret = ret_2
return(ret, response_code, response_data)
## Indicators
#############
# List indicator categories
def restListCategories(self, limit=DEFAULT_LIMIT, offset=0, share_mode=None, sort_term=None, search_term=None, filter_term={}, query_terms = {}):
endpoint_url = "indicator_categories"
params = {
'limit' : limit,
'offset' : offset
}
if share_mode:
params['share_mode'] = share_mode
if search_term:
params['search'] = search_term
if sort_term:
params['sort'] = sort_term
params.update(filter_term)
params.update(query_terms)
request = self.build_request(self.build_api_route(endpoint_url), params = params)
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# Submit a new category
def restCreateCategory(self, category_name, category_options = {}):
request = self.build_request(self.build_api_route('indicator_categories/{0}'.format(category_name)), method = 'PUT', data = json.dumps(category_options))
request.headers['If-None-Match'] = '*'
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# List all indicators
def restListIndicators(self, limit=DEFAULT_LIMIT, offset=0, share_mode=None, search_term=None, sort_term=None, filter_term={}, query_terms={}):
endpoint_url = "indicators"
params = {
'limit' : limit,
'offset' : offset
}
if share_mode:
params['share_mode'] = share_mode
if search_term:
params['search'] = search_term
if sort_term:
params['sort'] = sort_term
params.update(filter_term)
params.update(query_terms)
request = self.build_request(self.build_api_route(endpoint_url), params = params)
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# Add a new indicator
def restAddIndicator(self, ioc_category, display_name, create_text=None, platforms=None, description=None):
data = {
'display_name' : display_name
}
if create_text:
data['create_text'] = create_text
if platforms:
data['platforms'] = platforms
if description:
data['description'] = description
request = self.build_request(self.build_api_route('indicators/{0}'.format(ioc_category)), method = 'POST', data = json.dumps(data))
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# Delete an indicator by name
def restDeleteIndicator(self, indicator_category, indicator_name):
request = self.build_request(self.build_api_route('indicators/{0}/{1}'.format(indicator_category, indicator_name)), method = 'DELETE')
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# Delete a category
def restDeleteCategory(self, indicator_category):
request = self.build_request(self.build_api_route('indicator_categories/{0}'.format(indicator_category)), method = 'DELETE')
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# List all conditions
# TODO: Add has_alerts and enabled parameters
def restListConditions(self, limit=DEFAULT_LIMIT, offset=0, has_share_mode=None, search_term=None, query_terms={}):
endpoint_url = "conditions"
params = {
'limit' : limit,
'offset' : offset
}
if has_share_mode:
params['has_share_mode'] = has_share_mode
if search_term:
params['search'] = search_term
params.update(query_terms)
request = self.build_request(self.build_api_route(endpoint_url), params = param)
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# Add a new condition
def restAddCondition(self, ioc_category, ioc_guid, condition_class, condition_data):
request = self.build_request(self.build_api_route('indicators/{0}/{1}/conditions/{2}'.format(ioc_category, ioc_guid, condition_class)), method = 'POST', data = condition_data)
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# Grab conditions from an indicator
# NOTE: limit for conditions is hard capped at 10000
def restGetCondition(self, ioc_category, ioc_uri, condition_class, limit=10000):
request = self.build_request(self.build_api_route('indicators/{0}/{1}/conditions/{2}?limit={3}'.format(ioc_category, ioc_uri, condition_class, limit)))
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
def restDeleteCondition(self, ioc_category, ioc_uri, condition_class, condition_uuid):
request = self.build_request(self.build_api_route('indicators/{0}/{1}/conditions/{2}/{3}'.format(ioc_category, ioc_uri, condition_class, condition_uuid)), method = 'DELETE')
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# Get indicator based on condition
def restGetIndicatorFromCondition(self, condition_id):
request = self.build_request(self.build_api_route('conditions/{0}/indicators'.format(condition_id)))
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
def restGetConditionDetails(self, condition_id):
request = self.build_request(self.build_api_route('conditions/{0}'.format(condition_id)))
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
## Acquisitions
###############
def restListAllAcquisitions(self, limit=DEFAULT_LIMIT, offset=0, filter_term={}):
params = {
'limit' : limit,
'offset' : offset
}
params.update(filter_term)
request = self.build_request(self.build_api_route('acqs'), method = 'GET', params = params)
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# Acquire triage
def restAcquireTriage(self, agent_id, timestamp = False):
data = '{}'
if timestamp:
data = json.dumps({'req_timestamp' : timestamp})
request = self.build_request(self.build_api_route('hosts/{0}/triages'.format(agent_id)), method = 'POST', data = data)
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# Acquire file
def restAcquireFile(self, agent_id, path, filename, mode = True):
# Mode = True = API mode
# Mode = False = RAW mode
data = json.dumps({'req_path' : path, 'req_filename' : filename, 'req_use_api' : mode})
request = self.build_request(self.build_api_route('hosts/{0}/files'.format(agent_id)), method = 'POST', data = data)
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
def restNewAcquisition(self, agent_id, scriptname, script, skip_base64 = False):
if not skip_base64:
script = HXAPI.b64(script)
data = json.dumps({'name' : scriptname, 'script' : {'b64' : script}})
request = self.build_request(self.build_api_route('hosts/{0}/live'.format(agent_id)), method = 'POST', data = data)
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# Get File Acquisition Status
def restFileAcquisitionById(self, acq_id):
data = None
request = self.build_request(self.build_api_route('acqs/files/{0}'.format(acq_id)), method = 'GET', data = data)
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# Get Data Acquisition Status
def restDataAcquisitionByID(self, acq_id):
data = None
request = self.build_request(self.build_api_route('acqs/live/{0}'.format(acq_id)), method = 'GET', data = data)
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# Get Data Acquisition Collection
def restDataCollectionByID(self, acq_id):
data = None
request = self.build_request(self.build_api_route('acqs/live/{0}.mans'.format(acq_id)), method = 'GET', data = data)
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# List Bulk Acquisitions
def restListBulkAcquisitions(self, limit=DEFAULT_LIMIT, offset=0, search_term=None, sort_term=None, filter_term={}):
endpoint_url = "acqs/bulk"
params = {
'limit' : limit,
'offset' : offset
}
if search_term:
params['search'] = search_term
if sort_term:
params['sort'] = sort_term
params.update(filter_term)
request = self.build_request(self.build_api_route(endpoint_url), params = params)
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# List hosts in Bulk acquisition
def restListBulkHosts(self, bulk_id, limit=DEFAULT_LIMIT, offset=0, sort_term = {}, filter_term = {}):
endpoint_url = "acqs/bulk/{0}/hosts".format(bulk_id)
params = {
'limit' : limit,
'offset' : offset
}
if sort_term:
params['sort'] = sort_term
params.update(filter_term)
request = self.build_request(self.build_api_route(endpoint_url), params = params)
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# Get the status of a bulk acquisition for a single host
def restGetBulkHost(self, bulk_id, host_id):
request = self.build_request(self.build_api_route('acqs/bulk/{0}/hosts/{1}'.format(bulk_id, host_id)))
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# Get Bulk acquistion detail
def restGetBulkDetails(self, bulk_id):
request = self.build_request(self.build_api_route('acqs/bulk/{0}'.format(bulk_id)))
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# Download an acquisition (file)
def restDownloadFile(self, url, destination_file_path = None, accept = 'application/octet-stream'):
request = self.build_request(url, accept = accept)
try:
response = self._session.send(request, stream = True)
if not response.encoding:
response.encoding = self.default_encoding
if destination_file_path:
with open(destination_file_path, 'wb') as f:
shutil.copyfileobj(response.raw, f)
return(True, response.status_code, None)
else:
return(True, response.status_code, response)
except (requests.HTTPError, requests.ConnectionError) as e:
response_code = None
if e.response:
response_code = e.response.status_code
return(False, response_code, e)
# Delete bulk acquisition file
def restDeleteFile(self, url):
request = self.build_request(self.build_api_route(url), method = 'DELETE')
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# New Bulk acquisition
def restNewBulkAcq(self, script, hostset_id = None, hosts = None, comment = None, platforms = '*', skip_base64=False):
if not skip_base64:
script = HXAPI.b64(script)
data = {'scripts' : [{'platform' : platforms, 'b64' : script}]}
if hostset_id:
data['host_set'] = {'_id' : hostset_id}
elif hosts:
data['hosts'] = hosts
if comment:
data['comment'] = comment
request = self.build_request(self.build_api_route('acqs/bulk'), method = 'POST', data = json.dumps(data))
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
def restRefreshBulkAcq(self, bulk_acquisition_id, state = "ALL"):
request = self.build_request(self.build_api_route('acqs/bulk/{0}/actions/refresh?state={1}'.format(bulk_acquisition_id, state)), method = 'POST')
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# List normal acquisitions
def restListAcquisitions(self):
request = self.build_request(self.build_api_route('acqs'))
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
def restListFileAcquisitionsHost(self, host_id):
request = self.build_request(self.build_api_route('hosts/{0}/files'.format(host_id)))
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
def restListTriageAcquisitionsHost(self, host_id):
request = self.build_request(self.build_api_route('hosts/{0}/triages'.format(host_id)))
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
def restListDataAcquisitionsHost(self, host_id):
request = self.build_request(self.build_api_route('hosts/{0}/live'.format(host_id)))
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
def restListDataAcquisitions(self, limit=DEFAULT_LIMIT, offset=0, search_term=None, sort_term=None, filter_term={}):
endpoint_url = "acqs/live"
params = {
'limit' : limit,
'offset' : offset
}
if search_term:
params['search'] = search_term
if sort_term:
params['sort'] = sort_term
params.update(filter_term)
request = self.build_request(self.build_api_route(endpoint_url), params = params)
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
# List file acquisitions
def restListFileaq(self, limit=DEFAULT_LIMIT, offset=0, search_term=None, sort_term=None, filter_term={}):
endpoint_url = "acqs/files"
params = {
'limit' : limit,
'offset' : offset
}
if search_term:
params['search'] = search_term
if sort_term:
params['sort'] = sort_term
params.update(filter_term)
request = self.build_request(self.build_api_route(endpoint_url), params = params)
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
def restListTriages(self, limit=DEFAULT_LIMIT, offset=0, search_term=None, sort_term=None, filter_term={}):
endpoint_url = "acqs/triages"
params = {
'limit' : limit,
'offset' : offset
}
if search_term:
params['search'] = search_term
if sort_term:
params['sort'] = sort_term
params.update(filter_term)
request = self.build_request(self.build_api_route(endpoint_url), params = params)
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
#######################
## Enterprise Search ##
#######################
def restListSearches(self, limit=DEFAULT_LIMIT, offset=0, sort_term=None, filter_term={}):
endpoint_url = "searches"
params = {
'limit' : limit,
'offset' : offset
}
if sort_term:
params['sort'] = sort_term
params.update(filter_term)
request = self.build_request(self.build_api_route(endpoint_url), params = params)
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
def restSubmitSweep(self, indicator, host_set, ignore_unsupported_items = False, skip_base64 = False, displayname = False):
if not skip_base64:
indicator = HXAPI.b64(indicator)
data = {
'indicator' : indicator,
'host_set' : {'_id' : int(host_set)}
}
if displayname:
data['displayname'] = displayname
params = None
if self.hx_version >= [4,5,0]:
params = {'ignore_unsupported_items' : str(ignore_unsupported_items).lower()}
request = self.build_request(self.build_api_route('searches'), method = 'POST', params = params, data = json.dumps(data))
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
def restCancelJob(self, path, id):
request = self.build_request(self.build_api_route('{0}/{1}/actions/stop'.format(path, id)), method = 'POST')
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
def restDeleteJob(self, path, id):
request = self.build_request(self.build_api_route('{0}/{1}'.format(path, id)), method = 'DELETE')
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
def restGetSearchHosts(self, search_id):
request = self.build_request(self.build_api_route('searches/{0}/hosts?errors=true'.format(search_id)))
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
def restGetSearchResults(self, search_id, limit=DEFAULT_LIMIT):
request = self.build_request(self.build_api_route('searches/{0}/results?limit={1}'.format(search_id, limit)))
(ret, response_code, response_data, response_headers) = self.handle_response(request)
return(ret, response_code, response_data)
##########
# Alerts #
##########
def restGetAlertID(self, alert_id):