-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
AnomaliThreatStreamv3.py
2702 lines (2391 loc) · 116 KB
/
AnomaliThreatStreamv3.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
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
import emoji
import traceback
import urllib3
from datetime import date
# Disable insecure warnings
urllib3.disable_warnings()
''' GLOBALS/PARAMS '''
DEFAULT_LIMIT_PAGE_SIZE = 50
REPUTATION_COMMANDS = ['ip', 'domain', 'file', 'url', 'threatstream-email-reputation']
MODEL_TYPE_LIST = ['actor', 'attackpattern', 'campaign', 'courseofaction', 'incident',
'identity', 'infrastructure', 'intrusionset',
'malware', 'signature', 'tipreport', 'ttp', 'tool', 'vulnerability']
PUBLICATION_STATUS_LIST = ['new', 'pending_review', 'review_requested', 'reviewed', 'published']
SIGNATURE_TYPE_LIST = ['Bro', 'Carbon Black Query', 'ClamAV', 'Custom', 'CybOX',
'OpenIOC', 'RSA NetWitness',
'Snort', 'Splunk Query', 'Suricata', 'YARA']
THREAT_STREAM = 'ThreatStream'
NO_INDICATORS_FOUND_MSG = 'No intelligence has been found for {searchable_value}'
DEFAULT_MALICIOUS_THRESHOLD = 65
DEFAULT_SUSPICIOUS_THRESHOLD = 25
HEADERS = {
'Content-Type': 'application/json'
}
IOC_ARGS_TO_INDICATOR_KEY_MAP = {
'domain': {
'domain': 'value',
'dns': 'ip',
'organization': 'org',
'traffic_light_protocol': 'tlp',
'geo_country': 'country',
'creation_date': 'created_ts',
'updated_date': 'modified_ts',
'registrant_name': 'meta.registrant_name',
'registrant_email': 'meta.registrant_email',
'registrant_phone': 'meta.registrant_phone'
},
'url': {
'url': 'value',
'asn': 'asn',
'organization': 'org',
'geo_country': 'country',
'traffic_light_protocol': 'tlp'
},
'ip': {
'ip': 'value',
'asn': 'asn',
'geo_latitude': 'latitude',
'geo_longitude': 'longitude',
'geo_country': 'country',
'traffic_light_protocol': 'tlp'
},
'file': {
'organization': 'org',
'traffic_light_protocol': 'tlp'
}
}
DEFAULT_INDICATOR_MAPPING = {
'asn': 'ASN',
'value': 'Address',
'country': 'Country',
'type': 'Type',
'modified_ts': 'Modified',
'confidence': 'Confidence',
'status': 'Status',
'org': 'Organization',
'source': 'Source',
'tags': 'Tags',
'itype': 'IType',
}
FILE_INDICATOR_MAPPING = {
'modified_ts': 'Modified',
'confidence': 'Confidence',
'status': 'Status',
'source': 'Source',
'subtype': 'Type',
'tags': 'Tags',
'itype': 'IType',
}
INDICATOR_EXTENDED_MAPPING = {
'Value': 'value',
'ID': 'id',
'IType': 'itype',
'Confidence': 'confidence',
'Country': 'country',
'Organization': 'org',
'ASN': 'asn',
'Status': 'status',
'Tags': 'tags',
'Modified': 'modified_ts',
'Source': 'source',
'Type': 'type',
'Severity': 'severity'
}
RELATIONSHIPS_MAPPING = {
'ip': [
{
'name': EntityRelationship.Relationships.RESOLVES_TO,
'raw_field': 'rdns',
'entity_b_type': FeedIndicatorType.Domain
},
{
'name': EntityRelationship.Relationships.INDICATOR_OF,
'raw_field': 'meta.maltype',
'entity_b_type': 'Malware'
}
],
'domain': [
{
'name': EntityRelationship.Relationships.RESOLVED_FROM,
'raw_field': 'ip',
'entity_b_type': FeedIndicatorType.IP
},
{
'name': EntityRelationship.Relationships.INDICATOR_OF,
'raw_field': 'meta.maltype',
'entity_b_type': 'Malware'
}
],
'url': [
{
'name': EntityRelationship.Relationships.RESOLVED_FROM,
'raw_field': 'ip',
'entity_b_type': FeedIndicatorType.IP
},
{
'name': EntityRelationship.Relationships.INDICATOR_OF,
'raw_field': 'meta.maltype',
'entity_b_type': 'Malware'
}
],
'file': [
{
'name': EntityRelationship.Relationships.INDICATOR_OF,
'raw_field': 'meta.maltype',
'entity_b_type': 'Malware'
}
],
'email': [
{
'name': EntityRelationship.Relationships.INDICATOR_OF,
'raw_field': 'meta.maltype',
'entity_b_type': 'Malware'
}
]
}
INTELLIGENCE_TYPES = ['actor', 'signature', 'tipreport', 'ttp', 'vulnerability', 'campaign']
INTELLIGENCE_TYPE_TO_ENTITY_TYPE = {'actor': ThreatIntel.ObjectsNames.THREAT_ACTOR,
'signature': 'Signature',
'vulnerability': FeedIndicatorType.CVE,
'ttp': ThreatIntel.ObjectsNames.ATTACK_PATTERN,
'tipreport': 'Publication',
'campaign': ThreatIntel.ObjectsNames.CAMPAIGN}
INTELLIGENCE_TYPE_TO_CONTEXT = {'actor': 'Actor',
'signature': 'Signature',
'vulnerability': 'Vulnerability',
'ttp': 'TTP',
'tipreport': 'ThreatBulletin',
'campaign': 'Campaign'}
''' HELPER FUNCTIONS '''
class Client(BaseClient):
def __init__(self, base_url, user_name, api_key, verify, proxy, reliability, should_create_relationships, remote_api):
super().__init__(base_url=base_url, verify=verify, proxy=proxy, ok_codes=(200, 201, 202))
self.reliability = reliability
self.should_create_relationships = should_create_relationships
self.credentials = {
'username': user_name,
'api_key': api_key
}
self.remote_api = remote_api
def http_request(self, method,
url_suffix, params=None,
data=None, headers=None,
files=None, json=None,
resp_type='json'):
"""
A wrapper for requests lib to send our requests and handle requests and responses better.
"""
params = params or {}
params.update(self.credentials)
res = super()._http_request(
method=method,
url_suffix=url_suffix,
headers=headers,
params=params,
data=data,
json_data=json,
files=files,
resp_type=resp_type,
error_handler=self.error_handler,
)
return res
def error_handler(self, res: requests.Response): # pragma: no cover
"""
Error handler to call by super().http_request in case an error was occurred
"""
# Handle error responses gracefully
command = demisto.command()
if res.status_code == 401:
if command == 'threatstream-add-threat-model-association':
raise DemistoException(f'{THREAT_STREAM} - Got unauthorized from the server.'
'Make sure that the threat models belongs to your organization.')
if command == 'threatstream-list-import-job':
raise DemistoException(f'{THREAT_STREAM} - Got unauthorized from the server.'
'Make sure that the import job belongs to your organization.')
elif command == 'threatstream-approve-import-job':
raise DemistoException(f'{THREAT_STREAM} - Got unauthorized from the server.'
'Please ensure that you have the necessary Intel user permission and that'
' the import job belongs to your organization.')
else:
raise DemistoException(f"{THREAT_STREAM} - Got unauthorized from the server. Check the credentials.")
elif res.status_code == 204:
return
elif res.status_code in {404}:
if command in ['threatstream-get-model-description', 'threatstream-get-indicators-by-model',
'threatstream-get-analysis-status', 'threatstream-analysis-report']:
# in order to prevent raising en error in case model/indicator/report was not found
return
else:
raise DemistoException(f"{THREAT_STREAM} - The resource was not found.")
raise DemistoException(F"{THREAT_STREAM} - Error in API call {res.status_code} - {res.text}")
def list_rule_request(self, rule_id: Optional[str], params: dict) -> dict:
""" Gets a list of all the rules in ThreatStream.
If a specific rule_id is given, it will return the information about this rule.
Args:
rule_id (int): Unique ID assigned to the rule.
params (dict): The required parameters for the request.
Returns:
A response object in a form of a dictionary.
"""
url_suffix = 'v1/rule/'
if rule_id:
url_suffix += f'{rule_id}/'
return self.http_request('GET', url_suffix, params=params)
params['order_by'] = '-created_ts'
return self.http_request('GET', url_suffix, params=params)
def create_rule_request(self, request_body: dict) -> dict:
""" Creates a rule in ThreatStream.
Args:
request_body (dict): The request body.
Returns:
A response object in a form of a dictionary.
"""
return self.http_request('POST', 'v1/rule/', json=request_body)
def update_rule_request(self, rule_id: Optional[str], request_body: dict) -> dict:
""" Updates a rule in ThreatStream.
Args:
rule_id (dict): The rule ID.
request_body (dict): The request body.
Returns:
A response object in a form of a dictionary.
"""
return self.http_request('PATCH', f'v1/rule/{rule_id}/', json=request_body)
def delete_rule_request(self, rule_id: Optional[str]):
""" Deletes a rule in ThreatStream.
Args:
rule_id (dict): The rule ID.
Returns:
None.
"""
self.http_request('DELETE', f'v1/rule/{rule_id}/', resp_type='text')
def list_users_request(self, user_id: Optional[str], params: dict):
""" Gets a list of all the users in ThreatStream.
If a specific user_id is given, it will return the information about this user.
Args:
user_id (int): Unique ID assigned to the user.
params (dict): The request params.
Returns:
A response object in a form of a dictionary.
"""
url_suffix = 'v1/orgadmin/'
if user_id:
url_suffix += f'{user_id}/'
return self.http_request('GET', url_suffix)
return self.http_request('GET', url_suffix, params=params)
def list_investigation_request(self, investigation_id: Optional[str], params: dict):
""" Gets a list of all the investigations in ThreatStream.
If a specific investigation_id is given, it will return the information about this investigation.
Args:
user_id (int): Unique ID assigned to the investigation.
params (dict): The request params.
Returns:
A response object in a form of a dictionary.
"""
url_suffix = 'v1/investigation/'
if investigation_id:
url_suffix += f'{investigation_id}/'
return self.http_request('GET', url_suffix)
params['order_by'] = '-created_ts'
return self.http_request('GET', url_suffix, params=params)
def create_investigation_request(self, request_body: dict) -> dict:
""" Creats an investigation in ThreatStream.
Args:
request_body (dict): The request body.
Returns:
A response object in a form of a dictionary.
"""
url_suffix = 'v1/investigation/'
return self.http_request('POST', url_suffix, json=request_body)
def delete_investigation_request(self, investigation_id: Optional[str]):
""" Deletes an investigation in ThreatStream.
Args:
investigation_id (dict): The investigation ID.
Returns:
None.
"""
url_suffix = f'v1/investigation/{investigation_id}/'
self.http_request('DELETE', url_suffix, resp_type='text')
def update_investigation_request(self, investigation_id: Optional[str], request_body: dict) -> dict:
""" Updates an investigation in ThreatStream.
Args:
investigation_id (dict): The investigation ID.
request_body (dict): The request body.
Returns:
A response object in a form of a dictionary.
"""
url_suffix = f'v1/investigation/{investigation_id}/'
return self.http_request('PATCH', url_suffix, json=request_body)
def add_investigation_element_request(self, investigation_id: Optional[int], request_body: dict) -> dict:
""" Adds investigation elements to investigation.
Args:
investigation_id (dict): The rule ID.
request_body (dict): The request body.
Returns:
A response object in a form of a dictionary.
"""
url_suffix = 'v1/investigationelement/'
return self.http_request('POST', url_suffix, json=request_body, params={'investigation_id': investigation_id})
def list_whitelist_entry_request(self, format: str, params: dict) -> dict:
""" Gets a list of all whitelist entry in ThreatStream.
Args:
format (str): A URL parameter to define the format of the response CSV or JSON.
params (dict): The request params.
Returns:
A response object in a form of a dictionary.
"""
params['format'] = format.lower() if format else 'json'
params['showNote'] = 'true'
params['order_by'] = '-created_ts'
if format and format.lower() == 'json':
return self.http_request('GET', 'v1/orgwhitelist/', params=params)
return self.http_request('GET', 'v1/orgwhitelist/', params=params, resp_type='text')
def create_whitelist_entry_with_file_request(self, file_data: dict) -> dict:
""" Creates a whitelist entries in ThreatStream according to file data.
Args:
file_path (str): The path of the file.
Returns:
A response object in a form of a dictionary.
"""
return self.http_request('POST', 'v1/orgwhitelist/upload/', params={'remove_existing': 'false'},
files=file_data)
def create_whitelist_entry_without_file_request(self, whitelist: list) -> dict:
""" Creates a whitelist entries in ThreatStream according to arguments data.
Args:
whitelist (str): List of indicators.
Returns:
A response object in a form of a dictionary.
"""
return self.http_request('POST', 'v1/orgwhitelist/bulk/', json=assign_params(whitelist=whitelist))
def update_whitelist_entry_note_request(self, entry_id: Optional[str], note: Optional[str]):
""" Updates a whitelist entry note in ThreatStream.
Args:
entry_id (str): Unique ID assigned to the entry.
"""
url_suffix = f'v1/orgwhitelist/{entry_id}/'
self.http_request('PATCH', url_suffix, data=json.dumps(assign_params(notes=note)), resp_type='text')
def delete_whitelist_entry_request(self, entry_id: Optional[str]):
""" Deletes a whitelist entry in ThreatStream.
Args:
entry_id (str): Unique ID assigned to the entry.
"""
self.http_request('DELETE', f'v1/orgwhitelist/{entry_id}/', resp_type='text')
def list_import_job_request(self, import_id: Optional[str], params: dict) -> dict:
""" Gets a list of all the import job in ThreatStream.
If a specific import_id is given, it will return the information about this import.
Args:
import_id (int): Unique ID assigned to the import.
params (dict): The request params.
Returns:
A response object in a form of a dictionary.
"""
url_suffix = 'v1/importsession/'
if import_id:
url_suffix = f'v1/importsession/{import_id}/'
return self.http_request('GET', url_suffix, params=params)
def approve_import_job_request(self, import_id: Optional[str]) -> dict:
"""
Approving all observables in an import job
Args:
import_id (Str): The id of a specific import entry.
Returns:
A response object in a form of a dictionary.
"""
url_suffix = f'v1/importsession/{import_id}/approve_all/'
return self.http_request('PATCH', url_suffix)
def search_threat_model_request(self, params: dict) -> dict:
"""
Gets list of threat model according to search parameters
Args:
params (dict): The request params.
Returns:
A response object in a form of a dictionary.
"""
return self.http_request('GET', 'v1/threat_model_search/', params=params)
def add_threat_model_association_request(self, entity_type_url: Optional[str], entity_id: Optional[str],
associated_entity_type_url: Optional[str],
associated_entity_ids_list: Optional[list]) -> dict:
"""
Addes association between threat models
Args:
entity_type (Str): The type of threat model entity on which you are adding the association.
entity_id (Str): The ID of the threat model entity on which you are adding the association.
associated_entity_type (Str): The type of threat model entity on which you are adding the association.
associated_entity_ids (Str): The entity id we want to associate with the primary entity.
Returns:
A response object in a form of a dictionary.
"""
url_suffix = f'v1/{entity_type_url}/{entity_id}/{associated_entity_type_url}/bulk_add/'
return self.http_request("POST", url_suffix,
json={'ids': associated_entity_ids_list})
def add_indicator_tag(self, indicator_ids: list[str], tags: list[str]):
data_request = {
"ids": indicator_ids,
"tags": [{"name": tag, "tlp": "red"} for tag in tags],
}
self.http_request(
method="POST",
url_suffix="v2/intelligence/bulk_tagging/",
data=json.dumps(data_request))
def remove_indicator_tag(self, indicator_ids: list[str], tags: list[str]):
data_request = {
"ids": indicator_ids,
"tags": [{"name": tags}],
}
self.http_request(
method="PATCH",
url_suffix="v2/intelligence/bulk_remove_tags/",
data=json.dumps(data_request))
class DBotScoreCalculator:
"""
Class for DBot score calculation based on thresholds and confidence
"""
def __init__(self, params: Dict):
self.instance_defined_thresholds = {
DBotScoreType.IP: arg_to_number(params.get('ip_threshold')),
DBotScoreType.URL: arg_to_number(params.get('url_threshold')),
DBotScoreType.FILE: arg_to_number(params.get('file_threshold')),
DBotScoreType.DOMAIN: arg_to_number(params.get('domain_threshold')),
DBotScoreType.EMAIL: arg_to_number(params.get('email_threshold')),
}
indicator_default_score = params.get('indicator_default_score')
if indicator_default_score and indicator_default_score == 'Unknown':
self.default_score = Common.DBotScore.NONE
else:
self.default_score = Common.DBotScore.GOOD
def calculate_score(self, ioc_type: str, indicator, threshold=None):
"""
Calculate the DBot score according the indicator's confidence and thresholds if exist
"""
# in case threshold was defined in the instance or passed as argument
# we have only two scores levels - malicious or good
# if threshold wasn't defined we have three score levels malicious suspicious and good
confidence = indicator.get('confidence', Common.DBotScore.NONE)
defined_threshold = threshold or self.instance_defined_thresholds.get(ioc_type)
if defined_threshold:
return Common.DBotScore.BAD if confidence >= defined_threshold else self.default_score
else:
if confidence > DEFAULT_MALICIOUS_THRESHOLD:
return Common.DBotScore.BAD
if confidence > DEFAULT_SUSPICIOUS_THRESHOLD:
return Common.DBotScore.SUSPICIOUS
else:
return self.default_score
def find_worst_indicator(indicators):
"""
Sorts list of indicators by confidence score and returns one indicator with the highest confidence.
In case the indicator has no confidence value, the indicator score is set to 0 (NONE).
"""
indicators.sort(key=lambda ioc: ioc.get('confidence', Common.DBotScore.NONE), reverse=True)
return indicators[0]
def prepare_args(args, command, params):
# removing empty keys that can be passed from playbook input
args = {k: v for (k, v) in args.items() if v}
# special handling for ip, domain, file, url and threatstream-email-reputation commands
if command in REPUTATION_COMMANDS:
default_include_inactive = params.get('include_inactive', False)
include_inactive = argToBoolean(args.pop('include_inactive', default_include_inactive))
args['status'] = "active,inactive" if include_inactive else "active"
if 'threshold' in args:
args['threshold'] = arg_to_number(args['threshold'])
if 'threat_model_association' in args:
args['threat_model_association'] = argToBoolean(args.pop('threat_model_association', False))
# special handling for threatstream-get-indicators
if 'indicator_severity' in args:
args['meta.severity'] = args.pop('indicator_severity', None)
if 'tags_name' in args:
args['tags.name'] = args.pop('tags_name', None)
if 'indicator_value' in args:
args['value'] = args.pop('indicator_value', None)
return args
def get_tags(indicator):
"""
Return list of the indicator's tags threat_type and maltype
"""
tags = []
for key in ['meta.maltype', 'threat_type']:
val = demisto.get(indicator, key)
if val:
tags.append(val)
indicator_tags = indicator.get('tags', [])
if indicator_tags:
tags.extend([str(tag.get('name', '')) for tag in indicator_tags])
return tags
def search_worst_indicator_by_params(client: Client, params):
"""
Generic function that searches for indicators from ThreatStream by given query string.
Returns indicator with the highest confidence score.
"""
indicators_data = client.http_request("Get", "v2/intelligence/", params=params)
if not indicators_data['objects']:
return None
return find_worst_indicator(indicators_data['objects'])
def get_generic_threat_context(indicator, indicator_mapping=DEFAULT_INDICATOR_MAPPING):
"""
Receives indicator and builds new dictionary from values that were defined in
DEFAULT_INDICATOR_MAPPING keys and adds the Severity key with indicator severity value.
"""
context = {indicator_mapping[k]: v for (k, v) in indicator.items()
if k in indicator_mapping}
context['Tags'] = get_tags(indicator)
context['Severity'] = demisto.get(indicator, 'meta.severity') or 'low'
return context
def parse_network_elem(element_list, context_prefix):
"""
Parses the network elements list and returns a new dictionary.
"""
return [{
F'{context_prefix}Source': e.get('src', ''),
F'{context_prefix}Destination': e.get('dst', ''),
F'{context_prefix}Port': e.get('dport', ''),
} for e in element_list]
def parse_network_lists(network):
"""
Parses the network part that was received from sandbox report json.
In each list, only sublist of 10 elements is taken.
"""
hosts = [{'Hosts': h} for h in network.get('hosts', [])[:10]]
if 'packets' in network:
network = network['packets']
udp_list = parse_network_elem(network.get('udp', [])[:10], 'Udp')
icmp_list = parse_network_elem(network.get('icmp', [])[:10], 'Icmp')
tcp_list = parse_network_elem(network.get('tcp', [])[:10], 'Tcp')
http_list = parse_network_elem(network.get('http', [])[:10], 'Http')
https_list = parse_network_elem(network.get('https', [])[:10], 'Https')
network_result = udp_list + icmp_list + tcp_list + http_list + https_list + hosts
return network_result
def parse_info(info):
"""
Parses the info part that was received from sandbox report json
"""
info.update(info.pop('machine', {}))
parsed_info = {
'Category': info.get('category', '').title(),
'Started': info.get('started', ''),
'Completed': info.get('ended', ''),
'Duration': info.get('duration', ''),
'VmName': info.get('name', ''),
'VmID': info.get('id', '')
}
return parsed_info
def parse_indicators_list(iocs_list):
"""
Parses the indicator list and returns dictionary that will be set to context.
"""
iocs_context = []
for indicator in iocs_list:
if indicator.get('type', '') == 'md5':
indicator['type'] = indicator.get('subtype', '')
indicator['severity'] = demisto.get(indicator, 'meta.severity') or 'low'
tags = indicator.get('tags') or []
indicator['tags'] = ",".join(tag.get('name', '') for tag in tags)
iocs_context.append({key: indicator.get(ioc_key)
for (key, ioc_key) in INDICATOR_EXTENDED_MAPPING.items()})
return iocs_context
def build_model_data(model, name, is_public, tlp, tags, intelligence, description):
"""
Builds data dictionary that is used in Threat Model creation/update request.
"""
if model == 'tipreport':
description_field_name = 'body'
else:
description_field_name = 'description'
data = {k: v for (k, v) in (('name', name), ('is_public', is_public), ('tlp', tlp),
(description_field_name, description)) if v}
if tags:
data['tags'] = tags if isinstance(tags, list) else [t.strip() for t in tags.split(',')]
if intelligence:
data['intelligence'] = intelligence if isinstance(intelligence, list) else [i.strip() for i in
intelligence.split(',')]
return data
def create_relationships(client: Client, indicator, ioc_type, relation_mapper):
relationships: List[EntityRelationship] = []
if not client.should_create_relationships:
return relationships
for relation in relation_mapper:
entity_b = demisto.get(indicator, relation['raw_field'])
if entity_b:
relationships.append(EntityRelationship(entity_a=indicator['value'],
entity_a_type=ioc_type,
name=relation['name'],
entity_b=entity_b,
entity_b_type=relation['entity_b_type'],
source_reliability=client.reliability,
brand=THREAT_STREAM))
return relationships
def create_intelligence_relationship(client: Client, indicator, ioc_type, entity_b, entity_b_type):
relationship = None
if not client.should_create_relationships:
return relationship
if entity_b:
relationship = EntityRelationship(entity_a=indicator['value'],
entity_a_type=ioc_type,
name=EntityRelationship.Relationships.RELATED_TO,
entity_b=entity_b,
entity_b_type=entity_b_type,
source_reliability=client.reliability,
brand=THREAT_STREAM,
reverse_name=EntityRelationship.Relationships.RELATED_TO)
return relationship
''' COMMANDS + REQUESTS FUNCTIONS '''
def test_module(client: Client):
"""
Performs basic get request to get item samples
"""
client.http_request('GET', 'v2/intelligence/', params={'limit': 1})
return 'ok'
def ips_reputation_command(client: Client, score_calc: DBotScoreCalculator, ip, status, threshold=None,
threat_model_association=False):
results = [] # type: ignore
ips = argToList(ip, ',')
for single_ip in ips:
results.append(get_ip_reputation(client, score_calc, single_ip, status, threshold, threat_model_association))
return results
def get_ip_reputation(client: Client, score_calc: DBotScoreCalculator, ip, status, threshold=None,
threat_model_association=False):
"""
Checks the reputation of given ip from ThreatStream and
returns the indicator with highest confidence score.
"""
# get the indicator
params = {
'value': ip,
'type': DBotScoreType.IP,
'status': status,
'limit': 0,
}
indicator = search_worst_indicator_by_params(client, params)
if not indicator:
return create_indicator_result_with_dbotscore_unknown(indicator=ip,
indicator_type=DBotScoreType.IP,
reliability=client.reliability)
# Convert the tags objects into s string for the human readable.
threat_context = get_generic_threat_context(indicator)
tags_csv = ', '.join(threat_context.get('Tags', []))
human_readable = tableToMarkdown(f'IP reputation for: {ip}', threat_context | {'Tags': tags_csv})
# build relationships
relationships = create_relationships(
client,
indicator,
FeedIndicatorType.IP,
RELATIONSHIPS_MAPPING.get('ip'),
)
# create the IP instance
args_to_keys_map: Dict[str, str] = IOC_ARGS_TO_INDICATOR_KEY_MAP.get('ip') # type: ignore
kwargs = {arg: demisto.get(indicator, key) for (arg, key) in args_to_keys_map.items()}
dbot_score = Common.DBotScore(
ip,
DBotScoreType.IP,
THREAT_STREAM,
score=score_calc.calculate_score(DBotScoreType.IP, indicator, threshold),
reliability=client.reliability,
)
if threat_model_association:
intelligence_relationships, outputs = get_intelligence(client,
indicator,
FeedIndicatorType.IP
)
if intelligence_relationships:
relationships.extend(intelligence_relationships)
threat_context.update(outputs)
human_readable += create_human_readable(outputs)
ip_indicator = Common.IP(
dbot_score=dbot_score,
tags=get_tags(indicator),
threat_types=[Common.ThreatTypes(indicator.get('threat_type'))],
relationships=relationships,
**kwargs
)
return CommandResults(
outputs_prefix=f'{THREAT_STREAM}.IP',
outputs_key_field='Address',
indicator=ip_indicator,
readable_output=human_readable,
outputs=threat_context,
raw_response=indicator,
relationships=relationships
)
def return_params_of_pagination_or_limit(page: int = None, page_size: int = None, limit: int = None):
"""
Returns request params accroding to page, page_size and limit arguments.
Args:
page: page.
page_size: page size.
limit: limit.
Returns:
params (dict).
"""
params = {}
if (page_size and not page) or (not page_size and page):
raise DemistoException('Please specify page and page_size')
elif page and isinstance(page, int) and isinstance(page_size, int):
params['offset'] = (page * page_size) - (page_size)
params['limit'] = page_size
else:
params['limit'] = limit or DEFAULT_LIMIT_PAGE_SIZE
return params
def header_transformer(header: str) -> str:
"""
Returns a correct header.
Args:
header (Str): header.
Returns:
header (Str).
"""
if header == 'notify_me':
return 'Is Notify Me'
if header == 'modified_ts':
return 'Modified At'
if header == 'created_ts':
return 'Created At'
if header == 'email':
return 'Submitted By'
if header == 'numRejected':
return 'Excluded'
if header == 'numIndicators':
return 'Included'
if header == 'approved_by':
return 'Reviewed By'
if header == 'model_type':
return 'Type'
return string_to_table_header(header)
def list_rule_command(client: Client, rule_id: str = None, limit: str = '50', page: str = None,
page_size: str = None) -> CommandResults:
"""
Returns a list rules.
Args:
client: Client to perform calls to Anomali ThreatStream service.
rule_id: Unique ID assigned to the rule.
limit: The maximum number of results to return.
page: The page number of the results to retrieve.
page_size: The maximum number of objects to retrieve per page.
Returns:
(CommandResults).
"""
params = return_params_of_pagination_or_limit(arg_to_number(page), arg_to_number(page_size), arg_to_number(limit))
res = client.list_rule_request(rule_id, params)
data = res if rule_id else res.get('objects', [])
return CommandResults(
outputs_prefix=f"{THREAT_STREAM}.Rule",
outputs_key_field="id",
outputs=data,
readable_output=tableToMarkdown("Rules", data, removeNull=True,
headerTransform=header_transformer,
headers=["name", "id", "matches", "intelligence_initiatives",
"created_ts", "modified_ts", "notify_me", "is_enabled"]),
raw_response=res,
)
def create_request_body_rule(rule_id: str = None, rule_name: str = None, keywords: str = None, match_include: str = None,
actor_ids: str = None, campaign_ids: str = None, investigation_action: str = None,
new_investigation_name: str = None, existing_investigation_id: str = None,
exclude_indicator: str = None, include_indicator: str = None,
exclude_notify_org_whitelisted: str = None, exclude_notify_owner_org: str = None,
incident_ids: str = None, malware_ids: str = None, signature_ids: str = None,
threat_bulletin_ids: str = None,
ttp_ids: str = None, vulnerability_ids: str = None, tags: str = None) -> dict:
"""
Creates a request body for create and update rule command.
Args:
client (Client): Client to perform calls to Anomali ThreatStream service.
rule_id: The rule id.
rule_name: Rule name.
keywords: A comma-separated list of keywords.
match_include: Possible values: observables, sandbox reports, threat bulletins, signatures, vulnerabilities.
actor_ids: A comma-separated list of actor IDs.
campaign_ids: A comma-separated list of campaign IDs.
investigation_action: Possible values: Create New, Add To Existing, No Action.
new_investigation_name: Name of investigation.
existing_investigation_id: An id of existing investigation.
exclude_indicator: A comma-separated list of indicator type.
include_indicator: A comma-separated list of indicator type.
exclude_notify_org_whitelisted: 'true' or 'false' value.
exclude_notify_owner_org: 'true' or 'false' value.
incident_ids: A comma-separated list of incident IDs.
malware_ids: A comma-separated list of malwares IDs.
signature_ids: A comma-separated list of signatures IDs.
threat_bulletin_ids: A comma-separated list of threat bulletin IDs.
ttp_ids: A comma-separated list of ttp IDs.
vulnerability_ids: A comma-separated list of vulnerabilities IDs.
tags: A comma-separated list of tags.
Returns:
(CommandResults).
"""
match_include_list = argToList(match_include.lower()) if match_include else []
tag_list = argToList(tags) or []
request_body = assign_params(
name=rule_name,
keywords=argToList(keywords),
actors=argToList(actor_ids),
match_observables='observables' in match_include_list,
match_reportedfiles='sandbox reports' in match_include_list,
match_tips='threat bulletins' in match_include_list,
match_signatures='signatures' in match_include_list,
match_vulnerabilities='vulnerabilities' in match_include_list,
campaigns=argToList(campaign_ids),
exclude_impacts=argToList(exclude_indicator),
match_impacts=argToList(include_indicator),
exclude_notify_org_whitelisted=argToBoolean(exclude_notify_org_whitelisted) if exclude_notify_org_whitelisted else None,
exclude_notify_owner_org=argToBoolean(exclude_notify_owner_org) if exclude_notify_owner_org else None,
incidents=argToList(incident_ids),
malware=argToList(malware_ids),
signatures=argToList(signature_ids),
tips=argToList(threat_bulletin_ids),
ttps=argToList(ttp_ids),
vulnerabilities=argToList(vulnerability_ids),
tags=[{'name': tag} for tag in tag_list] if tag_list else None
)
if new_investigation_name:
request_body['create_investigation'] = True
request_body['investigation_config'] = {'name': new_investigation_name}
if existing_investigation_id:
request_body['create_investigation'] = True
request_body['investigation'] = existing_investigation_id
return request_body
def create_rule_command(client: Client, **kwargs) -> CommandResults:
"""
Creates a new rule in ThreatStream.
Args:
client: Client to perform calls to Anomali ThreatStream service.
rule_name: Rule name.
keywords: A comma-separated list of keywords.
match_include: Possible values: observables, sandbox reports, threat bulletins, signatures, vulnerabilities.
actor_ids: A comma-separated list of actor IDs.
campaign_ids: A comma-separated list of campaign IDs.
investigation_action: Possible values: Create New, Add To Existing, No Action.
new_investigation_name: Name of investigation.
existing_investigation_id: An id of existing investigation.
exclude_indicator: A comma-separated list of indicator type.
include_indicator: A comma-separated list of indicator type.
exclude_notify_org_whitelisted: 'true' or 'false' value.
exclude_notify_owner_org: 'true' or 'false' value.
incident_ids: A comma-separated list of incident IDs.
malware_ids: A comma-separated list of malwares IDs.
signature_ids: A comma-separated list of signatures IDs.
threat_bulletin_ids: A comma-separated list of threat bulletin IDs.
ttp_ids: A comma-separated list of ttp IDs.
vulnerability_ids: A comma-separated list of vulnerabilities IDs.
tags: A comma-separated list of tags.
Returns:
(CommandResults).
"""
investigation_action: Optional[str] = kwargs.get('investigation_action')
new_investigation_name: Optional[str] = kwargs.get('investigation_action')
existing_investigation_id: Optional[str] = kwargs.get('existing_investigation_id')
validate_investigation_action(investigation_action, new_investigation_name, existing_investigation_id)
request_body = create_request_body_rule(**kwargs)
res = client.create_rule_request(request_body)
demisto.debug("create rule command request body", request_body)
return CommandResults(
outputs_prefix=f'{THREAT_STREAM}.Rule',
outputs_key_field="id",
outputs=res,
readable_output=f'The rule was created successfully with id: {res.get("id")}.',
raw_response=res,