Commit 23d77df1 authored by Tim Taubert's avatar Tim Taubert

Bug 1295121 - Add the ability to load PKCS#8 ECDSA private keys r=franziskus

Differential Revision: https://nss-review.dev.mozaws.net/D185

--HG--
extra : amend_source : 52080036d5b28389b0046b5a00dba06d4865c15b
parent ca414b64
......@@ -3,6 +3,14 @@
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
{
'target_defaults': {
'cflags': [
'-Wsign-compare',
],
'xcode_settings': {
'OTHER_CFLAGS': [
'-Wsign-compare',
],
},
'conditions': [
['OS=="win"', {
'libraries': [
......
......@@ -116,11 +116,7 @@ class TestAgent {
if (cfg_.get<std::string>("key-file") != "") {
key_ = ReadPrivateKey(cfg_.get<std::string>("key-file"));
if (!key_) {
// Temporary to handle our inability to handle ECDSA.
exitCodeUnimplemented = true;
return false;
}
if (!key_) return false;
}
if (cfg_.get<std::string>("cert-file") != "") {
cert_ = ReadCertificate(cfg_.get<std::string>("cert-file"));
......
......@@ -63,7 +63,6 @@ SECKEYPrivateKey* ReadPrivateKey(const std::string& file) {
PK11_FreeSlot(slot);
SECITEM_FreeItem(&item, PR_FALSE);
if (rv != SECSuccess) {
// This is probably due to this being an ECDSA key (Bug 1295121).
std::cerr << "Couldn't import key " << PORT_ErrorToString(PORT_GetError())
<< "\n";
return nullptr;
......
......@@ -9,6 +9,7 @@ MODULE = nss
CPPSRCS = \
pk11_aeskeywrap_unittest.cc \
pk11_chacha20poly1305_unittest.cc \
pk11_ecdsa_unittest.cc \
pk11_export_unittest.cc \
pk11_pbkdf2_unittest.cc \
pk11_prf_unittest.cc \
......
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <memory>
#include "nss.h"
#include "pk11pub.h"
#include "sechash.h"
#include "gtest/gtest.h"
#include "scoped_ptrs.h"
#include "pk11_ecdsa_vectors.h"
#include "pk11_signature_test.h"
namespace nss_test {
class Pkcs11EcdsaTest : public Pk11SignatureTest {
protected:
CK_MECHANISM_TYPE mechanism() { return CKM_ECDSA; }
SECItem* parameters() { return nullptr; }
};
class Pkcs11EcdsaSha256Test : public Pkcs11EcdsaTest {
protected:
SECOidTag hashOID() { return SEC_OID_SHA256; }
};
class Pkcs11EcdsaSha384Test : public Pkcs11EcdsaTest {
protected:
SECOidTag hashOID() { return SEC_OID_SHA384; }
};
class Pkcs11EcdsaSha512Test : public Pkcs11EcdsaTest {
protected:
SECOidTag hashOID() { return SEC_OID_SHA512; }
};
TEST_F(Pkcs11EcdsaSha256Test, VerifyP256) {
SIG_TEST_VECTOR_VERIFY(kP256Spki, kP256Data, kP256Signature)
}
TEST_F(Pkcs11EcdsaSha256Test, SignAndVerifyP256) {
SIG_TEST_VECTOR_SIGN_VERIFY(kP256Pkcs8, kP256Spki, kP256Data)
}
TEST_F(Pkcs11EcdsaSha384Test, VerifyP384) {
SIG_TEST_VECTOR_VERIFY(kP384Spki, kP384Data, kP384Signature)
}
TEST_F(Pkcs11EcdsaSha384Test, SignAndVerifyP384) {
SIG_TEST_VECTOR_SIGN_VERIFY(kP384Pkcs8, kP384Spki, kP384Data)
}
TEST_F(Pkcs11EcdsaSha512Test, VerifyP521) {
SIG_TEST_VECTOR_VERIFY(kP521Spki, kP521Data, kP521Signature)
}
TEST_F(Pkcs11EcdsaSha512Test, SignAndVerifyP521) {
SIG_TEST_VECTOR_SIGN_VERIFY(kP521Pkcs8, kP521Spki, kP521Data)
}
// Importing a private key in PKCS#8 format must fail when the outer AlgID
// struct contains neither id-ecPublicKey nor a namedCurve parameter.
TEST_F(Pkcs11EcdsaSha256Test, ImportNoCurveOIDOrAlgorithmParams) {
EXPECT_FALSE(ImportPrivateKey(kP256Pkcs8NoCurveOIDOrAlgorithmParams,
sizeof(kP256Pkcs8NoCurveOIDOrAlgorithmParams)));
};
// Importing a private key in PKCS#8 format must succeed when only the outer
// AlgID struct contains the namedCurve parameters.
TEST_F(Pkcs11EcdsaSha256Test, ImportOnlyAlgorithmParams) {
EXPECT_TRUE(ImportPrivateKeyAndSignHashedData(
kP256Pkcs8OnlyAlgorithmParams, sizeof(kP256Pkcs8OnlyAlgorithmParams),
kP256Data, sizeof(kP256Data)));
};
// Importing a private key in PKCS#8 format must succeed when the outer AlgID
// struct and the inner ECPrivateKey contain the same namedCurve parameters.
// The inner curveOID is always ignored, so only the outer one will be used.
TEST_F(Pkcs11EcdsaSha256Test, ImportMatchingCurveOIDAndAlgorithmParams) {
EXPECT_TRUE(ImportPrivateKeyAndSignHashedData(
kP256Pkcs8MatchingCurveOIDAndAlgorithmParams,
sizeof(kP256Pkcs8MatchingCurveOIDAndAlgorithmParams), kP256Data,
sizeof(kP256Data)));
};
// Importing a private key in PKCS#8 format must succeed when the outer AlgID
// struct and the inner ECPrivateKey contain dissimilar namedCurve parameters.
// The inner curveOID is always ignored, so only the outer one will be used.
TEST_F(Pkcs11EcdsaSha256Test, ImportDissimilarCurveOIDAndAlgorithmParams) {
EXPECT_TRUE(ImportPrivateKeyAndSignHashedData(
kP256Pkcs8DissimilarCurveOIDAndAlgorithmParams,
sizeof(kP256Pkcs8DissimilarCurveOIDAndAlgorithmParams), kP256Data,
sizeof(kP256Data)));
};
// Importing a private key in PKCS#8 format must fail when the outer ASN.1
// AlgorithmID struct contains only id-ecPublicKey but no namedCurve parameter.
TEST_F(Pkcs11EcdsaSha256Test, ImportNoAlgorithmParams) {
EXPECT_FALSE(ImportPrivateKey(kP256Pkcs8NoAlgorithmParams,
sizeof(kP256Pkcs8NoAlgorithmParams)));
};
// Importing a private key in PKCS#8 format must fail when id-ecPublicKey is
// given (so we know it's an EC key) but the namedCurve parameter is unknown.
TEST_F(Pkcs11EcdsaSha256Test, ImportInvalidAlgorithmParams) {
EXPECT_FALSE(ImportPrivateKey(kP256Pkcs8InvalidAlgorithmParams,
sizeof(kP256Pkcs8InvalidAlgorithmParams)));
};
// Importing a private key in PKCS#8 format with a point not on the curve will
// succeed. Using the contained public key however will fail when trying to
// import it before using it for any operation.
TEST_F(Pkcs11EcdsaSha256Test, ImportPointNotOnCurve) {
ScopedSECKEYPrivateKey privKey(ImportPrivateKey(
kP256Pkcs8PointNotOnCurve, sizeof(kP256Pkcs8PointNotOnCurve)));
ASSERT_TRUE(privKey);
ScopedSECKEYPublicKey pubKey(SECKEY_ConvertToPublicKey(privKey.get()));
ASSERT_TRUE(pubKey);
ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
ASSERT_TRUE(slot);
auto handle = PK11_ImportPublicKey(slot.get(), pubKey.get(), false);
EXPECT_EQ(handle, static_cast<decltype(handle)>(CK_INVALID_HANDLE));
};
// Importing a private key in PKCS#8 format must fail when no point is given.
// PK11 currently offers no APIs to derive raw public keys from private values.
TEST_F(Pkcs11EcdsaSha256Test, ImportNoPublicKey) {
EXPECT_FALSE(
ImportPrivateKey(kP256Pkcs8NoPublicKey, sizeof(kP256Pkcs8NoPublicKey)));
};
// Importing a public key in SPKI format must fail when id-ecPublicKey is
// given (so we know it's an EC key) but the namedCurve parameter is missing.
TEST_F(Pkcs11EcdsaSha256Test, ImportSpkiNoAlgorithmParams) {
EXPECT_FALSE(ImportPublicKey(kP256SpkiNoAlgorithmParams,
sizeof(kP256SpkiNoAlgorithmParams)));
}
// Importing a public key in SPKI format with a point not on the curve will
// succeed. Using the public key however will fail when trying to import
// it before using it for any operation.
TEST_F(Pkcs11EcdsaSha256Test, ImportSpkiPointNotOnCurve) {
ScopedSECKEYPublicKey pubKey(ImportPublicKey(
kP256SpkiPointNotOnCurve, sizeof(kP256SpkiPointNotOnCurve)));
ASSERT_TRUE(pubKey);
ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
ASSERT_TRUE(slot);
auto handle = PK11_ImportPublicKey(slot.get(), pubKey.get(), false);
EXPECT_EQ(handle, static_cast<decltype(handle)>(CK_INVALID_HANDLE));
}
} // namespace nss_test
This diff is collapsed.
......@@ -13,6 +13,7 @@
'sources': [
'pk11_aeskeywrap_unittest.cc',
'pk11_chacha20poly1305_unittest.cc',
'pk11_ecdsa_unittest.cc',
'pk11_pbkdf2_unittest.cc',
'pk11_prf_unittest.cc',
'pk11_prng_unittest.cc',
......
This diff is collapsed.
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <memory>
#include "nss.h"
#include "pk11pub.h"
#include "sechash.h"
#include "gtest/gtest.h"
#include "scoped_ptrs.h"
namespace nss_test {
static unsigned char* toUcharPtr(const uint8_t* v) {
return const_cast<unsigned char*>(static_cast<const unsigned char*>(v));
}
class Pk11SignatureTest : public ::testing::Test {
protected:
virtual CK_MECHANISM_TYPE mechanism() = 0;
virtual SECItem* parameters() = 0;
virtual SECOidTag hashOID() = 0;
ScopedSECKEYPrivateKey ImportPrivateKey(const uint8_t* pkcs8,
size_t pkcs8_len) {
ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
if (!slot) {
return nullptr;
}
SECItem pkcs8Item = {siBuffer, toUcharPtr(pkcs8),
static_cast<unsigned int>(pkcs8_len)};
SECKEYPrivateKey* key = nullptr;
SECStatus rv = PK11_ImportDERPrivateKeyInfoAndReturnKey(
slot.get(), &pkcs8Item, nullptr, nullptr, false, false, KU_ALL, &key,
nullptr);
if (rv != SECSuccess) {
return nullptr;
}
return ScopedSECKEYPrivateKey(key);
}
ScopedSECKEYPublicKey ImportPublicKey(const uint8_t* spki, size_t spki_len) {
SECItem spkiItem = {siBuffer, toUcharPtr(spki),
static_cast<unsigned int>(spki_len)};
ScopedCERTSubjectPublicKeyInfo certSpki(
SECKEY_DecodeDERSubjectPublicKeyInfo(&spkiItem));
return ScopedSECKEYPublicKey(SECKEY_ExtractPublicKey(certSpki.get()));
}
ScopedSECItem ComputeHash(const uint8_t* data, size_t len) {
unsigned int hLen = HASH_ResultLenByOidTag(hashOID());
ScopedSECItem hash(SECITEM_AllocItem(nullptr, nullptr, hLen));
if (!hash) {
return nullptr;
}
SECStatus rv = PK11_HashBuf(hashOID(), hash->data, data, len);
if (rv != SECSuccess) {
return nullptr;
}
return hash;
}
ScopedSECItem SignHashedData(ScopedSECKEYPrivateKey& privKey,
ScopedSECItem& hash) {
unsigned int sLen = PK11_SignatureLen(privKey.get());
ScopedSECItem sig(SECITEM_AllocItem(nullptr, nullptr, sLen));
if (!sig) {
return nullptr;
}
SECStatus rv = PK11_SignWithMechanism(privKey.get(), mechanism(),
parameters(), sig.get(), hash.get());
if (rv != SECSuccess) {
return nullptr;
}
return sig;
}
ScopedSECItem ImportPrivateKeyAndSignHashedData(const uint8_t* pkcs8,
size_t pkcs8_len,
const uint8_t* data,
size_t data_len) {
ScopedSECKEYPrivateKey privKey(ImportPrivateKey(pkcs8, pkcs8_len));
if (!privKey) {
return nullptr;
}
ScopedSECItem hash(ComputeHash(data, data_len));
if (!hash) {
return nullptr;
}
return ScopedSECItem(SignHashedData(privKey, hash));
}
void Verify(const uint8_t* spki, size_t spki_len, const uint8_t* data,
size_t data_len, const uint8_t* sig, size_t sig_len) {
ScopedSECKEYPublicKey pubKey(ImportPublicKey(spki, spki_len));
ASSERT_TRUE(pubKey);
ScopedSECItem hash(ComputeHash(data, data_len));
ASSERT_TRUE(hash);
SECItem sigItem = {siBuffer, toUcharPtr(sig),
static_cast<unsigned int>(sig_len)};
// Verify.
SECStatus rv = PK11_VerifyWithMechanism(
pubKey.get(), mechanism(), parameters(), &sigItem, hash.get(), nullptr);
EXPECT_EQ(rv, SECSuccess);
}
void SignAndVerify(const uint8_t* pkcs8, size_t pkcs8_len,
const uint8_t* spki, size_t spki_len, const uint8_t* data,
size_t data_len) {
ScopedSECItem sig(
ImportPrivateKeyAndSignHashedData(pkcs8, pkcs8_len, data, data_len));
ASSERT_TRUE(sig);
Verify(spki, spki_len, data, data_len, sig->data, sig->len);
}
};
#define SIG_TEST_VECTOR_VERIFY(spki, data, sig) \
Verify(spki, sizeof(spki), data, sizeof(data), sig, sizeof(sig));
#define SIG_TEST_VECTOR_SIGN_VERIFY(pkcs8, spki, data) \
SignAndVerify(pkcs8, sizeof(pkcs8), spki, sizeof(spki), data, sizeof(data));
} // namespace nss_test
......@@ -1242,6 +1242,22 @@ SECKEY_ConvertToPublicKey(SECKEYPrivateKey *privk)
break;
return pubk;
break;
case ecKey:
rv = PK11_ReadAttribute(privk->pkcs11Slot, privk->pkcs11ID,
CKA_EC_PARAMS, arena, &pubk->u.ec.DEREncodedParams);
if (rv != SECSuccess) {
break;
}
rv = PK11_ReadAttribute(privk->pkcs11Slot, privk->pkcs11ID,
CKA_EC_POINT, arena, &pubk->u.ec.publicValue);
if (rv != SECSuccess || pubk->u.ec.publicValue.len == 0) {
break;
}
rv = seckey_SetPointEncoding(arena, pubk);
if (rv != SECSuccess) {
break;
}
return pubk;
default:
break;
}
......
......@@ -64,6 +64,19 @@ struct SECKEYDHPrivateKeyStr {
};
typedef struct SECKEYDHPrivateKeyStr SECKEYDHPrivateKey;
/*
** Elliptic Curve Private Key structures
** <https://tools.ietf.org/html/rfc5915#section-3>
*/
struct SECKEYECPrivateKeyStr {
PLArenaPool *arena;
SECItem version;
SECItem curveOID; /* optional/ignored */
SECItem publicValue; /* required (for now) */
SECItem privateValue;
};
typedef struct SECKEYECPrivateKeyStr SECKEYECPrivateKey;
/*
** raw private key object
*/
......@@ -74,6 +87,7 @@ struct SECKEYRawPrivateKeyStr {
SECKEYRSAPrivateKey rsa;
SECKEYDSAPrivateKey dsa;
SECKEYDHPrivateKey dh;
SECKEYECPrivateKey ec;
} u;
};
typedef struct SECKEYRawPrivateKeyStr SECKEYRawPrivateKey;
......@@ -139,6 +153,33 @@ const SEC_ASN1Template SECKEY_DHPrivateKeyExportTemplate[] = {
{ SEC_ASN1_INTEGER, offsetof(SECKEYRawPrivateKey, u.dh.prime) },
};
#ifndef NSS_DISABLE_ECC
SEC_ASN1_MKSUB(SEC_BitStringTemplate)
SEC_ASN1_MKSUB(SEC_ObjectIDTemplate)
const SEC_ASN1Template SECKEY_ECPrivateKeyExportTemplate[] = {
{ SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SECKEYRawPrivateKey) },
{ SEC_ASN1_INTEGER, offsetof(SECKEYRawPrivateKey, u.ec.version) },
{ SEC_ASN1_OCTET_STRING,
offsetof(SECKEYRawPrivateKey, u.ec.privateValue) },
/* This value will always be ignored. u.ec.curveOID will always be
* overriden with the outer AlgorithmID.parameters. */
{ SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED |
SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC |
SEC_ASN1_XTRN | 0,
offsetof(SECKEYRawPrivateKey, u.ec.curveOID),
SEC_ASN1_SUB(SEC_ObjectIDTemplate) },
/* The public value is optional per RFC, but required in NSS. We
* can't do scalar mult on ECs to get a raw point with PK11 APIs. */
{ SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED |
SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC |
SEC_ASN1_XTRN | 1,
offsetof(SECKEYRawPrivateKey, u.ec.publicValue),
SEC_ASN1_SUB(SEC_BitStringTemplate) },
{ 0 }
};
#endif /* NSS_DISABLE_ECC */
const SEC_ASN1Template SECKEY_EncryptedPrivateKeyInfoTemplate[] = {
{ SEC_ASN1_SEQUENCE,
0, NULL, sizeof(SECKEYEncryptedPrivateKeyInfo) },
......@@ -198,6 +239,15 @@ prepare_dh_priv_key_export_for_asn1(SECKEYRawPrivateKey *key)
key->u.dh.base.type = siUnsignedInteger;
}
static void
prepare_ec_priv_key_export_for_asn1(SECKEYRawPrivateKey *key)
{
key->u.ec.version.type = siUnsignedInteger;
key->u.ec.curveOID.type = siUnsignedInteger;
key->u.ec.privateValue.type = siUnsignedInteger;
key->u.ec.publicValue.type = siUnsignedInteger;
}
SECStatus
PK11_ImportDERPrivateKeyInfo(PK11SlotInfo *slot, SECItem *derPKI,
SECItem *nickname, SECItem *publicValue, PRBool isPerm,
......@@ -432,7 +482,50 @@ PK11_ImportAndReturnPrivateKey(PK11SlotInfo *slot, SECKEYRawPrivateKey *lpk,
lpk->u.dh.privateValue.len);
attrs++;
break;
/* what about fortezza??? */
#ifndef NSS_DISABLE_ECC
case ecKey:
keyType = CKK_EC;
if (lpk->u.ec.publicValue.len == 0) {
goto loser;
}
if (PK11_IsInternal(slot)) {
PK11_SETATTRS(attrs, CKA_NETSCAPE_DB,
lpk->u.ec.publicValue.data,
lpk->u.ec.publicValue.len);
attrs++;
}
PK11_SETATTRS(attrs, CKA_SIGN, (keyUsage & KU_DIGITAL_SIGNATURE) ? &cktrue
: &ckfalse,
sizeof(CK_BBOOL));
attrs++;
PK11_SETATTRS(attrs, CKA_SIGN_RECOVER,
(keyUsage & KU_DIGITAL_SIGNATURE) ? &cktrue
: &ckfalse,
sizeof(CK_BBOOL));
attrs++;
PK11_SETATTRS(attrs, CKA_DERIVE, (keyUsage & KU_KEY_AGREEMENT) ? &cktrue
: &ckfalse,
sizeof(CK_BBOOL));
attrs++;
ck_id = PK11_MakeIDFromPubKey(&lpk->u.ec.publicValue);
if (ck_id == NULL) {
goto loser;
}
PK11_SETATTRS(attrs, CKA_ID, ck_id->data, ck_id->len);
attrs++;
signedattr = attrs;
/* curveOID always is a copy of AlgorithmID.parameters. */
PK11_SETATTRS(attrs, CKA_EC_PARAMS, lpk->u.ec.curveOID.data,
lpk->u.ec.curveOID.len);
attrs++;
PK11_SETATTRS(attrs, CKA_VALUE, lpk->u.ec.privateValue.data,
lpk->u.ec.privateValue.len);
attrs++;
PK11_SETATTRS(attrs, CKA_EC_POINT, lpk->u.ec.publicValue.data,
lpk->u.ec.publicValue.len);
attrs++;
break;
#endif /* NSS_DISABLE_ECC */
default:
PORT_SetError(SEC_ERROR_BAD_KEY);
goto loser;
......@@ -513,6 +606,15 @@ PK11_ImportPrivateKeyInfoAndReturnKey(PK11SlotInfo *slot,
paramDest = NULL;
lpk->keyType = dhKey;
break;
#ifndef NSS_DISABLE_ECC
case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
prepare_ec_priv_key_export_for_asn1(lpk);
keyTemplate = SECKEY_ECPrivateKeyExportTemplate;
paramTemplate = NULL;
paramDest = NULL;
lpk->keyType = ecKey;
break;
#endif /* NSS_DISABLE_ECC */
default:
keyTemplate = NULL;
......@@ -526,10 +628,25 @@ PK11_ImportPrivateKeyInfoAndReturnKey(PK11SlotInfo *slot,
}
/* decode the private key and any algorithm parameters */
rv = SEC_ASN1DecodeItem(arena, lpk, keyTemplate, &pki->privateKey);
rv = SEC_QuickDERDecodeItem(arena, lpk, keyTemplate, &pki->privateKey);
if (rv != SECSuccess) {
goto loser;
}
#ifndef NSS_DISABLE_ECC
if (lpk->keyType == ecKey) {
/* Convert length in bits to length in bytes. */
lpk->u.ec.publicValue.len >>= 3;
/* Always override curveOID, we're ignoring any given value. */
rv = SECITEM_CopyItem(arena, &lpk->u.ec.curveOID,
&pki->algorithm.parameters);
if (rv != SECSuccess) {
goto loser;
}
}
#endif /* NSS_DISABLE_ECC */
if (paramDest && paramTemplate) {
rv = SEC_ASN1DecodeItem(arena, paramDest, paramTemplate,
&(pki->algorithm.parameters));
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment