Skip to content
Open
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
37 changes: 37 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,43 @@ UUID)::

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

dm-crypt workqueues
-------------------

On SSD and NVMe storage, vaultlocker opens devices with cryptsetup's
``--perf-no_read_workqueue`` and ``--perf-no_write_workqueue`` options,
which avoid the extra queuing dm-crypt otherwise adds. vaultlocker only
does this when all of the following are true:

* the kernel is 5.9 or later.
* cryptsetup is 2.3.4 or later.
* all storage backing the device is non-rotational. vaultlocker checks
through partitions, LVM and other device-mapper or MD RAID layers.

If any of these cannot be determined, vaultlocker does not add the
options. This applies to ``encrypt``, ``enroll`` and ``decrypt``,
including the unlock at boot.

To stop vaultlocker adding the options, for example while
troubleshooting, set ``bypass_workqueues = false`` in the ``[dmcrypt]``
section::

[dmcrypt]
bypass_workqueues = false

This does not override flags stored in a LUKS2 header with ``cryptsetup
--persistent``, which cryptsetup applies whenever the device is opened.
vaultlocker never stores these flags, but a device added with ``enroll``
may already have them. ``cryptsetup luksDump`` lists stored flags.

vaultlocker does not change devices that are already open. A device
opened by an earlier version of vaultlocker uses the new options after it
is next opened, such as after a reboot. Alternatively, ``cryptsetup
refresh --perf-no_read_workqueue --perf-no_write_workqueue crypt-<uuid>``
applies them to an open device; like ``open``, it needs the device key.
``cryptsetup status crypt-<uuid>`` lists ``no_read_workqueue
no_write_workqueue`` under ``flags`` when the workqueues are bypassed.

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

Expand Down
5 changes: 5 additions & 0 deletions etc/vaultlocker.conf
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,8 @@ secret_id = 9428ad25-7b4a-442f-8f20-f23be0575146
backend = secret
#kv_version = 1 # optional, defaults to 1. If you are using KV v2, set this to 2.
#ca_bundle =

[dmcrypt]
# Bypass the dm-crypt read and write workqueues on non-rotational storage
# when the kernel and cryptsetup support it. Set to false to disable.
#bypass_workqueues = true
148 changes: 147 additions & 1 deletion vaultlocker/dmcrypt.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
import base64
import logging
import os
import re
import stat
import subprocess

logger = logging.getLogger(__name__)
Expand All @@ -28,6 +30,21 @@
#: Maximum time to wait for a udevadm command.
UDEVADM_TIMEOUT_SECONDS = 60

#: cryptsetup options bypassing the dm-crypt read and write workqueues.
NO_WORKQUEUE_OPTIONS = (
'--perf-no_read_workqueue',
'--perf-no_write_workqueue',
)

#: First kernel release whose dm-crypt target can bypass its workqueues.
NO_WORKQUEUE_MIN_KERNEL = (5, 9, 0)

#: First cryptsetup release providing the workqueue bypass options.
NO_WORKQUEUE_MIN_CRYPTSETUP = (2, 3, 4)

#: sysfs directory linking block device numbers to their devices.
SYSFS_DEV_BLOCK = '/sys/dev/block'


def _key_bytes(key):
"""Normalize key material for subprocess input.
Expand Down Expand Up @@ -78,7 +95,130 @@ def luks_format(key, device, uuid):
)


def luks_open(key, uuid, device=None):
def _version(text):
"""Parse the first dotted version number in a string.

:param: text: string containing a version, e.g. a kernel release.
:returns: tuple. Major, minor and patch numbers.
:raises ValueError: if the string contains no version.
"""
match = re.search(r'(\d+)\.(\d+)(?:\.(\d+))?', text)
if not match:
raise ValueError('Unable to parse a version from {!r}'.format(text))
return tuple(int(part) for part in match.groups(default='0'))


def cryptsetup_version():
"""Get the installed cryptsetup version.

:returns: tuple. Major, minor and patch numbers.
"""
output = subprocess.check_output(
['cryptsetup', '--version'],
timeout=CRYPTSETUP_TIMEOUT_SECONDS,
).decode('utf-8')
return _version(output)


def _sysfs_block_dir(device):
"""Return the sysfs directory of a block device node.

:param: device: path to a block device node or a symlink to one.
:returns: str. Resolved sysfs directory of the device.
:raises ValueError: if the path is not a block device.
"""
device_stat = os.stat(device)
if not stat.S_ISBLK(device_stat.st_mode):
raise ValueError('{} is not a block device'.format(device))
return os.path.realpath(os.path.join(
SYSFS_DEV_BLOCK,
'{}:{}'.format(
os.major(device_stat.st_rdev),
os.minor(device_stat.st_rdev),
),
))


def _sysfs_rotational(sysfs_dir):
"""Return whether any storage beneath a sysfs block device rotates.

Partitions are resolved through their parent disk, and stacked
devices such as LVM, multipath and MD RAID through their slaves.

:param: sysfs_dir: resolved sysfs directory of a block device.
:returns: bool. True if any backing device is rotational.
"""
if os.path.exists(os.path.join(sysfs_dir, 'partition')):
# The parent may itself be a stacked device, e.g. an MD array.
return _sysfs_rotational(os.path.dirname(sysfs_dir))

slaves_dir = os.path.join(sysfs_dir, 'slaves')
slaves = os.listdir(slaves_dir) if os.path.isdir(slaves_dir) else []
if slaves:
return any(
_sysfs_rotational(
os.path.realpath(os.path.join(slaves_dir, slave))
)
for slave in slaves
)

with open(os.path.join(sysfs_dir, 'queue', 'rotational')) as rotational:
return rotational.read().strip() != '0'


def is_rotational(device):
"""Determine whether a block device is backed by rotational storage.

:param: device: path to a block device node or a symlink to one.
:returns: bool. True if any backing device is rotational.
"""
return _sysfs_rotational(_sysfs_block_dir(device))


def can_bypass_workqueues(device):
"""Determine whether to bypass the dm-crypt workqueues for a device.

The workqueues are bypassed when the kernel and cryptsetup support
it and all storage backing the device is non-rotational. If any of
these cannot be determined, the workqueues are kept.

:param: device: path to the LUKS block device.
:returns: bool. True if the workqueues can be bypassed.
"""
try:
kernel = os.uname().release
if _version(kernel) < NO_WORKQUEUE_MIN_KERNEL:
logger.info(
'Keeping dm-crypt workqueues for %s: kernel %s does not '
'support bypassing them', device, kernel,
)
return False

if is_rotational(device):
logger.info(
'Keeping dm-crypt workqueues for %s: backing storage is '
'rotational', device,
)
return False

if cryptsetup_version() < NO_WORKQUEUE_MIN_CRYPTSETUP:
logger.info(
'Keeping dm-crypt workqueues for %s: cryptsetup is older '
'than %s', device,
'.'.join(str(part) for part in NO_WORKQUEUE_MIN_CRYPTSETUP),
)
return False
except (OSError, ValueError, subprocess.SubprocessError) as error:
logger.warning(
'Keeping dm-crypt workqueues for %s: unable to determine '
'support for bypassing them: %s', device, error,
)
return False

return True


def luks_open(key, uuid, device=None, bypass_workqueues=False):
"""LUKS open a block device.

Open a block device using dm-crypt/LUKS with the
Expand All @@ -87,6 +227,8 @@ def luks_open(key, uuid, device=None):
:param: key: string containing the encryption key to use.
:param: uuid: uuid to use for encrypted block device.
:param: device: optional block device path. If omitted, use the UUID.
:param: bypass_workqueues: bypass the dm-crypt workqueues when the
kernel, cryptsetup and backing storage support it.
:returns: str. dm-crypt mapping
"""
logger.info('LUKS opening %s', uuid)
Expand All @@ -103,6 +245,10 @@ def luks_open(key, uuid, device=None):
'--type',
'luks',
]
if bypass_workqueues and can_bypass_workqueues(
device or '/dev/disk/by-uuid/{}'.format(uuid)):
logger.info('Bypassing dm-crypt workqueues for %s', handle)
command.extend(NO_WORKQUEUE_OPTIONS)
subprocess.check_output(
command,
input=_key_bytes(key),
Expand Down
41 changes: 34 additions & 7 deletions vaultlocker/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,25 @@ def _get_kv_version(config):
return version


def _bypass_workqueues(config):
"""Return whether dm-crypt workqueues may be bypassed.

:param config: configparser object of vaultlocker config
:returns: bool: False if disabled in the configuration
:raises exceptions.ConfigurationError: if the value is not a boolean
"""
try:
return config.getboolean(
'dmcrypt', 'bypass_workqueues', fallback=True,
)
except ValueError as value_error:
raise exceptions.ConfigurationError(
"Invalid bypass_workqueues in vaultlocker config: {}".format(
value_error,
)
) from value_error


def get_hostname(config):
"""Determine the hostname to use in Vault paths.

Expand Down Expand Up @@ -418,11 +437,15 @@ def _ensure_vault_key(store, path, expected_key):
)


def _open_and_register_device(block_device, block_uuid, key, config_path):
def _open_and_register_device(block_device, block_uuid, key, config,
config_path):
"""Open the mapper if needed and register it for boot."""
if not _device_exists(block_uuid):
try:
dmcrypt.luks_open(key, block_uuid, block_device)
dmcrypt.luks_open(
key, block_uuid, block_device,
bypass_workqueues=_bypass_workqueues(config),
)
except (subprocess.CalledProcessError,
subprocess.TimeoutExpired) as open_error:
raise exceptions.MapperOpenError(
Expand Down Expand Up @@ -466,7 +489,7 @@ def _open_existing_managed_device(args, client, config, block_device,
)

return _open_and_register_device(
block_device, block_uuid, vault_key, args.config,
block_device, block_uuid, vault_key, config, args.config,
)


Expand Down Expand Up @@ -533,7 +556,7 @@ def _format_device(args, client, config, block_device, block_uuid, key):
)

return _open_and_register_device(
block_device, block_uuid, key, args.config,
block_device, block_uuid, key, config, args.config,
)


Expand Down Expand Up @@ -587,7 +610,7 @@ def _enroll_block_device(args, client, config, get_operator_key):
if vault_key is not None and _key_unlocks_device(vault_key, block_device):
# Reuse an enrolled key without asking for the current key.
return _open_and_register_device(
block_device, block_uuid, vault_key, args.config,
block_device, block_uuid, vault_key, config, args.config,
)

# Read the operator's key only when the device needs to change.
Expand Down Expand Up @@ -618,7 +641,7 @@ def _enroll_block_device(args, client, config, get_operator_key):
)

return _open_and_register_device(
block_device, block_uuid, vault_key, args.config,
block_device, block_uuid, vault_key, config, args.config,
)


Expand Down Expand Up @@ -650,7 +673,10 @@ def _decrypt_block_device(args, client, config):
)

try:
dmcrypt.luks_open(vault_key, block_uuid)
dmcrypt.luks_open(
vault_key, block_uuid,
bypass_workqueues=_bypass_workqueues(config),
)
except (subprocess.CalledProcessError,
subprocess.TimeoutExpired) as open_error:
raise exceptions.MapperOpenError(
Expand Down Expand Up @@ -797,6 +823,7 @@ def get_config(config_path):
)

_get_kv_version(config)
_bypass_workqueues(config)
except exceptions.ConfigurationError:
raise
except (OSError, configparser.Error) as config_error:
Expand Down
1 change: 1 addition & 0 deletions vaultlocker/tests/functional/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ def setUp(self):
lambda s, k, **kwargs: self.test_config.get(s, {}).get(
k, kwargs.get('fallback')
)
self.config.getboolean.side_effect = self.config.get.side_effect

self.temp_dir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.temp_dir, ignore_errors=True)
Expand Down
18 changes: 12 additions & 6 deletions vaultlocker/tests/functional/test_keystorage.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,9 @@ def test_cluster_mismatch_warns_and_attempts_decrypt(
'Vault cluster identity mismatch' in warning
for warning in logged.output
))
_luks_open.assert_called_once_with('testkey', 'passed-UUID')
_luks_open.assert_called_once_with(
'testkey', 'passed-UUID', bypass_workqueues=True,
)
with open(pin_path, 'r', encoding='utf-8') as sidecar:
self.assertEqual('different-cluster', sidecar.read())

Expand All @@ -144,8 +146,9 @@ def test_encrypt(self, _luks_open, _luks_format, _boot_unlock,

_luks_format.assert_called_once_with(mock.ANY, '/dev/sdb',
'passed-UUID')
_luks_open.assert_called_once_with(mock.ANY, 'passed-UUID',
'/dev/sdb')
_luks_open.assert_called_once_with(
mock.ANY, 'passed-UUID', '/dev/sdb', bypass_workqueues=True,
)
_boot_unlock.register.assert_called_once_with('passed-UUID',
self.config_path)
_udevadm_rescan.assert_called_once_with('/dev/sdb')
Expand Down Expand Up @@ -231,7 +234,9 @@ def test_decrypt(self, _luks_open, _luks_format, _boot_unlock,

_luks_format.assert_not_called()
_boot_unlock.register.assert_not_called()
_luks_open.assert_called_once_with('testkey', 'passed-UUID')
_luks_open.assert_called_once_with(
'testkey', 'passed-UUID', bypass_workqueues=True,
)

def test_decrypt_missing_key(self, _luks_open, _luks_format, _boot_unlock,
_udevadm_rescan, _udevadm_settle):
Expand Down Expand Up @@ -272,8 +277,9 @@ def test_enroll_adds_managed_key(self, _luks_open, _luks_format,

add_key.assert_called_once_with(b'operatorpass', mock.ANY,
'/dev/sdb')
_luks_open.assert_called_once_with(mock.ANY, 'passed-UUID',
'/dev/sdb')
_luks_open.assert_called_once_with(
mock.ANY, 'passed-UUID', '/dev/sdb', bypass_workqueues=True,
)
_boot_unlock.register.assert_called_once_with('passed-UUID',
self.config_path)

Expand Down
Loading
Loading