-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
CiscoASA.py
1848 lines (1528 loc) · 63.5 KB
/
CiscoASA.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
from typing import Any, Callable, Optional
from functools import wraps
from copy import deepcopy
from http import HTTPStatus
import urllib3
import traceback
from CommonServerUserPython import *
# Disable insecure warnings
urllib3.disable_warnings()
''' GLOBAL VARIABLES'''
API_LIMIT = 100
INTEGRATION_COMMAND = "cisco-asa"
OBJECT_TYPES_DICT = {
'IPv4': 'IPv4Address',
'IP-Network': 'IPv4Network'
}
DEFAULT_LIMIT = 50
DEFAULT_KEYS_MAPPING = {
'objectId': 'object_id',
'name': 'name',
'description': 'description',
'members': {
'_include': True,
'kind': 'kind',
'objectId': 'object_id',
'value': 'value',
},
}
'''PAGINATION DECORATOR '''
class Pagination:
"""
Pagination decorator wrapper to control functionality within the decorator.
Args:
api_limit (int): Maximum number of items that can be returned from the API request.
items_key_path (list[str], optional): A list of keys to the items within an API response.
Defaults to None.
start_count_from_zero (bool | None): Whether the count of the first item is 0 or 1.
Defaults to True.
default_limit (int): The number of default items to return with an API request.
Defaults to DEFAULT_LIMIT.
Returns:
Callable: Pagination decorator.
"""
def __init__(
self,
api_limit: int,
items_key_path: list[str] | None = None,
start_count_from_zero: bool = True,
default_limit: int = DEFAULT_LIMIT,
) -> None:
self.api_limit = api_limit
self.items_key_path = items_key_path
self.start_count_from_zero = start_count_from_zero
self.default_limit = default_limit
def __call__(self, func: Callable) -> Callable:
"""
The __call__ method takes a function and returns a wrapped function that handles the pagination logic.
Args:
func (Callable): The function to be wrapped with pagination.
Returns:
Callable: The wrapped function with added pagination functionality.
"""
@wraps(func)
def wrapper(
client_instance: BaseClient,
page: int | None,
page_size: int | None,
limit: int = DEFAULT_LIMIT,
*args,
**kwargs,
) -> tuple[list | dict, list | dict]:
"""
The wrapper function handles the pagination logic before calling the original function.
Args:
client_instance (BaseClient): The instance of the Client class used to call the API request function.
page (int | None): Page number to return.
page_size (int | None): Number of items to return in a page.
*args: Positional arguments to be passed to the original function.
**kwargs: Keyword arguments to be passed to the original function.
Returns:
tuple[list | dict, list | dict]: All the items combined within raw response,
All the raw responses combined.
"""
remaining_items, offset = self._get_pagination_arguments(
page=page,
page_size=page_size,
limit=limit
)
return self._handle_pagination(
client_instance,
func,
remaining_items,
offset,
*args,
**kwargs,
)
return wrapper
def _get_pagination_arguments(
self,
page: int | None,
page_size: int | None,
limit: int = DEFAULT_LIMIT
) -> tuple[int, int | None]:
"""
Determine if pagination is automatic or manual and compute remaining items and offset values.
Args:
page (int | None): Page number to return.
page_size (int | None): Number of items to return in a page.
Returns:
tuple[bool, int, int | None]:
remaining_items: The number of remaining items to fetch.
offset: The offset for the next API request.
"""
is_manual = page is not None
if is_manual:
page = page or 1
page_size = page_size or self.default_limit
remaining_items = page_size
offset = (page - 1) * page_size + (0 if self.start_count_from_zero else 1)
else:
remaining_items = page_size or limit
offset = None
return remaining_items, offset
def _handle_pagination(
self,
client_instance: BaseClient,
func: Callable,
remaining_items: int,
offset: int | None,
*args,
**kwargs,
) -> tuple[list | dict, list | dict]:
"""
Handle pagination when the API supports both limit and offset parameters.
Args:
client_instance (BaseClient): The instance of the Client class used to call the API request function.
func (Callable): API request function to be called.
remaining_items (int): The number of remaining items to fetch.
offset (int | None): The offset for the next API request.
args: Positional arguments to be passed to the API request function.
kwarg: Keyword arguments to be passed to the API request function.
Returns:
tuple[list | dict, list | dict]:
All the items combined within raw response, All the raw responses combined
"""
kwargs['self'] = client_instance
raw_items: list[dict[str, Any]] = []
raw_responses: list[dict[str, Any]] = []
# Keep calling the API until the required amount of items have been met.
while remaining_items > 0:
limit = min(remaining_items, self.api_limit)
kwargs |= {
'limit': limit,
'offset': offset,
}
raw_response = func(
*args,
**kwargs,
)
raw_item = raw_response
if self.items_key_path:
raw_item = dict_safe_get(raw_item, self.items_key_path)
if raw_item is None:
break
raw_responses.append(raw_response)
raw_items += raw_item
if (received_items := len(raw_item)) < limit:
break
# Calculate the offset and limit for the next run.
remaining_items -= received_items
offset = (offset or 0) + received_items
return raw_items, raw_responses
'''Client'''
class Client(BaseClient):
isASAv = False
auth_token = ""
def login(self, isASAv) -> None:
"""
Receive an auth token from the headers after a basic authentication has been made.
Args:
isASAv (bool): Whether Cisco Adaptive Security Virtual Appliance is in use.
"""
if isASAv:
self.isASAv = True
res = self._http_request('POST', '/api/tokenservices', resp_type='response')
auth_token = res.headers._store.get('x-auth-token')[1]
self._headers['X-Auth-Token'] = auth_token
self.auth_token = auth_token
def logoff(self):
"""
Delete the generated auth token.
"""
try:
if self.isASAv and self.auth_token:
self._http_request('DELETE', f'/api/tokenservices/{self.auth_token}', resp_type='response')
except Exception as e:
# if failed to logoof just write to log. no need to raise error
demisto.debug(f'Logoff error: {str(e)}')
def get_all_rules(self, specific_interface: Optional[str] = None, rule_type: str = 'All') -> list:
"""
Gets a list all rules for the supplied interface.
Args:
specific_interface): the name of the interface
rule_type: All/Global/In
Returns:
all rules in Cisco ASA of the specified type/interface
"""
rules = [] # type: list
# Get global rules
if specific_interface is None and rule_type in ['All', 'Global']:
res = self._http_request('GET', '/api/access/global/rules')
items = res.get('items', [])
for item in items:
item['interface_type'] = "Global"
rules.extend(items)
# Get in rules
if rule_type in ['All', 'In']:
res = self._http_request('GET', '/api/access/in')
interfaces = []
for item in res.get('items', []):
interface_name = item.get('interface', {}).get('name')
if interface_name and specific_interface and specific_interface == interface_name:
interfaces.append(interface_name)
if interface_name and not specific_interface:
interfaces.append(interface_name)
for interface in interfaces:
res = self._http_request('GET', f'/api/access/in/{interface}/rules')
items = res.get('items', [])
for item in items:
item['interface'] = interface
item['interface_type'] = "In"
rules.extend(items)
# Get out rules
if rule_type in ['All', 'Out']:
res = self._http_request('GET', '/api/access/out')
interfaces = []
for item in res.get('items', []):
interface_name = item.get('interface', {}).get('name')
if interface_name and specific_interface and specific_interface == interface_name:
interfaces.append(interface_name)
if interface_name and not specific_interface:
interfaces.append(interface_name)
for interface in interfaces:
res = self._http_request('GET', f'/api/access/out/{interface}/rules')
items = res.get('items', [])
for item in items:
item['interface'] = interface
item['interface_type'] = "Out"
rules.extend(items)
return rules
def rule_action(self, rule_id: str, interface_name: str, interface_type: str, command: str = 'GET',
data: dict = None) -> dict:
"""
Get, update or delete a rule.
Args:
rule_id: The Rule ID.
interface_name: the name of the interface.
interface_type: The type of interface.
command: The operation to do on the rule.
data: The data of the rule to update.
Returns:
Does the command on the rule.
Delete - delete rule
GET - rule info
PATCH - edit rule
"""
resp_type = {"GET": "json",
"DELETE": "text",
"PATCH": "response"
}
if interface_type == "Global":
rule = self._http_request(command, f'/api/access/global/rules/{rule_id}', resp_type=resp_type[command],
json_data=data)
if interface_type == "In":
rule = self._http_request(command, f'/api/access/in/{interface_name}/rules/{rule_id}',
resp_type=resp_type[command], json_data=data)
if interface_type == 'Out':
rule = self._http_request(command, f'/api/access/out/{interface_name}/rules/{rule_id}',
resp_type=resp_type[command], json_data=data)
if command == 'GET':
rule['interface'] = interface_name
rule['interface_type'] = interface_type
return rule
def create_rule(self, interface_type: str, interface_name: str, rule_body: dict) -> dict:
"""
Create a rule.
Args:
interface_type: The interface type of the rule, can be one of: Global/In/Out.
interface_name: The name of the provided interface, applies to In/Out interface types.
rule_body: The information about the rule.
Returns:
The new created rule's information.
"""
if interface_type == "Global":
res = self._http_request("POST", '/api/access/global/rules', json_data=rule_body, resp_type="response")
if interface_type == 'In':
res = self._http_request("POST", f'/api/access/in/{interface_name}/rules', json_data=rule_body,
resp_type="response")
if interface_type == 'Out':
res = self._http_request("POST", f'/api/access/out/{interface_name}/rules', json_data=rule_body,
resp_type="response")
loc = res.headers.get("Location", "")
rule = self._http_request('GET', loc[loc.find('/api'):])
rule['interface'] = interface_name
rule['interface_type'] = interface_type
return rule
def test_command(self):
"""
A command to test the connection to the Cisco ASA server.
"""
self._http_request("GET", "/api/aaa/authorization")
def backup(self, data: dict):
"""
Creates a backup of the current settings (i.e., the backup.cfg file).
Args:
data (dict): The backup name and passphrase.
"""
self._http_request("POST", "/api/backup", json_data=data, resp_type="response")
def restore(self, data: dict):
"""
Restore a backup. Currently this command isn't in use through XSOAR.
Args:
data (dict): The backup name and passphrase.
"""
self._http_request("POST", "/api/restore", json_data=data, resp_type='response')
def get_network_obejcts(self):
"""
Gets a list of all the configured network objects.
"""
obj_res = self._http_request('GET', '/api/objects/networkobjects')
return obj_res.get('items', [])
def create_object(self, obj_name, obj_type, obj_value):
"""
Creates a network object.
Args:
obj_name (str): The name of the network object.
obj_type (str): The kind of the network object.
obj_value (_type_): The value of the network object.
Returns:
Whether the network object was created successfully.
"""
data = {
"kind": "object#NetworkObj",
"name": obj_name,
"host": {
"kind": OBJECT_TYPES_DICT.get(obj_type),
"value": obj_value
}
}
try:
return self._http_request('POST', '/api/objects/networkobjects', json_data=data, ok_codes=(200, 201, 204),
resp_type='response')
except Exception:
raise
def list_interfaces(self):
"""
Returns a list of interfaces.
"""
interfaces = list() # type: ignore
for type in ['global', 'in', 'out']:
resp = self._http_request('GET', f'/api/access/{type}')
interfaces.extend(resp.get('items', []))
return interfaces
@Pagination(api_limit=API_LIMIT, items_key_path=['items'])
def list_network_object_group(self, limit: int = DEFAULT_LIMIT, offset: int = None) -> dict[str, Any]:
"""
This command is decorated by Pagination class,
therefore the arguments that must be passed to it are: page, page_size and limit.
Retrieves information about network object groups.
Args:
limit (int, optional): The number of results to return.
Defaults to None.
offset (int, optional): The offset from where to start returning results.
Defaults to None.
Returns:
dict[str, Any]: Information about network object groups.
"""
return self._http_request(
method='GET',
url_suffix='api/objects/networkobjectgroups',
params=assign_params(limit=limit, offset=offset),
)
def get_network_object_group(self, object_id: str) -> dict[str, Any]:
"""
Retrieve information about a network object group.
Args:
object_id (str): The object ID of the network group to retrieve
Returns:
dict[str, Any]: Information about a network object group.
"""
return self._http_request(
method='GET',
url_suffix=f'api/objects/networkobjectgroups/{object_id}',
)
@Pagination(api_limit=API_LIMIT, items_key_path=['items'])
def list_local_user_group(self, limit: int = DEFAULT_LIMIT, offset: int = None) -> dict[str, Any]:
"""
This command is decorated by Pagination class,
therefore the arguments that must be passed to it are: page, page_size and limit.
Retrieves information about local user groups.
Args:
limit (int, optional): The number of results to return.
Defaults to None.
offset (int, optional): The offset from where to start returning results.
Defaults to None.
Returns:
dict[str, Any]: Information about local user groups.
"""
return self._http_request(
'GET',
'api/objects/localusergroups',
params=assign_params(limit=limit, offset=offset),
)
def get_local_user_group(self, object_id: str) -> dict[str, Any]:
"""
Retrieve information about a local user group.
Args:
object_id (str): The object ID of the local user group to retrieve
Returns:
dict[str, Any]: Information about the local user group.
"""
return self._http_request(
method='GET',
url_suffix=f'api/objects/localusergroups/{object_id}',
)
@Pagination(api_limit=API_LIMIT, items_key_path=['items'])
def list_local_user(self, limit: int = DEFAULT_LIMIT, offset: int = None) -> dict[str, Any]:
"""
This command is decorated by Pagination class,
therefore the arguments that must be passed to it are: page, page_size and limit.
Retrieves information about local users.
Args:
limit (int, optional): The number of results to return.
Defaults to None.
offset (int, optional): The offset from where to start returning results.
Defaults to None.
Returns:
dict[str, Any]: Information about local users.
"""
return self._http_request(
method='GET',
url_suffix='api/objects/localusers',
params=assign_params(limit=limit, offset=offset),
)
def get_local_user(self, object_id: str) -> dict[str, Any]:
"""
Retrieve information about a local user.
Args:
object_id (str): The object ID of the local user to retrieve
Returns:
dict[str, Any]: Information about the local user.
"""
return self._http_request(
method='GET',
url_suffix=f'api/objects/localusers/{object_id}',
)
@Pagination(api_limit=API_LIMIT, items_key_path=['items'])
def list_time_range(self, limit: int = DEFAULT_LIMIT, offset: int = None) -> dict[str, Any]:
"""
This command is decorated by Pagination class,
therefore the arguments that must be passed to it are: page, page_size and limit.
Retrieves information about time ranges.
Args:
limit (int, optional): The number of results to return.
Defaults to None.
offset (int, optional): The offset from where to start returning results.
Defaults to None.
Returns:
dict[str, Any]: Information about time ranges.
"""
return self._http_request(
method='GET',
url_suffix='api/objects/timeranges',
params=assign_params(limit=limit, offset=offset),
)
def get_time_range(self, object_id: str) -> dict[str, Any]:
"""
Retrieve information about a time range.
Args:
object_id (str): The object ID of the time range to retrieve
Returns:
dict[str, Any]: Information about the time range.
"""
return self._http_request(
method='GET',
url_suffix=f'api/objects/timeranges/{object_id}',
)
@Pagination(api_limit=API_LIMIT, items_key_path=['items'])
def list_security_object_group(self, limit: int = DEFAULT_LIMIT, offset: int = None) -> dict[str, Any]:
"""
This command is decorated by Pagination class,
therefore the arguments that must be passed to it are: page, page_size and limit.
Retrieves information about security object groups.
Args:
limit (int, optional): The number of results to return.
Defaults to None.
offset (int, optional): The offset from where to start returning results.
Defaults to None.
Returns:
dict[str, Any]: Information about security object groups.
"""
return self._http_request(
method='GET',
url_suffix='api/objects/securityobjectgroups',
params=assign_params(limit=limit, offset=offset),
)
def get_security_object_group(self, object_id: str) -> dict[str, Any]:
"""
Retrieve information about a security object group.
Args:
object_id (str): The object ID of the security object group to retrieve
Returns:
dict[str, Any]: Information about the security object group.
"""
return self._http_request(
method='GET',
url_suffix=f'api/objects/securityobjectgroups/{object_id}',
)
@Pagination(api_limit=API_LIMIT, items_key_path=['items'])
def list_user_object(self, limit: int = DEFAULT_LIMIT, offset: int = None) -> dict[str, Any]:
"""
This command is decorated by Pagination class,
therefore the arguments that must be passed to it are: page, page_size and limit.
Retrieves information about user objects.
Args:
limit (int, optional): The number of results to return.
Defaults to None.
offset (int, optional): The offset from where to start returning results.
Defaults to None.
Returns:
dict[str, Any]: Information about user objects.
"""
return self._http_request(
method='GET',
url_suffix='api/objects/userobjects',
params=assign_params(limit=limit, offset=offset),
)
def get_user_object(self, object_id: str) -> dict[str, Any]:
"""
Retrieve information about a user object.
Args:
object_id (str): The object ID of the user object to retrieve
Returns:
dict[str, Any]: Information about the user object.
"""
return self._http_request(
method='GET',
url_suffix=f'api/objects/userobjects/{object_id}',
)
def write_memory(self) -> dict[str, Any]:
"""
The write memory command saves the running configuration to the default location for the startup configuration.
Returns:
dict[str, Any]: shows a successful 'writemem' command execution on a Cisco ASA device,
building the configuration and generating a cryptochecksum for integrity.
The process is completed with an "[OK]" message.
"""
return self._http_request(
method='POST',
url_suffix='api/commands/writemem',
headers=self._headers | {'Content-Type': 'application/json'}
)
'''HELPER COMMANDS'''
@logger
def set_up_ip_kind(dict_body: dict, field_to_add: str, data: str) -> None:
"""
Takes the data, checks what kind of source/dest it is (IP, network, any or network object) and inserts to the
dict the field_to_add as key and the source/dest as value in the correct format.
Args:
dict_body: The dict to add the data to.
field_to_add: the name of the field to add to json.
data: the string to check its kind and insert to dict.
"""
if is_ip_valid(data):
dict_body[field_to_add] = {"kind": "IPv4Address",
"value": data}
elif data == 'any':
dict_body[field_to_add] = {"kind": "AnyIPAddress",
"value": "any4"}
elif '/' in data:
dict_body[field_to_add] = {"kind": "IPv4Network",
"value": data}
else:
dict_body[field_to_add] = {"kind": "objectRef#NetworkObj",
"objectId": data}
@logger
def raw_to_rules(raw_rules):
"""
:param raw_rules:
:return:
Gets raw rules as received from API and extracts only the relevant fields
"""
rules = list()
for rule in raw_rules:
source_services = rule.get('sourceService', {})
if isinstance(source_services, list):
source_services_list = [v['value'] for v in source_services]
else:
source_services_list = source_services.get('value')
dest_services = rule.get('destinationService', {})
if isinstance(dest_services, list):
dest_services_list = [v['value'] for v in dest_services]
else:
dest_services_list = dest_services.get('value')
rule_object_mapping: dict = remove_empty_elements({
new_object_key: {
'kind': dict_safe_get(rule, [object_key, 'kind']),
'value': dict_safe_get(rule, [object_key, 'value']),
'objectId': dict_safe_get(rule, [object_key, 'objectId']),
}
for new_object_key, object_key in [
('SourceSecurity', 'srcSecurity'),
('DestinationSecurity', 'dstSecurity'),
('User', 'user'),
('TimeRange', 'timeRange'),
]
})
rules.append(
{
'Source': safe_get_all_values(obj=rule.get('sourceAddress'), key='value'),
'SourceService': source_services_list,
'Dest': safe_get_all_values(obj=rule.get('destinationAddress'), key='value'),
'DestService': dest_services_list,
'IsActive': rule.get('active'),
'Interface': rule.get('interface'),
'InterfaceType': rule.get('interface_type'),
'Remarks': rule.get('remarks'),
'Position': rule.get('position'),
'ID': rule.get('objectId'),
'Permit': rule.get('permit'),
'SourceKind': dict_safe_get(rule, ['sourceAddress', 'kind']),
'DestKind': dict_safe_get(rule, ['destinationAddress', 'kind']),
} | rule_object_mapping
)
if not rules[-1].get('Source'):
rules[-1]['Source'] = safe_get_all_values(obj=rule.get('sourceAddress'), key='objectId')
if not rules[-1].get('Dest'):
rules[-1]['Dest'] = safe_get_all_values(obj=rule.get('destinationAddress'), key='objectId')
return rules
@logger
def is_get_request_type(get_args: list, list_args: list) -> bool:
"""
Determine whether the request arguments are for a GET or LIST request.
Args:
get_args (list): GET request arguments.
list_args (list): LIST request arguments.
Raises:
ValueError: In case the user has entered both GET and LIST arguments, raise an error.
Returns:
bool: True if the arguments are for a GET request, False otherwise.
"""
is_get_request = any(get_args)
is_list_request = any(list_args)
if is_get_request and is_list_request:
raise ValueError('GET and LIST arguments can not be supported simultaneously.')
return is_get_request
@logger
def extract_data(
obj: list[dict | list] | dict[str, Any],
keys_mapping: dict[str, Any]
) -> list[dict | list] | dict[str, Any]:
"""
Extract specific keys from a nested dictionary or a list of dictionaries
based on the provided keys_mapping structure.
Args:
obj (list[dict | list] | dict[str, Any]): The input object, either a dictionary or a list of dictionaries.
keys_mapping (dict[str, Any]): A dictionary specifying the mapping of keys to extract and their new names.
Returns:
list[dict | list] | dict[str, Any]:
The extracted object, either a dictionary or a list of dictionaries.
"""
if isinstance(obj, list):
return [extract_data(nested_obj, keys_mapping) for nested_obj in obj]
return extract_data_from_dict(obj, keys_mapping)
@logger
def extract_data_from_dict(dict_obj: dict[str, Any], keys_mapping: dict[str, Any]) -> dict[str, Any]:
"""
Extract specific keys from a dictionary based on the provided keys_mapping structure.
Args:
dict_obj (dict[str, Any]): The input dictionary to extract keys from.
keys_mapping (dict[str, Any]): A dictionary specifying the mapping of keys to extract and their new names.
The keys of this dictionary should correspond to keys in the dict_obj. The values can be either:
- a string: the corresponding key in the output dictionary will have the same name.
- a nested dictionary: the key-value pairs in the nested dictionary will be extracted recursively.
Returns:
dict[str, Any]: The extracted dictionary.
"""
extracted: dict[str, Any] = {}
for key, new_key in keys_mapping.items():
if isinstance(new_key, dict) and (nested_obj := dict_obj.get(key)) is not None:
nested_keys_mapping = deepcopy(new_key)
include_key = nested_keys_mapping.pop('_include', True)
extracted_data = extract_data(nested_obj, nested_keys_mapping)
extracted |= {key: extracted_data} if include_key else extracted_data
elif (value := dict_obj.get(key)) is not None:
extracted[new_key] = value
return extracted
def arg_to_optional_bool(arg: Optional[Any]) -> Optional[bool]:
"""
Wrapper to argToBoolean function that will allow Optional arguments.
Args:
arg (Optional[Any]): The value to evaluate.
Defaults to None.
Returns:
Optional[bool]: a boolean representation of 'arg' or None.
"""
return argToBoolean(arg) if arg is not None else None
def setup_address(
rule_body: dict[str, Any],
address_direction: str,
address_value: str,
address_kind: str,
) -> None:
"""
Sets up the source or destination address in the rule_body.
Args:
rule_body (dict[str, Any]): The rule body to set up the address.
address_direction (str): 'sourceAddress' or 'destinationAddress'.
address_value (str): The value of the address.
address_kind (str): The kind of the address.
"""
if address_kind in ['NetworkObj', 'NetworkObjGroup']:
key = 'objectId'
address_kind = f'objectRef#{address_kind}'
else:
key = 'value'
rule_body[address_direction] = {'kind': address_kind, key: address_value}
def handle_address_in_rule(
rule_body: dict[str, Any],
direction: str,
address_value: str = None,
address_kind: str = None,
) -> None:
"""
Handles the address kind and value in the rule update.
Args:
rule_body (dict[str, Any]): The rule body to set up the address.
direction (str): The direction of the address, 'source' or 'destination'.
address_value (str, optional): The value of the address.
Defaults to None.
address_kind (str, optional): The kind of the address.
Defaults to None.
"""
address_direction = f'{direction}Address'
if address_value and address_kind:
setup_address(
rule_body=rule_body,
address_direction=address_direction,
address_value=address_value,
address_kind=address_kind,
)
elif address_value:
set_up_ip_kind(rule_body, address_direction, address_value)
def setup_service(
rule_body: dict[str, Any],
source_service: str,
source_service_kind: str = None,
destination_service: str = None,
destination_service_kind: str = None,
) -> None:
"""
Sets up the source and destination services.
Args:
rule_body (dict[str, Any]): The rule body to update.
source_service (str): The source service.
source_service_kind (str, optional): The kind of the source service.
Defaults to None.
destination_service (str, optional): The destination service.
Defaults to None.
destination_service_kind (str, optional): The kind of the destination service.
Defaults to None.
Raises:
ValueError: Incase the user has only provided one of the destination service arguments.
"""
rule_body['sourceService'] = {'kind': source_service_kind or 'NetworkProtocol', 'value': source_service}
if destination_service and destination_service_kind:
rule_body['destinationService'] = {'kind': destination_service_kind, 'value': destination_service}
elif destination_service or destination_service_kind:
raise ValueError('Missing arg in destination service, please provide both destination kind and value.')
else:
rule_body['destinationService'] = {'kind': 'NetworkProtocol', 'value': source_service}
def setup_security(
rule_body: dict[str, Any],
direction: str,
security_kind: str = None,
security_value: str = None,
) -> None:
"""
Sets up the source or destination security in the rule_body.
Args:
rule_body (dict[str, Any]): The rule body to set up the security.
direction (str): The direction of the security, 'source' or 'destination'.
security_kind (str, optional): The kind of the security.
Defaults to None.
security_value (str, optional): The value of the security.
Defaults to None.
Raises:
ValueError: Incase the user has only provided one of the security arguments.
"""
if security_kind and security_value:
if security_kind == 'SecurityObjGroup':
security_kind = f'objectRef#{security_kind}'
key = 'objectId'
else:
key = 'value'
rule_body[f'{direction}Security'] = {'kind': security_kind, key: security_value}
elif security_kind or security_value:
raise ValueError(f'Missing arg in {direction} security, please provide both security kind and value.')
def setup_user(
rule_body: dict[str, Any],
user: str = None,
user_kind: str = None,
) -> None:
"""
Sets up the user in the rule_body.
Args:
rule_body (dict[str, Any]): The rule body to set up the user.
user (str, optional): The user.
Defaults to None.
user_kind (str, optional): The kind of the user.
Defaults to None.
Raises:
ValueError: Incase the user has only provided one of the user arguments.
"""
if user_kind and user:
rule_body['user'] = {'kind': f'objectRef#{user_kind}', 'objectId': user}
elif user_kind or user:
raise ValueError('Missing arg in user. Please provide both user kind and value.')