Debian Codegraph @

ansible_collections/fortinet/fortimanager/plugins/httpapi/fortimanager.py

raw symbols SCIP
1 # Copyright (c) 2018-2021 Fortinet and/or its affiliates.
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17 #
18
19 from __future__ import absolute_import, division, print_function
20
21 __metaclass__ = type
22
23 DOCUMENTATION = """
24 ---
25 name: fortimanager
26 author:
27 - Xinwei Du (@dux-fortinet)
28 - Xing Li (@lix-fortinet)
29 - Link Zheng (@chillancezen)
30 - Luke Weighall (@lweighall)
31 - Andrew Welsh (@Ghilli3)
32 - Jim Huber (@p4r4n0y1ng)
33 short_description: HttpApi Plugin for Fortinet FortiManager Appliance or VM.
34 description:
35 - This HttpApi plugin provides methods to connect to Fortinet FortiManager Appliance or VM via JSON RPC API.
36 version_added: "1.0.0"
37
38 """
39
40 import time
41 import json
42 import os
43 from ansible.plugins.httpapi import HttpApiBase
44 from ansible.module_utils.common.text.converters import to_text
45 from ansible_collections.fortinet.fortimanager.plugins.module_utils.common import FMGBaseException
46 from ansible_collections.fortinet.fortimanager.plugins.module_utils.common import FMGRCommon
47 from datetime import datetime
48
49 ENABLE_LOG = os.getenv("ANSIBLE_FORTIMANAGER_ENABLE_LOG", "false").lower() in ["true", "1", "yes", "y", "t"]
50
51
52 class HttpApi(HttpApiBase):
53 def __init__(self, connection):
54 super(HttpApi, self).__init__(connection)
55 self._req_id = 0
56 self._sid = None
57 self._url = "/jsonrpc"
58 self._tools = FMGRCommon
59 self._adoms_locked_by_user = []
60 self._uses_workspace = False
61 self._uses_adoms = False
62 self._inspected_fmgr = False
63 self._log_file = None
64 self._login_method = None
65 self._status = {}
66 self._customer_options = {}
67
68 def set_customer_option(self, key, value):
69 self._customer_options[key] = value
70
71 def get_customer_option(self, key, default=None):
72 return self._customer_options.get(key, default)
73
74 def log(self, msg):
75 if not (self.get_customer_option("enable_log", False) or ENABLE_LOG):
76 return
77 if not self._log_file:
78 self._log_file = open("/tmp/fortimanager.ansible.log", "a")
79 log_message = to_text(datetime.now())
80 log_message += ": " + to_text(msg) + "\n"
81 self._log_file.write(log_message)
82 self._log_file.flush()
83
84 def log_request(self, json_request):
85 if not (self.get_customer_option("enable_log", False) or ENABLE_LOG):
86 return
87 params = json_request["params"]
88 # Don't log sensitive information
89 if params[0]["url"] == "sys/login/user" and "data" in params[0] and "passwd" in params[0]["data"]:
90 params[0]["data"]["passwd"] = "******"
91 if "session" in params[0]:
92 params[0]["session"] = "******"
93 log_data = json.dumps(json_request, ensure_ascii=False)
94 self.log("request: %s" % (log_data))
95
96 def log_response(self, response):
97 if not (self.get_customer_option("enable_log", False) or ENABLE_LOG):
98 return
99 log_data = self._jsonize(response)
100 if log_data:
101 self.log("response: %s" % (log_data))
102 else:
103 self.log("response: %s" % (to_text(response)))
104
105 def set_become(self, become_context):
106 """
107 ELEVATION IS NOT REQUIRED ON FORTINET DEVICES - SKIPPED
108 :param become_context: Unused input.
109 :return: None
110 """
111 return None
112
113 def update_auth(self, response, response_text):
114 """
115 TOKENS ARE NOT USED SO NO NEED TO UPDATE AUTH
116 :param response: Unused input.
117 :param response_data Unused_input.
118 :return: None
119 """
120 return None
121
122 def forticloud_login(self):
123 login_data = '{"access_token": "%s"}' % (self.get_customer_option("forticloud_access_token", None))
124 try:
125 response, response_data = self.connection.send(
126 path="/p/forticloud_jsonrpc_login/",
127 data=login_data,
128 headers={"Content-Type": "application/json", "Accept": "application/json"},
129 )
130 result = json.loads(to_text(response_data.getvalue()))
131 self.log("forticloud login response: %s" % (self._jsonize(result)))
132 return self._set_sid(result)
133 except Exception as e:
134 raise FMGBaseException(e)
135
136 def login(self, username, password):
137 """
138 This function will log the plugin into FortiManager, and return the results.
139 :param username: Username of FortiManager Admin
140 :param password: Password of FortiManager Admin
141
142 :return: Dictionary of status, if it logged in or not.
143 """
144 self.log("login begin, user: %s" % (username))
145 forticloud_access_token = self.get_customer_option("forticloud_access_token", None)
146 access_token = self.get_customer_option("access_token", None)
147 if username is not None and password is not None:
148 self._login_method = "username_password"
149 json_request = {
150 "method": "exec",
151 "params": [{"url": "sys/login/user", "data": {"passwd": to_text(password), "user": to_text(username)}}],
152 "session": self._sid,
153 "id": self._update_request_id(),
154 "verbose": 1,
155 }
156 data = json.dumps(json_request, ensure_ascii=False)
157 self.log_request(json_request)
158 header_data = {"Content-Type": "application/json", "Accept": "application/json"}
159 response, response_data = self.connection.send(
160 path=self._url, data=data, headers=header_data
161 )
162 response_text = to_text(response_data.getvalue())
163 result = ""
164 try:
165 result = json.loads(response_text)
166 except Exception as e:
167 raise FMGBaseException(msg="Got unexpected result: %s" % (response_text))
168 self.log_response(result)
169 self._set_sid(result)
170 self._handle_response(result)
171 elif access_token:
172 self._login_method = "access_token"
173 self.connection._auth = {'Authorization': f'Bearer {access_token}'}
174 elif forticloud_access_token:
175 self._login_method = "forticloud"
176 self.forticloud_login()
177 else:
178 err_msg = "Please check whether you provide the correct information."
179 raise AssertionError(err_msg)
180 self.log("login method: " + self._login_method)
181 if (not self._sid and not access_token) or self.connection._url is None:
182 err_msg = "Can't login. Your login method is %s. " % (self._login_method)
183 err_msg += "Please check whether you provide the correct information or have necessary permissions."
184 raise FMGBaseException(msg=err_msg)
185
186 def inspect_fmgr(self):
187 self._inspected_fmgr = True
188 # CHECK FOR WORKSPACE MODE TO SEE IF WE HAVE TO ENABLE ADOM LOCKS
189 rc, status = self.get_system_status()
190 if rc == -11:
191 # THE CONNECTION GOT LOST SOMEHOW, REMOVE THE SID AND REPORT BAD LOGIN
192 self.logout()
193 raise FMGBaseException(msg="Error -11 -- Failed to get the FMG system status. Exiting")
194 elif rc == 0:
195 try:
196 self.check_mode()
197 except Exception as e:
198 self.log("inspect_fmgr exception: %s" % (e))
199
200 def logout(self):
201 """
202 This function will logout of the FortiManager.
203 """
204 self.log(
205 "log out, using workspace:%s sid: %s"
206 % (self._uses_workspace, self._sid)
207 )
208 # IF WE WERE USING WORKSPACES, THEN CLEAN UP OUR LOCKS IF THEY STILL EXIST
209 if self._uses_workspace:
210 self.run_unlock()
211 if self._sid:
212 rc, response = self.send_request("exec", self._tools.format_request("exec", "sys/logout"))
213 self._sid = None
214 return rc, response
215
216 def send_request(self, method, params):
217 """
218 Responsible for actual sending of data to the connection httpapi base plugin. Does some formatting as well.
219 :param params: A formatted dictionary that was returned by self.common_datagram_params()
220 before being called here.
221 :param method: The preferred API Request method (GET, ADD, POST, etc....)
222 :type method: basestring
223
224 :return: Dictionary of status, if it logged in or not.
225 """
226 # Must do a connection check here to get _sid before sending request
227 if not self.connection._connected:
228 self.connection._connect()
229 if not self._inspected_fmgr:
230 self.inspect_fmgr()
231 json_request = {
232 "method": method,
233 "params": params,
234 "session": self._sid,
235 "id": self._update_request_id(),
236 "verbose": 1,
237 }
238 data = json.dumps(json_request, ensure_ascii=False)
239
240 header_data = {"Content-Type": "application/json", "Accept": "application/json"}
241 response, response_data = self.connection.send(
242 path=self._url, data=data, headers=header_data
243 )
244 self.log_request(json_request)
245 response_text = to_text(response_data.getvalue())
246 result = ""
247 try:
248 result = json.loads(response_text)
249 except Exception as e:
250 raise FMGBaseException(msg="Got unexpected result: %s" % (response_text))
251 self.log_response(result)
252 return self._handle_response(result)
253
254 def _jsonize(self, data):
255 ret = None
256 try:
257 ret = json.dumps(data, indent=2)
258 except Exception as e:
259 pass
260 return ret
261
262 def _handle_response(self, response):
263 if isinstance(response["result"], list):
264 result = response["result"][0]
265 else:
266 result = response["result"]
267 return result["status"]["code"], result
268
269 def _set_sid(self, response):
270 if self._sid is None and "session" in response:
271 self._sid = response["session"]
272
273 def get_system_status(self):
274 """
275 Returns the system status page from the FortiManager, for logging and other uses.
276 return: status
277 """
278 if self._status:
279 return 0, self._status
280 rc, self._status = self.send_request("get", self._tools.format_request("get", "/sys/status"))
281 if rc == -11:
282 rc, self._status = self.send_request("get", self._tools.format_request("get", "/cli/global/system/status"))
283 return rc, self._status
284
285 def process_workspace_locking(self, param):
286 if not self._inspected_fmgr:
287 self.inspect_fmgr()
288 if not self._uses_workspace:
289 return
290 if "workspace_locking_adom" not in param or not param["workspace_locking_adom"]:
291 # The FortiManager is running in workspace mode, please specify `workspace_locking_adom` in your playbook
292 # FIXME:by default, users have to know whether their fmg devices are running in worksapce mode and
293 # specify the paramters in playbook, we will find a better way to notify the users of this error
294 return
295 adom_to_lock = param["workspace_locking_adom"]
296 if adom_to_lock in self._adoms_locked_by_user:
297 self.log("adom: %s has already been acquired by the user" % (adom_to_lock))
298 return
299 total_wait_time = 0
300 while total_wait_time < param["workspace_locking_timeout"]:
301 code, resp_obj = self.lock_adom(adom_to_lock)
302 if code == 0:
303 self.log("adom:%s locked status: success" % (adom_to_lock))
304 self._adoms_locked_by_user.append(adom_to_lock)
305 return
306 self.log(
307 "waiting adom:%s lock to be released by other user, total time spent:%s seconds status:%s"
308 % (adom_to_lock, total_wait_time, "success" if code == 0 else "failure")
309 )
310 time.sleep(5)
311 total_wait_time += 5
312
313 def _update_request_id(self, reqid=0):
314 self._req_id = reqid if reqid != 0 else self._req_id + 1
315 return self._req_id
316
317 def __str__(self):
318 if self.connection._url is not None:
319 return "FortiManager object connected to FortiManager: " + self.connection._url
320 return "FortiManager object with no valid connection to a FortiManager appliance."
321
322 ##################################
323 # BEGIN DATABASE LOCK CONTEXT CODE
324 ##################################
325
326 def check_mode(self):
327 """
328 Checks FortiManager for the use of Workspace mode
329 """
330 url = "/cli/global/system/global"
331 rc, resp_obj = self.send_request("get", self._tools.format_request("get", url, fields=["workspace-mode", "adom-status"]))
332 # Skip this step if user is not permitted to access this resource
333 if rc == -11:
334 self.log("Skip workspace-mode check due to no permission to access /cli/global/system/global")
335 if "data" in resp_obj and isinstance(resp_obj["data"], dict):
336 if resp_obj["data"].get("adom-status", "") in [1, "enable"]:
337 self._uses_adoms = True
338 if resp_obj["data"].get("workspace-mode", "") in ["workflow", "normal", "per-adom"]:
339 self._uses_workspace = True
340 self.log("workspace-mode: %s adom-status: %s" % (self._uses_workspace, self._uses_adoms))
341
342 def run_unlock(self):
343 """
344 Checks for ADOM status, if locked, it will unlock
345 """
346 for adom_locked in self._adoms_locked_by_user:
347 self.commit_changes(adom_locked)
348 self.unlock_adom(adom_locked)
349 self.log("unlock adom: %s with session_id:%s" % (adom_locked, self._sid))
350
351 def lock_adom(self, adom=None):
352 """
353 Locks an ADOM for changes
354 """
355 if adom:
356 if adom.lower() == "global":
357 url = "/dvmdb/global/workspace/lock/"
358 else:
359 url = "/dvmdb/adom/{adom}/workspace/lock/".format(adom=adom)
360 else:
361 url = "/dvmdb/adom/root/workspace/lock"
362 code, respobj = self.send_request("exec", self._tools.format_request("exec", url))
363 if code == 0 and respobj["status"]["message"].lower() == "ok":
364 pass
365 return code, respobj
366
367 def unlock_adom(self, adom=None):
368 """
369 Unlocks an ADOM after changes
370 """
371 if adom:
372 if adom.lower() == "global":
373 url = "/dvmdb/global/workspace/unlock/"
374 else:
375 url = "/dvmdb/adom/{adom}/workspace/unlock/".format(adom=adom)
376 else:
377 url = "/dvmdb/adom/root/workspace/unlock"
378 code, respobj = self.send_request("exec", self._tools.format_request("exec", url))
379 if code == 0 and respobj["status"]["message"].lower() == "ok":
380 pass
381 return code, respobj
382
383 def commit_changes(self, adom=None, aux=False):
384 """
385 Commits changes to an ADOM
386 """
387 if adom:
388 if aux:
389 url = "/pm/config/adom/{adom}/workspace/commit".format(adom=adom)
390 else:
391 if adom.lower() == "global":
392 url = "/dvmdb/global/workspace/commit/"
393 else:
394 url = "/dvmdb/adom/{adom}/workspace/commit".format(adom=adom)
395 else:
396 url = "/dvmdb/adom/root/workspace/commit"
397 return self.send_request("exec", self._tools.format_request("exec", url))
398
399 def get_lock_info(self, adom=None):
400 """
401 Gets ADOM lock info so it can be displayed with the error messages. Or if determined to be locked by ansible
402 for some reason, then unlock it.
403 """
404 url = "/dvmdb/adom/root/workspace/lockinfo"
405 if adom:
406 if adom.lower() == "global":
407 url = "/dvmdb/global/workspace/lockinfo"
408 else:
409 url = "/dvmdb/adom/{adom}/workspace/lockinfo".format(adom=adom)
410 rc, resp_obj = self.send_request("get", self._tools.format_request("get", url))
411 # rc=-9: current adom is not in the workspace mode.
412 return rc, resp_obj
413
414 def get_adom_lock_user(self, adom):
415 self.log("lockinfo for adom:%s" % (adom))
416 rc, adom_lock_info = self.get_lock_info(adom=adom)
417 if adom_lock_info["status"]["code"] != 0:
418 return None
419 # if "data" is not in the response, the adom is locked by no one
420 if "data" not in adom_lock_info:
421 return None
422 lock_data = adom_lock_info["data"]
423 if isinstance(lock_data, list):
424 lock_data = lock_data[0]
425 return lock_data["lock_user"]
426
427 ################################
428 # END DATABASE LOCK CONTEXT CODE
429 ################################