OpenSC / libp11

PKCS#11 wrapper library
GNU Lesser General Public License v2.1
310 stars 189 forks source link

[engine] ctx_load_privkey lists all the private keys on the token when an ID is provided #512

Closed nponsard closed 1 year ago

nponsard commented 1 year ago

I noticed that when I try to use a private key using the OpenSSL engine, all private keys of the PKCS11 token gets read (only some attributes) even when a label (object=) or id is provided.

This would be more efficient if those attributes are set in the template of C_FindObjectsInit, then the engine would have to read less attributes. This would greatly improve the startup time of programs like Nginx when using a token with thousands of keys.

Do you think this would be possible ?

jans23 commented 1 year ago

@frankmorgner Any thoughts on this one?

frankmorgner commented 1 year ago

Yes, possible.

look at eng_back.c, which implements match_private_key by

  1. enumerate all keys (PKCS11_enumerate_keys) and then
  2. matching it against the required attributes (match_key).

I think the call to PKCS11_enumerate_keys should be the expensive one which limits C_FindObjectsInit to only private keys. You need to reverse the order, i.e. you need to pass the relevant attributes from the matching key to the key enumeration. Note, that p11_key.c already has pkcs11_object_from_template for refining the call to C_FindObjectsInit.

Before implementing, I recommend to set a breakpoint at the most expensive PKCS11 calls to analyze the stack trace. This may bring up some other locations that need to be adjusted.

nponsard commented 1 year ago

Turns out on master this change has already been made in 21209b117bd0c0e96d27f2ea16a6b0940d4af7c0, I was looking at the 0.4.12 tag.