libp11 icon indicating copy to clipboard operation
libp11 copied to clipboard

PKCS#11 Library Initialization - issues in multithreaded env - apache worker mode

Open Rafal77x opened this issue 1 year ago • 1 comments

When PKCS11 Lib is loaded first time following code is used - p11_load.c: int pkcs11_CTX_load(PKCS11_CTX *ctx, const char *name) { PKCS11_CTX_private *cpriv = PRIVCTX(ctx); CK_C_INITIALIZE_ARGS args; CK_INFO ck_info; int rv;

cpriv->handle = C_LoadModule(name, &cpriv->method);
if (!cpriv->handle) {
	P11err(P11_F_PKCS11_CTX_LOAD, P11_R_LOAD_MODULE_ERROR);
	return -1;
}

/* Tell the PKCS11 to initialize itself */
memset(&args, 0, sizeof(args));
/* Unconditionally say using OS locking primitives is OK */
args.flags |= CKF_OS_LOCKING_OK;
args.pReserved = cpriv->init_args;
rv = cpriv->method->C_Initialize(&args);

After fork, code below is used which calls C_Initialize in single threaded mode /*

  • Reinitialize (e.g., after a fork). */ int pkcs11_CTX_reload(PKCS11_CTX_private *ctx) { CK_C_INITIALIZE_ARGS _args; CK_C_INITIALIZE_ARGS *args = NULL; int rv;

    if (!ctx->method) /* Module not loaded */ return 0;

    /* Tell the PKCS11 to initialize itself */ if (ctx->init_args) { memset(&_args, 0, sizeof(_args)); args = &_args; args->pReserved = ctx->init_args; } rv = ctx->method->C_Initialize(args);

This impacts issuess with some PKCS11 libraries and HSMs configured with libp11 04.12, OpenSSL and apache - ie. after 1st call apache is not able to serve content - SSL error -> eror in pkcs11_private_encrypt function. Adding CKF_OS_LOCKING_OK to flags in pkcs11_CTX_reload solves the issue. Is there any reason it was not done before ?

Rafal77x avatar May 22 '23 09:05 Rafal77x

Adding CKF_OS_LOCKING_OK to flags in pkcs11_CTX_reload solves the issue. Is there any reason it was not done before ?

I don't think so. Apparently, you are the first person to notice the problem since pkcs11_CTX_reload() was added to libp11 8 years ago. Please submit a PR.

mtrojnar avatar Jun 13 '23 13:06 mtrojnar