blob: f3bc4d19498f8fe93df19333797ae9a48314c5dc [file] [log] [blame]
[email protected]190933f2014-07-28 09:56:511// 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
mattmb3dfdd82015-12-28 22:18:227#include <cert.h>
8
[email protected]190933f2014-07-28 09:56:519#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
14namespace crypto {
15
16ScopedTestNSSDB::ScopedTestNSSDB() {
17 EnsureNSSInit();
18 // NSS is allowed to do IO on the current thread since dispatching
19 // to a dedicated thread would still have the affect of blocking
20 // the current thread, due to NSS's internal locking requirements
Francois Doraye6fb2d02017-10-18 21:29:1321 base::ScopedAllowBlockingForTesting allow_blocking;
[email protected]190933f2014-07-28 09:56:5122
23 if (!temp_dir_.CreateUniqueTempDir())
24 return;
25
26 const char kTestDescription[] = "Test DB";
vabr16e5f602016-09-15 18:14:0027 slot_ = OpenSoftwareNSSDB(temp_dir_.GetPath(), kTestDescription);
[email protected]190933f2014-07-28 09:56:5128}
29
30ScopedTestNSSDB::~ScopedTestNSSDB() {
mattmb3dfdd82015-12-28 22:18:2231 // Remove trust from any certs in the test DB before closing it. Otherwise NSS
32 // may cache verification results even after the test DB is gone.
Pavol Marko2f1971102020-08-07 09:57:2833 RemoveTrustFromAllCerts();
mattmb3dfdd82015-12-28 22:18:2234
[email protected]190933f2014-07-28 09:56:5135 // NSS is allowed to do IO on the current thread since dispatching
36 // to a dedicated thread would still have the affect of blocking
37 // the current thread, due to NSS's internal locking requirements
Francois Doraye6fb2d02017-10-18 21:29:1338 base::ScopedAllowBlockingForTesting allow_blocking;
[email protected]190933f2014-07-28 09:56:5139
[email protected]d09565c42014-08-03 12:47:4440 if (slot_) {
41 SECStatus status = SECMOD_CloseUserDB(slot_.get());
42 if (status != SECSuccess)
43 PLOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
44 }
[email protected]190933f2014-07-28 09:56:5145
46 if (!temp_dir_.Delete())
47 LOG(ERROR) << "Could not delete temporary directory.";
48}
49
Pavol Marko2f1971102020-08-07 09:57:2850void ScopedTestNSSDB::RemoveTrustFromAllCerts() {
51 if (!slot_)
52 return;
53
54 CERTCertList* cert_list = PK11_ListCertsInSlot(slot_.get());
55 if (!cert_list)
56 return;
57
58 for (CERTCertListNode* node = CERT_LIST_HEAD(cert_list);
59 !CERT_LIST_END(node, cert_list); node = CERT_LIST_NEXT(node)) {
60 CERTCertTrust trust = {0};
61 if (CERT_ChangeCertTrust(CERT_GetDefaultCertDB(), node->cert, &trust) !=
62 SECSuccess) {
63 LOG(ERROR) << "CERT_ChangeCertTrust failed: " << PORT_GetError();
64 }
65 }
66 CERT_DestroyCertList(cert_list);
67}
68
[email protected]190933f2014-07-28 09:56:5169} // namespace crypto