forked from PyFortiAPI/PyFortiAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyfortiapi.py
632 lines (511 loc) · 21.7 KB
/
pyfortiapi.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
#!/usr/bin/env Python
__author__ = "James Simpson"
__copyright__ = "Copyright 2017, James Simpson"
__license__ = "MIT"
__version__ = "0.3.0"
import requests
import logging
from requests.packages.urllib3.exceptions import InsecureRequestWarning
class FortiGate:
def __init__(self, ipaddr, username, password, timeout=10, vdom="root", port="443", verify=False):
self.ipaddr = ipaddr
self.username = username
self.password = password
self.port = port
self.urlbase = "https://{ipaddr}:{port}/".format(ipaddr=self.ipaddr,port=self.port)
self.timeout = timeout
self.vdom = vdom
self.verify = verify
# Login / Logout Handlers
def login(self):
"""
Log in to FortiGate with info provided in during class instantiation
:return: Open Session
"""
session = requests.session()
if not self.verify:
# Disable requests' warnings for insecure connections
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
url = self.urlbase + 'logincheck'
# Login
session.post(url,
data='username={username}&secretkey={password}'.format(username=self.username,
password=self.password),
verify=self.verify,
timeout=self.timeout)
# Get CSRF token from cookies, add to headers
for cookie in session.cookies:
if cookie.name == 'ccsrftoken':
csrftoken = cookie.value[1:-1] # strip quotes
session.headers.update({'X-CSRFTOKEN': csrftoken})
# Check whether login was successful
login_check = session.get(self.urlbase + "api/v2/cmdb/system/vdom")
login_check.raise_for_status()
return session
def logout(self, session):
"""
Log out of device
:param session: Session created by login method
:return: None
"""
url = self.urlbase + 'logout'
session.get(url, verify=self.verify, timeout=self.timeout)
logging.info("Session logged out.")
# General Logic Methods
def does_exist(self, object_url):
"""
GET URL to assert whether it exists within the firewall
:param object_url: Object to locate
:return: Bool - True if exists, False if not
"""
session = self.login()
request = session.get(object_url, verify=self.verify, timeout=self.timeout, params='vdom='+self.vdom)
self.logout(session)
if request.status_code == 200:
return True
else:
return False
# API Interaction Methods
def get(self, url):
"""
Perform GET operation on provided URL
:param url: Target of GET operation
:return: Request result if successful (type list), HTTP status code otherwise (type int)
"""
session = self.login()
request = session.get(url, verify=self.verify, timeout=self.timeout, params='vdom='+self.vdom)
self.logout(session)
if request.status_code == 200:
return request.json()['results']
else:
return request.status_code
def put(self, url, data):
"""
Perform PUT operation on provided URL
:param url: Target of PUT operation
:param data: JSON data. MUST be a correctly formatted string. e.g. "{'key': 'value'}"
:return: HTTP status code returned from PUT operation
"""
session = self.login()
result = session.put(url, data=data, verify=self.verify, timeout=self.timeout, params='vdom='+self.vdom).status_code
self.logout(session)
return result
def post(self, url, data):
"""
Perform POST operation on provided URL
:param url: Target of POST operation
:param data: JSON data. MUST be a correctly formatted string. e.g. "{'key': 'value'}"
:return: HTTP status code returned from POST operation
"""
session = self.login()
result = session.post(url, data=data, verify=self.verify, timeout=self.timeout, params='vdom='+self.vdom).status_code
self.logout(session)
return result
def delete(self, url):
"""
Perform DELETE operation on provided URL
:param url: Target of DELETE operation
:return: HTTP status code returned from DELETE operation
"""
session = self.login()
result = session.delete(url, verify=self.verify, timeout=self.timeout, params='vdom='+self.vdom).status_code
self.logout(session)
return result
# Firewall Address Methods
def get_firewall_address(self, specific=False, filters=False):
"""
Get address object information from firewall
:param specific: If provided, a specific object will be returned. If not, all objects will be returned.
:param filters: If provided, the raw filter is appended to the API call.
:return: JSON data for all objects in scope of request, nested in a list.
"""
api_url = self.urlbase + "api/v2/cmdb/firewall/address/"
if specific:
api_url += specific
elif filters:
api_url += "?filter=" + filters
results = self.get(api_url)
return results
def update_firewall_address(self, address, data):
"""
Update firewall address record with provided data
:param address: Address record being updated
:param data: JSON Data with which to upate the address record
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/firewall/address/" + requests.utils.quote(address, safe='')
# Check whether target object exists
if not self.does_exist(api_url):
logging.error('Requested address "{address}" does not exist in Firewall config.'.format(address=address))
return 404
result = self.put(api_url, data)
return result
def create_firewall_address(self, address, data):
"""
Create firewall address record
:param address: Address record to be created
:param data: JSON Data with which to create the address record
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/firewall/address/"
# Check whether target object already exists
if self.does_exist(api_url + address):
return 424
result = self.post(api_url, data)
return result
def delete_firewall_address(self, address):
"""
Delete firewall address record
:param address: Address record to be deleted
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/firewall/address/" + address
result = self.delete(api_url)
return result
# Address Group Methods
def get_address_group(self, specific=False, filters=False):
"""
Get address group object information from firewall
:param specific: If provided, a specific object will be returned. If not, all objects will be returned.
:param filters: If provided, the raw filter is appended to the API call.
:return: JSON data for all objects in scope of request, nested in a list.
"""
api_url = self.urlbase + "api/v2/cmdb/firewall/addrgrp/"
if specific:
api_url += specific
elif filters:
api_url += "?filter=" + filters
results = self.get(api_url)
return results
def update_address_group(self, group_name, data):
"""
Update address group with provided data
:param group_name: Address group being updated
:param data: JSON Data with which to upate the address group
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/firewall/addrgrp/" + group_name
# Check whether target object already exists
if not self.does_exist(api_url):
logging.error('Requested address group "{group_name}" does not exist in Firewall config.'.format(
group_name=group_name))
return 404
result = self.put(api_url, data)
return result
def create_address_group(self, group_name, data):
"""
Create address group
:param group_name: Address group to be created
:param data: JSON Data with which to create the address group
:return: HTTP Status Code.
"""
api_url = self.urlbase + "api/v2/cmdb/firewall/addrgrp/"
if self.does_exist(api_url + group_name):
return 424
result = self.post(api_url, data)
return result
def delete_address_group(self, group_name):
"""
Delete firewall address group
:param group_name: Address group to be deleted
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/firewall/addrgrp/" + group_name
result = self.delete(api_url)
return result
# Service Category Methods
def get_service_category(self, specific=False, filters=False):
"""
Get service category information from firewall
:param specific: If provided, a specific object will be returned. If not, all objects will be returned.
:param filters: If provided, the raw filter is appended to the API call.
:return: JSON data for all objects in scope of request, nested in a list.
"""
api_url = self.urlbase + "api/v2/cmdb/firewall.service/category/"
if specific:
api_url += specific
elif filters:
api_url += "?filter=" + filters
results = self.get(api_url)
return results
def update_service_category(self, category, data):
"""
Update service category with provided data.
:param category: Service category being updated
:param data: JSON Data with which to upate the service category
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/firewall.service/category/" + category
# Check whether target object already exists
if not self.does_exist(api_url):
logging.error('Requested service category "{category}" does not exist in Firewall config.'.format(
category=category))
return 404
result = self.put(api_url, data)
return result
def create_service_category(self, category, data):
"""
Create service category
:param category: Service category to be created
:param data: JSON Data with which to create the service category
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/firewall.service/category/"
if self.does_exist(api_url + category):
return 424
result = self.post(api_url, data)
return result
def delete_service_category(self, category):
"""
Delete firewall service category
:param category: Service categrory to be deleted
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/firewall.service/category/" + category
result = self.delete(api_url)
return result
# Service Group Methods
def get_service_group(self, specific=False, filters=False):
"""
Get service group information from firewall
:param specific: If provided, a specific object will be returned. If not, all objects will be returned.
:param filters: If provided, the raw filter is appended to the API call.
:return: JSON data for all objects in scope of request, nested in a list.
"""
api_url = self.urlbase + "api/v2/cmdb/firewall.service/group/"
if specific:
api_url += specific
elif filters:
api_url += "?filter=" + filters
results = self.get(api_url)
return results
def update_service_group(self, group_name, data):
"""
Update service group with provided data
:param group_name: Service group being updated
:param data: JSON Data with which to upate the service group
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/firewall.service/group/" + group_name
# Check whether target object already exists
if not self.does_exist(api_url):
logging.error('Requested service group "{group_name}" does not exist in Firewall config.'.format(
group_name=group_name))
return 404
result = self.put(api_url, data)
return result
def create_service_group(self, group_name, data):
"""
Create service group
:param group_name: Service group to be created
:param data: JSON Data with which to create the service group
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/firewall.service/group/"
if self.does_exist(api_url + group_name):
return 424
result = self.post(api_url, data)
return result
def delete_service_group(self, group_name):
"""
Delete firewall service group
:param group_name: Service categrory to be deleted
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/firewall.service/group/" + group_name
result = self.delete(api_url)
return result
# Firewall Service Methods
def get_firewall_service(self, specific=False, filters=False):
"""
Get service object information from firewall
:param specific: If provided, a specific object will be returned. If not, all objects will be returned.
:param filters: If provided, the raw filter is appended to the API call.
:return: JSON data for all objects in scope of request, nested in a list.
"""
api_url = self.urlbase + "api/v2/cmdb/firewall.service/custom/"
if specific:
api_url += specific
elif filters:
api_url += "?filter=" + filters
results = self.get(api_url)
return results
def update_firewall_service(self, service_name, data):
"""
Update service with provided data
:param service_name: Service being updated
:param data: JSON Data with which to upate the service
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/firewall.service/custom/" + service_name
# Check whether target object already exists
if not self.does_exist(api_url):
logging.error('Requested service "{service_name}" does not exist in Firewall config.'.format(
service_name=service_name))
return 404
result = self.put(api_url, data)
return result
def create_firewall_service(self, service_name, data):
"""
Create service
:param service_name: Service to be created
:param data: JSON Data with which to create the service
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/firewall.service/custom/"
if self.does_exist(api_url + service_name):
return 424
result = self.post(api_url, data)
return result
def delete_firewall_service(self, service_name):
"""
Delete firewall service
:param service_name: Service categrory to be deleted
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/firewall.service/custom/" + service_name
result = self.delete(api_url)
return result
# Firewall Policy Methods
def get_firewall_policy(self, specific=False, filters=False):
"""
Get firewall policy information from firewall
:param specific: If provided, a specific object will be returned. If not, all objects will be returned.
Specific can either be the policy name, or the policy ID.
:param filters: If provided, the raw filter is appended to the API call.
:return: JSON data for all objects in scope of request, nested in a list.
"""
api_url = self.urlbase + "api/v2/cmdb/firewall/policy/"
if specific:
if type(specific) == int:
api_url += str(specific)
else:
api_url += "?filter=name==" + specific
elif filters:
api_url += "?filter=" + filters
results = self.get(api_url)
if type(results) == int:
return results
elif len(results) == 0:
return 404
else:
return results
def update_firewall_policy(self, policy_id, data):
"""
Update firewall policy with provided data
:param policy_id: ID of firewall policy to be updated
:param data: Data with which to update the firewall policy
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/firewall/policy/" + str(policy_id)
# Check whether target object already exists
if not self.does_exist(api_url):
logging.error('Requested Policy ID {policy_id} does not exist in Firewall Config.'.format(
policy_id=str(policy_id)))
return 404
result = self.put(api_url, data)
return result
def move_firewall_policy(self, policy_id, position, neighbour):
"""
Move firewall policy to new location
:param policy_id: ID of firewall policy being moved
:param position: "before" or "after"
:param neighbour: ID of policy being used as positional reference
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/firewall/policy/" + str(policy_id)
data = "{{'action': 'move', '{position}': {neighbour}}}".format(position=position, neighbour=neighbour)
result = self.put(api_url, data)
return result
def create_firewall_policy(self, policy_id, data):
"""
Create firewall Policy
:param policy_id: ID of policy to be created
:param data: Data with which to create policy
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/firewall/policy/"
# Check whether object already exists
if self.does_exist(api_url + str(policy_id)):
return 424
result = self.post(api_url, "{{'json': {data}}}".format(data=data))
return result
def delete_firewall_policy(self, policy_id):
"""
Delete firewall policy
:param policy_id: ID of policy to be deleted
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/firewall/policy/" + str(policy_id)
result = self.delete(api_url)
return result
# SNMPv2 Community Methods
def get_snmp_community(self, specific=False, filters=False):
"""
Get SNMP community information from firewall
:param specific: If provided, a specific object will be returned. If not, all objects will be returned.
Specific can either be the Community string, or its internal ID.
:param filters: If provided, the raw filter is appended to the API call.
:return: JSON data for all objects in scope of request, nested in a list.
"""
api_url = self.urlbase + "api/v2/cmdb/system.snmp/community/"
if specific:
if type(specific) == int:
api_url += str(specific)
else:
api_url += "?filter=name==" + specific
elif filters:
api_url += "?filter=" + filters
results = self.get(api_url)
return results
def update_snmp_community(self, community_id, data):
"""
Update SNMP community with provided data
:param community_id: ID of community being updated
:param data: JSON Data with which to update the community
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/system.snmp/community/" + str(community_id)
# Check whether target object already exists
if not self.does_exist(api_url):
logging.error('Requested SNMP Community ID "{community_id}" does not exist in Firewall config.'.format(
community_id=community_id))
return 404
result = self.put(api_url, data)
return result
def create_snmp_community(self, community_id, data):
"""
Create SNMP community
:param community_id: ID of the SNMP Community to be created
:param data: JSON Data with which to create the SNMP community
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/system.snmp/community/"
if self.does_exist(api_url + str(community_id)):
return 424
result = self.post(api_url, data)
return result
def delete_snmp_community(self, community_id):
"""
Delete SNMP community
:param community_id: ID of the SNMP Community to be deleted
:return: HTTP Status Code
"""
api_url = self.urlbase + "api/v2/cmdb/system.snmp/community/" + str(community_id)
result = self.delete(api_url)
return result
# ISDB read
def get_internet_services(self, specific=False, filters=False):
"""
Get ISDB (internet services database)
:param specific: If provided, a specific object will be returned.
:param filters: If provided, the raw filter is appended to the API call.
:return: JSON data for all objects in scope of request, nested in a list.
"""
api_url = self.urlbase + "api/v2/cmdb/firewall/internet-service/"
if specific:
api_url += str(specific)
elif filters:
api_url += "?filter=" + filters
results = self.get(api_url)
return results