/
ZeroFox.py
1991 lines (1746 loc) · 64.4 KB
/
ZeroFox.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 *
""" IMPORTS """
from dateparser import parse as parse_date
from datetime import datetime
from typing import Any, TypedDict, BinaryIO
from collections.abc import Callable
from requests import Response
from copy import deepcopy
import urllib.parse as urlparse
import json
""" GLOBALS / PARAMS """
FETCH_TIME_DEFAULT = "3 days"
CLOSED_ALERT_STATUS = ["Closed", "Deleted"]
DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.%f"
MAX_ALERT_IDS_STORED = 200
""" Types """
FetchIncidentsStorage = TypedDict("FetchIncidentsStorage", {
"last_fetched": str,
"last_offset": str,
"first_run_at": str,
"last_modified_fetched": str,
"last_modified_offset": str,
"zf-ids": list[int],
})
""" CLIENT """
class ZFClient(BaseClient):
def __init__(
self, username, password, fetch_limit, only_escalated, *args, **kwargs
):
super().__init__(*args, **kwargs)
self.credentials = {
"username": username,
"password": password
}
self.fetch_limit = fetch_limit
self.only_escalated = only_escalated
self.auth_token = ""
def api_request(
self,
method: str,
url_suffix: str,
headers_builder_type: str | None = 'api',
params: dict[str, str] | None = None,
data: dict[str, Any] | None = None,
files: dict[str, Any] | None = None,
prefix: str | None = "1.0",
empty_response: bool = False,
error_handler: Callable[[Any], Any] | None = None,
) -> dict[str, Any]:
"""
:param method: HTTP request type
:param url_suffix: The suffix of the URL
:param headers_builder_type: It can be `api` or `cti`. It selects
the function to build the headers required
for each case
:param params: The request's query parameters
:param data: The request's body parameters
:param files: The request's files
:param version: api prefix to consider, default is to use version '1.0'
:param res_type: Selects the decoder of the response. It can be
`json` (default), `xml`, `text`, `content`, `response`
:param empty_response: Indicates if the response data is empty or not
:param error_handler: Function that receives the response and manage
the error
:return: Returns the content of the response received from the API.
"""
pref_string = f"/{prefix}" if prefix else ""
headers = {}
if headers_builder_type is not None:
if headers_builder_type not in ("api", "cti"):
raise ValueError(
"`headers_builder_type` should be 'api' or 'cti'"
)
header_builder = {
"api": self.get_api_request_header,
"cti": self.get_cti_request_header
}.get(headers_builder_type)
if header_builder is None:
raise ValueError(
"`headers_builder_type` should be 'api' or 'cti'"
)
headers = header_builder()
if files:
headers.pop("Content-Type", None)
return self._http_request(
method=method,
url_suffix=urljoin(pref_string, url_suffix),
headers=headers,
params=params,
json_data=data,
empty_valid_codes=(200, 201),
return_empty_response=empty_response,
error_handler=error_handler,
files=files,
)
def handle_auth_error(self, raw_response: Response):
response = raw_response.json()
if "res_content" in response:
raise Exception("Failure resolving URL.")
error_msg_list: list[str] = response.get("non_field_errors", [])
if not error_msg_list:
raise Exception("Unable to log in with provided credentials.")
else:
raise Exception(error_msg_list[0])
def get_authorization_token(self) -> str:
"""
:return: Returns the authorization token
"""
if self.auth_token:
return self.auth_token
url_suffix: str = "/1.0/api-token-auth/"
response_content = self.api_request(
"POST",
url_suffix,
data=self.credentials,
error_handler=self.handle_auth_error,
headers_builder_type=None,
prefix=None,
)
self.auth_token = response_content.get("token", "")
return self.auth_token
def _get_new_access_token(self) -> str:
url_suffix: str = "/auth/token/"
response_content = self.api_request(
"POST",
url_suffix,
data=self.credentials,
headers_builder_type=None,
prefix=None,
)
return response_content.get("access", "")
def get_cti_authorization_token(self) -> str:
"""
:return: returns the authorization token for the CTI feed
"""
token = self._get_new_access_token()
if not token:
raise Exception("Unable to retrieve token.")
return token
def get_api_request_header(self) -> dict[str, str]:
token: str = self.get_authorization_token()
return {
"Authorization": f"Token {token}",
"Content-Type": "application/json",
"Accept": "application/json",
"zf-source": "XSOAR",
}
def get_cti_request_header(self) -> dict[str, str]:
token: str = self.get_cti_authorization_token()
return {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
"Accept": "application/json",
"zf-source": "XSOAR",
}
def get_policy_types(self) -> dict[str, Any]:
"""
:return: HTTP request content.
"""
url_suffix: str = "/policies/"
response_content = self.api_request("GET", url_suffix)
return response_content
def list_alerts(self, params: dict[str, Any]) -> dict[str, Any]:
"""
:param params: The request's body parameters.
:return: HTTP request content.
"""
url_suffix: str = "/alerts/"
if not params.get("limit"):
params['limit'] = self.fetch_limit
if self.only_escalated:
params['escalated'] = 'true'
response_content = self.api_request(
"GET",
url_suffix,
params=params
)
return response_content
def get_alert(self, alert_id: int) -> dict[str, Any]:
"""
:param alert_id: The ID of the alert.
:return: HTTP request content.
"""
url_suffix: str = f"/alerts/{alert_id}/"
response_content = self.api_request("GET", url_suffix)
return response_content
def alert_user_assignment(
self,
alert_id: int,
username: str
) -> dict[str, Any]:
"""
:param alert_id: The ID of the alert.
:param username: The username we want to assign to the alert.
:return: HTTP request content.
"""
url_suffix: str = f"/alerts/{alert_id}/assign/"
request_body = {"subject": username}
response_content = self.api_request(
"POST",
url_suffix,
data=request_body,
empty_response=True,
)
return response_content
def close_alert(self, alert_id: int) -> dict[str, Any]:
"""
:param alert_id: The ID of the alert.
:return: HTTP request content.
"""
url_suffix: str = f"/alerts/{alert_id}/close/"
response_content = self.api_request(
"POST",
url_suffix,
empty_response=True,
)
return response_content
def open_alert(self, alert_id: int) -> dict[str, Any]:
"""
:param alert_id: The ID of the alert.
:return: HTTP request content.
"""
url_suffix: str = f"/alerts/{alert_id}/open/"
response_content = self.api_request(
"POST",
url_suffix,
empty_response=True,
)
return response_content
def alert_request_takedown(self, alert_id: int) -> dict[str, Any]:
"""
:param alert_id: The ID of the alert.
:return: HTTP request content.
"""
url_suffix: str = f"/alerts/{alert_id}/request_takedown/"
response_content = self.api_request(
"POST",
url_suffix,
empty_response=True,
)
return response_content
def alert_cancel_takedown(self, alert_id: int) -> dict[str, Any]:
"""
:param alert_id: The ID of the alert.
:return: HTTP request content.
"""
url_suffix: str = f"/alerts/{alert_id}/cancel_takedown/"
response_content = self.api_request(
"POST",
url_suffix,
empty_response=True,
)
return response_content
def modify_alert_tags(
self,
alert_id: int,
action: str,
tags_list: list[str]
) -> dict[str, Any]:
"""
:param alert_id: The ID of the alert.
:param action: action can be 'added' or 'removed'. It indicates
what action we want to do i.e add/remove tags/
:param tags_list: A string representation of the tags,
separated by a comma ','
:return: HTTP request content.
"""
url_suffix: str = "/alerttagchangeset/"
request_body = {
"changes": [
{
f"{action}": tags_list,
"alert": alert_id,
},
],
}
response_content = self.api_request(
"POST", url_suffix, data=request_body,
)
return response_content
def create_entity(
self,
name: str,
strict_name_matching: bool | None = None,
tags: list | None = None,
policy: int | None = None,
organization: str | None = None,
) -> dict[str, Any]:
"""
:param name: Name of the entity (may be non-unique).
:param strict_name_matching: Indicating type of string matching for
comparing name to impersonators.
:param tags: List of string tags for tagging the entity. Separated
by a comma ','.
:param policy: The ID of the policy to assign to the new entity.
:param organization: Organization name associated with entity.
:return: HTTP request content.
"""
url_suffix: str = "/entities/"
request_body = {
"name": name,
"strict_name_matching": strict_name_matching,
"labels": tags,
"policy": policy,
"policy_id": policy,
"organization": organization,
}
request_body = remove_none_dict(request_body)
response_content = self.api_request(
"POST", url_suffix, data=request_body,
)
return response_content
def list_entities(self, params: dict[str, Any]) -> dict[str, Any]:
"""
:param params: The request's body parameters.
:return: HTTP request content.
"""
url_suffix: str = "/entities/"
response_content = self.api_request(
"GET",
url_suffix,
params=params,
)
return response_content
def get_entity_types(self) -> dict[str, Any]:
"""
:return: HTTP request content.
"""
url_suffix: str = "/entities/types/"
response_content = self.api_request("GET", url_suffix)
return response_content
def modify_alert_notes(self, alert_id: int, notes: str) -> dict[str, Any]:
"""
:param alert_id: The ID of the alert.
:param notes: The notes for the alert.
:return: HTTP request content.
"""
url_suffix: str = f"/alerts/{alert_id}/"
request_body = {"notes": notes}
response_content = self.api_request(
"POST",
url_suffix,
data=request_body,
empty_response=True,
)
return response_content
def submit_threat(
self,
source: str,
alert_type: str,
violation: str,
entity_id: str
) -> dict[str, Any]:
"""
:param source: The source of the threat.
:param alert_type: The type of the alert.
:param violation: The violation of the alert.
:param entity_id: The ID of the entity.
:return: HTTP request content.
"""
url_suffix: str = "/threat_submit/"
request_body = {
"source": source,
"alert_type": alert_type,
"violation": violation,
"entity_id": entity_id,
}
request_body = remove_none_dict(request_body)
response_content = self.api_request(
"POST",
url_suffix,
data=request_body,
prefix="2.0",
)
return response_content
def send_alert_attachment(
self,
alert_id: int,
file_name: str,
file_content: BinaryIO,
attachment_type: str
) -> dict[str, Any]:
"""
:param alert_id: The ID of the alert.
:param file_name: The name of the file.
:param file_content: The content of the file.
:param attachment_type: The type of the attachment.
:return: HTTP request content.
"""
url_suffix = f"/alerts/{alert_id}/attachments/"
files = {
"file": (file_name, file_content),
"attachment_type": (None, attachment_type),
}
# request_body = {"attachment_type": attachment_type}
response_content = self.api_request(
'POST',
url_suffix,
files=files,
)
return response_content
def get_alert_attachments(self, alert_id: int) -> dict[str, Any]:
"""
:param alert_id: The ID of the alert.
:return: HTTP request content.
"""
url_suffix = f"/alerts/{alert_id}/attachments/"
response_content = self.api_request(
"GET",
url_suffix,
)
return response_content
def get_cti_c2_domains(self, domain: str) -> dict[str, Any]:
"""
:param domain: The domain to lookup in c2-domains CTI Feed
:return: HTTP request content.
"""
url_suffix = "/c2-domains/"
params = {"domain": domain}
response_content = self.api_request(
"GET",
url_suffix,
params=params,
prefix="cti",
headers_builder_type="cti",
)
return response_content
def get_cti_phishing(
self,
domain: str | None = None,
ip: str | None = None
) -> dict[str, Any]:
"""
:param domain: The domain to lookup in phishing CTI Feed
:param ip: The ip to lookup in phishing CTI Feed
:return: HTTP request content.
"""
url_suffix = "/phishing/"
params = remove_none_dict({"domain": domain, "host_ip": ip})
response_content = self.api_request(
"GET",
url_suffix,
params=params,
prefix="cti",
headers_builder_type="cti",
)
return response_content
def get_cti_email_addresses(self, email: str) -> dict[str, Any]:
"""
:param email: The email to lookup in email-addresses CTI Feed
:return: HTTP request content.
"""
url_suffix = "/email-addresses/"
params = {"email": email}
response_content = self.api_request(
"GET",
url_suffix,
params=params,
prefix="cti",
headers_builder_type="cti",
)
return response_content
def get_cti_compromised_credentials(self, email: str) -> dict[str, Any]:
"""
:param email: The email to lookup in compromised-credentials CTI Feed
:return: HTTP request content.
"""
url_suffix = "/compromised-credentials/"
params = {"email": email}
response_content = self.api_request(
"GET",
url_suffix,
params=params,
prefix="cti",
headers_builder_type="cti",
)
return response_content
def get_cti_botnet_compromised_credentials(
self,
email: str
) -> dict[str, Any]:
"""
:param email: The email to lookup in botnet-compromised-credentials
CTI Feed
:return: HTTP request content.
"""
url_suffix = "/botnet-compromised-credentials/"
params = {"email": email}
response_content = self.api_request(
"GET",
url_suffix,
params=params,
prefix="cti",
headers_builder_type="cti",
)
return response_content
def get_cti_botnet(self, ip: str) -> dict[str, Any]:
"""
:param ip: The ip to lookup in botnet CTI Feed
:return: HTTP request content.
"""
url_suffix = "/botnet/"
params = {"ip": ip}
response_content = self.api_request(
"GET",
url_suffix,
params=params,
prefix="cti",
headers_builder_type="cti",
)
return response_content
def get_cti_malware(self, hash_type: str, hash: str) -> dict[str, Any]:
"""
:param hash_type: The hash type to lookup in malware CTI Feed
:param hash: The hash to lookup in malware CTI Feed
:return: HTTP request content.
"""
url_suffix = "/malware/"
params = {hash_type: hash}
response_content = self.api_request(
"GET",
url_suffix,
params=params,
prefix="cti",
headers_builder_type="cti",
)
return response_content
def get_cti_exploits(self, since: str) -> dict[str, Any]:
"""
:param since: since date to query exploits
:return: HTTP request content.
"""
url_suffix = "/exploits/"
params = {"created_after": since}
response_content = self.api_request(
"GET",
url_suffix,
params=params,
prefix="cti",
headers_builder_type="cti",
)
return response_content
""" HELPERS """
def alert_to_incident(alert: dict[str, Any]) -> dict[str, str]:
"""
transforms an alert to incident convention
:param alert: alert is a dictionary
:return: Incident - dictionary
"""
alert_id = str(alert.get("id", ""))
incident = {
"rawJSON": json.dumps(alert),
"name": f"ZeroFox Alert {alert_id}",
"dbotMirrorId": str(alert_id),
"occurred": alert.get("timestamp", ""),
}
return incident
def parse_dict_values_to_integer(
params: dict[str, Any],
keys: list[str]
) -> dict[str, Any]:
params_copy = deepcopy(params)
for key in keys:
value = params_copy.get(key)
if value is not None:
try:
params_copy[key] = int(value)
except ValueError:
raise Exception(f"This value for {key} must be an integer.")
return params_copy
def severity_num_to_string(severity_num: int) -> str:
"""
transforms severity number to string representation
:param severity_num: Severity score as Integer
:return: Returns the String representation of the severity score
"""
severity_map = {1: "Info", 2: "Low", 3: "Medium", 4: "High", 5: "Critical"}
return severity_map.get(severity_num, "")
def severity_string_to_num(severity_str: str) -> int:
"""
:param severity_str: Severity score as String
:return: Returns the Integer representation of the severity score
"""
severity_map = {"Info": 1, "Low": 2, "Medium": 3, "High": 4, "Critical": 5}
return severity_map.get(severity_str, -1)
def get_nested_key(
obj: dict[str, Any],
path: list[str],
default_value: Any | None = None
) -> Any:
"""
It returns the value of a nested key in a dictionary
:param obj: The dictionary we want to get the value from
:param path: The path to the nested key
:param default_value: The default value to return if the key is not found
:return: The value of the nested key
Example:
obj = {"a": {"b": {"c": 1}}}
default_value = -1
get_nested_key(obj, ["a", "b", "c"], default_value) -> 1
get_nested_key(obj, ["a", "x", "d"], default_value) -> -1
"""
for key in path[:-1]:
obj = obj.get(key, {})
if not isinstance(obj, dict):
return default_value
return obj.get(path[-1])
def get_alert_contents(alert: dict[str, Any]) -> dict[str, Any]:
"""
:param alert: Alert is a dictionary
:return: A dict representing the alert contents
"""
return {
"AlertType": alert.get("alert_type"),
"OffendingContentURL": alert.get("offending_content_url"),
"Assignee": alert.get("assignee"),
"Entity": {
"ID": get_nested_key(alert, ["entity", "id"]),
"Name": get_nested_key(alert, ["entity", "name"]),
"Image": get_nested_key(alert, ["entity", "image"]),
},
"EntityID": get_nested_key(alert, ["entity", "id"]),
"EntityName": get_nested_key(alert, ["entity", "name"]),
"EntityImage": get_nested_key(alert, ["entity", "image"]),
"EntityTerm": {
"ID": get_nested_key(alert, ["entity_term", "id"]),
"Name": get_nested_key(alert, ["entity_term", "name"]),
"Deleted": get_nested_key(alert, ["entity_term", "deleted"]),
},
"EntityTermID": get_nested_key(alert, ["entity_term", "id"]),
"EntityTermName": get_nested_key(alert, ["entity_term", "name"]),
"EntityTermDeleted": get_nested_key(alert, ["entity_term", "deleted"]),
"ContentCreatedAt": alert.get("content_created_at"),
"ID": alert.get("id"),
"ProtectedAccount": alert.get("protected_account"),
"RiskRating": severity_num_to_string(int(alert.get("severity", ""))),
"Perpetrator": {
"Name": get_nested_key(alert, ["perpetrator", "name"]),
"Url": get_nested_key(alert, ["perpetrator", "url"]),
"TimeStamp": get_nested_key(alert, ["perpetrator", "timestamp"]),
"Type": get_nested_key(alert, ["perpetrator", "type"]),
"ID": get_nested_key(alert, ["perpetrator", "id"]),
"Network": get_nested_key(alert, ["perpetrator", "network"]),
},
"PerpetratorName": get_nested_key(alert, ["perpetrator", "name"]),
"PerpetratorUrl": get_nested_key(alert, ["perpetrator", "url"]),
"PerpetratorTimeStamp": get_nested_key(
alert, ["perpetrator", "timestamp"],
),
"PerpetratorType": get_nested_key(alert, ["perpetrator", "type"]),
"PerpetratorID": get_nested_key(alert, ["perpetrator", "id"]),
"PerpetratorNetwork": get_nested_key(
alert, ["perpetrator", "network"],
),
"RuleGroupID": alert.get("rule_group_id"),
"Status": alert.get("status"),
"Timestamp": alert.get("timestamp"),
"RuleName": alert.get("rule_name"),
"LastModified": alert.get("last_modified"),
"ProtectedLocations": alert.get("protected_locations"),
"DarkwebTerm": alert.get("darkweb_term"),
"Reviewed": alert.get("reviewed"),
"Escalated": alert.get("escalated"),
"Network": alert.get("network"),
"ProtectedSocialObject": alert.get("protected_social_object"),
"Notes": alert.get("notes"),
"RuleID": alert.get("rule_id"),
"EntityAccount": alert.get("entity_account"),
"Tags": alert.get("tags"),
}
def transform_alert_human_readable_values(
alert: dict[str, Any],
title_keys: list[str] | None = None
) -> dict[str, Any]:
"""
It takes an alert and convert the keys indicated in `title_keys` to
title case
:param alert: Dictionary representing the alert
:param title_keys: List of keys to convert to title case
:return: return a copy of the alert with the keys converted to title case
"""
title_keys = title_keys or []
transformed_alert = deepcopy(alert)
for key in title_keys:
transformed_alert[key] = transformed_alert.get(key, "").title()
return transformed_alert
def transform_alerts_human_readable_values(
alerts: dict[str, Any] | list[dict[str, Any]],
title_keys: list[str] | None = None
) -> dict[str, Any] | list[dict[str, Any]]:
"""
It takes an alert or a list of alerts and convert the keys specified in
`title_keys` to title case
:param alerts: Alert or list of alerts to transform
:parma title_keys: List of keys to convert to title case
:return: a copy of the alert or list of alerts with the corresponding
transformations
"""
title_keys = title_keys or []
if isinstance(alerts, list):
return [
transform_alert_human_readable_values(
alert,
title_keys=title_keys,
)
for alert in alerts
]
elif isinstance(alerts, dict):
return transform_alert_human_readable_values(
alerts,
title_keys=title_keys,
)
else:
raise Exception("alerts must be a list or a dict")
def transform_alert_human_readable_header(header: str) -> str:
"""
It returns the header name of the alert's key to human readable
:param header: the key to get the human readable header
:return: the human readable header name of the key requested
"""
transformations = {
"EntityName": "Protected Entity",
"AlertType": "Content Type",
"Timestamp": "Alert Date",
"Network": "Source",
"RuleName": "Rule",
"RiskRating": "Risk Rating",
"OffendingContentURL": "Offending Content",
}
return transformations.get(header, header)
def get_human_readable_alerts(
alerts: dict[str, Any] | list[dict[str, Any]]
) -> str:
visible_keys = [
"ID",
"EntityName",
"AlertType",
"Timestamp",
"Status",
"OffendingContentURL",
"Network",
"RuleName",
"RiskRating",
"Notes",
"Tags",
]
title_keys = ["AlertType", "RuleName", "Network", "EntityName"]
transformed_alerts = transform_alerts_human_readable_values(
alerts, title_keys=title_keys
)
readable_output: str = tableToMarkdown(
"ZeroFox Alerts",
transformed_alerts,
headers=visible_keys,
date_fields=["Timestamp"],
headerTransform=transform_alert_human_readable_header,
removeNull=True,
)
return readable_output
def remove_none_dict(input_dict: dict[Any, Any]) -> dict[Any, Any]:
"""
removes all none values from a dict
:param input_dict: any dictionary in the world is OK
:return: same dictionary but without None values
"""
return {
key: value for key, value in input_dict.items()
if value is not None
}
def get_entity_contents(entity: dict[str, Any]) -> dict[str, Any]:
"""
:param entity: Entity is a dictionary
:return: A dict representation of the contents of entity
"""
return {
"ID": entity.get("id"),
"Name": entity.get("name"),
"EmailAddress": entity.get("email_address"),
"Organization": entity.get("organization"),
"Tags": entity.get("labels"),
"StrictNameMatching": entity.get("strict_name_matching"),
"PolicyID": entity.get("policy_id"),
"Profile": entity.get("profile"),
"EntityGroupID": get_nested_key(entity, ["entity_group", "id"]),
"EntityGroupName": get_nested_key(entity, ["entity_group", "name"]),
"TypeID": get_nested_key(entity, ["type", "id"]),
"TypeName": get_nested_key(entity, ["type", "name"]),
}
def get_entity_human_readable_outputs(
contents: dict[str, Any]
) -> dict[str, Any]:
"""
returns the convention for the war room
:param contents: Contents is a dictionary
:return: A dict representation of the war room contents
displayed to the user
"""
return {
"Name": contents.get("Name"),
"Type": contents.get("TypeName"),
"Policy": contents.get("PolicyID"),
"Email": contents.get("EmailAddress"),
"Tags": contents.get("Tags"),
"ID": contents.get("ID"),
}
def get_c2_domain_content(c2_domain_record: dict[str, Any]) -> dict[str, Any]:
return {
"Domain": c2_domain_record.get("domain", ""),
"LastModified": c2_domain_record.get("created_at", ""),
"IPs": ", ".join(c2_domain_record.get("ip_addresses", []))
}
def get_phishing_content(phishing_record: dict[str, Any]) -> dict[str, Any]:
return {
"Domain": phishing_record.get("domain", ""),
"LastModified": phishing_record.get("scanned", ""),
"IPs": get_nested_key(phishing_record, ["host", "ip"], "")
}
def get_compromised_domain_content(
c2_domain_response: dict[str, Any],
phishing_response: dict[str, Any]
) -> list[dict[str, Any]]:
"""
It merges the content of c2_domain_response and phishing_response and
format it to be standardized as compromised domain content
:param c2_domain_response: The response of the c2-domains CTI Feed
:param phishing_response: The response of the phishing CTI Feed
:return: A list of dictionaries representing the compromised domain content
"""
compromised_domain_content = []
c2_domains_results = c2_domain_response.get("results", [])
compromised_domain_content += [
get_c2_domain_content(record) for record in c2_domains_results
]
phishing_results = phishing_response.get("results", [])
compromised_domain_content += [
get_phishing_content(record) for record in phishing_results
]
return compromised_domain_content
def get_email_address_content(
email_address_record: dict[str, Any]
) -> dict[str, Any]:
return {
"Domain": email_address_record.get("domain", ""),
"Email": email_address_record.get("email", ""),
"CreatedAt": email_address_record.get("created_at", ""),
}
def get_credentials_content(
credentials_record: dict[str, Any]
) -> dict[str, Any]:
return {
"Domain": credentials_record.get("domain", ""),
"Email": credentials_record.get("email", ""),
"CreatedAt": credentials_record.get("created_at", ""),
}
def get_botnet_credentials_content(
botnet_credentials_record: dict[str, Any]
) -> dict[str, Any]:
return {
"Domain": botnet_credentials_record.get("domain", ""),
"Email": botnet_credentials_record.get("email", ""),
"CreatedAt": botnet_credentials_record.get("created_at", ""),
}
def get_compromised_email_content(
email_addressed_response: dict[str, Any],
credentials_response: dict[str, Any],
botnet_credentials_response: dict[str, Any],
) -> list[dict[str, Any]]:
"""
It merges the content of email_addressed_response,
credentials_response and botnet_credentials_response and
format it to be standardized as compromised email content
:param email_addressed_response: The response of the email-addresses
:param credentials_response: The response of the compromised-credentials
:param botnet_credentials_response: The response of the
botnet-compromised-credentials
:return: A list of dictionaries representing the compromised email content
"""
compromised_email_content = []
email_addresses_results = email_addressed_response.get("results", [])
compromised_email_content += [
get_email_address_content(record)
for record in email_addresses_results
]
credentials_results = credentials_response.get("results", [])
compromised_email_content += [
get_credentials_content(record)
for record in credentials_results
]
botnet_credentials_results = botnet_credentials_response.get("results", [])
compromised_email_content += [
get_botnet_credentials_content(record)
for record in botnet_credentials_results
]
return compromised_email_content
def get_botnet_ip_content(botnet_result: dict[str, Any]) -> dict[str, Any]:
return {
"CreatedAt": botnet_result.get("acquired_at", ""),
"IPAddress": botnet_result.get("ip_address", ""),