]> git.ipfire.org Git - thirdparty/systemd.git/blobdiff - src/shared/pkcs11-util.c
Merge pull request #30284 from YHNdnzj/fstab-wantedby-defaultdeps
[thirdparty/systemd.git] / src / shared / pkcs11-util.c
index 9fc577ca3cf1c7c4dd1f2fc2f262e6d71cc91181..c3d97b80f9e4c30e870d53a0056a56f83eb14732 100644 (file)
@@ -3,6 +3,8 @@
 #include <fcntl.h>
 
 #include "ask-password-api.h"
+#include "dlfcn-util.h"
+#include "env-util.h"
 #include "escape.h"
 #include "fd-util.h"
 #include "format-table.h"
@@ -39,17 +41,59 @@ bool pkcs11_uri_valid(const char *uri) {
 
 #if HAVE_P11KIT
 
+static void *p11kit_dl = NULL;
+
+char *(*sym_p11_kit_module_get_name)(CK_FUNCTION_LIST *module);
+void (*sym_p11_kit_modules_finalize_and_release)(CK_FUNCTION_LIST **modules);
+CK_FUNCTION_LIST **(*sym_p11_kit_modules_load_and_initialize)(int flags);
+const char *(*sym_p11_kit_strerror)(CK_RV rv);
+int (*sym_p11_kit_uri_format)(P11KitUri *uri, P11KitUriType uri_type, char **string);
+void (*sym_p11_kit_uri_free)(P11KitUri *uri);
+CK_ATTRIBUTE_PTR (*sym_p11_kit_uri_get_attributes)(P11KitUri *uri, CK_ULONG *n_attrs);
+CK_INFO_PTR (*sym_p11_kit_uri_get_module_info)(P11KitUri *uri);
+CK_SLOT_INFO_PTR (*sym_p11_kit_uri_get_slot_info)(P11KitUri *uri);
+CK_TOKEN_INFO_PTR (*sym_p11_kit_uri_get_token_info)(P11KitUri *uri);
+int (*sym_p11_kit_uri_match_token_info)(const P11KitUri *uri, const CK_TOKEN_INFO *token_info);
+const char *(*sym_p11_kit_uri_message)(int code);
+P11KitUri *(*sym_p11_kit_uri_new)(void);
+int (*sym_p11_kit_uri_parse)(const char *string, P11KitUriType uri_type, P11KitUri *uri);
+
+int dlopen_p11kit(void) {
+        return dlopen_many_sym_or_warn(
+                        &p11kit_dl,
+                        "libp11-kit.so.0", LOG_DEBUG,
+                        DLSYM_ARG(p11_kit_module_get_name),
+                        DLSYM_ARG(p11_kit_modules_finalize_and_release),
+                        DLSYM_ARG(p11_kit_modules_load_and_initialize),
+                        DLSYM_ARG(p11_kit_strerror),
+                        DLSYM_ARG(p11_kit_uri_format),
+                        DLSYM_ARG(p11_kit_uri_free),
+                        DLSYM_ARG(p11_kit_uri_get_attributes),
+                        DLSYM_ARG(p11_kit_uri_get_module_info),
+                        DLSYM_ARG(p11_kit_uri_get_slot_info),
+                        DLSYM_ARG(p11_kit_uri_get_token_info),
+                        DLSYM_ARG(p11_kit_uri_match_token_info),
+                        DLSYM_ARG(p11_kit_uri_message),
+                        DLSYM_ARG(p11_kit_uri_new),
+                        DLSYM_ARG(p11_kit_uri_parse));
+}
+
 int uri_from_string(const char *p, P11KitUri **ret) {
-        _cleanup_(p11_kit_uri_freep) P11KitUri *uri = NULL;
+        _cleanup_(sym_p11_kit_uri_freep) P11KitUri *uri = NULL;
+        int r;
 
         assert(p);
         assert(ret);
 
-        uri = p11_kit_uri_new();
+        r = dlopen_p11kit();
+        if (r < 0)
+                return r;
+
+        uri = sym_p11_kit_uri_new();
         if (!uri)
                 return -ENOMEM;
 
-        if (p11_kit_uri_parse(p, P11_KIT_URI_FOR_ANY, uri) != P11_KIT_URI_OK)
+        if (sym_p11_kit_uri_parse(p, P11_KIT_URI_FOR_ANY, uri) != P11_KIT_URI_OK)
                 return -EINVAL;
 
         *ret = TAKE_PTR(uri);
@@ -61,11 +105,14 @@ P11KitUri *uri_from_module_info(const CK_INFO *info) {
 
         assert(info);
 
-        uri = p11_kit_uri_new();
+        if (dlopen_p11kit() < 0)
+                return NULL;
+
+        uri = sym_p11_kit_uri_new();
         if (!uri)
                 return NULL;
 
-        *p11_kit_uri_get_module_info(uri) = *info;
+        *sym_p11_kit_uri_get_module_info(uri) = *info;
         return uri;
 }
 
@@ -74,11 +121,14 @@ P11KitUri *uri_from_slot_info(const CK_SLOT_INFO *slot_info) {
 
         assert(slot_info);
 
-        uri = p11_kit_uri_new();
+        if (dlopen_p11kit() < 0)
+                return NULL;
+
+        uri = sym_p11_kit_uri_new();
         if (!uri)
                 return NULL;
 
-        *p11_kit_uri_get_slot_info(uri) = *slot_info;
+        *sym_p11_kit_uri_get_slot_info(uri) = *slot_info;
         return uri;
 }
 
@@ -87,11 +137,14 @@ P11KitUri *uri_from_token_info(const CK_TOKEN_INFO *token_info) {
 
         assert(token_info);
 
-        uri = p11_kit_uri_new();
+        if (dlopen_p11kit() < 0)
+                return NULL;
+
+        uri = sym_p11_kit_uri_new();
         if (!uri)
                 return NULL;
 
-        *p11_kit_uri_get_token_info(uri) = *token_info;
+        *sym_p11_kit_uri_get_token_info(uri) = *token_info;
         return uri;
 }
 
@@ -174,6 +227,60 @@ char *pkcs11_token_model(const CK_TOKEN_INFO *token_info) {
         return t;
 }
 
+int pkcs11_token_login_by_pin(
+                CK_FUNCTION_LIST *m,
+                CK_SESSION_HANDLE session,
+                const CK_TOKEN_INFO *token_info,
+                const char *token_label,
+                const void *pin,
+                size_t pin_size) {
+
+        CK_RV rv;
+        int r;
+
+        assert(m);
+        assert(token_info);
+
+        r = dlopen_p11kit();
+        if (r < 0)
+                return r;
+
+        if (FLAGS_SET(token_info->flags, CKF_PROTECTED_AUTHENTICATION_PATH)) {
+                rv = m->C_Login(session, CKU_USER, NULL, 0);
+                if (rv != CKR_OK)
+                        return log_error_errno(SYNTHETIC_ERRNO(EIO),
+                                               "Failed to log into security token '%s': %s", token_label, sym_p11_kit_strerror(rv));
+
+                log_info("Successfully logged into security token '%s' via protected authentication path.", token_label);
+                return 0;
+        }
+
+        if (!FLAGS_SET(token_info->flags, CKF_LOGIN_REQUIRED)) {
+                log_info("No login into security token '%s' required.", token_label);
+                return 0;
+        }
+
+        if (!pin)
+                return -ENOANO;
+
+        rv = m->C_Login(session, CKU_USER, (CK_UTF8CHAR*) pin, pin_size);
+        if (rv == CKR_OK)  {
+                log_info("Successfully logged into security token '%s'.", token_label);
+                return 0;
+        }
+
+        if (rv == CKR_PIN_LOCKED)
+                return log_error_errno(SYNTHETIC_ERRNO(EPERM),
+                                       "PIN has been locked, please reset PIN of security token '%s'.", token_label);
+        if (!IN_SET(rv, CKR_PIN_INCORRECT, CKR_PIN_LEN_RANGE))
+                return log_error_errno(SYNTHETIC_ERRNO(EIO),
+                                       "Failed to log into security token '%s': %s", token_label, sym_p11_kit_strerror(rv));
+
+        return log_notice_errno(SYNTHETIC_ERRNO(ENOLCK),
+                                "PIN for token '%s' is incorrect, please try again.",
+                                token_label);
+}
+
 int pkcs11_token_login(
                 CK_FUNCTION_LIST *m,
                 CK_SESSION_HANDLE session,
@@ -184,11 +291,12 @@ int pkcs11_token_login(
                 const char *key_name,
                 const char *credential_name,
                 usec_t until,
+                AskPasswordFlags ask_password_flags,
                 bool headless,
                 char **ret_used_pin) {
 
         _cleanup_free_ char *token_uri_string = NULL, *token_uri_escaped = NULL, *id = NULL, *token_label = NULL;
-        _cleanup_(p11_kit_uri_freep) P11KitUri *token_uri = NULL;
+        _cleanup_(sym_p11_kit_uri_freep) P11KitUri *token_uri = NULL;
         CK_TOKEN_INFO updated_token_info;
         int uri_result, r;
         CK_RV rv;
@@ -196,6 +304,10 @@ int pkcs11_token_login(
         assert(m);
         assert(token_info);
 
+        r = dlopen_p11kit();
+        if (r < 0)
+                return r;
+
         token_label = pkcs11_token_label(token_info);
         if (!token_label)
                 return log_oom();
@@ -204,28 +316,16 @@ int pkcs11_token_login(
         if (!token_uri)
                 return log_oom();
 
-        uri_result = p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, &token_uri_string);
+        uri_result = sym_p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, &token_uri_string);
         if (uri_result != P11_KIT_URI_OK)
-                return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN), "Failed to format slot URI: %s", p11_kit_uri_message(uri_result));
-
-        if (FLAGS_SET(token_info->flags, CKF_PROTECTED_AUTHENTICATION_PATH)) {
-                rv = m->C_Login(session, CKU_USER, NULL, 0);
-                if (rv != CKR_OK)
-                        return log_error_errno(SYNTHETIC_ERRNO(EIO),
-                                               "Failed to log into security token '%s': %s", token_label, p11_kit_strerror(rv));
+                return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN), "Failed to format slot URI: %s", sym_p11_kit_uri_message(uri_result));
 
-                log_info("Successfully logged into security token '%s' via protected authentication path.", token_label);
-                if (ret_used_pin)
-                        *ret_used_pin = NULL;
-                return 0;
-        }
+        r = pkcs11_token_login_by_pin(m, session, token_info, token_label, /* pin= */ NULL, 0);
+        if (r == 0 && ret_used_pin)
+                *ret_used_pin = NULL;
 
-        if (!FLAGS_SET(token_info->flags, CKF_LOGIN_REQUIRED)) {
-                log_info("No login into security token '%s' required.", token_label);
-                if (ret_used_pin)
-                        *ret_used_pin = NULL;
-                return 0;
-        }
+        if (r != -ENOANO) /* pin required */
+                return r;
 
         token_uri_escaped = cescape(token_uri_string);
         if (!token_uri_escaped)
@@ -237,17 +337,16 @@ int pkcs11_token_login(
 
         for (unsigned tries = 0; tries < 3; tries++) {
                 _cleanup_strv_free_erase_ char **passwords = NULL;
-                char **i, *e;
+                _cleanup_(erase_and_freep) char *envpin = NULL;
 
-                e = getenv("PIN");
-                if (e) {
-                        passwords = strv_new(e);
+                r = getenv_steal_erase("PIN", &envpin);
+                if (r < 0)
+                        return log_error_errno(r, "Failed to acquire PIN from environment: %m");
+                if (r > 0) {
+                        passwords = strv_new(envpin);
                         if (!passwords)
                                 return log_oom();
 
-                        string_erase(e);
-                        if (unsetenv("PIN") < 0)
-                                return log_error_errno(errno, "Failed to unset $PIN: %m");
                 } else if (headless)
                         return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "PIN querying disabled via 'headless' option. Use the 'PIN' environment variable.");
                 else {
@@ -273,44 +372,34 @@ int pkcs11_token_login(
                                 return log_oom();
 
                         /* We never cache PINs, simply because it's fatal if we use wrong PINs, since usually there are only 3 tries */
-                        r = ask_password_auto(text, icon_name, id, key_name, credential_name, until, 0, &passwords);
+                        r = ask_password_auto(text, icon_name, id, key_name, credential_name, until, ask_password_flags, &passwords);
                         if (r < 0)
                                 return log_error_errno(r, "Failed to query PIN for security token '%s': %m", token_label);
                 }
 
                 STRV_FOREACH(i, passwords) {
-                        rv = m->C_Login(session, CKU_USER, (CK_UTF8CHAR*) *i, strlen(*i));
-                        if (rv == CKR_OK)  {
-
-                                if (ret_used_pin) {
-                                        char *c;
-
-                                        c = strdup(*i);
-                                        if (!c)
-                                                return log_oom();
+                        r = pkcs11_token_login_by_pin(m, session, token_info, token_label, *i, strlen(*i));
+                        if (r == 0 && ret_used_pin) {
+                                char *c;
 
-                                        *ret_used_pin = c;
-                                }
+                                c = strdup(*i);
+                                if (!c)
+                                        return log_oom();
 
-                                log_info("Successfully logged into security token '%s'.", token_label);
-                                return 0;
+                                *ret_used_pin = c;
                         }
-                        if (rv == CKR_PIN_LOCKED)
-                                return log_error_errno(SYNTHETIC_ERRNO(EPERM),
-                                                       "PIN has been locked, please reset PIN of security token '%s'.", token_label);
-                        if (!IN_SET(rv, CKR_PIN_INCORRECT, CKR_PIN_LEN_RANGE))
-                                return log_error_errno(SYNTHETIC_ERRNO(EIO),
-                                                       "Failed to log into security token '%s': %s", token_label, p11_kit_strerror(rv));
 
-                        /* Referesh the token info, so that we can prompt knowing the new flags if they changed. */
+                        if (r != -ENOLCK)
+                                return r;
+
+                        /* Refresh the token info, so that we can prompt knowing the new flags if they changed. */
                         rv = m->C_GetTokenInfo(slotid, &updated_token_info);
                         if (rv != CKR_OK)
                                 return log_error_errno(SYNTHETIC_ERRNO(EIO),
                                                        "Failed to acquire updated security token information for slot %lu: %s",
-                                                       slotid, p11_kit_strerror(rv));
+                                                       slotid, sym_p11_kit_strerror(rv));
 
                         token_info = &updated_token_info;
-                        log_notice("PIN for token '%s' is incorrect, please try again.", token_label);
                 }
         }
 
@@ -329,12 +418,17 @@ int pkcs11_token_find_x509_certificate(
         CK_ATTRIBUTE *attributes = NULL;
         CK_OBJECT_HANDLE objects[2];
         CK_RV rv, rv2;
+        int r;
 
         assert(m);
         assert(search_uri);
         assert(ret_object);
 
-        attributes = p11_kit_uri_get_attributes(search_uri, &n_attributes);
+        r = dlopen_p11kit();
+        if (r < 0)
+                return r;
+
+        attributes = sym_p11_kit_uri_get_attributes(search_uri, &n_attributes);
         for (a = 0; a < n_attributes; a++) {
 
                 /* We use the URI's included match attributes, but make them more strict. This allows users
@@ -407,16 +501,16 @@ int pkcs11_token_find_x509_certificate(
         rv = m->C_FindObjectsInit(session, attributes, n_attributes);
         if (rv != CKR_OK)
                 return log_error_errno(SYNTHETIC_ERRNO(EIO),
-                                       "Failed to initialize object find call: %s", p11_kit_strerror(rv));
+                                       "Failed to initialize object find call: %s", sym_p11_kit_strerror(rv));
 
         rv = m->C_FindObjects(session, objects, ELEMENTSOF(objects), &n_objects);
         rv2 = m->C_FindObjectsFinal(session);
         if (rv != CKR_OK)
                 return log_error_errno(SYNTHETIC_ERRNO(EIO),
-                                       "Failed to find objects: %s", p11_kit_strerror(rv));
+                                       "Failed to find objects: %s", sym_p11_kit_strerror(rv));
         if (rv2 != CKR_OK)
                 return log_error_errno(SYNTHETIC_ERRNO(EIO),
-                                       "Failed to finalize object find call: %s", p11_kit_strerror(rv));
+                                       "Failed to finalize object find call: %s", sym_p11_kit_strerror(rv));
         if (n_objects == 0)
                 return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
                                        "Failed to find selected X509 certificate on token.");
@@ -444,11 +538,16 @@ int pkcs11_token_read_x509_certificate(
         _cleanup_(X509_freep) X509 *x509 = NULL;
         X509_NAME *name = NULL;
         const unsigned char *p;
+        int r;
+
+        r = dlopen_p11kit();
+        if (r < 0)
+                return r;
 
         rv = m->C_GetAttributeValue(session, object, &attribute, 1);
         if (rv != CKR_OK)
                 return log_error_errno(SYNTHETIC_ERRNO(EIO),
-                                       "Failed to read X.509 certificate size off token: %s", p11_kit_strerror(rv));
+                                       "Failed to read X.509 certificate size off token: %s", sym_p11_kit_strerror(rv));
 
         buffer = malloc(attribute.ulValueLen);
         if (!buffer)
@@ -459,7 +558,7 @@ int pkcs11_token_read_x509_certificate(
         rv = m->C_GetAttributeValue(session, object, &attribute, 1);
         if (rv != CKR_OK)
                 return log_error_errno(SYNTHETIC_ERRNO(EIO),
-                                       "Failed to read X.509 certificate data off token: %s", p11_kit_strerror(rv));
+                                       "Failed to read X.509 certificate data off token: %s", sym_p11_kit_strerror(rv));
 
         p = attribute.pValue;
         x509 = d2i_X509(NULL, &p, attribute.ulValueLen);
@@ -487,138 +586,419 @@ int pkcs11_token_find_private_key(
                 P11KitUri *search_uri,
                 CK_OBJECT_HANDLE *ret_object) {
 
-        bool found_decrypt = false, found_class = false, found_key_type = false;
+        uint_fast8_t n_objects = 0;
+        bool found_class = false;
         _cleanup_free_ CK_ATTRIBUTE *attributes_buffer = NULL;
-        CK_ULONG n_attributes, a, n_objects;
-        CK_ATTRIBUTE *attributes = NULL;
-        CK_OBJECT_HANDLE objects[2];
-        CK_RV rv, rv2;
+        CK_OBJECT_HANDLE object, candidate;
+        static const CK_OBJECT_CLASS class = CKO_PRIVATE_KEY;
+        CK_BBOOL decrypt_value, derive_value;
+        CK_ATTRIBUTE optional_attributes[] = {
+                { CKA_DECRYPT, &decrypt_value, sizeof(decrypt_value) },
+                { CKA_DERIVE,  &derive_value,  sizeof(derive_value)  }
+        };
+        CK_RV rv;
 
         assert(m);
         assert(search_uri);
         assert(ret_object);
 
-        attributes = p11_kit_uri_get_attributes(search_uri, &n_attributes);
-        for (a = 0; a < n_attributes; a++) {
+        CK_ULONG n_attributes;
+        CK_ATTRIBUTE *attributes = sym_p11_kit_uri_get_attributes(search_uri, &n_attributes);
+        for (CK_ULONG i = 0; i < n_attributes; i++) {
 
                 /* We use the URI's included match attributes, but make them more strict. This allows users
                  * to specify a token URL instead of an object URL and the right thing should happen if
                  * there's only one suitable key on the token. */
 
-                switch (attributes[a].type) {
-
+                switch (attributes[i].type) {
                 case CKA_CLASS: {
                         CK_OBJECT_CLASS c;
 
-                        if (attributes[a].ulValueLen != sizeof(c))
+                        if (attributes[i].ulValueLen != sizeof(c))
                                 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid PKCS#11 CKA_CLASS attribute size.");
 
-                        memcpy(&c, attributes[a].pValue, sizeof(c));
+                        memcpy(&c, attributes[i].pValue, sizeof(c));
                         if (c != CKO_PRIVATE_KEY)
                                 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                        "Selected PKCS#11 object is not a private key, refusing.");
 
                         found_class = true;
                         break;
-                }
+                }}
+        }
 
-                case CKA_DECRYPT: {
-                        CK_BBOOL b;
+        if (!found_class) {
+                /* Hmm, let's slightly extend the attribute list we search for */
 
-                        if (attributes[a].ulValueLen != sizeof(b))
-                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid PKCS#11 CKA_DECRYPT attribute size.");
+                attributes_buffer = new(CK_ATTRIBUTE, n_attributes + 1);
+                if (!attributes_buffer)
+                        return log_oom();
 
-                        memcpy(&b, attributes[a].pValue, sizeof(b));
-                        if (!b)
-                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
-                                                       "Selected PKCS#11 object is not suitable for decryption, refusing.");
+                memcpy(attributes_buffer, attributes, sizeof(CK_ATTRIBUTE) * n_attributes);
+
+                attributes_buffer[n_attributes++] = (CK_ATTRIBUTE) {
+                        .type = CKA_CLASS,
+                        .pValue = (CK_OBJECT_CLASS*) &class,
+                        .ulValueLen = sizeof(class),
+                };
+
+                attributes = attributes_buffer;
+        }
+
+        rv = m->C_FindObjectsInit(session, attributes, n_attributes);
+        if (rv != CKR_OK)
+                return log_error_errno(SYNTHETIC_ERRNO(EIO),
+                                       "Failed to initialize object find call: %s", sym_p11_kit_strerror(rv));
 
-                        found_decrypt = true;
+        for (;;) {
+                CK_ULONG b;
+                rv = m->C_FindObjects(session, &candidate, 1, &b);
+                if (rv != CKR_OK)
+                        return log_error_errno(SYNTHETIC_ERRNO(EIO),
+                                "Failed to find objects: %s", sym_p11_kit_strerror(rv));
+
+                if (b == 0)
                         break;
+
+                bool can_decrypt = false, can_derive = false;
+                optional_attributes[0].ulValueLen = sizeof(decrypt_value);
+                optional_attributes[1].ulValueLen = sizeof(derive_value);
+
+                rv = m->C_GetAttributeValue(session, candidate, optional_attributes, ELEMENTSOF(optional_attributes));
+                if (rv != CKR_OK && rv != CKR_ATTRIBUTE_TYPE_INVALID)
+                        return log_error_errno(SYNTHETIC_ERRNO(EIO),
+                                "Failed to get attributes of a selected private key: %s", sym_p11_kit_strerror(rv));
+
+                if (optional_attributes[0].ulValueLen != CK_UNAVAILABLE_INFORMATION && decrypt_value == CK_TRUE)
+                        can_decrypt = true;
+
+                if (optional_attributes[1].ulValueLen != CK_UNAVAILABLE_INFORMATION && derive_value == CK_TRUE)
+                        can_derive = true;
+
+                if (can_decrypt || can_derive) {
+                        n_objects++;
+                        if (n_objects > 1)
+                                break;
+                        object = candidate;
                 }
+        }
 
-                case CKA_KEY_TYPE: {
-                        CK_KEY_TYPE t;
+        rv = m->C_FindObjectsFinal(session);
+        if (rv != CKR_OK)
+                return log_error_errno(SYNTHETIC_ERRNO(EIO),
+                        "Failed to finalize object find call: %s", sym_p11_kit_strerror(rv));
 
-                        if (attributes[a].ulValueLen != sizeof(t))
-                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid PKCS#11 CKA_KEY_TYPE attribute size.");
+        if (n_objects == 0)
+                return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
+                        "Failed to find selected private key suitable for decryption or derivation on token.");
 
-                        memcpy(&t, attributes[a].pValue, sizeof(t));
-                        if (t != CKK_RSA)
-                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Selected PKCS#11 object is not an RSA key, refusing.");
+        if (n_objects > 1)
+                return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
+                        "Configured private key URI matches multiple keys, refusing.");
 
-                        found_key_type = true;
-                        break;
-                }}
+        *ret_object = object;
+        return 0;
+}
+
+static const char* object_class_to_string(CK_OBJECT_CLASS class) {
+        switch (class) {
+        case CKO_CERTIFICATE:
+                return "CKO_CERTIFICATE";
+        case CKO_PUBLIC_KEY:
+                return "CKO_PUBLIC_KEY";
+        case CKO_PRIVATE_KEY:
+                return "CKO_PRIVATE_KEY";
+        case CKO_SECRET_KEY:
+                return "CKO_SECRET_KEY";
+        default:
+                return NULL;
         }
+}
 
-        if (!found_decrypt || !found_class || !found_key_type) {
-                /* Hmm, let's slightly extend the attribute list we search for */
+/* Returns an object with the given class and the same CKA_ID or CKA_LABEL as prototype */
+int pkcs11_token_find_related_object(
+                CK_FUNCTION_LIST *m,
+                CK_SESSION_HANDLE session,
+                CK_OBJECT_HANDLE prototype,
+                CK_OBJECT_CLASS class,
+                CK_OBJECT_HANDLE *ret_object ) {
 
-                attributes_buffer = new(CK_ATTRIBUTE, n_attributes + !found_decrypt + !found_class + !found_key_type);
-                if (!attributes_buffer)
+        _cleanup_free_ void *buffer = NULL;
+        CK_ATTRIBUTE attributes[] = {
+                { CKA_ID,    NULL_PTR, 0 },
+                { CKA_LABEL, NULL_PTR, 0 }
+        };
+        CK_OBJECT_CLASS search_class = class;
+        CK_ATTRIBUTE search_attributes[2] = {
+                { CKA_CLASS, &search_class, sizeof(search_class) }
+        };
+        CK_ULONG n_objects;
+        CK_OBJECT_HANDLE objects[2];
+        CK_RV rv;
+
+        rv = m->C_GetAttributeValue(session, prototype, attributes, ELEMENTSOF(attributes));
+        if (rv != CKR_OK && rv != CKR_ATTRIBUTE_TYPE_INVALID)
+                return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to retrieve length of attributes: %s", sym_p11_kit_strerror(rv));
+
+        if (attributes[0].ulValueLen != CK_UNAVAILABLE_INFORMATION) {
+                buffer = malloc(attributes[0].ulValueLen);
+                if (!buffer)
                         return log_oom();
 
-                memcpy(attributes_buffer, attributes, sizeof(CK_ATTRIBUTE) * n_attributes);
+                attributes[0].pValue = buffer;
+                rv = m->C_GetAttributeValue(session, prototype, &attributes[0], 1);
+                if (rv != CKR_OK)
+                        return log_debug_errno(SYNTHETIC_ERRNO(EIO),
+                                "Failed to retrieve CKA_ID: %s", sym_p11_kit_strerror(rv));
 
-                if (!found_decrypt) {
-                        static const CK_BBOOL yes = true;
+                search_attributes[1] = attributes[0];
 
-                        attributes_buffer[n_attributes++] = (CK_ATTRIBUTE) {
-                                .type = CKA_DECRYPT,
-                                .pValue = (CK_BBOOL*) &yes,
-                                .ulValueLen = sizeof(yes),
-                        };
-                }
+        } else if (attributes[1].ulValueLen != CK_UNAVAILABLE_INFORMATION) {
+                buffer = malloc(attributes[1].ulValueLen);
+                if (!buffer)
+                        return log_oom();
 
-                if (!found_class) {
-                        static const CK_OBJECT_CLASS class = CKO_PRIVATE_KEY;
+                attributes[1].pValue = buffer;
+                rv = m->C_GetAttributeValue(session, prototype, &attributes[1], 1);
+                if (rv != CKR_OK)
+                        return log_debug_errno(SYNTHETIC_ERRNO(EIO),
+                                "Failed to retrieve CKA_LABEL: %s", sym_p11_kit_strerror(rv));
 
-                        attributes_buffer[n_attributes++] = (CK_ATTRIBUTE) {
-                                .type = CKA_CLASS,
-                                .pValue = (CK_OBJECT_CLASS*) &class,
-                                .ulValueLen = sizeof(class),
-                        };
-                }
+                search_attributes[1] = attributes[1];
 
-                if (!found_key_type) {
-                        static const CK_KEY_TYPE type = CKK_RSA;
+        } else
+                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "The prototype does not have CKA_ID or CKA_LABEL");
 
-                        attributes_buffer[n_attributes++] = (CK_ATTRIBUTE) {
-                                .type = CKA_KEY_TYPE,
-                                .pValue = (CK_KEY_TYPE*) &type,
-                                .ulValueLen = sizeof(type),
-                        };
-                }
+        rv = m->C_FindObjectsInit(session, search_attributes, 2);
+        if (rv != CKR_OK)
+                return log_debug_errno(SYNTHETIC_ERRNO(EIO),
+                        "Failed to initialize object find call: %s", sym_p11_kit_strerror(rv));
 
-                attributes = attributes_buffer;
+        rv = m->C_FindObjects(session, objects, 2, &n_objects);
+        if (rv != CKR_OK)
+                return log_debug_errno(SYNTHETIC_ERRNO(EIO),
+                        "Failed to find objects: %s", sym_p11_kit_strerror(rv));
+
+        rv = m->C_FindObjectsFinal(session);
+        if (rv != CKR_OK)
+                return log_debug_errno(SYNTHETIC_ERRNO(EIO),
+                        "Failed to finalize object find call: %s", sym_p11_kit_strerror(rv));
+
+         if (n_objects == 0)
+                return log_debug_errno(SYNTHETIC_ERRNO(ENOENT),
+                        "Failed to find a related object with class %s", object_class_to_string(class));
+
+         if (n_objects > 1)
+                log_warning("Found multiple related objects with class %s, using the first object.",
+                        object_class_to_string(class));
+
+        *ret_object = objects[0];
+        return 0;
+}
+
+#if HAVE_OPENSSL
+static int ecc_convert_to_compressed(
+                CK_FUNCTION_LIST *m,
+                CK_SESSION_HANDLE session,
+                CK_OBJECT_HANDLE object,
+                const void *uncompressed_point,
+                size_t uncompressed_point_size,
+                void **ret_compressed_point,
+                size_t *ret_compressed_point_size) {
+
+        _cleanup_free_ void *ec_params_buffer = NULL;
+        CK_ATTRIBUTE ec_params_attr = { CKA_EC_PARAMS, NULL_PTR, 0 };
+        CK_RV rv;
+        int r;
+
+        rv = m->C_GetAttributeValue(session, object, &ec_params_attr, 1);
+        if (rv != CKR_OK && rv != CKR_ATTRIBUTE_TYPE_INVALID)
+                return log_error_errno(SYNTHETIC_ERRNO(EIO),
+                        "Failed to retrieve length of CKA_EC_PARAMS: %s", sym_p11_kit_strerror(rv));
+
+        if (ec_params_attr.ulValueLen != CK_UNAVAILABLE_INFORMATION) {
+                ec_params_buffer = malloc(ec_params_attr.ulValueLen);
+                if (!ec_params_buffer)
+                        return log_oom();
+
+                ec_params_attr.pValue = ec_params_buffer;
+                rv = m->C_GetAttributeValue(session, object, &ec_params_attr, 1);
+                if (rv != CKR_OK)
+                        return log_error_errno(SYNTHETIC_ERRNO(EIO),
+                                "Failed to retrieve CKA_EC_PARAMS from a private key: %s", sym_p11_kit_strerror(rv));
+        } else {
+                CK_OBJECT_HANDLE public_key;
+                r = pkcs11_token_find_related_object(m, session, object, CKO_PUBLIC_KEY, &public_key);
+                if (r < 0)
+                        return log_error_errno(r, "Failed to find a public key for compressing a EC point");
+
+                ec_params_attr.ulValueLen = 0;
+                rv = m->C_GetAttributeValue(session, public_key, &ec_params_attr, 1);
+                if (rv != CKR_OK && rv != CKR_ATTRIBUTE_TYPE_INVALID)
+                        return log_error_errno(SYNTHETIC_ERRNO(EIO),
+                                "Failed to retrieve length of CKA_EC_PARAMS: %s", sym_p11_kit_strerror(rv));
+
+                if (ec_params_attr.ulValueLen == CK_UNAVAILABLE_INFORMATION)
+                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
+                                "The public key does not have CKA_EC_PARAMS");
+
+                ec_params_buffer = malloc(ec_params_attr.ulValueLen);
+                if (!ec_params_buffer)
+                        return log_oom();
+
+                ec_params_attr.pValue = ec_params_buffer;
+                rv = m->C_GetAttributeValue(session, public_key, &ec_params_attr, 1);
+                if (rv != CKR_OK)
+                        return log_error_errno(SYNTHETIC_ERRNO(EIO),
+                                "Failed to retrieve CKA_EC_PARAMS from a public key: %s", sym_p11_kit_strerror(rv));
         }
 
-        rv = m->C_FindObjectsInit(session, attributes, n_attributes);
+        _cleanup_(EC_GROUP_freep) EC_GROUP *group = NULL;
+        _cleanup_(EC_POINT_freep) EC_POINT *point = NULL;
+        _cleanup_(BN_CTX_freep) BN_CTX *bnctx = NULL;
+        _cleanup_free_ void *compressed_point = NULL;
+        size_t compressed_point_size;
+
+        const unsigned char *ec_params_value = ec_params_attr.pValue;
+        group = d2i_ECPKParameters(NULL, &ec_params_value, ec_params_attr.ulValueLen);
+        if (!group)
+                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unable to decode CKA_EC_PARAMS");
+
+        point = EC_POINT_new(group);
+        if (!point)
+                return log_oom();
+
+        bnctx = BN_CTX_new();
+        if (!bnctx)
+                return log_oom();
+
+        if (EC_POINT_oct2point(group, point, uncompressed_point, uncompressed_point_size, bnctx) != 1)
+                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unable to decode an uncompressed EC point");
+
+        compressed_point_size = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, bnctx);
+        if (compressed_point_size == 0)
+                return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to determine size of a compressed EC point");
+
+        compressed_point = malloc(compressed_point_size);
+        if (!compressed_point)
+                return log_oom();
+
+        compressed_point_size = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, compressed_point, compressed_point_size, bnctx);
+        if (compressed_point_size == 0)
+                return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to convert a EC point to compressed format");
+
+        *ret_compressed_point = TAKE_PTR(compressed_point);
+        *ret_compressed_point_size = compressed_point_size;
+        return 0;
+}
+#endif
+
+/* Since EC keys doesn't support encryption directly, we use ECDH protocol to derive shared secret here.
+ * We use PKCS#11 C_DeriveKey function to derive a shared secret with a private key stored in the token and
+ * a public key saved on enrollment. */
+static int pkcs11_token_decrypt_data_ecc(
+                CK_FUNCTION_LIST *m,
+                CK_SESSION_HANDLE session,
+                CK_OBJECT_HANDLE object,
+                const void *encrypted_data,
+                size_t encrypted_data_size,
+                void **ret_decrypted_data,
+                size_t *ret_decrypted_data_size) {
+
+        static const CK_BBOOL yes = CK_TRUE, no = CK_FALSE;
+        static const CK_OBJECT_CLASS shared_secret_class = CKO_SECRET_KEY;
+        static const CK_KEY_TYPE shared_secret_type = CKK_GENERIC_SECRET;
+        static const CK_ATTRIBUTE shared_secret_template[] = {
+                { CKA_TOKEN,       (void*) &no,                  sizeof(no)                  },
+                { CKA_CLASS,       (void*) &shared_secret_class, sizeof(shared_secret_class) },
+                { CKA_KEY_TYPE,    (void*) &shared_secret_type,  sizeof(shared_secret_type)  },
+                { CKA_SENSITIVE,   (void*) &no,                  sizeof(no)                  },
+                { CKA_EXTRACTABLE, (void*) &yes,                 sizeof(yes)                 }
+        };
+        CK_ECDH1_DERIVE_PARAMS params = {
+                .kdf = CKD_NULL,
+                .pPublicData = (void*) encrypted_data,
+                .ulPublicDataLen = encrypted_data_size
+        };
+        CK_MECHANISM mechanism = {
+                .mechanism = CKM_ECDH1_DERIVE,
+                .pParameter = &params,
+                .ulParameterLen = sizeof(params)
+        };
+        CK_OBJECT_HANDLE shared_secret_handle;
+        CK_SESSION_INFO session_info;
+        CK_MECHANISM_INFO mechanism_info;
+        CK_RV rv, rv2;
+#if HAVE_OPENSSL
+        _cleanup_free_ void *compressed_point = NULL;
+        int r;
+#endif
+
+        rv = m->C_GetSessionInfo(session, &session_info);
         if (rv != CKR_OK)
                 return log_error_errno(SYNTHETIC_ERRNO(EIO),
-                                       "Failed to initialize object find call: %s", p11_kit_strerror(rv));
+                        "Failed to get information about the PKCS#11 session: %s", sym_p11_kit_strerror(rv));
 
-        rv = m->C_FindObjects(session, objects, ELEMENTSOF(objects), &n_objects);
-        rv2 = m->C_FindObjectsFinal(session);
+        rv = m->C_GetMechanismInfo(session_info.slotID, CKM_ECDH1_DERIVE, &mechanism_info);
         if (rv != CKR_OK)
                 return log_error_errno(SYNTHETIC_ERRNO(EIO),
-                                       "Failed to find objects: %s", p11_kit_strerror(rv));
+                        "Failed to get information about CKM_ECDH1_DERIVE: %s", sym_p11_kit_strerror(rv));
+
+        if (!(mechanism_info.flags & CKF_EC_UNCOMPRESS)) {
+                if (mechanism_info.flags & CKF_EC_COMPRESS) {
+#if HAVE_OPENSSL
+                        log_debug("CKM_ECDH1_DERIVE accepts compressed EC points only, trying to convert.");
+                        size_t compressed_point_size;
+                        r = ecc_convert_to_compressed(m, session, object, encrypted_data, encrypted_data_size, &compressed_point, &compressed_point_size);
+                        if (r < 0)
+                                return r;
+
+                        params.pPublicData = compressed_point;
+                        params.ulPublicDataLen = compressed_point_size;
+#else
+                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
+                                "CKM_ECDH1_DERIVE does not support uncompressed format of EC points");
+#endif
+                } else
+                        log_debug("Both CKF_EC_UNCOMPRESS and CKF_EC_COMPRESS are false for CKM_ECDH1_DERIVE, ignoring.");
+        }
+
+        rv = m->C_DeriveKey(session, &mechanism, object, (CK_ATTRIBUTE*) shared_secret_template, ELEMENTSOF(shared_secret_template), &shared_secret_handle);
+        if (rv != CKR_OK)
+                return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to derive a shared secret: %s", sym_p11_kit_strerror(rv));
+
+        CK_ATTRIBUTE shared_secret_attr = { CKA_VALUE, NULL_PTR, 0};
+
+        rv = m->C_GetAttributeValue(session, shared_secret_handle, &shared_secret_attr, 1);
+        if (rv != CKR_OK) {
+                rv2 = m->C_DestroyObject(session, shared_secret_handle);
+                if (rv2 != CKR_OK)
+                        log_warning("Failed to destroy a shared secret, ignoring: %s", sym_p11_kit_strerror(rv2));
+                return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to retrieve shared secret length: %s", sym_p11_kit_strerror(rv));
+        }
+
+        shared_secret_attr.pValue = malloc(shared_secret_attr.ulValueLen);
+        if (!shared_secret_attr.pValue)
+                return log_oom();
+
+        rv = m->C_GetAttributeValue(session, shared_secret_handle, &shared_secret_attr, 1);
+        rv2 = m->C_DestroyObject(session, shared_secret_handle);
         if (rv2 != CKR_OK)
-                return log_error_errno(SYNTHETIC_ERRNO(EIO),
-                                       "Failed to finalize object find call: %s", p11_kit_strerror(rv));
-        if (n_objects == 0)
-                return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
-                                       "Failed to find selected private key suitable for decryption on token.");
-        if (n_objects > 1)
-                return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
-                                       "Configured private key URI matches multiple keys, refusing.");
+                log_warning("Failed to destroy a shared secret, ignoring: %s", sym_p11_kit_strerror(rv2));
 
-        *ret_object = objects[0];
+        if (rv != CKR_OK) {
+                erase_and_free(shared_secret_attr.pValue);
+                return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to retrieve a shared secret: %s", sym_p11_kit_strerror(rv));
+        }
+
+        log_info("Successfully derived key with security token.");
+
+        *ret_decrypted_data = shared_secret_attr.pValue;
+        *ret_decrypted_data_size = shared_secret_attr.ulValueLen;
         return 0;
 }
 
-int pkcs11_token_decrypt_data(
+static int pkcs11_token_decrypt_data_rsa(
                 CK_FUNCTION_LIST *m,
                 CK_SESSION_HANDLE session,
                 CK_OBJECT_HANDLE object,
@@ -634,16 +1014,10 @@ int pkcs11_token_decrypt_data(
         CK_ULONG dbuffer_size = 0;
         CK_RV rv;
 
-        assert(m);
-        assert(encrypted_data);
-        assert(encrypted_data_size > 0);
-        assert(ret_decrypted_data);
-        assert(ret_decrypted_data_size);
-
         rv = m->C_DecryptInit(session, (CK_MECHANISM*) &mechanism, object);
         if (rv != CKR_OK)
                 return log_error_errno(SYNTHETIC_ERRNO(EIO),
-                                       "Failed to initialize decryption on security token: %s", p11_kit_strerror(rv));
+                                       "Failed to initialize decryption on security token: %s", sym_p11_kit_strerror(rv));
 
         dbuffer_size = encrypted_data_size; /* Start with something reasonable */
         dbuffer = malloc(dbuffer_size);
@@ -662,7 +1036,7 @@ int pkcs11_token_decrypt_data(
         }
         if (rv != CKR_OK)
                 return log_error_errno(SYNTHETIC_ERRNO(EIO),
-                                       "Failed to decrypt key on security token: %s", p11_kit_strerror(rv));
+                                       "Failed to decrypt key on security token: %s", sym_p11_kit_strerror(rv));
 
         log_info("Successfully decrypted key with security token.");
 
@@ -671,6 +1045,42 @@ int pkcs11_token_decrypt_data(
         return 0;
 }
 
+int pkcs11_token_decrypt_data(
+                CK_FUNCTION_LIST *m,
+                CK_SESSION_HANDLE session,
+                CK_OBJECT_HANDLE object,
+                const void *encrypted_data,
+                size_t encrypted_data_size,
+                void **ret_decrypted_data,
+                size_t *ret_decrypted_data_size) {
+
+        CK_KEY_TYPE key_type;
+        CK_ATTRIBUTE key_type_template = { CKA_KEY_TYPE, &key_type, sizeof(key_type) };
+        CK_RV rv;
+
+        assert(m);
+        assert(encrypted_data);
+        assert(encrypted_data_size > 0);
+        assert(ret_decrypted_data);
+        assert(ret_decrypted_data_size);
+
+        rv = m->C_GetAttributeValue(session, object, &key_type_template, 1);
+        if (rv != CKR_OK)
+                return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to retrieve private key type");
+
+        switch (key_type) {
+
+        case CKK_RSA:
+                return pkcs11_token_decrypt_data_rsa(m, session, object, encrypted_data, encrypted_data_size, ret_decrypted_data, ret_decrypted_data_size);
+
+        case CKK_EC:
+                return pkcs11_token_decrypt_data_ecc(m, session, object, encrypted_data, encrypted_data_size, ret_decrypted_data, ret_decrypted_data_size);
+
+        default:
+                return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Unsupported private key type: %lu", key_type);
+        }
+}
+
 int pkcs11_token_acquire_rng(
                 CK_FUNCTION_LIST *m,
                 CK_SESSION_HANDLE session) {
@@ -682,6 +1092,10 @@ int pkcs11_token_acquire_rng(
 
         assert(m);
 
+        r = dlopen_p11kit();
+        if (r < 0)
+                return r;
+
         /* While we are at it, let's read some RNG data from the PKCS#11 token and pass it to the kernel
          * random pool. This should be cheap if we are talking to the device already. Note that we don't
          * credit any entropy, since we don't know about the quality of the pkcs#11 token's RNG. Why bother
@@ -698,7 +1112,7 @@ int pkcs11_token_acquire_rng(
         rv = m->C_GenerateRandom(session, buffer, rps);
         if (rv != CKR_OK)
                 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
-                                       "Failed to generate RNG data on security token: %s", p11_kit_strerror(rv));
+                                       "Failed to generate RNG data on security token: %s", sym_p11_kit_strerror(rv));
 
         r = random_write_entropy(-1, buffer, rps, false);
         if (r < 0)
@@ -734,7 +1148,7 @@ static int token_process(
         rv = m->C_OpenSession(slotid, CKF_SERIAL_SESSION, NULL, NULL, &session);
         if (rv != CKR_OK)
                 return log_error_errno(SYNTHETIC_ERRNO(EIO),
-                                       "Failed to create session for security token '%s': %s", token_label, p11_kit_strerror(rv));
+                                       "Failed to create session for security token '%s': %s", token_label, sym_p11_kit_strerror(rv));
 
         if (callback)
                 r = callback(m, session, slotid, slot_info, token_info, search_uri, userdata);
@@ -743,7 +1157,7 @@ static int token_process(
 
         rv = m->C_CloseSession(session);
         if (rv != CKR_OK)
-                log_warning("Failed to close session on PKCS#11 token, ignoring: %s", p11_kit_strerror(rv));
+                log_warning("Failed to close session on PKCS#11 token, ignoring: %s", sym_p11_kit_strerror(rv));
 
         return r;
 }
@@ -755,21 +1169,25 @@ static int slot_process(
                 pkcs11_find_token_callback_t callback,
                 void *userdata) {
 
-        _cleanup_(p11_kit_uri_freep) P11KitUri* slot_uri = NULL, *token_uri = NULL;
+        _cleanup_(sym_p11_kit_uri_freep) P11KitUri* slot_uri = NULL, *token_uri = NULL;
         _cleanup_free_ char *token_uri_string = NULL;
         CK_TOKEN_INFO token_info;
         CK_SLOT_INFO slot_info;
-        int uri_result;
+        int uri_result, r;
         CK_RV rv;
 
         assert(m);
 
+        r = dlopen_p11kit();
+        if (r < 0)
+                return r;
+
         /* We return -EAGAIN for all failures we can attribute to a specific slot in some way, so that the
          * caller might try other slots before giving up. */
 
         rv = m->C_GetSlotInfo(slotid, &slot_info);
         if (rv != CKR_OK) {
-                log_warning("Failed to acquire slot info for slot %lu, ignoring slot: %s", slotid, p11_kit_strerror(rv));
+                log_warning("Failed to acquire slot info for slot %lu, ignoring slot: %s", slotid, sym_p11_kit_strerror(rv));
                 return -EAGAIN;
         }
 
@@ -780,9 +1198,9 @@ static int slot_process(
         if (DEBUG_LOGGING) {
                 _cleanup_free_ char *slot_uri_string = NULL;
 
-                uri_result = p11_kit_uri_format(slot_uri, P11_KIT_URI_FOR_ANY, &slot_uri_string);
+                uri_result = sym_p11_kit_uri_format(slot_uri, P11_KIT_URI_FOR_ANY, &slot_uri_string);
                 if (uri_result != P11_KIT_URI_OK) {
-                        log_warning("Failed to format slot URI, ignoring slot: %s", p11_kit_uri_message(uri_result));
+                        log_warning("Failed to format slot URI, ignoring slot: %s", sym_p11_kit_uri_message(uri_result));
                         return -EAGAIN;
                 }
 
@@ -794,7 +1212,7 @@ static int slot_process(
                 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
                                        "Token not present in slot, ignoring.");
         } else if (rv != CKR_OK) {
-                log_warning("Failed to acquire token info for slot %lu, ignoring slot: %s", slotid, p11_kit_strerror(rv));
+                log_warning("Failed to acquire token info for slot %lu, ignoring slot: %s", slotid, sym_p11_kit_strerror(rv));
                 return -EAGAIN;
         }
 
@@ -802,13 +1220,13 @@ static int slot_process(
         if (!token_uri)
                 return log_oom();
 
-        uri_result = p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, &token_uri_string);
+        uri_result = sym_p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, &token_uri_string);
         if (uri_result != P11_KIT_URI_OK) {
-                log_warning("Failed to format slot URI: %s", p11_kit_uri_message(uri_result));
+                log_warning("Failed to format slot URI: %s", sym_p11_kit_uri_message(uri_result));
                 return -EAGAIN;
         }
 
-        if (search_uri && !p11_kit_uri_match_token_info(search_uri, &token_info))
+        if (search_uri && !sym_p11_kit_uri_match_token_info(search_uri, &token_info))
                 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
                                        "Found non-matching token with URI %s.",
                                        token_uri_string);
@@ -831,8 +1249,8 @@ static int module_process(
                 pkcs11_find_token_callback_t callback,
                 void *userdata) {
 
+        _cleanup_(sym_p11_kit_uri_freep) P11KitUri* module_uri = NULL;
         _cleanup_free_ char *name = NULL, *module_uri_string = NULL;
-        _cleanup_(p11_kit_uri_freep) P11KitUri* module_uri = NULL;
         _cleanup_free_ CK_SLOT_ID *slotids = NULL;
         CK_ULONG n_slotids = 0;
         int uri_result;
@@ -843,11 +1261,15 @@ static int module_process(
 
         assert(m);
 
+        r = dlopen_p11kit();
+        if (r < 0)
+                return r;
+
         /* We ignore most errors from modules here, in order to skip over faulty modules: one faulty module
          * should not have the effect that we don't try the others anymore. We indicate such per-module
          * failures with -EAGAIN, which let's the caller try the next module. */
 
-        name = p11_kit_module_get_name(m);
+        name = sym_p11_kit_module_get_name(m);
         if (!name)
                 return log_oom();
 
@@ -855,7 +1277,7 @@ static int module_process(
 
         rv = m->C_GetInfo(&info);
         if (rv != CKR_OK) {
-                log_warning("Failed to get info on PKCS#11 module, ignoring module: %s", p11_kit_strerror(rv));
+                log_warning("Failed to get info on PKCS#11 module, ignoring module: %s", sym_p11_kit_strerror(rv));
                 return -EAGAIN;
         }
 
@@ -863,9 +1285,9 @@ static int module_process(
         if (!module_uri)
                 return log_oom();
 
-        uri_result = p11_kit_uri_format(module_uri, P11_KIT_URI_FOR_ANY, &module_uri_string);
+        uri_result = sym_p11_kit_uri_format(module_uri, P11_KIT_URI_FOR_ANY, &module_uri_string);
         if (uri_result != P11_KIT_URI_OK) {
-                log_warning("Failed to format module URI, ignoring module: %s", p11_kit_uri_message(uri_result));
+                log_warning("Failed to format module URI, ignoring module: %s", sym_p11_kit_uri_message(uri_result));
                 return -EAGAIN;
         }
 
@@ -873,7 +1295,7 @@ static int module_process(
 
         rv = pkcs11_get_slot_list_malloc(m, &slotids, &n_slotids);
         if (rv != CKR_OK) {
-                log_warning("Failed to get slot list, ignoring module: %s", p11_kit_strerror(rv));
+                log_warning("Failed to get slot list, ignoring module: %s", sym_p11_kit_strerror(rv));
                 return -EAGAIN;
         }
         if (n_slotids == 0)
@@ -899,10 +1321,14 @@ int pkcs11_find_token(
                 pkcs11_find_token_callback_t callback,
                 void *userdata) {
 
-        _cleanup_(p11_kit_modules_finalize_and_releasep) CK_FUNCTION_LIST **modules = NULL;
-        _cleanup_(p11_kit_uri_freep) P11KitUri *search_uri = NULL;
+        _cleanup_(sym_p11_kit_modules_finalize_and_releasep) CK_FUNCTION_LIST **modules = NULL;
+        _cleanup_(sym_p11_kit_uri_freep) P11KitUri *search_uri = NULL;
         int r;
 
+        r = dlopen_p11kit();
+        if (r < 0)
+                return r;
+
         /* Execute the specified callback for each matching token found. If nothing is found returns
          * -EAGAIN. Logs about all errors, except for EAGAIN, which the caller has to log about. */
 
@@ -912,7 +1338,7 @@ int pkcs11_find_token(
                         return log_error_errno(r, "Failed to parse PKCS#11 URI '%s': %m", pkcs11_uri);
         }
 
-        modules = p11_kit_modules_load_and_initialize(0);
+        modules = sym_p11_kit_modules_load_and_initialize(0);
         if (!modules)
                 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to initialize pkcs11 modules");
 
@@ -934,6 +1360,8 @@ struct pkcs11_acquire_certificate_callback_data {
         char *pin_used;
         X509 *cert;
         const char *askpw_friendly_name, *askpw_icon_name;
+        AskPasswordFlags askpw_flags;
+        bool headless;
 };
 
 static void pkcs11_acquire_certificate_callback_data_release(struct pkcs11_acquire_certificate_callback_data *data) {
@@ -951,7 +1379,7 @@ static int pkcs11_acquire_certificate_callback(
                 void *userdata) {
 
         _cleanup_(erase_and_freep) char *pin_used = NULL;
-        struct pkcs11_acquire_certificate_callback_data *data = userdata;
+        struct pkcs11_acquire_certificate_callback_data *data = ASSERT_PTR(userdata);
         CK_OBJECT_HANDLE object;
         int r;
 
@@ -959,11 +1387,22 @@ static int pkcs11_acquire_certificate_callback(
         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->askpw_friendly_name, data->askpw_icon_name, "pkcs11-pin", "pkcs11-pin", UINT64_MAX, false, &pin_used);
+        r = pkcs11_token_login(
+                        m,
+                        session,
+                        slot_id,
+                        token_info,
+                        data->askpw_friendly_name,
+                        data->askpw_icon_name,
+                        "pkcs11-pin",
+                        "pkcs11-pin",
+                        UINT64_MAX,
+                        data->askpw_flags,
+                        data->headless,
+                        &pin_used);
         if (r < 0)
                 return r;
 
@@ -1027,18 +1466,22 @@ static int list_callback(
                 void *userdata) {
 
         _cleanup_free_ char *token_uri_string = NULL, *token_label = NULL, *token_manufacturer_id = NULL, *token_model = NULL;
-        _cleanup_(p11_kit_uri_freep) P11KitUri *token_uri = NULL;
+        _cleanup_(sym_p11_kit_uri_freep) P11KitUri *token_uri = NULL;
         Table *t = userdata;
         int uri_result, r;
 
         assert(slot_info);
         assert(token_info);
 
+        r = dlopen_p11kit();
+        if (r < 0)
+                return r;
+
         /* We only care about hardware devices here with a token inserted. Let's filter everything else
          * out. (Note that the user can explicitly specify non-hardware tokens if they like, but during
          * enumeration we'll filter those, since software tokens are typically the system certificate store
          * and such, and it's typically not what people want to bind their home directories to.) */
-        if (!FLAGS_SET(token_info->flags, CKF_HW_SLOT|CKF_TOKEN_PRESENT))
+        if (!FLAGS_SET(slot_info->flags, CKF_HW_SLOT|CKF_TOKEN_PRESENT))
                 return -EAGAIN;
 
         token_label = pkcs11_token_label(token_info);
@@ -1057,9 +1500,9 @@ static int list_callback(
         if (!token_uri)
                 return log_oom();
 
-        uri_result = p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, &token_uri_string);
+        uri_result = sym_p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, &token_uri_string);
         if (uri_result != P11_KIT_URI_OK)
-                return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN), "Failed to format slot URI: %s", p11_kit_uri_message(uri_result));
+                return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN), "Failed to format slot URI: %s", sym_p11_kit_uri_message(uri_result));
 
         r = table_add_many(
                         t,
@@ -1113,13 +1556,17 @@ static int auto_callback(
                 P11KitUri *uri,
                 void *userdata) {
 
-        _cleanup_(p11_kit_uri_freep) P11KitUri *token_uri = NULL;
+        _cleanup_(sym_p11_kit_uri_freep) P11KitUri *token_uri = NULL;
         char **t = userdata;
-        int uri_result;
+        int uri_result, r;
 
         assert(slot_info);
         assert(token_info);
 
+        r = dlopen_p11kit();
+        if (r < 0)
+                return r;
+
         if (!FLAGS_SET(token_info->flags, CKF_HW_SLOT|CKF_TOKEN_PRESENT))
                 return -EAGAIN;
 
@@ -1131,9 +1578,9 @@ static int auto_callback(
         if (!token_uri)
                 return log_oom();
 
-        uri_result = p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, t);
+        uri_result = sym_p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, t);
         if (uri_result != P11_KIT_URI_OK)
-                return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN), "Failed to format slot URI: %s", p11_kit_uri_message(uri_result));
+                return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN), "Failed to format slot URI: %s", sym_p11_kit_uri_message(uri_result));
 
         return 0;
 }
@@ -1155,3 +1602,71 @@ int pkcs11_find_token_auto(char **ret) {
                                "PKCS#11 tokens not supported on this build.");
 #endif
 }
+
+#if HAVE_P11KIT
+void pkcs11_crypt_device_callback_data_release(pkcs11_crypt_device_callback_data *data) {
+        erase_and_free(data->decrypted_key);
+
+        if (data->free_encrypted_key)
+                free(data->encrypted_key);
+}
+
+int pkcs11_crypt_device_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) {
+
+        pkcs11_crypt_device_callback_data *data = ASSERT_PTR(userdata);
+        CK_OBJECT_HANDLE object;
+        int r;
+
+        assert(m);
+        assert(slot_info);
+        assert(token_info);
+        assert(uri);
+
+        /* Called for every token matching our URI */
+
+        r = pkcs11_token_login(
+                        m,
+                        session,
+                        slot_id,
+                        token_info,
+                        data->friendly_name,
+                        "drive-harddisk",
+                        "pkcs11-pin",
+                        "cryptsetup.pkcs11-pin",
+                        data->until,
+                        data->askpw_flags,
+                        data->headless,
+                        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;
+}
+#endif