Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # Copyright (c) 2016-2017, Yanis Guenane <[email protected]>
3 # Copyright (c) 2017, Markus Teufelberger <[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_privatekey_info
11 short_description: Provide information for OpenSSL private keys
12 description:
13 - This module allows one to query information on OpenSSL private keys.
14 - In case the key consistency checks fail, the module will fail as this indicates a faked private key. In this case, all
15 return variables are still returned. Note that key consistency checks are not available all key types; if none is available,
16 V(none) is returned for RV(key_is_consistent).
17 - It uses the cryptography python library to interact with OpenSSL.
18 author:
19 - Felix Fontein (@felixfontein)
20 - Yanis Guenane (@Spredzy)
21 extends_documentation_fragment:
22 - community.crypto._attributes
23 - community.crypto._attributes.info_module
24 - community.crypto._attributes.idempotent_not_modify_state
25 - community.crypto._cryptography_dep.minimum
26 options:
27 path:
28 description:
29 - Remote absolute path where the private key file is loaded from.
30 type: path
31 content:
32 description:
33 - Content of the private key file.
34 - Either O(path) or O(content) must be specified, but not both.
35 type: str
36 version_added: '1.0.0'
37 passphrase:
38 description:
39 - The passphrase for the private key.
40 type: str
41 return_private_key_data:
42 description:
43 - Whether to return private key data.
44 - Only set this to V(true) when you want private information about this key to leave the remote machine.
45 - B(WARNING:) you have to make sure that private key data is not accidentally logged!
46 type: bool
47 default: false
48 check_consistency:
49 description:
50 - Whether to check consistency of the private key.
51 - In community.crypto < 2.0.0, consistency was always checked.
52 - Since community.crypto 2.0.0, the consistency check has been disabled by default to avoid private key material to
53 be transported around and computed with, and only do so when requested explicitly. This can potentially prevent L(side-channel
54 attacks,https://en.wikipedia.org/wiki/Side-channel_attack).
55 - Note that consistency checks only work for certain key types, and might depend on the version of the cryptography
56 library. For example, with cryptography 42.0.0 and newer consistency of RSA keys can no longer be checked.
57 type: bool
58 default: false
59 version_added: 2.0.0
60
61 select_crypto_backend:
62 description:
63 - Determines which crypto backend to use.
64 - The default choice is V(auto), which tries to use C(cryptography) if available.
65 - If set to V(cryptography), will try to use the L(cryptography,https://cryptography.io/) library.
66 - Note that with community.crypto 3.0.0, all values behave the same.
67 This option will be deprecated in a later version.
68 We recommend to not set it explicitly.
69 type: str
70 default: auto
71 choices: [auto, cryptography]
72
73 seealso:
74 - module: community.crypto.openssl_privatekey
75 - module: community.crypto.openssl_privatekey_pipe
76 - plugin: community.crypto.openssl_privatekey_info
77 plugin_type: filter
78 description: A filter variant of this module.
79 """
80
81 EXAMPLES = r"""
82 ---
83 - name: Generate an OpenSSL private key with the default values (4096 bits, RSA)
84 community.crypto.openssl_privatekey:
85 path: /etc/ssl/private/ansible.com.pem
86
87 - name: Get information on generated key
88 community.crypto.openssl_privatekey_info:
89 path: /etc/ssl/private/ansible.com.pem
90 register: result
91
92 - name: Dump information
93 ansible.builtin.debug:
94 var: result
95 """
96
97 RETURN = r"""
98 can_load_key:
99 description: Whether the module was able to load the private key from disk.
100 returned: always
101 type: bool
102 can_parse_key:
103 description: Whether the module was able to parse the private key.
104 returned: always
105 type: bool
106 key_is_consistent:
107 description:
108 - Whether the key is consistent. Can also return V(none) next to V(true) and V(false), to indicate that consistency could
109 not be checked.
110 - In case the check returns V(false), the module will fail.
111 returned: when O(check_consistency=true)
112 type: bool
113 public_key:
114 description: Private key's public key in PEM format.
115 returned: success
116 type: str
117 sample: "-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8A..."
118 public_key_fingerprints:
119 description:
120 - Fingerprints of private key's public key.
121 - For every hash algorithm available, the fingerprint is computed.
122 returned: success
123 type: dict
124 sample: "{'sha256': 'd4:b3:aa:6d:c8:04:ce:4e:ba:f6:29:4d:92:a3:94:b0:c2:ff:bd:bf:33:63:11:43:34:0f:51:b0:95:09:2f:63', 'sha512':
125 'f7:07:4a:f0:b0:f0:e6:8b:95:5f:f9:e6:61:0a:32:68:f1..."
126 type:
127 description:
128 - The key's type.
129 - One of V(RSA), V(DSA), V(ECC), V(Ed25519), V(X25519), V(Ed448), or V(X448).
130 - Will start with V(unknown) if the key type cannot be determined.
131 returned: success
132 type: str
133 sample: RSA
134 public_data:
135 description:
136 - Public key data. Depends on key type.
137 returned: success
138 type: dict
139 contains:
140 size:
141 description:
142 - Bit size of modulus (RSA) or prime number (DSA).
143 type: int
144 returned: When RV(type=RSA) or RV(type=DSA)
145 modulus:
146 description:
147 - The RSA key's modulus.
148 type: int
149 returned: When RV(type=RSA)
150 exponent:
151 description:
152 - The RSA key's public exponent.
153 type: int
154 returned: When RV(type=RSA)
155 p:
156 description:
157 - The C(p) value for DSA.
158 - This is the prime modulus upon which arithmetic takes place.
159 type: int
160 returned: When RV(type=DSA)
161 q:
162 description:
163 - The C(q) value for DSA.
164 - This is a prime that divides C(p - 1), and at the same time the order of the subgroup of the multiplicative group
165 of the prime field used.
166 type: int
167 returned: When RV(type=DSA)
168 g:
169 description:
170 - The C(g) value for DSA.
171 - This is the element spanning the subgroup of the multiplicative group of the prime field used.
172 type: int
173 returned: When RV(type=DSA)
174 curve:
175 description:
176 - The curve's name for ECC.
177 type: str
178 returned: When RV(type=ECC)
179 exponent_size:
180 description:
181 - The maximum number of bits of a private key. This is basically the bit size of the subgroup used.
182 type: int
183 returned: When RV(type=ECC)
184 x:
185 description:
186 - The C(x) coordinate for the public point on the elliptic curve.
187 type: int
188 returned: When RV(type=ECC)
189 y:
190 description:
191 - For RV(type=ECC), this is the C(y) coordinate for the public point on the elliptic curve.
192 - For RV(type=DSA), this is the publicly known group element whose discrete logarithm w.r.t. C(g) is the private key.
193 type: int
194 returned: When RV(type=DSA) or RV(type=ECC)
195 private_data:
196 description:
197 - Private key data. Depends on key type.
198 returned: success and when O(return_private_key_data) is set to V(true)
199 type: dict
200 """
201
202 import typing as t
203
204 from ansible.module_utils.basic import AnsibleModule
205
206 from ansible_collections.community.crypto.plugins.module_utils._crypto.basic import (
207 OpenSSLObjectError,
208 )
209 from ansible_collections.community.crypto.plugins.module_utils._crypto.module_backends.privatekey_info import (
210 PrivateKeyConsistencyError,
211 PrivateKeyParseError,
212 select_backend,
213 )
214
215
216 def main() -> t.NoReturn:
217 module = AnsibleModule(
218 argument_spec={
219 "path": {"type": "path"},
220 "content": {"type": "str", "no_log": True},
221 "passphrase": {"type": "str", "no_log": True},
222 "return_private_key_data": {"type": "bool", "default": False},
223 "check_consistency": {"type": "bool", "default": False},
224 "select_crypto_backend": {
225 "type": "str",
226 "default": "auto",
227 "choices": ["auto", "cryptography"],
228 },
229 },
230 required_one_of=(["path", "content"],),
231 mutually_exclusive=(["path", "content"],),
232 supports_check_mode=True,
233 )
234
235 result = {
236 "can_load_key": False,
237 "can_parse_key": False,
238 "key_is_consistent": None,
239 }
240
241 if module.params["content"] is not None:
242 data = module.params["content"].encode("utf-8")
243 else:
244 try:
245 with open(module.params["path"], "rb") as f:
246 data = f.read()
247 except (IOError, OSError) as e:
248 module.fail_json(
249 msg=f"Error while reading private key file from disk: {e}",
250 **result, # type: ignore
251 )
252
253 result["can_load_key"] = True
254
255 module_backend = select_backend(
256 module=module,
257 content=data,
258 passphrase=module.params["passphrase"],
259 return_private_key_data=module.params["return_private_key_data"],
260 check_consistency=module.params["check_consistency"],
261 )
262
263 try:
264 result.update(module_backend.get_info())
265 module.exit_json(**result)
266 except PrivateKeyParseError as exc:
267 result.update(exc.result)
268 module.fail_json(msg=exc.error_message, **result) # type: ignore
269 except PrivateKeyConsistencyError as exc:
270 result.update(exc.result)
271 module.fail_json(msg=exc.error_message, **result) # type: ignore
272 except OpenSSLObjectError as exc:
273 module.fail_json(msg=str(exc))
274
275
276 if __name__ == "__main__":
277 main()