• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifdef UNSAFE_BUFFERS_BUILD
6 // TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
7 #pragma allow_unsafe_buffers
8 #endif
9 
10 #include "net/ssl/client_cert_store_nss.h"
11 
12 #include <nss.h>
13 #include <ssl.h>
14 
15 #include <algorithm>
16 #include <memory>
17 #include <utility>
18 #include <vector>
19 
20 #include "base/functional/bind.h"
21 #include "base/functional/callback_helpers.h"
22 #include "base/location.h"
23 #include "base/logging.h"
24 #include "base/task/thread_pool.h"
25 #include "base/threading/scoped_blocking_call.h"
26 #include "crypto/nss_crypto_module_delegate.h"
27 #include "crypto/nss_util.h"
28 #include "crypto/scoped_nss_types.h"
29 #include "net/base/features.h"
30 #include "net/cert/scoped_nss_types.h"
31 #include "net/cert/x509_util.h"
32 #include "net/cert/x509_util_nss.h"
33 #include "net/ssl/client_cert_matcher.h"
34 #include "net/ssl/ssl_cert_request_info.h"
35 #include "net/ssl/ssl_platform_key_nss.h"
36 #include "net/ssl/threaded_ssl_private_key.h"
37 #include "net/third_party/nss/ssl/cmpcert.h"
38 #include "third_party/boringssl/src/include/openssl/pool.h"
39 
40 namespace net {
41 
42 namespace {
43 
44 class ClientCertIdentityNSS : public ClientCertIdentity {
45  public:
ClientCertIdentityNSS(scoped_refptr<net::X509Certificate> cert,ScopedCERTCertificate cert_certificate,scoped_refptr<crypto::CryptoModuleBlockingPasswordDelegate> password_delegate)46   ClientCertIdentityNSS(
47       scoped_refptr<net::X509Certificate> cert,
48       ScopedCERTCertificate cert_certificate,
49       scoped_refptr<crypto::CryptoModuleBlockingPasswordDelegate>
50           password_delegate)
51       : ClientCertIdentity(std::move(cert)),
52         cert_certificate_(std::move(cert_certificate)),
53         password_delegate_(std::move(password_delegate)) {}
54   ~ClientCertIdentityNSS() override = default;
55 
AcquirePrivateKey(base::OnceCallback<void (scoped_refptr<SSLPrivateKey>)> private_key_callback)56   void AcquirePrivateKey(base::OnceCallback<void(scoped_refptr<SSLPrivateKey>)>
57                              private_key_callback) override {
58     // Caller is responsible for keeping the ClientCertIdentity alive until
59     // the |private_key_callback| is run, so it's safe to use Unretained here.
60     base::ThreadPool::PostTaskAndReplyWithResult(
61         FROM_HERE,
62         {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
63         base::BindOnce(&FetchClientCertPrivateKey,
64                        base::Unretained(certificate()), cert_certificate_.get(),
65                        password_delegate_),
66         std::move(private_key_callback));
67   }
68 
69  private:
70   ScopedCERTCertificate cert_certificate_;
71   scoped_refptr<crypto::CryptoModuleBlockingPasswordDelegate>
72       password_delegate_;
73 };
74 
75 }  // namespace
76 
77 std::vector<bssl::UniquePtr<CRYPTO_BUFFER>>
GetCertsByName(base::span<const uint8_t> name)78 ClientCertStoreNSS::IssuerSourceNSS::GetCertsByName(
79     base::span<const uint8_t> name) {
80   // This method may acquire the NSS lock or reenter this code via extension
81   // hooks (such as smart card UI). To ensure threads are not starved or
82   // deadlocked, the base::ScopedBlockingCall below increments the thread pool
83   // capacity if this method takes too much time to run.
84   // (The ScopedBlockingCall here is not redundant with the one below since
85   // the IssuerSourceNSS class may be used from other places outside of
86   // ClientCertStoreNSS.)
87   base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
88                                                 base::BlockingType::MAY_BLOCK);
89 
90   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> result;
91 
92   SECItem issuer_item;
93   issuer_item.len = name.size();
94   issuer_item.data = const_cast<unsigned char*>(name.data());
95   ScopedCERTCertificate nss_issuer(
96       CERT_FindCertByName(CERT_GetDefaultCertDB(), &issuer_item));
97   if (nss_issuer) {
98     result.push_back(x509_util::CreateCryptoBuffer(
99         x509_util::CERTCertificateAsSpan(nss_issuer.get())));
100   }
101 
102   return result;
103 }
104 
ClientCertStoreNSS(const PasswordDelegateFactory & password_delegate_factory)105 ClientCertStoreNSS::ClientCertStoreNSS(
106     const PasswordDelegateFactory& password_delegate_factory)
107     : password_delegate_factory_(password_delegate_factory) {}
108 
109 ClientCertStoreNSS::~ClientCertStoreNSS() = default;
110 
GetClientCerts(scoped_refptr<const SSLCertRequestInfo> request,ClientCertListCallback callback)111 void ClientCertStoreNSS::GetClientCerts(
112     scoped_refptr<const SSLCertRequestInfo> request,
113     ClientCertListCallback callback) {
114   scoped_refptr<crypto::CryptoModuleBlockingPasswordDelegate> password_delegate;
115   if (!password_delegate_factory_.is_null()) {
116     password_delegate = password_delegate_factory_.Run(request->host_and_port);
117   }
118   base::ThreadPool::PostTaskAndReplyWithResult(
119       FROM_HERE,
120       {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
121       base::BindOnce(&ClientCertStoreNSS::GetAndFilterCertsOnWorkerThread,
122                      std::move(password_delegate), std::move(request)),
123       base::BindOnce(&ClientCertStoreNSS::OnClientCertsResponse,
124                      weak_factory_.GetWeakPtr(), std::move(callback)));
125 }
126 
OnClientCertsResponse(ClientCertListCallback callback,ClientCertIdentityList identities)127 void ClientCertStoreNSS::OnClientCertsResponse(
128     ClientCertListCallback callback,
129     ClientCertIdentityList identities) {
130   std::move(callback).Run(std::move(identities));
131 }
132 
133 // static
FilterCertsOnWorkerThread(ClientCertIdentityList * identities,const SSLCertRequestInfo & request)134 void ClientCertStoreNSS::FilterCertsOnWorkerThread(
135     ClientCertIdentityList* identities,
136     const SSLCertRequestInfo& request) {
137   if (base::FeatureList::IsEnabled(features::kNewClientCertPathBuilding)) {
138     ClientCertIssuerSourceCollection sources;
139     sources.push_back(std::make_unique<IssuerSourceNSS>());
140     FilterMatchingClientCertIdentities(identities, request, sources);
141   } else {
142     size_t num_raw = 0;
143 
144     auto keep_iter = identities->begin();
145 
146     base::Time now = base::Time::Now();
147 
148     for (auto examine_iter = identities->begin();
149          examine_iter != identities->end(); ++examine_iter) {
150       ++num_raw;
151 
152       X509Certificate* cert = (*examine_iter)->certificate();
153 
154       // Only offer unexpired certificates.
155       if (now < cert->valid_start() || now > cert->valid_expiry()) {
156         continue;
157       }
158 
159       ScopedCERTCertificateList nss_intermediates;
160       if (!MatchClientCertificateIssuers(cert, request.cert_authorities,
161                                          &nss_intermediates)) {
162         continue;
163       }
164 
165       std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
166       intermediates.reserve(nss_intermediates.size());
167       for (const ScopedCERTCertificate& nss_intermediate : nss_intermediates) {
168         intermediates.push_back(x509_util::CreateCryptoBuffer(
169             x509_util::CERTCertificateAsSpan(nss_intermediate.get())));
170       }
171 
172       // Retain a copy of the intermediates. Some deployments expect the client
173       // to supply intermediates out of the local store. See
174       // https://crbug.com/548631.
175       (*examine_iter)->SetIntermediates(std::move(intermediates));
176 
177       if (examine_iter == keep_iter) {
178         ++keep_iter;
179       } else {
180         *keep_iter++ = std::move(*examine_iter);
181       }
182     }
183     identities->erase(keep_iter, identities->end());
184 
185     DVLOG(2) << "num_raw:" << num_raw << " num_filtered:" << identities->size();
186 
187     std::sort(identities->begin(), identities->end(),
188               ClientCertIdentitySorter());
189   }
190 }
191 
192 // static
GetAndFilterCertsOnWorkerThread(scoped_refptr<crypto::CryptoModuleBlockingPasswordDelegate> password_delegate,scoped_refptr<const SSLCertRequestInfo> request)193 ClientCertIdentityList ClientCertStoreNSS::GetAndFilterCertsOnWorkerThread(
194     scoped_refptr<crypto::CryptoModuleBlockingPasswordDelegate>
195         password_delegate,
196     scoped_refptr<const SSLCertRequestInfo> request) {
197   // This method may acquire the NSS lock or reenter this code via extension
198   // hooks (such as smart card UI). To ensure threads are not starved or
199   // deadlocked, the base::ScopedBlockingCall below increments the thread pool
200   // capacity if this method takes too much time to run.
201   base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
202                                                 base::BlockingType::MAY_BLOCK);
203   ClientCertIdentityList selected_identities;
204   GetPlatformCertsOnWorkerThread(std::move(password_delegate), CertFilter(),
205                                  &selected_identities);
206   FilterCertsOnWorkerThread(&selected_identities, *request);
207   return selected_identities;
208 }
209 
210 // static
GetPlatformCertsOnWorkerThread(scoped_refptr<crypto::CryptoModuleBlockingPasswordDelegate> password_delegate,const CertFilter & cert_filter,ClientCertIdentityList * identities)211 void ClientCertStoreNSS::GetPlatformCertsOnWorkerThread(
212     scoped_refptr<crypto::CryptoModuleBlockingPasswordDelegate>
213         password_delegate,
214     const CertFilter& cert_filter,
215     ClientCertIdentityList* identities) {
216   crypto::EnsureNSSInit();
217 
218   crypto::ScopedCERTCertList found_certs(CERT_FindUserCertsByUsage(
219       CERT_GetDefaultCertDB(), certUsageSSLClient, PR_FALSE, PR_FALSE,
220       password_delegate ? password_delegate->wincx() : nullptr));
221   if (!found_certs) {
222     DVLOG(2) << "No client certs found.";
223     return;
224   }
225   for (CERTCertListNode* node = CERT_LIST_HEAD(found_certs);
226        !CERT_LIST_END(node, found_certs); node = CERT_LIST_NEXT(node)) {
227     if (!cert_filter.is_null() && !cert_filter.Run(node->cert))
228       continue;
229     // Allow UTF-8 inside PrintableStrings in client certificates. See
230     // crbug.com/770323.
231     X509Certificate::UnsafeCreateOptions options;
232     options.printable_string_is_utf8 = true;
233     scoped_refptr<X509Certificate> cert =
234         x509_util::CreateX509CertificateFromCERTCertificate(node->cert, {},
235                                                             options);
236     if (!cert) {
237       DVLOG(2) << "x509_util::CreateX509CertificateFromCERTCertificate failed";
238       continue;
239     }
240     identities->push_back(std::make_unique<ClientCertIdentityNSS>(
241         cert, x509_util::DupCERTCertificate(node->cert), password_delegate));
242   }
243 }
244 
245 }  // namespace net
246