xref: /aosp_15_r20/external/cronet/net/ssl/client_cert_store_nss.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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 #include "net/ssl/client_cert_store_nss.h"
6 
7 #include <nss.h>
8 #include <ssl.h>
9 
10 #include <algorithm>
11 #include <memory>
12 #include <utility>
13 #include <vector>
14 
15 #include "base/functional/bind.h"
16 #include "base/functional/callback_helpers.h"
17 #include "base/location.h"
18 #include "base/logging.h"
19 #include "base/strings/string_piece.h"
20 #include "base/task/thread_pool.h"
21 #include "base/threading/scoped_blocking_call.h"
22 #include "crypto/nss_crypto_module_delegate.h"
23 #include "crypto/nss_util.h"
24 #include "crypto/scoped_nss_types.h"
25 #include "net/cert/scoped_nss_types.h"
26 #include "net/cert/x509_util.h"
27 #include "net/cert/x509_util_nss.h"
28 #include "net/ssl/ssl_cert_request_info.h"
29 #include "net/ssl/ssl_platform_key_nss.h"
30 #include "net/ssl/threaded_ssl_private_key.h"
31 #include "net/third_party/nss/ssl/cmpcert.h"
32 #include "third_party/boringssl/src/include/openssl/pool.h"
33 
34 namespace net {
35 
36 namespace {
37 
38 class ClientCertIdentityNSS : public ClientCertIdentity {
39  public:
ClientCertIdentityNSS(scoped_refptr<net::X509Certificate> cert,ScopedCERTCertificate cert_certificate,scoped_refptr<crypto::CryptoModuleBlockingPasswordDelegate> password_delegate)40   ClientCertIdentityNSS(
41       scoped_refptr<net::X509Certificate> cert,
42       ScopedCERTCertificate cert_certificate,
43       scoped_refptr<crypto::CryptoModuleBlockingPasswordDelegate>
44           password_delegate)
45       : ClientCertIdentity(std::move(cert)),
46         cert_certificate_(std::move(cert_certificate)),
47         password_delegate_(std::move(password_delegate)) {}
48   ~ClientCertIdentityNSS() override = default;
49 
AcquirePrivateKey(base::OnceCallback<void (scoped_refptr<SSLPrivateKey>)> private_key_callback)50   void AcquirePrivateKey(base::OnceCallback<void(scoped_refptr<SSLPrivateKey>)>
51                              private_key_callback) override {
52     // Caller is responsible for keeping the ClientCertIdentity alive until
53     // the |private_key_callback| is run, so it's safe to use Unretained here.
54     base::ThreadPool::PostTaskAndReplyWithResult(
55         FROM_HERE,
56         {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
57         base::BindOnce(&FetchClientCertPrivateKey,
58                        base::Unretained(certificate()), cert_certificate_.get(),
59                        password_delegate_),
60         std::move(private_key_callback));
61   }
62 
63  private:
64   ScopedCERTCertificate cert_certificate_;
65   scoped_refptr<crypto::CryptoModuleBlockingPasswordDelegate>
66       password_delegate_;
67 };
68 
69 }  // namespace
70 
ClientCertStoreNSS(const PasswordDelegateFactory & password_delegate_factory)71 ClientCertStoreNSS::ClientCertStoreNSS(
72     const PasswordDelegateFactory& password_delegate_factory)
73     : password_delegate_factory_(password_delegate_factory) {}
74 
75 ClientCertStoreNSS::~ClientCertStoreNSS() = default;
76 
GetClientCerts(const SSLCertRequestInfo & request,ClientCertListCallback callback)77 void ClientCertStoreNSS::GetClientCerts(const SSLCertRequestInfo& request,
78                                         ClientCertListCallback callback) {
79   scoped_refptr<crypto::CryptoModuleBlockingPasswordDelegate> password_delegate;
80   if (!password_delegate_factory_.is_null())
81     password_delegate = password_delegate_factory_.Run(request.host_and_port);
82   base::ThreadPool::PostTaskAndReplyWithResult(
83       FROM_HERE,
84       {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
85       base::BindOnce(&ClientCertStoreNSS::GetAndFilterCertsOnWorkerThread,
86                      // Caller is responsible for keeping the ClientCertStore
87                      // alive until the callback is run.
88                      base::Unretained(this), std::move(password_delegate),
89                      base::Unretained(&request)),
90       std::move(callback));
91 }
92 
93 // static
FilterCertsOnWorkerThread(ClientCertIdentityList * identities,const SSLCertRequestInfo & request)94 void ClientCertStoreNSS::FilterCertsOnWorkerThread(
95     ClientCertIdentityList* identities,
96     const SSLCertRequestInfo& request) {
97   size_t num_raw = 0;
98 
99   auto keep_iter = identities->begin();
100 
101   base::Time now = base::Time::Now();
102 
103   for (auto examine_iter = identities->begin();
104        examine_iter != identities->end(); ++examine_iter) {
105     ++num_raw;
106 
107     X509Certificate* cert = (*examine_iter)->certificate();
108 
109     // Only offer unexpired certificates.
110     if (now < cert->valid_start() || now > cert->valid_expiry()) {
111       continue;
112     }
113 
114     ScopedCERTCertificateList nss_intermediates;
115     if (!MatchClientCertificateIssuers(cert, request.cert_authorities,
116                                        &nss_intermediates)) {
117       continue;
118     }
119 
120     std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
121     intermediates.reserve(nss_intermediates.size());
122     for (const ScopedCERTCertificate& nss_intermediate : nss_intermediates) {
123       intermediates.push_back(x509_util::CreateCryptoBuffer(base::make_span(
124           nss_intermediate->derCert.data, nss_intermediate->derCert.len)));
125     }
126 
127     // Retain a copy of the intermediates. Some deployments expect the client to
128     // supply intermediates out of the local store. See
129     // https://crbug.com/548631.
130     (*examine_iter)->SetIntermediates(std::move(intermediates));
131 
132     if (examine_iter == keep_iter)
133       ++keep_iter;
134     else
135       *keep_iter++ = std::move(*examine_iter);
136   }
137   identities->erase(keep_iter, identities->end());
138 
139   DVLOG(2) << "num_raw:" << num_raw << " num_filtered:" << identities->size();
140 
141   std::sort(identities->begin(), identities->end(), ClientCertIdentitySorter());
142 }
143 
GetAndFilterCertsOnWorkerThread(scoped_refptr<crypto::CryptoModuleBlockingPasswordDelegate> password_delegate,const SSLCertRequestInfo * request)144 ClientCertIdentityList ClientCertStoreNSS::GetAndFilterCertsOnWorkerThread(
145     scoped_refptr<crypto::CryptoModuleBlockingPasswordDelegate>
146         password_delegate,
147     const SSLCertRequestInfo* request) {
148   // This method may acquire the NSS lock or reenter this code via extension
149   // hooks (such as smart card UI). To ensure threads are not starved or
150   // deadlocked, the base::ScopedBlockingCall below increments the thread pool
151   // capacity if this method takes too much time to run.
152   base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
153                                                 base::BlockingType::MAY_BLOCK);
154   ClientCertIdentityList selected_identities;
155   GetPlatformCertsOnWorkerThread(std::move(password_delegate), CertFilter(),
156                                  &selected_identities);
157   FilterCertsOnWorkerThread(&selected_identities, *request);
158   return selected_identities;
159 }
160 
161 // static
GetPlatformCertsOnWorkerThread(scoped_refptr<crypto::CryptoModuleBlockingPasswordDelegate> password_delegate,const CertFilter & cert_filter,ClientCertIdentityList * identities)162 void ClientCertStoreNSS::GetPlatformCertsOnWorkerThread(
163     scoped_refptr<crypto::CryptoModuleBlockingPasswordDelegate>
164         password_delegate,
165     const CertFilter& cert_filter,
166     ClientCertIdentityList* identities) {
167   crypto::EnsureNSSInit();
168 
169   crypto::ScopedCERTCertList found_certs(CERT_FindUserCertsByUsage(
170       CERT_GetDefaultCertDB(), certUsageSSLClient, PR_FALSE, PR_FALSE,
171       password_delegate ? password_delegate->wincx() : nullptr));
172   if (!found_certs) {
173     DVLOG(2) << "No client certs found.";
174     return;
175   }
176   for (CERTCertListNode* node = CERT_LIST_HEAD(found_certs);
177        !CERT_LIST_END(node, found_certs); node = CERT_LIST_NEXT(node)) {
178     if (!cert_filter.is_null() && !cert_filter.Run(node->cert))
179       continue;
180     // Allow UTF-8 inside PrintableStrings in client certificates. See
181     // crbug.com/770323.
182     X509Certificate::UnsafeCreateOptions options;
183     options.printable_string_is_utf8 = true;
184     scoped_refptr<X509Certificate> cert =
185         x509_util::CreateX509CertificateFromCERTCertificate(node->cert, {},
186                                                             options);
187     if (!cert) {
188       DVLOG(2) << "x509_util::CreateX509CertificateFromCERTCertificate failed";
189       continue;
190     }
191     identities->push_back(std::make_unique<ClientCertIdentityNSS>(
192         cert, x509_util::DupCERTCertificate(node->cert), password_delegate));
193   }
194 }
195 
196 }  // namespace net
197