xref: /aosp_15_r20/external/cronet/net/socket/ssl_client_socket_impl.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2012 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/socket/ssl_client_socket_impl.h"
6 
7 #include <errno.h>
8 #include <string.h>
9 
10 #include <algorithm>
11 #include <cstring>
12 #include <map>
13 #include <memory>
14 #include <string_view>
15 #include <utility>
16 
17 #include "base/containers/span.h"
18 #include "base/feature_list.h"
19 #include "base/functional/bind.h"
20 #include "base/functional/callback_helpers.h"
21 #include "base/lazy_instance.h"
22 #include "base/location.h"
23 #include "base/memory/singleton.h"
24 #include "base/metrics/field_trial.h"
25 #include "base/metrics/histogram_functions.h"
26 #include "base/metrics/histogram_macros.h"
27 #include "base/notreached.h"
28 #include "base/rand_util.h"
29 #include "base/synchronization/lock.h"
30 #include "base/task/sequenced_task_runner.h"
31 #include "base/values.h"
32 #include "build/build_config.h"
33 #include "components/miracle_parameter/common/public/miracle_parameter.h"
34 #include "crypto/ec_private_key.h"
35 #include "crypto/openssl_util.h"
36 #include "net/base/features.h"
37 #include "net/base/ip_address.h"
38 #include "net/base/ip_endpoint.h"
39 #include "net/base/net_errors.h"
40 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
41 #include "net/base/trace_constants.h"
42 #include "net/base/tracing.h"
43 #include "net/base/url_util.h"
44 #include "net/cert/cert_verifier.h"
45 #include "net/cert/ct_verifier.h"
46 #include "net/cert/sct_auditing_delegate.h"
47 #include "net/cert/sct_status_flags.h"
48 #include "net/cert/x509_certificate_net_log_param.h"
49 #include "net/cert/x509_util.h"
50 #include "net/http/transport_security_state.h"
51 #include "net/log/net_log_event_type.h"
52 #include "net/log/net_log_values.h"
53 #include "net/ssl/cert_compression.h"
54 #include "net/ssl/ssl_cert_request_info.h"
55 #include "net/ssl/ssl_cipher_suite_names.h"
56 #include "net/ssl/ssl_connection_status_flags.h"
57 #include "net/ssl/ssl_handshake_details.h"
58 #include "net/ssl/ssl_info.h"
59 #include "net/ssl/ssl_key_logger.h"
60 #include "net/ssl/ssl_private_key.h"
61 #include "net/traffic_annotation/network_traffic_annotation.h"
62 #include "third_party/boringssl/src/include/openssl/bio.h"
63 #include "third_party/boringssl/src/include/openssl/bytestring.h"
64 #include "third_party/boringssl/src/include/openssl/err.h"
65 #include "third_party/boringssl/src/include/openssl/evp.h"
66 #include "third_party/boringssl/src/include/openssl/mem.h"
67 #include "third_party/boringssl/src/include/openssl/ssl.h"
68 
69 namespace net {
70 
71 namespace {
72 
73 // This constant can be any non-negative/non-zero value (eg: it does not
74 // overlap with any value of the net::Error range, including net::OK).
75 const int kSSLClientSocketNoPendingResult = 1;
76 // This constant can be any non-negative/non-zero value (eg: it does not
77 // overlap with any value of the net::Error range, including net::OK).
78 const int kCertVerifyPending = 1;
79 
80 BASE_FEATURE(kDefaultOpenSSLBufferSizeFeature,
81              "DefaultOpenSSLBufferSizeFeature",
82              base::FEATURE_ENABLED_BY_DEFAULT);
83 
84 // Default size of the internal BoringSSL buffers.
85 MIRACLE_PARAMETER_FOR_INT(GetDefaultOpenSSLBufferSize,
86                           kDefaultOpenSSLBufferSizeFeature,
87                           "DefaultOpenSSLBufferSize",
88                           17 * 1024)
89 
NetLogPrivateKeyOperationParams(uint16_t algorithm,SSLPrivateKey * key)90 base::Value::Dict NetLogPrivateKeyOperationParams(uint16_t algorithm,
91                                                   SSLPrivateKey* key) {
92   return base::Value::Dict()
93       .Set("algorithm",
94            SSL_get_signature_algorithm_name(algorithm, 0 /* exclude curve */))
95       .Set("provider", key->GetProviderName());
96 }
97 
NetLogSSLInfoParams(SSLClientSocketImpl * socket)98 base::Value::Dict NetLogSSLInfoParams(SSLClientSocketImpl* socket) {
99   SSLInfo ssl_info;
100   if (!socket->GetSSLInfo(&ssl_info)) {
101     return base::Value::Dict();
102   }
103 
104   const char* version_str;
105   SSLVersionToString(&version_str,
106                      SSLConnectionStatusToVersion(ssl_info.connection_status));
107   return base::Value::Dict()
108       .Set("version", version_str)
109       .Set("is_resumed", ssl_info.handshake_type == SSLInfo::HANDSHAKE_RESUME)
110       .Set("cipher_suite",
111            SSLConnectionStatusToCipherSuite(ssl_info.connection_status))
112       .Set("key_exchange_group", ssl_info.key_exchange_group)
113       .Set("peer_signature_algorithm", ssl_info.peer_signature_algorithm)
114       .Set("encrypted_client_hello", ssl_info.encrypted_client_hello)
115       .Set("next_proto", NextProtoToString(socket->GetNegotiatedProtocol()));
116 }
117 
NetLogSSLAlertParams(const void * bytes,size_t len)118 base::Value::Dict NetLogSSLAlertParams(const void* bytes, size_t len) {
119   return base::Value::Dict().Set("bytes", NetLogBinaryValue(bytes, len));
120 }
121 
NetLogSSLMessageParams(bool is_write,const void * bytes,size_t len,NetLogCaptureMode capture_mode)122 base::Value::Dict NetLogSSLMessageParams(bool is_write,
123                                          const void* bytes,
124                                          size_t len,
125                                          NetLogCaptureMode capture_mode) {
126   if (len == 0) {
127     NOTREACHED();
128     return base::Value::Dict();
129   }
130 
131   base::Value::Dict dict;
132   // The handshake message type is the first byte. Include it so elided messages
133   // still report their type.
134   uint8_t type = reinterpret_cast<const uint8_t*>(bytes)[0];
135   dict.Set("type", type);
136 
137   // Elide client certificate messages unless logging socket bytes. The client
138   // certificate does not contain information needed to impersonate the user
139   // (that's the private key which isn't sent over the wire), but it may contain
140   // information on the user's identity.
141   if (!is_write || type != SSL3_MT_CERTIFICATE ||
142       NetLogCaptureIncludesSocketBytes(capture_mode)) {
143     dict.Set("bytes", NetLogBinaryValue(bytes, len));
144   }
145 
146   return dict;
147 }
148 
HostIsIPAddressNoBrackets(std::string_view host)149 bool HostIsIPAddressNoBrackets(std::string_view host) {
150   // Note this cannot directly call url::HostIsIPAddress, because that function
151   // expects bracketed IPv6 literals. By the time hosts reach SSLClientSocket,
152   // brackets have been removed.
153   IPAddress unused;
154   return unused.AssignFromIPLiteral(host);
155 }
156 
157 }  // namespace
158 
159 class SSLClientSocketImpl::SSLContext {
160  public:
GetInstance()161   static SSLContext* GetInstance() {
162     return base::Singleton<SSLContext,
163                            base::LeakySingletonTraits<SSLContext>>::get();
164   }
ssl_ctx()165   SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
166 
GetClientSocketFromSSL(const SSL * ssl)167   SSLClientSocketImpl* GetClientSocketFromSSL(const SSL* ssl) {
168     DCHECK(ssl);
169     SSLClientSocketImpl* socket = static_cast<SSLClientSocketImpl*>(
170         SSL_get_ex_data(ssl, ssl_socket_data_index_));
171     DCHECK(socket);
172     return socket;
173   }
174 
SetClientSocketForSSL(SSL * ssl,SSLClientSocketImpl * socket)175   bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketImpl* socket) {
176     return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
177   }
178 
SetSSLKeyLogger(std::unique_ptr<SSLKeyLogger> logger)179   void SetSSLKeyLogger(std::unique_ptr<SSLKeyLogger> logger) {
180     net::SSLKeyLoggerManager::SetSSLKeyLogger(std::move(logger));
181     SSL_CTX_set_keylog_callback(ssl_ctx_.get(),
182                                 SSLKeyLoggerManager::KeyLogCallback);
183   }
184 
185   static const SSL_PRIVATE_KEY_METHOD kPrivateKeyMethod;
186 
187  private:
188   friend struct base::DefaultSingletonTraits<SSLContext>;
189 
SSLContext()190   SSLContext() {
191     crypto::EnsureOpenSSLInit();
192     ssl_socket_data_index_ =
193         SSL_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
194     DCHECK_NE(ssl_socket_data_index_, -1);
195     ssl_ctx_.reset(SSL_CTX_new(TLS_with_buffers_method()));
196     SSL_CTX_set_cert_cb(ssl_ctx_.get(), ClientCertRequestCallback, nullptr);
197 
198     // Verifies the server certificate even on resumed sessions.
199     SSL_CTX_set_reverify_on_resume(ssl_ctx_.get(), 1);
200     SSL_CTX_set_custom_verify(ssl_ctx_.get(), SSL_VERIFY_PEER,
201                               VerifyCertCallback);
202     // Disable the internal session cache. Session caching is handled
203     // externally (i.e. by SSLClientSessionCache).
204     SSL_CTX_set_session_cache_mode(
205         ssl_ctx_.get(), SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL);
206     SSL_CTX_sess_set_new_cb(ssl_ctx_.get(), NewSessionCallback);
207     SSL_CTX_set_timeout(ssl_ctx_.get(), 1 * 60 * 60 /* one hour */);
208 
209     SSL_CTX_set_grease_enabled(ssl_ctx_.get(), 1);
210 
211     // Deduplicate all certificates minted from the SSL_CTX in memory.
212     SSL_CTX_set0_buffer_pool(ssl_ctx_.get(), x509_util::GetBufferPool());
213 
214     SSL_CTX_set_msg_callback(ssl_ctx_.get(), MessageCallback);
215 
216     ConfigureCertificateCompression(ssl_ctx_.get());
217   }
218 
ClientCertRequestCallback(SSL * ssl,void * arg)219   static int ClientCertRequestCallback(SSL* ssl, void* arg) {
220     SSLClientSocketImpl* socket = GetInstance()->GetClientSocketFromSSL(ssl);
221     DCHECK(socket);
222     return socket->ClientCertRequestCallback(ssl);
223   }
224 
NewSessionCallback(SSL * ssl,SSL_SESSION * session)225   static int NewSessionCallback(SSL* ssl, SSL_SESSION* session) {
226     SSLClientSocketImpl* socket = GetInstance()->GetClientSocketFromSSL(ssl);
227     return socket->NewSessionCallback(session);
228   }
229 
PrivateKeySignCallback(SSL * ssl,uint8_t * out,size_t * out_len,size_t max_out,uint16_t algorithm,const uint8_t * in,size_t in_len)230   static ssl_private_key_result_t PrivateKeySignCallback(SSL* ssl,
231                                                          uint8_t* out,
232                                                          size_t* out_len,
233                                                          size_t max_out,
234                                                          uint16_t algorithm,
235                                                          const uint8_t* in,
236                                                          size_t in_len) {
237     SSLClientSocketImpl* socket = GetInstance()->GetClientSocketFromSSL(ssl);
238     return socket->PrivateKeySignCallback(out, out_len, max_out, algorithm, in,
239                                           in_len);
240   }
241 
PrivateKeyCompleteCallback(SSL * ssl,uint8_t * out,size_t * out_len,size_t max_out)242   static ssl_private_key_result_t PrivateKeyCompleteCallback(SSL* ssl,
243                                                              uint8_t* out,
244                                                              size_t* out_len,
245                                                              size_t max_out) {
246     SSLClientSocketImpl* socket = GetInstance()->GetClientSocketFromSSL(ssl);
247     return socket->PrivateKeyCompleteCallback(out, out_len, max_out);
248   }
249 
MessageCallback(int is_write,int version,int content_type,const void * buf,size_t len,SSL * ssl,void * arg)250   static void MessageCallback(int is_write,
251                               int version,
252                               int content_type,
253                               const void* buf,
254                               size_t len,
255                               SSL* ssl,
256                               void* arg) {
257     SSLClientSocketImpl* socket = GetInstance()->GetClientSocketFromSSL(ssl);
258     return socket->MessageCallback(is_write, content_type, buf, len);
259   }
260 
261   // This is the index used with SSL_get_ex_data to retrieve the owner
262   // SSLClientSocketImpl object from an SSL instance.
263   int ssl_socket_data_index_;
264 
265   bssl::UniquePtr<SSL_CTX> ssl_ctx_;
266 };
267 
268 const SSL_PRIVATE_KEY_METHOD
269     SSLClientSocketImpl::SSLContext::kPrivateKeyMethod = {
270         &SSLClientSocketImpl::SSLContext::PrivateKeySignCallback,
271         nullptr /* decrypt */,
272         &SSLClientSocketImpl::SSLContext::PrivateKeyCompleteCallback,
273 };
274 
SSLClientSocketImpl(SSLClientContext * context,std::unique_ptr<StreamSocket> stream_socket,const HostPortPair & host_and_port,const SSLConfig & ssl_config)275 SSLClientSocketImpl::SSLClientSocketImpl(
276     SSLClientContext* context,
277     std::unique_ptr<StreamSocket> stream_socket,
278     const HostPortPair& host_and_port,
279     const SSLConfig& ssl_config)
280     : pending_read_error_(kSSLClientSocketNoPendingResult),
281       context_(context),
282       cert_verification_result_(kCertVerifyPending),
283       stream_socket_(std::move(stream_socket)),
284       host_and_port_(host_and_port),
285       ssl_config_(ssl_config),
286       signature_result_(kSSLClientSocketNoPendingResult),
287       net_log_(stream_socket_->NetLog()) {
288   CHECK(context_);
289 }
290 
~SSLClientSocketImpl()291 SSLClientSocketImpl::~SSLClientSocketImpl() {
292   Disconnect();
293 }
294 
SetSSLKeyLogger(std::unique_ptr<SSLKeyLogger> logger)295 void SSLClientSocketImpl::SetSSLKeyLogger(
296     std::unique_ptr<SSLKeyLogger> logger) {
297   SSLContext::GetInstance()->SetSSLKeyLogger(std::move(logger));
298 }
299 
GetECHRetryConfigs()300 std::vector<uint8_t> SSLClientSocketImpl::GetECHRetryConfigs() {
301   const uint8_t* retry_configs;
302   size_t retry_configs_len;
303   SSL_get0_ech_retry_configs(ssl_.get(), &retry_configs, &retry_configs_len);
304   return std::vector<uint8_t>(retry_configs, retry_configs + retry_configs_len);
305 }
306 
ExportKeyingMaterial(std::string_view label,bool has_context,std::string_view context,unsigned char * out,unsigned int outlen)307 int SSLClientSocketImpl::ExportKeyingMaterial(std::string_view label,
308                                               bool has_context,
309                                               std::string_view context,
310                                               unsigned char* out,
311                                               unsigned int outlen) {
312   if (!IsConnected())
313     return ERR_SOCKET_NOT_CONNECTED;
314 
315   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
316 
317   if (!SSL_export_keying_material(
318           ssl_.get(), out, outlen, label.data(), label.size(),
319           reinterpret_cast<const unsigned char*>(context.data()),
320           context.length(), has_context ? 1 : 0)) {
321     LOG(ERROR) << "Failed to export keying material.";
322     return ERR_FAILED;
323   }
324 
325   return OK;
326 }
327 
Connect(CompletionOnceCallback callback)328 int SSLClientSocketImpl::Connect(CompletionOnceCallback callback) {
329   // Although StreamSocket does allow calling Connect() after Disconnect(),
330   // this has never worked for layered sockets. CHECK to detect any consumers
331   // reconnecting an SSL socket.
332   //
333   // TODO(davidben,mmenke): Remove this API feature. See
334   // https://crbug.com/499289.
335   CHECK(!disconnected_);
336 
337   net_log_.BeginEvent(NetLogEventType::SSL_CONNECT);
338 
339   // Set up new ssl object.
340   int rv = Init();
341   if (rv != OK) {
342     LogConnectEndEvent(rv);
343     return rv;
344   }
345 
346   // Set SSL to client mode. Handshake happens in the loop below.
347   SSL_set_connect_state(ssl_.get());
348 
349   next_handshake_state_ = STATE_HANDSHAKE;
350   rv = DoHandshakeLoop(OK);
351   if (rv == ERR_IO_PENDING) {
352     user_connect_callback_ = std::move(callback);
353   } else {
354     LogConnectEndEvent(rv);
355   }
356 
357   return rv > OK ? OK : rv;
358 }
359 
Disconnect()360 void SSLClientSocketImpl::Disconnect() {
361   disconnected_ = true;
362 
363   // Shut down anything that may call us back.
364   cert_verifier_request_.reset();
365   weak_factory_.InvalidateWeakPtrs();
366   transport_adapter_.reset();
367 
368   // Release user callbacks.
369   user_connect_callback_.Reset();
370   user_read_callback_.Reset();
371   user_write_callback_.Reset();
372   user_read_buf_ = nullptr;
373   user_read_buf_len_ = 0;
374   user_write_buf_ = nullptr;
375   user_write_buf_len_ = 0;
376 
377   stream_socket_->Disconnect();
378 }
379 
380 // ConfirmHandshake may only be called on a connected socket and, like other
381 // socket methods, there may only be one ConfirmHandshake operation in progress
382 // at once.
ConfirmHandshake(CompletionOnceCallback callback)383 int SSLClientSocketImpl::ConfirmHandshake(CompletionOnceCallback callback) {
384   CHECK(completed_connect_);
385   CHECK(!in_confirm_handshake_);
386   if (!SSL_in_early_data(ssl_.get())) {
387     return OK;
388   }
389 
390   net_log_.BeginEvent(NetLogEventType::SSL_CONFIRM_HANDSHAKE);
391   next_handshake_state_ = STATE_HANDSHAKE;
392   in_confirm_handshake_ = true;
393   int rv = DoHandshakeLoop(OK);
394   if (rv == ERR_IO_PENDING) {
395     user_connect_callback_ = std::move(callback);
396   } else {
397     net_log_.EndEvent(NetLogEventType::SSL_CONFIRM_HANDSHAKE);
398     in_confirm_handshake_ = false;
399   }
400 
401   return rv > OK ? OK : rv;
402 }
403 
IsConnected() const404 bool SSLClientSocketImpl::IsConnected() const {
405   // If the handshake has not yet completed or the socket has been explicitly
406   // disconnected.
407   if (!completed_connect_ || disconnected_)
408     return false;
409   // If an asynchronous operation is still pending.
410   if (user_read_buf_.get() || user_write_buf_.get())
411     return true;
412 
413   return stream_socket_->IsConnected();
414 }
415 
IsConnectedAndIdle() const416 bool SSLClientSocketImpl::IsConnectedAndIdle() const {
417   // If the handshake has not yet completed or the socket has been explicitly
418   // disconnected.
419   if (!completed_connect_ || disconnected_)
420     return false;
421   // If an asynchronous operation is still pending.
422   if (user_read_buf_.get() || user_write_buf_.get())
423     return false;
424 
425   // If there is data read from the network that has not yet been consumed, do
426   // not treat the connection as idle.
427   //
428   // Note that this does not check whether there is ciphertext that has not yet
429   // been flushed to the network. |Write| returns early, so this can cause race
430   // conditions which cause a socket to not be treated reusable when it should
431   // be. See https://crbug.com/466147.
432   if (transport_adapter_->HasPendingReadData())
433     return false;
434 
435   return stream_socket_->IsConnectedAndIdle();
436 }
437 
GetPeerAddress(IPEndPoint * addressList) const438 int SSLClientSocketImpl::GetPeerAddress(IPEndPoint* addressList) const {
439   return stream_socket_->GetPeerAddress(addressList);
440 }
441 
GetLocalAddress(IPEndPoint * addressList) const442 int SSLClientSocketImpl::GetLocalAddress(IPEndPoint* addressList) const {
443   return stream_socket_->GetLocalAddress(addressList);
444 }
445 
NetLog() const446 const NetLogWithSource& SSLClientSocketImpl::NetLog() const {
447   return net_log_;
448 }
449 
WasEverUsed() const450 bool SSLClientSocketImpl::WasEverUsed() const {
451   return was_ever_used_;
452 }
453 
GetNegotiatedProtocol() const454 NextProto SSLClientSocketImpl::GetNegotiatedProtocol() const {
455   return negotiated_protocol_;
456 }
457 
458 std::optional<std::string_view>
GetPeerApplicationSettings() const459 SSLClientSocketImpl::GetPeerApplicationSettings() const {
460   if (!SSL_has_application_settings(ssl_.get())) {
461     return std::nullopt;
462   }
463 
464   const uint8_t* out_data;
465   size_t out_len;
466   SSL_get0_peer_application_settings(ssl_.get(), &out_data, &out_len);
467   return std::string_view{reinterpret_cast<const char*>(out_data), out_len};
468 }
469 
GetSSLInfo(SSLInfo * ssl_info)470 bool SSLClientSocketImpl::GetSSLInfo(SSLInfo* ssl_info) {
471   ssl_info->Reset();
472   if (!server_cert_)
473     return false;
474 
475   ssl_info->cert = server_cert_verify_result_.verified_cert;
476   ssl_info->unverified_cert = server_cert_;
477   ssl_info->cert_status = server_cert_verify_result_.cert_status;
478   ssl_info->is_issued_by_known_root =
479       server_cert_verify_result_.is_issued_by_known_root;
480   ssl_info->pkp_bypassed = pkp_bypassed_;
481   ssl_info->public_key_hashes = server_cert_verify_result_.public_key_hashes;
482   ssl_info->client_cert_sent = send_client_cert_ && client_cert_.get();
483   ssl_info->encrypted_client_hello = SSL_ech_accepted(ssl_.get());
484   ssl_info->ocsp_result = server_cert_verify_result_.ocsp_result;
485   ssl_info->is_fatal_cert_error = is_fatal_cert_error_;
486   ssl_info->signed_certificate_timestamps = server_cert_verify_result_.scts;
487   ssl_info->ct_policy_compliance = server_cert_verify_result_.policy_compliance;
488 
489   const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_.get());
490   CHECK(cipher);
491   // Historically, the "group" was known as "curve".
492   ssl_info->key_exchange_group = SSL_get_curve_id(ssl_.get());
493   ssl_info->peer_signature_algorithm =
494       SSL_get_peer_signature_algorithm(ssl_.get());
495 
496   SSLConnectionStatusSetCipherSuite(SSL_CIPHER_get_protocol_id(cipher),
497                                     &ssl_info->connection_status);
498   SSLConnectionStatusSetVersion(GetNetSSLVersion(ssl_.get()),
499                                 &ssl_info->connection_status);
500 
501   ssl_info->handshake_type = SSL_session_reused(ssl_.get())
502                                  ? SSLInfo::HANDSHAKE_RESUME
503                                  : SSLInfo::HANDSHAKE_FULL;
504 
505   return true;
506 }
507 
GetTotalReceivedBytes() const508 int64_t SSLClientSocketImpl::GetTotalReceivedBytes() const {
509   return stream_socket_->GetTotalReceivedBytes();
510 }
511 
GetSSLCertRequestInfo(SSLCertRequestInfo * cert_request_info) const512 void SSLClientSocketImpl::GetSSLCertRequestInfo(
513     SSLCertRequestInfo* cert_request_info) const {
514   if (!ssl_) {
515     NOTREACHED();
516     return;
517   }
518 
519   cert_request_info->host_and_port = host_and_port_;
520 
521   cert_request_info->cert_authorities.clear();
522   const STACK_OF(CRYPTO_BUFFER)* authorities =
523       SSL_get0_server_requested_CAs(ssl_.get());
524   for (const CRYPTO_BUFFER* ca_name : authorities) {
525     cert_request_info->cert_authorities.emplace_back(
526         reinterpret_cast<const char*>(CRYPTO_BUFFER_data(ca_name)),
527         CRYPTO_BUFFER_len(ca_name));
528   }
529 
530   const uint16_t* algorithms;
531   size_t num_algorithms =
532       SSL_get0_peer_verify_algorithms(ssl_.get(), &algorithms);
533   cert_request_info->signature_algorithms.assign(algorithms,
534                                                  algorithms + num_algorithms);
535 }
536 
ApplySocketTag(const SocketTag & tag)537 void SSLClientSocketImpl::ApplySocketTag(const SocketTag& tag) {
538   return stream_socket_->ApplySocketTag(tag);
539 }
540 
Read(IOBuffer * buf,int buf_len,CompletionOnceCallback callback)541 int SSLClientSocketImpl::Read(IOBuffer* buf,
542                               int buf_len,
543                               CompletionOnceCallback callback) {
544   int rv = ReadIfReady(buf, buf_len, std::move(callback));
545   if (rv == ERR_IO_PENDING) {
546     user_read_buf_ = buf;
547     user_read_buf_len_ = buf_len;
548   }
549   return rv;
550 }
551 
ReadIfReady(IOBuffer * buf,int buf_len,CompletionOnceCallback callback)552 int SSLClientSocketImpl::ReadIfReady(IOBuffer* buf,
553                                      int buf_len,
554                                      CompletionOnceCallback callback) {
555   int rv = DoPayloadRead(buf, buf_len);
556 
557   if (rv == ERR_IO_PENDING) {
558     user_read_callback_ = std::move(callback);
559   } else {
560     if (rv > 0)
561       was_ever_used_ = true;
562   }
563   return rv;
564 }
565 
CancelReadIfReady()566 int SSLClientSocketImpl::CancelReadIfReady() {
567   DCHECK(user_read_callback_);
568   DCHECK(!user_read_buf_);
569 
570   // Cancel |user_read_callback_|, because caller does not expect the callback
571   // to be invoked after they have canceled the ReadIfReady.
572   //
573   // We do not pass the signal on to |stream_socket_| or |transport_adapter_|.
574   // Multiple operations may be waiting on a transport ReadIfReady().
575   // Conversely, an SSL ReadIfReady() may be blocked on something other than a
576   // transport ReadIfReady(). Instead, the underlying transport ReadIfReady()
577   // will continue running (with no underlying buffer). When it completes, it
578   // will signal OnReadReady(), which will notice there is no read operation to
579   // progress and skip it.
580   user_read_callback_.Reset();
581   return OK;
582 }
583 
Write(IOBuffer * buf,int buf_len,CompletionOnceCallback callback,const NetworkTrafficAnnotationTag & traffic_annotation)584 int SSLClientSocketImpl::Write(
585     IOBuffer* buf,
586     int buf_len,
587     CompletionOnceCallback callback,
588     const NetworkTrafficAnnotationTag& traffic_annotation) {
589   user_write_buf_ = buf;
590   user_write_buf_len_ = buf_len;
591 
592   int rv = DoPayloadWrite();
593 
594   if (rv == ERR_IO_PENDING) {
595     user_write_callback_ = std::move(callback);
596   } else {
597     if (rv > 0) {
598       CHECK_LE(rv, buf_len);
599       was_ever_used_ = true;
600     }
601     user_write_buf_ = nullptr;
602     user_write_buf_len_ = 0;
603   }
604 
605   return rv;
606 }
607 
SetReceiveBufferSize(int32_t size)608 int SSLClientSocketImpl::SetReceiveBufferSize(int32_t size) {
609   return stream_socket_->SetReceiveBufferSize(size);
610 }
611 
SetSendBufferSize(int32_t size)612 int SSLClientSocketImpl::SetSendBufferSize(int32_t size) {
613   return stream_socket_->SetSendBufferSize(size);
614 }
615 
OnReadReady()616 void SSLClientSocketImpl::OnReadReady() {
617   // During a renegotiation, either Read or Write calls may be blocked on a
618   // transport read.
619   RetryAllOperations();
620 }
621 
OnWriteReady()622 void SSLClientSocketImpl::OnWriteReady() {
623   // During a renegotiation, either Read or Write calls may be blocked on a
624   // transport read.
625   RetryAllOperations();
626 }
627 
Init()628 int SSLClientSocketImpl::Init() {
629   DCHECK(!ssl_);
630 
631   SSLContext* context = SSLContext::GetInstance();
632   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
633 
634   ssl_.reset(SSL_new(context->ssl_ctx()));
635   if (!ssl_ || !context->SetClientSocketForSSL(ssl_.get(), this))
636     return ERR_UNEXPECTED;
637 
638   const bool host_is_ip_address =
639       HostIsIPAddressNoBrackets(host_and_port_.host());
640 
641   // SNI should only contain valid DNS hostnames, not IP addresses (see RFC
642   // 6066, Section 3).
643   //
644   // TODO(rsleevi): Should this code allow hostnames that violate the LDH rule?
645   // See https://crbug.com/496472 and https://crbug.com/496468 for discussion.
646   if (!host_is_ip_address &&
647       !SSL_set_tlsext_host_name(ssl_.get(), host_and_port_.host().c_str())) {
648     return ERR_UNEXPECTED;
649   }
650 
651   if (context_->config().PostQuantumKeyAgreementEnabled()) {
652     static const int kCurves[] = {NID_X25519Kyber768Draft00, NID_X25519,
653                                   NID_X9_62_prime256v1, NID_secp384r1};
654     if (!SSL_set1_curves(ssl_.get(), kCurves, std::size(kCurves))) {
655       return ERR_UNEXPECTED;
656     }
657   }
658 
659   if (IsCachingEnabled()) {
660     bssl::UniquePtr<SSL_SESSION> session =
661         context_->ssl_client_session_cache()->Lookup(
662             GetSessionCacheKey(/*dest_ip_addr=*/std::nullopt));
663     if (!session) {
664       // If a previous session negotiated an RSA cipher suite then it may have
665       // been inserted into the cache keyed by both hostname and resolved IP
666       // address. See https://crbug.com/969684.
667       IPEndPoint peer_address;
668       if (stream_socket_->GetPeerAddress(&peer_address) == OK) {
669         session = context_->ssl_client_session_cache()->Lookup(
670             GetSessionCacheKey(peer_address.address()));
671       }
672     }
673     if (session)
674       SSL_set_session(ssl_.get(), session.get());
675   }
676 
677   const int kBufferSize = GetDefaultOpenSSLBufferSize();
678   transport_adapter_ = std::make_unique<SocketBIOAdapter>(
679       stream_socket_.get(), kBufferSize, kBufferSize, this);
680   BIO* transport_bio = transport_adapter_->bio();
681 
682   BIO_up_ref(transport_bio);  // SSL_set0_rbio takes ownership.
683   SSL_set0_rbio(ssl_.get(), transport_bio);
684 
685   BIO_up_ref(transport_bio);  // SSL_set0_wbio takes ownership.
686   SSL_set0_wbio(ssl_.get(), transport_bio);
687 
688   uint16_t version_min =
689       ssl_config_.version_min_override.value_or(context_->config().version_min);
690   uint16_t version_max =
691       ssl_config_.version_max_override.value_or(context_->config().version_max);
692   if (version_min < TLS1_2_VERSION || version_max < TLS1_2_VERSION) {
693     // TLS versions before TLS 1.2 are no longer supported.
694     return ERR_UNEXPECTED;
695   }
696 
697   if (!SSL_set_min_proto_version(ssl_.get(), version_min) ||
698       !SSL_set_max_proto_version(ssl_.get(), version_max)) {
699     return ERR_UNEXPECTED;
700   }
701 
702   SSL_set_early_data_enabled(ssl_.get(), ssl_config_.early_data_enabled);
703 
704   // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
705   // set everything we care about to an absolute value.
706   SslSetClearMask options;
707   options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
708 
709   // TODO(joth): Set this conditionally, see http://crbug.com/55410
710   options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
711 
712   SSL_set_options(ssl_.get(), options.set_mask);
713   SSL_clear_options(ssl_.get(), options.clear_mask);
714 
715   // Same as above, this time for the SSL mode.
716   SslSetClearMask mode;
717 
718   mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
719   mode.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING, true);
720 
721   mode.ConfigureFlag(SSL_MODE_ENABLE_FALSE_START, true);
722 
723   SSL_set_mode(ssl_.get(), mode.set_mask);
724   SSL_clear_mode(ssl_.get(), mode.clear_mask);
725 
726   // Use BoringSSL defaults, but disable 3DES and HMAC-SHA1 ciphers in ECDSA.
727   // These are the remaining CBC-mode ECDSA ciphers.
728   std::string command("ALL:!aPSK:!ECDSA+SHA1:!3DES");
729 
730   if (ssl_config_.require_ecdhe)
731     command.append(":!kRSA");
732 
733   // Remove any disabled ciphers.
734   for (uint16_t id : context_->config().disabled_cipher_suites) {
735     const SSL_CIPHER* cipher = SSL_get_cipher_by_value(id);
736     if (cipher) {
737       command.append(":!");
738       command.append(SSL_CIPHER_get_name(cipher));
739     }
740   }
741 
742   if (!SSL_set_strict_cipher_list(ssl_.get(), command.c_str())) {
743     LOG(ERROR) << "SSL_set_cipher_list('" << command << "') failed";
744     return ERR_UNEXPECTED;
745   }
746 
747   // Disable SHA-1 server signatures.
748   // TODO(crbug.com/boringssl/699): Once the default is flipped in BoringSSL, we
749   // no longer need to override it.
750   static const uint16_t kVerifyPrefs[] = {
751       SSL_SIGN_ECDSA_SECP256R1_SHA256, SSL_SIGN_RSA_PSS_RSAE_SHA256,
752       SSL_SIGN_RSA_PKCS1_SHA256,       SSL_SIGN_ECDSA_SECP384R1_SHA384,
753       SSL_SIGN_RSA_PSS_RSAE_SHA384,    SSL_SIGN_RSA_PKCS1_SHA384,
754       SSL_SIGN_RSA_PSS_RSAE_SHA512,    SSL_SIGN_RSA_PKCS1_SHA512,
755   };
756   if (!SSL_set_verify_algorithm_prefs(ssl_.get(), kVerifyPrefs,
757                                       std::size(kVerifyPrefs))) {
758     return ERR_UNEXPECTED;
759   }
760 
761   SSL_set_alps_use_new_codepoint(
762       ssl_.get(),
763       base::FeatureList::IsEnabled(features::kUseNewAlpsCodepointHttp2));
764 
765   if (!ssl_config_.alpn_protos.empty()) {
766     std::vector<uint8_t> wire_protos =
767         SerializeNextProtos(ssl_config_.alpn_protos);
768     SSL_set_alpn_protos(ssl_.get(), wire_protos.data(), wire_protos.size());
769 
770     for (NextProto proto : ssl_config_.alpn_protos) {
771       auto iter = ssl_config_.application_settings.find(proto);
772       if (iter != ssl_config_.application_settings.end()) {
773         const char* proto_string = NextProtoToString(proto);
774         if (!SSL_add_application_settings(
775                 ssl_.get(), reinterpret_cast<const uint8_t*>(proto_string),
776                 strlen(proto_string), iter->second.data(),
777                 iter->second.size())) {
778           return ERR_UNEXPECTED;
779         }
780       }
781     }
782   }
783 
784   SSL_enable_signed_cert_timestamps(ssl_.get());
785   SSL_enable_ocsp_stapling(ssl_.get());
786 
787   // Configure BoringSSL to allow renegotiations. Once the initial handshake
788   // completes, if renegotiations are not allowed, the default reject value will
789   // be restored. This is done in this order to permit a BoringSSL
790   // optimization. See https://crbug.com/boringssl/123. Use
791   // ssl_renegotiate_explicit rather than ssl_renegotiate_freely so DoPeek()
792   // does not trigger renegotiations.
793   SSL_set_renegotiate_mode(ssl_.get(), ssl_renegotiate_explicit);
794 
795   SSL_set_shed_handshake_config(ssl_.get(), 1);
796 
797   // TODO(https://crbug.com/775438), if |ssl_config_.privacy_mode| is enabled,
798   // this should always continue with no client certificate.
799   if (ssl_config_.privacy_mode == PRIVACY_MODE_ENABLED_WITHOUT_CLIENT_CERTS) {
800     send_client_cert_ = true;
801   } else {
802     send_client_cert_ = context_->GetClientCertificate(
803         host_and_port_, &client_cert_, &client_private_key_);
804   }
805 
806   if (context_->config().ech_enabled) {
807     // TODO(https://crbug.com/1509597): Enable this unconditionally.
808     SSL_set_enable_ech_grease(ssl_.get(), 1);
809   }
810   if (!ssl_config_.ech_config_list.empty()) {
811     DCHECK(context_->config().ech_enabled);
812     net_log_.AddEvent(NetLogEventType::SSL_ECH_CONFIG_LIST, [&] {
813       return base::Value::Dict().Set(
814           "bytes", NetLogBinaryValue(ssl_config_.ech_config_list));
815     });
816     if (!SSL_set1_ech_config_list(ssl_.get(),
817                                   ssl_config_.ech_config_list.data(),
818                                   ssl_config_.ech_config_list.size())) {
819       return ERR_INVALID_ECH_CONFIG_LIST;
820     }
821   }
822 
823   SSL_set_permute_extensions(ssl_.get(), base::FeatureList::IsEnabled(
824                                              features::kPermuteTLSExtensions));
825 
826   return OK;
827 }
828 
DoReadCallback(int rv)829 void SSLClientSocketImpl::DoReadCallback(int rv) {
830   // Since Run may result in Read being called, clear |user_read_callback_|
831   // up front.
832   if (rv > 0)
833     was_ever_used_ = true;
834   user_read_buf_ = nullptr;
835   user_read_buf_len_ = 0;
836   std::move(user_read_callback_).Run(rv);
837 }
838 
DoWriteCallback(int rv)839 void SSLClientSocketImpl::DoWriteCallback(int rv) {
840   // Since Run may result in Write being called, clear |user_write_callback_|
841   // up front.
842   if (rv > 0)
843     was_ever_used_ = true;
844   user_write_buf_ = nullptr;
845   user_write_buf_len_ = 0;
846   std::move(user_write_callback_).Run(rv);
847 }
848 
DoHandshake()849 int SSLClientSocketImpl::DoHandshake() {
850   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
851 
852   int rv = SSL_do_handshake(ssl_.get());
853   int net_error = OK;
854   if (rv <= 0) {
855     int ssl_error = SSL_get_error(ssl_.get(), rv);
856     if (ssl_error == SSL_ERROR_WANT_X509_LOOKUP && !send_client_cert_) {
857       return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
858     }
859     if (ssl_error == SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
860       DCHECK(client_private_key_);
861       DCHECK_NE(kSSLClientSocketNoPendingResult, signature_result_);
862       next_handshake_state_ = STATE_HANDSHAKE;
863       return ERR_IO_PENDING;
864     }
865     if (ssl_error == SSL_ERROR_WANT_CERTIFICATE_VERIFY) {
866       DCHECK(cert_verifier_request_);
867       next_handshake_state_ = STATE_HANDSHAKE;
868       return ERR_IO_PENDING;
869     }
870 
871     OpenSSLErrorInfo error_info;
872     net_error = MapLastOpenSSLError(ssl_error, err_tracer, &error_info);
873     if (net_error == ERR_IO_PENDING) {
874       // If not done, stay in this state
875       next_handshake_state_ = STATE_HANDSHAKE;
876       return ERR_IO_PENDING;
877     }
878 
879     LOG(ERROR) << "handshake failed; returned " << rv << ", SSL error code "
880                << ssl_error << ", net_error " << net_error;
881     NetLogOpenSSLError(net_log_, NetLogEventType::SSL_HANDSHAKE_ERROR,
882                        net_error, ssl_error, error_info);
883   }
884 
885   next_handshake_state_ = STATE_HANDSHAKE_COMPLETE;
886   return net_error;
887 }
888 
DoHandshakeComplete(int result)889 int SSLClientSocketImpl::DoHandshakeComplete(int result) {
890   if (result < 0)
891     return result;
892 
893   if (in_confirm_handshake_) {
894     next_handshake_state_ = STATE_NONE;
895     return OK;
896   }
897 
898   // If ECH overrode certificate verification to authenticate a fallback, using
899   // the socket for application data would bypass server authentication.
900   // BoringSSL will never complete the handshake in this case, so this should
901   // not happen.
902   CHECK(!used_ech_name_override_);
903 
904   const uint8_t* alpn_proto = nullptr;
905   unsigned alpn_len = 0;
906   SSL_get0_alpn_selected(ssl_.get(), &alpn_proto, &alpn_len);
907   if (alpn_len > 0) {
908     std::string_view proto(reinterpret_cast<const char*>(alpn_proto), alpn_len);
909     negotiated_protocol_ = NextProtoFromString(proto);
910   }
911 
912   RecordNegotiatedProtocol();
913 
914   const uint8_t* ocsp_response_raw;
915   size_t ocsp_response_len;
916   SSL_get0_ocsp_response(ssl_.get(), &ocsp_response_raw, &ocsp_response_len);
917   set_stapled_ocsp_response_received(ocsp_response_len != 0);
918 
919   const uint8_t* sct_list;
920   size_t sct_list_len;
921   SSL_get0_signed_cert_timestamp_list(ssl_.get(), &sct_list, &sct_list_len);
922   set_signed_cert_timestamps_received(sct_list_len != 0);
923 
924   if (!IsRenegotiationAllowed())
925     SSL_set_renegotiate_mode(ssl_.get(), ssl_renegotiate_never);
926 
927   uint16_t signature_algorithm = SSL_get_peer_signature_algorithm(ssl_.get());
928   if (signature_algorithm != 0) {
929     base::UmaHistogramSparse("Net.SSLSignatureAlgorithm", signature_algorithm);
930   }
931 
932   SSLInfo ssl_info;
933   bool ok = GetSSLInfo(&ssl_info);
934   // Ensure the verify callback was called, and got far enough to fill
935   // in server_cert_.
936   CHECK(ok);
937 
938   SSLHandshakeDetails details;
939   if (SSL_version(ssl_.get()) < TLS1_3_VERSION) {
940     if (SSL_session_reused(ssl_.get())) {
941       details = SSLHandshakeDetails::kTLS12Resume;
942     } else if (SSL_in_false_start(ssl_.get())) {
943       details = SSLHandshakeDetails::kTLS12FalseStart;
944     } else {
945       details = SSLHandshakeDetails::kTLS12Full;
946     }
947   } else {
948     bool used_hello_retry_request = SSL_used_hello_retry_request(ssl_.get());
949     if (SSL_in_early_data(ssl_.get())) {
950       DCHECK(!used_hello_retry_request);
951       details = SSLHandshakeDetails::kTLS13Early;
952     } else if (SSL_session_reused(ssl_.get())) {
953       details = used_hello_retry_request
954                     ? SSLHandshakeDetails::kTLS13ResumeWithHelloRetryRequest
955                     : SSLHandshakeDetails::kTLS13Resume;
956     } else {
957       details = used_hello_retry_request
958                     ? SSLHandshakeDetails::kTLS13FullWithHelloRetryRequest
959                     : SSLHandshakeDetails::kTLS13Full;
960     }
961   }
962   UMA_HISTOGRAM_ENUMERATION("Net.SSLHandshakeDetails", details);
963 
964   // Measure TLS connections that implement the renegotiation_info extension.
965   // Note this records true for TLS 1.3. By removing renegotiation altogether,
966   // TLS 1.3 is implicitly patched against the bug. See
967   // https://crbug.com/850800.
968   base::UmaHistogramBoolean("Net.SSLRenegotiationInfoSupported",
969                             SSL_get_secure_renegotiation_support(ssl_.get()));
970 
971   completed_connect_ = true;
972   next_handshake_state_ = STATE_NONE;
973 
974   // Read from the transport immediately after the handshake, whether Read() is
975   // called immediately or not. This serves several purposes:
976   //
977   // First, if this socket is preconnected and negotiates 0-RTT, the ServerHello
978   // will not be processed. See https://crbug.com/950706
979   //
980   // Second, in False Start and TLS 1.3, the tickets arrive after immediately
981   // after the handshake. This allows preconnected sockets to process the
982   // tickets sooner. This also avoids a theoretical deadlock if the tickets are
983   // too large. See
984   // https://boringssl-review.googlesource.com/c/boringssl/+/34948.
985   //
986   // TODO(https://crbug.com/958638): It is also a step in making TLS 1.3 client
987   // certificate alerts less unreliable.
988   base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
989       FROM_HERE,
990       base::BindOnce(&SSLClientSocketImpl::DoPeek, weak_factory_.GetWeakPtr()));
991 
992   return OK;
993 }
994 
VerifyCertCallback(SSL * ssl,uint8_t * out_alert)995 ssl_verify_result_t SSLClientSocketImpl::VerifyCertCallback(
996     SSL* ssl,
997     uint8_t* out_alert) {
998   SSLClientSocketImpl* socket =
999       SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
1000   DCHECK(socket);
1001   return socket->VerifyCert();
1002 }
1003 
1004 // This function is called by BoringSSL, so it has to return an
1005 // ssl_verify_result_t. When specific //net errors need to be
1006 // returned, use OpenSSLPutNetError to add them directly to the
1007 // OpenSSL error queue.
VerifyCert()1008 ssl_verify_result_t SSLClientSocketImpl::VerifyCert() {
1009   if (cert_verification_result_ != kCertVerifyPending) {
1010     // The certificate verifier updates cert_verification_result_ when
1011     // it returns asynchronously. If there is a result in
1012     // cert_verification_result_, return it instead of triggering
1013     // another verify.
1014     return HandleVerifyResult();
1015   }
1016 
1017   // In this configuration, BoringSSL will perform exactly one certificate
1018   // verification, so there cannot be state from a previous verification.
1019   CHECK(!server_cert_);
1020   server_cert_ = x509_util::CreateX509CertificateFromBuffers(
1021       SSL_get0_peer_certificates(ssl_.get()));
1022 
1023   // OpenSSL decoded the certificate, but the X509Certificate implementation
1024   // could not. This is treated as a fatal SSL-level protocol error rather than
1025   // a certificate error. See https://crbug.com/91341.
1026   if (!server_cert_) {
1027     OpenSSLPutNetError(FROM_HERE, ERR_SSL_SERVER_CERT_BAD_FORMAT);
1028     return ssl_verify_invalid;
1029   }
1030 
1031   net_log_.AddEvent(NetLogEventType::SSL_CERTIFICATES_RECEIVED, [&] {
1032     return base::Value::Dict().Set(
1033         "certificates", NetLogX509CertificateList(server_cert_.get()));
1034   });
1035 
1036   // If the certificate is bad and has been previously accepted, use
1037   // the previous status and bypass the error.
1038   CertStatus cert_status;
1039   if (IsAllowedBadCert(server_cert_.get(), &cert_status)) {
1040     server_cert_verify_result_.Reset();
1041     server_cert_verify_result_.cert_status = cert_status;
1042     server_cert_verify_result_.verified_cert = server_cert_;
1043     cert_verification_result_ = OK;
1044     return HandleVerifyResult();
1045   }
1046 
1047   std::string_view ech_name_override = GetECHNameOverride();
1048   if (!ech_name_override.empty()) {
1049     // If ECH was offered but not negotiated, BoringSSL will ask to verify a
1050     // different name than the origin. If verification succeeds, we continue the
1051     // handshake, but BoringSSL will not report success from SSL_do_handshake().
1052     // If all else succeeds, BoringSSL will report |SSL_R_ECH_REJECTED|, mapped
1053     // to |ERR_R_ECH_NOT_NEGOTIATED|. |ech_name_override| is only used to
1054     // authenticate GetECHRetryConfigs().
1055     DCHECK(!ssl_config_.ech_config_list.empty());
1056     used_ech_name_override_ = true;
1057 
1058     // CertVerifier::Verify takes a string host and internally interprets it as
1059     // either a DNS name or IP address. However, the ECH public name is only
1060     // defined to be an DNS name. Thus, reject all public names that would not
1061     // be interpreted as IP addresses. Distinguishing IPv4 literals from DNS
1062     // names varies by spec, however. BoringSSL internally checks for an LDH
1063     // string, and that the last component is non-numeric. This should be
1064     // sufficient for the web, but check with Chromium's parser, in case they
1065     // diverge.
1066     //
1067     // See section 6.1.7 of draft-ietf-tls-esni-13.
1068     if (HostIsIPAddressNoBrackets(ech_name_override)) {
1069       NOTREACHED();
1070       OpenSSLPutNetError(FROM_HERE, ERR_INVALID_ECH_CONFIG_LIST);
1071       return ssl_verify_invalid;
1072     }
1073   }
1074 
1075   const uint8_t* ocsp_response_raw;
1076   size_t ocsp_response_len;
1077   SSL_get0_ocsp_response(ssl_.get(), &ocsp_response_raw, &ocsp_response_len);
1078   std::string_view ocsp_response(
1079       reinterpret_cast<const char*>(ocsp_response_raw), ocsp_response_len);
1080 
1081   const uint8_t* sct_list_raw;
1082   size_t sct_list_len;
1083   SSL_get0_signed_cert_timestamp_list(ssl_.get(), &sct_list_raw, &sct_list_len);
1084   std::string_view sct_list(reinterpret_cast<const char*>(sct_list_raw),
1085                             sct_list_len);
1086 
1087   cert_verification_result_ = context_->cert_verifier()->Verify(
1088       CertVerifier::RequestParams(
1089           server_cert_,
1090           ech_name_override.empty() ? host_and_port_.host() : ech_name_override,
1091           ssl_config_.GetCertVerifyFlags(), std::string(ocsp_response),
1092           std::string(sct_list)),
1093       &server_cert_verify_result_,
1094       base::BindOnce(&SSLClientSocketImpl::OnVerifyComplete,
1095                      base::Unretained(this)),
1096       &cert_verifier_request_, net_log_);
1097 
1098   return HandleVerifyResult();
1099 }
1100 
OnVerifyComplete(int result)1101 void SSLClientSocketImpl::OnVerifyComplete(int result) {
1102   cert_verification_result_ = result;
1103   // In handshake phase. The parameter to OnHandshakeIOComplete is unused.
1104   OnHandshakeIOComplete(OK);
1105 }
1106 
HandleVerifyResult()1107 ssl_verify_result_t SSLClientSocketImpl::HandleVerifyResult() {
1108   // Verification is in progress. Inform BoringSSL it should retry the
1109   // callback later. The next call to VerifyCertCallback will be a
1110   // continuation of the same verification, so leave
1111   // cert_verification_result_ as-is.
1112   if (cert_verification_result_ == ERR_IO_PENDING)
1113     return ssl_verify_retry;
1114 
1115   // In BoringSSL's calling convention for asynchronous callbacks,
1116   // after a callback returns a non-retry value, the operation has
1117   // completed. Subsequent calls are of new operations with potentially
1118   // different arguments. Reset cert_verification_result_ to inform
1119   // VerifyCertCallback not to replay the result on subsequent calls.
1120   int result = cert_verification_result_;
1121   cert_verification_result_ = kCertVerifyPending;
1122 
1123   cert_verifier_request_.reset();
1124 
1125   // If the connection was good, check HPKP and CT status simultaneously,
1126   // but prefer to treat the HPKP error as more serious, if there was one.
1127   if (result == OK) {
1128     int ct_result = CheckCTRequirements();
1129     TransportSecurityState::PKPStatus pin_validity =
1130         context_->transport_security_state()->CheckPublicKeyPins(
1131             host_and_port_, server_cert_verify_result_.is_issued_by_known_root,
1132             server_cert_verify_result_.public_key_hashes);
1133     switch (pin_validity) {
1134       case TransportSecurityState::PKPStatus::VIOLATED:
1135         server_cert_verify_result_.cert_status |=
1136             CERT_STATUS_PINNED_KEY_MISSING;
1137         result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1138         break;
1139       case TransportSecurityState::PKPStatus::BYPASSED:
1140         pkp_bypassed_ = true;
1141         [[fallthrough]];
1142       case TransportSecurityState::PKPStatus::OK:
1143         // Do nothing.
1144         break;
1145     }
1146     if (result != ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN && ct_result != OK)
1147       result = ct_result;
1148   }
1149 
1150   is_fatal_cert_error_ =
1151       IsCertStatusError(server_cert_verify_result_.cert_status) &&
1152       result != ERR_CERT_KNOWN_INTERCEPTION_BLOCKED &&
1153       context_->transport_security_state()->ShouldSSLErrorsBeFatal(
1154           host_and_port_.host());
1155 
1156   if (IsCertificateError(result)) {
1157     if (!GetECHNameOverride().empty()) {
1158       // Certificate exceptions are only applicable for the origin name. For
1159       // simplicity, we do not allow certificate exceptions for the public name
1160       // and map all bypassable errors to fatal ones.
1161       result = ERR_ECH_FALLBACK_CERTIFICATE_INVALID;
1162     }
1163     if (ssl_config_.ignore_certificate_errors) {
1164       result = OK;
1165     }
1166   }
1167 
1168   if (result == OK) {
1169     return ssl_verify_ok;
1170   }
1171 
1172   OpenSSLPutNetError(FROM_HERE, result);
1173   return ssl_verify_invalid;
1174 }
1175 
CheckCTRequirements()1176 int SSLClientSocketImpl::CheckCTRequirements() {
1177   TransportSecurityState::CTRequirementsStatus ct_requirement_status =
1178       context_->transport_security_state()->CheckCTRequirements(
1179           host_and_port_, server_cert_verify_result_.is_issued_by_known_root,
1180           server_cert_verify_result_.public_key_hashes,
1181           server_cert_verify_result_.verified_cert.get(),
1182           server_cert_verify_result_.policy_compliance);
1183 
1184   if (context_->sct_auditing_delegate()) {
1185     context_->sct_auditing_delegate()->MaybeEnqueueReport(
1186         host_and_port_, server_cert_verify_result_.verified_cert.get(),
1187         server_cert_verify_result_.scts);
1188   }
1189 
1190   switch (ct_requirement_status) {
1191     case TransportSecurityState::CT_REQUIREMENTS_NOT_MET:
1192       server_cert_verify_result_.cert_status |=
1193           CERT_STATUS_CERTIFICATE_TRANSPARENCY_REQUIRED;
1194       return ERR_CERTIFICATE_TRANSPARENCY_REQUIRED;
1195     case TransportSecurityState::CT_REQUIREMENTS_MET:
1196     case TransportSecurityState::CT_NOT_REQUIRED:
1197       return OK;
1198   }
1199 
1200   NOTREACHED();
1201   return OK;
1202 }
1203 
DoConnectCallback(int rv)1204 void SSLClientSocketImpl::DoConnectCallback(int rv) {
1205   if (!user_connect_callback_.is_null()) {
1206     std::move(user_connect_callback_).Run(rv > OK ? OK : rv);
1207   }
1208 }
1209 
OnHandshakeIOComplete(int result)1210 void SSLClientSocketImpl::OnHandshakeIOComplete(int result) {
1211   int rv = DoHandshakeLoop(result);
1212   if (rv != ERR_IO_PENDING) {
1213     if (in_confirm_handshake_) {
1214       in_confirm_handshake_ = false;
1215       net_log_.EndEvent(NetLogEventType::SSL_CONFIRM_HANDSHAKE);
1216     } else {
1217       LogConnectEndEvent(rv);
1218     }
1219     DoConnectCallback(rv);
1220   }
1221 }
1222 
DoHandshakeLoop(int last_io_result)1223 int SSLClientSocketImpl::DoHandshakeLoop(int last_io_result) {
1224   TRACE_EVENT0(NetTracingCategory(), "SSLClientSocketImpl::DoHandshakeLoop");
1225   int rv = last_io_result;
1226   do {
1227     // Default to STATE_NONE for next state.
1228     // (This is a quirk carried over from the windows
1229     // implementation.  It makes reading the logs a bit harder.)
1230     // State handlers can and often do call GotoState just
1231     // to stay in the current state.
1232     State state = next_handshake_state_;
1233     next_handshake_state_ = STATE_NONE;
1234     switch (state) {
1235       case STATE_HANDSHAKE:
1236         rv = DoHandshake();
1237         break;
1238       case STATE_HANDSHAKE_COMPLETE:
1239         rv = DoHandshakeComplete(rv);
1240         break;
1241       case STATE_NONE:
1242       default:
1243         rv = ERR_UNEXPECTED;
1244         NOTREACHED() << "unexpected state" << state;
1245         break;
1246     }
1247   } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1248   return rv;
1249 }
1250 
DoPayloadRead(IOBuffer * buf,int buf_len)1251 int SSLClientSocketImpl::DoPayloadRead(IOBuffer* buf, int buf_len) {
1252   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1253 
1254   DCHECK_LT(0, buf_len);
1255   DCHECK(buf);
1256 
1257   int rv;
1258   if (pending_read_error_ != kSSLClientSocketNoPendingResult) {
1259     rv = pending_read_error_;
1260     pending_read_error_ = kSSLClientSocketNoPendingResult;
1261     if (rv == 0) {
1262       net_log_.AddByteTransferEvent(NetLogEventType::SSL_SOCKET_BYTES_RECEIVED,
1263                                     rv, buf->data());
1264     } else {
1265       NetLogOpenSSLError(net_log_, NetLogEventType::SSL_READ_ERROR, rv,
1266                          pending_read_ssl_error_, pending_read_error_info_);
1267     }
1268     pending_read_ssl_error_ = SSL_ERROR_NONE;
1269     pending_read_error_info_ = OpenSSLErrorInfo();
1270     return rv;
1271   }
1272 
1273   int total_bytes_read = 0;
1274   int ssl_ret, ssl_err;
1275   do {
1276     ssl_ret = SSL_read(ssl_.get(), buf->data() + total_bytes_read,
1277                        buf_len - total_bytes_read);
1278     ssl_err = SSL_get_error(ssl_.get(), ssl_ret);
1279     if (ssl_ret > 0) {
1280       total_bytes_read += ssl_ret;
1281     } else if (ssl_err == SSL_ERROR_WANT_RENEGOTIATE) {
1282       if (!SSL_renegotiate(ssl_.get())) {
1283         ssl_err = SSL_ERROR_SSL;
1284       }
1285     }
1286     // Continue processing records as long as there is more data available
1287     // synchronously.
1288   } while (ssl_err == SSL_ERROR_WANT_RENEGOTIATE ||
1289            (total_bytes_read < buf_len && ssl_ret > 0 &&
1290             transport_adapter_->HasPendingReadData()));
1291 
1292   // Although only the final SSL_read call may have failed, the failure needs to
1293   // processed immediately, while the information still available in OpenSSL's
1294   // error queue.
1295   if (ssl_ret <= 0) {
1296     pending_read_ssl_error_ = ssl_err;
1297     if (pending_read_ssl_error_ == SSL_ERROR_ZERO_RETURN) {
1298       pending_read_error_ = 0;
1299     } else if (pending_read_ssl_error_ == SSL_ERROR_WANT_X509_LOOKUP &&
1300                !send_client_cert_) {
1301       pending_read_error_ = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1302     } else if (pending_read_ssl_error_ ==
1303                SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
1304       DCHECK(client_private_key_);
1305       DCHECK_NE(kSSLClientSocketNoPendingResult, signature_result_);
1306       pending_read_error_ = ERR_IO_PENDING;
1307     } else {
1308       pending_read_error_ = MapLastOpenSSLError(
1309           pending_read_ssl_error_, err_tracer, &pending_read_error_info_);
1310     }
1311 
1312     // Many servers do not reliably send a close_notify alert when shutting down
1313     // a connection, and instead terminate the TCP connection. This is reported
1314     // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a
1315     // graceful EOF, instead of treating it as an error as it should be.
1316     if (pending_read_error_ == ERR_CONNECTION_CLOSED)
1317       pending_read_error_ = 0;
1318   }
1319 
1320   if (total_bytes_read > 0) {
1321     // Return any bytes read to the caller. The error will be deferred to the
1322     // next call of DoPayloadRead.
1323     rv = total_bytes_read;
1324 
1325     // Do not treat insufficient data as an error to return in the next call to
1326     // DoPayloadRead() - instead, let the call fall through to check SSL_read()
1327     // again. The transport may have data available by then.
1328     if (pending_read_error_ == ERR_IO_PENDING)
1329       pending_read_error_ = kSSLClientSocketNoPendingResult;
1330   } else {
1331     // No bytes were returned. Return the pending read error immediately.
1332     DCHECK_NE(kSSLClientSocketNoPendingResult, pending_read_error_);
1333     rv = pending_read_error_;
1334     pending_read_error_ = kSSLClientSocketNoPendingResult;
1335   }
1336 
1337   if (rv >= 0) {
1338     net_log_.AddByteTransferEvent(NetLogEventType::SSL_SOCKET_BYTES_RECEIVED,
1339                                   rv, buf->data());
1340   } else if (rv != ERR_IO_PENDING) {
1341     NetLogOpenSSLError(net_log_, NetLogEventType::SSL_READ_ERROR, rv,
1342                        pending_read_ssl_error_, pending_read_error_info_);
1343     pending_read_ssl_error_ = SSL_ERROR_NONE;
1344     pending_read_error_info_ = OpenSSLErrorInfo();
1345   }
1346   return rv;
1347 }
1348 
DoPayloadWrite()1349 int SSLClientSocketImpl::DoPayloadWrite() {
1350   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1351   int rv = SSL_write(ssl_.get(), user_write_buf_->data(), user_write_buf_len_);
1352 
1353   if (rv >= 0) {
1354     CHECK_LE(rv, user_write_buf_len_);
1355     net_log_.AddByteTransferEvent(NetLogEventType::SSL_SOCKET_BYTES_SENT, rv,
1356                                   user_write_buf_->data());
1357     if (first_post_handshake_write_ && SSL_is_init_finished(ssl_.get())) {
1358       if (base::FeatureList::IsEnabled(features::kTLS13KeyUpdate) &&
1359           SSL_version(ssl_.get()) == TLS1_3_VERSION) {
1360         const int ok = SSL_key_update(ssl_.get(), SSL_KEY_UPDATE_REQUESTED);
1361         DCHECK(ok);
1362       }
1363       first_post_handshake_write_ = false;
1364     }
1365     return rv;
1366   }
1367 
1368   int ssl_error = SSL_get_error(ssl_.get(), rv);
1369   if (ssl_error == SSL_ERROR_WANT_PRIVATE_KEY_OPERATION)
1370     return ERR_IO_PENDING;
1371   OpenSSLErrorInfo error_info;
1372   int net_error = MapLastOpenSSLError(ssl_error, err_tracer, &error_info);
1373 
1374   if (net_error != ERR_IO_PENDING) {
1375     NetLogOpenSSLError(net_log_, NetLogEventType::SSL_WRITE_ERROR, net_error,
1376                        ssl_error, error_info);
1377   }
1378   return net_error;
1379 }
1380 
DoPeek()1381 void SSLClientSocketImpl::DoPeek() {
1382   if (!completed_connect_) {
1383     return;
1384   }
1385 
1386   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1387 
1388   if (ssl_config_.early_data_enabled && !handled_early_data_result_) {
1389     // |SSL_peek| will implicitly run |SSL_do_handshake| if needed, but run it
1390     // manually to pick up the reject reason.
1391     int rv = SSL_do_handshake(ssl_.get());
1392     int ssl_err = SSL_get_error(ssl_.get(), rv);
1393     int err = rv > 0 ? OK : MapOpenSSLError(ssl_err, err_tracer);
1394     if (err == ERR_IO_PENDING) {
1395       return;
1396     }
1397 
1398     // Since the two-parameter version of the macro (which asks for a max value)
1399     // requires that the max value sentinel be named |kMaxValue|, transform the
1400     // max-value sentinel into a one-past-the-end ("boundary") sentinel by
1401     // adding 1, in order to be able to use the three-parameter macro.
1402     UMA_HISTOGRAM_ENUMERATION("Net.SSLHandshakeEarlyDataReason",
1403                               SSL_get_early_data_reason(ssl_.get()),
1404                               ssl_early_data_reason_max_value + 1);
1405     if (IsGoogleHost(host_and_port_.host())) {
1406       // Most Google hosts are known to implement 0-RTT, so this gives more
1407       // targeted metrics as we initially roll out client support. See
1408       // https://crbug.com/641225.
1409       UMA_HISTOGRAM_ENUMERATION("Net.SSLHandshakeEarlyDataReason.Google",
1410                                 SSL_get_early_data_reason(ssl_.get()),
1411                                 ssl_early_data_reason_max_value + 1);
1412     }
1413 
1414     // On early data reject, clear early data on any other sessions in the
1415     // cache, so retries do not get stuck attempting 0-RTT. See
1416     // https://crbug.com/1066623.
1417     if (err == ERR_EARLY_DATA_REJECTED ||
1418         err == ERR_WRONG_VERSION_ON_EARLY_DATA) {
1419       context_->ssl_client_session_cache()->ClearEarlyData(
1420           GetSessionCacheKey(std::nullopt));
1421     }
1422 
1423     handled_early_data_result_ = true;
1424 
1425     if (err != OK) {
1426       peek_complete_ = true;
1427       return;
1428     }
1429   }
1430 
1431   if (ssl_config_.disable_post_handshake_peek_for_testing || peek_complete_) {
1432     return;
1433   }
1434 
1435   char byte;
1436   int rv = SSL_peek(ssl_.get(), &byte, 1);
1437   int ssl_err = SSL_get_error(ssl_.get(), rv);
1438   if (ssl_err != SSL_ERROR_WANT_READ && ssl_err != SSL_ERROR_WANT_WRITE) {
1439     peek_complete_ = true;
1440   }
1441 }
1442 
RetryAllOperations()1443 void SSLClientSocketImpl::RetryAllOperations() {
1444   // SSL_do_handshake, SSL_read, and SSL_write may all be retried when blocked,
1445   // so retry all operations for simplicity. (Otherwise, SSL_get_error for each
1446   // operation may be remembered to retry only the blocked ones.)
1447 
1448   // Performing these callbacks may cause |this| to be deleted. If this
1449   // happens, the other callbacks should not be invoked. Guard against this by
1450   // holding a WeakPtr to |this| and ensuring it's still valid.
1451   base::WeakPtr<SSLClientSocketImpl> guard(weak_factory_.GetWeakPtr());
1452   if (next_handshake_state_ == STATE_HANDSHAKE) {
1453     // In handshake phase. The parameter to OnHandshakeIOComplete is unused.
1454     OnHandshakeIOComplete(OK);
1455   }
1456 
1457   if (!guard.get())
1458     return;
1459 
1460   DoPeek();
1461 
1462   int rv_read = ERR_IO_PENDING;
1463   int rv_write = ERR_IO_PENDING;
1464   if (user_read_buf_) {
1465     rv_read = DoPayloadRead(user_read_buf_.get(), user_read_buf_len_);
1466   } else if (!user_read_callback_.is_null()) {
1467     // ReadIfReady() is called by the user. Skip DoPayloadRead() and just let
1468     // the user know that read can be retried.
1469     rv_read = OK;
1470   }
1471 
1472   if (user_write_buf_)
1473     rv_write = DoPayloadWrite();
1474 
1475   if (rv_read != ERR_IO_PENDING)
1476     DoReadCallback(rv_read);
1477 
1478   if (!guard.get())
1479     return;
1480 
1481   if (rv_write != ERR_IO_PENDING)
1482     DoWriteCallback(rv_write);
1483 }
1484 
ClientCertRequestCallback(SSL * ssl)1485 int SSLClientSocketImpl::ClientCertRequestCallback(SSL* ssl) {
1486   DCHECK(ssl == ssl_.get());
1487 
1488   net_log_.AddEvent(NetLogEventType::SSL_CLIENT_CERT_REQUESTED);
1489   certificate_requested_ = true;
1490 
1491   // Clear any currently configured certificates.
1492   SSL_certs_clear(ssl_.get());
1493 
1494 #if !BUILDFLAG(ENABLE_CLIENT_CERTIFICATES)
1495   LOG(WARNING) << "Client auth is not supported";
1496 #else   // BUILDFLAG(ENABLE_CLIENT_CERTIFICATES)
1497   if (!send_client_cert_) {
1498     // First pass: we know that a client certificate is needed, but we do not
1499     // have one at hand. Suspend the handshake. SSL_get_error will return
1500     // SSL_ERROR_WANT_X509_LOOKUP.
1501     return -1;
1502   }
1503 
1504   // Second pass: a client certificate should have been selected.
1505   if (client_cert_.get()) {
1506     if (!client_private_key_) {
1507       // The caller supplied a null private key. Fail the handshake and surface
1508       // an appropriate error to the caller.
1509       LOG(WARNING) << "Client cert found without private key";
1510       OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1511       return -1;
1512     }
1513 
1514     if (!SetSSLChainAndKey(ssl_.get(), client_cert_.get(), nullptr,
1515                            &SSLContext::kPrivateKeyMethod)) {
1516       OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1517       return -1;
1518     }
1519 
1520     std::vector<uint16_t> preferences =
1521         client_private_key_->GetAlgorithmPreferences();
1522     SSL_set_signing_algorithm_prefs(ssl_.get(), preferences.data(),
1523                                     preferences.size());
1524 
1525     net_log_.AddEventWithIntParams(
1526         NetLogEventType::SSL_CLIENT_CERT_PROVIDED, "cert_count",
1527         base::checked_cast<int>(1 +
1528                                 client_cert_->intermediate_buffers().size()));
1529     return 1;
1530   }
1531 #endif  // !BUILDFLAG(ENABLE_CLIENT_CERTIFICATES)
1532 
1533   // Send no client certificate.
1534   net_log_.AddEventWithIntParams(NetLogEventType::SSL_CLIENT_CERT_PROVIDED,
1535                                  "cert_count", 0);
1536   return 1;
1537 }
1538 
NewSessionCallback(SSL_SESSION * session)1539 int SSLClientSocketImpl::NewSessionCallback(SSL_SESSION* session) {
1540   if (!IsCachingEnabled())
1541     return 0;
1542 
1543   std::optional<IPAddress> ip_addr;
1544   if (SSL_CIPHER_get_kx_nid(SSL_SESSION_get0_cipher(session)) == NID_kx_rsa) {
1545     // If RSA key exchange was used, additionally key the cache with the
1546     // destination IP address. Of course, if a proxy is being used, the
1547     // semantics of this are a little complex, but we're doing our best. See
1548     // https://crbug.com/969684
1549     IPEndPoint ip_endpoint;
1550     if (stream_socket_->GetPeerAddress(&ip_endpoint) != OK) {
1551       return 0;
1552     }
1553     ip_addr = ip_endpoint.address();
1554   }
1555 
1556   // OpenSSL optionally passes ownership of |session|. Returning one signals
1557   // that this function has claimed it.
1558   context_->ssl_client_session_cache()->Insert(
1559       GetSessionCacheKey(ip_addr), bssl::UniquePtr<SSL_SESSION>(session));
1560   return 1;
1561 }
1562 
GetSessionCacheKey(std::optional<IPAddress> dest_ip_addr) const1563 SSLClientSessionCache::Key SSLClientSocketImpl::GetSessionCacheKey(
1564     std::optional<IPAddress> dest_ip_addr) const {
1565   SSLClientSessionCache::Key key;
1566   key.server = host_and_port_;
1567   key.dest_ip_addr = dest_ip_addr;
1568   if (NetworkAnonymizationKey::IsPartitioningEnabled()) {
1569     key.network_anonymization_key = ssl_config_.network_anonymization_key;
1570   }
1571   key.privacy_mode = ssl_config_.privacy_mode;
1572   return key;
1573 }
1574 
IsRenegotiationAllowed() const1575 bool SSLClientSocketImpl::IsRenegotiationAllowed() const {
1576   if (negotiated_protocol_ == kProtoUnknown)
1577     return ssl_config_.renego_allowed_default;
1578 
1579   for (NextProto allowed : ssl_config_.renego_allowed_for_protos) {
1580     if (negotiated_protocol_ == allowed)
1581       return true;
1582   }
1583   return false;
1584 }
1585 
IsCachingEnabled() const1586 bool SSLClientSocketImpl::IsCachingEnabled() const {
1587   return context_->ssl_client_session_cache() != nullptr;
1588 }
1589 
PrivateKeySignCallback(uint8_t * out,size_t * out_len,size_t max_out,uint16_t algorithm,const uint8_t * in,size_t in_len)1590 ssl_private_key_result_t SSLClientSocketImpl::PrivateKeySignCallback(
1591     uint8_t* out,
1592     size_t* out_len,
1593     size_t max_out,
1594     uint16_t algorithm,
1595     const uint8_t* in,
1596     size_t in_len) {
1597   DCHECK_EQ(kSSLClientSocketNoPendingResult, signature_result_);
1598   DCHECK(signature_.empty());
1599   DCHECK(client_private_key_);
1600 
1601   net_log_.BeginEvent(NetLogEventType::SSL_PRIVATE_KEY_OP, [&] {
1602     return NetLogPrivateKeyOperationParams(
1603         algorithm,
1604         // Pass the SSLPrivateKey pointer to avoid making copies of the
1605         // provider name in the common case with logging disabled.
1606         client_private_key_.get());
1607   });
1608 
1609   base::UmaHistogramSparse("Net.SSLClientCertSignatureAlgorithm", algorithm);
1610   signature_result_ = ERR_IO_PENDING;
1611   client_private_key_->Sign(
1612       algorithm, base::make_span(in, in_len),
1613       base::BindOnce(&SSLClientSocketImpl::OnPrivateKeyComplete,
1614                      weak_factory_.GetWeakPtr()));
1615   return ssl_private_key_retry;
1616 }
1617 
PrivateKeyCompleteCallback(uint8_t * out,size_t * out_len,size_t max_out)1618 ssl_private_key_result_t SSLClientSocketImpl::PrivateKeyCompleteCallback(
1619     uint8_t* out,
1620     size_t* out_len,
1621     size_t max_out) {
1622   DCHECK_NE(kSSLClientSocketNoPendingResult, signature_result_);
1623   DCHECK(client_private_key_);
1624 
1625   if (signature_result_ == ERR_IO_PENDING)
1626     return ssl_private_key_retry;
1627   if (signature_result_ != OK) {
1628     OpenSSLPutNetError(FROM_HERE, signature_result_);
1629     return ssl_private_key_failure;
1630   }
1631   if (signature_.size() > max_out) {
1632     OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
1633     return ssl_private_key_failure;
1634   }
1635   memcpy(out, signature_.data(), signature_.size());
1636   *out_len = signature_.size();
1637   signature_.clear();
1638   return ssl_private_key_success;
1639 }
1640 
OnPrivateKeyComplete(Error error,const std::vector<uint8_t> & signature)1641 void SSLClientSocketImpl::OnPrivateKeyComplete(
1642     Error error,
1643     const std::vector<uint8_t>& signature) {
1644   DCHECK_EQ(ERR_IO_PENDING, signature_result_);
1645   DCHECK(signature_.empty());
1646   DCHECK(client_private_key_);
1647 
1648   net_log_.EndEventWithNetErrorCode(NetLogEventType::SSL_PRIVATE_KEY_OP, error);
1649 
1650   signature_result_ = error;
1651   if (signature_result_ == OK)
1652     signature_ = signature;
1653 
1654   // During a renegotiation, either Read or Write calls may be blocked on an
1655   // asynchronous private key operation.
1656   RetryAllOperations();
1657 }
1658 
MessageCallback(int is_write,int content_type,const void * buf,size_t len)1659 void SSLClientSocketImpl::MessageCallback(int is_write,
1660                                           int content_type,
1661                                           const void* buf,
1662                                           size_t len) {
1663   switch (content_type) {
1664     case SSL3_RT_ALERT:
1665       net_log_.AddEvent(is_write ? NetLogEventType::SSL_ALERT_SENT
1666                                  : NetLogEventType::SSL_ALERT_RECEIVED,
1667                         [&] { return NetLogSSLAlertParams(buf, len); });
1668       break;
1669     case SSL3_RT_HANDSHAKE:
1670       net_log_.AddEvent(
1671           is_write ? NetLogEventType::SSL_HANDSHAKE_MESSAGE_SENT
1672                    : NetLogEventType::SSL_HANDSHAKE_MESSAGE_RECEIVED,
1673           [&](NetLogCaptureMode capture_mode) {
1674             return NetLogSSLMessageParams(!!is_write, buf, len, capture_mode);
1675           });
1676       break;
1677     case SSL3_RT_CLIENT_HELLO_INNER:
1678       DCHECK(is_write);
1679       net_log_.AddEvent(NetLogEventType::SSL_ENCRYPTED_CLIENT_HELLO,
1680                         [&](NetLogCaptureMode capture_mode) {
1681                           return NetLogSSLMessageParams(!!is_write, buf, len,
1682                                                         capture_mode);
1683                         });
1684       break;
1685   }
1686 }
1687 
LogConnectEndEvent(int rv)1688 void SSLClientSocketImpl::LogConnectEndEvent(int rv) {
1689   if (rv != OK) {
1690     net_log_.EndEventWithNetErrorCode(NetLogEventType::SSL_CONNECT, rv);
1691     return;
1692   }
1693 
1694   net_log_.EndEvent(NetLogEventType::SSL_CONNECT,
1695                     [&] { return NetLogSSLInfoParams(this); });
1696 }
1697 
RecordNegotiatedProtocol() const1698 void SSLClientSocketImpl::RecordNegotiatedProtocol() const {
1699   UMA_HISTOGRAM_ENUMERATION("Net.SSLNegotiatedAlpnProtocol",
1700                             negotiated_protocol_, kProtoLast + 1);
1701 }
1702 
MapLastOpenSSLError(int ssl_error,const crypto::OpenSSLErrStackTracer & tracer,OpenSSLErrorInfo * info)1703 int SSLClientSocketImpl::MapLastOpenSSLError(
1704     int ssl_error,
1705     const crypto::OpenSSLErrStackTracer& tracer,
1706     OpenSSLErrorInfo* info) {
1707   int net_error = MapOpenSSLErrorWithDetails(ssl_error, tracer, info);
1708 
1709   if (ssl_error == SSL_ERROR_SSL &&
1710       ERR_GET_LIB(info->error_code) == ERR_LIB_SSL) {
1711     // TLS does not provide an alert for missing client certificates, so most
1712     // servers send a generic handshake_failure alert. Detect this case by
1713     // checking if we have received a CertificateRequest but sent no
1714     // certificate. See https://crbug.com/646567.
1715     if (ERR_GET_REASON(info->error_code) ==
1716             SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE &&
1717         certificate_requested_ && send_client_cert_ && !client_cert_) {
1718       net_error = ERR_BAD_SSL_CLIENT_AUTH_CERT;
1719     }
1720 
1721     // Per spec, access_denied is only for client-certificate-based access
1722     // control, but some buggy firewalls use it when blocking a page. To avoid a
1723     // confusing error, map it to a generic protocol error if no
1724     // CertificateRequest was sent. See https://crbug.com/630883.
1725     if (ERR_GET_REASON(info->error_code) == SSL_R_TLSV1_ALERT_ACCESS_DENIED &&
1726         !certificate_requested_) {
1727       net_error = ERR_SSL_PROTOCOL_ERROR;
1728     }
1729 
1730     // This error is specific to the client, so map it here.
1731     if (ERR_GET_REASON(info->error_code) ==
1732         SSL_R_NO_COMMON_SIGNATURE_ALGORITHMS) {
1733       net_error = ERR_SSL_CLIENT_AUTH_NO_COMMON_ALGORITHMS;
1734     }
1735   }
1736 
1737   return net_error;
1738 }
1739 
GetECHNameOverride() const1740 std::string_view SSLClientSocketImpl::GetECHNameOverride() const {
1741   const char* data;
1742   size_t len;
1743   SSL_get0_ech_name_override(ssl_.get(), &data, &len);
1744   return std::string_view(data, len);
1745 }
1746 
IsAllowedBadCert(X509Certificate * cert,CertStatus * cert_status) const1747 bool SSLClientSocketImpl::IsAllowedBadCert(X509Certificate* cert,
1748                                            CertStatus* cert_status) const {
1749   if (!GetECHNameOverride().empty()) {
1750     // Certificate exceptions are only applicable for the origin name. For
1751     // simplicity, we do not allow certificate exceptions for the public name.
1752     return false;
1753   }
1754   return ssl_config_.IsAllowedBadCert(cert, cert_status);
1755 }
1756 
1757 }  // namespace net
1758