File: multi_threaded_cert_verifier.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (328 lines) | stat: -rw-r--r-- 12,636 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/cert/multi_threaded_cert_verifier.h"

#include "base/check_op.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram_macros.h"
#include "base/task/thread_pool.h"
#include "base/threading/thread_restrictions.h"
#include "base/timer/elapsed_timer.h"
#include "net/base/net_errors.h"
#include "net/base/trace_constants.h"
#include "net/base/tracing.h"
#include "net/base/url_util.h"
#include "net/cert/cert_verify_proc.h"
#include "net/cert/cert_verify_result.h"
#include "net/cert/x509_certificate.h"
#include "net/log/net_log_event_type.h"
#include "net/log/net_log_source_type.h"
#include "net/log/net_log_with_source.h"

namespace net {

// Allows DoVerifyOnWorkerThread to wait on a base::WaitableEvent.
// DoVerifyOnWorkerThread may wait on network operations done on a separate
// sequence. For instance when using the NSS-based implementation of certificate
// verification, the library requires a blocking callback for fetching OCSP and
// AIA responses.
class [[maybe_unused,
        nodiscard]] MultiThreadedCertVerifierScopedAllowBaseSyncPrimitives
    : public base::ScopedAllowBaseSyncPrimitives{};

namespace {

// Used to pass the result of DoVerifyOnWorkerThread() to
// MultiThreadedCertVerifier::InternalRequest::OnJobComplete().
struct ResultHelper {
  int error;
  CertVerifyResult result;
  NetLogWithSource net_log;
};

int GetFlagsForConfig(const CertVerifier::Config& config) {
  int flags = 0;

  if (config.enable_rev_checking)
    flags |= CertVerifyProc::VERIFY_REV_CHECKING_ENABLED;
  if (config.require_rev_checking_local_anchors)
    flags |= CertVerifyProc::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
  if (config.enable_sha1_local_anchors)
    flags |= CertVerifyProc::VERIFY_ENABLE_SHA1_LOCAL_ANCHORS;

  return flags;
}

// Runs the verification synchronously on a worker thread.
std::unique_ptr<ResultHelper> DoVerifyOnWorkerThread(
    const scoped_refptr<CertVerifyProc>& verify_proc,
    const scoped_refptr<X509Certificate>& cert,
    const std::string& hostname,
    const std::string& ocsp_response,
    const std::string& sct_list,
    int flags,
    const NetLogWithSource& net_log) {
  TRACE_EVENT0(NetTracingCategory(), "DoVerifyOnWorkerThread");
  base::ElapsedTimer timer;
  auto verify_result = std::make_unique<ResultHelper>();
  verify_result->net_log = net_log;
  MultiThreadedCertVerifierScopedAllowBaseSyncPrimitives
      allow_base_sync_primitives;
  verify_result->error =
      verify_proc->Verify(cert.get(), hostname, ocsp_response, sct_list, flags,
                          &verify_result->result, net_log);
  base::TimeDelta elapsed_time = timer.Elapsed();
  UMA_HISTOGRAM_CUSTOM_TIMES("Net.CertVerifier.DoVerifyOnWorkerThreadTime",
                             elapsed_time, base::Milliseconds(1),
                             base::Minutes(10), 100);
  if (IsGoogleHost(hostname)) {
    if (IsGoogleHostWithAlpnH3(hostname)) {
      UMA_HISTOGRAM_CUSTOM_TIMES(
          "Net.CertVerifier.DoVerifyOnWorkerThreadTime.GoogleWithAlpnH3",
          elapsed_time, base::Milliseconds(1), base::Minutes(10), 100);
    }
    UMA_HISTOGRAM_CUSTOM_TIMES(
        "Net.CertVerifier.DoVerifyOnWorkerThreadTime.Google", elapsed_time,
        base::Milliseconds(1), base::Minutes(10), 100);
  }
  return verify_result;
}

scoped_refptr<X509Certificate> DoVerify2QwacBindingOnWorkerThread(
    const scoped_refptr<CertVerifyProc>& verify_proc,
    const std::string& binding,
    const std::string& hostname,
    const scoped_refptr<X509Certificate>& tls_cert,
    const NetLogWithSource& net_log) {
  TRACE_EVENT0(NetTracingCategory(), "DoVerify2QwacBindingOnWorkerThread");
  return verify_proc->Verify2QwacBinding(binding, hostname,
                                         tls_cert->cert_span(), net_log);
}

}  // namespace

// Helper to allow callers to cancel pending CertVerifier::Verify requests.
// Note that because the CertVerifyProc is blocking, it's not actually
// possible to cancel the in-progress request; instead, this simply guarantees
// that the provided callback will not be invoked if the Request is deleted.
class MultiThreadedCertVerifier::InternalRequest
    : public CertVerifier::Request,
      public base::LinkNode<InternalRequest> {
 public:
  InternalRequest(CompletionOnceCallback callback,
                  CertVerifyResult* caller_result);
  ~InternalRequest() override;

  void Start(const scoped_refptr<CertVerifyProc>& verify_proc,
             const CertVerifier::Config& config,
             const CertVerifier::RequestParams& params,
             const NetLogWithSource& caller_net_log);

  void ResetCallback() { callback_.Reset(); }

 private:
  // This is a static method with a |self| weak pointer instead of a regular
  // method, so that PostTask will still run it even if the weakptr is no
  // longer valid.
  static void OnJobComplete(base::WeakPtr<InternalRequest> self,
                            const std::string hostname,
                            base::TimeTicks start_time,
                            std::unique_ptr<ResultHelper> verify_result);

  CompletionOnceCallback callback_;
  raw_ptr<CertVerifyResult> caller_result_;

  base::WeakPtrFactory<InternalRequest> weak_factory_{this};
};

MultiThreadedCertVerifier::InternalRequest::InternalRequest(
    CompletionOnceCallback callback,
    CertVerifyResult* caller_result)
    : callback_(std::move(callback)), caller_result_(caller_result) {}

MultiThreadedCertVerifier::InternalRequest::~InternalRequest() {
  if (callback_) {
    // This InternalRequest was eagerly cancelled as the callback is still
    // valid, so |this| needs to be removed from MultiThreadedCertVerifier's
    // list.
    RemoveFromList();
  }
}

void MultiThreadedCertVerifier::InternalRequest::Start(
    const scoped_refptr<CertVerifyProc>& verify_proc,
    const CertVerifier::Config& config,
    const CertVerifier::RequestParams& params,
    const NetLogWithSource& caller_net_log) {
  const NetLogWithSource net_log(NetLogWithSource::Make(
      caller_net_log.net_log(), NetLogSourceType::CERT_VERIFIER_TASK));
  net_log.BeginEvent(NetLogEventType::CERT_VERIFIER_TASK);
  caller_net_log.AddEventReferencingSource(
      NetLogEventType::CERT_VERIFIER_TASK_BOUND, net_log.source());

  int flags = GetFlagsForConfig(config);
  if (params.flags() & CertVerifier::VERIFY_DISABLE_NETWORK_FETCHES) {
    flags |= CertVerifyProc::VERIFY_DISABLE_NETWORK_FETCHES;
  }
  if (params.flags() & CertVerifier::VERIFY_SXG_CT_REQUIREMENTS) {
    flags |= CertVerifyProc::VERIFY_SXG_CT_REQUIREMENTS;
  }
  base::TimeTicks start_time = base::TimeTicks::Now();
  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE,
      {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(&DoVerifyOnWorkerThread, verify_proc, params.certificate(),
                     params.hostname(), params.ocsp_response(),
                     params.sct_list(), flags, net_log),
      base::BindOnce(&MultiThreadedCertVerifier::InternalRequest::OnJobComplete,
                     weak_factory_.GetWeakPtr(), params.hostname(),
                     start_time));
}

// static
void MultiThreadedCertVerifier::InternalRequest::OnJobComplete(
    base::WeakPtr<InternalRequest> self,
    const std::string hostname,
    base::TimeTicks start_time,
    std::unique_ptr<ResultHelper> verify_result) {
  // Always log the EndEvent, even if the Request has been destroyed.
  verify_result->net_log.EndEvent(NetLogEventType::CERT_VERIFIER_TASK);

  base::TimeDelta verify_time = base::TimeTicks::Now() - start_time;
  UMA_HISTOGRAM_CUSTOM_TIMES("Net.MultiThreadedCertVerifier.RequestDuration",
                             verify_time, base::Milliseconds(1),
                             base::Minutes(10), 100);
  if (IsGoogleHost(hostname)) {
    if (IsGoogleHostWithAlpnH3(hostname)) {
      UMA_HISTOGRAM_CUSTOM_TIMES(
          "Net.MultiThreadedCertVerifier.RequestDuration.GoogleWithAlpnH3",
          verify_time, base::Milliseconds(1), base::Minutes(10), 100);
    }
    UMA_HISTOGRAM_CUSTOM_TIMES(
        "Net.MultiThreadedCertVerifier.RequestDuration.Google", verify_time,
        base::Milliseconds(1), base::Minutes(10), 100);
  }

  // Check |self| weakptr and don't continue if the Request was destroyed.
  if (!self)
    return;

  DCHECK(verify_result);

  // If the MultiThreadedCertVerifier has been deleted, the callback will have
  // been reset to null.
  if (!self->callback_)
    return;

  // If ~MultiThreadedCertVerifier has not Reset() our callback, then this
  // InternalRequest will not have been removed from MultiThreadedCertVerifier's
  // list yet.
  self->RemoveFromList();

  *self->caller_result_ = verify_result->result;
  // Note: May delete |self|.
  std::move(self->callback_).Run(verify_result->error);
}

MultiThreadedCertVerifier::MultiThreadedCertVerifier(
    scoped_refptr<CertVerifyProc> verify_proc,
    scoped_refptr<CertVerifyProcFactory> verify_proc_factory)
    : verify_proc_(std::move(verify_proc)),
      verify_proc_factory_(std::move(verify_proc_factory)) {
  CHECK(verify_proc_);
  CHECK(verify_proc_factory_);
}

MultiThreadedCertVerifier::~MultiThreadedCertVerifier() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  // Reset the callbacks for each InternalRequest to fulfill the respective
  // net::CertVerifier contract.
  for (base::LinkNode<InternalRequest>* node = request_list_.head();
       node != request_list_.end();) {
    // Resetting the callback may delete the request, so save a pointer to the
    // next node first.
    base::LinkNode<InternalRequest>* next_node = node->next();
    node->value()->ResetCallback();
    node = next_node;
  }
}

int MultiThreadedCertVerifier::Verify(const RequestParams& params,
                                      CertVerifyResult* verify_result,
                                      CompletionOnceCallback callback,
                                      std::unique_ptr<Request>* out_req,
                                      const NetLogWithSource& net_log) {
  CHECK(params.certificate());
  out_req->reset();

  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  if (callback.is_null() || !verify_result || params.hostname().empty())
    return ERR_INVALID_ARGUMENT;

  std::unique_ptr<InternalRequest> request =
      std::make_unique<InternalRequest>(std::move(callback), verify_result);
  request->Start(verify_proc_, config_, params, net_log);
  request_list_.Append(request.get());
  *out_req = std::move(request);
  return ERR_IO_PENDING;
}

void MultiThreadedCertVerifier::Verify2QwacBinding(
    const std::string& binding,
    const std::string& hostname,
    const scoped_refptr<X509Certificate>& tls_cert,
    base::OnceCallback<void(const scoped_refptr<X509Certificate>&)> callback,
    const NetLogWithSource& net_log) {
  CHECK(!callback.is_null());

  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE,
      {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(&DoVerify2QwacBindingOnWorkerThread, verify_proc_, binding,
                     hostname, tls_cert, net_log),
      std::move(callback));
}

void MultiThreadedCertVerifier::UpdateVerifyProcData(
    scoped_refptr<CertNetFetcher> cert_net_fetcher,
    const net::CertVerifyProc::ImplParams& impl_params,
    const net::CertVerifyProc::InstanceParams& instance_params) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  verify_proc_ = verify_proc_factory_->CreateCertVerifyProc(
      std::move(cert_net_fetcher), impl_params, instance_params);
  CHECK(verify_proc_);
  NotifyCertVerifierChanged();
}

void MultiThreadedCertVerifier::SetConfig(const CertVerifier::Config& config) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  config_ = config;
}

void MultiThreadedCertVerifier::AddObserver(Observer* observer) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  observers_.AddObserver(observer);
}

void MultiThreadedCertVerifier::RemoveObserver(Observer* observer) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  observers_.RemoveObserver(observer);
}

void MultiThreadedCertVerifier::NotifyCertVerifierChanged() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  for (Observer& observer : observers_) {
    observer.OnCertVerifierChanged();
  }
}

}  // namespace net