HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/cryptsetup/cryptsetup.c

114,006 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 425fc7be32b5b7f2d380a78cfecc8640727d6b68

Lines 1001–2000 of 2,795

 
static int measure_volume_key(
                struct crypt_device *cd,
                const char *name,
                const void *volume_key,
                size_t volume_key_size) {
 
        int r;
 
        assert(cd);
        assert(name);
        assert(volume_key);
        assert(volume_key_size > 0);
 
        if (arg_tpm2_measure_pcr == UINT_MAX) {
                log_debug("Not measuring volume key, deactivated.");
                return 0;
        }
 
        r = efi_measured_os(LOG_WARNING);
        if (r < 0)
                return r;
        if (r == 0) {
                log_debug("OS measurements not explicitly requested and kernel stub did not measure kernel image into the expected PCR, skipping userspace volume key measurement, too.");
                return 0;
        }
 
        _cleanup_free_ char *prefix = NULL;
 
        /* Note: what is extended to the SHA256 bank here must match the expected hash of 'fixate-volume-key='
         * calculated by cryptsetup_get_volume_key_id(). */
        r = cryptsetup_get_volume_key_prefix(cd, name, &prefix);
        if (r < 0)
                return log_error_errno(r, "Failed to get volume key prefix: %m");
 
        /* Pass the volume key as HMAC secret. pcrextend extends HMAC(volume_key, prefix),
         * never a bare hash. Matches cryptsetup_get_volume_key_id(). */
        r = pcrextend_pcr_now(arg_tpm2_measure_pcr, prefix, &IOVEC_MAKE(volume_key, volume_key_size), "volume_key");
        if (r < 0)
                return log_error_errno(r, "Could not extend PCR: %m");
 
        return 0;
}
 
static int measure_keyslot(
                struct crypt_device *cd,
                const char *name,
                const char *mechanism,
                int keyslot) {
 
        int r;
 
        assert(cd);
        assert(name);
 
        if (!arg_tpm2_measure_keyslot_nvpcr) {
                log_debug("Not measuring unlock keyslot, deactivated.");
                return 0;
        }
 
        r = efi_measured_os(LOG_WARNING);
        if (r < 0)
                return r;
        if (r == 0) {
                log_debug("OS measurements not explicitly requested and kernel stub did not measure kernel image into the expected PCR, skipping userspace key slot measurement, too.");
                return 0;
        }
 
        _cleanup_free_ char *escaped = NULL;
        escaped = xescape(name, ":"); /* avoid ambiguity around ":" once we join things below */
        if (!escaped)
                return log_oom();
 
        _cleanup_free_ char *k = NULL;
        if (keyslot >= 0 && asprintf(&k, "%i", keyslot) < 0)
                return log_oom();
 
        _cleanup_free_ char *s = NULL;
        s = strjoin("cryptsetup-keyslot:", escaped, ":", strempty(sym_crypt_get_uuid(cd)), ":", strempty(mechanism), ":", strempty(k));
        if (!s)
                return log_oom();
 
        r = pcrextend_nvpcr_now(arg_tpm2_measure_keyslot_nvpcr, s, "keyslot");
        if (r < 0)
                return log_error_errno(r, "Could not extend NvPCR: %m");
 
        return 0;
}
 
static int log_external_activation(int r, const char *volume) {
        assert(volume);
 
        log_notice_errno(r, "Volume '%s' has been activated externally while we have been trying to activate it.", volume);
        return 0;
}
 
static int measured_crypt_activate_by_volume_key(
                struct crypt_device *cd,
                const char *name,
                const char *mechanism,
                int keyslot,
                const void *volume_key,
                size_t volume_key_size,
                uint32_t flags) {
 
        int r;
 
        assert(cd);
        assert(name);
 
        /* A wrapper around crypt_activate_by_volume_key() which also measures to a PCR if that's requested. */
 
        /* First, check if volume key digest matches the expectation. */
        if (arg_fixate_volume_key) {
                 _cleanup_free_ char *key_id = NULL;
 
                 r = cryptsetup_get_volume_key_id(
                                 cd,
                                 /* volume_name= */ name,
                                 /* volume_key= */ volume_key,
                                 /* volume_key_size= */ volume_key_size,
                                 /* ret= */ &key_id);
                 if (r < 0)
                         return log_error_errno(r, "Failed to get volume key id.");
 
                 if (!streq(arg_fixate_volume_key, key_id))
                         return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                "Volume key id: '%s' does not match the expectation: '%s'.",
                                                key_id, arg_fixate_volume_key);
        }
 
        r = sym_crypt_activate_by_volume_key(cd, name, volume_key, volume_key_size, flags);
        if (r == -EEXIST) /* volume is already active */
                return log_external_activation(r, name);
        if (r < 0)
                return r;
 
        if (arg_tpm2_measure_pcr == UINT_MAX) {
                log_debug("Not measuring volume key, deactivated.");
                return 0;
        }
 
        if (volume_key_size > 0)
                (void) measure_volume_key(cd, name, volume_key, volume_key_size); /* OK if fails */
        else
                log_debug("Not measuring volume key, none specified.");
 
        (void) measure_keyslot(cd, name, mechanism, keyslot); /* ditto */
        return r;
}
 
static int measured_crypt_activate_by_passphrase(
                struct crypt_device *cd,
                const char *name,
                const char *mechanism,
                int keyslot,
                const char *passphrase,
                size_t passphrase_size,
                uint32_t flags) {
 
        _cleanup_(erase_and_freep) void *vk = NULL;
        size_t vks;
        int r;
 
        assert(cd);
 
        /* A wrapper around crypt_activate_by_passphrase() which also measures to a PCR if that's
         * requested. Note that we may need the volume key for the measurement and/or for the comparison, and
         * crypt_activate_by_passphrase() doesn't give us access to this. Hence, we operate indirectly, and
         * retrieve the volume key first, and then activate through that. */
 
        if (arg_tpm2_measure_pcr == UINT_MAX && !arg_fixate_volume_key)
                goto shortcut;
 
        r = sym_crypt_get_volume_key_size(cd);
        if (r < 0)
                return r;
        if (r == 0) {
                log_debug("Not measuring volume key, none defined.");
                goto shortcut;
        }
 
        vk = malloc(vks = r);
        if (!vk)
                return -ENOMEM;
 
        keyslot = sym_crypt_volume_key_get(cd, keyslot, vk, &vks, passphrase, passphrase_size);
        if (keyslot < 0)
                return keyslot;
 
        return measured_crypt_activate_by_volume_key(cd, name, mechanism, keyslot, vk, vks, flags);
 
shortcut:
        keyslot = sym_crypt_activate_by_passphrase(cd, name, keyslot, passphrase, passphrase_size, flags);
        if (keyslot == -EEXIST) /* volume is already active */
                return log_external_activation(keyslot, name);
        if (keyslot < 0)
                return keyslot;
 
        (void) measure_keyslot(cd, name, mechanism, keyslot);
        return keyslot;
}
 
static int attach_tcrypt(
                struct crypt_device *cd,
                const char *name,
                TokenType token_type,
                const char *key_file,
                const struct iovec *key_data,
                char **passwords,
                uint32_t flags) {
 
        int r = 0;
        _cleanup_(erase_and_freep) 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 (token_type >= 0)
                /* Ask for a regular password */
                return log_error_errno(SYNTHETIC_ERRNO(EAGAIN),
                                       "Sorry, but tcrypt devices are currently not supported in conjunction with pkcs11/fido2/tpm2 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 (arg_tcrypt_veracrypt && arg_tcrypt_veracrypt_pim != 0)
                params.veracrypt_pim = arg_tcrypt_veracrypt_pim;
 
        if (key_data) {
                params.passphrase = key_data->iov_base;
                params.passphrase_size = key_data->iov_len;
                r = sym_crypt_load(cd, CRYPT_TCRYPT, &params);
        } 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;
                params.passphrase_size = strlen(passphrase);
                r = sym_crypt_load(cd, CRYPT_TCRYPT, &params);
        } else {
                r = -EINVAL;
                STRV_FOREACH(p, passwords){
                        params.passphrase = *p;
                        params.passphrase_size = strlen(*p);
                        r = sym_crypt_load(cd, CRYPT_TCRYPT, &params);
                        if (r >= 0)
                                break;
                }
        }
 
        if (r < 0) {
                if (r == -EPERM) {
                        if (key_data)
                                log_error_errno(r, "Failed to activate using discovered key. (Key not correct?)");
                        else if (key_file)
                                log_error_errno(r, "Failed to activate using password file '%s'. (Key data not correct?)", key_file);
                        else
                                log_error_errno(r, "Failed to activate using supplied passwords.");
 
                        return r;
                }
 
                return log_error_errno(r, "Failed to load tcrypt superblock on device %s: %m", sym_crypt_get_device_name(cd));
        }
 
        r = measured_crypt_activate_by_volume_key(
                        cd,
                        name,
                        /* mechanism= */ NULL,
                        /* keyslot= */ -1,
                        /* volume_key= */ NULL,
                        /* volume_key_size= */ 0,
                        flags);
        if (r < 0)
                return log_error_errno(r, "Failed to activate tcrypt device %s: %m", sym_crypt_get_device_name(cd));
 
        return 0;
}
 
static char *make_bindname(const char *volume, TokenType token_type) {
        const char *token_type_name = token_type_to_string(token_type), *suffix;
        char *bindname;
        int r;
 
        switch (token_type) {
 
        case TOKEN_FIDO2:
                suffix = "-salt";
                break;
 
        default:
                suffix = NULL;
        }
 
        r = asprintf(&bindname,
                     "@%" PRIx64"/cryptsetup%s%s%s/%s",
                     random_u64(),
                     token_type_name ? "-" : "",
                     strempty(token_type_name),
                     strempty(suffix),
                     volume);
        if (r < 0)
                return NULL;
 
        return bindname;
}
 
static int make_security_device_monitor(
                sd_event **ret_event,
                sd_device_monitor **ret_monitor) {
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
        int r;
 
        assert(ret_event);
        assert(ret_monitor);
 
        /* Waits for a device with "security-device" tag to show up in udev */
        log_debug("Creating device monitor for tag 'security-device' with timeout %s",
                  FORMAT_TIMESPAN(arg_token_timeout_usec, 1*USEC_PER_SEC));
 
        r = sd_event_default(&event);
        if (r < 0)
                return log_error_errno(r, "Failed to allocate event loop: %m");
 
        r = sd_event_add_time_relative(event, NULL, CLOCK_MONOTONIC, arg_token_timeout_usec, USEC_PER_SEC, NULL, INT_TO_PTR(-ETIMEDOUT));
        if (r < 0)
                return log_error_errno(r, "Failed to install timeout event source: %m");
 
        r = sd_device_monitor_new(&monitor);
        if (r < 0)
                return log_error_errno(r, "Failed to allocate device monitor: %m");
 
        (void) sd_device_monitor_set_description(monitor, "security-device");
 
        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");
 
        *ret_event = TAKE_PTR(event);
        *ret_monitor = TAKE_PTR(monitor);
        return 0;
}
 
static int run_security_device_monitor(
                sd_event *event,
                sd_device_monitor *monitor) {
        bool processed = false;
        int r;
 
        assert(event);
        assert(monitor);
 
        /* Runs the event loop for the device monitor until either something happens, or the timeout is
         * hit. */
 
        for (;;) {
                int x;
 
                r = sd_event_get_exit_code(event, &x);
                if (r < 0) {
                        if (r != -ENODATA)
                                return log_error_errno(r, "Failed to query exit code from event loop: %m");
 
                        /* On ENODATA we aren't told to exit yet. */
                } else {
                        assert(x == -ETIMEDOUT);
                        return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN),
                                                "Timed out waiting for security device, aborting security device based authentication attempt.");
                }
 
                /* 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) /* no events queued anymore */
                        return 0;
 
                processed = true;
        }
}
 
static bool use_token_plugins(void) {
 
#if HAVE_TPM2
        /* Currently, there's no way for us to query the volume key when plugins are used. Hence don't use
         * plugins, if measurement has been requested. */
        if (arg_tpm2_measure_pcr != UINT_MAX)
                return false;
        if (arg_tpm2_measure_keyslot_nvpcr)
                return false;
        /* Volume key is also needed if the expected key id is set */
        if (arg_fixate_volume_key)
                return false;
#endif
 
        /* Disable tokens if we're in FIDO2 mode with manual parameters. */
        if (arg_fido2_cid)
                return false;
 
#if HAVE_LIBCRYPTSETUP_PLUGINS
        int r;
 
        /* Permit a way to disable libcryptsetup token module support, for debugging purposes. */
        r = getenv_bool("SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE");
        if (r < 0 && r != -ENXIO)
                log_debug_errno(r, "Failed to parse $SYSTEMD_CRYPTSETUP_USE_TOKEN_MODULE env var: %m");
        if (r == 0)
                return false;
 
        return sym_crypt_token_external_path();
#else
        return false;
#endif
}
 
#if HAVE_LIBCRYPTSETUP_PLUGINS
static int acquire_pins_from_env_variable(char ***ret_pins) {
        _cleanup_(erase_and_freep) char *envpin = NULL;
        _cleanup_strv_free_erase_ char **pins = NULL;
        int r;
 
        assert(ret_pins);
 
        r = getenv_steal_erase("PIN", &envpin);
        if (r < 0)
                return log_error_errno(r, "Failed to acquire PIN from environment: %m");
        if (r > 0) {
                pins = strv_new(envpin);
                if (!pins)
                        return log_oom();
        }
 
        *ret_pins = TAKE_PTR(pins);
 
        return 0;
}
#endif
 
static int crypt_activate_by_token_pin_ask_password(
                struct crypt_device *cd,
                const char *name,
                const char *type,
                usec_t until,
                void *userdata,
                uint32_t activation_flags,
                const char *message,
                const char *keyring,
                const char *credential) {
 
#if HAVE_LIBCRYPTSETUP_PLUGINS
        AskPasswordFlags flags = arg_ask_password_flags;
        _cleanup_strv_free_erase_ char **pins = NULL;
        int r;
 
        r = sym_crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, /* pin= */ NULL, /* pin_size= */ 0, userdata, activation_flags);
        if (r > 0) /* returns unlocked keyslot id on success */
                return 0;
        if (r == -EEXIST) /* volume is already active */
                return log_external_activation(r, name);
        if (r != -ENOANO) /* needs pin or pin is wrong */
                return r;
 
        r = acquire_pins_from_env_variable(&pins);
        if (r < 0)
                return r;
 
        STRV_FOREACH(p, pins) {
                r = sym_crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, *p, strlen(*p), userdata, activation_flags);
                if (r > 0) /* returns unlocked keyslot id on success */
                        return 0;
                if (r == -EEXIST) /* volume is already active */
                        return log_external_activation(r, name);
                if (r != -ENOANO) /* needs pin or pin is wrong */
                        return r;
        }
 
        if (FLAGS_SET(arg_ask_password_flags, ASK_PASSWORD_HEADLESS))
                return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "PIN querying disabled via 'headless' option. Use the '$PIN' environment variable.");
 
        for (;;) {
                pins = strv_free_erase(pins);
 
                AskPasswordRequest req = {
                        .tty_fd = -EBADF,
                        .message = message,
                        .icon = "drive-harddisk",
                        .keyring = keyring,
                        .credential = credential,
                        .until = until,
                        .hup_fd = -EBADF,
                };
 
                r = ask_password_auto(&req, flags, &pins);
                if (r < 0)
                        return r;
 
                STRV_FOREACH(p, pins) {
                        r = sym_crypt_activate_by_token_pin(cd, name, type, CRYPT_ANY_TOKEN, *p, strlen(*p), userdata, activation_flags);
                        if (r > 0) /* returns unlocked keyslot id on success */
                                return 0;
                        if (r == -EEXIST) /* volume is already active */
                                return log_external_activation(r, name);
                        if (r != -ENOANO) /* needs pin or pin is wrong */
                                return r;
                }
 
                flags &= ~ASK_PASSWORD_ACCEPT_CACHED;
        }
        return r;
#else
        return -EOPNOTSUPP;
#endif
}
 
static int attach_luks2_by_fido2_via_plugin(
                struct crypt_device *cd,
                const char *name,
                usec_t until,
                void *userdata,
                uint32_t activation_flags) {
 
        return crypt_activate_by_token_pin_ask_password(
                        cd,
                        name,
                        "systemd-fido2",
                        until,
                        userdata,
                        activation_flags,
                        "Please enter security token PIN:",
                        "fido2-pin",
                        "cryptsetup.fido2-pin");
}
 
static int attach_luks_or_plain_or_bitlk_by_fido2(
                struct crypt_device *cd,
                const char *name,
                const char *key_file,
                const struct iovec *key_data,
                usec_t until,
                uint32_t flags,
                bool pass_volume_key) {
 
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
        _cleanup_(erase_and_freep) void *decrypted_key = NULL;
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
        size_t decrypted_key_size;
        _cleanup_free_ char *friendly = NULL;
        int keyslot = arg_key_slot, r;
        bool use_libcryptsetup_plugin = use_token_plugins();
 
        assert(cd);
        assert(name);
        assert(arg_fido2_device || arg_fido2_device_auto);
 
        if (arg_fido2_cid && !key_file && !iovec_is_set(key_data))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                        "FIDO2 mode with manual parameters selected, but no keyfile specified, refusing.");
 
        friendly = friendly_disk_name(sym_crypt_get_device_name(cd), name);
        if (!friendly)
                return log_oom();
 
        for (;;) {
                if (use_libcryptsetup_plugin && !arg_fido2_cid) {
                        r = attach_luks2_by_fido2_via_plugin(cd, name, until, arg_fido2_device, flags);
                        if (IN_SET(r, -ENOTUNIQ, -ENXIO, -ENOENT))
                                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
                                                       "Automatic FIDO2 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
 
                } else {
                        if (arg_fido2_cid)
                                r = acquire_fido2_key(
                                                name,
                                                friendly,
                                                arg_fido2_device,
                                                arg_fido2_rp_id,
                                                arg_fido2_cid, arg_fido2_cid_size,
                                                key_file, arg_keyfile_size, arg_keyfile_offset,
                                                key_data,
                                                until,
                                                arg_fido2_manual_flags,
                                                "cryptsetup.fido2-pin",
                                                arg_ask_password_flags,
                                                &decrypted_key,
                                                &decrypted_key_size);
                        else
                                r = acquire_fido2_key_auto(
                                                cd,
                                                name,
                                                friendly,
                                                arg_fido2_device,
                                                until,
                                                "cryptsetup.fido2-pin",
                                                arg_ask_password_flags,
                                                &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 = make_security_device_monitor(&event, &monitor);
                        if (r < 0)
                                return r;
 
                        log_notice("Security token not present for unlocking volume %s, please plug it in.", friendly);
 
                        /* Let's immediately rescan in case the token appeared in the time we needed
                         * to create and configure the monitor */
                        continue;
                }
 
                r = run_security_device_monitor(event, monitor);
                if (r < 0)
                        return r;
 
                log_debug("Got one or more potentially relevant udev events, rescanning FIDO2...");
        }
 
        if (pass_volume_key)
                r = measured_crypt_activate_by_volume_key(
                                cd,
                                name,
                                "fido2",
                                /* keyslot= */ -1,
                                decrypted_key,
                                decrypted_key_size,
                                flags);
        else {
                _cleanup_(erase_and_freep) char *base64_encoded = NULL;
                ssize_t base64_encoded_size;
 
                /* Before using this key as passphrase we base64 encode it, for compat with homed */
 
                base64_encoded_size = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
                if (base64_encoded_size < 0)
                        return log_oom();
 
                r = measured_crypt_activate_by_passphrase(
                                cd,
                                name,
                                "fido2",
                                keyslot,
                                base64_encoded,
                                base64_encoded_size,
                                flags);
        }
        if (r == -EPERM) {
                log_error_errno(r, "Failed to activate with FIDO2 decrypted key. (Key incorrect?)");
                return -EAGAIN; /* log actual error, but return EAGAIN */
        }
        if (r < 0)
                return log_error_errno(r, "Failed to activate with FIDO2 acquired key: %m");
 
        return 0;
}
 
static int attach_luks2_by_pkcs11_via_plugin(
                struct crypt_device *cd,
                const char *name,
                const char *friendly_name,
                usec_t until,
                const char *askpw_credential,
                uint32_t flags) {
 
#if HAVE_LIBCRYPTSETUP_PLUGINS
        int r;
 
        if (!streq_ptr(sym_crypt_get_type(cd), CRYPT_LUKS2))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Automatic PKCS#11 metadata requires LUKS2 device.");
 
        systemd_pkcs11_plugin_params params = {
                .friendly_name = friendly_name,
                .until = until,
                .askpw_credential = askpw_credential,
                .askpw_flags = arg_ask_password_flags,
        };
 
        r = sym_crypt_activate_by_token_pin(cd, name, "systemd-pkcs11", CRYPT_ANY_TOKEN, NULL, 0, &params, flags);
        if (r > 0) /* returns unlocked keyslot id on success */
                r = 0;
        if (r == -EEXIST) /* volume is already active */
                r = log_external_activation(r, name);
 
        return r;
#else
        return -EOPNOTSUPP;
#endif
}
 
static int attach_luks_or_plain_or_bitlk_by_pkcs11(
                struct crypt_device *cd,
                const char *name,
                const char *key_file,
                const struct iovec *key_data,
                usec_t until,
                uint32_t flags,
                bool pass_volume_key) {
 
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
        _cleanup_free_ char *friendly = NULL, *discovered_uri = NULL;
        size_t decrypted_key_size = 0, discovered_key_size = 0;
        _cleanup_(erase_and_freep) void *decrypted_key = NULL;
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
        _cleanup_free_ void *discovered_key = NULL;
        struct iovec discovered_key_data = {};
        Pkcs11RsaPadding rsa_padding = PKCS11_RSA_PADDING_PKCS1V15;
        int keyslot = arg_key_slot, r;
        const char *uri = NULL;
        bool use_libcryptsetup_plugin = use_token_plugins();
 
        assert(cd);
        assert(name);
        assert(arg_pkcs11_uri || arg_pkcs11_uri_auto);
 
        if (arg_pkcs11_uri_auto) {
                if (!use_libcryptsetup_plugin) {
                        r = find_pkcs11_auto_data(cd, &discovered_uri, &discovered_key, &discovered_key_size, &rsa_padding, &keyslot);
                        if (IN_SET(r, -ENOTUNIQ, -ENXIO))
                                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
                                                       "Automatic PKCS#11 metadata discovery was not possible because missing or not unique, falling back to traditional unlocking.");
                        if (r < 0)
                                return r;
 
                        uri = discovered_uri;
                        discovered_key_data = IOVEC_MAKE(discovered_key, discovered_key_size);
                        key_data = &discovered_key_data;
                }
        } else {
                uri = arg_pkcs11_uri;
 
                if (!key_file && !iovec_is_set(key_data))
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "PKCS#11 mode selected but no key file specified, refusing.");
        }
 
        friendly = friendly_disk_name(sym_crypt_get_device_name(cd), name);
        if (!friendly)
                return log_oom();
 
        for (;;) {
                if (use_libcryptsetup_plugin && arg_pkcs11_uri_auto)
                        r = attach_luks2_by_pkcs11_via_plugin(
                                        cd,
                                        name,
                                        friendly,
                                        until,
                                        "cryptsetup.pkcs11-pin",
                                        flags);
                else {
                        r = decrypt_pkcs11_key(
                                        name,
                                        friendly,
                                        uri,
                                        rsa_padding,
                                        key_file, arg_keyfile_size, arg_keyfile_offset,
                                        key_data,
                                        until,
                                        arg_ask_password_flags,
                                        &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 = make_security_device_monitor(&event, &monitor);
                        if (r < 0)
                                return r;
 
                        log_notice("Security token%s%s not present for unlocking volume %s, please plug it in.",
                                   uri ? " " : "", strempty(uri), friendly);
 
                        /* Let's immediately rescan in case the token appeared in the time we needed
                         * to create and configure the monitor */
                        continue;
                }
 
                r = run_security_device_monitor(event, monitor);
                if (r < 0)
                        return r;
 
                log_debug("Got one or more potentially relevant udev events, rescanning PKCS#11...");
        }
        assert(decrypted_key);
 
        if (pass_volume_key)
                r = measured_crypt_activate_by_volume_key(
                                cd,
                                name,
                                "pkcs11",
                                /* keyslot= */ -1,
                                decrypted_key,
                                decrypted_key_size,
                                flags);
        else {
                _cleanup_(erase_and_freep) char *base64_encoded = NULL;
                ssize_t base64_encoded_size;
 
                /* 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 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. */
 
                base64_encoded_size = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
                if (base64_encoded_size < 0)
                        return log_oom();
 
                r = measured_crypt_activate_by_passphrase(
                                cd,
                                name,
                                "pkcs11",
                                keyslot,
                                base64_encoded,
                                base64_encoded_size,
                                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");
 
        return 0;
}
 
static int make_tpm2_device_monitor(
                sd_event **ret_event,
                sd_device_monitor **ret_monitor) {
 
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
        int r;
 
        assert(ret_event);
        assert(ret_monitor);
 
        r = sd_event_default(&event);
        if (r < 0)
                return log_error_errno(r, "Failed to allocate event loop: %m");
 
        r = sd_event_add_time_relative(event, NULL, CLOCK_MONOTONIC, arg_token_timeout_usec, USEC_PER_SEC, NULL, INT_TO_PTR(-ETIMEDOUT));
        if (r < 0)
                return log_error_errno(r, "Failed to install timeout event source: %m");
 
        r = sd_device_monitor_new(&monitor);
        if (r < 0)
                return log_error_errno(r, "Failed to allocate device monitor: %m");
 
        (void) sd_device_monitor_set_description(monitor, "tpmrm");
 
        r = sd_device_monitor_filter_add_match_subsystem_devtype(monitor, "tpmrm", NULL);
        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");
 
        *ret_event = TAKE_PTR(event);
        *ret_monitor = TAKE_PTR(monitor);
        return 0;
}
 
static int attach_luks2_by_tpm2_via_plugin(
                struct crypt_device *cd,
                const char *name,
                usec_t until,
                uint32_t flags) {
 
#if HAVE_LIBCRYPTSETUP_PLUGINS
        systemd_tpm2_plugin_params params = {
                .search_pcr_mask = arg_tpm2_pcr_mask,
                .device = arg_tpm2_device,
                .signature_path = arg_tpm2_signature,
                .pcrlock_path = arg_tpm2_pcrlock,
        };
 
        if (!use_token_plugins())
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                       "libcryptsetup has external plugins support disabled.");
 
        return crypt_activate_by_token_pin_ask_password(
                        cd,
                        name,
                        "systemd-tpm2",
                        until,
                        &params,
                        flags,
                        "Please enter TPM2 PIN:",
                        "tpm2-pin",
                        "cryptsetup.tpm2-pin");
#else
        return -EOPNOTSUPP;
#endif
}
 
static int attach_luks_or_plain_or_bitlk_by_tpm2(
                struct crypt_device *cd,
                const char *name,
                const char *key_file,
                const struct iovec *key_data,
                usec_t until,
                uint32_t flags,
                bool pass_volume_key) {
 
        _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
        _cleanup_(iovec_done_erase) struct iovec decrypted_key = {};
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
        _cleanup_free_ char *friendly = NULL;
        int keyslot = arg_key_slot, r;
 
        assert(cd);
        assert(name);
        assert(arg_tpm2_device || arg_tpm2_device_auto);
 
        friendly = friendly_disk_name(sym_crypt_get_device_name(cd), name);
        if (!friendly)
                return log_oom();
 
        for (;;) {
                if (key_file || iovec_is_set(key_data)) {
                        /* If key data is specified, use that */
 
                        r = acquire_tpm2_key(
                                        name,
                                        arg_tpm2_device,
                                        arg_tpm2_pcr_mask == UINT32_MAX ? TPM2_PCR_MASK_DEFAULT_LEGACY : arg_tpm2_pcr_mask,
                                        UINT16_MAX,
                                        /* pubkey= */ NULL,
                                        /* pubkey_policy_ref= */ NULL,
                                        /* pubkey_pcr_mask= */ 0,
                                        /* signature_path= */ NULL,
                                        /* pcrlock_path= */ NULL,
                                        /* primary_alg= */ 0,
                                        key_file, arg_keyfile_size, arg_keyfile_offset,
                                        key_data, /* n_blobs= */ iovec_is_set(key_data) ? 1 : 0,
                                        /* policy_hash= */ NULL, /* we don't know the policy hash */
                                        /* n_policy_hash= */ 0,
                                        /* salt= */ NULL,
                                        /* srk= */ NULL,
                                        /* pcrlock_nv= */ NULL,
                                        arg_tpm2_pin ? TPM2_FLAGS_USE_PIN : 0,
                                        until,
                                        "cryptsetup.tpm2-pin",
                                        arg_ask_password_flags,
                                        /* argon2id_params= */ NULL,
                                        &decrypted_key);
                        if (r >= 0)
                                break;
                        if (IN_SET(r, -EACCES, -ENOLCK))
                                return log_error_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 PIN unlock failed, falling back to traditional unlocking.");
                        if (ERRNO_IS_NOT_SUPPORTED(r)) /* TPM2 support not compiled in? */
                                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 support not available, falling back to traditional unlocking.");