pk11_key_unittest.cc (2539B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this file, 3 * You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 #include <memory> 6 #include "nss.h" 7 #include "pk11pub.h" 8 #include "pk11pqg.h" 9 #include "prerror.h" 10 #include "secoid.h" 11 12 #include "gtest/gtest.h" 13 #include "nss_scoped_ptrs.h" 14 #include "pk11_keygen.h" 15 16 namespace nss_test { 17 18 class Pkcs11NullKeyTestBase : public ::testing::Test { 19 protected: 20 // This constructs a key pair, then erases the public value from the public 21 // key. NSS should reject this. 22 void Test(const Pkcs11KeyPairGenerator& generator, 23 CK_MECHANISM_TYPE dh_mech) { 24 ScopedSECKEYPrivateKey priv; 25 ScopedSECKEYPublicKey pub; 26 generator.GenerateKey(&priv, &pub); 27 ASSERT_TRUE(priv); 28 29 // These don't leak because they are allocated to the arena associated with 30 // the public key. 31 SECItem* pub_val = nullptr; 32 switch (SECKEY_GetPublicKeyType(pub.get())) { 33 case rsaKey: 34 pub_val = &pub->u.rsa.modulus; 35 break; 36 37 case dsaKey: 38 pub_val = &pub->u.dsa.publicValue; 39 break; 40 41 case dhKey: 42 pub_val = &pub->u.dh.publicValue; 43 break; 44 45 case ecKey: 46 pub_val = &pub->u.ec.publicValue; 47 break; 48 49 default: 50 FAIL() << "Unknown key type " << SECKEY_GetPublicKeyType(pub.get()); 51 } 52 pub_val->data = nullptr; 53 pub_val->len = 0; 54 55 ScopedPK11SymKey symKey(PK11_PubDeriveWithKDF( 56 priv.get(), pub.get(), false, nullptr, nullptr, dh_mech, 57 CKM_SHA512_HMAC, CKA_DERIVE, 0, CKD_NULL, nullptr, nullptr)); 58 ASSERT_FALSE(symKey); 59 } 60 }; 61 62 class Pkcs11DhNullKeyTest : public Pkcs11NullKeyTestBase {}; 63 TEST_F(Pkcs11DhNullKeyTest, UseNullPublicValue) { 64 Test(Pkcs11KeyPairGenerator(CKM_DH_PKCS_KEY_PAIR_GEN), CKM_DH_PKCS_DERIVE); 65 } 66 67 class Pkcs11EcdhNullKeyTest : public Pkcs11NullKeyTestBase, 68 public ::testing::WithParamInterface<SECOidTag> { 69 }; 70 TEST_P(Pkcs11EcdhNullKeyTest, UseNullPublicValue) { 71 Test(Pkcs11KeyPairGenerator(CKM_EC_KEY_PAIR_GEN, GetParam()), 72 CKM_ECDH1_DERIVE); 73 } 74 INSTANTIATE_TEST_SUITE_P(Pkcs11EcdhNullKeyTest, Pkcs11EcdhNullKeyTest, 75 ::testing::Values(SEC_OID_SECG_EC_SECP256R1, 76 SEC_OID_SECG_EC_SECP384R1, 77 SEC_OID_SECG_EC_SECP521R1, 78 SEC_OID_CURVE25519)); 79 80 } // namespace nss_test