Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2019, 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_device_certificate
13 short_description: Manage self-signed device certificates
14 description:
15 - Module used to create and/or renew self-signed device certificates for BIG-IP.
16 version_added: "1.0.0"
17 options:
18 days_valid:
19 description:
20 - Specifies the interval for which the self-signed certificate is valid.
21 - "The maximum value is 25 years: C(9125) days"
22 type: int
23 required: True
24 cert_name:
25 description:
26 - Specifies the full name of the certificate file.
27 - If the name is not default C(server.crt), the module will configure C(httpd) to use them
28 prior to restarting the C(httpd) daemon.
29 type: str
30 default: server.crt
31 key_name:
32 description:
33 - Specifies the full name of the key file.
34 - If the name is not default C(server.key), the module will configure C(httpd) to use them
35 prior to restarting the C(httpd) daemon.
36 type: str
37 default: server.key
38 key_size:
39 description:
40 - Specifies the desired key size in bits.
41 - Mandatory option when generating a new certificate.
42 type: int
43 choices:
44 - 512
45 - 1024
46 - 2048
47 - 4096
48 default: 2048
49 issuer:
50 description:
51 - Certificate properties, required when generating new certificates.
52 suboptions:
53 country:
54 description:
55 - Specifies the Country name attribute for the certificate.
56 type: str
57 state:
58 description:
59 - Specifies the State or Province attribute for the certificate.
60 type: str
61 locality:
62 description:
63 - Specifies the city or town name for the certificate.
64 type: str
65 organization:
66 description:
67 - Specifies the Organization attribute for the certificate.
68 type: str
69 division:
70 description:
71 - Specifies the department name attribute for the certificate.
72 type: str
73 common_name:
74 description:
75 - Specifies the Common Name attribute for the certificate.
76 type: str
77 email:
78 description:
79 - "Specifies the email address of the domain administrator."
80 type: str
81 type: dict
82 add_to_trusted:
83 description:
84 - Specifies if the certificate should be added to the trusted client and server certificate files.
85 type: bool
86 default: false
87 new_cert:
88 description:
89 - Specifies if the module should generate a new certificate.
90 - When C(true), the device certificate and key will be replaced.
91 type: bool
92 default: false
93 force:
94 description:
95 - When C(true), will update or overwrite the existing certificate when it is not expired on the device.
96 - When C(false), the certificate will only be updated/overwritten if expired.
97 - Generally should be C(true) only in cases where you need to update certificate that is about to expire.
98 - This option is also needed when generating a new certificate to replace non-expired one.
99 type: bool
100 default: false
101 extends_documentation_fragment: f5networks.f5_modules.f5ssh
102 author:
103 - Wojciech Wypior (@wojtek0806)
104 notes:
105 - When using this module make sure SSH type is not set to libssh. To do this you could either
106 set the environment variable like this C(ANSIBLE_NETWORK_CLI_SSH_TYPE=paramiko) or set C(add
107 ssh_type = paramiko) under section persistent_connection in ansible.cfg.
108 '''
109
110 EXAMPLES = r'''
111 - name: Update expired certificate
112 bigip_device_certificate:
113 days_valid: 365
114 provider:
115 password: secret
116 server: lb.mydomain.com
117 user: admin
118 transport: cli
119 server_port: 22
120 delegate_to: localhost
121
122 - name: Update expired certificate non-default names
123 bigip_device_certificate:
124 days_valid: 60
125 cert_name: custom.crt
126 key_name: custom.key
127 provider:
128 password: secret
129 server: lb.mydomain.com
130 user: admin
131 transport: cli
132 server_port: 22
133 delegate_to: localhost
134
135 - name: Force update not expired certificate
136 bigip_device_certificate:
137 days_valid: 365
138 force: true
139 provider:
140 password: secret
141 server: lb.mydomain.com
142 user: admin
143 transport: cli
144 server_port: 22
145 delegate_to: localhost
146
147 - name: Create a new certificate to replace expired certificate
148 bigip_device_certificate:
149 days_valid: 365
150 new_cert: true
151 issuer:
152 country: US
153 state: WA
154 common_name: foobar.foo.local
155 provider:
156 password: secret
157 server: lb.mydomain.com
158 user: admin
159 transport: cli
160 server_port: 22
161 delegate_to: localhost
162
163 - name: Force create a new custom named certificate to replace not expired certificate
164 bigip_device_certificate:
165 days_valid: 365
166 cert_name: custom.crt
167 key_name: custom.key
168 new_cert: true
169 force: true
170 issuer:
171 country: US
172 state: WA
173 common_name: foobar.foo.local
174 key_size: 2048
175 provider:
176 password: secret
177 server: lb.mydomain.com
178 user: admin
179 transport: cli
180 server_port: 22
181 delegate_to: localhost
182 '''
183
184 RETURN = r'''
185 days_valid:
186 description: The interval for which the self-signed certificate is valid.
187 returned: changed
188 type: int
189 sample: 365
190 issuer:
191 description: Specifies certificate properties.
192 type: complex
193 returned: changed
194 contains:
195 country:
196 description: The Country name attribute of the certificate.
197 returned: changed
198 type: str
199 sample: US
200 state:
201 description: The State or Province attribute of the certificate.
202 returned: changed
203 type: str
204 sample: WA
205 locality:
206 description: The city or town name attribute of the certificate.
207 returned: changed
208 type: str
209 sample: Seattle
210 organization:
211 description: The Organization attribute of the certificate.
212 returned: changed
213 type: str
214 sample: F5
215 division:
216 description: The department name attribute of the certificate.
217 returned: changed
218 type: str
219 sample: IT
220 common_name:
221 description: The Common Name attribute of the certificate.
222 returned: changed
223 type: str
224 sample: foo.bar.local
225 email:
226 description: "The domain administrator's email address."
227 returned: changed
228 type: str
229 sample: [email protected]
230 cert_name:
231 description: The full name of the certificate file.
232 returned: changed
233 type: str
234 sample: common.crt
235 key_name:
236 description: The full name of the key file.
237 returned: changed
238 type: str
239 sample: common.key
240 key_size:
241 description: The desired key size in bits.
242 returned: changed
243 type: int
244 sample: 2048
245 '''
246 import copy
247 import os
248 import ssl
249 from datetime import datetime
250
251 from ansible.module_utils.basic import (
252 AnsibleModule, env_fallback
253 )
254 from ansible.module_utils.connection import exec_command
255
256
257 from ..module_utils.common import (
258 F5ModuleError, AnsibleF5Parameters, is_cli, f5_argument_spec
259 )
260
261
262 class Parameters(AnsibleF5Parameters):
263 returnables = [
264 'days_valid',
265 'issuer',
266 'key_size',
267 'cert_name',
268 'key_name',
269 ]
270
271 updatables = [
272 'days_valid',
273 ]
274
275
276 class ApiParameters(Parameters):
277 pass
278
279
280 class ModuleParameters(Parameters):
281 issuer_map = {
282 'country': 'C',
283 'state': 'ST',
284 'locality': 'L',
285 'organization': 'O',
286 'division': 'OU',
287 'common_name': 'CN',
288 'email': 'emailAddress'
289 }
290
291 @property
292 def issuer(self):
293 if self._values['issuer'] is None:
294 return None
295 filtered = dict((self.issuer_map[k], v) for k, v in self._values['issuer'].items() if v is not None)
296 to_parse = ['{0}={1}'.format(k, v) for k, v in filtered.items()]
297 result = '/' + '/'.join(to_parse) + '/'
298 return result
299
300 @property
301 def days_valid(self):
302 if 1 <= self._values['days_valid'] <= 9125:
303 return self._values['days_valid']
304 raise F5ModuleError(
305 "Valid 'days_valid' must be in range 1 - 9125 days."
306 )
307
308
309 class Changes(Parameters):
310 def to_return(self):
311 result = {}
312 try:
313 for returnable in self.returnables:
314 result[returnable] = getattr(self, returnable)
315 result = self._filter_params(result)
316 except Exception:
317 raise
318 return result
319
320
321 class UsableChanges(Changes):
322 pass
323
324
325 class ReportableChanges(Changes):
326 issuer_map = {
327 'C': 'country',
328 'ST': 'state',
329 'L': 'locality',
330 'O': 'organization',
331 'OU': 'division',
332 'CN': 'common_name',
333 'emailAddress': 'email'
334 }
335
336 @property
337 def issuer(self):
338 if self._values['issuer'] is None:
339 return None
340 to_dict = [tuple(item.split('=')) for item in self._values['issuer'].strip('/').split('/')]
341 result = dict((self.issuer_map[k], v) for k, v in to_dict)
342 return result
343
344
345 class Difference(object):
346 def __init__(self, want, have=None):
347 self.want = want
348 self.have = have
349
350 def compare(self, param):
351 try:
352 result = getattr(self, param)
353 return result
354 except AttributeError:
355 return self.__default(param)
356
357 def __default(self, param):
358 attr1 = getattr(self.want, param)
359 try:
360 attr2 = getattr(self.have, param)
361 if attr1 != attr2:
362 return attr1
363 except AttributeError:
364 return attr1
365
366
367 class ModuleManager(object):
368 def __init__(self, *args, **kwargs):
369 self.module = kwargs.get('module', None)
370 self.want = ModuleParameters(params=self.module.params)
371 self.have = ApiParameters()
372 self.changes = UsableChanges()
373
374 def _set_changed_options(self):
375 changed = {}
376 for key in Parameters.returnables:
377 if getattr(self.want, key) is not None:
378 changed[key] = getattr(self.want, key)
379 if changed:
380 self.changes = UsableChanges(params=changed)
381
382 def _update_changed_options(self):
383 diff = Difference(self.want, self.have)
384 updatables = Parameters.updatables
385 changed = dict()
386 for k in updatables:
387 change = diff.compare(k)
388 if change is None:
389 continue
390 else:
391 if isinstance(change, dict):
392 changed.update(change)
393 else:
394 changed[k] = change
395 if changed:
396 self.changes = UsableChanges(params=changed)
397 return True
398 return False
399
400 def exec_module(self):
401 if not is_cli(self.module):
402 raise F5ModuleError('Module can only be run via SSH, set the transport property to CLI')
403
404 result = dict()
405
406 changed = self.present()
407
408 reportable = ReportableChanges(params=self.changes.to_return())
409 changes = reportable.to_return()
410 result.update(**changes)
411 result.update(dict(changed=changed))
412 return result
413
414 def present(self):
415 if self.expired():
416 if self.want.new_cert:
417 self.create()
418 return True
419 self.update()
420 return True
421 if self.want.force and self.want.new_cert:
422 self.create()
423 return True
424 if self.want.force:
425 self.update()
426 return True
427 return False
428
429 def create(self):
430 self._set_changed_options()
431 if self.module.check_mode:
432 return True
433 self.generate_new()
434 return True
435
436 def update(self):
437 self._update_changed_options()
438 if self.module.check_mode:
439 return True
440 self.update_certificate()
441 if self.want.cert_name != 'server.crt' or self.want.key_name != 'server.key':
442 self.configure_new_cert()
443 self.restart_daemon()
444 if self.want.add_to_trusted:
445 self.copy_files_to_trusted()
446 return True
447
448 def expired(self):
449 self.have = self.read_current_certificate()
450 current_epoch = int(datetime.now().timestamp())
451 if current_epoch > self.have.epoch:
452 return True
453 return False
454
455 def generate_new(self):
456 self.generate_cert_key()
457 if self.want.cert_name != 'server.crt' or self.want.key_name != 'server.key':
458 self.configure_new_cert()
459 self.restart_daemon()
460 if self.want.add_to_trusted:
461 self.copy_files_to_trusted()
462 return True
463
464 def generate_cert_key(self):
465 cmd = 'openssl req -x509 -nodes -days {3} -newkey rsa:{4} -keyout {0}/ssl.key/{2} ' \
466 '-out {0}/ssl.crt/{1} -subj "{5}"'.format('/config/httpd/conf', self.want.cert_name, self.want.key_name,
467 self.want.days_valid, self.want.key_size, self.want.issuer)
468 rc, out, err = exec_command(self.module, cmd)
469 if rc != 0:
470 raise F5ModuleError(err)
471
472 def create_csr(self):
473 cmd = 'openssl x509 -x509toreq -in {0}/ssl.crt/{1} -out {0}/ssl.csr/{3}.csr -signkey {0}/ssl.key/{2}'.format(
474 '/config/httpd/conf', self.want.cert_name, self.want.key_name, os.path.splitext(self.want.cert_name)[0]
475 )
476
477 rc, out, err = exec_command(self.module, cmd)
478 if rc != 0:
479 raise F5ModuleError(err)
480
481 def update_certificate(self):
482 self.create_csr()
483 cmd = 'openssl x509 -req -in {0}/ssl.csr/{3}.csr -signkey {0}/ssl.key/{2} -days {4} -out {0}/ssl.crt/{1}'.\
484 format('/config/httpd/conf', self.want.cert_name, self.want.key_name,
485 os.path.splitext(self.want.cert_name)[0], self.want.days_valid)
486 rc, out, err = exec_command(self.module, cmd)
487 if rc != 0:
488 raise F5ModuleError(err)
489
490 def configure_new_cert(self):
491 cmd1 = 'tmsh modify sys httpd ssl-certkeyfile /config/httpd/conf/ssl.key/{1} ' \
492 'ssl-certfile /config/httpd/conf/ssl.crt/{0}'.format(self.want.cert_name, self.want.key_name)
493
494 cmd2 = 'tmsh save /sys config partitions all'
495
496 rc, out, err = exec_command(self.module, cmd1)
497 if rc != 0:
498 raise F5ModuleError(err)
499
500 rc, out, err = exec_command(self.module, cmd2)
501 if rc != 0:
502 raise F5ModuleError(err)
503
504 def restart_daemon(self):
505 cmd = 'tmsh restart /sys service httpd'
506 rc, out, err = exec_command(self.module, cmd)
507 if rc != 0:
508 raise F5ModuleError(err)
509
510 def copy_files_to_trusted(self):
511 cmd1 = 'cat /config/httpd/conf/ssl.crt/{0} >> /config/big3d/client.crt'.format(self.want.cert_name)
512 cmd2 = 'cat /config/httpd/conf/ssl.crt/{0} >> /config/gtm/server.crt'.format(self.want.cert_name)
513 rc, out, err = exec_command(self.module, cmd1)
514 if rc != 0:
515 raise F5ModuleError(err)
516 rc, out, err = exec_command(self.module, cmd2)
517 if rc != 0:
518 raise F5ModuleError(err)
519
520 def read_current_certificate(self):
521 result = dict()
522 command = 'openssl x509 -in /config/httpd/conf/ssl.crt/{0} -dates -issuer -noout'.format(self.want.cert_name)
523 rc, out, err = exec_command(self.module, command)
524 if rc != 0:
525 raise F5ModuleError(err)
526 if rc == 0:
527 result['epoch'] = self._parse_cert_date(out)
528 return ApiParameters(params=result)
529
530 def _parse_cert_date(self, to_parse):
531 c_time = to_parse.split('\n')[1].split('=')[1]
532 result = ssl.cert_time_to_seconds(c_time)
533 return result
534
535
536 class ArgumentSpec(object):
537 def __init__(self):
538 self.supports_check_mode = True
539 argument_spec = dict(
540 key_size=dict(
541 type='int',
542 choices=[512, 1024, 2048, 4096],
543 default=2048
544 ),
545 cert_name=dict(
546 default='server.crt'
547 ),
548 key_name=dict(
549 default='server.key'
550 ),
551 days_valid=dict(
552 type='int',
553 required=True
554 ),
555 issuer=dict(
556 type='dict',
557 options=dict(
558 country=dict(),
559 state=dict(),
560 locality=dict(),
561 organization=dict(),
562 division=dict(),
563 common_name=dict(),
564 email=dict(),
565 ),
566 required_one_of=[
567 ['country', 'state', 'locality', 'organization', 'division', 'common_name', 'email']
568 ]
569 ),
570
571 add_to_trusted=dict(
572 type='bool',
573 default='no'
574 ),
575 new_cert=dict(
576 type='bool',
577 default='no'
578 ),
579 force=dict(
580 type='bool',
581 default='no'
582 ),
583 )
584 # required to remove REST option from choices and set default to CLI to be in line with docs
585 provider_update = dict(
586 transport=dict(
587 type='str',
588 default='cli',
589 choices=['cli']
590 ),
591 ssh_keyfile=dict(
592 type='path'
593 ),
594 server_port=dict(
595 type='int',
596 default=22,
597 fallback=(env_fallback, ['F5_SERVER_PORT'])
598 ),
599 )
600 new_spec = copy.deepcopy(f5_argument_spec)
601 self.argument_spec = {}
602 self.argument_spec.update(new_spec)
603 self.argument_spec['provider']['options'].update(provider_update)
604 self.argument_spec.update(argument_spec)
605 self.required_if = [
606 ['new_cert', 'yes', ['days_valid', 'issuer', 'key_size']]
607 ]
608
609
610 def main():
611 spec = ArgumentSpec()
612
613 module = AnsibleModule(
614 argument_spec=spec.argument_spec,
615 supports_check_mode=spec.supports_check_mode,
616 required_if=spec.required_if,
617 )
618
619 try:
620 mm = ModuleManager(module=module)
621 results = mm.exec_module()
622 module.exit_json(**results)
623 except F5ModuleError as ex:
624 module.fail_json(msg=str(ex))
625
626
627 if __name__ == '__main__':
628 main()