Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_ssl_certificate.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_ssl_certificate
13 short_description: Import/Delete certificates from BIG-IP
14 description:
15 - This module imports/deletes SSL certificates on BIG-IP LTM.
16 Certificates can be imported from certificate and key files on the local
17 disk, in PEM format.
18 version_added: "1.0.0"
19 options:
20 content:
21 description:
22 - Sets the contents of a certificate directly to the specified value.
23 This is used with lookup plugins or for anything with formatting, or
24 - C(content) must be provided when C(state) is C(present).
25 type: str
26 aliases: ['cert_content']
27 state:
28 description:
29 - Certificate state. This determines if the provided certificate
30 and key is to be made C(present) on the device or C(absent).
31 type: str
32 choices:
33 - present
34 - absent
35 default: present
36 name:
37 description:
38 - SSL Certificate Name. This is the cert name used when importing a certificate
39 into the BIG-IP. It also determines the filenames of the objects on the LTM.
40 type: str
41 required: True
42 issuer_cert:
43 description:
44 - Issuer certificate used for OCSP monitoring.
45 - This parameter is only valid on versions of BIG-IP 13.0.0 or above.
46 type: str
47 true_names:
48 description:
49 - When C(true), the module does not append C(.crt) extension to the given certificate name.
50 - When C(false), the module appends C(.crt) extension to the given certificate name.
51 type: bool
52 default: false
53 version_added: "1.24.0"
54 partition:
55 description:
56 - Device partition to manage resources on.
57 type: str
58 default: Common
59 notes:
60 - This module does not behave like other modules that you might include in
61 roles, where referencing files or templates first looks in the role's
62 files or templates directory. To have it behave that way, use the Ansible
63 file or template lookup (see Examples). The lookups behave as expected in
64 a role context.
65 extends_documentation_fragment: f5networks.f5_modules.f5
66 requirements:
67 - BIG-IP >= v12
68 author:
69 - Tim Rupp (@caphrim007)
70 - Wojciech Wypior (@wojtek0806)
71 '''
72
73 EXAMPLES = r'''
74 - name: Use a file lookup to import PEM Certificate
75 bigip_ssl_certificate:
76 name: certificate-name
77 state: present
78 content: "{{ lookup('file', '/path/to/cert.crt') }}"
79 provider:
80 server: lb.mydomain.com
81 user: admin
82 password: secret
83 delegate_to: localhost
84
85 - name: Use a file lookup to import CA certificate chain
86 bigip_ssl_certificate:
87 name: ca-chain-name
88 state: present
89 content: "{{ lookup('file', '/path/to/ca-chain.crt') }}"
90 provider:
91 server: lb.mydomain.com
92 user: admin
93 password: secret
94 delegate_to: localhost
95
96 - name: Delete Certificate
97 bigip_ssl_certificate:
98 name: certificate-name
99 state: absent
100 provider:
101 server: lb.mydomain.com
102 user: admin
103 password: secret
104 delegate_to: localhost
105 '''
106
107 RETURN = r'''
108 cert_name:
109 description: The name of the certificate.
110 returned: created
111 type: str
112 sample: cert1
113 filename:
114 description:
115 - The name of the SSL certificate.
116 returned: created
117 type: str
118 sample: cert1.crt
119 checksum:
120 description: SHA1 checksum of the cert.
121 returned: changed and created
122 type: str
123 sample: f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0
124 source_path:
125 description: Path on BIG-IP where the source of the certificate is stored.
126 returned: created
127 type: str
128 sample: /var/config/rest/downloads/cert1.crt
129 '''
130
131 import hashlib
132 import os
133 import re
134 from datetime import datetime
135
136 from ansible.module_utils.basic import (
137 AnsibleModule, env_fallback
138 )
139
140 from ..module_utils.bigip import F5RestClient
141 from ..module_utils.common import (
142 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, fq_name, flatten_boolean
143 )
144 from ..module_utils.icontrol import (
145 upload_file, tmos_version
146 )
147 from ..module_utils.teem import send_teem
148
149 try:
150 from StringIO import StringIO
151 except ImportError:
152 from io import StringIO
153
154
155 class Parameters(AnsibleF5Parameters):
156 download_path = '/var/config/rest/downloads'
157
158 api_map = {
159 'sourcePath': 'source_path',
160 'issuerCert': 'issuer_cert',
161 }
162
163 updatables = [
164 'content',
165 'issuer_cert',
166 'source_path',
167 ]
168
169 returnables = [
170 'filename',
171 'checksum',
172 'source_path',
173 'issuer_cert',
174 ]
175
176 api_attributes = [
177 'issuerCert',
178 'sourcePath',
179 ]
180
181
182 class ApiParameters(Parameters):
183 @property
184 def checksum(self):
185 if self._values['checksum'] is None:
186 return None
187 pattern = r'SHA1:\d+:(?P<value>[\w+]{40})'
188 matches = re.match(pattern, self._values['checksum'])
189 if matches:
190 return matches.group('value')
191 else:
192 return None
193
194 @property
195 def filename(self):
196 return self._values['name']
197
198
199 class ModuleParameters(Parameters):
200 def _get_hash(self, content):
201 k = hashlib.sha1()
202 s = StringIO(content)
203 while True:
204 data = s.read(1024)
205 if not data:
206 break
207 k.update(data.encode('utf-8'))
208 return k.hexdigest()
209
210 @property
211 def issuer_cert(self):
212 if self._values['issuer_cert'] is None:
213 return None
214 name = fq_name(self.partition, self._values['issuer_cert'])
215 true_name = flatten_boolean(self.true_names)
216 if true_name == ' yes':
217 return self.name
218 else:
219 if name.endswith('.crt'):
220 return name
221 else:
222 return name + '.crt'
223
224 @property
225 def checksum(self):
226 if self.content is None:
227 return None
228 return self._get_hash(self.content)
229
230 @property
231 def filename(self):
232 true_name = flatten_boolean(self.true_names)
233 if true_name == 'yes':
234 return self.name
235 else:
236 if self.name.endswith('.crt'):
237 return self.name
238 else:
239 return self.name + '.crt'
240
241 @property
242 def source_path(self):
243 result = 'file://' + os.path.join(
244 self.download_path,
245 self.filename
246 )
247 return result
248
249
250 class Changes(Parameters):
251 def to_return(self):
252 result = {}
253 try:
254 for returnable in self.returnables:
255 result[returnable] = getattr(self, returnable)
256 result = self._filter_params(result)
257 except Exception:
258 raise
259 return result
260
261
262 class ReportableChanges(Changes):
263 pass
264
265
266 class UsableChanges(Changes):
267 pass
268
269
270 class Difference(object):
271 def __init__(self, want, have=None):
272 self.want = want
273 self.have = have
274
275 def compare(self, param):
276 try:
277 result = getattr(self, param)
278 return result
279 except AttributeError:
280 result = self.__default(param)
281 return result
282
283 def __default(self, param):
284 attr1 = getattr(self.want, param)
285 try:
286 attr2 = getattr(self.have, param)
287 if attr1 != attr2:
288 return attr1
289 except AttributeError:
290 return attr1
291
292 @property
293 def source_path(self):
294 if self.want.source_path is None:
295 return None
296 if self.want.source_path == self.have.source_path:
297 if self.content:
298 return self.want.source_path
299 if self.want.source_path != self.have.source_path:
300 return self.want.source_path
301
302 @property
303 def content(self):
304 if self.want.checksum != self.have.checksum:
305 result = dict(
306 checksum=self.want.checksum,
307 content=self.want.content
308 )
309 return result
310
311
312 class ModuleManager(object):
313 def __init__(self, *args, **kwargs):
314 self.module = kwargs.get('module', None)
315 self.client = F5RestClient(**self.module.params)
316 self.want = ModuleParameters(params=self.module.params)
317 self.have = ApiParameters()
318 self.changes = UsableChanges()
319
320 def exec_module(self):
321 start = datetime.now().isoformat()
322 version = tmos_version(self.client)
323 changed = False
324 result = dict()
325 state = self.want.state
326
327 if state == "present":
328 changed = self.present()
329 elif state == "absent":
330 changed = self.absent()
331
332 reportable = ReportableChanges(params=self.changes.to_return())
333 changes = reportable.to_return()
334 result.update(**changes)
335 result.update(dict(changed=changed))
336 self._announce_deprecations(result)
337 send_teem(start, self.client, self.module, version)
338 return result
339
340 def _announce_deprecations(self, result):
341 warnings = result.pop('__warnings', [])
342 for warning in warnings:
343 self.module.deprecate(
344 msg=warning['msg'],
345 version=warning['version']
346 )
347
348 def present(self):
349 if self.exists():
350 return self.update()
351 else:
352 return self.create()
353
354 def create(self):
355 self._set_changed_options()
356 if self.module.check_mode:
357 return True
358 self.create_on_device()
359 self.remove_uploaded_file_from_device(self.want.filename)
360 return True
361
362 def should_update(self):
363 result = self._update_changed_options()
364 if result:
365 return True
366 return False
367
368 def update(self):
369 self.have = self.read_current_from_device()
370 if not self.should_update():
371 return False
372 if self.module.check_mode:
373 return True
374 self.update_on_device()
375 self.remove_uploaded_file_from_device(self.want.filename)
376 return True
377
378 def absent(self):
379 if self.exists():
380 return self.remove()
381 return False
382
383 def remove(self):
384 if self.module.check_mode:
385 return True
386 self.remove_from_device()
387 return True
388
389 def _set_changed_options(self):
390 changed = {}
391 for key in Parameters.returnables:
392 if getattr(self.want, key) is not None:
393 changed[key] = getattr(self.want, key)
394 if changed:
395 self.changes = UsableChanges(params=changed)
396
397 def _update_changed_options(self):
398 diff = Difference(self.want, self.have)
399 updatables = Parameters.updatables
400 changed = dict()
401 for k in updatables:
402 change = diff.compare(k)
403 if change is None:
404 continue
405 else:
406 if isinstance(change, dict):
407 changed.update(change)
408 else:
409 changed[k] = change
410 if changed:
411 self.changes = UsableChanges(params=changed)
412 return True
413 return False
414
415 def remove_uploaded_file_from_device(self, name):
416 filepath = '/var/config/rest/downloads/{0}'.format(name)
417 params = {
418 "command": "run",
419 "utilCmdArgs": filepath
420 }
421 uri = "https://{0}:{1}/mgmt/tm/util/unix-rm".format(
422 self.client.provider['server'],
423 self.client.provider['server_port']
424 )
425 resp = self.client.api.post(uri, json=params)
426 try:
427 response = resp.json()
428 except ValueError as ex:
429 raise F5ModuleError(str(ex))
430 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
431 return True
432 raise F5ModuleError(resp.content)
433
434 def exists(self):
435 uri = "https://{0}:{1}/mgmt/tm/sys/file/ssl-cert/{2}".format(
436 self.client.provider['server'],
437 self.client.provider['server_port'],
438 transform_name(self.want.partition, self.want.filename)
439 )
440 resp = self.client.api.get(uri)
441 try:
442 response = resp.json()
443 except ValueError as ex:
444 raise F5ModuleError(str(ex))
445
446 if resp.status == 404 or 'code' in response and response['code'] == 404:
447 return False
448 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
449 return True
450
451 errors = [401, 403, 409, 500, 501, 502, 503, 504]
452
453 if resp.status in errors or 'code' in response and response['code'] in errors:
454 if 'message' in response:
455 raise F5ModuleError(response['message'])
456 else:
457 raise F5ModuleError(resp.content)
458
459 def upload_file_to_device(self, content, name):
460 url = 'https://{0}:{1}/mgmt/shared/file-transfer/uploads'.format(
461 self.client.provider['server'],
462 self.client.provider['server_port']
463 )
464 try:
465 upload_file(self.client, url, content, name)
466 except F5ModuleError:
467 raise F5ModuleError(
468 "Failed to upload the file."
469 )
470
471 def update_on_device(self):
472 content = StringIO(self.want.content)
473 self.upload_file_to_device(content, self.want.filename)
474 params = self.changes.api_params()
475 uri = "https://{0}:{1}/mgmt/tm/sys/file/ssl-cert/{2}".format(
476 self.client.provider['server'],
477 self.client.provider['server_port'],
478 transform_name(self.want.partition, self.want.filename)
479 )
480 resp = self.client.api.put(uri, json=params)
481 try:
482 response = resp.json()
483 except ValueError as ex:
484 raise F5ModuleError(str(ex))
485
486 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
487 return True
488
489 raise F5ModuleError(resp.content)
490
491 def create_on_device(self):
492 content = StringIO(self.want.content)
493 self.upload_file_to_device(content, self.want.filename)
494 uri = "https://{0}:{1}/mgmt/tm/sys/file/ssl-cert/".format(
495 self.client.provider['server'],
496 self.client.provider['server_port'],
497 )
498 params = dict(
499 sourcePath=self.want.source_path,
500 name=self.want.filename,
501 partition=self.want.partition
502 )
503
504 resp = self.client.api.post(uri, json=params)
505 try:
506 response = resp.json()
507 except ValueError as ex:
508 raise F5ModuleError(str(ex))
509
510 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
511 raise F5ModuleError(resp.content)
512
513 # This needs to be done because of the way that BIG-IP creates certificates.
514 #
515 # The extra params (such as OCSP and issuer stuff) are not available in the
516 # payload. In a nutshell, the available resource attributes *change* after
517 # a create so that *more* are available.
518 params = self.want.api_params()
519 if params:
520 uri = "https://{0}:{1}/mgmt/tm/sys/file/ssl-cert/{2}".format(
521 self.client.provider['server'],
522 self.client.provider['server_port'],
523 transform_name(self.want.partition, self.want.filename)
524 )
525 resp = self.client.api.put(uri, json=params)
526 try:
527 response = resp.json()
528 except ValueError as ex:
529 raise F5ModuleError(str(ex))
530
531 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
532 return True
533
534 raise F5ModuleError(resp.content)
535
536 def read_current_from_device(self):
537 uri = "https://{0}:{1}/mgmt/tm/sys/file/ssl-cert/{2}".format(
538 self.client.provider['server'],
539 self.client.provider['server_port'],
540 transform_name(self.want.partition, self.want.filename)
541 )
542
543 query = '?expandSubcollections=true'
544 resp = self.client.api.get(uri + query)
545
546 try:
547 response = resp.json()
548 except ValueError as ex:
549 raise F5ModuleError(str(ex))
550
551 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
552 return ApiParameters(params=response)
553 raise F5ModuleError(resp.content)
554
555 def remove_from_device(self):
556 uri = "https://{0}:{1}/mgmt/tm/sys/file/ssl-cert/{2}".format(
557 self.client.provider['server'],
558 self.client.provider['server_port'],
559 transform_name(self.want.partition, self.want.filename)
560 )
561 response = self.client.api.delete(uri)
562 if response.status == 200:
563 return True
564 raise F5ModuleError(response.content)
565
566
567 class ArgumentSpec(object):
568 def __init__(self):
569 self.supports_check_mode = True
570 argument_spec = dict(
571 name=dict(
572 required=True
573 ),
574 content=dict(aliases=['cert_content']),
575 state=dict(
576 default='present',
577 choices=['absent', 'present']
578 ),
579 issuer_cert=dict(),
580 true_names=dict(
581 type='bool',
582 default='no'
583 ),
584 partition=dict(
585 default='Common',
586 fallback=(env_fallback, ['F5_PARTITION'])
587 )
588 )
589 self.argument_spec = {}
590 self.argument_spec.update(f5_argument_spec)
591 self.argument_spec.update(argument_spec)
592
593
594 def main():
595 spec = ArgumentSpec()
596
597 module = AnsibleModule(
598 argument_spec=spec.argument_spec,
599 supports_check_mode=spec.supports_check_mode
600 )
601
602 try:
603 mm = ModuleManager(module=module)
604 results = mm.exec_module()
605 module.exit_json(**results)
606 except F5ModuleError as ex:
607 module.fail_json(msg=str(ex))
608
609
610 if __name__ == '__main__':
611 main()