IAIK PKCS#11 Wrapper 1.4 with NSS 3.47.1

137 views
Skip to first unread message

Usha Nayak

unread,
Dec 9, 2019, 4:58:23 PM12/9/19
to dev-se...@lists.mozilla.org
Hello

Our application connects to software security plugin like NSS via PKCS#11
IAIK Wrapper 1.4. We had no issue when IAIK1.4 was connecting with NSS
3.42.1. However, we are upgrading NSS to 3.47.1 and we are encountering
issues with keypair generation. (above NSS 3.43 seems to be an issue)

Below is the excerpt of code for KeyPair generation :

public KeyPairHandle generateWrappingKeyPair(String component) throws
Exception
{
// This function returns the public key handle only
// Minimum key size is 2048-bit
int keySize = 2048;
Mechanism keyPairGenerationMechanism = Mechanism
.get(PKCS11Constants.CKM_RSA_PKCS_KEY_PAIR_GEN);

RSAPublicKey rsaPublicKeyTemplate = new RSAPublicKey();
RSAPrivateKey rsaPrivateKeyTemplate = new RSAPrivateKey();

String id = KeyPairHandleImpl.generateId();

rsaPublicKeyTemplate.getId().setByteArrayValue(id.getBytes(StandardCharsets.UTF_8));

rsaPrivateKeyTemplate.getId().setByteArrayValue(id.getBytes(StandardCharsets.UTF_8));

// set the general attributes for the public key
//
rsaPublicKeyTemplate.getModulusBits().setLongValue(new
Long(keySize));
byte[] publicExponentBytes = { (byte)0x01, (byte)0x00, (byte)0x01 };

rsaPublicKeyTemplate.getPublicExponent().setByteArrayValue(publicExponentBytes);
rsaPublicKeyTemplate.getToken().setBooleanValue(Boolean.TRUE);
rsaPublicKeyTemplate.getLabel().setValue(component.toCharArray());
rsaPublicKeyTemplate.getEncrypt().setBooleanValue(Boolean.TRUE);
rsaPublicKeyTemplate.getWrap().setBooleanValue(Boolean.TRUE);
rsaPublicKeyTemplate.getVerify().setBooleanValue(Boolean.TRUE);

// set the general attributes for the private key
//
rsaPrivateKeyTemplate.getSensitive().setBooleanValue(Boolean.TRUE);
rsaPrivateKeyTemplate.getToken().setBooleanValue(Boolean.TRUE);
rsaPrivateKeyTemplate.getPrivate().setBooleanValue(Boolean.FALSE);
rsaPrivateKeyTemplate.getLabel().setValue(component.toCharArray());
rsaPrivateKeyTemplate.getDecrypt().setBooleanValue(Boolean.TRUE);
rsaPrivateKeyTemplate.getUnwrap().setBooleanValue(Boolean.TRUE);
rsaPrivateKeyTemplate.getSign().setBooleanValue(Boolean.TRUE);

KeyPair generatedKeyPair;
try
{
generatedKeyPair =
session.generateKeyPair(keyPairGenerationMechanism,
rsaPublicKeyTemplate, rsaPrivateKeyTemplate);
}
catch (TokenException e)
{
String msg = "Failed to generate RSA key pair on token: " +
e.getMessage();
log.error( msg );
throw new XXException( msg, e );
}

We get below exception:
iaik.pkcs.pkcs11.wrapper.PKCS11Exception: CKR_GENERAL_ERROR

I establish session with the NSS via IAIK wrapper fine:

Slot :
Slot ID: 0x2
Module: Module Name: softokn3.dll

Token info:
Label: NSS Certificate DB
Manufacturer ID: Mozilla Foundation
Model: NSS 3
Serial Number: 0000000000000000
Random Number Generator: true
Write protected: false
Login required: true
User PIN initialized: true
Restore Key not needed: false
Clock on Token: false
Protected Authentication Path: false
Dual Crypto Operations: true
Token initialized: true
Secondary Authentication: false
User PIN-Count low: false
User PIN final Try: false
User PIN locked: false
User PIN to be changed: false
Security Officer PIN-Count low: false
Security Officer PIN final Try: false
Security Officer PIN locked: false
Security Officer PIN to be changed: false
Maximum Session Count: <effectively infinite>
Session Count: 0
Maximum Read/Write Session Count: <effectively infinite>
Read/Write Session Count: 0
Maximum PIN Length: 500
Minimum PIN Length: 0
Total Public Memory: 1
Free Public Memory: 1
Total Private Memory: 1
Free Private Memory: 1
Hardware Version: 0.00
Firmware Version: 0.00
Time: Sat Nov 29 18:00:00 CST 2


capturing information of the variables :
rsaPublicKeyTemplate info:
Object Class: Public Key
Token: true
Private: <Attribute not present>
Modifiable: <Attribute not present>
Label: XXX
Key Type: RSA
ID:
64626639363437362d313639302d343766642d393161392d6433623138346134613135323b31353735393138303336323139
Start Date: <Attribute not present>
End Date: <Attribute not present>
Derive: <Attribute not present>
Local: <Attribute not present>
Key Generation Mechanism: <Attribute not present>
Allowed Mechanisms: <Attribute not present>
Subject (DER, hex): <Attribute not present>
Encrypt: true
Verify: true
Verify Recover: <Attribute not present>
Wrap: true
Trusted: <Attribute not present>
Wrap Template: <Attribute not present>
Modulus (hex): <Attribute not present>
Public Exponent (hex): 010001
Modulus Bits (dec): 2048

rsaPrivateKeyTemplate info:
Object Class: Private Key
Token: true
Private: false
Modifiable: <Attribute not present>
Label: XXX
Key Type: RSA
ID:
64626639363437362d313639302d343766642d393161392d6433623138346134613135323b31353735393138303336323139
Start Date: <Attribute not present>
End Date: <Attribute not present>
Derive: <Attribute not present>
Local: <Attribute not present>
Key Generation Mechanism: <Attribute not present>
Allowed Mechanisms: <Attribute not present>
Subject (DER, hex): <Attribute not present>
Sensitive: true
Secondary Authentication: <Attribute not present>
Secondary Authentication PIN Flags: <Attribute not present>
Decrypt: true
Sign: true
Sign Recover: <Attribute not present>
Unwrap: true
Extractable: <Attribute not present>
Always Sensitive: <Attribute not present>
Never Extractable: <Attribute not present>
Wrap With Trusted: <Attribute not present>
Unwrap Template: <Attribute not present>
Always Authenticate: <Attribute not present>
Modulus (hex): <Attribute not present>
Public Exponent (hex): <Attribute not present>
Private Exponent (hex): <Attribute not present>
Prime 1 (hex): <Attribute not present>
Prime 2 (hex): <Attribute not present>
Exponent 1 (hex): <Attribute not present>
Exponent 2 (hex): <Attribute not present>
Coefficient (hex): <Attribute not present>

I can create keypair fine using NSS tool certutil but can't do so via our
application.

Is there a compatibility issue by any chance ?

Any help greatly appreciated.

Thanks..
Usha

jjo...@mozilla.com

unread,
Dec 17, 2019, 12:34:25 PM12/17/19
to mozilla-de...@lists.mozilla.org
On Monday, December 9, 2019 at 2:58:23 PM UTC-7, Usha Nayak wrote:
> Any help greatly appreciated.

Hi Usha,

We've talked about this a couple times now and two of us have searched our change history without finding any obvious culprits. I think we're going to need a minimal case we can run locally to reproduce the issue, and then attach a debugger to make any progress. Is that possible to do?

Thanks,
J.C.

Usha Nayak

unread,
Jan 20, 2020, 5:22:19 PM1/20/20
to jjo...@mozilla.com, mozilla-de...@lists.mozilla.org
Hi All,

We were able to build NSS-3.49 on Windows and reproduce the issue with the
sample testclient:

java.lang.Exception: Failed to generate RSA key pair on token:
CKR_GENERAL_ERROR

at GenerateKeyPair.main(GenerateKeyPair.java:274)

Caused by: iaik.pkcs.pkcs11.wrapper.PKCS11Exception: CKR_GENERAL_ERROR

at
iaik.pkcs.pkcs11.wrapper.PKCS11Implementation.C_GetAttributeValue(Native
Method)

at
iaik.pkcs.pkcs11.objects.Object.getAttributeValue(Object.java:716)

at iaik.pkcs.pkcs11.objects.Key.readAttributes(Key.java:622)

at
iaik.pkcs.pkcs11.objects.PublicKey.readAttributes(PublicKey.java:398)

at
iaik.pkcs.pkcs11.objects.RSAPublicKey.readAttributes(RSAPublicKey.java:242)

at iaik.pkcs.pkcs11.objects.Object.<init>(Object.java:223)

at iaik.pkcs.pkcs11.objects.Storage.<init>(Storage.java:105)

at iaik.pkcs.pkcs11.objects.Key.<init>(Key.java:321)

at iaik.pkcs.pkcs11.objects.PublicKey.<init>(PublicKey.java:119)

at
iaik.pkcs.pkcs11.objects.RSAPublicKey.<init>(RSAPublicKey.java:96)

at
iaik.pkcs.pkcs11.objects.RSAPublicKey.getInstance(RSAPublicKey.java:118)

at
iaik.pkcs.pkcs11.objects.PublicKey.getInstance(PublicKey.java:156)

at iaik.pkcs.pkcs11.objects.Object.getInstance(Object.java:262)

at iaik.pkcs.pkcs11.Session.generateKeyPair(Session.java:1260)

at demo.pkcs.pkcs11.GenerateKeyPair.main(GenerateKeyPair.java:269)

################################################################################



Below is an excerpt of the sample client that connects to NSS via IAIK
PKCS#11 Wrapper :


public static void main(String[] args) {


String pkcs11NSSPropertiesFilePath = args[0];

Module pkcs11Module = null;
Session session = null;

try {

Properties config = loadKeyPkcs11Config(
pkcs11NSSPropertiesFilePath );
pkcs11Module = initializeModule( config );
session = getSession( config, pkcs11Module );



System.out.println("################################################################################");
System.out.println("Generating new 2048 bit RSA key-pair... ");

String component = "KMRootCA";
int keySize = 2048;

Mechanism keyPairGenerationMechanism =
Mechanism.get(PKCS11Constants.CKM_RSA_PKCS_KEY_PAIR_GEN);

RSAPublicKey rsaPublicKeyTemplate = new RSAPublicKey();
RSAPrivateKey rsaPrivateKeyTemplate = new RSAPrivateKey();

String id = generateId();

rsaPublicKeyTemplate.getId().setByteArrayValue(id.getBytes(StandardCharsets.UTF_8));

rsaPrivateKeyTemplate.getId().setByteArrayValue(id.getBytes(StandardCharsets.UTF_8));

// set the general attributes for the public key
throw new Exception( msg, e );
}

......

It looks like when we create token objects as highlighted above, we see the
exception. But, if we modify the code to not create token objects ( as
shown below ) everything looks good. Please note this was not an issue in
3.42.1 NSS version.

rsaPublicKeyTemplate.getToken().setBooleanValue(Boolean.TRUE);
....
rsaPrivateKeyTemplate.getToken().setBooleanValue(Boolean.TRUE);


Output :
################################################################################
Information of Token:
################################################################################
PKCS#11 session login successful
################################################################################
Generating new 2048 bit RSA key-pair...
################################################################################
Output KeyPair...
The public key is
_______________________________________________________________________________
Object Class: Public Key
Token: false
Private: false
Modifiable: true
Label: KMRootCA
Key Type: RSA
ID:
39616130393234332d643635312d343835662d613430632d6164613936343365323434653b31353739353437363034343534
Start Date: <NULL_PTR>
End Date: <NULL_PTR>
Derive: false
Local: false
Key Generation Mechanism: <Attribute not present>
Allowed Mechanisms: <Attribute not present>
Subject (DER, hex): <NULL_PTR>
Encrypt: true
Verify: true
Verify Recover: true
Wrap: true
Trusted: <Attribute not present>
Wrap Template: <Attribute not present>
Modulus (hex):
d5a3c3265e3fa3be258565fab165ac9f694dab04b79eee4e749870a6e0b9251267855fe72aa8bd21fac910336a07cf710a533a7681657e25869260bee261b3b67c7a7706fdb43a50d311213e48a488958c8d77873889fbfa8cbf0b4476ed7cee78aebd195b241da986750f4099d6849b872e2d08953a4ba4c1583ebfcbde614e8601d99c31d384c7ea9735e986f913cf9691b2e6868031999ac01e6a85712a9af94ac589c6c79e7e8246ff8aed45eb46d14c916549a35299a0a7621f45a94d54b0d1fdee80972a514216063aef6f59326a27bf0695f01592a1c7382d1beadf8c81dde13d20b18324ddce62627baa95028a04ddd1a4928cc5a5b4bf0db15fc3d7
Public Exponent (hex): 010001
Modulus Bits (dec): <Attribute not present>
_______________________________________________________________________________
The private key is
_______________________________________________________________________________
Object Class: Private Key
Token: false
Private: true
Modifiable: true
Label: KMRootCA
Key Type: RSA
ID:
39616130393234332d643635312d343835662d613430632d6164613936343365323434653b31353739353437363034343534
Start Date: <NULL_PTR>
End Date: <NULL_PTR>
Derive: false
Local: false
Key Generation Mechanism: <Attribute not present>
Allowed Mechanisms: <Attribute not present>
Subject (DER, hex): <NULL_PTR>
Sensitive: true
Secondary Authentication: <Attribute not present>
Secondary Authentication PIN Flags: <Attribute not present>
Decrypt: true
Sign: true
Sign Recover: true
Unwrap: true
Extractable: true
Always Sensitive: true
Never Extractable: false
Wrap With Trusted: <Attribute not present>
Unwrap Template: <Attribute not present>
Always Authenticate: <Attribute not present>
Modulus (hex):
d5a3c3265e3fa3be258565fab165ac9f694dab04b79eee4e749870a6e0b9251267855fe72aa8bd21fac910336a07cf710a533a7681657e25869260bee261b3b67c7a7706fdb43a50d311213e48a488958c8d77873889fbfa8cbf0b4476ed7cee78aebd195b241da986750f4099d6849b872e2d08953a4ba4c1583ebfcbde614e8601d99c31d384c7ea9735e986f913cf9691b2e6868031999ac01e6a85712a9af94ac589c6c79e7e8246ff8aed45eb46d14c916549a35299a0a7621f45a94d54b0d1fdee80972a514216063aef6f59326a27bf0695f01592a1c7382d1beadf8c81dde13d20b18324ddce62627baa95028a04ddd1a4928cc5a5b4bf0db15fc3d7
Public Exponent (hex): 010001
Private Exponent (hex): <Value is sensitive>
Prime 1 (hex): <Value is sensitive>
Prime 2 (hex): <Value is sensitive>
Exponent 1 (hex): <Value is sensitive>
Exponent 2 (hex): <Value is sensitive>
Coefficient (hex): <Value is sensitive>
_____________________________________________


Would appreciate help ...

Thanks..
Usha
> _______________________________________________
> dev-security mailing list
> dev-se...@lists.mozilla.org
> https://lists.mozilla.org/listinfo/dev-security
>

Usha Nayak

unread,
Jan 21, 2020, 9:01:56 AM1/21/20
to mozilla-de...@lists.mozilla.org
Correction ...

Client executes succcessfully if public/private keypairs are created as session objects :

rsaPublicKeyTemplate.getToken().setBooleanValue(Boolean.FALSE);
....

rsaPrivateKeyTemplate.getToken().setBooleanValue(Boolean.FALSE);

Exception occurs if they are created as token objects:

rsaPublicKeyTemplate.getToken().setBooleanValue(Boolean.TRUE);
....

rsaPrivateKeyTemplate.getToken().setBooleanValue(Boolean.TRUE);

NOTE: This issue started to occur after we upgraded NSS from 3.42.1 to 3.47.1. Sample client was using NSS 3.49 ( same behavior ) .

Thanks..

Usha Nayak

unread,
Jan 28, 2020, 6:01:19 PM1/28/20
to mozilla-de...@lists.mozilla.org
Hello,

Adding few more details to this issue we are facing in regards to NSS.
Please note: this was not an issue with NSS3.42.1. We are looking to upgrade to NSS3.47.1 and have noticed it from then on. We approached IAIK aswell in regards to this after debugging their pkcs#11wrapper module. Please see their response at the below of the post.

We created sample Java client that uses IAIK PKCS#11 Wrapper 1.4 to connect to NSS

Module pkcs11Module = Module.getInstance( library ); // library -> softokn3.dll
.....
pkcs11Module.initialize(arguments); // arguments -> maps to initializeArguments
....
session = token.openSession(Token.SessionType.SERIAL_SESSION, Token.SessionReadWriteBehavior.RW_SESSION, null, null);
...
session.login(Session.UserType.USER, pin.toCharArray()); // login is fine
...

// set the general attributes for the public key
rsaPublicKeyTemplate.getToken().setBooleanValue(Boolean.TRUE); /// this is source of problem . If set to False ( meaning session object), client works fine.
...

// set the general attributes for the private key
rsaPrivateKeyTemplate.getToken().setBooleanValue(Boolean.TRUE); /// this is source of problem . If set to False ( meaning session object), client works fine.
....

KeyPair generatedKeyPair = null;
try
{
generatedKeyPair = session.generateKeyPair(keyPairGenerationMechanism,rsaPublicKeyTemplate, rsaPrivateKeyTemplate);
}
catch (TokenException e)
{
String msg = "Failed to generate RSA key pair on token: " + e.getMessage();
throw new Exception( msg, e );
}
...

Input file for the sample client :
library=softokn3.dll

initializeArguments=configDir='sql:D:/workdir/devunit/KMDemo/NSS/db' certPrefix='' keyPrefix='' secmod='' flags='readWrite' updatedir='' updateCertPrefix='' updateKeyPrefix='' updateTokenDescription=''

pin=XXXXX

slot=1

libPath=D:/workdir/devunit/KMDemo/NSS-3.49/lib

libList=libnspr4.dll,libplc4.dll,libplds4.dll,sqlite3.dll,nssutil3.dll,softokn3.dll


Steps I've been following ::

1) I cleanup NSS db directory.
2) Prior to executing the client code, I recreate the NSS db.
a) Create NSS db ---> modutil -create -dbdir sql:D:\workdir\devunit\KMDemo\NSS\db
b) Provide password ---> modutil -dbdir sql:D:\workdir\devunit\KMDemo\NSS\db -changepw "NSS Certificate DB"
c) Check content of the db --> certutil -K -d sql:D:\workdir\devunit\KMDemo\NSS\db ( displays no keys )
3) Run the Sample client code. Saw exception
################################################################################
PKCS#11 session login successful
################################################################################
Generating new 2048 bit RSA key-pair...
java.lang.Exception: Failed to generate RSA key pair on token: CKR_GENERAL_ERROR
at demo.pkcs.pkcs11.GenerateKeyPair.main(GenerateKeyPair.java:110)
Caused by: iaik.pkcs.pkcs11.wrapper.PKCS11Exception: CKR_GENERAL_ERROR
at iaik.pkcs.pkcs11.wrapper.PKCS11Implementation.C_GetAttributeValue(Native Method)
at iaik.pkcs.pkcs11.objects.Object.getAttributeValue(Object.java:716)
at iaik.pkcs.pkcs11.objects.Key.readAttributes(Key.java:622)
at iaik.pkcs.pkcs11.objects.PublicKey.readAttributes(PublicKey.java:398)
at iaik.pkcs.pkcs11.objects.RSAPublicKey.readAttributes(RSAPublicKey.java:242)
at iaik.pkcs.pkcs11.objects.Object.<init>(Object.java:223)
at iaik.pkcs.pkcs11.objects.Storage.<init>(Storage.java:105)
at iaik.pkcs.pkcs11.objects.Key.<init>(Key.java:321)
at iaik.pkcs.pkcs11.objects.PublicKey.<init>(PublicKey.java:119)
at iaik.pkcs.pkcs11.objects.RSAPublicKey.<init>(RSAPublicKey.java:96)
at iaik.pkcs.pkcs11.objects.RSAPublicKey.getInstance(RSAPublicKey.java:118)
at iaik.pkcs.pkcs11.objects.PublicKey.getInstance(PublicKey.java:156)
at iaik.pkcs.pkcs11.objects.Object.getInstance(Object.java:262)
at iaik.pkcs.pkcs11.Session.generateKeyPair(Session.java:1260)
at demo.pkcs.pkcs11.GenerateKeyPair.main(GenerateKeyPair.java:105)
################################################################################
Close Session...
PKCS#11 session logout successful

4) Check the NSS key db store for the contents:
D:\workdir\devunit\KMDemo>certutil -K -d sql:D:\workdir\devunit\KMDemo\NSS\db
certutil: Checking token "NSS Certificate DB" in slot "NSS User Private Key and Certificate Services"
Enter Password or Pin for "NSS Certificate DB":
< 0> rsa "60b0df57-df82-4a73-b1c9-7fc17204e1d0;157" KMRootCA

NOTE: I see the exception in the console as well as notice that NSS store having the key.


Debugged IAIK:
• Enabled debugging of IAIK PKCS#11 Wrapper module.

01/23/20 19:38:18 ERROR: got 5 instead of CKR_OK, going to raise an exception (in Java_iaik_pkcs_pkcs11_wrapper_PKCS11Implementation_C_1GetAttributeValue)

• I decided to build/debug the native pkcs11Wrapper code with the Java sample client.

JNIEXPORT void JNICALL Java_iaik_pkcs_pkcs11_wrapper_PKCS11Implementation_C_1GetAttributeValue
(JNIEnv *env, jobject obj, jlong jSessionHandle, jlong jObjectHandle, jobjectArray jTemplate, jboolean jUseUtf8)
{
.....
rv = (*ckpFunctions->C_GetAttributeValue)(ckSessionHandle, ckObjectHandle, ckpAttributes, ckAttributesLength);
...

}
Values in the variable when this failure occurred ..

rv = 5

+ ckpAttributes 0x0000000017e7cb00 {type=1073742353 pValue=0x0000000017e76980 ulValueLen=240 } CK_ATTRIBUTE *
ckObjectHandle 2357156729 unsigned long
+ ckpFunctions softokn3.dll!0x00007ffee9b0c620 (load symbols for additional information) {version={major=1 '\x1' minor=...} ...} CK_FUNCTION_LIST *
ckSessionHandle 16777217 unsigned long
ckAttributesLength 23 unsigned long


• The above highlighted code does make a call to NSS ( softtokn3 ) and receives 5 ( which stands for CKR_GENERAL_ERROR ) for the ckpAttributes type=1073742353.

I approached IAIK, here’s the response they provided …


On Fri, Jan 24, 2020 at 3:12 AM SIC/IAIK <XXXX> wrote:
The ckpAttributes that you have viewed in the debugger is actually an array with multiple ckAttributes. Specifically 1073742353 is the CKA_WRAP_TEMPLATE attribute.
I traced the error down to this NSS git commit [1]. There is seemingly a problem when querying ArrayAttributes. It produces an sqlite_error in the NSS code.
However, I'm pretty sure that this error is an actual NSS error and cannot be fixed from our side. I would suggest to file a bug report.
[1]: https://github.com/nss-dev/nss/commit/f572a15e45c5c4a26a0ada7ee008843ad19ec202


Please let us know ..

Thanks..

Kevin Jacobs

unread,
Jan 31, 2020, 6:19:03 AM1/31/20
to mozilla-de...@lists.mozilla.org
Hi Usha,

Thanks for the additional information. Unfortunately, we've not been able to reproduce this. More details (minimally, all arguments passed in each NSS function call) would be helpful. A C/C++ reproducer would be ideal.

Thanks,
Kevin
Reply all
Reply to author
Forward
0 new messages