| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
from __future__ import absolute_import, division, print_function |
| 10 |
|
| 11 |
__metaclass__ = type |
| 12 |
|
| 13 |
DOCUMENTATION = """ |
| 14 |
--- |
| 15 |
name: fortios |
| 16 |
short_description: HttpApi Plugin for Fortinet FortiOS Appliance or VM |
| 17 |
description: |
| 18 |
- This HttpApi plugin provides methods to connect to Fortinet FortiOS Appliance or VM via REST API |
| 19 |
author: |
| 20 |
- Miguel Angel Munoz (@magonzalez) |
| 21 |
version_added: "2.0.0" |
| 22 |
""" |
| 23 |
|
| 24 |
import json |
| 25 |
from ansible.plugins.httpapi import HttpApiBase |
| 26 |
from ansible.module_utils.basic import to_text |
| 27 |
from ansible.module_utils.six.moves import urllib |
| 28 |
import re |
| 29 |
|
| 30 |
from datetime import datetime |
| 31 |
|
| 32 |
|
| 33 |
class HttpApi(HttpApiBase): |
| 34 |
def __init__(self, connection): |
| 35 |
super(HttpApi, self).__init__(connection) |
| 36 |
|
| 37 |
self._conn = connection |
| 38 |
self._system_version = None |
| 39 |
self._ansible_fos_version = 'v6.0.0' |
| 40 |
self._ansible_galaxy_version = '2.5.1' |
| 41 |
self._log = None |
| 42 |
self._logged_in = False |
| 43 |
self._api_login = False |
| 44 |
self._session_key = None |
| 45 |
self._cookie = None |
| 46 |
self._ccsrf_token = None |
| 47 |
self._admin_password = None |
| 48 |
|
| 49 |
def set_custom_option(self, k, v): |
| 50 |
|
| 51 |
|
| 52 |
self._options[k] = v |
| 53 |
|
| 54 |
def log(self, msg): |
| 55 |
log_enabled = self._options.get('enable_log', False) |
| 56 |
if not log_enabled: |
| 57 |
return |
| 58 |
if not self._log: |
| 59 |
self._log = open("/tmp/fortios.ansible.log", "w") |
| 60 |
self._log.write('All set options:') |
| 61 |
self._log.write(str(self.get_options()) + '\n') |
| 62 |
log_message = str(datetime.now()) |
| 63 |
log_message += ": " + str(msg) + '\n' |
| 64 |
self._log.write(log_message) |
| 65 |
self._log.flush() |
| 66 |
|
| 67 |
def get_access_token(self): |
| 68 |
'''get pre issued access token for API access or session_key from API based authentication.''' |
| 69 |
|
| 70 |
token = self._options.get('access_token', None) |
| 71 |
if token: |
| 72 |
return token |
| 73 |
|
| 74 |
|
| 75 |
if self._conn.get_option('session_key'): |
| 76 |
token_from_session = self._conn.get_option('session_key').get("access_token", None) |
| 77 |
if token_from_session: |
| 78 |
return token_from_session |
| 79 |
|
| 80 |
return self._session_key |
| 81 |
|
| 82 |
def set_become(self, become_context): |
| 83 |
""" |
| 84 |
Elevation is not required on Fortinet devices - Skipped |
| 85 |
:param become_context: Unused input. |
| 86 |
:return: None |
| 87 |
""" |
| 88 |
return None |
| 89 |
|
| 90 |
def login(self, username, password): |
| 91 |
"""Call a defined login endpoint to receive an authentication token. |
| 92 |
try API based authentication first and fall back to web based auth.""" |
| 93 |
|
| 94 |
if self._logged_in: |
| 95 |
self.log("Already logged in, skipping") |
| 96 |
return |
| 97 |
|
| 98 |
if (username is None or password is None) and self.get_access_token() is None: |
| 99 |
raise Exception('Please provide access token or username/password to login') |
| 100 |
|
| 101 |
if self.get_access_token() is not None: |
| 102 |
self.log('login with access token') |
| 103 |
self._logged_in = True |
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
status, dummy = self.send_request( |
| 110 |
url="/api/v2/monitor/system/status", |
| 111 |
should_pre_login=False, |
| 112 |
) |
| 113 |
|
| 114 |
if status == 401: |
| 115 |
raise Exception('Invalid access token. Please check') |
| 116 |
|
| 117 |
self.log('login with access token succeeded') |
| 118 |
return |
| 119 |
|
| 120 |
|
| 121 |
self._admin_password = password |
| 122 |
|
| 123 |
self.log('login with username and password, try API based auth first') |
| 124 |
auth_payload = { |
| 125 |
"username": username, |
| 126 |
"secretkey": str(password), |
| 127 |
"password": str(password), |
| 128 |
"ack_post_disclaimer": True, |
| 129 |
"ack_pre_disclaimer": True, |
| 130 |
"request_key": True |
| 131 |
} |
| 132 |
status_code, result_data = self.send_request( |
| 133 |
url='/api/v2/authentication', |
| 134 |
should_pre_login=False, |
| 135 |
data=json.dumps(auth_payload), |
| 136 |
method='POST', |
| 137 |
) |
| 138 |
self.log('API based auth returned status code %s, data: %s' % (status_code, result_data)) |
| 139 |
if status_code in [401, 404]: |
| 140 |
self.log('API based auth login attempt failed, fall back to /logincheck') |
| 141 |
data = "username=" + urllib.parse.quote(username) + "&secretkey=" + urllib.parse.quote(password) + "&ajax=1" |
| 142 |
dummy, result_data = self.send_request(url='/logincheck', should_pre_login=False, data=data, method='POST') |
| 143 |
self.log('/logincheck with user: %s %s' % (username, 'succeeds' if result_data[0] == '1' else 'fails')) |
| 144 |
if result_data[0] != '1': |
| 145 |
raise Exception('Wrong credentials. Please check') |
| 146 |
self._logged_in = True |
| 147 |
else: |
| 148 |
self.log('API based auth with user: %s %s' % (username, 'succeeds' if "LOGIN_SUCCESS" in result_data else 'fails')) |
| 149 |
if "LOGIN_SUCCESS" not in result_data: |
| 150 |
raise Exception('API based auth failed: wrong credentials. Please check') |
| 151 |
self._logged_in = True |
| 152 |
self._api_login = True |
| 153 |
try: |
| 154 |
json_result_data = json.loads(result_data) |
| 155 |
self._session_key = json_result_data['session_key'] |
| 156 |
except Exception: |
| 157 |
|
| 158 |
self.log('no session_key obtained from response body, fallback to parse headers, data %s' % (result_data)) |
| 159 |
|
| 160 |
|
| 161 |
self.update_system_version() |
| 162 |
|
| 163 |
def logout(self): |
| 164 |
"""Call to implement session logout.""" |
| 165 |
|
| 166 |
if self._api_login: |
| 167 |
self.log("logout with API based auth") |
| 168 |
self.send_request(url="/api/v2/authentication", method="DELETE") |
| 169 |
else: |
| 170 |
self.send_request(url="/logout", method="POST") |
| 171 |
self.log("logout with basic based auth") |
| 172 |
|
| 173 |
def update_auth(self, response, response_text): |
| 174 |
""" |
| 175 |
Get cookies and obtain value for csrftoken/session_key that will be used on next requests |
| 176 |
:param response: Response given by the server. |
| 177 |
:param response_text Unused_input. |
| 178 |
:return: Dictionary containing headers |
| 179 |
""" |
| 180 |
headers = { |
| 181 |
"Accept": "application/json", |
| 182 |
} |
| 183 |
|
| 184 |
access_token = self.get_access_token() |
| 185 |
if access_token is not None: |
| 186 |
self.log('using access token - no auth update needed: %s' % access_token) |
| 187 |
headers["Authorization"] = "Bearer " + access_token |
| 188 |
return headers |
| 189 |
if self._cookie or self._ccsrf_token: |
| 190 |
self.log('using existing cookie: %s; ccsrf_token %s' % (self._cookie, self._ccsrf_token)) |
| 191 |
headers['Cookie'] = self._cookie |
| 192 |
headers['x-csrftoken'] = self._ccsrf_token |
| 193 |
return headers |
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
raw_cookies = [] |
| 198 |
cookie_dict = {} |
| 199 |
for attr, val in response.getheaders(): |
| 200 |
if attr.lower() == 'set-cookie' and 'APSCOOKIE_' in val: |
| 201 |
headers['Cookie'] = val |
| 202 |
elif attr.lower() == 'set-cookie' and 'session_key' in val: |
| 203 |
session_key = re.search(r'_(\d+=\".*\")', val) |
| 204 |
if session_key: |
| 205 |
cookie_dict["session_key"] = session_key.group(1) |
| 206 |
|
| 207 |
|
| 208 |
else: |
| 209 |
raw_cookies.append(val.split(';')[0]) |
| 210 |
elif attr.lower() == 'set-cookie' and ('ccsrftoken' in val or 'ccsrf_token' in val): |
| 211 |
csrftoken_search = re.search('(.*)', val) |
| 212 |
|
| 213 |
self.log( |
| 214 |
'found csrftoken returned from server: %s, filtered %s' |
| 215 |
% ( |
| 216 |
to_text(val), |
| 217 |
to_text(csrftoken_search.group(1) if csrftoken_search else ''), |
| 218 |
) |
| 219 |
) |
| 220 |
if csrftoken_search: |
| 221 |
token = val.split(';')[0].split('=')[1] |
| 222 |
|
| 223 |
|
| 224 |
headers['x-csrftoken'] = token |
| 225 |
self._ccsrf_token = token |
| 226 |
elif attr.lower() == 'set-cookie' and 'ccsrf_token' in val: |
| 227 |
token = val.split(';')[0].split('=')[1] |
| 228 |
headers['x-csrftoken'] = token |
| 229 |
self._ccsrf_token = token |
| 230 |
elif attr.lower() == 'set-cookie': |
| 231 |
self.log('other raw cookie returned from server: %s' % to_text(val.split(';')[0])) |
| 232 |
raw_cookies.append(val.split(';')[0]) |
| 233 |
|
| 234 |
if len(cookie_dict) > 0: |
| 235 |
cookie = "" |
| 236 |
for key, value in cookie_dict.items(): |
| 237 |
cookie += key + "_" + value + "; " |
| 238 |
if "Cookie" in headers: |
| 239 |
cookie += '; ' + headers["Cookie"] |
| 240 |
headers['Cookie'] = cookie |
| 241 |
self._cookie = cookie |
| 242 |
self.log('Updated Cookie: %s' % (self._cookie)) |
| 243 |
|
| 244 |
if len(raw_cookies) > 0: |
| 245 |
raw_cookie = "; ".join(raw_cookies) |
| 246 |
if "Cookie" in headers: |
| 247 |
raw_cookie += '; ' + headers["Cookie"] |
| 248 |
headers['Cookie'] = raw_cookie |
| 249 |
self._cookie = headers['Cookie'] |
| 250 |
self.log('Added raw Cookie: %s' % (self._cookie)) |
| 251 |
|
| 252 |
self.log('updated auth headers: %s' % (headers.items())) |
| 253 |
return headers |
| 254 |
|
| 255 |
def handle_httperror(self, exc): |
| 256 |
""" |
| 257 |
propogate exceptions to users |
| 258 |
:param exc: Exception |
| 259 |
""" |
| 260 |
self.log('Exception thrown from handling http: ' + to_text(exc)) |
| 261 |
|
| 262 |
return exc |
| 263 |
|
| 264 |
def _concat_token(self, url): |
| 265 |
if self.get_access_token(): |
| 266 |
token_pair = 'access_token=' + self.get_access_token() |
| 267 |
return url + '&' + token_pair if '?' in url else url + '?' + token_pair |
| 268 |
return url |
| 269 |
|
| 270 |
def _concat_params(self, url, params): |
| 271 |
if not params or not len(params): |
| 272 |
return url |
| 273 |
url = url + '?' if '?' not in url else url |
| 274 |
for param_key in params: |
| 275 |
param_value = params[param_key] |
| 276 |
if url[-1] == '?': |
| 277 |
url += '%s=%s' % (param_key, param_value) |
| 278 |
else: |
| 279 |
url += '&%s=%s' % (param_key, param_value) |
| 280 |
return url |
| 281 |
|
| 282 |
def send_request(self, **message_kwargs): |
| 283 |
""" |
| 284 |
Responsible for actual sending of data to the connection httpapi base plugin. |
| 285 |
:param should_pre_login: should perform login in place instead of having connection obj to trigger. |
| 286 |
this is required because for httpapi update_auth can only update headers but /api/v2/authentication |
| 287 |
returns sessio_key in resp body. |
| 288 |
:param message_kwargs: A formatted dictionary containing request info: url, data, method |
| 289 |
|
| 290 |
:return: Status code and response data. |
| 291 |
""" |
| 292 |
if not self._logged_in and message_kwargs.get('should_pre_login', True): |
| 293 |
self.log('perform pre request login') |
| 294 |
|
| 295 |
self.connection.send("/api/v2/monitor/system/status", data={}, method='GET') |
| 296 |
|
| 297 |
url = message_kwargs.get('url', '/') |
| 298 |
data = message_kwargs.get('data', '') |
| 299 |
method = message_kwargs.get('method', 'GET') |
| 300 |
params = message_kwargs.get('params', {}) |
| 301 |
headers = message_kwargs.get('headers') or {} |
| 302 |
|
| 303 |
|
| 304 |
|
| 305 |
if "X-Admin-Passwd" in headers and headers.get("X-Admin-Passwd") is True: |
| 306 |
if self._admin_password is None: |
| 307 |
|
| 308 |
try: |
| 309 |
self._admin_password = self._conn.get_option("password") |
| 310 |
except Exception: |
| 311 |
self._admin_password = None |
| 312 |
if self._admin_password is not None: |
| 313 |
headers["X-Admin-Passwd"] = str(self._admin_password) |
| 314 |
|
| 315 |
if self.get_access_token() is not None: |
| 316 |
|
| 317 |
headers['Authorization'] = f"Bearer {self.get_access_token()}" |
| 318 |
|
| 319 |
url = self._concat_params(url, params) |
| 320 |
safe_headers = headers |
| 321 |
if "X-Admin-Passwd" in headers: |
| 322 |
safe_headers = dict(headers) |
| 323 |
safe_headers["X-Admin-Passwd"] = "***" |
| 324 |
self.log( |
| 325 |
"Sending request: METHOD:%s URL:%s DATA:%s HEADERS:%s" |
| 326 |
% (method, url, data, safe_headers) |
| 327 |
) |
| 328 |
|
| 329 |
|
| 330 |
try: |
| 331 |
response, response_data = self.connection.send(url, data, method=method, headers=headers) |
| 332 |
|
| 333 |
json_formatted = to_text(response_data.getvalue()) |
| 334 |
|
| 335 |
self.log("response status: %s, data: %s...<truncated>" % (to_text(response.status), json_formatted[:200])) |
| 336 |
|
| 337 |
return response.status, json_formatted |
| 338 |
except Exception as err: |
| 339 |
raise Exception('Error in send_request', err) |
| 340 |
|
| 341 |
def update_system_version(self): |
| 342 |
""" |
| 343 |
retrieve the system status of fortigate device |
| 344 |
""" |
| 345 |
self.log('checking system_version') |
| 346 |
check_system_status = self._options.get('check_system_status', True) |
| 347 |
if not check_system_status or self._system_version: |
| 348 |
return |
| 349 |
url = '/api/v2/monitor/system/status' |
| 350 |
status, result = self.send_request(url=url) |
| 351 |
self.log('system status returned status code %s, data: %s' % (status, result)) |
| 352 |
result_json = json.loads(result) |
| 353 |
self._system_version = result_json.get('version', 'undefined') |
| 354 |
self.log('system version: %s' % (self._system_version)) |
| 355 |
self.log('ansible version: %s' % (self._ansible_fos_version)) |
| 356 |
|
| 357 |
def get_system_version(self): |
| 358 |
self.update_system_version() |
| 359 |
self.log('returning system version: %s' % (self._system_version)) |
| 360 |
return self._system_version |