HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/shared/pkcs11-util.c

86,914 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 88cdffa4b6128d0680badc0bb5f078f07a8ed062

Lines 1001–2000 of 2,140

                        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));
        }
 
        _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;
 
        r = dlopen_libcrypto(LOG_DEBUG);
        if (r < 0)
                return r;
 
        const unsigned char *ec_params_value = ec_params_attr.pValue;
        group = sym_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 = sym_EC_POINT_new(group);
        if (!point)
                return log_oom();
 
        bnctx = sym_BN_CTX_new();
        if (!bnctx)
                return log_oom();
 
        if (sym_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 = sym_EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, bnctx);
        if (compressed_point_size == 0)
                return log_openssl_errors(LOG_ERR, "Failed to determine size of a compressed EC point");
 
        compressed_point = malloc(compressed_point_size);
        if (!compressed_point)
                return log_oom();
 
        compressed_point_size = sym_EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, compressed_point, compressed_point_size, bnctx);
        if (compressed_point_size == 0)
                return log_openssl_errors(LOG_ERR, "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
 
        assert(ret_decrypted_data);
        assert(ret_decrypted_data_size);
 
        rv = m->C_GetSessionInfo(session, &session_info);
        if (rv != CKR_OK)
                return log_error_errno(SYNTHETIC_ERRNO(EIO),
                        "Failed to get information about the PKCS#11 session: %s", sym_p11_kit_strerror(rv));
 
        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 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 = 0; /* Explicit initialization to appease gcc */
                        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)
                log_warning("Failed to destroy a shared secret, ignoring: %s", sym_p11_kit_strerror(rv2));
 
        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;
}
 
static int pkcs11_token_decrypt_data_rsa(
                CK_FUNCTION_LIST *m,
                CK_SESSION_HANDLE session,
                CK_OBJECT_HANDLE object,
                const void *encrypted_data,
                size_t encrypted_data_size,
                Pkcs11RsaPadding rsa_padding,
                void **ret_decrypted_data,
                size_t *ret_decrypted_data_size) {
 
        /* For RSA-OAEP we use SHA-256 or SHA-1 with the matching MGF1 and an empty (zero-length) label.
         * SHA-256 is preferred when the token supports it, but for example SoftHSM doesn't support it. */
        CK_RSA_PKCS_OAEP_PARAMS oaep_params_sha1 = {
                .hashAlg = CKM_SHA_1,
                .mgf = CKG_MGF1_SHA1,
                .source = CKZ_DATA_SPECIFIED,
        };
        CK_RSA_PKCS_OAEP_PARAMS oaep_params_sha256 = {
                .hashAlg = CKM_SHA256,
                .mgf = CKG_MGF1_SHA256,
                .source = CKZ_DATA_SPECIFIED,
        };
        CK_MECHANISM mechanism;
        _cleanup_(erase_and_freep) CK_BYTE *dbuffer = NULL;
        CK_ULONG dbuffer_size = 0;
        CK_RV rv;
 
        assert(ret_decrypted_data);
        assert(ret_decrypted_data_size);
 
        switch (rsa_padding) {
 
        case PKCS11_RSA_PADDING_PKCS1V15:
                mechanism = (CK_MECHANISM) {
                        .mechanism = CKM_RSA_PKCS,
                };
                break;
 
        case PKCS11_RSA_PADDING_OAEP_SHA1:
                mechanism = (CK_MECHANISM) {
                        .mechanism = CKM_RSA_PKCS_OAEP,
                        .pParameter = &oaep_params_sha1,
                        .ulParameterLen = sizeof(oaep_params_sha1),
                };
                break;
 
        case PKCS11_RSA_PADDING_OAEP_SHA256:
                mechanism = (CK_MECHANISM) {
                        .mechanism = CKM_RSA_PKCS_OAEP,
                        .pParameter = &oaep_params_sha256,
                        .ulParameterLen = sizeof(oaep_params_sha256),
                };
                break;
 
        default:
                return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                       "Unknown RSA padding scheme requested for PKCS#11 decryption.");
        }
 
        rv = m->C_DecryptInit(session, &mechanism, object);
        if (rv != CKR_OK)
                return log_error_errno(SYNTHETIC_ERRNO(EIO),
                                       "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);
        if (!dbuffer)
                return log_oom();
 
        rv = m->C_Decrypt(session, (CK_BYTE*) encrypted_data, encrypted_data_size, dbuffer, &dbuffer_size);
        if (rv == CKR_BUFFER_TOO_SMALL) {
                erase_and_free(dbuffer);
 
                dbuffer = malloc(dbuffer_size);
                if (!dbuffer)
                        return log_oom();
 
                rv = m->C_Decrypt(session, (CK_BYTE*) encrypted_data, encrypted_data_size, dbuffer, &dbuffer_size);
        }
        if (rv != CKR_OK)
                return log_error_errno(SYNTHETIC_ERRNO(EIO),
                                       "Failed to decrypt key on security token: %s", sym_p11_kit_strerror(rv));
 
        log_info("Successfully decrypted key with security token (%s padding).",
                 pkcs11_rsa_padding_to_string(rsa_padding));
 
        *ret_decrypted_data = TAKE_PTR(dbuffer);
        *ret_decrypted_data_size = dbuffer_size;
        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,
                Pkcs11RsaPadding rsa_padding,
                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, rsa_padding, 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) {
 
        _cleanup_free_ void *buffer = NULL;
        size_t rps;
        CK_RV rv;
        int r;
 
        assert(m);
 
        r = dlopen_p11kit(LOG_DEBUG);
        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
         * at all? There are two sides to the argument whether to generate private keys on tokens or on the
         * host. By crediting some data from the token RNG to the host's pool we at least can say that any
         * key generated from it is at least as good as both sources individually. */
 
        rps = random_pool_size();
 
        buffer = malloc(rps);
        if (!buffer)
                return log_oom();
 
        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", sym_p11_kit_strerror(rv));
 
        r = random_write_entropy(-1, buffer, rps, false);
        if (r < 0)
                return log_debug_errno(r, "Failed to write PKCS#11 acquired random data to /dev/urandom: %m");
 
        log_debug("Successfully written %zu bytes random data acquired via PKCS#11 to kernel random pool.", rps);
 
        return 0;
}
 
static int token_process(
                CK_FUNCTION_LIST *m,
                CK_SLOT_ID slotid,
                const CK_SLOT_INFO *slot_info,
                const CK_TOKEN_INFO *token_info,
                P11KitUri *search_uri,
                pkcs11_find_token_callback_t callback,
                void *userdata) {
 
        _cleanup_free_ char *token_label = NULL;
        CK_SESSION_HANDLE session;
        CK_RV rv;
        int r;
 
        assert(m);
        assert(slot_info);
        assert(token_info);
 
        token_label = pkcs11_token_label(token_info);
        if (!token_label)
                return log_oom();
 
        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, sym_p11_kit_strerror(rv));
 
        if (callback)
                r = callback(m, session, slotid, slot_info, token_info, search_uri, userdata);
        else
                r = 1; /* if not callback was specified, just say we found what we were looking for */
 
        rv = m->C_CloseSession(session);
        if (rv != CKR_OK)
                log_warning("Failed to close session on PKCS#11 token, ignoring: %s", sym_p11_kit_strerror(rv));
 
        return r;
}
 
static int slot_process(
                CK_FUNCTION_LIST *m,
                CK_SLOT_ID slotid,
                P11KitUri *search_uri,
                pkcs11_find_token_callback_t callback,
                void *userdata) {
 
        _cleanup_(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, r;
        CK_RV rv;
 
        assert(m);
 
        r = dlopen_p11kit(LOG_DEBUG);
        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, sym_p11_kit_strerror(rv));
                return -EAGAIN;
        }
 
        slot_uri = uri_from_slot_info(&slot_info);
        if (!slot_uri)
                return log_oom();
 
        if (DEBUG_LOGGING) {
                _cleanup_free_ char *slot_uri_string = NULL;
 
                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", sym_p11_kit_uri_message(uri_result));
                        return -EAGAIN;
                }
 
                log_debug("Found slot with URI %s", slot_uri_string);
        }
 
        rv = m->C_GetTokenInfo(slotid, &token_info);
        if (rv == CKR_TOKEN_NOT_PRESENT) {
                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, sym_p11_kit_strerror(rv));
                return -EAGAIN;
        }
 
        token_uri = uri_from_token_info(&token_info);
        if (!token_uri)
                return log_oom();
 
        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", sym_p11_kit_uri_message(uri_result));
                return -EAGAIN;
        }
 
        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);
 
        log_debug("Found matching token with URI %s.", token_uri_string);
 
        return token_process(
                        m,
                        slotid,
                        &slot_info,
                        &token_info,
                        search_uri,
                        callback,
                        userdata);
}
 
static int module_process(
                CK_FUNCTION_LIST *m,
                P11KitUri *search_uri,
                pkcs11_find_token_callback_t callback,
                void *userdata) {
 
        _cleanup_(p11_kit_uri_freep) P11KitUri* module_uri = NULL;
        _cleanup_free_ char *name = NULL, *module_uri_string = NULL;
        _cleanup_free_ CK_SLOT_ID *slotids = NULL;
        CK_ULONG n_slotids = 0;
        int uri_result;
        CK_INFO info;
        size_t k;
        CK_RV rv;
        int r;
 
        assert(m);
 
        r = dlopen_p11kit(LOG_DEBUG);
        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 = sym_p11_kit_module_get_name(m);
        if (!name)
                return log_oom();
 
        log_debug("Trying PKCS#11 module %s.", name);
 
        rv = m->C_GetInfo(&info);
        if (rv != CKR_OK) {
                log_warning("Failed to get info on PKCS#11 module, ignoring module: %s", sym_p11_kit_strerror(rv));
                return -EAGAIN;
        }
 
        module_uri = uri_from_module_info(&info);
        if (!module_uri)
                return log_oom();
 
        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", sym_p11_kit_uri_message(uri_result));
                return -EAGAIN;
        }
 
        log_debug("Found module with URI %s", module_uri_string);
 
        rv = pkcs11_get_slot_list_malloc(m, &slotids, &n_slotids);
        if (rv != CKR_OK) {
                log_warning("Failed to get slot list, ignoring module: %s", sym_p11_kit_strerror(rv));
                return -EAGAIN;
        }
        if (n_slotids == 0)
                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
                                       "This module has no slots? Ignoring module.");
 
        for (k = 0; k < n_slotids; k++) {
                r = slot_process(
                                m,
                                slotids[k],
                                search_uri,
                                callback,
                                userdata);
                if (r != -EAGAIN)
                        return r;
        }
 
        return -EAGAIN;
}
 
int pkcs11_find_token(
                const char *pkcs11_uri,
                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;
        int r;
 
        r = dlopen_p11kit(LOG_DEBUG);
        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. */
 
        if (pkcs11_uri) {
                r = uri_from_string(pkcs11_uri, &search_uri);
                if (r < 0)
                        return log_error_errno(r, "Failed to parse PKCS#11 URI '%s': %m", pkcs11_uri);
        }
 
        modules = sym_p11_kit_modules_load_and_initialize(0);
        if (!modules)
                return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to initialize pkcs11 modules");
 
        for (CK_FUNCTION_LIST **i = modules; *i; i++) {
                r = module_process(
                                *i,
                                search_uri,
                                callback,
                                userdata);
                if (r != -EAGAIN)
                        return r;
        }
 
        return -EAGAIN;
}
 
#if HAVE_OPENSSL
struct pkcs11_acquire_public_key_callback_data {
        char *pin_used;
        EVP_PKEY *pkey;
        Pkcs11RsaPadding rsa_padding;
        const char *askpw_friendly_name, *askpw_icon, *askpw_credential;
        AskPasswordFlags askpw_flags;
};
 
static void pkcs11_acquire_public_key_callback_data_release(struct pkcs11_acquire_public_key_callback_data *data) {
        erase_and_free(data->pin_used);
        if (data->pkey)
                sym_EVP_PKEY_free(data->pkey);
}
 
static int pkcs11_token_try_oaep_mechanism(
                CK_FUNCTION_LIST *m,
                CK_SESSION_HANDLE session,
                CK_OBJECT_HANDLE private_key,
                CK_MECHANISM_TYPE hash_alg,
                CK_RSA_PKCS_MGF_TYPE mgf) {
 
        CK_RSA_PKCS_OAEP_PARAMS params = {
                .hashAlg = hash_alg,
                .mgf = mgf,
                .source = CKZ_DATA_SPECIFIED,
        };
        CK_MECHANISM mechanism = {
                .mechanism = CKM_RSA_PKCS_OAEP,
                .pParameter = &params,
                .ulParameterLen = sizeof(params),
        };
        CK_RV rv;
 
        rv = m->C_DecryptInit(session, &mechanism, private_key);
        if (rv != CKR_OK)
                return -EIO;
 
        /* Accepted: terminate the operation. Per PKCS#11 spec section 5.2 any cryptographic function
         * returning an error other than CKR_BUFFER_TOO_SMALL terminates the active operation, so feed
         * deliberately invalid (too-short) ciphertext to C_Decrypt to trigger a cancellation that's
         * likely to be portable across token implementations. */
        CK_BYTE in[1] = {};
        CK_BYTE out[1];
        CK_ULONG out_len = sizeof(out);
        (void) m->C_Decrypt(session, in, sizeof(in), out, &out_len);
 
        return 0;
}
 
static int pkcs11_token_probe_rsa_oaep_padding(
                CK_FUNCTION_LIST *m,
                CK_SESSION_HANDLE session,
                CK_OBJECT_HANDLE private_key,
                Pkcs11RsaPadding *ret) {
 
        CK_KEY_TYPE key_type;
        CK_ATTRIBUTE key_type_template = { CKA_KEY_TYPE, &key_type, sizeof(key_type) };
        CK_RV rv;
        int r;
 
        assert(m);
        assert(ret);
 
        /* Probes whether the token will accept the OAEP-SHA256 or OAEP-SHA1 mechanism for decryption with
         * the given private key. On any failure (wrong key type, related-object lookup ambiguity yielded
         * an EC private key, both mechanisms rejected, etc.) we bail out, this can only be best-effort. */
        rv = m->C_GetAttributeValue(session, private_key, &key_type_template, /* ulCount= */ 1);
        if (rv != CKR_OK)
                return log_debug_errno(SYNTHETIC_ERRNO(EIO),
                                       "Failed to retrieve private key type: %s", sym_p11_kit_strerror(rv));
        if (key_type != CKK_RSA)
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                       "Located private key is not RSA, skipping OAEP padding probe.");
 
        /* For RSA-OAEP we use SHA-256 or SHA-1 with the matching MGF1 and an empty (zero-length) label.
         * SHA-256 is preferred when the token supports it, but for example SoftHSM doesn't support it, so
         * fall back to SHA-1 if it gets rejected. */
        r = pkcs11_token_try_oaep_mechanism(m, session, private_key, CKM_SHA256, CKG_MGF1_SHA256);
        if (r >= 0) {
                *ret = PKCS11_RSA_PADDING_OAEP_SHA256;
                log_debug("Token accepts OAEP-SHA256 for decryption.");
                return 0;
        }
 
        r = pkcs11_token_try_oaep_mechanism(m, session, private_key, CKM_SHA_1, CKG_MGF1_SHA1);
        if (r >= 0) {
                *ret = PKCS11_RSA_PADDING_OAEP_SHA1;
                log_debug("Token accepts OAEP-SHA1 for decryption.");
                return 0;
        }
 
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Token rejected both OAEP-SHA256 and OAEP-SHA1.");
}
 
static int pkcs11_acquire_public_key_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) {
 
        _cleanup_(erase_and_freep) char *pin_used = NULL;
        _cleanup_(EVP_PKEY_freep) EVP_PKEY *pkey = NULL;
        CK_OBJECT_CLASS class;
        CK_CERTIFICATE_TYPE type;
        CK_ATTRIBUTE candidate_attributes[] = {
                { CKA_CLASS,            &class,   sizeof(class) },
                { CKA_CERTIFICATE_TYPE, &type,    sizeof(type)  },
        };
        CK_OBJECT_HANDLE candidate, public_key = CK_INVALID_HANDLE, certificate = CK_INVALID_HANDLE;
        uint8_t n_public_keys = 0, n_certificates = 0;
        CK_RV rv;
        int r;
 
        assert(m);
        assert(slot_info);
        assert(token_info);
        assert(uri);
 
        struct pkcs11_acquire_public_key_callback_data *data = ASSERT_PTR(userdata);
 
        /* Called for every token matching our URI */
 
        r = pkcs11_token_login(
                        m,
                        session,
                        slot_id,
                        token_info,
                        data->askpw_friendly_name,
                        data->askpw_icon,
                        "pkcs11-pin",
                        data->askpw_credential,
                        UINT64_MAX,
                        data->askpw_flags,
                        &pin_used);
        if (r < 0)
                return r;
 
        CK_ULONG n_attributes;
        CK_ATTRIBUTE *attributes = sym_p11_kit_uri_get_attributes(uri, &n_attributes);
        for (CK_ULONG i = 0; i < n_attributes; i++) {
                switch (attributes[i].type) {
                case CKA_CLASS: {
                        CK_OBJECT_CLASS requested_class = *((CK_OBJECT_CLASS*) attributes[i].pValue);
                        if (!IN_SET(requested_class, CKO_PUBLIC_KEY, CKO_CERTIFICATE))
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                       "Selected PKCS#11 object is not a public key or certificate, refusing.");
                        break;
                }
 
                case CKA_CERTIFICATE_TYPE: {
                        CK_CERTIFICATE_TYPE requested_type = *((CK_CERTIFICATE_TYPE*) attributes[i].pValue);
                        if (requested_type != CKC_X_509)
                                return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Selected PKCS#11 object is not an X.509 certificate, refusing.");
                        break;
                }}
        }
 
        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));
 
        for (;;) {
                CK_ULONG n;
                rv = m->C_FindObjects(session, &candidate, 1, &n);
                if (rv != CKR_OK)
                        return log_error_errno(SYNTHETIC_ERRNO(EIO),
                                "Failed to find objects: %s", sym_p11_kit_strerror(rv));
 
                if (n == 0)
                        break;
 
                candidate_attributes[0].ulValueLen = sizeof(class);
                candidate_attributes[1].ulValueLen = sizeof(type);
                rv = m->C_GetAttributeValue(session, candidate, candidate_attributes, ELEMENTSOF(candidate_attributes));
                if (!IN_SET(rv, CKR_OK, CKR_ATTRIBUTE_TYPE_INVALID))
                        return log_error_errno(SYNTHETIC_ERRNO(EIO),
                                "Failed to get attributes of a selected candidate: %s", sym_p11_kit_strerror(rv));
 
                if (candidate_attributes[0].ulValueLen == CK_UNAVAILABLE_INFORMATION) {
                        log_debug("Failed to get CKA_CLASS of a selected candidate");
                        continue;
                }
 
                if (class == CKO_PUBLIC_KEY) {
                        n_public_keys++;
                        if (n_public_keys > 1)
                                break;
                        public_key = candidate;
                        continue;
                }
 
                if (class == CKO_CERTIFICATE) {
                        if (candidate_attributes[1].ulValueLen == CK_UNAVAILABLE_INFORMATION) {
                                log_debug("Failed to get CKA_CERTIFICATE_TYPE of a selected candidate");
                                continue;
                        }
                        if (type != CKC_X_509)
                                continue;
                        n_certificates++;
                        if (n_certificates > 1)
                                break;
                        certificate = candidate;
                        continue;
                }
        }
 
        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 (n_public_keys == 0 && n_certificates == 0)
                return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
                        "Failed to find selected public key or X.509 certificate.");
 
        if (n_public_keys > 1)
                return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
                        "Provided URI matches multiple public keys, refusing.");
 
        if (n_certificates > 1)
                return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
                        "Provided URI matches multiple certificates, refusing.");
 
        if (n_public_keys != 0) {
                r = pkcs11_token_read_public_key(m, session, public_key, &pkey);
                if (r >= 0)
                        goto success;
        }
 
        if (n_certificates == 0)
                return log_error_errno(r, "Failed to read a found public key.");
 
        {
                _cleanup_(X509_freep) X509 *cert = NULL;
 
                r = pkcs11_token_read_x509_certificate(m, session, certificate, &cert);
                if (r < 0)
                        return log_error_errno(r, "Failed to read a found X.509 certificate.");
 
                r = dlopen_libcrypto(LOG_DEBUG);
                if (r < 0)
                        return r;
 
                pkey = sym_X509_get_pubkey(cert);
                if (!pkey)
                        return log_openssl_errors(LOG_ERR, "Failed to extract public key from X.509 certificate.");
        }
success:
        /* Let's read some random data off the token and write it to the kernel pool before we generate our
         * random key from it. This way we can claim the quality of the RNG is at least as good as the
         * kernel's and the token's pool */
        (void) pkcs11_token_acquire_rng(m, session);
 
        /* Decide whether the enrolled key needs RSA padding metadata at all based on the public key we
         * extracted (RSA vs EC). For RSA, default to OAEP-SHA1 which works on all known tokens (e.g.
         * SoftHSM only accepts SHA-1), then try to upgrade to OAEP-SHA256 by probing the matching private
         * key on the token. The probe is best-effort: if we cannot find the private key (e.g. token holds
         * only the certificate, or the related-object lookup is ambiguous because CKA_ID is missing or
         * doesn't match) we keep the OAEP-SHA1 default. For non-RSA keys (EC) we leave rsa_padding as
         * _INVALID, so no padding tag is recorded and the decrypt path uses ECDH instead. */
        data->rsa_padding = _PKCS11_RSA_PADDING_INVALID;
 
        if (sym_EVP_PKEY_get_base_id(pkey) == EVP_PKEY_RSA) {
                CK_OBJECT_HANDLE prototype = public_key != CK_INVALID_HANDLE ? public_key : certificate;
                CK_OBJECT_HANDLE private_key = CK_INVALID_HANDLE;
                Pkcs11RsaPadding padding = PKCS11_RSA_PADDING_OAEP_SHA1; /* default to SHA1 unless we can do better */
 
                if (pkcs11_token_find_related_object(m, session, prototype, CKO_PRIVATE_KEY, &private_key) >= 0) {
                        r = pkcs11_token_probe_rsa_oaep_padding(m, session, private_key, &padding);
                        if (r < 0)
                                log_info_errno(r, "Token rejected both OAEP-SHA256 and OAEP-SHA1, defaulting RSA enrollment to OAEP-SHA1.");
                } else
                        log_info("No matching PKCS#11 private key found, OAEP padding probe skipped, defaulting RSA enrollment to OAEP-SHA1.");
 
                data->rsa_padding = padding;
        }
 
        data->pin_used = TAKE_PTR(pin_used);
        data->pkey = TAKE_PTR(pkey);
        return 0;
}
 
int pkcs11_acquire_public_key(
                const char *uri,
                const char *askpw_friendly_name,
                const char *askpw_icon,
                const char *askpw_credential,
                AskPasswordFlags askpw_flags,
                EVP_PKEY **ret_pkey,
                Pkcs11RsaPadding *ret_rsa_padding,
                char **ret_pin_used) {
 
        _cleanup_(pkcs11_acquire_public_key_callback_data_release) struct pkcs11_acquire_public_key_callback_data data = {
                .askpw_friendly_name = askpw_friendly_name,
                .askpw_icon = askpw_icon,
                .askpw_credential = askpw_credential,
                .askpw_flags = askpw_flags,
                .rsa_padding = _PKCS11_RSA_PADDING_INVALID,
        };
        int r;
 
        assert(uri);
        assert(ret_pkey);
 
        r = pkcs11_find_token(uri, pkcs11_acquire_public_key_callback, &data);
        if (r == -EAGAIN) /* pkcs11_find_token() doesn't log about this error, but all others */
                return log_error_errno(SYNTHETIC_ERRNO(ENXIO),
                                       "Specified PKCS#11 token with URI '%s' not found.",
                                       uri);
        if (r < 0)
                return r;
 
        *ret_pkey = TAKE_PTR(data.pkey);
        if (ret_rsa_padding)
                *ret_rsa_padding = data.rsa_padding;
        if (ret_pin_used)
                *ret_pin_used = TAKE_PTR(data.pin_used);
        return 0;
}
#endif
 
static int list_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) {
 
        _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;
        Table *t = userdata;
        int uri_result, r;
 
        assert(slot_info);
        assert(token_info);
 
        r = dlopen_p11kit(LOG_DEBUG);
        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(slot_info->flags, CKF_HW_SLOT|CKF_TOKEN_PRESENT))
                return -EAGAIN;
 
        token_label = pkcs11_token_label(token_info);
        if (!token_label)
                return log_oom();
 
        token_manufacturer_id = pkcs11_token_manufacturer_id(token_info);
        if (!token_manufacturer_id)
                return log_oom();
 
        token_model = pkcs11_token_model(token_info);
        if (!token_model)
                return log_oom();
 
        token_uri = uri_from_token_info(token_info);
        if (!token_uri)
                return log_oom();
 
        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", sym_p11_kit_uri_message(uri_result));
 
        r = table_add_many(
                        t,
                        TABLE_STRING, token_uri_string,
                        TABLE_STRING, token_label,
                        TABLE_STRING, token_manufacturer_id,
                        TABLE_STRING, token_model);
        if (r < 0)
                return table_log_add_error(r);
 
        return -EAGAIN; /* keep scanning */
}
#endif
 
int dlopen_p11kit(int log_level) {
#if HAVE_P11KIT
        static void *p11kit_dl = NULL;
 
        LIBP11KIT_NOTE(suggested);
 
        return dlopen_many_sym_or_warn(
                        &p11kit_dl,
                        "libp11-kit.so.0", log_level,
                        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_attribute),
                        DLSYM_ARG(p11_kit_uri_set_attribute),
                        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));
#else
        return log_full_errno(log_level, SYNTHETIC_ERRNO(EOPNOTSUPP),
                              "libp11-kit support is not compiled in.");
#endif
}
 
int pkcs11_list_tokens(void) {
#if HAVE_P11KIT
        _cleanup_(table_unrefp) Table *t = NULL;
        int r;
 
        t = table_new("uri", "label", "manufacturer", "model");
        if (!t)
                return log_oom();
 
        r = pkcs11_find_token(NULL, list_callback, t);