From fb19eaaedda9a294857ea9a709d2b6b466a0c2f6 Mon Sep 17 00:00:00 2001 From: Peter Sabaini Date: Tue, 27 Oct 2026 01:56:08 +0100 Subject: [PATCH] feat: bypass dm-crypt workqueues on non-rotational storage Open LUKS devices with --perf-no_read_workqueue and --perf-no_write_workqueue when the kernel is 5.9 or later, cryptsetup is 2.3.4 or later, and all backing storage is non-rotational. Backing storage is resolved through sysfs, following partitions to their parent device and device-mapper and MD devices to their slaves. If support cannot be determined, vaultlocker does not add the options. This applies to encrypt, enroll and decrypt, including boot-time unlocking. Set bypass_workqueues = false in the [dmcrypt] section of the configuration to stop vaultlocker adding the options. Flags stored persistently in a LUKS2 header still apply. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Peter Sabaini --- README.rst | 37 +++ etc/vaultlocker.conf | 5 + vaultlocker/dmcrypt.py | 148 +++++++++- vaultlocker/shell.py | 41 ++- vaultlocker/tests/functional/base.py | 1 + .../tests/functional/test_keystorage.py | 18 +- vaultlocker/tests/unit/test_dmcrypt.py | 273 ++++++++++++++++++ vaultlocker/tests/unit/test_vaultlocker.py | 103 +++++-- 8 files changed, 595 insertions(+), 31 deletions(-) diff --git a/README.rst b/README.rst index b697174..b7fe80f 100644 --- a/README.rst +++ b/README.rst @@ -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-`` +applies them to an open device; like ``open``, it needs the device key. +``cryptsetup status crypt-`` lists ``no_read_workqueue +no_write_workqueue`` under ``flags`` when the workqueues are bypassed. + Vault authentication and cluster identity ----------------------------------------- diff --git a/etc/vaultlocker.conf b/etc/vaultlocker.conf index ed52891..7a81a86 100644 --- a/etc/vaultlocker.conf +++ b/etc/vaultlocker.conf @@ -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 diff --git a/vaultlocker/dmcrypt.py b/vaultlocker/dmcrypt.py index b827baf..5953c68 100644 --- a/vaultlocker/dmcrypt.py +++ b/vaultlocker/dmcrypt.py @@ -15,6 +15,8 @@ import base64 import logging import os +import re +import stat import subprocess logger = logging.getLogger(__name__) @@ -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. @@ -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 @@ -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) @@ -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), diff --git a/vaultlocker/shell.py b/vaultlocker/shell.py index 9b85ef6..72e7523 100644 --- a/vaultlocker/shell.py +++ b/vaultlocker/shell.py @@ -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. @@ -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( @@ -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, ) @@ -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, ) @@ -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. @@ -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, ) @@ -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( @@ -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: diff --git a/vaultlocker/tests/functional/base.py b/vaultlocker/tests/functional/base.py index ace5731..b6f4619 100644 --- a/vaultlocker/tests/functional/base.py +++ b/vaultlocker/tests/functional/base.py @@ -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) diff --git a/vaultlocker/tests/functional/test_keystorage.py b/vaultlocker/tests/functional/test_keystorage.py index 83825a7..f9baf15 100644 --- a/vaultlocker/tests/functional/test_keystorage.py +++ b/vaultlocker/tests/functional/test_keystorage.py @@ -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()) @@ -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') @@ -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): @@ -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) diff --git a/vaultlocker/tests/unit/test_dmcrypt.py b/vaultlocker/tests/unit/test_dmcrypt.py index dfe1852..0281fb2 100644 --- a/vaultlocker/tests/unit/test_dmcrypt.py +++ b/vaultlocker/tests/unit/test_dmcrypt.py @@ -20,7 +20,10 @@ """ import base64 +import os +import stat import subprocess +import tempfile from unittest import mock from vaultlocker import dmcrypt @@ -78,6 +81,68 @@ def test_luks_open_by_device(self, _subprocess): timeout=dmcrypt.CRYPTSETUP_TIMEOUT_SECONDS, ) + @mock.patch.object(dmcrypt, 'can_bypass_workqueues', return_value=True) + @mock.patch.object(dmcrypt, 'subprocess') + def test_luks_open_bypasses_workqueues(self, _subprocess, _can_bypass): + dmcrypt.luks_open('mykey', 'test-uuid', bypass_workqueues=True) + _can_bypass.assert_called_once_with('/dev/disk/by-uuid/test-uuid') + _subprocess.check_output.assert_called_once_with( + ['cryptsetup', + '--batch-mode', + '--key-file', '-', + 'open', 'UUID=test-uuid', 'crypt-test-uuid', + '--type', 'luks', + '--perf-no_read_workqueue', + '--perf-no_write_workqueue'], + input='mykey'.encode('UTF-8'), + timeout=dmcrypt.CRYPTSETUP_TIMEOUT_SECONDS, + ) + + @mock.patch.object(dmcrypt, 'can_bypass_workqueues', return_value=True) + @mock.patch.object(dmcrypt, 'subprocess') + def test_luks_open_by_device_bypasses_workqueues( + self, _subprocess, _can_bypass): + dmcrypt.luks_open( + 'mykey', 'test-uuid', '/dev/sdb', bypass_workqueues=True, + ) + _can_bypass.assert_called_once_with('/dev/sdb') + _subprocess.check_output.assert_called_once_with( + ['cryptsetup', + '--batch-mode', + '--key-file', '-', + 'open', '/dev/sdb', 'crypt-test-uuid', + '--type', 'luks', + '--perf-no_read_workqueue', + '--perf-no_write_workqueue'], + input='mykey'.encode('UTF-8'), + timeout=dmcrypt.CRYPTSETUP_TIMEOUT_SECONDS, + ) + + @mock.patch.object(dmcrypt, 'can_bypass_workqueues', return_value=False) + @mock.patch.object(dmcrypt, 'subprocess') + def test_luks_open_keeps_workqueues_when_unsupported( + self, _subprocess, _can_bypass): + dmcrypt.luks_open( + 'mykey', 'test-uuid', '/dev/sdb', bypass_workqueues=True, + ) + _can_bypass.assert_called_once_with('/dev/sdb') + _subprocess.check_output.assert_called_once_with( + ['cryptsetup', + '--batch-mode', + '--key-file', '-', + 'open', '/dev/sdb', 'crypt-test-uuid', + '--type', 'luks'], + input='mykey'.encode('UTF-8'), + timeout=dmcrypt.CRYPTSETUP_TIMEOUT_SECONDS, + ) + + @mock.patch.object(dmcrypt, 'can_bypass_workqueues') + @mock.patch.object(dmcrypt, 'subprocess') + def test_luks_open_does_not_probe_when_disabled( + self, _subprocess, _can_bypass): + dmcrypt.luks_open('mykey', 'test-uuid', '/dev/sdb') + _can_bypass.assert_not_called() + @mock.patch.object(dmcrypt, 'os') def test_generate_key(self, _os): _key = b'randomdatastringfromentropy' @@ -261,3 +326,211 @@ def test_luks_format_timeout_propagates(self, _check_output): with self.assertRaises(subprocess.TimeoutExpired): dmcrypt.luks_format('mykey', '/dev/sdb', 'test-uuid') + + +class TestWorkqueueBypass(base.TestCase): + """Tests deciding whether to bypass the dm-crypt workqueues.""" + + def test_version_parses_kernel_release(self): + self.assertEqual((7, 0, 0), dmcrypt._version('7.0.0-38-generic')) + self.assertEqual((5, 9, 0), dmcrypt._version('5.9-rc1')) + + def test_version_parses_cryptsetup_output(self): + self.assertEqual( + (2, 7, 0), + dmcrypt._version('cryptsetup 2.7.0 flags: UDEV BLKID KEYRING\n'), + ) + + def test_version_rejects_text_without_version(self): + with self.assertRaises(ValueError): + dmcrypt._version('cryptsetup') + + @mock.patch.object(dmcrypt.subprocess, 'check_output') + def test_cryptsetup_version(self, _check_output): + _check_output.return_value = b'cryptsetup 2.3.7\n' + + self.assertEqual((2, 3, 7), dmcrypt.cryptsetup_version()) + _check_output.assert_called_once_with( + ['cryptsetup', '--version'], + timeout=dmcrypt.CRYPTSETUP_TIMEOUT_SECONDS, + ) + + @mock.patch.object(dmcrypt, 'cryptsetup_version', return_value=(2, 7, 0)) + @mock.patch.object(dmcrypt, 'is_rotational', return_value=False) + @mock.patch.object(dmcrypt.os, 'uname') + def test_bypass_when_supported_and_non_rotational( + self, _uname, _is_rotational, _cryptsetup_version): + _uname.return_value.release = '7.0.0-38-generic' + + self.assertTrue(dmcrypt.can_bypass_workqueues('/dev/nvme0n1')) + _is_rotational.assert_called_once_with('/dev/nvme0n1') + + @mock.patch.object(dmcrypt, 'cryptsetup_version') + @mock.patch.object(dmcrypt, 'is_rotational') + @mock.patch.object(dmcrypt.os, 'uname') + def test_keep_workqueues_on_old_kernel( + self, _uname, _is_rotational, _cryptsetup_version): + _uname.return_value.release = '5.8.0-63-generic' + + self.assertFalse(dmcrypt.can_bypass_workqueues('/dev/nvme0n1')) + _is_rotational.assert_not_called() + _cryptsetup_version.assert_not_called() + + @mock.patch.object(dmcrypt, 'cryptsetup_version') + @mock.patch.object(dmcrypt, 'is_rotational', return_value=True) + @mock.patch.object(dmcrypt.os, 'uname') + def test_keep_workqueues_on_rotational_storage( + self, _uname, _is_rotational, _cryptsetup_version): + _uname.return_value.release = '6.8.0-31-generic' + + self.assertFalse(dmcrypt.can_bypass_workqueues('/dev/sdb')) + _cryptsetup_version.assert_not_called() + + @mock.patch.object(dmcrypt, 'cryptsetup_version', return_value=(2, 3, 3)) + @mock.patch.object(dmcrypt, 'is_rotational', return_value=False) + @mock.patch.object(dmcrypt.os, 'uname') + def test_keep_workqueues_with_old_cryptsetup( + self, _uname, _is_rotational, _cryptsetup_version): + _uname.return_value.release = '6.8.0-31-generic' + + self.assertFalse(dmcrypt.can_bypass_workqueues('/dev/nvme0n1')) + + @mock.patch.object(dmcrypt, 'cryptsetup_version', return_value=(2, 7, 0)) + @mock.patch.object(dmcrypt, 'is_rotational', return_value=False) + @mock.patch.object(dmcrypt.os, 'uname') + def test_keep_workqueues_when_detection_fails( + self, _uname, _is_rotational, _cryptsetup_version): + _uname.return_value.release = '6.8.0-31-generic' + failures = ( + ('is_rotational', FileNotFoundError('no such device')), + ('is_rotational', ValueError('not a block device')), + ('cryptsetup_version', subprocess.CalledProcessError( + returncode=1, cmd='cryptsetup --version')), + ('cryptsetup_version', subprocess.TimeoutExpired( + cmd='cryptsetup --version', timeout=300)), + ) + for name, failure in failures: + with self.subTest(name=name, failure=failure): + with mock.patch.object(dmcrypt, name, side_effect=failure): + self.assertFalse( + dmcrypt.can_bypass_workqueues('/dev/nvme0n1'), + ) + + @mock.patch.object(dmcrypt, 'is_rotational') + @mock.patch.object(dmcrypt.os, 'uname') + def test_keep_workqueues_with_unknown_kernel( + self, _uname, _is_rotational): + _uname.return_value.release = 'unknown' + + self.assertFalse(dmcrypt.can_bypass_workqueues('/dev/nvme0n1')) + _is_rotational.assert_not_called() + + +class TestRotational(base.TestCase): + """Tests resolving rotational storage through sysfs.""" + + def setUp(self): + super().setUp() + temp_dir = tempfile.TemporaryDirectory() + self.addCleanup(temp_dir.cleanup) + self.sysfs = temp_dir.name + + # Non-rotational disk with a partition. + self.nvme = self._disk('devices/nvme0n1', rotational='0') + self.nvme_part = self._partition(self.nvme, 'nvme0n1p1') + # Rotational disk. + self.sda = self._disk('devices/sda', rotational='1') + # LVM on the NVMe partition. Some kernels report device-mapper + # devices as rotational, so the slaves decide. + self.lv = self._disk( + 'devices/virtual/dm-0', rotational='1', + slaves=[self.nvme_part], + ) + # LVM spanning both disks. + self.mixed_lv = self._disk( + 'devices/virtual/dm-1', rotational='0', + slaves=[self.nvme_part, self.sda], + ) + # A device stacked on the first LVM volume. + self.nested = self._disk( + 'devices/virtual/dm-2', rotational='1', slaves=[self.lv], + ) + # A partitioned MD array on the NVMe disk. Linux reports a + # degraded array as rotational, so the slaves decide. + self.md = self._disk( + 'devices/virtual/md0', rotational='1', slaves=[self.nvme], + ) + self.md_part = self._partition(self.md, 'md0p1') + + def _disk(self, path, rotational, slaves=()): + disk = os.path.join(self.sysfs, path) + os.makedirs(os.path.join(disk, 'queue')) + os.makedirs(os.path.join(disk, 'slaves')) + with open(os.path.join(disk, 'queue', 'rotational'), 'w') as f: + f.write('{}\n'.format(rotational)) + for slave in slaves: + os.symlink( + slave, + os.path.join(disk, 'slaves', os.path.basename(slave)), + ) + return disk + + def _partition(self, disk, name): + partition = os.path.join(disk, name) + os.makedirs(partition) + with open(os.path.join(partition, 'partition'), 'w') as f: + f.write('1\n') + return partition + + def test_non_rotational_disk(self): + self.assertFalse(dmcrypt._sysfs_rotational(self.nvme)) + + def test_partition_uses_parent_disk(self): + self.assertFalse(dmcrypt._sysfs_rotational(self.nvme_part)) + + def test_rotational_disk(self): + self.assertTrue(dmcrypt._sysfs_rotational(self.sda)) + + def test_device_mapper_resolves_slaves(self): + self.assertFalse(dmcrypt._sysfs_rotational(self.lv)) + + def test_any_rotational_slave_is_rotational(self): + self.assertTrue(dmcrypt._sysfs_rotational(self.mixed_lv)) + + def test_nested_device_mapper_resolves_slaves(self): + self.assertFalse(dmcrypt._sysfs_rotational(self.nested)) + + def test_partition_of_stacked_device_resolves_slaves(self): + self.assertFalse(dmcrypt._sysfs_rotational(self.md)) + self.assertFalse(dmcrypt._sysfs_rotational(self.md_part)) + + def test_missing_rotational_attribute_raises(self): + os.remove(os.path.join(self.nvme, 'queue', 'rotational')) + + with self.assertRaises(OSError): + dmcrypt._sysfs_rotational(self.nvme_part) + + def test_is_rotational_resolves_device_number(self): + dev_block = os.path.join(self.sysfs, 'dev', 'block') + os.makedirs(dev_block) + os.symlink(self.lv, os.path.join(dev_block, '252:0')) + real_stat = os.stat + + def fake_stat(path, *args, **kwargs): + if path == '/dev/vg/lv': + return mock.Mock( + st_mode=stat.S_IFBLK | 0o660, + st_rdev=os.makedev(252, 0), + ) + return real_stat(path, *args, **kwargs) + + with mock.patch.object(dmcrypt, 'SYSFS_DEV_BLOCK', dev_block), \ + mock.patch.object(dmcrypt.os, 'stat', side_effect=fake_stat): + self.assertFalse(dmcrypt.is_rotational('/dev/vg/lv')) + + def test_is_rotational_rejects_non_block_device(self): + regular_file = os.path.join(self.sysfs, 'regular') + open(regular_file, 'w').close() + + with self.assertRaises(ValueError): + dmcrypt.is_rotational(regular_file) diff --git a/vaultlocker/tests/unit/test_vaultlocker.py b/vaultlocker/tests/unit/test_vaultlocker.py index d014ba3..f227e67 100644 --- a/vaultlocker/tests/unit/test_vaultlocker.py +++ b/vaultlocker/tests/unit/test_vaultlocker.py @@ -55,6 +55,7 @@ def side_effect(_, key, **kwargs): kwargs.get('fallback'), ) self.config.get.side_effect = side_effect + self.config.getboolean.side_effect = side_effect def _hostname_config(self, hostname=None): config = configparser.ConfigParser() @@ -135,7 +136,7 @@ def test_decrypt(self, _dmcrypt, _boot_unlock, _vault_store, store.read.assert_called_once_with('host/passed-UUID') _dmcrypt.luks_open.assert_called_once_with( - 'testkey', 'passed-UUID' + 'testkey', 'passed-UUID', bypass_workqueues=True, ) _boot_unlock.register.assert_not_called() @@ -928,17 +929,22 @@ def test_different_existing_key_fails_without_writing(self): class TestOpenAndRegisterDevice(base.TestCase): """Tests opening and registering a device.""" + def setUp(self): + super().setUp() + self.config = configparser.ConfigParser() + @mock.patch.object(shell, '_register_boot_unlock') @mock.patch.object(shell, '_device_exists', return_value=False) @mock.patch.object(shell, 'dmcrypt') def test_opens_mapper_when_missing( self, _dmcrypt, _device_exists, _register): result = shell._open_and_register_device( - '/dev/sdb', 'test-uuid', 'the-key', '/path/to/conf', + '/dev/sdb', 'test-uuid', 'the-key', self.config, + '/path/to/conf', ) _dmcrypt.luks_open.assert_called_once_with( - 'the-key', 'test-uuid', '/dev/sdb', + 'the-key', 'test-uuid', '/dev/sdb', bypass_workqueues=True, ) _register.assert_called_once_with( '/dev/sdb', 'test-uuid', '/path/to/conf', @@ -958,7 +964,8 @@ def test_skips_opening_an_already_open_mapper( self, _dmcrypt, _device_exists, _register): """An open mapper is not opened again.""" result = shell._open_and_register_device( - '/dev/sdb', 'test-uuid', 'the-key', '/path/to/conf', + '/dev/sdb', 'test-uuid', 'the-key', self.config, + '/path/to/conf', ) _dmcrypt.luks_open.assert_not_called() @@ -976,9 +983,26 @@ def test_mapper_open_failure_is_reported(self, _dmcrypt, _device_exists): with self.assertRaises(exceptions.MapperOpenError): shell._open_and_register_device( - '/dev/sdb', 'test-uuid', 'the-key', '/path/to/conf', + '/dev/sdb', 'test-uuid', 'the-key', self.config, + '/path/to/conf', ) + @mock.patch.object(shell, '_register_boot_unlock') + @mock.patch.object(shell, '_device_exists', return_value=False) + @mock.patch.object(shell, 'dmcrypt') + def test_workqueue_bypass_can_be_disabled( + self, _dmcrypt, _device_exists, _register): + self.config.read_dict({'dmcrypt': {'bypass_workqueues': 'false'}}) + + shell._open_and_register_device( + '/dev/sdb', 'test-uuid', 'the-key', self.config, + '/path/to/conf', + ) + + _dmcrypt.luks_open.assert_called_once_with( + 'the-key', 'test-uuid', '/dev/sdb', bypass_workqueues=False, + ) + class TestReuseEncryptedDevice(base.TestCase): """Tests reusing an encrypted device.""" @@ -996,15 +1020,17 @@ def test_reuses_when_the_managed_key_works( args = mock.MagicMock() args.uuid = None args.config = '/path/to/conf' + config = mock.MagicMock() result = shell._open_existing_managed_device( - args, mock.MagicMock(), mock.MagicMock(), '/dev/sdb', + args, mock.MagicMock(), config, '/dev/sdb', 'existing-uuid', ) _key_unlocks_device.assert_called_once_with('managed-key', '/dev/sdb') _open_and_register.assert_called_once_with( - '/dev/sdb', 'existing-uuid', 'managed-key', '/path/to/conf', + '/dev/sdb', 'existing-uuid', 'managed-key', config, + '/path/to/conf', ) self.assertEqual({'luks_uuid': 'existing-uuid'}, result) @@ -1155,9 +1181,10 @@ def test_formats_stores_key_first_and_completes( args = mock.MagicMock() args.config = '/path/to/conf' + config = mock.MagicMock() result = shell._format_device( - args, mock.MagicMock(), mock.MagicMock(), '/dev/sdb', + args, mock.MagicMock(), config, '/dev/sdb', 'new-uuid', 'new-key', ) @@ -1169,7 +1196,8 @@ def test_formats_stores_key_first_and_completes( _udevadm_rescan.assert_called_once_with('/dev/sdb') _udevadm_settle.assert_called_once_with('new-uuid') _open_and_register.assert_called_once_with( - '/dev/sdb', 'new-uuid', 'new-key', '/path/to/conf', + '/dev/sdb', 'new-uuid', 'new-key', config, + '/path/to/conf', ) self.assertEqual({'luks_uuid': 'new-uuid'}, result) @@ -1187,9 +1215,10 @@ def test_format_skips_udev_in_snap( _running_in_snap): args = mock.MagicMock() args.config = '/path/to/conf' + config = mock.MagicMock() shell._format_device( - args, mock.MagicMock(), mock.MagicMock(), '/dev/sdb', + args, mock.MagicMock(), config, '/dev/sdb', 'new-uuid', 'new-key', ) @@ -1199,7 +1228,8 @@ def test_format_skips_udev_in_snap( _udevadm_rescan.assert_not_called() _udevadm_settle.assert_not_called() _open_and_register.assert_called_once_with( - '/dev/sdb', 'new-uuid', 'new-key', '/path/to/conf', + '/dev/sdb', 'new-uuid', 'new-key', config, + '/path/to/conf', ) @mock.patch.object(shell, '_open_and_register_device') @@ -1221,9 +1251,10 @@ def test_timeout_that_actually_completed_is_not_fatal( args = mock.MagicMock() args.config = '/path/to/conf' + config = mock.MagicMock() result = shell._format_device( - args, mock.MagicMock(), mock.MagicMock(), '/dev/sdb', + args, mock.MagicMock(), config, '/dev/sdb', 'new-uuid', 'new-key', ) @@ -1231,7 +1262,8 @@ def test_timeout_that_actually_completed_is_not_fatal( '/dev/sdb', 'new-uuid', 'new-key', ) _open_and_register.assert_called_once_with( - '/dev/sdb', 'new-uuid', 'new-key', '/path/to/conf', + '/dev/sdb', 'new-uuid', 'new-key', config, + '/path/to/conf', ) self.assertEqual({'luks_uuid': 'new-uuid'}, result) @@ -1461,18 +1493,20 @@ def test_succeeds_without_the_original_credential_when_already_enrolled( args = mock.MagicMock() args.block_device = ['/dev/sdb'] args.config = '/path/to/conf' + config = mock.MagicMock() with mock.patch.object( shell, '_key_unlocks_device', return_value=True, ) as key_check: result = shell._enroll_block_device( - args, mock.MagicMock(), mock.MagicMock(), get_operator_key, + args, mock.MagicMock(), config, get_operator_key, ) get_operator_key.assert_not_called() key_check.assert_called_once_with('managed-key', '/dev/sdb') _open_and_register.assert_called_once_with( - '/dev/sdb', 'test-uuid', 'managed-key', '/path/to/conf', + '/dev/sdb', 'test-uuid', 'managed-key', config, + '/path/to/conf', ) self.assertEqual({'luks_uuid': 'test-uuid'}, result) @@ -1496,13 +1530,14 @@ def can_unlock(key, device): args = mock.MagicMock() args.block_device = ['/dev/sdb'] args.config = '/path/to/conf' + config = mock.MagicMock() with mock.patch.object( shell, '_key_unlocks_device', side_effect=can_unlock, ) as key_check: result = shell._enroll_block_device( - args, mock.MagicMock(), mock.MagicMock(), get_operator_key, + args, mock.MagicMock(), config, get_operator_key, ) get_operator_key.assert_called_once() @@ -1513,7 +1548,8 @@ def can_unlock(key, device): b'existing-key', 'new-managed-key', '/dev/sdb', ) _open_and_register.assert_called_once_with( - '/dev/sdb', 'test-uuid', 'new-managed-key', '/path/to/conf', + '/dev/sdb', 'test-uuid', 'new-managed-key', config, + '/path/to/conf', ) self.assertEqual({'luks_uuid': 'test-uuid'}, result) self.assertEqual(2, key_check.call_count) @@ -1812,6 +1848,24 @@ def test_kv_version_rejects_other_number(self): str(error.exception), ) + def test_bypass_workqueues_defaults_to_enabled(self): + self.assertTrue(shell._bypass_workqueues(self._config())) + + def test_bypass_workqueues_can_be_disabled(self): + config = self._config() + config.read_dict({'dmcrypt': {'bypass_workqueues': 'no'}}) + + self.assertFalse(shell._bypass_workqueues(config)) + + def test_bypass_workqueues_rejects_non_boolean(self): + config = self._config() + config.read_dict({'dmcrypt': {'bypass_workqueues': 'auto'}}) + + with self.assertRaises(exceptions.ConfigurationError) as error: + shell._bypass_workqueues(config) + + self.assertIn('bypass_workqueues', str(error.exception)) + @mock.patch.object(shell, 'get_hostname') def test_secret_path_is_relative_to_mount(self, _get_hostname): _get_hostname.return_value = 'test-host' @@ -1923,6 +1977,21 @@ def test_get_config_empty_required_option_is_controlled(self): approle = role-id secret_id = secret-id backend = +""" + with mock.patch( + 'builtins.open', mock.mock_open(read_data=contents)): + with self.assertRaises(exceptions.ConfigurationError): + shell.get_config('/path/to/conf') + + def test_get_config_invalid_bypass_workqueues_is_controlled(self): + contents = """[vault] +url = https://vault.example +approle = role-id +secret_id = secret-id +backend = vaultlocker + +[dmcrypt] +bypass_workqueues = sometimes """ with mock.patch( 'builtins.open', mock.mock_open(read_data=contents)):