forked from splunk-soar-connectors/eclecticiq
-
Notifications
You must be signed in to change notification settings - Fork 1
/
eclecticiqapp_connector.py
1785 lines (1461 loc) · 75.2 KB
/
eclecticiqapp_connector.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
# Phantom App imports
import phantom.app as phantom
from phantom.base_connector import BaseConnector
from phantom.action_result import ActionResult
import requests
import json
import urllib
import re
import logging
import datetime
import time
from bs4 import UnicodeDammit
API_PATHS = {
'2.1': {
'auth': '/api/auth',
'group_id_search': '/api/sources/',
'feeds_list': '/private/outgoing-feed-download/',
'feed_info': '/private/outgoing-feeds/',
'feed_content_blocks': '/private/outgoing-feed-download/',
'groups': '/private/groups/',
'entities': '/private/entities/',
'observable_search': '/api/observables/',
'entity_search': '/private/search-all/',
'entity_get': '/private/entities/',
'taxonomy_get': '/private/taxonomies/',
'observables': '/private/search-all/'
}
}
USER_AGENT = 'Phantom Integration'
def format_ts(dt):
return dt.replace(microsecond=0).isoformat() + 'Z'
def format_ts_human(dt):
return dt.replace(microsecond=0).isoformat() + 'Z'
class RetVal(tuple):
def __new__(cls, val1, val2=None):
return tuple.__new__(RetVal, (val1, val2))
class EclecticIQ_api(object):
def __init__(self,
baseurl,
eiq_version,
username,
password,
verify_ssl=True,
proxy_ip=None,
proxy_username=None,
proxy_password=None,
logger=None
):
self.eiq_logging = self.set_logger(logger)
self.eiq_username = username
self.eiq_password = password
self.baseurl = baseurl
self.verify_ssl = self.set_verify_ssl(verify_ssl)
self.proxy_ip = proxy_ip
self.proxy_username = proxy_username
self.proxy_password = proxy_password
self.proxies = self.set_eiq_proxy()
self.eiq_api_version = self.set_eiq_api_version(eiq_version)
self.eiq_datamodel_version = self.set_eiq_datamodel_version(eiq_version)
self.token_expires = 0
self.headers = {
'user-agent': USER_AGENT,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
self.get_outh_token()
def set_logger(self, logger):
if logger is None:
logging.basicConfig(level=logging.INFO)
logger_output = logging.getLogger()
return logger_output
else:
return logger
def set_verify_ssl(self, ssl_status):
if ssl_status in ["1", "True", "true", True]:
return True
elif ssl_status in ["0", "False", "false", False]:
return False
else:
return True
def sanitize_eiq_url(self, eiq_url):
# TD
return
def sanitize_eiq_version(self, eiq_version):
if "." in eiq_version:
eiq_version = re.search(r"^\d+\.\d", eiq_version).group()
return float(eiq_version)
elif re.findall(r"fc\-essentials", eiq_version, flags=re.IGNORECASE):
return "FC-Essentials"
elif re.findall(r"fc\-spotlight", eiq_version, flags=re.IGNORECASE):
return "FC-Spotlight"
else:
# TD check code below
try:
eiq_version = re.search(r"^\d+\.\d", eiq_version).group()
return int(eiq_version)
except ValueError:
pass
def set_eiq_proxy(self):
# TD sanitize proxy?
if self.proxy_ip and self.proxy_username and self.proxy_password:
return {
'http': 'http://{0}{1}{2}{3}{4}{5}'.format(self.proxy_username, ':', self.proxy_password, '@', self.proxy_ip, '/'),
'https': 'http://{0}{1}{2}{3}{4}{5}'.format(self.proxy_username, ':', self.proxy_password, '@', self.proxy_ip, '/'),
}
elif self.proxy_ip:
return {
'http': 'http://{0}{1}'.format(self.proxy_ip, '/'),
'https': 'http://{0}{1}'.format(self.proxy_ip, '/'),
}
else:
return None
def set_eiq_api_version(self, eiq_version):
eiq_version = self.sanitize_eiq_version(eiq_version)
if (isinstance(eiq_version, float) or isinstance(eiq_version, int)) and eiq_version < 2.1:
return '2.0'
elif (isinstance(eiq_version, float) or isinstance(eiq_version, int)) and eiq_version >= 2.1:
return '2.1'
elif re.match(r"FC", eiq_version):
return 'FC'
else:
# TD add warning
return 'WARNING'
def set_eiq_datamodel_version(self, eiq_version):
eiq_version = self.sanitize_eiq_version(eiq_version)
if (isinstance(eiq_version, float) or isinstance(eiq_version, int)) and eiq_version < 2.2:
return "pre2.2"
elif (isinstance(eiq_version, float) or isinstance(eiq_version, int)) and eiq_version >= 2.2:
return "2.2"
elif eiq_version == "FC-Essentials":
return "FC-Essentials"
elif eiq_version == "FC-Spotlight":
return "FC-Spotlight"
else:
# TD add warning
return 'WARNING'
def get_outh_token(self):
self.eiq_logging.info('Authenticating using username: {0}'.format(self.eiq_username))
if (re.match("^[\\dabcdef]{64}$", self.eiq_password)) is None:
try:
r = requests.post(
self.baseurl + API_PATHS[self.eiq_api_version]['auth'],
headers=self.headers,
data=json.dumps({
'username': self.eiq_username,
'password': self.eiq_password
}),
verify=self.verify_ssl,
proxies=self.proxies,
timeout=30
)
if r and r.status_code in [100, 200, 201, 202]:
self.headers['Authorization'] = 'Bearer ' + r.json()['token']
self.token_expires = time.time() + 1500
self.eiq_logging.info('Authentication successful')
else:
if not r:
msg = 'Could not perform auth request to EclecticIQ'
self.eiq_logging.exception(msg)
raise Exception(msg)
try:
err = r.json()
detail = err['errors'][0]['detail']
msg = ('EclecticIQ VA returned an error, code:[{0}], reason:[{1}], URL: [{2}], details:[{3}]'
.format(r.status_code, r.reason, r.url, detail))
except Exception:
msg = ('EclecticIQ VA returned an error, code:[{0}], reason:[{1}], URL: [{2}]'
.format(r.status_code, r.reason, r.url))
raise Exception(msg)
except Exception:
self.eiq_logging.error("Authentication failed")
raise
else:
try:
self.headers['Authorization'] = 'Bearer ' + self.eiq_password
r = requests.get(
self.baseurl + '/api',
headers=self.headers,
verify=self.verify_ssl,
proxies=self.proxies,
timeout=30
)
if r and r.status_code in [100, 200, 201, 202]:
self.token_expires = time.time() + 1500
self.eiq_logging.info('Authentication successful')
else:
if not r:
msg = 'Could not perform auth request to EclecticIQ'
self.eiq_logging.exception(msg)
raise Exception(msg)
try:
err = r.json()
detail = err['errors'][0]['detail']
msg = ('EclecticIQ VA returned an error, code:[{0}], reason:[{1}], URL: [{2}], details:[{3}]'
.format(r.status_code, r.reason, r.url, detail))
except Exception:
msg = ('EclecticIQ VA returned an error, code:[{0}], reason:[{1}], URL: [{2}]'
.format(r.status_code, r.reason, r.url))
raise Exception(msg)
except Exception:
self.eiq_logging.error("Authentication failed")
raise
def send_api_request(self, method, path, params=None, data=None):
if self.token_expires < time.time():
self.get_outh_token()
url = self.baseurl + path
r = None
try:
if method == 'post':
r = requests.post(
url,
headers=self.headers,
params=params,
data=json.dumps(data),
verify=self.verify_ssl,
proxies=self.proxies,
timeout=30
)
elif method == 'get':
r = requests.get(
url,
headers=self.headers,
params=params,
data=json.dumps(data),
verify=self.verify_ssl,
proxies=self.proxies,
timeout=30
)
else:
self.eiq_logging.error("Unknown method: {0}".format(method))
raise Exception
except Exception:
self.eiq_logging.exception(
'Could not perform request to EclecticIQ VA: {0}: {1}'.format(method, url))
if r and r.status_code in [100, 200, 201, 202]:
return r
else:
if not r:
msg = ('Could not perform request to EclecticIQ VA: {0}: {1}'.format(method, url))
self.eiq_logging.exception(msg)
raise Exception(msg)
try:
err = r.json()
detail = err['errors'][0]['detail']
msg = ('EclecticIQ VA returned an error, code:[{0}], reason:[{1}], URL: [{2}], details:[{3}]'
.format(
r.status_code,
r.reason,
r.url,
detail))
except Exception:
msg = ('EclecticIQ VA returned an error, code:[{0}], reason:[{1}], URL: [{2}]').format(
r.status_code,
r.reason,
r.url)
raise Exception(msg)
def get_source_group_uid(self, group_name):
self.eiq_logging.debug("Requesting source id for specified group, name=[\"{0}\"]".format(group_name))
r = self.send_api_request(
'get',
path=API_PATHS[self.eiq_api_version]['groups'],
params='filter[name]={0}'.format(group_name))
if not r.json()['data']:
self.eiq_logging.error(
'Something went wrong fetching the group id. '
'Please note the source group name is case sensitive! '
'Received response:{0}'.format(r.json()))
return "error_in_fetching_group_id"
else:
self.eiq_logging.debug('Source group id received')
self.eiq_logging.debug('Source group id is: {0}'.format(r.json()['data'][0]['source']))
return r.json()['data'][0]['source']
def get_feed_info(self, feed_ids):
self.eiq_logging.info("Requesting feed info for feed id={0}".format(feed_ids))
feed_ids = (feed_ids.replace(" ", "")).split(',')
result = []
if self.eiq_api_version == "FC":
for k in feed_ids:
feed_result = {'id': k, 'created_at': '', 'update_strategy': 'REPLACE', 'packaging_status': 'SUCCESS'}
result.append(feed_result)
self.feeds_info = result
return result
for k in feed_ids:
feed_result = {}
try:
r = self.send_api_request(
'get',
path=API_PATHS[self.eiq_api_version]['feed_info'] + k)
except Exception:
self.eiq_logging.error('Feed id={0} information cannot be requested.'.format(k))
continue
if not r.json()['data']:
self.eiq_logging.error(
'Feed id={0} information cannot be requested. Received response:{1}'.format(k, r.json()))
return "error_in_fetching_feed_info"
else:
self.eiq_logging.debug('Feed id={0} information requested'.format(k))
feed_result['id'] = r.json()['data']['id']
feed_result['created_at'] = r.json()['data']['created_at']
feed_result['update_strategy'] = r.json()['data']['update_strategy']
feed_result['packaging_status'] = r.json()['data']['packaging_status']
feed_result['name'] = r.json()['data']['name']
result.append(feed_result)
self.eiq_logging.debug(
'Feed id={0} information retrieved successfully. Received response: {1}'.format(k, json.dumps(feed_result)))
return result
def download_block_list(self, block):
self.eiq_logging.debug("Downloading block url{0}".format(block))
if self.eiq_api_version == "FC":
block = (str(block)).replace(self.baseurl, '')
r = self.send_api_request('get', path=str(block))
data = r.text
return data
def get_feed_content_blocks(self, feed, feed_last_run=None):
self.eiq_logging.debug("Requesting block list for feed id={0}".format(feed['id']))
if feed_last_run is None:
feed_last_run = {}
feed_last_run['last_ingested'] = None
feed_last_run['created_at'] = None
if feed['packaging_status'] == 'SUCCESS' and feed['update_strategy'] == 'REPLACE':
self.eiq_logging.debug("Requesting block list for REPLACE feed.")
r = self.send_api_request(
'get',
path=API_PATHS[self.eiq_api_version]['feed_content_blocks'] + "{0}/runs/latest".format(feed['id']))
data = r.json()['data']['content_blocks']
if feed_last_run['last_ingested'] == data[-1]:
self.eiq_logging.info(
"Received list contains {0} blocks for feed id={1}.".format(len(data), feed['id']))
return []
self.eiq_logging.info("Received list contains {0} blocks for feed id={1}.".format(len(data), feed['id']))
return data
elif feed['packaging_status'] == 'SUCCESS' and (feed['update_strategy'] in ['APPEND', 'DIFF']):
self.eiq_logging.debug("Requesting block list for {0} feed.".format(feed['update_strategy']))
r = self.send_api_request(
'get',
path=API_PATHS[self.eiq_api_version]['feed_content_blocks'] + "{0}".format(feed['id']))
data = r.json()['data']['content_blocks']
if (feed['created_at'] != feed_last_run['created_at']) or feed_last_run['last_ingested'] is None:
self.eiq_logging.info(
"Received list contains {0} blocks for {1} feed:{2}. Feed created time changed or first run, "
"reingestion of all the feed content.".format(len(data), feed['update_strategy'], feed['id']))
return data
else:
try:
last_ingested_index = data.index(feed_last_run['last_ingested'])
diff_data = data[last_ingested_index + 1:]
self.eiq_logging.info("Received list contains {0} blocks for {1} feed:{2}."
.format(len(diff_data), feed['update_strategy'], feed['id']))
return diff_data
except ValueError:
self.eiq_logging.error("Value of last ingested block not available in Feed {0}.".format(feed['id']))
return None
elif feed['packaging_status'] == 'RUNNING':
self.eiq_logging.info("Feed id={0} is running now. Collecting data is not possible.".format(feed['id']))
else:
self.eiq_logging.info(
"Feed id={0} update strategy is not supported. Use Replace or Diff".format(feed['id']))
def get_group_name(self, group_id):
self.eiq_logging.info("Getting group name by id:{0}".format(group_id))
r = self.send_api_request(
'get',
path=API_PATHS[self.eiq_api_version]['group_id_search'] + str(group_id))
response = json.loads(r.text)
result = {}
result['name'] = response['data'].get('name', 'N/A')
result['type'] = response['data'].get('type', 'N/A')
return result
def lookup_observable(self, value, type):
"""Method lookups specific observable by value and type.
Args:
value: value of Observable
type: type of observable, e.g. ipv4, hash-md5 etc
Returns:
Return dictionary with Observable details:
{created: date and time of creation,
last_updated: last update time,
maliciousness: value of maliciousness,
type: type of Observable from args ,
value: value of Observable from args,
source_name: who produced Observable,
platform_link: direct link o the platform
}
Otherwise returns None.
"""
self.eiq_logging.info("Searching Observable:{0}, type:{1}".format(value, type))
r = self.send_api_request(
'get',
path=API_PATHS[self.eiq_api_version]['observable_search'],
params={'filter[type]': type, 'filter[value]': value})
observable_response = json.loads(r.text)
if observable_response['count'] == 1:
result = {}
result['created'] = str(observable_response['data'][0]['created_at'])[:16]
result['last_updated'] = str(observable_response['data'][0]['last_updated_at'])[:16]
result['maliciousness'] = observable_response['data'][0]['meta']['maliciousness']
result['type'] = observable_response['data'][0]['type']
result['value'] = observable_response['data'][0]['value']
result['source_name'] = ""
for k in observable_response['data'][0]['sources']:
source_lookup_data = self.get_group_name(k)
result['source_name'] += str(source_lookup_data['type']) + ': ' + str(source_lookup_data['name']) + '; '
result['platform_link'] = self.baseurl + "/observables/" + type + "/" + urllib.quote_plus(value)
return result
elif observable_response['count'] > 1:
self.eiq_logging.info("Finding duplicates for observable:{0}, type:{1}, return first one".format(value, type))
result = {}
result['created'] = str(observable_response['data'][0]['created_at'])[:16]
result['last_updated'] = str(observable_response['data'][0]['last_updated_at'])[:16]
result['maliciousness'] = observable_response['data'][0]['meta']['maliciousness']
result['type'] = observable_response['data'][0]['type']
result['value'] = observable_response['data'][0]['value']
for k in observable_response['data'][0]['sources']:
source_lookup_data = self.get_group_name(k)
result['source_name'] += str(source_lookup_data['type']) + ': ' + str(source_lookup_data['name']) + '; '
result['platform_link'] = self.baseurl + "/observables/" + type + "/" + urllib.quote_plus(value)
return result
else:
return None
def get_taxonomy_dict(self):
"""Method returns dictionary with all the available taxonomy in Platform.
Returns:
Return dictionary with {taxonomy ids:taxonomy title}. Otherwise returns False.
"""
self.eiq_logging.info("Get all the taxonomy titles from Platform.")
r = self.send_api_request(
'get',
path=API_PATHS[self.eiq_api_version]['taxonomy_get'])
taxonomy = json.loads(r.text)
taxonomy_dict = {}
for i in taxonomy['data']:
try:
id = i['id']
name = i['name']
taxonomy_dict[id] = name
except KeyError:
continue
if len(taxonomy_dict) > 0:
return taxonomy_dict
else:
return False
def get_entity_by_id(self, entity_id):
"""Method lookups specific entity by Id.
Args:
entity_id: Requested entity Id.
Returns:
Return dictionary with entity details:
{entity_title: value,
entity_type: value,
created_at: value,
source_name: value,
tags_list: [
tag and taxonomy list ...
],
relationships_list: [
{relationship_type: incoming/outgoing,
connected_node: id,
connected_node_type: value,
connected_node_type: value
}
relationship list ...
],
observables_list: [
{value: obs_value,
type: obs_type
},
...
]
}
Otherwise returns False.
"""
self.eiq_logging.info("Looking up Entity {0}.".format(entity_id))
r = self.send_api_request(
'get',
path=API_PATHS[self.eiq_api_version]['entity_get'] + str(entity_id))
parsed_response = json.loads(r.text)
taxonomy = self.get_taxonomy_dict()
result = dict()
result['entity_title'] = parsed_response['data']['meta'].get('title', 'N/A')
result['entity_type'] = parsed_response['data']['data'].get('type', 'N/A')
result['created_at'] = str(parsed_response['data'].get('created_at', 'N/A'))[:16]
source = self.get_group_name(parsed_response['data']['sources'][0].get('source_id', 'N/A'))
result['source_name'] = source['type'] + ': ' + source['name']
result['tags_list'] = []
try:
for i in parsed_response['data']['meta']['tags']:
result['tags_list'].append(i)
except KeyError:
pass
try:
for i in parsed_response['data']['meta']['taxonomy']:
result['tags_list'].append(taxonomy.get(i))
except KeyError:
pass
result['observables_list'] = []
search_result = self.search_entity(entity_id=entity_id)
try:
for i in search_result[0]['_source']['extracts']:
observable_to_add = {'value': i['value'],
'type': i['kind']}
result['observables_list'].append(observable_to_add)
except (KeyError, TypeError):
pass
result['relationships_list'] = []
if len(parsed_response['data']['incoming_stix_relations']) > 0:
for i in parsed_response['data']['incoming_stix_relations']:
relationship_to_add = {'relationship_type': 'incoming',
'connected_node': i['data']['source'],
'connection_type': i['data']['key'],
'connected_node_type': i['data']['source_type']
}
result['relationships_list'].append(relationship_to_add)
if len(parsed_response['data']['outgoing_stix_relations']) > 0:
for i in parsed_response['data']['outgoing_stix_relations']:
relationship_to_add = {'relationship_type': 'outgoing',
'connected_node': i['data']['target'],
'connection_type': i['data']['key'],
'connected_node_type': i['data']['target_type']
}
result['relationships_list'].append(relationship_to_add)
return result
def search_entity(self, entity_value=None, entity_type=None, entity_id=None, observable_value=None):
"""Method search specific entity by specific search conditions.
Note: search works with wildcards for entity value and with strict conditions for everything else.
Also, it's recommended to use this method to lookup entity name based on the entity ID, because it doesnt
return all the relationships.
if you need to find specific entity - search by entity id
if you need to find all the entities with specific observables extracted - search with observable values
Args:
entity_value: entity value to search. add " or * to make search wildcard or strict
entity_type: value to search
entity_id: entity id to search
observable_value: observable value to search inside entity
Returns:
Return dictionary with all the entity details.
Otherwise returns False.
"""
self.eiq_logging.info("Searching Entity:{0} with extracted observable:{1}, type:{2}"
.format(entity_value, observable_value, entity_type))
query_list = []
if entity_value is not None:
if entity_value[0] == '"' and entity_value[-1] == '"':
entity_value = entity_value[1:-1]
entity_value = entity_value.replace('"', '\\"')
entity_value = '"' + entity_value + '"'
else:
entity_value = entity_value.replace('"', '\\"')
query_list.append("data.title:" + entity_value)
if observable_value is not None:
query_list.append(UnicodeDammit("extracts.value:\"" + observable_value + "\"").unicode_markup.encode('utf-8'))
if entity_type is not None:
query_list.append("data.type:" + entity_type)
if entity_id is not None:
query_list.append("id:\"" + entity_id + "\"")
search_dict = {
"query": {
"query_string": {
"query": " AND ".join(query_list)
}
}
}
r = self.send_api_request(
'post',
path=API_PATHS[self.eiq_api_version]['entity_search'],
data=search_dict)
search_response = json.loads(r.text)
if len(search_response['hits']['hits']) > 0:
return search_response['hits']['hits']
else:
return False
def create_entity(self, observable_dict, source_group_name, entity_title, entity_description,
entity_confidence='Medium', entity_tags=[], entity_type='eclecticiq-sighting',
entity_impact_value="None", indicator_type=None):
"""Method creates entity in Platform.
Args:
observable_dict: list of dictionaries with observables to create. Format:
[{
observable_type: "value",
observable_value: value,
observable_maliciousness: high/medium/low,
observable_classification: good/bad
}]
source_group_name: group name in Platform for Source. Case sensitive.
entity_title: value
entity_description: value
entity_confidence: Low/Medium/High
entity_tags: list of strings
entity_type: type of entity. e.g. indicator, ttp, eclecticiq-sighting etc
entity_impact_value: "None", "Unknown", "Low", "Medium", "High"
Returns:
Return created entity id if successful otherwise returns False.
"""
self.eiq_logging.info("Creating Entity in EclecticIQ Platform. Type:{0}, title:{1}"
.format(entity_type, entity_title))
group_id = self.get_source_group_uid(source_group_name)
today = datetime.datetime.utcnow().date()
today_begin = format_ts(datetime.datetime(today.year, today.month, today.day, 0, 0, 0))
threat_start = format_ts(datetime.datetime.utcnow())
observable_dict_to_add = []
record = {}
for i in observable_dict:
record = {}
if entity_type == 'eclecticiq-sighting':
record['link_type'] = "sighted"
else:
record['link_type'] = "observed"
if i.get('observable_maliciousness', "") in ["low", "medium", "high"]:
record['confidence'] = i['observable_maliciousness']
if i.get('observable_classification', "") in ["bad", "good", "unknown"]:
record['classification'] = i['observable_classification']
if i.get('observable_value', ""):
record['value'] = i['observable_value']
else:
continue
if i.get('observable_type', "") in ["asn", "country", "cve", "domain", "email", "email-subject", "file",
"handle",
"hash-md5", "hash-sha1", "hash-sha256", "hash-sha512", "industry",
"ipv4",
"ipv6", "malware", "name", "organization", "port", "snort", "uri",
"yara"]:
record['kind'] = i['observable_type']
else:
continue
observable_dict_to_add.append(record)
if self.eiq_datamodel_version == '2.2':
entity = {"data": {
"data": {
"confidence": {
"type": "confidence",
"value": entity_confidence
},
"description": entity_description,
"description_structuring_format": "html",
"likely_impact": {
"type": "statement",
"value": entity_impact_value,
"value_vocab": "{http://stix.mitre.org/default_vocabularies-1}HighMediumLowVocab-1.0",
},
"type": entity_type,
"title": entity_title,
"security_control": {
"type": "information-source",
"identity": {
"name": "",
"type": "identity"
},
"time": {
"type": "time",
"start_time": today_begin,
"start_time_precision": "second"
}
},
},
"meta": {
"manual_extracts": observable_dict_to_add,
"taxonomy": [],
"estimated_threat_start_time": threat_start,
"tags": entity_tags,
"ingest_time": threat_start
},
"sources": [{
"source_id": group_id
}]
}}
if indicator_type is not None:
entity["data"]["data"]["types"] = []
entity["data"]["data"]["types"].append({"value": indicator_type})
if entity_type == 'eclecticiq-sighting':
entity["data"]["data"]["security_control"]["identity"]["name"] = "3rd party Sightings script"
else:
# TD recheck
entity = {"data": {
"data": {
"confidence": {
"type": "confidence",
"value": "Low"
},
"description": entity_description,
"related_extracts": observable_dict_to_add,
"description_structuring_format": "html",
"type": entity_type,
"title": entity_title,
"security_control": {
"type": "information-source",
"identity": {
"name": "EclecticIQ Platform App for Splunk",
"type": "identity"
},
"time": {
"type": "time",
"start_time": today_begin,
"start_time_precision": "second"
}
},
},
"meta": {
"source": group_id,
"taxonomy": [],
"estimated_threat_start_time": threat_start,
"tags": ["Splunk Alert"],
"ingest_time": threat_start
}
}}
r = self.send_api_request(
'post',
path=API_PATHS[self.eiq_api_version]['entities'],
data=entity)
entity_response = json.loads(r.text)
try:
return entity_response['data']['id']
except KeyError:
return False
def get_observable(self, observable):
self.eiq_logging.info('EclecticIQ_api: Searching for Observable: {0}'.format(observable))
path = API_PATHS[self.eiq_api_version]['observables'] + '?q=extracts.value:' + observable
r = self.send_api_request(
'get',
path=path)
return r.json()
class EclecticiqAppConnector(BaseConnector):
def __init__(self):
super(EclecticiqAppConnector, self).__init__()
self._state = None
self._headers = None
self._base_url = None
def _get_error_message_from_exception(self, e):
""" This function is used to get appropriate error message from the exception.
:param e: Exception object
:return: error message
"""
error_msg = "Unknown error occurred. Please check the asset configuration and|or the action parameters."
try:
if hasattr(e, 'message') and e.message:
error_code = "Error code unavailable"
error_msg = self._unicode_string_handler(e.message)
elif hasattr(e, 'args') and e.args:
if len(e.args) > 1:
error_code = e.args[0]
error_msg = e.args[1]
elif len(e.args) == 1:
error_code = "Error code unavailable"
error_msg = e.args[0]
else:
error_code = "Error code unavailable"
error_msg = "Unknown error occurred. Please check the asset configuration and|or action parameters."
except:
error_code = "Error code unavailable"
error_msg = "Unknown error occurred. Please check the asset configuration and|or action parameters."
try:
error_msg = UnicodeDammit(error_msg).unicode_markup.encode('utf-8')
except:
error_msg = "Unknown error occurred. Please check the asset configuration and|or action parameters."
return error_code, error_msg
def _unicode_string_handler(self, input_str):
"""helper method for handling unicode strings
Arguments:
input_str -- Input string that needs to be processed
Returns:
-- Processed input string based on input_str
"""
try:
if input_str:
return UnicodeDammit(input_str).unicode_markup.encode('utf-8')
except:
self.debug_print("Error ocurred while converting the string")
return input_str
def _handle_on_poll(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
if self._tip_of_id is None:
return RetVal(action_result.set_status(phantom.APP_ERROR, "No Outgoing Feed ID in asset parameters"), None)
artifact_count = param.get("artifact_count", 0)
container_count = param.get("container_count", 0)
try:
feed_info = self.eiq_api.get_feed_info(self._tip_of_id)
if not feed_info:
return action_result.set_status(phantom.APP_ERROR, "Unable to fetch the feed information from the provided Outgoing Feed ID")
except Exception as e:
error_code, error_msg = self._get_error_message_from_exception(e)
return action_result.set_status(phantom.APP_ERROR, "Error connecting to server. Error Code: {0}. Error Message: {1}".format(error_code, error_msg))
if feed_info[0]['update_strategy'] not in ['REPLACE', 'APPEND']:
return action_result.set_status(phantom.APP_ERROR, "Outgoing feed update strategy not supported.")
elif feed_info[0]['packaging_status'] != 'SUCCESS':
return action_result.set_status(phantom.APP_ERROR, "Outgoing feed is running now. Wait for run"
" complete first.")
if feed_info[0]['update_strategy'] == 'REPLACE':
feed_content_block_list = self.eiq_api.get_feed_content_blocks(feed=feed_info[0])
containers_processed = 0
artifacts_processed = 0
for idx, record in enumerate(feed_content_block_list):
if containers_processed >= container_count != 0:
self.send_progress("Reached container polling limit: {0}".format(containers_processed))
return self.set_status(phantom.APP_SUCCESS)
if artifacts_processed >= artifact_count != 0:
self.send_progress("Reached artifacts polling limit: {0}".format(artifacts_processed))
return self.set_status(phantom.APP_SUCCESS)
self.send_progress("Processing block # {0}".format(idx))
downloaded_block = json.loads(self.eiq_api.download_block_list(record))
events = downloaded_block.get('entities', [])
results = []
for i in events:
idref = i['meta'].get('is_unresolved_idref', False)
if i['data']['type'] != "relation" and idref is not True:
container = {}
container['data'] = i
container['source_data_identifier'] = "EIQ Platform, OF: {0}, id#{1}. Entity id:{2}"\
.format(feed_info[0]["name"], feed_info[0]["id"], i['id'])
container['name'] = i['data'].get('title', 'No Title') + " - type: "\
+ i['data'].get('type', 'No Type')
container['id'] = i['id']
if i['meta'].get('tlp_color', "") in ["RED", "AMBER", "GREEN", "WHITE"]:
container['sensitivity'] = i['meta'].get('tlp_color', "").lower()
try:
severity = i['data']['impact']['value']
if severity in ["High", "Medium", "Low"]:
container['severity'] = severity.lower()
except KeyError:
pass
container['tags'] = i["meta"]["tags"]
if len(i["meta"].get("taxonomy_paths", "")) > 0:
for ii in i["meta"]["taxonomy_paths"]:
container['tags'].append(ii[-1])
artifacts = self._create_artifacts_for_event(i)
results.append({'container': container, 'artifacts': artifacts})
containers_processed, artifacts_processed = \
self._save_results(results, containers_processed, artifacts_processed, artifact_count, container_count)