Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_keyvaultsecuritydomain.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2024 Bill Peck, <[email protected]>
4 #
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
11 DOCUMENTATION = '''
12 ---
13 module: azure_rm_keyvaultsecuritydomain
14 version_added: "3.0.0"
15 short_description: Manage Key Vault security domain for HSM
16 description:
17 - Create and delete instance of Key Vault Security Domain.
18
19 options:
20 keyvault_uri:
21 description:
22 - URI of the keyvault endpoint.
23 type: str
24 hsm_name:
25 description:
26 - Name of the HSM.
27 type: str
28 sd_quorum:
29 description:
30 - The minimum number of shares required to decrypt the security domain for recovery.
31 - The quorum of security domain should be in range [2, 10].
32 required: True
33 type: int
34 sd_wrapping_keys:
35 description:
36 - List of wrapping keys containing public keys.
37 - The number of wrapping keys should be in range [3, 10].
38 required: True
39 type: list
40 elements: str
41 no_wait:
42 description:
43 - Don't wait for the operation to finish
44 type: bool
45 default: False
46 action:
47 description:
48 - Action to take on Security Domain. Use C(download) to download security domain file and C(upload) to restore the HSM.
49 default: download
50 type: str
51 choices:
52 - download
53 - upload
54
55 extends_documentation_fragment:
56 - azure.azcollection.azure
57
58 author:
59 - Bill Peck (@p3ck)
60
61 '''
62
63 EXAMPLES = '''
64 - name: Download Security domain file
65 azure_rm_keyvaultsecuritydomain:
66 keyvault_uri: https://samplehsmvault.managedhsm.azure.net
67 sd_quorum: 2
68 sd_wrapping_keys:
69 - "{{ lookup('file', 'certfile1') }}"
70 - "{{ lookup('file', 'certfile2') }}"
71 - "{{ lookup('file', 'certfile3') }}"
72 action: download
73
74 - name: Upload Security domain
75 azure_rm_keyvaultsecuritydomain:
76 keyvault_uri: https://samplehsmvault.managedhsm.azure.net
77 action: upload
78 '''
79
80 RETURN = '''
81 security_domain:
82 description:
83 - JSON blob
84 returned: always
85 type: str
86 '''
87
88 import time
89 import codecs
90 import hashlib
91 import traceback
92 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
93 from ansible.module_utils.basic import missing_required_lib
94 from ansible_collections.azure.azcollection.plugins.module_utils.security_domain_utils import Utils
95
96
97 try:
98 from cryptography.x509 import load_pem_x509_certificate
99 from cryptography.hazmat.backends import default_backend
100 from cryptography.hazmat.primitives.serialization import Encoding
101 HAS_CRYPTO = True
102 HAS_CRYPTO_EXC = None
103 except ImportError:
104 load_pem_x509_certificate = None
105 default_backend = None
106 Encoding = None
107 HAS_CRYPTO = False
108 HAS_CRYPTO_EXC = traceback.format_exc()
109
110
111 try:
112 from azure.keyvault.securitydomain import SecurityDomainClient
113 from azure.keyvault.securitydomain.models import CertificateInfo, SecurityDomainJsonWebKey
114 except ImportError:
115 CertificateInfo = None
116 SecurityDomainJsonWebKey = None
117 SecurityDomainClient = None
118
119
120 class AzureRMVaultSecurityDomain(AzureRMModuleBaseExt):
121 """Configuration class for an Azure RM Vault Security Domain resource"""
122
123 def __init__(self):
124 self.module_arg_spec = dict(
125 keyvault_uri=dict(
126 no_log=True,
127 type='str'
128 ),
129 hsm_name=dict(
130 type='str'
131 ),
132 sd_wrapping_keys=dict(
133 type='list',
134 required=True,
135 no_log=True,
136 elements='str'
137 ),
138 sd_quorum=dict(
139 type='int',
140 required=True
141 ),
142 no_wait=dict(
143 type='bool',
144 default=False
145 ),
146 action=dict(
147 type='str',
148 default='download',
149 choices=['download', 'upload']
150 )
151 )
152
153 self.module_required_if = []
154
155 self.keyvault_uri = None
156 self.hsm_name = None
157
158 self.results = dict(changed=False)
159 self.client = None
160 self.action = None
161 self.sd_wrapping_keys = []
162 self.sd_quorum = None
163 self.no_wait = False
164
165 required_one_of = [('keyvault_uri', 'hsm_name')]
166
167 super(AzureRMVaultSecurityDomain, self).__init__(derived_arg_spec=self.module_arg_spec,
168 supports_check_mode=False,
169 supports_tags=False,
170 required_one_of=required_one_of,
171 required_if=self.module_required_if)
172
173 if not HAS_CRYPTO:
174 self.fail(msg=missing_required_lib('cryptography'),
175 exception=HAS_CRYPTO_EXC)
176
177 def exec_module(self, **kwargs):
178 """Main module execution method"""
179
180 # translate Ansible input to SDK-formatted dict in self.parameters
181 for key in list(self.module_arg_spec.keys()):
182 if hasattr(self, key):
183 setattr(self, key, kwargs[key])
184
185 vault_base_url = self.hsm_name or self.keyvault_uri
186 self.client = SecurityDomainClient(vault_base_url, credential=self.azure_auth.azure_credential_track2)
187
188 response = None
189 if self.action == 'download':
190 response = self.security_domain_download()
191
192 if response:
193 self.results["security_domain"] = response.value
194
195 return self.results
196
197 def security_domain_download(self):
198
199 N = len(self.sd_wrapping_keys)
200 if N < 3 or N > 10:
201 self.fail('The number of wrapping keys {0} should be in range [3, 10].'.format(N))
202 if self.sd_quorum < 2 or self.sd_quorum > 10:
203 self.fail('The quorum of security domain {0} should be in range [2, 10].'.format(self.sd_quorum))
204
205 certificates = []
206 for pem_string in self.sd_wrapping_keys:
207 pem_data = pem_string.encode('UTF-8')
208
209 cert = load_pem_x509_certificate(pem_data, backend=default_backend())
210 public_key = cert.public_key()
211 public_bytes = cert.public_bytes(Encoding.DER)
212 x5c = [Utils.security_domain_b64_url_encode_for_x5c(public_bytes)] # only one cert, not a chain
213 x5t = Utils.security_domain_b64_url_encode(hashlib.sha1(public_bytes).digest())
214 x5tS256 = Utils.security_domain_b64_url_encode(hashlib.sha256(public_bytes).digest())
215 key_ops = ["verify", "encrypt", "wrapKey"]
216
217 # populate key into jwk
218 kty = "RSA"
219 alg = "RSA-OAEP-256"
220 n, e = _public_rsa_key_to_jwk(public_key, encoding=Utils.security_domain_b64_url_encode)
221
222 certificates.append(
223 SecurityDomainJsonWebKey(
224 kid=cert.subject.rfc4514_string(),
225 kty=kty,
226 key_ops=key_ops,
227 n=n,
228 e=e,
229 x5_c=x5c,
230 alg=alg,
231 x5_t=x5t,
232 x5_t_s256=x5tS256,
233 )
234 )
235
236 certs_object = CertificateInfo(certificates=certificates, required=self.sd_quorum)
237
238 poller = self.client.begin_download(certificate_info=certs_object, skip_activation_polling=True)
239 security_domain = poller.result()
240
241 if not self.no_wait:
242 wait_second = 5
243 time.sleep(wait_second)
244 polling_ret = _wait_security_domain_operation(self.client,
245 'download')
246 if polling_ret is None or getattr(polling_ret, 'status', None) == 'Failed':
247 self.fail('Status: {0}'.format(polling_ret))
248
249 return security_domain
250
251
252 def _int_to_bytes(i):
253 h = hex(i)
254 if len(h) > 1 and h[0:2] == '0x':
255 h = h[2:]
256 # need to strip L in python 2.x
257 h = h.strip('L')
258 if len(h) % 2:
259 h = '0' + h
260 return codecs.decode(h, 'hex')
261
262
263 def _public_rsa_key_to_jwk(rsa_key, encoding=None):
264 public_numbers = rsa_key.public_numbers()
265 n = _int_to_bytes(public_numbers.n)
266 if encoding:
267 n = encoding(n)
268 e = _int_to_bytes(public_numbers.e)
269 if encoding:
270 e = encoding(e)
271 return (n, e)
272
273
274 def _wait_security_domain_operation(client, target_operation='upload'):
275 retries = 0
276 max_retries = 30
277 wait_second = 10
278 while retries < max_retries:
279 try:
280 ret = None
281 if target_operation == 'upload':
282 ret = client.get_upload_status()
283 elif target_operation == 'download':
284 ret = client.get_download_status()
285
286 # v7.2-preview and v7.2 will change the upload operation from Sync to Async
287 # due to service defects, it returns 'Succeeded' before the change and 'Success' after the change
288 if ret and getattr(ret, 'status', None) in ['Succeeded', 'Success', 'Failed']:
289 return ret
290 except Exception:
291 pass
292 time.sleep(wait_second)
293 retries += 1
294
295 return None
296
297
298 def main():
299 """Main execution"""
300 AzureRMVaultSecurityDomain()
301
302
303 if __name__ == '__main__':
304 main()