diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-06 02:25:50 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-06 02:25:50 +0000 |
commit | 19f4f86bfed21c5326ed2acebe1163f3a83e832b (patch) | |
tree | d59b9989ce55ed23693e80974d94c856f1c2c8b1 /src/cryptsetup | |
parent | Initial commit. (diff) | |
download | systemd-19f4f86bfed21c5326ed2acebe1163f3a83e832b.tar.xz systemd-19f4f86bfed21c5326ed2acebe1163f3a83e832b.zip |
Adding upstream version 241.upstream/241upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/cryptsetup')
-rw-r--r-- | src/cryptsetup/cryptsetup-generator.c | 609 | ||||
-rw-r--r-- | src/cryptsetup/cryptsetup.c | 745 |
2 files changed, 1354 insertions, 0 deletions
diff --git a/src/cryptsetup/cryptsetup-generator.c b/src/cryptsetup/cryptsetup-generator.c new file mode 100644 index 0000000..8759a26 --- /dev/null +++ b/src/cryptsetup/cryptsetup-generator.c @@ -0,0 +1,609 @@ +/* SPDX-License-Identifier: LGPL-2.1+ */ + +#include <errno.h> +#include <stdio_ext.h> + +#include "alloc-util.h" +#include "dropin.h" +#include "escape.h" +#include "fd-util.h" +#include "fileio.h" +#include "fstab-util.h" +#include "generator.h" +#include "hashmap.h" +#include "id128-util.h" +#include "log.h" +#include "mkdir.h" +#include "parse-util.h" +#include "path-util.h" +#include "proc-cmdline.h" +#include "specifier.h" +#include "string-util.h" +#include "strv.h" +#include "unit-name.h" +#include "util.h" + +typedef struct crypto_device { + char *uuid; + char *keyfile; + char *keydev; + char *name; + char *options; + bool create; +} crypto_device; + +static const char *arg_dest = NULL; +static bool arg_enabled = true; +static bool arg_read_crypttab = true; +static bool arg_whitelist = false; +static Hashmap *arg_disks = NULL; +static char *arg_default_options = NULL; +static char *arg_default_keyfile = NULL; + +STATIC_DESTRUCTOR_REGISTER(arg_disks, hashmap_freep); +STATIC_DESTRUCTOR_REGISTER(arg_default_options, freep); +STATIC_DESTRUCTOR_REGISTER(arg_default_keyfile, freep); + +static int generate_keydev_mount(const char *name, const char *keydev, char **unit, char **mount) { + _cleanup_free_ char *u = NULL, *what = NULL, *where = NULL, *name_escaped = NULL; + _cleanup_fclose_ FILE *f = NULL; + int r; + + assert(name); + assert(keydev); + assert(unit); + assert(mount); + + r = mkdir_parents("/run/systemd/cryptsetup", 0755); + if (r < 0) + return r; + + r = mkdir("/run/systemd/cryptsetup", 0700); + if (r < 0 && errno != EEXIST) + return -errno; + + name_escaped = cescape(name); + if (!name_escaped) + return -ENOMEM; + + where = strjoin("/run/systemd/cryptsetup/keydev-", name_escaped); + if (!where) + return -ENOMEM; + + r = mkdir(where, 0700); + if (r < 0 && errno != EEXIST) + return -errno; + + r = unit_name_from_path(where, ".mount", &u); + if (r < 0) + return r; + + r = generator_open_unit_file(arg_dest, NULL, u, &f); + if (r < 0) + return r; + + what = fstab_node_to_udev_node(keydev); + if (!what) + return -ENOMEM; + + fprintf(f, + "[Unit]\n" + "DefaultDependencies=no\n\n" + "[Mount]\n" + "What=%s\n" + "Where=%s\n" + "Options=ro\n", what, where); + + r = fflush_and_check(f); + if (r < 0) + return r; + + *unit = TAKE_PTR(u); + *mount = TAKE_PTR(where); + + return 0; +} + +static int create_disk( + const char *name, + const char *device, + const char *keydev, + const char *password, + const char *options) { + + _cleanup_free_ char *n = NULL, *d = NULL, *u = NULL, *e = NULL, + *filtered = NULL, *u_escaped = NULL, *password_escaped = NULL, *filtered_escaped = NULL, *name_escaped = NULL, *keydev_mount = NULL; + _cleanup_fclose_ FILE *f = NULL; + const char *dmname; + bool noauto, nofail, tmp, swap, netdev; + int r; + + assert(name); + assert(device); + + noauto = fstab_test_yes_no_option(options, "noauto\0" "auto\0"); + nofail = fstab_test_yes_no_option(options, "nofail\0" "fail\0"); + tmp = fstab_test_option(options, "tmp\0"); + swap = fstab_test_option(options, "swap\0"); + netdev = fstab_test_option(options, "_netdev\0"); + + if (tmp && swap) + return log_error_errno(SYNTHETIC_ERRNO(EINVAL), + "Device '%s' cannot be both 'tmp' and 'swap'. Ignoring.", + name); + + name_escaped = specifier_escape(name); + if (!name_escaped) + return log_oom(); + + e = unit_name_escape(name); + if (!e) + return log_oom(); + + u = fstab_node_to_udev_node(device); + if (!u) + return log_oom(); + + r = unit_name_build("systemd-cryptsetup", e, ".service", &n); + if (r < 0) + return log_error_errno(r, "Failed to generate unit name: %m"); + + u_escaped = specifier_escape(u); + if (!u_escaped) + return log_oom(); + + r = unit_name_from_path(u, ".device", &d); + if (r < 0) + return log_error_errno(r, "Failed to generate unit name: %m"); + + if (password) { + password_escaped = specifier_escape(password); + if (!password_escaped) + return log_oom(); + } + + if (keydev && !password) + return log_error_errno(SYNTHETIC_ERRNO(EINVAL), + "Key device is specified, but path to the password file is missing."); + + r = generator_open_unit_file(arg_dest, NULL, n, &f); + if (r < 0) + return r; + + fprintf(f, + "[Unit]\n" + "Description=Cryptography Setup for %%I\n" + "Documentation=man:crypttab(5) man:systemd-cryptsetup-generator(8) man:systemd-cryptsetup@.service(8)\n" + "SourcePath=/etc/crypttab\n" + "DefaultDependencies=no\n" + "Conflicts=umount.target\n" + "IgnoreOnIsolate=true\n" + "After=%s\n", + netdev ? "remote-fs-pre.target" : "cryptsetup-pre.target"); + + if (keydev) { + _cleanup_free_ char *unit = NULL, *p = NULL; + + r = generate_keydev_mount(name, keydev, &unit, &keydev_mount); + if (r < 0) + return log_error_errno(r, "Failed to generate keydev mount unit: %m"); + + p = prefix_root(keydev_mount, password_escaped); + if (!p) + return log_oom(); + + free_and_replace(password_escaped, p); + } + + if (!nofail) + fprintf(f, + "Before=%s\n", + netdev ? "remote-cryptsetup.target" : "cryptsetup.target"); + + if (password) { + if (PATH_IN_SET(password, "/dev/urandom", "/dev/random", "/dev/hw_random")) + fputs("After=systemd-random-seed.service\n", f); + else if (!STR_IN_SET(password, "-", "none")) { + _cleanup_free_ char *uu; + + uu = fstab_node_to_udev_node(password); + if (!uu) + return log_oom(); + + if (!path_equal(uu, "/dev/null")) { + + if (path_startswith(uu, "/dev/")) { + _cleanup_free_ char *dd = NULL; + + r = unit_name_from_path(uu, ".device", &dd); + if (r < 0) + return log_error_errno(r, "Failed to generate unit name: %m"); + + fprintf(f, "After=%1$s\nRequires=%1$s\n", dd); + } else + fprintf(f, "RequiresMountsFor=%s\n", password_escaped); + } + } + } + + if (path_startswith(u, "/dev/")) { + fprintf(f, + "BindsTo=%s\n" + "After=%s\n" + "Before=umount.target\n", + d, d); + + if (swap) + fputs("Before=dev-mapper-%i.swap\n", + f); + } else + /* For loopback devices, add systemd-tmpfiles-setup-dev.service + dependency to ensure that loopback support is available in + the kernel (/dev/loop-control needs to exist) */ + fprintf(f, + "RequiresMountsFor=%s\n" + "Requires=systemd-tmpfiles-setup-dev.service\n" + "After=systemd-tmpfiles-setup-dev.service\n", + u_escaped); + + r = generator_write_timeouts(arg_dest, device, name, options, &filtered); + if (r < 0) + return r; + + if (filtered) { + filtered_escaped = specifier_escape(filtered); + if (!filtered_escaped) + return log_oom(); + } + + fprintf(f, + "\n[Service]\n" + "Type=oneshot\n" + "RemainAfterExit=yes\n" + "TimeoutSec=0\n" /* the binary handles timeouts anyway */ + "KeyringMode=shared\n" /* make sure we can share cached keys among instances */ + "ExecStart=" SYSTEMD_CRYPTSETUP_PATH " attach '%s' '%s' '%s' '%s'\n" + "ExecStop=" SYSTEMD_CRYPTSETUP_PATH " detach '%s'\n", + name_escaped, u_escaped, strempty(password_escaped), strempty(filtered_escaped), + name_escaped); + + if (tmp) + fprintf(f, + "ExecStartPost=/sbin/mke2fs '/dev/mapper/%s'\n", + name_escaped); + + if (swap) + fprintf(f, + "ExecStartPost=/sbin/mkswap '/dev/mapper/%s'\n", + name_escaped); + + if (keydev) + fprintf(f, + "ExecStartPost=" UMOUNT_PATH " %s\n\n", + keydev_mount); + + r = fflush_and_check(f); + if (r < 0) + return log_error_errno(r, "Failed to write unit file %s: %m", n); + + if (!noauto) { + r = generator_add_symlink(arg_dest, d, "wants", n); + if (r < 0) + return r; + + r = generator_add_symlink(arg_dest, + netdev ? "remote-cryptsetup.target" : "cryptsetup.target", + nofail ? "wants" : "requires", n); + if (r < 0) + return r; + } + + dmname = strjoina("dev-mapper-", e, ".device"); + r = generator_add_symlink(arg_dest, dmname, "requires", n); + if (r < 0) + return r; + + if (!noauto && !nofail) { + r = write_drop_in(arg_dest, dmname, 90, "device-timeout", + "# Automatically generated by systemd-cryptsetup-generator \n\n" + "[Unit]\nJobTimeoutSec=0"); + if (r < 0) + return log_error_errno(r, "Failed to write device drop-in: %m"); + } + + return 0; +} + +static crypto_device* crypt_device_free(crypto_device *d) { + if (!d) + return NULL; + + free(d->uuid); + free(d->keyfile); + free(d->keydev); + free(d->name); + free(d->options); + return mfree(d); +} + +static crypto_device *get_crypto_device(const char *uuid) { + int r; + crypto_device *d; + + assert(uuid); + + d = hashmap_get(arg_disks, uuid); + if (!d) { + d = new0(struct crypto_device, 1); + if (!d) + return NULL; + + d->create = false; + d->keyfile = d->options = d->name = NULL; + + d->uuid = strdup(uuid); + if (!d->uuid) + return mfree(d); + + r = hashmap_put(arg_disks, d->uuid, d); + if (r < 0) { + free(d->uuid); + return mfree(d); + } + } + + return d; +} + +static int parse_proc_cmdline_item(const char *key, const char *value, void *data) { + _cleanup_free_ char *uuid = NULL, *uuid_value = NULL; + crypto_device *d; + int r; + + if (streq(key, "luks")) { + + r = value ? parse_boolean(value) : 1; + if (r < 0) + log_warning("Failed to parse luks= kernel command line switch %s. Ignoring.", value); + else + arg_enabled = r; + + } else if (streq(key, "luks.crypttab")) { + + r = value ? parse_boolean(value) : 1; + if (r < 0) + log_warning("Failed to parse luks.crypttab= kernel command line switch %s. Ignoring.", value); + else + arg_read_crypttab = r; + + } else if (streq(key, "luks.uuid")) { + + if (proc_cmdline_value_missing(key, value)) + return 0; + + d = get_crypto_device(startswith(value, "luks-") ? value+5 : value); + if (!d) + return log_oom(); + + d->create = arg_whitelist = true; + + } else if (streq(key, "luks.options")) { + + if (proc_cmdline_value_missing(key, value)) + return 0; + + r = sscanf(value, "%m[0-9a-fA-F-]=%ms", &uuid, &uuid_value); + if (r == 2) { + d = get_crypto_device(uuid); + if (!d) + return log_oom(); + + free_and_replace(d->options, uuid_value); + } else if (free_and_strdup(&arg_default_options, value) < 0) + return log_oom(); + + } else if (streq(key, "luks.key")) { + size_t n; + _cleanup_free_ char *keyfile = NULL, *keydev = NULL; + char *c; + const char *keyspec; + + if (proc_cmdline_value_missing(key, value)) + return 0; + + n = strspn(value, LETTERS DIGITS "-"); + if (value[n] != '=') { + if (free_and_strdup(&arg_default_keyfile, value) < 0) + return log_oom(); + return 0; + } + + uuid = strndup(value, n); + if (!uuid) + return log_oom(); + + if (!id128_is_valid(uuid)) { + log_warning("Failed to parse luks.key= kernel command line switch. UUID is invalid, ignoring."); + return 0; + } + + d = get_crypto_device(uuid); + if (!d) + return log_oom(); + + keyspec = value + n + 1; + c = strrchr(keyspec, ':'); + if (c) { + *c = '\0'; + keyfile = strdup(keyspec); + keydev = strdup(c + 1); + + if (!keyfile || !keydev) + return log_oom(); + } else { + /* No keydev specified */ + keyfile = strdup(keyspec); + if (!keyfile) + return log_oom(); + } + + free_and_replace(d->keyfile, keyfile); + free_and_replace(d->keydev, keydev); + } else if (streq(key, "luks.name")) { + + if (proc_cmdline_value_missing(key, value)) + return 0; + + r = sscanf(value, "%m[0-9a-fA-F-]=%ms", &uuid, &uuid_value); + if (r == 2) { + d = get_crypto_device(uuid); + if (!d) + return log_oom(); + + d->create = arg_whitelist = true; + + free_and_replace(d->name, uuid_value); + } else + log_warning("Failed to parse luks name switch %s. Ignoring.", value); + } + + return 0; +} + +static int add_crypttab_devices(void) { + _cleanup_fclose_ FILE *f = NULL; + unsigned crypttab_line = 0; + struct stat st; + int r; + + if (!arg_read_crypttab) + return 0; + + f = fopen("/etc/crypttab", "re"); + if (!f) { + if (errno != ENOENT) + log_error_errno(errno, "Failed to open /etc/crypttab: %m"); + return 0; + } + + (void) __fsetlocking(f, FSETLOCKING_BYCALLER); + + if (fstat(fileno(f), &st) < 0) { + log_error_errno(errno, "Failed to stat /etc/crypttab: %m"); + return 0; + } + + for (;;) { + _cleanup_free_ char *line = NULL, *name = NULL, *device = NULL, *keyfile = NULL, *options = NULL; + crypto_device *d = NULL; + char *l, *uuid; + int k; + + r = read_line(f, LONG_LINE_MAX, &line); + if (r < 0) + return log_error_errno(r, "Failed to read /etc/crypttab: %m"); + if (r == 0) + break; + + crypttab_line++; + + l = strstrip(line); + if (IN_SET(l[0], 0, '#')) + continue; + + k = sscanf(l, "%ms %ms %ms %ms", &name, &device, &keyfile, &options); + if (k < 2 || k > 4) { + log_error("Failed to parse /etc/crypttab:%u, ignoring.", crypttab_line); + continue; + } + + uuid = STARTSWITH_SET(device, "UUID=", "luks-"); + if (!uuid) + uuid = path_startswith(device, "/dev/disk/by-uuid/"); + if (uuid) + d = hashmap_get(arg_disks, uuid); + + if (arg_whitelist && !d) { + log_info("Not creating device '%s' because it was not specified on the kernel command line.", name); + continue; + } + + r = create_disk(name, device, NULL, keyfile, (d && d->options) ? d->options : options); + if (r < 0) + return r; + + if (d) + d->create = false; + } + + return 0; +} + +static int add_proc_cmdline_devices(void) { + int r; + Iterator i; + crypto_device *d; + + HASHMAP_FOREACH(d, arg_disks, i) { + const char *options; + _cleanup_free_ char *device = NULL; + + if (!d->create) + continue; + + if (!d->name) { + d->name = strappend("luks-", d->uuid); + if (!d->name) + return log_oom(); + } + + device = strappend("UUID=", d->uuid); + if (!device) + return log_oom(); + + if (d->options) + options = d->options; + else if (arg_default_options) + options = arg_default_options; + else + options = "timeout=0"; + + r = create_disk(d->name, device, d->keydev, d->keyfile ?: arg_default_keyfile, options); + if (r < 0) + return r; + } + + return 0; +} + +DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(crypt_device_hash_ops, char, string_hash_func, string_compare_func, + crypto_device, crypt_device_free); + +static int run(const char *dest, const char *dest_early, const char *dest_late) { + int r; + + assert_se(arg_dest = dest); + + arg_disks = hashmap_new(&crypt_device_hash_ops); + if (!arg_disks) + return log_oom(); + + r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, PROC_CMDLINE_STRIP_RD_PREFIX); + if (r < 0) + return log_warning_errno(r, "Failed to parse kernel command line: %m"); + + if (!arg_enabled) + return 0; + + r = add_crypttab_devices(); + if (r < 0) + return r; + + r = add_proc_cmdline_devices(); + if (r < 0) + return r; + + return 0; +} + +DEFINE_MAIN_GENERATOR_FUNCTION(run); diff --git a/src/cryptsetup/cryptsetup.c b/src/cryptsetup/cryptsetup.c new file mode 100644 index 0000000..9cb52dd --- /dev/null +++ b/src/cryptsetup/cryptsetup.c @@ -0,0 +1,745 @@ +/* SPDX-License-Identifier: LGPL-2.1+ */ + +#include <errno.h> +#include <mntent.h> +#include <string.h> +#include <sys/mman.h> + +#include "sd-device.h" + +#include "alloc-util.h" +#include "ask-password-api.h" +#include "crypt-util.h" +#include "device-util.h" +#include "escape.h" +#include "fileio.h" +#include "log.h" +#include "main-func.h" +#include "mount-util.h" +#include "parse-util.h" +#include "path-util.h" +#include "string-util.h" +#include "strv.h" +#include "pretty-print.h" +#include "util.h" + +/* internal helper */ +#define ANY_LUKS "LUKS" +/* as in src/cryptsetup.h */ +#define CRYPT_SECTOR_SIZE 512 +#define CRYPT_MAX_SECTOR_SIZE 4096 + +static const char *arg_type = NULL; /* ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2, CRYPT_TCRYPT or CRYPT_PLAIN */ +static char *arg_cipher = NULL; +static unsigned arg_key_size = 0; +#if HAVE_LIBCRYPTSETUP_SECTOR_SIZE +static unsigned arg_sector_size = CRYPT_SECTOR_SIZE; +#endif +static int arg_key_slot = CRYPT_ANY_SLOT; +static unsigned arg_keyfile_size = 0; +static uint64_t arg_keyfile_offset = 0; +static char *arg_hash = NULL; +static char *arg_header = NULL; +static unsigned arg_tries = 3; +static bool arg_readonly = false; +static bool arg_verify = false; +static bool arg_discards = false; +static bool arg_tcrypt_hidden = false; +static bool arg_tcrypt_system = false; +#ifdef CRYPT_TCRYPT_VERA_MODES +static bool arg_tcrypt_veracrypt = false; +#endif +static char **arg_tcrypt_keyfiles = NULL; +static uint64_t arg_offset = 0; +static uint64_t arg_skip = 0; +static usec_t arg_timeout = USEC_INFINITY; + +STATIC_DESTRUCTOR_REGISTER(arg_cipher, freep); +STATIC_DESTRUCTOR_REGISTER(arg_hash, freep); +STATIC_DESTRUCTOR_REGISTER(arg_header, freep); +STATIC_DESTRUCTOR_REGISTER(arg_tcrypt_keyfiles, strv_freep); + +/* Options Debian's crypttab knows we don't: + + precheck= + check= + checkargs= + noearly= + loud= + keyscript= +*/ + +static int parse_one_option(const char *option) { + const char *val; + int r; + + assert(option); + + /* Handled outside of this tool */ + if (STR_IN_SET(option, "noauto", "auto", "nofail", "fail", "_netdev")) + return 0; + + if ((val = startswith(option, "cipher="))) { + r = free_and_strdup(&arg_cipher, val); + if (r < 0) + return log_oom(); + + } else if ((val = startswith(option, "size="))) { + + r = safe_atou(val, &arg_key_size); + if (r < 0) { + log_error_errno(r, "Failed to parse %s, ignoring: %m", option); + return 0; + } + + if (arg_key_size % 8) { + log_error("size= not a multiple of 8, ignoring."); + return 0; + } + + arg_key_size /= 8; + + } else if ((val = startswith(option, "sector-size="))) { + +#if HAVE_LIBCRYPTSETUP_SECTOR_SIZE + r = safe_atou(val, &arg_sector_size); + if (r < 0) { + log_error_errno(r, "Failed to parse %s, ignoring: %m", option); + return 0; + } + + if (arg_sector_size % 2) { + log_error("sector-size= not a multiple of 2, ignoring."); + return 0; + } + + if (arg_sector_size < CRYPT_SECTOR_SIZE || arg_sector_size > CRYPT_MAX_SECTOR_SIZE) { + log_error("sector-size= is outside of %u and %u, ignoring.", CRYPT_SECTOR_SIZE, CRYPT_MAX_SECTOR_SIZE); + return 0; + } +#else + log_error("sector-size= is not supported, compiled with old libcryptsetup."); + return 0; +#endif + + } else if ((val = startswith(option, "key-slot="))) { + + arg_type = ANY_LUKS; + r = safe_atoi(val, &arg_key_slot); + if (r < 0) { + log_error_errno(r, "Failed to parse %s, ignoring: %m", option); + return 0; + } + + } else if ((val = startswith(option, "tcrypt-keyfile="))) { + + arg_type = CRYPT_TCRYPT; + if (path_is_absolute(val)) { + if (strv_extend(&arg_tcrypt_keyfiles, val) < 0) + return log_oom(); + } else + log_error("Key file path \"%s\" is not absolute. Ignoring.", val); + + } else if ((val = startswith(option, "keyfile-size="))) { + + r = safe_atou(val, &arg_keyfile_size); + if (r < 0) { + log_error_errno(r, "Failed to parse %s, ignoring: %m", option); + return 0; + } + + } else if ((val = startswith(option, "keyfile-offset="))) { + uint64_t off; + + r = safe_atou64(val, &off); + if (r < 0) { + log_error_errno(r, "Failed to parse %s, ignoring: %m", option); + return 0; + } + + if ((size_t) off != off) { + /* https://gitlab.com/cryptsetup/cryptsetup/issues/359 */ + log_error("keyfile-offset= value would truncated to %zu, ignoring.", (size_t) off); + return 0; + } + + arg_keyfile_offset = off; + + } else if ((val = startswith(option, "hash="))) { + r = free_and_strdup(&arg_hash, val); + if (r < 0) + return log_oom(); + + } else if ((val = startswith(option, "header="))) { + arg_type = ANY_LUKS; + + if (!path_is_absolute(val)) + return log_error_errno(SYNTHETIC_ERRNO(EINVAL), + "Header path \"%s\" is not absolute, refusing.", val); + + if (arg_header) + return log_error_errno(SYNTHETIC_ERRNO(EINVAL), + "Duplicate header= option, refusing."); + + arg_header = strdup(val); + if (!arg_header) + return log_oom(); + + } else if ((val = startswith(option, "tries="))) { + + r = safe_atou(val, &arg_tries); + if (r < 0) { + log_error_errno(r, "Failed to parse %s, ignoring: %m", option); + return 0; + } + + } else if (STR_IN_SET(option, "readonly", "read-only")) + arg_readonly = true; + else if (streq(option, "verify")) + arg_verify = true; + else if (STR_IN_SET(option, "allow-discards", "discard")) + arg_discards = true; + else if (streq(option, "luks")) + arg_type = ANY_LUKS; + else if (streq(option, "tcrypt")) + arg_type = CRYPT_TCRYPT; + else if (streq(option, "tcrypt-hidden")) { + arg_type = CRYPT_TCRYPT; + arg_tcrypt_hidden = true; + } else if (streq(option, "tcrypt-system")) { + arg_type = CRYPT_TCRYPT; + arg_tcrypt_system = true; + } else if (streq(option, "tcrypt-veracrypt")) { +#ifdef CRYPT_TCRYPT_VERA_MODES + arg_type = CRYPT_TCRYPT; + arg_tcrypt_veracrypt = true; +#else + return log_error_errno(SYNTHETIC_ERRNO(EINVAL), + "This version of cryptsetup does not support tcrypt-veracrypt; refusing."); +#endif + } else if (STR_IN_SET(option, "plain", "swap", "tmp")) + arg_type = CRYPT_PLAIN; + else if ((val = startswith(option, "timeout="))) { + + r = parse_sec_fix_0(val, &arg_timeout); + if (r < 0) { + log_error_errno(r, "Failed to parse %s, ignoring: %m", option); + return 0; + } + + } else if ((val = startswith(option, "offset="))) { + + r = safe_atou64(val, &arg_offset); + if (r < 0) + return log_error_errno(r, "Failed to parse %s: %m", option); + + } else if ((val = startswith(option, "skip="))) { + + r = safe_atou64(val, &arg_skip); + if (r < 0) + return log_error_errno(r, "Failed to parse %s: %m", option); + + } else if (!streq(option, "none")) + log_warning("Encountered unknown /etc/crypttab option '%s', ignoring.", option); + + return 0; +} + +static int parse_options(const char *options) { + const char *word, *state; + size_t l; + int r; + + assert(options); + + FOREACH_WORD_SEPARATOR(word, l, options, ",", state) { + _cleanup_free_ char *o; + + o = strndup(word, l); + if (!o) + return -ENOMEM; + r = parse_one_option(o); + if (r < 0) + return r; + } + + /* sanity-check options */ + if (arg_type != NULL && !streq(arg_type, CRYPT_PLAIN)) { + if (arg_offset) + log_warning("offset= ignored with type %s", arg_type); + if (arg_skip) + log_warning("skip= ignored with type %s", arg_type); + } + + return 0; +} + +static char* disk_description(const char *path) { + static const char name_fields[] = + "ID_PART_ENTRY_NAME\0" + "DM_NAME\0" + "ID_MODEL_FROM_DATABASE\0" + "ID_MODEL\0"; + + _cleanup_(sd_device_unrefp) sd_device *device = NULL; + const char *i, *name; + struct stat st; + + assert(path); + + if (stat(path, &st) < 0) + return NULL; + + if (!S_ISBLK(st.st_mode)) + return NULL; + + if (sd_device_new_from_devnum(&device, 'b', st.st_rdev) < 0) + return NULL; + + NULSTR_FOREACH(i, name_fields) + if (sd_device_get_property_value(device, i, &name) >= 0 && + !isempty(name)) + return strdup(name); + + return NULL; +} + +static char *disk_mount_point(const char *label) { + _cleanup_free_ char *device = NULL; + _cleanup_endmntent_ FILE *f = NULL; + struct mntent *m; + + /* Yeah, we don't support native systemd unit files here for now */ + + if (asprintf(&device, "/dev/mapper/%s", label) < 0) + return NULL; + + f = setmntent("/etc/fstab", "re"); + if (!f) + return NULL; + + while ((m = getmntent(f))) + if (path_equal(m->mnt_fsname, device)) + return strdup(m->mnt_dir); + + return NULL; +} + +static int get_password(const char *vol, const char *src, usec_t until, bool accept_cached, char ***ret) { + _cleanup_free_ char *description = NULL, *name_buffer = NULL, *mount_point = NULL, *text = NULL, *disk_path = NULL; + _cleanup_strv_free_erase_ char **passwords = NULL; + const char *name = NULL; + char **p, *id; + int r = 0; + + assert(vol); + assert(src); + assert(ret); + + description = disk_description(src); + mount_point = disk_mount_point(vol); + + disk_path = cescape(src); + if (!disk_path) + return log_oom(); + + if (description && streq(vol, description)) + /* If the description string is simply the + * volume name, then let's not show this + * twice */ + description = mfree(description); + + if (mount_point && description) + r = asprintf(&name_buffer, "%s (%s) on %s", description, vol, mount_point); + else if (mount_point) + r = asprintf(&name_buffer, "%s on %s", vol, mount_point); + else if (description) + r = asprintf(&name_buffer, "%s (%s)", description, vol); + + if (r < 0) + return log_oom(); + + name = name_buffer ? name_buffer : vol; + + if (asprintf(&text, "Please enter passphrase for disk %s:", name) < 0) + return log_oom(); + + id = strjoina("cryptsetup:", disk_path); + + r = ask_password_auto(text, "drive-harddisk", id, "cryptsetup", until, + ASK_PASSWORD_PUSH_CACHE | (accept_cached*ASK_PASSWORD_ACCEPT_CACHED), + &passwords); + if (r < 0) + return log_error_errno(r, "Failed to query password: %m"); + + if (arg_verify) { + _cleanup_strv_free_erase_ char **passwords2 = NULL; + + assert(strv_length(passwords) == 1); + + if (asprintf(&text, "Please enter passphrase for disk %s (verification):", name) < 0) + return log_oom(); + + id = strjoina("cryptsetup-verification:", disk_path); + + r = ask_password_auto(text, "drive-harddisk", id, "cryptsetup", until, ASK_PASSWORD_PUSH_CACHE, &passwords2); + if (r < 0) + return log_error_errno(r, "Failed to query verification password: %m"); + + assert(strv_length(passwords2) == 1); + + if (!streq(passwords[0], passwords2[0])) { + log_warning("Passwords did not match, retrying."); + return -EAGAIN; + } + } + + strv_uniq(passwords); + + STRV_FOREACH(p, passwords) { + char *c; + + if (strlen(*p)+1 >= arg_key_size) + continue; + + /* Pad password if necessary */ + c = new(char, arg_key_size); + if (!c) + return log_oom(); + + strncpy(c, *p, arg_key_size); + free_and_replace(*p, c); + } + + *ret = TAKE_PTR(passwords); + + return 0; +} + +static int attach_tcrypt( + struct crypt_device *cd, + const char *name, + const char *key_file, + char **passwords, + uint32_t flags) { + + int r = 0; + _cleanup_free_ char *passphrase = NULL; + struct crypt_params_tcrypt params = { + .flags = CRYPT_TCRYPT_LEGACY_MODES, + .keyfiles = (const char **)arg_tcrypt_keyfiles, + .keyfiles_count = strv_length(arg_tcrypt_keyfiles) + }; + + assert(cd); + assert(name); + assert(key_file || (passwords && passwords[0])); + + if (arg_tcrypt_hidden) + params.flags |= CRYPT_TCRYPT_HIDDEN_HEADER; + + if (arg_tcrypt_system) + params.flags |= CRYPT_TCRYPT_SYSTEM_HEADER; + +#ifdef CRYPT_TCRYPT_VERA_MODES + if (arg_tcrypt_veracrypt) + params.flags |= CRYPT_TCRYPT_VERA_MODES; +#endif + + if (key_file) { + r = read_one_line_file(key_file, &passphrase); + if (r < 0) { + log_error_errno(r, "Failed to read password file '%s': %m", key_file); + return -EAGAIN; /* log with the actual error, but return EAGAIN */ + } + + params.passphrase = passphrase; + } else + params.passphrase = passwords[0]; + params.passphrase_size = strlen(params.passphrase); + + r = crypt_load(cd, CRYPT_TCRYPT, ¶ms); + if (r < 0) { + if (key_file && r == -EPERM) { + log_error_errno(r, "Failed to activate using password file '%s'. (Key data not correct?)", key_file); + return -EAGAIN; /* log the actual error, but return EAGAIN */ + } + + return log_error_errno(r, "Failed to load tcrypt superblock on device %s: %m", crypt_get_device_name(cd)); + } + + r = crypt_activate_by_volume_key(cd, name, NULL, 0, flags); + if (r < 0) + return log_error_errno(r, "Failed to activate tcrypt device %s: %m", crypt_get_device_name(cd)); + + return 0; +} + +static int attach_luks_or_plain(struct crypt_device *cd, + const char *name, + const char *key_file, + const char *data_device, + char **passwords, + uint32_t flags) { + int r = 0; + bool pass_volume_key = false; + + assert(cd); + assert(name); + assert(key_file || passwords); + + if (!arg_type || STR_IN_SET(arg_type, ANY_LUKS, CRYPT_LUKS1)) { + r = crypt_load(cd, CRYPT_LUKS, NULL); + if (r < 0) + return log_error_errno(r, "Failed to load LUKS superblock on device %s: %m", crypt_get_device_name(cd)); + + if (data_device) + r = crypt_set_data_device(cd, data_device); + } + + if ((!arg_type && r < 0) || streq_ptr(arg_type, CRYPT_PLAIN)) { + struct crypt_params_plain params = { + .offset = arg_offset, + .skip = arg_skip, +#if HAVE_LIBCRYPTSETUP_SECTOR_SIZE + .sector_size = arg_sector_size, +#endif + }; + const char *cipher, *cipher_mode; + _cleanup_free_ char *truncated_cipher = NULL; + + if (arg_hash) { + /* plain isn't a real hash type. it just means "use no hash" */ + if (!streq(arg_hash, "plain")) + params.hash = arg_hash; + } else if (!key_file) + /* for CRYPT_PLAIN, the behaviour of cryptsetup + * package is to not hash when a key file is provided */ + params.hash = "ripemd160"; + + if (arg_cipher) { + size_t l; + + l = strcspn(arg_cipher, "-"); + truncated_cipher = strndup(arg_cipher, l); + if (!truncated_cipher) + return log_oom(); + + cipher = truncated_cipher; + cipher_mode = arg_cipher[l] ? arg_cipher+l+1 : "plain"; + } else { + cipher = "aes"; + cipher_mode = "cbc-essiv:sha256"; + } + + /* for CRYPT_PLAIN limit reads from keyfile to key length, and ignore keyfile-size */ + arg_keyfile_size = arg_key_size; + + /* In contrast to what the name crypt_setup() might suggest this doesn't actually format + * anything, it just configures encryption parameters when used for plain mode. */ + r = crypt_format(cd, CRYPT_PLAIN, cipher, cipher_mode, NULL, NULL, arg_keyfile_size, ¶ms); + + /* hash == NULL implies the user passed "plain" */ + pass_volume_key = (params.hash == NULL); + } + if (r < 0) + return log_error_errno(r, "Loading of cryptographic parameters failed: %m"); + + log_info("Set cipher %s, mode %s, key size %i bits for device %s.", + crypt_get_cipher(cd), + crypt_get_cipher_mode(cd), + crypt_get_volume_key_size(cd)*8, + crypt_get_device_name(cd)); + + if (key_file) { + r = crypt_activate_by_keyfile_offset(cd, name, arg_key_slot, key_file, arg_keyfile_size, arg_keyfile_offset, flags); + if (r == -EPERM) { + log_error_errno(r, "Failed to activate with key file '%s'. (Key data incorrect?)", key_file); + return -EAGAIN; /* Log actual error, but return EAGAIN */ + } + if (r < 0) + return log_error_errno(r, "Failed to activate with key file '%s': %m", key_file); + } else { + char **p; + + r = -EINVAL; + STRV_FOREACH(p, passwords) { + if (pass_volume_key) + r = crypt_activate_by_volume_key(cd, name, *p, arg_key_size, flags); + else + r = crypt_activate_by_passphrase(cd, name, arg_key_slot, *p, strlen(*p), flags); + if (r >= 0) + break; + } + if (r == -EPERM) { + log_error_errno(r, "Failed to activate with specified passphrase. (Passphrase incorrect?)"); + return -EAGAIN; /* log actual error, but return EAGAIN */ + } + if (r < 0) + return log_error_errno(r, "Failed to activate with specified passphrase: %m"); + } + + return r; +} + +static int help(void) { + _cleanup_free_ char *link = NULL; + int r; + + r = terminal_urlify_man("systemd-cryptsetup@.service", "8", &link); + if (r < 0) + return log_oom(); + + printf("%s attach VOLUME SOURCEDEVICE [PASSWORD] [OPTIONS]\n" + "%s detach VOLUME\n\n" + "Attaches or detaches an encrypted block device.\n" + "\nSee the %s for details.\n" + , program_invocation_short_name + , program_invocation_short_name + , link + ); + + return 0; +} + +static int run(int argc, char *argv[]) { + _cleanup_(crypt_freep) struct crypt_device *cd = NULL; + int r; + + if (argc <= 1) + return help(); + + if (argc < 3) { + log_error("This program requires at least two arguments."); + return -EINVAL; + } + + log_setup_service(); + + umask(0022); + + if (streq(argv[1], "attach")) { + uint32_t flags = 0; + unsigned tries; + usec_t until; + crypt_status_info status; + const char *key_file = NULL; + + /* Arguments: systemd-cryptsetup attach VOLUME SOURCE-DEVICE [PASSWORD] [OPTIONS] */ + + if (argc < 4) + return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "attach requires at least two arguments."); + + if (argc >= 5 && + argv[4][0] && + !streq(argv[4], "-") && + !streq(argv[4], "none")) { + + if (!path_is_absolute(argv[4])) + log_warning("Password file path '%s' is not absolute. Ignoring.", argv[4]); + else + key_file = argv[4]; + } + + if (argc >= 6 && argv[5][0] && !streq(argv[5], "-")) { + r = parse_options(argv[5]); + if (r < 0) + return r; + } + + /* A delicious drop of snake oil */ + mlockall(MCL_FUTURE); + + if (arg_header) { + log_debug("LUKS header: %s", arg_header); + r = crypt_init(&cd, arg_header); + } else + r = crypt_init(&cd, argv[3]); + if (r < 0) + return log_error_errno(r, "crypt_init() failed: %m"); + + crypt_set_log_callback(cd, cryptsetup_log_glue, NULL); + + status = crypt_status(cd, argv[2]); + if (IN_SET(status, CRYPT_ACTIVE, CRYPT_BUSY)) { + log_info("Volume %s already active.", argv[2]); + return 0; + } + + if (arg_readonly) + flags |= CRYPT_ACTIVATE_READONLY; + + if (arg_discards) + flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS; + + if (arg_timeout == USEC_INFINITY) + until = 0; + else + until = now(CLOCK_MONOTONIC) + arg_timeout; + + arg_key_size = (arg_key_size > 0 ? arg_key_size : (256 / 8)); + + if (key_file) { + struct stat st; + + /* Ideally we'd do this on the open fd, but since this is just a + * warning it's OK to do this in two steps. */ + if (stat(key_file, &st) >= 0 && S_ISREG(st.st_mode) && (st.st_mode & 0005)) + log_warning("Key file %s is world-readable. This is not a good idea!", key_file); + } + + for (tries = 0; arg_tries == 0 || tries < arg_tries; tries++) { + _cleanup_strv_free_erase_ char **passwords = NULL; + + if (!key_file) { + r = get_password(argv[2], argv[3], until, tries == 0 && !arg_verify, &passwords); + if (r == -EAGAIN) + continue; + if (r < 0) + return r; + } + + if (streq_ptr(arg_type, CRYPT_TCRYPT)) + r = attach_tcrypt(cd, argv[2], key_file, passwords, flags); + else + r = attach_luks_or_plain(cd, + argv[2], + key_file, + arg_header ? argv[3] : NULL, + passwords, + flags); + if (r >= 0) + break; + if (r != -EAGAIN) + return r; + + /* Passphrase not correct? Let's try again! */ + key_file = NULL; + } + + if (arg_tries != 0 && tries >= arg_tries) + return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Too many attempts to activate; giving up."); + + } else if (streq(argv[1], "detach")) { + + r = crypt_init_by_name(&cd, argv[2]); + if (r == -ENODEV) { + log_info("Volume %s already inactive.", argv[2]); + return 0; + } + if (r < 0) + return log_error_errno(r, "crypt_init_by_name() failed: %m"); + + crypt_set_log_callback(cd, cryptsetup_log_glue, NULL); + + r = crypt_deactivate(cd, argv[2]); + if (r < 0) + return log_error_errno(r, "Failed to deactivate: %m"); + + } else + return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown verb %s.", argv[1]); + + return 0; +} + +DEFINE_MAIN_FUNCTION(run); |