diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-27 13:00:47 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-27 13:00:47 +0000 |
commit | 2cb7e0aaedad73b076ea18c6900b0e86c5760d79 (patch) | |
tree | da68ca54bb79f4080079bf0828acda937593a4e1 /src/cryptsetup | |
parent | Initial commit. (diff) | |
download | systemd-upstream.tar.xz systemd-upstream.zip |
Adding upstream version 247.3.upstream/247.3upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/cryptsetup')
-rw-r--r-- | src/cryptsetup/cryptsetup-generator.c | 917 | ||||
-rw-r--r-- | src/cryptsetup/cryptsetup-keyfile.c | 110 | ||||
-rw-r--r-- | src/cryptsetup/cryptsetup-keyfile.h | 13 | ||||
-rw-r--r-- | src/cryptsetup/cryptsetup-pkcs11.c | 144 | ||||
-rw-r--r-- | src/cryptsetup/cryptsetup-pkcs11.h | 41 | ||||
-rw-r--r-- | src/cryptsetup/cryptsetup.c | 1058 |
6 files changed, 2283 insertions, 0 deletions
diff --git a/src/cryptsetup/cryptsetup-generator.c b/src/cryptsetup/cryptsetup-generator.c new file mode 100644 index 0000000..68c7349 --- /dev/null +++ b/src/cryptsetup/cryptsetup-generator.c @@ -0,0 +1,917 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include <errno.h> +#include <fcntl.h> +#include <sys/stat.h> +#include <sys/types.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 *headerdev; + char *datadev; + 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 const char *arg_crypttab = NULL; +static const char *arg_runtime_directory = NULL; +static bool arg_allow_list = 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 split_locationspec(const char *locationspec, char **ret_file, char **ret_device) { + _cleanup_free_ char *file = NULL, *device = NULL; + const char *c; + + assert(ret_file); + assert(ret_device); + + if (!locationspec) { + *ret_file = *ret_device = NULL; + return 0; + } + + c = strrchr(locationspec, ':'); + if (c) { + /* The device part has to be either an absolute path to device node (/dev/something, + * /dev/foo/something, or even possibly /dev/foo/something:part), or a fstab device + * specification starting with LABEL= or similar. The file part has the same syntax. + * + * Let's try to guess if the second part looks like a device specification, or just part of a + * filename with a colon. fstab_node_to_udev_node() will convert the fstab device syntax to + * an absolute path. If we didn't get an absolute path, assume that it is just part of the + * first file argument. */ + + device = fstab_node_to_udev_node(c + 1); + if (!device) + return log_oom(); + + if (path_is_absolute(device)) + file = strndup(locationspec, c-locationspec); + else { + log_debug("Location specification argument contains a colon, but \"%s\" doesn't look like a device specification.\n" + "Assuming that \"%s\" is a single device specification.", + c + 1, locationspec); + device = mfree(device); + c = NULL; + } + } + + if (!c) + /* No device specified */ + file = strdup(locationspec); + + if (!file) + return log_oom(); + + *ret_file = TAKE_PTR(file); + *ret_device = TAKE_PTR(device); + + return 0; +} + +static int generate_device_mount( + const char *name, + const char *device, + const char *type_prefix, /* "keydev" or "headerdev" */ + const char *device_timeout, + bool canfail, + bool readonly, + char **unit, + char **mount) { + + _cleanup_free_ char *u = NULL, *where = NULL, *name_escaped = NULL, *device_unit = NULL; + _cleanup_fclose_ FILE *f = NULL; + int r; + usec_t timeout_us; + + assert(name); + assert(device); + assert(unit); + assert(mount); + + r = mkdir_parents(arg_runtime_directory, 0755); + if (r < 0) + return r; + + r = mkdir(arg_runtime_directory, 0700); + if (r < 0 && errno != EEXIST) + return -errno; + + name_escaped = cescape(name); + if (!name_escaped) + return -ENOMEM; + + where = strjoin(arg_runtime_directory, "/", type_prefix, "-", 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; + + fprintf(f, + "[Unit]\n" + "DefaultDependencies=no\n\n" + "[Mount]\n" + "What=%s\n" + "Where=%s\n" + "Options=%s%s\n", device, where, readonly ? "ro" : "rw", canfail ? ",nofail" : ""); + + if (device_timeout) { + r = parse_sec_fix_0(device_timeout, &timeout_us); + if (r >= 0) { + r = unit_name_from_path(device, ".device", &device_unit); + if (r < 0) + return log_error_errno(r, "Failed to generate unit name: %m"); + + r = write_drop_in_format(arg_dest, device_unit, 90, "device-timeout", + "# Automatically generated by systemd-cryptsetup-generator \n\n" + "[Unit]\nJobRunningTimeoutSec=%s", device_timeout); + if (r < 0) + return log_error_errno(r, "Failed to write device drop-in: %m"); + + } else + log_warning_errno(r, "Failed to parse %s, ignoring: %m", device_timeout); + + } + + r = fflush_and_check(f); + if (r < 0) + return r; + + *unit = TAKE_PTR(u); + *mount = TAKE_PTR(where); + + return 0; +} + +static int generate_device_umount(const char *name, + const char *device_mount, + const char *type_prefix, /* "keydev" or "headerdev" */ + char **ret_umount_unit) { + _cleanup_fclose_ FILE *f = NULL; + _cleanup_free_ char *u = NULL, *name_escaped = NULL, *mount = NULL; + int r; + + assert(name); + assert(ret_umount_unit); + + name_escaped = cescape(name); + if (!name_escaped) + return -ENOMEM; + + u = strjoin(type_prefix, "-", name_escaped, "-umount.service"); + if (!u) + return -ENOMEM; + + r = unit_name_from_path(device_mount, ".mount", &mount); + if (r < 0) + return r; + + r = generator_open_unit_file(arg_dest, NULL, u, &f); + if (r < 0) + return r; + + fprintf(f, + "[Unit]\n" + "DefaultDependencies=no\n" + "After=%s\n\n" + "[Service]\n" + "ExecStart=-" UMOUNT_PATH " %s\n\n", mount, device_mount); + + r = fflush_and_check(f); + if (r < 0) + return r; + + *ret_umount_unit = TAKE_PTR(u); + return 0; +} + +static int print_dependencies(FILE *f, const char* device_path) { + int r; + + if (STR_IN_SET(device_path, "-", "none")) + /* None, nothing to do */ + return 0; + + if (PATH_IN_SET(device_path, + "/dev/urandom", + "/dev/random", + "/dev/hw_random", + "/dev/hwrng")) { + /* RNG device, add random dep */ + fputs("After=systemd-random-seed.service\n", f); + return 0; + } + + _cleanup_free_ char *udev_node = fstab_node_to_udev_node(device_path); + if (!udev_node) + return log_oom(); + + if (path_equal(udev_node, "/dev/null")) + return 0; + + if (path_startswith(udev_node, "/dev/")) { + /* We are dealing with a block device, add dependency for corresponding unit */ + _cleanup_free_ char *unit = NULL; + + r = unit_name_from_path(udev_node, ".device", &unit); + if (r < 0) + return log_error_errno(r, "Failed to generate unit name: %m"); + + fprintf(f, + "After=%1$s\n" + "Requires=%1$s\n", unit); + } else { + /* Regular file, add mount dependency */ + _cleanup_free_ char *escaped_path = specifier_escape(device_path); + if (!escaped_path) + return log_oom(); + + fprintf(f, "RequiresMountsFor=%s\n", escaped_path); + } + + return 0; +} + +static int create_disk( + const char *name, + const char *device, + const char *password, + const char *keydev, + const char *headerdev, + const char *options, + const char *source) { + + _cleanup_free_ char *n = NULL, *d = NULL, *u = NULL, *e = NULL, + *keydev_mount = NULL, *keyfile_timeout_value = NULL, + *filtered = NULL, *u_escaped = NULL, *name_escaped = NULL, *header_path = NULL, *password_buffer = NULL, + *tmp_fstype = NULL, *filtered_header = NULL, *headerdev_mount = NULL; + _cleanup_fclose_ FILE *f = NULL; + const char *dmname; + bool noauto, nofail, swap, netdev, attach_in_initrd; + int r, detached_header, keyfile_can_timeout, tmp; + + 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"); + swap = fstab_test_option(options, "swap\0"); + netdev = fstab_test_option(options, "_netdev\0"); + attach_in_initrd = fstab_test_option(options, "x-initrd.attach\0"); + + keyfile_can_timeout = fstab_filter_options(options, "keyfile-timeout\0", NULL, &keyfile_timeout_value, NULL); + if (keyfile_can_timeout < 0) + return log_error_errno(keyfile_can_timeout, "Failed to parse keyfile-timeout= option value: %m"); + + detached_header = fstab_filter_options( + options, + "header\0", + NULL, + &header_path, + headerdev ? &filtered_header : NULL); + if (detached_header < 0) + return log_error_errno(detached_header, "Failed to parse header= option value: %m"); + + tmp = fstab_filter_options(options, "tmp\0", NULL, &tmp_fstype, NULL); + if (tmp < 0) + return log_error_errno(tmp, "Failed to parse tmp= option value: %m"); + + 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 (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; + + r = generator_write_cryptsetup_unit_section(f, source); + if (r < 0) + return r; + + if (netdev) + fprintf(f, "After=remote-fs-pre.target\n"); + + /* If initrd takes care of attaching the disk then it should also detach it during shutdown. */ + if (!attach_in_initrd) + fprintf(f, "Conflicts=umount.target\n"); + + if (keydev) { + _cleanup_free_ char *unit = NULL, *umount_unit = NULL; + + r = generate_device_mount( + name, + keydev, + "keydev", + keyfile_timeout_value, + /* canfail = */ keyfile_can_timeout > 0, + /* readonly= */ true, + &unit, + &keydev_mount); + if (r < 0) + return log_error_errno(r, "Failed to generate keydev mount unit: %m"); + + r = generate_device_umount(name, keydev_mount, "keydev", &umount_unit); + if (r < 0) + return log_error_errno(r, "Failed to generate keydev umount unit: %m"); + + password_buffer = path_join(keydev_mount, password); + if (!password_buffer) + return log_oom(); + + password = password_buffer; + + fprintf(f, "After=%s\n", unit); + if (keyfile_can_timeout > 0) + fprintf(f, "Wants=%s\n", unit); + else + fprintf(f, "Requires=%s\n", unit); + + if (umount_unit) + fprintf(f, + "Wants=%s\n" + "Before=%s\n", + umount_unit, + umount_unit + ); + } + + if (headerdev) { + _cleanup_free_ char *unit = NULL, *umount_unit = NULL, *p = NULL; + + r = generate_device_mount( + name, + headerdev, + "headerdev", + NULL, + /* canfail= */ false, /* header is always necessary */ + /* readonly= */ false, /* LUKS2 recovery requires rw header access */ + &unit, + &headerdev_mount); + if (r < 0) + return log_error_errno(r, "Failed to generate header device mount unit: %m"); + + r = generate_device_umount(name, headerdev_mount, "headerdev", &umount_unit); + if (r < 0) + return log_error_errno(r, "Failed to generate header device umount unit: %m"); + + p = path_join(headerdev_mount, header_path); + if (!p) + return log_oom(); + + free_and_replace(header_path, p); + + if (isempty(filtered_header)) + p = strjoin("header=", header_path); + else + p = strjoin(filtered_header, ",header=", header_path); + + if (!p) + return log_oom(); + + free_and_replace(filtered_header, p); + options = filtered_header; + + fprintf(f, "After=%s\n" + "Requires=%s\n", unit, unit); + + if (umount_unit) { + fprintf(f, + "Wants=%s\n" + "Before=%s\n", + umount_unit, + umount_unit + ); + } + } + + if (!nofail) + fprintf(f, + "Before=%s\n", + netdev ? "remote-cryptsetup.target" : "cryptsetup.target"); + + if (password && !keydev) { + r = print_dependencies(f, password); + if (r < 0) + return r; + } + + /* Check if a header option was specified */ + if (detached_header > 0 && !headerdev) { + r = print_dependencies(f, header_path); + if (r < 0) + return r; + } + + if (path_startswith(u, "/dev/")) + fprintf(f, + "BindsTo=%s\n" + "After=%s\n" + "Before=umount.target\n", + d, d); + 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) + log_warning_errno(r, "Failed to write device timeout drop-in: %m"); + + r = generator_write_cryptsetup_service_section(f, name, u, password, filtered); + if (r < 0) + return r; + + if (tmp) { + _cleanup_free_ char *tmp_fstype_escaped = NULL; + + if (tmp_fstype) { + tmp_fstype_escaped = specifier_escape(tmp_fstype); + if (!tmp_fstype_escaped) + return log_oom(); + } + + fprintf(f, + "ExecStartPost=" ROOTLIBEXECDIR "/systemd-makefs '%s' '/dev/mapper/%s'\n", + tmp_fstype_escaped ?: "ext4", name_escaped); + } + + if (swap) + fprintf(f, + "ExecStartPost=" ROOTLIBEXECDIR "/systemd-makefs swap '/dev/mapper/%s'\n", + name_escaped); + + 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, + 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, 40, "device-timeout", + "# Automatically generated by systemd-cryptsetup-generator\n\n" + "[Unit]\nJobTimeoutSec=0"); + if (r < 0) + log_warning_errno(r, "Failed to write device timeout 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->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 bool warn_uuid_invalid(const char *uuid, const char *key) { + assert(key); + + if (!id128_is_valid(uuid)) { + log_warning("Failed to parse %s= kernel command line switch. UUID is invalid, ignoring.", key); + return true; + } + + return false; +} + +static int filter_header_device(const char *options, + char **ret_headerdev, + char **ret_filtered_headerdev_options) { + int r; + _cleanup_free_ char *headerfile = NULL, *headerdev = NULL, *headerspec = NULL, + *filtered_headerdev = NULL, *filtered_headerspec = NULL; + + assert(ret_headerdev); + assert(ret_filtered_headerdev_options); + + r = fstab_filter_options(options, "header\0", NULL, &headerspec, &filtered_headerspec); + if (r < 0) + return log_error_errno(r, "Failed to parse header= option value: %m"); + + if (r > 0) { + r = split_locationspec(headerspec, &headerfile, &headerdev); + if (r < 0) + return r; + + if (isempty(filtered_headerspec)) + filtered_headerdev = strjoin("header=", headerfile); + else + filtered_headerdev = strjoin(filtered_headerspec, ",header=", headerfile); + + if (!filtered_headerdev) + return log_oom(); + } else + filtered_headerdev = TAKE_PTR(filtered_headerspec); + + *ret_filtered_headerdev_options = TAKE_PTR(filtered_headerdev); + *ret_headerdev = TAKE_PTR(headerdev); + + return 0; +} + +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); + if (!d) + return log_oom(); + + d->create = arg_allow_list = true; + + } else if (streq(key, "luks.options")) { + _cleanup_free_ char *headerdev = NULL, *filtered_headerdev_options = NULL; + + if (proc_cmdline_value_missing(key, value)) + return 0; + + r = sscanf(value, "%m[0-9a-fA-F-]=%ms", &uuid, &uuid_value); + if (r != 2) + return free_and_strdup(&arg_default_options, value) < 0 ? log_oom() : 0; + + if (warn_uuid_invalid(uuid, key)) + return 0; + + d = get_crypto_device(uuid); + if (!d) + return log_oom(); + + r = filter_header_device(uuid_value, &headerdev, &filtered_headerdev_options); + if (r < 0) + return r; + + free_and_replace(d->options, filtered_headerdev_options); + free_and_replace(d->headerdev, headerdev); + } else if (streq(key, "luks.key")) { + size_t n; + _cleanup_free_ char *keyfile = NULL, *keydev = NULL; + const char *keyspec; + + if (proc_cmdline_value_missing(key, value)) + return 0; + + n = strspn(value, ALPHANUMERICAL "-"); + 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 (warn_uuid_invalid(uuid, key)) + return 0; + + d = get_crypto_device(uuid); + if (!d) + return log_oom(); + + keyspec = value + n + 1; + r = split_locationspec(keyspec, &keyfile, &keydev); + if (r < 0) + return r; + + free_and_replace(d->keyfile, keyfile); + free_and_replace(d->keydev, keydev); + } else if (streq(key, "luks.data")) { + size_t n; + _cleanup_free_ char *datadev = NULL; + + if (proc_cmdline_value_missing(key, value)) + return 0; + + n = strspn(value, ALPHANUMERICAL "-"); + if (value[n] != '=') { + log_warning("Failed to parse luks.data= kernel command line switch. UUID is invalid, ignoring."); + return 0; + } + + uuid = strndup(value, n); + if (!uuid) + return log_oom(); + + if (warn_uuid_invalid(uuid, key)) + return 0; + + d = get_crypto_device(uuid); + if (!d) + return log_oom(); + + datadev = fstab_node_to_udev_node(value + n + 1); + if (!datadev) + return log_oom(); + + free_and_replace(d->datadev, datadev); + } 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_allow_list = 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; + int r; + + if (!arg_read_crypttab) + return 0; + + r = fopen_unlocked(arg_crypttab, "re", &f); + if (r < 0) { + if (errno != ENOENT) + log_error_errno(errno, "Failed to open %s: %m", arg_crypttab); + return 0; + } + + for (;;) { + _cleanup_free_ char *line = NULL, *name = NULL, *device = NULL, *keyspec = NULL, *options = NULL, + *keyfile = NULL, *keydev = NULL, *headerdev = NULL, *filtered_header = 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 %s: %m", arg_crypttab); + 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, &keyspec, &options); + if (k < 2 || k > 4) { + log_error("Failed to parse %s:%u, ignoring.", arg_crypttab, crypttab_line); + continue; + } + + uuid = startswith(device, "UUID="); + if (!uuid) + uuid = path_startswith(device, "/dev/disk/by-uuid/"); + if (!uuid) + uuid = startswith(name, "luks-"); + if (uuid) + d = hashmap_get(arg_disks, uuid); + + if (arg_allow_list && !d) { + log_info("Not creating device '%s' because it was not specified on the kernel command line.", name); + continue; + } + + r = split_locationspec(keyspec, &keyfile, &keydev); + if (r < 0) + return r; + + if (options && (!d || !d->options)) { + r = filter_header_device(options, &headerdev, &filtered_header); + if (r < 0) + return r; + free_and_replace(options, filtered_header); + } + + r = create_disk(name, + device, + keyfile, + keydev, + (d && d->options) ? d->headerdev : headerdev, + (d && d->options) ? d->options : options, + arg_crypttab); + if (r < 0) + return r; + + if (d) + d->create = false; + } + + return 0; +} + +static int add_proc_cmdline_devices(void) { + int r; + crypto_device *d; + + HASHMAP_FOREACH(d, arg_disks) { + _cleanup_free_ char *device = NULL; + + if (!d->create) + continue; + + if (!d->name) { + d->name = strjoin("luks-", d->uuid); + if (!d->name) + return log_oom(); + } + + device = strjoin("UUID=", d->uuid); + if (!device) + return log_oom(); + + r = create_disk(d->name, + d->datadev ?: device, + d->keyfile ?: arg_default_keyfile, + d->keydev, + d->headerdev, + d->options ?: arg_default_options, + "/proc/cmdline"); + 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_crypttab = getenv("SYSTEMD_CRYPTTAB") ?: "/etc/crypttab"; + arg_runtime_directory = getenv("RUNTIME_DIRECTORY") ?: "/run/systemd/cryptsetup"; + + 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-keyfile.c b/src/cryptsetup/cryptsetup-keyfile.c new file mode 100644 index 0000000..f849123 --- /dev/null +++ b/src/cryptsetup/cryptsetup-keyfile.c @@ -0,0 +1,110 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include <unistd.h> + +#include "cryptsetup-keyfile.h" +#include "fd-util.h" +#include "format-util.h" +#include "memory-util.h" +#include "path-util.h" +#include "stat-util.h" +#include "strv.h" + +#define KEY_FILE_SIZE_MAX (16U*1024U*1024U) /* 16 MiB */ + +int load_key_file( + const char *key_file, + char **search_path, + size_t key_file_size, + uint64_t key_file_offset, + void **ret_key, + size_t *ret_key_size) { + + _cleanup_(erase_and_freep) char *buffer = NULL; + _cleanup_free_ char *discovered_path = NULL; + _cleanup_close_ int fd = -1; + ssize_t n; + int r; + + assert(key_file); + assert(ret_key); + assert(ret_key_size); + + if (strv_isempty(search_path) || path_is_absolute(key_file)) { + fd = open(key_file, O_RDONLY|O_CLOEXEC); + if (fd < 0) + return log_error_errno(errno, "Failed to load key file '%s': %m", key_file); + } else { + char **i; + + STRV_FOREACH(i, search_path) { + _cleanup_free_ char *joined; + + joined = path_join(*i, key_file); + if (!joined) + return log_oom(); + + fd = open(joined, O_RDONLY|O_CLOEXEC); + if (fd >= 0) { + discovered_path = TAKE_PTR(joined); + break; + } + if (errno != ENOENT) + return log_error_errno(errno, "Failed to load key file '%s': %m", joined); + } + + if (!discovered_path) { + /* Search path supplied, but file not found, report by returning NULL, but not failing */ + *ret_key = NULL; + *ret_key_size = 0; + return 0; + } + + assert(fd >= 0); + key_file = discovered_path; + } + + if (key_file_size == 0) { + struct stat st; + + if (fstat(fd, &st) < 0) + return log_error_errno(errno, "Failed to stat key file '%s': %m", key_file); + + r = stat_verify_regular(&st); + if (r < 0) + return log_error_errno(r, "Key file is not a regular file: %m"); + + if (st.st_size == 0) + return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Key file is empty, refusing."); + if ((uint64_t) st.st_size > KEY_FILE_SIZE_MAX) { + char buf1[FORMAT_BYTES_MAX], buf2[FORMAT_BYTES_MAX]; + return log_error_errno(SYNTHETIC_ERRNO(ERANGE), + "Key file larger (%s) than allowed maximum size (%s), refusing.", + format_bytes(buf1, sizeof(buf1), st.st_size), + format_bytes(buf2, sizeof(buf2), KEY_FILE_SIZE_MAX)); + } + + if (key_file_offset >= (uint64_t) st.st_size) + return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Key file offset too large for file, refusing."); + + key_file_size = st.st_size - key_file_offset; + } + + buffer = malloc(key_file_size); + if (!buffer) + return log_oom(); + + if (key_file_offset > 0) + n = pread(fd, buffer, key_file_size, key_file_offset); + else + n = read(fd, buffer, key_file_size); + if (n < 0) + return log_error_errno(errno, "Failed to read key file '%s': %m", key_file); + if (n == 0) + return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Empty encrypted key found, refusing."); + + *ret_key = TAKE_PTR(buffer); + *ret_key_size = (size_t) n; + + return 1; +} diff --git a/src/cryptsetup/cryptsetup-keyfile.h b/src/cryptsetup/cryptsetup-keyfile.h new file mode 100644 index 0000000..308f5eb --- /dev/null +++ b/src/cryptsetup/cryptsetup-keyfile.h @@ -0,0 +1,13 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +#pragma once + +#include <inttypes.h> +#include <sys/types.h> + +int load_key_file( + const char *key_file, + char **search_path, + size_t key_file_size, + uint64_t key_file_offset, + void **ret_key, + size_t *ret_key_size); diff --git a/src/cryptsetup/cryptsetup-pkcs11.c b/src/cryptsetup/cryptsetup-pkcs11.c new file mode 100644 index 0000000..50db46f --- /dev/null +++ b/src/cryptsetup/cryptsetup-pkcs11.c @@ -0,0 +1,144 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include <fcntl.h> +#include <unistd.h> +#include <sys/stat.h> + +#include <p11-kit/p11-kit.h> +#include <p11-kit/uri.h> + +#include "alloc-util.h" +#include "ask-password-api.h" +#include "cryptsetup-pkcs11.h" +#include "cryptsetup-keyfile.h" +#include "escape.h" +#include "fd-util.h" +#include "format-util.h" +#include "macro.h" +#include "memory-util.h" +#include "pkcs11-util.h" +#include "stat-util.h" +#include "strv.h" + +struct pkcs11_callback_data { + const char *friendly_name; + usec_t until; + void *encrypted_key; + size_t encrypted_key_size; + void *decrypted_key; + size_t decrypted_key_size; + bool free_encrypted_key; +}; + +static void pkcs11_callback_data_release(struct pkcs11_callback_data *data) { + free(data->decrypted_key); + + if (data->free_encrypted_key) + free(data->encrypted_key); +} + +static int pkcs11_callback( + CK_FUNCTION_LIST *m, + CK_SESSION_HANDLE session, + CK_SLOT_ID slot_id, + const CK_SLOT_INFO *slot_info, + const CK_TOKEN_INFO *token_info, + P11KitUri *uri, + void *userdata) { + + struct pkcs11_callback_data *data = userdata; + CK_OBJECT_HANDLE object; + int r; + + assert(m); + assert(slot_info); + assert(token_info); + assert(uri); + assert(data); + + /* Called for every token matching our URI */ + + r = pkcs11_token_login( + m, + session, + slot_id, + token_info, + data->friendly_name, + "drive-harddisk", + "pkcs11-pin", + data->until, + NULL); + if (r < 0) + return r; + + /* We are likely called during early boot, where entropy is scarce. Mix some data from the PKCS#11 + * token, if it supports that. It should be cheap, given that we already are talking to it anyway and + * shouldn't hurt. */ + (void) pkcs11_token_acquire_rng(m, session); + + r = pkcs11_token_find_private_key(m, session, uri, &object); + if (r < 0) + return r; + + r = pkcs11_token_decrypt_data( + m, + session, + object, + data->encrypted_key, + data->encrypted_key_size, + &data->decrypted_key, + &data->decrypted_key_size); + if (r < 0) + return r; + + return 0; +} + +int decrypt_pkcs11_key( + const char *friendly_name, + const char *pkcs11_uri, + const char *key_file, /* We either expect key_file and associated parameters to be set (for file keys) … */ + size_t key_file_size, + uint64_t key_file_offset, + const void *key_data, /* … or key_data and key_data_size (for literal keys) */ + size_t key_data_size, + usec_t until, + void **ret_decrypted_key, + size_t *ret_decrypted_key_size) { + + _cleanup_(pkcs11_callback_data_release) struct pkcs11_callback_data data = { + .friendly_name = friendly_name, + .until = until, + }; + int r; + + assert(friendly_name); + assert(pkcs11_uri); + assert(key_file || key_data); + assert(ret_decrypted_key); + assert(ret_decrypted_key_size); + + /* The functions called here log about all errors, except for EAGAIN which means "token not found right now" */ + + if (key_data) { + data.encrypted_key = (void*) key_data; + data.encrypted_key_size = key_data_size; + + data.free_encrypted_key = false; + } else { + r = load_key_file(key_file, NULL, key_file_size, key_file_offset, &data.encrypted_key, &data.encrypted_key_size); + if (r < 0) + return r; + + data.free_encrypted_key = true; + } + + r = pkcs11_find_token(pkcs11_uri, pkcs11_callback, &data); + if (r < 0) + return r; + + *ret_decrypted_key = TAKE_PTR(data.decrypted_key); + *ret_decrypted_key_size = data.decrypted_key_size; + + return 0; +} diff --git a/src/cryptsetup/cryptsetup-pkcs11.h b/src/cryptsetup/cryptsetup-pkcs11.h new file mode 100644 index 0000000..266c8e1 --- /dev/null +++ b/src/cryptsetup/cryptsetup-pkcs11.h @@ -0,0 +1,41 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +#pragma once + +#include <sys/types.h> + +#include "log.h" +#include "time-util.h" + +#if HAVE_P11KIT + +int decrypt_pkcs11_key( + const char *friendly_name, + const char *pkcs11_uri, + const char *key_file, + size_t key_file_size, + uint64_t key_file_offset, + const void *key_data, + size_t key_data_size, + usec_t until, + void **ret_decrypted_key, + size_t *ret_decrypted_key_size); + +#else + +static inline int decrypt_pkcs11_key( + const char *friendly_name, + const char *pkcs11_uri, + const char *key_file, + size_t key_file_size, + uint64_t key_file_offset, + const void *key_data, + size_t key_data_size, + usec_t until, + void **ret_decrypted_key, + size_t *ret_decrypted_key_size) { + + return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), + "PKCS#11 Token support not available."); +} + +#endif diff --git a/src/cryptsetup/cryptsetup.c b/src/cryptsetup/cryptsetup.c new file mode 100644 index 0000000..129f5fc --- /dev/null +++ b/src/cryptsetup/cryptsetup.c @@ -0,0 +1,1058 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include <errno.h> +#include <mntent.h> +#include <sys/mman.h> +#include <sys/stat.h> +#include <sys/types.h> +#include <unistd.h> + +#include "sd-device.h" + +#include "alloc-util.h" +#include "ask-password-api.h" +#include "cryptsetup-keyfile.h" +#include "cryptsetup-pkcs11.h" +#include "cryptsetup-util.h" +#include "device-util.h" +#include "escape.h" +#include "fileio.h" +#include "fs-util.h" +#include "fstab-util.h" +#include "hexdecoct.h" +#include "log.h" +#include "main-func.h" +#include "memory-util.h" +#include "mount-util.h" +#include "nulstr-util.h" +#include "parse-util.h" +#include "path-util.h" +#include "pkcs11-util.h" +#include "pretty-print.h" +#include "string-util.h" +#include "strv.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, CRYPT_BITLK or CRYPT_PLAIN */ +static char *arg_cipher = NULL; +static unsigned arg_key_size = 0; +static unsigned arg_sector_size = CRYPT_SECTOR_SIZE; +static int arg_key_slot = CRYPT_ANY_SLOT; +static unsigned arg_keyfile_size = 0; +static uint64_t arg_keyfile_offset = 0; +static bool arg_keyfile_erase = false; +static bool arg_try_empty_password = false; +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_same_cpu_crypt = false; +static bool arg_submit_from_crypt_cpus = false; +static bool arg_no_read_workqueue = false; +static bool arg_no_write_workqueue = false; +static bool arg_tcrypt_hidden = false; +static bool arg_tcrypt_system = false; +static bool arg_tcrypt_veracrypt = false; +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 char *arg_pkcs11_uri = NULL; + +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); +STATIC_DESTRUCTOR_REGISTER(arg_pkcs11_uri, freep); + +/* Options Debian's crypttab knows we don't: + + check= + checkargs= + noearly + loud + quiet + keyscript= + initramfs +*/ + +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", "keyfile-timeout")) + return 0; + + if (startswith(option, "keyfile-timeout=")) + 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="))) { + + 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 if ((val = startswith(option, "key-slot=")) || + (val = startswith(option, "keyslot="))) { + + 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="))) { + + r = safe_atou64(val, &arg_keyfile_offset); + if (r < 0) { + log_error_errno(r, "Failed to parse %s, ignoring: %m", option); + return 0; + } + + } else if ((val = startswith(option, "keyfile-erase="))) { + + r = parse_boolean(val); + if (r < 0) { + log_error_errno(r, "Failed to parse %s, ignoring: %m", option); + return 0; + } + + arg_keyfile_erase = r; + + } else if (streq(option, "keyfile-erase")) + arg_keyfile_erase = true; + + 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, "same-cpu-crypt")) + arg_same_cpu_crypt = true; + else if (streq(option, "submit-from-crypt-cpus")) + arg_submit_from_crypt_cpus = true; + else if (streq(option, "no-read-workqueue")) + arg_no_read_workqueue = true; + else if (streq(option, "no-write-workqueue")) + arg_no_write_workqueue = true; + else if (streq(option, "luks")) + arg_type = ANY_LUKS; +/* since cryptsetup 2.3.0 (Feb 2020) */ +#ifdef CRYPT_BITLK + else if (streq(option, "bitlk")) + arg_type = CRYPT_BITLK; +#endif + else if (streq(option, "tcrypt")) + arg_type = CRYPT_TCRYPT; + else if (STR_IN_SET(option, "tcrypt-hidden", "tcrypthidden")) { + arg_type = CRYPT_TCRYPT; + arg_tcrypt_hidden = true; + } else if (streq(option, "tcrypt-system")) { + arg_type = CRYPT_TCRYPT; + arg_tcrypt_system = true; + } else if (STR_IN_SET(option, "tcrypt-veracrypt", "veracrypt")) { + arg_type = CRYPT_TCRYPT; + arg_tcrypt_veracrypt = true; + } else if (STR_IN_SET(option, "plain", "swap", "tmp") || + startswith(option, "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 ((val = startswith(option, "pkcs11-uri="))) { + + if (!pkcs11_uri_valid(val)) + return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "pkcs11-uri= parameter expects a PKCS#11 URI, refusing"); + + r = free_and_strdup(&arg_pkcs11_uri, val); + if (r < 0) + return log_oom(); + + } else if ((val = startswith(option, "try-empty-password="))) { + + r = parse_boolean(val); + if (r < 0) { + log_error_errno(r, "Failed to parse %s, ignoring: %m", option); + return 0; + } + + arg_try_empty_password = r; + + } else if (streq(option, "try-empty-password")) + arg_try_empty_password = true; + + else if (!streq(option, "x-initrd.attach")) + log_warning("Encountered unknown /etc/crypttab option '%s', ignoring.", option); + + return 0; +} + +static int parse_options(const char *options) { + assert(options); + + for (;;) { + _cleanup_free_ char *word = NULL; + int r; + + r = extract_first_word(&options, &word, ",", EXTRACT_DONT_COALESCE_SEPARATORS | EXTRACT_UNESCAPE_SEPARATORS); + if (r < 0) + return log_error_errno(r, "Failed to parse options: %m"); + if (r == 0) + break; + + r = parse_one_option(word); + if (r < 0) + return r; + } + + /* sanity-check options */ + if (arg_type && !streq(arg_type, CRYPT_PLAIN)) { + if (arg_offset != 0) + log_warning("offset= ignored with type %s", arg_type); + if (arg_skip != 0) + 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 */ + + device = strjoin("/dev/mapper/", label); + if (!device) + return NULL; + + f = setmntent(fstab_path(), "re"); + if (!f) + return NULL; + + while ((m = getmntent(f))) + if (path_equal(m->mnt_fsname, device)) + return strdup(m->mnt_dir); + + return NULL; +} + +static char *friendly_disk_name(const char *src, const char *vol) { + _cleanup_free_ char *description = NULL, *mount_point = NULL; + char *name_buffer = NULL; + int r; + + assert(src); + assert(vol); + + description = disk_description(src); + mount_point = disk_mount_point(vol); + + /* If the description string is simply the volume name, then let's not show this twice */ + if (description && streq(vol, description)) + 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); + else + return strdup(vol); + if (r < 0) + return NULL; + + return name_buffer; +} + +static int get_password( + const char *vol, + const char *src, + usec_t until, + bool accept_cached, + char ***ret) { + + _cleanup_free_ char *friendly = NULL, *text = NULL, *disk_path = NULL; + _cleanup_strv_free_erase_ char **passwords = NULL; + char **p, *id; + int r = 0; + + assert(vol); + assert(src); + assert(ret); + + friendly = friendly_disk_name(src, vol); + if (!friendly) + return log_oom(); + + if (asprintf(&text, "Please enter passphrase for disk %s:", friendly) < 0) + return log_oom(); + + disk_path = cescape(src); + if (!disk_path) + 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):", friendly) < 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])) + return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN), + "Passwords did not match, retrying."); + } + + 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, + const void *key_data, + size_t key_data_size, + 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 || key_data || !strv_isempty(passwords)); + + if (arg_pkcs11_uri) + /* Ask for a regular password */ + return log_error_errno(SYNTHETIC_ERRNO(EAGAIN), + "Sorry, but tcrypt devices are currently not supported in conjunction with pkcs11 support."); + + if (arg_tcrypt_hidden) + params.flags |= CRYPT_TCRYPT_HIDDEN_HEADER; + + if (arg_tcrypt_system) + params.flags |= CRYPT_TCRYPT_SYSTEM_HEADER; + + if (arg_tcrypt_veracrypt) + params.flags |= CRYPT_TCRYPT_VERA_MODES; + + if (key_data) { + params.passphrase = key_data; + params.passphrase_size = key_data_size; + } else { + 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 (r == -EPERM) { + if (key_data) + log_error_errno(r, "Failed to activate using discovered key. (Key not correct?)"); + + if (key_file) + 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_or_bitlk( + struct crypt_device *cd, + const char *name, + const char *key_file, + const void *key_data, + size_t key_data_size, + char **passwords, + uint32_t flags, + usec_t until) { + + int r = 0; + bool pass_volume_key = false; + + assert(cd); + assert(name); + + if ((!arg_type && !crypt_get_type(cd)) || streq_ptr(arg_type, CRYPT_PLAIN)) { + struct crypt_params_plain params = { + .offset = arg_offset, + .skip = arg_skip, + .sector_size = arg_sector_size, + }; + 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_format() 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); + if (r < 0) + return log_error_errno(r, "Loading of cryptographic parameters failed: %m"); + + /* hash == NULL implies the user passed "plain" */ + pass_volume_key = (params.hash == NULL); + } + + 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 (arg_pkcs11_uri) { + _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL; + _cleanup_(sd_event_unrefp) sd_event *event = NULL; + _cleanup_free_ void *decrypted_key = NULL; + _cleanup_free_ char *friendly = NULL; + size_t decrypted_key_size = 0; + + if (!key_file && !key_data) + return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "PKCS#11 mode selected but no key file specified, refusing."); + + friendly = friendly_disk_name(crypt_get_device_name(cd), name); + if (!friendly) + return log_oom(); + + for (;;) { + bool processed = false; + + r = decrypt_pkcs11_key( + friendly, + arg_pkcs11_uri, + key_file, arg_keyfile_size, arg_keyfile_offset, + key_data, key_data_size, + until, + &decrypted_key, &decrypted_key_size); + if (r >= 0) + break; + if (r != -EAGAIN) /* EAGAIN means: token not found */ + return r; + + if (!monitor) { + /* We didn't find the token. In this case, watch for it via udev. Let's + * create an event loop and monitor first. */ + + assert(!event); + + r = sd_event_default(&event); + if (r < 0) + return log_error_errno(r, "Failed to allocate event loop: %m"); + + r = sd_device_monitor_new(&monitor); + if (r < 0) + return log_error_errno(r, "Failed to allocate device monitor: %m"); + + r = sd_device_monitor_filter_add_match_tag(monitor, "security-device"); + if (r < 0) + return log_error_errno(r, "Failed to configure device monitor: %m"); + + r = sd_device_monitor_attach_event(monitor, event); + if (r < 0) + return log_error_errno(r, "Failed to attach device monitor: %m"); + + r = sd_device_monitor_start(monitor, NULL, NULL); + if (r < 0) + return log_error_errno(r, "Failed to start device monitor: %m"); + + log_notice("Security token %s not present for unlocking volume %s, please plug it in.", + arg_pkcs11_uri, friendly); + + /* Let's immediately rescan in case the token appeared in the time we needed + * to create and configure the monitor */ + continue; + } + + for (;;) { + /* Wait for one event, and then eat all subsequent events until there are no + * further ones */ + r = sd_event_run(event, processed ? 0 : UINT64_MAX); + if (r < 0) + return log_error_errno(r, "Failed to run event loop: %m"); + if (r == 0) + break; + + processed = true; + } + + log_debug("Got one or more potentially relevant udev events, rescanning PKCS#11..."); + } + + if (pass_volume_key) + r = crypt_activate_by_volume_key(cd, name, decrypted_key, decrypted_key_size, flags); + else { + _cleanup_free_ char *base64_encoded = NULL; + + /* Before using this key as passphrase we base64 encode it. Why? For compatibility + * with homed's PKCS#11 hookup: there we want to use the key we acquired through + * PKCS#11 for other authentication/decryption mechanisms too, and some of them do + * not not take arbitrary binary blobs, but require NUL-terminated strings — most + * importantly UNIX password hashes. Hence, for compatibility we want to use a string + * without embedded NUL here too, and that's easiest to generate from a binary blob + * via base64 encoding. */ + + r = base64mem(decrypted_key, decrypted_key_size, &base64_encoded); + if (r < 0) + return log_oom(); + + r = crypt_activate_by_passphrase(cd, name, arg_key_slot, base64_encoded, strlen(base64_encoded), flags); + } + if (r == -EPERM) { + log_error_errno(r, "Failed to activate with PKCS#11 decrypted key. (Key incorrect?)"); + return -EAGAIN; /* log actual error, but return EAGAIN */ + } + if (r < 0) + return log_error_errno(r, "Failed to activate with PKCS#11 acquired key: %m"); + + } else if (key_data) { + if (pass_volume_key) + r = crypt_activate_by_volume_key(cd, name, key_data, key_data_size, flags); + else + r = crypt_activate_by_passphrase(cd, name, arg_key_slot, key_data, key_data_size, flags); + if (r == -EPERM) { + log_error_errno(r, "Failed to activate. (Key incorrect?)"); + return -EAGAIN; /* Log actual error, but return EAGAIN */ + } + if (r < 0) + return log_error_errno(r, "Failed to activate: %m"); + + } else if (key_file) { + r = crypt_activate_by_keyfile_device_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 == -EINVAL) { + log_error_errno(r, "Failed to activate with key file '%s'. (Key file missing?)", 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 uint32_t determine_flags(void) { + uint32_t flags = 0; + + if (arg_readonly) + flags |= CRYPT_ACTIVATE_READONLY; + + if (arg_discards) + flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS; + + if (arg_same_cpu_crypt) + flags |= CRYPT_ACTIVATE_SAME_CPU_CRYPT; + + if (arg_submit_from_crypt_cpus) + flags |= CRYPT_ACTIVATE_SUBMIT_FROM_CRYPT_CPUS; + + if (arg_no_read_workqueue) + flags |= CRYPT_ACTIVATE_NO_READ_WORKQUEUE; + + if (arg_no_write_workqueue) + flags |= CRYPT_ACTIVATE_NO_WRITE_WORKQUEUE; + +#ifdef CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF + /* Try to decrease the risk of OOM event if memory hard key derivation function is in use */ + /* https://gitlab.com/cryptsetup/cryptsetup/issues/446/ */ + flags |= CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF; +#endif + + return flags; +} + +static void remove_and_erasep(const char **p) { + int r; + + if (!*p) + return; + + r = unlinkat_deallocate(AT_FDCWD, *p, UNLINK_ERASE); + if (r < 0 && r != -ENOENT) + log_warning_errno(r, "Unable to erase key file '%s', ignoring: %m", *p); +} + +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) + return log_error_errno(SYNTHETIC_ERRNO(EINVAL), + "This program requires at least two arguments."); + + log_setup_service(); + + cryptsetup_enable_logging(cd); + + umask(0022); + + if (streq(argv[1], "attach")) { + uint32_t flags = 0; + unsigned tries; + usec_t until; + crypt_status_info status; + _cleanup_(remove_and_erasep) const char *destroy_key_file = NULL; + const char *key_file = NULL; + _cleanup_(erase_and_freep) void *key_data = NULL; + size_t key_data_size = 0; + + /* 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 (!filename_is_valid(argv[2])) + return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Volume name '%s' is not valid.", argv[2]); + + if (argc >= 5 && !STR_IN_SET(argv[4], "", "-", "none")) { + if (path_is_absolute(argv[4])) + key_file = argv[4]; + else + log_warning("Password file path '%s' is not absolute. Ignoring.", argv[4]); + } + + if (argc >= 6 && !STR_IN_SET(argv[5], "", "-", "none")) { + r = parse_options(argv[5]); + if (r < 0) + return r; + } + + log_debug("%s %s ← %s type=%s cipher=%s", __func__, + argv[2], argv[3], strempty(arg_type), strempty(arg_cipher)); + + /* A delicious drop of snake oil */ + (void) mlockall(MCL_FUTURE); + + if (!key_file) { + const char *fn; + + /* If a key file is not explicitly specified, search for a key in a well defined + * search path, and load it. */ + + fn = strjoina(argv[2], ".key"); + r = load_key_file(fn, + STRV_MAKE("/etc/cryptsetup-keys.d", "/run/cryptsetup-keys.d"), + 0, 0, /* Note we leave arg_keyfile_offset/arg_keyfile_size as something that only applies to arg_keyfile! */ + &key_data, &key_data_size); + if (r < 0) + return r; + if (r > 0) + log_debug("Automatically discovered key for volume '%s'.", argv[2]); + } else if (arg_keyfile_erase) + destroy_key_file = key_file; /* let's get this baby erased when we leave */ + + 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"); + + cryptsetup_enable_logging(cd); + + status = crypt_status(cd, argv[2]); + if (IN_SET(status, CRYPT_ACTIVE, CRYPT_BUSY)) { + log_info("Volume %s already active.", argv[2]); + return 0; + } + + flags = determine_flags(); + + 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); + } + + if (!arg_type || STR_IN_SET(arg_type, ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2)) { + r = crypt_load(cd, !arg_type || streq(arg_type, ANY_LUKS) ? CRYPT_LUKS : arg_type, NULL); + if (r < 0) + return log_error_errno(r, "Failed to load LUKS superblock on device %s: %m", crypt_get_device_name(cd)); + + if (arg_header) { + r = crypt_set_data_device(cd, argv[3]); + if (r < 0) + return log_error_errno(r, "Failed to set LUKS data device %s: %m", argv[3]); + } + + /* Tokens are available in LUKS2 only, but it is ok to call (and fail) with LUKS1. */ + if (!key_file && !key_data) { + r = crypt_activate_by_token(cd, argv[2], CRYPT_ANY_TOKEN, NULL, flags); + if (r >= 0) { + log_debug("Volume %s activated with LUKS token id %i.", argv[2], r); + return 0; + } + + log_debug_errno(r, "Token activation unsuccessful for device %s: %m", crypt_get_device_name(cd)); + } + } + +/* since cryptsetup 2.3.0 (Feb 2020) */ +#ifdef CRYPT_BITLK + if (streq_ptr(arg_type, CRYPT_BITLK)) { + r = crypt_load(cd, CRYPT_BITLK, NULL); + if (r < 0) + return log_error_errno(r, "Failed to load Bitlocker superblock on device %s: %m", crypt_get_device_name(cd)); + } +#endif + + for (tries = 0; arg_tries == 0 || tries < arg_tries; tries++) { + _cleanup_strv_free_erase_ char **passwords = NULL; + + /* When we were able to acquire multiple keys, let's always process them in this order: + * + * 1. A key acquired via PKCS#11 token + * 2. The discovered key: i.e. key_data + key_data_size + * 3. The configured key: i.e. key_file + arg_keyfile_offset + arg_keyfile_size + * 4. The empty password, in case arg_try_empty_password is set + * 5. We enquire the user for a password + */ + + if (!key_file && !key_data && !arg_pkcs11_uri) { + + if (arg_try_empty_password) { + /* Hmm, let's try an empty password now, but only once */ + arg_try_empty_password = false; + + key_data = strdup(""); + if (!key_data) + return log_oom(); + + key_data_size = 0; + } else { + /* Ask the user for a passphrase only as last resort, if we have + * nothing else to check for */ + + 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, key_data, key_data_size, passwords, flags); + else + r = attach_luks_or_plain_or_bitlk(cd, argv[2], key_file, key_data, key_data_size, passwords, flags, until); + if (r >= 0) + break; + if (r != -EAGAIN) + return r; + + /* Key not correct? Let's try again! */ + + key_file = NULL; + key_data = erase_and_free(key_data); + key_data_size = 0; + arg_pkcs11_uri = mfree(arg_pkcs11_uri); + } + + 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")) { + + if (!filename_is_valid(argv[2])) + return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Volume name '%s' is not valid.", argv[2]); + + 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"); + + cryptsetup_enable_logging(cd); + + 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); |