/
Panorama_test.py
7167 lines (6194 loc) · 306 KB
/
Panorama_test.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 json
from defusedxml import ElementTree
import pytest
import requests_mock
import demistomock as demisto
from unittest.mock import patch, MagicMock
from panos.device import Vsys
from panos.panorama import Panorama, DeviceGroup, Template
from panos.firewall import Firewall
from CommonServerPython import DemistoException, CommandResults
from panos.objects import LogForwardingProfile, LogForwardingProfileMatchList
import dateparser
from test_data import fetch_incidents_input
from test_data import mock_rules
from freezegun import freeze_time
integration_firewall_params = {
'port': '443',
'vsys': 'vsys1',
'server': 'https://1.1.1.1',
'key': 'thisisabogusAPIKEY!',
}
mock_demisto_args = {
'threat_id': "11111",
'vulnerability_profile': "mock_vuln_profile"
}
integration_panorama_params = {
'port': '443',
'device_group': 'Lab-Devices',
'server': 'https://1.1.1.1',
'key': 'thisisabogusAPIKEY!',
'template': 'test'
}
def load_json(path):
with open(path, encoding='utf-8') as f:
return json.loads(f.read())
@pytest.fixture(autouse=True)
def set_params(mocker):
mocker.patch.object(demisto, 'params', return_value=integration_firewall_params)
mocker.patch.object(demisto, 'args', return_value=mock_demisto_args)
@pytest.fixture
def patched_requests_mocker(requests_mock):
"""
This function mocks various PANOS API responses so we can accurately test the instance
"""
base_url = "{}:{}/api/".format(integration_firewall_params['server'], integration_firewall_params['port'])
# Version information
mock_version_xml = """
<response status = "success">
<result>
<sw-version>9.0.6</sw-version>
<multi-vsys>off</multi-vsys>
<model>Panorama</model>
<serial>FAKESERIALNUMBER</serial>
</result>
</response>
"""
version_path = "{}{}{}".format(base_url, "?type=version&key=", integration_firewall_params['key'])
requests_mock.get(version_path, text=mock_version_xml, status_code=200)
mock_response_xml = """
<response status="success" code="20">
<msg>command succeeded</msg>
</response>
"""
requests_mock.post(base_url, text=mock_response_xml, status_code=200)
return requests_mock
def test_panorama_get_os_version(patched_requests_mocker):
from Panorama import get_pan_os_version
import Panorama
Panorama.URL = 'https://1.1.1.1:443/api/'
Panorama.API_KEY = 'thisisabogusAPIKEY!'
r = get_pan_os_version()
assert r == '9.0.6'
def test_panorama_override_vulnerability(patched_requests_mocker):
from Panorama import panorama_override_vulnerability
import Panorama
Panorama.URL = 'https://1.1.1.1:443/api/'
r = panorama_override_vulnerability(mock_demisto_args['threat_id'], mock_demisto_args['vulnerability_profile'],
'reset-both')
assert r['response']['@status'] == 'success'
def test_add_argument_list():
from Panorama import add_argument_list
list_argument = ["foo", "bar"]
response_with_member = add_argument_list(list_argument, "test", True)
expected_with_member = '<test><member>foo</member><member>bar</member></test>'
assert response_with_member == expected_with_member
response_with_member_field_name = add_argument_list(list_argument, "member", True)
expected_with_member_field_name = '<member>foo</member><member>bar</member>'
assert response_with_member_field_name == expected_with_member_field_name
def test_add_argument():
from Panorama import add_argument
argument = "foo"
response_with_member = add_argument(argument, "test", True)
expected_with_member = '<test><member>foo</member></test>'
assert response_with_member == expected_with_member
response_without_member = add_argument(argument, "test", False)
expected_without_member = '<test>foo</test>'
assert response_without_member == expected_without_member
def test_add_argument_yes_no():
from Panorama import add_argument_yes_no
arg = 'No'
field = 'test'
option = True
response_option_true = add_argument_yes_no(arg, field, option)
expected_option_true = '<option><test>no</test></option>'
assert response_option_true == expected_option_true
option = False
response_option_false = add_argument_yes_no(arg, field, option)
expected_option_false = '<test>no</test>'
assert response_option_false == expected_option_false
def test_add_argument_target():
from Panorama import add_argument_target
response = add_argument_target('foo', 'bar')
expected = '<bar><devices><entry name=\"foo\"/></devices></bar>'
assert response == expected
@pytest.mark.parametrize('disabled, rules_file, expected_results_file',
[
('yes', 'test_data/filter_rules_sample.json',
'test_data/filter_rules_expected_result.json'),
])
def test_filter_rules_by_status(disabled: str, rules_file: str, expected_results_file: str):
from Panorama import filter_rules_by_status
with open(rules_file) as f:
rules = json.loads(f.read())
with open(expected_results_file) as f:
expected_result = json.loads(f.read())
result = filter_rules_by_status(disabled, rules)
assert result == expected_result
def test_get_address(mocker):
"""
Given:
- an address_name argument which does not exist
When:
- running the panorama_get_address function
Then:
- Ensure the return value is an empty dictionary
"""
import Panorama
from Panorama import panorama_get_address
exception_msg = 'Object was not found, verify that the name is correct and that the instance was committed.'
mocker.patch.object(Panorama, "http_request", side_effect=Exception(exception_msg))
result = panorama_get_address("TEST")
assert result == {}
def test_get_address_command(mocker):
"""
Given:
- an address_name argument which does not exist
When:
- running the panorama_get_address_command function
Then:
- Ensure the return value is None, without any errors, and return_results contains the correct informative message.
"""
import Panorama
from Panorama import panorama_get_address_command
mocker.patch.object(Panorama, "panorama_get_address", return_value={})
return_results_mock = mocker.patch.object(Panorama, 'return_results')
result = panorama_get_address_command({'name': 'TEST'})
assert not result
assert return_results_mock.call_args[0][0] == 'Address name TEST was not found'
def test_prettify_addresses_arr():
from Panorama import prettify_addresses_arr
addresses_arr = [{'@name': 'my_name', 'fqdn': 'a.com'},
{'@name': 'my_name2', 'fqdn': 'b.com'},
{'@name': 'test', 'ip-netmask': '1.1.1.1', 'tag': None}]
response = prettify_addresses_arr(addresses_arr)
expected = [{'Name': 'my_name', 'FQDN': 'a.com'},
{'Name': 'my_name2', 'FQDN': 'b.com'},
{'Name': 'test', 'IP_Netmask': '1.1.1.1'}]
assert response == expected
def test_prettify_address():
from Panorama import prettify_address
address = {'@name': 'my_name', 'ip-netmask': '1.1.1.1', 'description': 'lala'}
response = prettify_address(address)
expected = {'Name': 'my_name', 'IP_Netmask': '1.1.1.1', 'Description': 'lala'}
assert response == expected
def test_prettify_address_tag_none():
from Panorama import prettify_address
address = {'@name': 'test', 'ip-netmask': '1.1.1.1', 'tag': None}
response = prettify_address(address)
expected = {'Name': 'test', 'IP_Netmask': '1.1.1.1'}
assert response == expected
def test_prettify_address_group():
from Panorama import prettify_address_group
address_group_static = {'@name': 'foo', 'static': {'member': 'address object'}}
response_static = prettify_address_group(address_group_static)
expected_address_group_static = {'Name': 'foo', 'Type': 'static', 'Addresses': 'address object'}
assert response_static == expected_address_group_static
address_group_dynamic = {'@name': 'foo', 'dynamic': {'filter': '1.1.1.1 and 2.2.2.2'}}
response_dynamic = prettify_address_group(address_group_dynamic)
expected_address_group_dynamic = {'Name': 'foo', 'Type': 'dynamic', 'Match': '1.1.1.1 and 2.2.2.2'}
assert response_dynamic == expected_address_group_dynamic
address_group_dynamic_tag_none = {'@name': 'foo', 'dynamic': {'filter': '1.1.1.1 or 2.2.2.2'}, 'tag': None}
response_dynamic_tag_none = prettify_address_group(address_group_dynamic_tag_none)
expected_address_group_dynamic_tag_none = {'Name': 'foo', 'Type': 'dynamic', 'Match': '1.1.1.1 or 2.2.2.2'}
assert response_dynamic_tag_none == expected_address_group_dynamic_tag_none
def test_prettify_service():
from Panorama import prettify_service
service = {'@name': 'service_name', 'description': 'foo', 'protocol': {'tcp': {'port': '443'}}}
response = prettify_service(service)
expected = {'Name': 'service_name', 'Description': 'foo', 'Protocol': 'tcp', 'DestinationPort': '443'}
assert response == expected
def test_prettify_service_tag_none():
from Panorama import prettify_service
service = {'@name': 'service_name', 'description': 'foo', 'protocol': {'tcp': {'port': '443'}}, 'tag': None}
response = prettify_service(service)
expected = {'Name': 'service_name', 'Description': 'foo', 'Protocol': 'tcp', 'DestinationPort': '443'}
assert response == expected
def test_prettify_service_group():
from Panorama import prettify_service_group
service_group = {'@name': 'sg', 'members': {'member': ['service1', 'service2']}}
response = prettify_service_group(service_group)
expected = {'Name': 'sg', 'Services': ['service1', 'service2']}
assert response == expected
def test_prettify_service_group_tag_none():
from Panorama import prettify_service_group
service_group = {'@name': 'sg_group', 'members': {'member': ['service1', 'service2']}, 'tag': None}
response = prettify_service_group(service_group)
expected = {'Name': 'sg_group', 'Services': ['service1', 'service2']}
assert response == expected
def test_prettify_custom_url_category():
from Panorama import prettify_custom_url_category
custom_url_category = {'@name': 'foo', 'list': {'member': ['a', 'b', 'c']}}
response = prettify_custom_url_category(custom_url_category)
expected = {'Name': 'foo', 'Sites': ['a', 'b', 'c']}
assert response == expected
def test_panorama_create_custom_url_category_8_x(mocker):
"""
Given:
- an only > 9.x valid argument for custom url category creation
When:
- running the panorama_create_custom_url_category function
- mocking the pan-os version to be 8.x
Then:
- a proper error is raised
"""
from Panorama import panorama_create_custom_url_category
mocker.patch('Panorama.get_pan_os_major_version', return_value=8)
custom_url_category_name = 'name'
description = 'test_desc'
type_ = 'URL List'
with pytest.raises(DemistoException,
match='The type and categories arguments are only relevant for PAN-OS 9.x versions.'):
panorama_create_custom_url_category(custom_url_category_name, type_=type_, description=description)
def test_panorama_create_custom_url_category_9_x(mocker):
"""
Given:
- a non valid argument for custom url category creation
When:
- running the panorama_create_custom_url_category function
- mocking the pan-os version to be 9.x
Then:
- a proper error is raised
"""
from Panorama import panorama_create_custom_url_category
mocker.patch('Panorama.get_pan_os_major_version', return_value=9)
custom_url_category_name = 'name'
type_ = 'URL List'
categories = 'phishing'
sites = 'a.com'
description = 'test_desc'
with pytest.raises(DemistoException,
match='The type argument is mandatory for PAN-OS 9.x versions.'):
panorama_create_custom_url_category(custom_url_category_name, sites=sites, description=description)
with pytest.raises(DemistoException,
match='Exactly one of the sites and categories arguments should be defined.'):
panorama_create_custom_url_category(custom_url_category_name, type_=type_, sites=sites, categories=categories)
with pytest.raises(DemistoException,
match='URL List type is only for sites, Category Match is only for categories.'):
panorama_create_custom_url_category(custom_url_category_name, type_=type_, categories=categories)
def test_create_url_filter_params_8_x(mocker):
"""
Given:
- a valid argument for url filter creation
When:
- running the create_url_filter_params utility function
- mocking the pan-os version to be 8.x
Then:
- a proper xml element is generated
"""
from Panorama import create_url_filter_params
mocker.patch('Panorama.get_pan_os_major_version', return_value=8)
url_filter_name = 'name'
action = 'alert'
url_category_list = 'adult'
description = 'test_desc'
url_filter_params = create_url_filter_params(url_filter_name, action, url_category_list=url_category_list,
description=description)
assert url_filter_params['element'].find('<action>block</action>') != -1 # if not -1, then it is found
def test_create_url_filter_params_9_x(mocker):
"""
Given:
- a valid argument for url filter creation
When:
- running the create_url_filter_params utility function
- mocking the pan-os version to be 9.x
Then:
- a proper xml element is generated
"""
from Panorama import create_url_filter_params
mocker.patch('Panorama.get_pan_os_major_version', return_value=9)
url_filter_name = 'name'
action = 'alert'
url_category_list = 'adult'
description = 'test_desc'
url_filter_params = create_url_filter_params(url_filter_name, action, url_category_list=url_category_list,
description=description)
assert url_filter_params['element'].find('<action>block</action>') == -1 # if -1, then it is not found
def test_edit_url_filter_non_valid_args_8_x(mocker):
"""
Given:
- a non valid argument for edit url filter
When:
- running the edit_url_filter function
- mocking the pan-os version to be 8.x
Then:
- a proper error is raised
"""
from Panorama import panorama_edit_url_filter
url_filter_object = {
"@name": "fw_test_pb_dont_delete",
"action": "block",
"allow": {
"member": [
"Demisto- block sites",
"test3"
]
},
"allow-list": {
"member": "www.thepill2.com"
},
"block": {
"member": [
"abortion",
"abused-drugs"
]
},
"block-list": {
"member": "www.thepill.com"
},
"credential-enforcement": {
"allow": {
"member": [
"Demisto- block sites",
"test3"
]
},
"block": {
"member": [
"abortion",
"abused-drugs"
]
},
"log-severity": "medium",
},
"description": "gogo"
}
mocker.patch('Panorama.get_pan_os_major_version', return_value=8)
mocker.patch('Panorama.panorama_get_url_filter', return_value=url_filter_object)
url_filter_name = 'fw_test_pb_dont_delete'
element_to_change = 'allow_categories'
element_value = 'gambling'
add_remove_element = 'remove'
err_msg = 'Only the override_allow_list, override_block_list, description properties can be' \
' changed in PAN-OS 8.x or earlier versions.'
with pytest.raises(DemistoException, match=err_msg):
panorama_edit_url_filter(url_filter_name, element_to_change, element_value, add_remove_element)
def test_edit_url_filter_non_valid_args_9_x(mocker):
"""
Given:
- a non valid argument for edit url filter
When:
- running the edit_url_filter function
- mocking the pan-os version to be 9.x
Then:
- a proper error is raised
"""
from Panorama import panorama_edit_url_filter
url_filter_object = {
"@name": "fw_test_pb_dont_delete",
"allow": {
"member": "Test_pb_custom_url_DONT_DELETE"
},
"credential-enforcement": {
"block": {
"member": [
"gambling",
"abortion"
]
},
"log-severity": "medium",
},
"description": "wowo"
}
mocker.patch('Panorama.get_pan_os_major_version', return_value=9)
mocker.patch('Panorama.panorama_get_url_filter', return_value=url_filter_object)
url_filter_name = 'fw_test_pb_dont_delete'
element_to_change = 'override_block_list'
element_value = 'gambling'
add_remove_element = 'remove'
err_msg = 'Only the allow_categories, block_categories, description properties can be changed in PAN-OS 9.x or' \
' later versions.'
with pytest.raises(DemistoException, match=err_msg):
panorama_edit_url_filter(url_filter_name, element_to_change, element_value, add_remove_element)
def http_mock(url: str, method: str, body: dict = {}):
return body
@pytest.mark.parametrize('category_name, items', [('category_name', ['www.good.com'],)])
def test_remove_from_custom_url_category(category_name, items, mocker):
"""
Given:
- a valid argument for edit custom url group
When:
- running the custom_url_category_remove_items function
Then:
- checks an assertion
"""
import Panorama
from Panorama import panorama_custom_url_category_remove_items
return_results_mock = mocker.patch.object(Panorama, 'return_results')
mocker.patch('Panorama.panorama_get_custom_url_category', return_value={'description': 'description',
'list': {'member': "www.test.com"}
})
mocker.patch('Panorama.get_pan_os_major_version', return_value=9)
mocker.patch('Panorama.http_request', side_effect=http_mock)
panorama_custom_url_category_remove_items(category_name, items, "URL List")
demisto_result_got = return_results_mock.call_args.args[0]['Contents']
assert "www.test.com" in demisto_result_got['element']
class TestQueryLogsCommand:
@staticmethod
def create_logs_query_queue(status_count, no_logs_found):
response_queue = [
MockedResponse(
text='<response status="success" code="19"><result><msg><line>query '
'job enqueued with jobid 1</line></msg><job>1</job></result></response>',
status_code=200
)
]
for _ in range(status_count):
response_queue.append(
MockedResponse(
text='<response status="success"><result><job><tenq>15:05:47</tenq><tdeq>15:05:47</tdeq><tlast>'
'01:00:00</tlast><status>ACT</status><id>1238</id></job><log><logs count="0" progress="20"/'
'></log></result></response>',
status_code=200
)
)
if no_logs_found:
# job has finished without finding any logs
response_queue.append(
MockedResponse(
text='<response status="success"><result><job><tenq>15:05:47</tenq><tdeq>15:05:47</tdeq><tlast>'
'15:06:52</tlast><status>FIN</status><id>1</id></job><log><logs count="0"'
' progress="100"/></log></result></response>',
status_code=200
)
)
else:
with open('test_data/query_logs.xml') as f:
# job has finished with finding logs
response_queue.append(
MockedResponse(
text=f.read(),
status_code=200
)
)
return response_queue
def test_query_logs_command_without_polling(self, mocker):
"""
Given
- an api response indicating a log query job has been created
When
- querying logs without polling
Then
- make sure polling is not triggered.
- make sure context output indicates that the status of the job is 'Pending'
"""
import Panorama
import requests
from Panorama import panorama_query_logs_command
Panorama.API_KEY = 'thisisabogusAPIKEY!'
mocker.patch.object(
requests,
'request',
return_value=MockedResponse(
text='<response status="success" code="19"><result><msg><line>query '
'job enqueued with jobid 1</line></msg><job>1</job></result></response>',
status_code=200
)
)
command_result = panorama_query_logs_command({'log-type': 'traffic', 'polling': 'false'})
assert command_result.outputs == {
'JobID': '1', 'Status': 'Pending', 'LogType': 'traffic', 'Message': 'query job enqueued with jobid 1'
}
assert not command_result.scheduled_command
assert command_result.readable_output == '### Query Logs:\n|JobID|Status|\n|---|---|\n| 1 | Pending |\n'
@pytest.mark.parametrize(
'status_count, no_logs_found', [(1, False), (2, True), (3, False), (5, True), (8, False), (10, True)]
)
def test_query_logs_command_with_polling(self, mocker, status_count, no_logs_found):
"""
Given
- a queue of api responses
- responses indicating query logs succeeded or not succeeded.
- a status count which means how many times polling was done.
When
- querying logs with polling
Then
- make sure the readable output indicating polling is active is printed only once.
- make sure context is returned only at the end of polling, and that the context is valid
if there are logs available and if there aren't.
"""
import Panorama
import requests
from Panorama import panorama_query_logs_command
from CommonServerPython import ScheduledCommand
Panorama.API_KEY = 'thisisabogusAPIKEY!'
mocker.patch.object(
requests,
'request',
side_effect=self.create_logs_query_queue(status_count=status_count, no_logs_found=no_logs_found)
)
mocker.patch.object(ScheduledCommand, 'raise_error_if_not_supported', return_value=None)
command_result = panorama_query_logs_command({'log-type': 'traffic', 'polling': 'true'})
assert command_result.readable_output == 'Fetching traffic logs for job ID 1...'
assert not command_result.outputs # no context should be returned until polling is done.
polling_args = {
'query_log_job_id': '1', 'hide_polling_output': True, 'polling': True, 'log-type': 'traffic'
}
command_result = panorama_query_logs_command(polling_args)
while command_result.scheduled_command: # if scheduled_command is set, it means that command should still poll
assert not command_result.readable_output # make sure that indication of polling is printed only once
assert not command_result.outputs # make sure no context output is being returned to war-room during polling
command_result = panorama_query_logs_command(polling_args)
if no_logs_found:
assert command_result.outputs == {'JobID': '1', 'LogType': 'traffic', 'Logs': [], 'Status': 'Completed'}
else:
partial_expected_outputs = {'JobID': '1', 'LogType': 'traffic', 'Status': 'Completed'}
assert partial_expected_outputs.items() <= command_result.outputs.items()
assert 'Logs' in command_result.outputs
assert command_result.outputs['Logs'] # make sure there are log outputs available.
def test_prettify_edl():
from Panorama import prettify_edl
edl = {'@name': 'edl_name', 'type': {'my_type': {'url': 'abc.com', 'description': 'my_desc'}}}
response = prettify_edl(edl)
expected = {'Name': 'edl_name', 'Type': 'my_type', 'URL': 'abc.com', 'Description': 'my_desc'}
assert response == expected
def test_build_traffic_logs_query():
"""
Given:
- a valid arguments for traffic logs query generation
When:
- running the build_traffic_logs_query utility function
Then:
- a proper query is generated
(addr.src in 192.168.1.222) and (app eq netbios-dg) and (action eq allow) and (port.dst eq 138)
"""
from Panorama import build_traffic_logs_query
source = '192.168.1.222'
application = 'netbios-dg'
action = 'allow'
to_port = '138'
response = build_traffic_logs_query(source, None, None, application, to_port, action)
expected = '(addr.src in 192.168.1.222) and (app eq netbios-dg) and (port.dst eq 138) and (action eq allow)'
assert response == expected
def test_prettify_traffic_logs():
from Panorama import prettify_traffic_logs
traffic_logs = [{'action': 'my_action1', 'category': 'my_category1', 'rule': 'my_rule1'},
{'action': 'my_action2', 'category': 'my_category2', 'rule': 'my_rule2'}]
response = prettify_traffic_logs(traffic_logs)
expected = [{'Action': 'my_action1', 'Category': 'my_category1', 'Rule': 'my_rule1'},
{'Action': 'my_action2', 'Category': 'my_category2', 'Rule': 'my_rule2'}]
assert response == expected
def test_build_logs_query():
"""
Given:
- a valid arguments for logs query generation
When:
- running the build_logs_query utility function
Then:
- a proper query is generated
((url contains 'demisto.com') or (url contains 'paloaltonetworks.com'))
"""
from Panorama import build_logs_query
urls_as_string = "demisto.com, paloaltonetworks.com"
response = build_logs_query(None, None, None, None, None, None, None, None, None, urls_as_string, None)
expected = "((url contains 'demisto.com') or (url contains 'paloaltonetworks.com'))"
assert response == expected
def test_prettify_logs():
from Panorama import prettify_logs
traffic_logs = [{'action': 'my_action1', 'category': 'my_category1', 'rule': 'my_rule1', 'natdport': '100',
'bytes': '12'},
{'action': 'my_action2', 'category': 'my_category2', 'rule': 'my_rule2', 'natdport': '101',
'bytes_sent': '11'}]
response = prettify_logs(traffic_logs)
expected = [{'Action': 'my_action1', 'CategoryOrVerdict': 'my_category1', 'Rule': 'my_rule1',
'NATDestinationPort': '100', 'Bytes': '12'},
{'Action': 'my_action2', 'CategoryOrVerdict': 'my_category2', 'Rule': 'my_rule2',
'NATDestinationPort': '101', 'BytesSent': '11'}]
assert response == expected
prepare_security_rule_inputs = [
('after', 'test_rule_name', ['user1'], '<source-user><member>user1</member></source-user>'),
('after', 'test_rule_name', ['user1,user2'], '<source-user><member>user1,user2</member></source-user>'),
]
@pytest.mark.parametrize('where, dst, source_user, expected_result', prepare_security_rule_inputs)
def test_prepare_security_rule_params(where, dst, source_user, expected_result):
"""
Given:
- valid arguments for the prepare_security_rule_params function
When:
- running the prepare_security_rule_params utility function
Then:
- a valid security rule dictionary is returned.
"""
from Panorama import prepare_security_rule_params
params = prepare_security_rule_params(api_action='set', action='drop', destination=['any'], source=['any'],
rulename='test', where=where, dst=dst, source_user=source_user)
assert expected_result in params.get('element', '')
prepare_security_rule_fail_inputs = [
('top', 'test_rule_name'),
('bottom', 'test_rule_name'),
]
@pytest.mark.parametrize('where, dst', prepare_security_rule_fail_inputs)
def test_prepare_security_rule_params_fail(where, dst):
"""
Given:
- a non valid arguments for the prepare_security_rule_params function
When:
- running the prepare_security_rule_params utility function
Then:
- a proper exception is raised
"""
from Panorama import prepare_security_rule_params
err_msg = 'Please provide a dst rule only when the where argument is before or after.'
with pytest.raises(DemistoException, match=err_msg):
prepare_security_rule_params(api_action='set', action='drop', destination=['any'], source=['any'],
rulename='test', where=where, dst=dst)
def test_build_policy_match_query():
"""
Given:
- a valid arguments for policy match query generation
When:
- running the build_policy_match_query utility function
Then:
- a proper xml is generated
"""
from Panorama import build_policy_match_query
source = '1.1.1.1'
destination = '6.7.8.9'
protocol = '1'
application = 'gmail-base'
response = build_policy_match_query(application, None, destination, None, None, None, protocol, source)
expected = '<test><security-policy-match><source>1.1.1.1</source><destination>6.7.8.9</destination>' \
'<protocol>1</protocol><application>gmail-base</application></security-policy-match></test>'
assert response == expected
def test_panorama_register_ip_tag_command_wrongful_args(mocker):
"""
Given:
- a non valid arguments for the panorama_register_ip_tag_command function
When:
- running the panorama_register_ip_tag_command function
Then:
- a proper exception is raised
"""
from Panorama import panorama_register_ip_tag_command
args = {'IPs': '1.1.1.1', 'tag': 'test_tag', 'persistent': 'false', 'timeout': '5'}
mocker.patch('Panorama.get_pan_os_major_version', return_value=8)
with pytest.raises(DemistoException,
match='The timeout argument is only applicable on 9.x PAN-OS versions or higher.'):
panorama_register_ip_tag_command(args)
def test_prettify_matching_rule():
from Panorama import prettify_matching_rule
matching_rule = {'action': 'my_action1', '@name': 'very_important_rule', 'source': '6.7.8.9', 'destination': 'any'}
response = prettify_matching_rule(matching_rule)
expected = {'Action': 'my_action1', 'Name': 'very_important_rule', 'Source': '6.7.8.9', 'Destination': 'any'}
assert response == expected
def test_prettify_static_route():
from Panorama import prettify_static_route
static_route = {'@name': 'name1', 'destination': '1.2.3.4', 'metric': '10', 'nexthop': {'fqdn': 'demisto.com'}}
virtual_router = 'my_virtual_router'
response = prettify_static_route(static_route, virtual_router)
expected = {'Name': 'name1', 'Destination': '1.2.3.4', 'Metric': 10,
'NextHop': 'demisto.com', 'VirtualRouter': 'my_virtual_router'}
assert response == expected
def test_validate_search_time():
from Panorama import validate_search_time
assert validate_search_time('2019/12/26')
assert validate_search_time('2019/12/26 00:00:00')
with pytest.raises(Exception):
assert validate_search_time('219/12/26 00:00:00')
assert validate_search_time('219/10/35')
def test_show_user_id_interface_config_command():
"""
Given:
- missing template and template_stack arguments for the show_user_id_interface_config_command command
When:
- running the show_user_id_interface_config_request function
Then:
- a proper exception is raised
"""
from Panorama import show_user_id_interface_config_command
args = {}
str_match = 'In order to show the User Interface configuration in your Panorama, ' \
'supply either the template or the template_stack arguments.'
with pytest.raises(DemistoException, match=str_match):
show_user_id_interface_config_command(args)
def test_prettify_user_interface_config():
from Panorama import prettify_user_interface_config
raw_response = [{'@name': 'internal', 'network': {'layer3': {'member': 'ethernet1/2'},
'log-setting': 'ToLoggingService'},
'enable-user-identification': 'yes'},
{'@name': 'External', 'network': {'tap': {'member': 'ethernet1/1'},
'log-setting': 'ToLoggingService'}}]
response = prettify_user_interface_config(raw_response)
expected = [{'Name': 'ethernet1/2', 'Zone': 'internal', 'EnableUserIdentification': 'yes'},
{'Name': 'ethernet1/1', 'Zone': 'External', 'EnableUserIdentification': 'no'}]
assert response == expected
def test_list_configured_user_id_agents_command(mocker):
"""
Given:
- missing template and template_stack arguments for the list_configured_user_id_agents_command command
When:
- running the list_configured_user_id_agents_request function
Then:
- a proper exception is raised
"""
from Panorama import list_configured_user_id_agents_command
mocker.patch('Panorama.get_pan_os_major_version', return_value=9)
args = {}
str_match = 'In order to show the the User ID Agents in your Panorama, ' \
'supply either the template or the template_stack arguments.'
with pytest.raises(DemistoException, match=str_match):
list_configured_user_id_agents_command(args)
def test_prettify_configured_user_id_agents__multi_result():
from Panorama import prettify_configured_user_id_agents
raw_response = [{'@name': 'testing2', 'serial-number': 'panorama2'},
{'@name': 'fullinfo', 'host-port': {'port': '67', 'ntlm-auth': 'yes',
'ldap-proxy': 'yes', 'collectorname': 'demisto',
'secret': 'secret', 'host': 'what'}, 'ip-user-mappings': 'yes'}]
response = prettify_configured_user_id_agents(raw_response)
expected = [{'Name': 'testing2', 'Host': None, 'Port': None, 'NtlmAuth': 'no', 'LdapProxy': 'no',
'CollectorName': None, 'Secret': None, 'EnableHipCollection': 'no', 'SerialNumber': 'panorama2',
'IpUserMapping': 'no', 'Disabled': 'no'},
{'Name': 'fullinfo', 'Host': 'what', 'Port': '67', 'NtlmAuth': 'yes', 'LdapProxy': 'yes',
'CollectorName': 'demisto', 'Secret': 'secret', 'EnableHipCollection': 'no', 'SerialNumber': None,
'IpUserMapping': 'yes', 'Disabled': 'no'}]
assert response == expected
def test_prettify_configured_user_id_agents__single_result():
from Panorama import prettify_configured_user_id_agents
raw_response = {'@name': 'fullinfo', 'host-port': {'port': '67', 'ntlm-auth': 'yes',
'ldap-proxy': 'yes', 'collectorname': 'demisto',
'secret': 'secret', 'host': 'what'}, 'ip-user-mappings': 'yes'}
response = prettify_configured_user_id_agents(raw_response)
expected = {'Name': 'fullinfo', 'Host': 'what', 'Port': '67', 'NtlmAuth': 'yes', 'LdapProxy': 'yes',
'CollectorName': 'demisto', 'Secret': 'secret', 'EnableHipCollection': 'no', 'SerialNumber': None,
'IpUserMapping': 'yes', 'Disabled': 'no'}
assert response == expected
def test_prettify_rule():
from Panorama import prettify_rule
with open("test_data/rule.json") as f:
rule = json.load(f)
with open("test_data/prettify_rule.json") as f:
expected_pretty_rule = json.load(f)
pretty_rule = prettify_rule(rule)
del pretty_rule['DeviceGroup']
assert pretty_rule == expected_pretty_rule
class TestPcap:
@staticmethod
def test_list_pcaps_flow_with_no_existing_pcaps(mocker):
"""
Given -
a response which indicates there are no pcap files on the firewall.
When -
listing all the available pcap files.
Then -
make sure that a message which indicates there are no Pcaps is printed out.
"""
from Panorama import panorama_list_pcaps_command
no_pcaps_response = MockedResponse(
text='<?xml version="1.0"?>\n<response status="success">\n '
'<result>\n <dir-listing/>\n </result>\n</response>\n',
status_code=200,
)
mocker.patch('Panorama.http_request', return_value=no_pcaps_response)
results_mocker = mocker.patch.object(demisto, "results")
panorama_list_pcaps_command({'pcapType': 'filter-pcap'})
assert results_mocker.called
assert results_mocker.call_args.args[0] == 'PAN-OS has no Pcaps of type: filter-pcap.'
@staticmethod
@pytest.mark.parametrize(
'api_response, expected_context, expected_markdown_table', [
(
'<?xml version="1.0"?>\n<response status="success">\n <result>\n <dir-listing>\n '
'<file>/pcap</file>\n <file>/pcap_test</file>\n </dir-listing>\n </result>\n</response>\n',
['pcap', 'pcap_test'],
'### List of Pcaps:\n|Pcap name|\n|---|\n| pcap |\n| pcap_test |\n'
),
(
'<?xml version="1.0"?>\n<response status="success">\n <result>\n <dir-listing>\n '
'<file>/pcap_test</file>\n </dir-listing>\n </result>\n</response>\n',
['pcap_test'],
'### List of Pcaps:\n|Pcap name|\n|---|\n| pcap_test |\n'
)
]
)
def test_list_pcaps_flow(mocker, api_response, expected_context, expected_markdown_table):
"""
Given
- a response which indicates there are two pcaps in the firewall.
- a response which indicates there is only one pcap in the firewall.