-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfw-mgt-cert-rollout.py
1344 lines (1275 loc) · 53 KB
/
fw-mgt-cert-rollout.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
###############################################################################
#
# Script: fw-mgt-cert-rollout.py
#
# Author: Chris Goodwin <chrisgoodwins@gmail.com>
#
# Description: A menu-driven script that automates the entire process for
# creating and pushing management certificates to Palo Alto
# Networks firewalls throughout the enterprise.
#
# Usage: fw-mgt-cert-rollout.py
#
# Requirements: requests, lxml, requests_ntlm, certsrv, pyopenssl
#
# Python: Version 3
#
###############################################################################
import os
import re
import sys
import time
import random
import getpass
from xml.etree import ElementTree as ET
try:
from lxml import html
except ImportError:
raise ValueError("lxml support not available, please install module - run 'pip install lxml'")
try:
import requests
from requests_ntlm import HttpNtlmAuth
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
except ImportError:
raise ValueError("requests support not available, please install module - run 'pip install requests' and 'pip install requests_ntlm'")
try:
import certsrv
except ImportError:
raise ValueError("certsrv support not available, please install module - run 'pip install certsrv'")
try:
from OpenSSL import crypto, SSL
except ImportError:
raise ValueError("pyopenssl support not available, please install module - run 'pip install pyopenssl'")
###############################################################################
###############################################################################
##Global Variables##
fw_addr_list = []
fw_csr_list = []
mainkey = ''
country = ''
state = ''
locality = ''
organization = ''
department = ''
email = ''
hostname = ''
ip = ''
altEmail = ''
algorithm = 'RSA'
bits = '2048'
digest = 'sha256'
expiration = '365'
# Prompts the user to enter the IP/FQDN of a firewall
def getfwipfqdn():
while True:
try:
fwipraw = input("Please enter a comma separated list of IP/FQDNs (These will be the CN on the certs): ")
ipr = re.match(r"^(?:(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))|(?:(?=.{4,253})(((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63})))(,\s*(?:(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))|(?=.{4,253})(((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63})))*$", fwipraw)
if ipr:
break
else:
time.sleep(1)
print("\nThere was something wrong with your entry. Please try again...\nThe format should look like this: 10.11.12.13, 20.21.22.23, 42.42.42.42, foo.bar.com\n\n")
except:
print("\nThere was some kind of problem entering your IP. Please try again...\n")
return fwipraw
# Prompts the user to enter their username to retrieve the api key
def getuname():
while True:
try:
username = input("Please enter your user name: ")
usernamer = re.match(r"^[a-zA-Z0-9_-]{3,24}$", username) # 3 - 24 characters {3,24}
if usernamer:
break
else:
print("\nThere was something wrong with your entry. Please try again...\n")
except:
print("\nThere was some kind of problem entering your user name. Please try again...\n")
return username
# Prompts the user to enter their password to retrieve the api key
def getpassword():
while True:
try:
password = getpass.getpass("Please enter your password: ")
passwordr = re.match(r"^.{5,50}$", password) # simple validate PANOS has no password characterset restrictions
if passwordr:
break
else:
print("\nThere was something wrong with your entry. Please try again...\n")
except:
print("\nThere was some kind of problem entering your password. Please try again...\n")
return password
# Retrieves the user's api key
def getkey(fwip):
while True:
try:
fwipgetkey = fwip
username = getuname()
password = getpassword()
keycall = "https://%s/api/?type=keygen&user=%s&password=%s" % (fwipgetkey, username, password)
r = requests.get(keycall, verify=False)
tree = ET.fromstring(r.text)
if tree.get('status') == "success":
apikey = tree[0][0].text
break
else:
print("\nYou have entered an incorrect username or password. Please try again...\n")
except requests.exceptions.ConnectionError as e:
print("\nThere was a problem connecting to the firewall. Please check the IP or FQDN and try again...\n")
exit()
return apikey
# Prompts the user with the option to commit each firewall individually, after validating the config
def fwCommit_withValidation(fwip, mainkey):
while True:
commit = input("\n\nWe'll now validate and commit the config for %s, are you ok with this? [Y/n] " % (fwip))
if commit == 'n' or commit == 'N':
print('\nPlease login to %s and commit your changes manaully\n' % (fwip))
break
elif commit == 'y' or commit == 'Y' or commit == '':
fw_url = 'https://' + fwip + '/api/?type=op&cmd=<validate><full></full></validate>&key=' + mainkey
r = requests.get(fw_url, verify=False)
tree = ET.fromstring(r.text)
if tree.get('status') == "success":
print('\nValidating the config, please hold...', end='')
job = tree.find('./result/job').text
count = 1
while True:
fw_url = 'https://' + fwip + '/api/?type=op&cmd=<show><jobs><id>%s</id></jobs></show>&key=%s' % (job, mainkey)
r = requests.get(fw_url, verify=False)
tree = ET.fromstring(r.text)
if tree.find('./result/job/result').text == 'PEND':
if count % 8 == 0:
print('\nStill waiting for validation...', end='')
else:
sys.stdout.write('.')
count += 1
time.sleep(1)
elif tree.find('./result/job/result').text == 'OK' and tree.find('./result/job/details/line').text == 'Configuration is valid':
fw_url = 'https://' + fwip + '/api/?type=commit&cmd=<commit></commit>&key=' + mainkey
r = requests.get(fw_url, verify=False)
print('\n\nCongrats the config is valid!\n\n', '\n-----The commit job was successfully sent to %s-----\n' % (fwip))
break
else:
print('Could not validate the config, please login to the firewall and commit manaully\n\n')
break
else:
print('Could not validate the config, please login to the firewall and commit manaully\n\n')
break
break
else:
time.sleep(1)
print("\nYou seemed to have chosen the wrong key. Please try \"y\" or \"n\" this time...\n")
# Allows the user to commit the firewalls without first validating the config
def fwCommit_withoutValidation(fwip, mainkey):
fw_url = 'https://' + fwip + '/api/?type=commit&cmd=<commit></commit>&key=' + mainkey
r = requests.get(fw_url, verify=False)
tree = ET.fromstring(r.text)
if tree.get('status') == "success":
time.sleep(1)
print('-----A commit job was successfully sent to %s-----' % (fwip))
time.sleep(1)
else:
time.sleep(1)
print('\n-----PLEASE NOTE THERE WAS A PROBLEM WITH SENDING A COMMIT JOB TO %s-----' % (fwip))
time.sleep(1)
# Function to allow user to choose cert attributes
def menu_1():
global country, state, locality, organization, department, email, hostname, ip, altEmail
print('\n\n')
while True:
try:
attrMenuChoice = int(input('Choose an option below to add or modify certificate attributes\nChoose exit when finished...\n\n1. Country\n2. State\n3. Locality\n4. Organization\n5. Department\n6. Email\n7. Hostname\n8. IP Address\n9. Alt Email\n10. Exit to Main Menu\n\nEnter your choice: '))
if attrMenuChoice == 1:
country = input('\nWhat would you like to set the country to? [US] ')
if country == '':
country = 'US'
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
elif attrMenuChoice == 2:
state = input('\nWhat would you like to set the state to? ')
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
elif attrMenuChoice == 3:
locality = input('\nWhat would you like to set the locality to? ')
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
elif attrMenuChoice == 4:
organization = input('\nWhat would you like to set the organization to? ')
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
elif attrMenuChoice == 5:
department = [input('\nWhat would you like to set the department to? ')]
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
while True:
anotherItem = input('Would you like to add another department entry? [y/N] ')
if anotherItem == 'Y' or anotherItem == 'y':
department.append(input('\nWhat department entry would you like to add? '))
time.sleep(1)
print('\nOk, got it...\n\n')
elif anotherItem == '' or anotherItem == 'N' or anotherItem == 'n':
print('\n')
break
elif attrMenuChoice == 6:
email = input('\nWhat would you like to set the email to? ')
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
elif attrMenuChoice == 7:
hostname = [input('\nWhat would you like to set the hostname to? ')]
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
while True:
anotherItem = input('\nWould you like to add another hostname entry? [y/N] ')
if anotherItem == 'Y' or anotherItem == 'y':
hostname.append(input('\nWhat hostname entry would you like to add? '))
time.sleep(1)
print('\nOk, got it...\n\n')
elif anotherItem == '' or anotherItem == 'N' or anotherItem == 'n':
print('\n')
break
elif attrMenuChoice == 8:
ip = [input('\nWhat would you like to set the IP address to? ')]
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
while True:
anotherItem = input('\nWould you like to add another IP Address entry? [y/N] ')
if anotherItem == 'Y' or anotherItem == 'y':
ip.append(input('\nWhat IP Address entry would you like to add? '))
time.sleep(1)
print('\nOk, got it...\n\n')
elif anotherItem == '' or anotherItem == 'N' or anotherItem == 'n':
print('\n')
break
elif attrMenuChoice == 9:
altEmail = [input('\nWhat would you like to set the altEmail to? ')]
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
while True:
anotherItem = input('\nWould you like to add another altEmail entry? [y/N] ')
if anotherItem == 'Y' or anotherItem == 'y':
altEmail.append(input('\nWhat altEmail entry would you like to add? '))
time.sleep(1)
print('\nOk, got it...\n\n')
elif anotherItem == '' or anotherItem == 'N' or anotherItem == 'n':
print('\n')
break
elif attrMenuChoice == 10:
time.sleep(1)
print('\n\n')
break
continue
else:
time.sleep(1)
print("\nYou've entered a number that is not in the list, try again...\n")
time.sleep(1)
continue
except ValueError:
time.sleep(1)
print('\nYou must enter a number, try again...\n')
time.sleep(1)
continue
# Function to allow user to choose crypto settings
# Default setting for crypto if nothing chosen are: RSA, 2048 bits, sha256
def menu_2():
global algorithm, bits, digest
while True:
try:
algorithm = int(input('\nWhat algorithm would you like to use?\n\n1. RSA\n2. Elliptic Curve DSA\n\nEnter your choice: '))
if algorithm == 1:
algorithm = 'RSA'
while True:
try:
bits = int(input('\nWhat number of bits would you like to use? [2048]\n\n1. 512\n2. 1024\n3. 2048\n4. 3072\n5. 4096\n\nEnter your choice: '))
if bits == 1:
bits = '512'
elif bits == 2:
bits = '1024'
elif bits == 3:
bits = '2048'
elif bits == 4:
bits = '3072'
elif bits == 5:
bits = '4096'
else:
time.sleep(1)
print("\nYou've entered a number that is not in the list, try again...\n")
time.sleep(1)
continue
except ValueError as e:
## Handles the default value, which isn't an integer (enter key) ##
if str(e) == "invalid literal for int() with base 10: ''":
bits = '2048'
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
break
else:
time.sleep(1)
print('\nYou must enter a number, try again...\n')
time.sleep(1)
continue
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
break
while True:
try:
digest = int(input('What digest would you like to use? [sha256]\n\n1. sha1\n2. sha256\n3. sha384\n4. sha512\n5. md5\n\nEnter your choice: '))
if digest == 1:
digest = 'sha1'
elif digest == 2:
digest = 'sha256'
elif digest == 3:
digest = 'sha384'
elif digest == 4:
digest = 'sha512'
elif digest == 5:
digest = 'md5'
else:
time.sleep(1)
print("\nYou've entered a number that is not in the list, try again...\n")
time.sleep(1)
continue
except ValueError as e:
## Handles the default value, which isn't an integer (enter key) ##
if str(e) == "invalid literal for int() with base 10: ''":
digest = 'sha256'
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
break
else:
time.sleep(1)
print('\nYou must enter a number, try again...\n')
time.sleep(1)
continue
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
break
break
elif algorithm == 2:
algorithm = 'Elliptic Curve DSA'
while True:
try:
bits = int(input('\nWhat number of bits would you like to use? [256]\n\n1. 256\n2. 384\n\nEnter your choice: '))
if bits == 1:
bits = '256'
elif bits == 2:
bits = '384'
else:
time.sleep(1)
print("\nYou've entered a number that is not in the list, try again...\n")
time.sleep(1)
continue
except ValueError as e:
## Handles the default value, which isn't an integer (enter key) ##
if str(e) == "invalid literal for int() with base 10: ''":
bits = '256'
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
break
else:
time.sleep(1)
print('\nYou must enter a number, try again...\n')
time.sleep(1)
continue
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
break
while True:
try:
digest = int(input('What digest would you like to use? [sha256]\n\n1. sha256\n2. sha384\n3. sha512\n\nEnter your choice: '))
if digest == 1:
digest = 'sha256'
elif digest == 2:
digest = 'sha384'
elif digest == 3:
digest = 'sha512'
else:
time.sleep(1)
print("\nYou've entered a number that is not in the list, try again...\n")
time.sleep(1)
continue
except ValueError as e:
## Handles the default value, which isn't an integer (enter key) ##
if str(e) == "invalid literal for int() with base 10: ''":
digest = 'sha256'
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
break
else:
time.sleep(1)
print('\nYou must enter a number, try again...\n')
time.sleep(1)
continue
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
break
break
else:
time.sleep(1)
print("\nYou've entered a number that is not in the list, try again...\n")
time.sleep(1)
continue
except ValueError:
time.sleep(1)
print('\nYou must enter a number, try again...\n')
time.sleep(1)
continue
break
# Function to allow user to set the expiration
def menu_3():
global expiration
while True:
try:
expiration = int(input('\nWhat would you like to set the expiration to (in days)? [365] '))
if 1 <= expiration <= 7200:
expiration = str(expiration)
else:
time.sleep(1)
print('\nThe expiration must be set between 1 and 7200 days\n')
time.sleep(1)
continue
except ValueError as e:
## Handles the default value, which isn't an integer (enter key) ##
if str(e) == "invalid literal for int() with base 10: ''":
expiration = '365'
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
break
else:
time.sleep(1)
print('\nYou must enter a number, try again...\n')
time.sleep(1)
continue
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
break
# Allows user to clear all attributes and sets crypto settings to default
def menu_4():
global country, state, locality, organization, department, email, hostname, ip, altEmail, algorithm, bits, digest, expiration
country = ''
state = ''
locality = ''
organization = ''
department = ''
email = ''
hostname = ''
ip = ''
altEmail = ''
algorithm = 'RSA'
bits = '2048'
digest = 'sha256'
expiration = '365'
time.sleep(1)
print('\nAll attributes were cleared, and crypto settings were set to default\n\n')
time.sleep(1)
# Prints all attributes and crypto settings
def menu_5():
global country, state, locality, organization, department, email, hostname, ip, altEmail, algorithm, bits, digest, expiration
print("\n\nOk, here's your stuff...\n")
time.sleep(1)
if country == '':
print('Country: None')
else:
print('Country: ' + country)
if state == '':
print('State: None')
else:
print('State: ' + state)
if locality == '':
print('Locality: None')
else:
print('Locality: ' + locality)
if organization == '':
print('Organization: None')
else:
print('Organization: ' + organization)
if department == '':
print('Department: None')
else:
if len(department) > 1:
print('Department: ' + str(department))
else:
print('Department: ' + department[0])
if email == '':
print('Email: None')
else:
print('Email: ' + email)
if hostname == '':
print('Hostname: None')
else:
if len(hostname) > 1:
print('Hostname: ' + str(hostname))
else:
print('Hostname: ' + hostname[0])
if ip == '':
print('IP Address: None')
else:
if len(ip) > 1:
print('IP Address: ' + str(ip))
else:
print('IP Address: ' + ip[0])
if altEmail == '':
print('Alt Email: None')
else:
if len(altEmail) > 1:
print('Alt Email: ' + str(altEmail))
else:
print('Alt Email: ' + altEmail[0])
print('Algorithm: ' + algorithm + '\nBits: ' + bits + '\nDigest: ' + digest + '\nExpiration: ' + expiration + '\n\n')
time.sleep(1)
input('\nPress Enter to continue...')
print('\n\n')
# Allows user to input IP or FQDN addresses via terminal or via CSV file
def menu_6():
global fw_addr_list, fw_csr_list
print('\n\n')
fwListCheck = False
while True:
try:
addrMenuChoice = int(input('Choose an option below to input or print addresses\nChoose exit when finished...\n\n1. Input Addresses Via Terminal\n2. Input Addresses/Attributes/Crypto Settings Via CSV File\n3. Print Addresses/Attributes/Crypto Settings\n4. Exit to Main Menu\n\nEnter your choice: '))
if addrMenuChoice == 1:
print('')
fw_addr_list = getfwipfqdn()
fwListCheck = True
## Changes the firewall list from string to list format, removing any spaces if they exist, then makes each entry its own list ##
fw_addr_list = fw_addr_list.replace(' ', '')
fw_addr_list = fw_addr_list.split(',')
index = 0
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
## Input addresses from CSV file ##
elif addrMenuChoice == 2:
while True:
csvChoice = input('\nWhat is the name of your CSV file? ')
if not os.path.exists(csvChoice):
time.sleep(1)
print('\n\nCould not find ' + csvChoice + '\nMake sure your CSV file is in the same directory as this script...')
else:
readFile = open(csvChoice, 'r')
csvList = readFile.readlines()
readFile.close()
break
for item in csvList:
item = item.replace(', ', ',')
item = item.replace('\n', '')
multiLists = re.findall(r'(?<=\[)([^\]]+)(?=\])', item)
item_temp = re.sub(r'([\'\"]?\[)([^\]]+)(\][\'\"]?)', '_regVar_', item).split(',')
item_new = []
count = 0
index = 0
for i in item_temp:
if i == '_regVar_':
item_new.append(multiLists[count].split(','))
count += 1
index += 1
else:
item_new.append(item_temp[index])
index += 1
fw_csr_list.append(item_new)
time.sleep(1)
print('\nOk, got it...\n\n')
time.sleep(1)
## Prints addresses entered from terminal, and addresses/attributes/crypto settings from CSV file ##
elif addrMenuChoice == 3:
time.sleep(1)
print('\n')
if len(fw_csr_list) > 0:
print('\nAddresses input via CSV file:')
for item in fw_csr_list:
print(item[0] + ' - ' + str(item[1:]))
if fwListCheck == True:
print('\nAddresses input via terminal:')
for addr in fw_addr_list:
print(addr)
if len(fw_csr_list) == 0 and fwListCheck == False:
print('\nThere are no addresses input through terminal and CSV file')
print('\n\n')
time.sleep(1)
elif addrMenuChoice == 4:
time.sleep(1)
print('\n\n')
break
continue
else:
time.sleep(1)
print("\nYou've entered a number that is not in the list, try again...\n")
time.sleep(1)
continue
except ValueError:
time.sleep(1)
print('\nYou must enter a number, try again...\n')
time.sleep(1)
continue
# Allows the user to generate CSRs
def menu_7():
global fw_addr_list, fw_csr_list, mainkey, country, state, locality, organization, department, email, hostname, ip, altEmail, algorithm, bits, digest, expiration
csrPath = 'PAN-FW-CSRs'
## Create the CSR dir if it doesn't already exist ##
if not os.path.exists(csrPath):
os.mkdir(csrPath)
certVals = []
## If there were addresses entered via the terminal, add them to fw_csr_list, addresses from CSV would have already been added if they exist ##
if len(fw_addr_list) > 0:
[certVals.append(x) for x in [country, state, locality, organization, department, email, hostname, ip, altEmail, algorithm, bits, digest, expiration]]
for item in fw_addr_list:
x = [val for val in certVals]
x.insert(0, item)
fw_csr_list.append(x)
## If the list is not empty (if the user didn't forget to add addresses) ##
if len(fw_csr_list) > 0:
if mainkey != '':
print('\n\nAuthenticating to the first firewall in the list using your cached credentials...\n\n')
time.sleep(1)
else:
print('\nEnter your credentials below, and you will be authenticated against the first firewall in the list...\n\n')
mainkey = getkey(fw_csr_list[0][0])
print('\n\n')
## Process each firewall in the list, building the API call for each for generating CSRs ##
for item in fw_csr_list:
if item[10] == 'RSA':
attributesXML = '<request><certificate><generate><certificate-name>PAN-FW_' + item[0] + '</certificate-name><name>' + item[0] + '</name><algorithm><RSA><rsa-nbits>' + item[11] + '</rsa-nbits></RSA></algorithm><digest>' + item[12] + '</digest><days-till-expiry>' + item[13] + '</days-till-expiry><signed-by>external</signed-by><ca>no</ca>'
else:
attributesXML = '<request><certificate><generate><certificate-name>PAN-FW_' + item[0] + '</certificate-name><name>' + item[0] + '</name><algorithm><ECDSA><ecdsa-nbits>' + item[11] + '</ecdsa-nbits></ECDSA></algorithm><digest>' + item[12] + '</digest><days-till-expiry>' + item[13] + '</days-till-expiry><signed-by>external</signed-by><ca>no</ca>'
if item[1] != '':
attributesXML = attributesXML + '<country-code>' + item[1] + '</country-code>'
if item[2] != '':
attributesXML = attributesXML + '<state>' + item[2] + '</state>'
if item[3] != '':
attributesXML = attributesXML + '<locality>' + item[3] + '</locality>'
if item[4] != '':
attributesXML = attributesXML + '<organization>' + item[4] + '</organization>'
if item[6] != '':
attributesXML = attributesXML + '<email>' + item[6] + '</email>'
if item[5] != '':
attributesXML = attributesXML + '<organization-unit>'
if type(item[5]) == list:
for i in item[5]:
attributesXML = attributesXML + '<member>' + i + '</member>'
else:
attributesXML = attributesXML + '<member>' + item[5] + '</member>'
attributesXML = attributesXML + '</organization-unit>'
if item[7] != '':
attributesXML = attributesXML + '<hostname>'
if type(item[7]) == list:
for i in item[7]:
attributesXML = attributesXML + '<member>' + i + '</member>'
else:
attributesXML = attributesXML + '<member>' + item[7] + '</member>'
attributesXML = attributesXML + '</hostname>'
if item[8] != '':
attributesXML = attributesXML + '<ip>'
if type(item[8]) == list:
for i in item[8]:
attributesXML = attributesXML + '<member>' + i + '</member>'
else:
attributesXML = attributesXML + '<member>' + item[8] + '</member>'
attributesXML = attributesXML + '</ip>'
if item[9] != '':
attributesXML = attributesXML + '<alt-email>'
if type(item[9]) == list:
for i in item[9]:
attributesXML = attributesXML + '<member>' + i + '</member>'
else:
attributesXML = attributesXML + '<member>' + item[9] + '</member>'
attributesXML = attributesXML + '</generate></certificate></request>'
xmlURL_generate = 'https://' + item[0] + '/api/?type=op&cmd=' + attributesXML + '&key=' + mainkey
## Send the API call to generate the CSR ##
try:
r = requests.get(xmlURL_generate, verify=False)
tree = ET.fromstring(r.text)
if tree.get('status') == "success":
print('Certificate signing request was successfully generated for ' + item[0])
xmlURL_export = 'https://' + item[0] + '/api/?type=export&category=certificate&certificate-name=PAN-FW_' + item[0] + '&format=pkcs10&include-key=no&key=' + mainkey
r = requests.get(xmlURL_export, verify=False)
csrFile = open(csrPath + '/PAN-FW_' + item[0] + '.csr', 'wb+')
csrFile.write(r.content)
csrFile.close()
if os.path.exists(csrPath + '/PAN-FW_' + item[0] + '.csr'):
print('CSR file (PAN-FW_' + item[0] + '.csr) was exported and placed in the ' + csrPath + ' directory\n')
if item[0] == fw_csr_list[-1][0]:
input('\nHit the Enter key to continue... ')
print('\n\n')
else:
time.sleep(1)
print('\n\n################ There was a problem with exporting the certificate signing request for ' + item[0] + ' ################')
print("\nHere's the API call that went wonky:\n" + xmlURL_export)
input('\nHit the Enter key to continue... ')
print('\n\n')
else:
time.sleep(1)
print('\n\n################ There was a problem with generating the certificate signing request for ' + item[0] + ' ################')
print("\nHere's the API call that went wonky:\n" + xmlURL_generate)
input('\nHit the Enter key to continue... ')
print('\n\n')
except Exception as e:
time.sleep(1)
print('\n\n[ERROR]: ' + str(e.message))
time.sleep(1)
input('\nThis firewall will be skipped, hit the Enter key to continue... ')
fileCheck = True
## Just in cases the user forgot upload any address info ##
else:
time.sleep(1)
print('\nYou forgot to input your firewall adresses, make sure you do that first...')
time.sleep(1)
input('\n\nPress Enter to continue...\n\n')
fileCheck = False
## Saves the information from cert requests being generated, this will be used for pushing the signed certs back to the firewalls ##
if fileCheck == True:
datFile = open(csrPath + '/fw-list_mgt-certs.txt', 'w')
datFile.write('##This file contains data from the last set of firewalls for which certificate signing requests were generated. This data will be used by the fw-mgt-cert rollout script for pushing the signed certificates back out to the firewalls listed in this file##\n')
for item in fw_csr_list:
for i in item:
datFile.write(str(i) + ',')
datFile.write('\n')
datFile.close()
# Allows user to export CSR files to be signed by CA server
def menu_8():
csrPath = 'PAN-FW-CSRs'
pemPath = 'PAN-FW-PEMs'
caPath = 'PAN-CA-Cert'
if not os.path.exists(pemPath):
os.mkdir(pemPath)
print('\n\n')
self_signed_CA = False
allReqIDs = []
input("If you have a PKI, the script has built-in support for Microsoft ADCS. Otherwise, you will have the\nability to create your own self-signed CA within this script. You can also create a CA on a Panorama\nor firewall, you would just need to export the certificate with the key in pem format, then save it to a\nfolder named 'PAN-CA-Cert' within the working directory. The script will automatically find it if it exists.\n\n\nHit enter to continue...\n\n")
run = True
while run:
if not os.path.exists(csrPath):
time.sleep(1)
print('\n\nThe PAN-FW-CSRs directory does not exist...\nMake sure the directory exists and is populated with CSRs\n')
time.sleep(1)
break
## Create a list of CSRs in the directory, removing the fw-list_mgt-certs.txt file from the list ##
fwCSRs = os.listdir(csrPath)
if os.path.exists(csrPath + '/fw-list_mgt-certs.txt'):
fwCSRs.remove('fw-list_mgt-certs.txt')
if fwCSRs == []:
time.sleep(1)
print('\n\nThe PAN-FW-CSRs directory is empty...\nMake sure the directory is populated with CSRs\n')
time.sleep(1)
break
if os.path.exists(caPath):
if any(fname.endswith('.pem') for fname in os.listdir(caPath)) or (any(fname.endswith('.crt') for fname in os.listdir(caPath)) and any(fname.endswith('.key') for fname in os.listdir(caPath))):
print('Found a CA cert...\n\n')
time.sleep(1)
self_signed_CA = True
if not self_signed_CA:
while True:
create_CA = input('\nNo CA cert was found, would you like to create one? [y/n] ')
if create_CA.lower() == 'n':
break
elif create_CA.lower() == 'y':
self_signed_CA = True
if not os.path.exists(caPath):
os.mkdir(caPath)
CN = input("\nEnter the common name for the CA certificate: ")
pubkey = f"{caPath}/{CN.replace('.', '_')}.crt"
privkey = f"{caPath}/{CN.replace('.', '_')}.key"
key = crypto.PKey()
key.generate_key(crypto.TYPE_RSA, 2048)
cert = crypto.X509()
print('\nEnter the CA certificate attributes...\n\n')
cert.get_subject().C = input("Country: ") or ' '
cert.get_subject().ST = input("State: ") or ' '
cert.get_subject().L = input("City: ") or ' '
cert.get_subject().O = input("Organization: ") or ' '
cert.get_subject().OU = input("Organizational Unit: ") or ' '
cert.get_subject().CN = CN
cert.set_serial_number(random.getrandbits(64))
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(60 * 60 * 24 * 365 * 20) # 20 years
cert.set_issuer(cert.get_subject())
cert.set_pubkey(key)
cert.sign(key, 'sha512')
pub = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
priv = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)
open(pubkey, "wt").write(pub.decode("utf-8"))
open(privkey, "wt").write(priv.decode("utf-8"))
print(f"\n{pubkey.replace(caPath, '')} and {privkey.replace(caPath, '')} were successfully saved to the {caPath} folder\n\n")
break
else:
time.sleep(1)
print("\n\nYou've entered an incorrect option, try 'y' or 'n' this time...\n")
time.sleep(1)
if self_signed_CA:
for fname in os.listdir(caPath):
if fname.endswith('.pem'):
pubkey = f'{caPath}/{fname}'
privkey = f'{caPath}/{fname}'
elif fname.endswith('.crt'):
pubkey = f'{caPath}/{fname}'
elif fname.endswith('.key'):
privkey = f'{caPath}/{fname}'
while True:
try:
ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM, open(pubkey).read())
ca_key = crypto.load_privatekey(crypto.FILETYPE_PEM, open(privkey).read())
break
except:
time.sleep(1)
print("\nYou've entered an incorrect password, try again...")
print('\n\n')
for req_file in os.listdir(csrPath):
if req_file.endswith('.csr'):
req = crypto.load_certificate_request(crypto.FILETYPE_PEM, open(f'{csrPath}/{req_file}').read())
cert = crypto.X509()
cert.set_subject(req.get_subject())
cert.set_serial_number(random.getrandbits(64))
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(60 * 60 * 24 * int(expiration))
cert.set_issuer(ca_cert.get_subject())
cert.set_pubkey(req.get_pubkey())
cert.sign(ca_key, digest)
fw_cert = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
fw_cert_name = f'{req_file[:-4]}.pem'
open(f'{pemPath}/{fw_cert_name}', "wt").write(fw_cert.decode("utf-8"))
print(f'{fw_cert_name} was successfully saved to the {pemPath} folder')
break
else:
while True:
caSvr_Address = input('\n\nEnter the IP/FQDN address of your Microsoft CA server: ')
ipr = re.match(r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$", caSvr_Address)
fqdnr = re.match(r"(?=^.{4,253}$)(^((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}$)", caSvr_Address)
if ipr:
break
elif fqdnr:
break
else:
print("There was something wrong with your entry. Please try again...\n")
caSvr_uname = input('Enter the username to perform CSR import: ')
caSvr_password = getpass.getpass('Please enter your password: ')
while True:
caSvr_authType = input('Enter the authentication type: [NTLM/basic] ')
if caSvr_authType == 'NTLM' or caSvr_authType == 'ntlm' or caSvr_authType == '':
caSvr_authType = 'ntlm'
caSvr_domain = input('Enter your domain: ')
break
elif caSvr_authType == 'basic':
break
else:
time.sleep(1)
print("\n\nYou've entered an incorrect option, try 'ntlm' or 'basic' this time...\n")
time.sleep(1)
## Prompts the user to enter the name of the CA cert on the server, and checks to make sure it exists in the current directory ##
while True:
caSvr_caCert = input("\nYou'll neeed to provide the root CA certificate for the CA server,\nmake sure you put it in the same directory as this script\n\nEnter the name of the cert: ")
pwd = os.getcwd()
if os.path.exists(pwd + '/' + caSvr_caCert):
break
else:
time.sleep(1)
print('The file does not exist (' + pwd.replace('\\\\', '\\') + '\\' + caSvr_caCert + ')\n\nPlease try again...')
time.sleep(1)
## Authenticates the user to the CA server, using the specified auth type and CA cert ##
ca_server = certsrv.Certsrv(caSvr_Address, caSvr_uname, caSvr_password, auth_method=caSvr_authType, cafile=caSvr_caCert)
## Checks the user's credentials to see if we can successfully authenticate to the CA server ##
while True:
try:
credCheck = ca_server.check_credentials()
except requests.exceptions.SSLError as e:
time.sleep(1)
print('\n\n' + str(e.message))
print('\nThere was an issue with connecting over HTTPS - either the CA cert that you provided does not match the\nCA cert on the ADCS server, or the cert is not trusted for some reason. Check the cert and try again\n\n')
time.sleep(1)
exit()
if credCheck == False:
time.sleep(1)
print("\n\nAuthentication to the CA server failed with the user credentials you provided, please try again...\n\n")
caSvr_uname = input('Enter the username to perform CSR import: ')
caSvr_password = getpass.getpass('Please enter your password: ')
ca_server = certsrv.Certsrv(caSvr_Address, caSvr_uname, caSvr_password, auth_method=caSvr_authType, cafile=caSvr_caCert)
else:
break
## Pulls the html from the CA server to get the list of templates available to the user ##
if caSvr_authType == 'ntlm':
r = requests.get('https://' + caSvr_Address + '/certsrv/certrqxt.asp', auth=HttpNtlmAuth(caSvr_domain + '\\' + caSvr_uname, caSvr_password), verify=False)
else:
r = requests.get('https://' + caSvr_Address + '/certsrv/certrqxt.asp', auth=HTTPBasicAuth(caSvr_uname, caSvr_password), verify=False)
tree = html.fromstring(r.content)
templateOptions_display = tree.xpath('//*[@id="lbCertTemplateID"]/option/text()') # Display values for template ##
templateOptions = []
for i in range(len(templateOptions_display)):
templateOptions.append(tree.xpath('//*[@id="lbCertTemplateID"]/option')[i].get('value').split(';')[1]) # Actual template names ##
## Displays a menu for the user to choose the template ##
while True:
time.sleep(1)
print('\nPlease choose a template:\n')
count = 1
for item in templateOptions_display:
print(str(count) + '. ' + item)
count += 1
try:
templateChoice = int(input('\nEnter your choice: '))
except ValueError:
time.sleep(1)
print('\nYou must enter a number, try again...\n')
time.sleep(1)
continue
if 0 >= templateChoice >= len(templateOptions_display):
time.sleep(1)
print("\nYou've entered a number that is not in the list, try again...\n")
time.sleep(1)
continue
else:
break
caSvr_template = templateOptions[templateChoice - 1]
## If there are are requests that are pending approval from previous sessions... ##
reqIDcheck = True
if os.path.exists(pemPath + '/reqIDs.txt'):
reqFile = open(pemPath + '/reqIDs.txt', 'r')
reqData = reqFile.read()
reqFile.close()
reqData = reqData.split(',')[:-1]
run = True
while run:
reqIDprompt = input('\n\nIt looks like there are requests that were pending approval.\nWould you like to attempt to retrieve the certs based off of those request IDs? [Y/n] ')
if reqIDprompt == 'n' or reqIDprompt == 'N':
time.sleep(1)
input('\nOk, the CSRs in the ' + csrPath + ' directory will be uploaded to the CA server to be signed\n\nHit Enter to continue...')
time.sleep(1)