Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_user_certificate.py

raw symbols SCIP
1 #!/usr/bin/python
2 from __future__ import absolute_import, division, print_function
3
4 # Copyright: (c) 2022 Fortinet
5 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 __metaclass__ = type
13
14 ANSIBLE_METADATA = {
15 "status": ["preview"],
16 "supported_by": "community",
17 "metadata_version": "1.1",
18 }
19
20 DOCUMENTATION = """
21 ---
22 module: fortios_user_certificate
23 short_description: Configure certificate users in Fortinet's FortiOS and FortiGate.
24 description:
25 - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the
26 user to set and modify user feature and certificate category.
27 Examples include all parameters and values need to be adjusted to datasources before usage.
28 Tested with FOS v6.0.0
29 version_added: "2.0.0"
30 author:
31 - Link Zheng (@chillancezen)
32 - Jie Xue (@JieX19)
33 - Hongbin Lu (@fgtdev-hblu)
34 - Frank Shen (@frankshen01)
35 - Miguel Angel Munoz (@mamunozgonzalez)
36 - Nicolas Thomas (@thomnico)
37 notes:
38 - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks
39
40 - The module supports check_mode.
41
42 requirements:
43 - ansible>=2.16
44 options:
45 access_token:
46 description:
47 - Token-based authentication.
48 Generated from GUI of Fortigate.
49 type: str
50 required: false
51 enable_log:
52 description:
53 - Enable/Disable logging for task.
54 type: bool
55 required: false
56 default: false
57 vdom:
58 description:
59 - Virtual domain, among those defined previously. A vdom is a
60 virtual instance of the FortiGate that can be configured and
61 used as a different unit.
62 type: str
63 default: root
64 member_path:
65 type: str
66 description:
67 - Member attribute path to operate on.
68 - Delimited by a slash character if there are more than one attribute.
69 - Parameter marked with member_path is legitimate for doing member operation.
70 member_state:
71 type: str
72 description:
73 - Add or delete a member under specified attribute path.
74 - When member_state is specified, the state option is ignored.
75 choices:
76 - 'present'
77 - 'absent'
78
79 state:
80 description:
81 - Indicates whether to create or remove the object.
82 type: str
83 required: true
84 choices:
85 - 'present'
86 - 'absent'
87 user_certificate:
88 description:
89 - Configure certificate users.
90 default: null
91 type: dict
92 suboptions:
93 common_name:
94 description:
95 - Certificate common name.
96 type: str
97 id:
98 description:
99 - User ID.
100 type: int
101 issuer:
102 description:
103 - CA certificate used for client certificate verification. Source vpn.certificate.ca.name.
104 type: str
105 name:
106 description:
107 - User name.
108 required: true
109 type: str
110 status:
111 description:
112 - Enable/disable allowing the certificate user to authenticate with the FortiGate unit.
113 type: str
114 choices:
115 - 'enable'
116 - 'disable'
117 type:
118 description:
119 - Type of certificate authentication method.
120 type: str
121 choices:
122 - 'single-certificate'
123 - 'trusted-issuer'
124 """
125
126 EXAMPLES = """
127 - name: Configure certificate users.
128 fortinet.fortios.fortios_user_certificate:
129 vdom: "{{ vdom }}"
130 state: "present"
131 access_token: "<your_own_value>"
132 user_certificate:
133 common_name: "<your_own_value>"
134 id: "4"
135 issuer: "<your_own_value> (source vpn.certificate.ca.name)"
136 name: "default_name_6"
137 status: "enable"
138 type: "single-certificate"
139 """
140
141 RETURN = """
142 build:
143 description: Build number of the fortigate image
144 returned: always
145 type: str
146 sample: '1547'
147 http_method:
148 description: Last method used to provision the content into FortiGate
149 returned: always
150 type: str
151 sample: 'PUT'
152 http_status:
153 description: Last result given by FortiGate on last operation applied
154 returned: always
155 type: str
156 sample: "200"
157 mkey:
158 description: Master key (id) used in the last call to FortiGate
159 returned: success
160 type: str
161 sample: "id"
162 name:
163 description: Name of the table used to fulfill the request
164 returned: always
165 type: str
166 sample: "urlfilter"
167 path:
168 description: Path of the table used to fulfill the request
169 returned: always
170 type: str
171 sample: "webfilter"
172 revision:
173 description: Internal revision number
174 returned: always
175 type: str
176 sample: "17.0.2.10658"
177 serial:
178 description: Serial number of the unit
179 returned: always
180 type: str
181 sample: "FGVMEVYYQT3AB5352"
182 status:
183 description: Indication of the operation's result
184 returned: always
185 type: str
186 sample: "success"
187 vdom:
188 description: Virtual domain used
189 returned: always
190 type: str
191 sample: "root"
192 version:
193 description: Version of the FortiGate
194 returned: always
195 type: str
196 sample: "v5.6.3"
197 """
198 from ansible.module_utils.basic import AnsibleModule
199 from ansible.module_utils.connection import Connection
200 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
201 FortiOSHandler,
202 )
203 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
204 check_legacy_fortiosapi,
205 )
206 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
207 schema_to_module_spec,
208 )
209 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
210 check_schema_versioning,
211 )
212 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
213 FAIL_SOCKET_MSG,
214 )
215 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
216 remove_invalid_fields,
217 )
218 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
219 is_same_comparison,
220 )
221 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
222 serialize,
223 )
224 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
225 find_current_values,
226 )
227 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
228 unify_data_format,
229 )
230
231
232 def filter_user_certificate_data(json):
233 option_list = ["common_name", "id", "issuer", "name", "status", "type"]
234
235 json = remove_invalid_fields(json)
236 dictionary = {}
237
238 for attribute in option_list:
239 if attribute in json and json[attribute] is not None:
240 dictionary[attribute] = json[attribute]
241
242 return dictionary
243
244
245 def underscore_to_hyphen(data):
246 new_data = None
247 if isinstance(data, list):
248 new_data = []
249 for i, elem in enumerate(data):
250 new_data.append(underscore_to_hyphen(elem))
251 elif isinstance(data, dict):
252 new_data = {}
253 for k, v in data.items():
254 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
255 else:
256 return data
257 return new_data
258
259
260 def user_certificate(data, fos, check_mode=False):
261
262 state = None
263 vdom = data["vdom"]
264 parameters = None
265 state = data.get("state", None)
266 user_certificate_data = data["user_certificate"]
267
268 filtered_data = filter_user_certificate_data(user_certificate_data)
269 converted_data = underscore_to_hyphen(filtered_data)
270
271 # check_mode starts from here
272 if check_mode:
273 diff = {
274 "before": "",
275 "after": filtered_data,
276 }
277 mkeyname = fos.get_mkeyname(None, None)
278 mkey = fos.get_mkey("user", "certificate", filtered_data, vdom=vdom)
279 current_data = fos.get(
280 "user", "certificate", vdom=vdom, mkey=mkey, parameters=parameters
281 )
282 is_existed = (
283 current_data
284 and current_data.get("http_status") == 200
285 and (
286 mkeyname
287 and isinstance(current_data.get("results"), list)
288 and len(current_data["results"]) > 0
289 or not mkeyname
290 and current_data["results"] # global object response
291 )
292 )
293
294 # 2. if it exists and the state is 'present' then compare current settings with desired
295 if state == "present" or state is True or state is None:
296 # for non global modules, mkeyname must exist and it's a new module when mkey is None
297 if mkeyname is not None and mkey is None:
298 return False, True, filtered_data, diff
299
300 # if mkey exists then compare each other
301 # record exits and they're matched or not
302 copied_filtered_data = filtered_data.copy()
303 copied_filtered_data.pop(mkeyname, None)
304 unified_filtered_data = unify_data_format(copied_filtered_data)
305
306 current_data_results = current_data.get("results", {})
307 current_config = (
308 current_data_results[0]
309 if mkeyname
310 and isinstance(current_data_results, list)
311 and len(current_data_results) > 0
312 else current_data_results
313 )
314 if is_existed:
315 unified_current_values = find_current_values(
316 unified_filtered_data,
317 unify_data_format(current_config),
318 )
319
320 is_same = is_same_comparison(
321 serialize(unified_current_values), serialize(unified_filtered_data)
322 )
323
324 return (
325 False,
326 not is_same,
327 filtered_data,
328 {"before": unified_current_values, "after": unified_filtered_data},
329 )
330
331 # record does not exist
332 return False, True, filtered_data, diff
333
334 if state == "absent":
335 if mkey is None:
336 return (
337 False,
338 False,
339 filtered_data,
340 {"before": current_data["results"][0], "after": ""},
341 )
342
343 if is_existed:
344 return (
345 False,
346 True,
347 filtered_data,
348 {"before": current_data["results"][0], "after": ""},
349 )
350 return False, False, filtered_data, {}
351
352 return True, False, {"reason: ": "Must provide state parameter"}, {}
353 # pass post processed data to member operations
354 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
355 data_copy = data.copy()
356 data_copy["user_certificate"] = filtered_data
357 fos.do_member_operation(
358 "user",
359 "certificate",
360 data_copy,
361 )
362
363 if state == "present" or state is True:
364 return fos.set(
365 "user", "certificate", data=converted_data, vdom=vdom, parameters=parameters
366 )
367
368 elif state == "absent":
369 return fos.delete(
370 "user",
371 "certificate",
372 mkey=converted_data["name"],
373 vdom=vdom,
374 parameters=parameters,
375 )
376 else:
377 fos._module.fail_json(msg="state must be present or absent!")
378
379
380 def is_successful_status(resp):
381 return (
382 "status" in resp
383 and resp["status"] == "success"
384 or "http_status" in resp
385 and resp["http_status"] == 200
386 or "http_method" in resp
387 and resp["http_method"] == "DELETE"
388 and resp["http_status"] == 404
389 )
390
391
392 def fortios_user(data, fos, check_mode):
393
394 if data["user_certificate"]:
395 resp = user_certificate(data, fos, check_mode)
396 else:
397 fos._module.fail_json(msg="missing task body: %s" % ("user_certificate"))
398 if isinstance(resp, tuple) and len(resp) == 4:
399 return resp
400 return (
401 not is_successful_status(resp),
402 is_successful_status(resp)
403 and (resp["revision_changed"] if "revision_changed" in resp else True),
404 resp,
405 {},
406 )
407
408
409 versioned_schema = {
410 "type": "list",
411 "elements": "dict",
412 "children": {
413 "name": {"v_range": [["v7.0.1", ""]], "type": "string", "required": True},
414 "status": {
415 "v_range": [["v7.0.1", ""]],
416 "type": "string",
417 "options": [{"value": "enable"}, {"value": "disable"}],
418 },
419 "type": {
420 "v_range": [["v7.0.1", ""]],
421 "type": "string",
422 "options": [{"value": "single-certificate"}, {"value": "trusted-issuer"}],
423 },
424 "common_name": {"v_range": [["v7.0.1", ""]], "type": "string"},
425 "issuer": {"v_range": [["v7.0.1", ""]], "type": "string"},
426 "id": {
427 "v_range": [["v7.0.1", "v7.0.5"], ["v7.2.0", "v7.2.0"]],
428 "type": "integer",
429 },
430 },
431 "v_range": [["v7.0.1", ""]],
432 }
433
434
435 def main():
436 module_spec = schema_to_module_spec(versioned_schema)
437 mkeyname = "name"
438 fields = {
439 "access_token": {"required": False, "type": "str", "no_log": True},
440 "enable_log": {"required": False, "type": "bool", "default": False},
441 "vdom": {"required": False, "type": "str", "default": "root"},
442 "member_path": {"required": False, "type": "str"},
443 "member_state": {
444 "type": "str",
445 "required": False,
446 "choices": ["present", "absent"],
447 },
448 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
449 "user_certificate": {
450 "required": False,
451 "type": "dict",
452 "default": None,
453 "options": {},
454 },
455 }
456 for attribute_name in module_spec["options"]:
457 fields["user_certificate"]["options"][attribute_name] = module_spec["options"][
458 attribute_name
459 ]
460 if mkeyname and mkeyname == attribute_name:
461 fields["user_certificate"]["options"][attribute_name]["required"] = True
462
463 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
464 check_legacy_fortiosapi(module)
465
466 is_error = False
467 has_changed = False
468 result = None
469 diff = None
470
471 versions_check_result = None
472 if module._socket_path:
473 connection = Connection(module._socket_path)
474 if "access_token" in module.params:
475 connection.set_custom_option("access_token", module.params["access_token"])
476
477 if "enable_log" in module.params:
478 connection.set_custom_option("enable_log", module.params["enable_log"])
479 else:
480 connection.set_custom_option("enable_log", False)
481 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
482 versions_check_result = check_schema_versioning(
483 fos, versioned_schema, "user_certificate"
484 )
485
486 is_error, has_changed, result, diff = fortios_user(
487 module.params, fos, module.check_mode
488 )
489
490 else:
491 module.fail_json(**FAIL_SOCKET_MSG)
492
493 if versions_check_result and versions_check_result["matched"] is False:
494 module.warn(
495 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
496 )
497
498 if not is_error:
499 if versions_check_result and versions_check_result["matched"] is False:
500 module.exit_json(
501 changed=has_changed,
502 version_check_warning=versions_check_result,
503 meta=result,
504 diff=diff,
505 )
506 else:
507 module.exit_json(changed=has_changed, meta=result, diff=diff)
508 else:
509 if versions_check_result and versions_check_result["matched"] is False:
510 module.fail_json(
511 msg="Error in repo",
512 version_check_warning=versions_check_result,
513 meta=result,
514 )
515 else:
516 module.fail_json(msg="Error in repo", meta=result)
517
518
519 if __name__ == "__main__":
520 main()