-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFMC-IPS-Script.py
More file actions
920 lines (840 loc) · 38.7 KB
/
FMC-IPS-Script.py
File metadata and controls
920 lines (840 loc) · 38.7 KB
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
import time ## Time
import json ##JAVA + API handler
import sys
import requests ##POSTMAN
#import queue
import getpass ## Password hide
import getch
import re
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
####<<Function for a yes/no question via raw_input() and return their answer >>#####
####################################################################################
def query_yes_no(question, default="yes"):
valid = {"yes":True, "y":True, "ye":True,
"no":False, "n":False}
if default == None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "\
"(or 'y' or 'n').\n")
####<<Function for removing error info from list>>#####
#######################################################
def remove_error_info(d):
if not isinstance(d, (dict, list)):
return d
if isinstance(d, list):
return [remove_error_info(v) for v in d]
return {k: remove_error_info(v) for k, v in d.items()
if k not in {'metadata', 'links'}}
####<<Function to get new Token from REST API and returns the headers>>########
###############################################################################
def new_token(ipaddr,user1,pass1):
url_start = "https://"
headers = {
'cache-control': "no-cache",
'postman-token': "ff30c506-4739-9d4d-2e53-0dc7efc2036a"
}
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
return auth_token
print ("==========================================")
print ("= =")
print ("= Cisco Firepower API =")
print ("= Enabling IPS and Logging to ACP Script =")
print ("= =")
print ("==========================================")
print ("= Coded by:DTMDENNIS =")
print ("==========================================")
url_start = "https://" ####<< start of URL to be Added to REST API URL >> ####
ipaddr = input("Enter your FMC IP address or hostname: ") ####<< Input FMC IP Address by user and store it in ipaddr >> ####
user1= input("Enter your FMC username: ") ####<< Input FMC username by user and store it in user1 >> ####
pass1= input("Enter your FMC password: ") ####<< Input FMC password by user and store it in pass1 >> ####
#pass1 = getpass.getpass("Enter your FMC password:") ####<< Input and hide FMC password by user and store it in pass1 >> ####
querystring = {"limit":"1000"} ####<< FMC Access-Control Max number of query per one Page >>####
####<< declear headers list with Postman token to use it in REST API Call>>####
headers = {
'cache-control': "no-cache",
'postman-token': "ff30c506-4739-9d4d-2e53-0dc7efc2036a"
}
print ("Retrieving all Intrusion Policies ...")
#######################################################################
#######################################################################
headers['X-auth-access-token']= new_token(ipaddr,user1,pass1) #### << Function to get New Token >> #####
####<<Calling the IPS Rules , adding number for each rule and display them to user to choose one>>####
######################################################################################################
api_path = "/api/fmc_config/v1/domain/e276abec-e0f2-11e3-8169-6d9ed49b625f/policy/intrusionpolicies"
url = url_start + ipaddr + api_path
if (url[-1] == '/'):
url = url[:-1]
num_array = list()
try:
r6 = requests.get(url, headers=headers,params=querystring, verify=False)
status_code = r6.status_code
resp = r6.text
if (status_code == 200):
print ("The current Intrusion Policies are: ")
number=1
json_resp6 = json.loads(resp)
for i in range(len(json_resp6["items"])):
num_array.append(json_resp6["items"][i]["name"])
print ("%d. %s" % (number,json_resp6["items"][i]["name"]))
number+=1
else:
r6.raise_for_status()
print("Error occurred in --> "+resp)
except requests.exceptions.HTTPError as err:
print ("Error in connection --> "+str(err))
finally:
if r6 : r6.close()
####<<choose number of the IPS rule want to push>>####
######################################################
while True:
choicenum = int(input ("Type the number of the IPS Policy for which you would like to apply: "))
choicenum-=1
if choicenum in range(len(num_array)):
for i in range(len(num_array)):
if choicenum == i:
choice6 = num_array.pop(i)
break
else:
print("Please type right number!")
for i in range(len(json_resp6["items"])):
if choice6 in json_resp6["items"][i].values():
ipspolicy_name = json_resp6["items"][i]["name"]
ipspolicy_type = json_resp6["items"][i]["type"]
ipspolicy_id = json_resp6["items"][i]["id"]
####<<using the IPS rule data and adding them to ipsfull>>####
##############################################################
ipsfull= {"ipsPolicy": {"name": "n", "id": "d", "type": "IntrusionPolicy"}, "logBegin": True, "logEnd": True, "sendEventsToFMC": True}
####<< enable Log >>####
########################
logingfull = {"logBegin": True, "logEnd": True, "sendEventsToFMC": True}
ipsfull['ipsPolicy']['name'] = ipspolicy_name
ipsfull['ipsPolicy']['id'] = ipspolicy_id
print('=================================================================================================')
print('=================================================================================================')
print('=================================================================================================')
choiceyesno=query_yes_no("did you choose the right Intrusion Policie?")
##### << getting Malware Policy infromation from FMC >> #####
################################################################################
###api_path = "/api/fmc_config/v1/domain/e276abec-e0f2-11e3-8169-6d9ed49b625f/policy/filepolicies"
###url = url_start + ipaddr + api_path
###if (url[-1] == '/'):
### url = url[:-1]
###num_array = list()
###try:
### r16 = requests.get(url, headers=headers,params=querystring, verify=False)
### status_code = r16.status_code
### resp = r16.text
### if (status_code == 200):
### print ("The current Malware Policies are: ")
### number=1
### json_resp16 = json.loads(resp)
### for i in range(len(json_resp16["items"])):
### num_array.append(json_resp16["items"][i]["name"])
### print ("%d. %s" % (number,json_resp16["items"][i]["name"]))
### #inpolicy = json_resp6["items"][i]["name"]
### number+=1
### else:
### r16.raise_for_status()
### print("Error occurred in --> "+resp)
###except requests.exceptions.HTTPError as err:
### print ("Error in connection --> "+str(err))
###finally:
### if r16 : r16.close()
###while True:
### choicenum = int(input ("Type the number of the Malware Policy for which you would like to apply: "))
### choicenum-=1
### if choicenum in range(len(num_array)):
### for i in range(len(num_array)):
### if choicenum == i:
### choice7 = num_array.pop(i)
### break
### else:
### print("Please type right number!")
###for i in range(len(json_resp16["items"])):
### if choice7 in json_resp16["items"][i].values():
### malwarepolicy_name = json_resp16["items"][i]["name"]
### malwarepolicy_type = json_resp16["items"][i]["type"]
### malwarepolicy_id = json_resp16["items"][i]["id"]
###malwarefull= {"filePolicy": {"name": "n", "id": "d", "type": "FilePolicy"}}
###malwarefull['filePolicy']['name'] = malwarepolicy_name
###malwarefull['filePolicy']['id'] = malwarepolicy_id
#print(ipspolicy_name)
#print(ipspolicy_type)
#print(ipspolicy_id)
#print(ipsfull)
#ips={"ipsPolicy": { "name": "Security Over Connectivity", "id": "abba9b63-bb10-4729-b901-2e2aa0f4491c","type": "IntrusionPolicy"},"logBegin": True,"logEnd": True,"sendEventsToFMC": True,}
#print(ipsfull)
#print(ips)
#= json.loads(resp)
#data.update(ips)
#data = remove_error_info(data)
#ips2 = json.dumps(data)
###print('=================================================================================================')
###print('=================================================================================================')
###print('=================================================================================================')
###choiceyesno=query_yes_no("did you choose the right Malware Policy?")
########################################################################################################
########################################################################################################
########################################################################################################
########################################################################################################
####<<Calling the Accesspolicies , adding number for each policy and display them to user to choose one>>####
#############################################################################################################
if choiceyesno == 1:
api_path = "/api/fmc_config/v1/domain/e276abec-e0f2-11e3-8169-6d9ed49b625f/policy/accesspolicies" # param
url = url_start + ipaddr + api_path
if (url[-1] == '/'):
url = url[:-1]
num_array2= list()
try:
r2 = requests.get(url, headers=headers,params=querystring, verify=False)
status_code = r2.status_code
resp = r2.text
if (status_code == 200):
print ("The current Access Policies are: ")
number=1
json_resp1 = json.loads(resp)
for i in range(len(json_resp1["items"])):
num_array2.append(json_resp1["items"][i]["name"])
print ("%d. %s" % (number,json_resp1["items"][i]["name"]))
number+=1
else:
r2.raise_for_status()
print("Error occurred in --> "+resp)
except requests.exceptions.HTTPError as err:
print ("Error in connection --> "+str(err))
finally:
if r2 : r2.close()
####<<choose number of the accesspolicies want to Modify>>####
##############################################################
while True:
choicenum2 = int(input ("Type the number of the Access Policy for which you would like to apply IPS and Logging features: "))
choicenum2-=1
if choicenum2 in range(len(num_array2)):
for i in range(len(num_array2)):
if choicenum2 == i:
choice = num_array2.pop(i)
break
else:
print("Please type right number!")
for i in range(len(json_resp1["items"])):
if choice in json_resp1["items"][i].values():
container_id = json_resp1["items"][i]["id"]
##print(container_id)
####<< Accessing accesspolicy and modfiy each access-rule inside it and appling IPS and logging >>####
#######################################################################################################
api_path = "/api/fmc_config/v1/domain/e276abec-e0f2-11e3-8169-6d9ed49b625f/policy/accesspolicies/" + container_id + "/accessrules" # param
url = url_start + ipaddr + api_path
if (url[-1] == '/'):
url = url[:-1]
print ("Applying IPS and Logging features to Access Rules........")
try:
global items
global items2
global items3
items = None
items2 = None
items3 = None
##with open('rules6.text', 'w') as target3:
for i in range(3):
offsetStr = "?offset=%d&limit=1000" % (i*1000)
url = url_start + ipaddr + api_path + offsetStr;
r3 = requests.get(url, headers=headers, verify=False)
status_code = r3.status_code
resp = r3.text
numcount=1
##with open('rules2.text', 'w') as target2:
##target2.write(resp)
if (status_code == 200):
if (i==0):
items = json.loads(resp)
## target2.write(resp)
if (i==1):
json_resp2= json.loads(resp)
items2 = json.loads(resp)
## target3.write("%s\n" % items2)
if (i==2):
items3 = json.loads(resp)
else:
r3.raise_for_status()
print("Error occurred in --> "+resp)
##target3.close()
except requests.exceptions.HTTPError as err:
print ("Error in connection --> "+str(err))
finally:
if r3 : r3.close()
policycount=0
####<<geting new Token from REST API and returns the headers>>########
###############################################################################
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
##############################################################################
rules_count=0
####<< For Loop for first 1000 accesspolicies to Get and Put the IPS & Logging on them >>####
#############################################################################################
for i in range(len(items["items"])):
if (rules_count == 150 ):
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
if (rules_count == 300):
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
if (rules_count == 450):
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
if (rules_count == 600):
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
if (rules_count == 750):
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
if (rules_count == 900):
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
rules_count+=1
print("Appling IPS and Logging on Rule number: %d " % rules_count)
rule_id = items["items"][i]["id"]
api_path = "/api/fmc_config/v1/domain/e276abec-e0f2-11e3-8169-6d9ed49b625f/policy/accesspolicies/" + container_id + "/accessrules/" + rule_id
url = url_start + ipaddr + api_path
if (url[-1] == '/'):
url = url[:-1]
r1 = requests.get(url, headers=headers, verify=False)
status_code = r1.status_code
resp = r1.text
if (status_code == 200):
json_resp = json.loads(resp)
ips=ipsfull.copy()
log=logingfull.copy()
###malware=malwarefull.copy()
data_log = json.loads(resp)
data = json.loads(resp)
data.update(ips)
###data.update(malware)
data = remove_error_info(data)
json_string = json.dumps(data)
data_log = remove_error_info(data_log)
json_string = json.dumps(data_log)
if data["action"] == 'ALLOW':
r1 = requests.put(url, data=json.dumps(data ,indent=25), headers=headers, verify=False)
status_code = r1.status_code
resp = r1.text
if (status_code == 200):
json_resp = json.loads(resp)
print ("IPS and Logging features applied to Acces Rule name << %s >>---> Done"%(data["name"]))
policycount+=1
else:
r1.raise_for_status()
print("Status code:-->"+status_code)
print("Error occurred in --> "+resp)
else:
data_log.update(log)
r1 = requests.put(url, data=json.dumps(data_log ,indent=25), headers=headers, verify=False)
status_code = r1.status_code
resp = r1.text
if (status_code == 200):
json_resp = json.loads(resp)
print("Applying Logging to Access rule << %s >> , rule action is blocked."%(data_log["name"]))
else:
r1.raise_for_status()
print("Error occurred in --> "+resp)
number+=1
time.sleep(.5)
if (items2['paging']['count'] == 0):
print(" ===== ")
print(" === ")
print(" = ")
print("Thank you for using this Script, Bye!")
key = input('Press Any Key To Exit.')
quit()
####<<geting new Token from REST API and returns the headers>>########
###############################################################################
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
##############################################################################
####<< For Loop for second 1000 accesspolicies to Get and Put the IPS & Logging on them >>####
#############################################################################################
for i in range(len(items2["items"])):
if (rules_count == 1050 ):
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
if (rules_count == 1200):
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
if (rules_count == 1350):
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
if (rules_count == 1500):
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
if (rules_count == 1650):
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
if (rules_count == 1800):
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
if (rules_count == 1950):
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
rules_count+=1
print("Rules Count: %d " % rules_count)
rule_id = items["items"][i]["id"]
api_path = "/api/fmc_config/v1/domain/e276abec-e0f2-11e3-8169-6d9ed49b625f/policy/accesspolicies/" + container_id + "/accessrules/" + rule_id
url = url_start + ipaddr + api_path
if (url[-1] == '/'):
url = url[:-1]
r1 = requests.get(url, headers=headers, verify=False)
status_code = r1.status_code
resp = r1.text
if (status_code == 200):
json_resp = json.loads(resp)
ips=ipsfull.copy()
log=logingfull.copy()
###malware=malwarefull.copy()
data_log = json.loads(resp)
data = json.loads(resp)
data.update(ips)
###data.update(malware)
data = remove_error_info(data)
json_string = json.dumps(data)
data_log = remove_error_info(data_log)
json_string = json.dumps(data_log)
if data["action"] == 'ALLOW':
r1 = requests.put(url, data=json.dumps(data ,indent=25), headers=headers, verify=False)
status_code = r1.status_code
resp = r1.text
if (status_code == 200):
json_resp = json.loads(resp)
print ("IPS and Logging features applied to Acces Rule name << %s >>---> Done"%(data["name"]))
policycount+=1
else:
r1.raise_for_status()
print("Status code:-->"+status_code)
print("Error occurred in --> "+resp)
else:
data_log.update(log)
r1 = requests.put(url, data=json.dumps(data_log ,indent=25), headers=headers, verify=False)
status_code = r1.status_code
resp = r1.text
if (status_code == 200):
json_resp = json.loads(resp)
print("Applying Logging to Access rule << %s >> , rule action is blocked."%(data_log["name"]))
else:
r.raise_for_status()
print("Error occurred in --> "+resp)
number+=1
time.sleep(.5)
if (items3['paging']['count'] == 0):
print(" ===== ")
print(" === ")
print(" = ")
print("Thank you for using this Script, Bye!")
key = input('Press Any Key To Exit.')
quit()
####<<geting new Token from REST API and returns the headers>>########
###############################################################################
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
##############################################################################
####<< For Loop for third 1000 accesspolicies to Get and Put the IPS & Logging on them >>####
#############################################################################################
for i in range(len(items3["items"])):
if (rules_count == 2100 ):
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
if (rules_count == 2250):
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
if (rules_count == 2400):
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
if (rules_count == 2550):
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
if (rules_count == 2700):
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
if (rules_count == 2850):
r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = url_start + ipaddr + api_auth_path
try:
r1 = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(user1,pass1), verify=False)
auth_headers = r1.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("Authentication Token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating Authentication Token --> "+str(err))
sys.exit()
headers['X-auth-access-token']=auth_token
rules_count+=1
print("Rules Count: %d " % rules_count)
rule_id = items["items"][i]["id"]
api_path = "/api/fmc_config/v1/domain/e276abec-e0f2-11e3-8169-6d9ed49b625f/policy/accesspolicies/" + container_id + "/accessrules/" + rule_id
url = url_start + ipaddr + api_path
if (url[-1] == '/'):
url = url[:-1]
### print("URL: %s " % url)
r1 = requests.get(url, headers=headers, verify=False)
status_code = r1.status_code
resp = r1.text
if (status_code == 200):
json_resp = json.loads(resp)
ips=ipsfull.copy()
log=logingfull.copy()
###malware=malwarefull.copy()
data_log = json.loads(resp)
data = json.loads(resp)
data.update(ips)
###data.update(malware)
data = remove_error_info(data)
json_string = json.dumps(data)
data_log = remove_error_info(data_log)
json_string = json.dumps(data_log)
if data["action"] == 'ALLOW':
r1 = requests.put(url, data=json.dumps(data ,indent=25), headers=headers, verify=False)
status_code = r1.status_code
resp = r1.text
if (status_code == 200):
json_resp = json.loads(resp)
print ("IPS and Logging features applied to Acces Rule name << %s >>---> Done"%(data["name"]))
policycount+=1
else:
r1.raise_for_status()
print("Status code:-->"+status_code)
print("Error occurred in --> "+resp)
else:
data_log.update(log)
r1 = requests.put(url, data=json.dumps(data_log ,indent=25), headers=headers, verify=False)
status_code = r1.status_code
resp = r1.text
if (status_code == 200):
json_resp = json.loads(resp)
print("Applying Logging to Access rule << %s >> , rule action is blocked."%(data_log["name"]))
else:
r.raise_for_status()
print("Error occurred in --> "+resp)
number+=1
time.sleep(.5)
print(' ')
print(' ')
print(' ')
print('=================================================================================================')
print('=================================================================================================')
print('=================================================================================================')
print("IPS and Logging features have been applied into %d Access Rule" %(policycount))
else:
print(" ===== ")
print(" === ")
print(" = ")
print("Thank you for using this Script, Bye!")
key = input('Press Any Key To Exit.')
quit()
print(" ===== ")
print(" === ")
print(" = ")
print("Thank you for using this Script, Bye!")
key = input('Press Any Key To Exit.')
quit()