Debian Codegraph @

ansible_collections/community/crypto/plugins/modules/openssl_dhparam.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2017, Thom Wiggers <[email protected]>
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: openssl_dhparam
10 short_description: Generate OpenSSL Diffie-Hellman Parameters
11 description:
12 - This module allows one to (re)generate OpenSSL DH-params.
13 - This module uses file common arguments to specify generated file permissions.
14 - Please note that the module regenerates existing DH params if they do not match the module's options. If you are concerned
15 that this could overwrite your existing DH params, consider using the O(backup) option.
16 - The module can use the cryptography Python library, or the C(openssl) executable. By default, it tries to detect which
17 one is available. This can be overridden with the O(select_crypto_backend) option.
18 requirements:
19 - Either cryptography >= 3.3
20 - Or OpenSSL binary C(openssl)
21 author:
22 - Thom Wiggers (@thomwiggers)
23 extends_documentation_fragment:
24 - ansible.builtin.files
25 - community.crypto._attributes
26 - community.crypto._attributes.files
27 attributes:
28 check_mode:
29 support: full
30 diff_mode:
31 support: none
32 safe_file_operations:
33 support: full
34 idempotent:
35 support: partial
36 details:
37 - The module is not idempotent if O(force=true).
38 options:
39 state:
40 description:
41 - Whether the parameters should exist or not, taking action if the state is different from what is stated.
42 type: str
43 default: present
44 choices: [absent, present]
45 size:
46 description:
47 - Size (in bits) of the generated DH-params.
48 type: int
49 default: 4096
50 force:
51 description:
52 - Should the parameters be regenerated even it it already exists.
53 type: bool
54 default: false
55 path:
56 description:
57 - Name of the file in which the generated parameters will be saved.
58 type: path
59 required: true
60 backup:
61 description:
62 - Create a backup file including a timestamp so you can get the original DH params back if you overwrote them with new
63 ones by accident.
64 type: bool
65 default: false
66 select_crypto_backend:
67 description:
68 - Determines which crypto backend to use.
69 - The default choice is V(auto), which tries to use C(cryptography) if available, and falls back to C(openssl).
70 - If set to V(openssl), will try to use the OpenSSL C(openssl) executable.
71 - If set to V(cryptography), will try to use the L(cryptography,https://cryptography.io/) library.
72 type: str
73 default: auto
74 choices: [auto, cryptography, openssl]
75 version_added: "1.0.0"
76 return_content:
77 description:
78 - If set to V(true), will return the (current or generated) DH parameter's content as RV(dhparams).
79 type: bool
80 default: false
81 version_added: "1.0.0"
82 seealso:
83 - module: community.crypto.x509_certificate
84 - module: community.crypto.openssl_csr
85 - module: community.crypto.openssl_pkcs12
86 - module: community.crypto.openssl_privatekey
87 - module: community.crypto.openssl_publickey
88 """
89
90 EXAMPLES = r"""
91 ---
92 - name: Generate Diffie-Hellman parameters with the default size (4096 bits)
93 community.crypto.openssl_dhparam:
94 path: /etc/ssl/dhparams.pem
95
96 - name: Generate DH Parameters with a different size (2048 bits)
97 community.crypto.openssl_dhparam:
98 path: /etc/ssl/dhparams.pem
99 size: 2048
100
101 - name: Force regenerate an DH parameters if they already exist
102 community.crypto.openssl_dhparam:
103 path: /etc/ssl/dhparams.pem
104 force: true
105 """
106
107 RETURN = r"""
108 size:
109 description: Size (in bits) of the Diffie-Hellman parameters.
110 returned: changed or success
111 type: int
112 sample: 4096
113 filename:
114 description: Path to the generated Diffie-Hellman parameters.
115 returned: changed or success
116 type: str
117 sample: /etc/ssl/dhparams.pem
118 backup_file:
119 description: Name of backup file created.
120 returned: changed and if O(backup) is V(true)
121 type: str
122 sample: /path/to/dhparams.pem.2019-03-09@11:22~
123 dhparams:
124 description: The (current or generated) DH params' content.
125 returned: if O(state) is V(present) and O(return_content) is V(true)
126 type: str
127 version_added: "1.0.0"
128 """
129
130 import abc
131 import os
132 import re
133 import tempfile
134 import typing as t
135
136 from ansible.module_utils.basic import AnsibleModule
137 from ansible.module_utils.common.text.converters import to_text
138
139 from ansible_collections.community.crypto.plugins.module_utils._crypto.math import (
140 count_bits,
141 )
142 from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep import (
143 COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION,
144 assert_required_cryptography_version,
145 )
146 from ansible_collections.community.crypto.plugins.module_utils._io import (
147 load_file_if_exists,
148 write_file,
149 )
150 from ansible_collections.community.crypto.plugins.module_utils._version import (
151 LooseVersion,
152 )
153
154 MINIMAL_CRYPTOGRAPHY_VERSION = COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION
155
156 try:
157 import cryptography
158 import cryptography.exceptions
159 import cryptography.hazmat.backends
160 import cryptography.hazmat.primitives.asymmetric.dh
161 import cryptography.hazmat.primitives.serialization
162
163 CRYPTOGRAPHY_VERSION = LooseVersion(cryptography.__version__)
164 except ImportError:
165 CRYPTOGRAPHY_FOUND = False
166 else:
167 CRYPTOGRAPHY_FOUND = True
168
169
170 class DHParameterError(Exception):
171 pass
172
173
174 class DHParameterBase:
175 def __init__(self, module: AnsibleModule) -> None:
176 self.state: t.Literal["absent", "present"] = module.params["state"]
177 self.path: str = module.params["path"]
178 self.size: int = module.params["size"]
179 self.force: bool = module.params["force"]
180 self.changed = False
181 self.return_content: bool = module.params["return_content"]
182
183 self.backup: bool = module.params["backup"]
184 self.backup_file: str | None = None
185
186 @abc.abstractmethod
187 def _do_generate(self, module: AnsibleModule) -> None:
188 """Actually generate the DH params."""
189
190 def generate(self, module: AnsibleModule) -> None:
191 """Generate DH params."""
192 changed = False
193
194 # only generate when necessary
195 if self.force or not self._check_params_valid(module):
196 self._do_generate(module)
197 changed = True
198
199 # fix permissions (checking force not necessary as done above)
200 if not self._check_fs_attributes(module):
201 # Fix done implicitly by
202 # AnsibleModule.set_fs_attributes_if_different
203 changed = True
204
205 self.changed = changed
206
207 def remove(self, module: AnsibleModule) -> None:
208 if self.backup:
209 self.backup_file = module.backup_local(self.path)
210 try:
211 os.remove(self.path)
212 self.changed = True
213 except OSError as exc:
214 module.fail_json(msg=str(exc))
215
216 def check(self, module: AnsibleModule) -> bool:
217 """Ensure the resource is in its desired state."""
218 if self.force:
219 return False
220 return self._check_params_valid(module) and self._check_fs_attributes(module)
221
222 @abc.abstractmethod
223 def _check_params_valid(self, module: AnsibleModule) -> bool:
224 """Check if the params are in the correct state"""
225
226 def _check_fs_attributes(self, module: AnsibleModule) -> bool:
227 """Checks (and changes if not in check mode!) fs attributes"""
228 file_args = module.load_file_common_arguments(module.params)
229 if module.check_file_absent_if_check_mode(file_args["path"]):
230 return False
231 return not module.set_fs_attributes_if_different(file_args, False)
232
233 def dump(self) -> dict[str, t.Any]:
234 """Serialize the object into a dictionary."""
235
236 result: dict[str, t.Any] = {
237 "size": self.size,
238 "filename": self.path,
239 "changed": self.changed,
240 }
241 if self.backup_file:
242 result["backup_file"] = self.backup_file
243 if self.return_content:
244 content = load_file_if_exists(path=self.path, ignore_errors=True)
245 result["dhparams"] = content.decode("utf-8") if content else None
246
247 return result
248
249
250 class DHParameterAbsent(DHParameterBase):
251 def __init__(self, module: AnsibleModule) -> None:
252 super().__init__(module)
253
254 def _do_generate(self, module: AnsibleModule) -> None:
255 """Actually generate the DH params."""
256
257 def _check_params_valid(self, module: AnsibleModule) -> bool:
258 """Check if the params are in the correct state"""
259 return False
260
261
262 class DHParameterOpenSSL(DHParameterBase):
263 def __init__(self, module: AnsibleModule) -> None:
264 super().__init__(module)
265 self.openssl_bin = module.get_bin_path("openssl", True)
266
267 def _do_generate(self, module: AnsibleModule) -> None:
268 """Actually generate the DH params."""
269 # create a tempfile
270 fd, tmpsrc = tempfile.mkstemp()
271 os.close(fd)
272 module.add_cleanup_file(tmpsrc) # Ansible will delete the file on exit
273 # openssl dhparam -out <path> <bits>
274 command = [self.openssl_bin, "dhparam", "-out", tmpsrc, str(self.size)]
275 rc, dummy, err = module.run_command(command, check_rc=False)
276 if rc != 0:
277 raise DHParameterError(str(err))
278 if self.backup:
279 self.backup_file = module.backup_local(self.path)
280 try:
281 module.atomic_move(os.path.abspath(tmpsrc), os.path.abspath(self.path))
282 except Exception as e:
283 module.fail_json(msg=f"Failed to write to file {self.path}: {str(e)}")
284
285 def _check_params_valid(self, module: AnsibleModule) -> bool:
286 """Check if the params are in the correct state"""
287 command = [
288 self.openssl_bin,
289 "dhparam",
290 "-check",
291 "-text",
292 "-noout",
293 "-in",
294 self.path,
295 ]
296 rc, out, err = module.run_command(command, check_rc=False)
297 result = to_text(out)
298 if rc != 0:
299 # If the call failed the file probably does not exist or is
300 # unreadable
301 return False
302 # output contains "(xxxx bit)"
303 match = re.search(r"Parameters:\s+\((\d+) bit\).*", result)
304 if not match:
305 return False # No "xxxx bit" in output
306
307 bits = int(match.group(1))
308
309 # if output contains "WARNING" we've got a problem
310 if "WARNING" in result or "WARNING" in to_text(err):
311 return False
312
313 return bits == self.size
314
315
316 class DHParameterCryptography(DHParameterBase):
317 def __init__(self, module: AnsibleModule) -> None:
318 super().__init__(module)
319
320 def _do_generate(self, module: AnsibleModule) -> None:
321 """Actually generate the DH params."""
322 # Generate parameters
323 params = cryptography.hazmat.primitives.asymmetric.dh.generate_parameters(
324 generator=2,
325 key_size=self.size,
326 )
327 # Serialize parameters
328 result = params.parameter_bytes(
329 encoding=cryptography.hazmat.primitives.serialization.Encoding.PEM,
330 format=cryptography.hazmat.primitives.serialization.ParameterFormat.PKCS3,
331 )
332 # Write result
333 if self.backup:
334 self.backup_file = module.backup_local(self.path)
335 write_file(module=module, content=result)
336
337 def _check_params_valid(self, module: AnsibleModule) -> bool:
338 """Check if the params are in the correct state"""
339 # Load parameters
340 try:
341 with open(self.path, "rb") as f:
342 data = f.read()
343 params = cryptography.hazmat.primitives.serialization.load_pem_parameters(
344 data
345 )
346 except Exception:
347 return False
348 # Check parameters
349 bits = count_bits(params.parameter_numbers().p)
350 return bits == self.size
351
352
353 def main() -> t.NoReturn:
354 """Main function"""
355
356 module = AnsibleModule(
357 argument_spec={
358 "state": {
359 "type": "str",
360 "default": "present",
361 "choices": ["absent", "present"],
362 },
363 "size": {"type": "int", "default": 4096},
364 "force": {"type": "bool", "default": False},
365 "path": {"type": "path", "required": True},
366 "backup": {"type": "bool", "default": False},
367 "select_crypto_backend": {
368 "type": "str",
369 "default": "auto",
370 "choices": ["auto", "cryptography", "openssl"],
371 },
372 "return_content": {"type": "bool", "default": False},
373 },
374 supports_check_mode=True,
375 add_file_common_args=True,
376 )
377
378 base_dir = os.path.dirname(module.params["path"]) or "."
379 if not os.path.isdir(base_dir):
380 module.fail_json(
381 name=base_dir,
382 msg=f"The directory '{base_dir}' does not exist or the file is not a directory",
383 )
384
385 dhparam: DHParameterOpenSSL | DHParameterCryptography | DHParameterAbsent
386 if module.params["state"] == "present":
387 backend = module.params["select_crypto_backend"]
388 if backend == "auto":
389 # Detection what is possible
390 can_use_cryptography = (
391 CRYPTOGRAPHY_FOUND
392 and LooseVersion(MINIMAL_CRYPTOGRAPHY_VERSION) <= CRYPTOGRAPHY_VERSION
393 )
394 can_use_openssl = module.get_bin_path("openssl", False) is not None
395
396 # First try cryptography, then OpenSSL
397 if can_use_cryptography:
398 backend = "cryptography"
399 elif can_use_openssl:
400 backend = "openssl"
401
402 # Success?
403 if backend == "auto":
404 module.fail_json(
405 msg=(
406 f"Cannot detect either the required Python library cryptography (>= {MINIMAL_CRYPTOGRAPHY_VERSION}) or the OpenSSL binary openssl"
407 )
408 )
409
410 if backend == "openssl":
411 dhparam = DHParameterOpenSSL(module)
412 elif backend == "cryptography":
413 assert_required_cryptography_version(
414 module, minimum_cryptography_version=MINIMAL_CRYPTOGRAPHY_VERSION
415 )
416 dhparam = DHParameterCryptography(module)
417 else:
418 raise AssertionError("Internal error: unknown backend") # pragma: no cover
419
420 if module.check_mode:
421 result = dhparam.dump()
422 result["changed"] = module.params["force"] or not dhparam.check(module)
423 module.exit_json(**result)
424
425 try:
426 dhparam.generate(module)
427 except DHParameterError as exc:
428 module.fail_json(msg=str(exc))
429 else:
430 dhparam = DHParameterAbsent(module)
431
432 if module.check_mode:
433 result = dhparam.dump()
434 result["changed"] = os.path.exists(module.params["path"])
435 module.exit_json(**result)
436
437 if os.path.exists(module.params["path"]):
438 try:
439 dhparam.remove(module)
440 except Exception as exc:
441 module.fail_json(msg=str(exc))
442
443 result = dhparam.dump()
444
445 module.exit_json(**result)
446
447
448 if __name__ == "__main__":
449 main()