-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
CofenseTriagev3.py
2100 lines (1583 loc) · 72.8 KB
/
CofenseTriagev3.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
from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import
from CommonServerUserPython import * # noqa
import time
import requests
import traceback
from typing import Any, Callable, Dict, Tuple
import urllib3
# Disable insecure warnings
urllib3.disable_warnings()
''' CONSTANTS '''
DATE_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ' # ISO8601 format with UTC, default in XSOAR
DEFAULT_MAX_FETCH = "15"
DEFAULT_FIRST_FETCH = "3 days"
URL_SUFFIX = {
"SYSTEM_STATUS": "/api/public/v2/system/status",
"AUTH": "oauth/token",
"REPORTS": "api/public/v2/reports",
"REPORTS_BY_CATEGORY": "api/public/v2/categories/{}/reports",
"REPORTS_BY_CLUSTER": "api/public/v2/clusters/{}/reports",
"THREAT_INDICATORS": "/api/public/v2/threat_indicators",
"REPORT_DOWNLOAD": "api/public/v2/reports/{}/download",
"REPORT_IMAGE_DOWNLOAD": "api/public/v2/reports/{}/download.{}",
"REPORT_CATEGORIZE": "/api/public/v2/reports/{}/categorize",
"CATEGORY": "api/public/v2/categories/",
"URLS": "api/public/v2/urls",
"RULE": "api/public/v2/rules",
"REPORTERS": "api/public/v2/reporters",
"INTEGRATION_SUBMISSION": "/api/public/v2/{}/{}/integration_submissions",
"ATTACHMENT_PAYLOAD": "api/public/v2/attachment_payloads",
"COMMENTS": "api/public/v2/comments/",
"REPORT_ID": "api/public/v2/reports/{}",
"CLUSTER": "api/public/v2/clusters",
"REPORT_ATTACHMENT_PAYLOAD": "/api/public/v2/reports/{}/attachment_payloads"
}
OUTPUT_PREFIX = {
"REPORT": "Cofense.Report",
"THREAT_INDICATOR": "Cofense.ThreatIndicator",
"CATEGORY": "Cofense.Category",
"URL": "Cofense.Url",
"RULE": "Cofense.Rule",
"REPORTER": "Cofense.Reporter",
"ATTACHMENT_PAYLOAD": "Cofense.AttachmentPayload",
"INTEGRATION_SUBMISSION": "Cofense.IntegrationSubmission",
"COMMENT": "Cofense.Comment",
"CLUSTER": "Cofense.Cluster"
}
MESSAGES = {
'NO_RECORDS_FOUND': "No {} were found for the given argument(s).",
"API_TOKEN": "No API token found. Please try again.",
"PAGE_SIZE": "{} is an invalid value for page size. Page size must be between 1 and 200.",
"PAGE_NUMBER": "{} is an invalid value for page number. Page number must be greater than 0",
"FILTER": 'Please provide the filter in the valid JSON format. Format accepted- \' '
'{"attribute1_operator" : "value1, value2" , "attribute2_operator" : "value3, value4"} \'',
"REQUIRED_ARGUMENT": "Invalid argument value. {} is a required argument.",
"INVALID_MAX_FETCH": "{} is an invalid value for maximum fetch. Maximum fetch must be between 1 and 200.",
"INVALID_FIRST_FETCH": "Argument 'First fetch time interval' should be a valid date or relative timestamp such as "
"'2 days', '2 months', 'yyyy-mm-dd', 'yyyy-mm-ddTHH:MM:SSZ'",
"INVALID_LOCATION_FOR_CATEGORY_ID": "If Category ID is provided in fetch incident parameters, the Report Location "
"cannot be 'Inbox' or 'Reconnaissance'.",
"INVALID_LOCATION_FOR_CATEGORIZATION_TAGS": "If Categorization Tags are provided in fetch incident parameters, "
"the Report Location cannot be 'Inbox' or 'Reconnaissance'.",
"INVALID_LOCATION_FOR_TAGS": "If Tags are provided in fetch incident parameters, the Report Location "
"must be 'Reconnaissance'.",
"BODY_FORMAT": "Invalid value for body format. Body format must be text or json.",
"INTEGRATION_SUBMISSION_TYPE": "Invalid value for integration submission type. Type must be urls or "
"attachment_payloads.",
"INVALID_IMAGE_TYPE": "Invalid value for type. Type must be png or jpg."
}
TYPE_HEADER = 'application/vnd.api+json'
CREATED_AT = "Created At"
UPDATED_AT = "Updated At"
TOKEN_EXPIRY_TIMEOUT = 60 * 60 * 2
BODY_FORMAT = ["text", "json"]
INTEGRATION_SUBMISSION_TYPE = ["urls", "attachment_payloads"]
DEFAULT_THREAT_SOURCE = "XSOAR-UI"
DEFAULT_REPORT_IMAGE_TYPE = "png"
VALID_IMAGE_TYPE = ["png", "jpg"]
MIRROR_DIRECTION = {
'None': None,
'Incoming': 'In'
}
HTTP_ERRORS = {
400: "Bad request: an error occurred while fetching the data.",
401: "Authentication error: please provide valid Client ID and Client Secret.",
403: "Forbidden: please provide valid Client ID and Client Secret.",
404: "Resource not found: invalid endpoint was called.",
500: "The server encountered an internal error for Cofense Triage v3 and was unable to complete your request."
}
''' CLIENT CLASS '''
class Client(BaseClient):
"""Client class to interact with the service API
"""
def __init__(self, base_url: str, verify: bool, proxy: bool, client_id, client_secret):
super().__init__(base_url=base_url, verify=verify, proxy=proxy)
self.client_id = client_id,
self.client_secret = client_secret
def http_request(self, url_suffix, method="GET", resp_type="json", headers=None, json_data=None,
params=None) -> Any:
"""
Function to make http requests using inbuilt _http_request() method.
Handles token expiration case and makes request using refreshed token.
:param json_data: The data to send in a 'POST' request.
:param resp_type:Determines which data format to return from the HTTP request. The default
is 'json'
:param headers: headers to send with request
:param method: http method to use
:param url_suffix: the API endpoint
:param params: parameters to send with request
:return: response from the request
"""
token = self.get_api_token()
if not token:
response = self._http_request(
method='POST',
url_suffix=URL_SUFFIX["AUTH"],
params={
'client_id': self.client_id,
'client_secret': self.client_secret,
'grant_type': 'client_credentials'
},
headers={'Content-Type': 'application/json'},
error_handler=self.exception_handler
)
token = self.set_integration_context(response)
if not headers:
headers = {
'Accept': TYPE_HEADER
}
headers['Authorization'] = token
response = self._http_request(method=method, url_suffix=url_suffix, params=params, json_data=json_data,
headers=headers, resp_type=resp_type,
error_handler=self.exception_handler)
return response
@staticmethod
def exception_handler(response: requests.models.Response):
"""
Handle error in the response and display error message based on status code.
:type response: ``requests.models.Response``
:param response: response from API.
:raises: raise DemistoException based on status code abd response.
"""
err_msg = ""
if response.status_code in HTTP_ERRORS:
err_msg = HTTP_ERRORS[response.status_code]
if response.status_code not in HTTP_ERRORS or response.status_code in [400, 404]:
if response.status_code not in [400, 404]:
err_msg = response.reason
try:
# Try to parse json error response
error_entry = response.json().get("errors")
if error_entry:
err_details = ','.join([entry.get('detail') for entry in error_entry if entry.get('detail')])
if err_details:
err_msg = f"{err_msg}\nDetails: {err_details}"
except (ValueError, AttributeError):
if response.text:
err_msg = f"{err_msg}\nDetails: {response.text}"
raise DemistoException(err_msg)
@staticmethod
def set_integration_context(resp) -> Any:
"""
set API token and expiry time in integration configuration context.
Will raise value error if api-token is not found.
:param resp: resp from API.
:return: integration context
"""
integration_context = {}
api_token = resp.get('access_token')
if api_token:
integration_context['api_token'] = "Bearer " + api_token
integration_context['valid_until'] = int(time.time() + resp.get("expires_in", TOKEN_EXPIRY_TIMEOUT))
else:
raise ValueError(MESSAGES["API_TOKEN"])
set_integration_context(integration_context)
return integration_context.get('api_token')
@staticmethod
def get_api_token() -> Any:
"""
Retrieve API token from integration context.
if API token is not found or expired it will return false
"""
integration_context = get_integration_context()
api_token = integration_context.get('api_token')
valid_until = integration_context.get('valid_until')
# Return API token from integration context, if found and not expired
if api_token and valid_until and time.time() < valid_until:
demisto.debug('[CofenseTriagev3] Retrieved api-token from integration cache.')
return api_token
return False
'''HELPER FUNCTIONS '''
def retrieve_fields(arg: str) -> str:
"""Strip and filter out the empty elements from the string.
:type arg: ``str``
:param arg: The string from which we want to filter out the empty elements.
:return: Filtered out result.
:rtype: ``str``
"""
return ",".join([x.strip() for x in arg.split(",") if x.strip()])
def validate_filter_by_argument(args: Dict[str, Any], custom_args: List[str]) -> Dict[str, Any]:
"""
Validate filters in arguments for all list commands, raise ValueError on invalid arguments.
:type args: ``Dict[str, Any]``
:param args: The command arguments provided by the user.
:type custom_args: ``List[str]``
:param custom_args: The custom command arguments provided by the user.
:return: Parameters related to the filters.
:rtype: ``Dict[str, Any]``
"""
params = {}
if args.get("filter_by"):
try:
filters = json.loads(args["filter_by"])
for key, value in filters.items():
key, value = key.strip(), value.strip()
if not key or not value:
continue
if all([False if key.startswith(arg) else True for arg in custom_args]):
params[f"filter[{key}]"] = value
except (json.JSONDecodeError, json.decoder.JSONDecodeError, AttributeError):
raise ValueError(MESSAGES["FILTER"])
remove_nulls_from_dictionary(params)
return params
def validate_list_command_args(args: Dict[str, str], field_type: str) -> tuple:
"""
Validate arguments for all list commands, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:type field_type: ``str``
:param field_type: The type of the field to be set in parameter for sending the request.
:return: Parameters to send in request
:rtype: ``Tuple[Any]``
"""
params: Dict[str, Any] = {}
custom_args = []
page_size = arg_to_number(args.get("page_size"))
if page_size is not None:
if page_size <= 0 or page_size > 200:
raise ValueError(MESSAGES['PAGE_SIZE'].format(page_size))
params["page[size]"] = page_size
page_number = arg_to_number(args.get("page_number"))
if page_number is not None:
if page_number <= 0:
raise ValueError(MESSAGES['PAGE_NUMBER'].format(page_number))
params["page[number]"] = page_number
if args.get("sort_by"):
params["sort"] = retrieve_fields(args["sort_by"])
if args.get("fields_to_retrieve"):
params[f"fields[{field_type}]"] = retrieve_fields(args["fields_to_retrieve"])
if args.get("created_at"):
created_at = arg_to_datetime(args["created_at"])
params["filter[created_at_gteq]"] = created_at
custom_args.append("created_at")
if args.get("updated_at"):
updated_at = arg_to_datetime(args["updated_at"])
params["filter[updated_at_gteq]"] = updated_at
custom_args.append("updated_at")
return params, custom_args
def validate_fetch_incidents_parameters(params: dict) -> dict:
"""
Validate fetch incidents params, throw ValueError on non-compliant arguments
:param params: dictionary of parameters to be tested for fetch_incidents
:rtype: ``dict``
return: dictionary containing valid parameters
"""
fetch_params: Dict[str, Any] = {}
custom_args = []
max_fetch = arg_to_number(params.get("max_fetch", DEFAULT_MAX_FETCH))
if (max_fetch is None) or (not 0 < max_fetch <= 200):
raise ValueError(MESSAGES["INVALID_MAX_FETCH"].format(max_fetch))
fetch_params["page[size]"] = max_fetch
first_fetch = params.get("first_fetch")
first_fetch_time = arg_to_datetime(first_fetch)
if first_fetch_time is None:
raise ValueError(MESSAGES["INVALID_FIRST_FETCH"])
fetch_params["filter[updated_at_gteq]"] = first_fetch_time.strftime(DATE_FORMAT)
locations = params.get('mailbox_location', [])
if locations:
mailbox_location = retrieve_fields(','.join(locations))
custom_args.append("location")
fetch_params["filter[location]"] = mailbox_location
priorities = params.get("match_priority", [])
if priorities:
match_priority = retrieve_fields(','.join(priorities))
for priority in match_priority.split(","):
arg_to_number(priority)
custom_args.append("match_priority")
fetch_params["filter[match_priority]"] = match_priority
if params.get('tags'):
tags = retrieve_fields(params.get("tags", ""))
custom_args.append("tags")
fetch_params["filter[tags_any]"] = tags
if params.get('categorization_tags'):
categorization_tags = retrieve_fields(params.get("categorization_tags", ""))
custom_args.append("categorization_tags")
fetch_params["filter[categorization_tags_any]"] = categorization_tags
fetch_params.update(validate_filter_by_argument(params, custom_args))
remove_nulls_from_dictionary(fetch_params)
return fetch_params
def validate_list_threat_indicator_args(args: Dict[str, str]) -> Dict[str, Any]:
"""
Validate arguments for cofense-threat-indicator-list command, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Parameters to send in request
:rtype: ``Dict[str, Any]``
"""
params, custom_args = validate_list_command_args(args, "threat_indicators")
threat_levels = retrieve_fields(args.get("threat_level", ""))
if threat_levels:
custom_args.append("threat_level")
params["filter[threat_level]"] = threat_levels
threat_types = retrieve_fields(args.get("threat_type", ""))
if args.get("threat_type"):
custom_args.append("threat_type")
params["filter[threat_type]"] = threat_types
threat_values = retrieve_fields(args.get("threat_value", ""))
if threat_values:
custom_args.append("threat_value")
params["filter[threat_value]"] = threat_values
threat_sources = retrieve_fields(args.get("threat_source", ""))
if threat_sources:
custom_args.append("threat_source")
params["filter[threat_source]"] = threat_sources
params.update(validate_filter_by_argument(args, custom_args))
remove_nulls_from_dictionary(params)
return params
def prepare_hr_for_threat_indicators(results: List[Dict[str, Any]]) -> str:
"""
Parse and convert the threat indicators in response into human-readable markdown string.
:type results: ``List[Dict[str, Any]]``
:param results: Details of threat indicators.
:return: Human Readable string containing threat indicators.
:rtype: ``str``
"""
threat_indicators_hr = []
for res in results:
attributes = res.get("attributes")
hr = {"Threat Indicator ID": res.get("id", "")}
if attributes:
hr["Threat Level"] = attributes.get("threat_level", "")
hr["Threat Type"] = attributes.get("threat_type", "")
hr["Threat Value"] = attributes.get("threat_value", "")
hr["Threat Source"] = attributes.get("threat_source", "")
hr[CREATED_AT] = attributes.get("created_at", "")
hr[UPDATED_AT] = attributes.get("updated_at", "")
threat_indicators_hr.append(hr)
return tableToMarkdown("Threat Indicator(s)", threat_indicators_hr,
headers=["Threat Indicator ID", "Threat Level", "Threat Type", "Threat Value",
"Threat Source", CREATED_AT, UPDATED_AT], removeNull=True)
def prepare_hr_for_reports(reports: List[Dict[str, Any]]) -> str:
"""
Prepare human readable for list reports command.
:param reports:The report data.
:return: Human readable.
"""
hr_list = []
for report in reports:
hr_record = {
'Report ID': report.get('id', ''),
}
attributes = report.get('attributes')
if attributes:
hr_record['From Address'] = attributes.get('from_address', '')
hr_record['Subject'] = attributes.get('subject', '')
hr_record['Match Priority'] = attributes.get('match_priority', '')
hr_record['Location'] = attributes.get('location', '')
hr_record['MD5'] = attributes.get('md5', '')
hr_record['SHA256'] = attributes.get('sha256', '')
hr_record[CREATED_AT] = attributes.get('created_at', '')
hr_list.append(hr_record)
return tableToMarkdown('Report(s)', hr_list, ['Report ID', 'From Address', 'Subject', 'Match Priority', 'Location',
'MD5', 'SHA256', CREATED_AT], removeNull=True)
def prepare_hr_for_categories(categories: List[Dict[str, Any]]) -> str:
"""
Prepare human readable for list Categories command.
:param categories:The category data.
:return: Human readable.
"""
hr_list = []
for category in categories:
hr_record = {
'Category ID': category.get('id', ''),
}
attributes = category.get('attributes')
if attributes:
hr_record['Name'] = attributes.get('name', '')
hr_record['Malicious'] = attributes.get('malicious', '')
hr_record['Archived'] = attributes.get('archived', '')
hr_record[CREATED_AT] = attributes.get('created_at', '')
hr_record[UPDATED_AT] = attributes.get('updated_at', '')
hr_list.append(hr_record)
return tableToMarkdown('Categories', hr_list, ['Category ID', 'Name', 'Malicious', 'Archived', CREATED_AT,
UPDATED_AT], removeNull=True)
def prepare_hr_for_clusters(clusters: List[Dict[str, Any]]) -> str:
"""
Prepare human readable for list clusters command.
:param clusters:The cluster data.
:return: Human readable.
"""
hr_list = []
for cluster in clusters:
hr_record = {
'Cluster ID': cluster.get('id', ''),
}
attributes = cluster.get('attributes')
if attributes:
hr_record['Unprocessed Report'] = attributes.get('unprocessed_reports_count', '')
hr_record['Total Report Count'] = attributes.get('total_reports_count', '')
hr_record['Match Priority'] = attributes.get('match_priority', '')
hr_record['Tags'] = attributes.get('tags', '')
hr_record['Host Source'] = attributes.get('host_source', '')
hr_record['Average Reporter Reputation Score'] = attributes.get('average_reporter_reputation', '')
hr_record['VIP Reporter count'] = attributes.get('vip_reporters_count', '')
hr_record[CREATED_AT] = attributes.get('created_at', '')
hr_record[UPDATED_AT] = attributes.get('updated_at', '')
hr_list.append(hr_record)
return tableToMarkdown('Cluster(s)', hr_list, ['Cluster ID', 'Unprocessed Report', 'Total Report Count',
'Match Priority', 'Tags', 'Host Source',
'Average Reporter Reputation Score', 'VIP Reporter count',
CREATED_AT, UPDATED_AT], removeNull=True)
def prepare_hr_for_rules(rules: List[Dict[str, Any]]) -> str:
"""
Prepare human readable for list rules command.
:param rules:The rule data.
:return: Human readable.
"""
hr_list = []
for rule in rules:
hr_record = {
'Rule ID': rule.get('id', ''),
}
attributes = rule.get('attributes')
if attributes:
hr_record['Rule Name'] = attributes.get('name', '')
hr_record['Description'] = attributes.get('description', '')
hr_record['Active'] = attributes.get('active', '')
hr_record['Priority'] = attributes.get('priority', '')
hr_record['Scope'] = attributes.get('scope', '')
hr_record['Author Name'] = attributes.get('author_name', '')
hr_record['Rule Context'] = attributes.get('rule_context', '')
hr_record['Created At'] = attributes.get('created_at', '')
hr_record['Updated At'] = attributes.get('updated_at', '')
hr_list.append(hr_record)
return tableToMarkdown('Rule(s)', hr_list, ['Rule ID', 'Rule Name', 'Description', 'Active', 'Priority', 'Scope',
'Author Name', 'Rule Context', 'Created At', 'Updated At'],
removeNull=True)
def validate_tags_argument(args: Dict[str, str]) -> Dict:
"""
Validate tags argument.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Parameters to send in request
:rtype: ``Dict[str, str]``
"""
params = {}
tags = retrieve_fields(args.get("tags", ""))
if tags:
params["filter[tags_any]"] = tags
return params
def validate_match_priority_argument(args: Dict[str, str]) -> Dict:
"""
Validate match_priority argument.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Parameters to send in request
:rtype: ``Dict[str, str]``
"""
params = {}
match_priority = retrieve_fields(args.get("match_priority", ""))
if match_priority:
for priority in match_priority.split(","):
arg_to_number(priority)
params["filter[match_priority]"] = match_priority
return params
def validate_list_report_args(args: Dict[str, str]) -> Dict[str, Any]:
"""
Validate arguments for cofense-report-list command, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Parameters to send in request
:rtype: ``Dict[str, str]``
"""
params, custom_args = validate_list_command_args(args, "reports")
tags = validate_tags_argument(args)
if tags:
params.update(tags)
custom_args.append("tags")
match_priority = validate_match_priority_argument(args)
if match_priority:
params.update(match_priority)
custom_args.append("match_priority")
categorization_tags = retrieve_fields(args.get("categorization_tags", ""))
if categorization_tags:
custom_args.append("categorization_tags")
params["filter[categorization_tags_any]"] = categorization_tags
mailbox_location = retrieve_fields(args.get("report_location", ""))
if mailbox_location:
custom_args.append("location")
params["filter[location]"] = mailbox_location
params.update(validate_filter_by_argument(args, custom_args))
remove_nulls_from_dictionary(params)
return params
def validate_list_category_args(args: Dict[str, str]) -> Dict[str, Any]:
"""
Validate arguments for cofense-category-list command, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Parameters to send in request
:rtype: ``Dict[str, str]``
"""
params, custom_args = validate_list_command_args(args, "categories")
is_malicious = args.get("is_malicious", "")
if is_malicious:
is_malicious = "true" if argToBoolean(is_malicious) else "false"
custom_args.append("malicious")
params["filter[malicious]"] = is_malicious
names = retrieve_fields(args.get("name", ""))
if names:
custom_args.append("name")
params["filter[name]"] = names
scores = retrieve_fields(args.get("score", ""))
if scores:
for score in scores.split(","):
arg_to_number(score)
custom_args.append("score")
params["filter[score]"] = scores
params.update(validate_filter_by_argument(args, custom_args))
remove_nulls_from_dictionary(params)
return params
def validate_list_cluster_args(args: Dict[str, str]) -> Dict[str, Any]:
"""
Validate arguments for cofense-cluster-list command, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Parameters to send in request
:rtype: ``Dict[str, str]``
"""
params, custom_args = validate_list_command_args(args, "clusters")
match_priority = validate_match_priority_argument(args)
if match_priority:
params.update(match_priority)
custom_args.append("match_priority")
tags = validate_tags_argument(args)
if tags:
params.update(tags)
custom_args.append("tags")
total_reports_count = retrieve_fields(args.get("total_reports_count", ""))
if total_reports_count:
for report_count in total_reports_count.split(","):
arg_to_number(report_count)
custom_args.append("total_reports_count")
params["filter[total_reports_count]"] = total_reports_count
params.update(validate_filter_by_argument(args, custom_args))
remove_nulls_from_dictionary(params)
return params
def validate_list_url_args(args: Dict[str, str]) -> Dict[str, Any]:
"""
Validate arguments for cofense-url-list command, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Parameters to send in request
:rtype: ``Dict[str, Any]``
"""
params, custom_args = validate_list_command_args(args, "urls")
risk_score = retrieve_fields(args.get("risk_score", ""))
if risk_score:
for score in risk_score.split(","):
arg_to_number(score)
custom_args.append("risk_score")
params["filter[risk_score]"] = risk_score
params.update(validate_filter_by_argument(args, custom_args))
remove_nulls_from_dictionary(params)
return params
def prepare_hr_for_urls(results: List[Dict[str, Any]]) -> str:
"""
Parse and convert the urls in the response into human-readable markdown string.
:type results: ``List[Dict[str, Any]]``
:param results: Details of urls.
:return: Human Readable string containing information of urls.
:rtype: ``str``
"""
urls_hr = []
for res in results:
attributes = res.get("attributes")
hr = {"URL ID": res.get("id", "")}
if attributes:
hr["URL"] = attributes.get("url", "")
hr["Risk Score"] = attributes.get("risk_score", "")
hr[CREATED_AT] = attributes.get("created_at", "")
hr[UPDATED_AT] = attributes.get("updated_at", "")
urls_hr.append(hr)
return tableToMarkdown("URL(s)", urls_hr,
headers=["URL ID", "URL", "Risk Score", CREATED_AT, UPDATED_AT], removeNull=True)
def validate_list_rule_args(args: Dict[str, str]) -> Dict[str, Any]:
"""
Validate arguments for cofense-rule-list command, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Parameters to send in request
:rtype: ``Dict[str, str]``
"""
params, custom_args = validate_list_command_args(args, "rules")
names = retrieve_fields(args.get("name", ""))
if names:
custom_args.append("name")
params["filter[name]"] = names
priority = retrieve_fields(args.get("priority", ""))
if priority:
for score in priority.split(","):
arg_to_number(score)
custom_args.append("priority")
params["filter[priority]"] = priority
tags = validate_tags_argument(args)
if tags:
params.update(tags)
custom_args.append("tags")
scope = retrieve_fields(args.get("scope", ""))
if scope:
custom_args.append("scope")
params["filter[scope]"] = scope
active = args.get("active", "")
if active:
active = "true" if argToBoolean(active) else "false"
custom_args.append("active")
params["filter[active]"] = active
author_name = retrieve_fields(args.get("author_name", ""))
if author_name:
custom_args.append("author_name")
params["filter[author_name]"] = author_name
rule_context = retrieve_fields(args.get("rule_context", ""))
if rule_context:
custom_args.append("rule_context")
params["filter[rule_context]"] = rule_context
params.update(validate_filter_by_argument(args, custom_args))
remove_nulls_from_dictionary(params)
return params
def validate_create_threat_indicator_args(args: Dict[str, str]) -> Dict[str, Any]:
"""
Validate arguments for cofense-threat-indicator-create command, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Parameters to send in request
:rtype: ``Dict[str, str]``
"""
params = dict()
if not args.get("threat_level"):
raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("threat_level"))
params["threat_level"] = args["threat_level"]
if not args.get("threat_type"):
raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("threat_type"))
params["threat_type"] = args["threat_type"]
if not args.get("threat_value", ""):
raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("threat_value"))
params["threat_value"] = args["threat_value"]
if not args.get("threat_source"):
params["threat_source"] = DEFAULT_THREAT_SOURCE
else:
params["threat_source"] = args["threat_source"]
return params
def validate_list_reporter_args(args: Dict[str, str]) -> Dict[str, Any]:
"""
Validate arguments for cofense-reporter-list command, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Parameters to send in request
:rtype: ``Dict[str, Any]``
"""
params, custom_args = validate_list_command_args(args, "reporters")
reputation_score = retrieve_fields(args.get("reputation_score", ""))
if reputation_score:
for score in reputation_score.split(","):
arg_to_number(score)
custom_args.append("reputation_score")
params["filter[reputation_score]"] = reputation_score
vip = args.get("vip", "")
if vip:
vip = "true" if argToBoolean(vip) else "false"
custom_args.append("vip")
params["filter[vip]"] = vip
emails = retrieve_fields(args.get("email", ""))
if emails:
custom_args.append("email")
params["filter[email]"] = emails
params.update(validate_filter_by_argument(args, custom_args))
remove_nulls_from_dictionary(params)
return params
def prepare_hr_for_reporters(results: List[Dict[str, Any]]) -> str:
"""
Parse and convert the reporters in the response into human-readable markdown string.
:type results: ``List[Dict[str, Any]]``
:param results: Details of reporters.
:return: Human Readable string containing information of reporters.
:rtype: ``str``
"""
reporters_hr = []
for res in results:
attributes = res.get("attributes")
hr = {"Reporter ID": res.get("id", "")}
if attributes:
hr["Reporter Email"] = attributes.get("email", "")
hr["Reports Count"] = attributes.get("reports_count", "")
hr["Reputation Score"] = attributes.get("reputation_score", "")
hr["VIP"] = attributes.get("vip", "")
hr["Last Reported At"] = attributes.get("last_reported_at", "")
hr[CREATED_AT] = attributes.get("created_at", "")
hr[UPDATED_AT] = attributes.get("updated_at", "")
reporters_hr.append(hr)
return tableToMarkdown("Reporter(s)", reporters_hr,
headers=["Reporter ID", "Reporter Email", "Reports Count", "Reputation Score", "VIP",
"Last Reported At", CREATED_AT, UPDATED_AT], removeNull=True)
def validate_categorize_report_args(args: Dict[str, str]) -> Dict[str, Any]:
"""
Validate arguments for cofense-report-categorize command, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:raises: ValueError if the required arguments are missing
"""
if not args.get("id"):
raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("id"))
arg_to_number(args.get("id"))
if not args.get("category_id"):
raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("category_id"))
arg_to_number(args.get("category_id"))
params: Dict[str, Any] = {"category_id": args["category_id"]}
categorization_tags = retrieve_fields(args.get("categorization_tags", ""))
if categorization_tags:
params["categorization_tags"] = categorization_tags.split(",") # type: ignore
return params
def validate_list_attachment_payload_args(args: Dict[str, str]) -> Dict[str, Any]:
"""
Validate arguments for cofense-attachment-payload-list command, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Parameters to send in request
:rtype: ``Dict[str, Any]``
"""
params, custom_args = validate_list_command_args(args, "attachment_payloads")
risk_score = retrieve_fields(args.get("risk_score", ""))
if risk_score:
for score in risk_score.split(","):
arg_to_number(score)
custom_args.append("risk_score")
params["filter[risk_score]"] = risk_score
params.update(validate_filter_by_argument(args, custom_args))
remove_nulls_from_dictionary(params)
return params
def prepare_hr_for_attachment_payloads(results: List[Dict[str, Any]]) -> str:
"""
Parse and convert the attachment payloads in the response into human-readable markdown string.
:type results: ``List[Dict[str, Any]]``
:param results: Details of urls.
:return: Human Readable string containing information of attachment payloads.
:rtype: ``str``
"""
payloads_hr = []
for res in results:
attributes = res.get("attributes")
hr = {"Attachment Payload ID": res.get("id", "")}
if attributes:
hr["Mime Type"] = attributes.get("mime_type", "")
hr["MD5"] = attributes.get("md5", "")
hr["SHA256"] = attributes.get("sha256", "")
hr["Risk Score"] = attributes.get("risk_score", "")
hr[CREATED_AT] = attributes.get("created_at", "")
hr[UPDATED_AT] = attributes.get("updated_at", "")
payloads_hr.append(hr)
return tableToMarkdown("Attachment Payload(s)", payloads_hr,
headers=["Attachment Payload ID", "Mime Type", "MD5", "SHA256", "Risk Score", CREATED_AT,
UPDATED_AT], removeNull=True)
def validate_comment_list_args(args: Dict[str, str]) -> Dict[str, Any]:
"""
Validate arguments for cofense-comment-list command, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Parameters to send in request
:rtype: ``Dict[str, str]``
"""
params, custom_args = validate_list_command_args(args, "comments")
body_format = retrieve_fields(args.get("body_format", ""))