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