Commit graph

105 commits

Author SHA1 Message Date
Sam Doran c0cb353ce1
Remove PyCrypto (#74699)
* Remove PyCrypto from setup.py and packaging script
* Remove mention of pycrpto from installation docs
* Remove PyCrypto from vault
* Remove pycryto constraint and unit test requirement
* Remove PyCrypto tests from unit tests
* Add docs and fix warning message
* Remove section about cryptography library in Ansible Vault docs
2021-05-18 16:12:32 -04:00
Lazuardi N Putra bcefb6b5f1
fix typo in ansible vault decrypt if vault error (#73542) 2021-02-11 14:14:50 -05:00
Sven Wegener 08cc6edc64
vault: Read stdin data as binary on python3 (#52229)
On python3 sys.stdin is an encoded file object that does not support
reading raw binary data. Use the supplied buffer object to do so.

Signed-off-by: Sven Wegener <sven.wegener@inovex.de>

Co-authored-by: Sven Wegener <sven.wegener@inovex.de>
2020-12-09 09:46:32 +01:00
Matt Martz f8ef34672b
Provide better decryption errors for single vault values (#72362)
Fixes #72276
Fixes #72281
2020-11-18 14:25:32 -06:00
Matt Martz 9667f221a5
Make AnsibleVaultEncryptedUnicode work more like a string (#67823)
* Make AnsibleVaultEncryptedUnicode work more like a string. Fixes #24425

* Remove debugging

* Wrap some things

* Reduce diff

* data should always result in text

* add tests

* Don't just copy and paste, kids

* Add eq and ne back

* Go full UserString copy/paste

* Various version related fixes

* Remove trailing newline

* py2v3

* Add a test that can evaluate whether a variable is vault encrypted

* map was introduces in jinja2 2.7

* moar jinja

* type fix

Co-Authored-By: Sam Doran <sdoran@redhat.com>

* Remove duplicate __hash__

* Fix typo

* Add changelog fragment

* ci_complete

Co-authored-by: Sam Doran <sdoran@redhat.com>
2020-06-08 16:30:14 -05:00
Brian Coca 28f9fbdb5e
safely use vault to edit secrets (#68644)
* when possible, use filedescriptors from mkstemp to avoid race
  * when using path strings, ensure we are always creating the file

CVE-2020-1740
Fixes #67798

Co-authored-by: samdoran
2020-04-03 10:19:01 -04:00
Brian Coca 6452a82452
fix vault temp file handling (#68433)
* fix vault tmpe file handling

 * use local temp dir instead of system temp
 * ensure each worker clears dataloader temp files
 * added test for dangling temp files
 * added notes to data loader

CVE-2020-10685
2020-03-25 15:24:04 -04:00
Klaus Frank fbdf6e59f2 Fix ansible-vault cipher_whitelist (#57272)
* Fix ansible-vault cipher_whitelist Fixes: #57271

* Add changelog for #57272
2019-06-22 11:14:37 -04:00
Matt Martz db6cc60352
Migrate command line parsing to argparse (#50610)
* Start of migration to argparse

* various fixes and improvements

* Linting fixes

* Test fixes

* Fix vault_password_files

* Add PrependAction for argparse

* A bunch of additional tweak/fixes

* Fix ansible-config tests

* Fix man page generation

* linting fix

* More adhoc pattern fixes

* Add changelog fragment

* Add support for argcomplete

* Enable argcomplete global completion

* Rename PrependAction to PrependListAction to better describe what it does

* Add documentation for installing and configuring argcomplete

* Address rebase issues

* Fix display encoding for vault

* Fix line length

* Address rebase issues

* Handle rebase issues

* Use mutually exclusive group instead of handling manually

* Fix rebase issues

* Address rebase issue

* Update version added for argcomplete support

* -e must be given a value

* ci_complete
2019-04-23 13:54:39 -05:00
Abhijeet Kasurde 5c992fcc3f
ansible-vault: handle utf-8 filename in vault (#50341)
Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
2019-02-12 16:13:51 +05:30
Matt Clay b971ebd343 More path encoding fixes. 2019-01-16 15:44:50 -08:00
Matt Martz c9040d7579
Don't just raise AnsibleError with the exception message (#49654)
* Don't just raise AnsibleError with the exception message. Fixes #49252

* Add changelog fragment
2018-12-11 09:27:10 -06:00
Matt Martz 9773a1f289
Add a Singleton metaclass, use it with Display (#48935)
* Add a Singleton class, use it with Display

* update six import

* Move remaining failes to display singleton

* Fix rebase issues

* Singleton improvements

* Add code-smell for 'from __main__ import display'. ci_complete

* s/self/cls/g

* Add docs for no-main-display

* Address linting issues

* Add changelog fragment. ci_complete

* Implement reentrant lock for class instantiation in Singleton

* Add Display singleton porting guide
2018-11-20 17:06:51 -06:00
Martin Krizek a80c25cbd9
Do not use str() on exceptions (#46950) 2018-11-09 07:59:30 +01:00
Brendan Jurd ab96bbdef9 Clean up Vault docs in User Guide. (#46188)
* Fix spelling of 'separate' throughout.

* Various cleanups in the User Guide for Vault.

- Fix spelling of 'algorithm'
- Fix indentation of nested list in payload format
- Fix mysterious refernce to 'b_pkey1'.
- Fix reference to newline as '\n': the backslash is lost when rendered
to the docs website. Specify the hex value for newline instead of the
backslash escape.

* Fix formatting

* Update vault.rst
2018-09-28 10:16:58 -04:00
Matt Martz 81ca04512d
Raise a nicer error when we cannot execute the editor (#44423)
* Raise a nicer error when we cannot execute the editor. Fixes #44419

* Don't use to_bytes when constructing an exception

* Add changelog fragment
2018-08-22 10:24:11 -05:00
Matt Martz 617372f8c0
Mass nuke deprecated items that are easily removed. ci_complete (#44320) 2018-08-20 16:26:10 -05:00
Abhijeet Kasurde 4f1746ee1d
vault: check dir value before passing (#43184)
This fix checks if dirname is not equal to '' before proceeding
to create actual directory with name.

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
2018-07-24 16:27:17 +05:30
Troy Murray 15ce7c5bab change OS X to macOS (#41294)
* change OS X to macOS

<!--- Your description here -->

+label: docsite_pr

* Update all Mac OS X references to be macOS

* Drop extra Mac
2018-06-26 14:09:23 -04:00
Tom Wassenberg 6097776dc0 Fix flag in debug message (#40753)
The debug message stated that the vault password client script was invoked as `example.py --vault-id=example`, while it's actually `example.py --vault-id example`.
2018-06-01 13:48:22 -04:00
Martin Krizek dccb0d035b
vault: check dir existence before creating a file (#40010) 2018-05-11 19:29:44 +02:00
Adrian Likins 6e737c8cb6
Fix 'New Vault password' on vault 'edit' (#35923)
* Fix 'New Vault password' on vault 'edit'

ffe0ddea96 introduce a
change on 'ansible-vault edit' that tried to check
for --encrypt-vault-id in that mode. But '--encrypt-vault-id'
is not intended for 'edit' since the 'edit' should always
reuse the vault secret that was used to decrypt the text.

Change cli to not check for --encrypt-vault-id on 'edit'.

VaultLib.decrypt_and_get_vault_id() was change to return
the vault secret used to decrypt (in addition to vault_id
and the plaintext).

VaultEditor.edit_file() will now use 'vault_secret_used'
as returned from decrypt_and_get_vault_id() so that
an edited file always gets reencrypted with the same
secret, regardless of any vault id configuration or
cli options.

Fixes #35834
2018-03-27 14:12:21 -04:00
Michael Scherer 060001b08d Remove deprecated code (#34828)
* Remove compat code for to_unicode, to_str and to_bytes

Code was marked as deprecated and to be removed after 2.4

* Remove is_encrypted and is_encrypted_file

Code was marked as deprecated after 2.4 release.
2018-01-23 12:02:09 -06:00
Adrian Likins ffe0ddea96
add a vault --encrypt-vault-to specify vault id to use for encrypt (#31067)
Enforce that there can be only one --new-vault-id or
--new-vault-password-file and use this instead of
--encrypt-vault-id

* Add a config option for default vault encrypt id
2018-01-22 17:12:10 -05:00
Adrian Likins fc180a378a
Support using vault password files that are themselves vault encrypted (#27668)
Extract vault related bits of DataLoader._get_file_contents to DataLoader._decrypt_if_vault_data

When loading vault password files, detect if they are vault encrypted, and if so, try to decrypt with any already known vault secrets.

This implements the 'Allow vault password files to be vault encrypted'  (#31002) feature card from
the 2.5.0 project at https://github.com/ansible/ansible/projects/9

Fixes #31002
2018-01-20 14:56:18 -05:00
Abhijeet Kasurde 9f969a2176
Misc. typo is display log (#34388)
Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
2018-01-05 07:44:28 +05:30
Matt Martz 0b9f1f7982
Handle vault filenames with nonascii chars when displaying messages. Fixes #33879 (#33926) 2017-12-14 16:02:25 -06:00
Matt Martz 99d4f5bab4 Remove uses of assert in production code (#32079)
* Remove uses of assert in production code

* Fix assertion

* Add code smell test for assertions, currently limited to lib/ansible

* Fix assertion

* Add docs for no-assert

* Remove new assert from enos

* Fix assert in module_utils.connection
2017-11-13 11:51:18 -05:00
Adrian Likins 9c58827410
Better handling of malformed vault data envelope (#32515)
* Better handling of malformed vault data envelope

If an embedded vaulted variable ('!vault' in yaml)
had an invalid format, it would eventually cause
an error for seemingly unrelated reasons.
"Invalid" meaning not valid hexlify (extra chars,
non-hex chars, etc).

For ex, if a host_vars file had invalid vault format
variables, on py2, it would cause an error like:

  'ansible.vars.hostvars.HostVars object' has no
  attribute u'broken.example.com'

Depending on where the invalid vault is, it could
also cause "VARIABLE IS NOT DEFINED!". The behavior
can also change if ansible-playbook is py2 or py3.

Root cause is errors from binascii.unhexlify() not
being handled consistently.

Fix is to add a AnsibleVaultFormatError exception and
raise it on any unhexlify() errors and to handle it
properly elsewhere.

Add a _unhexlify() that try/excepts around a binascii.unhexlify()
and raises an AnsibleVaultFormatError on invalid vault data.
This is so the same exception type is always raised for this
case. Previous it was different between py2 and py3.

binascii.unhexlify() raises a binascii.Error if the hexlified
blobs in a vault data blob are invalid.

On py2, binascii.Error is a subclass of Exception.
On py3, binascii.Error is a subclass of TypeError

When decrypting content of vault encrypted variables,
if a binascii.Error is raised it propagates up to
playbook.base.Base.post_validate(). post_validate()
handles exceptions for TypeErrors but not for
base Exception subclasses (like py2 binascii.Error).

* Add a display.warning on vault format errors
* Unit tests for _unhexlify, parse_vaulttext*
* Add intg test cases for invalid vault formats

Fixes #28038
2017-11-10 14:24:56 -05:00
Adrian Likins 297dfb1d50 Vault secrets script client inc new 'keyring' client (#27669)
This adds a new type of vault-password script  (a 'client') that takes advantage of and enhances the 
multiple vault password support.

If a vault password script basename ends with the name '-client', consider it a vault password script client. 

A vault password script 'client' just means that the script will take a '--vault-id' command line arg.

The previous vault password script (as invoked by --vault-password-file pointing to an executable) takes
no args and returns the password on stdout. But it doesnt know anything about --vault-id or multiple vault
passwords.

The new 'protocol' of the vault password script takes a cli arg ('--vault-id') so that it can lookup that specific
vault-id and return it's password.

Since existing vault password scripts don't know the new 'protocol', a way to distinguish password scripts
that do understand the protocol was needed.  The convention now is to consider password scripts that are
named like 'something-client.py' (and executable) to be vault password client scripts.

The new client scripts get invoked with the '--vault-id' they were requested for. An example:

     ansible-playbook --vault-id my_vault_id@contrib/vault/vault-keyring-client.py some_playbook.yml

That will cause the 'contrib/vault/vault-keyring-client.py' script to be invoked as:

     contrib/vault/vault-keyring-client.py --vault-id my_vault_id

The previous vault-keyring.py password script was extended to become vault-keyring-client.py. It uses
the python 'keyring' module to request secrets from various backends. The plain 'vault-keyring.py' script
would determine which key id and keyring name to use based on values that had to be set in ansible.cfg.
So it was also limited to one keyring name.

The new vault-keyring-client.py will request the secret for the vault id provided via the '--vault-id' option.
The script can be used without config and can be used for multiple keyring ids (and keyrings).

On success, a vault password client script will print the password to stdout and exit with a return code of 0.
If the 'client' script can't find a secret for the --vault-id, the script will exit with return code of 2 and print an error to stderr.
2017-10-13 15:23:08 -04:00
Michael Vermaes fad3a4dc83 Fix typo in vault decrypt error message (#31335) 2017-10-05 18:09:22 -04:00
Adrian Likins a14d0f3586 Use vault_id when encrypted via vault-edit (#30772)
* Use vault_id when encrypted via vault-edit

On the encryption stage of
'ansible-vault edit --vault-id=someid@passfile somefile',
the vault id was not being passed to encrypt() so the files were
always saved with the default vault id in the 1.1 version format.

When trying to edit that file a second time, also with a --vault-id,
the file would be decrypted with the secret associated with the
provided vault-id, but since the encrypted file had no vault id
in the envelope there would be no match for 'default' secrets.
(Only the --vault-id was included in the potential matches, so
the vault id actually used to decrypt was not).

If that list was empty, there would be an IndexError when trying
to encrypted the changed file. This would result in the displayed
error:

ERROR! Unexpected Exception, this is probably a bug: list index out of range

Fix is two parts:

1) use the vault id when encrypting from edit

2) when matching the secret to use for encrypting after edit,
include the vault id that was used for decryption and not just
the vault id (or lack of vault id) from the envelope.

add unit tests for #30575 and intg tests for 'ansible-vault edit'

Fixes #30575
2017-09-26 12:28:31 -04:00
Reid Wahl f787be3597 Fixes #22335: Adds filename extension to tempfile for Vault 2017-08-28 11:01:04 -04:00
Adrian Likins e287af1ac8 Vault secrets empty password (#28186)
* Better handling of empty/invalid passwords

empty password files are global error and cause an
exit. A warning is also emitted with more detail.

ie, if any of the password/secret sources provide
a bogus password (ie, empty) or fail (exception,
 ctrl-d, EOFError), we stop at the first error and exit. 

This makes behavior when entering empty password at
prompt match 2.3 (ie, an error)
2017-08-15 11:01:46 -04:00
Adrian Likins 220db9cdd2 Better vault pass prompt behav on EOF, more unit tests (#27981) 2017-08-10 09:34:57 -04:00
Adrian Likins c38ff3b8f8 pylint fixes for vault related code (#27721)
* rm unneeded parens following assert
* rm unused parse_vaulttext_envelope from yaml.constructor
* No longer need index/enumerate over vault_ids
* rm unnecessary else
* rm unused VaultCli.secrets
* rm unused vault_id arg on VaultAES.decrypt()

pylint: Unused argument 'vault_id'
pylint: Unused parse_vaulttext_envelope imported from ansible.parsing.vault
pylint: Unused variable 'index'
pylint: Unnecessary parens after 'assert' keyword
pylint: Unnecessary "else" after "return" (no-else-return)
pylint: Attribute 'editor' defined outside __init__

* use 'dummy' for unused variables instead of _

Based on pylint unused variable warnings.

Existing code use '_' for this, but that is old
and busted. The hot new thing is 'dummy'. It
is so fetch.

Except for where we get warnings for reusing
the 'dummy' var name inside of a list comprehension.

* Add super().__init__ call to PromptVaultSecret.__init__
pylint: __init__ method from base class 'VaultSecret' is not called (super-init-not-called)

* Make FileVaultSecret.read_file reg method again

The base class read_file() doesnt need self but
the sub classes do.

Rm now unneeded loader arg to read_file()

* Fix err msg string literal that had no effect
pylint: String statement has no effect

The indent on the continuation of the msg_format was wrong
so the second half was dropped.

There was also no need to join() filename (copy/paste from
original with a command list I assume...)

* Use local cipher_name in VaultEditor.edit_file not instance
pylint: Unused variable 'cipher_name'
pylint: Unused variable 'b_ciphertext'

Use the local cipher_name returned from parse_vaulttext_envelope()
instead of the instance self.cipher_name var.

Since there is only one valid cipher_name either way, it was
equilivent, but it will not be with more valid cipher_names

* Rm unused b_salt arg on VaultAES256._encrypt*
pylint: Unused argument 'b_salt'

Previously the methods computed the keys and iv themselves
so needed to be passed in the salt, but now the key/iv
are built before and passed in so b_salt arg is not used
anymore.

* rm redundant import of call from subprocess
pylint: Imports from package subprocess are not grouped

use via subprocess module now instead of direct
import.

* self._bytes is set in super init now, rm dup

* Make FileVaultSecret.read_file() -> _read_file()

_read_file() is details of the implementation of
load(), so now 'private'.
2017-08-08 16:10:03 -04:00
Adrian Likins 2b0a7338d4 Handle win style CRLF newlines in vault text (#27590)
When parsing a vaulttext blob, use .splitlines()
instead of split(b'\n') to handle \n newlines and
windows style \r\n (CRLF) new lines.

The vaulttext enevelope at this point is just the header line
and a hexlify()'ed blob, so CRLF is a valid newline here.

Fixes #22914
2017-08-01 18:53:22 -04:00
Adrian Likins 9f57920eab Fix --ask-vault-pass prompt to match old when poss (#27602)
If we don't use more than one vault-id, and we use
--ask-vault-pass, instead of using the new vault prompt
format ('Vault password (my_vault_id): ') we use the old
one ('Vault password: ').

This avoids confusing Tower when it needs to detect an
interactive vault password prompt.

This also potentially could allow vault password prompts
to be customized per vault_id.
2017-08-01 16:39:54 -04:00
Adrian Likins 934b645191 Support multiple vault passwords (#22756)
Fixes #13243

** Add --vault-id to name/identify multiple vault passwords

Use --vault-id to indicate id and path/type

 --vault-id=prompt  # prompt for default vault id password
 --vault-id=myorg@prompt  # prompt for a vault_id named 'myorg'
 --vault-id=a_password_file  # load ./a_password_file for default id
 --vault-id=myorg@a_password_file # load file for 'myorg' vault id

vault_id's are created implicitly for existing --vault-password-file
and --ask-vault-pass options.

Vault ids are just for UX purposes and bookkeeping. Only the vault
payload and the password bytestring is needed to decrypt a
vault blob.

Replace passing password around everywhere with
a VaultSecrets object.

If we specify a vault_id, mention that in password prompts

Specifying multiple -vault-password-files will
now try each until one works

** Rev vault format in a backwards compatible way

The 1.2 vault format adds the vault_id to the header line
of the vault text. This is backwards compatible with older
versions of ansible. Old versions will just ignore it and
treat it as the default (and only) vault id.

Note: only 2.4+ supports multiple vault passwords, so while
earlier ansible versions can read the vault-1.2 format, it
does not make them magically support multiple vault passwords.

use 1.1 format for 'default' vault_id

Vaulted items that need to include a vault_id will be
written in 1.2 format.

If we set a new DEFAULT_VAULT_IDENTITY, then the default will
use version 1.2

vault will only use a vault_id if one is specified. So if none
is specified and C.DEFAULT_VAULT_IDENTITY is 'default'
we use the old format.

** Changes/refactors needed to implement multiple vault passwords

raise exceptions on decrypt fail, check vault id early

split out parsing the vault plaintext envelope (with the
sha/original plaintext) to _split_plaintext_envelope()

some cli fixups for specifying multiple paths in
the unfrack_paths optparse callback

fix py3 dict.keys() 'dict_keys object is not indexable' error

pluralize cli.options.vault_password_file -> vault_password_files
pluralize cli.options.new_vault_password_file -> new_vault_password_files
pluralize cli.options.vault_id -> cli.options.vault_ids

** Add a config option (vault_id_match) to force vault id matching.

With 'vault_id_match=True' and an ansible
vault that provides a vault_id, then decryption will require
that a matching vault_id is required. (via
--vault-id=my_vault_id@password_file, for ex).

In other words, if the config option is true, then only
the vault secrets with matching vault ids are candidates for
decrypting a vault. If option is false (the default), then
all of the provided vault secrets will be selected.

If a user doesn't want all vault secrets to be tried to
decrypt any vault content, they can enable this option.

Note: The vault id used for the match is not encrypted or
cryptographically signed. It is just a label/id/nickname used
for referencing a specific vault secret.
2017-07-28 15:20:58 -04:00
Toshio Kuratomi e238ae999b Cyptography pr 20566 rebase (#25560)
Make pyca/cryptography the preferred backend for cryptographic needs (mainly vault) falling back to pycrypto

pyca/cryptography is already implicitly a dependency in many cases
through paramiko (2.0+) as well as the new openssl_publickey module,
which requires pyOpenSSL 16.0+. Additionally, pyca/cryptography is
an optional dep for better performance with vault already.

This commit leverages cryptography's padding, constant time comparisons,
and CBC/CTR modes to reduce the amount of code ansible needs to
maintain.

* Handle wrong password given for VaultAES format

* Do not display deprecation warning for cryptography on python-2.6

* Namespace all of the pycrypto imports and always import them

  Makes unittests better and the code less likely to get stupid mistakes
  (like using HMAC from cryptogrpahy when the one from pycrypto is needed)

* Add back in atfork since we need pycrypto to reinitialize its RNG just in case we're being used with old paramiko

* contrib/inventory/gce: Remove spurious require on pycrypto

(cherry picked from commit 9e16b9db275263b3ea8d1b124966fdebfc9ab271)

* Add cryptography to ec2_win_password module requirements
  * Fix python3 bug which would pass text strings to a function which
    requires byte strings.

* Attempt to add pycrypto version to setup deps

* Change hacking README for dual pycrypto/cryptography

* update dependencies for various CI scripts

* additional CI dockerfile/script updates

* add paramiko to the windows and sanity requirement set

  This is needed because ansible lists it as a requirement. Previously
  the missing dep wasn't enforced, but cryptography imports pkg_resources
  so you can't ignore a requirement any more

* Add integration test cases for old vault and for wrong passwords

* helper script for manual testing of pycrypto/cryptography

* Skip the pycrypto tests so that users without it installed can still run the unittests

* Run unittests for vault with both cryptography and pycrypto backend
2017-06-27 06:00:15 -07:00
Dag Wieers 6f6bdf7914 ansible/parsing: PEP8 compliancy (#24701)
- Make PEP8 compliant
2017-05-18 18:41:00 +01:00
Adrian Likins e0a7105c2d Use sys.stdout.buffer to write vault bytes to stdout on py3 (#23760)
* Use sys.stdout.buffer to write vault bytes to stdout on py3

We need sys.stdout.buffer on py3 so we can write bytes to it since the plaintext
of the vaulted object could be anything/binary/etc

Before, attempting to write bytes to stdout on py3 would cause:

  TypeError: write() argument must be str, not bytes
2017-04-24 10:09:03 -04:00
Adrian Likins ae3d7fb29e Fix vault reading from stdin (avoid realpath() on non-links) (#23583)
* Fix vault reading from stdin (avoid realpath() on non-links)

os.path.realpath() is used to find the target of file paths that
are symlinks so vault operations happen directly on the target.

However, in addition to resolving symlinks, realpath() also returns
a full path. when reading from stdin, vault cli uses '-' as a special
file path so VaultEditor() will replace with stdin.
realpath() was expanding '-' with the CWD to something like
'/home/user/playbooks/-' causing errors like:

        ERROR! [Errno 2] No such file or directory: u'/home/user/ansible/-'

Fix is to specialcase '-' to not use realpath()

Fixes #23567

* to_text decrypt output when writing to stdout
2017-04-18 13:09:02 -04:00
Hugo Chargois 1bc5527c69 Vault: Remove tmp decrypted file when experiencing error while writing (#14835)
* Vault edit: Erase tmp file if error while writing to it

* Close the FDs returned by mkstemp()
2017-03-27 16:52:18 -04:00
Toshio Kuratomi 2fff690caa Update module_utils.six to latest (#22855)
* Update module_utils.six to latest

We've been held back on the version of six we could use on the module
side to 1.4.x because of python-2.4 compatibility.  Now that our minimum
is Python-2.6, we can update to the latest version of six in
module_utils and get rid of the second copy in lib/ansible/compat.
2017-03-23 13:35:05 -07:00
Nicolas Braud-Santoni f689cca0b8 vault: Uniformize construction of cipher objects 2017-03-08 15:14:20 -05:00
Nicolas Braud-Santoni 680d61c609 vault: call is_encrypted directly in is_encrypted_file
Doing the conversion and checking for exceptions there is pointless
since is_encrypted already does it.
2017-03-08 15:14:20 -05:00
Adrian Likins edcbef27ec Retain vault password as bytes in 2.2 (#22378)
* Retain vault password as bytes in 2.2

Prior to 2.2.1, the vault password was read in as byes and then remained
bytes all the way through the code.  A bug existed where bytes and text
were mixed, leading to a traceback with non-ascii passwords.  In devel,
this was fixed by changing the read in password to text type to match
with our overall strategy of converting at the borders.  This was
backported to stable-2.2 for the 2.2.1 release.

On reflection, this should not have been backported as it causes
passwords which were originally non-utf-8 to become utf-8.  People will
then have their working 2.2.x vault files become in-accessible.

this commit pipes bytes all the way through the system for vault
password.  That way if a password is read in as a non-utf-8 character
sequence, it will continue to work in 2.2.2+.  This change is only for
the 2.2 branch, not for 2.3 and beyond.

Why not everywhere?  The reason is that non-utf-8 passwords will cause
problems when vault files are shared between systems or users.  If the
password is read from the prompt and one user/machine has a latin1
encoded locale while a second one has utf-8, the non-ascii password
typed in won't match between machines.  Deal with this by making sure
that when we encrypt the data, we always use valid utf-8.

Fixes #20398

(cherry picked from commit 5dcce0666a)
2017-03-07 15:30:09 -05:00
Adrian Likins 6c6b647182 Fix 'ansible-vault edit /some/symlink' (#20417)
Since vault edit attempts to unlink
edited files before creating a new file
with the same name and writing to it, if
the file was a symlink, the symlink would
be replaced with a regular file.

VaultEditor file ops now check if files
it is changing are symlinks and instead
works directly on the target, so that
os.rename() and shutils do the right thing.

Add unit tests cases for this case and
assorted VaultEditor test cases.

Fixes #20264
2017-02-24 12:35:39 -05:00
Adrian Likins 7b6c992c46 Vault encrypt string cli (#21024)
* Add a vault 'encrypt_string' command.

The command will encrypt the string on the command
line and print out the yaml block that can be included
in a playbook.

To be prompted for a string to encrypt:
   
   ansible-vault encrypt_string --prompt

To specify a string on the command line:

   ansible-vault encrypt_string "some string to encrypt"

To read a string from stdin to encrypt:

   echo  "the plaintext to encrypt" | ansible-vault encrypt_string

If a --name or --stdin-name is provided, the output will include that name in yaml key value format: 

   $ ansible-vault encrypt_string "42" --name "the_answer"
    the_answer: !vault-encrypted |
          $ANSIBLE_VAULT;1.1;AES256
          <vault cipher text here>

plaintext provided via prompt, cli, and/or stdin can be mixed:

      $ ansible-vault encrypt_string "42" --name "the_answer" --prompt
      Vault password: 
      Variable name (enter for no name): some_variable
      String to encrypt: microfiber
      # The encrypted version of variable ("some_variable", the string #1 from the interactive prompt).
     some_variable: !vault-encrypted |
              $ANSIBLE_VAULT;1.1;AES256
              < vault cipher text here>
      # The encrypted version of variable ("the_answer", the string #2 from the command line args).
      the_answer: !vault-encrypted |
             $ANSIBLE_VAULT;1.1;AES256
             < vault cipher text here>

Encryption successful
* add stdin and prompting to vault 'encrypt_string'
* add a --name to encrypt_string to optional specify a var name
* prompt for a var name to use with --prompt
* add a --stdin-name for the var name for value read from stdin
2017-02-17 10:12:14 -05:00