Closed quinnwencn closed 11 months ago
The root cause is that you need to logout and log in again with a normal user, bellow is the POC that works.
#include <libp11.h>
#include <cstdio>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char** argv) {
auto ctx = PKCS11_CTX_new();
int ret = PKCS11_CTX_load(ctx, "/usr/lib/softhsm/libsofthsm2.so");
if (ret != 0) {
std::printf("can not load the pkcs11 module.\n");
return -1;
}
PKCS11_SLOT* slots {nullptr};
unsigned int slotNum {0};
ret = PKCS11_enumerate_slots(ctx, &slots, &slotNum);
if (ret != 0) {
printf("unable to enumerate the slots.\n");
return -1;
}
auto slot = PKCS11_find_token(ctx, slots, slotNum);
if (slot == nullptr) {
printf("can not find a token.\n");
return -1;
}
printf("Slot manufacturer......: %s\n", slot->manufacturer);
printf("Slot description.......: %s\n", slot->description);
printf("Slot token label.......: %s\n", slot->token->label);
printf("Slot token manufacturer: %s\n", slot->token->manufacturer);
printf("Slot token model.......: %s\n", slot->token->model);
printf("Slot token serialnr....: %s\n", slot->token->serialnr);
string soPass { "SoPass" };
string noPass { "NoPass" };
if (slot->token->initialized == 0) {
ret = PKCS11_init_token(slot->token, soPass.c_str(), "debug-token");
if (ret != 0) {
printf("init token failed: %s\n", ERR_reason_error_string(ERR_get_error()));
return -1;
}
ret = PKCS11_open_session(slot, 1);
if (ret != 0) {
printf("open so session failed: %s\n", ERR_reason_error_string(ERR_get_error()));
return -1;
}
ret = PKCS11_login(slot, 1, soPass.c_str());
if (ret != 0) {
printf("so login failed: %s\n", ERR_reason_error_string(ERR_get_error()));
return -1;
}
ret = PKCS11_init_pin(slot->token, noPass.c_str());
if (ret != 0) {
printf("init pin failed: %s\n", ERR_reason_error_string(ERR_get_error()));
return -1;
}
ret = PKCS11_logout(slot);
if (ret != 0) {
printf("so logout failed: %s\n", ERR_reason_error_string(ERR_get_error()));
return -1;
}
ret = PKCS11_open_session(slot, 1);
if (ret != 0) {
printf("open no session failed: %s\n", ERR_reason_error_string(ERR_get_error()));
return -1;
}
ret = PKCS11_login(slot, 0, noPass.c_str());
if (ret != 0) {
printf("no login failed: %s\n", ERR_reason_error_string(ERR_get_error()));
return -1;
}
}
vector<unsigned char> id { 1, 2, 3, 4, 5, 6, 7, 8};
ret = PKCS11_generate_key(slot->token, 0, 2048, "debug-rsa-key", id.data(), id.size());
if (ret != 0) {
printf("generate key failed: %s\n", ERR_reason_error_string(ERR_get_error()));
return -1;
}
PKCS11_release_all_slots(ctx, slots, slotNum);
PKCS11_CTX_unload(ctx);
PKCS11_CTX_free(ctx);
return 0;
}
Line 64 ~ 74 is missed in the initial version, so PKCS11_generate_key failed due to not log in.
After Initializing a token with so pin and no pin, I create a RSA key pair and try to store them into HSM. But it fails with Return code of pkcs11: 257, which is CKR_USER_NOT_LOGGED_IN. But I definitely log in.