Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
[run]
branch = True
source = vaultlocker
omit =
vaultlocker/tests/*

[report]
ignore_errors = True
fail_under = 90
13 changes: 11 additions & 2 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,22 @@ UUID)::

sudo vaultlocker decrypt f65b9e66-8f0c-4cae-b6f5-6ec85ea134f2

Vault authentication
--------------------
Vault authentication and cluster identity
-----------------------------------------

Authentication to Vault is done using an AppRole with a secret_id; its assumed
that a CIDR based ACL is in use to only allow permitted systems within the
Data Center to login and retrieve secrets from Vault.

After authentication, vaultlocker saves the Vault cluster ID in ``<config-path>.cluster-id``.
If the ID later changes, ``encrypt`` and ``enroll`` operations will fail with an error.
``decrypt`` will log a warning and try to find the key in the observed Vault cluster. If
that Vault does not have the key, vaultlocker cannot unlock the device.

If the change is unexpected, check the Vault url and restore the connection to
the original cluster. Deleting the pin does not move existing keys.
Vaultlocker does not support automatically migrating keys between clusters.

* Free software: Apache license
* Documentation: https://docs.openstack.org/vaultlocker/latest
* Source: https://git.openstack.org/cgit/openstack/vaultlocker
Expand Down
1 change: 1 addition & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ commands =
coverage combine
coverage html -d cover
coverage xml -o cover/coverage.xml
coverage report --show-missing

[testenv:docs]
commands = python setup.py build_sphinx
Expand Down
14 changes: 14 additions & 0 deletions vaultlocker/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,17 @@ class MapperOpenError(LUKSFailure):

class BootConfigError(LUKSFailure):
"""Registering the boot-time unlock mechanism failed."""


class ClusterIdentityError(VaultlockerException):
"""The Vault cluster identity could not be verified."""


class ClusterIdentityMismatchError(ClusterIdentityError):
"""The connected Vault cluster does not match the saved cluster."""

def __init__(self, expected, actual):
super().__init__(
"Vault cluster identity mismatch: pinned cluster_id={}, "
"observed cluster_id={}".format(expected, actual)
)
Comment on lines +121 to +128

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

todo: A user may not be aware of the sidecar file used to verify the cluster ID. We should add remediation steps to this message. For example: "If this change is expected, remove {pin_path} and re-run."

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

todo: In addition to suggesting how to correct the issue in this message, we should also add some documentation (in the README for now) of steps to take when migrating Vault.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we should suggest removing the pin. A mismatch can mean the original Vault still holds keys for devices we already manage. If we remove the pin, new operations could start using a different Vault without those keys being migrated. Vault migration is currently out of scope but it may be worth documenting this in the README.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That makes sense, thanks. My primary concern was having some way to advertise that the pin file exists and what it's for.

110 changes: 99 additions & 11 deletions vaultlocker/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@
import json
import logging
import os
from pathlib import Path
import platform
import socket
import subprocess
import sys
import tempfile
import uuid

import hvac
Expand All @@ -40,22 +42,96 @@

REQUIRED_VAULT_SETTINGS = ('url', 'approle', 'secret_id', 'backend')

#: Suffix of the sidecar file pinning the Vault cluster identity.
CLUSTER_ID_SUFFIX = '.cluster-id'

def _vault_client(config):
"""Helper wrapper to create Vault Client

:param: config: configparser object of vaultlocker config
:returns: hvac.Client. configured Vault Client object
"""
client = hvac.Client(
def _vault_client(config):
"""Create an unauthenticated Vault client."""
return hvac.Client(
url=config.get('vault', 'url'),
verify=config.get('vault', 'ca_bundle', fallback=True)
verify=config.get('vault', 'ca_bundle', fallback=True),
)


def _login_to_vault(client, config):
"""Authenticate a Vault client with AppRole credentials."""
client.auth.approle.login(
role_id=config.get('vault', 'approle'),
secret_id=config.get('vault', 'secret_id')
secret_id=config.get('vault', 'secret_id'),
)
return client


def _cluster_pin_path(config_path):
"""Return the cluster pin path for a configuration file."""
return '{}{}'.format(config_path, CLUSTER_ID_SUFFIX)


def _read_cluster_pin(path):
"""Read the cluster pin from a sidecar."""
try:
with open(path, 'r', encoding='utf-8') as sidecar:
value = sidecar.read().strip()
except (OSError, UnicodeError) as read_error:
raise exceptions.ClusterIdentityError(
'Unable to read Vault cluster identity {}: {}'.format(
path, read_error,
)
) from read_error
if not value:
raise exceptions.ClusterIdentityError(
'Invalid Vault cluster identity in {}'.format(path)
)
return value


def _create_cluster_pin(path, cluster_id):
"""Create a complete pin without replacing an existing one."""
path = Path(path)
try:
# For almost all runs, the pin already exists.
try:
path.lstat()
except FileNotFoundError:
pass
else:
return _read_cluster_pin(path)

fd, temporary_name = tempfile.mkstemp(dir=path.parent)
temporary_path = Path(temporary_name)
try:
with os.fdopen(fd, 'w', encoding='utf-8') as temp_file:
os.fchmod(temp_file.fileno(), 0o600)
temp_file.write(cluster_id)

try:
os.link(temporary_path, path)
except FileExistsError:
# Another process created it first.
return _read_cluster_pin(path)

return cluster_id
finally:
temporary_path.unlink(missing_ok=True)
except (OSError, UnicodeError) as error:
raise exceptions.ClusterIdentityError(
'Unable to create Vault cluster identity {}: {}'.format(
path, error,
)
) from error


def _verify_cluster_identity(client, config_path):
"""Pin the Vault cluster on first use and verify later connections."""
observed_id = vault.get_cluster_id(client)

pin_path = _cluster_pin_path(config_path)
pinned_id = _create_cluster_pin(pin_path, observed_id)

if pinned_id != observed_id:
raise exceptions.ClusterIdentityMismatchError(
pinned_id, observed_id,
)


def _get_kv_version(config):
Expand Down Expand Up @@ -590,12 +666,14 @@ def _device_exists(block_uuid):
return os.path.exists(path)


def _do_it_with_persistence(func, args, config):
def _do_it_with_persistence(func, args, config,
fail_on_cluster_mismatch=True):
"""Run an operation, retrying temporary Vault availability failures.

:param: func: function to attempt to execute
:param: args: argparser generated cli arguments
:param: config: configparser object of vaultlocker config
:param: fail_on_cluster_mismatch: whether to stop on a mismatch
:returns: the operation result
"""
@tenacity.retry(
Expand All @@ -613,6 +691,13 @@ def _do_it_with_persistence(func, args, config):
)
def _do_it():
client = _vault_client(config)
_login_to_vault(client, config)
try:
_verify_cluster_identity(client, args.config)
except exceptions.ClusterIdentityMismatchError as mismatch_error:
if fail_on_cluster_mismatch:
raise
logger.warning('Cluster identity mismatch: %s', mismatch_error)
Comment on lines +694 to +700

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: According to the hvac docs, read_seal_status() reads from an unauthenticated endpoint, so the login should not be necessary since that's what _verify_cluster_identity() calls. If login is needed for other actions, it can be moved after verifying the cluster's identity.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So on the first run we create the cluster id pin. If we verify the cluster before authenticating, we could end up pinning a vault that we were never able to authenticate to. If login fails, we should not pin a Vault that these credentials could not access. I will add a comment to clarify this order.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for clarifying

return func(args, client, config)

try:
Expand Down Expand Up @@ -678,7 +763,10 @@ def decrypt(args, config):
:param: args: argparser generated cli arguments
:param: config: configparser object of vaultlocker config
"""
return _do_it_with_persistence(_decrypt_block_device, args, config)
return _do_it_with_persistence(
_decrypt_block_device, args, config,
fail_on_cluster_mismatch=False,
)


def get_config(config_path):
Expand Down
88 changes: 88 additions & 0 deletions vaultlocker/tests/functional/test_keystorage.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,94 @@ class KeyStorageTestCase(base.VaultlockerFuncBaseTestCase):
Subclasses run this suite against KV version 1 and 2.
"""

def test_cluster_identity_pin_with_real_vault(
self, _luks_open, _luks_format, _boot_unlock,
_udevadm_rescan, _udevadm_settle):
"""Seal status provides the value stored in the pin."""
shell._verify_cluster_identity(self.vault_client, self.config_path)

pin_path = shell._cluster_pin_path(self.config_path)
with open(pin_path, 'r', encoding='utf-8') as sidecar:
self.assertEqual(
shell.vault.get_cluster_id(self.vault_client),
sidecar.read(),
)

def _write_mismatching_pin(self):
pin_path = shell._cluster_pin_path(self.config_path)
with open(pin_path, 'w', encoding='utf-8') as sidecar:
sidecar.write('different-cluster')
return pin_path

def test_cluster_mismatch_stops_encrypt(
self, _luks_open, _luks_format, _boot_unlock,
_udevadm_rescan, _udevadm_settle):
"""Encrypt does not change a device on a cluster mismatch."""
pin_path = self._write_mismatching_pin()

args = mock.MagicMock()
args.uuid = 'passed-UUID'
args.block_device = ['/dev/sdb']
args.retry = -1
args.config = self.config_path

with self.assertRaises(shell.exceptions.ClusterIdentityMismatchError):
shell.encrypt(args, self.config)

_luks_open.assert_not_called()
_luks_format.assert_not_called()
with open(pin_path, 'r', encoding='utf-8') as sidecar:
self.assertEqual('different-cluster', sidecar.read())

def test_cluster_mismatch_stops_enroll(
self, _luks_open, _luks_format, _boot_unlock,
_udevadm_rescan, _udevadm_settle):
"""Enroll does not change a device on a cluster mismatch."""
pin_path = self._write_mismatching_pin()

args = mock.MagicMock()
args.block_device = ['/dev/sdb']
args.existing_key_file = None
args.retry = -1
args.config = self.config_path

with mock.patch.object(shell, '_read_existing_key') as read_key:
with self.assertRaises(
shell.exceptions.ClusterIdentityMismatchError):
shell.enroll(args, self.config)

read_key.assert_not_called()
_luks_open.assert_not_called()
with open(pin_path, 'r', encoding='utf-8') as sidecar:
self.assertEqual('different-cluster', sidecar.read())

def test_cluster_mismatch_warns_and_attempts_decrypt(
self, _luks_open, _luks_format, _boot_unlock,
_udevadm_rescan, _udevadm_settle):
"""Decrypt attempts an unlock with a key from the observed Vault."""
pin_path = self._write_mismatching_pin()
self.vault_store().write(
self.secret_path('passed-UUID'),
{'dmcrypt_key': 'testkey'},
)

args = mock.MagicMock()
args.uuid = ['passed-UUID']
args.retry = -1
args.config = self.config_path

with mock.patch.object(shell, '_device_exists', return_value=False):
with self.assertLogs(shell.logger, level='WARNING') as logged:
shell.decrypt(args, self.config)

self.assertTrue(any(
'Vault cluster identity mismatch' in warning
for warning in logged.output
))
_luks_open.assert_called_once_with('testkey', 'passed-UUID')
with open(pin_path, 'r', encoding='utf-8') as sidecar:
self.assertEqual('different-cluster', sidecar.read())

def test_encrypt(self, _luks_open, _luks_format, _boot_unlock,
_udevadm_rescan, _udevadm_settle):
"""Test encrypt function stores correct data in vault"""
Expand Down
7 changes: 6 additions & 1 deletion vaultlocker/tests/unit/test_command_results.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,10 @@ def test_main_returns_unexpected_failure_for_unknown_error(
file=shell.sys.stderr,
)

@mock.patch.object(shell, '_verify_cluster_identity')
@mock.patch.object(shell, '_vault_client')
def test_retry_wrapper_returns_operation_result(self, vault_client):
def test_retry_wrapper_returns_operation_result(
self, vault_client, verify_cluster_identity):
operation = mock.Mock(return_value={'luks_uuid': 'test-uuid'})
args = mock.Mock(retry=-1)
config = mock.Mock()
Expand All @@ -95,6 +97,9 @@ def test_retry_wrapper_returns_operation_result(self, vault_client):
operation.assert_called_once_with(
args, vault_client.return_value, config,
)
verify_cluster_identity.assert_called_once_with(
vault_client.return_value, args.config,
)

@mock.patch.object(shell, '_vault_client')
def test_retry_wrapper_reports_vault_errors(self, vault_client):
Expand Down
7 changes: 7 additions & 0 deletions vaultlocker/tests/unit/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ def test_base_uses_first_argument_as_message(self):

self.assertEqual('boom', str(error))

def test_cluster_identity_mismatch_message(self):
error = exceptions.ClusterIdentityMismatchError('cluster-a',
'cluster-b')

self.assertIn('cluster-a', str(error))
self.assertIn('cluster-b', str(error))

def test_managed_key_not_found_message(self):
error = exceptions.ManagedKeyNotFoundError('mount/host/uuid')

Expand Down
30 changes: 30 additions & 0 deletions vaultlocker/tests/unit/test_vault.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import hvac

from vaultlocker import exceptions
from vaultlocker.tests.unit import base
from vaultlocker import vault

Expand Down Expand Up @@ -181,3 +182,32 @@ def test_get_store_rejects_unsupported_version(self):
)

self.assertIn("Unsupported kv_version '3'", str(error.exception))


class TestClusterId(base.TestCase):

def setUp(self):
super().setUp()
self.client = mock.MagicMock()

def test_get_cluster_id(self):
self.client.sys.read_seal_status.return_value = {
'cluster_id': 'test-cluster-id',
}

self.assertEqual(
'test-cluster-id',
vault.get_cluster_id(self.client),
)
self.client.sys.read_seal_status.assert_called_once_with()

def test_invalid_cluster_id_fails(self):
invalid_responses = (
{}, {'cluster_id': ''}, {'cluster_id': None},
{'cluster_id': 42}, None,
)
for response in invalid_responses:
with self.subTest(response=response):
self.client.sys.read_seal_status.return_value = response
with self.assertRaises(exceptions.ClusterIdentityError):
vault.get_cluster_id(self.client)
Loading
Loading