Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # Copyright (c) 2019, Patrick Pichler <[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_signature
10 version_added: 1.1.0
11 short_description: Sign data with openssl
12 description:
13 - This module allows one to sign data using a private key.
14 - The module uses the cryptography Python library.
15 author:
16 - Patrick Pichler (@aveexy)
17 - Markus Teufelberger (@MarkusTeufelberger)
18 extends_documentation_fragment:
19 - community.crypto._attributes
20 - community.crypto._cryptography_dep.minimum
21 attributes:
22 check_mode:
23 support: full
24 details:
25 - This action does not modify state.
26 diff_mode:
27 support: none
28 idempotent:
29 support: partial
30 details:
31 - Signature algorithms are generally not deterministic. Thus the generated signature
32 can change from one invocation to the next.
33 options:
34 privatekey_path:
35 description:
36 - The path to the private key to use when signing.
37 - Either O(privatekey_path) or O(privatekey_content) must be specified, but not both.
38 type: path
39 privatekey_content:
40 description:
41 - The content of the private key to use when signing the certificate signing request.
42 - Either O(privatekey_path) or O(privatekey_content) must be specified, but not both.
43 type: str
44 privatekey_passphrase:
45 description:
46 - The passphrase for the private key.
47 - This is required if the private key is password protected.
48 type: str
49 path:
50 description:
51 - The file to sign.
52 - This file will only be read and not modified.
53 type: path
54 required: true
55 select_crypto_backend:
56 description:
57 - Determines which crypto backend to use.
58 - The default choice is V(auto), which tries to use C(cryptography) if available.
59 - If set to V(cryptography), will try to use the L(cryptography,https://cryptography.io/) library.
60 - Note that with community.crypto 3.0.0, all values behave the same.
61 This option will be deprecated in a later version.
62 We recommend to not set it explicitly.
63 type: str
64 default: auto
65 choices: [auto, cryptography]
66 seealso:
67 - module: community.crypto.openssl_signature_info
68 - module: community.crypto.openssl_privatekey
69 """
70
71 EXAMPLES = r"""
72 ---
73 - name: Sign example file
74 community.crypto.openssl_signature:
75 privatekey_path: private.key
76 path: /tmp/example_file
77 register: sig
78
79 - name: Verify signature of example file
80 community.crypto.openssl_signature_info:
81 certificate_path: cert.pem
82 path: /tmp/example_file
83 signature: "{{ sig.signature }}"
84 register: verify
85
86 - name: Make sure the signature is valid
87 ansible.builtin.assert:
88 that:
89 - verify.valid
90 """
91
92 RETURN = r"""
93 signature:
94 description: Base64 encoded signature.
95 returned: success
96 type: str
97 """
98
99 import base64
100 import os
101 import typing as t
102
103 from ansible_collections.community.crypto.plugins.module_utils._cryptography_dep import (
104 COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION,
105 assert_required_cryptography_version,
106 )
107 from ansible_collections.community.crypto.plugins.module_utils._version import (
108 LooseVersion,
109 )
110
111 MINIMAL_CRYPTOGRAPHY_VERSION = COLLECTION_MINIMUM_CRYPTOGRAPHY_VERSION
112
113 try:
114 import cryptography
115 import cryptography.hazmat.primitives.asymmetric.padding
116 import cryptography.hazmat.primitives.hashes
117
118 except ImportError:
119 CRYPTOGRAPHY_VERSION = LooseVersion("0.0") # pylint: disable=invalid-name
120 else:
121 # pylint: disable-next=invalid-name
122 CRYPTOGRAPHY_VERSION = LooseVersion(cryptography.__version__)
123
124 from ansible.module_utils.basic import AnsibleModule
125
126 from ansible_collections.community.crypto.plugins.module_utils._crypto.basic import (
127 OpenSSLObjectError,
128 )
129 from ansible_collections.community.crypto.plugins.module_utils._crypto.support import (
130 OpenSSLObject,
131 load_privatekey,
132 )
133
134
135 class SignatureBase(OpenSSLObject):
136 def __init__(self, module: AnsibleModule) -> None:
137 super().__init__(
138 path=module.params["path"],
139 state="present",
140 force=False,
141 check_mode=module.check_mode,
142 )
143
144 self.module = module
145 self.privatekey_path: str | None = module.params["privatekey_path"]
146 privatekey_content: str | None = module.params["privatekey_content"]
147 if privatekey_content is not None:
148 self.privatekey_content: bytes | None = privatekey_content.encode("utf-8")
149 else:
150 self.privatekey_content = None
151 self.privatekey_passphrase: str | None = module.params["privatekey_passphrase"]
152
153 def generate(self, module: AnsibleModule) -> None:
154 # Empty method because OpenSSLObject wants this
155 pass
156
157 def dump(self) -> dict[str, t.Any]:
158 # Empty method because OpenSSLObject wants this
159 return {}
160
161
162 # Implementation with using cryptography
163 class SignatureCryptography(SignatureBase):
164 def __init__(self, module: AnsibleModule) -> None:
165 super().__init__(module)
166
167 def run(self) -> dict[str, t.Any]:
168 _padding = cryptography.hazmat.primitives.asymmetric.padding.PKCS1v15()
169 _hash = cryptography.hazmat.primitives.hashes.SHA256()
170
171 result: dict[str, t.Any] = {}
172
173 try:
174 with open(self.path, "rb") as f:
175 _in = f.read()
176
177 private_key = load_privatekey(
178 path=self.privatekey_path,
179 content=self.privatekey_content,
180 passphrase=self.privatekey_passphrase,
181 )
182
183 signature = None
184
185 if isinstance(
186 private_key,
187 cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKey,
188 ):
189 signature = private_key.sign(_in, _hash)
190
191 elif isinstance(
192 private_key,
193 cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey,
194 ):
195 signature = private_key.sign(
196 _in, cryptography.hazmat.primitives.asymmetric.ec.ECDSA(_hash)
197 )
198
199 elif isinstance(
200 private_key,
201 (
202 cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey,
203 cryptography.hazmat.primitives.asymmetric.ed448.Ed448PrivateKey,
204 ),
205 ):
206 signature = private_key.sign(_in)
207
208 elif isinstance(
209 private_key,
210 cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey,
211 ):
212 signature = private_key.sign(_in, _padding, _hash)
213
214 if signature is None:
215 self.module.fail_json(
216 msg=f"Unsupported key type. Your cryptography version is {CRYPTOGRAPHY_VERSION}"
217 )
218
219 result["signature"] = base64.b64encode(signature)
220 return result
221
222 except Exception as e:
223 raise OpenSSLObjectError(e) from e
224
225
226 def main() -> t.NoReturn:
227 module = AnsibleModule(
228 argument_spec={
229 "privatekey_path": {"type": "path"},
230 "privatekey_content": {"type": "str", "no_log": True},
231 "privatekey_passphrase": {"type": "str", "no_log": True},
232 "path": {"type": "path", "required": True},
233 "select_crypto_backend": {
234 "type": "str",
235 "choices": ["auto", "cryptography"],
236 "default": "auto",
237 },
238 },
239 mutually_exclusive=(["privatekey_path", "privatekey_content"],),
240 required_one_of=(["privatekey_path", "privatekey_content"],),
241 supports_check_mode=True,
242 )
243
244 if not os.path.isfile(module.params["path"]):
245 module.fail_json(
246 name=module.params["path"],
247 msg=f"The file {module.params['path']} does not exist",
248 )
249
250 assert_required_cryptography_version(
251 module, minimum_cryptography_version=MINIMAL_CRYPTOGRAPHY_VERSION
252 )
253
254 try:
255 _sign = SignatureCryptography(module)
256
257 result = _sign.run()
258
259 module.exit_json(**result)
260 except OpenSSLObjectError as exc:
261 module.fail_json(msg=str(exc))
262
263
264 if __name__ == "__main__":
265 main()