Andrew Top | 0d1858f | 2019-05-15 22:01:47 -0700 | [diff] [blame] | 1 | // Copyright 2014 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "crypto/scoped_test_nss_db.h" |
| 6 | |
| 7 | #include <cert.h> |
| 8 | |
| 9 | #include "base/logging.h" |
| 10 | #include "base/threading/thread_restrictions.h" |
| 11 | #include "crypto/nss_util.h" |
| 12 | #include "crypto/nss_util_internal.h" |
| 13 | #include "starboard/types.h" |
| 14 | |
| 15 | namespace crypto { |
| 16 | |
| 17 | ScopedTestNSSDB::ScopedTestNSSDB() { |
| 18 | EnsureNSSInit(); |
| 19 | // NSS is allowed to do IO on the current thread since dispatching |
| 20 | // to a dedicated thread would still have the affect of blocking |
| 21 | // the current thread, due to NSS's internal locking requirements |
| 22 | base::ScopedAllowBlockingForTesting allow_blocking; |
| 23 | |
| 24 | if (!temp_dir_.CreateUniqueTempDir()) |
| 25 | return; |
| 26 | |
| 27 | const char kTestDescription[] = "Test DB"; |
| 28 | slot_ = OpenSoftwareNSSDB(temp_dir_.GetPath(), kTestDescription); |
| 29 | } |
| 30 | |
| 31 | ScopedTestNSSDB::~ScopedTestNSSDB() { |
| 32 | // Remove trust from any certs in the test DB before closing it. Otherwise NSS |
| 33 | // may cache verification results even after the test DB is gone. |
| 34 | if (slot_) { |
| 35 | CERTCertList* cert_list = PK11_ListCertsInSlot(slot_.get()); |
| 36 | for (CERTCertListNode* node = CERT_LIST_HEAD(cert_list); |
| 37 | !CERT_LIST_END(node, cert_list); |
| 38 | node = CERT_LIST_NEXT(node)) { |
| 39 | CERTCertTrust trust = {0}; |
| 40 | if (CERT_ChangeCertTrust(CERT_GetDefaultCertDB(), node->cert, &trust) != |
| 41 | SECSuccess) { |
| 42 | LOG(ERROR) << "CERT_ChangeCertTrust failed: " << PORT_GetError(); |
| 43 | } |
| 44 | } |
| 45 | CERT_DestroyCertList(cert_list); |
| 46 | } |
| 47 | |
| 48 | // NSS is allowed to do IO on the current thread since dispatching |
| 49 | // to a dedicated thread would still have the affect of blocking |
| 50 | // the current thread, due to NSS's internal locking requirements |
| 51 | base::ScopedAllowBlockingForTesting allow_blocking; |
| 52 | |
| 53 | if (slot_) { |
| 54 | SECStatus status = SECMOD_CloseUserDB(slot_.get()); |
| 55 | if (status != SECSuccess) |
| 56 | PLOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError(); |
| 57 | } |
| 58 | |
| 59 | if (!temp_dir_.Delete()) |
| 60 | LOG(ERROR) << "Could not delete temporary directory."; |
| 61 | } |
| 62 | |
| 63 | } // namespace crypto |