--- a/security/certverifier/NSSCertDBTrustDomain.cpp
+++ b/security/certverifier/NSSCertDBTrustDomain.cpp
@@ -4,34 +4,33 @@
* 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 "NSSCertDBTrustDomain.h"
#include <stdint.h>
#include "ExtendedValidation.h"
+#include "NSSErrorsService.h"
#include "OCSPRequestor.h"
#include "OCSPVerificationTrustDomain.h"
+#include "PublicKeyPinningService.h"
+#include "cert.h"
#include "certdb.h"
-#include "cert.h"
#include "mozilla/UniquePtr.h"
#include "nsNSSCertificate.h"
+#include "nsServiceManagerUtils.h"
#include "nss.h"
-#include "NSSErrorsService.h"
-#include "nsServiceManagerUtils.h"
#include "pk11pub.h"
+#include "pkix/Result.h"
#include "pkix/pkix.h"
#include "pkix/pkixnss.h"
-#include "pkix/Result.h"
#include "prerror.h"
#include "prmem.h"
#include "prprf.h"
-#include "PublicKeyPinningService.h"
-#include "ScopedNSSTypes.h"
#include "secerr.h"
#include "CNNICHashWhitelist.inc"
using namespace mozilla;
using namespace mozilla::pkix;
extern LazyLogModule gCertVerifierLog;
@@ -1131,17 +1130,17 @@ SaveIntermediateCerts(const UniqueCERTCe
if (node->cert->isperm) {
// We don't need to remember certs already stored in perm db.
continue;
}
// We have found a signer cert that we want to remember.
char* nickname = DefaultServerNicknameForCert(node->cert);
if (nickname && *nickname) {
- ScopedPK11SlotInfo slot(PK11_GetInternalKeySlot());
+ UniquePK11SlotInfo slot(PK11_GetInternalKeySlot());
if (slot) {
PK11_ImportCert(slot.get(), node->cert, CK_INVALID_HANDLE,
nickname, false);
}
}
PR_FREEIF(nickname);
}
}
--- a/security/certverifier/NSSCertDBTrustDomain.h
+++ b/security/certverifier/NSSCertDBTrustDomain.h
@@ -3,16 +3,17 @@
/* 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/. */
#ifndef NSSCertDBTrustDomain_h
#define NSSCertDBTrustDomain_h
#include "CertVerifier.h"
+#include "ScopedNSSTypes.h"
#include "nsICertBlocklist.h"
#include "pkix/pkixtypes.h"
#include "secmodt.h"
namespace mozilla { namespace psm {
enum class ValidityCheckingMode {
CheckingOff = 0,
--- a/security/manager/ssl/LocalCertService.cpp
+++ b/security/manager/ssl/LocalCertService.cpp
@@ -104,17 +104,17 @@ private:
return NS_OK;
}
nsresult Generate()
{
nsresult rv;
// Get the key slot for generation later
- ScopedPK11SlotInfo slot(PK11_GetInternalKeySlot());
+ UniquePK11SlotInfo slot(PK11_GetInternalKeySlot());
if (!slot) {
return mozilla::psm::GetXPCOMFromNSSError(PR_GetError());
}
// Remove existing certs with this name (if any)
rv = RemoveExisting();
if (NS_FAILED(rv)) {
return rv;
@@ -136,22 +136,22 @@ private:
// Get key params from the curve
ScopedAutoSECItem keyParams(2 + curveOidData->oid.len);
keyParams.data[0] = SEC_ASN1_OBJECT_ID;
keyParams.data[1] = curveOidData->oid.len;
memcpy(keyParams.data + 2, curveOidData->oid.data, curveOidData->oid.len);
// Generate cert key pair
- ScopedSECKEYPrivateKey privateKey;
ScopedSECKEYPublicKey publicKey;
SECKEYPublicKey* tempPublicKey;
- privateKey = PK11_GenerateKeyPair(slot, CKM_EC_KEY_PAIR_GEN, &keyParams,
- &tempPublicKey, true /* token */,
- true /* sensitive */, nullptr);
+ UniqueSECKEYPrivateKey privateKey(
+ PK11_GenerateKeyPair(slot.get(), CKM_EC_KEY_PAIR_GEN, &keyParams,
+ &tempPublicKey, true /* token */,
+ true /* sensitive */, nullptr));
if (!privateKey) {
return mozilla::psm::GetXPCOMFromNSSError(PR_GetError());
}
publicKey = tempPublicKey;
// Create subject public key info and cert request
ScopedCERTSubjectPublicKeyInfo spki(
SECKEY_CreateSubjectPublicKeyInfo(publicKey));
@@ -177,17 +177,17 @@ private:
if (!validity) {
return mozilla::psm::GetXPCOMFromNSSError(PR_GetError());
}
// Generate random serial
unsigned long serial;
// This serial in principle could collide, but it's unlikely
rv = MapSECStatus(
- PK11_GenerateRandomOnSlot(slot,
+ PK11_GenerateRandomOnSlot(slot.get(),
reinterpret_cast<unsigned char *>(&serial),
sizeof(serial)));
if (NS_FAILED(rv)) {
return rv;
}
// Create the cert from these pieces
ScopedCERTCertificate cert(
@@ -219,32 +219,32 @@ private:
ScopedSECItem certDER(
SEC_ASN1EncodeItem(nullptr, nullptr, cert,
SEC_ASN1_GET(CERT_CertificateTemplate)));
if (!certDER) {
return mozilla::psm::GetXPCOMFromNSSError(PR_GetError());
}
rv = MapSECStatus(
SEC_DerSignData(arena, &cert->derCert, certDER->data, certDER->len,
- privateKey,
+ privateKey.get(),
SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE));
if (NS_FAILED(rv)) {
return rv;
}
// Create a CERTCertificate from the signed data
ScopedCERTCertificate certFromDER(
CERT_NewTempCertificate(CERT_GetDefaultCertDB(), &cert->derCert, nullptr,
true /* perm */, true /* copyDER */));
if (!certFromDER) {
return mozilla::psm::GetXPCOMFromNSSError(PR_GetError());
}
// Save the cert in the DB
- rv = MapSECStatus(PK11_ImportCert(slot, certFromDER, CK_INVALID_HANDLE,
+ rv = MapSECStatus(PK11_ImportCert(slot.get(), certFromDER, CK_INVALID_HANDLE,
mNickname.get(), false /* unused */));
if (NS_FAILED(rv)) {
return rv;
}
// We should now have cert in the DB, read it back in nsIX509Cert form
return GetFromDB();
}
@@ -363,31 +363,31 @@ LocalCertService::~LocalCertService()
}
nsresult
LocalCertService::LoginToKeySlot()
{
nsresult rv;
// Get access to key slot
- ScopedPK11SlotInfo slot(PK11_GetInternalKeySlot());
+ UniquePK11SlotInfo slot(PK11_GetInternalKeySlot());
if (!slot) {
return mozilla::psm::GetXPCOMFromNSSError(PR_GetError());
}
// If no user password yet, set it an empty one
- if (PK11_NeedUserInit(slot)) {
- rv = MapSECStatus(PK11_InitPin(slot, "", ""));
+ if (PK11_NeedUserInit(slot.get())) {
+ rv = MapSECStatus(PK11_InitPin(slot.get(), "", ""));
if (NS_FAILED(rv)) {
return rv;
}
}
// If user has a password set, prompt to login
- if (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, nullptr)) {
+ if (PK11_NeedLogin(slot.get()) && !PK11_IsLoggedIn(slot.get(), nullptr)) {
// Switching to XPCOM to get the UI prompt that PSM owns
nsCOMPtr<nsIPK11TokenDB> tokenDB =
do_GetService(NS_PK11TOKENDB_CONTRACTID);
if (!tokenDB) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIPK11Token> keyToken;
tokenDB->GetInternalKeyToken(getter_AddRefs(keyToken));
@@ -447,30 +447,31 @@ LocalCertService::RemoveCert(const nsACS
}
NS_IMETHODIMP
LocalCertService::GetLoginPromptRequired(bool* aRequired)
{
nsresult rv;
// Get access to key slot
- ScopedPK11SlotInfo slot(PK11_GetInternalKeySlot());
+ UniquePK11SlotInfo slot(PK11_GetInternalKeySlot());
if (!slot) {
return mozilla::psm::GetXPCOMFromNSSError(PR_GetError());
}
// If no user password yet, set it an empty one
- if (PK11_NeedUserInit(slot)) {
- rv = MapSECStatus(PK11_InitPin(slot, "", ""));
+ if (PK11_NeedUserInit(slot.get())) {
+ rv = MapSECStatus(PK11_InitPin(slot.get(), "", ""));
if (NS_FAILED(rv)) {
return rv;
}
}
- *aRequired = PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, nullptr);
+ *aRequired = PK11_NeedLogin(slot.get()) &&
+ !PK11_IsLoggedIn(slot.get(), nullptr);
return NS_OK;
}
#define LOCALCERTSERVICE_CID \
{ 0x47402be2, 0xe653, 0x45d0, \
{ 0x8d, 0xaa, 0x9f, 0x0d, 0xce, 0x0a, 0xc1, 0x48 } }
NS_GENERIC_FACTORY_CONSTRUCTOR(LocalCertService)
--- a/security/manager/ssl/nsCertOverrideService.cpp
+++ b/security/manager/ssl/nsCertOverrideService.cpp
@@ -371,23 +371,23 @@ nsCertOverrideService::RememberValidityO
UniqueCERTCertificate nsscert(aCert->GetCert());
if (!nsscert) {
return NS_ERROR_FAILURE;
}
char* nickname = DefaultServerNicknameForCert(nsscert.get());
if (!aTemporary && nickname && *nickname)
{
- ScopedPK11SlotInfo slot(PK11_GetInternalKeySlot());
+ UniquePK11SlotInfo slot(PK11_GetInternalKeySlot());
if (!slot) {
PR_Free(nickname);
return NS_ERROR_FAILURE;
}
-
- SECStatus srv = PK11_ImportCert(slot, nsscert.get(), CK_INVALID_HANDLE,
+
+ SECStatus srv = PK11_ImportCert(slot.get(), nsscert.get(), CK_INVALID_HANDLE,
nickname, false);
if (srv != SECSuccess) {
PR_Free(nickname);
return NS_ERROR_FAILURE;
}
}
PR_FREEIF(nickname);
--- a/security/manager/ssl/nsKeyModule.cpp
+++ b/security/manager/ssl/nsKeyModule.cpp
@@ -132,17 +132,17 @@ nsKeyObjectFactory::KeyFromString(int16_
}
// Convert the raw string into a SECItem
const nsCString& flatKey = PromiseFlatCString(aKey);
SECItem keyItem;
keyItem.data = (unsigned char*)flatKey.get();
keyItem.len = flatKey.Length();
- ScopedPK11SlotInfo slot(PK11_GetBestSlot(cipherMech, nullptr));
+ UniquePK11SlotInfo slot(PK11_GetBestSlot(cipherMech, nullptr));
if (!slot) {
return NS_ERROR_FAILURE;
}
UniquePK11SymKey symKey(PK11_ImportSymKey(slot.get(), cipherMech,
PK11_OriginUnwrap, cipherOperation,
&keyItem, nullptr));
if (!symKey) {
--- a/security/manager/ssl/nsNSSCertificateDB.cpp
+++ b/security/manager/ssl/nsNSSCertificateDB.cpp
@@ -60,24 +60,24 @@ attemptToLogInWithDefaultPassword()
#ifdef NSS_DISABLE_DBM
// The SQL NSS DB requires the user to be authenticated to set certificate
// trust settings, even if the user's password is empty. To maintain
// compatibility with the DBM-based database, try to log in with the
// default empty password. This will allow, at least, tests that need to
// change certificate trust to pass on all platforms. TODO(bug 978120): Do
// proper testing and/or implement a better solution so that we are confident
// that this does the correct thing outside of xpcshell tests too.
- ScopedPK11SlotInfo slot(PK11_GetInternalKeySlot());
+ UniquePK11SlotInfo slot(PK11_GetInternalKeySlot());
if (!slot) {
return MapSECStatus(SECFailure);
}
- if (PK11_NeedUserInit(slot)) {
+ if (PK11_NeedUserInit(slot.get())) {
// Ignore the return value. Presumably PK11_InitPin will fail if the user
// has a non-default password.
- (void) PK11_InitPin(slot, nullptr, nullptr);
+ Unused << PK11_InitPin(slot.get(), nullptr, nullptr);
}
#endif
return NS_OK;
}
NS_IMPL_ISUPPORTS(nsNSSCertificateDB, nsIX509CertDB)
@@ -1004,60 +1004,58 @@ nsNSSCertificateDB::ImportCertsFromFile(
default:
MOZ_ASSERT(false, "Unsupported type should have been filtered out");
break;
}
return NS_ERROR_FAILURE;
}
-NS_IMETHODIMP
+NS_IMETHODIMP
nsNSSCertificateDB::ImportPKCS12File(nsISupports* aToken, nsIFile* aFile)
{
nsNSSShutDownPreventionLock locker;
if (isAlreadyShutDown()) {
return NS_ERROR_NOT_AVAILABLE;
}
NS_ENSURE_ARG(aFile);
nsPKCS12Blob blob;
nsCOMPtr<nsIPK11Token> token = do_QueryInterface(aToken);
if (token) {
blob.SetToken(token);
}
return blob.ImportFromFile(aFile);
}
-NS_IMETHODIMP
+NS_IMETHODIMP
nsNSSCertificateDB::ExportPKCS12File(nsISupports* aToken,
nsIFile* aFile,
uint32_t count,
nsIX509Cert** certs)
- //const char16_t **aCertNames)
{
nsNSSShutDownPreventionLock locker;
if (isAlreadyShutDown()) {
return NS_ERROR_NOT_AVAILABLE;
}
NS_ENSURE_ARG(aFile);
nsPKCS12Blob blob;
if (count == 0) return NS_OK;
nsCOMPtr<nsIPK11Token> localRef;
if (!aToken) {
- ScopedPK11SlotInfo keySlot(PK11_GetInternalKeySlot());
- NS_ASSERTION(keySlot,"Failed to get the internal key slot");
- localRef = new nsPK11Token(keySlot);
- }
- else {
+ UniquePK11SlotInfo keySlot(PK11_GetInternalKeySlot());
+ if (!keySlot) {
+ return NS_ERROR_FAILURE;
+ }
+ localRef = new nsPK11Token(keySlot.get());
+ } else {
localRef = do_QueryInterface(aToken);
}
blob.SetToken(localRef);
- //blob.LoadCerts(aCertNames, count);
- //return blob.ExportToFile(aFile);
return blob.ExportToFile(aFile, certs, count);
}
NS_IMETHODIMP
nsNSSCertificateDB::FindEmailEncryptionCert(const nsAString& aNickname,
nsIX509Cert** _retval)
{
NS_ENSURE_ARG_POINTER(_retval);
@@ -1302,22 +1300,23 @@ nsNSSCertificateDB::get_default_nickname
nickname = baseName;
/*
* We need to see if the private key exists on a token, if it does
* then we need to check for nicknames that already exist on the smart
* card.
*/
- ScopedPK11SlotInfo slot(PK11_KeyForCertExists(cert, &keyHandle, ctx));
+ UniquePK11SlotInfo slot(PK11_KeyForCertExists(cert, &keyHandle, ctx));
if (!slot)
return;
- if (!PK11_IsInternal(slot)) {
- char *tmp = PR_smprintf("%s:%s", PK11_GetTokenName(slot), baseName.get());
+ if (!PK11_IsInternal(slot.get())) {
+ char* tmp = PR_smprintf("%s:%s", PK11_GetTokenName(slot.get()),
+ baseName.get());
if (!tmp) {
nickname.Truncate();
return;
}
baseName = tmp;
PR_smprintf_free(tmp);
nickname = baseName;
@@ -1332,29 +1331,24 @@ nsNSSCertificateDB::get_default_nickname
return;
}
nickname = tmp;
PR_smprintf_free(tmp);
}
UniqueCERTCertificate dummycert;
- if (PK11_IsInternal(slot)) {
+ if (PK11_IsInternal(slot.get())) {
/* look up the nickname to make sure it isn't in use already */
dummycert.reset(CERT_FindCertByNickname(defaultcertdb, nickname.get()));
} else {
- /*
- * Check the cert against others that already live on the smart
- * card.
- */
+ // Check the cert against others that already live on the smart card.
dummycert.reset(PK11_FindCertFromNickname(nickname.get(), ctx));
if (dummycert) {
- /*
- * Make sure the subject names are different.
- */
+ // Make sure the subject names are different.
if (CERT_CompareName(&cert->subject, &dummycert->subject) == SECEqual)
{
/*
* There is another certificate with the same nickname and
* the same subject name on the smart card, so let's use this
* nickname.
*/
dummycert = nullptr;
--- a/security/manager/ssl/nsNSSU2FToken.cpp
+++ b/security/manager/ssl/nsNSSU2FToken.cpp
@@ -78,46 +78,46 @@ nsNSSU2FToken::virtualDestroyNSSReferenc
void
nsNSSU2FToken::destructorSafeDestroyNSSReference()
{
mWrappingKey = nullptr;
}
static PK11SymKey*
-GetSymKeyByNickname(PK11SlotInfo* aSlot,
+GetSymKeyByNickname(const UniquePK11SlotInfo& aSlot,
nsCString aNickname,
const nsNSSShutDownPreventionLock&)
{
MOZ_LOG(gNSSTokenLog, LogLevel::Debug,
("Searching for a symmetric key named %s", aNickname.get()));
PK11SymKey* keyList;
- keyList = PK11_ListFixedKeysInSlot(aSlot, const_cast<char*>(aNickname.get()),
+ keyList = PK11_ListFixedKeysInSlot(aSlot.get(),
+ const_cast<char*>(aNickname.get()),
/* wincx */ nullptr);
while (keyList) {
ScopedPK11SymKey freeKey(keyList);
- UniquePtr<char, void(&)(void*)>
- freeKeyName(PK11_GetSymKeyNickname(freeKey), PORT_Free);
+ UniquePORTString freeKeyName(PK11_GetSymKeyNickname(freeKey.get()));
if (aNickname == freeKeyName.get()) {
MOZ_LOG(gNSSTokenLog, LogLevel::Debug, ("Symmetric key found!"));
return freeKey.forget();
}
keyList = PK11_GetNextSymKey(keyList);
}
MOZ_LOG(gNSSTokenLog, LogLevel::Debug, ("Symmetric key not found."));
return nullptr;
}
static nsresult
-GenEcKeypair(PK11SlotInfo* aSlot, ScopedSECKEYPrivateKey& aPrivKey,
+GenEcKeypair(const UniquePK11SlotInfo& aSlot, ScopedSECKEYPrivateKey& aPrivKey,
ScopedSECKEYPublicKey& aPubKey, const nsNSSShutDownPreventionLock&)
{
UniquePLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
if (!arena) {
return NS_ERROR_OUT_OF_MEMORY;
}
// Set the curve parameters; keyParams belongs to the arena memory space
@@ -125,51 +125,51 @@ GenEcKeypair(PK11SlotInfo* aSlot, Scoped
if (!keyParams) {
return NS_ERROR_OUT_OF_MEMORY;
}
// Generate a key pair
CK_MECHANISM_TYPE mechanism = CKM_EC_KEY_PAIR_GEN;
SECKEYPublicKey* pubKeyRaw;
- aPrivKey = PK11_GenerateKeyPair(aSlot, mechanism, keyParams, &pubKeyRaw,
+ aPrivKey = PK11_GenerateKeyPair(aSlot.get(), mechanism, keyParams, &pubKeyRaw,
/* ephemeral */ PR_FALSE, PR_FALSE,
/* wincx */ nullptr);
aPubKey = pubKeyRaw;
if (!aPrivKey.get() || !aPubKey.get()) {
return NS_ERROR_FAILURE;
}
// Check that the public key has the correct length
if (aPubKey->u.ec.publicValue.len != kPublicKeyLen) {
return NS_ERROR_FAILURE;
}
return NS_OK;
}
nsresult
-nsNSSU2FToken::GetOrCreateWrappingKey(PK11SlotInfo* aSlot,
+nsNSSU2FToken::GetOrCreateWrappingKey(const UniquePK11SlotInfo& aSlot,
const nsNSSShutDownPreventionLock& locker)
{
// Search for an existing wrapping key. If we find it,
// store it for later and mark ourselves initialized.
mWrappingKey = GetSymKeyByNickname(aSlot, mSecretNickname, locker);
if (mWrappingKey) {
MOZ_LOG(gNSSTokenLog, LogLevel::Debug, ("U2F Soft Token Key found."));
mInitialized = true;
return NS_OK;
}
MOZ_LOG(gNSSTokenLog, LogLevel::Info,
("No keys found. Generating new U2F Soft Token wrapping key."));
// We did not find an existing wrapping key, so we generate one in the
// persistent database (e.g, Token).
- mWrappingKey = PK11_TokenKeyGenWithFlags(aSlot, CKM_AES_KEY_GEN,
+ mWrappingKey = PK11_TokenKeyGenWithFlags(aSlot.get(), CKM_AES_KEY_GEN,
/* default params */ nullptr,
kWrappingKeyByteLen,
/* empty keyid */ nullptr,
/* flags */ CKF_WRAP | CKF_UNWRAP,
/* attributes */ PK11_ATTR_TOKEN |
PK11_ATTR_PRIVATE,
/* wincx */ nullptr);
@@ -189,17 +189,17 @@ nsNSSU2FToken::GetOrCreateWrappingKey(PK
MOZ_LOG(gNSSTokenLog, LogLevel::Debug,
("Key stored, nickname set to %s.", mSecretNickname.get()));
Preferences::SetUint(PREF_U2F_NSSTOKEN_COUNTER, 0);
return NS_OK;
}
static nsresult
-GetAttestationCertificate(PK11SlotInfo* aSlot,
+GetAttestationCertificate(const UniquePK11SlotInfo& aSlot,
ScopedSECKEYPrivateKey& aAttestPrivKey,
ScopedCERTCertificate& aAttestCert,
const nsNSSShutDownPreventionLock& locker)
{
ScopedSECKEYPublicKey pubKey;
// Construct an ephemeral keypair for this Attestation Certificate
nsresult rv = GenEcKeypair(aSlot, aAttestPrivKey, pubKey, locker);
@@ -241,17 +241,18 @@ GetAttestationCertificate(PK11SlotInfo*
if (!validity) {
MOZ_LOG(gNSSTokenLog, LogLevel::Warning,
("Failed to gen validity, NSS error #%d", PORT_GetError()));
return NS_ERROR_FAILURE;
}
unsigned long serial;
unsigned char* serialBytes = reinterpret_cast<unsigned char *>(&serial);
- SECStatus srv = PK11_GenerateRandomOnSlot(aSlot, serialBytes, sizeof(serial));
+ SECStatus srv = PK11_GenerateRandomOnSlot(aSlot.get(), serialBytes,
+ sizeof(serial));
if (srv != SECSuccess) {
MOZ_LOG(gNSSTokenLog, LogLevel::Warning,
("Failed to gen serial, NSS error #%d", PORT_GetError()));
return NS_ERROR_FAILURE;
}
// Ensure that the most significant bit isn't set (which would
// indicate a negative number, which isn't valid for serial
// numbers).
@@ -315,82 +316,83 @@ nsNSSU2FToken::Init()
return NS_ERROR_FAILURE;
}
nsNSSShutDownPreventionLock locker;
if (isAlreadyShutDown()) {
return NS_ERROR_NOT_AVAILABLE;
}
- ScopedPK11SlotInfo slot(PK11_GetInternalKeySlot());
+ UniquePK11SlotInfo slot(PK11_GetInternalKeySlot());
MOZ_ASSERT(slot.get());
// Search for an existing wrapping key, or create one.
- nsresult rv = GetOrCreateWrappingKey(slot.get(), locker);
+ nsresult rv = GetOrCreateWrappingKey(slot, locker);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
mInitialized = true;
MOZ_LOG(gNSSTokenLog, LogLevel::Debug, ("U2F Soft Token initialized."));
return NS_OK;
}
// Convert a Private Key object into an opaque key handle, using AES Key Wrap
// and aWrappingKey to convert aPrivKey.
static SECItem*
-KeyHandleFromPrivateKey(PK11SlotInfo* aSlot,
+KeyHandleFromPrivateKey(const UniquePK11SlotInfo& aSlot,
PK11SymKey* aWrappingKey,
SECKEYPrivateKey* aPrivKey,
const nsNSSShutDownPreventionLock&)
{
ScopedSECItem wrappedKey(SECITEM_AllocItem(/* default arena */ nullptr,
/* no buffer */ nullptr,
kWrappedKeyBufLen));
if (!wrappedKey) {
MOZ_LOG(gNSSTokenLog, LogLevel::Warning,
("Failed to allocate memory, NSS error #%d", PORT_GetError()));
return nullptr;
}
ScopedSECItem param(PK11_ParamFromIV(CKM_NSS_AES_KEY_WRAP_PAD,
/* default IV */ nullptr ));
- SECStatus srv = PK11_WrapPrivKey(aSlot, aWrappingKey, aPrivKey,
+ SECStatus srv = PK11_WrapPrivKey(aSlot.get(), aWrappingKey, aPrivKey,
CKM_NSS_AES_KEY_WRAP_PAD, param,
wrappedKey.get(), /* wincx */ nullptr);
if (srv != SECSuccess) {
MOZ_LOG(gNSSTokenLog, LogLevel::Warning,
("Failed to wrap U2F key, NSS error #%d", PORT_GetError()));
return nullptr;
}
return wrappedKey.forget();
}
// Convert an opaque key handle aKeyHandle back into a Private Key object, using
// aWrappingKey and the AES Key Wrap algorithm.
static SECKEYPrivateKey*
-PrivateKeyFromKeyHandle(PK11SlotInfo* aSlot, PK11SymKey* aWrappingKey,
+PrivateKeyFromKeyHandle(const UniquePK11SlotInfo& aSlot,
+ PK11SymKey* aWrappingKey,
uint8_t* aKeyHandle, uint32_t aKeyHandleLen,
const nsNSSShutDownPreventionLock&)
{
ScopedAutoSECItem pubKey(kPublicKeyLen);
ScopedAutoSECItem keyHandleItem(aKeyHandleLen);
memcpy(keyHandleItem.data, aKeyHandle, keyHandleItem.len);
ScopedSECItem param(PK11_ParamFromIV(CKM_NSS_AES_KEY_WRAP_PAD,
/* default IV */ nullptr ));
CK_ATTRIBUTE_TYPE usages[] = { CKA_SIGN };
int usageCount = 1;
SECKEYPrivateKey* unwrappedKey;
- unwrappedKey = PK11_UnwrapPrivKey(aSlot, aWrappingKey,
+ unwrappedKey = PK11_UnwrapPrivKey(aSlot.get(), aWrappingKey,
CKM_NSS_AES_KEY_WRAP_PAD,
param, &keyHandleItem,
/* no nickname */ nullptr,
/* discard pubkey */ &pubKey,
/* not permanent */ PR_FALSE,
/* non-exportable */ PR_TRUE,
CKK_EC, usages, usageCount,
/* wincx */ nullptr);
@@ -432,21 +434,21 @@ nsNSSU2FToken::IsRegistered(uint8_t* aKe
return NS_ERROR_FAILURE;
}
MOZ_ASSERT(mInitialized);
if (!mInitialized) {
return NS_ERROR_FAILURE;
}
- ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
+ UniquePK11SlotInfo slot(PK11_GetInternalSlot());
MOZ_ASSERT(slot.get());
// Decode the key handle
- ScopedSECKEYPrivateKey privKey(PrivateKeyFromKeyHandle(slot.get(),
+ UniqueSECKEYPrivateKey privKey(PrivateKeyFromKeyHandle(slot,
mWrappingKey.get(),
aKeyHandle,
aKeyHandleLen,
locker));
*aResult = (privKey.get() != nullptr);
return NS_OK;
}
@@ -495,41 +497,40 @@ nsNSSU2FToken::Register(uint8_t* aApplic
MOZ_ASSERT(mInitialized);
if (!mInitialized) {
return NS_ERROR_NOT_INITIALIZED;
}
// We should already have a wrapping key
MOZ_ASSERT(mWrappingKey);
- ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
+ UniquePK11SlotInfo slot(PK11_GetInternalSlot());
MOZ_ASSERT(slot.get());
// Construct a one-time-use Attestation Certificate
ScopedSECKEYPrivateKey attestPrivKey;
ScopedCERTCertificate attestCert;
- nsresult rv = GetAttestationCertificate(slot.get(), attestPrivKey, attestCert,
+ nsresult rv = GetAttestationCertificate(slot, attestPrivKey, attestCert,
locker);
if (NS_WARN_IF(NS_FAILED(rv))) {
return NS_ERROR_FAILURE;
}
MOZ_ASSERT(attestCert);
MOZ_ASSERT(attestPrivKey);
// Generate a new keypair; the private will be wrapped into a Key Handle
ScopedSECKEYPrivateKey privKey;
ScopedSECKEYPublicKey pubKey;
- rv = GenEcKeypair(slot.get(), privKey, pubKey, locker);
+ rv = GenEcKeypair(slot, privKey, pubKey, locker);
if (NS_WARN_IF(NS_FAILED(rv))) {
return NS_ERROR_FAILURE;
}
// The key handle will be the result of keywrap(privKey, key=mWrappingKey)
- ScopedSECItem keyHandleItem(KeyHandleFromPrivateKey(slot.get(),
- mWrappingKey.get(),
+ UniqueSECItem keyHandleItem(KeyHandleFromPrivateKey(slot, mWrappingKey.get(),
privKey.get(),
locker));
if (!keyHandleItem.get()) {
return NS_ERROR_FAILURE;
}
// Sign the challenge using the Attestation privkey (from attestCert)
mozilla::dom::CryptoBuffer signedDataBuf;
@@ -623,29 +624,29 @@ nsNSSU2FToken::Sign(uint8_t* aApplicatio
MOZ_ASSERT(mInitialized);
if (!mInitialized) {
return NS_ERROR_NOT_INITIALIZED;
}
MOZ_ASSERT(mWrappingKey);
- ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
+ UniquePK11SlotInfo slot(PK11_GetInternalSlot());
MOZ_ASSERT(slot.get());
if ((aChallengeLen != kParamLen) || (aApplicationLen != kParamLen)) {
MOZ_LOG(gNSSTokenLog, LogLevel::Warning,
("Parameter lengths are wrong! challenge=%d app=%d expected=%d",
aChallengeLen, aApplicationLen, kParamLen));
return NS_ERROR_ILLEGAL_VALUE;
}
// Decode the key handle
- ScopedSECKEYPrivateKey privKey(PrivateKeyFromKeyHandle(slot.get(),
+ UniqueSECKEYPrivateKey privKey(PrivateKeyFromKeyHandle(slot,
mWrappingKey.get(),
aKeyHandle,
aKeyHandleLen,
locker));
if (!privKey.get()) {
MOZ_LOG(gNSSTokenLog, LogLevel::Warning, ("Couldn't get the priv key!"));
return NS_ERROR_FAILURE;
}
--- a/security/manager/ssl/nsNSSU2FToken.h
+++ b/security/manager/ssl/nsNSSU2FToken.h
@@ -31,13 +31,13 @@ public:
private:
bool mInitialized;
mozilla::ScopedPK11SymKey mWrappingKey;
static const nsCString mSecretNickname;
static const nsString mVersion;
~nsNSSU2FToken();
- nsresult GetOrCreateWrappingKey(PK11SlotInfo* aSlot,
+ nsresult GetOrCreateWrappingKey(const mozilla::UniquePK11SlotInfo& aSlot,
const nsNSSShutDownPreventionLock&);
};
#endif // nsNSSU2FToken_h
--- a/security/manager/ssl/nsNTLMAuthModule.cpp
+++ b/security/manager/ssl/nsNTLMAuthModule.cpp
@@ -2,35 +2,36 @@
/* 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 "nsNTLMAuthModule.h"
#include <time.h>
+#include "ScopedNSSTypes.h"
#include "md4.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/Endian.h"
#include "mozilla/Likely.h"
+#include "mozilla/Logging.h"
#include "mozilla/Preferences.h"
#include "mozilla/Snprintf.h"
#include "mozilla/Telemetry.h"
#include "nsCOMPtr.h"
#include "nsComponentManagerUtils.h"
+#include "nsICryptoHMAC.h"
#include "nsICryptoHash.h"
-#include "nsICryptoHMAC.h"
#include "nsIKeyModule.h"
#include "nsKeyModule.h"
+#include "nsNSSShutDown.h"
#include "nsNativeCharsetUtils.h"
#include "nsNetCID.h"
-#include "nsNSSShutDown.h"
#include "nsUnicharUtils.h"
#include "pk11pub.h"
-#include "mozilla/Logging.h"
#include "prsystem.h"
static bool sNTLMv1Forced = false;
static mozilla::LazyLogModule sNTLMLog("NTLM");
#define LOG(x) MOZ_LOG(sNTLMLog, mozilla::LogLevel::Debug, x)
#define LOG_ENABLED() MOZ_LOG_TEST(sNTLMLog, mozilla::LogLevel::Debug)
@@ -1097,33 +1098,32 @@ des_makekey(const uint8_t *raw, uint8_t
key[7] = des_setkeyparity((raw[6] << 1));
}
// run des encryption algorithm (using NSS)
static void
des_encrypt(const uint8_t *key, const uint8_t *src, uint8_t *hash)
{
CK_MECHANISM_TYPE cipherMech = CKM_DES_ECB;
- PK11SlotInfo *slot = nullptr;
PK11SymKey *symkey = nullptr;
PK11Context *ctxt = nullptr;
SECItem keyItem, *param = nullptr;
SECStatus rv;
unsigned int n;
-
- slot = PK11_GetBestSlot(cipherMech, nullptr);
+
+ mozilla::UniquePK11SlotInfo slot(PK11_GetBestSlot(cipherMech, nullptr));
if (!slot)
{
NS_ERROR("no slot");
goto done;
}
keyItem.data = (uint8_t *) key;
keyItem.len = 8;
- symkey = PK11_ImportSymKey(slot, cipherMech,
+ symkey = PK11_ImportSymKey(slot.get(), cipherMech,
PK11_OriginUnwrap, CKA_ENCRYPT,
&keyItem, nullptr);
if (!symkey)
{
NS_ERROR("no symkey");
goto done;
}
@@ -1156,11 +1156,9 @@ des_encrypt(const uint8_t *key, const ui
done:
if (ctxt)
PK11_DestroyContext(ctxt, true);
if (symkey)
PK11_FreeSymKey(symkey);
if (param)
SECITEM_FreeItem(param, true);
- if (slot)
- PK11_FreeSlot(slot);
}
--- a/security/manager/ssl/nsPKCS12Blob.cpp
+++ b/security/manager/ssl/nsPKCS12Blob.cpp
@@ -10,17 +10,16 @@
#include "nsICertificateDialogs.h"
#include "nsIDirectoryService.h"
#include "nsIFile.h"
#include "nsIInputStream.h"
#include "nsKeygenHandler.h" // For GetSlotWithMechanism
#include "nsNSSCertificate.h"
#include "nsNSSComponent.h"
#include "nsNSSHelper.h"
-#include "nsNSSHelper.h"
#include "nsNSSShutDown.h"
#include "nsNetUtil.h"
#include "nsPK11TokenDB.h"
#include "nsReadableUtils.h"
#include "nsString.h"
#include "nsThreadUtils.h"
#include "pkix/pkixtypes.h"
#include "prmem.h"
@@ -141,49 +140,49 @@ nsPKCS12Blob::ImportFromFileHelper(nsIFi
nsPKCS12Blob::RetryReason &aWantRetry)
{
nsNSSShutDownPreventionLock locker;
nsresult rv = NS_OK;
SECStatus srv = SECSuccess;
SEC_PKCS12DecoderContext *dcx = nullptr;
SECItem unicodePw;
- PK11SlotInfo *slot=nullptr;
+ UniquePK11SlotInfo slot;
nsXPIDLString tokenName;
unicodePw.data = nullptr;
-
+
aWantRetry = rr_do_not_retry;
if (aImportMode == im_try_zero_length_secitem)
{
unicodePw.len = 0;
}
else
{
// get file password (unicode)
rv = getPKCS12FilePassword(&unicodePw);
if (NS_FAILED(rv)) goto finish;
if (!unicodePw.data) {
handleError(PIP_PKCS12_USER_CANCELED);
return NS_OK;
}
}
-
+
mToken->GetTokenName(getter_Copies(tokenName));
{
NS_ConvertUTF16toUTF8 tokenNameCString(tokenName);
- slot = PK11_FindSlotByName(tokenNameCString.get());
+ slot = UniquePK11SlotInfo(PK11_FindSlotByName(tokenNameCString.get()));
}
if (!slot) {
srv = SECFailure;
goto finish;
}
// initialize the decoder
- dcx = SEC_PKCS12DecoderStart(&unicodePw, slot, nullptr,
+ dcx = SEC_PKCS12DecoderStart(&unicodePw, slot.get(), nullptr,
digest_open, digest_close,
digest_read, digest_write,
this);
if (!dcx) {
srv = SECFailure;
goto finish;
}
// read input file and feed it to the decoder
@@ -223,21 +222,19 @@ finish:
aWantRetry = rr_bad_password;
handleError(PIP_PKCS12_NSS_ERROR);
}
}
else
{
handleError(PIP_PKCS12_NSS_ERROR);
}
- } else if (NS_FAILED(rv)) {
+ } else if (NS_FAILED(rv)) {
handleError(PIP_PKCS12_RESTORE_FAILED);
}
- if (slot)
- PK11_FreeSlot(slot);
// finish the decoder
if (dcx)
SEC_PKCS12DecoderFinish(dcx);
SECITEM_ZfreeItem(&unicodePw, false);
return NS_OK;
}
static bool
--- a/security/manager/ssl/nsRandomGenerator.cpp
+++ b/security/manager/ssl/nsRandomGenerator.cpp
@@ -1,14 +1,15 @@
/* 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 "nsRandomGenerator.h"
+#include "ScopedNSSTypes.h"
#include "nsNSSComponent.h"
#include "pk11pub.h"
#include "prerror.h"
#include "secerr.h"
NS_IMPL_ISUPPORTS(nsRandomGenerator, nsIRandomGenerator)
NS_IMETHODIMP
@@ -18,28 +19,27 @@ nsRandomGenerator::GenerateRandomBytes(u
NS_ENSURE_ARG_POINTER(aBuffer);
*aBuffer = nullptr;
nsNSSShutDownPreventionLock locker;
if (isAlreadyShutDown()) {
return NS_ERROR_NOT_AVAILABLE;
}
- mozilla::ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
+ mozilla::UniquePK11SlotInfo slot(PK11_GetInternalSlot());
if (!slot) {
return NS_ERROR_FAILURE;
}
uint8_t* buf = reinterpret_cast<uint8_t*>(moz_xmalloc(aLength));
if (!buf) {
return NS_ERROR_OUT_OF_MEMORY;
}
- SECStatus srv = PK11_GenerateRandomOnSlot(slot, buf, aLength);
-
+ SECStatus srv = PK11_GenerateRandomOnSlot(slot.get(), buf, aLength);
if (srv != SECSuccess) {
free(buf);
return NS_ERROR_FAILURE;
}
*aBuffer = buf;
return NS_OK;
--- a/security/manager/ssl/nsSmartCardMonitor.cpp
+++ b/security/manager/ssl/nsSmartCardMonitor.cpp
@@ -1,19 +1,21 @@
/* 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 "nspr.h"
+#include "nsSmartCardMonitor.h"
+
+#include "ScopedNSSTypes.h"
#include "mozilla/Services.h"
#include "mozilla/unused.h"
#include "nsIObserverService.h"
#include "nsServiceManagerUtils.h"
-#include "nsSmartCardMonitor.h"
#include "nsThreadUtils.h"
+#include "nspr.h"
#include "pk11func.h"
using namespace mozilla;
//
// The SmartCard monitoring thread should start up for each module we load
// that has removable tokens. This code calls an NSS function which waits
// until there is a change in the token state. NSS uses the
@@ -313,17 +315,16 @@ SmartCardMonitoringThread::SendEvent(con
NS_DispatchToMainThread(runnable);
}
//
// This is the main loop.
//
void SmartCardMonitoringThread::Execute()
{
- PK11SlotInfo* slot;
const char* tokenName;
//
// populate token names for already inserted tokens.
//
PK11SlotList* sl = PK11_FindSlotsByNames(mModule->dllName, nullptr, nullptr,
true);
@@ -334,55 +335,54 @@ void SmartCardMonitoringThread::Execute(
SetTokenName(PK11_GetSlotID(sle->slot), PK11_GetTokenName(sle->slot),
PK11_GetSlotSeries(sle->slot));
}
PK11_FreeSlotList(sl);
}
// loop starts..
do {
- slot = SECMOD_WaitForAnyTokenEvent(mModule, 0, PR_SecondsToInterval(1));
+ UniquePK11SlotInfo slot(
+ SECMOD_WaitForAnyTokenEvent(mModule, 0, PR_SecondsToInterval(1)));
if (!slot) {
break;
}
// now we have a potential insertion or removal event, see if the slot
// is present to determine which it is...
- if (PK11_IsPresent(slot)) {
+ if (PK11_IsPresent(slot.get())) {
// insertion
- CK_SLOT_ID slotID = PK11_GetSlotID(slot);
- uint32_t series = PK11_GetSlotSeries(slot);
+ CK_SLOT_ID slotID = PK11_GetSlotID(slot.get());
+ uint32_t series = PK11_GetSlotSeries(slot.get());
// skip spurious insertion events...
if (series != GetTokenSeries(slotID)) {
// if there's a token name, then we have not yet issued a remove
// event for the previous token, do so now...
tokenName = GetTokenName(slotID);
if (tokenName) {
SendEvent(NS_LITERAL_STRING("smartcard-remove"), tokenName);
}
- tokenName = PK11_GetTokenName(slot);
+ tokenName = PK11_GetTokenName(slot.get());
// save the token name and series
SetTokenName(slotID, tokenName, series);
SendEvent(NS_LITERAL_STRING("smartcard-insert"), tokenName);
}
} else {
// retrieve token name
- CK_SLOT_ID slotID = PK11_GetSlotID(slot);
+ CK_SLOT_ID slotID = PK11_GetSlotID(slot.get());
tokenName = GetTokenName(slotID);
// if there's not a token name, then the software isn't expecting
// a (or another) remove event.
if (tokenName) {
SendEvent(NS_LITERAL_STRING("smartcard-remove"), tokenName);
// clear the token name (after we send it)
SetTokenName(slotID, nullptr, 0);
}
}
- PK11_FreeSlot(slot);
-
} while (1);
}
// accessor to help searching active Monitoring threads
const SECMODModule* SmartCardMonitoringThread::GetModule()
{
return mModule;
}
--- a/security/manager/ssl/tests/unit/tlsserver/lib/TLSServer.cpp
+++ b/security/manager/ssl/tests/unit/tlsserver/lib/TLSServer.cpp
@@ -3,17 +3,16 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "TLSServer.h"
#include <stdio.h>
#include <string>
#include <vector>
-#include "ScopedNSSTypes.h"
#include "base64.h"
#include "mozilla/Move.h"
#include "mozilla/Snprintf.h"
#include "nspr.h"
#include "nss.h"
#include "plarenas.h"
#include "prenv.h"
#include "prerror.h"
@@ -136,31 +135,31 @@ AddKeyFromFile(const char* basePath, con
return SECFailure;
}
ScopedSECItem secitem(::SECITEM_AllocItem(nullptr, nullptr, binLength));
if (!secitem) {
PrintPRError("SECITEM_AllocItem failed");
return SECFailure;
}
PORT_Memcpy(secitem->data, bin.get(), binLength);
- ScopedPK11SlotInfo slot(PK11_GetInternalKeySlot());
+ UniquePK11SlotInfo slot(PK11_GetInternalKeySlot());
if (!slot) {
PrintPRError("PK11_GetInternalKeySlot failed");
return SECFailure;
}
- if (PK11_NeedUserInit(slot)) {
- if (PK11_InitPin(slot, nullptr, nullptr) != SECSuccess) {
+ if (PK11_NeedUserInit(slot.get())) {
+ if (PK11_InitPin(slot.get(), nullptr, nullptr) != SECSuccess) {
PrintPRError("PK11_InitPin failed");
return SECFailure;
}
}
SECKEYPrivateKey* privateKey;
- if (PK11_ImportDERPrivateKeyInfoAndReturnKey(slot, secitem, nullptr, nullptr,
- true, false, KU_ALL,
- &privateKey, nullptr)
+ if (PK11_ImportDERPrivateKeyInfoAndReturnKey(slot.get(), secitem.get(),
+ nullptr, nullptr, true, false,
+ KU_ALL, &privateKey, nullptr)
!= SECSuccess) {
PrintPRError("PK11_ImportDERPrivateKeyInfoAndReturnKey failed");
return SECFailure;
}
SECKEY_DestroyPrivateKey(privateKey);
return SECSuccess;
}
@@ -193,17 +192,17 @@ AddCertificateFromFile(const char* baseP
UniqueCERTCertificate cert(CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
&certDER, nullptr, false,
true));
PORT_Free(certDER.data);
if (!cert) {
PrintPRError("CERT_NewTempCertificate failed");
return SECFailure;
}
- ScopedPK11SlotInfo slot(PK11_GetInternalKeySlot());
+ UniquePK11SlotInfo slot(PK11_GetInternalKeySlot());
if (!slot) {
PrintPRError("PK11_GetInternalKeySlot failed");
return SECFailure;
}
// The nickname is the filename without '.pem'.
std::string nickname(filename, strlen(filename) - 4);
rv = PK11_ImportCert(slot.get(), cert.get(), CK_INVALID_HANDLE,
nickname.c_str(), false);
@@ -458,17 +457,21 @@ ConfigSecureServerWithNamedCert(PRFileDe
if (SECITEM_CopyItem(certList->arena, certList->certs + 1,
&issuerCert->derCert) != SECSuccess) {
PrintPRError("SECITEM_CopyItem failed");
return SECFailure;
}
certList->len = 2;
}
- ScopedPK11SlotInfo slot(PK11_GetInternalKeySlot());
+ UniquePK11SlotInfo slot(PK11_GetInternalKeySlot());
+ if (!slot) {
+ PrintPRError("PK11_GetInternalKeySlot failed");
+ return SECFailure;
+ }
UniqueSECKEYPrivateKey key(
PK11_FindKeyByDERCert(slot.get(), cert.get(), nullptr));
if (!key) {
PrintPRError("PK11_FindKeyByDERCert failed");
return SECFailure;
}
SSLKEAType certKEA = NSS_FindCertKEAType(cert.get());