This repository has been archived by the owner on Oct 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bluecoat_tracer.py
1175 lines (1005 loc) · 41.9 KB
/
bluecoat_tracer.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
#!/bin/python3
"""
How To
------
1. Add API_URL and FILE_PATH variables to vars.py file
2. Exec pip install -r requirements.txt
2. Exec python3 bluecoat_tracer.py
Versions
--------
Tested in vpmxml-info version = 631.
Limitations
-----------
Only check UserAuthenticationPolicyTable & WebAccessPolicyTable layers
Not check Threat Risk Level (TL) (Not available in API)
Not check ip-address in "Proxy IP Address/Port" object
Not check Certificate objects <svr-cert>
"""
# Import dependencies
import xml.etree.ElementTree as ET
import ipaddress
import sys
import logging
from urllib.parse import urlparse
import re
from getpass import getpass
import requests
import urllib3
from tabulate import tabulate
# Import var file
from vars import *
# Disable HTTPS server certificate exception terminal output
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# Define Colors
colormap = {
"red": "\033[91m",
"yellow": "\033[93m",
"green": "\033[92m",
"blue": "\033[1;36m",
"reset": "\033[0m"
}
def red(text):
"""
Description:
Return text in red color.
"""
return colormap["red"] + text + colormap["reset"]
def yellow(text):
"""
Description:
Return text in yellow color.
"""
return colormap["yellow"] + text + colormap["reset"]
def green(text):
"""
Description:
Return text in green color.
"""
return colormap["green"] + text + colormap["reset"]
def blue(text):
"""
Description:
Return text in blue color.
"""
return colormap["blue"] + text + colormap["reset"]
# Check python version
if sys.version_info[0] < 3:
sys.exit(red("Upgrade Python Version"))
# Set Log
if sys.version_info[1] < 9:
logging.basicConfig(filename=LOG_FILE_NAME, level=logging.DEBUG, \
format='%(asctime)s - %(levelname)s - %(message)s') # for python <3.9
else:
logging.basicConfig(filename=LOG_FILE_NAME, encoding='utf-8', level=logging.DEBUG, \
format='%(asctime)s - %(levelname)s - %(message)s') # add encoding in python >=3.9
# Init Banner
print()
print()
print(blue("#####################################"))
print(blue("## Symantec ProxySG Utility Tool ##"))
print(blue("#####################################"))
print(green("https://github.com/sburgosl"))
print()
##############################
# Main menu
##############################
logging.debug("START SCRIPT")
def main():
"""
Description:
Main menu.
"""
logging.debug("Exec: main()")
print()
print(blue("[GLOBAL VARIABLES]"))
if ONLINE:
print("Mode: " + green("Online"))
else:
print("Mode: " + red("Offline Work in progress")) #WIP
print("Auth method: " + AUTH_METHOD)
print("Proxy Port: " + str(PROXY_PORT))
print("Exclude layers: " + str(EXCLUDE_LAYERS))
print()
print(blue("[OPTIONS]"))
print("[1]: Search source IP match")
print("[2]: " + red("[WIP]") + "Search destination (IP/FQDN/URL)")
print("[3]: Search source/destination")
print("[4]: Get / Select authentication")
print("[5]: Select proxy port")
print("[6]: Download policy xml")
print("[0]: Exit")
print("Select Option: ", end="")
try:
option = int(input())
switcher = {
1: menu_search_source_ip,
2: get_online_categories,
3: search_complete,
4: edit_auth,
5: edit_proxy_port,
6: menu_download_policy,
0: sys.exit
}
switcher.get(option, main)()
except ValueError as error:
msg_wrn("Not valid input")
logging.warning("Not int on main() input: %s",error)
except KeyboardInterrupt:
sys.exit("")
except Exception as error:
logging.critical(error)
sys.exit('Error')
main()
##############################
# [1]: Search source IP match
##############################
def menu_search_source_ip():
"""
Description:
Dispalys the policy rules that match with a source IP.
"""
logging.debug("Exec: menu_search_source_ip()")
root = get_xml_root()
try:
print("\nEnter source IP: ", end="")
input_src = ipaddress.ip_address(input())
print_start()
# Get all ipobjects that matches with source ip
match_src_objects = get_xml_src_object_match(root, input_src)
# Get comb-obj that contains match_ipbojects. This improves efficency
match_comb_obj = get_xml_com_obj_match(root, match_src_objects)
layers_enabled = get_xml_policy_layers(root)
for layer in layers_enabled:
if layer.attrib.get('layertype') == 'com.bluecoat.sgos.vpm.UserAuthenticationPolicyTable'\
or layer.attrib.get('layertype') == 'com.bluecoat.sgos.vpm.WebAccessPolicyTable':
match_array_src = get_rows_src_match(layer, match_src_objects, match_comb_obj)
print_layer_row(match_array_src)
msg_wrn("INFO: Objects matched")
print(match_src_objects)
print(match_comb_obj)
print_end()
except ValueError as error:
logging.warning("Input menu_search_source_ip() is not ipadress: %s",error)
msg_wrn("Input not valid")
menu_search_source_ip()
##############################
# [2]: search_dest
##############################
##############################
# [3]: search_complete
##############################
def search_complete():
"""
Description:
Dispalys the policy rules that match with a source IP and destination.
"""
logging.debug("Exec: search_complete()")
if not ONLINE:
msg_wrn("Warning: Function limited with var ONLINE = False")
msg_wrn("Not check Blue Coat Categories")
sys.exit(red("Offile mode Currently Work In Progress"))
root = get_xml_root()
try:
print("\nEnter source IP: ", end="")
input_src = ipaddress.ip_address(input())
print("Enter destination in URL Format. Example '//192.168.1.1' or 'http://google.es:443/test.jpg': ", end="")
input_dest = urlparse(input())
if input_dest.netloc == '':
msg_wrn('[Error]: Destination is not in URL format')
logging.warning("Input destination search_complete() is not URL: %s",input_dest)
else:
print_start()
# Get all objects that matches with source ip
match_src_objects = get_xml_src_object_match(root, input_src)
# Get comb-obj that contains match_ipbojects. This improves efficency
match_comb_obj_src = get_xml_com_obj_match(root, match_src_objects)
# Get all objects that matches with destination
match_dst_objects = get_xml_dst_object_match(root, input_dest)
# Get comb-obj that contains match_ipbojects. This improves efficency
match_comb_obj_dst = get_xml_com_obj_match(root, match_dst_objects)
layers_enabled = get_xml_policy_layers(root)
for layer in layers_enabled:
if layer.attrib.get('layertype') == 'com.bluecoat.sgos.vpm.UserAuthenticationPolicyTable'\
or layer.attrib.get('layertype') == 'com.bluecoat.sgos.vpm.WebAccessPolicyTable':
match_array_src = get_rows_src_match(layer, match_src_objects, match_comb_obj_src)
match_array_dst = get_rows_dst_match(match_array_src, match_dst_objects, match_comb_obj_dst)
print_layer_row(match_array_dst)
msg_wrn("INFO: Objects matched")
msg_wrn("Source")
print(match_src_objects)
print(match_comb_obj_src)
msg_wrn("Destination (bypass threat-risk & svr-cert objects)")
print(match_dst_objects)
print(match_comb_obj_dst)
print_end()
except ValueError as error:
logging.warning("Input search_complete() is not ipadress: %s",error)
search_complete()
##############################
# [4]: edit_auth
##############################
def edit_auth():
"""
Description:
List and select authentication groups.
"""
logging.debug("Exec: edit_auth()")
root = get_xml_root()
auth_groups = root.findall('conditionObjects/group')
print()
i = 0
for auth_group in auth_groups:
auth_group_base = auth_group.attrib.get('group-base')
auth_group_location = auth_group.attrib.get('group-location')
auth_realm_name = auth_group.attrib.get('realm-name')
print( "[" + str(i) + "] " + auth_realm_name + " - " + auth_group_location + " / " + auth_group_base )
i += 1
print("Select Authentication: ", end="")
try:
auth_select = auth_groups[int(input())].attrib.get('group-base')
global AUTH_METHOD
AUTH_METHOD = auth_select
logging.info("Change authentication method value to '%s'", AUTH_METHOD)
except IndexError as error:
logging.warning("Out of index on edit_auth() input: %s", error)
##############################
# [5]: edit_proxy_port
##############################
def edit_proxy_port():
"""
Description:
Edit proxy_port value. Default proxy_port value is defined in vars.py file.
"""
logging.debug("Exec: edit_proxy_port()")
try:
print("Insert proxy port: ", end="")
global PROXY_PORT
PROXY_PORT = int(input())
print()
logging.info("Change proxy port value to '%s'",PROXY_PORT)
except ValueError as error:
logging.warning("Not int in edit_proxy_port() input: %s",error)
##############################
# [6]: menu_download_policy
##############################
def menu_download_policy():
"""
Description:
Get user and password.
List and select policies.
List and select versions.
Download selected policy version.
"""
logging.debug("Exec: menu_download_policy()")
if not ONLINE:
msg_wrn("WARNING: Option not available with var ONLINE = False")
else:
# Ask User & Pass
print("Enter User (Management Center): ", end="")
user = input()
print("Enter Pass: ", end="")
password = getpass()
print()
# Get policies
loop = True
while loop:
policies = get_proxy_policies(user,password)
if policies == "error":
return
loop = False
# Print policies and Ask uuid
loop = True
while loop:
for policy in policies:
print("Policy uuid: '" + policy['uuid'] + "' Name: '" + policy['name'] + "' Desc: '" + policy['description'] + "'")
print("Enter Policy uuid: ", end="")
policy_uuid = input()
# Get Versions
versions = get_proxy_policy_versions(user, password, policy_uuid)
if versions == "error":
return
if not versions == "retry":
loop = False
# Print versions and ask version number
loop = True
while loop:
for version in versions:
print("Version: '" + version['revisionNumber'] + "' Date: '" + version['revisionDate'] + "' : '" + version['revisionDescription'] + "'")
print("Enter Version: ", end="")
revision = input()
# Get policy
policy_download = get_proxy_policy_download(user, password, policy_uuid, revision)
if not policy_download == "retry":
loop = False
print(green("[OK]"))
def get_proxy_policies(user, password):
"""
Description:
List and select policy from Symantec Management Center using API
Input:
user - (str) user of symantec management center
password - (str) password of symantec management center
Output:
policies - (str) json array policies response or "error".
"""
logging.debug("Exec: get_proxy_policies()")
try:
url = API_URL+"policies/"
req = requests.get(url, verify=False, auth=(user, password))
logging.info("HTTP Status code in get_proxy_policies() '%s'", req.status_code)
if req.status_code == 200:
return req.json()
if req.status_code == 401:
msg_wrn("HTTP 401: Unauthorized")
elif req.status_code == 403:
msg_wrn("HTTP 403: Forbidden")
elif req.status_code == 404:
msg_wrn("HTTP 404: Not Found")
else:
logging.error("Status Code not handled in get_proxy_policies()")
except ValueError as error:
logging.error("Error in response in get_proxy_policies(): %s", error)
except requests.exceptions.ConnectionError as error:
logging.error("Connection error in get_proxy_policies(): %s", error)
except Exception as error:
logging.error("Error not handled in get_proxy_policies(): %s", error)
msg_wrn("Connection Error: see logs for more info")
return "error"
def get_proxy_policy_versions(user, password, policy_uuid):
"""
Description:
List and select policy versions from Symantec Management Center using API.
Input:
user - (str) user of symantec management center.
password - (str) password of symantec management center.
policy_uuid - (str) uuid of selected policy.
Output:
versions - (str List) json array versions response, or "error" / "retry".
"""
logging.debug("Exec: get_proxy_policy_versions()")
try:
url = API_URL+"policies/"+policy_uuid+"/versions/"
req = requests.get(url, verify=False, auth=(user, password))
logging.info("HTTP Status code in get_proxy_policy_versions(): %s", req.status_code)
if req.status_code == 200:
return req.json()
if req.status_code == 401:
msg_wrn("HTTP 401: Unauthorized")
elif req.status_code == 403:
msg_wrn("HTTP 403: Forbidden")
elif req.status_code == 404:
msg_wrn("HTTP 404: Not Found")
return "retry"
else:
logging.error("Status Code not handled in get_proxy_policy_versions()")
except ValueError as error:
logging.error("Error in response in get_proxy_policy_versions(): %s", error)
except requests.exceptions.ConnectionError as error:
logging.error("Connection error in get_proxy_policy_versions(): %s", error)
except Exception as error:
logging.error("Error not handled in get_proxy_policy_versions(): %s", error)
msg_wrn("Connection Error: see logs for more info")
return "error"
def get_proxy_policy_download(user, password, policy_uuid, revision):
"""
Description:
Download and save policy xml.
Input:
user - (str) user of symantec management center.
password - (str) password of symantec management center.
policy_uuid - (str) uuid of selected policy.
revision - (str) revisionNumber of selected policy version.
Output:
string - (str) Empty if it is OK. "retry" to reselect version, "error" for exit.
"""
logging.debug("Exec: get_proxy_policy_download()")
try:
url = API_URL+"policies/"+policy_uuid+"/content/"+revision
req = requests.get(url, verify=False, auth=(user, password))
logging.info("HTTP Status code in get_proxy_policy_download(): %s", req.status_code)
if req.status_code == 200:
data = req.json()
content = data['content']['xml']
file = open(FILE_PATH, 'w')
file.write(content)
file.close()
return
if req.status_code == 401:
msg_wrn("HTTP 401: Unauthorized")
elif req.status_code == 403:
msg_wrn("HTTP 403: Forbidden")
elif req.status_code == 404:
msg_wrn("HTTP 404: Not Found")
return "retry"
else:
logging.error("Status Code not handled in get_proxy_policy_download()")
except ValueError as error:
logging.error("Error in response in get_proxy_policy_download(): %s", error)
except requests.exceptions.ConnectionError as error:
logging.error("Connection error in get_proxy_policy_download(): %s", error)
except Exception as error:
logging.error("Error not handled in get_proxy_policy_versions(): %s", error)
msg_wrn("Connection Error: see logs for more info")
return "error"
##############################
# Proxy Node Methods
##############################
def get_online_categories(destination):
"""
Description:
Get user and password
Get custom and Symantec predefined Categories from proxy node
Input:
destination - (str) destination input.
Output:
categories - (str list) [policy, bluecoat] categories.
"""
logging.debug("Exec: get_online_categories()")
# Ask User & Pass
print("Enter User (Proxy Node): ", end="")
user = input()
print("Enter Pass: ", end="")
password = getpass()
print()
rtext = get_proxy_categories(user,password, destination)
logging.info("HTTP Response: %s",rtext)
if "Error" in str(rtext):
logging.error("Error in response in get_online_categories(): %s",rtext)
msg_sys(str(rtext))
else:
print()
policy = rtext[0].rsplit(':',1)[1].strip()
bluecoat = rtext[1].rsplit(':',1)[1].strip()
categories = [policy, bluecoat]
return categories
def get_proxy_categories(user, password, destination):
"""
Description:
Get custom and Symantec predefined Categories from proxy node.
Input:
user - (str) user of symantec management center.
password - (str) password of symantec management center.
destination - (str) destination input.
Output:
rtext - (str) HTTP Response categories in text.
"""
logging.debug("Exec: get_proxy_categories()")
try:
req = requests.get(NODE_URL+"ContentFilter/TestUrl/"+destination,\
verify=False, auth=(user, password))
logging.info("HTTP Status code in get_proxy_categories() + '%s'",req.status_code)
if req.status_code == 200:
rtext = req.text.strip().split('\n')
return rtext
if req.status_code == 401:
sys.exit(red("Authentication Error"))
elif req.status_code == 403:
sys.exit(red("Forbidden"))
else:
logging.error("Status Code not handled in get_proxy_categories()")
except ValueError as error:
logging.error("Error in response in get_proxy_categories(): %s", error)
except requests.exceptions.ConnectionError as error:
logging.error("Connection error in get_proxy_categories(): %s", error)
except Exception as error:
logging.error("Error not handled in get_proxy_categories(): %s", error)
sys.exit(red("Connection Error: see logs for more info"))
##############################
# XML Methods
##############################
def get_xml_root():
"""
Description:
Get xml tree root.
Output:
policy_xml_root - (XML Element) XML root.
"""
try:
policy_xml = ET.parse(FILE_PATH)
policy_xml_root = policy_xml.getroot()
return policy_xml_root
except OSError as error:
logging.error("No such file in get_xml_root(): %s", error)
sys.exit(red("No such xml file: Edit variable FILE_PATH in vars.py file or download it with option [6]"))
def get_xml_object_type(object_search):
"""
Return xml object type
"""
# logging.debug("Exec: get_xml_object_type() for '" + object_search + "'")
root = get_xml_root()
object_type = root.find('conditionObjects/*[@name="'+ object_search +'"]').tag
# logging.debug("Object '" + object_search + "' XML Type '" + object_type + "'")
return object_type
def get_xml_src_object_match(root, input_src):
"""
Description:
Search match in source objects (ipobject, h-o, proxy, group).
Input:
root - (XML Element) XML root.
input_src - (ipaddress) source IP address.
Output:
match_src_objects - (str List) Name of XML objects that matches.
"""
logging.debug("Exec: get_xml_src_object_match()")
logging.debug("Source IP: %s",input_src)
match_src_objects = []
# ipobject
for ipobject in root.findall('conditionObjects/ipobject'):
if input_src in ipaddress.ip_network(ipobject.attrib.get('value'), False):
ipobject_name = ipobject.attrib.get('name')
ipobject_subnet = ipobject.attrib.get('value')
match_src_objects.append(ipobject_name)
logging.info("Object match. Name '%s' Subnet '%s'", ipobject_name, ipobject_subnet)
# h-o
for h_o_object in root.findall('conditionObjects/h-o'):
if input_src in ipaddress.ip_network(h_o_object.attrib.get('h'), False):
h_o_object_name = h_o_object.attrib.get('name')
h_o_object_host = h_o_object.attrib.get('h')
match_src_objects.append(h_o_object_name)
logging.info("Object match. Name '%s' Host '%s'", h_o_object_name, h_o_object_host)
# proxy
for proxy_object in root.findall("conditionObjects/proxy[@port='"+str(PROXY_PORT)+"']"):
proxy_name = proxy_object.attrib.get('name')
match_src_objects.append(proxy_name)
logging.info("Object match. Name '%s' Port '%s'", proxy_name, PROXY_PORT)
# group
for group_object in root.findall("conditionObjects/group[@group-base='"+AUTH_METHOD+"']"):
group_name = group_object.attrib.get('name')
match_src_objects.append(group_name)
logging.info("Object match. Name '%s' Group-base '%s'", group_name, AUTH_METHOD)
return match_src_objects
def get_xml_dst_object_match(root, destination):
"""
Description:
Search match in destination objects (ipobject, a-url, categorylist4).
Input:
root - (XML Element) XML root.
Output:
match_dst_objects - (str List) Name of XML objects that matches.
"""
logging.debug("Exec: get_xml_dst_object_match()")
logging.debug("Destination: %s",destination)
match_dst_objects = []
# vpm categories
if ONLINE:
if destination.geturl().startswith("//"):
categories = get_online_categories(destination.geturl().strip("//"))
else:
categories = get_online_categories(destination.geturl())
categories_custom = categories[0].rsplit('; ')
categories_bluecoat = categories[1].rsplit('; ')
logging.info("Object match. vpm-cat %s; %s",categories_custom,categories_bluecoat)
if not categories_custom == ['none']:
for category in categories_custom:
match_dst_objects.append(category)
if not categories_bluecoat == ['none']:
for category in categories_bluecoat:
match_dst_objects.append(category)
else: #WIP
# If online not search <node> (vpm cat)
categories_custom = [] #WIP
match_dst_objects.append(categories_custom)
# categorylist4
for category in root.findall('conditionObjects/categorylist4'):
category_name = category.attrib.get('name')
for cat_i in category.findall('sel/i'):
cat_i_name = cat_i.text.strip(' \n\t')
if cat_i_name in match_dst_objects:
match_dst_objects.append(category_name)
logging.info("Object match. Name '%s' cat <i> '%s'", category_name, cat_i_name)
for cat_ai in category.findall('sel/ai'):
cat_ai_name = cat_ai.attrib.get('n')
if cat_ai_name in match_dst_objects:
match_dst_objects.append(category_name)
logging.info("Object match. Name '%s' cat <ai> '%s'", category_name, cat_ai_name)
# a-url
for a_url_object in root.findall("conditionObjects/a-url"):
a_url_object_name = a_url_object.attrib.get('name')
xml_h = a_url_object.attrib.get('h')
xml_p = a_url_object.attrib.get('p')
xml_d = a_url_object.attrib.get('d')
if not xml_h is None:
xml_h_t = a_url_object.attrib.get('h-t')
if xml_h_t == 'exact-phrase':
if not destination.hostname == xml_h:
continue
elif xml_h_t == 'at-end':
if not destination.hostname.endswith(xml_h):
continue
elif xml_h_t == 'at-beginning':
if not destination.hostname.startswith(xml_h):
continue
elif xml_h_t == 'regex':
if not re.match(xml_h, destination.hostname):
continue
elif xml_h_t == 'contains':
if not xml_h in destination.hostname:
continue
else:
logging.warning("a-url '%s' host condition (h-t in xml) not implemented in get_a_url_match()",xml_h_t)
if not xml_p is None:
xml_p_t = a_url_object.attrib.get('p-t')
if xml_p_t == 'exact-phrase':
if destination.path == xml_p:
match_dst_objects.append(a_url_object_name)
logging.info("Object match. Name '%s' ", a_url_object_name)
continue
if xml_p_t == 'at-end':
if destination.path.endswith(xml_p):
match_dst_objects.append(a_url_object_name)
logging.info("Object match. Name '%s' ", a_url_object_name)
continue
if xml_p_t == 'at-beginning':
if destination.path.startswith(xml_p):
match_dst_objects.append(a_url_object_name)
logging.info("Object match. Name '%s' ", a_url_object_name)
continue
if xml_p_t == 'regex':
if bool(re.match(xml_p, destination.path)):
match_dst_objects.append(a_url_object_name)
logging.info("Object match. Name '%s' ", a_url_object_name)
continue
if xml_p_t== 'contains':
if xml_p in destination.path:
match_dst_objects.append(a_url_object_name)
logging.info("Object match. Name '%s' ", a_url_object_name)
continue
logging.warning("a-url '%s' path condition (p-t in xml) not implemented in get_xml_dst_object_match()",xml_p_t)
continue
# Simple match
if not xml_d is None:
if xml_d in destination.hostname:
match_dst_objects.append(a_url_object_name)
logging.info("Object match. Name '%s' ", a_url_object_name)
continue
# Advanced match without xml_p
match_dst_objects.append(a_url_object_name)
logging.info("Object match. Name '%s' ", a_url_object_name)
# ipobject
try:
dest_ip = ipaddress.ip_address(destination.netloc)
for ipobject in root.findall('conditionObjects/ipobject'):
if dest_ip in ipaddress.ip_network(ipobject.attrib.get('value'), False):
ipobject_name = ipobject.attrib.get('name')
ipobject_subnet = ipobject.attrib.get('value')
match_dst_objects.append(ipobject_name)
logging.info("Object match. Name '%s' Subnet '%s'", ipobject_name, ipobject_subnet)
except ValueError as error:
logging.debug("Input get_xml_dst_object_match() is not ipadress: %s", error)
# Bypass objects threat-risk & svr-cert
for xml_object in root.findall("conditionObjects/threat-risk"):
xml_object_name = xml_object.attrib.get('name')
match_dst_objects.append(xml_object_name)
for xml_object in root.findall("conditionObjects/svr-cert"):
xml_object_name = xml_object.attrib.get('name')
match_dst_objects.append(xml_object_name)
return match_dst_objects
def get_xml_com_obj_match(root, match_objects):
"""
Description:
Search comb-obj that contains match_objects.
Input:
root - (XML Element) XML root,
match_objects - (str List) XML ipobjects/h-o names that include input_src IP.
Output:
match_comb_obj - (str List) XML comb_obj names that include some match_objects.
"""
logging.debug("Exec: get_xml_com_obj_match()")
comb_obj_match = []
# comb_obj_no_match = []
comb_objs = root.findall('conditionObjects/comb-obj')
for comb_obj in comb_objs:
comb_obj_name = comb_obj.attrib.get('name')
comb_obj_cl1 = comb_obj.attrib.get('n-1') # 'false' = select, 'true' = negate
comb_obj_cl2 = comb_obj.attrib.get('n-2') # 'false' = select, 'true' = negate
cl1_list = comb_obj.findall('c-l-1')
cl2_list = comb_obj.findall('c-l-2')
# cl1 false and cl2 false
if comb_obj_cl1 == 'false' and comb_obj_cl2 == 'false':
cl1_match = False
cl2_match = False
for cl1 in cl1_list:
cl1_name = cl1.attrib.get('n')
if cl1_name in match_objects or cl1_name in comb_obj_match:
cl1_match = True
break
if cl1_match:
if cl2_list == []:
comb_obj_match.append(comb_obj_name) # cl1 ok, cl2 empty
logging.info("Comb-obj match. Name '%s' Contains '%s'",\
comb_obj_name, cl1_name)
else:
for cl2 in cl2_list:
cl2_name = cl2.attrib.get('n')
if cl2_name in match_objects or cl2_name in comb_obj_match:
cl2_match = True
comb_obj_match.append(comb_obj_name) # cl1 ok, cl2 ok
logging.info("Comb-obj match. Name '%s' Contains '%s' & '%s'",\
comb_obj_name, cl1_name, cl2_name)
break
# if not cl1_match or not cl2_match:
# comb_obj_no_match.append(comb_obj_name) # cl1 ko
# cl1 false and cl2 true
elif comb_obj_cl1 == 'false' and comb_obj_cl2 == 'true':
cl1_match = False
cl2_match = False
for cl1 in cl1_list:
cl1_name = cl1.attrib.get('n')
if cl1_name in match_objects or cl1_name in comb_obj_match:
cl1_match = True
break
if cl1_match:
if cl2_list == []:
comb_obj_match.append(comb_obj_name) # cl1 ok, !cl2 empty
logging.info("Comb-obj match. Name '%s' Contains '%s'",\
comb_obj_name, cl1_name)
else:
for cl2 in cl2_list:
cl2_name = cl2.attrib.get('n')
if cl2_name in match_objects or cl2_name in comb_obj_match:
cl2_match = True
# comb_obj_no_match.append(comb_obj_name) # cl1 ok, !cl2 ok
break
if not cl2_match:
comb_obj_match.append(comb_obj_name) # cl1 ok, !cl2 ko
logging.info("Comb-obj match. Name '%s' Contains '%s' & '%s'",\
comb_obj_name, cl1_name, cl2_name)
# if not cl1_match:
# comb_obj_no_match.append(comb_obj_name) # cl1 ko
# cl1 true and cl2 false
elif comb_obj_cl1 == 'true' and comb_obj_cl2 == 'false':
cl1_match = False
cl2_match = False
for cl1 in cl1_list:
cl1_name = cl1.attrib.get('n')
if cl1_name in match_objects or cl1_name in comb_obj_match:
# comb_obj_no_match.append(comb_obj_name) # !cl1 ok
cl1_match = True
break
if not cl1_match:
if cl2_list == []:
comb_obj_match.append(comb_obj_name) # !cl1 ko && cl2 empty
logging.info("Comb-obj match. Name '%s' Negate source ", comb_obj_name)
else:
for cl2 in cl2_list:
cl2_name = cl2.attrib.get('n')
if cl2_name in match_objects or cl2_name in comb_obj_match:
cl2_match = True
comb_obj_match.append(comb_obj_name) # !cl1 ko, cl2 ok
logging.info("Comb-obj match. Name '%s' Negate cl1, cl2 '%s'",\
comb_obj_name, cl2_name)
break
# if not cl2_match:
# comb_obj_no_match.append(comb_obj_name) # !cl1 ko && cl2 ko
# cl1 true and cl2 true
else:
cl1_match = False
cl2_match = False
for cl1 in cl1_list:
cl1_name = cl1.attrib.get('n')
if cl1_name in match_objects or cl1_name in comb_obj_match:
# comb_obj_no_match.append(comb_obj_name) # !cl1 ok
cl1_match = True
break
if not cl1_match:
if cl2_list == []:
comb_obj_match.append(comb_obj_name) # !cl1 ko && !cl2 empty
logging.info("Comb-obj match. Name '%s' Negate source ", comb_obj_name)
else:
for cl2 in cl2_list:
cl2_name = cl2.attrib.get('n')
if cl2_name in match_objects or cl2_name in comb_obj_match:
cl2_match = True
# comb_obj_no_match.append(comb_obj_name) # !cl1 ko, !cl2 ok
break
if not cl2_match:
comb_obj_match.append(comb_obj_name) # !cl1 ko, !cl2 ko
logging.info("Comb-obj match. Name '%s' Negate cl1 '%s' & cl2 '%s'",\
comb_obj_name, cl1_name, cl2_name)
return comb_obj_match
def get_auth_obj_match(auth_obj_name):
"""
Description:
Check if xml auth-obj match with selected AUTH_METHOD (group in xml).
Output:
Boolean.
"""
logging.debug("Exec: get_auth_obj_match(%s)", auth_obj_name)
root = get_xml_root()
realm_search = root.find("conditionObjects/auth-obj[@name='" + auth_obj_name + "']").attrib.get('r-n')
if AUTH_METHOD == '':
return False
realm_select = root.find("conditionObjects/group[@group-base='" + AUTH_METHOD + "']").attrib.get('realm-name')
return bool(realm_search == realm_select)
def get_adm_auth_obj_match(auth_obj_name):
"""
Description:
Check if xml adm-auth-obj match with selected AUTH_METHOD (group in xml).
Output:
Boolean.
"""
logging.debug("Exec: get_adm_auth_obj_match()")
root = get_xml_root()
realm_search = root.find("conditionObjects/adm-auth-obj[@name='" + auth_obj_name + "']").attrib.get('r-n')
if AUTH_METHOD == '':
return False
realm_select = root.find("conditionObjects/group[@group-base='" + AUTH_METHOD + "']").attrib.get('realm-name')
return bool(realm_search == realm_select)
def get_xml_policy_layers(root):
"""
Description:
Get all layers enabled and not exclued in var exclude_layers.
Input:
root - (XML Element) XML root.
Output:
layers_enabled - (XML Element List) Policy layers enabled.
"""
logging.debug("Exec: get_xml_policy_layers()")
layers_enabled = []
for layer in root.findall('layers/layer'):
if not layer.attrib.get('disabled') == 'true':
layer_type = layer.attrib.get('layertype')
layer_name = layer.find('name').text.strip(' \n\t')
logging.debug("Layertype '%s' Layer Name '%s'",layer_type, layer_name)
if not layer_name in EXCLUDE_LAYERS:
layers_enabled.append(layer)
return layers_enabled
def evaluate_action(row):
"""
Description:
Return if action permit (True) or deny (False) traffic.
Input:
row - (XML Element) row with match.
Output:
Boolean / None.
"""
col_ac = row.find('colItem[@id="ac"]').attrib.get('name')