Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_ssl_ocsp.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2018, F5 Networks Inc.
5 # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = r'''
11 ---
12 module: bigip_ssl_ocsp
13 short_description: Manage OCSP configurations on BIG-IP
14 description:
15 - Manage OCSP configurations on a BIG-IP system.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - Specifies the name of the OCSP certificate validator.
21 type: str
22 required: True
23 cache_error_timeout:
24 description:
25 - Specifies the lifetime of an error response in the cache, in seconds.
26 type: int
27 proxy_server_pool:
28 description:
29 - Specifies the proxy server pool the BIG-IP system uses to fetch the OCSP
30 response.
31 - This involves creating a pool with proxy-servers.
32 - Use this option when either the OCSP responder cannot be reached on any of
33 BIG-IP system's interfaces, or one or more servers can proxy an HTTP request
34 to an external server and fetch the response.
35 type: str
36 cache_timeout:
37 description:
38 - Specifies the lifetime of the OCSP response in the cache, in seconds.
39 type: str
40 clock_skew:
41 description:
42 - Specifies the tolerable absolute difference in the clocks of the responder
43 and the BIG-IP system, in seconds.
44 type: int
45 connections_limit:
46 description:
47 - Specifies the maximum number of connections per second allowed for the
48 OCSP certificate validator.
49 type: int
50 dns_resolver:
51 description:
52 - Specifies the internal DNS resolver the BIG-IP system uses to fetch the
53 OCSP response.
54 - This involves specifying one or more DNS servers in the DNS resolver
55 configuration.
56 - Use this option when either there is a DNS server that can do the
57 name-resolution of the OCSP responders, or the OCSP responder can be
58 reached on one of BIG-IP system's interfaces.
59 type: str
60 route_domain:
61 description:
62 - Specifies the route domain for fetching an OCSP response using HTTP
63 forward proxy.
64 type: str
65 hash_algorithm:
66 description:
67 - Specifies a hash algorithm used to sign an OCSP request.
68 type: str
69 choices:
70 - sha256
71 - sha1
72 certificate:
73 description:
74 - Specifies a certificate used to sign an OCSP request.
75 type: str
76 key:
77 description:
78 - Specifies a key used to sign an OCSP request.
79 type: str
80 passphrase:
81 description:
82 - Specifies a passphrase used to sign an OCSP request.
83 type: str
84 status_age:
85 description:
86 - Specifies the maximum allowed lag time the BIG-IP system accepts for
87 the 'thisUpdate' time in the OCSP response.
88 type: int
89 strict_responder_checking:
90 description:
91 - Specifies whether the responder's certificate is checked for an OCSP
92 signing extension.
93 type: bool
94 connection_timeout:
95 description:
96 - Specifies the time interval the BIG-IP system waits for before
97 ending the connection to the OCSP responder, in seconds.
98 type: int
99 trusted_responders:
100 description:
101 - Specifies the certificates used for validating the OCSP response
102 when the responder's certificate has been omitted from the response.
103 type: str
104 responder_url:
105 description:
106 - Specifies the absolute URL that overrides the OCSP responder URL
107 obtained from the certificate's AIA extensions. This should be an
108 HTTP-based URL.
109 type: str
110 update_password:
111 description:
112 - C(always) allows the user to update passwords.
113 C(on_create) only sets the password for newly created OCSP validators.
114 type: str
115 choices:
116 - always
117 - on_create
118 default: always
119 partition:
120 description:
121 - Device partition to manage resources on.
122 type: str
123 default: Common
124 state:
125 description:
126 - When C(present), ensures the resource exists.
127 - When C(absent), ensures the resource does not exist.
128 type: str
129 choices:
130 - present
131 - absent
132 default: present
133 extends_documentation_fragment: f5networks.f5_modules.f5
134 notes:
135 - Requires BIG-IP >= 13.x.
136 author:
137 - Tim Rupp (@caphrim007)
138 '''
139
140 EXAMPLES = r'''
141 - name: Create a OCSP validator
142 bigip_ssl_ocsp:
143 name: foo
144 proxy_server_pool: validators-pool
145 provider:
146 password: secret
147 server: lb.mydomain.com
148 user: admin
149 delegate_to: localhost
150 '''
151
152 RETURN = r'''
153 cache_error_timeout:
154 description: The new Response Caching Error Timeout value.
155 returned: changed
156 type: int
157 sample: 3600
158 cache_timeout:
159 description: The new Response Caching Timeout value.
160 returned: changed
161 type: str
162 sample: indefinite
163 clock_skew:
164 description: The new Response Validation Clock Skew value.
165 returned: changed
166 type: int
167 sample: 300
168 connections_limit:
169 description: The new Concurrent Connections Limit value.
170 returned: changed
171 type: int
172 sample: 50
173 dns_resolver:
174 description: The new DNS Resolver value.
175 returned: changed
176 type: str
177 sample: /Common/resolver1
178 route_domain:
179 description: The new Route Domain value.
180 returned: changed
181 type: str
182 sample: /Common/0
183 hash_algorithm:
184 description: The new Request Signing Hash Algorithm value.
185 returned: changed
186 type: str
187 sample: sha256
188 certificate:
189 description: The new Request Signing Certificate value.
190 returned: changed
191 type: str
192 sample: /Common/cert1
193 key:
194 description: The new Request Signing Key value.
195 returned: changed
196 type: str
197 sample: /Common/key1
198 proxy_server_pool:
199 description: The new Proxy Server Pool value.
200 returned: changed
201 type: str
202 sample: /Common/pool1
203 responder_url:
204 description: The new Connection Responder URL value.
205 returned: changed
206 type: str
207 sample: "http://responder.site.com"
208 status_age:
209 description: The new Response Validation Status Age value.
210 returned: changed
211 type: int
212 sample: 0
213 strict_responder_checking:
214 description: The new Response Validation Strict Responder Certificate Checking value.
215 returned: changed
216 type: bool
217 sample: true
218 connection_timeout:
219 description: The new Connection Timeout value.
220 returned: changed
221 type: int
222 sample: 8
223 trusted_responders:
224 description: The new Response Validation Trusted Responders value.
225 returned: changed
226 type: int
227 sample: /Common/default
228 '''
229 import traceback
230 from datetime import datetime
231
232 try:
233 from packaging.version import Version
234 except ImportError:
235 HAS_PACKAGING = False
236 Version = None
237 PACKAGING_IMPORT_ERROR = traceback.format_exc()
238 else:
239 HAS_PACKAGING = True
240 PACKAGING_IMPORT_ERROR = None
241
242 from ansible.module_utils.basic import (
243 AnsibleModule, missing_required_lib, env_fallback
244 )
245
246 from ..module_utils.bigip import F5RestClient
247 from ..module_utils.common import (
248 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean, fq_name
249 )
250 from ..module_utils.icontrol import tmos_version
251 from ..module_utils.teem import send_teem
252
253
254 class Parameters(AnsibleF5Parameters):
255 api_map = {
256 'cacheErrorTimeout': 'cache_error_timeout',
257 'cacheTimeout': 'cache_timeout',
258 'clockSkew': 'clock_skew',
259 'concurrentConnectionsLimit': 'connections_limit',
260 'dnsResolver': 'dns_resolver',
261 'proxyServerPool': 'proxy_server_pool',
262 'responderUrl': 'responder_url',
263 'routeDomain': 'route_domain',
264 'signHash': 'hash_algorithm',
265 'signerCert': 'certificate',
266 'signerKey': 'key',
267 'signerKeyPassphrase': 'passphrase',
268 'statusAge': 'status_age',
269 'strictRespCertCheck': 'strict_responder_checking',
270 'timeout': 'connection_timeout',
271 'trustedResponders': 'trusted_responders',
272 }
273
274 api_attributes = [
275 'cacheErrorTimeout',
276 'cacheTimeout',
277 'clockSkew',
278 'concurrentConnectionsLimit',
279 'dnsResolver',
280 'routeDomain',
281 'proxyServerPool',
282 'responderUrl',
283 'signHash',
284 'signerCert',
285 'signerKey',
286 'signerKeyPassphrase',
287 'statusAge',
288 'strictRespCertCheck',
289 'timeout',
290 'trustedResponders',
291 ]
292
293 returnables = [
294 'cache_error_timeout',
295 'cache_timeout',
296 'clock_skew',
297 'connections_limit',
298 'dns_resolver',
299 'route_domain',
300 'hash_algorithm',
301 'certificate',
302 'key',
303 'passphrase',
304 'proxy_server_pool',
305 'responder_url',
306 'status_age',
307 'strict_responder_checking',
308 'connection_timeout',
309 'trusted_responders',
310 ]
311
312 updatables = [
313 'cache_error_timeout',
314 'cache_timeout',
315 'clock_skew',
316 'connections_limit',
317 'dns_resolver',
318 'route_domain',
319 'hash_algorithm',
320 'certificate',
321 'key',
322 'passphrase',
323 'proxy_server_pool',
324 'responder_url',
325 'status_age',
326 'strict_responder_checking',
327 'connection_timeout',
328 'trusted_responders',
329 ]
330
331 @property
332 def strict_responder_checking(self):
333 return flatten_boolean(self._values['strict_responder_checking'])
334
335 @property
336 def cache_timeout(self):
337 if self._values['cache_timeout'] is None:
338 return None
339 try:
340 return int(self._values['cache_timeout'])
341 except ValueError:
342 return self._values['cache_timeout']
343
344
345 class ApiParameters(Parameters):
346 pass
347
348
349 class ModuleParameters(Parameters):
350 @property
351 def route_domain(self):
352 if self._values['route_domain'] is None:
353 return None
354 result = fq_name(self.partition, self._values['route_domain'])
355 return result
356
357 @property
358 def dns_resolver(self):
359 if self._values['dns_resolver'] is None:
360 return None
361 result = fq_name(self.partition, self._values['dns_resolver'])
362 return result
363
364 @property
365 def proxy_server_pool(self):
366 if self._values['proxy_server_pool'] is None:
367 return None
368 result = fq_name(self.partition, self._values['proxy_server_pool'])
369 return result
370
371 @property
372 def responder_url(self):
373 if self._values['responder_url'] is None:
374 return None
375 if self._values['responder_url'] in ['', 'none']:
376 return ''
377 return self._values['responder_url']
378
379 @property
380 def certificate(self):
381 if self._values['certificate'] is None:
382 return None
383 if self._values['certificate'] in ['', 'none']:
384 return ''
385 result = fq_name(self.partition, self._values['certificate'])
386 return result
387
388 @property
389 def key(self):
390 if self._values['key'] is None:
391 return None
392 if self._values['key'] in ['', 'none']:
393 return ''
394 result = fq_name(self.partition, self._values['key'])
395 return result
396
397 @property
398 def trusted_responders(self):
399 if self._values['trusted_responders'] is None:
400 return None
401 if self._values['trusted_responders'] in ['', 'none']:
402 return ''
403 result = fq_name(self.partition, self._values['trusted_responders'])
404 return result
405
406
407 class Changes(Parameters):
408 def to_return(self):
409 result = {}
410 try:
411 for returnable in self.returnables:
412 result[returnable] = getattr(self, returnable)
413 result = self._filter_params(result)
414 except Exception:
415 pass
416 return result
417
418
419 class UsableChanges(Changes):
420 @property
421 def strict_responder_checking(self):
422 if self._values['strict_responder_checking'] == 'yes':
423 return 'enabled'
424 elif self._values['strict_responder_checking'] == 'no':
425 return 'disabled'
426
427
428 class ReportableChanges(Changes):
429 @property
430 def strict_responder_checking(self):
431 result = flatten_boolean(self._values['strict_responder_checking'])
432 return result
433
434 @property
435 def passphrase(self):
436 return None
437
438
439 class Difference(object):
440 def __init__(self, want, have=None):
441 self.want = want
442 self.have = have
443
444 def compare(self, param):
445 try:
446 result = getattr(self, param)
447 return result
448 except AttributeError:
449 return self.__default(param)
450
451 def __default(self, param):
452 attr1 = getattr(self.want, param)
453 try:
454 attr2 = getattr(self.have, param)
455 if attr1 != attr2:
456 return attr1
457 except AttributeError:
458 return attr1
459
460 @property
461 def responder_url(self):
462 if self.want.responder_url is None:
463 return None
464 if self.want.responder_url == '' and self.have.responder_url is None:
465 return None
466 if self.want.responder_url != self.have.responder_url:
467 return self.want.responder_url
468
469 @property
470 def certificate(self):
471 if self.want.certificate is None:
472 return None
473 if self.want.certificate == '' and self.have.certificate is None:
474 return None
475 if self.want.certificate != self.have.certificate:
476 return self.want.certificate
477
478 @property
479 def key(self):
480 if self.want.key is None:
481 return None
482 if self.want.key == '' and self.have.key is None:
483 return None
484 if self.want.key != self.have.key:
485 return self.want.key
486
487 @property
488 def trusted_responders(self):
489 if self.want.trusted_responders is None:
490 return None
491 if self.want.trusted_responders == '' and self.have.trusted_responders is None:
492 return None
493 if self.want.trusted_responders != self.have.trusted_responders:
494 return self.want.trusted_responders
495
496
497 class ModuleManager(object):
498 def __init__(self, *args, **kwargs):
499 self.module = kwargs.get('module', None)
500 self.client = F5RestClient(**self.module.params)
501 self.want = ModuleParameters(params=self.module.params)
502 self.have = ApiParameters()
503 self.changes = UsableChanges()
504
505 def _set_changed_options(self):
506 changed = {}
507 for key in Parameters.returnables:
508 if getattr(self.want, key) is not None:
509 changed[key] = getattr(self.want, key)
510 if changed:
511 self.changes = UsableChanges(params=changed)
512
513 def _update_changed_options(self):
514 diff = Difference(self.want, self.have)
515 updatables = Parameters.updatables
516 changed = dict()
517 for k in updatables:
518 change = diff.compare(k)
519 if change is None:
520 continue
521 else:
522 if isinstance(change, dict):
523 changed.update(change)
524 else:
525 changed[k] = change
526 if changed:
527 self.changes = UsableChanges(params=changed)
528 return True
529 return False
530
531 def should_update(self):
532 result = self._update_changed_options()
533 if result:
534 return True
535 return False
536
537 def exec_module(self):
538 start = datetime.now().isoformat()
539 version = tmos_version(self.client)
540 if Version(version) < Version('13.0.0'):
541 raise F5ModuleError(
542 "BIG-IP v13 or greater is required to use this module."
543 )
544 changed = False
545 result = dict()
546 state = self.want.state
547
548 if state == "present":
549 changed = self.present()
550 elif state == "absent":
551 changed = self.absent()
552
553 reportable = ReportableChanges(params=self.changes.to_return())
554 changes = reportable.to_return()
555 result.update(**changes)
556 result.update(dict(changed=changed))
557 self._announce_deprecations(result)
558 send_teem(start, self.client, self.module, version)
559 return result
560
561 def _announce_deprecations(self, result):
562 warnings = result.pop('__warnings', [])
563 for warning in warnings:
564 self.client.module.deprecate(
565 msg=warning['msg'],
566 version=warning['version']
567 )
568
569 def present(self):
570 if self.exists():
571 return self.update()
572 else:
573 return self.create()
574
575 def exists(self):
576 uri = "https://{0}:{1}/mgmt/tm/sys/crypto/cert-validator/ocsp/{2}".format(
577 self.client.provider['server'],
578 self.client.provider['server_port'],
579 transform_name(self.want.partition, self.want.name)
580 )
581 resp = self.client.api.get(uri)
582 try:
583 response = resp.json()
584 except ValueError as ex:
585 raise F5ModuleError(str(ex))
586
587 if resp.status == 404 or 'code' in response and response['code'] == 404:
588 return False
589 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
590 return True
591
592 errors = [401, 403, 409, 500, 501, 502, 503, 504]
593
594 if resp.status in errors or 'code' in response and response['code'] in errors:
595 if 'message' in response:
596 raise F5ModuleError(response['message'])
597 else:
598 raise F5ModuleError(resp.content)
599
600 def update(self):
601 self.have = self.read_current_from_device()
602
603 if self.want.update_password == 'always':
604 self.want.update({'passphrase': self.want.passphrase})
605 else:
606 if self.want.passphrase:
607 del self.want._values['passphrase']
608
609 if not self.should_update():
610 return False
611
612 # these two params are mutually exclusive, and so one must be zeroed
613 # out so that the other can be set. This zeros the non-specified values
614 # out so that the PATCH can happen
615 if self.want.dns_resolver:
616 self.changes.update({'proxy_server_pool': ''})
617 if self.want.proxy_server_pool:
618 self.changes.update({'dns_resolver': ''})
619
620 if self.module.check_mode:
621 return True
622 self.update_on_device()
623 return True
624
625 def remove(self):
626 if self.module.check_mode:
627 return True
628 self.remove_from_device()
629 if self.exists():
630 raise F5ModuleError("Failed to delete the resource.")
631 return True
632
633 def create(self):
634 self._set_changed_options()
635 if self.module.check_mode:
636 return True
637 self.create_on_device()
638 return True
639
640 def create_on_device(self):
641 params = self.changes.api_params()
642 params['name'] = self.want.name
643 params['partition'] = self.want.partition
644 uri = "https://{0}:{1}/mgmt/tm/sys/crypto/cert-validator/ocsp/".format(
645 self.client.provider['server'],
646 self.client.provider['server_port']
647 )
648 resp = self.client.api.post(uri, json=params)
649 try:
650 response = resp.json()
651 except ValueError as ex:
652 raise F5ModuleError(str(ex))
653
654 if 'code' in response and response['code'] in [400, 403]:
655 if 'message' in response:
656 raise F5ModuleError(response['message'])
657 else:
658 raise F5ModuleError(resp.content)
659
660 def update_on_device(self):
661 params = self.changes.api_params()
662 uri = "https://{0}:{1}/mgmt/tm/sys/crypto/cert-validator/ocsp/{2}".format(
663 self.client.provider['server'],
664 self.client.provider['server_port'],
665 transform_name(self.want.partition, self.want.name)
666 )
667 resp = self.client.api.patch(uri, json=params)
668 try:
669 response = resp.json()
670 except ValueError as ex:
671 raise F5ModuleError(str(ex))
672
673 if 'code' in response and response['code'] == 400:
674 if 'message' in response:
675 raise F5ModuleError(response['message'])
676 else:
677 raise F5ModuleError(resp.content)
678
679 def absent(self):
680 if self.exists():
681 return self.remove()
682 return False
683
684 def remove_from_device(self):
685 uri = "https://{0}:{1}/mgmt/tm/sys/crypto/cert-validator/ocsp/{2}".format(
686 self.client.provider['server'],
687 self.client.provider['server_port'],
688 transform_name(self.want.partition, self.want.name)
689 )
690 response = self.client.api.delete(uri)
691 if response.status == 200:
692 return True
693 raise F5ModuleError(response.content)
694
695 def read_current_from_device(self):
696 uri = "https://{0}:{1}/mgmt/tm/sys/crypto/cert-validator/ocsp/{2}".format(
697 self.client.provider['server'],
698 self.client.provider['server_port'],
699 transform_name(self.want.partition, self.want.name)
700 )
701 resp = self.client.api.get(uri)
702 try:
703 response = resp.json()
704 except ValueError as ex:
705 raise F5ModuleError(str(ex))
706
707 if 'code' in response and response['code'] == 400:
708 if 'message' in response:
709 raise F5ModuleError(response['message'])
710 else:
711 raise F5ModuleError(resp.content)
712 return ApiParameters(params=response)
713
714
715 class ArgumentSpec(object):
716 def __init__(self):
717 self.supports_check_mode = True
718 argument_spec = dict(
719 name=dict(required=True),
720 cache_error_timeout=dict(type='int'),
721 proxy_server_pool=dict(),
722 cache_timeout=dict(),
723 clock_skew=dict(type='int'),
724 connections_limit=dict(type='int'),
725 dns_resolver=dict(),
726 route_domain=dict(),
727 hash_algorithm=dict(
728 choices=['sha256', 'sha1']
729 ),
730 certificate=dict(),
731 key=dict(no_log=True),
732 passphrase=dict(no_log=True),
733 status_age=dict(type='int'),
734 strict_responder_checking=dict(type='bool'),
735 connection_timeout=dict(type='int'),
736 trusted_responders=dict(),
737 responder_url=dict(),
738 update_password=dict(
739 default='always',
740 choices=['always', 'on_create'],
741 no_log=False
742 ),
743 state=dict(
744 default='present',
745 choices=['present', 'absent']
746 ),
747 partition=dict(
748 default='Common',
749 fallback=(env_fallback, ['F5_PARTITION'])
750 )
751 )
752 self.argument_spec = {}
753 self.argument_spec.update(f5_argument_spec)
754 self.argument_spec.update(argument_spec)
755 self.mutually_exclusive = [
756 ['dns_resolver', 'proxy_server_pool']
757 ]
758 self.required_together = [
759 ['certificate', 'key']
760 ]
761
762
763 def main():
764 spec = ArgumentSpec()
765
766 module = AnsibleModule(
767 argument_spec=spec.argument_spec,
768 supports_check_mode=spec.supports_check_mode,
769 mutually_exclusive=spec.mutually_exclusive,
770 required_together=spec.required_together,
771 )
772
773 if not HAS_PACKAGING:
774 module.fail_json(
775 msg=missing_required_lib('packaging'),
776 exception=PACKAGING_IMPORT_ERROR
777 )
778
779 try:
780 mm = ModuleManager(module=module)
781 results = mm.exec_module()
782 module.exit_json(**results)
783 except F5ModuleError as ex:
784 module.fail_json(msg=str(ex))
785
786
787 if __name__ == '__main__':
788 main()