forked from napalm-automation-community/napalm-asa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasa.py
452 lines (370 loc) · 15.8 KB
/
asa.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
# -*- coding: utf-8 -*-
# Copyright 2016 Dravetech AB. All rights reserved.
#
# The contents of this file are licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with the
# License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
"""
Napalm driver for Cisco ASA.
Read https://napalm.readthedocs.io for more information.
"""
from __future__ import unicode_literals
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import json
import re
from collections import OrderedDict
import time
# import third party lib
from napalm_asa._MC_INCOMPATIBLE_ENDPOINTS import MC_INCOMPATIBLE_ENDPOINTS
from netaddr import IPNetwork
from napalm.base import NetworkDriver
from napalm.base.utils import py23_compat
from napalm.base.exceptions import (
ConnectionException,
CommandErrorException,
)
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
class RespFetcherHttps:
"""Response fetcher."""
def __init__(
self,
username='admin',
password='insieme',
base_url='https://172.21.128.227/api',
timeout=30
):
"""Class init."""
self.username = username
self.password = password
self.base_url = base_url
self.timeout = timeout
self.token = ""
self.session = requests.Session()
self.headers = {'Content-Type': 'application/json'}
def get_auth_token(self):
""" Authenticate with user and password to get an auth token."""
full_url = self.base_url + "/tokenservices"
try:
token_request = self.session.post(full_url, auth=(self.username, self.password),
data="", timeout=self.timeout, verify=False)
if token_request.status_code is 204 and 'X-Auth-Token' in token_request.headers.keys():
self.token = token_request.headers['X-Auth-Token']
self.session.headers.update({'X-Auth-Token': token_request.headers['X-Auth-Token']})
return (True, None)
else:
return (False, token_request.status_code)
except requests.exceptions.RequestException as e:
raise ConnectionException(py23_compat.text_type(e))
def delete_token(self):
"""Delete auth token."""
full_url = self.base_url + "/tokenservices/{}".format(self.token)
try:
token_delete_request = self.session.delete(full_url,
auth=(self.username, self.password),
timeout=self.timeout, verify=False)
if token_delete_request.status_code is 204:
self.session.headers.pop('X-Auth-Token', None)
return (True, None)
else:
return (False, token_delete_request.status_code)
except requests.exceptions.RequestException as e:
raise ConnectionException(py23_compat.text_type(e))
def get_resp(self, endpoint="", data=None, params={}, throw=True):
"""Get response from device and returne parsed json."""
full_url = self.base_url + endpoint
f = None
try:
if data is not None:
f = self.session.post(full_url, data=data,
headers=self.headers, timeout=self.timeout,
params=params, verify=False)
else:
f = self.session.get(full_url,
headers=self.headers, timeout=self.timeout,
params=params, verify=False)
if (f.status_code != 200):
if throw:
errMsg = "Operation returned an error: {}".format(f.status_code)
raise CommandErrorException(errMsg)
else:
return False
return f.json()
except requests.exceptions.RequestException as e:
if throw:
raise ConnectionException(py23_compat.text_type(e))
else:
return False
def has_active_token(self):
status = False
if "X-Auth-Token" in self.session.headers:
response = self.get_resp('/monitoring/serialnumber', throw=False)
if 'kind' in response and response['kind'] == "object#QuerySerialNumber":
status = True
return status
class ASADriver(NetworkDriver):
"""Napalm driver for Cisco ASA."""
def __init__(self,
hostname,
username,
password,
timeout=60,
optional_args=None):
"""Class init."""
optional_args = optional_args or dict()
self.username = username
self.password = password
self.hostname = hostname
self.multicontext = False
self.contexts = None
self._context = None
self.port = optional_args.get('port', 443)
self.timeout = timeout
# delay factor is used for delaying api rest calls that show
# problematic behaviour when being followed by a subsequent call
# that follows to fast
self.delay = optional_args.get('delay', .5)
self.up = False
self.base_url = "https://{}:{}/api".format(self.hostname, self.port)
self.device = RespFetcherHttps(self.username, self.password, self.base_url, self.timeout)
def _authenticate(self):
"""Authenticate with device."""
auth_result = self.device.get_auth_token()
return auth_result
def _delete_token(self):
"""Delete auth token."""
delete_result = self.device.delete_token()
return delete_result
def _send_request(self, endpoint, data=None):
"""Send request method."""
if self._proxy_to_other_context(endpoint):
endpoint = "{}?context={}".format(endpoint, self._context)
if data is None:
response = self.device.get_resp(endpoint)
else:
response = self.device.get_resp(endpoint, json.dumps(data))
if 'rangeInfo' in response:
if response['rangeInfo']['limit'] < response['rangeInfo']['total']:
fetched_items = len(response['items'])
while fetched_items < response['rangeInfo']['total']:
offset = fetched_items
params = {'offset': offset}
if data is None:
r = self.device.get_resp(endpoint=endpoint, params=params)
else:
r = self.device.get_resp(endpoint=endpoint, data=json.dumps(data),
params=params)
fetched_items = fetched_items + len(r['items'])
response['items'] = response['items'] + r['items']
return response
def _get_interfaces_details(self, interfaces):
commands = []
for interface in interfaces:
commands.append("show interface " + interface)
results = self.cli(commands)
ifs_details = {}
for command, details in results.items():
if_name = re.search(r"show interface (.*)", command).group(1)
mac = re.search(r"MAC address (.{14}),", details).group(1)
match_if_status = re.search(r"line protocol is (.{2,4})\n", results[command])
if match_if_status.group(1) == 'up':
if_up = True
else:
if_up = False
ifs_details[if_name] = {
'mac_address': mac,
'is_up': if_up
}
return ifs_details
@property
def context(self):
return self._context
@context.setter
def context(self, value):
self._check_context_exists(value)
self._context = value
def _get_contexts(self):
try:
resp = self._send_request('/contextmgmt/securitycontexts')
except CommandErrorException as e:
if str(e)[-3:] == "400":
self.multicontext = False
return
self.multicontext = True
self.contexts = [ c['name'] for c in resp['items']]
self.contexts.append('system')
def _proxy_to_other_context(self, endpoint):
return self.multicontext and \
self._context and \
endpoint not in MC_INCOMPATIBLE_ENDPOINTS
def open(self):
"""
Open a connection to the device.
This method can be used to verify if the device is reachable
and credentials are valid before moving on to other, more complex,
requests.
"""
auth_result, code = self._authenticate()
if auth_result:
self.up = True
self._get_contexts()
return True
else:
self.up = False
raise ConnectionException('Cannot connect to {}. Error {}'.format(self.hostname, code))
def close(self):
"""Mark the connection to the device as closed."""
delete_result, code = self._delete_token()
if delete_result:
self.up = False
return True
else:
raise ConnectionException('Cannot connect to {}. Error {}'.format(self.hostname, code))
def cli(self, commands):
"""Run CLI commands via the API."""
data = {
"commands": commands
}
response = self._send_request("/cli", data)
result_dict = {}
for i, result in enumerate(response['response']):
result_dict[commands[i]] = result
return result_dict
def get_facts(self):
"""Get Facts."""
facts = {
'uptime': 0.0,
'vendor': u'Cisco Systems',
'os_version': u'',
'serial_number': u'',
'model': u'',
'hostname': u'',
'fqdn': u'',
'interface_list': []
}
serialNumber = self._send_request('/monitoring/serialnumber')
facts['serial_number'] = serialNumber['serialNumber']
deviceDetails = self._send_request('/monitoring/device/components/version')
facts['os_version'] = deviceDetails['asaVersion']
facts['uptime'] = deviceDetails['upTimeinSeconds']
facts['model'] = deviceDetails['deviceType']
results_from_cli = self.cli(['show hostname', 'show hostname fqdn'])
facts['hostname'] = results_from_cli['show hostname'].replace('\n', '')
facts['fqdn'] = results_from_cli['show hostname fqdn'].replace('\n', '')
interfaces = self.get_interfaces()
for if_name in interfaces:
facts['interface_list'].append(if_name)
return facts
def get_interfaces(self):
"""Get Interfaces."""
interfaces = OrderedDict()
response = self._send_request('/interfaces/physical')
if response['rangeInfo']['total'] > 0:
for int_info in response['items']:
interfaces[int_info['hardwareID']] = {
'is_up': False,
'is_enabled': not int_info['shutdown'],
'description': int_info['interfaceDesc'],
'last_flapped': -1.0,
'speed': 0,
'mac_address': u'',
}
ifs = []
for if_name in interfaces:
ifs.append(if_name)
# This is a nasty solution for an issue seen with ASA's
# using the /api/interfaces/physical endpoint. If you call
# that endpoint and then send another request to quickly
# (?), then the ASA closes the HTTPS connection without
# sending a reponse
if self.multicontext:
time.sleep(self.delay)
ifs_details = self._get_interfaces_details(ifs)
for if_name, details in ifs_details.items():
interfaces[if_name]['mac_address'] = details['mac_address']
interfaces[if_name]['is_up'] = details['is_up']
return interfaces
def _check_context_exists(self,context):
if context:
if not self.multicontext:
e = "Device is not in multicontext mode"
raise CommandErrorException(e)
if not context in self.contexts:
e = "Context {} does not exist on device".format(context)
raise CommandErrorException(e)
def get_config(self, retrieve='all'):
"""Get config."""
config = {
'startup': '',
'running': '',
'candidate': ''
}
commands = []
startup_cmd = "show startup-config"
running_cmd = "show running-config"
if retrieve.lower() in ['startup', 'all']:
commands.append(startup_cmd)
if retrieve.lower() in ['running', 'all']:
commands.append(running_cmd)
if retrieve.lower() in ['running', 'startup', 'all']:
results = self.cli(commands)
if retrieve.lower() in ['startup', 'all']:
config['startup'] = results[startup_cmd]
if retrieve.lower() in ['running', 'all']:
config['running'] = results[running_cmd]
return config
def get_interfaces_ip(self):
"""Get interfaces ip."""
interfaces = {}
response = self._send_request('/interfaces/physical')
if response['rangeInfo']['total'] > 0:
for int_info in response['items']:
if int_info['ipAddress'] != "NoneSelected":
interfaces[int_info['hardwareID']] = {}
ipv4 = int_info['ipAddress']
ip = ipv4['ip']['value']
mask = ipv4['netMask']['value']
network = ip + '/' + mask
prefix_length = IPNetwork(network).prefixlen
interfaces[int_info['hardwareID']]['ipv4'] = \
{ip: {'prefix_length': prefix_length}}
if len(int_info['ipv6Info']['ipv6Addresses']) > 0:
if int_info['hardwareID'] not in interfaces:
interfaces[int_info['hardwareID']] = {}
interfaces[int_info['hardwareID']]['ipv6'] = {}
for ipv6 in int_info['ipv6Info']['ipv6Addresses']:
ip = ipv6['address']['value']
prefix_length = ipv6['prefixLength']
interfaces[int_info['hardwareID']]['ipv6'][ip] = \
{'prefix_length': prefix_length}
return interfaces
def get_arp_table(self):
"""Get ARP Table."""
arp_table = []
response = self._send_request('/monitoring/arp')
if response['rangeInfo']['total'] > 0:
for item in response['items']:
mac = item['macAddress'].replace('.', '')
regex = re.compile(r'.{2}')
mac = ":".join(re.findall(regex, mac))
arp_table.append(
{
'interface': item['interface'],
'ip': item['ipAddress'],
'mac': mac,
'age': 0.0
}
)
return arp_table
def is_alive(self):
"""Check if connection is still valid."""
status = {"is_alive": self.device.has_active_token()}
return status