Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2017, 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_client_ssl
13 short_description: Manages client SSL profiles on a BIG-IP
14 description:
15 - Manages client SSL profiles on a BIG-IP device.
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. By default, this value is the C(clientssl)
27 parent on the C(Common) partition.
28 type: str
29 ciphers:
30 description:
31 - Specifies the list of ciphers the system supports.
32 - When the C(cipher_group) parameter is in use, the C(ciphers) parameter needs to be set to either C(none) or C('').
33 type: str
34 cipher_group:
35 description:
36 - Specifies the cipher group to assign to this profile.
37 - When the C(ciphers) parameter is in use, the C(cipher_group) must be set to either C(none) or C('').
38 - When creating a new profile with C(cipher_group), if the parent profile has C(ciphers) set by default,
39 the C(cipher) parameter must be set to C(none) or C('') during creation.
40 - The parameter only works on TMOS version 13.x and later.
41 type: str
42 version_added: "1.2.0"
43 cert_key_chain:
44 description:
45 - One or more certificates and keys to associate with the SSL profile. This
46 option is always a list. The keys in the list dictate the details of the
47 client/key/chain combination. Note that BIG-IPs can only have one of each
48 type of each certificate/key type. This means you can only have one
49 RSA, one DSA, and one ECDSA per profile. If you attempt to assign two
50 RSA, DSA, or ECDSA certificate/key combo, the device rejects it.
51 - This list is a complex list that specifies a number of keys.
52 type: list
53 elements: dict
54 suboptions:
55 cert:
56 description:
57 - Specifies a certificate name for use.
58 type: str
59 required: True
60 key:
61 description:
62 - Contains a key name.
63 type: str
64 required: True
65 chain:
66 description:
67 - Contains a certificate chain relevant to the certificate and key
68 mentioned previously.
69 - This key is optional.
70 type: str
71 passphrase:
72 description:
73 - Contains the passphrase of the key file, if required.
74 - Passphrases are encrypted on the remote BIG-IP device. Therefore, there is no way
75 to compare them when updating a client SSL profile. Due to this, if you specify a
76 passphrase, this module will always register a C(changed) event.
77 type: str
78 true_names:
79 description:
80 - When C(true), the module does not append C(.crt) and C(.key) extensions to the given certificate and key names.
81 - When C(false), the module appends C(.crt) and C(.key) extensions to the given certificate and key names.
82 type: bool
83 default: false
84 version_added: "1.1.0"
85 partition:
86 description:
87 - Device partition to manage resources on.
88 type: str
89 default: Common
90 options:
91 description:
92 - Options the system uses for SSL processing in the form of a list. When
93 creating a new profile, the list is provided by the parent profile.
94 - When C('') or C(none), all options for SSL processing are disabled.
95 type: list
96 elements: str
97 choices:
98 - netscape-reuse-cipher-change-bug
99 - microsoft-big-sslv3-buffer
100 - msie-sslv2-rsa-padding
101 - ssleay-080-client-dh-bug
102 - tls-d5-bug
103 - tls-block-padding-bug
104 - dont-insert-empty-fragments
105 - no-ssl
106 - no-dtls
107 - no-session-resumption-on-renegotiation
108 - no-tlsv1.1
109 - no-tlsv1.2
110 - no-tlsv1.3
111 - single-dh-use
112 - ephemeral-rsa
113 - cipher-server-preference
114 - tls-rollback-bug
115 - no-sslv2
116 - no-sslv3
117 - no-tls
118 - no-tlsv1
119 - pkcs1-check-1
120 - pkcs1-check-2
121 - netscape-ca-dn-bug
122 - netscape-demo-cipher-change-bug
123 - "none"
124 secure_renegotiation:
125 description:
126 - Specifies the method of secure renegotiations for SSL connections. When
127 creating a new profile, the setting is provided by the parent profile.
128 - When C(request), the system requests secure renegotiation of SSL
129 connections.
130 - C(require) is a default setting and when set, the system permits initial SSL
131 handshakes from clients, but terminates renegotiations from unpatched clients.
132 - With the C(require-strict) setting, the system requires strict renegotiation of SSL
133 connections. In this mode, the system refuses connections to insecure servers,
134 and terminates existing SSL connections to insecure servers.
135 type: str
136 choices:
137 - require
138 - require-strict
139 - request
140 allow_non_ssl:
141 description:
142 - Enables or disables acceptance of non-SSL connections.
143 - When creating a new profile, the setting is provided by the parent profile.
144 type: bool
145 server_name:
146 description:
147 - Specifies the fully qualified DNS hostname of the server used in Server Name Indication communications.
148 When creating a new profile, the setting is provided by the parent profile.
149 - The server name can also be a wildcard string containing the asterisk C(*) character.
150 type: str
151 sni_default:
152 description:
153 - Indicates the system uses this profile as the default SSL profile when there is no match to the
154 server name, or when the client provides no SNI extension support.
155 - When creating a new profile, the setting is provided by the parent profile.
156 - There can be only one SSL profile with this setting enabled.
157 type: bool
158 sni_require:
159 description:
160 - Requires the network peers also provide SNI support. This setting only takes effect when C(sni_default) is
161 set to C(true).
162 - When creating a new profile, the setting is provided by the parent profile.
163 type: bool
164 strict_resume:
165 description:
166 - Enables or disables the resumption of SSL sessions after an unclean shutdown.
167 - When creating a new profile, the setting is provided by the parent profile.
168 type: bool
169 client_certificate:
170 description:
171 - Specifies the way the system handles client certificates.
172 - When C(ignore), specifies the system ignores certificates from client
173 systems.
174 - When C(require), specifies the system requires a client to present a
175 valid certificate.
176 - When C(request), specifies the system requests a valid certificate from a
177 client but always authenticate the client.
178 type: str
179 choices:
180 - ignore
181 - require
182 - request
183 client_auth_frequency:
184 description:
185 - Specifies the frequency of client authentication for an SSL session.
186 - When C(once), specifies the system authenticates the client once for an
187 SSL session.
188 - When C(always), specifies the system authenticates the client once for an
189 SSL session and also upon reuse of that session.
190 type: str
191 choices:
192 - once
193 - always
194 renegotiation:
195 description:
196 - Enables or disables SSL renegotiation.
197 - When creating a new profile, the setting is provided by the parent profile.
198 type: bool
199 retain_certificate:
200 description:
201 - When C(true), the client certificate is retained in SSL session.
202 type: bool
203 cert_auth_depth:
204 description:
205 - Specifies the maximum number of certificates to be traversed in a client
206 certificate chain.
207 type: int
208 trusted_cert_authority:
209 description:
210 - Specifies a client CA the system trusts.
211 type: str
212 advertised_cert_authority:
213 description:
214 - Specifies the CAs the system advertises to clients is being trusted
215 by the profile.
216 type: str
217 client_auth_crl:
218 description:
219 - Specifies the name of a file containing a list of revoked client certificates.
220 type: str
221 allow_expired_crl:
222 description:
223 - Instructs the system to use the specified CRL file even if it has expired.
224 type: bool
225 cache_size:
226 description:
227 - Specifies the number of sessions in the SSL session cache.
228 - The valid value range is between 0 and 4194304 inclusive.
229 - When creating a new profile, if this parameter is not specified, the default is provided
230 by the parent profile.
231 type: int
232 version_added: "1.0.0"
233 cache_timeout:
234 description:
235 - Specifies the timeout value in seconds of the SSL session cache entries.
236 - Acceptable values are between 0 and 86400 inclusive.
237 - When creating a new profile, if this parameter is not specified, the default is provided
238 by the parent profile.
239 type: int
240 version_added: "1.0.0"
241 state:
242 description:
243 - When C(present), ensures the profile exists.
244 - When C(absent), ensures the profile is removed.
245 type: str
246 choices:
247 - present
248 - absent
249 default: present
250 notes:
251 - Requires BIG-IP software version >= 12
252 extends_documentation_fragment: f5networks.f5_modules.f5
253 author:
254 - Tim Rupp (@caphrim007)
255 - Wojciech Wypior (@wojtek0806)
256 '''
257
258 EXAMPLES = r'''
259 - name: Create client SSL profile
260 bigip_profile_client_ssl:
261 state: present
262 name: my_profile
263 provider:
264 server: lb.mydomain.com
265 user: admin
266 password: secret
267 delegate_to: localhost
268
269 - name: Create client SSL profile with specific ciphers
270 bigip_profile_client_ssl:
271 state: present
272 name: my_profile
273 ciphers: "!SSLv3:!SSLv2:ECDHE+AES-GCM+SHA256:ECDHE-RSA-AES128-CBC-SHA"
274 provider:
275 server: lb.mydomain.com
276 user: admin
277 password: secret
278 delegate_to: localhost
279
280 - name: Create client SSL profile with specific cipher group
281 bigip_profile_client_ssl:
282 state: present
283 name: my_profile
284 ciphers: "none"
285 cipher_group: "/Common/f5-secure"
286 provider:
287 server: lb.mydomain.com
288 user: admin
289 password: secret
290 delegate_to: localhost
291
292 - name: Create client SSL profile with specific SSL options
293 bigip_profile_client_ssl:
294 state: present
295 name: my_profile
296 options:
297 - no-sslv2
298 - no-sslv3
299 provider:
300 server: lb.mydomain.com
301 user: admin
302 password: secret
303 delegate_to: localhost
304
305 - name: Create client SSL profile require secure renegotiation
306 bigip_profile_client_ssl:
307 state: present
308 name: my_profile
309 secure_renegotiation: request
310 provider:
311 server: lb.mydomain.com
312 user: admin
313 password: secret
314 delegate_to: localhost
315
316 - name: Create a client SSL profile with a cert/key/chain setting
317 bigip_profile_client_ssl:
318 state: present
319 name: my_profile
320 cert_key_chain:
321 - cert: bigip_ssl_cert1
322 key: bigip_ssl_key1
323 chain: bigip_ssl_cert1
324 provider:
325 server: lb.mydomain.com
326 user: admin
327 password: secret
328 delegate_to: localhost
329 '''
330
331 RETURN = r'''
332 ciphers:
333 description: The ciphers applied to the profile.
334 returned: changed
335 type: str
336 sample: "!SSLv3:!SSLv2:ECDHE+AES-GCM+SHA256:ECDHE-RSA-AES128-CBC-SHA"
337 cipher_group:
338 description: The cipher group applied to the profile.
339 returned: changed
340 type: str
341 sample: "/Common/f5-secure"
342 options:
343 description: The list of options for SSL processing.
344 returned: changed
345 type: list
346 sample: ['no-sslv2', 'no-sslv3']
347 secure_renegotiation:
348 description: The method of secure SSL renegotiation.
349 returned: changed
350 type: str
351 sample: request
352 allow_non_ssl:
353 description: Acceptance of non-SSL connections.
354 returned: changed
355 type: bool
356 sample: true
357 strict_resume:
358 description: Resumption of SSL sessions after an unclean shutdown.
359 returned: changed
360 type: bool
361 sample: true
362 renegotiation:
363 description: Renegotiation of SSL sessions.
364 returned: changed
365 type: bool
366 sample: true
367 cache_size:
368 description: Specifies the number of sessions in the SSL session cache.
369 returned: changed
370 type: int
371 sample: 2000
372 cache_timeout:
373 description: Specifies the timeout value in seconds of the SSL session cache entries.
374 returned: changed
375 type: int
376 sample: 1800
377 '''
378
379 import os
380 from datetime import datetime
381
382 from ansible.module_utils.basic import (
383 AnsibleModule, env_fallback
384 )
385 from ansible.module_utils.six import iteritems
386
387 from ..module_utils.bigip import F5RestClient
388 from ..module_utils.common import (
389 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean, fq_name, is_empty_list
390 )
391 from ..module_utils.icontrol import tmos_version
392 from ..module_utils.teem import send_teem
393
394
395 class Parameters(AnsibleF5Parameters):
396 api_map = {
397 'certKeyChain': 'cert_key_chain',
398 'cipherGroup': 'cipher_group',
399 'defaultsFrom': 'parent',
400 'allowNonSsl': 'allow_non_ssl',
401 'secureRenegotiation': 'secure_renegotiation',
402 'tmOptions': 'options',
403 'sniDefault': 'sni_default',
404 'sniRequire': 'sni_require',
405 'serverName': 'server_name',
406 'peerCertMode': 'client_certificate',
407 'authenticate': 'client_auth_frequency',
408 'retainCertificate': 'retain_certificate',
409 'authenticateDepth': 'cert_auth_depth',
410 'caFile': 'trusted_cert_authority',
411 'clientCertCa': 'advertised_cert_authority',
412 'crlFile': 'client_auth_crl',
413 'allowExpiredCrl': 'allow_expired_crl',
414 'strictResume': 'strict_resume',
415 'cacheSize': 'cache_size',
416 'cacheTimeout': 'cache_timeout',
417 }
418
419 api_attributes = [
420 'ciphers',
421 'cipherGroup',
422 'certKeyChain',
423 'defaultsFrom',
424 'tmOptions',
425 'secureRenegotiation',
426 'allowNonSsl',
427 'sniDefault',
428 'sniRequire',
429 'serverName',
430 'peerCertMode',
431 'authenticate',
432 'retainCertificate',
433 'authenticateDepth',
434 'caFile',
435 'clientCertCa',
436 'crlFile',
437 'allowExpiredCrl',
438 'strictResume',
439 'renegotiation',
440 'cacheSize',
441 'cacheTimeout',
442 ]
443
444 returnables = [
445 'ciphers',
446 'cipher_group',
447 'allow_non_ssl',
448 'options',
449 'secure_renegotiation',
450 'cert_key_chain',
451 'parent',
452 'sni_default',
453 'sni_require',
454 'server_name',
455 'client_certificate',
456 'client_auth_frequency',
457 'retain_certificate',
458 'cert_auth_depth',
459 'trusted_cert_authority',
460 'advertised_cert_authority',
461 'client_auth_crl',
462 'allow_expired_crl',
463 'strict_resume',
464 'renegotiation',
465 'cache_size',
466 'cache_timeout',
467 ]
468
469 updatables = [
470 'parent',
471 'ciphers',
472 'cipher_group',
473 'cert_key_chain',
474 'allow_non_ssl',
475 'options',
476 'secure_renegotiation',
477 'sni_default',
478 'sni_require',
479 'server_name',
480 'client_certificate',
481 'client_auth_frequency',
482 'retain_certificate',
483 'cert_auth_depth',
484 'trusted_cert_authority',
485 'advertised_cert_authority',
486 'client_auth_crl',
487 'allow_expired_crl',
488 'strict_resume',
489 'renegotiation',
490 'cache_size',
491 'cache_timeout',
492 ]
493
494 @property
495 def retain_certificate(self):
496 return flatten_boolean(self._values['retain_certificate'])
497
498 @property
499 def allow_expired_crl(self):
500 return flatten_boolean(self._values['allow_expired_crl'])
501
502
503 class ModuleParameters(Parameters):
504 def _key_filename(self, name, true_name):
505 if true_name:
506 return name
507 if name.endswith('.key'):
508 return name
509 else:
510 return name + '.key'
511
512 def _cert_filename(self, name, true_name):
513 if true_name:
514 return name
515 if name.endswith('.crt'):
516 return name
517 else:
518 return name + '.crt'
519
520 def _get_chain_value(self, item, true_name):
521 if 'chain' not in item or item['chain'] in ('none', None, 'None'):
522 result = 'none'
523 else:
524 result = self._cert_filename(fq_name(self.partition, item['chain']), true_name)
525 return result
526
527 def _get_true_names(self, item):
528 if 'true_names' not in item:
529 return False
530 result = flatten_boolean(item['true_names'])
531 if result == 'yes':
532 return True
533 if result == 'no':
534 return False
535
536 @property
537 def parent(self):
538 if self._values['parent'] is None:
539 return None
540 if self._values['parent'] == 'clientssl':
541 return '/Common/clientssl'
542 result = fq_name(self.partition, self._values['parent'])
543 return result
544
545 @property
546 def cert_key_chain(self):
547 if self._values['cert_key_chain'] is None:
548 return None
549 result = []
550 for item in self._values['cert_key_chain']:
551 if 'key' in item and 'cert' not in item:
552 raise F5ModuleError(
553 "When providing a 'key', you must also provide a 'cert'"
554 )
555 if 'cert' in item and 'key' not in item:
556 raise F5ModuleError(
557 "When providing a 'cert', you must also provide a 'key'"
558 )
559 item['true_names'] = self._get_true_names(item)
560 key = self._key_filename(item['key'], item['true_names'])
561 cert = self._cert_filename(item['cert'], item['true_names'])
562 chain = self._get_chain_value(item, item['true_names'])
563 name = os.path.basename(cert)
564 filename, ex = os.path.splitext(name)
565 tmp = {
566 'name': filename,
567 'cert': fq_name(self.partition, cert),
568 'key': fq_name(self.partition, key),
569 'chain': chain
570 }
571 if 'passphrase' in item and item['passphrase'] not in ('None', None, 'none'):
572 tmp['passphrase'] = item['passphrase']
573 result.append(tmp)
574 result = sorted(result, key=lambda x: x['name'])
575 return result
576
577 @property
578 def allow_non_ssl(self):
579 result = flatten_boolean(self._values['allow_non_ssl'])
580 if result is None:
581 return None
582 if result == 'yes':
583 return 'enabled'
584 return 'disabled'
585
586 @property
587 def strict_resume(self):
588 result = flatten_boolean(self._values['strict_resume'])
589 if result is None:
590 return None
591 if result == 'yes':
592 return 'enabled'
593 return 'disabled'
594
595 @property
596 def renegotiation(self):
597 result = flatten_boolean(self._values['renegotiation'])
598 if result is None:
599 return None
600 if result == 'yes':
601 return 'enabled'
602 return 'disabled'
603
604 @property
605 def options(self):
606 options = self._values['options']
607 if options is None:
608 return None
609 if is_empty_list(options):
610 return []
611 return options
612
613 @property
614 def sni_require(self):
615 require = flatten_boolean(self._values['sni_require'])
616 default = self.sni_default
617 if require is None:
618 return None
619 if default in [None, False]:
620 if require == 'yes':
621 raise F5ModuleError(
622 "Cannot set 'sni_require' to {0} if 'sni_default' is set as {1}".format(require, default))
623 if require == 'yes':
624 return True
625 else:
626 return False
627
628 @property
629 def trusted_cert_authority(self):
630 if self._values['trusted_cert_authority'] is None:
631 return None
632 if self._values['trusted_cert_authority'] in ['', 'none']:
633 return ''
634 result = fq_name(self.partition, self._values['trusted_cert_authority'])
635 return result
636
637 @property
638 def advertised_cert_authority(self):
639 if self._values['advertised_cert_authority'] is None:
640 return None
641 if self._values['advertised_cert_authority'] in ['', 'none']:
642 return ''
643 result = fq_name(self.partition, self._values['advertised_cert_authority'])
644 return result
645
646 @property
647 def client_auth_crl(self):
648 if self._values['client_auth_crl'] is None:
649 return None
650 if self._values['client_auth_crl'] in ['', 'none']:
651 return ''
652 result = fq_name(self.partition, self._values['client_auth_crl'])
653 return result
654
655 @property
656 def ciphers(self):
657 if self._values['ciphers'] is None:
658 return None
659 if self._values['ciphers'] in ['', 'none']:
660 return 'none'
661 if self.cipher_group and self.cipher_group != 'none':
662 raise F5ModuleError("The cipher parameter must be set to 'none' if cipher_group is defined.")
663 return self._values['ciphers']
664
665 @property
666 def cipher_group(self):
667 if self._values['cipher_group'] is None:
668 return None
669 if self._values['cipher_group'] in ['', 'none']:
670 return 'none'
671 if self.ciphers and self.ciphers != 'none':
672 raise F5ModuleError("The cipher_group parameter must be set to 'none' if cipher is defined.")
673 result = fq_name(self.partition, self._values['cipher_group'])
674 return result
675
676
677 class ApiParameters(Parameters):
678 @property
679 def cert_key_chain(self):
680 if self._values['cert_key_chain'] is None:
681 return None
682 result = []
683 for item in self._values['cert_key_chain']:
684 tmp = dict(
685 name=item['name'],
686 )
687 for x in ['cert', 'key', 'chain', 'passphrase', 'true_names']:
688 if x in item:
689 tmp[x] = item[x]
690 if 'chain' not in item:
691 tmp['chain'] = 'none'
692 result.append(tmp)
693 result = sorted(result, key=lambda y: y['name'])
694 return result
695
696 @property
697 def sni_default(self):
698 result = self._values['sni_default']
699 if result is None:
700 return None
701 if result == 'true':
702 return True
703 else:
704 return False
705
706 @property
707 def sni_require(self):
708 result = self._values['sni_require']
709 if result is None:
710 return None
711 if result == 'true':
712 return True
713 else:
714 return False
715
716 @property
717 def trusted_cert_authority(self):
718 if self._values['trusted_cert_authority'] in [None, 'none']:
719 return None
720 return self._values['trusted_cert_authority']
721
722 @property
723 def advertised_cert_authority(self):
724 if self._values['advertised_cert_authority'] in [None, 'none']:
725 return None
726 return self._values['advertised_cert_authority']
727
728 @property
729 def client_auth_crl(self):
730 if self._values['client_auth_crl'] in [None, 'none']:
731 return None
732 return self._values['client_auth_crl']
733
734 @property
735 def cache_size(self):
736 if self._values['cache_size'] is None:
737 return None
738 if 0 <= self._values['cache_size'] <= 4194304:
739 return self._values['cache_size']
740 raise F5ModuleError(
741 "Valid 'cache_size' must be in range 0 - 4194304 sessions."
742 )
743
744 @property
745 def cache_timeout(self):
746 if self._values['cache_timeout'] is None:
747 return None
748 if 0 <= self._values['cache_timeout'] <= 4194304:
749 return self._values['cache_timeout']
750 raise F5ModuleError(
751 "Valid 'cache_timeout' must be in range 0 - 86400 seconds."
752 )
753
754
755 class Changes(Parameters):
756 def to_return(self):
757 result = {}
758 try:
759 for returnable in self.returnables:
760 result[returnable] = getattr(self, returnable)
761 result = self._filter_params(result)
762 except Exception:
763 pass
764 return result
765
766
767 class UsableChanges(Changes):
768 @property
769 def retain_certificate(self):
770 if self._values['retain_certificate'] is None:
771 return None
772 elif self._values['retain_certificate'] == 'yes':
773 return 'true'
774 return 'false'
775
776 @property
777 def allow_expired_crl(self):
778 if self._values['allow_expired_crl'] is None:
779 return None
780 elif self._values['allow_expired_crl'] == 'yes':
781 return 'enabled'
782 return 'disabled'
783
784
785 class ReportableChanges(Changes):
786 @property
787 def allow_non_ssl(self):
788 if self._values['allow_non_ssl'] is None:
789 return None
790 elif self._values['allow_non_ssl'] == 'enabled':
791 return 'yes'
792 return 'no'
793
794 @property
795 def strict_resume(self):
796 if self._values['strict_resume'] is None:
797 return None
798 elif self._values['strict_resume'] == 'enabled':
799 return 'yes'
800 return 'no'
801
802 @property
803 def retain_certificate(self):
804 return flatten_boolean(self._values['retain_certificate'])
805
806 @property
807 def allow_expired_crl(self):
808 return flatten_boolean(self._values['allow_expired_crl'])
809
810
811 class Difference(object):
812 def __init__(self, want, have=None):
813 self.want = want
814 self.have = have
815
816 def compare(self, param):
817 try:
818 result = getattr(self, param)
819 return result
820 except AttributeError:
821 result = self.__default(param)
822 return result
823
824 def __default(self, param):
825 attr1 = getattr(self.want, param)
826 try:
827 attr2 = getattr(self.have, param)
828 if attr1 != attr2:
829 return attr1
830 except AttributeError:
831 return attr1
832
833 def to_tuple(self, items):
834 result = []
835 for x in items:
836 tmp = [(str(k), str(v)) for k, v in iteritems(x)]
837 result += tmp
838 return result
839
840 def _diff_complex_items(self, want, have):
841 if want == [] and have is None:
842 return None
843 if want is None:
844 return None
845 w = self.to_tuple(want)
846 h = self.to_tuple(have)
847 if set(w).issubset(set(h)):
848 return None
849 else:
850 return want
851
852 @property
853 def cert_key_chain(self):
854 result = self._diff_complex_items(self.want.cert_key_chain, self.have.cert_key_chain)
855 return result
856
857 @property
858 def options(self):
859 if self.want.options is None:
860 return None
861 # starting with v14 options may return as a space delimited string in curly
862 # braces, eg "{ option1 option2 }", or simply "none" to indicate empty set
863 if self.have.options is None or self.have.options == 'none':
864 self.have.options = []
865 if not isinstance(self.have.options, list):
866 if self.have.options.startswith('{'):
867 self.have.options = self.have.options[2:-2].split(' ')
868 else:
869 self.have.options = [self.have.options]
870 if not self.want.options:
871 # we don't want options. If we have any, indicate we should remove, else noop
872 return [] if self.have.options else None
873 if not self.have.options:
874 return self.want.options
875 if set(self.want.options) != set(self.have.options):
876 return self.want.options
877
878 @property
879 def sni_require(self):
880 if self.want.sni_require is None:
881 return None
882 if self.want.sni_require is False:
883 if self.have.sni_default is True and self.want.sni_default is None:
884 raise F5ModuleError(
885 "Cannot set 'sni_require' to {0} if 'sni_default' is {1}".format(
886 self.want.sni_require, self.have.sni_default)
887 )
888 if self.want.sni_require == self.have.sni_require:
889 return None
890 return self.want.sni_require
891
892 @property
893 def trusted_cert_authority(self):
894 if self.want.trusted_cert_authority is None:
895 return None
896 if self.want.trusted_cert_authority == '' and self.have.trusted_cert_authority is None:
897 return None
898 if self.want.trusted_cert_authority != self.have.trusted_cert_authority:
899 return self.want.trusted_cert_authority
900
901 @property
902 def advertised_cert_authority(self):
903 if self.want.advertised_cert_authority is None:
904 return None
905 if self.want.advertised_cert_authority == '' and self.have.advertised_cert_authority is None:
906 return None
907 if self.want.advertised_cert_authority != self.have.advertised_cert_authority:
908 return self.want.advertised_cert_authority
909
910 @property
911 def client_auth_crl(self):
912 if self.want.client_auth_crl is None:
913 return None
914 if self.want.client_auth_crl == '' and self.have.client_auth_crl is None:
915 return None
916 if self.want.client_auth_crl != self.have.client_auth_crl:
917 return self.want.client_auth_crl
918
919 @property
920 def ciphers(self):
921 if self.want.ciphers is None:
922 return None
923 if self.want.ciphers == 'none' and self.have.ciphers == 'none':
924 return None
925 if self.want.ciphers != self.have.ciphers:
926 return self.want.ciphers
927
928 @property
929 def cipher_group(self):
930 if self.want.cipher_group is None:
931 return None
932 if self.want.cipher_group == 'none' and self.have.cipher_group == 'none':
933 return None
934 if self.want.cipher_group != self.have.cipher_group:
935 return self.want.cipher_group
936
937
938 class ModuleManager(object):
939 def __init__(self, *args, **kwargs):
940 self.module = kwargs.get('module', None)
941 self.client = F5RestClient(**self.module.params)
942 self.want = ModuleParameters(params=self.module.params)
943 self.have = ApiParameters()
944 self.changes = UsableChanges()
945
946 def _set_changed_options(self):
947 changed = {}
948 for key in Parameters.returnables:
949 if getattr(self.want, key) is not None:
950 changed[key] = getattr(self.want, key)
951 if changed:
952 self.changes = UsableChanges(params=changed)
953
954 def _update_changed_options(self):
955 diff = Difference(self.want, self.have)
956 updatables = Parameters.updatables
957 changed = dict()
958 for k in updatables:
959 change = diff.compare(k)
960 if change is None:
961 continue
962 else:
963 if isinstance(change, dict):
964 changed.update(change)
965 else:
966 changed[k] = change
967 if changed:
968 self.changes = UsableChanges(params=changed)
969 return True
970 return False
971
972 def should_update(self):
973 result = self._update_changed_options()
974 if result:
975 return True
976 return False
977
978 def exec_module(self):
979 start = datetime.now().isoformat()
980 version = tmos_version(self.client)
981 changed = False
982 result = dict()
983 state = self.want.state
984
985 if state == "present":
986 changed = self.present()
987 elif state == "absent":
988 changed = self.absent()
989
990 reportable = ReportableChanges(params=self.changes.to_return())
991 changes = reportable.to_return()
992 result.update(**changes)
993 result.update(dict(changed=changed))
994 self._announce_deprecations(result)
995 send_teem(start, self.client, self.module, version)
996 return result
997
998 def _announce_deprecations(self, result):
999 warnings = result.pop('__warnings', [])
1000 for warning in warnings:
1001 self.client.module.deprecate(
1002 msg=warning['msg'],
1003 version=warning['version']
1004 )
1005
1006 def present(self):
1007 if self.exists():
1008 return self.update()
1009 else:
1010 return self.create()
1011
1012 def exists(self):
1013 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/client-ssl/{2}".format(
1014 self.client.provider['server'],
1015 self.client.provider['server_port'],
1016 transform_name(self.want.partition, self.want.name)
1017 )
1018 resp = self.client.api.get(uri)
1019 try:
1020 response = resp.json()
1021 except ValueError as ex:
1022 raise F5ModuleError(str(ex))
1023
1024 if resp.status == 404 or 'code' in response and response['code'] == 404:
1025 return False
1026 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1027 return True
1028
1029 errors = [401, 403, 409, 500, 501, 502, 503, 504]
1030
1031 if resp.status in errors or 'code' in response and response['code'] in errors:
1032 if 'message' in response:
1033 raise F5ModuleError(response['message'])
1034 else:
1035 raise F5ModuleError(resp.content)
1036
1037 def update(self):
1038 self.have = self.read_current_from_device()
1039 if not self.should_update():
1040 return False
1041 if self.module.check_mode:
1042 return True
1043 self.update_on_device()
1044 return True
1045
1046 def remove(self):
1047 if self.module.check_mode:
1048 return True
1049 self.remove_from_device()
1050 if self.exists():
1051 raise F5ModuleError("Failed to delete the resource.")
1052 return True
1053
1054 def create(self):
1055 self._set_changed_options()
1056 if self.module.check_mode:
1057 return True
1058 self.create_on_device()
1059 return True
1060
1061 def create_on_device(self):
1062 params = self.changes.api_params()
1063 params['name'] = self.want.name
1064 params['partition'] = self.want.partition
1065 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/client-ssl/".format(
1066 self.client.provider['server'],
1067 self.client.provider['server_port']
1068 )
1069 resp = self.client.api.post(uri, json=params)
1070 try:
1071 response = resp.json()
1072 except ValueError as ex:
1073 raise F5ModuleError(str(ex))
1074
1075 if 'code' in response and response['code'] in [400, 403, 404]:
1076 if 'message' in response:
1077 raise F5ModuleError(response['message'])
1078 else:
1079 raise F5ModuleError(resp.content)
1080
1081 def update_on_device(self):
1082 params = self.changes.api_params()
1083 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/client-ssl/{2}".format(
1084 self.client.provider['server'],
1085 self.client.provider['server_port'],
1086 transform_name(self.want.partition, self.want.name)
1087 )
1088 resp = self.client.api.patch(uri, json=params)
1089 try:
1090 response = resp.json()
1091 except ValueError as ex:
1092 raise F5ModuleError(str(ex))
1093
1094 if 'code' in response and response['code'] in [400, 404]:
1095 if 'message' in response:
1096 raise F5ModuleError(response['message'])
1097 else:
1098 raise F5ModuleError(resp.content)
1099
1100 def absent(self):
1101 if self.exists():
1102 return self.remove()
1103 return False
1104
1105 def remove_from_device(self):
1106 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/client-ssl/{2}".format(
1107 self.client.provider['server'],
1108 self.client.provider['server_port'],
1109 transform_name(self.want.partition, self.want.name)
1110 )
1111 response = self.client.api.delete(uri)
1112 if response.status == 200:
1113 return True
1114 raise F5ModuleError(response.content)
1115
1116 def read_current_from_device(self):
1117 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/client-ssl/{2}".format(
1118 self.client.provider['server'],
1119 self.client.provider['server_port'],
1120 transform_name(self.want.partition, self.want.name)
1121 )
1122 resp = self.client.api.get(uri)
1123 try:
1124 response = resp.json()
1125 except ValueError as ex:
1126 raise F5ModuleError(str(ex))
1127
1128 if 'code' in response and response['code'] == 400:
1129 if 'message' in response:
1130 raise F5ModuleError(response['message'])
1131 else:
1132 raise F5ModuleError(resp.content)
1133 return ApiParameters(params=response)
1134
1135
1136 class ArgumentSpec(object):
1137 def __init__(self):
1138 self.supports_check_mode = True
1139 argument_spec = dict(
1140 name=dict(required=True),
1141 parent=dict(),
1142 ciphers=dict(),
1143 cipher_group=dict(),
1144 allow_non_ssl=dict(type='bool'),
1145 secure_renegotiation=dict(
1146 choices=['require', 'require-strict', 'request']
1147 ),
1148 options=dict(
1149 type='list',
1150 elements='str',
1151 choices=[
1152 'netscape-reuse-cipher-change-bug',
1153 'microsoft-big-sslv3-buffer',
1154 'msie-sslv2-rsa-padding',
1155 'ssleay-080-client-dh-bug',
1156 'tls-d5-bug',
1157 'tls-block-padding-bug',
1158 'dont-insert-empty-fragments',
1159 'no-ssl',
1160 'no-dtls',
1161 'no-session-resumption-on-renegotiation',
1162 'no-tlsv1.1',
1163 'no-tlsv1.2',
1164 'no-tlsv1.3',
1165 'single-dh-use',
1166 'ephemeral-rsa',
1167 'cipher-server-preference',
1168 'tls-rollback-bug',
1169 'no-sslv2',
1170 'no-sslv3',
1171 'no-tls',
1172 'no-tlsv1',
1173 'pkcs1-check-1',
1174 'pkcs1-check-2',
1175 'netscape-ca-dn-bug',
1176 'netscape-demo-cipher-change-bug',
1177 'none',
1178 ]
1179 ),
1180 cert_key_chain=dict(
1181 type='list',
1182 elements='dict',
1183 no_log=True,
1184 options=dict(
1185 cert=dict(required=True),
1186 key=dict(required=True, no_log=True),
1187 chain=dict(),
1188 passphrase=dict(no_log=True),
1189 true_names=dict(
1190 type='bool',
1191 default='no'
1192 ),
1193 )
1194 ),
1195 state=dict(
1196 default='present',
1197 choices=['present', 'absent']
1198 ),
1199 sni_default=dict(type='bool'),
1200 sni_require=dict(type='bool'),
1201 server_name=dict(),
1202 client_certificate=dict(
1203 choices=['require', 'ignore', 'request']
1204 ),
1205 client_auth_frequency=dict(
1206 choices=['once', 'always']
1207 ),
1208 cert_auth_depth=dict(type='int'),
1209 retain_certificate=dict(type='bool'),
1210 trusted_cert_authority=dict(),
1211 advertised_cert_authority=dict(),
1212 client_auth_crl=dict(),
1213 allow_expired_crl=dict(type='bool'),
1214 strict_resume=dict(type='bool'),
1215 renegotiation=dict(type='bool'),
1216 cache_size=dict(type='int'),
1217 cache_timeout=dict(type='int'),
1218 partition=dict(
1219 default='Common',
1220 fallback=(env_fallback, ['F5_PARTITION'])
1221 )
1222 )
1223 self.argument_spec = {}
1224 self.argument_spec.update(f5_argument_spec)
1225 self.argument_spec.update(argument_spec)
1226
1227
1228 def main():
1229 spec = ArgumentSpec()
1230
1231 module = AnsibleModule(
1232 argument_spec=spec.argument_spec,
1233 supports_check_mode=spec.supports_check_mode,
1234 )
1235
1236 try:
1237 mm = ModuleManager(module=module)
1238 results = mm.exec_module()
1239 module.exit_json(**results)
1240 except F5ModuleError as ex:
1241 module.fail_json(msg=str(ex))
1242
1243
1244 if __name__ == '__main__':
1245 main()