opendnssec / SoftHSMv2

SoftHSM version 2
http://www.softhsm.org/
Other
767 stars 339 forks source link

softhsm2-util AES key import fails whenever a newline character is present in file #746

Open ijsf opened 5 months ago

ijsf commented 5 months ago

I have just ran into an obscure problem where softhsm2-util --import --aes results in a (seemingly) succesful import of an AES key into SoftHSM v2, but actually has an incorrect AES key length. This results in a corrupted AES key that cannot be used.

The test case was a 32-byte (AES-256) secret key while the import listed by PKCS#11 (pkcs11-tool) resulted in an AES key with a length less than 32 bytes.

For example, the following key will result in an incorrect AES key length of 25 (notice the 0A newline character):

echo 2BC9931E0E50B4F6995CF194321D7DDDB91FA104925B6F8A0AFBAEF0207BB612 | xxd -r -p - > p.key

While looking at the relevant source code, I noticed that fgets and strlen are used to read out the binary key file:

This is incorrect behaviour as the C function fgets is intended for text strings, not binary strings, and stops whenever a newline character is encountered (even though the file is opened with rb attributes) leading to a silent corruption of the key. fread should probably be used instead to properly read the key in all conditions.

Furthermore, strlen is used in a similar manner to determine the AES key length, as if it were a text string while it is actually a binary byte array. As far as I know and have tested, the CKA_VALUE expects a byte array.

ijsf commented 5 months ago

I've also created a PR to fix this issue: #747

AlexanderBand commented 5 months ago

Please note this statement on the status of SoftHSM v2 development.