Bug 891066, Part 5: Switch to security::pkix::ScopedCERTCertList, r=cviecco
authorBrian Smith <brian@briansmith.org>
Wed, 22 Jan 2014 17:13:19 -0800
changeset 165297 aaad90a5936fe7c70754712365d4b06338dd43f3
parent 165296 4c4220bf9e14a7c5871f5631e82fc253617996d4
child 165298 3e3ddb3ce8d331b9898c04e1bb90764738366edc
push id4582
push usercbook@mozilla.com
push dateMon, 27 Jan 2014 13:18:52 +0000
treeherderfx-team@a3451e7f4856 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewerscviecco
bugs891066
milestone29.0a1
Bug 891066, Part 5: Switch to security::pkix::ScopedCERTCertList, r=cviecco
security/certverifier/CertVerifier.cpp
security/certverifier/CertVerifier.h
security/certverifier/ExtendedValidation.cpp
security/insanity/include/insanity/ScopedPtr.h
security/manager/ssl/src/SSLServerCertVerification.cpp
security/manager/ssl/src/TransportSecurityInfo.cpp
security/manager/ssl/src/nsCMS.cpp
security/manager/ssl/src/nsCertOverrideService.cpp
security/manager/ssl/src/nsCertPicker.cpp
security/manager/ssl/src/nsCertTree.cpp
security/manager/ssl/src/nsCertTree.h
security/manager/ssl/src/nsCrypto.cpp
security/manager/ssl/src/nsNSSCallbacks.cpp
security/manager/ssl/src/nsNSSCertCache.cpp
security/manager/ssl/src/nsNSSCertificate.cpp
security/manager/ssl/src/nsNSSCertificate.h
security/manager/ssl/src/nsNSSCertificateDB.cpp
security/manager/ssl/src/nsNSSIOLayer.cpp
security/manager/ssl/src/nsPKCS12Blob.cpp
security/manager/ssl/src/nsPKCS12Blob.h
security/manager/ssl/src/nsRecentBadCerts.cpp
security/manager/ssl/tests/gtest/moz.build
--- a/security/certverifier/CertVerifier.cpp
+++ b/security/certverifier/CertVerifier.cpp
@@ -1,21 +1,29 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* 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 "CertVerifier.h"
+
+#include <stdint.h>
+
+#include "insanity/pkixtypes.h"
 #include "ExtendedValidation.h"
-#include "ScopedNSSTypes.h"
 #include "cert.h"
 #include "secerr.h"
 #include "prerror.h"
 
+// ScopedXXX in this file are insanity::pkix::ScopedXXX, not
+// mozilla::ScopedXXX.
+using namespace insanity::pkix;
+using namespace mozilla::psm;
+
 #ifdef PR_LOGGING
 extern PRLogModuleInfo* gPIPNSSLog;
 #endif
 
 namespace mozilla { namespace psm {
 
 const CertVerifier::Flags CertVerifier::FLAG_LOCAL_ONLY = 1;
 const CertVerifier::Flags CertVerifier::FLAG_NO_DV_FALLBACK_FOR_EV = 2;
@@ -39,17 +47,17 @@ CertVerifier::~CertVerifier()
 {
 }
 
 static SECStatus
 ClassicVerifyCert(CERTCertificate* cert,
                   const SECCertificateUsage usage,
                   const PRTime time,
                   void* pinArg,
-                  /*optional out*/ CERTCertList** validationChain,
+                  /*optional out*/ ScopedCERTCertList* validationChain,
                   /*optional out*/ CERTVerifyLog* verifyLog)
 {
   SECStatus rv;
   SECCertUsage enumUsage;
   if (validationChain) {
     switch(usage){
       case  certificateUsageSSLClient:
         enumUsage = certUsageSSLClient;
@@ -107,23 +115,38 @@ ClassicVerifyCert(CERTCertificate* cert,
     *validationChain = CERT_GetCertChainFromCert(cert, time, enumUsage);
     if (!*validationChain) {
       rv = SECFailure;
     }
   }
   return rv;
 }
 
+#ifndef NSS_NO_LIBPKIX
+static void
+destroyCertListThatShouldNotExist(CERTCertList** certChain)
+{
+  PR_ASSERT(certChain);
+  PR_ASSERT(!*certChain);
+  if (certChain && *certChain) {
+    // There SHOULD not be a validation chain on failure, asserion here for
+    // the debug builds AND a fallback for production builds
+    CERT_DestroyCertList(*certChain);
+    *certChain = nullptr;
+  }
+}
+#endif
+
 SECStatus
 CertVerifier::VerifyCert(CERTCertificate* cert,
                          const SECCertificateUsage usage,
                          const PRTime time,
                          void* pinArg,
                          const Flags flags,
-                         /*optional out*/ CERTCertList** validationChain,
+                         /*optional out*/ ScopedCERTCertList* validationChain,
                          /*optional out*/ SECOidTag* evOidPolicy,
                          /*optional out*/ CERTVerifyLog* verifyLog)
 {
   if (!cert ||
       ((flags & FLAG_NO_DV_FALLBACK_FOR_EV) &&
       (usage != certificateUsageSSLServer || !evOidPolicy)))
   {
     PR_NOT_REACHED("Invalid arguments to CertVerifier::VerifyCert");
@@ -142,17 +165,16 @@ CertVerifier::VerifyCert(CERTCertificate
     case certificateUsageSSLServer:
     case certificateUsageSSLCA:
     case certificateUsageEmailSigner:
     case certificateUsageEmailRecipient:
     case certificateUsageObjectSigner:
     case certificateUsageStatusResponder:
       break;
     default:
-      NS_WARNING("Calling VerifyCert with invalid usage");
       PORT_SetError(SEC_ERROR_INVALID_ARGS);
       return SECFailure;
   }
 
 #ifndef NSS_NO_LIBPKIX
   ScopedCERTCertList trustAnchors;
   SECStatus rv;
   SECOidTag evPolicy = SEC_OID_UNKNOWN;
@@ -174,36 +196,36 @@ CertVerifier::VerifyCert(CERTCertificate
         evPolicy = SEC_OID_UNKNOWN;
       }
     } else {
       // Do not setup EV verification params
       evPolicy = SEC_OID_UNKNOWN;
     }
   }
 
-  MOZ_ASSERT_IF(evPolicy != SEC_OID_UNKNOWN, trustAnchors);
+  PR_ASSERT(evPolicy == SEC_OID_UNKNOWN || trustAnchors);
 
   size_t i = 0;
   size_t validationChainLocation = 0;
   size_t validationTrustAnchorLocation = 0;
   CERTValOutParam cvout[4];
   if (verifyLog) {
      cvout[i].type = cert_po_errorLog;
      cvout[i].value.pointer.log = verifyLog;
      ++i;
   }
   if (validationChain) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("VerifyCert: setting up validation chain outparam.\n"));
     validationChainLocation = i;
     cvout[i].type = cert_po_certList;
-    cvout[i].value.pointer.cert = nullptr;
+    cvout[i].value.pointer.chain = nullptr;
     ++i;
     validationTrustAnchorLocation = i;
     cvout[i].type = cert_po_trustAnchor;
-    cvout[i].value.pointer.chain = nullptr;
+    cvout[i].value.pointer.cert = nullptr;
     ++i;
   }
   cvout[i].type = cert_po_end;
 
   CERTRevocationFlags rev;
 
   CERTRevocationMethodIndex revPreferredMethods[2];
   rev.leafTests.preferred_methods =
@@ -263,42 +285,38 @@ CertVerifier::VerifyCert(CERTCertificate
 
     rev.leafTests.preferred_methods[0] =
     rev.chainTests.preferred_methods[0] = cert_revocation_method_ocsp;
 
     cvin[i].type = cert_pi_policyOID;
     cvin[i].value.arraySize = 1;
     cvin[i].value.array.oids = &evPolicy;
     ++i;
-    MOZ_ASSERT(trustAnchors);
+    PR_ASSERT(trustAnchors);
     cvin[i].type = cert_pi_trustAnchors;
-    cvin[i].value.pointer.chain = trustAnchors;
+    cvin[i].value.pointer.chain = trustAnchors.get();
     ++i;
 
     cvin[i].type = cert_pi_end;
 
     rv = CERT_PKIXVerifyCert(cert, usage, cvin, cvout, pinArg);
     if (rv == SECSuccess) {
       if (evOidPolicy) {
         *evOidPolicy = evPolicy;
       }
       PR_LOG(gPIPNSSLog, PR_LOG_DEBUG,
              ("VerifyCert: successful CERT_PKIXVerifyCert(ev) \n"));
       goto pkix_done;
     }
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG,
            ("VerifyCert: failed CERT_PKIXVerifyCert(ev)\n"));
 
-    if (validationChain && *validationChain) {
-      // There SHOULD not be a validation chain on failure, asserion here for
-      // the debug builds AND a fallback for production builds
-      MOZ_ASSERT(false,
-                 "certPKIXVerifyCert returned failure AND a validationChain");
-      CERT_DestroyCertList(*validationChain);
-      *validationChain = nullptr;
+    if (validationChain) {
+      destroyCertListThatShouldNotExist(
+        &cvout[validationChainLocation].value.pointer.chain);
     }
 
     if (verifyLog) {
       // Cleanup the log so that it is ready the the next validation
       CERTVerifyLogNode* i_node;
       for (i_node = verifyLog->head; i_node; i_node = i_node->next) {
          //destroy cert if any.
          if (i_node->cert) {
@@ -408,34 +426,31 @@ pkix_done:
         return SECFailure;
       }
       PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("VerifyCert: I have a chain\n"));
       *validationChain = cvout[validationChainLocation].value.pointer.chain;
       if (trustAnchor) {
         // we should only add the issuer to the chain if it is not already
         // present. On CA cert checking, the issuer is the same cert, so in
         // that case we do not add the cert to the chain.
-        if (!CERT_CompareCerts(trustAnchor, cert)) {
+        if (!CERT_CompareCerts(trustAnchor.get(), cert)) {
           PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("VerifyCert:  adding issuer to tail for display\n"));
           // note: rv is reused to catch errors on cert creation!
-          ScopedCERTCertificate tempCert(CERT_DupCertificate(trustAnchor));
-          rv = CERT_AddCertToListTail(*validationChain, tempCert);
+          ScopedCERTCertificate tempCert(CERT_DupCertificate(trustAnchor.get()));
+          rv = CERT_AddCertToListTail(validationChain->get(), tempCert.get());
           if (rv == SECSuccess) {
-            tempCert.forget(); // ownership traferred to validationChain
+            tempCert.release(); // ownership traferred to validationChain
           } else {
-            CERT_DestroyCertList(*validationChain);
             *validationChain = nullptr;
           }
         }
       }
     } else {
-      // Validation was a fail, clean up if needed
-      if (cvout[validationChainLocation].value.pointer.chain) {
-        CERT_DestroyCertList(cvout[validationChainLocation].value.pointer.chain);
-      }
+      destroyCertListThatShouldNotExist(
+        &cvout[validationChainLocation].value.pointer.chain);
     }
   }
 
   return rv;
 #endif
 }
 
 } } // namespace mozilla::psm
--- a/security/certverifier/CertVerifier.h
+++ b/security/certverifier/CertVerifier.h
@@ -3,17 +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 mozilla_psm__CertVerifier_h
 #define mozilla_psm__CertVerifier_h
 
 #include "certt.h"
-#include "insanity/ScopedPtr.h"
+#include "insanity/pkixtypes.h"
 
 namespace mozilla { namespace psm {
 
 class CertVerifier
 {
 public:
   typedef unsigned int Flags;
   // XXX: FLAG_LOCAL_ONLY is ignored in the classic verification case
@@ -23,19 +23,19 @@ public:
 
   // *evOidPolicy == SEC_OID_UNKNOWN means the cert is NOT EV
   // Only one usage per verification is supported.
   SECStatus VerifyCert(CERTCertificate* cert,
                        const SECCertificateUsage usage,
                        const PRTime time,
                        void* pinArg,
                        const Flags flags = 0,
-                       /*optional out*/ CERTCertList** validationChain = nullptr,
-                       /*optional out*/ SECOidTag* evOidPolicy = nullptr ,
-                       /*optional out*/ CERTVerifyLog* verifyLog = nullptr);
+      /*optional out*/ insanity::pkix::ScopedCERTCertList* validationChain = nullptr,
+      /*optional out*/ SECOidTag* evOidPolicy = nullptr ,
+      /*optional out*/ CERTVerifyLog* verifyLog = nullptr);
 
   enum implementation_config {
     classic = 0,
 #ifndef NSS_NO_LIBPKIX
     libpkix = 1,
 #endif
   };
 
--- a/security/certverifier/ExtendedValidation.cpp
+++ b/security/certverifier/ExtendedValidation.cpp
@@ -905,27 +905,27 @@ IdentityInfoInit()
 #endif
       PR_NOT_REACHED("Could not find EV root in NSS storage");
       continue;
     }
 
     unsigned char certFingerprint[20];
     rv = PK11_HashBuf(SEC_OID_SHA1, certFingerprint,
                       entry.cert->derCert.data, entry.cert->derCert.len);
-    MOZ_ASSERT(rv == SECSuccess);
+    PR_ASSERT(rv == SECSuccess);
     if (rv == SECSuccess) {
       bool same = !memcmp(certFingerprint, entry.ev_root_sha1_fingerprint, 20);
-      MOZ_ASSERT(same);
+      PR_ASSERT(same);
       if (same) {
 
         SECItem ev_oid_item;
         ev_oid_item.data = nullptr;
         ev_oid_item.len = 0;
         rv = SEC_StringToOID(nullptr, &ev_oid_item, entry.dotted_oid, 0);
-        MOZ_ASSERT(rv == SECSuccess);
+        PR_ASSERT(rv == SECSuccess);
         if (rv == SECSuccess) {
           entry.oid_tag = register_oid(&ev_oid_item, entry.oid_name);
           if (entry.oid_tag == SEC_OID_UNKNOWN) {
             rv = SECFailure;
           }
           SECITEM_FreeItem(&ev_oid_item, false);
         }
       } else {
--- a/security/insanity/include/insanity/ScopedPtr.h
+++ b/security/insanity/include/insanity/ScopedPtr.h
@@ -66,11 +66,39 @@ public:
 
 protected:
   T* mValue;
 
   ScopedPtr(const ScopedPtr&) /* = delete */;
   void operator=(const ScopedPtr&) /* = delete */;
 };
 
+template <typename T, void(*Destroyer)(T*)>
+inline bool
+operator==(T* a, const ScopedPtr<T, Destroyer>& b)
+{
+  return a == b.get();
+}
+
+template <typename T, void(*Destroyer)(T*)>
+inline bool
+operator==(const ScopedPtr<T, Destroyer>& a, T* b)
+{
+  return a.get() == b;
+}
+
+template <typename T, void(*Destroyer)(T*)>
+inline bool
+operator!=(T* a, const ScopedPtr<T, Destroyer>& b)
+{
+  return a != b.get();
+}
+
+template <typename T, void(*Destroyer)(T*)>
+inline bool
+operator!=(const ScopedPtr<T, Destroyer>& a, T* b)
+{
+  return a.get() != b;
+}
+
 } } // namespace insanity::pkix
 
 #endif // insanity_pkix__ScopedPtr_h
--- a/security/manager/ssl/src/SSLServerCertVerification.cpp
+++ b/security/manager/ssl/src/SSLServerCertVerification.cpp
@@ -89,17 +89,17 @@
 // thread since they may do I/O, because many parts of nsNSSSocketInfo (the
 // subclass of TransportSecurityInfo used when validating certificates during
 // an SSL handshake) and the PSM NSS I/O layer are not thread-safe, and because
 // we need the event to interrupt the PR_Poll that may waiting for I/O on the
 // socket for which we are validating the cert.
 
 #include "SSLServerCertVerification.h"
 
-#include <cstring>
+#include "insanity/pkixtypes.h"
 
 #include "CertVerifier.h"
 #include "CryptoTask.h"
 #include "ExtendedValidation.h"
 #include "nsIBadCertListener2.h"
 #include "nsICertOverrideService.h"
 #include "nsISiteSecurityService.h"
 #include "nsNSSComponent.h"
@@ -629,17 +629,17 @@ private:
                                const void* fdForLogging,
                                TransportSecurityInfo* infoObject,
                                CERTCertificate* cert,
                                SECItem* stapledOCSPResponse,
                                uint32_t providerFlags);
   const RefPtr<SharedCertVerifier> mCertVerifier;
   const void* const mFdForLogging;
   const RefPtr<TransportSecurityInfo> mInfoObject;
-  const ScopedCERTCertificate mCert;
+  const insanity::pkix::ScopedCERTCertificate mCert;
   const uint32_t mProviderFlags;
   const TimeStamp mJobStartTime;
   const ScopedSECItem mStapledOCSPResponse;
 };
 
 SSLServerCertVerificationJob::SSLServerCertVerificationJob(
     const RefPtr<SharedCertVerifier>& certVerifier, const void* fdForLogging,
     TransportSecurityInfo* infoObject, CERTCertificate* cert,
@@ -654,17 +654,17 @@ SSLServerCertVerificationJob::SSLServerC
 {
 }
 
 SECStatus
 PSM_SSL_PKIX_AuthCertificate(CertVerifier& certVerifier,
                              CERTCertificate* peerCert,
                              nsIInterfaceRequestor* pinarg,
                              const char* hostname,
-                             CERTCertList** validationChain,
+                             insanity::pkix::ScopedCERTCertList* validationChain,
                              SECOidTag* evOidPolicy)
 {
     SECStatus rv = certVerifier.VerifyCert(peerCert, certificateUsageSSLServer,
                                            PR_Now(), pinarg, 0,
                                            validationChain, evOidPolicy);
 
     if (rv == SECSuccess) {
         // cert is OK. This is the client side of an SSL connection.
@@ -797,21 +797,22 @@ AuthCertificate(CertVerifier& certVerifi
     if (!certVerifier.mOCSPDownloadEnabled) {
       reasonsForNotFetching |= 2;
     }
 
     Telemetry::Accumulate(Telemetry::SSL_OCSP_MAY_FETCH,
                           reasonsForNotFetching);
   }
 
-  CERTCertList* verifyCertChain = nullptr;
+
+  insanity::pkix::ScopedCERTCertList certList;
   SECOidTag evOidPolicy;
   rv = PSM_SSL_PKIX_AuthCertificate(certVerifier, cert, infoObject,
                                     infoObject->GetHostNameRaw(),
-                                    &verifyCertChain, &evOidPolicy);
+                                    &certList, &evOidPolicy);
 
   // We want to remember the CA certs in the temp db, so that the application can find the
   // complete chain at any time it might need it.
   // But we keep only those CA certs in the temp db, that we didn't already know.
 
   RefPtr<nsSSLStatus> status(infoObject->SSLStatus());
   RefPtr<nsNSSCertificate> nsc;
 
@@ -819,18 +820,16 @@ AuthCertificate(CertVerifier& certVerifi
     if( rv == SECSuccess ){
       nsc = nsNSSCertificate::Create(cert, &evOidPolicy);
     }
     else {
       nsc = nsNSSCertificate::Create(cert);
     }
   }
 
-  ScopedCERTCertList certList(verifyCertChain);
-
   if (rv == SECSuccess && certList) {
     // We want to avoid storing any intermediate cert information when browsing
     // in private, transient contexts.
     if (!(providerFlags & nsISocketProvider::NO_PERMANENT_STORAGE)) {
       for (CERTCertListNode* node = CERT_LIST_HEAD(certList);
            !CERT_LIST_END(node, certList);
            node = CERT_LIST_NEXT(node)) {
 
@@ -976,17 +975,17 @@ SSLServerCertVerificationJob::Run()
 #endif
       default:
         MOZ_CRASH("Unknown CertVerifier mode");
     }
 
     // Reset the error code here so we can detect if AuthCertificate fails to
     // set the error code if/when it fails.
     PR_SetError(0, 0);
-    SECStatus rv = AuthCertificate(*mCertVerifier, mInfoObject, mCert,
+    SECStatus rv = AuthCertificate(*mCertVerifier, mInfoObject, mCert.get(),
                                    mStapledOCSPResponse, mProviderFlags);
     if (rv == SECSuccess) {
       uint32_t interval = (uint32_t) ((TimeStamp::Now() - mJobStartTime).ToMilliseconds());
       RefPtr<SSLServerCertVerificationResult> restart(
         new SSLServerCertVerificationResult(mInfoObject, 0,
                                             successTelemetry, interval));
       restart->Dispatch();
       return NS_OK;
@@ -997,18 +996,19 @@ SSLServerCertVerificationJob::Run()
     error = PR_GetError();
     {
       TimeStamp now = TimeStamp::Now();
       MutexAutoLock telemetryMutex(*gSSLVerificationTelemetryMutex);
       Telemetry::AccumulateTimeDelta(failureTelemetry, mJobStartTime, now);
     }
     if (error != 0) {
       RefPtr<CertErrorRunnable> runnable(
-          CreateCertErrorRunnable(*mCertVerifier, error, mInfoObject, mCert,
-                                  mFdForLogging, mProviderFlags, PR_Now()));
+          CreateCertErrorRunnable(*mCertVerifier, error, mInfoObject,
+                                  mCert.get(), mFdForLogging, mProviderFlags,
+                                  PR_Now()));
       if (!runnable) {
         // CreateCertErrorRunnable set a new error code
         error = PR_GetError();
       } else {
         // We must block the the socket transport service thread while the
         // main thread executes the CertErrorRunnable. The CertErrorRunnable
         // will dispatch the result asynchronously, so we don't have to block
         // this thread waiting for it.
--- a/security/manager/ssl/src/TransportSecurityInfo.cpp
+++ b/security/manager/ssl/src/TransportSecurityInfo.cpp
@@ -1,31 +1,32 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  *
  * 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 "TransportSecurityInfo.h"
+
+#include "insanity/pkixtypes.h"
 #include "nsNSSComponent.h"
 #include "nsIWebProgressListener.h"
 #include "nsNSSCertificate.h"
 #include "nsIX509CertValidity.h"
 #include "nsIDateTimeFormat.h"
 #include "nsDateTimeFormatCID.h"
 #include "nsICertOverrideService.h"
 #include "nsIObjectInputStream.h"
 #include "nsIObjectOutputStream.h"
 #include "nsNSSCertHelper.h"
 #include "nsIProgrammingLanguage.h"
 #include "nsIArray.h"
 #include "nsComponentManagerUtils.h"
 #include "nsServiceManagerUtils.h"
 #include "PSMRunnable.h"
-#include "ScopedNSSTypes.h"
 
 #include "secerr.h"
 
 //#define DEBUG_SSL_VERBOSE //Enable this define to get minimal 
                             //reports when doing SSL read/write
                             
 //#define DUMP_BUFFER  //Enable this define along with
                        //DEBUG_SSL_VERBOSE to dump SSL
@@ -752,17 +753,17 @@ AppendErrorTextMismatch(const nsString &
                         nsIX509Cert* ix509,
                         nsINSSComponent *component,
                         bool wantsHtml,
                         nsString &returnedMessage)
 {
   const char16_t *params[1];
   nsresult rv;
 
-  ScopedCERTCertificate nssCert;
+  insanity::pkix::ScopedCERTCertificate nssCert;
 
   nsCOMPtr<nsIX509Cert2> cert2 = do_QueryInterface(ix509, &rv);
   if (cert2)
     nssCert = cert2->GetCert();
 
   if (!nssCert) {
     // We are unable to extract the valid names, say "not valid for name".
     params[0] = host.get();
@@ -777,17 +778,17 @@ AppendErrorTextMismatch(const nsString &
     return;
   }
 
   nsString allNames;
   uint32_t nameCount = 0;
   bool useSAN = false;
 
   if (nssCert)
-    useSAN = GetSubjectAltNames(nssCert, component, allNames, nameCount);
+    useSAN = GetSubjectAltNames(nssCert.get(), component, allNames, nameCount);
 
   if (!useSAN) {
     char *certName = nullptr;
     // currently CERT_FindNSStringExtension is not being exported by NSS.
     // If it gets exported, enable the following line.
     //   certName = CERT_FindNSStringExtension(nssCert, SEC_OID_NS_CERT_EXT_SSL_SERVER_NAME);
     // However, it has been discussed to treat the extension as obsolete and ignore it.
     if (!certName)
--- a/security/manager/ssl/src/nsCMS.cpp
+++ b/security/manager/ssl/src/nsCMS.cpp
@@ -1,25 +1,26 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* 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 "nsCMS.h"
+
+#include "CertVerifier.h"
+#include "insanity/pkixtypes.h"
 #include "nsISupports.h"
-#include "nsCMS.h"
-#include "CertVerifier.h"
 #include "nsNSSHelper.h"
 #include "nsNSSCertificate.h"
 #include "smime.h"
 #include "cms.h"
 #include "nsICMSMessageErrors.h"
 #include "nsIArray.h"
 #include "nsArrayUtils.h"
 #include "nsCertVerificationThread.h"
-#include "ScopedNSSTypes.h"
 
 #include "prlog.h"
 
 using namespace mozilla;
 using namespace mozilla::psm;
 
 #ifdef PR_LOGGING
 extern PRLogModuleInfo* gPIPNSSLog;
@@ -509,18 +510,18 @@ NS_IMETHODIMP nsCMSMessage::CreateEncryp
   for (i=0; i<recipientCertCount; i++) {
     nsCOMPtr<nsIX509Cert> x509cert = do_QueryElementAt(aRecipientCerts, i);
 
     nssRecipientCert = do_QueryInterface(x509cert);
 
     if (!nssRecipientCert)
       return NS_ERROR_FAILURE;
 
-    ScopedCERTCertificate c(nssRecipientCert->GetCert());
-    recipientCerts.set(i, c);
+    insanity::pkix::ScopedCERTCertificate c(nssRecipientCert->GetCert());
+    recipientCerts.set(i, c.get());
   }
   
   // Find a bulk key algorithm //
   if (NSS_SMIMEUtil_FindBulkAlgForRecipients(recipientCerts.getRawArray(), &bulkAlgTag,
                                             &keySize) != SECSuccess) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateEncrypted - can't find bulk alg for recipients\n"));
     rv = NS_ERROR_CMS_ENCRYPT_NO_BULK_ALG;
     goto loser;
@@ -547,18 +548,18 @@ NS_IMETHODIMP nsCMSMessage::CreateEncryp
   cinfo = NSS_CMSEnvelopedData_GetContentInfo(envd);
   if (NSS_CMSContentInfo_SetContent_Data(m_cmsMsg, cinfo, nullptr, false) != SECSuccess) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateEncrypted - can't set content data\n"));
     goto loser;
   }
 
   // Create and attach recipient information //
   for (i=0; i < recipientCertCount; i++) {
-    ScopedCERTCertificate rc(recipientCerts.get(i));
-    if ((recipientInfo = NSS_CMSRecipientInfo_Create(m_cmsMsg, rc)) == nullptr) {
+    insanity::pkix::ScopedCERTCertificate rc(recipientCerts.get(i));
+    if ((recipientInfo = NSS_CMSRecipientInfo_Create(m_cmsMsg, rc.get())) == nullptr) {
       PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateEncrypted - can't create recipient info\n"));
       goto loser;
     }
     if (NSS_CMSEnvelopedData_AddRecipient(envd, recipientInfo) != SECSuccess) {
       PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateEncrypted - can't add recipient info\n"));
       goto loser;
     }
   }
@@ -578,18 +579,18 @@ NS_IMETHODIMP nsCMSMessage::CreateSigned
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned\n"));
   NSSCMSContentInfo *cinfo;
   NSSCMSSignedData *sigd;
   NSSCMSSignerInfo *signerinfo;
-  ScopedCERTCertificate scert;
-  ScopedCERTCertificate ecert;
+  insanity::pkix::ScopedCERTCertificate scert;
+  insanity::pkix::ScopedCERTCertificate ecert;
   nsCOMPtr<nsIX509Cert2> aSigningCert2 = do_QueryInterface(aSigningCert);
   nsresult rv = NS_ERROR_FAILURE;
 
   /* Get the certs */
   if (aSigningCert2) {
     scert = aSigningCert2->GetCert();
   }
   if (!scert) {
@@ -634,17 +635,17 @@ NS_IMETHODIMP nsCMSMessage::CreateSigned
           != SECSuccess) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't set content data\n"));
     goto loser;
   }
 
   /* 
    * create & attach signer information
    */
-  if ((signerinfo = NSS_CMSSignerInfo_Create(m_cmsMsg, scert, SEC_OID_SHA1)) 
+  if ((signerinfo = NSS_CMSSignerInfo_Create(m_cmsMsg, scert.get(), SEC_OID_SHA1)) 
           == nullptr) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't create signer info\n"));
     goto loser;
   }
 
   /* we want the cert chain included for this one */
   if (NSS_CMSSignerInfo_IncludeCerts(signerinfo, NSSCMSCM_CertChain, 
                                        certUsageEmailSigner) 
@@ -660,36 +661,36 @@ NS_IMETHODIMP nsCMSMessage::CreateSigned
   }
 
   if (NSS_CMSSignerInfo_AddSMIMECaps(signerinfo) != SECSuccess) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't add smime caps\n"));
     goto loser;
   }
 
   if (ecert) {
-    if (NSS_CMSSignerInfo_AddSMIMEEncKeyPrefs(signerinfo, ecert, 
-	                                    CERT_GetDefaultCertDB())
+    if (NSS_CMSSignerInfo_AddSMIMEEncKeyPrefs(signerinfo, ecert.get(),
+	                                      CERT_GetDefaultCertDB())
 	  != SECSuccess) {
       PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't add smime enc key prefs\n"));
       goto loser;
     }
 
-    if (NSS_CMSSignerInfo_AddMSSMIMEEncKeyPrefs(signerinfo, ecert, 
-	                                    CERT_GetDefaultCertDB())
+    if (NSS_CMSSignerInfo_AddMSSMIMEEncKeyPrefs(signerinfo, ecert.get(),
+	                                        CERT_GetDefaultCertDB())
 	  != SECSuccess) {
       PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't add MS smime enc key prefs\n"));
       goto loser;
     }
 
     // If signing and encryption cert are identical, don't add it twice.
     bool addEncryptionCert =
-      (ecert && (!scert || !CERT_CompareCerts(ecert, scert)));
+      (ecert && (!scert || !CERT_CompareCerts(ecert.get(), scert.get())));
 
     if (addEncryptionCert &&
-        NSS_CMSSignedData_AddCertificate(sigd, ecert) != SECSuccess) {
+        NSS_CMSSignedData_AddCertificate(sigd, ecert.get()) != SECSuccess) {
       PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't add own encryption certificate\n"));
       goto loser;
     }
   }
 
   if (NSS_CMSSignedData_AddSignerInfo(sigd, signerinfo) != SECSuccess) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsCMSMessage::CreateSigned - can't add signer info\n"));
     goto loser;
--- a/security/manager/ssl/src/nsCertOverrideService.cpp
+++ b/security/manager/ssl/src/nsCertOverrideService.cpp
@@ -1,15 +1,17 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  *
  * 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 "nsCertOverrideService.h"
+
+#include "insanity/pkixtypes.h"
 #include "nsIX509Cert.h"
 #include "nsNSSCertificate.h"
 #include "nsNSSCertHelper.h"
 #include "nsCRT.h"
 #include "nsAppDirectoryServiceDefs.h"
 #include "nsStreamUtils.h"
 #include "nsNetUtil.h"
 #include "nsILineInputStream.h"
@@ -24,17 +26,17 @@
 
 #include "nspr.h"
 #include "pk11pub.h"
 #include "certdb.h"
 #include "sechash.h"
 #include "ssl.h" // For SSL_ClearSessionCache
 
 using namespace mozilla;
-using mozilla::psm::SharedSSLState;
+using namespace mozilla::psm;
 
 static const char kCertOverrideFileName[] = "cert_override.txt";
 
 void
 nsCertOverride::convertBitsToString(OverrideBits ob, nsACString &str)
 {
   str.Truncate();
 
@@ -386,21 +388,21 @@ static nsresult
 GetCertFingerprintByOidTag(nsIX509Cert *aCert,
                            SECOidTag aOidTag, 
                            nsCString &fp)
 {
   nsCOMPtr<nsIX509Cert2> cert2 = do_QueryInterface(aCert);
   if (!cert2)
     return NS_ERROR_FAILURE;
 
-  ScopedCERTCertificate nsscert(cert2->GetCert());
+  insanity::pkix::ScopedCERTCertificate nsscert(cert2->GetCert());
   if (!nsscert)
     return NS_ERROR_FAILURE;
 
-  return GetCertFingerprintByOidTag(nsscert, aOidTag, fp);
+  return GetCertFingerprintByOidTag(nsscert.get(), aOidTag, fp);
 }
 
 static nsresult
 GetCertFingerprintByDottedOidString(CERTCertificate* nsscert,
                                     const nsCString &dottedOid, 
                                     nsCString &fp)
 {
   SECItem oid;
@@ -424,21 +426,21 @@ static nsresult
 GetCertFingerprintByDottedOidString(nsIX509Cert *aCert,
                                     const nsCString &dottedOid, 
                                     nsCString &fp)
 {
   nsCOMPtr<nsIX509Cert2> cert2 = do_QueryInterface(aCert);
   if (!cert2)
     return NS_ERROR_FAILURE;
 
-  ScopedCERTCertificate nsscert(cert2->GetCert());
+  insanity::pkix::ScopedCERTCertificate nsscert(cert2->GetCert());
   if (!nsscert)
     return NS_ERROR_FAILURE;
 
-  return GetCertFingerprintByDottedOidString(nsscert, dottedOid, fp);
+  return GetCertFingerprintByDottedOidString(nsscert.get(), dottedOid, fp);
 }
 
 NS_IMETHODIMP
 nsCertOverrideService::RememberValidityOverride(const nsACString & aHostName, int32_t aPort, 
                                                 nsIX509Cert *aCert,
                                                 uint32_t aOverrideBits, 
                                                 bool aTemporary)
 {
@@ -447,40 +449,40 @@ nsCertOverrideService::RememberValidityO
     return NS_ERROR_INVALID_ARG;
   if (aPort < -1)
     return NS_ERROR_INVALID_ARG;
 
   nsCOMPtr<nsIX509Cert2> cert2 = do_QueryInterface(aCert);
   if (!cert2)
     return NS_ERROR_FAILURE;
 
-  ScopedCERTCertificate nsscert(cert2->GetCert());
+  insanity::pkix::ScopedCERTCertificate nsscert(cert2->GetCert());
   if (!nsscert)
     return NS_ERROR_FAILURE;
 
-  char* nickname = nsNSSCertificate::defaultServerNickname(nsscert);
+  char* nickname = nsNSSCertificate::defaultServerNickname(nsscert.get());
   if (!aTemporary && nickname && *nickname)
   {
     ScopedPK11SlotInfo slot(PK11_GetInternalKeySlot());
     if (!slot) {
       PR_Free(nickname);
       return NS_ERROR_FAILURE;
     }
   
-    SECStatus srv = PK11_ImportCert(slot, nsscert, CK_INVALID_HANDLE, 
+    SECStatus srv = PK11_ImportCert(slot, nsscert.get(), CK_INVALID_HANDLE,
                                     nickname, false);
     if (srv != SECSuccess) {
       PR_Free(nickname);
       return NS_ERROR_FAILURE;
     }
   }
   PR_FREEIF(nickname);
 
   nsAutoCString fpStr;
-  nsresult rv = GetCertFingerprintByOidTag(nsscert, 
+  nsresult rv = GetCertFingerprintByOidTag(nsscert.get(),
                   mOidTagForStoringNewHashes, fpStr);
   if (NS_FAILED(rv))
     return rv;
 
   char *dbkey = nullptr;
   rv = aCert->GetDbKey(&dbkey);
   if (NS_FAILED(rv) || !dbkey)
     return rv;
--- a/security/manager/ssl/src/nsCertPicker.cpp
+++ b/security/manager/ssl/src/nsCertPicker.cpp
@@ -1,14 +1,15 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* 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 "nsCertPicker.h"
+#include "insanity/pkixtypes.h"
 #include "nsMemory.h"
 #include "nsCOMPtr.h"
 #include "nsXPIDLString.h"
 #include "nsIServiceManager.h"
 #include "nsNSSComponent.h"
 #include "nsNSSCertificate.h"
 #include "nsReadableUtils.h"
 #include "nsICertPickDialogs.h"
@@ -44,50 +45,52 @@ NS_IMETHODIMP nsCertPicker::PickByUsage(
   char16_t **certNicknameList = nullptr;
   char16_t **certDetailsList = nullptr;
   CERTCertListNode* node = nullptr;
   nsresult rv = NS_OK;
 
   {
     // Iterate over all certs. This assures that user is logged in to all hardware tokens.
     nsCOMPtr<nsIInterfaceRequestor> ctx = new PipUIContext();
-    ScopedCERTCertList allcerts(PK11_ListCerts(PK11CertListUnique, ctx));
+    insanity::pkix::ScopedCERTCertList allcerts(
+      PK11_ListCerts(PK11CertListUnique, ctx));
   }
 
   /* find all user certs that are valid and for SSL */
   /* note that we are allowing expired certs in this list */
 
-  ScopedCERTCertList certList( 
+  insanity::pkix::ScopedCERTCertList certList( 
     CERT_FindUserCertsByUsage(CERT_GetDefaultCertDB(), 
                               (SECCertUsage)certUsage,
                               !allowDuplicateNicknames,
                               !allowInvalid,
                               ctx));
   if (!certList) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
-  ScopedCERTCertNicknames nicknames(getNSSCertNicknamesFromCertList(certList));
+  ScopedCERTCertNicknames nicknames(getNSSCertNicknamesFromCertList(certList.get()));
   if (!nicknames) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
   certNicknameList = (char16_t **)nsMemory::Alloc(sizeof(char16_t *) * nicknames->numnicknames);
   certDetailsList = (char16_t **)nsMemory::Alloc(sizeof(char16_t *) * nicknames->numnicknames);
 
   if (!certNicknameList || !certDetailsList) {
     nsMemory::Free(certNicknameList);
     nsMemory::Free(certDetailsList);
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   int32_t CertsToUse;
 
-  for (CertsToUse = 0, node = CERT_LIST_HEAD(certList);
-       !CERT_LIST_END(node, certList) && CertsToUse < nicknames->numnicknames;
+  for (CertsToUse = 0, node = CERT_LIST_HEAD(certList.get());
+       !CERT_LIST_END(node, certList.get()) &&
+         CertsToUse < nicknames->numnicknames;
        node = CERT_LIST_NEXT(node)
       )
   {
     nsNSSCertificate *tempCert = nsNSSCertificate::Create(node->cert);
 
     if (tempCert) {
 
       // XXX we really should be using an nsCOMPtr instead of manually add-refing,
--- a/security/manager/ssl/src/nsCertTree.cpp
+++ b/security/manager/ssl/src/nsCertTree.cpp
@@ -1,31 +1,32 @@
 /* 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 "nsCertTree.h"
+
+#include "insanity/pkixtypes.h"
 #include "nsNSSComponent.h" // for PIPNSS string bundle calls.
-#include "nsCertTree.h"
 #include "nsITreeColumns.h"
 #include "nsIX509Cert.h"
 #include "nsIX509CertValidity.h"
 #include "nsIX509CertDB.h"
 #include "nsXPIDLString.h"
 #include "nsReadableUtils.h"
 #include "nsUnicharUtils.h"
 #include "nsNSSCertificate.h"
 #include "nsNSSCertHelper.h"
 #include "nsINSSCertCache.h"
 #include "nsIMutableArray.h"
 #include "nsArrayUtils.h"
 #include "nsISupportsPrimitives.h"
 #include "nsXPCOMCID.h"
 #include "nsTHashtable.h"
 #include "nsHashKeys.h"
-#include "ScopedNSSTypes.h"
  
 #include "prlog.h"
 
 using namespace mozilla;
 
 #ifdef PR_LOGGING
 extern PRLogModuleInfo* gPIPNSSLog;
 #endif
@@ -632,19 +633,20 @@ nsCertTree::GetCertsByTypeFromCertList(C
 
 nsresult 
 nsCertTree::GetCertsByType(uint32_t           aType,
                            nsCertCompareFunc  aCertCmpFn,
                            void              *aCertCmpFnArg)
 {
   nsNSSShutDownPreventionLock locker;
   nsCOMPtr<nsIInterfaceRequestor> cxt = new PipUIContext();
-  ScopedCERTCertList certList(PK11_ListCerts(PK11CertListUnique, cxt));
-  nsresult rv = GetCertsByTypeFromCertList(certList, aType, aCertCmpFn, aCertCmpFnArg);
-  return rv;
+  insanity::pkix::ScopedCERTCertList certList(
+    PK11_ListCerts(PK11CertListUnique, cxt));
+  return GetCertsByTypeFromCertList(certList.get(), aType, aCertCmpFn,
+                                    aCertCmpFnArg);
 }
 
 nsresult 
 nsCertTree::GetCertsByTypeFromCache(nsINSSCertCache   *aCache,
                                     uint32_t           aType,
                                     nsCertCompareFunc  aCertCmpFn,
                                     void              *aCertCmpFnArg)
 {
@@ -802,30 +804,31 @@ nsCertTree::DeleteEntryObject(uint32_t i
           } 
         }
         else {
           if (addonInfo && addonInfo->mUsageCount > 1) {
             // user is trying to delete a perm trusted cert,
             // although there are still overrides stored,
             // so, we keep the cert, but remove the trust
 
-            ScopedCERTCertificate nsscert;
+            insanity::pkix::ScopedCERTCertificate nsscert;
 
             nsCOMPtr<nsIX509Cert2> cert2 = do_QueryInterface(cert);
             if (cert2) {
               nsscert = cert2->GetCert();
             }
 
             if (nsscert) {
               CERTCertTrust trust;
               memset((void*)&trust, 0, sizeof(trust));
             
               SECStatus srv = CERT_DecodeTrustString(&trust, ""); // no override 
               if (srv == SECSuccess) {
-                CERT_ChangeCertTrust(CERT_GetDefaultCertDB(), nsscert, &trust);
+                CERT_ChangeCertTrust(CERT_GetDefaultCertDB(), nsscert.get(),
+                                     &trust);
               }
             }
           }
           else {
             canRemoveEntry = true;
           }
         }
       }
--- a/security/manager/ssl/src/nsCertTree.h
+++ b/security/manager/ssl/src/nsCertTree.h
@@ -7,23 +7,23 @@
 
 #include "nsCOMPtr.h"
 #include "nsIServiceManager.h"
 #include "nsICertTree.h"
 #include "nsITreeView.h"
 #include "nsITreeBoxObject.h"
 #include "nsITreeSelection.h"
 #include "nsIMutableArray.h"
+#include "nsNSSComponent.h"
 #include "nsTArray.h"
 #include "pldhash.h"
 #include "nsIX509CertDB.h"
 #include "nsCertOverrideService.h"
 #include "mozilla/Attributes.h"
 
-
 typedef struct treeArrayElStr treeArrayEl;
 
 struct CompareCacheHashEntry {
   enum { max_criterions = 3 };
   CompareCacheHashEntry();
 
   void *key; // no ownership
   bool mCritInit[max_criterions];
--- a/security/manager/ssl/src/nsCrypto.cpp
+++ b/security/manager/ssl/src/nsCrypto.cpp
@@ -1043,22 +1043,22 @@ nsFreeCertReqMessages(CRMFCertReqMsg **c
 static nsresult
 nsSetEscrowAuthority(CRMFCertRequest *certReq, nsKeyPairInfo *keyInfo,
                      nsNSSCertificate *wrappingCert)
 {
   if (!wrappingCert ||
       CRMF_CertRequestIsControlPresent(certReq, crmfPKIArchiveOptionsControl)){
     return NS_ERROR_FAILURE;
   }
-  ScopedCERTCertificate cert(wrappingCert->GetCert());
+  insanity::pkix::ScopedCERTCertificate cert(wrappingCert->GetCert());
   if (!cert)
     return NS_ERROR_FAILURE;
 
   CRMFEncryptedKey *encrKey = 
-      CRMF_CreateEncryptedKeyWithEncryptedValue(keyInfo->privKey, cert);
+      CRMF_CreateEncryptedKeyWithEncryptedValue(keyInfo->privKey, cert.get());
   if (!encrKey)
     return NS_ERROR_FAILURE;
 
   CRMFPKIArchiveOptions *archOpt = 
       CRMF_CreatePKIArchiveOptions(crmfEncryptedPrivateKey, encrKey);
   if (!archOpt) {
     CRMF_DestroyEncryptedKey(encrKey);
     return NS_ERROR_FAILURE;
@@ -1944,25 +1944,25 @@ nsCrypto::GenerateCRMFRequest(JSContext*
   bool willEscrow = false;
   if (!aEaCert.IsVoid()) {
     SECItem certDer = {siBuffer, nullptr, 0};
     SECStatus srv = ATOB_ConvertAsciiToItem(&certDer, aEaCert.get());
     if (srv != SECSuccess) {
       aRv.Throw(NS_ERROR_FAILURE);
       return nullptr;
     }
-    ScopedCERTCertificate cert(CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
-                                                       &certDer, nullptr,
-                                                       false, true));
+    insanity::pkix::ScopedCERTCertificate cert(
+      CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
+                              &certDer, nullptr, false, true));
     if (!cert) {
       aRv.Throw(NS_ERROR_FAILURE);
       return nullptr;
     }
 
-    escrowCert = nsNSSCertificate::Create(cert);
+    escrowCert = nsNSSCertificate::Create(cert.get());
     nssCert = escrowCert;
     if (!nssCert) {
       aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
       return nullptr;
     }
 
     nsCOMPtr<nsIDOMCryptoDialogs> dialogs;
     nsresult rv = getNSSDialogs(getter_AddRefs(dialogs),
@@ -2226,22 +2226,23 @@ nsCryptoRunnable::Run()
 //Quick helper function to check if a newly issued cert
 //already exists in the user's database.
 static bool
 nsCertAlreadyExists(SECItem *derCert)
 {
   CERTCertDBHandle *handle = CERT_GetDefaultCertDB();
   bool retVal = false;
 
-  ScopedCERTCertificate cert(CERT_FindCertByDERCert(handle, derCert));
+  insanity::pkix::ScopedCERTCertificate cert(
+    CERT_FindCertByDERCert(handle, derCert));
   if (cert) {
     if (cert->isperm && !cert->nickname && !cert->emailAddr) {
       //If the cert doesn't have a nickname or email addr, it is
       //bogus cruft, so delete it.
-      SEC_DeletePermCertificate(cert);
+      SEC_DeletePermCertificate(cert.get());
     } else if (cert->isperm) {
       retVal = true;
     }
   }
   return retVal;
 }
 
 static int32_t
--- a/security/manager/ssl/src/nsNSSCallbacks.cpp
+++ b/security/manager/ssl/src/nsNSSCallbacks.cpp
@@ -1,28 +1,27 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  *
  * 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 "nsNSSCallbacks.h"
-
+#include "insanity/pkixtypes.h"
 #include "mozilla/Telemetry.h"
 #include "mozilla/TimeStamp.h"
 #include "nsNSSComponent.h"
 #include "nsNSSIOLayer.h"
 #include "nsIWebProgressListener.h"
 #include "nsProtectedAuthThread.h"
 #include "nsITokenDialogs.h"
 #include "nsIUploadChannel.h"
 #include "nsIPrompt.h"
 #include "nsProxyRelease.h"
 #include "PSMRunnable.h"
-#include "ScopedNSSTypes.h"
 #include "nsContentUtils.h"
 #include "nsIHttpChannelInternal.h"
 #include "nsISupportsPriority.h"
 #include "nsNetUtil.h"
 #include "SharedSSLState.h"
 #include "ssl.h"
 #include "sslproto.h"
 
@@ -1185,29 +1184,29 @@ void HandshakeCallback(PRFileDesc* fd, v
 
     nsAutoString msg;
     msg.Append(NS_ConvertASCIItoUTF16(hostName));
     msg.Append(NS_LITERAL_STRING(" : server does not support RFC 5746, see CVE-2009-3555"));
 
     nsContentUtils::LogSimpleConsoleError(msg, "SSL");
   }
 
-  ScopedCERTCertificate serverCert(SSL_PeerCertificate(fd));
+  insanity::pkix::ScopedCERTCertificate serverCert(SSL_PeerCertificate(fd));
 
   /* Set the SSL Status information */
   RefPtr<nsSSLStatus> status(infoObject->SSLStatus());
   if (!status) {
     status = new nsSSLStatus();
     infoObject->SetSSLStatus(status);
   }
 
   RememberCertErrorsTable::GetInstance().LookupCertErrorBits(infoObject,
                                                              status);
 
-  RefPtr<nsNSSCertificate> nssc(nsNSSCertificate::Create(serverCert));
+  RefPtr<nsNSSCertificate> nssc(nsNSSCertificate::Create(serverCert.get()));
   nsCOMPtr<nsIX509Cert> prevcert;
   infoObject->GetPreviousCert(getter_AddRefs(prevcert));
 
   bool equals_previous = false;
   if (prevcert && nssc) {
     nsresult rv = nssc->Equals(prevcert, &equals_previous);
     if (NS_FAILED(rv)) {
       equals_previous = false;
--- a/security/manager/ssl/src/nsNSSCertCache.cpp
+++ b/security/manager/ssl/src/nsNSSCertCache.cpp
@@ -42,17 +42,18 @@ NS_IMETHODIMP
 nsNSSCertCache::CacheAllCerts()
 {
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
   nsCOMPtr<nsIInterfaceRequestor> cxt = new PipUIContext();
   
-  CERTCertList *newList = PK11_ListCerts(PK11CertListUnique, cxt);
+  insanity::pkix::ScopedCERTCertList newList(
+    PK11_ListCerts(PK11CertListUnique, cxt));
 
   if (newList) {
     MutexAutoLock lock(mutex);
     mCertList = new nsNSSCertList(newList, locker);
   }
   
   return NS_OK;
 }
--- a/security/manager/ssl/src/nsNSSCertificate.cpp
+++ b/security/manager/ssl/src/nsNSSCertificate.cpp
@@ -1,20 +1,21 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* 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 "nsNSSCertificate.h"
+
 #include "prmem.h"
 #include "prerror.h"
 #include "prprf.h"
-
-#include "nsNSSCertificate.h"
 #include "CertVerifier.h"
 #include "ExtendedValidation.h"
+#include "insanity/pkixtypes.h"
 #include "nsNSSComponent.h" // for PIPNSS string bundle calls.
 #include "nsNSSCleaner.h"
 #include "nsCOMPtr.h"
 #include "nsIMutableArray.h"
 #include "nsNSSCertValidity.h"
 #include "nsPKCS12Blob.h"
 #include "nsPK11TokenDB.h"
 #include "nsIX509Cert.h"
@@ -182,36 +183,34 @@ void nsNSSCertificate::virtualDestroyNSS
   destructorSafeDestroyNSSReference();
 }
 
 void nsNSSCertificate::destructorSafeDestroyNSSReference()
 {
   if (mPermDelete) {
     if (mCertType == nsNSSCertificate::USER_CERT) {
       nsCOMPtr<nsIInterfaceRequestor> cxt = new PipUIContext();
-      PK11_DeleteTokenCertAndKey(mCert, cxt);
+      PK11_DeleteTokenCertAndKey(mCert.get(), cxt);
     } else if (!PK11_IsReadOnly(mCert->slot)) {
       // If the list of built-ins does contain a non-removable
       // copy of this certificate, our call will not remove
       // the certificate permanently, but rather remove all trust.
-      SEC_DeletePermCertificate(mCert);
+      SEC_DeletePermCertificate(mCert.get());
     }
   }
 
-  if (mCert) {
-    mCert = nullptr;
-  }
+  mCert = nullptr;
 }
 
 nsresult
 nsNSSCertificate::GetCertType(uint32_t* aCertType)
 {
   if (mCertType == CERT_TYPE_NOT_YET_INITIALIZED) {
      // only determine cert type once and cache it
-     mCertType = getCertType(mCert);
+     mCertType = getCertType(mCert.get());
   }
   *aCertType = mCertType;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsNSSCertificate::GetIsSelfSigned(bool* aIsSelfSigned)
 {
@@ -405,33 +404,34 @@ nsNSSCertificate::FormatUIStrings(const 
         details.Append(char16_t(' '));
       }
       details.Append(temp1);
     }
 
     details.Append(char16_t('\n'));
   }
 
-  if (NS_SUCCEEDED(GetKeyUsagesString(mCert, nssComponent, temp1)) && !temp1.IsEmpty()) {
+  if (NS_SUCCEEDED(GetKeyUsagesString(mCert.get(), nssComponent, temp1)) &&
+      !temp1.IsEmpty()) {
     details.AppendLiteral("  ");
     if (NS_SUCCEEDED(nssComponent->GetPIPNSSBundleString("CertDumpKeyUsage", info))) {
       details.Append(info);
       details.AppendLiteral(": ");
     }
     details.Append(temp1);
     details.Append(char16_t('\n'));
   }
 
   nsAutoString firstEmail;
   const char* aWalkAddr;
-  for (aWalkAddr = CERT_GetFirstEmailAddress(mCert)
+  for (aWalkAddr = CERT_GetFirstEmailAddress(mCert.get())
         ;
         aWalkAddr
         ;
-        aWalkAddr = CERT_GetNextEmailAddress(mCert, aWalkAddr))
+        aWalkAddr = CERT_GetNextEmailAddress(mCert.get(), aWalkAddr))
   {
     NS_ConvertUTF8toUTF16 email(aWalkAddr);
     if (email.IsEmpty())
       continue;
 
     if (firstEmail.IsEmpty()) {
       // If the first email address from the subject DN is also present
       // in the subjectAltName extension, GetEmailAddresses() will return
@@ -604,35 +604,35 @@ nsNSSCertificate::GetEmailAddresses(uint
     return NS_ERROR_NOT_AVAILABLE;
 
   NS_ENSURE_ARG(aLength);
   NS_ENSURE_ARG(aAddresses);
 
   *aLength = 0;
 
   const char* aAddr;
-  for (aAddr = CERT_GetFirstEmailAddress(mCert)
+  for (aAddr = CERT_GetFirstEmailAddress(mCert.get())
        ;
        aAddr
        ;
-       aAddr = CERT_GetNextEmailAddress(mCert, aAddr))
+       aAddr = CERT_GetNextEmailAddress(mCert.get(), aAddr))
   {
     ++(*aLength);
   }
 
   *aAddresses = (char16_t**) nsMemory::Alloc(sizeof(char16_t*) * (*aLength));
   if (!*aAddresses)
     return NS_ERROR_OUT_OF_MEMORY;
 
   uint32_t iAddr;
-  for (aAddr = CERT_GetFirstEmailAddress(mCert), iAddr = 0
+  for (aAddr = CERT_GetFirstEmailAddress(mCert.get()), iAddr = 0
        ;
        aAddr
        ;
-       aAddr = CERT_GetNextEmailAddress(mCert, aAddr), ++iAddr)
+       aAddr = CERT_GetNextEmailAddress(mCert.get(), aAddr), ++iAddr)
   {
     (*aAddresses)[iAddr] = ToNewUnicode(NS_ConvertUTF8toUTF16(aAddr));
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
@@ -642,21 +642,21 @@ nsNSSCertificate::ContainsEmailAddress(c
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
   NS_ENSURE_ARG(result);
   *result = false;
 
   const char* aAddr = nullptr;
-  for (aAddr = CERT_GetFirstEmailAddress(mCert)
+  for (aAddr = CERT_GetFirstEmailAddress(mCert.get())
        ;
        aAddr
        ;
-       aAddr = CERT_GetNextEmailAddress(mCert, aAddr))
+       aAddr = CERT_GetNextEmailAddress(mCert.get(), aAddr))
   {
     NS_ConvertUTF8toUTF16 certAddr(aAddr);
     ToLowerCase(certAddr);
 
     nsAutoString testAddr(aEmailAddress);
     ToLowerCase(testAddr);
 
     if (certAddr == testAddr)
@@ -817,79 +817,76 @@ nsNSSCertificate::GetChain(nsIArray** _r
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
   NS_ENSURE_ARG(_rvChain);
   nsresult rv;
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Getting chain for \"%s\"\n", mCert->nickname));
 
-  ScopedCERTCertList nssChain;
+  ::insanity::pkix::ScopedCERTCertList nssChain;
   SECStatus srv;
-  nssChain = nullptr;
   RefPtr<SharedCertVerifier> certVerifier(GetDefaultCertVerifier());
   NS_ENSURE_TRUE(certVerifier, NS_ERROR_UNEXPECTED);
-  CERTCertList* pkixNssChain = nullptr;
 
   // We want to test all usages, but we start with server because most of the
   // time Firefox users care about server certs.
-  srv = certVerifier->VerifyCert(mCert,
+  srv = certVerifier->VerifyCert(mCert.get(),
                                  certificateUsageSSLServer, PR_Now(),
                                  nullptr, /*XXX fixme*/
                                  CertVerifier::FLAG_LOCAL_ONLY,
-                                 &pkixNssChain);
+                                 &nssChain);
   // This is the whitelist of all non-SSLServer usages that are supported by
   // verifycert.
   const int otherUsagesToTest = certificateUsageSSLClient |
                                 certificateUsageSSLCA |
                                 certificateUsageEmailSigner |
                                 certificateUsageEmailRecipient |
                                 certificateUsageObjectSigner |
                                 certificateUsageStatusResponder;
   for (int usage = certificateUsageSSLClient;
-       usage < certificateUsageAnyCA && !pkixNssChain;
+       usage < certificateUsageAnyCA && !nssChain;
        usage = usage << 1) {
     if ((usage & otherUsagesToTest) == 0) {
       continue;
     }
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG,
            ("pipnss: PKIX attempting chain(%d) for '%s'\n",
             usage, mCert->nickname));
-    srv = certVerifier->VerifyCert(mCert,
+    srv = certVerifier->VerifyCert(mCert.get(),
                                    usage, PR_Now(),
                                    nullptr, /*XXX fixme*/
                                    CertVerifier::FLAG_LOCAL_ONLY,
-                                   &pkixNssChain);
+                                   &nssChain);
   }
 
-  if (!pkixNssChain) {
-    // There is not verified path for the chain, howeever we still want to
+  if (!nssChain) {
+    // There is not verified path for the chain, howeever we still want to 
     // present to the user as much of a possible chain as possible, in the case
     // where there was a problem with the cert or the issuers.
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG,
            ("pipnss: getchain :CertVerify failed to get chain for '%s'\n",
             mCert->nickname));
-    nssChain = CERT_GetCertChainFromCert(mCert, PR_Now(), certUsageSSLClient);
-  } else {
-    nssChain = pkixNssChain;
-  }
+    nssChain = CERT_GetCertChainFromCert(mCert.get(), PR_Now(),
+                                         certUsageSSLClient);
+  } 
 
   if (!nssChain) {
     return NS_ERROR_FAILURE;
   }
 
   // enumerate the chain for scripting purposes
   nsCOMPtr<nsIMutableArray> array =
     do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
   if (NS_FAILED(rv)) {
     goto done;
   }
   CERTCertListNode* node;
-  for (node = CERT_LIST_HEAD(nssChain);
-       !CERT_LIST_END(node, nssChain);
+  for (node = CERT_LIST_HEAD(nssChain.get());
+       !CERT_LIST_END(node, nssChain.get());
        node = CERT_LIST_NEXT(node)) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG,
            ("adding %s to chain\n", node->cert->nickname));
     nsCOMPtr<nsIX509Cert> cert = nsNSSCertificate::Create(node->cert);
     array->AppendElement(cert, false);
   }
   *_rvChain = array;
   NS_IF_ADDREF(*_rvChain);
@@ -908,17 +905,17 @@ nsNSSCertificate::GetAllTokenNames(uint3
   NS_ENSURE_ARG(aLength);
   NS_ENSURE_ARG(aTokenNames);
   *aLength = 0;
   *aTokenNames = nullptr;
 
   // Get the slots from NSS
   ScopedPK11SlotList slots;
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Getting slots for \"%s\"\n", mCert->nickname));
-  slots = PK11_GetAllSlotsForCert(mCert, nullptr);
+  slots = PK11_GetAllSlotsForCert(mCert.get(), nullptr);
   if (!slots) {
     if (PORT_GetError() == SEC_ERROR_NO_TOKEN)
       return NS_OK; // List of slots is empty, return empty array
     else
       return NS_ERROR_FAILURE;
   }
 
   // read the token names from slots
@@ -1134,36 +1131,36 @@ nsNSSCertificate::ExportAsCMS(uint32_t c
   ScopedNSSCMSMessage cmsg(NSS_CMSMessage_Create(nullptr));
   if (!cmsg) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG,
            ("nsNSSCertificate::ExportAsCMS - can't create CMS message\n"));
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   // first, create SignedData with the certificate only (no chain)
-  ScopedNSSCMSSignedData sigd(NSS_CMSSignedData_CreateCertsOnly(cmsg, mCert,
-                                                                false));
+  ScopedNSSCMSSignedData sigd(
+    NSS_CMSSignedData_CreateCertsOnly(cmsg, mCert.get(), false));
   if (!sigd) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG,
            ("nsNSSCertificate::ExportAsCMS - can't create SignedData\n"));
     return NS_ERROR_FAILURE;
   }
 
   // Calling NSS_CMSSignedData_CreateCertsOnly() will not allow us
   // to specify the inclusion of the root, but CERT_CertChainFromCert() does.
   // Since CERT_CertChainFromCert() also includes the certificate itself,
   // we have to start at the issuing cert (to avoid duplicate certs
   // in the SignedData).
   if (chainMode == nsIX509Cert3::CMS_CHAIN_MODE_CertChain ||
       chainMode == nsIX509Cert3::CMS_CHAIN_MODE_CertChainWithRoot) {
     ScopedCERTCertificate issuerCert(
-        CERT_FindCertIssuer(mCert, PR_Now(), certUsageAnyCA));
+        CERT_FindCertIssuer(mCert.get(), PR_Now(), certUsageAnyCA));
     // the issuerCert of a self signed root is the cert itself,
     // so make sure we're not adding duplicates, again
-    if (issuerCert && issuerCert != mCert) {
+    if (issuerCert && issuerCert != mCert.get()) {
       bool includeRoot =
         (chainMode == nsIX509Cert3::CMS_CHAIN_MODE_CertChainWithRoot);
       ScopedCERTCertificateList certChain(
           CERT_CertChainFromCert(issuerCert, certUsageAnyCA, includeRoot));
       if (certChain) {
         if (NSS_CMSSignedData_AddCertList(sigd, certChain) == SECSuccess) {
           certChain.forget();
         }
@@ -1227,28 +1224,28 @@ nsNSSCertificate::ExportAsCMS(uint32_t c
 
 CERTCertificate*
 nsNSSCertificate::GetCert()
 {
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown())
     return nullptr;
 
-  return (mCert) ? CERT_DupCertificate(mCert) : nullptr;
+  return (mCert) ? CERT_DupCertificate(mCert.get()) : nullptr;
 }
 
 NS_IMETHODIMP
 nsNSSCertificate::GetValidity(nsIX509CertValidity** aValidity)
 {
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
   NS_ENSURE_ARG(aValidity);
-  nsX509CertValidity* validity = new nsX509CertValidity(mCert);
+  nsX509CertValidity* validity = new nsX509CertValidity(mCert.get());
 
   NS_ADDREF(validity);
   *aValidity = static_cast<nsIX509CertValidity*>(validity);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsNSSCertificate::GetUsagesArray(bool localOnly,
@@ -1260,17 +1257,17 @@ nsNSSCertificate::GetUsagesArray(bool lo
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
   nsresult rv;
   const int max_usages = 13;
   char16_t* tmpUsages[max_usages];
   const char* suffix = "";
   uint32_t tmpCount;
-  nsUsageArrayHelper uah(mCert);
+  nsUsageArrayHelper uah(mCert.get());
   rv = uah.GetUsagesArray(suffix, localOnly, max_usages, _verified, &tmpCount,
                           tmpUsages);
   NS_ENSURE_SUCCESS(rv,rv);
   if (tmpCount > 0) {
     *_usages = (char16_t**) nsMemory::Alloc(sizeof(char16_t*) * tmpCount);
     if (!*_usages)
       return NS_ERROR_OUT_OF_MEMORY;
     for (uint32_t i=0; i<tmpCount; i++) {
@@ -1316,17 +1313,17 @@ nsNSSCertificate::GetUsagesString(bool l
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
   nsresult rv;
   const int max_usages = 13;
   char16_t* tmpUsages[max_usages];
   const char* suffix = "_p";
   uint32_t tmpCount;
-  nsUsageArrayHelper uah(mCert);
+  nsUsageArrayHelper uah(mCert.get());
   rv = uah.GetUsagesArray(suffix, localOnly, max_usages, _verified, &tmpCount,
                           tmpUsages);
   NS_ENSURE_SUCCESS(rv,rv);
   _usages.Truncate();
   for (uint32_t i=0; i<tmpCount; i++) {
     if (i>0) _usages.AppendLiteral(",");
     _usages.Append(tmpUsages[i]);
     nsMemory::Free(tmpUsages[i]);
@@ -1403,28 +1400,28 @@ nsNSSCertificate::Equals(nsIX509Cert* ot
   NS_ENSURE_ARG(other);
   NS_ENSURE_ARG(result);
 
   nsCOMPtr<nsIX509Cert2> other2 = do_QueryInterface(other);
   if (!other2)
     return NS_ERROR_FAILURE;
 
   ScopedCERTCertificate cert(other2->GetCert());
-  *result = (mCert == cert);
+  *result = (mCert.get() == cert.get());
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsNSSCertificate::SaveSMimeProfile()
 {
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
-  if (SECSuccess != CERT_SaveSMimeProfile(mCert, nullptr, nullptr))
+  if (SECSuccess != CERT_SaveSMimeProfile(mCert.get(), nullptr, nullptr))
     return NS_ERROR_FAILURE;
   else
     return NS_OK;
 }
 
 
 char* nsNSSCertificate::defaultServerNickname(CERTCertificate* cert)
 {
@@ -1497,17 +1494,17 @@ nsNSSCertificate::hasValidEVOidTag(SECOi
     certVerifier(mozilla::psm::GetDefaultCertVerifier());
   NS_ENSURE_TRUE(certVerifier, NS_ERROR_UNEXPECTED);
 
   validEV = false;
   resultOidTag = SEC_OID_UNKNOWN;
 
   uint32_t flags = mozilla::psm::CertVerifier::FLAG_LOCAL_ONLY |
     mozilla::psm::CertVerifier::FLAG_NO_DV_FALLBACK_FOR_EV;
-  SECStatus rv = certVerifier->VerifyCert(mCert,
+  SECStatus rv = certVerifier->VerifyCert(mCert.get(),
     certificateUsageSSLServer, PR_Now(),
     nullptr /* XXX pinarg */,
     flags, nullptr, &resultOidTag);
 
   if (rv != SECSuccess) {
     resultOidTag = SEC_OID_UNKNOWN;
   }
   if (resultOidTag != SEC_OID_UNKNOWN) {
@@ -1598,21 +1595,21 @@ nsNSSCertificate::GetValidEVPolicyOid(ns
   }
 #endif
 
   return NS_OK;
 }
 
 NS_IMPL_ISUPPORTS1(nsNSSCertList, nsIX509CertList)
 
-nsNSSCertList::nsNSSCertList(CERTCertList* certList,
+nsNSSCertList::nsNSSCertList(insanity::pkix::ScopedCERTCertList& certList,
                              const nsNSSShutDownPreventionLock& proofOfLock)
 {
   if (certList) {
-    mCertList = certList;
+    mCertList = certList.release();
   } else {
     mCertList = CERT_NewCertList();
   }
 }
 
 nsNSSCertList::~nsNSSCertList()
 {
   nsNSSShutDownPreventionLock locker;
@@ -1650,17 +1647,18 @@ nsNSSCertList::AddCert(nsIX509Cert* aCer
     NS_ERROR("Somehow got nullptr for mCertificate in nsNSSCertificate.");
     return NS_ERROR_FAILURE;
   }
 
   if (!mCertList) {
     NS_ERROR("Somehow got nullptr for mCertList in nsNSSCertList.");
     return NS_ERROR_FAILURE;
   }
-  CERT_AddCertToListTail(mCertList,cert);
+  // XXX: check return value!
+  CERT_AddCertToListTail(mCertList.get(), cert);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsNSSCertList::DeleteCert(nsIX509Cert* aCert)
 {
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown()) {
@@ -1675,18 +1673,18 @@ nsNSSCertList::DeleteCert(nsIX509Cert* a
     return NS_ERROR_FAILURE;
   }
 
   if (!mCertList) {
     NS_ERROR("Somehow got nullptr for mCertList in nsNSSCertList.");
     return NS_ERROR_FAILURE;
   }
 
-  for (node = CERT_LIST_HEAD(mCertList); !CERT_LIST_END(node,mCertList);
-                                             node = CERT_LIST_NEXT(node)) {
+  for (node = CERT_LIST_HEAD(mCertList.get());
+       !CERT_LIST_END(node, mCertList.get()); node = CERT_LIST_NEXT(node)) {
     if (node->cert == cert) {
 	CERT_RemoveCertListNode(node);
         return NS_OK;
     }
   }
   return NS_OK; // XXX Should we fail if we couldn't find it?
 }
 
@@ -1712,28 +1710,28 @@ nsNSSCertList::DupCertList(CERTCertList*
   return newList;
 }
 
 void*
 nsNSSCertList::GetRawCertList()
 {
   // This function should only be called after adquiring a
   // nsNSSShutDownPreventionLock
-  return mCertList;
+  return mCertList.get();
 }
 
 NS_IMETHODIMP
 nsNSSCertList::GetEnumerator(nsISimpleEnumerator** _retval)
 {
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown()) {
     return NS_ERROR_NOT_AVAILABLE;
   }
   nsCOMPtr<nsISimpleEnumerator> enumerator =
-    new nsNSSCertListEnumerator(mCertList, locker);
+    new nsNSSCertListEnumerator(mCertList.get(), locker);
 
   *_retval = enumerator;
   NS_ADDREF(*_retval);
   return NS_OK;
 }
 
 NS_IMPL_ISUPPORTS1(nsNSSCertListEnumerator, nsISimpleEnumerator)
 
--- a/security/manager/ssl/src/nsNSSCertificate.h
+++ b/security/manager/ssl/src/nsNSSCertificate.h
@@ -14,17 +14,17 @@
 #include "nsIASN1Object.h"
 #include "nsISMimeCert.h"
 #include "nsIIdentityInfo.h"
 #include "nsCOMPtr.h"
 #include "nsNSSShutDown.h"
 #include "nsISimpleEnumerator.h"
 #include "nsISerializable.h"
 #include "nsIClassInfo.h"
-#include "ScopedNSSTypes.h"
+#include "insanity/pkixtypes.h"
 #include "certt.h"
 
 class nsAutoString;
 class nsINSSComponent;
 class nsIASN1Sequence;
 
 class nsNSSCertificate : public nsIX509Cert3,
                          public nsIIdentityInfo,
@@ -53,17 +53,17 @@ public:
                                   SECOidTag* evOidPolicy = nullptr);
   static nsNSSCertificate* ConstructFromDER(char* certDER, int derLen);
 
   // It is the responsibility of the caller of this method to free the returned
   // string using PR_Free.
   static char* defaultServerNickname(CERTCertificate* cert);
 
 private:
-  mozilla::ScopedCERTCertificate mCert;
+  insanity::pkix::ScopedCERTCertificate mCert;
   bool             mPermDelete;
   uint32_t         mCertType;
   nsresult CreateASN1Struct(nsIASN1Object** aRetVal);
   nsresult CreateTBSCertificateASN1Struct(nsIASN1Sequence** retSequence,
                                           nsINSSComponent* nssComponent);
   nsresult GetSortableDate(PRTime aTime, nsAString& _aSortableDate);
   virtual void virtualDestroyNSSReference();
   void destructorSafeDestroyNSSReference();
@@ -79,28 +79,29 @@ private:
 
 class nsNSSCertList: public nsIX509CertList,
                      public nsNSSShutDownObject
 {
 public:
   NS_DECL_THREADSAFE_ISUPPORTS
   NS_DECL_NSIX509CERTLIST
 
-  nsNSSCertList(CERTCertList* certList,
+  // certList is adopted 
+  nsNSSCertList(insanity::pkix::ScopedCERTCertList& certList,
                 const nsNSSShutDownPreventionLock& proofOfLock);
 
   static CERTCertList* DupCertList(CERTCertList* aCertList,
                                    const nsNSSShutDownPreventionLock&
                                      proofOfLock);
 private:
    virtual ~nsNSSCertList();
    virtual void virtualDestroyNSSReference();
    void destructorSafeDestroyNSSReference();
 
-   mozilla::ScopedCERTCertList mCertList;
+   insanity::pkix::ScopedCERTCertList mCertList;
 
    nsNSSCertList(const nsNSSCertList&) MOZ_DELETE;
    void operator=(const nsNSSCertList&) MOZ_DELETE;
 };
 
 class nsNSSCertListEnumerator: public nsISimpleEnumerator,
                                public nsNSSShutDownObject
 {
@@ -110,17 +111,17 @@ public:
 
    nsNSSCertListEnumerator(CERTCertList* certList,
                            const nsNSSShutDownPreventionLock& proofOfLock);
 private:
    virtual ~nsNSSCertListEnumerator();
    virtual void virtualDestroyNSSReference();
    void destructorSafeDestroyNSSReference();
 
-   mozilla::ScopedCERTCertList mCertList;
+   insanity::pkix::ScopedCERTCertList mCertList;
 
    nsNSSCertListEnumerator(const nsNSSCertListEnumerator&) MOZ_DELETE;
    void operator=(const nsNSSCertListEnumerator&) MOZ_DELETE;
 };
 
 
 #define NS_NSS_LONG 4
 #define NS_NSS_GET_LONG(x) ((((unsigned long)((x)[0])) << 24) | \
--- a/security/manager/ssl/src/nsNSSCertificateDB.cpp
+++ b/security/manager/ssl/src/nsNSSCertificateDB.cpp
@@ -81,17 +81,17 @@ nsNSSCertificateDB::FindCertByNickname(n
 {
   NS_ENSURE_ARG_POINTER(_rvCert);
   *_rvCert = nullptr;
 
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown()) {
     return NS_ERROR_NOT_AVAILABLE;
   }
-  ScopedCERTCertificate cert;
+  insanity::pkix::ScopedCERTCertificate cert;
   char *asciiname = nullptr;
   NS_ConvertUTF16toUTF8 aUtf8Nickname(nickname);
   asciiname = const_cast<char*>(aUtf8Nickname.get());
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Getting \"%s\"\n", asciiname));
 #if 0
   // what it should be, but for now...
   if (aToken) {
     cert = PK11_FindCertFromNickname(asciiname, nullptr);
@@ -100,17 +100,17 @@ nsNSSCertificateDB::FindCertByNickname(n
   }
 #endif
   cert = PK11_FindCertFromNickname(asciiname, nullptr);
   if (!cert) {
     cert = CERT_FindCertByNickname(CERT_GetDefaultCertDB(), asciiname);
   }
   if (cert) {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("got it\n"));
-    nsCOMPtr<nsIX509Cert> pCert = nsNSSCertificate::Create(cert);
+    nsCOMPtr<nsIX509Cert> pCert = nsNSSCertificate::Create(cert.get());
     if (pCert) {
       pCert.forget(_rvCert);
       return NS_OK;
     }
   }
   return NS_ERROR_FAILURE;
 }
 
@@ -135,17 +135,17 @@ nsNSSCertificateDB::FindCertByDBKey(cons
 
   dummy = NSSBase64_DecodeBuffer(nullptr, &keyItem, aDBkey,
                                  (uint32_t)strlen(aDBkey)); 
   if (!dummy || keyItem.len < NS_NSS_LONG*4) {
     PR_FREEIF(keyItem.data);
     return NS_ERROR_INVALID_ARG;
   }
 
-  ScopedCERTCertificate cert;
+  insanity::pkix::ScopedCERTCertificate cert;
   // someday maybe we can speed up the search using the moduleID and slotID
   // moduleID = NS_NSS_GET_LONG(keyItem.data);
   // slotID = NS_NSS_GET_LONG(&keyItem.data[NS_NSS_LONG]);
 
   // build the issuer/SN structure
   issuerSN.serialNumber.len = NS_NSS_GET_LONG(&keyItem.data[NS_NSS_LONG*2]);
   issuerSN.derIssuer.len = NS_NSS_GET_LONG(&keyItem.data[NS_NSS_LONG*3]);
   if (issuerSN.serialNumber.len == 0 || issuerSN.derIssuer.len == 0
@@ -156,17 +156,17 @@ nsNSSCertificateDB::FindCertByDBKey(cons
   }
   issuerSN.serialNumber.data= &keyItem.data[NS_NSS_LONG*4];
   issuerSN.derIssuer.data= &keyItem.data[NS_NSS_LONG*4+
                                               issuerSN.serialNumber.len];
 
   cert = CERT_FindCertByIssuerAndSN(CERT_GetDefaultCertDB(), &issuerSN);
   PR_FREEIF(keyItem.data);
   if (cert) {
-    nsCOMPtr<nsIX509Cert> nssCert = nsNSSCertificate::Create(cert);
+    nsCOMPtr<nsIX509Cert> nssCert = nsNSSCertificate::Create(cert.get());
     if (!nssCert)
       return NS_ERROR_OUT_OF_MEMORY;
     nssCert.forget(_cert);
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP 
@@ -179,34 +179,34 @@ nsNSSCertificateDB::FindCertNicknames(ns
   if (isAlreadyShutDown()) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
   nsresult rv = NS_ERROR_FAILURE;
   /*
    * obtain the cert list from NSS
    */
-  ScopedCERTCertList certList;
+  insanity::pkix::ScopedCERTCertList certList;
   PK11CertListType pk11type;
 #if 0
   // this would seem right, but it didn't work...
   // oh, I know why - bonks out on internal slot certs
   if (aType == nsIX509Cert::USER_CERT)
     pk11type = PK11CertListUser;
   else 
 #endif
     pk11type = PK11CertListUnique;
   certList = PK11_ListCerts(pk11type, nullptr);
   if (!certList)
     goto cleanup;
   /*
    * get list of cert names from list of certs
    * XXX also cull the list (NSS only distinguishes based on user/non-user
    */
-  getCertNames(certList, aType, _count, _certNames, locker);
+  getCertNames(certList.get(), aType, _count, _certNames, locker);
   rv = NS_OK;
   /*
    * finish up
    */
 cleanup:
   return rv;
 }
 
@@ -343,33 +343,33 @@ nsNSSCertificateDB::handleCACertDownload
  
   SECItem der;
   rv=certToShow->GetRawDER(&der.len, (uint8_t **)&der.data);
 
   if (NS_FAILED(rv))
     return rv;
 
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Creating temp cert\n"));
-  ScopedCERTCertificate tmpCert;
+  insanity::pkix::ScopedCERTCertificate tmpCert;
   CERTCertDBHandle *certdb = CERT_GetDefaultCertDB();
   tmpCert = CERT_FindCertByDERCert(certdb, &der);
   if (!tmpCert) {
     tmpCert = CERT_NewTempCertificate(certdb, &der,
                                       nullptr, false, true);
   }
   nsMemory::Free(der.data);
   der.data = nullptr;
   der.len = 0;
   
   if (!tmpCert) {
     NS_ERROR("Couldn't create cert from DER blob");
     return NS_ERROR_FAILURE;
   }
 
-  if (!CERT_IsCACert(tmpCert, nullptr)) {
+  if (!CERT_IsCACert(tmpCert.get(), nullptr)) {
     DisplayCertificateAlert(ctx, "NotACACert", certToShow, proofOfLock);
     return NS_ERROR_FAILURE;
   }
 
   if (tmpCert->isperm) {
     DisplayCertificateAlert(ctx, "CaCertExists", certToShow, proofOfLock);
     return NS_ERROR_FAILURE;
   }
@@ -380,37 +380,37 @@ nsNSSCertificateDB::handleCACertDownload
   if (NS_FAILED(rv))
     return rv;
 
   if (!allows)
     return NS_ERROR_NOT_AVAILABLE;
 
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("trust is %d\n", trustBits));
   nsXPIDLCString nickname;
-  nickname.Adopt(CERT_MakeCANickname(tmpCert));
+  nickname.Adopt(CERT_MakeCANickname(tmpCert.get()));
 
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Created nick \"%s\"\n", nickname.get()));
 
   nsNSSCertTrust trust;
   trust.SetValidCA();
   trust.AddCATrust(!!(trustBits & nsIX509CertDB::TRUSTED_SSL),
                    !!(trustBits & nsIX509CertDB::TRUSTED_EMAIL),
                    !!(trustBits & nsIX509CertDB::TRUSTED_OBJSIGN));
 
-  SECStatus srv = __CERT_AddTempCertToPerm(tmpCert,
+  SECStatus srv = __CERT_AddTempCertToPerm(tmpCert.get(),
                                            const_cast<char*>(nickname.get()),
                                            trust.GetTrust());
 
   if (srv != SECSuccess)
     return NS_ERROR_FAILURE;
 
   // Import additional delivered certificates that can be verified.
 
   // build a CertList for filtering
-  ScopedCERTCertList certList(CERT_NewCertList());
+  insanity::pkix::ScopedCERTCertList certList(CERT_NewCertList());
   if (!certList) {
     return NS_ERROR_FAILURE;
   }
 
   // get all remaining certs into temp store
 
   for (uint32_t i=0; i<numCerts; i++) {
     if (i == selCertIndex) {
@@ -428,20 +428,20 @@ nsNSSCertificateDB::handleCACertDownload
     der.data = nullptr;
     der.len = 0;
 
     if (!tmpCert2) {
       NS_ERROR("Couldn't create temp cert from DER blob");
       continue;  // Let's try to import the rest of 'em
     }
     
-    CERT_AddCertToListTail(certList, tmpCert2);
+    CERT_AddCertToListTail(certList.get(), tmpCert2);
   }
 
-  return ImportValidCACertsInList(certList, ctx, proofOfLock);
+  return ImportValidCACertsInList(certList.get(), ctx, proofOfLock);
 }
 
 /*
  *  [noscript] void importCertificates(in charPtr data, in unsigned long length,
  *                                     in unsigned long type, 
  *                                     in nsIInterfaceRequestor ctx);
  */
 NS_IMETHODIMP 
@@ -495,18 +495,19 @@ nsNSSCertificateDB::ImportCertificates(u
      break;
   }  
   PORT_FreeArena(arena, false);
   return nsrv;
 }
 
 static 
 SECStatus 
-ImportCertsIntoPermanentStorage(const ScopedCERTCertList &certChain, const SECCertUsage usage,
-                               const PRBool caOnly)
+ImportCertsIntoPermanentStorage(
+  const insanity::pkix::ScopedCERTCertList& certChain,
+  const SECCertUsage usage, const PRBool caOnly)
 {
   CERTCertDBHandle *certdb = CERT_GetDefaultCertDB();
 
   int chainLen = 0;
   for (CERTCertListNode *chainNode = CERT_LIST_HEAD(certChain);
        !CERT_LIST_END(chainNode, certChain);
        chainNode = CERT_LIST_NEXT(chainNode)) {
     chainLen++;
@@ -545,17 +546,17 @@ nsNSSCertificateDB::ImportEmailCertifica
   if (isAlreadyShutDown()) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
   SECStatus srv = SECFailure;
   nsresult nsrv = NS_OK;
   CERTCertDBHandle *certdb;
   CERTCertificate **certArray = nullptr;
-  ScopedCERTCertList certList;
+  insanity::pkix::ScopedCERTCertList certList;
   CERTCertListNode *node;
   SECItem **rawArray;
   int numcerts;
   int i;
 
   PLArenaPool *arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   if (!arena)
     return NS_ERROR_OUT_OF_MEMORY;
@@ -601,45 +602,44 @@ nsNSSCertificateDB::ImportEmailCertifica
     nsrv = NS_ERROR_FAILURE;
     goto loser;
   }
   for (i=0; i < numcerts; i++) {
     CERTCertificate *cert = certArray[i];
     if (cert)
       cert = CERT_DupCertificate(cert);
     if (cert)
-      CERT_AddCertToListTail(certList, cert);
+      CERT_AddCertToListTail(certList.get(), cert);
   }
 
   /* go down the remaining list of certs and verify that they have
    * valid chains, then import them.
    */
 
   for (node = CERT_LIST_HEAD(certList);
        !CERT_LIST_END(node,certList);
        node = CERT_LIST_NEXT(node)) {
 
     if (!node->cert) {
       continue;
     }
 
-    CERTCertList *verifyCertChain = nullptr;
+    insanity::pkix::ScopedCERTCertList certChain;
 
     SECStatus rv = certVerifier->VerifyCert(node->cert,
                                             certificateUsageEmailRecipient,
-                                            now, ctx, 0, &verifyCertChain);
-
-    ScopedCERTCertList certChain(verifyCertChain);
+                                            now, ctx, 0, &certChain);
 
     if (rv != SECSuccess) {
       nsCOMPtr<nsIX509Cert> certToShow = nsNSSCertificate::Create(node->cert);
       DisplayCertificateAlert(ctx, "NotImportingUnverifiedCert", certToShow, locker);
       continue;
     }
-    rv = ImportCertsIntoPermanentStorage(certChain, certUsageEmailRecipient, false);
+    rv = ImportCertsIntoPermanentStorage(certChain, certUsageEmailRecipient,
+                                         false);
     if (rv != SECSuccess) {
       goto loser;
     } 
     CERT_SaveSMimeProfile(node->cert, nullptr, nullptr);
 
   }
 
 loser:
@@ -658,17 +658,17 @@ nsNSSCertificateDB::ImportServerCertific
 {
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown()) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
   SECStatus srv = SECFailure;
   nsresult nsrv = NS_OK;
-  ScopedCERTCertificate cert;
+  insanity::pkix::ScopedCERTCertificate cert;
   SECItem **rawCerts = nullptr;
   int numcerts;
   int i;
   nsNSSCertTrust trust;
   char *serverNickname = nullptr;
  
   PLArenaPool *arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   if (!arena)
@@ -691,28 +691,29 @@ nsNSSCertificateDB::ImportServerCertific
     nsrv = NS_ERROR_FAILURE;
     goto loser;
   }
 
   for ( i = 0; i < numcerts; i++ ) {
     rawCerts[i] = &certCollection->rawCerts[i];
   }
 
-  serverNickname = nsNSSCertificate::defaultServerNickname(cert);
+  serverNickname = nsNSSCertificate::defaultServerNickname(cert.get());
   srv = CERT_ImportCerts(CERT_GetDefaultCertDB(), certUsageSSLServer,
              numcerts, rawCerts, nullptr, true, false,
              serverNickname);
   PR_FREEIF(serverNickname);
   if ( srv != SECSuccess ) {
     nsrv = NS_ERROR_FAILURE;
     goto loser;
   }
 
   trust.SetValidServerPeer();
-  srv = CERT_ChangeCertTrust(CERT_GetDefaultCertDB(), cert, trust.GetTrust());
+  srv = CERT_ChangeCertTrust(CERT_GetDefaultCertDB(), cert.get(),
+                             trust.GetTrust());
   if ( srv != SECSuccess ) {
     nsrv = NS_ERROR_FAILURE;
     goto loser;
   }
 loser:
   PORT_Free(rawCerts);
   if (arena) 
     PORT_FreeArena(arena, true);
@@ -784,25 +785,19 @@ nsNSSCertificateDB::ImportValidCACertsIn
   /* go down the remaining list of certs and verify that they have
    * valid chains, if yes, then import.
    */
   CERTCertListNode *node;
 
   for (node = CERT_LIST_HEAD(certList);
        !CERT_LIST_END(node,certList);
        node = CERT_LIST_NEXT(node)) {
-
-    //bool alert_and_skip = false;
-    CERTCertList *verifyCertChain = nullptr;
-
+    insanity::pkix::ScopedCERTCertList certChain;
     SECStatus rv = certVerifier->VerifyCert(node->cert, certificateUsageVerifyCA,
-                                            PR_Now(), ctx, 0, &verifyCertChain);
-
-    ScopedCERTCertList certChain(verifyCertChain);
-
+                                            PR_Now(), ctx, 0, &certChain);
     if (rv != SECSuccess) {
       nsCOMPtr<nsIX509Cert> certToShow = nsNSSCertificate::Create(node->cert);
       DisplayCertificateAlert(ctx, "NotImportingUnverifiedCert", certToShow, proofOfLock);
       continue;
     }
 
     rv = ImportCertsIntoPermanentStorage(certChain, certUsageAnyCA, true);
     if (rv != SECSuccess) {
@@ -866,17 +861,17 @@ nsNSSCertificateDB::ImportUserCertificat
 
   ScopedPK11SlotInfo slot;
   nsAutoCString nickname;
   nsresult rv = NS_ERROR_FAILURE;
   int numCACerts;
   SECItem *CACerts;
   CERTDERCerts * collectArgs;
   PLArenaPool *arena;
-  ScopedCERTCertificate cert;
+  insanity::pkix::ScopedCERTCertificate cert;
 
   arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   if (!arena) {
     goto loser;
   }
 
   collectArgs = getCertsFromPackage(arena, data, length, locker);
   if (!collectArgs) {
@@ -884,47 +879,47 @@ nsNSSCertificateDB::ImportUserCertificat
   }
 
   cert = CERT_NewTempCertificate(CERT_GetDefaultCertDB(), collectArgs->rawCerts,
                                  nullptr, false, true);
   if (!cert) {
     goto loser;
   }
 
-  slot = PK11_KeyForCertExists(cert, nullptr, ctx);
+  slot = PK11_KeyForCertExists(cert.get(), nullptr, ctx);
   if (!slot) {
-    nsCOMPtr<nsIX509Cert> certToShow = nsNSSCertificate::Create(cert);
+    nsCOMPtr<nsIX509Cert> certToShow = nsNSSCertificate::Create(cert.get());
     DisplayCertificateAlert(ctx, "UserCertIgnoredNoPrivateKey", certToShow, locker);
     goto loser;
   }
   slot = nullptr;
 
   /* pick a nickname for the cert */
   if (cert->nickname) {
 	/* sigh, we need a call to look up other certs with this subject and
 	 * identify nicknames from them. We can no longer walk down internal
 	 * database structures  rjr */
   	nickname = cert->nickname;
   }
   else {
-    get_default_nickname(cert, ctx, nickname, locker);
+    get_default_nickname(cert.get(), ctx, nickname, locker);
   }
 
   /* user wants to import the cert */
   {
     char *cast_const_away = const_cast<char*>(nickname.get());
-    slot = PK11_ImportCertForKey(cert, cast_const_away, ctx);
+    slot = PK11_ImportCertForKey(cert.get(), cast_const_away, ctx);
   }
   if (!slot) {
     goto loser;
   }
   slot = nullptr;
 
   {
-    nsCOMPtr<nsIX509Cert> certToShow = nsNSSCertificate::Create(cert);
+    nsCOMPtr<nsIX509Cert> certToShow = nsNSSCertificate::Create(cert.get());
     DisplayCertificateAlert(ctx, "UserCertImported", certToShow, locker);
   }
   rv = NS_OK;
 
   numCACerts = collectArgs->numcerts - 1;
   if (numCACerts) {
     CACerts = collectArgs->rawCerts+1;
     rv = ImportValidCACerts(numCACerts, CACerts, ctx, locker);
@@ -943,17 +938,17 @@ loser:
 NS_IMETHODIMP 
 nsNSSCertificateDB::DeleteCertificate(nsIX509Cert *aCert)
 {
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown()) {
     return NS_ERROR_NOT_AVAILABLE;
   }
   nsCOMPtr<nsIX509Cert2> nssCert = do_QueryInterface(aCert);
-  ScopedCERTCertificate cert(nssCert->GetCert());
+  insanity::pkix::ScopedCERTCertificate cert(nssCert->GetCert());
   if (!cert) return NS_ERROR_FAILURE;
   SECStatus srv = SECSuccess;
 
   uint32_t certType;
   nssCert->GetCertType(&certType);
   if (NS_FAILED(nssCert->MarkForPermDeletion()))
   {
     return NS_ERROR_FAILURE;
@@ -964,17 +959,17 @@ nsNSSCertificateDB::DeleteCertificate(ns
     // completely untrusted.  This way we keep a copy cached in the
     // local database, and next time we try to load it off of the 
     // external token/slot, we'll know not to trust it.  We don't 
     // want to do that with user certs, because a user may  re-store
     // the cert onto the card again at which point we *will* want to 
     // trust that cert if it chains up properly.
     nsNSSCertTrust trust(0, 0, 0);
     srv = CERT_ChangeCertTrust(CERT_GetDefaultCertDB(), 
-                               cert, trust.GetTrust());
+                               cert.get(), trust.GetTrust());
   }
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("cert deleted: %d", srv));
   return (srv) ? NS_ERROR_FAILURE : NS_OK;
 }
 
 /*
  * void setCertTrust(in nsIX509Cert cert,
  *                   in unsigned long type,
@@ -989,40 +984,40 @@ nsNSSCertificateDB::SetCertTrust(nsIX509
   if (isAlreadyShutDown()) {
     return NS_ERROR_NOT_AVAILABLE;
   }
   SECStatus srv;
   nsNSSCertTrust trust;
   nsCOMPtr<nsIX509Cert2> pipCert = do_QueryInterface(cert);
   if (!pipCert)
     return NS_ERROR_FAILURE;
-  ScopedCERTCertificate nsscert(pipCert->GetCert());
+  insanity::pkix::ScopedCERTCertificate nsscert(pipCert->GetCert());
 
   if (type == nsIX509Cert::CA_CERT) {
     // always start with untrusted and move up
     trust.SetValidCA();
     trust.AddCATrust(!!(trusted & nsIX509CertDB::TRUSTED_SSL),
                      !!(trusted & nsIX509CertDB::TRUSTED_EMAIL),
                      !!(trusted & nsIX509CertDB::TRUSTED_OBJSIGN));
     srv = CERT_ChangeCertTrust(CERT_GetDefaultCertDB(), 
-                               nsscert,
+                               nsscert.get(),
                                trust.GetTrust());
   } else if (type == nsIX509Cert::SERVER_CERT) {
     // always start with untrusted and move up
     trust.SetValidPeer();
     trust.AddPeerTrust(trusted & nsIX509CertDB::TRUSTED_SSL, 0, 0);
     srv = CERT_ChangeCertTrust(CERT_GetDefaultCertDB(), 
-                               nsscert,
+                               nsscert.get(),
                                trust.GetTrust());
   } else if (type == nsIX509Cert::EMAIL_CERT) {
     // always start with untrusted and move up
     trust.SetValidPeer();
     trust.AddPeerTrust(0, !!(trusted & nsIX509CertDB::TRUSTED_EMAIL), 0);
     srv = CERT_ChangeCertTrust(CERT_GetDefaultCertDB(), 
-                               nsscert,
+                               nsscert.get(),
                                trust.GetTrust());
   } else {
     // ignore user certs
     return NS_OK;
   }
   return (srv) ? NS_ERROR_FAILURE : NS_OK;
 }
 
@@ -1036,19 +1031,19 @@ nsNSSCertificateDB::IsCertTrusted(nsIX50
   *_isTrusted = false;
 
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown()) {
     return NS_ERROR_NOT_AVAILABLE;
   }
   SECStatus srv;
   nsCOMPtr<nsIX509Cert2> pipCert = do_QueryInterface(cert);
-  ScopedCERTCertificate nsscert(pipCert->GetCert());
+  insanity::pkix::ScopedCERTCertificate nsscert(pipCert->GetCert());
   CERTCertTrust nsstrust;
-  srv = CERT_GetCertTrust(nsscert, &nsstrust);
+  srv = CERT_GetCertTrust(nsscert.get(), &nsstrust);
   if (srv != SECSuccess)
     return NS_ERROR_FAILURE;
 
   nsNSSCertTrust trust(&nsstrust);
   if (certType == nsIX509Cert::CA_CERT) {
     if (trustType & nsIX509CertDB::TRUSTED_SSL) {
       *_isTrusted = trust.HasTrustedCA(true, false, false);
     } else if (trustType & nsIX509CertDB::TRUSTED_EMAIL) {
@@ -1284,24 +1279,24 @@ nsNSSCertificateDB::FindEmailEncryptionC
   }
 
   nsCOMPtr<nsIInterfaceRequestor> ctx = new PipUIContext();
   char *asciiname = nullptr;
   NS_ConvertUTF16toUTF8 aUtf8Nickname(aNickname);
   asciiname = const_cast<char*>(aUtf8Nickname.get());
 
   /* Find a good cert in the user's database */
-  ScopedCERTCertificate cert;
+  insanity::pkix::ScopedCERTCertificate cert;
   cert = CERT_FindUserCertByUsage(CERT_GetDefaultCertDB(), asciiname, 
            certUsageEmailRecipient, true, ctx);
   if (!cert) {
     return NS_OK;
   }
 
-  nsCOMPtr<nsIX509Cert> nssCert = nsNSSCertificate::Create(cert);
+  nsCOMPtr<nsIX509Cert> nssCert = nsNSSCertificate::Create(cert.get());
   if (!nssCert) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
   nssCert.forget(_retval);
   return NS_OK;
 }
 
 /* nsIX509Cert getDefaultEmailSigningCert (); */
@@ -1314,30 +1309,30 @@ nsNSSCertificateDB::FindEmailSigningCert
   if (aNickname.IsEmpty())
     return NS_OK;
 
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown()) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
-  ScopedCERTCertificate cert;
+  insanity::pkix::ScopedCERTCertificate cert;
   nsCOMPtr<nsIInterfaceRequestor> ctx = new PipUIContext();
   char *asciiname = nullptr;
   NS_ConvertUTF16toUTF8 aUtf8Nickname(aNickname);
   asciiname = const_cast<char*>(aUtf8Nickname.get());
 
   /* Find a good cert in the user's database */
   cert = CERT_FindUserCertByUsage(CERT_GetDefaultCertDB(), asciiname, 
            certUsageEmailSigner, true, ctx);
   if (!cert) {
     return NS_OK;
   }
 
-  nsCOMPtr<nsIX509Cert> nssCert = nsNSSCertificate::Create(cert);
+  nsCOMPtr<nsIX509Cert> nssCert = nsNSSCertificate::Create(cert.get());
   if (!nssCert) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
   nssCert.forget(_retval);
   return NS_OK;
 }
 
 NS_IMETHODIMP
@@ -1424,27 +1419,27 @@ nsNSSCertificateDB::ConstructX509FromBas
   }
 
 
   SECItem secitem_cert;
   secitem_cert.type = siDERCertBuffer;
   secitem_cert.data = (unsigned char*)certDER;
   secitem_cert.len = lengthDER;
 
-  ScopedCERTCertificate cert;
+  insanity::pkix::ScopedCERTCertificate cert;
   cert =
     CERT_NewTempCertificate(CERT_GetDefaultCertDB(), &secitem_cert,
                             nullptr, false, true);
   PL_strfree(certDER);
 
   if (!cert)
     return (PORT_GetError() == SEC_ERROR_NO_MEMORY)
       ? NS_ERROR_OUT_OF_MEMORY : NS_ERROR_FAILURE;
 
-  nsCOMPtr<nsIX509Cert> nssCert = nsNSSCertificate::Create(cert);
+  nsCOMPtr<nsIX509Cert> nssCert = nsNSSCertificate::Create(cert.get());
   if (!nssCert) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
   nssCert.forget(_retval);
   return NS_OK;
 }
 
 void
@@ -1525,17 +1520,17 @@ nsNSSCertificateDB::get_default_nickname
       if (!tmp) {
         nickname.Truncate();
         return;
       }
       nickname = tmp;
       PR_smprintf_free(tmp);
     }
 
-    ScopedCERTCertificate dummycert;
+    insanity::pkix::ScopedCERTCertificate dummycert;
 
     if (PK11_IsInternal(slot)) {
       /* look up the nickname to make sure it isn't in use already */
       dummycert = CERT_FindCertByNickname(defaultcertdb, nickname.get());
 
     } else {
       /*
        * Check the cert against others that already live on the smart 
@@ -1586,17 +1581,17 @@ NS_IMETHODIMP nsNSSCertificateDB::AddCer
   NS_ENSURE_SUCCESS(rv, rv);
 
   SECItem der;
   rv = newCert->GetRawDER(&der.len, (uint8_t **)&der.data);
   NS_ENSURE_SUCCESS(rv, rv);
 
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Creating temp cert\n"));
   CERTCertDBHandle *certdb = CERT_GetDefaultCertDB();
-  ScopedCERTCertificate tmpCert(CERT_FindCertByDERCert(certdb, &der));
+  insanity::pkix::ScopedCERTCertificate tmpCert(CERT_FindCertByDERCert(certdb, &der));
   if (!tmpCert) 
     tmpCert = CERT_NewTempCertificate(certdb, &der,
                                       nullptr, false, true);
   nsMemory::Free(der.data);
   der.data = nullptr;
   der.len = 0;
 
   if (!tmpCert) {
@@ -1604,21 +1599,21 @@ NS_IMETHODIMP nsNSSCertificateDB::AddCer
     return NS_ERROR_FAILURE;
   }
 
   if (tmpCert->isperm) {
     return NS_OK;
   }
 
   nsXPIDLCString nickname;
-  nickname.Adopt(CERT_MakeCANickname(tmpCert));
+  nickname.Adopt(CERT_MakeCANickname(tmpCert.get()));
 
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Created nick \"%s\"\n", nickname.get()));
 
-  SECStatus srv = __CERT_AddTempCertToPerm(tmpCert,
+  SECStatus srv = __CERT_AddTempCertToPerm(tmpCert.get(),
                                            const_cast<char*>(nickname.get()),
                                            trust.GetTrust());
 
 
   return (srv == SECSuccess) ? NS_OK : NS_ERROR_FAILURE;
 }
 
 NS_IMETHODIMP
@@ -1634,21 +1629,22 @@ nsNSSCertificateDB::AddCert(const nsACSt
 NS_IMETHODIMP 
 nsNSSCertificateDB::GetCerts(nsIX509CertList **_retval)
 {
   nsNSSShutDownPreventionLock locker;
   if (isAlreadyShutDown()) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
-  CERTCertList *certList;
+  
 
   nsCOMPtr<nsIInterfaceRequestor> ctx = new PipUIContext();
   nsCOMPtr<nsIX509CertList> nssCertList;
-  certList = PK11_ListCerts(PK11CertListUnique, ctx);
+  insanity::pkix::ScopedCERTCertList certList(
+    PK11_ListCerts(PK11CertListUnique, ctx));
 
   // nsNSSCertList 1) adopts certList, and 2) handles the nullptr case fine.
   // (returns an empty list) 
   nssCertList = new nsNSSCertList(certList, locker);
 
   *_retval = nssCertList;
   NS_ADDREF(*_retval);
   return NS_OK;
@@ -1707,17 +1703,17 @@ nsNSSCertificateDB::VerifyCertNow(nsIX50
   if (!x509Cert) {
     return NS_ERROR_INVALID_ARG;
   }
   ScopedCERTCertificate nssCert(x509Cert->GetCert());
 
   RefPtr<SharedCertVerifier> certVerifier(GetDefaultCertVerifier());
   NS_ENSURE_TRUE(certVerifier, NS_ERROR_FAILURE);
 
-  CERTCertList* resultChain = nullptr;
+  insanity::pkix::ScopedCERTCertList resultChain;
   SECOidTag evOidPolicy;
   SECStatus srv;
 
   srv = certVerifier->VerifyCert(nssCert,
                                  aUsage, PR_Now(),
                                  nullptr, // Assume no context
                                  aFlags,
                                  &resultChain,
--- a/security/manager/ssl/src/nsNSSIOLayer.cpp
+++ b/security/manager/ssl/src/nsNSSIOLayer.cpp
@@ -1,17 +1,18 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  *
  * 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 "nsNSSComponent.h"
 #include "nsNSSIOLayer.h"
 
+#include "insanity/pkixtypes.h"
+#include "nsNSSComponent.h"
 #include "mozilla/Casting.h"
 #include "mozilla/DebugOnly.h"
 #include "mozilla/Telemetry.h"
 
 #include "prlog.h"
 #include "prnetdb.h"
 #include "nsIPrefService.h"
 #include "nsIClientAuthDialogs.h"
@@ -1879,19 +1880,19 @@ nsNSS_SSLGetClientAuthData(void* arg, PR
   return runnable->mRV;
 }
 
 void
 ClientAuthDataRunnable::RunOnTargetThread()
 {
   PLArenaPool* arena = nullptr;
   char** caNameStrings;
-  ScopedCERTCertificate cert;
+  insanity::pkix::ScopedCERTCertificate cert;
   ScopedSECKEYPrivateKey privKey;
-  ScopedCERTCertList certList;
+  insanity::pkix::ScopedCERTCertList certList;
   CERTCertListNode* node;
   ScopedCERTCertNicknames nicknames;
   char* extracted = nullptr;
   int keyError = 0; // used for private key retrieval error
   SSM_UserCertChoice certChoice;
   int32_t NumberOfCerts = 0;
   void* wincx = mSocketInfo;
   nsresult rv;
@@ -1926,17 +1927,17 @@ ClientAuthDataRunnable::RunOnTargetThrea
     certList = CERT_FindUserCertsByUsage(CERT_GetDefaultCertDB(),
                                          certUsageSSLClient, false,
                                          true, wincx);
     if (!certList) {
       goto noCert;
     }
 
     // filter the list to those issued by CAs supported by the server
-    mRV = CERT_FilterCertListByCANames(certList, mCANames->nnames,
+    mRV = CERT_FilterCertListByCANames(certList.get(), mCANames->nnames,
                                        caNameStrings, certUsageSSLClient);
     if (mRV != SECSuccess) {
       goto noCert;
     }
 
     // make sure the list is not empty
     node = CERT_LIST_HEAD(certList);
     if (CERT_LIST_END(node, certList)) {
@@ -1969,17 +1970,17 @@ ClientAuthDataRunnable::RunOnTargetThrea
         goto loser;
       }
 
       node = CERT_LIST_NEXT(node);
     }
 
     if (!cert && low_prio_nonrep_cert) {
       cert = low_prio_nonrep_cert.forget();
-      privKey = PK11_FindKeyByAnyCert(cert, wincx);
+      privKey = PK11_FindKeyByAnyCert(cert.get(), wincx);
     }
 
     if (!cert) {
       goto noCert;
     }
   } else { // Not Auto => ask
     // Get the SSL Certificate
 
@@ -2041,40 +2042,41 @@ ClientAuthDataRunnable::RunOnTargetThrea
         certUsageSSLClient, false,
         false, wincx);
       if (!certList) {
         goto noCert;
       }
 
       if (mCANames->nnames != 0) {
         // filter the list to those issued by CAs supported by the server
-        mRV = CERT_FilterCertListByCANames(certList, mCANames->nnames,
-          caNameStrings,
-          certUsageSSLClient);
+        mRV = CERT_FilterCertListByCANames(certList.get(),
+                                           mCANames->nnames,
+                                           caNameStrings,
+                                           certUsageSSLClient);
         if (mRV != SECSuccess) {
           goto loser;
         }
       }
 
       if (CERT_LIST_END(CERT_LIST_HEAD(certList), certList)) {
         // list is empty - no matching certs
         goto noCert;
       }
 
       // filter it further for hostname restriction
-      node = CERT_LIST_HEAD(certList);
-      while (!CERT_LIST_END(node, certList)) {
+      node = CERT_LIST_HEAD(certList.get());
+      while (!CERT_LIST_END(node, certList.get())) {
         ++NumberOfCerts;
         node = CERT_LIST_NEXT(node);
       }
-      if (CERT_LIST_END(CERT_LIST_HEAD(certList), certList)) {
+      if (CERT_LIST_END(CERT_LIST_HEAD(certList.get()), certList.get())) {
         goto noCert;
       }
 
-      nicknames = getNSSCertNicknamesFromCertList(certList);
+      nicknames = getNSSCertNicknamesFromCertList(certList.get());
 
       if (!nicknames) {
         goto loser;
       }
 
       NS_ASSERTION(nicknames->numnicknames == NumberOfCerts, "nicknames->numnicknames != NumberOfCerts");
 
       // Get CN and O of the subject and O of the issuer
@@ -2200,17 +2202,17 @@ ClientAuthDataRunnable::RunOnTargetThrea
 
     if (canceled) { rv = NS_ERROR_NOT_AVAILABLE; goto loser; }
 
     if (!cert) {
       goto loser;
     }
 
     // go get the private key
-    privKey = PK11_FindKeyByAnyCert(cert, wincx);
+    privKey = PK11_FindKeyByAnyCert(cert.get(), wincx);
     if (!privKey) {
       keyError = PR_GetError();
       if (keyError == SEC_ERROR_BAD_PASSWORD) {
         // problem with password: bail
         goto loser;
       } else {
         goto noCert;
       }
@@ -2228,17 +2230,17 @@ done:
 
   if (extracted) {
     PR_Free(extracted);
   }
   if (arena) {
     PORT_FreeArena(arena, false);
   }
 
-  *mPRetCert = cert.forget();
+  *mPRetCert = cert.release();
   *mPRetKey = privKey.forget();
 
   if (mRV == SECFailure) {
     mErrorCodeToReport = error;
   }
 }
 
 static PRFileDesc*
--- a/security/manager/ssl/src/nsPKCS12Blob.cpp
+++ b/security/manager/ssl/src/nsPKCS12Blob.cpp
@@ -1,36 +1,38 @@
 /* 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/. */
 /* $Id: nsPKCS12Blob.cpp,v 1.49 2007/09/05 07:13:46 jwalden%mit.edu Exp $ */
 
+#include "nsPKCS12Blob.h"
+
+#include "insanity/pkixtypes.h"
+
 #include "prmem.h"
 #include "prprf.h"
 
 #include "nsIFile.h"
 #include "nsNetUtil.h"
 #include "nsIDirectoryService.h"
 #include "nsThreadUtils.h"
 
 #include "nsNSSComponent.h"
 #include "nsNSSHelper.h"
-#include "nsPKCS12Blob.h"
 #include "nsString.h"
 #include "nsReadableUtils.h"
 #include "nsXPIDLString.h"
 #include "nsDirectoryServiceDefs.h"
 #include "nsNSSHelper.h"
 #include "nsNSSCertificate.h"
 #include "nsKeygenHandler.h" //For GetSlotWithMechanism
 #include "nsPK11TokenDB.h"
 #include "nsICertificateDialogs.h"
 #include "nsNSSShutDown.h"
 #include "nsCRT.h"
-#include "ScopedNSSTypes.h"
 
 #include "secerr.h"
 
 #ifdef PR_LOGGING
 extern PRLogModuleInfo* gPIPNSSLog;
 #endif
 
 using namespace mozilla;
@@ -351,30 +353,30 @@ nsPKCS12Blob::ExportToFile(nsIFile *file
     nsCOMPtr<nsIX509Cert> cert;
     nrv = mCertArray->GetElementAt(i, getter_AddRefs(cert));
     if (NS_FAILED(nrv)) goto finish;
 #endif
   for (i=0; i<numCerts; i++) {
 //    nsNSSCertificate *cert = reinterpret_cast<nsNSSCertificate *>(certs[i]);
     nsNSSCertificate *cert = (nsNSSCertificate *)certs[i];
     // get it as a CERTCertificate XXX
-    ScopedCERTCertificate nssCert(cert->GetCert());
+    insanity::pkix::ScopedCERTCertificate nssCert(cert->GetCert());
     if (!nssCert) {
       rv = NS_ERROR_FAILURE;
       goto finish;
     }
     // We can only successfully export certs that are on 
     // internal token.  Most, if not all, smart card vendors
     // won't let you extract the private key (in any way
     // shape or form) from the card.  So let's punt if 
     // the cert is not in the internal db.
     if (nssCert->slot && !PK11_IsInternal(nssCert->slot)) {
       // we aren't the internal token, see if the key is extractable.
       SECKEYPrivateKey *privKey=PK11_FindKeyByDERCert(nssCert->slot,
-                                                      nssCert, this);
+                                                      nssCert.get(), this);
 
       if (privKey) {
         bool privKeyIsExtractable = isExtractable(privKey);
 
         SECKEY_DestroyPrivateKey(privKey);
 
         if (!privKeyIsExtractable) {
           if (!InformedUserNoSmartcardBackup) {
@@ -396,17 +398,17 @@ nsPKCS12Blob::ExportToFile(nsIFile *file
       certSafe = SEC_PKCS12CreatePasswordPrivSafe(ecx, &unicodePw,
                            SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_40_BIT_RC2_CBC);
     }
     if (!certSafe || !keySafe) {
       rv = NS_ERROR_FAILURE;
       goto finish;
     }
     // add the cert and key to the blob
-    srv = SEC_PKCS12AddCertAndKey(ecx, certSafe, nullptr, nssCert,
+    srv = SEC_PKCS12AddCertAndKey(ecx, certSafe, nullptr, nssCert.get(),
                                   CERT_GetDefaultCertDB(), // XXX
                                   keySafe, nullptr, true, &unicodePw,
                       SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_3KEY_TRIPLE_DES_CBC);
     if (srv) goto finish;
     // cert was dup'ed, so release it
     ++numCertsExported;
   }
   
--- a/security/manager/ssl/src/nsPKCS12Blob.h
+++ b/security/manager/ssl/src/nsPKCS12Blob.h
@@ -2,16 +2,17 @@
  * 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/. */
 /* $Id: nsPKCS12Blob.h,v 1.16 2006/04/12 15:43:32 benjamin%smedbergs.us Exp $ */
 
 #ifndef _NS_PKCS12BLOB_H_
 #define _NS_PKCS12BLOB_H_
 
 #include "nsCOMPtr.h"
+#include "nsString.h"
 #include "nsIFile.h"
 #include "nsIPK11TokenDB.h"
 #include "nsNSSHelper.h"
 #include "nsIPK11Token.h"
 #include "nsIMutableArray.h"
 
 #include "nss.h"
 
--- a/security/manager/ssl/src/nsRecentBadCerts.cpp
+++ b/security/manager/ssl/src/nsRecentBadCerts.cpp
@@ -1,15 +1,17 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  *
  * 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 "nsRecentBadCerts.h"
+
+#include "insanity/pkixtypes.h"
 #include "nsIX509Cert.h"
 #include "nsIObserverService.h"
 #include "mozilla/RefPtr.h"
 #include "mozilla/Services.h"
 #include "nsSSLStatus.h"
 #include "nsCOMPtr.h"
 #include "nsNSSCertificate.h"
 #include "nsCRT.h"
@@ -65,29 +67,30 @@ nsRecentBadCerts::GetRecentBadCert(const
         isNotValidAtThisTime = mCerts[i].isNotValidAtThisTime;
         isUntrusted = mCerts[i].isUntrusted;
       }
     }
   }
 
   if (foundDER.len) {
     CERTCertDBHandle *certdb = CERT_GetDefaultCertDB();
-    ScopedCERTCertificate nssCert(CERT_FindCertByDERCert(certdb, &foundDER));
+    insanity::pkix::ScopedCERTCertificate nssCert(
+      CERT_FindCertByDERCert(certdb, &foundDER));
     if (!nssCert) 
       nssCert = CERT_NewTempCertificate(certdb, &foundDER,
                                         nullptr, // no nickname
                                         false, // not perm
                                         true); // copy der
 
     SECITEM_FreeItem(&foundDER, false);
 
     if (!nssCert)
       return NS_ERROR_FAILURE;
 
-    status->mServerCert = nsNSSCertificate::Create(nssCert);
+    status->mServerCert = nsNSSCertificate::Create(nssCert.get());
     status->mHaveCertErrorBits = true;
     status->mIsDomainMismatch = isDomainMismatch;
     status->mIsNotValidAtThisTime = isNotValidAtThisTime;
     status->mIsUntrusted = isUntrusted;
 
     *aStatus = status;
     NS_IF_ADDREF(*aStatus);
   }
--- a/security/manager/ssl/tests/gtest/moz.build
+++ b/security/manager/ssl/tests/gtest/moz.build
@@ -7,9 +7,13 @@
 LIBRARY_NAME = 'ssltest'
 
 LIBXUL_LIBRARY = True
 
 SOURCES += [
 	'TLSIntoleranceTest.cpp',
 ]
 
+LOCAL_INCLUDES += [
+    '../../../../insanity/include',
+]
+
 include('/ipc/chromium/chromium-config.mozbuild')