-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Panorama.py
14495 lines (12193 loc) · 561 KB
/
Panorama.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
from collections import defaultdict
from dataclasses import dataclass, fields
from types import SimpleNamespace
import enum
import html
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
import panos.errors
from panos.base import PanDevice, VersionedPanObject, Root, ENTRY, VersionedParamPath # type: ignore
from panos.panorama import Panorama, DeviceGroup, Template, PanoramaCommitAll
from panos.policies import Rulebase, PreRulebase, PostRulebase, SecurityRule, NatRule
from panos.objects import (
LogForwardingProfile, LogForwardingProfileMatchList, AddressObject, AddressGroup, ServiceObject, ServiceGroup,
ApplicationObject, ApplicationGroup, SecurityProfileGroup
)
from panos.firewall import Firewall
from panos.device import Vsys
from panos.network import Zone
from urllib.error import HTTPError
import shutil
''' IMPORTS '''
import json
import uuid
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple, Union, Callable, ValuesView, Iterator
import re
import requests
import urllib3
from urllib.parse import urlparse, quote
# disable insecure warnings
urllib3.disable_warnings()
''' GLOBALS '''
URL = ''
API_KEY = None
USE_SSL = None
USE_URL_FILTERING = None
TEMPLATE = None
VSYS = ''
PRE_POST = ''
OUTPUT_PREFIX = "PANOS."
UNICODE_FAIL = u'\U0000274c'
UNICODE_PASS = u'\U00002714\U0000FE0F'
DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ' # ISO8601 format with UTC, default in XSOAR
QUERY_DATE_FORMAT = '%Y/%m/%d %H:%M:%S'
FETCH_DEFAULT_TIME = '1 day'
MAX_INCIDENTS_TO_FETCH = 100
FETCH_INCIDENTS_LOG_TYPES = ['Traffic', 'Threat', 'URL', 'Data', 'Correlation', 'System', 'Wildfire', 'Decryption']
GET_LOG_JOB_ID_MAX_RETRIES = 10
XPATH_SECURITY_RULES = ''
DEVICE_GROUP = ''
DEVICE_GROUP_PARAM_NAME = 'device_group'
DEVICE_GROUP_ARG_NAME = 'device-group'
XPATH_OBJECTS = ''
XPATH_RULEBASE = ''
# pan-os-python device timeout value, in seconds
DEVICE_TIMEOUT = 120
DEFAULT_LIMIT_PAGE_SIZE = 50
# Security rule arguments for output handling
SECURITY_RULE_ARGS = {
'rulename': 'Name',
'source': 'Source',
'destination': 'Destination',
'negate_source': 'NegateSource',
'negate_destination': 'NegateDestination',
'action': 'Action',
'service': 'Service',
'disable': 'Disabled',
'disabled': 'Disabled',
'application': 'Application',
'source_user': 'SourceUser',
'disable_server_response_inspection': 'DisableServerResponseInspection',
'description': 'Description',
'target': 'Target',
'log_forwarding': 'LogForwarding',
'log-setting': 'LogForwarding',
'tag': 'Tags',
'profile-setting': 'ProfileSetting',
'audit-comment': 'AuditComment'
}
PAN_OS_ERROR_DICT = {
'1': 'Unknown command - The specific config or operational command is not recognized.',
'2': 'Internal errors - Check with technical support when seeing these errors.',
'3': 'Internal errors - Check with technical support when seeing these errors.',
'4': 'Internal errors - Check with technical support when seeing these errors.',
'5': 'Internal errors - Check with technical support when seeing these errors.',
'6': 'Bad Xpath -The xpath specified in one or more attributes of the command is invalid.'
'Check the API browser for proper xpath values.',
'7': 'Object not present - Object specified by the xpath is not present. For example,'
'entry[@name=value] where no object with name value is present.',
'8': 'Object not unique - For commands that operate on a single object, the specified object is not unique.',
'10': 'Reference count not zero - Object cannot be deleted as there are other objects that refer to it.'
'For example, address object still in use in policy.',
'11': 'Internal error - Check with technical support when seeing these errors.',
'12': 'Invalid object - Xpath or element values provided are not complete.',
'14': 'Operation not possible - Operation is allowed but not possible in this case.'
'For example, moving a rule up one position when it is already at the top.',
'15': 'Operation denied - Operation is allowed. For example, Admin not allowed to delete own account,'
'Running a command that is not allowed on a passive device.',
'16': 'Unauthorized -The API role does not have access rights to run this query.',
'17': 'Invalid command -Invalid command or parameters.',
'18': 'Malformed command - The XML is malformed.',
# 19,20: success
'21': 'Internal error - Check with technical support when seeing these errors.',
'22': 'Session timed out - The session for this query timed out.'
}
OBJ_NOT_FOUND_ERR = 'Object was not found'
# was taken from here: https://knowledgebase.paloaltonetworks.com/KCSArticleDetail?id=kA10g000000Cm5hCAC
PAN_DB_URL_FILTERING_CATEGORIES = {
'abortion',
'abused-drugs',
'adult',
'alcohol-and-tobacco',
'auctions',
'business-and-economy',
'command-and-control',
'computer-and-internet-info',
'content-delivery-networks',
'copyright-infringement',
'cryptocurrency',
'dating',
'dynamic-dns',
'educational-institutions',
'entertainment-and-arts',
'extremism',
'financial-services',
'gambling',
'games',
'government',
'grayware',
'hacking',
'health-and-medicine',
'home-and-garden',
'hunting-and-fishing',
'insufficient-content',
'internet-Communications-and-telephony',
'internet-portals',
'job-search',
'legal',
'malware',
'military',
'motor-vehicles',
'music',
'newly-registered-domain',
'news',
'nudity',
'online-storage-and-backup',
'parked',
'peer-to-peer',
'personal-sites-and-blogs',
'philosophy-and-political-advocacy',
'phishing',
'private-ip-addresses',
'proxy-avoidance-and-anonymizers',
'questionable',
'real-estate',
'recreation-and-hobbies',
'reference-and-research ',
'religion',
'search-engines',
'sex-education',
'shareware-and-freeware',
'shopping',
'social-networking',
'society',
'sports',
'stock-advice-and-tools',
'streaming-media',
'swimsuits-and-intimate-apparel',
'training-and-tools',
'translation',
'travel',
'unknown',
'weapons',
'web-advertisements',
'web-hosting',
'web-based-email',
'high-risk',
'medium-risk',
'low-risk',
'real-time-detection',
'ransomware'
}
RULE_FILTERS = ('nat-type', 'action')
APPILICATION_FILTERS = ('risk', 'category', 'subcategory', 'technology')
CHARACTERISTICS_LIST = ('virus-ident',
'file-type-ident',
'evasive-behavior',
'consume-big-bandwidth',
'used-by-malware',
'able-to-transfer-file',
'has-known-vulnerability',
'tunnel-other-application',
'prone-to-misuse',
'pervasive-use',
'data-ident',
'file-forward',
'is-saas')
class PAN_OS_Not_Found(Exception):
""" PAN-OS Error. """
def __init__(self, *args): # real signature unknown
pass
class InvalidUrlLengthException(Exception):
pass
class PanosResponse():
class PanosNamespace(SimpleNamespace):
"""
Namespace class for the PanosResponse
"""
def __init__(self, ignored_keys: set = None, **kwargs):
if not ignored_keys:
ignored_keys = set()
super().__init__(**{k: v for k, v in kwargs.items() if k not in ignored_keys})
def __getattr__(self, attr):
"""
If an AttributeError is raised, this method is called, if the attr was not found, Returns None.
"""
return [] if attr == 'entry' else None
def __init__(self, response: dict, ignored_keys: set = None, illegal_chars: set = None):
self.raw = response
self.ns = self.to_class(response, ignored_keys=ignored_keys, illegal_chars=illegal_chars)
def get_nested_key(self, items: str):
"""
Arguments:
-------
items: string of dotted notation to retrieve
Returns:
-------
Dicitonary value of the requested items
"""
return_response = self.raw
for item in items.split("."):
return_response = return_response.get(item, {})
return return_response
def handle_illegal_chars(self, dictionary: dict, illegal_chars: set = None):
if not illegal_chars:
return dictionary
return {
key.replace(char, ''): val for key, val in dictionary.items() for char in illegal_chars
}
def to_class(self, response, ignored_keys: set = None, illegal_chars: set = None) -> PanosNamespace:
if not ignored_keys:
ignored_keys = set()
if not illegal_chars:
illegal_chars = set()
json_dump = json.dumps(response)
return json.loads(
json_dump,
object_hook=lambda d: self.PanosNamespace(
**self.handle_illegal_chars(d, illegal_chars=illegal_chars),
ignored_keys=ignored_keys
)
)
def http_request(uri: str, method: str, headers: dict = {},
body: dict = {}, params: dict = {}, files: dict = None, is_pcap: bool = False, is_xml: bool = False) -> Any:
"""
Makes an API call with the given arguments
"""
result = requests.request(
method,
uri,
headers=headers,
data=body,
verify=USE_SSL,
params=params,
files=files
)
if result.status_code < 200 or result.status_code >= 300:
raise Exception(
'Request Failed. with status: ' + str(result.status_code) + '. Reason is: ' + str(result.reason))
# if pcap download
if is_pcap:
return result
if is_xml:
return result.text
json_result = json.loads(xml2json(result.text))
# handle raw response that does not contain the response key, e.g configuration export
if ('response' not in json_result or '@code' not in json_result['response']) and \
not json_result['response']['@status'] != 'success':
return json_result
# handle non success
if json_result['response']['@status'] != 'success':
if 'msg' in json_result['response'] and 'line' in json_result['response']['msg']:
response_msg = json_result['response']['msg']['line']
# catch non existing object error and display a meaningful message
if response_msg == 'No such node':
raise Exception(
'Object was not found, verify that the name is correct and that the instance was committed.')
# catch urlfiltering error and display a meaningful message
elif str(response_msg).find('test -> url') != -1:
if DEVICE_GROUP:
raise Exception('URL filtering commands are only available on Firewall devices.')
if 'Node can be at most 1278 characters' in response_msg:
raise InvalidUrlLengthException('URL Node can be at most 1278 characters.')
raise Exception('The URL filtering license is either expired or not active.'
' Please contact your PAN-OS representative.')
# catch non valid jobID errors and display a meaningful message
elif isinstance(json_result['response']['msg']['line'], str) and \
json_result['response']['msg']['line'].find('job') != -1 and \
(json_result['response']['msg']['line'].find('not found') != -1
or json_result['response']['msg']['line'].find('No such query job')) != -1:
raise Exception('Invalid Job ID error: ' + json_result['response']['msg']['line'])
# catch already at the top/bottom error for rules and return this as an entry.note
elif str(json_result['response']['msg']['line']).find('already at the') != -1:
return_results('Rule ' + str(json_result['response']['msg']['line']))
sys.exit(0)
# catch already registered ip tags and return this as an entry.note
elif str(json_result['response']['msg']['line']).find('already exists, ignore') != -1:
if isinstance(json_result['response']['msg']['line']['uid-response']['payload']['register']['entry'],
list):
ips = [o['@ip'] for o in
json_result['response']['msg']['line']['uid-response']['payload']['register']['entry']]
else:
ips = json_result['response']['msg']['line']['uid-response']['payload']['register']['entry']['@ip']
return_results(
'IP ' + str(ips) + ' already exist in the tag. All submitted IPs were not registered to the tag.')
sys.exit(0)
# catch timed out log queries and return this as an entry.note
elif str(json_result['response']['msg']['line']).find('Query timed out') != -1:
return_results(str(json_result['response']['msg']['line']) + '. Rerun the query.')
sys.exit(0)
if '@code' in json_result['response']:
raise Exception(
'Request Failed.\nStatus code: ' + str(json_result['response']['@code']) + '\nWith message: ' + str(
json_result['response']['msg']['line']))
else:
raise Exception('Request Failed.\n' + str(json_result['response']))
# handle @code
if json_result['response']['@code'] in PAN_OS_ERROR_DICT:
error_message = 'Request Failed.\n' + PAN_OS_ERROR_DICT[json_result['response']['@code']]
if json_result['response']['@code'] == '7' and DEVICE_GROUP:
device_group_names = get_device_groups_names()
if DEVICE_GROUP not in device_group_names:
error_message += (f'\nDevice Group: {DEVICE_GROUP} does not exist.'
f' The available Device Groups for this instance:'
f' {", ".join(device_group_names)}.')
xpath = params.get('xpath') or body.get('xpath')
demisto.debug(f'Object with {xpath=} was not found')
raise PAN_OS_Not_Found(error_message)
return_warning('List not found and might be empty', True)
if json_result['response']['@code'] not in ['19', '20']:
# error code non exist in dict and not of success
if 'msg' in json_result['response']:
raise Exception(
'Request Failed.\nStatus code: ' + str(json_result['response']['@code']) + '\nWith message: ' + str(
json_result['response']['msg']))
else:
raise Exception('Request Failed.\n' + str(json_result['response']))
return json_result
def parse_pan_os_un_committed_data(dictionary, keys_to_remove):
"""
When retrieving an un-committed object from panorama, a lot of un-relevant data is returned by the api.
This function takes any api response of pan-os with data that was not committed and removes the un-relevant data
from the response recursively so the response would be just like an object that was already committed.
This must be done to keep the context aligned with both committed and un-committed objects.
Args:
dictionary (dict): The entry that the pan-os objects is in.
keys_to_remove (list): keys which should be removed from the pan-os api response
"""
for key in keys_to_remove:
if key in dictionary:
del dictionary[key]
for key in dictionary:
if isinstance(dictionary[key], dict) and '#text' in dictionary[key]:
dictionary[key] = dictionary[key]['#text']
elif isinstance(dictionary[key], list) and isinstance(dictionary[key][0], dict) \
and dictionary[key][0].get('#text'):
dictionary[key] = [text.get('#text') for text in dictionary[key]]
for value in dictionary.values():
if isinstance(value, dict):
parse_pan_os_un_committed_data(value, keys_to_remove)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
parse_pan_os_un_committed_data(item, keys_to_remove)
def do_pagination(
entries: list,
page: Optional[int] = None,
page_size: int = DEFAULT_LIMIT_PAGE_SIZE,
limit: int = DEFAULT_LIMIT_PAGE_SIZE
):
if isinstance(entries, list) and page is not None:
if page <= 0:
raise DemistoException(f'page {page} must be a positive number')
entries = entries[(page - 1) * page_size:page_size * page] # do pagination
elif isinstance(entries, list):
entries = entries[:limit]
return entries
def extract_objects_info_by_key(_entry, _key):
if isinstance(_entry, dict):
key_info = _entry.get(_key)
if not key_info: # api could not return the key
return None
if isinstance(key_info, dict) and (_member := key_info.get('member')):
return _member
elif isinstance(key_info, str):
return key_info
elif isinstance(_entry, list):
return [item.get(_key) for item in _entry]
return None
def build_body_request_to_edit_pan_os_object(
behavior,
object_name,
element_value,
is_listable,
xpath='',
should_contain_entries=True,
is_entry=False,
is_empty_tag=False,
is_commit_required=True
):
"""
This function builds up a general body-request (element) to add/remove/replace an existing pan-os object by
the requested behavior and a full xpath to the object.
Args:
behavior (str): must be one of add/remove/replace.
object_name (str): the name of the object that needs to be updated.
element_value (str): the value of the new element.
is_listable (bool): whether the object is listable or not, not relevant when behavior == 'replace'.
xpath (str): the full xpath to the object that should be edit. not required if behavior == 'replace'
should_contain_entries (bool): whether an object should contain at least one entry. True if yes, False if not.
is_entry (bool): whether the element should be of the following form:
<entry name="{entry_name}"/>
is_empty_tag (bool): whether tag should be created completely empty, for example <action/>
is_commit_required (bool): whether a commit is required when trying to add pan-os-object.
Returns:
dict: a body request for the new object to update it.
"""
if behavior not in {'replace', 'remove', 'add'}:
raise ValueError(f'behavior argument must be one of replace/remove/add values')
if behavior == 'replace':
element = prepare_pan_os_objects_body_request(
object_name, element_value, is_list=is_listable, is_entry=is_entry, is_empty_tag=is_empty_tag
)
else: # add or remove is only for listable objects.
current_objects_items = panorama_get_current_element(
element_to_change=object_name, xpath=xpath, is_commit_required=is_commit_required
)
if behavior == 'add':
updated_object_items = list((set(current_objects_items)).union(set(argToList(element_value))))
else: # remove
updated_object_items = [item for item in current_objects_items if item not in argToList(element_value)]
if not updated_object_items and should_contain_entries:
raise DemistoException(f'The object: {object_name} must have at least one item.')
element = prepare_pan_os_objects_body_request(
object_name, updated_object_items, is_list=True, is_entry=is_entry, is_empty_tag=is_empty_tag
)
return element
def prepare_pan_os_objects_body_request(key, value, is_list=True, is_entry=False, is_empty_tag=False):
if is_entry:
return {key: ''.join([f'<entry name="{entry}"/>' for entry in argToList(value)])}
if is_empty_tag:
return {key: f'<{value}/>'}
return {key: {'member': argToList(value)}} if is_list else {key: value}
def dict_to_xml(_dictionary, contains_xml_chars=False):
"""
Transforms a dict object to an XML string.
Args:
_dictionary (dict): the dict to parse into XML
contains_xml_chars (bool): whether dict contains any XML special chars such as < or >
Returns:
str: the dict representation in XML.
"""
xml = re.sub('<\/*xml2json>', '', json2xml({'xml2json': _dictionary}).decode('utf-8'))
if contains_xml_chars:
return xml.replace('>', '>').replace('<', '<')
return xml
def add_argument_list(arg: Any, field_name: str, member: Optional[bool], any_: Optional[bool] = False) -> str:
member_stringify_list = ''
if arg:
if isinstance(arg, str):
arg = [arg]
for item in arg:
member_stringify_list += '<member>' + item + '</member>'
if field_name == 'member':
return member_stringify_list
elif member:
return '<' + field_name + '>' + member_stringify_list + '</' + field_name + '>'
else:
return '<' + field_name + '>' + arg + '</' + field_name + '>'
if any_:
if member:
return '<' + field_name + '><member>any</member></' + field_name + '>'
else:
return '<' + field_name + '>any</' + field_name + '>'
else:
return ''
def add_argument(arg: Optional[str], field_name: str, member: bool) -> str:
if arg:
if member:
return '<' + field_name + '><member>' + arg + '</member></' + field_name + '>'
else:
return '<' + field_name + '>' + arg + '</' + field_name + '>'
else:
return ''
def add_argument_open(arg: Optional[str], field_name: str, member: bool) -> str:
if arg:
if member:
return '<' + field_name + '><member>' + arg + '</member></' + field_name + '>'
else:
return '<' + field_name + '>' + arg + '</' + field_name + '>'
else:
if member:
return '<' + field_name + '><member>any</member></' + field_name + '>'
else:
return '<' + field_name + '>any</' + field_name + '>'
def add_argument_yes_no(arg: Optional[str], field_name: str, option: bool = False) -> str:
if arg and arg.lower() == 'no':
result = '<' + field_name + '>' + 'no' + '</' + field_name + '>'
else:
result = '<' + field_name + '>' + ('yes' if arg else 'no') + '</' + field_name + '>'
if option:
result = '<option>' + result + '</option>'
return result
def add_argument_target(arg: Optional[str], field_name: str) -> str:
if arg:
return '<' + field_name + '>' + '<devices>' + '<entry name=\"' + arg + '\"/>' + '</devices>' + '</' + \
field_name + '>'
else:
return ''
def add_argument_profile_setting(arg: Optional[str], field_name: str) -> str:
if not arg:
return ''
member_stringify_list = '<member>' + arg + '</member>'
return '<' + field_name + '>' + '<group>' + member_stringify_list + '</group>' + '</' + field_name + '>'
def set_xpath_network(template: str = None) -> Tuple[str, Optional[str]]:
"""
Setting template xpath relevant to panorama instances.
"""
if template:
if not DEVICE_GROUP or VSYS:
raise Exception('Template is only relevant for Panorama instances.')
if not template:
template = TEMPLATE
# setting network xpath relevant to FW or panorama management
if DEVICE_GROUP:
xpath_network = f'/config/devices/entry[@name=\'localhost.localdomain\']/template/entry[@name=\'{template}\']' \
f'/config/devices/entry[@name=\'localhost.localdomain\']/network'
else:
xpath_network = "/config/devices/entry[@name='localhost.localdomain']/network"
return xpath_network, template
def prepare_security_rule_params(api_action: str = None, rulename: str = None, source: Any = None,
destination: Any = None, negate_source: str = None,
negate_destination: str = None, action: str = None, service: List[str] = None,
disable: str = None, application: List[str] = None, source_user: str = None,
category: List[str] = None, from_: str = None, to: str = None, description: str = None,
target: str = None, log_forwarding: str = None,
disable_server_response_inspection: str = None, tags: List[str] = None,
profile_setting: str = None, where: str = 'bottom', dst: str = None) -> Dict:
if application is None or len(application) == 0:
# application always must be specified and the default should be any
application = ['any']
# flake8: noqa
rulename = rulename if rulename else f'demisto-{str(uuid.uuid4())[:8]}'
params = {
'type': 'config',
'action': api_action,
'key': API_KEY,
'where': where, # default where will be bottom for BC purposes
'element': add_argument_open(action, 'action', False)
+ add_argument_target(target, 'target')
+ add_argument_open(description, 'description', False)
+ add_argument_list(source, 'source', True, True)
+ add_argument_list(destination, 'destination', True, True)
+ add_argument_list(application, 'application', True)
+ add_argument_list(category, 'category', True)
+ add_argument_open(source_user, 'source-user', True)
+ add_argument_list(from_, 'from', True, True) # default from will always be any
+ add_argument_list(to, 'to', True, True) # default to will always be any
+ add_argument_list(service, 'service', True, True)
+ add_argument_yes_no(negate_source, 'negate-source')
+ add_argument_yes_no(negate_destination, 'negate-destination')
+ add_argument_yes_no(disable, 'disabled')
+ add_argument_yes_no(disable_server_response_inspection, 'disable-server-response-inspection', True)
+ add_argument(log_forwarding, 'log-setting', False)
+ add_argument_list(tags, 'tag', True)
+ add_argument_profile_setting(profile_setting, 'profile-setting')
}
if dst:
if where not in ('before', 'after'):
raise DemistoException('Please provide a dst rule only when the where argument is before or after.')
else:
params['dst'] = dst
if DEVICE_GROUP:
if not PRE_POST:
raise Exception('Please provide the pre_post argument when configuring '
'a security rule in Panorama instance.')
else:
params['xpath'] = f"{XPATH_SECURITY_RULES}{PRE_POST}/security/rules/entry[@name='{rulename}']"
else:
params['xpath'] = f"{XPATH_SECURITY_RULES}[@name='{rulename}']"
return params
def get_pan_os_version() -> str:
"""Retrieves pan-os version
Returns:
String representation of the version
"""
params = {
'type': 'version',
'key': API_KEY
}
result = http_request(URL, 'GET', params=params)
version = result['response']['result']['sw-version']
return version
def get_pan_os_major_version() -> int:
"""Retrieves pan-os major version
Returns:
String representation of the major version
"""
major_version = int(get_pan_os_version().split('.')[0])
return major_version
def build_xpath_filter(name_match: str = None, name_contains: str = None, filters: dict = None) -> str:
xpath_prefix = ''
if name_match:
xpath_prefix = f"@name='{name_match}'"
if name_contains:
xpath_prefix = f"contains(@name,'{name_contains}')"
if filters:
for key, value in filters.items():
if key in RULE_FILTERS or key in APPILICATION_FILTERS:
if xpath_prefix:
xpath_prefix += 'and'
xpath_prefix += f"({key}='{value}')"
if key == 'tags':
for tag in value:
if xpath_prefix:
xpath_prefix += 'and'
xpath_prefix += f"(tag/member='{tag}')"
if key == 'characteristics':
for characteristic in value:
if xpath_prefix:
xpath_prefix += 'and'
xpath_prefix += f"({characteristic}='yes')"
return xpath_prefix
def filter_rules_by_status(disabled: str, rules: list) -> list:
for rule in rules:
parse_pan_os_un_committed_data(rule, ['@admin', '@dirtyId', '@time'])
if disabled.lower() == 'yes':
return list(filter(lambda x: x.get('disabled', '').lower() == 'yes', rules))
else:
return list(filter(lambda x: x.get('disabled', '').lower() != 'yes', rules))
''' FUNCTIONS'''
def panorama_test(fetch_params):
"""
test module
"""
params = {
'type': 'op',
'cmd': '<show><system><info></info></system></show>',
'key': API_KEY
}
http_request(
URL,
'GET',
params=params
)
if DEVICE_GROUP and DEVICE_GROUP != 'shared':
device_group_test()
_, template = set_xpath_network()
if template:
template_test(template)
try:
# Test the topology functionality
topology = get_topology()
test_topology_connectivity(topology)
# Test fetch incidents parameters
if fetch_params.get('isFetch'):
test_fetch_incidents_parameters(fetch_params)
except DemistoException as e:
raise e
except Exception as exception_text:
demisto.debug(f"Failed to create topology; topology commands will not work. {exception_text}")
pass
return_results('ok')
def get_device_groups_names():
"""
Get device group names in the Panorama
"""
params = {
'action': 'get',
'type': 'config',
'xpath': "/config/devices/entry/device-group/entry",
'key': API_KEY
}
result = http_request(
URL,
'GET',
params=params
)
device_groups = result['response']['result']['entry']
device_group_names = []
if isinstance(device_groups, dict):
# only one device group in the panorama
device_group_names.append(device_groups.get('@name'))
else:
for device_group in device_groups:
device_group_names.append(device_group.get('@name'))
return device_group_names
def device_group_test():
"""
Test module for the Device group specified
"""
device_group_names = get_device_groups_names()
if DEVICE_GROUP not in device_group_names:
raise Exception(f'Device Group: {DEVICE_GROUP} does not exist.'
f' The available Device Groups for this instance: {", ".join(device_group_names)}.')
def get_templates_names():
"""
Get templates names in the Panorama
"""
params = {
'action': 'get',
'type': 'config',
'xpath': "/config/devices/entry[@name=\'localhost.localdomain\']/template/entry",
'key': API_KEY
}
result = http_request(
URL,
'GET',
params=params
)
templates = result['response']['result']['entry']
template_names = []
if isinstance(templates, dict):
# only one device group in the panorama
template_names.append(templates.get('@name'))
else:
for template in templates:
template_names.append(template.get('@name'))
return template_names
def template_test(template: str):
"""
Test module for the Template specified
"""
template_names = get_templates_names()
if template not in template_names:
raise Exception(f'Template: {template} does not exist.'
f' The available Templates for this instance: {", ".join(template_names)}.')
@logger
def panorama_command(args: dict):
"""
Executes a command
"""
params = {}
for arg in args.keys():
params[arg] = args[arg]
params['key'] = API_KEY
result = http_request(
URL,
'POST',
body=params
)
return_results({
'Type': entryTypes['note'],
'ContentsFormat': formats['json'],
'Contents': result,
'ReadableContentsFormat': formats['text'],
'HumanReadable': 'Command was executed successfully.',
})
@logger
def panorama_commit(args):
command: str = ''
partial_command: str = ''
is_partial = False
if device_group := args.get('device-group'):
command += f'<device-group><entry name="{device_group}"/></device-group>'
admin_name = args.get('admin_name')
if admin_name:
is_partial = True
partial_command += f'<admin><member>{admin_name}</member></admin>'
force_commit = argToBoolean(args.get('force_commit')) if args.get('force_commit') else None
if force_commit:
command += '<force></force>'
exclude_device_network = args.get('exclude_device_network_configuration')
exclude_device_network_configuration = argToBoolean(exclude_device_network) if exclude_device_network else None
if exclude_device_network_configuration:
is_partial = True
partial_command += '<device-and-network>excluded</device-and-network>'
exclude_shared_objects_str = args.get('exclude_shared_objects')
exclude_shared_objects = argToBoolean(exclude_shared_objects_str) if exclude_shared_objects_str else None
if exclude_shared_objects:
is_partial = True
partial_command += '<shared-object>excluded</shared-object>'
if is_partial:
command = f'{command}<partial>{partial_command}</partial>'
params = {
'type': 'commit',
'cmd': f'<commit>{command}</commit>',
'key': API_KEY
}
if is_partial:
params['action'] = 'partial'
result = http_request(
URL,
'POST',
body=params
)
return result
@polling_function(
name=demisto.command(), # should fit to both pan-os-commit and panorama-commit (deprecated)
interval=arg_to_number(demisto.args().get('interval_in_seconds', 10)),
timeout=arg_to_number(demisto.args().get('timeout', 120))
)
def panorama_commit_command(args: dict):
"""
Commit any configuration in PAN-OS
This function implements the 'pan-os-commit' command.
Supports polling as well.
"""
commit_description = args.get('description', '')
if job_id := args.get('commit_job_id'):
commit_status = panorama_commit_status({'job_id': job_id}).get('response', {}).get('result', {})
job_result = commit_status.get('job', {}).get('result')
commit_output = {
'JobID': job_id,
'Description': commit_description,
'Status': 'Success' if job_result == 'OK' else 'Failure'
}
return PollResult(
response=CommandResults( # this is what the response will be in case job has finished
outputs_prefix='Panorama.Commit',
outputs_key_field='JobID',
outputs=commit_output,
readable_output=tableToMarkdown('Commit Status:', commit_output, removeNull=True)
),
continue_to_poll=commit_status.get('job', {}).get('status') != 'FIN', # continue polling if job isn't done
)
else: # either no polling is required or this is the first run
result = panorama_commit(args)
job_id = result.get('response', {}).get('result', {}).get('job', '')
if job_id:
context_output = {
'JobID': job_id,
'Description': commit_description,
'Status': 'Pending'
}
continue_to_poll = True
commit_output = CommandResults( # type: ignore[assignment]
outputs_prefix='Panorama.Commit',
outputs_key_field='JobID',
outputs=context_output,
readable_output=tableToMarkdown('Commit Status:', context_output, removeNull=True)
)
else: # nothing to commit in pan-os, hence even if polling=true, no reason to poll anymore.
commit_output = result.get('response', {}).get('msg') or 'There are no changes to commit.' # type: ignore[assignment]
continue_to_poll = False
return PollResult(
response=commit_output,
continue_to_poll=continue_to_poll,
args_for_next_run={
'commit_job_id': job_id,
'description': commit_description,
'polling': argToBoolean(args.get('polling')),
'interval_in_seconds': arg_to_number(args.get('interval_in_seconds')),
'timeout': arg_to_number(args.get('timeout'))
},