Debian Codegraph @

lib/ansible/parsing/vault/__init__.py

raw
1 # (c) 2014, James Tanner <[email protected]>
2 # (c) 2016, Adrian Likins <[email protected]>
3 # (c) 2016 Toshio Kuratomi <[email protected]>
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import annotations
19
20 import fcntl
21 import functools
22 import os
23 import random
24 import shlex
25 import shutil
26 import subprocess
27 import sys
28 import tempfile
29 import warnings
30 import typing as t
31
32 from binascii import hexlify
33 from binascii import unhexlify
34 from binascii import Error as BinasciiError
35
36 from ansible.module_utils._internal._datatag import (
37 AnsibleTagHelper, AnsibleTaggedObject, _AnsibleTagsMapping, _EmptyROInternalTagsMapping, _EMPTY_INTERNAL_TAGS_MAPPING,
38 )
39 from ansible.module_utils.secrets import register_secret
40 from ansible._internal._templating import _jinja_common
41 from ansible._internal._datatag._tags import Origin, VaultedValue, TrustedAsTemplate
42
43 HAS_CRYPTOGRAPHY = False
44 CRYPTOGRAPHY_BACKEND = None
45 try:
46 with warnings.catch_warnings():
47 warnings.simplefilter("ignore", DeprecationWarning)
48 from cryptography.exceptions import InvalidSignature
49 from cryptography.hazmat.backends import default_backend
50 from cryptography.hazmat.primitives import hashes, padding
51 from cryptography.hazmat.primitives.hmac import HMAC
52 from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
53 from cryptography.hazmat.primitives.ciphers import (
54 Cipher as C_Cipher, algorithms, modes
55 )
56 CRYPTOGRAPHY_BACKEND = default_backend()
57 HAS_CRYPTOGRAPHY = True
58 except ImportError:
59 pass
60
61 from ansible.errors import AnsibleError, AnsibleAssertionError
62 from ansible import constants as C
63 from ansible.module_utils.common.text.converters import to_bytes, to_text, to_native
64 from ansible.utils.display import Display
65 from ansible.utils.path import makedirs_safe, unfrackpath
66
67 display = Display()
68
69
70 b_HEADER = b'$ANSIBLE_VAULT'
71 CIPHER_ALLOWLIST = frozenset((u'AES256',))
72 CIPHER_WRITE_ALLOWLIST = frozenset((u'AES256',))
73 # See also CIPHER_MAPPING at the bottom of the file which maps cipher strings
74 # (used in VaultFile header) to a cipher class
75
76 NEED_CRYPTO_LIBRARY = "ansible-vault requires the cryptography library in order to function"
77
78
79 class AnsibleVaultError(AnsibleError):
80 pass
81
82
83 class AnsibleVaultPasswordError(AnsibleVaultError):
84 pass
85
86
87 class AnsibleVaultFormatError(AnsibleError):
88 pass
89
90
91 def is_encrypted(data):
92 """ Test if this is vault encrypted data blob
93
94 :arg data: a byte or text string to test whether it is recognized as vault
95 encrypted data
96 :returns: True if it is recognized. Otherwise, False.
97 """
98 try:
99 # Make sure we have a byte string and that it only contains ascii
100 # bytes.
101 b_data = to_bytes(to_text(data, encoding='ascii', errors='strict', nonstring='strict'), encoding='ascii', errors='strict')
102 except (UnicodeError, TypeError):
103 # The vault format is pure ascii so if we failed to encode to bytes
104 # via ascii we know that this is not vault data.
105 # Similarly, if it's not a string, it's not vault data
106 return False
107
108 if b_data.startswith(b_HEADER):
109 return True
110 return False
111
112
113 def is_encrypted_file(file_obj, start_pos=0, count=len(b_HEADER)):
114 """Test if the contents of a file obj are a vault encrypted data blob.
115
116 :arg file_obj: A file object that will be read from.
117 :kwarg start_pos: A byte offset in the file to start reading the header
118 from. Defaults to 0, the beginning of the file.
119 :kwarg count: Read up to this number of bytes from the file to determine
120 if it looks like encrypted vault data. The default is the size of the
121 the vault header, which is what is needed most times.
122 For some IO classes, or files that don't begin with the vault itself,
123 set to -1 to read to the end of file.
124 :returns: True if the file looks like a vault file. Otherwise, False.
125 """
126 # read the header and reset the file stream to where it started
127 current_position = file_obj.tell()
128 try:
129 file_obj.seek(start_pos)
130 return is_encrypted(file_obj.read(count))
131
132 finally:
133 file_obj.seek(current_position)
134
135
136 def _parse_vaulttext_envelope(b_vaulttext_envelope, default_vault_id=None):
137
138 b_tmpdata = b_vaulttext_envelope.splitlines()
139 b_tmpheader = b_tmpdata[0].strip().split(b';')
140
141 b_version = b_tmpheader[1].strip()
142 cipher_name = to_text(b_tmpheader[2].strip())
143 vault_id = default_vault_id
144
145 # Only attempt to find vault_id if the vault file is version 1.2 or newer
146 # if self.b_version == b'1.2':
147 if len(b_tmpheader) >= 4:
148 vault_id = to_text(b_tmpheader[3].strip())
149
150 b_ciphertext = b''.join(b_tmpdata[1:])
151 # DTFIX7: possible candidate for propagate_origin
152 b_ciphertext = AnsibleTagHelper.tag_copy(b_vaulttext_envelope, b_ciphertext)
153
154 return b_ciphertext, b_version, cipher_name, vault_id
155
156
157 def parse_vaulttext_envelope(b_vaulttext_envelope, default_vault_id=None):
158 """Parse the vaulttext envelope
159
160 When data is saved, it has a header prepended and is formatted into 80
161 character lines. This method extracts the information from the header
162 and then removes the header and the inserted newlines. The string returned
163 is suitable for processing by the Cipher classes.
164
165 :arg b_vaulttext_envelope: byte str containing the data from a save file
166 :arg default_vault_id: The vault_id name to use if the vaulttext does not provide one.
167 :returns: A tuple of byte str of the vaulttext suitable to pass to parse_vaultext,
168 a byte str of the vault format version,
169 the name of the cipher used, and the vault_id.
170 :raises: AnsibleVaultFormatError: if the vaulttext_envelope format is invalid
171 """
172 # used by decrypt
173 default_vault_id = default_vault_id or C.DEFAULT_VAULT_IDENTITY
174
175 try:
176 return _parse_vaulttext_envelope(b_vaulttext_envelope, default_vault_id)
177 except Exception as ex:
178 raise AnsibleVaultFormatError("Vault envelope format error.", obj=b_vaulttext_envelope) from ex
179
180
181 def format_vaulttext_envelope(b_ciphertext, cipher_name, version=None, vault_id=None):
182 """ Add header and format to 80 columns
183
184 :arg b_ciphertext: the encrypted and hexlified data as a byte string
185 :arg cipher_name: unicode cipher name (for ex, u'AES256')
186 :arg version: unicode vault version (for ex, '1.2'). Optional ('1.1' is default)
187 :arg vault_id: unicode vault identifier. If provided, the version will be bumped to 1.2.
188 :returns: a byte str that should be dumped into a file. It's
189 formatted to 80 char columns and has the header prepended
190 """
191
192 if not cipher_name:
193 raise AnsibleError("the cipher must be set before adding a header")
194
195 version = version or '1.1'
196
197 # If we specify a vault_id, use format version 1.2. For no vault_id, stick to 1.1
198 if vault_id and vault_id != u'default':
199 version = '1.2'
200
201 b_version = to_bytes(version, 'utf-8', errors='strict')
202 b_vault_id = to_bytes(vault_id, 'utf-8', errors='strict')
203 b_cipher_name = to_bytes(cipher_name, 'utf-8', errors='strict')
204
205 header_parts = [b_HEADER,
206 b_version,
207 b_cipher_name]
208
209 if b_version == b'1.2' and b_vault_id:
210 header_parts.append(b_vault_id)
211
212 header = b';'.join(header_parts)
213
214 b_vaulttext = [header]
215 b_vaulttext += [b_ciphertext[i:i + 80] for i in range(0, len(b_ciphertext), 80)]
216 b_vaulttext += [b'']
217 b_vaulttext = b'\n'.join(b_vaulttext)
218
219 return b_vaulttext
220
221
222 def _unhexlify(b_data):
223 try:
224 # DTFIX7: possible candidate for propagate_origin
225 return AnsibleTagHelper.tag_copy(b_data, unhexlify(b_data))
226 except (BinasciiError, TypeError) as ex:
227 raise AnsibleVaultFormatError('Vault format unhexlify error.', obj=b_data) from ex
228
229
230 def _parse_vaulttext(b_vaulttext):
231 b_vaulttext = _unhexlify(b_vaulttext)
232 b_salt, b_crypted_hmac, b_ciphertext = b_vaulttext.split(b"\n", 2)
233 b_salt = _unhexlify(b_salt)
234 b_ciphertext = _unhexlify(b_ciphertext)
235
236 return b_ciphertext, b_salt, b_crypted_hmac
237
238
239 def parse_vaulttext(b_vaulttext):
240 """Parse the vaulttext
241
242 :arg b_vaulttext: byte str containing the vaulttext (ciphertext, salt, crypted_hmac)
243 :returns: A tuple of byte str of the ciphertext suitable for passing to a
244 Cipher class's decrypt() function, a byte str of the salt,
245 and a byte str of the crypted_hmac
246 :raises: AnsibleVaultFormatError: if the vaulttext format is invalid
247 """
248 # SPLIT SALT, DIGEST, AND DATA
249 try:
250 return _parse_vaulttext(b_vaulttext)
251 except AnsibleVaultFormatError:
252 raise
253 except Exception as ex:
254 raise AnsibleVaultFormatError("Vault vaulttext format error.", obj=b_vaulttext) from ex
255
256
257 def verify_secret_is_not_empty(secret, msg=None):
258 """Check the secret against minimal requirements.
259
260 Raises: AnsibleVaultPasswordError if the password does not meet requirements.
261
262 Currently, only requirement is that the password is not None or an empty string.
263 """
264 msg = msg or 'Invalid vault password was provided'
265 if not secret:
266 raise AnsibleVaultPasswordError(msg)
267
268
269 class VaultSecret:
270 """Opaque/abstract objects for a single vault secret. ie, a password or a key."""
271
272 def __init__(self, _bytes=None):
273 # FIXME: ? that seems wrong... Unset etc?
274 self._bytes = _bytes
275
276 @property
277 def bytes(self):
278 """The secret as a bytestring.
279
280 Sub classes that store text types will need to override to encode the text to bytes.
281 """
282 return self._bytes
283
284 def load(self):
285 return self._bytes
286
287
288 class PromptVaultSecret(VaultSecret):
289 default_prompt_formats = ["Vault password (%s): "]
290
291 def __init__(self, _bytes=None, vault_id=None, prompt_formats=None):
292 super(PromptVaultSecret, self).__init__(_bytes=_bytes)
293 self.vault_id = vault_id
294
295 if prompt_formats is None:
296 self.prompt_formats = self.default_prompt_formats
297 else:
298 self.prompt_formats = prompt_formats
299
300 @property
301 def bytes(self):
302 return self._bytes
303
304 def load(self):
305 self._bytes = self.ask_vault_passwords()
306
307 def ask_vault_passwords(self):
308 b_vault_passwords = []
309
310 for prompt_format in self.prompt_formats:
311 prompt = prompt_format % {'vault_id': self.vault_id}
312 try:
313 vault_pass = display.prompt(prompt, private=True)
314 except EOFError:
315 raise AnsibleVaultError('EOFError (ctrl-d) on prompt for (%s)' % self.vault_id)
316
317 verify_secret_is_not_empty(vault_pass)
318
319 b_vault_pass = to_bytes(vault_pass, errors='strict', nonstring='simplerepr').strip()
320 b_vault_passwords.append(b_vault_pass)
321
322 # Make sure the passwords match by comparing them all to the first password
323 for b_vault_password in b_vault_passwords:
324 self.confirm(b_vault_passwords[0], b_vault_password)
325
326 if b_vault_passwords:
327 register_secret(to_text(b_vault_passwords[0], errors='surrogate_or_strict'))
328 return b_vault_passwords[0]
329
330 return None
331
332 def confirm(self, b_vault_pass_1, b_vault_pass_2):
333 # enforce no newline chars at the end of passwords
334
335 if b_vault_pass_1 != b_vault_pass_2:
336 # FIXME: more specific exception
337 raise AnsibleError("Passwords do not match")
338
339
340 def script_is_client(filename):
341 """Determine if a vault secret script is a client script that can be given --vault-id args"""
342
343 # if password script is 'something-client' or 'something-client.[sh|py|rb|etc]'
344 # script_name can still have '.' or could be entire filename if there is no ext
345 script_name, dummy = os.path.splitext(filename)
346
347 # TODO: for now, this is entirely based on filename
348 if script_name.endswith('-client'):
349 return True
350
351 return False
352
353
354 def get_file_vault_secret(filename=None, vault_id=None, encoding=None, loader=None):
355 """ Get secret from file content or execute file and get secret from stdout """
356
357 # we unfrack but not follow the full path/context to possible vault script
358 # so when the script uses 'adjacent' file for configuration or similar
359 # it still works (as inventory scripts often also do).
360 # while files from --vault-password-file are already unfracked, other sources are not
361 this_path = unfrackpath(filename, follow=False)
362 if not os.path.exists(this_path):
363 raise AnsibleError("The vault password file %s was not found" % this_path)
364
365 if os.path.isdir(this_path):
366 raise AnsibleError(f"The vault password file provided '{this_path}' can not be a directory")
367
368 # it is a script?
369 if loader.is_executable(this_path):
370
371 if script_is_client(filename):
372 # this is special script type that handles vault ids
373 display.vvvv(u'The vault password file %s is a client script.' % to_text(this_path))
374 # TODO: pass vault_id_name to script via cli
375 return ClientScriptVaultSecret(filename=this_path, vault_id=vault_id, encoding=encoding, loader=loader)
376
377 # just a plain vault password script. No args, returns a byte array
378 return ScriptVaultSecret(filename=this_path, encoding=encoding, loader=loader)
379
380 return FileVaultSecret(filename=this_path, encoding=encoding, loader=loader)
381
382
383 # TODO: mv these classes to a separate file so we don't pollute vault with 'subprocess' etc
384 class FileVaultSecret(VaultSecret):
385 def __init__(self, filename=None, encoding=None, loader=None):
386 super(FileVaultSecret, self).__init__()
387 self.filename = filename
388 self.loader = loader
389
390 self.encoding = encoding or 'utf8'
391
392 # We could load from file here, but that is eventually a pain to test
393 self._bytes = None
394 self._text = None
395
396 @property
397 def bytes(self):
398 if self._bytes:
399 return self._bytes
400 if self._text:
401 return self._text.encode(self.encoding)
402 return None
403
404 def load(self):
405 self._bytes = self._read_file(self.filename)
406
407 def _read_file(self, filename):
408 """
409 Read a vault password from a file or if executable, execute the script and
410 retrieve password from STDOUT
411 """
412
413 # TODO: replace with use of self.loader
414 try:
415 with open(filename, "rb") as f:
416 vault_pass = f.read().strip()
417 except OSError as ex:
418 raise AnsibleError(f"Could not read vault password file {filename!r}.") from ex
419
420 b_vault_data, dummy = self.loader._decrypt_if_vault_data(vault_pass)
421
422 vault_pass = b_vault_data.strip(b'\r\n')
423
424 verify_secret_is_not_empty(vault_pass,
425 msg='Invalid vault password was provided from file (%s)' % filename)
426
427 register_secret(to_text(vault_pass, errors='surrogate_or_strict'))
428
429 return vault_pass
430
431 def __repr__(self):
432 if self.filename:
433 return "%s(filename='%s')" % (self.__class__.__name__, self.filename)
434 return "%s()" % (self.__class__.__name__)
435
436
437 class ScriptVaultSecret(FileVaultSecret):
438 def _read_file(self, filename):
439 if not self.loader.is_executable(filename):
440 raise AnsibleVaultError("The vault password script %s was not executable" % filename)
441
442 command = self._build_command()
443
444 stdout, stderr, p = self._run(command)
445
446 self._check_results(stdout, stderr, p)
447
448 vault_pass = stdout.strip(b'\r\n')
449
450 empty_password_msg = 'Invalid vault password was provided from script (%s)' % filename
451 verify_secret_is_not_empty(vault_pass, msg=empty_password_msg)
452
453 register_secret(to_text(vault_pass, errors='surrogate_or_strict'))
454
455 return vault_pass
456
457 def _run(self, command):
458 try:
459 # STDERR not captured to make it easier for users to prompt for input in their scripts
460 p = subprocess.Popen(command, stdout=subprocess.PIPE)
461 except OSError as e:
462 msg_format = "Problem running vault password script %s (%s)." \
463 " If this is not a script, remove the executable bit from the file."
464 msg = msg_format % (self.filename, e)
465
466 raise AnsibleError(msg)
467
468 stdout, stderr = p.communicate()
469 return stdout, stderr, p
470
471 def _check_results(self, stdout, stderr, popen):
472 if popen.returncode != 0:
473 raise AnsibleError("Vault password script %s returned non-zero (%s): %s" %
474 (self.filename, popen.returncode, stderr))
475
476 def _build_command(self):
477 return [self.filename]
478
479
480 class ClientScriptVaultSecret(ScriptVaultSecret):
481 VAULT_ID_UNKNOWN_RC = 2
482
483 def __init__(self, filename=None, encoding=None, loader=None, vault_id=None):
484 super(ClientScriptVaultSecret, self).__init__(filename=filename,
485 encoding=encoding,
486 loader=loader)
487 self._vault_id = vault_id
488 display.vvvv(u'Executing vault password client script: %s --vault-id %s' % (to_text(filename), to_text(vault_id)))
489
490 def _run(self, command):
491 try:
492 p = subprocess.Popen(command,
493 stdout=subprocess.PIPE,
494 stderr=subprocess.PIPE)
495 except OSError as e:
496 msg_format = "Problem running vault password client script %s (%s)." \
497 " If this is not a script, remove the executable bit from the file."
498 msg = msg_format % (self.filename, e)
499
500 raise AnsibleError(msg)
501
502 stdout, stderr = p.communicate()
503 return stdout, stderr, p
504
505 def _check_results(self, stdout, stderr, popen):
506 if popen.returncode == self.VAULT_ID_UNKNOWN_RC:
507 raise AnsibleError('Vault password client script %s did not find a secret for vault-id=%s: %s' %
508 (self.filename, self._vault_id, stderr))
509
510 if popen.returncode != 0:
511 raise AnsibleError("Vault password client script %s returned non-zero (%s) when getting secret for vault-id=%s: %s" %
512 (self.filename, popen.returncode, self._vault_id, stderr))
513
514 def _build_command(self):
515 command = [self.filename]
516 if self._vault_id:
517 command.extend(['--vault-id', self._vault_id])
518
519 return command
520
521 def __repr__(self):
522 if self.filename:
523 return "%s(filename='%s', vault_id='%s')" % \
524 (self.__class__.__name__, self.filename, self._vault_id)
525 return "%s()" % (self.__class__.__name__)
526
527
528 def match_secrets(secrets, target_vault_ids):
529 """Find all VaultSecret objects that are mapped to any of the target_vault_ids in secrets"""
530 if not secrets:
531 return []
532
533 matches = [(vault_id, secret) for vault_id, secret in secrets if vault_id in target_vault_ids]
534 return matches
535
536
537 def match_best_secret(secrets, target_vault_ids):
538 """Find the best secret from secrets that matches target_vault_ids
539
540 Since secrets should be ordered so the early secrets are 'better' than later ones, this
541 just finds all the matches, then returns the first secret"""
542 matches = match_secrets(secrets, target_vault_ids)
543 if matches:
544 return matches[0]
545 # raise exception?
546 return None
547
548
549 def match_encrypt_vault_id_secret(secrets, encrypt_vault_id=None):
550 # See if the --encrypt-vault-id matches a vault-id
551 display.vvvv(u'encrypt_vault_id=%s' % to_text(encrypt_vault_id))
552
553 if encrypt_vault_id is None:
554 raise AnsibleError('match_encrypt_vault_id_secret requires a non None encrypt_vault_id')
555
556 encrypt_vault_id_matchers = [encrypt_vault_id]
557 encrypt_secret = match_best_secret(secrets, encrypt_vault_id_matchers)
558
559 # return the best match for --encrypt-vault-id
560 if encrypt_secret:
561 return encrypt_secret
562
563 # If we specified a encrypt_vault_id and we couldn't find it, dont
564 # fallback to using the first/best secret
565 raise AnsibleVaultError('Did not find a match for --encrypt-vault-id=%s in the known vault-ids %s' % (encrypt_vault_id,
566 [_v for _v, _vs in secrets]))
567
568
569 def match_encrypt_secret(secrets, encrypt_vault_id=None):
570 """Find the best/first/only secret in secrets to use for encrypting"""
571
572 display.vvvv(u'encrypt_vault_id=%s' % to_text(encrypt_vault_id))
573 # See if the --encrypt-vault-id matches a vault-id
574 if encrypt_vault_id:
575 return match_encrypt_vault_id_secret(secrets,
576 encrypt_vault_id=encrypt_vault_id)
577
578 # Find the best/first secret from secrets since we didn't specify otherwise
579 # ie, consider all the available secrets as matches
580 _vault_id_matchers = [_vault_id for _vault_id, dummy in secrets]
581 best_secret = match_best_secret(secrets, _vault_id_matchers)
582
583 # can be empty list sans any tuple
584 return best_secret
585
586
587 class VaultLib:
588 def __init__(self, secrets=None):
589 self.secrets = secrets or []
590 self.cipher_name = None
591 self.b_version = b'1.2'
592
593 @staticmethod
594 def is_encrypted(vaulttext):
595 return is_encrypted(vaulttext)
596
597 def encrypt(self, plaintext, secret=None, vault_id=None, salt=None):
598 """Vault encrypt a piece of data.
599
600 :arg plaintext: a text or byte string to encrypt.
601 :returns: a utf-8 encoded byte str of encrypted data. The string
602 contains a header identifying this as vault encrypted data and
603 formatted to newline terminated lines of 80 characters. This is
604 suitable for dumping as is to a vault file.
605
606 If the string passed in is a text string, it will be encoded to UTF-8
607 before encryption.
608 """
609
610 if secret is None:
611 if self.secrets:
612 dummy, secret = match_encrypt_secret(self.secrets)
613 else:
614 raise AnsibleVaultError("A vault password must be specified to encrypt data")
615
616 b_plaintext = to_bytes(plaintext, errors='surrogate_or_strict')
617
618 if is_encrypted(b_plaintext):
619 raise AnsibleError("input is already encrypted")
620
621 if not self.cipher_name or self.cipher_name not in CIPHER_WRITE_ALLOWLIST:
622 self.cipher_name = u"AES256"
623
624 try:
625 this_cipher = CIPHER_MAPPING[self.cipher_name]()
626 except KeyError:
627 raise AnsibleError(u"{0} cipher could not be found".format(self.cipher_name))
628
629 # encrypt data
630 if vault_id:
631 display.vvvvv(u'Encrypting with vault_id "%s" and vault secret %s' % (to_text(vault_id), to_text(secret)))
632 else:
633 display.vvvvv(u'Encrypting without a vault_id using vault secret %s' % to_text(secret))
634
635 b_ciphertext = this_cipher.encrypt(b_plaintext, secret, salt)
636
637 # format the data for output to the file
638 b_vaulttext = format_vaulttext_envelope(b_ciphertext,
639 self.cipher_name,
640 vault_id=vault_id)
641 return b_vaulttext
642
643 def decrypt(self, vaulttext):
644 """Decrypt a piece of vault encrypted data.
645
646 :arg vaulttext: a string to decrypt. Since vault encrypted data is an
647 ascii text format this can be either a byte str or unicode string.
648 :returns: a byte string containing the decrypted data
649 """
650 plaintext, vault_id, vault_secret = self.decrypt_and_get_vault_id(vaulttext)
651 return plaintext
652
653 def decrypt_and_get_vault_id(self, vaulttext):
654 """Decrypt a piece of vault encrypted data.
655
656 :arg vaulttext: a string to decrypt. Since vault encrypted data is an
657 ascii text format this can be either a byte str or unicode string.
658 :returns: a byte string containing the decrypted data and the vault-id vault-secret that was used
659 """
660 origin = Origin.get_tag(vaulttext)
661
662 b_vaulttext = to_bytes(vaulttext, nonstring='error') # enforce vaulttext is str/bytes, keep type check if removing type conversion
663
664 if self.secrets is None:
665 raise AnsibleVaultError("A vault password must be specified to decrypt data.", obj=vaulttext)
666
667 if not is_encrypted(b_vaulttext):
668 raise AnsibleVaultError("Input is not vault encrypted data.", obj=vaulttext)
669
670 b_vaulttext, dummy, cipher_name, vault_id = parse_vaulttext_envelope(b_vaulttext)
671
672 # create the cipher object, note that the cipher used for decrypt can
673 # be different than the cipher used for encrypt
674 if cipher_name in CIPHER_ALLOWLIST:
675 this_cipher = CIPHER_MAPPING[cipher_name]()
676 else:
677 raise AnsibleVaultError(f"Cipher {cipher_name!r} could not be found.", obj=vaulttext)
678
679 if not self.secrets:
680 raise AnsibleVaultError('Attempting to decrypt but no vault secrets found.', obj=vaulttext)
681
682 # WARNING: Currently, the vault id is not required to match the vault id in the vault blob to
683 # decrypt a vault properly. The vault id in the vault blob is not part of the encrypted
684 # or signed vault payload. There is no cryptographic checking/verification/validation of the
685 # vault blobs vault id. It can be tampered with and changed. The vault id is just a nick
686 # name to use to pick the best secret and provide some ux/ui info.
687
688 # iterate over all the applicable secrets (all of them by default) until one works...
689 # if we specify a vault_id, only the corresponding vault secret is checked and
690 # we check it first.
691
692 vault_id_matchers = []
693
694 if vault_id:
695 display.vvvvv(u'Found a vault_id (%s) in the vaulttext' % to_text(vault_id))
696 vault_id_matchers.append(vault_id)
697 _matches = match_secrets(self.secrets, vault_id_matchers)
698 if _matches:
699 display.vvvvv(u'We have a secret associated with vault id (%s), will try to use to decrypt %s' % (to_text(vault_id), to_text(origin)))
700 else:
701 display.vvvvv(u'Found a vault_id (%s) in the vault text, but we do not have a associated secret (--vault-id)' % to_text(vault_id))
702
703 # Not adding the other secrets to vault_secret_ids enforces a match between the vault_id from the vault_text and
704 # the known vault secrets.
705 if not C.DEFAULT_VAULT_ID_MATCH:
706 # Add all of the known vault_ids as candidates for decrypting a vault.
707 vault_id_matchers.extend([_vault_id for _vault_id, _dummy in self.secrets if _vault_id != vault_id])
708
709 matched_secrets = match_secrets(self.secrets, vault_id_matchers)
710
711 # for vault_secret_id in vault_secret_ids:
712 for vault_secret_id, vault_secret in matched_secrets:
713 display.vvvvv(u'Trying to use vault secret=(%s) id=%s to decrypt %s' % (to_text(vault_secret), to_text(vault_secret_id), to_text(origin)))
714
715 try:
716 # secret = self.secrets[vault_secret_id]
717 display.vvvv(u'Trying secret %s for vault_id=%s' % (to_text(vault_secret), to_text(vault_secret_id)))
718 b_plaintext = this_cipher.decrypt(b_vaulttext, vault_secret)
719 # DTFIX7: possible candidate for propagate_origin
720 b_plaintext = AnsibleTagHelper.tag_copy(vaulttext, b_plaintext)
721 if b_plaintext is not None:
722 vault_id_used = vault_secret_id
723 vault_secret_used = vault_secret
724 file_slug = ''
725 if origin:
726 file_slug = ' of "%s"' % origin
727 display.vvvvv(
728 u'Decrypt%s successful with secret=%s and vault_id=%s' % (to_text(file_slug), to_text(vault_secret), to_text(vault_secret_id))
729 )
730 break
731 except AnsibleVaultFormatError:
732 raise
733 except AnsibleError as e:
734 display.vvvv(u'Tried to use the vault secret (%s) to decrypt (%s) but it failed. Error: %s' %
735 (to_text(vault_secret_id), to_text(origin), e))
736 continue
737 else:
738 raise AnsibleVaultError("Decryption failed (no vault secrets were found that could decrypt).", obj=vaulttext)
739
740 return b_plaintext, vault_id_used, vault_secret_used
741
742
743 class VaultEditor:
744
745 def __init__(self, vault=None):
746 # TODO: it may be more useful to just make VaultSecrets and index of VaultLib objects...
747 self.vault = vault or VaultLib()
748
749 # TODO: mv shred file stuff to it's own class
750 def _shred_file_custom(self, tmp_path):
751 """"Destroy a file, when shred (core-utils) is not available
752
753 Unix `shred' destroys files "so that they can be recovered only with great difficulty with
754 specialised hardware, if at all". It is based on the method from the paper
755 "Secure Deletion of Data from Magnetic and Solid-State Memory",
756 Proceedings of the Sixth USENIX Security Symposium (San Jose, California, July 22-25, 1996).
757
758 We do not go to that length to re-implement shred in Python; instead, overwriting with a block
759 of random data should suffice.
760
761 See https://github.com/ansible/ansible/pull/13700 .
762 """
763
764 file_len = os.path.getsize(tmp_path)
765
766 if file_len > 0: # avoid work when file was empty
767 max_chunk_len = min(1024 * 1024 * 2, file_len)
768
769 passes = 3
770 with open(tmp_path, "wb") as fh:
771 for dummy in range(passes):
772 fh.seek(0, 0)
773 # get a random chunk of data, each pass with other length
774 chunk_len = random.randint(max_chunk_len // 2, max_chunk_len)
775 data = os.urandom(chunk_len)
776
777 for dummy in range(0, file_len // chunk_len):
778 fh.write(data)
779 fh.write(data[:file_len % chunk_len])
780
781 # FIXME remove this assert once we have unittests to check its accuracy
782 if fh.tell() != file_len:
783 raise AnsibleAssertionError()
784
785 os.fsync(fh)
786
787 def _shred_file(self, tmp_path):
788 """Securely destroy a decrypted file
789
790 Note standard limitations of GNU shred apply (For flash, overwriting would have no effect
791 due to wear leveling; for other storage systems, the async kernel->filesystem->disk calls never
792 guarantee data hits the disk; etc). Furthermore, if your tmp dirs is on tmpfs (ramdisks),
793 it is a non-issue.
794
795 Nevertheless, some form of overwriting the data (instead of just removing the fs index entry) is
796 a good idea. If shred is not available (e.g. on windows, or no core-utils installed), fall back on
797 a custom shredding method.
798 """
799
800 if not os.path.isfile(tmp_path):
801 # file is already gone
802 return
803
804 try:
805 r = subprocess.call(['shred', tmp_path])
806 except (OSError, ValueError):
807 # shred is not available on this system, or some other error occurred.
808 # ValueError caught because macOS El Capitan is raising an
809 # exception big enough to hit a limit in python2-2.7.11 and below.
810 # Symptom is ValueError: insecure pickle when shred is not
811 # installed there.
812 r = 1
813
814 if r != 0:
815 # we could not successfully execute unix shred; therefore, do custom shred.
816 self._shred_file_custom(tmp_path)
817
818 os.remove(tmp_path)
819
820 def _edit_file_helper(self, filename, secret, existing_data=None, force_save=False, vault_id=None):
821
822 # Create a tempfile
823 root, ext = os.path.splitext(os.path.realpath(filename))
824 fd, tmp_path = tempfile.mkstemp(suffix=ext, dir=C.DEFAULT_LOCAL_TMP)
825
826 cmd = self._editor_shell_command(tmp_path)
827 try:
828 if existing_data:
829 self.write_data(existing_data, fd, shred=False)
830 except Exception:
831 # if an error happens, destroy the decrypted file
832 self._shred_file(tmp_path)
833 raise
834 finally:
835 os.close(fd)
836
837 try:
838 # drop the user into an editor on the tmp file
839 subprocess.check_call(cmd)
840 except Exception as e:
841 # if an error happens, destroy the decrypted file
842 self._shred_file(tmp_path)
843 raise AnsibleError('Unable to execute the command "%s": %s' % (' '.join(cmd), to_native(e)))
844
845 b_tmpdata = self.read_data(tmp_path)
846
847 # Do nothing if the content has not changed
848 if force_save or existing_data != b_tmpdata:
849
850 # encrypt new data and write out to tmp
851 # An existing vaultfile will always be UTF-8,
852 # so decode to unicode here
853 b_ciphertext = self.vault.encrypt(b_tmpdata, secret, vault_id=vault_id)
854 self.write_data(b_ciphertext, tmp_path)
855
856 # shuffle tmp file into place
857 self.shuffle_files(tmp_path, filename)
858 display.vvvvv(u'Saved edited file "%s" encrypted using %s and vault id "%s"' % (to_text(filename), to_text(secret), to_text(vault_id)))
859
860 # always shred temp, jic
861 self._shred_file(tmp_path)
862
863 def _real_path(self, filename):
864 # '-' is special to VaultEditor, dont expand it.
865 if filename == '-':
866 return filename
867
868 real_path = os.path.realpath(filename)
869 return real_path
870
871 def encrypt_bytes(self, b_plaintext, secret, vault_id=None):
872
873 b_ciphertext = self.vault.encrypt(b_plaintext, secret, vault_id=vault_id)
874
875 return b_ciphertext
876
877 def encrypt_file(self, filename, secret, vault_id=None, output_file=None):
878
879 # A file to be encrypted into a vaultfile could be any encoding
880 # so treat the contents as a byte string.
881
882 # follow the symlink
883 filename = self._real_path(filename)
884
885 b_plaintext = self.read_data(filename)
886 b_ciphertext = self.vault.encrypt(b_plaintext, secret, vault_id=vault_id)
887 self.write_data(b_ciphertext, output_file or filename)
888
889 def decrypt_file(self, filename, output_file=None):
890
891 # follow the symlink
892 filename = self._real_path(filename)
893
894 ciphertext = self.read_data(filename)
895
896 try:
897 plaintext = self.vault.decrypt(ciphertext)
898 except AnsibleError as e:
899 raise AnsibleError(f"Failed to decrypt {filename!r}.") from e
900 self.write_data(plaintext, output_file or filename, shred=False)
901
902 def create_file(self, filename, secret, vault_id=None):
903 """ create a new encrypted file """
904
905 dirname = os.path.dirname(filename)
906 if dirname and not os.path.exists(dirname):
907 display.warning(u"%s does not exist, creating..." % to_text(dirname))
908 makedirs_safe(dirname)
909
910 # FIXME: If we can raise an error here, we can probably just make it
911 # behave like edit instead.
912 if os.path.isfile(filename):
913 raise AnsibleError("%s exists, please use 'edit' instead" % filename)
914
915 self._edit_file_helper(filename, secret, vault_id=vault_id)
916
917 def edit_file(self, filename):
918 vault_id_used = None
919 vault_secret_used = None
920 # follow the symlink
921 filename = self._real_path(filename)
922
923 b_vaulttext = self.read_data(filename)
924
925 try:
926 # vaulttext gets converted back to bytes, but alas
927 # TODO: return the vault_id that worked?
928 plaintext, vault_id_used, vault_secret_used = self.vault.decrypt_and_get_vault_id(b_vaulttext)
929 except AnsibleError as e:
930 raise AnsibleError(f"Failed to edit {filename!r}.") from e
931
932 # Figure out the vault id from the file, to select the right secret to re-encrypt it
933 # (duplicates parts of decrypt, but alas...)
934 dummy, dummy, cipher_name, vault_id = parse_vaulttext_envelope(b_vaulttext)
935
936 # vault id here may not be the vault id actually used for decrypting
937 # as when the edited file has no vault-id but is decrypted by non-default id in secrets
938 # (vault_id=default, while a different vault-id decrypted)
939
940 # we want to get rid of files encrypted with the AES cipher
941 force_save = (cipher_name not in CIPHER_WRITE_ALLOWLIST)
942
943 # Keep the same vault-id (and version) as in the header
944 self._edit_file_helper(filename, vault_secret_used, existing_data=plaintext, force_save=force_save, vault_id=vault_id)
945
946 def plaintext(self, filename):
947
948 b_vaulttext = self.read_data(filename)
949
950 try:
951 plaintext = self.vault.decrypt(b_vaulttext)
952 return plaintext
953 except AnsibleError as e:
954 raise AnsibleError(f"Failed to view {filename!r}.") from e
955
956 # FIXME/TODO: make this use VaultSecret
957 def rekey_file(self, filename, new_vault_secret, new_vault_id=None):
958
959 # follow the symlink
960 filename = self._real_path(filename)
961
962 prev = os.stat(filename)
963 b_vaulttext = self.read_data(filename)
964
965 display.vvvvv(u'Rekeying file "%s" to with new vault-id "%s" and vault secret %s' %
966 (to_text(filename), to_text(new_vault_id), to_text(new_vault_secret)))
967 try:
968 plaintext, vault_id_used, _dummy = self.vault.decrypt_and_get_vault_id(b_vaulttext)
969 except AnsibleError as e:
970 raise AnsibleError(f"Failed to rekey {filename!r}.") from e
971 # This is more or less an assert, see #18247
972 if new_vault_secret is None:
973 raise AnsibleError('The value for the new_password to rekey %s with is not valid' % filename)
974
975 # FIXME: VaultContext...? could rekey to a different vault_id in the same VaultSecrets
976
977 # Need a new VaultLib because the new vault data can be a different
978 # vault lib format or cipher (for ex, when we migrate 1.0 style vault data to
979 # 1.1 style data we change the version and the cipher). This is where a VaultContext might help
980
981 # the new vault will only be used for encrypting, so it doesn't need the vault secrets
982 # (we will pass one in directly to encrypt)
983 new_vault = VaultLib(secrets={})
984 b_new_vaulttext = new_vault.encrypt(plaintext, new_vault_secret, vault_id=new_vault_id)
985
986 self.write_data(b_new_vaulttext, filename)
987
988 # preserve permissions
989 os.chmod(filename, prev.st_mode)
990 os.chown(filename, prev.st_uid, prev.st_gid)
991
992 display.vvvvv(u'Rekeyed file "%s" (decrypted with vault id "%s") was encrypted with new vault-id "%s" and vault secret %s' %
993 (to_text(filename), to_text(vault_id_used), to_text(new_vault_id), to_text(new_vault_secret)))
994
995 def read_data(self, filename):
996
997 try:
998 if filename == '-':
999 data = Origin(description='<stdin>').tag(sys.stdin.buffer.read())
1000 else:
1001 filename = os.path.abspath(filename)
1002
1003 with open(filename, "rb") as fh:
1004 data = Origin(path=filename).tag(fh.read())
1005 except Exception as e:
1006 msg = to_native(e)
1007 if not msg:
1008 msg = repr(e)
1009 raise AnsibleError('Unable to read source file (%s): %s' % (to_native(filename), msg))
1010
1011 return data
1012
1013 def write_data(self, data, thefile, shred=True, mode=0o600):
1014 # TODO: add docstrings for arg types since this code is picky about that
1015 """Write the data bytes to given path
1016
1017 This is used to write a byte string to a file or stdout. It is used for
1018 writing the results of vault encryption or decryption. It is used for
1019 saving the ciphertext after encryption and it is also used for saving the
1020 plaintext after decrypting a vault. The type of the 'data' arg should be bytes,
1021 since in the plaintext case, the original contents can be of any text encoding
1022 or arbitrary binary data.
1023
1024 When used to write the result of vault encryption, the value of the 'data' arg
1025 should be a utf-8 encoded byte string and not a text type.
1026
1027 When used to write the result of vault decryption, the value of the 'data' arg
1028 should be a byte string and not a text type.
1029
1030 :arg data: the byte string (bytes) data
1031 :arg thefile: file descriptor or filename to save 'data' to.
1032 :arg shred: if shred==True, make sure that the original data is first shredded so that is cannot be recovered.
1033 :returns: None
1034 """
1035 # FIXME: do we need this now? data_bytes should always be a utf-8 byte string
1036 b_file_data = to_bytes(data, errors='strict')
1037
1038 # check if we have a file descriptor instead of a path
1039 is_fd = False
1040 try:
1041 is_fd = (isinstance(thefile, int) and fcntl.fcntl(thefile, fcntl.F_GETFD) != -1)
1042 except Exception:
1043 pass
1044
1045 if is_fd:
1046 # if passed descriptor, use that to ensure secure access, otherwise it is a string.
1047 # assumes the fd is securely opened by caller (mkstemp)
1048 os.ftruncate(thefile, 0)
1049 os.write(thefile, b_file_data)
1050 elif thefile == '-':
1051 # get a ref to either sys.stdout.buffer for py3 or plain old sys.stdout for py2
1052 # We need sys.stdout.buffer on py3 so we can write bytes to it since the plaintext
1053 # of the vaulted object could be anything/binary/etc
1054 output = getattr(sys.stdout, 'buffer', sys.stdout)
1055 output.write(b_file_data)
1056 else:
1057 if not os.access(os.path.dirname(thefile), os.W_OK):
1058 raise AnsibleError("Destination '%s' not writable" % (os.path.dirname(thefile)))
1059 # file names are insecure and prone to race conditions, so remove and create securely
1060 if os.path.isfile(thefile):
1061 if shred:
1062 self._shred_file(thefile)
1063 else:
1064 os.remove(thefile)
1065
1066 # when setting new umask, we get previous as return
1067 current_umask = os.umask(0o077)
1068 try:
1069 try:
1070 # create file with secure permissions
1071 fd = os.open(thefile, os.O_CREAT | os.O_EXCL | os.O_RDWR | os.O_TRUNC, mode)
1072 except FileExistsError as ex:
1073 raise AnsibleError('Vault file got recreated while we were operating on it.') from ex
1074 except OSError as ex:
1075 raise AnsibleError('Problem creating temporary vault file.') from ex
1076
1077 try:
1078 # now write to the file and ensure ours is only data in it
1079 os.ftruncate(fd, 0)
1080 os.write(fd, b_file_data)
1081 except OSError as e:
1082 raise AnsibleError('Unable to write to temporary vault file: %s' % to_native(e))
1083 finally:
1084 # Make sure the file descriptor is always closed and reset umask
1085 os.close(fd)
1086 finally:
1087 os.umask(current_umask)
1088
1089 def shuffle_files(self, src, dest):
1090 prev = None
1091 # overwrite dest with src
1092 if os.path.isfile(dest):
1093 prev = os.stat(dest)
1094 # old file 'dest' was encrypted, no need to _shred_file
1095 os.remove(dest)
1096 shutil.move(src, dest)
1097
1098 # reset permissions if needed
1099 if prev is not None:
1100 # TODO: selinux, ACLs, xattr?
1101 os.chmod(dest, prev.st_mode)
1102 os.chown(dest, prev.st_uid, prev.st_gid)
1103
1104 def _editor_shell_command(self, filename):
1105 env_editor = C.config.get_config_value('EDITOR')
1106 editor = shlex.split(env_editor)
1107 editor.append(filename)
1108
1109 return editor
1110
1111
1112 ########################################
1113 # CIPHERS #
1114 ########################################
1115
1116 class VaultAES256:
1117
1118 """
1119 Vault implementation using AES-CTR with an HMAC-SHA256 authentication code.
1120 Keys are derived using PBKDF2
1121 """
1122
1123 # http://www.daemonology.net/blog/2009-06-11-cryptographic-right-answers.html
1124
1125 # Note: strings in this class should be byte strings by default.
1126
1127 def __init__(self):
1128 if not HAS_CRYPTOGRAPHY:
1129 raise AnsibleError(NEED_CRYPTO_LIBRARY)
1130
1131 @staticmethod
1132 def _create_key_cryptography(b_password, b_salt, key_length, iv_length):
1133 kdf = PBKDF2HMAC(
1134 algorithm=hashes.SHA256(),
1135 length=2 * key_length + iv_length,
1136 salt=b_salt,
1137 iterations=10000,
1138 backend=CRYPTOGRAPHY_BACKEND)
1139 b_derivedkey = kdf.derive(b_password)
1140
1141 return b_derivedkey
1142
1143 @classmethod
1144 @functools.cache # Concurrent first-use by multiple threads will all execute the method body.
1145 def _gen_key_initctr(cls, b_password, b_salt):
1146 # 16 for AES 128, 32 for AES256
1147 key_length = 32
1148
1149 if HAS_CRYPTOGRAPHY:
1150 # AES is a 128-bit block cipher, so IVs and counter nonces are 16 bytes
1151 iv_length = algorithms.AES.block_size // 8
1152
1153 b_derivedkey = cls._create_key_cryptography(b_password, b_salt, key_length, iv_length)
1154 b_iv = b_derivedkey[(key_length * 2):(key_length * 2) + iv_length]
1155 else:
1156 raise AnsibleError(NEED_CRYPTO_LIBRARY + '(Detected in initctr)')
1157
1158 b_key1 = b_derivedkey[:key_length]
1159 b_key2 = b_derivedkey[key_length:(key_length * 2)]
1160
1161 return b_key1, b_key2, b_iv
1162
1163 @staticmethod
1164 def _encrypt_cryptography(b_plaintext, b_key1, b_key2, b_iv):
1165 cipher = C_Cipher(algorithms.AES(b_key1), modes.CTR(b_iv), CRYPTOGRAPHY_BACKEND)
1166 encryptor = cipher.encryptor()
1167 padder = padding.PKCS7(algorithms.AES.block_size).padder()
1168 b_ciphertext = encryptor.update(padder.update(b_plaintext) + padder.finalize())
1169 b_ciphertext += encryptor.finalize()
1170
1171 # COMBINE SALT, DIGEST AND DATA
1172 hmac = HMAC(b_key2, hashes.SHA256(), CRYPTOGRAPHY_BACKEND)
1173 hmac.update(b_ciphertext)
1174 b_hmac = hmac.finalize()
1175
1176 return to_bytes(hexlify(b_hmac), errors='surrogate_or_strict'), hexlify(b_ciphertext)
1177
1178 @classmethod
1179 def _get_salt(cls):
1180 custom_salt = C.config.get_config_value('VAULT_ENCRYPT_SALT')
1181 if not custom_salt:
1182 custom_salt = os.urandom(32)
1183 return to_bytes(custom_salt)
1184
1185 @classmethod
1186 def encrypt(cls, b_plaintext, secret, salt=None):
1187
1188 if secret is None:
1189 raise AnsibleVaultError('The secret passed to encrypt() was None')
1190
1191 if salt is None:
1192 b_salt = cls._get_salt()
1193 elif not salt:
1194 raise AnsibleVaultError('Empty or invalid salt passed to encrypt()')
1195 else:
1196 b_salt = to_bytes(salt)
1197
1198 b_password = secret.bytes
1199 b_key1, b_key2, b_iv = cls._gen_key_initctr(b_password, b_salt)
1200
1201 if HAS_CRYPTOGRAPHY:
1202 b_hmac, b_ciphertext = cls._encrypt_cryptography(b_plaintext, b_key1, b_key2, b_iv)
1203 else:
1204 raise AnsibleError(NEED_CRYPTO_LIBRARY + '(Detected in encrypt)')
1205
1206 b_vaulttext = b'\n'.join([hexlify(b_salt), b_hmac, b_ciphertext])
1207 # Unnecessary but getting rid of it is a backwards incompatible vault
1208 # format change
1209 b_vaulttext = hexlify(b_vaulttext)
1210 return b_vaulttext
1211
1212 @classmethod
1213 def _decrypt_cryptography(cls, b_ciphertext, b_crypted_hmac, b_key1, b_key2, b_iv):
1214 # b_key1, b_key2, b_iv = self._gen_key_initctr(b_password, b_salt)
1215 # EXIT EARLY IF DIGEST DOESN'T MATCH
1216 hmac = HMAC(b_key2, hashes.SHA256(), CRYPTOGRAPHY_BACKEND)
1217 hmac.update(b_ciphertext)
1218 try:
1219 hmac.verify(_unhexlify(b_crypted_hmac))
1220 except InvalidSignature as e:
1221 raise AnsibleVaultError('HMAC verification failed: %s' % e)
1222
1223 cipher = C_Cipher(algorithms.AES(b_key1), modes.CTR(b_iv), CRYPTOGRAPHY_BACKEND)
1224 decryptor = cipher.decryptor()
1225 unpadder = padding.PKCS7(128).unpadder()
1226 b_plaintext = unpadder.update(
1227 decryptor.update(b_ciphertext) + decryptor.finalize()
1228 ) + unpadder.finalize()
1229
1230 return b_plaintext
1231
1232 @staticmethod
1233 def _is_equal(b_a, b_b):
1234 """
1235 Comparing 2 byte arrays in constant time to avoid timing attacks.
1236
1237 It would be nice if there were a library for this but hey.
1238 """
1239 if not (isinstance(b_a, bytes) and isinstance(b_b, bytes)):
1240 raise TypeError('_is_equal can only be used to compare two byte strings')
1241
1242 # http://codahale.com/a-lesson-in-timing-attacks/
1243 if len(b_a) != len(b_b):
1244 return False
1245
1246 result = 0
1247 for b_x, b_y in zip(b_a, b_b):
1248 result |= b_x ^ b_y
1249 return result == 0
1250
1251 @classmethod
1252 def decrypt(cls, b_vaulttext, secret):
1253
1254 b_ciphertext, b_salt, b_crypted_hmac = parse_vaulttext(b_vaulttext)
1255
1256 # TODO: would be nice if a VaultSecret could be passed directly to _decrypt_*
1257 # (move _gen_key_initctr() to a AES256 VaultSecret or VaultContext impl?)
1258 # though, likely needs to be python cryptography specific impl that basically
1259 # creates a Cipher() with b_key1, a Mode.CTR() with b_iv, and a HMAC() with sign key b_key2
1260 b_password = secret.bytes
1261
1262 b_key1, b_key2, b_iv = cls._gen_key_initctr(b_password, b_salt)
1263
1264 if HAS_CRYPTOGRAPHY:
1265 b_plaintext = cls._decrypt_cryptography(b_ciphertext, b_crypted_hmac, b_key1, b_key2, b_iv)
1266 else:
1267 raise AnsibleError(NEED_CRYPTO_LIBRARY + '(Detected in decrypt)')
1268
1269 return b_plaintext
1270
1271
1272 # Keys could be made bytes later if the code that gets the data is more
1273 # naturally byte-oriented
1274 CIPHER_MAPPING = {
1275 u'AES256': VaultAES256,
1276 }
1277
1278
1279 class VaultSecretsContext:
1280 """Provides context-style access to vault secrets."""
1281 _current: t.ClassVar[t.Self | None] = None
1282
1283 def __init__(self, secrets: list[tuple[str, VaultSecret]]) -> None:
1284 self.secrets = secrets
1285
1286 @classmethod
1287 def initialize(cls, value: t.Self) -> None:
1288 """
1289 Initialize VaultSecretsContext with the specified instance and secrets (since it's not a lazy or per-thread context).
1290 This method will fail if called more than once.
1291 """
1292 if cls._current:
1293 raise RuntimeError(f"The {cls.__name__} context is already initialized.")
1294
1295 cls._current = value
1296
1297 @classmethod
1298 def current(cls, optional: bool = False) -> t.Self:
1299 """Access vault secrets, if initialized, ala `AmbientContextBase.current()`."""
1300 if not cls._current and not optional:
1301 raise ReferenceError(f"A required {cls.__name__} context is not active.")
1302
1303 return cls._current
1304
1305
1306 @t.final
1307 class EncryptedString(AnsibleTaggedObject):
1308 """
1309 An encrypted string which supports tagging and on-demand decryption.
1310 All methods provided by Python's built-in `str` are supported, all of which operate on the decrypted value.
1311 Any attempt to use this value when it cannot be decrypted will raise an exception.
1312 Despite supporting `str` methods, access to an instance of this type through templating is recommended over direct access.
1313 """
1314
1315 __slots__ = ('_ciphertext', '_plaintext', '_ansible_tags_mapping')
1316
1317 _subclasses_native_type: t.ClassVar[bool] = False
1318 _empty_tags_as_native: t.ClassVar[bool] = False
1319
1320 _ciphertext: str
1321 _plaintext: str | None
1322 _ansible_tags_mapping: _AnsibleTagsMapping | _EmptyROInternalTagsMapping
1323
1324 def __init__(self, *, ciphertext: str) -> None:
1325 if type(ciphertext) is not str: # pylint: disable=unidiomatic-typecheck
1326 raise TypeError(f'ciphertext must be {str} instead of {type(ciphertext)}')
1327
1328 object.__setattr__(self, '_ciphertext', ciphertext)
1329 object.__setattr__(self, '_plaintext', None)
1330 object.__setattr__(self, '_ansible_tags_mapping', _EMPTY_INTERNAL_TAGS_MAPPING)
1331
1332 @classmethod
1333 def _instance_factory(cls, value: t.Any, tags_mapping: _AnsibleTagsMapping) -> EncryptedString:
1334 instance = EncryptedString.__new__(EncryptedString)
1335
1336 # In 2.18 and earlier, vaulted values were not trusted.
1337 # This maintains backwards compatibility with that.
1338 # Additionally, supporting templating on vaulted values could be problematic for a few cases:
1339 # 1) There's no way to compose YAML tags, so you can't use `!unsafe` and `!vault` together.
1340 # 2) It would make composing `EncryptedString` with a possible future `TemplateString` more difficult.
1341 tags_mapping.pop(TrustedAsTemplate, None)
1342
1343 object.__setattr__(instance, '_ciphertext', value._ciphertext)
1344 object.__setattr__(instance, '_plaintext', value._plaintext)
1345 object.__setattr__(instance, '_ansible_tags_mapping', tags_mapping)
1346
1347 return instance
1348
1349 def __setstate__(self, state: tuple[None, dict[str, t.Any]]) -> None:
1350 for key, value in state[1].items():
1351 object.__setattr__(self, key, value)
1352
1353 def __delattr__(self, item: str) -> t.NoReturn:
1354 raise AttributeError(f'{self.__class__.__name__!r} object is read-only')
1355
1356 def __setattr__(self, key: str, value: object) -> t.NoReturn:
1357 raise AttributeError(f'{self.__class__.__name__!r} object is read-only')
1358
1359 @classmethod
1360 def _init_class(cls) -> None:
1361 """
1362 Add proxies for the specified `str` methods.
1363 These proxies operate on the plaintext, which is decrypted on-demand.
1364 """
1365 cls._native_type = cls
1366
1367 operator_method_names = (
1368 '__eq__',
1369 '__ge__',
1370 '__gt__',
1371 '__le__',
1372 '__lt__',
1373 '__ne__',
1374 )
1375
1376 method_names = (
1377 '__add__',
1378 '__contains__',
1379 '__format__',
1380 '__getitem__',
1381 '__hash__',
1382 '__iter__',
1383 '__len__',
1384 '__mod__',
1385 '__mul__',
1386 '__rmod__',
1387 '__rmul__',
1388 'capitalize',
1389 'casefold',
1390 'center',
1391 'count',
1392 'encode',
1393 'endswith',
1394 'expandtabs',
1395 'find',
1396 'format',
1397 'format_map',
1398 'index',
1399 'isalnum',
1400 'isalpha',
1401 'isascii',
1402 'isdecimal',
1403 'isdigit',
1404 'isidentifier',
1405 'islower',
1406 'isnumeric',
1407 'isprintable',
1408 'isspace',
1409 'istitle',
1410 'isupper',
1411 'join',
1412 'ljust',
1413 'lower',
1414 'lstrip',
1415 'maketrans', # static, but implemented for simplicity/consistency
1416 'partition',
1417 'removeprefix',
1418 'removesuffix',
1419 'replace',
1420 'rfind',
1421 'rindex',
1422 'rjust',
1423 'rpartition',
1424 'rsplit',
1425 'rstrip',
1426 'split',
1427 'splitlines',
1428 'startswith',
1429 'strip',
1430 'swapcase',
1431 'title',
1432 'translate',
1433 'upper',
1434 'zfill',
1435 )
1436
1437 for method_name in operator_method_names:
1438 setattr(cls, method_name, functools.partialmethod(cls._proxy_str_operator_method, getattr(str, method_name)))
1439
1440 for method_name in method_names:
1441 setattr(cls, method_name, functools.partialmethod(cls._proxy_str_method, getattr(str, method_name)))
1442
1443 def _decrypt(self) -> str:
1444 """
1445 Attempt to decrypt the ciphertext and return the plaintext, which will be cached.
1446 If decryption fails an exception will be raised and no result will be cached.
1447 """
1448 if self._plaintext is None:
1449 vault = VaultLib(secrets=VaultSecretsContext.current().secrets)
1450 # use the utility method to ensure that origin tags are available
1451 plaintext = to_text(vault.decrypt(VaultHelper.get_ciphertext(self, with_tags=True))) # raises if the ciphertext cannot be decrypted
1452
1453 # propagate source value tags plus VaultedValue for round-tripping ciphertext
1454 plaintext = AnsibleTagHelper.tag(plaintext, AnsibleTagHelper.tags(self) | {VaultedValue(ciphertext=self._ciphertext)})
1455
1456 object.__setattr__(self, '_plaintext', plaintext)
1457
1458 register_secret(plaintext)
1459
1460 return self._plaintext
1461
1462 def _as_dict(self) -> t.Dict[str, t.Any]:
1463 return dict(
1464 value=self._ciphertext,
1465 tags=list(self._ansible_tags_mapping.values()),
1466 )
1467
1468 def _native_copy(self) -> str:
1469 return AnsibleTagHelper.untag(self._decrypt())
1470
1471 def _proxy_str_operator_method(self, method: t.Callable, other) -> t.Any:
1472 obj = self._decrypt()
1473
1474 if type(other) is EncryptedString: # pylint: disable=unidiomatic-typecheck
1475 other = other._decrypt()
1476
1477 return method(obj, other)
1478
1479 def _proxy_str_method(self, method: t.Callable, *args, **kwargs) -> t.Any:
1480 obj = self._decrypt()
1481 return method(obj, *args, **kwargs)
1482
1483 def __repr__(self) -> str:
1484 return f'{self.__class__.__name__}(ciphertext={self._ciphertext!r})'
1485
1486 def __str__(self) -> str:
1487 return self._decrypt()
1488
1489 def __float__(self) -> float:
1490 return float(self._decrypt())
1491
1492 def __int__(self) -> int:
1493 return int(self._decrypt())
1494
1495 def __radd__(self, other: t.Any) -> str:
1496 return other + self._decrypt()
1497
1498 def __fspath__(self) -> str:
1499 return self._decrypt()
1500
1501
1502 class VaultHelper:
1503 """Vault specific utility methods."""
1504
1505 @staticmethod
1506 def get_ciphertext(value: t.Any, *, with_tags: bool) -> str | None:
1507 """
1508 If the given value is an `EncryptedString`, `VaultExceptionMarker` or tagged with `VaultedValue`, return the ciphertext, otherwise return `None`.
1509 Tags on the value other than `VaultedValue` will be included on the ciphertext if `with_tags` is `True`, otherwise it will be tagless.
1510 """
1511 value_type = type(value)
1512 ciphertext: str | None
1513 tags = AnsibleTagHelper.tags(value)
1514
1515 if value_type is _jinja_common.VaultExceptionMarker:
1516 ciphertext = value._marker_undecryptable_ciphertext
1517 tags = AnsibleTagHelper.tags(ciphertext) # ciphertext has tags but value does not
1518 elif value_type is EncryptedString:
1519 ciphertext = value._ciphertext
1520 elif value_type in _jinja_common.Marker._concrete_subclasses: # avoid wasteful raise/except of Marker when calling get_tag below
1521 ciphertext = None
1522 elif vaulted_value := VaultedValue.get_tag(value):
1523 ciphertext = vaulted_value.ciphertext
1524 else:
1525 ciphertext = None
1526
1527 if ciphertext:
1528 if with_tags:
1529 ciphertext = VaultedValue.untag(AnsibleTagHelper.tag(ciphertext, tags))
1530 else:
1531 ciphertext = AnsibleTagHelper.untag(ciphertext)
1532
1533 return ciphertext