]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
Add support for systemd-tpm2 libcryptsetup plugin.
authorOndrej Kozina <okozina@redhat.com>
Tue, 16 Mar 2021 19:13:28 +0000 (20:13 +0100)
committerZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
Mon, 26 Jul 2021 13:15:16 +0000 (15:15 +0200)
Add support for systemd-tpm2 based LUKS2 device activation
via libcryptsetup plugin. This make the feature (tpm2 sealed
LUKS2 keyslot passphrase) usable from both systemd utilities
and cryptsetup cli.

The feature is configured via -Dlibcryptsetup-plugins combo
with default value set to 'auto'. It get's enabled automatically
when cryptsetup 2.4.0 or later is installed in build system.

12 files changed:
meson.build
meson_options.txt
src/cryptsetup/cryptsetup-tokens/cryptsetup-token-systemd-tpm2.c [new file with mode: 0644]
src/cryptsetup/cryptsetup-tokens/cryptsetup-token-util.c [new file with mode: 0644]
src/cryptsetup/cryptsetup-tokens/cryptsetup-token-util.h [new file with mode: 0644]
src/cryptsetup/cryptsetup-tokens/cryptsetup-token.h [new file with mode: 0644]
src/cryptsetup/cryptsetup-tokens/cryptsetup-token.sym [new file with mode: 0644]
src/cryptsetup/cryptsetup-tokens/luks2-tpm2.c [new file with mode: 0644]
src/cryptsetup/cryptsetup-tokens/luks2-tpm2.h [new file with mode: 0644]
src/cryptsetup/cryptsetup-tokens/meson.build [new file with mode: 0644]
src/cryptsetup/cryptsetup.c
src/shared/tpm2-util.h

index 171d7bcfabc9abbec2dbd8ff2e98e71d6aa8df85..cb023f7f132722b65748d279b80ff8f349c3f575 100644 (file)
@@ -209,6 +209,11 @@ if pamconfdir == ''
         pamconfdir = join_paths(prefixdir, 'lib/pam.d')
 endif
 
+libcryptsetup_plugins_dir = get_option('libcryptsetup-plugins-dir')
+if libcryptsetup_plugins_dir == ''
+        libcryptsetup_plugins_dir = join_paths(rootlibdir, 'cryptsetup')
+endif
+
 memory_accounting_default = get_option('memory-accounting-default')
 status_unit_format_default = get_option('status-unit-format-default')
 
@@ -1106,10 +1111,16 @@ endif
 conf.set10('HAVE_MICROHTTPD', have)
 
 want_libcryptsetup = get_option('libcryptsetup')
+want_libcryptsetup_plugins = get_option('libcryptsetup-plugins')
+
+if want_libcryptsetup_plugins == 'true' and want_libcryptsetup == 'false'
+        error('libcryptsetup-plugins can not be requested without libcryptsetup')
+endif
+
 if want_libcryptsetup != 'false' and not skip_deps
         libcryptsetup = dependency('libcryptsetup',
-                                   version : '>= 2.0.1',
-                                   required : want_libcryptsetup == 'true')
+                                   version : want_libcryptsetup_plugins == 'true' ? '>= 2.4.0' : '>= 2.0.1',
+                                   required : want_libcryptsetup == 'true' or want_libcryptsetup_plugins == 'true')
         have = libcryptsetup.found()
 
         conf.set10('HAVE_CRYPT_SET_METADATA_SIZE',
@@ -1124,6 +1135,14 @@ else
 endif
 conf.set10('HAVE_LIBCRYPTSETUP', have)
 
+if want_libcryptsetup_plugins != 'false' and not skip_deps
+        have = (cc.has_function('crypt_activate_by_token_pin', dependencies : libcryptsetup) and
+                cc.has_function('crypt_token_external_path', dependencies : libcryptsetup))
+else
+        have = false
+endif
+conf.set10('HAVE_LIBCRYPTSETUP_PLUGINS', have)
+
 want_libcurl = get_option('libcurl')
 if want_libcurl != 'false' and not skip_deps
         libcurl = dependency('libcurl',
@@ -1676,6 +1695,7 @@ subdir('src/libsystemd')
 subdir('src/shared')
 subdir('src/udev')
 subdir('src/libudev')
+subdir('src/cryptsetup/cryptsetup-tokens')
 
 libsystemd = shared_library(
         'systemd',
@@ -1752,6 +1772,22 @@ install_libudev_static = static_library(
         c_args : static_libudev_pic ? [] : ['-fno-PIC'],
         pic : static_libudev_pic)
 
+if conf.get('HAVE_LIBCRYPTSETUP_PLUGINS') == 1
+        if conf.get('HAVE_TPM2') == 1
+                cryptsetup_token_systemd_tpm2 = shared_library(
+                        'cryptsetup-token-systemd-tpm2',
+                        link_args : ['-shared',
+                                     '-Wl,--version-script=' + cryptsetup_token_sym_path],
+                        dependencies : libshared_deps + [libcryptsetup],
+                        link_with : [libshared],
+                        link_whole : [cryptsetup_token_systemd_tpm2_static],
+                        link_depends : cryptsetup_token_sym,
+                        install_rpath : rootlibexecdir,
+                        install : true,
+                        install_dir : libcryptsetup_plugins_dir)
+        endif
+endif
+
 ############################################################
 
 # systemd-analyze requires 'libcore'
@@ -3747,6 +3783,7 @@ status = [
         'SysV rc?.d directories:            @0@'.format(sysvrcnd_path),
         'PAM modules directory:             @0@'.format(pamlibdir),
         'PAM configuration directory:       @0@'.format(pamconfdir),
+        'libcryptsetup plugins directory:   @0@'.format(libcryptsetup_plugins_dir),
         'RPM macros directory:              @0@'.format(rpmmacrosdir),
         'modprobe.d directory:              @0@'.format(modprobedir),
         'D-Bus policy directory:            @0@'.format(dbuspolicydir),
@@ -3831,6 +3868,7 @@ foreach tuple : [
         ['gnutls'],
         ['libbpf'],
         ['libcryptsetup'],
+        ['libcryptsetup-plugins'],
         ['libcurl'],
         ['libfdisk'],
         ['libfido2'],
index 50f2b7b5e996dcb4fa97311468828f18df6869a7..0b01fb2cbf2665edcf2d88acfb731dca2f721ffb 100644 (file)
@@ -188,6 +188,8 @@ option('pamlibdir', type : 'string',
        description : 'directory for PAM modules')
 option('pamconfdir', type : 'string',
        description : 'directory for PAM configuration ["no" disables]')
+option('libcryptsetup-plugins-dir', type : 'string',
+       description : 'directory for libcryptsetup plugins')
 option('docdir', type : 'string',
        description : 'documentation directory')
 option('install-sysconfdir', type : 'combo', choices : ['true', 'no-samples', 'false'], value : 'true',
@@ -355,6 +357,8 @@ option('microhttpd', type : 'combo', choices : ['auto', 'true', 'false'],
        description : 'libµhttpd support')
 option('libcryptsetup', type : 'combo', choices : ['auto', 'true', 'false'],
        description : 'libcryptsetup support')
+option('libcryptsetup-plugins', type : 'combo', choices : ['auto', 'true', 'false'],
+       description : 'libcryptsetup LUKS2 external token handlers support (plugins)')
 option('libcurl', type : 'combo', choices : ['auto', 'true', 'false'],
        description : 'libcurl support')
 option('idn', type : 'boolean',
diff --git a/src/cryptsetup/cryptsetup-tokens/cryptsetup-token-systemd-tpm2.c b/src/cryptsetup/cryptsetup-tokens/cryptsetup-token-systemd-tpm2.c
new file mode 100644 (file)
index 0000000..152b06b
--- /dev/null
@@ -0,0 +1,232 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+
+#include <errno.h>
+#include <libcryptsetup.h>
+
+#include "cryptsetup-token.h"
+#include "cryptsetup-token-util.h"
+#include "hexdecoct.h"
+#include "luks2-tpm2.h"
+#include "memory-util.h"
+#include "tpm2-util.h"
+#include "version.h"
+
+#define TOKEN_NAME "systemd-tpm2"
+#define TOKEN_VERSION_MAJOR "1"
+#define TOKEN_VERSION_MINOR "0"
+
+/* for libcryptsetup debug purpose */
+_public_ const char *cryptsetup_token_version(void) {
+
+        return TOKEN_VERSION_MAJOR "." TOKEN_VERSION_MINOR " systemd-v" STRINGIFY(PROJECT_VERSION) " (" GIT_VERSION ")";
+}
+
+static int log_debug_open_error(struct crypt_device *cd, int r) {
+        if (r == -EAGAIN) {
+                crypt_log_debug(cd, "TPM2 device not found.");
+                return r;
+        } else if (r == -ENXIO) {
+                crypt_log_debug(cd, "No matching TPM2 token data found.");
+                return r;
+        }
+
+        return crypt_log_debug_errno(cd, r, TOKEN_NAME " open failed: %m.");
+}
+
+/*
+ * This function is called from within following libcryptsetup calls
+ * provided conditions further below are met:
+ *
+ * crypt_activate_by_token(), crypt_activate_by_token_type(type == 'systemd-tpm2'):
+ *
+ * - token is assigned to at least one luks2 keyslot eligible to activate LUKS2 device
+ *   (alternatively: name is set to null, flags contains CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY
+ *    and token is assigned to at least single keyslot).
+ *
+ * - if plugin defines validate funtion (see cryptsetup_token_validate below) it must have
+ *   passed the check (aka return 0)
+ */
+_public_ int cryptsetup_token_open(
+                struct crypt_device *cd, /* is always LUKS2 context */
+                int token /* is always >= 0 */,
+                char **password, /* freed by cryptsetup_token_buffer_free */
+                size_t *password_len,
+                void *usrptr /* plugin defined parameter passed to crypt_activate_by_token*() API */) {
+
+        int r;
+        const char *json;
+        size_t blob_size, policy_hash_size, decrypted_key_size;
+        uint32_t pcr_mask;
+        systemd_tpm2_plugin_params params = {
+                .search_pcr_mask = UINT32_MAX
+        };
+        _cleanup_free_ void *blob = NULL, *policy_hash = NULL;
+        _cleanup_free_ char *base64_blob = NULL, *hex_policy_hash = NULL;
+        _cleanup_(erase_and_freep) void *decrypted_key = NULL;
+        _cleanup_(erase_and_freep) char *base64_encoded = NULL;
+
+        assert(password);
+        assert(password_len);
+        assert(token >= 0);
+
+        /* This must not fail at this moment (internal error) */
+        r = crypt_token_json_get(cd, token, &json);
+        assert(token == r);
+        assert(json);
+
+        if (usrptr)
+                params = *(systemd_tpm2_plugin_params *)usrptr;
+
+        r = parse_luks2_tpm2_data(json, params.search_pcr_mask, &pcr_mask, &base64_blob, &hex_policy_hash);
+        if (r < 0)
+                return log_debug_open_error(cd, r);
+
+        /* should not happen since cryptsetup_token_validate have passed */
+        r = unbase64mem(base64_blob, SIZE_MAX, &blob, &blob_size);
+        if (r < 0)
+                return log_debug_open_error(cd, r);
+
+        /* should not happen since cryptsetup_token_validate have passed */
+        r = unhexmem(hex_policy_hash, SIZE_MAX, &policy_hash, &policy_hash_size);
+        if (r < 0)
+                return log_debug_open_error(cd, r);
+
+        r = acquire_luks2_key(
+                        pcr_mask,
+                        params.device,
+                        blob,
+                        blob_size,
+                        policy_hash,
+                        policy_hash_size,
+                        &decrypted_key,
+                        &decrypted_key_size);
+        if (r < 0)
+                return log_debug_open_error(cd, r);
+
+        /* Before using this key as passphrase we base64 encode it, for compat with homed */
+        r = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
+        if (r < 0)
+                return log_debug_open_error(cd, r);
+
+        /* free'd automaticaly by libcryptsetup */
+        *password_len = strlen(base64_encoded);
+        *password = TAKE_PTR(base64_encoded);
+
+        return 0;
+}
+
+/*
+ * libcryptsetup callback for memory deallocation of 'password' parameter passed in
+ * any crypt_token_open_* plugin function
+ */
+_public_ void cryptsetup_token_buffer_free(void *buffer, size_t buffer_len) {
+        erase_and_free(buffer);
+}
+
+/*
+ * prints systemd-tpm2 token content in crypt_dump().
+ * 'type' and 'keyslots' fields are printed by libcryptsetup
+ */
+_public_ void cryptsetup_token_dump(
+                struct crypt_device *cd /* is always LUKS2 context */,
+                const char *json /* validated 'systemd-tpm2' token if cryptsetup_token_validate is defined */) {
+
+        int r;
+        uint32_t i, pcr_mask;
+        size_t decoded_blob_size;
+        _cleanup_free_ char *base64_blob = NULL, *hex_policy_hash = NULL,
+                            *pcrs_str = NULL, *blob_str = NULL, *policy_hash_str = NULL;
+        _cleanup_free_ void *decoded_blob = NULL;
+
+        assert(json);
+
+        r = parse_luks2_tpm2_data(json, UINT32_MAX, &pcr_mask, &base64_blob, &hex_policy_hash);
+        if (r < 0)
+                return (void) crypt_log_debug_errno(cd, r, "Failed to parse " TOKEN_NAME " metadata: %m.");
+
+        for (i = 0; i < TPM2_PCRS_MAX; i++) {
+                if ((pcr_mask & (UINT32_C(1) << i)) &&
+                    ((r = strextendf_with_separator(&pcrs_str, ", ", "%" PRIu32, i)) < 0))
+                        return (void) crypt_log_debug_errno(cd, r, "Can not dump " TOKEN_NAME " content: %m");
+        }
+
+        r = unbase64mem(base64_blob, SIZE_MAX, &decoded_blob, &decoded_blob_size);
+        if (r < 0)
+                return (void) crypt_log_debug_errno(cd, r, "Can not dump " TOKEN_NAME " content: %m");
+
+        r = crypt_dump_buffer_to_hex_string(decoded_blob, decoded_blob_size, &blob_str);
+        if (r < 0)
+                return (void) crypt_log_debug_errno(cd, r, "Can not dump " TOKEN_NAME " content: %m");
+
+        r = crypt_dump_hex_string(hex_policy_hash, &policy_hash_str);
+        if (r < 0)
+                return (void) crypt_log_debug_errno(cd, r, "Can not dump " TOKEN_NAME " content: %m");
+
+        crypt_log(cd, "\ttpm2-pcrs:  %s\n", pcrs_str ?: "");
+        crypt_log(cd, "\ttmp2-blob:  %s\n", blob_str);
+        crypt_log(cd, "\ttmp2-policy-hash:" CRYPT_DUMP_LINE_SEP "%s\n", policy_hash_str);
+}
+
+/*
+ * Note:
+ *   If plugin is available in library path, it's called in before following libcryptsetup calls:
+ *
+ *   crypt_token_json_set, crypt_dump, any crypt_activate_by_token_* flavour
+ */
+_public_ int cryptsetup_token_validate(
+                struct crypt_device *cd, /* is always LUKS2 context */
+                const char *json /* contains valid 'type' and 'keyslots' fields. 'type' is 'systemd-tpm2' */) {
+
+        int r;
+        JsonVariant *w, *e;
+        _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
+
+        assert(json);
+
+        r = json_parse(json, 0, &v, NULL, NULL);
+        if (r < 0)
+                return crypt_log_debug_errno(cd, r, "Could not parse " TOKEN_NAME " json object: %m");
+
+        w = json_variant_by_key(v, "tpm2-pcrs");
+        if (!w || !json_variant_is_array(w)) {
+                crypt_log_debug(cd, "TPM2 token data lacks 'tpm2-pcrs' field.");
+                return 1;
+        }
+
+        JSON_VARIANT_ARRAY_FOREACH(e, w) {
+                uintmax_t u;
+
+                if (!json_variant_is_number(e)) {
+                        crypt_log_debug(cd, "TPM2 PCR is not a number.");
+                        return 1;
+                }
+
+                u = json_variant_unsigned(e);
+                if (u >= TPM2_PCRS_MAX) {
+                        crypt_log_debug(cd, "TPM2 PCR number out of range.");
+                        return 1;
+                }
+        }
+
+        w = json_variant_by_key(v, "tpm2-blob");
+        if (!w || !json_variant_is_string(w)) {
+                crypt_log_debug(cd, "TPM2 token data lacks 'tpm2-blob' field.");
+                return 1;
+        }
+
+        r = unbase64mem(json_variant_string(w), SIZE_MAX, NULL, NULL);
+        if (r < 0)
+                return crypt_log_debug_errno(cd, r, "Invalid base64 data in 'tpm2-blob' field: %m");
+
+        w = json_variant_by_key(v, "tpm2-policy-hash");
+        if (!w || !json_variant_is_string(w)) {
+                crypt_log_debug(cd, "TPM2 token data lacks 'tpm2-policy-hash' field.");
+                return 1;
+        }
+
+        r = unhexmem(json_variant_string(w), SIZE_MAX, NULL, NULL);
+        if (r < 0)
+                return crypt_log_debug_errno(cd, r, "Invalid base64 data in 'tpm2-policy-hash' field: %m");
+
+        return 0;
+}
diff --git a/src/cryptsetup/cryptsetup-tokens/cryptsetup-token-util.c b/src/cryptsetup/cryptsetup-tokens/cryptsetup-token-util.c
new file mode 100644 (file)
index 0000000..f4086ae
--- /dev/null
@@ -0,0 +1,58 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+
+#include "cryptsetup-token-util.h"
+#include "string-util.h"
+
+int crypt_dump_buffer_to_hex_string(
+                const char *buf,
+                size_t buf_size,
+                char **ret_dump_str) {
+
+        int r;
+        _cleanup_free_ char *dump_str = NULL;
+
+        assert(buf || !buf_size);
+        assert(ret_dump_str);
+
+        for (size_t i = 0; i < buf_size; i++) {
+                /* crypt_dump() breaks line after every
+                 * 16th couple of chars in dumped hexstring */
+                r = strextendf_with_separator(
+                        &dump_str,
+                        (i && !(i % 16)) ? CRYPT_DUMP_LINE_SEP : " ",
+                        "%02hhx", buf[i]);
+                if (r < 0)
+                        return r;
+        }
+
+        *ret_dump_str = TAKE_PTR(dump_str);
+
+        return 0;
+}
+
+int crypt_dump_hex_string(const char *hex_str, char **ret_dump_str) {
+
+        int r;
+        size_t len;
+        _cleanup_free_ char *dump_str = NULL;
+
+        assert(hex_str);
+        assert(ret_dump_str);
+
+        len = strlen(hex_str) >> 1;
+
+        for (size_t i = 0; i < len; i++) {
+                /* crypt_dump() breaks line after every
+                 * 16th couple of chars in dumped hexstring */
+                r = strextendf_with_separator(
+                        &dump_str,
+                        (i && !(i % 16)) ? CRYPT_DUMP_LINE_SEP : " ",
+                        "%.2s", hex_str + (i<<1));
+                if (r < 0)
+                        return r;
+        }
+
+        *ret_dump_str = TAKE_PTR(dump_str);
+
+        return 0;
+}
diff --git a/src/cryptsetup/cryptsetup-tokens/cryptsetup-token-util.h b/src/cryptsetup/cryptsetup-tokens/cryptsetup-token-util.h
new file mode 100644 (file)
index 0000000..b8ea4c2
--- /dev/null
@@ -0,0 +1,27 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+
+#pragma once
+
+#include <stddef.h>
+
+/* crypt_dump() internal indentation magic */
+#define CRYPT_DUMP_LINE_SEP "\n\t            "
+
+#define crypt_log_debug(cd, ...) crypt_logf(cd, CRYPT_LOG_DEBUG,  __VA_ARGS__)
+#define crypt_log_error(cd, ...) crypt_logf(cd, CRYPT_LOG_ERROR,  __VA_ARGS__)
+#define crypt_log(cd, ...)       crypt_logf(cd, CRYPT_LOG_NORMAL, __VA_ARGS__)
+
+#define crypt_log_debug_errno(cd, e, ...) ({ \
+        int _e = abs(e), _s = errno; \
+        errno = _e; \
+        crypt_logf(cd, CRYPT_LOG_DEBUG, __VA_ARGS__); \
+        errno = _s; \
+        -_e; \
+})
+
+int crypt_dump_buffer_to_hex_string(
+                const char *buf,
+                size_t buf_size,
+                char **ret_dump_str);
+
+int crypt_dump_hex_string(const char *hex_str, char **ret_dump_str);
diff --git a/src/cryptsetup/cryptsetup-tokens/cryptsetup-token.h b/src/cryptsetup/cryptsetup-tokens/cryptsetup-token.h
new file mode 100644 (file)
index 0000000..010e010
--- /dev/null
@@ -0,0 +1,15 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+#pragma once
+
+/* for more information see libcryptsetup.h crypt-tokens section */
+
+const char *cryptsetup_token_version(void);
+
+int cryptsetup_token_open(struct crypt_device *cd, int token,
+        char **password, size_t *password_len, void *usrptr);
+
+void cryptsetup_token_dump(struct crypt_device *cd, const char *json);
+
+int cryptsetup_token_validate(struct crypt_device *cd, const char *json);
+
+void cryptsetup_token_buffer_free(void *buffer, size_t buffer_len);
diff --git a/src/cryptsetup/cryptsetup-tokens/cryptsetup-token.sym b/src/cryptsetup/cryptsetup-tokens/cryptsetup-token.sym
new file mode 100644 (file)
index 0000000..bddf1b5
--- /dev/null
@@ -0,0 +1,18 @@
+/***
+  SPDX-License-Identifier: LGPL-2.1-or-later
+
+  systemd is free software; you can redistribute it and/or modify it
+  under the terms of the GNU Lesser General Public License as published by
+  the Free Software Foundation; either version 2.1 of the License, or
+  (at your option) any later version.
+***/
+
+CRYPTSETUP_TOKEN_1.0 {
+global:
+        cryptsetup_token_open;
+        cryptsetup_token_buffer_free;
+        cryptsetup_token_validate;
+        cryptsetup_token_dump;
+        cryptsetup_token_version;
+local: *;
+};
diff --git a/src/cryptsetup/cryptsetup-tokens/luks2-tpm2.c b/src/cryptsetup/cryptsetup-tokens/luks2-tpm2.c
new file mode 100644 (file)
index 0000000..0054065
--- /dev/null
@@ -0,0 +1,105 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+
+#include "alloc-util.h"
+#include "hexdecoct.h"
+#include "json.h"
+#include "luks2-tpm2.h"
+#include "parse-util.h"
+#include "random-util.h"
+#include "tpm2-util.h"
+
+int acquire_luks2_key(
+                uint32_t pcr_mask,
+                const char *device,
+                const void *key_data,
+                size_t key_data_size,
+                const void *policy_hash,
+                size_t policy_hash_size,
+                void **ret_decrypted_key,
+                size_t *ret_decrypted_key_size) {
+
+        _cleanup_free_ char *auto_device = NULL;
+        int r;
+
+        assert(ret_decrypted_key);
+        assert(ret_decrypted_key_size);
+
+        if (!device) {
+                r = tpm2_find_device_auto(LOG_DEBUG, &auto_device);
+                if (r == -ENODEV)
+                        return -EAGAIN; /* Tell the caller to wait for a TPM2 device to show up */
+                if (r < 0)
+                        return r;
+
+                device = auto_device;
+        }
+
+        return tpm2_unseal(device, pcr_mask, key_data, key_data_size, policy_hash, policy_hash_size, ret_decrypted_key, ret_decrypted_key_size);
+}
+
+/* this function expects valid "systemd-tpm2" in json */
+int parse_luks2_tpm2_data(
+                const char *json,
+                uint32_t search_pcr_mask,
+                uint32_t *ret_pcr_mask,
+                char **ret_base64_blob,
+                char **ret_hex_policy_hash) {
+
+        int r;
+        JsonVariant *w, *e;
+        uint32_t pcr_mask = 0;
+        _cleanup_free_ char *base64_blob = NULL, *hex_policy_hash = NULL;
+        _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
+
+        assert(json);
+        assert(ret_base64_blob);
+        assert(ret_hex_policy_hash);
+        assert(ret_pcr_mask);
+
+        r = json_parse(json, 0, &v, NULL, NULL);
+        if (r < 0)
+                return -EINVAL;
+
+        w = json_variant_by_key(v, "tpm2-pcrs");
+        if (!w || !json_variant_is_array(w))
+                return -EINVAL;
+
+        JSON_VARIANT_ARRAY_FOREACH(e, w) {
+                uintmax_t u;
+
+                if (!json_variant_is_number(e))
+                        return -EINVAL;
+
+                u = json_variant_unsigned(e);
+                if (u >= TPM2_PCRS_MAX)
+                        return -EINVAL;
+
+                pcr_mask |= UINT32_C(1) << u;
+        }
+
+        if (search_pcr_mask != UINT32_MAX &&
+            search_pcr_mask != pcr_mask)
+                return -ENXIO;
+
+        w = json_variant_by_key(v, "tpm2-blob");
+        if (!w || !json_variant_is_string(w))
+                return -EINVAL;
+
+        base64_blob = strdup(json_variant_string(w));
+        if (!base64_blob)
+                return -ENOMEM;
+
+        w = json_variant_by_key(v, "tpm2-policy-hash");
+        if (!w || !json_variant_is_string(w))
+                return -EINVAL;
+
+        hex_policy_hash = strdup(json_variant_string(w));
+        if (!hex_policy_hash)
+                return -ENOMEM;
+
+        *ret_pcr_mask = pcr_mask;
+        *ret_base64_blob = TAKE_PTR(base64_blob);
+        *ret_hex_policy_hash = TAKE_PTR(hex_policy_hash);
+
+        return 0;
+}
diff --git a/src/cryptsetup/cryptsetup-tokens/luks2-tpm2.h b/src/cryptsetup/cryptsetup-tokens/luks2-tpm2.h
new file mode 100644 (file)
index 0000000..d36623b
--- /dev/null
@@ -0,0 +1,22 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+
+#pragma once
+
+struct crypt_device;
+
+int acquire_luks2_key(
+                uint32_t pcr_mask,
+                const char *device,
+                const void *key_data,
+                size_t key_data_size,
+                const void *policy_hash,
+                size_t policy_hash_size,
+                void **ret_decrypted_key,
+                size_t *ret_decrypted_key_size);
+
+int parse_luks2_tpm2_data(
+                const char *json,
+                uint32_t search_pcr_mask,
+                uint32_t *ret_pcr_mask,
+                char **ret_base64_blob,
+                char **ret_hex_policy_hash);
diff --git a/src/cryptsetup/cryptsetup-tokens/meson.build b/src/cryptsetup/cryptsetup-tokens/meson.build
new file mode 100644 (file)
index 0000000..61c879c
--- /dev/null
@@ -0,0 +1,28 @@
+# SPDX-License-Identifier: LGPL-2.1-or-later
+
+if conf.get('HAVE_LIBCRYPTSETUP_PLUGINS') == 1
+
+cryptsetup_token_c_args = ['-fvisibility=hidden']
+
+cryptsetup_token_sym = files('cryptsetup-token.sym')
+cryptsetup_token_sym_path = join_paths(meson.current_source_dir(), 'cryptsetup-token.sym')
+
+if conf.get('HAVE_TPM2') == 1
+        cryptsetup_token_systemd_tpm2_sources = files('''
+                cryptsetup-token-systemd-tpm2.c
+                cryptsetup-token.h
+                cryptsetup-token-util.h
+                cryptsetup-token-util.c
+                luks2-tpm2.c
+                luks2-tpm2.h
+        '''.split())
+
+        cryptsetup_token_systemd_tpm2_static = static_library(
+                'cryptsetup-token-systemd-tpm2_static',
+                cryptsetup_token_systemd_tpm2_sources,
+                include_directories : includes,
+                dependencies : libshared_deps + [libcryptsetup],
+                c_args : cryptsetup_token_c_args)
+endif
+
+endif
index 8243ea108f5c64073593167d1e62ff55dea0ab0f..48621ef5838e45e91907c315f0d3d64a84e9a9cd 100644 (file)
@@ -1041,6 +1041,33 @@ static int make_tpm2_device_monitor(sd_event *event, sd_device_monitor **ret) {
         return 0;
 }
 
+static int attach_luks2_by_tpm2(
+                struct crypt_device *cd,
+                const char *name,
+                uint32_t flags) {
+
+#if HAVE_LIBCRYPTSETUP_PLUGINS
+        int r;
+
+        systemd_tpm2_plugin_params params = {
+                .search_pcr_mask = arg_tpm2_pcr_mask,
+                .device = arg_tpm2_device
+        };
+
+        if (crypt_token_external_path() == NULL)
+                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
+                                       "Libcryptsetup has external plugins support disabled.");
+
+        r = crypt_activate_by_token_pin(cd, name, "systemd-tpm2", CRYPT_ANY_TOKEN, NULL, 0, &params, flags);
+        if (r > 0) /* returns unlocked keyslot id on success */
+                r = 0;
+
+        return r;
+#else
+        return -EOPNOTSUPP;
+#endif
+}
+
 static int attach_luks_or_plain_or_bitlk_by_tpm2(
                 struct crypt_device *cd,
                 const char *name,
@@ -1087,6 +1114,20 @@ static int attach_luks_or_plain_or_bitlk_by_tpm2(
                         if (r != -EAGAIN) /* EAGAIN means: no tpm2 chip found */
                                 return r;
                 } else {
+                        r = attach_luks2_by_tpm2(cd, name, flags);
+                        /* EAGAIN     means: no tpm2 chip found
+                         * EOPNOTSUPP means: no libcryptsetup plugins support */
+                        if (r == -ENXIO)
+                                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
+                                                       "No TPM2 metadata matching the current system state found in LUKS2 header, falling back to traditional unlocking.");
+                        if (r == -ENOENT)
+                                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
+                                                       "No TPM2 metadata enrolled in LUKS2 header or TPM2 support not available, falling back to traditional unlocking.");
+                        if (!IN_SET(r, -EOPNOTSUPP, -EAGAIN))
+                                return r;
+                }
+
+                if (r == -EOPNOTSUPP) {
                         _cleanup_free_ void *blob = NULL, *policy_hash = NULL;
                         size_t blob_size, policy_hash_size;
                         bool found_some = false;
index 82cd186e1162c7056ad955cd3811ecdbb9d19cdf..9f60fef083df96819f2b909aeae5d4c030326b8b 100644 (file)
@@ -49,3 +49,8 @@ int tpm2_make_luks2_json(int keyslot, uint32_t pcr_mask, const void *blob, size_
 
 /* Default to PCR 7 only */
 #define TPM2_PCR_MASK_DEFAULT (UINT32_C(1) << 7)
+
+typedef struct {
+        uint32_t search_pcr_mask;
+        const char *device;
+} systemd_tpm2_plugin_params;