Debian Codegraph @

ansible_collections/cisco/aci/plugins/httpapi/aci.py

raw
1 # Copyright (c) 2020 Cisco and/or its affiliates.
2 # Copyright: (c) 2020, Shreyas Srish (@shrsr) <[email protected]>
3 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17
18 from __future__ import absolute_import, division, print_function
19
20 __metaclass__ = type
21
22 DOCUMENTATION = """
23 ---
24 name: aci
25 author:
26 - Shreyas Srish (@shrsr)
27 short_description: Ansible ACI HTTPAPI Plugin.
28 description:
29 - This ACI plugin provides the HTTPAPI methods needed to initiate
30 a connection to the APIC, send API requests and process the
31 response from the controller.
32 """
33
34 import ast
35 import base64
36 import json
37 import os
38 import re
39
40 from ansible.module_utils._text import to_text, to_native
41 from ansible.module_utils.connection import ConnectionError
42 from ansible.plugins.httpapi import HttpApiBase
43 from copy import copy, deepcopy
44
45 # Optional, only used for APIC signature-based authentication
46 try:
47 from OpenSSL.crypto import FILETYPE_PEM, load_privatekey, sign
48
49 HAS_OPENSSL = True
50 except ImportError:
51 HAS_OPENSSL = False
52
53 # Signature-based authentication using cryptography
54 try:
55 from cryptography.hazmat.primitives import serialization, hashes
56 from cryptography.hazmat.primitives.asymmetric import padding
57 from cryptography.hazmat.backends import default_backend
58
59 HAS_CRYPTOGRAPHY = True
60 except ImportError:
61 HAS_CRYPTOGRAPHY = False
62
63 CONNECTION_MAP = {"username": "remote_user", "timeout": "persistent_command_timeout"}
64 RESET_KEYS = ["username", "password", "port"]
65 CONNECTION_KEYS = RESET_KEYS + ["timeout", "use_proxy", "use_ssl", "validate_certs"]
66
67
68 class HttpApi(HttpApiBase):
69 def __init__(self, *args, **kwargs):
70 super(HttpApi, self).__init__(*args, **kwargs)
71 self.params = None
72 self.result = {}
73 self.backup_hosts = None
74 self.connection_error_check = False
75 self.connection_parameters = {}
76 self.current_host = None
77 self.provided_hosts = None
78 self.inventory_hosts = None
79
80 def set_params(self, params):
81 self.params = params
82
83 # Login function is executed until connection to a host is established or until all the hosts in the list are exhausted
84 def login(self, username, password):
85 """Log in to APIC"""
86 # Perform login request
87 self.connection.queue_message("debug", "Establishing login for {0} to {1}".format(username, self.connection.get_option("host")))
88 method = "POST"
89 path = "/api/aaaLogin.json"
90 payload = {"aaaUser": {"attributes": {"name": username, "pwd": password}}}
91 data = json.dumps(payload)
92 self.connection._connected = True
93 try:
94 response, response_data = self.connection.send(path, data, method=method)
95 self.connection._auth = {"Cookie": response.headers.get("Set-Cookie")}
96 self.connection.queue_message("debug", "Connection to {0} was successful".format(self.connection.get_option("host")))
97 except Exception as exc_login:
98 self.connection._connected = False
99 exc_login.path = path
100 raise
101
102 def set_parameters(self):
103 connection_parameters = {}
104 for key in CONNECTION_KEYS:
105 value = self.params.get(key) if self.params.get(key) is not None else self.connection.get_option(CONNECTION_MAP.get(key, key))
106 if key == "username" and value is None:
107 value = "admin"
108 self.connection.set_option(CONNECTION_MAP.get(key, key), value)
109 if key == "timeout" and self.connection.get_option("persistent_connect_timeout") <= value:
110 self.connection.set_option("persistent_connect_timeout", value + 30)
111
112 connection_parameters[key] = value
113 if self.connection_parameters and value != self.connection_parameters.get(key) and key in RESET_KEYS:
114 self.connection._connected = False
115 self.connection.queue_message("debug", "Re-setting connection due to change in the {0}".format(key))
116
117 if self.params.get("private_key") is not None:
118 self.connection.set_option("session_key", None)
119 connection_parameters["certificate_name"] = self.params.get("certificate_name")
120 connection_parameters["private_key"] = self.params.get("private_key")
121 elif self.connection.get_option("session_key") is not None and self.params.get("password") is None:
122 connection_parameters["certificate_name"] = list(self.connection.get_option("session_key").keys())[0]
123 connection_parameters["private_key"] = list(self.connection.get_option("session_key").values())[0]
124 else:
125 if self.connection_parameters.get("private_key") is not None:
126 self.connection._connected = False
127 self.connection.queue_message(
128 "debug", "Re-setting connection due to change from private/session key authentication to password authentication"
129 )
130 self.connection.set_option("session_key", None)
131 connection_parameters["private_key"] = None
132 connection_parameters["certificate_name"] = None
133
134 if self.connection_parameters != connection_parameters:
135 self.connection_parameters = copy(connection_parameters)
136
137 self.set_hosts()
138
139 def set_hosts(self):
140 if self.params.get("host") is not None:
141 hosts = ast.literal_eval(self.params.get("host")) if "[" in self.params.get("host") else self.params.get("host").split(",")
142 else:
143 if self.inventory_hosts is None:
144 self.inventory_hosts = re.sub(r"[[\]]", "", self.connection.get_option("host")).split(",")
145 hosts = self.inventory_hosts
146
147 if self.provided_hosts is None:
148 self.provided_hosts = deepcopy(hosts)
149 self.connection.queue_message("debug", "Provided Hosts: {0}".format(self.provided_hosts))
150 self.backup_hosts = deepcopy(hosts)
151 self.current_host = self.backup_hosts.pop(0)
152 self.connection.queue_message("debug", "Initializing operation on {0}".format(self.current_host))
153 elif self.provided_hosts != hosts:
154 self.provided_hosts = deepcopy(hosts)
155 self.connection.queue_message("debug", "Provided Hosts have changed: {0}".format(self.provided_hosts))
156 self.backup_hosts = deepcopy(hosts)
157 try:
158 self.backup_hosts.pop(self.backup_hosts.index(self.current_host))
159 self.connection.queue_message("debug", "Connected host {0} found in the provided hosts. Continuing with it.".format(self.current_host))
160 except Exception:
161 self.current_host = self.backup_hosts.pop(0)
162 self.connection._connected = False
163 self.connection.queue_message("debug", "Initializing operation on {0}".format(self.current_host))
164 self.connection.set_option("host", self.current_host)
165
166 # One API call is made via each call to send_request from aci.py in module_utils
167 # As long as a host is active in the list the API call will go through
168 def send_request(self, method, path, data):
169 """This method handles all APIC REST API requests other than login"""
170
171 self.set_parameters()
172
173 if self.connection_parameters.get("private_key") is not None:
174 try:
175 self.connection._auth = {"Cookie": "{0}".format(self.cert_auth(method, path, data).get("Cookie"))}
176 self.connection._connected = True
177 except Exception as exc_response:
178 self.connection._connected = False
179 return self._return_info("", method, self.validate_url(self.connection._url + path), str(exc_response))
180
181 try:
182 if self.connection._connected is False:
183 self.login(self.connection.get_option("remote_user"), self.connection.get_option("password"))
184 self.connection.queue_message("debug", "Sending {0} request to {1}".format(method, self.connection._url + path))
185 response, response_data = self.connection.send(path, data, method=method)
186 self.connection.queue_message(
187 "debug", "Received response from {0} for {1} operation with HTTP: {2}".format(self.connection.get_option("host"), method, response.getcode())
188 )
189 except Exception as exc_response:
190 self.connection.queue_message("debug", "Connection to {0} has failed: {1}".format(self.connection.get_option("host"), exc_response))
191 if len(self.backup_hosts) == 0:
192 self.provided_hosts = None
193 self.connection._connected = False
194 error = dict(
195 code=-1, text="No hosts left in the cluster to continue operation! Error on final host {0}".format(self.connection.get_option("host"))
196 )
197 if "path" in dir(exc_response):
198 path = exc_response.path
199 return self._return_info("", method, self.validate_url(self.connection._url + path), str(exc_response), error=error)
200 else:
201 self.current_host = self.backup_hosts.pop(0)
202 self.connection.queue_message("debug", "Switching host from {0} to {1}".format(self.connection.get_option("host"), self.current_host))
203 self.connection.set_option("host", self.current_host)
204 # recurse through function for retrying the request
205 return self.send_request(method, path, data)
206 # return statement executed upon each successful response from the request function
207 return self._verify_response(response, method, path, response_data)
208
209 # Built-in-function
210 def handle_httperror(self, exc):
211 self.connection.queue_message("debug", "Failed to receive response from {0} with {1}".format(self.connection.get_option("host"), exc))
212 if exc.code == 401:
213 raise ConnectionError(exc)
214 elif exc.code == 403 and self.connection_parameters.get("private_key") is None:
215 self.connection._auth = None
216 self.login(self.connection.get_option("remote_user"), self.connection.get_option("password"))
217 return True
218 return exc
219
220 def validate_url(self, url):
221 validated_url = re.match(r"^.*?\.json|^.*?\.xml", url).group(0)
222 if self.connection_parameters.get("port") is None:
223 return validated_url.replace(re.match(r"(https?:\/\/.*)(:\d*)\/?(.*)", url).group(2), "")
224 else:
225 return validated_url
226
227 def _verify_response(self, response, method, path, response_data):
228 """Process the return code and response object from APIC"""
229 response_value = self._get_response_value(response_data)
230 response_code = response.getcode()
231 path = self.validate_url(response.url)
232 # Response check to remain consistent with fetch_url's response
233 if str(response) == "HTTP Error 400: Bad Request":
234 msg = "{0}".format(response)
235 else:
236 msg = "{0} ({1} bytes)".format(response.msg, len(response_value))
237 return self._return_info(response_code, method, path, msg, respond_data=response_value)
238
239 def _get_response_value(self, response_data):
240 """Extract string data from response_data returned from APIC"""
241 return to_text(response_data.getvalue())
242
243 def _response_to_json(self, response_text):
244 """Convert response_text to json format"""
245 try:
246 return json.loads(response_text) if response_text else {}
247 # JSONDecodeError only available on Python 3.5+
248 except Exception:
249 return "Invalid JSON response: {0}".format(response_text)
250
251 def _return_info(self, response_code, method, path, msg, respond_data=None, error=None):
252 """Format success/error data and return with consistent format"""
253 info = {}
254 info["status"] = response_code
255 info["method"] = method
256 info["url"] = path
257 info["msg"] = msg
258 if error is not None:
259 info["error"] = error
260 else:
261 info["error"] = {}
262 # Response check to trigger key error if response_data is invalid
263 if respond_data is not None:
264 info["body"] = respond_data
265 return info
266
267 def cert_auth(self, method, path, payload=""):
268 """Perform APIC signature-based authentication, not the expected SSL client certificate authentication."""
269
270 if payload is None:
271 payload = ""
272
273 headers = dict()
274
275 try:
276 if HAS_CRYPTOGRAPHY:
277 key = self.connection_parameters.get("private_key").encode()
278 sig_key = serialization.load_pem_private_key(
279 key,
280 password=None,
281 backend=default_backend(),
282 )
283 else:
284 sig_key = load_privatekey(FILETYPE_PEM, self.connection_parameters.get("private_key"))
285 except Exception:
286 private_key_file_path = os.path.abspath(os.path.join(self.params.get("working_directory"), self.connection_parameters.get("private_key")))
287 if os.path.exists(private_key_file_path):
288 try:
289 permission = "r"
290 if HAS_CRYPTOGRAPHY:
291 permission = "rb"
292 with open(private_key_file_path, permission) as fh:
293 private_key_content = fh.read()
294 except Exception:
295 raise ConnectionError("Cannot open private key file {0}".format(private_key_file_path))
296 try:
297 if HAS_CRYPTOGRAPHY:
298 sig_key = serialization.load_pem_private_key(private_key_content, password=None, backend=default_backend())
299 else:
300 sig_key = load_privatekey(FILETYPE_PEM, private_key_content)
301 except Exception:
302 raise ConnectionError("Cannot load private key file {0}".format(self.connection_parameters.get("private_key")))
303 if self.connection_parameters.get("certificate_name") is None:
304 self.connection_parameters["certificate_name"] = os.path.basename(os.path.splitext(self.connection_parameters.get("private_key"))[0])
305 else:
306 raise ConnectionError(
307 "Provided private key {0} does not appear to be a private key or provided file does not exist.".format(private_key_file_path)
308 )
309 if self.connection_parameters.get("certificate_name") is None:
310 self.connection_parameters["certificate_name"] = self.connection.get_option("remote_user")
311 sig_request = method + path + payload
312 if HAS_CRYPTOGRAPHY:
313 sig_signature = sig_key.sign(sig_request.encode(), padding.PKCS1v15(), hashes.SHA256())
314 else:
315 sig_signature = sign(sig_key, sig_request, "sha256")
316 sig_dn = "uni/userext/user-{0}/usercert-{1}".format(self.connection.get_option("remote_user"), self.connection_parameters.get("certificate_name"))
317 headers["Cookie"] = (
318 "APIC-Certificate-Algorithm=v1.0; "
319 + "APIC-Certificate-DN={0}; ".format(sig_dn)
320 + "APIC-Certificate-Fingerprint=fingerprint; "
321 + "APIC-Request-Signature={0}".format(to_native(base64.b64encode(sig_signature)))
322 )
323 return headers