Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # Copyright (c) 2017, Yanis Guenane <[email protected]>
3 # Copyright (c) 2020, Felix Fontein <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: openssl_csr_pipe
11 short_description: Generate OpenSSL Certificate Signing Request (CSR)
12 version_added: 1.3.0
13 description:
14 - Please note that the module regenerates an existing CSR if it does not match the module's options, or if it seems to be
15 corrupt.
16 author:
17 - Yanis Guenane (@Spredzy)
18 - Felix Fontein (@felixfontein)
19 extends_documentation_fragment:
20 - community.crypto._attributes
21 - community.crypto._module_csr
22 attributes:
23 check_mode:
24 support: full
25 details:
26 - Since community.crypto 3.0.0, the module ignores check mode and always behaves as if check mode is not active.
27 options:
28 content:
29 description:
30 - The existing CSR.
31 type: str
32 privatekey_path:
33 description:
34 - The path to the private key to use when signing the certificate signing request.
35 - Either O(privatekey_path) or O(privatekey_content) must be specified, but not both.
36 privatekey_content:
37 description:
38 - The content of the private key to use when signing the certificate signing request.
39 - Either O(privatekey_path) or O(privatekey_content) must be specified, but not both.
40 seealso:
41 - module: community.crypto.openssl_csr
42 """
43
44 EXAMPLES = r"""
45 ---
46 - name: Generate an OpenSSL Certificate Signing Request
47 community.crypto.openssl_csr_pipe:
48 privatekey_path: /etc/ssl/private/ansible.com.pem
49 common_name: www.ansible.com
50 register: result
51 - name: Print CSR
52 ansible.builtin.debug:
53 var: result.csr
54
55 - name: Generate an OpenSSL Certificate Signing Request with an inline CSR
56 community.crypto.openssl_csr:
57 content: "{{ lookup('ansible.builtin.file', '/etc/ssl/csr/www.ansible.com.csr') }}"
58 privatekey_content: "{{ private_key_content }}"
59 common_name: www.ansible.com
60 register: result
61 - name: Store CSR
62 ansible.builtin.copy:
63 dest: /etc/ssl/csr/www.ansible.com.csr
64 content: "{{ result.csr }}"
65 when: result is changed
66 """
67
68 RETURN = r"""
69 privatekey:
70 description:
71 - Path to the TLS/SSL private key the CSR was generated for.
72 - Will be V(none) if the private key has been provided in O(privatekey_content).
73 returned: changed or success
74 type: str
75 sample: /etc/ssl/private/ansible.com.pem
76 subject:
77 description: A list of the subject tuples attached to the CSR.
78 returned: changed or success
79 type: list
80 elements: list
81 sample: [['CN', 'www.ansible.com'], ['O', 'Ansible']]
82 subjectAltName:
83 description: The alternative names this CSR is valid for.
84 returned: changed or success
85 type: list
86 elements: str
87 sample: ['DNS:www.ansible.com', 'DNS:m.ansible.com']
88 keyUsage:
89 description: Purpose for which the public key may be used.
90 returned: changed or success
91 type: list
92 elements: str
93 sample: ['digitalSignature', 'keyAgreement']
94 extendedKeyUsage:
95 description: Additional restriction on the public key purposes.
96 returned: changed or success
97 type: list
98 elements: str
99 sample: ['clientAuth']
100 basicConstraints:
101 description: Indicates if the certificate belongs to a CA.
102 returned: changed or success
103 type: list
104 elements: str
105 sample: ['CA:TRUE', 'pathLenConstraint:0']
106 ocsp_must_staple:
107 description: Indicates whether the certificate has the OCSP Must Staple feature enabled.
108 returned: changed or success
109 type: bool
110 sample: false
111 name_constraints_permitted:
112 description: List of permitted subtrees to sign certificates for.
113 returned: changed or success
114 type: list
115 elements: str
116 sample: ['email:.somedomain.com']
117 name_constraints_excluded:
118 description: List of excluded subtrees the CA cannot sign certificates for.
119 returned: changed or success
120 type: list
121 elements: str
122 sample: ['email:.com']
123 csr:
124 description: The (current or generated) CSR's content.
125 returned: changed or success
126 type: str
127 """
128
129 import typing as t
130
131 from ansible_collections.community.crypto.plugins.module_utils._crypto.basic import (
132 OpenSSLObjectError,
133 )
134 from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.csr import (
135 get_csr_argument_spec,
136 select_backend,
137 )
138
139 if t.TYPE_CHECKING:
140 from ansible.module_utils.basic import AnsibleModule # pragma: no cover
141
142 from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.csr import ( # pragma: no cover
143 CertificateSigningRequestBackend,
144 )
145
146
147 class CertificateSigningRequestModule:
148 def __init__(
149 self, module: AnsibleModule, module_backend: CertificateSigningRequestBackend
150 ) -> None:
151 self.check_mode = module.check_mode
152 self.module = module
153 self.module_backend = module_backend
154 self.changed = False
155 if module.params["content"] is not None:
156 self.module_backend.set_existing(
157 csr_bytes=module.params["content"].encode("utf-8")
158 )
159
160 def generate(self, module: AnsibleModule) -> None:
161 """Generate the certificate signing request."""
162 if self.module_backend.needs_regeneration():
163 self.module_backend.generate_csr()
164 self.changed = True
165
166 def dump(self) -> dict[str, t.Any]:
167 """Serialize the object into a dictionary."""
168 result = self.module_backend.dump(include_csr=True)
169 result.update(
170 {
171 "changed": self.changed,
172 }
173 )
174 return result
175
176
177 def main() -> t.NoReturn:
178 argument_spec = get_csr_argument_spec()
179 argument_spec.argument_spec.update(
180 {
181 "content": {"type": "str"},
182 }
183 )
184 module = argument_spec.create_ansible_module(
185 supports_check_mode=True,
186 )
187
188 try:
189 module_backend = select_backend(module)
190
191 csr = CertificateSigningRequestModule(module, module_backend)
192 csr.generate(module)
193 result = csr.dump()
194 module.exit_json(**result)
195 except OpenSSLObjectError as exc:
196 module.fail_json(msg=str(exc))
197
198
199 if __name__ == "__main__":
200 main()