def main():
    vault_file = sys.argv[1]
    new_vault_file = sys.argv[2]
    in_file = sys.argv[3]

    target_env = 'test'
    external_system_name = 'blabla'

    # Load vault password and prepare secrets for decryption
    loader = DataLoader()
    secret = vault.get_file_vault_secret(filename=vault_file, loader=loader)
    secret.load()
    vault_secrets = [('default', secret)]
    _vault = vault.VaultLib(vault_secrets)

    new_loader = DataLoader()
    new_secret = vault.get_file_vault_secret(filename=new_vault_file, loader=new_loader)
    new_secret.load()
    new_vault_secrets = [('default', new_secret)]
    _new_vault = vault.VaultLib(new_vault_secrets)

    # Load encrypted yml for processing
    with codecs.open(in_file, 'r', encoding='utf-8') as f:
        loaded_yaml = AnsibleLoader(f, vault_secrets=_vault.secrets).get_single_data()

    # Modify yml with new encrypted values
    new_encrypted_variable = objects.AnsibleVaultEncryptedUnicode.from_plaintext(external_system_password, _new_vault, new_vault_secrets[0][1])

    loaded_yaml[target_env]['credentials'][external_system_name]['password'] = new_encrypted_variable

    # Write a new encrypted yml
    with open("%s.new" % argv[1], 'wb') as fd:
        yaml.dump(loaded_yaml, fd, Dumper=AnsibleDumper, encoding=None, default_flow_style=False)

    print(loaded_yaml)
Example #2
0
    def setUp(self):
        self.vault_password = "******"
        self.good_vault = vault.VaultLib(self.vault_password)

        self.wrong_vault_password = '******'
        self.wrong_vault = vault.VaultLib(self.wrong_vault_password)

        self.vault = self.good_vault
Example #3
0
    def test_encrypt_decrypt_aes256_empty_secrets(self):
        vault_secrets = self._vault_secrets_from_password('default', 'ansible')
        v = vault.VaultLib(vault_secrets)

        plaintext = u"foobar"
        b_vaulttext = v.encrypt(plaintext)

        vault_secrets_empty = []
        v_none = vault.VaultLib(vault_secrets_empty)

        self.assertRaisesRegexp(
            vault.AnsibleVaultError,
            '.*Attempting to decrypt but no vault secrets found.*',
            v_none.decrypt, b_vaulttext)
Example #4
0
    def setUp(self):
        self.good_vault_password = "******"
        good_vault_secret = TextVaultSecret(self.good_vault_password)
        self.good_vault_secrets = [('good_vault_password', good_vault_secret)]
        self.good_vault = vault.VaultLib(self.good_vault_secrets)

        # TODO: make this use two vault secret identities instead of two vaultSecrets
        self.wrong_vault_password = '******'
        wrong_vault_secret = TextVaultSecret(self.wrong_vault_password)
        self.wrong_vault_secrets = [('wrong_vault_password', wrong_vault_secret)]
        self.wrong_vault = vault.VaultLib(self.wrong_vault_secrets)

        self.vault = self.good_vault
        self.vault_secrets = self.good_vault_secrets
Example #5
0
    def test_encrypt_decrypt_aes256_none_secrets(self):
        vault_secrets = self._vault_secrets_from_password('default', 'ansible')
        v = vault.VaultLib(vault_secrets)

        plaintext = u"foobar"
        b_vaulttext = v.encrypt(plaintext)

        # VaultLib will default to empty {} if secrets is None
        v_none = vault.VaultLib(None)
        # so set secrets None explicitly
        v_none.secrets = None
        self.assertRaisesRegexp(
            vault.AnsibleVaultError,
            '.*A vault password must be specified to decrypt data.*',
            v_none.decrypt, b_vaulttext)
    def get_password(self, account_id):
        """This method enables users to retrieve the password of an
        existing account that is identified by its Account ID.
        """

        api_endpoint = 'WebServices/PIMServices.svc/Accounts/{account_id}/Credentials'.format(
            account_id=account_id)

        v = vault.VaultLib([
            (to_bytes(account_id),
             vault.VaultSecret(
                 to_bytes(
                     self.cyberark_connection.get('password',
                                                  ANSIBLE_CYBERARK_PASSWORD))))
        ])

        if self._cache and to_bytes(account_id) in self._cache:
            result = v.decrypt(self._cache.get(to_bytes(account_id)))
        else:
            try:
                response = self.request(api_endpoint=api_endpoint)
                result = to_text(response.read())
                if self._cache:
                    self._cache[to_bytes(account_id)] = v.encrypt(result)
            except HTTPError as e:
                return

        return result
Example #7
0
 def setUp(self):
     self.vault_password = "******"
     vault_secret = TextVaultSecret(self.vault_password)
     self.vault_secrets = [('vault_secret', vault_secret)]
     self.good_vault = vault.VaultLib(self.vault_secrets)
     self.vault = self.good_vault
     self.stream = self._build_stream()
     self.dumper = dumper.AnsibleDumper
Example #8
0
def vault_decrypt(value):
    vault_password = cli.CLI.read_vault_password_file(
        _get_vault_password_file(), dataloader.DataLoader())
    this_vault = vault.VaultLib(vault_password)
    try:
        return this_vault.decrypt(value)
    except errors.AnsibleError:
        return None
Example #9
0
    def test_encrypt_no_secret_empty_secrets(self):
        vault_secrets = []
        v = vault.VaultLib(vault_secrets)

        plaintext = u'Some text to encrypt in a café'
        self.assertRaisesRegexp(
            vault.AnsibleVaultError,
            '.*A vault password must be specified to encrypt data.*',
            v.encrypt, plaintext)
Example #10
0
def _get_vault_lib():
    loader = dataloader.DataLoader()
    vault_ids = constants.DEFAULT_VAULT_IDENTITY_LIST

    vault_secrets = cli.CLI.setup_vault_secrets(loader, vault_ids=vault_ids,
                            vault_password_files=[_get_vault_password_file()],
                            ask_vault_pass=False,
                            auto_prompt=False)
    return vault.VaultLib(secrets=vault_secrets)
Example #11
0
    def test_wrong_password(self):
        plaintext = u"Ansible"
        bob_password = "******"

        bobs_vault = vault.VaultLib(bob_password)

        ciphertext = bobs_vault.encrypt(plaintext)

        try:
            self.vault.decrypt(ciphertext)
        except Exception as e:
            self.assertIsInstance(e, errors.AnsibleError)
            self.assertEqual(e.message, 'Decryption failed')
Example #12
0
    def test_encrypt_decrypt_aes256_multiple_secrets_all_wrong(self):
        plaintext = u'Some text to encrypt in a café'
        b_vaulttext = self.v.encrypt(plaintext)

        vault_secrets = [('default', TextVaultSecret('another-wrong-password')),
                         ('wrong-password', TextVaultSecret('wrong-password'))]

        v_multi = vault.VaultLib(vault_secrets)
        self.assertRaisesRegexp(errors.AnsibleError,
                                '.*Decryption failed.*',
                                v_multi.decrypt,
                                b_vaulttext,
                                filename='/dev/null/fake/filename')
Example #13
0
    def test_encrypt_decrypt_aes256_multiple_secrets_one_valid(self):
        plaintext = u'Some text to encrypt in a café'
        b_vaulttext = self.v.encrypt(plaintext)

        correct_secret = TextVaultSecret(self.vault_password)
        wrong_secret = TextVaultSecret('wrong-password')

        vault_secrets = [('default', wrong_secret),
                         ('corect_secret', correct_secret),
                         ('wrong_secret', wrong_secret)]

        v_multi = vault.VaultLib(vault_secrets)
        b_plaintext = v_multi.decrypt(b_vaulttext)
        self.assertNotEqual(b_vaulttext, to_bytes(plaintext), msg="encryption failed")
        self.assertEqual(b_plaintext, to_bytes(plaintext), msg="decryption failed")
Example #14
0
    def test_wrong_password(self):
        plaintext = u"Ansible"
        bob_password = "******"

        bobs_secret = TextVaultSecret(bob_password)
        bobs_secrets = [('default', bobs_secret)]

        bobs_vault = vault.VaultLib(bobs_secrets)

        ciphertext = bobs_vault.encrypt(plaintext, vault.match_encrypt_secret(bobs_secrets)[1])

        try:
            self.vault.decrypt(ciphertext)
        except Exception as e:
            self.assertIsInstance(e, errors.AnsibleError)
            self.assertEqual(e.message, 'Decryption failed (no vault secrets were found that could decrypt)')
Example #15
0
def decrypt(secrets_file_path, decrypted_file_path):

    try:
        vault_password_file = os.environ["ANSIBLE_VAULT_PASSWORD_FILE"]
    except KeyError:
        sys.exit(3)

    with open(vault_password_file, 'r') as vpf:
        vault_password = vpf.read().replace('\n', '')

    # Load vault password and prepare secrets for decryption
    loader = DataLoader()
    secret = vault.get_file_vault_secret(filename=vault_password_file, loader=loader)
    secret.load()
    vault_secrets = [('default', secret)]
    _vault = vault.VaultLib(vault_secrets)

    # Load encrypted yml for processing
    with codecs.open(secrets_file_path, 'r', encoding='utf-8') as f:
        loaded_yaml = AnsibleLoader(f, vault_secrets=_vault.secrets).get_single_data()

    # Define decrypted file params
    flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    mode = stat.S_IRUSR | stat.S_IWUSR  # 0o600 in octal
    umask = os.umask(0)  # Save current umask to prevent downgrading to 0

    # Delete and replace decrypted secrets to ensure file permissions
    try:
        os.remove(decrypted_file_path)
    except OSError:
        pass

    # Open the file descriptor
    umask_original = os.umask(umask)
    try:
        decrypted_file_fd = os.open(decrypted_file_path, flags, mode)
    finally:
        os.umask(umask_original)

    # Open file handle and write the decrypted file
    decrypted_file_out = os.fdopen(decrypted_file_fd, 'w')
    for k, v in loaded_yaml.items():
        line = "export " + str(k) + "=" + str(v) + "\n"
        decrypted_file_out.write(line)
    decrypted_file_out.close()
    print("secrets decrypted")
Example #16
0
    def test_decrypt_and_get_vault_id(self):
        b_expected_plaintext = to_bytes('foo bar\n')
        vaulttext = '''$ANSIBLE_VAULT;1.2;AES256;ansible_devel
65616435333934613466373335363332373764363365633035303466643439313864663837393234
3330656363343637313962633731333237313636633534630a386264363438363362326132363239
39363166646664346264383934393935653933316263333838386362633534326664646166663736
6462303664383765650a356637643633366663643566353036303162386237336233393065393164
6264'''

        vault_secrets = self._vault_secrets_from_password('ansible_devel', 'ansible')
        v = vault.VaultLib(vault_secrets)

        b_vaulttext = to_bytes(vaulttext)

        b_plaintext, vault_id_used, vault_secret_used = v.decrypt_and_get_vault_id(b_vaulttext)

        self.assertEqual(b_expected_plaintext, b_plaintext)
        self.assertEqual(vault_id_used, 'ansible_devel')
        self.assertEqual(vault_secret_used.text, 'ansible')
Example #17
0
    def test_decrypt_non_default_1_2(self):
        b_expected_plaintext = to_bytes('foo bar\n')
        vaulttext = '''$ANSIBLE_VAULT;1.2;AES256;ansible_devel
65616435333934613466373335363332373764363365633035303466643439313864663837393234
3330656363343637313962633731333237313636633534630a386264363438363362326132363239
39363166646664346264383934393935653933316263333838386362633534326664646166663736
6462303664383765650a356637643633366663643566353036303162386237336233393065393164
6264'''

        vault_secrets = self._vault_secrets_from_password('default', 'ansible')
        v = vault.VaultLib(vault_secrets)

        b_vaulttext = to_bytes(vaulttext)

        b_plaintext = v.decrypt(b_vaulttext)
        self.assertEqual(b_expected_plaintext, b_plaintext)

        b_ciphertext, b_version, cipher_name, vault_id = vault.parse_vaulttext_envelope(b_vaulttext)
        self.assertEqual('ansible_devel', vault_id)
        self.assertEqual(b'1.2', b_version)
Example #18
0
    def test_rekey_migration(self):
        # Skip testing rekeying files if we don't have access to AES, KDF or Counter.
        if not HAS_AES or not HAS_COUNTER or not HAS_PBKDF2:
            raise SkipTest

        v10_file = tempfile.NamedTemporaryFile(delete=False)
        with v10_file as f:
            f.write(to_bytes(v10_data))

        ve = vault.VaultEditor("ansible")

        # make sure the password functions for the cipher
        error_hit = False
        try:
            ve.rekey_file(v10_file.name, 'ansible2')
        except errors.AnsibleError:
            error_hit = True

        # verify decrypted content
        f = open(v10_file.name, "rb")
        fdata = f.read()
        f.close()

        assert error_hit is False, "error rekeying 1.0 file to 1.1"

        # ensure filedata can be decrypted, is 1.1 and is AES256
        vl = vault.VaultLib("ansible2")
        dec_data = None
        error_hit = False
        try:
            dec_data = vl.decrypt(fdata)
        except errors.AnsibleError:
            error_hit = True

        os.unlink(v10_file.name)

        assert vl.cipher_name == "AES256", "wrong cipher name set after rekey: %s" % vl.cipher_name
        assert error_hit is False, "error decrypting migrated 1.0 file"
        assert dec_data.strip(
        ) == b"foo", "incorrect decryption of rekeyed/migrated file: %s" % dec_data
Example #19
0
def vault_encrypt(value):
    vault_password = cli.CLI.read_vault_password_file(
        _get_vault_password_file(), dataloader.DataLoader())
    this_vault = vault.VaultLib(vault_password)
    return this_vault.encrypt(value)
Example #20
0
 def setUp(self):
     self.vault_password = "******"
     self.vault = vault.VaultLib(self.vault_password)
Example #21
0
 def setUp(self):
     self.vault_password = "******"
     self.good_vault = vault.VaultLib(self.vault_password)
     self.vault = self.good_vault
     self.stream = self._build_stream()
     self.dumper = dumper.AnsibleDumper
Example #22
0
 def setUp(self):
     self.vault_password = "******"
     text_secret = TextVaultSecret(self.vault_password)
     self.vault_secrets = [('default', text_secret),
                           ('test_id', text_secret)]
     self.v = vault.VaultLib(self.vault_secrets)
Example #23
0
def vault_encrypt(value):
    reload(constants)
    vault_password = cli.CLI.read_vault_password_file(
        constants.DEFAULT_VAULT_PASSWORD_FILE, dataloader.DataLoader())
    this_vault = vault.VaultLib(vault_password)
    return this_vault.encrypt(value)
Example #24
0
 def setUp(self):
     self.vault_password = "******"
     vault_secret = TextVaultSecret(self.vault_password)
     self.vault_secrets = [('vault_secret', vault_secret),
                           ('default', vault_secret)]
     self.vault = vault.VaultLib(self.vault_secrets)
Example #25
0
def vault_encrypt(value):
    this_vault = vault.VaultLib(_read_vault_password_file())
    return this_vault.encrypt(value)