Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_profile_server_ssl.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_profile_server_ssl
13 short_description: Manages server SSL profiles on a BIG-IP
14 description:
15 - Manages server SSL profiles on a BIG-IP system.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - Specifies the name of the profile.
21 type: str
22 required: True
23 parent:
24 description:
25 - The parent template of this monitor template. Once this value has
26 been set, it cannot be changed.
27 type: raw
28 default: /Common/serverssl
29 ciphers:
30 description:
31 - Specifies the list of ciphers the system supports. When creating a new
32 profile, the default cipher list is provided by the parent profile.
33 - When the C(cipher_group) parameter is in use, the C(ciphers) parameter needs to be set to either C(none) or C('').
34 type: str
35 cipher_group:
36 description:
37 - Specifies the cipher group to assign to this profile.
38 - When the C(ciphers) parameter is in use, the C(cipher_group) must be set to either C(none) or C('').
39 - When creating a new profile with C(cipher_group), if the parent profile has C(ciphers) set by default,
40 the C(cipher) parameter must be set to C(none) or C('') during creation.
41 - The parameter only works on TMOS version 13.x and later.
42 type: str
43 version_added: "1.12.0"
44 renegotiation:
45 description:
46 - Enables or disables SSL renegotiation.
47 - When creating a new profile, the setting is provided by the parent profile.
48 type: bool
49 secure_renegotiation:
50 description:
51 - Specifies the method of secure renegotiations for SSL connections. When
52 creating a new profile, the setting is provided by the parent profile.
53 - When C(request) is set, the system requests secure renegotiation of SSL
54 connections.
55 - C(require) is a default setting and when set, the system permits initial SSL
56 handshakes from clients but terminates renegotiations from unpatched clients.
57 - With the C(require-strict) setting, the system requires strict renegotiation of SSL
58 connections. In this mode the system refuses connections to insecure servers,
59 and terminates existing SSL connections to insecure servers.
60 type: str
61 choices:
62 - require
63 - require-strict
64 - request
65 server_name:
66 description:
67 - Specifies the fully qualified DNS hostname of the server used in Server Name
68 Indication communications. When creating a new profile, the setting is provided
69 by the parent profile.
70 type: str
71 sni_default:
72 description:
73 - Indicates the system uses this profile as the default SSL profile when there
74 is no match to the server name, or when the client provides no SNI extension support.
75 - When creating a new profile, the setting is provided by the parent profile.
76 - There can be only one SSL profile with this setting enabled.
77 type: bool
78 sni_require:
79 description:
80 - Requires the network peers also provide SNI support. This setting only takes
81 effect when C(sni_default) is C(true).
82 - When creating a new profile, the setting is provided by the parent profile.
83 type: bool
84 server_certificate:
85 description:
86 - Specifies the way the system handles server certificates.
87 - When C(ignore), specifies the system ignores certificates from server systems.
88 - When C(require), specifies the system requires a server to present a valid
89 certificate.
90 type: str
91 choices:
92 - ignore
93 - require
94 certificate:
95 description:
96 - Specifies the name of the certificate the system uses for server-side SSL
97 processing.
98 type: str
99 key:
100 description:
101 - Specifies the file name of the SSL key.
102 type: str
103 chain:
104 description:
105 - Specifies the certificates-key chain to associate with the SSL profile.
106 type: str
107 authenticate_name:
108 description:
109 - Specifies a Common Name (CN) that is embedded in a server certificate.
110 The system authenticates a server based on the specified CN.
111 type: str
112 ca_file:
113 description:
114 - Specifies a server CA the system trusts.
115 The default is (None).
116 type: str
117 options:
118 description:
119 - Options the system uses for SSL processing in the form of a list. When
120 creating a new profile, the list is provided by the parent profile.
121 - When C('') or C(none), all options for SSL processing are disabled.
122 type: list
123 elements: str
124 choices:
125 - dont-insert-empty-fragments
126 - no-ssl
127 - no-dtls
128 - no-session-resumption-on-renegotiation
129 - no-tlsv1.1
130 - no-tlsv1.2
131 - no-tlsv1.3
132 - single-dh-use
133 - tls-rollback-bug
134 - no-sslv3
135 - no-tls
136 - no-tlsv1
137 - "none"
138 passphrase:
139 description:
140 - Specifies a passphrase used to encrypt the key.
141 type: str
142 update_password:
143 description:
144 - C(always) allows users to update passwords if they choose to do so.
145 C(on_create) only sets the password for newly created profiles.
146 type: str
147 choices:
148 - always
149 - on_create
150 default: always
151 ocsp_profile:
152 description:
153 - Specifies the name of the OCSP profile for purpose of validating the status
154 of server certificate.
155 type: str
156 partition:
157 description:
158 - Device partition to manage resources on.
159 type: str
160 default: Common
161 state:
162 description:
163 - When C(present), ensures the profile exists.
164 - When C(absent), ensures the profile is removed.
165 type: str
166 choices:
167 - present
168 - absent
169 default: present
170 extends_documentation_fragment: f5networks.f5_modules.f5
171 author:
172 - Tim Rupp (@caphrim007)
173 '''
174
175 EXAMPLES = r'''
176 - name: Create a new server SSL profile
177 bigip_profile_server_ssl:
178 name: foo
179 provider:
180 password: secret
181 server: lb.mydomain.com
182 user: admin
183 delegate_to: localhost
184
185 - name: Create server SSL profile with specific cipher group
186 bigip_profile_server_ssl:
187 state: present
188 name: foo_group
189 ciphers: "none"
190 cipher_group: "/Common/f5-secure"
191 provider:
192 server: lb.mydomain.com
193 user: admin
194 password: secret
195 delegate_to: localhost
196 '''
197
198 RETURN = r'''
199 ciphers:
200 description: The ciphers applied to the profile.
201 returned: changed
202 type: str
203 sample: "!SSLv3:!SSLv2:ECDHE+AES-GCM+SHA256:ECDHE-RSA-AES128-CBC-SHA"
204 cipher_group:
205 description: The cipher group applied to the profile.
206 returned: changed
207 type: str
208 sample: "/Common/f5-secure"
209 secure_renegotiation:
210 description: The method of secure SSL renegotiation.
211 returned: changed
212 type: str
213 sample: request
214 renegotiation:
215 description: Renegotiation of SSL sessions.
216 returned: changed
217 type: bool
218 sample: true
219 options:
220 description: The list of options for SSL processing.
221 returned: changed
222 type: list
223 sample: ['no-ssl', 'no-sslv3']
224 '''
225 from datetime import datetime
226
227 from ansible.module_utils.basic import (
228 AnsibleModule, env_fallback
229 )
230
231 from ..module_utils.bigip import F5RestClient
232 from ..module_utils.common import (
233 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean, fq_name, is_empty_list
234 )
235 from ..module_utils.icontrol import tmos_version
236 from ..module_utils.teem import send_teem
237
238
239 class Parameters(AnsibleF5Parameters):
240 api_map = {
241 'cert': 'certificate',
242 'cipherGroup': 'cipher_group',
243 'ocsp': 'ocsp_profile',
244 'defaultsFrom': 'parent',
245 'secureRenegotiation': 'secure_renegotiation',
246 'sniDefault': 'sni_default',
247 'sniRequire': 'sni_require',
248 'serverName': 'server_name',
249 'peerCertMode': 'server_certificate',
250 'caFile': 'ca_file',
251 'authenticateName': 'authenticate_name',
252 'tmOptions': 'options',
253 }
254
255 api_attributes = [
256 'cert',
257 'chain',
258 'ciphers',
259 'cipherGroup',
260 'defaultsFrom',
261 'key',
262 'ocsp',
263 'secureRenegotiation',
264 'sniDefault',
265 'sniRequire',
266 'serverName',
267 'peerCertMode',
268 'renegotiation',
269 'caFile',
270 'authenticateName',
271 'tmOptions',
272 'passphrase'
273 ]
274
275 returnables = [
276 'certificate',
277 'chain',
278 'ciphers',
279 'cipher_group',
280 'key',
281 'ocsp_profile',
282 'secure_renegotiation',
283 'parent',
284 'sni_default',
285 'sni_require',
286 'server_name',
287 'server_certificate',
288 'renegotiation',
289 'ca_file',
290 'authenticate_name',
291 'options',
292 ]
293
294 updatables = [
295 'certificate',
296 'chain',
297 'ciphers',
298 'cipher_group',
299 'key',
300 'ocsp_profile',
301 'secure_renegotiation',
302 'sni_default',
303 'sni_require',
304 'server_name',
305 'server_certificate',
306 'renegotiation',
307 'parent',
308 'ca_file',
309 'authenticate_name',
310 'options',
311 ]
312
313 @property
314 def sni_default(self):
315 return flatten_boolean(self._values['sni_default'])
316
317 @property
318 def certificate(self):
319 if self._values['certificate'] is None:
320 return None
321 if self._values['certificate'] in ['', 'none']:
322 return ''
323 result = fq_name(self.partition, self._values['certificate'])
324 return result
325
326 @property
327 def key(self):
328 if self._values['key'] is None:
329 return None
330 if self._values['key'] in ['', 'none']:
331 return ''
332 result = fq_name(self.partition, self._values['key'])
333 return result
334
335 @property
336 def chain(self):
337 if self._values['chain'] is None:
338 return None
339 if self._values['chain'] in ['', 'none']:
340 return ''
341 result = fq_name(self.partition, self._values['chain'])
342 return result
343
344 @property
345 def ocsp_profile(self):
346 if self._values['ocsp_profile'] is None:
347 return None
348 if self._values['ocsp_profile'] in ['', 'none']:
349 return ''
350 result = fq_name(self.partition, self._values['ocsp_profile'])
351 return result
352
353 @property
354 def ca_file(self):
355 if self._values['ca_file'] is None:
356 return None
357 if self._values['ca_file'] in ['', 'none']:
358 return ''
359 result = fq_name(self.partition, self._values['ca_file'])
360 return result
361
362
363 class ApiParameters(Parameters):
364 @property
365 def sni_require(self):
366 return flatten_boolean(self._values['sni_require'])
367
368 @property
369 def server_name(self):
370 if self._values['server_name'] in [None, 'none']:
371 return None
372 return self._values['server_name']
373
374
375 class ModuleParameters(Parameters):
376 @property
377 def server_name(self):
378 if self._values['server_name'] is None:
379 return None
380 if self._values['server_name'] in ['', 'none']:
381 return ''
382 return self._values['server_name']
383
384 @property
385 def parent(self):
386 parent = self._values.get("parent")
387 if parent in [None, "", "None"]:
388 return None
389 if parent == "serverssl":
390 return "/Common/serverssl"
391 result = fq_name(self.partition, self._values['parent'])
392 return result
393
394 @property
395 def renegotiation(self):
396 result = flatten_boolean(self._values['renegotiation'])
397 if result is None:
398 return None
399 if result == 'yes':
400 return 'enabled'
401 return 'disabled'
402
403 @property
404 def sni_require(self):
405 require = flatten_boolean(self._values['sni_require'])
406 default = self.sni_default
407 if require is None:
408 return None
409 if default in [None, 'no']:
410 if require == 'yes':
411 raise F5ModuleError(
412 "Cannot set 'sni_require' to {0} if 'sni_default' is set as {1}".format(require, default))
413 return require
414
415 @property
416 def ciphers(self):
417 if self._values['ciphers'] is None:
418 return None
419 if self._values['ciphers'] in ['', 'none']:
420 return 'none'
421 if self.cipher_group and self.cipher_group != 'none':
422 raise F5ModuleError("The cipher parameter must be set to 'none' if cipher_group is defined.")
423 return self._values['ciphers']
424
425 @property
426 def cipher_group(self):
427 if self._values['cipher_group'] is None:
428 return None
429 if self._values['cipher_group'] in ['', 'none']:
430 return 'none'
431 if self.ciphers and self.ciphers != 'none':
432 raise F5ModuleError("The cipher_group parameter must be set to 'none' if cipher is defined.")
433 result = fq_name(self.partition, self._values['cipher_group'])
434 return result
435
436 @property
437 def options(self):
438 options = self._values['options']
439 if options is None:
440 return None
441 if is_empty_list(options):
442 return []
443 return options
444
445 @property
446 def passphrase(self):
447 if self._values['passphrase'] is None:
448 return None
449 if self._values['passphrase'] in ['', 'none']:
450 return ''
451 return self._values['passphrase']
452
453
454 class Changes(Parameters):
455 def to_return(self):
456 result = {}
457 try:
458 for returnable in self.returnables:
459 result[returnable] = getattr(self, returnable)
460 result = self._filter_params(result)
461 except Exception:
462 pass
463 return result
464
465
466 class UsableChanges(Changes):
467 @property
468 def sni_default(self):
469 if self._values['sni_default'] is None:
470 return None
471 elif self._values['sni_default'] == 'yes':
472 return 'true'
473 else:
474 return 'false'
475
476 @property
477 def sni_require(self):
478 if self._values['sni_require'] is None:
479 return None
480 elif self._values['sni_require'] == 'yes':
481 return 'true'
482 else:
483 return 'false'
484
485
486 class ReportableChanges(Changes):
487 @property
488 def sni_default(self):
489 result = flatten_boolean(self._values['sni_default'])
490 return result
491
492 @property
493 def sni_require(self):
494 result = flatten_boolean(self._values['sni_require'])
495 return result
496
497
498 class Difference(object):
499 def __init__(self, want, have=None):
500 self.want = want
501 self.have = have
502
503 def compare(self, param):
504 try:
505 result = getattr(self, param)
506 return result
507 except AttributeError:
508 return self.__default(param)
509
510 def __default(self, param):
511 attr1 = getattr(self.want, param)
512 try:
513 attr2 = getattr(self.have, param)
514 if attr1 != attr2:
515 return attr1
516 except AttributeError:
517 return attr1
518
519 @property
520 def sni_require(self):
521 if self.want.sni_require is None:
522 return None
523 if self.want.sni_require == 'no':
524 if self.have.sni_default == 'yes' and self.want.sni_default is None:
525 raise F5ModuleError(
526 "Cannot set 'sni_require' to {0} if 'sni_default' is {1}".format(
527 self.want.sni_require, self.have.sni_default
528 )
529 )
530 if self.want.sni_require != self.have.sni_require:
531 return self.want.sni_require
532
533 @property
534 def server_name(self):
535 if self.want.server_name is None:
536 return None
537 if self.want.server_name == '' and self.have.server_name is None:
538 return None
539 if self.want.server_name != self.have.server_name:
540 return self.want.server_name
541
542 @property
543 def cipher_group(self):
544 if self.want.cipher_group is None:
545 return None
546 if self.want.cipher_group == 'none' and self.have.cipher_group == 'none':
547 return None
548 if self.want.cipher_group != self.have.cipher_group:
549 return self.want.cipher_group
550
551 @property
552 def options(self):
553 if self.want.options is None:
554 return None
555 # starting with v14 options may return as a space delimited string in curly
556 # braces, eg "{ option1 option2 }", or simply "none" to indicate empty set
557 if self.have.options is None or self.have.options == 'none':
558 self.have.options = []
559 if not isinstance(self.have.options, list):
560 if self.have.options.startswith('{'):
561 self.have.options = self.have.options[2:-2].split(' ')
562 else:
563 self.have.options = [self.have.options]
564 if not self.want.options:
565 # we don't want options. If we have any, indicate we should remove, else noop
566 return [] if self.have.options else None
567 if not self.have.options:
568 return self.want.options
569 if set(self.want.options) != set(self.have.options):
570 return self.want.options
571
572
573 class ModuleManager(object):
574 def __init__(self, *args, **kwargs):
575 self.module = kwargs.get('module', None)
576 self.client = F5RestClient(**self.module.params)
577 self.want = ModuleParameters(params=self.module.params)
578 self.have = ApiParameters()
579 self.changes = UsableChanges()
580
581 def _set_changed_options(self):
582 changed = {}
583 for key in Parameters.returnables:
584 if getattr(self.want, key) is not None:
585 changed[key] = getattr(self.want, key)
586 if changed:
587 self.changes = UsableChanges(params=changed)
588
589 def _update_changed_options(self):
590 diff = Difference(self.want, self.have)
591 updatables = Parameters.updatables
592 changed = dict()
593 for k in updatables:
594 change = diff.compare(k)
595 if change is None:
596 continue
597 else:
598 if isinstance(change, dict):
599 changed.update(change)
600 else:
601 changed[k] = change
602 if changed:
603 self.changes = UsableChanges(params=changed)
604 return True
605 return False
606
607 def should_update(self):
608 result = self._update_changed_options()
609 if result:
610 return True
611 return False
612
613 def exec_module(self):
614 start = datetime.now().isoformat()
615 version = tmos_version(self.client)
616 changed = False
617 result = dict()
618 state = self.want.state
619
620 if state == "present":
621 changed = self.present()
622 elif state == "absent":
623 changed = self.absent()
624
625 reportable = ReportableChanges(params=self.changes.to_return())
626 changes = reportable.to_return()
627 result.update(**changes)
628 result.update(dict(changed=changed))
629 self._announce_deprecations(result)
630 send_teem(start, self.client, self.module, version)
631 return result
632
633 def _announce_deprecations(self, result):
634 warnings = result.pop('__warnings', [])
635 for warning in warnings:
636 self.client.module.deprecate(
637 msg=warning['msg'],
638 version=warning['version']
639 )
640
641 def present(self):
642 if self.exists():
643 return self.update()
644 else:
645 return self.create()
646
647 def exists(self):
648 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/server-ssl/{2}".format(
649 self.client.provider['server'],
650 self.client.provider['server_port'],
651 transform_name(self.want.partition, self.want.name)
652 )
653 resp = self.client.api.get(uri)
654 try:
655 response = resp.json()
656 except ValueError as ex:
657 raise F5ModuleError(str(ex))
658
659 if resp.status == 404 or 'code' in response and response['code'] == 404:
660 return False
661 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
662 return True
663
664 errors = [401, 403, 409, 500, 501, 502, 503, 504]
665
666 if resp.status in errors or 'code' in response and response['code'] in errors:
667 if 'message' in response:
668 raise F5ModuleError(response['message'])
669 else:
670 raise F5ModuleError(resp.content)
671
672 def update(self):
673 self.have = self.read_current_from_device()
674
675 if self.want.update_password == 'always':
676 self.want.update({'passphrase': self.want.passphrase})
677 else:
678 if self.want.passphrase:
679 del self.want._values['passphrase']
680
681 if not self.should_update():
682 return False
683
684 if self.module.check_mode:
685 return True
686 self.update_on_device()
687 return True
688
689 def remove(self):
690 if self.module.check_mode:
691 return True
692 self.remove_from_device()
693 if self.exists():
694 raise F5ModuleError("Failed to delete the resource.")
695 return True
696
697 def create(self):
698 self._set_changed_options()
699 if self.module.check_mode:
700 return True
701 self.create_on_device()
702 return True
703
704 def create_on_device(self):
705 params = self.changes.api_params()
706 params['name'] = self.want.name
707 params['partition'] = self.want.partition
708 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/server-ssl/".format(
709 self.client.provider['server'],
710 self.client.provider['server_port']
711 )
712 params['passphrase'] = self.want.passphrase
713 resp = self.client.api.post(uri, json=params)
714 try:
715 response = resp.json()
716 except ValueError as ex:
717 raise F5ModuleError(str(ex))
718
719 if 'code' in response and response['code'] in [400, 403, 404]:
720 if 'message' in response:
721 raise F5ModuleError(response['message'])
722 else:
723 raise F5ModuleError(resp.content)
724
725 def update_on_device(self):
726 params = self.changes.api_params()
727 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/server-ssl/{2}".format(
728 self.client.provider['server'],
729 self.client.provider['server_port'],
730 transform_name(self.want.partition, self.want.name)
731 )
732 resp = self.client.api.patch(uri, json=params)
733 try:
734 response = resp.json()
735 except ValueError as ex:
736 raise F5ModuleError(str(ex))
737
738 if 'code' in response and response['code'] in [400, 404]:
739 if 'message' in response:
740 raise F5ModuleError(response['message'])
741 else:
742 raise F5ModuleError(resp.content)
743
744 def absent(self):
745 if self.exists():
746 return self.remove()
747 return False
748
749 def remove_from_device(self):
750 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/server-ssl/{2}".format(
751 self.client.provider['server'],
752 self.client.provider['server_port'],
753 transform_name(self.want.partition, self.want.name)
754 )
755 response = self.client.api.delete(uri)
756 if response.status == 200:
757 return True
758 raise F5ModuleError(response.content)
759
760 def read_current_from_device(self):
761 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/server-ssl/{2}".format(
762 self.client.provider['server'],
763 self.client.provider['server_port'],
764 transform_name(self.want.partition, self.want.name)
765 )
766 resp = self.client.api.get(uri)
767 try:
768 response = resp.json()
769 except ValueError as ex:
770 raise F5ModuleError(str(ex))
771
772 if 'code' in response and response['code'] == 400:
773 if 'message' in response:
774 raise F5ModuleError(response['message'])
775 else:
776 raise F5ModuleError(resp.content)
777 return ApiParameters(params=response)
778
779
780 class ArgumentSpec(object):
781 def __init__(self):
782 self.supports_check_mode = True
783 argument_spec = dict(
784 name=dict(required=True),
785 certificate=dict(),
786 chain=dict(),
787 key=dict(no_log=True),
788 passphrase=dict(no_log=True),
789 parent=dict(type='raw', default='/Common/serverssl'),
790 ciphers=dict(),
791 cipher_group=dict(),
792 authenticate_name=dict(),
793 ca_file=dict(),
794 options=dict(
795 type='list',
796 elements='str',
797 choices=[
798 'dont-insert-empty-fragments',
799 'no-ssl',
800 'no-dtls',
801 'no-session-resumption-on-renegotiation',
802 'no-tlsv1.1',
803 'no-tlsv1.2',
804 'no-tlsv1.3',
805 'single-dh-use',
806 'tls-rollback-bug',
807 'no-sslv3',
808 'no-tls',
809 'no-tlsv1',
810 'none',
811 ]
812 ),
813 secure_renegotiation=dict(
814 choices=['require', 'require-strict', 'request']
815 ),
816 server_certificate=dict(
817 choices=['ignore', 'require']
818 ),
819 state=dict(
820 default='present',
821 choices=['present', 'absent']
822 ),
823 update_password=dict(
824 default='always',
825 choices=['always', 'on_create'],
826 no_log=False
827 ),
828 sni_default=dict(type='bool'),
829 sni_require=dict(type='bool'),
830 server_name=dict(),
831 ocsp_profile=dict(),
832 renegotiation=dict(type='bool'),
833 partition=dict(
834 default='Common',
835 fallback=(env_fallback, ['F5_PARTITION'])
836 )
837 )
838 self.argument_spec = {}
839 self.argument_spec.update(f5_argument_spec)
840 self.argument_spec.update(argument_spec)
841 self.required_together = [
842 ['certificate', 'key']
843 ]
844
845
846 def main():
847 spec = ArgumentSpec()
848
849 module = AnsibleModule(
850 argument_spec=spec.argument_spec,
851 supports_check_mode=spec.supports_check_mode,
852 required_together=spec.required_together,
853 )
854
855 try:
856 mm = ModuleManager(module=module)
857 results = mm.exec_module()
858 module.exit_json(**results)
859 except F5ModuleError as ex:
860 module.fail_json(msg=str(ex))
861
862
863 if __name__ == '__main__':
864 main()