pk11_key_unittest.cc 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. #include <memory>
  5. #include "nss.h"
  6. #include "pk11pub.h"
  7. #include "pk11pqg.h"
  8. #include "prerror.h"
  9. #include "secoid.h"
  10. #include "gtest/gtest.h"
  11. #include "nss_scoped_ptrs.h"
  12. #include "pk11_keygen.h"
  13. namespace nss_test {
  14. class Pkcs11NullKeyTestBase : public ::testing::Test {
  15. protected:
  16. // This constructs a key pair, then erases the public value from the public
  17. // key. NSS should reject this.
  18. void Test(const Pkcs11KeyPairGenerator& generator,
  19. CK_MECHANISM_TYPE dh_mech) {
  20. ScopedSECKEYPrivateKey priv;
  21. ScopedSECKEYPublicKey pub;
  22. generator.GenerateKey(&priv, &pub);
  23. ASSERT_TRUE(priv);
  24. // These don't leak because they are allocated to the arena associated with
  25. // the public key.
  26. SECItem* pub_val = nullptr;
  27. switch (SECKEY_GetPublicKeyType(pub.get())) {
  28. case rsaKey:
  29. pub_val = &pub->u.rsa.modulus;
  30. break;
  31. case dsaKey:
  32. pub_val = &pub->u.dsa.publicValue;
  33. break;
  34. case dhKey:
  35. pub_val = &pub->u.dh.publicValue;
  36. break;
  37. case ecKey:
  38. pub_val = &pub->u.ec.publicValue;
  39. break;
  40. default:
  41. FAIL() << "Unknown key type " << SECKEY_GetPublicKeyType(pub.get());
  42. }
  43. pub_val->data = nullptr;
  44. pub_val->len = 0;
  45. ScopedPK11SymKey symKey(PK11_PubDeriveWithKDF(
  46. priv.get(), pub.get(), false, nullptr, nullptr, dh_mech,
  47. CKM_SHA512_HMAC, CKA_DERIVE, 0, CKD_NULL, nullptr, nullptr));
  48. ASSERT_FALSE(symKey);
  49. }
  50. };
  51. class Pkcs11DhNullKeyTest : public Pkcs11NullKeyTestBase {};
  52. TEST_F(Pkcs11DhNullKeyTest, UseNullPublicValue) {
  53. Test(Pkcs11KeyPairGenerator(CKM_DH_PKCS_KEY_PAIR_GEN), CKM_DH_PKCS_DERIVE);
  54. }
  55. class Pkcs11EcdhNullKeyTest : public Pkcs11NullKeyTestBase,
  56. public ::testing::WithParamInterface<SECOidTag> {
  57. };
  58. TEST_P(Pkcs11EcdhNullKeyTest, UseNullPublicValue) {
  59. Test(Pkcs11KeyPairGenerator(CKM_EC_KEY_PAIR_GEN, GetParam()),
  60. CKM_ECDH1_DERIVE);
  61. }
  62. INSTANTIATE_TEST_CASE_P(Pkcs11EcdhNullKeyTest, Pkcs11EcdhNullKeyTest,
  63. ::testing::Values(SEC_OID_SECG_EC_SECP256R1,
  64. SEC_OID_SECG_EC_SECP384R1,
  65. SEC_OID_SECG_EC_SECP521R1,
  66. SEC_OID_CURVE25519));
  67. } // namespace nss_test