blob: 623c7b5ef295a79aa04581f0af5e370cbcfabe49 [file] [log] [blame]
Avi Drissman64595482022-09-14 20:52:291// Copyright 2012 The Chromium Authors
[email protected]d518cd92010-09-29 12:27:442// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Tom Sepez3afe88c2024-05-23 20:35:235#ifdef UNSAFE_BUFFERS_BUILD
6// TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
7#pragma allow_unsafe_buffers
8#endif
9
svaldeze83af292016-04-26 14:33:3710#include "net/socket/ssl_client_socket_impl.h"
[email protected]d518cd92010-09-29 12:27:4411
[email protected]edfd0f42014-07-22 18:20:3712#include <errno.h>
bnc67da3de2015-01-15 21:02:2613#include <string.h>
[email protected]d518cd92010-09-29 12:27:4414
mabb51c5142016-12-07 09:32:4015#include <algorithm>
Bence Békycc859862021-02-08 17:26:4016#include <cstring>
David Benjaminf8ebd2b2017-12-15 19:22:4117#include <map>
Peter Boström8a7540692021-04-05 20:48:2018#include <memory>
Md Hasibul Hasan7495cd72024-03-26 01:02:3219#include <string_view>
davidben752bcf22015-12-21 22:55:5020#include <utility>
21
David Benjamin9ba36b02017-11-10 19:01:5322#include "base/containers/span.h"
David Benjamin6f2da652019-06-26 23:36:3523#include "base/feature_list.h"
Avi Drissman41c4a412023-01-11 22:45:3724#include "base/functional/bind.h"
25#include "base/functional/callback_helpers.h"
davidben1d489522015-07-01 18:48:4626#include "base/lazy_instance.h"
David Benjamin43527bf2019-10-04 17:59:4027#include "base/location.h"
[email protected]3b63f8f42011-03-28 01:54:1528#include "base/memory/singleton.h"
mmenke1beda3d2016-07-22 03:33:4529#include "base/metrics/field_trial.h"
Ilya Sherman0eb39802017-12-08 20:58:1830#include "base/metrics/histogram_functions.h"
asvitkinec3c93722015-06-17 14:48:3731#include "base/metrics/histogram_macros.h"
David Benjamin2cd5f6092021-10-18 18:54:4932#include "base/notreached.h"
Adam Langley2b6f8dea2019-09-16 23:40:1833#include "base/rand_util.h"
[email protected]20305ec2011-01-21 04:55:5234#include "base/synchronization/lock.h"
Sean Maher52fa5a72022-11-14 15:53:2535#include "base/task/sequenced_task_runner.h"
estade5e5529d2015-05-21 20:59:1136#include "base/values.h"
Adam Langleya0301772019-08-01 22:10:4937#include "build/build_config.h"
Minoru Chikamune15e7fdf2023-10-11 02:20:0038#include "components/miracle_parameter/common/public/miracle_parameter.h"
[email protected]ee0f2aa82013-10-25 11:59:2639#include "crypto/ec_private_key.h"
[email protected]4b559b4d2011-04-14 17:37:1440#include "crypto/openssl_util.h"
David Benjamin570460e2018-10-16 06:01:2941#include "net/base/features.h"
martijna2e83bd2016-03-18 13:10:4542#include "net/base/ip_address.h"
David Benjamin95ea68322022-04-25 19:55:1943#include "net/base/ip_endpoint.h"
[email protected]d518cd92010-09-29 12:27:4444#include "net/base/net_errors.h"
Adam Langley7d873ea2021-03-26 20:24:2045#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
xunjieli0b7f5b62016-12-06 20:43:4846#include "net/base/trace_constants.h"
Stefano Duo6bfd45d2023-04-03 16:38:2247#include "net/base/tracing.h"
David Benjamind5503c82018-02-01 20:59:3848#include "net/base/url_util.h"
[email protected]6e7845ae2013-03-29 21:48:1149#include "net/cert/cert_verifier.h"
davidbeneb5f8ef32014-09-04 14:14:3250#include "net/cert/ct_verifier.h"
Chris Thompsonf31b2492020-07-21 05:47:4251#include "net/cert/sct_auditing_delegate.h"
Chris Thompson15f50ffc2020-10-05 21:53:4852#include "net/cert/sct_status_flags.h"
[email protected]6e7845ae2013-03-29 21:48:1153#include "net/cert/x509_certificate_net_log_param.h"
mattm316af822017-02-23 04:05:5654#include "net/cert/x509_util.h"
[email protected]8bd4e7a2014-08-09 14:49:1755#include "net/http/transport_security_state.h"
mikecirone8b85c432016-09-08 19:11:0056#include "net/log/net_log_event_type.h"
Eric Roman45f155c2019-07-15 19:47:3157#include "net/log/net_log_values.h"
Victor Vasiliev5c5f62b2020-12-03 22:27:5258#include "net/ssl/cert_compression.h"
[email protected]536fd0b2013-03-14 17:41:5759#include "net/ssl/ssl_cert_request_info.h"
davidben281d13f02016-04-27 20:43:2860#include "net/ssl/ssl_cipher_suite_names.h"
[email protected]536fd0b2013-03-14 17:41:5761#include "net/ssl/ssl_connection_status_flags.h"
David Benjamin0627236e2019-06-27 02:01:1862#include "net/ssl/ssl_handshake_details.h"
[email protected]536fd0b2013-03-14 17:41:5763#include "net/ssl/ssl_info.h"
David Benjaminbd37c172018-07-11 17:24:5764#include "net/ssl/ssl_key_logger.h"
davidben1d489522015-07-01 18:48:4665#include "net/ssl/ssl_private_key.h"
[email protected]a2b2cfc2017-12-06 09:06:0866#include "net/traffic_annotation/network_traffic_annotation.h"
tfarinae8cb8aa2016-10-21 02:44:0167#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"
[email protected]d518cd92010-09-29 12:27:4473
74namespace net {
75
76namespace {
77
[email protected]4b768562013-02-16 04:10:0778// 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).
Oscar Johanssond49464e2018-07-02 09:35:4580const int kSSLClientSocketNoPendingResult = 1;
Jesse Selover94c9a942019-01-16 01:18:0481// 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).
83const int kCertVerifyPending = 1;
[email protected]4b768562013-02-16 04:10:0784
Minoru Chikamune007273b2023-09-01 10:11:1685BASE_FEATURE(kDefaultOpenSSLBufferSizeFeature,
86 "DefaultOpenSSLBufferSizeFeature",
87 base::FEATURE_ENABLED_BY_DEFAULT);
88
haavardm2d92e722014-12-19 13:45:4489// Default size of the internal BoringSSL buffers.
Minoru Chikamune15e7fdf2023-10-11 02:20:0090MIRACLE_PARAMETER_FOR_INT(GetDefaultOpenSSLBufferSize,
91 kDefaultOpenSSLBufferSizeFeature,
92 "DefaultOpenSSLBufferSize",
93 17 * 1024)
haavardm2d92e722014-12-19 13:45:4494
Liam Brady0c651722023-02-24 23:48:2095base::Value::Dict NetLogPrivateKeyOperationParams(uint16_t algorithm,
96 SSLPrivateKey* key) {
Sergii Bykov8064c1dc2024-01-03 09:16:4997 return base::Value::Dict()
98 .Set("algorithm",
99 SSL_get_signature_algorithm_name(algorithm, 0 /* exclude curve */))
100 .Set("provider", key->GetProviderName());
davidben752bcf22015-12-21 22:55:50101}
102
Liam Brady0c651722023-02-24 23:48:20103base::Value::Dict NetLogSSLInfoParams(SSLClientSocketImpl* socket) {
davidben281d13f02016-04-27 20:43:28104 SSLInfo ssl_info;
Sergii Bykov8064c1dc2024-01-03 09:16:49105 if (!socket->GetSSLInfo(&ssl_info)) {
Liam Brady0c651722023-02-24 23:48:20106 return base::Value::Dict();
Sergii Bykov8064c1dc2024-01-03 09:16:49107 }
davidben281d13f02016-04-27 20:43:28108
davidben281d13f02016-04-27 20:43:28109 const char* version_str;
110 SSLVersionToString(&version_str,
111 SSLConnectionStatusToVersion(ssl_info.connection_status));
Sergii Bykov8064c1dc2024-01-03 09:16:49112 return base::Value::Dict()
113 .Set("version", version_str)
114 .Set("is_resumed", ssl_info.handshake_type == SSLInfo::HANDSHAKE_RESUME)
115 .Set("cipher_suite",
116 SSLConnectionStatusToCipherSuite(ssl_info.connection_status))
117 .Set("key_exchange_group", ssl_info.key_exchange_group)
118 .Set("peer_signature_algorithm", ssl_info.peer_signature_algorithm)
119 .Set("encrypted_client_hello", ssl_info.encrypted_client_hello)
120 .Set("next_proto", NextProtoToString(socket->GetNegotiatedProtocol()));
davidben281d13f02016-04-27 20:43:28121}
122
Liam Brady0c651722023-02-24 23:48:20123base::Value::Dict NetLogSSLAlertParams(const void* bytes, size_t len) {
Sergii Bykov8064c1dc2024-01-03 09:16:49124 return base::Value::Dict().Set("bytes", NetLogBinaryValue(bytes, len));
davidbencef9e212017-04-19 15:00:10125}
126
Liam Brady0c651722023-02-24 23:48:20127base::Value::Dict NetLogSSLMessageParams(bool is_write,
128 const void* bytes,
129 size_t len,
130 NetLogCaptureMode capture_mode) {
davidbencef9e212017-04-19 15:00:10131 if (len == 0) {
Peter Boströmb5035d512024-05-14 22:37:30132 NOTREACHED_IN_MIGRATION();
Liam Brady0c651722023-02-24 23:48:20133 return base::Value::Dict();
davidbencef9e212017-04-19 15:00:10134 }
135
Matt Menkeca721da2022-06-01 04:47:29136 base::Value::Dict dict;
davidbencef9e212017-04-19 15:00:10137 // The handshake message type is the first byte. Include it so elided messages
138 // still report their type.
139 uint8_t type = reinterpret_cast<const uint8_t*>(bytes)[0];
Matt Menkeca721da2022-06-01 04:47:29140 dict.Set("type", type);
davidbencef9e212017-04-19 15:00:10141
142 // Elide client certificate messages unless logging socket bytes. The client
143 // certificate does not contain information needed to impersonate the user
144 // (that's the private key which isn't sent over the wire), but it may contain
145 // information on the user's identity.
146 if (!is_write || type != SSL3_MT_CERTIFICATE ||
Eric Roman3124cde2019-07-10 22:26:15147 NetLogCaptureIncludesSocketBytes(capture_mode)) {
Matt Menkeca721da2022-06-01 04:47:29148 dict.Set("bytes", NetLogBinaryValue(bytes, len));
davidbencef9e212017-04-19 15:00:10149 }
150
Liam Brady0c651722023-02-24 23:48:20151 return dict;
davidbencef9e212017-04-19 15:00:10152}
153
Md Hasibul Hasan7495cd72024-03-26 01:02:32154bool HostIsIPAddressNoBrackets(std::string_view host) {
David Benjamin2cd5f6092021-10-18 18:54:49155 // Note this cannot directly call url::HostIsIPAddress, because that function
156 // expects bracketed IPv6 literals. By the time hosts reach SSLClientSocket,
157 // brackets have been removed.
158 IPAddress unused;
159 return unused.AssignFromIPLiteral(host);
160}
161
[email protected]821e3bb2013-11-08 01:06:01162} // namespace
163
svaldeze83af292016-04-26 14:33:37164class SSLClientSocketImpl::SSLContext {
[email protected]fbef13932010-11-23 12:38:53165 public:
olli.raula36aa8be2015-09-10 11:14:22166 static SSLContext* GetInstance() {
fdoray33e7c3c52017-01-19 18:37:23167 return base::Singleton<SSLContext,
168 base::LeakySingletonTraits<SSLContext>>::get();
olli.raula36aa8be2015-09-10 11:14:22169 }
[email protected]fbef13932010-11-23 12:38:53170 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
[email protected]fbef13932010-11-23 12:38:53171
svaldeze83af292016-04-26 14:33:37172 SSLClientSocketImpl* GetClientSocketFromSSL(const SSL* ssl) {
[email protected]fbef13932010-11-23 12:38:53173 DCHECK(ssl);
svaldeze83af292016-04-26 14:33:37174 SSLClientSocketImpl* socket = static_cast<SSLClientSocketImpl*>(
[email protected]fbef13932010-11-23 12:38:53175 SSL_get_ex_data(ssl, ssl_socket_data_index_));
176 DCHECK(socket);
177 return socket;
178 }
179
svaldeze83af292016-04-26 14:33:37180 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketImpl* socket) {
[email protected]fbef13932010-11-23 12:38:53181 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
182 }
183
David Benjaminbd37c172018-07-11 17:24:57184 void SetSSLKeyLogger(std::unique_ptr<SSLKeyLogger> logger) {
Matt Mueller37a27b572020-11-25 19:15:10185 net::SSLKeyLoggerManager::SetSSLKeyLogger(std::move(logger));
186 SSL_CTX_set_keylog_callback(ssl_ctx_.get(),
187 SSLKeyLoggerManager::KeyLogCallback);
davidben2a811e4e2015-12-01 10:49:34188 }
davidben2a811e4e2015-12-01 10:49:34189
davidben1d489522015-07-01 18:48:46190 static const SSL_PRIVATE_KEY_METHOD kPrivateKeyMethod;
191
[email protected]fbef13932010-11-23 12:38:53192 private:
olli.raula36aa8be2015-09-10 11:14:22193 friend struct base::DefaultSingletonTraits<SSLContext>;
[email protected]fbef13932010-11-23 12:38:53194
Daniel McArdle3a663d62019-01-31 00:48:47195 SSLContext() {
[email protected]4b559b4d2011-04-14 17:37:14196 crypto::EnsureOpenSSLInit();
Raul Tambre94493c652019-03-11 17:18:35197 ssl_socket_data_index_ =
198 SSL_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
[email protected]fbef13932010-11-23 12:38:53199 DCHECK_NE(ssl_socket_data_index_, -1);
davidbena35b40c32017-03-09 17:33:45200 ssl_ctx_.reset(SSL_CTX_new(TLS_with_buffers_method()));
Raul Tambre94493c652019-03-11 17:18:35201 SSL_CTX_set_cert_cb(ssl_ctx_.get(), ClientCertRequestCallback, nullptr);
davidbena35b40c32017-03-09 17:33:45202
Jesse Selover94c9a942019-01-16 01:18:04203 // Verifies the server certificate even on resumed sessions.
204 SSL_CTX_set_reverify_on_resume(ssl_ctx_.get(), 1);
Steven Valdez3eaa9962017-07-18 21:51:05205 SSL_CTX_set_custom_verify(ssl_ctx_.get(), SSL_VERIFY_PEER,
Jesse Selover94c9a942019-01-16 01:18:04206 VerifyCertCallback);
davidbendafe4e52015-04-08 22:53:52207 // Disable the internal session cache. Session caching is handled
svaldeze83af292016-04-26 14:33:37208 // externally (i.e. by SSLClientSessionCache).
davidbendafe4e52015-04-08 22:53:52209 SSL_CTX_set_session_cache_mode(
210 ssl_ctx_.get(), SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL);
davidben44aeae62015-06-24 20:47:43211 SSL_CTX_sess_set_new_cb(ssl_ctx_.get(), NewSessionCallback);
davidben99ce6302016-11-09 17:30:28212 SSL_CTX_set_timeout(ssl_ctx_.get(), 1 * 60 * 60 /* one hour */);
nharper736ceda2015-11-07 00:16:59213
davidbenfacfac7b2016-09-27 22:39:53214 SSL_CTX_set_grease_enabled(ssl_ctx_.get(), 1);
215
davidbenbf0fcf12017-02-10 21:00:34216 // Deduplicate all certificates minted from the SSL_CTX in memory.
217 SSL_CTX_set0_buffer_pool(ssl_ctx_.get(), x509_util::GetBufferPool());
218
davidbencef9e212017-04-19 15:00:10219 SSL_CTX_set_msg_callback(ssl_ctx_.get(), MessageCallback);
Adam Langley93cbfad12018-07-06 22:07:16220
Victor Vasiliev5c5f62b2020-12-03 22:27:52221 ConfigureCertificateCompression(ssl_ctx_.get());
[email protected]fbef13932010-11-23 12:38:53222 }
223
[email protected]82c59022014-08-15 09:38:27224 static int ClientCertRequestCallback(SSL* ssl, void* arg) {
svaldeze83af292016-04-26 14:33:37225 SSLClientSocketImpl* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]82c59022014-08-15 09:38:27226 DCHECK(socket);
227 return socket->ClientCertRequestCallback(ssl);
[email protected]718c9672010-12-02 10:04:10228 }
229
davidben44aeae62015-06-24 20:47:43230 static int NewSessionCallback(SSL* ssl, SSL_SESSION* session) {
svaldeze83af292016-04-26 14:33:37231 SSLClientSocketImpl* socket = GetInstance()->GetClientSocketFromSSL(ssl);
davidben44aeae62015-06-24 20:47:43232 return socket->NewSessionCallback(session);
davidbendafe4e52015-04-08 22:53:52233 }
234
David Benjaminb9bafbe2017-11-07 21:41:38235 static ssl_private_key_result_t PrivateKeySignCallback(SSL* ssl,
236 uint8_t* out,
237 size_t* out_len,
238 size_t max_out,
239 uint16_t algorithm,
240 const uint8_t* in,
241 size_t in_len) {
svaldeze83af292016-04-26 14:33:37242 SSLClientSocketImpl* socket = GetInstance()->GetClientSocketFromSSL(ssl);
David Benjaminb9bafbe2017-11-07 21:41:38243 return socket->PrivateKeySignCallback(out, out_len, max_out, algorithm, in,
244 in_len);
davidben0bca07fd2016-07-18 15:12:03245 }
246
247 static ssl_private_key_result_t PrivateKeyCompleteCallback(SSL* ssl,
248 uint8_t* out,
249 size_t* out_len,
250 size_t max_out) {
251 SSLClientSocketImpl* socket = GetInstance()->GetClientSocketFromSSL(ssl);
252 return socket->PrivateKeyCompleteCallback(out, out_len, max_out);
davidben1d489522015-07-01 18:48:46253 }
254
davidbencef9e212017-04-19 15:00:10255 static void MessageCallback(int is_write,
256 int version,
257 int content_type,
258 const void* buf,
259 size_t len,
260 SSL* ssl,
261 void* arg) {
262 SSLClientSocketImpl* socket = GetInstance()->GetClientSocketFromSSL(ssl);
263 return socket->MessageCallback(is_write, content_type, buf, len);
264 }
265
[email protected]fbef13932010-11-23 12:38:53266 // This is the index used with SSL_get_ex_data to retrieve the owner
svaldeze83af292016-04-26 14:33:37267 // SSLClientSocketImpl object from an SSL instance.
[email protected]fbef13932010-11-23 12:38:53268 int ssl_socket_data_index_;
269
davidbend80c12c2016-10-11 00:13:49270 bssl::UniquePtr<SSL_CTX> ssl_ctx_;
[email protected]1279de12013-12-03 15:13:32271};
272
davidben1d489522015-07-01 18:48:46273const SSL_PRIVATE_KEY_METHOD
svaldeze83af292016-04-26 14:33:37274 SSLClientSocketImpl::SSLContext::kPrivateKeyMethod = {
David Benjaminb9bafbe2017-11-07 21:41:38275 &SSLClientSocketImpl::SSLContext::PrivateKeySignCallback,
davidben0bca07fd2016-07-18 15:12:03276 nullptr /* decrypt */,
277 &SSLClientSocketImpl::SSLContext::PrivateKeyCompleteCallback,
davidben1d489522015-07-01 18:48:46278};
279
svaldeze83af292016-04-26 14:33:37280SSLClientSocketImpl::SSLClientSocketImpl(
David Benjamin24725be2019-07-24 20:57:18281 SSLClientContext* context,
Matt Menke841fc412019-03-05 23:20:12282 std::unique_ptr<StreamSocket> stream_socket,
[email protected]055d7f22010-11-15 12:03:12283 const HostPortPair& host_and_port,
David Benjamin24725be2019-07-24 20:57:18284 const SSLConfig& ssl_config)
Oscar Johanssond49464e2018-07-02 09:35:45285 : pending_read_error_(kSSLClientSocketNoPendingResult),
David Benjamin24725be2019-07-24 20:57:18286 context_(context),
Jesse Selover94c9a942019-01-16 01:18:04287 cert_verification_result_(kCertVerifyPending),
Matt Menke841fc412019-03-05 23:20:12288 stream_socket_(std::move(stream_socket)),
Matt Menkefd956922019-02-04 23:44:03289 host_and_port_(host_and_port),
290 ssl_config_(ssl_config),
Matt Menkefd956922019-02-04 23:44:03291 signature_result_(kSSLClientSocketNoPendingResult),
Jeremy Romand54000b22019-07-08 18:40:16292 net_log_(stream_socket_->NetLog()) {
David Benjamin24725be2019-07-24 20:57:18293 CHECK(context_);
[email protected]8e458552014-08-05 00:02:15294}
[email protected]d518cd92010-09-29 12:27:44295
svaldeze83af292016-04-26 14:33:37296SSLClientSocketImpl::~SSLClientSocketImpl() {
[email protected]d518cd92010-09-29 12:27:44297 Disconnect();
298}
299
David Benjaminbd37c172018-07-11 17:24:57300void SSLClientSocketImpl::SetSSLKeyLogger(
301 std::unique_ptr<SSLKeyLogger> logger) {
302 SSLContext::GetInstance()->SetSSLKeyLogger(std::move(logger));
zhongyi81f85c6d92015-10-16 19:34:14303}
304
David Benjamin2cd5f6092021-10-18 18:54:49305std::vector<uint8_t> SSLClientSocketImpl::GetECHRetryConfigs() {
306 const uint8_t* retry_configs;
307 size_t retry_configs_len;
308 SSL_get0_ech_retry_configs(ssl_.get(), &retry_configs, &retry_configs_len);
309 return std::vector<uint8_t>(retry_configs, retry_configs + retry_configs_len);
310}
311
Md Hasibul Hasan7495cd72024-03-26 01:02:32312int SSLClientSocketImpl::ExportKeyingMaterial(std::string_view label,
svaldeze83af292016-04-26 14:33:37313 bool has_context,
Md Hasibul Hasan7495cd72024-03-26 01:02:32314 std::string_view context,
svaldeze83af292016-04-26 14:33:37315 unsigned char* out,
316 unsigned int outlen) {
davidben86935f72015-05-06 22:24:49317 if (!IsConnected())
318 return ERR_SOCKET_NOT_CONNECTED;
319
[email protected]b9b651f2013-11-09 04:32:22320 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
321
davidbenf225b262016-09-15 22:09:22322 if (!SSL_export_keying_material(
davidbend80c12c2016-10-11 00:13:49323 ssl_.get(), out, outlen, label.data(), label.size(),
davidbenf225b262016-09-15 22:09:22324 reinterpret_cast<const unsigned char*>(context.data()),
325 context.length(), has_context ? 1 : 0)) {
326 LOG(ERROR) << "Failed to export keying material.";
327 return ERR_FAILED;
[email protected]b9b651f2013-11-09 04:32:22328 }
davidbenf225b262016-09-15 22:09:22329
[email protected]b9b651f2013-11-09 04:32:22330 return OK;
331}
332
Brad Lassey3a814172018-04-26 03:30:21333int SSLClientSocketImpl::Connect(CompletionOnceCallback callback) {
svaldez4af14d22015-08-20 13:48:24334 // Although StreamSocket does allow calling Connect() after Disconnect(),
335 // this has never worked for layered sockets. CHECK to detect any consumers
336 // reconnecting an SSL socket.
337 //
338 // TODO(davidben,mmenke): Remove this API feature. See
339 // https://crbug.com/499289.
340 CHECK(!disconnected_);
341
mikecirone8b85c432016-09-08 19:11:00342 net_log_.BeginEvent(NetLogEventType::SSL_CONNECT);
[email protected]b9b651f2013-11-09 04:32:22343
344 // Set up new ssl object.
[email protected]c8a80e92014-05-17 16:02:08345 int rv = Init();
346 if (rv != OK) {
davidben281d13f02016-04-27 20:43:28347 LogConnectEndEvent(rv);
[email protected]c8a80e92014-05-17 16:02:08348 return rv;
[email protected]b9b651f2013-11-09 04:32:22349 }
350
351 // Set SSL to client mode. Handshake happens in the loop below.
davidbend80c12c2016-10-11 00:13:49352 SSL_set_connect_state(ssl_.get());
[email protected]b9b651f2013-11-09 04:32:22353
rsleeviadbd4982016-06-13 22:10:27354 next_handshake_state_ = STATE_HANDSHAKE;
[email protected]c8a80e92014-05-17 16:02:08355 rv = DoHandshakeLoop(OK);
[email protected]b9b651f2013-11-09 04:32:22356 if (rv == ERR_IO_PENDING) {
Brad Lassey3a814172018-04-26 03:30:21357 user_connect_callback_ = std::move(callback);
[email protected]b9b651f2013-11-09 04:32:22358 } else {
davidben281d13f02016-04-27 20:43:28359 LogConnectEndEvent(rv);
[email protected]b9b651f2013-11-09 04:32:22360 }
361
362 return rv > OK ? OK : rv;
363}
364
svaldeze83af292016-04-26 14:33:37365void SSLClientSocketImpl::Disconnect() {
svaldez4af14d22015-08-20 13:48:24366 disconnected_ = true;
367
[email protected]b9b651f2013-11-09 04:32:22368 // Shut down anything that may call us back.
eroman7f9236a2015-05-11 21:23:43369 cert_verifier_request_.reset();
davidben67e83912016-10-12 18:36:32370 weak_factory_.InvalidateWeakPtrs();
davidben3418e81f2016-10-19 00:09:45371 transport_adapter_.reset();
[email protected]b9b651f2013-11-09 04:32:22372
davidben67e83912016-10-12 18:36:32373 // Release user callbacks.
[email protected]b9b651f2013-11-09 04:32:22374 user_connect_callback_.Reset();
375 user_read_callback_.Reset();
376 user_write_callback_.Reset();
Raul Tambre94493c652019-03-11 17:18:35377 user_read_buf_ = nullptr;
svaldeze83af292016-04-26 14:33:37378 user_read_buf_len_ = 0;
Raul Tambre94493c652019-03-11 17:18:35379 user_write_buf_ = nullptr;
svaldeze83af292016-04-26 14:33:37380 user_write_buf_len_ = 0;
[email protected]b9b651f2013-11-09 04:32:22381
Matt Menkefd956922019-02-04 23:44:03382 stream_socket_->Disconnect();
[email protected]b9b651f2013-11-09 04:32:22383}
384
Steven Valdez6af02df2018-07-15 21:52:33385// ConfirmHandshake may only be called on a connected socket and, like other
386// socket methods, there may only be one ConfirmHandshake operation in progress
387// at once.
388int SSLClientSocketImpl::ConfirmHandshake(CompletionOnceCallback callback) {
389 CHECK(completed_connect_);
390 CHECK(!in_confirm_handshake_);
391 if (!SSL_in_early_data(ssl_.get())) {
392 return OK;
393 }
394
395 net_log_.BeginEvent(NetLogEventType::SSL_CONFIRM_HANDSHAKE);
396 next_handshake_state_ = STATE_HANDSHAKE;
397 in_confirm_handshake_ = true;
398 int rv = DoHandshakeLoop(OK);
399 if (rv == ERR_IO_PENDING) {
400 user_connect_callback_ = std::move(callback);
401 } else {
402 net_log_.EndEvent(NetLogEventType::SSL_CONFIRM_HANDSHAKE);
403 in_confirm_handshake_ = false;
404 }
405
406 return rv > OK ? OK : rv;
407}
408
svaldeze83af292016-04-26 14:33:37409bool SSLClientSocketImpl::IsConnected() const {
davidben67e83912016-10-12 18:36:32410 // If the handshake has not yet completed or the socket has been explicitly
411 // disconnected.
412 if (!completed_connect_ || disconnected_)
[email protected]b9b651f2013-11-09 04:32:22413 return false;
414 // If an asynchronous operation is still pending.
415 if (user_read_buf_.get() || user_write_buf_.get())
416 return true;
417
Matt Menkefd956922019-02-04 23:44:03418 return stream_socket_->IsConnected();
[email protected]b9b651f2013-11-09 04:32:22419}
420
svaldeze83af292016-04-26 14:33:37421bool SSLClientSocketImpl::IsConnectedAndIdle() const {
davidben67e83912016-10-12 18:36:32422 // If the handshake has not yet completed or the socket has been explicitly
423 // disconnected.
424 if (!completed_connect_ || disconnected_)
[email protected]b9b651f2013-11-09 04:32:22425 return false;
426 // If an asynchronous operation is still pending.
427 if (user_read_buf_.get() || user_write_buf_.get())
428 return false;
davidbenfc9a6b82015-04-15 23:47:32429
430 // If there is data read from the network that has not yet been consumed, do
431 // not treat the connection as idle.
432 //
davidben3418e81f2016-10-19 00:09:45433 // Note that this does not check whether there is ciphertext that has not yet
434 // been flushed to the network. |Write| returns early, so this can cause race
435 // conditions which cause a socket to not be treated reusable when it should
436 // be. See https://crbug.com/466147.
437 if (transport_adapter_->HasPendingReadData())
[email protected]b9b651f2013-11-09 04:32:22438 return false;
[email protected]b9b651f2013-11-09 04:32:22439
Matt Menkefd956922019-02-04 23:44:03440 return stream_socket_->IsConnectedAndIdle();
[email protected]b9b651f2013-11-09 04:32:22441}
442
svaldeze83af292016-04-26 14:33:37443int SSLClientSocketImpl::GetPeerAddress(IPEndPoint* addressList) const {
Matt Menkefd956922019-02-04 23:44:03444 return stream_socket_->GetPeerAddress(addressList);
[email protected]b9b651f2013-11-09 04:32:22445}
446
svaldeze83af292016-04-26 14:33:37447int SSLClientSocketImpl::GetLocalAddress(IPEndPoint* addressList) const {
Matt Menkefd956922019-02-04 23:44:03448 return stream_socket_->GetLocalAddress(addressList);
[email protected]b9b651f2013-11-09 04:32:22449}
450
tfarina42834112016-09-22 13:38:20451const NetLogWithSource& SSLClientSocketImpl::NetLog() const {
[email protected]b9b651f2013-11-09 04:32:22452 return net_log_;
453}
454
svaldeze83af292016-04-26 14:33:37455bool SSLClientSocketImpl::WasEverUsed() const {
[email protected]0dc88b32014-03-26 20:12:28456 return was_ever_used_;
[email protected]b9b651f2013-11-09 04:32:22457}
458
bnc3cf2a592016-08-11 14:48:36459NextProto SSLClientSocketImpl::GetNegotiatedProtocol() const {
460 return negotiated_protocol_;
461}
462
Md Hasibul Hasan7495cd72024-03-26 01:02:32463std::optional<std::string_view>
Bence Békycc859862021-02-08 17:26:40464SSLClientSocketImpl::GetPeerApplicationSettings() const {
465 if (!SSL_has_application_settings(ssl_.get())) {
Arthur Sonzogni4787fce2024-02-08 13:42:48466 return std::nullopt;
Bence Békycc859862021-02-08 17:26:40467 }
468
469 const uint8_t* out_data;
470 size_t out_len;
471 SSL_get0_peer_application_settings(ssl_.get(), &out_data, &out_len);
Md Hasibul Hasan7495cd72024-03-26 01:02:32472 return std::string_view{reinterpret_cast<const char*>(out_data), out_len};
Bence Békycc859862021-02-08 17:26:40473}
474
svaldeze83af292016-04-26 14:33:37475bool SSLClientSocketImpl::GetSSLInfo(SSLInfo* ssl_info) {
[email protected]b9b651f2013-11-09 04:32:22476 ssl_info->Reset();
davidbenc7e06c92017-03-07 18:54:11477 if (!server_cert_)
[email protected]b9b651f2013-11-09 04:32:22478 return false;
479
480 ssl_info->cert = server_cert_verify_result_.verified_cert;
estark03d644f2015-06-13 00:11:32481 ssl_info->unverified_cert = server_cert_;
[email protected]b9b651f2013-11-09 04:32:22482 ssl_info->cert_status = server_cert_verify_result_.cert_status;
483 ssl_info->is_issued_by_known_root =
484 server_cert_verify_result_.is_issued_by_known_root;
dadriandf302c42016-06-10 18:48:59485 ssl_info->pkp_bypassed = pkp_bypassed_;
svaldeze83af292016-04-26 14:33:37486 ssl_info->public_key_hashes = server_cert_verify_result_.public_key_hashes;
David Benjaminbac8dff2019-08-07 01:30:41487 ssl_info->client_cert_sent = send_client_cert_ && client_cert_.get();
David Benjaminf3b8b512021-09-01 21:14:01488 ssl_info->encrypted_client_hello = SSL_ech_accepted(ssl_.get());
dadrian612337a2016-07-20 22:36:58489 ssl_info->ocsp_result = server_cert_verify_result_.ocsp_result;
Carlos IL81133382017-12-06 17:18:45490 ssl_info->is_fatal_cert_error = is_fatal_cert_error_;
Chris Thompson15f50ffc2020-10-05 21:53:48491 ssl_info->signed_certificate_timestamps = server_cert_verify_result_.scts;
492 ssl_info->ct_policy_compliance = server_cert_verify_result_.policy_compliance;
davidbeneb5f8ef32014-09-04 14:14:32493
davidbend80c12c2016-10-11 00:13:49494 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_.get());
[email protected]b9b651f2013-11-09 04:32:22495 CHECK(cipher);
davidben3b00e402016-09-20 14:31:06496 // Historically, the "group" was known as "curve".
davidbend80c12c2016-10-11 00:13:49497 ssl_info->key_exchange_group = SSL_get_curve_id(ssl_.get());
David Benjamine7e073ef2018-10-25 01:26:06498 ssl_info->peer_signature_algorithm =
499 SSL_get_peer_signature_algorithm(ssl_.get());
[email protected]b9b651f2013-11-09 04:32:22500
David Benjamin29c8eedd2022-08-30 17:37:41501 SSLConnectionStatusSetCipherSuite(SSL_CIPHER_get_protocol_id(cipher),
502 &ssl_info->connection_status);
davidbend80c12c2016-10-11 00:13:49503 SSLConnectionStatusSetVersion(GetNetSSLVersion(ssl_.get()),
ryanchung987b2ff2016-02-19 00:17:12504 &ssl_info->connection_status);
[email protected]b9b651f2013-11-09 04:32:22505
davidbend80c12c2016-10-11 00:13:49506 ssl_info->handshake_type = SSL_session_reused(ssl_.get())
svaldeze83af292016-04-26 14:33:37507 ? SSLInfo::HANDSHAKE_RESUME
508 : SSLInfo::HANDSHAKE_FULL;
[email protected]b9b651f2013-11-09 04:32:22509
[email protected]b9b651f2013-11-09 04:32:22510 return true;
511}
512
svaldeze83af292016-04-26 14:33:37513int64_t SSLClientSocketImpl::GetTotalReceivedBytes() const {
Matt Menkefd956922019-02-04 23:44:03514 return stream_socket_->GetTotalReceivedBytes();
tbansalf82cc8e2015-10-14 20:05:49515}
516
Bence Békydae8af5f2018-04-13 08:53:17517void SSLClientSocketImpl::GetSSLCertRequestInfo(
518 SSLCertRequestInfo* cert_request_info) const {
519 if (!ssl_) {
Peter Boströmb5035d512024-05-14 22:37:30520 NOTREACHED_IN_MIGRATION();
Bence Békydae8af5f2018-04-13 08:53:17521 return;
522 }
523
524 cert_request_info->host_and_port = host_and_port_;
525
526 cert_request_info->cert_authorities.clear();
527 const STACK_OF(CRYPTO_BUFFER)* authorities =
528 SSL_get0_server_requested_CAs(ssl_.get());
529 for (const CRYPTO_BUFFER* ca_name : authorities) {
Tsuyoshi Horoebc507882022-06-30 11:16:45530 cert_request_info->cert_authorities.emplace_back(
531 reinterpret_cast<const char*>(CRYPTO_BUFFER_data(ca_name)),
532 CRYPTO_BUFFER_len(ca_name));
Bence Békydae8af5f2018-04-13 08:53:17533 }
534
David Benjamin28be559d2023-05-31 23:38:18535 const uint16_t* algorithms;
536 size_t num_algorithms =
537 SSL_get0_peer_verify_algorithms(ssl_.get(), &algorithms);
538 cert_request_info->signature_algorithms.assign(algorithms,
539 algorithms + num_algorithms);
Bence Békydae8af5f2018-04-13 08:53:17540}
541
Paul Jensen0f49dec2017-12-12 23:39:58542void SSLClientSocketImpl::ApplySocketTag(const SocketTag& tag) {
Matt Menkefd956922019-02-04 23:44:03543 return stream_socket_->ApplySocketTag(tag);
Paul Jensen0f49dec2017-12-12 23:39:58544}
545
svaldeze83af292016-04-26 14:33:37546int SSLClientSocketImpl::Read(IOBuffer* buf,
547 int buf_len,
Brad Lassey3a814172018-04-26 03:30:21548 CompletionOnceCallback callback) {
549 int rv = ReadIfReady(buf, buf_len, std::move(callback));
xunjieli321a96f32017-03-07 19:42:17550 if (rv == ERR_IO_PENDING) {
551 user_read_buf_ = buf;
552 user_read_buf_len_ = buf_len;
553 }
554 return rv;
555}
[email protected]b9b651f2013-11-09 04:32:22556
xunjieli321a96f32017-03-07 19:42:17557int SSLClientSocketImpl::ReadIfReady(IOBuffer* buf,
558 int buf_len,
Brad Lassey3a814172018-04-26 03:30:21559 CompletionOnceCallback callback) {
xunjieli321a96f32017-03-07 19:42:17560 int rv = DoPayloadRead(buf, buf_len);
[email protected]b9b651f2013-11-09 04:32:22561
562 if (rv == ERR_IO_PENDING) {
Brad Lassey3a814172018-04-26 03:30:21563 user_read_callback_ = std::move(callback);
[email protected]b9b651f2013-11-09 04:32:22564 } else {
[email protected]0dc88b32014-03-26 20:12:28565 if (rv > 0)
566 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22567 }
[email protected]b9b651f2013-11-09 04:32:22568 return rv;
569}
570
Helen Li5f3d96a2018-08-10 20:37:24571int SSLClientSocketImpl::CancelReadIfReady() {
David Benjamine992af92021-03-11 20:27:46572 DCHECK(user_read_callback_);
573 DCHECK(!user_read_buf_);
574
Helen Li5f3d96a2018-08-10 20:37:24575 // Cancel |user_read_callback_|, because caller does not expect the callback
576 // to be invoked after they have canceled the ReadIfReady.
David Benjamine992af92021-03-11 20:27:46577 //
578 // We do not pass the signal on to |stream_socket_| or |transport_adapter_|.
579 // Multiple operations may be waiting on a transport ReadIfReady().
580 // Conversely, an SSL ReadIfReady() may be blocked on something other than a
581 // transport ReadIfReady(). Instead, the underlying transport ReadIfReady()
582 // will continue running (with no underlying buffer). When it completes, it
583 // will signal OnReadReady(), which will notice there is no read operation to
584 // progress and skip it.
Helen Li5f3d96a2018-08-10 20:37:24585 user_read_callback_.Reset();
David Benjamine992af92021-03-11 20:27:46586 return OK;
Helen Li5f3d96a2018-08-10 20:37:24587}
588
[email protected]a2b2cfc2017-12-06 09:06:08589int SSLClientSocketImpl::Write(
590 IOBuffer* buf,
591 int buf_len,
Brad Lassey3a814172018-04-26 03:30:21592 CompletionOnceCallback callback,
[email protected]a2b2cfc2017-12-06 09:06:08593 const NetworkTrafficAnnotationTag& traffic_annotation) {
[email protected]b9b651f2013-11-09 04:32:22594 user_write_buf_ = buf;
595 user_write_buf_len_ = buf_len;
596
davidben3418e81f2016-10-19 00:09:45597 int rv = DoPayloadWrite();
[email protected]b9b651f2013-11-09 04:32:22598
599 if (rv == ERR_IO_PENDING) {
Brad Lassey3a814172018-04-26 03:30:21600 user_write_callback_ = std::move(callback);
[email protected]b9b651f2013-11-09 04:32:22601 } else {
David Benjamind3054132023-05-16 00:15:05602 if (rv > 0) {
603 CHECK_LE(rv, buf_len);
[email protected]0dc88b32014-03-26 20:12:28604 was_ever_used_ = true;
David Benjamind3054132023-05-16 00:15:05605 }
Raul Tambre94493c652019-03-11 17:18:35606 user_write_buf_ = nullptr;
[email protected]b9b651f2013-11-09 04:32:22607 user_write_buf_len_ = 0;
608 }
609
610 return rv;
611}
612
svaldeze83af292016-04-26 14:33:37613int SSLClientSocketImpl::SetReceiveBufferSize(int32_t size) {
Matt Menkefd956922019-02-04 23:44:03614 return stream_socket_->SetReceiveBufferSize(size);
[email protected]b9b651f2013-11-09 04:32:22615}
616
svaldeze83af292016-04-26 14:33:37617int SSLClientSocketImpl::SetSendBufferSize(int32_t size) {
Matt Menkefd956922019-02-04 23:44:03618 return stream_socket_->SetSendBufferSize(size);
[email protected]b9b651f2013-11-09 04:32:22619}
620
davidben3418e81f2016-10-19 00:09:45621void SSLClientSocketImpl::OnReadReady() {
622 // During a renegotiation, either Read or Write calls may be blocked on a
623 // transport read.
624 RetryAllOperations();
625}
626
627void SSLClientSocketImpl::OnWriteReady() {
628 // During a renegotiation, either Read or Write calls may be blocked on a
629 // transport read.
630 RetryAllOperations();
631}
632
svaldeze83af292016-04-26 14:33:37633int SSLClientSocketImpl::Init() {
[email protected]9e733f32010-10-04 18:19:08634 DCHECK(!ssl_);
[email protected]9e733f32010-10-04 18:19:08635
[email protected]b29af7d2010-12-14 11:52:47636 SSLContext* context = SSLContext::GetInstance();
[email protected]4b559b4d2011-04-14 17:37:14637 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:44638
davidbend80c12c2016-10-11 00:13:49639 ssl_.reset(SSL_new(context->ssl_ctx()));
640 if (!ssl_ || !context->SetClientSocketForSSL(ssl_.get(), this))
[email protected]c8a80e92014-05-17 16:02:08641 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53642
Adam Langley7d873ea2021-03-26 20:24:20643 const bool host_is_ip_address =
David Benjamin2cd5f6092021-10-18 18:54:49644 HostIsIPAddressNoBrackets(host_and_port_.host());
Adam Langley7d873ea2021-03-26 20:24:20645
davidben9bc0466f2015-06-16 22:21:27646 // SNI should only contain valid DNS hostnames, not IP addresses (see RFC
647 // 6066, Section 3).
648 //
649 // TODO(rsleevi): Should this code allow hostnames that violate the LDH rule?
650 // See https://crbug.com/496472 and https://crbug.com/496468 for discussion.
Adam Langley7d873ea2021-03-26 20:24:20651 if (!host_is_ip_address &&
davidbend80c12c2016-10-11 00:13:49652 !SSL_set_tlsext_host_name(ssl_.get(), host_and_port_.host().c_str())) {
[email protected]c8a80e92014-05-17 16:02:08653 return ERR_UNEXPECTED;
davidben9bc0466f2015-06-16 22:21:27654 }
[email protected]fbef13932010-11-23 12:38:53655
Hubert Chao84a07ba2023-06-16 15:18:38656 if (context_->config().PostQuantumKeyAgreementEnabled()) {
David Benjaminae7f3f32023-05-05 08:29:41657 static const int kCurves[] = {NID_X25519Kyber768Draft00, NID_X25519,
Adam Langleye49cd7e2023-04-11 15:15:00658 NID_X9_62_prime256v1, NID_secp384r1};
Daniel Cheng5feb16f2022-02-28 06:52:07659 if (!SSL_set1_curves(ssl_.get(), kCurves, std::size(kCurves))) {
Adam Langley7d873ea2021-03-26 20:24:20660 return ERR_UNEXPECTED;
661 }
662 }
663
Daniel McArdle3a663d62019-01-31 00:48:47664 if (IsCachingEnabled()) {
David Benjamin24725be2019-07-24 20:57:18665 bssl::UniquePtr<SSL_SESSION> session =
666 context_->ssl_client_session_cache()->Lookup(
Arthur Sonzogni4787fce2024-02-08 13:42:48667 GetSessionCacheKey(/*dest_ip_addr=*/std::nullopt));
Adam Langley26cf55a2019-07-01 21:14:57668 if (!session) {
669 // If a previous session negotiated an RSA cipher suite then it may have
670 // been inserted into the cache keyed by both hostname and resolved IP
671 // address. See https://crbug.com/969684.
672 IPEndPoint peer_address;
673 if (stream_socket_->GetPeerAddress(&peer_address) == OK) {
David Benjamin24725be2019-07-24 20:57:18674 session = context_->ssl_client_session_cache()->Lookup(
Adam Langley26cf55a2019-07-01 21:14:57675 GetSessionCacheKey(peer_address.address()));
676 }
677 }
David Benjaminb3840f42017-08-03 15:50:16678 if (session)
679 SSL_set_session(ssl_.get(), session.get());
680 }
[email protected]d518cd92010-09-29 12:27:44681
Minoru Chikamune15e7fdf2023-10-11 02:20:00682 const int kBufferSize = GetDefaultOpenSSLBufferSize();
Peter Boström8a7540692021-04-05 20:48:20683 transport_adapter_ = std::make_unique<SocketBIOAdapter>(
Minoru Chikamune007273b2023-09-01 10:11:16684 stream_socket_.get(), kBufferSize, kBufferSize, this);
davidben3418e81f2016-10-19 00:09:45685 BIO* transport_bio = transport_adapter_->bio();
mmenke1beda3d2016-07-22 03:33:45686
davidben3418e81f2016-10-19 00:09:45687 BIO_up_ref(transport_bio); // SSL_set0_rbio takes ownership.
688 SSL_set0_rbio(ssl_.get(), transport_bio);
haavardm2d92e722014-12-19 13:45:44689
davidben3418e81f2016-10-19 00:09:45690 BIO_up_ref(transport_bio); // SSL_set0_wbio takes ownership.
691 SSL_set0_wbio(ssl_.get(), transport_bio);
[email protected]d518cd92010-09-29 12:27:44692
David Benjamin151ec6b2019-08-02 19:38:52693 uint16_t version_min =
694 ssl_config_.version_min_override.value_or(context_->config().version_min);
695 uint16_t version_max =
696 ssl_config_.version_max_override.value_or(context_->config().version_max);
David Benjamin6122b922023-02-15 00:33:50697 if (version_min < TLS1_2_VERSION || version_max < TLS1_2_VERSION) {
698 // TLS versions before TLS 1.2 are no longer supported.
699 return ERR_UNEXPECTED;
David Benjamin0a594692022-10-20 19:32:24700 }
David Benjamin6122b922023-02-15 00:33:50701
David Benjamin151ec6b2019-08-02 19:38:52702 if (!SSL_set_min_proto_version(ssl_.get(), version_min) ||
703 !SSL_set_max_proto_version(ssl_.get(), version_max)) {
davidben952bdf22016-09-21 23:42:16704 return ERR_UNEXPECTED;
705 }
davidbenb937d6c2015-05-14 04:53:42706
Steven Valdez6af02df2018-07-15 21:52:33707 SSL_set_early_data_enabled(ssl_.get(), ssl_config_.early_data_enabled);
708
[email protected]9e733f32010-10-04 18:19:08709 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
710 // set everything we care about to an absolute value.
[email protected]fb10e2282010-12-01 17:08:48711 SslSetClearMask options;
[email protected]d0f00492012-08-03 22:35:13712 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
[email protected]9e733f32010-10-04 18:19:08713
714 // TODO(joth): Set this conditionally, see http://crbug.com/55410
[email protected]fb10e2282010-12-01 17:08:48715 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
[email protected]9e733f32010-10-04 18:19:08716
davidbend80c12c2016-10-11 00:13:49717 SSL_set_options(ssl_.get(), options.set_mask);
718 SSL_clear_options(ssl_.get(), options.clear_mask);
[email protected]9e733f32010-10-04 18:19:08719
[email protected]fb10e2282010-12-01 17:08:48720 // Same as above, this time for the SSL mode.
721 SslSetClearMask mode;
[email protected]9e733f32010-10-04 18:19:08722
[email protected]fb10e2282010-12-01 17:08:48723 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
ishermane5c05e12014-09-09 20:32:15724 mode.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING, true);
[email protected]fb10e2282010-12-01 17:08:48725
David Benjamin4e0215d2019-08-13 19:11:18726 mode.ConfigureFlag(SSL_MODE_ENABLE_FALSE_START, true);
[email protected]b788de02014-04-23 18:06:07727
davidbend80c12c2016-10-11 00:13:49728 SSL_set_mode(ssl_.get(), mode.set_mask);
729 SSL_clear_mode(ssl_.get(), mode.clear_mask);
[email protected]109805a2010-12-07 18:17:06730
David Benjamindc1219b2021-10-15 16:28:26731 // Use BoringSSL defaults, but disable 3DES and HMAC-SHA1 ciphers in ECDSA.
732 // These are the remaining CBC-mode ECDSA ciphers.
733 std::string command("ALL:!aPSK:!ECDSA+SHA1:!3DES");
davidben9b4a9b9c2015-10-12 18:46:51734
735 if (ssl_config_.require_ecdhe)
davidben1863716b2017-05-03 20:06:20736 command.append(":!kRSA");
davidben8ecc3072014-09-03 23:19:09737
davidben9b4a9b9c2015-10-12 18:46:51738 // Remove any disabled ciphers.
David Benjamin151ec6b2019-08-02 19:38:52739 for (uint16_t id : context_->config().disabled_cipher_suites) {
davidben9b4a9b9c2015-10-12 18:46:51740 const SSL_CIPHER* cipher = SSL_get_cipher_by_value(id);
741 if (cipher) {
742 command.append(":!");
743 command.append(SSL_CIPHER_get_name(cipher));
744 }
745 }
746
davidben1863716b2017-05-03 20:06:20747 if (!SSL_set_strict_cipher_list(ssl_.get(), command.c_str())) {
748 LOG(ERROR) << "SSL_set_cipher_list('" << command << "') failed";
749 return ERR_UNEXPECTED;
750 }
[email protected]ee0f2aa82013-10-25 11:59:26751
David Benjamin1f006942024-03-07 22:00:40752 // Disable SHA-1 server signatures.
753 // TODO(crbug.com/boringssl/699): Once the default is flipped in BoringSSL, we
754 // no longer need to override it.
755 static const uint16_t kVerifyPrefs[] = {
756 SSL_SIGN_ECDSA_SECP256R1_SHA256, SSL_SIGN_RSA_PSS_RSAE_SHA256,
757 SSL_SIGN_RSA_PKCS1_SHA256, SSL_SIGN_ECDSA_SECP384R1_SHA384,
758 SSL_SIGN_RSA_PSS_RSAE_SHA384, SSL_SIGN_RSA_PKCS1_SHA384,
759 SSL_SIGN_RSA_PSS_RSAE_SHA512, SSL_SIGN_RSA_PKCS1_SHA512,
760 };
761 if (!SSL_set_verify_algorithm_prefs(ssl_.get(), kVerifyPrefs,
762 std::size(kVerifyPrefs))) {
763 return ERR_UNEXPECTED;
David Benjamin07a07d652020-02-26 22:26:59764 }
765
Victor Tan914785302023-11-08 15:59:50766 SSL_set_alps_use_new_codepoint(
Victor Tan2d266752023-12-07 20:19:56767 ssl_.get(),
768 base::FeatureList::IsEnabled(features::kUseNewAlpsCodepointHttp2));
Victor Tan914785302023-11-08 15:59:50769
bnc1f295372015-10-21 23:24:22770 if (!ssl_config_.alpn_protos.empty()) {
bnc988e68d2016-06-27 14:03:21771 std::vector<uint8_t> wire_protos =
772 SerializeNextProtos(ssl_config_.alpn_protos);
David Benjamin0627236e2019-06-27 02:01:18773 SSL_set_alpn_protos(ssl_.get(), wire_protos.data(), wire_protos.size());
[email protected]abc44b752014-07-30 03:52:15774
David Benjaminf9f9bc72023-12-14 01:57:21775 for (NextProto proto : ssl_config_.alpn_protos) {
776 auto iter = ssl_config_.application_settings.find(proto);
777 if (iter != ssl_config_.application_settings.end()) {
778 const char* proto_string = NextProtoToString(proto);
779 if (!SSL_add_application_settings(
780 ssl_.get(), reinterpret_cast<const uint8_t*>(proto_string),
781 strlen(proto_string), iter->second.data(),
782 iter->second.size())) {
783 return ERR_UNEXPECTED;
784 }
785 }
Bence Békycc859862021-02-08 17:26:40786 }
787 }
788
Ryan Sleevid1a894e2018-04-03 20:24:07789 SSL_enable_signed_cert_timestamps(ssl_.get());
790 SSL_enable_ocsp_stapling(ssl_.get());
davidbeneb5f8ef32014-09-04 14:14:32791
davidben971a681a2017-02-16 18:57:46792 // Configure BoringSSL to allow renegotiations. Once the initial handshake
793 // completes, if renegotiations are not allowed, the default reject value will
794 // be restored. This is done in this order to permit a BoringSSL
David Benjamin43527bf2019-10-04 17:59:40795 // optimization. See https://crbug.com/boringssl/123. Use
796 // ssl_renegotiate_explicit rather than ssl_renegotiate_freely so DoPeek()
797 // does not trigger renegotiations.
798 SSL_set_renegotiate_mode(ssl_.get(), ssl_renegotiate_explicit);
davidben971a681a2017-02-16 18:57:46799
David Benjamin8373dea2018-05-07 15:39:10800 SSL_set_shed_handshake_config(ssl_.get(), 1);
David Benjaminbac8dff2019-08-07 01:30:41801
Alison Gale81f4f2c2024-04-22 19:33:31802 // TODO(crbug.com/40089326), if |ssl_config_.privacy_mode| is enabled,
David Benjaminbac8dff2019-08-07 01:30:41803 // this should always continue with no client certificate.
Rayan Kanso90e6b602020-07-09 18:15:54804 if (ssl_config_.privacy_mode == PRIVACY_MODE_ENABLED_WITHOUT_CLIENT_CERTS) {
805 send_client_cert_ = true;
806 } else {
807 send_client_cert_ = context_->GetClientCertificate(
808 host_and_port_, &client_cert_, &client_private_key_);
809 }
David Benjaminbac8dff2019-08-07 01:30:41810
David Benjamin1808fed2023-12-14 16:35:42811 if (context_->config().ech_enabled) {
Alison Galed94ce4f2024-04-22 15:20:39812 // TODO(crbug.com/41482204): Enable this unconditionally.
David Benjamin4c81d93e2021-10-12 17:32:36813 SSL_set_enable_ech_grease(ssl_.get(), 1);
814 }
David Benjamin6e79f752021-09-14 01:20:50815 if (!ssl_config_.ech_config_list.empty()) {
David Benjamin1808fed2023-12-14 16:35:42816 DCHECK(context_->config().ech_enabled);
David Benjamin6e79f752021-09-14 01:20:50817 net_log_.AddEvent(NetLogEventType::SSL_ECH_CONFIG_LIST, [&] {
Sergii Bykov8064c1dc2024-01-03 09:16:49818 return base::Value::Dict().Set(
819 "bytes", NetLogBinaryValue(ssl_config_.ech_config_list));
David Benjamin6e79f752021-09-14 01:20:50820 });
821 if (!SSL_set1_ech_config_list(ssl_.get(),
822 ssl_config_.ech_config_list.data(),
823 ssl_config_.ech_config_list.size())) {
824 return ERR_INVALID_ECH_CONFIG_LIST;
825 }
David Benjaminf3b8b512021-09-01 21:14:01826 }
827
David Benjamin918732f2024-04-24 17:54:24828 SSL_set_permute_extensions(ssl_.get(), 1);
David Benjamin08631bdf2022-03-07 23:30:57829
[email protected]c8a80e92014-05-17 16:02:08830 return OK;
[email protected]d518cd92010-09-29 12:27:44831}
832
svaldeze83af292016-04-26 14:33:37833void SSLClientSocketImpl::DoReadCallback(int rv) {
[email protected]b9b651f2013-11-09 04:32:22834 // Since Run may result in Read being called, clear |user_read_callback_|
835 // up front.
[email protected]0dc88b32014-03-26 20:12:28836 if (rv > 0)
837 was_ever_used_ = true;
xunjieli321a96f32017-03-07 19:42:17838 user_read_buf_ = nullptr;
[email protected]b9b651f2013-11-09 04:32:22839 user_read_buf_len_ = 0;
Brad Lassey3a814172018-04-26 03:30:21840 std::move(user_read_callback_).Run(rv);
[email protected]b9b651f2013-11-09 04:32:22841}
842
svaldeze83af292016-04-26 14:33:37843void SSLClientSocketImpl::DoWriteCallback(int rv) {
[email protected]b9b651f2013-11-09 04:32:22844 // Since Run may result in Write being called, clear |user_write_callback_|
845 // up front.
[email protected]0dc88b32014-03-26 20:12:28846 if (rv > 0)
847 was_ever_used_ = true;
Raul Tambre94493c652019-03-11 17:18:35848 user_write_buf_ = nullptr;
[email protected]b9b651f2013-11-09 04:32:22849 user_write_buf_len_ = 0;
Brad Lassey3a814172018-04-26 03:30:21850 std::move(user_write_callback_).Run(rv);
[email protected]b9b651f2013-11-09 04:32:22851}
852
svaldeze83af292016-04-26 14:33:37853int SSLClientSocketImpl::DoHandshake() {
[email protected]b9b651f2013-11-09 04:32:22854 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
vadimt5a243282014-12-24 00:26:16855
David Benjamin5f98efe2018-04-12 07:32:41856 int rv = SSL_do_handshake(ssl_.get());
davidbenc4212c02015-05-12 22:30:18857 int net_error = OK;
858 if (rv <= 0) {
davidbend80c12c2016-10-11 00:13:49859 int ssl_error = SSL_get_error(ssl_.get(), rv);
David Benjaminbac8dff2019-08-07 01:30:41860 if (ssl_error == SSL_ERROR_WANT_X509_LOOKUP && !send_client_cert_) {
davidbenced4aa9b2015-05-12 21:22:35861 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
862 }
davidben1d489522015-07-01 18:48:46863 if (ssl_error == SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
David Benjaminbac8dff2019-08-07 01:30:41864 DCHECK(client_private_key_);
Oscar Johanssond49464e2018-07-02 09:35:45865 DCHECK_NE(kSSLClientSocketNoPendingResult, signature_result_);
rsleeviadbd4982016-06-13 22:10:27866 next_handshake_state_ = STATE_HANDSHAKE;
davidben1d489522015-07-01 18:48:46867 return ERR_IO_PENDING;
868 }
Jesse Selover94c9a942019-01-16 01:18:04869 if (ssl_error == SSL_ERROR_WANT_CERTIFICATE_VERIFY) {
870 DCHECK(cert_verifier_request_);
871 next_handshake_state_ = STATE_HANDSHAKE;
872 return ERR_IO_PENDING;
873 }
[email protected]b9b651f2013-11-09 04:32:22874
davidbena4409c62014-08-27 17:05:51875 OpenSSLErrorInfo error_info;
davidbenfe132d92016-09-27 18:07:21876 net_error = MapLastOpenSSLError(ssl_error, err_tracer, &error_info);
[email protected]b9b651f2013-11-09 04:32:22877 if (net_error == ERR_IO_PENDING) {
davidbenc4212c02015-05-12 22:30:18878 // If not done, stay in this state
rsleeviadbd4982016-06-13 22:10:27879 next_handshake_state_ = STATE_HANDSHAKE;
davidbenc4212c02015-05-12 22:30:18880 return ERR_IO_PENDING;
881 }
882
883 LOG(ERROR) << "handshake failed; returned " << rv << ", SSL error code "
884 << ssl_error << ", net_error " << net_error;
Eric Roman06bd9742019-07-13 15:19:13885 NetLogOpenSSLError(net_log_, NetLogEventType::SSL_HANDSHAKE_ERROR,
886 net_error, ssl_error, error_info);
davidbenc4212c02015-05-12 22:30:18887 }
888
rsleeviadbd4982016-06-13 22:10:27889 next_handshake_state_ = STATE_HANDSHAKE_COMPLETE;
davidbenc4212c02015-05-12 22:30:18890 return net_error;
891}
892
svaldeze83af292016-04-26 14:33:37893int SSLClientSocketImpl::DoHandshakeComplete(int result) {
davidbenc4212c02015-05-12 22:30:18894 if (result < 0)
895 return result;
896
Steven Valdez6af02df2018-07-15 21:52:33897 if (in_confirm_handshake_) {
898 next_handshake_state_ = STATE_NONE;
899 return OK;
900 }
901
David Benjamin2cd5f6092021-10-18 18:54:49902 // If ECH overrode certificate verification to authenticate a fallback, using
903 // the socket for application data would bypass server authentication.
904 // BoringSSL will never complete the handshake in this case, so this should
905 // not happen.
906 CHECK(!used_ech_name_override_);
907
Raul Tambre94493c652019-03-11 17:18:35908 const uint8_t* alpn_proto = nullptr;
bncce6ea242016-09-15 20:22:32909 unsigned alpn_len = 0;
davidbend80c12c2016-10-11 00:13:49910 SSL_get0_alpn_selected(ssl_.get(), &alpn_proto, &alpn_len);
bncce6ea242016-09-15 20:22:32911 if (alpn_len > 0) {
Md Hasibul Hasan7495cd72024-03-26 01:02:32912 std::string_view proto(reinterpret_cast<const char*>(alpn_proto), alpn_len);
bncce6ea242016-09-15 20:22:32913 negotiated_protocol_ = NextProtoFromString(proto);
[email protected]b9b651f2013-11-09 04:32:22914 }
davidbenc4212c02015-05-12 22:30:18915
bncbd442c22016-09-14 20:49:16916 RecordNegotiatedProtocol();
davidbenc4212c02015-05-12 22:30:18917
dadriand476e652016-07-26 21:33:24918 const uint8_t* ocsp_response_raw;
919 size_t ocsp_response_len;
davidbend80c12c2016-10-11 00:13:49920 SSL_get0_ocsp_response(ssl_.get(), &ocsp_response_raw, &ocsp_response_len);
dadriand476e652016-07-26 21:33:24921 set_stapled_ocsp_response_received(ocsp_response_len != 0);
davidbenc4212c02015-05-12 22:30:18922
923 const uint8_t* sct_list;
924 size_t sct_list_len;
davidbend80c12c2016-10-11 00:13:49925 SSL_get0_signed_cert_timestamp_list(ssl_.get(), &sct_list, &sct_list_len);
davidbenc4212c02015-05-12 22:30:18926 set_signed_cert_timestamps_received(sct_list_len != 0);
927
davidben971a681a2017-02-16 18:57:46928 if (!IsRenegotiationAllowed())
929 SSL_set_renegotiate_mode(ssl_.get(), ssl_renegotiate_never);
davidbenc4212c02015-05-12 22:30:18930
davidbend80c12c2016-10-11 00:13:49931 uint16_t signature_algorithm = SSL_get_peer_signature_algorithm(ssl_.get());
davidben0653c8d2016-07-08 02:16:17932 if (signature_algorithm != 0) {
Ilya Sherman0eb39802017-12-08 20:58:18933 base::UmaHistogramSparse("Net.SSLSignatureAlgorithm", signature_algorithm);
davidben4fe4f982015-11-11 22:00:12934 }
935
Jesse Seloverdaf87902018-12-03 20:44:30936 SSLInfo ssl_info;
937 bool ok = GetSSLInfo(&ssl_info);
Jesse Selover94c9a942019-01-16 01:18:04938 // Ensure the verify callback was called, and got far enough to fill
939 // in server_cert_.
940 CHECK(ok);
Jesse Seloverdaf87902018-12-03 20:44:30941
David Benjamin0627236e2019-06-27 02:01:18942 SSLHandshakeDetails details;
943 if (SSL_version(ssl_.get()) < TLS1_3_VERSION) {
944 if (SSL_session_reused(ssl_.get())) {
945 details = SSLHandshakeDetails::kTLS12Resume;
946 } else if (SSL_in_false_start(ssl_.get())) {
947 details = SSLHandshakeDetails::kTLS12FalseStart;
948 } else {
949 details = SSLHandshakeDetails::kTLS12Full;
950 }
951 } else {
David Benjaminc1329bc2019-11-13 03:44:58952 bool used_hello_retry_request = SSL_used_hello_retry_request(ssl_.get());
David Benjamin0627236e2019-06-27 02:01:18953 if (SSL_in_early_data(ssl_.get())) {
David Benjaminc1329bc2019-11-13 03:44:58954 DCHECK(!used_hello_retry_request);
David Benjamin0627236e2019-06-27 02:01:18955 details = SSLHandshakeDetails::kTLS13Early;
956 } else if (SSL_session_reused(ssl_.get())) {
David Benjaminc1329bc2019-11-13 03:44:58957 details = used_hello_retry_request
958 ? SSLHandshakeDetails::kTLS13ResumeWithHelloRetryRequest
959 : SSLHandshakeDetails::kTLS13Resume;
David Benjamin0627236e2019-06-27 02:01:18960 } else {
David Benjaminc1329bc2019-11-13 03:44:58961 details = used_hello_retry_request
962 ? SSLHandshakeDetails::kTLS13FullWithHelloRetryRequest
963 : SSLHandshakeDetails::kTLS13Full;
David Benjamin0627236e2019-06-27 02:01:18964 }
965 }
966 UMA_HISTOGRAM_ENUMERATION("Net.SSLHandshakeDetails", details);
967
David Benjamin7f45ed92022-01-12 23:10:21968 // Measure TLS connections that implement the renegotiation_info extension.
969 // Note this records true for TLS 1.3. By removing renegotiation altogether,
970 // TLS 1.3 is implicitly patched against the bug. See
971 // https://crbug.com/850800.
972 base::UmaHistogramBoolean("Net.SSLRenegotiationInfoSupported",
973 SSL_get_secure_renegotiation_support(ssl_.get()));
974
[email protected]64b5c892014-08-08 09:39:26975 completed_connect_ = true;
Jesse Selover94c9a942019-01-16 01:18:04976 next_handshake_state_ = STATE_NONE;
David Benjamin43527bf2019-10-04 17:59:40977
978 // Read from the transport immediately after the handshake, whether Read() is
979 // called immediately or not. This serves several purposes:
980 //
981 // First, if this socket is preconnected and negotiates 0-RTT, the ServerHello
982 // will not be processed. See https://crbug.com/950706
983 //
984 // Second, in False Start and TLS 1.3, the tickets arrive after immediately
985 // after the handshake. This allows preconnected sockets to process the
986 // tickets sooner. This also avoids a theoretical deadlock if the tickets are
987 // too large. See
988 // https://boringssl-review.googlesource.com/c/boringssl/+/34948.
989 //
Alison Galed94ce4f2024-04-22 15:20:39990 // TODO(crbug.com/41456237): It is also a step in making TLS 1.3 client
David Benjamin43527bf2019-10-04 17:59:40991 // certificate alerts less unreliable.
Sean Maher52fa5a72022-11-14 15:53:25992 base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
David Benjamin43527bf2019-10-04 17:59:40993 FROM_HERE,
994 base::BindOnce(&SSLClientSocketImpl::DoPeek, weak_factory_.GetWeakPtr()));
995
Jesse Seloverdaf87902018-12-03 20:44:30996 return OK;
[email protected]b9b651f2013-11-09 04:32:22997}
998
Jesse Selover94c9a942019-01-16 01:18:04999ssl_verify_result_t SSLClientSocketImpl::VerifyCertCallback(
1000 SSL* ssl,
1001 uint8_t* out_alert) {
1002 SSLClientSocketImpl* socket =
1003 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
1004 DCHECK(socket);
1005 return socket->VerifyCert();
1006}
1007
1008// This function is called by BoringSSL, so it has to return an
1009// ssl_verify_result_t. When specific //net errors need to be
1010// returned, use OpenSSLPutNetError to add them directly to the
1011// OpenSSL error queue.
1012ssl_verify_result_t SSLClientSocketImpl::VerifyCert() {
1013 if (cert_verification_result_ != kCertVerifyPending) {
1014 // The certificate verifier updates cert_verification_result_ when
1015 // it returns asynchronously. If there is a result in
1016 // cert_verification_result_, return it instead of triggering
1017 // another verify.
1018 return HandleVerifyResult();
1019 }
1020
1021 // In this configuration, BoringSSL will perform exactly one certificate
1022 // verification, so there cannot be state from a previous verification.
1023 CHECK(!server_cert_);
1024 server_cert_ = x509_util::CreateX509CertificateFromBuffers(
1025 SSL_get0_peer_certificates(ssl_.get()));
1026
1027 // OpenSSL decoded the certificate, but the X509Certificate implementation
1028 // could not. This is treated as a fatal SSL-level protocol error rather than
1029 // a certificate error. See https://crbug.com/91341.
1030 if (!server_cert_) {
1031 OpenSSLPutNetError(FROM_HERE, ERR_SSL_SERVER_CERT_BAD_FORMAT);
1032 return ssl_verify_invalid;
1033 }
1034
Eric Roman06bd9742019-07-13 15:19:131035 net_log_.AddEvent(NetLogEventType::SSL_CERTIFICATES_RECEIVED, [&] {
Sergii Bykov8064c1dc2024-01-03 09:16:491036 return base::Value::Dict().Set(
1037 "certificates", NetLogX509CertificateList(server_cert_.get()));
Eric Roman06bd9742019-07-13 15:19:131038 });
Jesse Selover94c9a942019-01-16 01:18:041039
1040 // If the certificate is bad and has been previously accepted, use
1041 // the previous status and bypass the error.
1042 CertStatus cert_status;
David Benjamin2cd5f6092021-10-18 18:54:491043 if (IsAllowedBadCert(server_cert_.get(), &cert_status)) {
Jesse Selover94c9a942019-01-16 01:18:041044 server_cert_verify_result_.Reset();
1045 server_cert_verify_result_.cert_status = cert_status;
1046 server_cert_verify_result_.verified_cert = server_cert_;
1047 cert_verification_result_ = OK;
1048 return HandleVerifyResult();
1049 }
1050
Md Hasibul Hasan7495cd72024-03-26 01:02:321051 std::string_view ech_name_override = GetECHNameOverride();
David Benjamin2cd5f6092021-10-18 18:54:491052 if (!ech_name_override.empty()) {
1053 // If ECH was offered but not negotiated, BoringSSL will ask to verify a
1054 // different name than the origin. If verification succeeds, we continue the
1055 // handshake, but BoringSSL will not report success from SSL_do_handshake().
1056 // If all else succeeds, BoringSSL will report |SSL_R_ECH_REJECTED|, mapped
1057 // to |ERR_R_ECH_NOT_NEGOTIATED|. |ech_name_override| is only used to
1058 // authenticate GetECHRetryConfigs().
1059 DCHECK(!ssl_config_.ech_config_list.empty());
1060 used_ech_name_override_ = true;
1061
1062 // CertVerifier::Verify takes a string host and internally interprets it as
1063 // either a DNS name or IP address. However, the ECH public name is only
1064 // defined to be an DNS name. Thus, reject all public names that would not
1065 // be interpreted as IP addresses. Distinguishing IPv4 literals from DNS
1066 // names varies by spec, however. BoringSSL internally checks for an LDH
1067 // string, and that the last component is non-numeric. This should be
1068 // sufficient for the web, but check with Chromium's parser, in case they
1069 // diverge.
1070 //
1071 // See section 6.1.7 of draft-ietf-tls-esni-13.
1072 if (HostIsIPAddressNoBrackets(ech_name_override)) {
Peter Boströmb5035d512024-05-14 22:37:301073 NOTREACHED_IN_MIGRATION();
David Benjamin2cd5f6092021-10-18 18:54:491074 OpenSSLPutNetError(FROM_HERE, ERR_INVALID_ECH_CONFIG_LIST);
1075 return ssl_verify_invalid;
1076 }
1077 }
1078
Jesse Selover94c9a942019-01-16 01:18:041079 const uint8_t* ocsp_response_raw;
1080 size_t ocsp_response_len;
1081 SSL_get0_ocsp_response(ssl_.get(), &ocsp_response_raw, &ocsp_response_len);
Md Hasibul Hasan7495cd72024-03-26 01:02:321082 std::string_view ocsp_response(
Jesse Selover94c9a942019-01-16 01:18:041083 reinterpret_cast<const char*>(ocsp_response_raw), ocsp_response_len);
1084
Matt Mueller7d5464b2019-05-15 20:18:451085 const uint8_t* sct_list_raw;
1086 size_t sct_list_len;
1087 SSL_get0_signed_cert_timestamp_list(ssl_.get(), &sct_list_raw, &sct_list_len);
Md Hasibul Hasan7495cd72024-03-26 01:02:321088 std::string_view sct_list(reinterpret_cast<const char*>(sct_list_raw),
1089 sct_list_len);
Matt Mueller7d5464b2019-05-15 20:18:451090
David Benjamin24725be2019-07-24 20:57:181091 cert_verification_result_ = context_->cert_verifier()->Verify(
Matt Mueller7d5464b2019-05-15 20:18:451092 CertVerifier::RequestParams(
David Benjamin2cd5f6092021-10-18 18:54:491093 server_cert_,
1094 ech_name_override.empty() ? host_and_port_.host() : ech_name_override,
1095 ssl_config_.GetCertVerifyFlags(), std::string(ocsp_response),
1096 std::string(sct_list)),
Jesse Selover94c9a942019-01-16 01:18:041097 &server_cert_verify_result_,
1098 base::BindOnce(&SSLClientSocketImpl::OnVerifyComplete,
1099 base::Unretained(this)),
1100 &cert_verifier_request_, net_log_);
1101
1102 return HandleVerifyResult();
1103}
1104
1105void SSLClientSocketImpl::OnVerifyComplete(int result) {
1106 cert_verification_result_ = result;
1107 // In handshake phase. The parameter to OnHandshakeIOComplete is unused.
1108 OnHandshakeIOComplete(OK);
1109}
1110
1111ssl_verify_result_t SSLClientSocketImpl::HandleVerifyResult() {
1112 // Verification is in progress. Inform BoringSSL it should retry the
1113 // callback later. The next call to VerifyCertCallback will be a
1114 // continuation of the same verification, so leave
1115 // cert_verification_result_ as-is.
1116 if (cert_verification_result_ == ERR_IO_PENDING)
1117 return ssl_verify_retry;
1118
1119 // In BoringSSL's calling convention for asynchronous callbacks,
1120 // after a callback returns a non-retry value, the operation has
1121 // completed. Subsequent calls are of new operations with potentially
1122 // different arguments. Reset cert_verification_result_ to inform
1123 // VerifyCertCallback not to replay the result on subsequent calls.
1124 int result = cert_verification_result_;
1125 cert_verification_result_ = kCertVerifyPending;
1126
1127 cert_verifier_request_.reset();
1128
Jesse Selover94c9a942019-01-16 01:18:041129 // If the connection was good, check HPKP and CT status simultaneously,
1130 // but prefer to treat the HPKP error as more serious, if there was one.
Matt Mueller936511442019-09-03 18:15:121131 if (result == OK) {
Matt Mueller635c4a02023-12-15 19:05:401132 int ct_result = CheckCTRequirements();
Jesse Selover94c9a942019-01-16 01:18:041133 TransportSecurityState::PKPStatus pin_validity =
David Benjamin24725be2019-07-24 20:57:181134 context_->transport_security_state()->CheckPublicKeyPins(
Jesse Selover94c9a942019-01-16 01:18:041135 host_and_port_, server_cert_verify_result_.is_issued_by_known_root,
Emily Starke4fc52a2023-12-27 08:02:581136 server_cert_verify_result_.public_key_hashes);
Jesse Selover94c9a942019-01-16 01:18:041137 switch (pin_validity) {
1138 case TransportSecurityState::PKPStatus::VIOLATED:
1139 server_cert_verify_result_.cert_status |=
1140 CERT_STATUS_PINNED_KEY_MISSING;
1141 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1142 break;
1143 case TransportSecurityState::PKPStatus::BYPASSED:
1144 pkp_bypassed_ = true;
Roland Bock3abf56852022-01-04 23:49:341145 [[fallthrough]];
Jesse Selover94c9a942019-01-16 01:18:041146 case TransportSecurityState::PKPStatus::OK:
1147 // Do nothing.
1148 break;
1149 }
1150 if (result != ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN && ct_result != OK)
1151 result = ct_result;
1152 }
1153
1154 is_fatal_cert_error_ =
1155 IsCertStatusError(server_cert_verify_result_.cert_status) &&
Ryan Sleevi54fe7662019-11-21 01:31:581156 result != ERR_CERT_KNOWN_INTERCEPTION_BLOCKED &&
David Benjamin24725be2019-07-24 20:57:181157 context_->transport_security_state()->ShouldSSLErrorsBeFatal(
1158 host_and_port_.host());
Jesse Selover94c9a942019-01-16 01:18:041159
David Benjamin2cd5f6092021-10-18 18:54:491160 if (IsCertificateError(result)) {
1161 if (!GetECHNameOverride().empty()) {
1162 // Certificate exceptions are only applicable for the origin name. For
1163 // simplicity, we do not allow certificate exceptions for the public name
1164 // and map all bypassable errors to fatal ones.
Chris Thompsond708d342021-11-22 21:42:271165 result = ERR_ECH_FALLBACK_CERTIFICATE_INVALID;
David Benjamin2cd5f6092021-10-18 18:54:491166 }
1167 if (ssl_config_.ignore_certificate_errors) {
1168 result = OK;
1169 }
Jesse Selover94c9a942019-01-16 01:18:041170 }
1171
1172 if (result == OK) {
1173 return ssl_verify_ok;
1174 }
1175
1176 OpenSSLPutNetError(FROM_HERE, result);
1177 return ssl_verify_invalid;
1178}
1179
Matt Mueller635c4a02023-12-15 19:05:401180int SSLClientSocketImpl::CheckCTRequirements() {
Chris Thompsonb20d5892020-11-25 02:54:021181 TransportSecurityState::CTRequirementsStatus ct_requirement_status =
1182 context_->transport_security_state()->CheckCTRequirements(
1183 host_and_port_, server_cert_verify_result_.is_issued_by_known_root,
1184 server_cert_verify_result_.public_key_hashes,
Emily Stark97eb35f2023-12-19 03:01:221185 server_cert_verify_result_.verified_cert.get(),
Emily Starkcb34a30f2022-12-22 19:46:311186 server_cert_verify_result_.policy_compliance);
Chris Thompsonb20d5892020-11-25 02:54:021187
Nina Satragno4a6fc452022-02-03 16:08:221188 if (context_->sct_auditing_delegate()) {
Chris Thompsonb20d5892020-11-25 02:54:021189 context_->sct_auditing_delegate()->MaybeEnqueueReport(
1190 host_and_port_, server_cert_verify_result_.verified_cert.get(),
1191 server_cert_verify_result_.scts);
1192 }
1193
1194 switch (ct_requirement_status) {
1195 case TransportSecurityState::CT_REQUIREMENTS_NOT_MET:
1196 server_cert_verify_result_.cert_status |=
1197 CERT_STATUS_CERTIFICATE_TRANSPARENCY_REQUIRED;
1198 return ERR_CERTIFICATE_TRANSPARENCY_REQUIRED;
1199 case TransportSecurityState::CT_REQUIREMENTS_MET:
1200 case TransportSecurityState::CT_NOT_REQUIRED:
1201 return OK;
1202 }
1203
Peter Boströmb5035d512024-05-14 22:37:301204 NOTREACHED_IN_MIGRATION();
Chris Thompsonb20d5892020-11-25 02:54:021205 return OK;
1206}
1207
svaldeze83af292016-04-26 14:33:371208void SSLClientSocketImpl::DoConnectCallback(int rv) {
[email protected]b9b651f2013-11-09 04:32:221209 if (!user_connect_callback_.is_null()) {
Brad Lassey3a814172018-04-26 03:30:211210 std::move(user_connect_callback_).Run(rv > OK ? OK : rv);
[email protected]b9b651f2013-11-09 04:32:221211 }
1212}
1213
svaldeze83af292016-04-26 14:33:371214void SSLClientSocketImpl::OnHandshakeIOComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221215 int rv = DoHandshakeLoop(result);
1216 if (rv != ERR_IO_PENDING) {
Steven Valdez6af02df2018-07-15 21:52:331217 if (in_confirm_handshake_) {
1218 in_confirm_handshake_ = false;
1219 net_log_.EndEvent(NetLogEventType::SSL_CONFIRM_HANDSHAKE);
1220 } else {
1221 LogConnectEndEvent(rv);
1222 }
[email protected]b9b651f2013-11-09 04:32:221223 DoConnectCallback(rv);
1224 }
1225}
1226
svaldeze83af292016-04-26 14:33:371227int SSLClientSocketImpl::DoHandshakeLoop(int last_io_result) {
Alexandr Ilin33126632018-11-14 14:48:171228 TRACE_EVENT0(NetTracingCategory(), "SSLClientSocketImpl::DoHandshakeLoop");
[email protected]b9b651f2013-11-09 04:32:221229 int rv = last_io_result;
1230 do {
1231 // Default to STATE_NONE for next state.
1232 // (This is a quirk carried over from the windows
1233 // implementation. It makes reading the logs a bit harder.)
1234 // State handlers can and often do call GotoState just
1235 // to stay in the current state.
1236 State state = next_handshake_state_;
rsleeviadbd4982016-06-13 22:10:271237 next_handshake_state_ = STATE_NONE;
[email protected]b9b651f2013-11-09 04:32:221238 switch (state) {
1239 case STATE_HANDSHAKE:
1240 rv = DoHandshake();
1241 break;
davidbenc4212c02015-05-12 22:30:181242 case STATE_HANDSHAKE_COMPLETE:
1243 rv = DoHandshakeComplete(rv);
1244 break;
[email protected]b9b651f2013-11-09 04:32:221245 case STATE_NONE:
1246 default:
1247 rv = ERR_UNEXPECTED;
Peter Boströmb5035d512024-05-14 22:37:301248 NOTREACHED_IN_MIGRATION() << "unexpected state" << state;
[email protected]b9b651f2013-11-09 04:32:221249 break;
1250 }
[email protected]b9b651f2013-11-09 04:32:221251 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1252 return rv;
1253}
1254
xunjieli321a96f32017-03-07 19:42:171255int SSLClientSocketImpl::DoPayloadRead(IOBuffer* buf, int buf_len) {
[email protected]b9b651f2013-11-09 04:32:221256 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1257
xunjieli321a96f32017-03-07 19:42:171258 DCHECK_LT(0, buf_len);
1259 DCHECK(buf);
davidben7e555daf2015-03-25 17:03:291260
[email protected]b9b651f2013-11-09 04:32:221261 int rv;
Oscar Johanssond49464e2018-07-02 09:35:451262 if (pending_read_error_ != kSSLClientSocketNoPendingResult) {
[email protected]b9b651f2013-11-09 04:32:221263 rv = pending_read_error_;
Oscar Johanssond49464e2018-07-02 09:35:451264 pending_read_error_ = kSSLClientSocketNoPendingResult;
[email protected]b9b651f2013-11-09 04:32:221265 if (rv == 0) {
mikecirone8b85c432016-09-08 19:11:001266 net_log_.AddByteTransferEvent(NetLogEventType::SSL_SOCKET_BYTES_RECEIVED,
xunjieli321a96f32017-03-07 19:42:171267 rv, buf->data());
davidbenb8c23212014-10-28 00:12:161268 } else {
Eric Roman06bd9742019-07-13 15:19:131269 NetLogOpenSSLError(net_log_, NetLogEventType::SSL_READ_ERROR, rv,
1270 pending_read_ssl_error_, pending_read_error_info_);
[email protected]b9b651f2013-11-09 04:32:221271 }
davidbenb8c23212014-10-28 00:12:161272 pending_read_ssl_error_ = SSL_ERROR_NONE;
1273 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221274 return rv;
1275 }
1276
1277 int total_bytes_read = 0;
David Benjamin43527bf2019-10-04 17:59:401278 int ssl_ret, ssl_err;
[email protected]b9b651f2013-11-09 04:32:221279 do {
xunjieli321a96f32017-03-07 19:42:171280 ssl_ret = SSL_read(ssl_.get(), buf->data() + total_bytes_read,
1281 buf_len - total_bytes_read);
David Benjamin43527bf2019-10-04 17:59:401282 ssl_err = SSL_get_error(ssl_.get(), ssl_ret);
1283 if (ssl_ret > 0) {
davidben7e555daf2015-03-25 17:03:291284 total_bytes_read += ssl_ret;
David Benjamin43527bf2019-10-04 17:59:401285 } else if (ssl_err == SSL_ERROR_WANT_RENEGOTIATE) {
1286 if (!SSL_renegotiate(ssl_.get())) {
1287 ssl_err = SSL_ERROR_SSL;
1288 }
1289 }
davidben8ea6b172017-03-07 23:53:501290 // Continue processing records as long as there is more data available
1291 // synchronously.
David Benjamin43527bf2019-10-04 17:59:401292 } while (ssl_err == SSL_ERROR_WANT_RENEGOTIATE ||
1293 (total_bytes_read < buf_len && ssl_ret > 0 &&
1294 transport_adapter_->HasPendingReadData()));
[email protected]b9b651f2013-11-09 04:32:221295
davidben7e555daf2015-03-25 17:03:291296 // Although only the final SSL_read call may have failed, the failure needs to
1297 // processed immediately, while the information still available in OpenSSL's
1298 // error queue.
davidbenced4aa9b2015-05-12 21:22:351299 if (ssl_ret <= 0) {
David Benjamin43527bf2019-10-04 17:59:401300 pending_read_ssl_error_ = ssl_err;
davidben7e555daf2015-03-25 17:03:291301 if (pending_read_ssl_error_ == SSL_ERROR_ZERO_RETURN) {
1302 pending_read_error_ = 0;
davidbenced4aa9b2015-05-12 21:22:351303 } else if (pending_read_ssl_error_ == SSL_ERROR_WANT_X509_LOOKUP &&
David Benjaminbac8dff2019-08-07 01:30:411304 !send_client_cert_) {
davidbenced4aa9b2015-05-12 21:22:351305 pending_read_error_ = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
davidben1d489522015-07-01 18:48:461306 } else if (pending_read_ssl_error_ ==
1307 SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
David Benjaminbac8dff2019-08-07 01:30:411308 DCHECK(client_private_key_);
Oscar Johanssond49464e2018-07-02 09:35:451309 DCHECK_NE(kSSLClientSocketNoPendingResult, signature_result_);
davidben1d489522015-07-01 18:48:461310 pending_read_error_ = ERR_IO_PENDING;
davidben7e555daf2015-03-25 17:03:291311 } else {
davidbenfe132d92016-09-27 18:07:211312 pending_read_error_ = MapLastOpenSSLError(
davidben7e555daf2015-03-25 17:03:291313 pending_read_ssl_error_, err_tracer, &pending_read_error_info_);
[email protected]b9b651f2013-11-09 04:32:221314 }
1315
davidben7e555daf2015-03-25 17:03:291316 // Many servers do not reliably send a close_notify alert when shutting down
1317 // a connection, and instead terminate the TCP connection. This is reported
1318 // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a
1319 // graceful EOF, instead of treating it as an error as it should be.
1320 if (pending_read_error_ == ERR_CONNECTION_CLOSED)
1321 pending_read_error_ = 0;
1322 }
davidbenbe6ce7ec2014-10-20 19:15:561323
davidben7e555daf2015-03-25 17:03:291324 if (total_bytes_read > 0) {
1325 // Return any bytes read to the caller. The error will be deferred to the
1326 // next call of DoPayloadRead.
1327 rv = total_bytes_read;
davidbenbe6ce7ec2014-10-20 19:15:561328
davidben7e555daf2015-03-25 17:03:291329 // Do not treat insufficient data as an error to return in the next call to
1330 // DoPayloadRead() - instead, let the call fall through to check SSL_read()
davidben3418e81f2016-10-19 00:09:451331 // again. The transport may have data available by then.
davidben7e555daf2015-03-25 17:03:291332 if (pending_read_error_ == ERR_IO_PENDING)
Oscar Johanssond49464e2018-07-02 09:35:451333 pending_read_error_ = kSSLClientSocketNoPendingResult;
davidben7e555daf2015-03-25 17:03:291334 } else {
1335 // No bytes were returned. Return the pending read error immediately.
Oscar Johanssond49464e2018-07-02 09:35:451336 DCHECK_NE(kSSLClientSocketNoPendingResult, pending_read_error_);
davidben7e555daf2015-03-25 17:03:291337 rv = pending_read_error_;
Oscar Johanssond49464e2018-07-02 09:35:451338 pending_read_error_ = kSSLClientSocketNoPendingResult;
[email protected]b9b651f2013-11-09 04:32:221339 }
1340
1341 if (rv >= 0) {
mikecirone8b85c432016-09-08 19:11:001342 net_log_.AddByteTransferEvent(NetLogEventType::SSL_SOCKET_BYTES_RECEIVED,
xunjieli321a96f32017-03-07 19:42:171343 rv, buf->data());
davidbenb8c23212014-10-28 00:12:161344 } else if (rv != ERR_IO_PENDING) {
Eric Roman06bd9742019-07-13 15:19:131345 NetLogOpenSSLError(net_log_, NetLogEventType::SSL_READ_ERROR, rv,
1346 pending_read_ssl_error_, pending_read_error_info_);
davidbenb8c23212014-10-28 00:12:161347 pending_read_ssl_error_ = SSL_ERROR_NONE;
1348 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221349 }
1350 return rv;
1351}
1352
svaldeze83af292016-04-26 14:33:371353int SSLClientSocketImpl::DoPayloadWrite() {
[email protected]b9b651f2013-11-09 04:32:221354 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
davidbend80c12c2016-10-11 00:13:491355 int rv = SSL_write(ssl_.get(), user_write_buf_->data(), user_write_buf_len_);
rsleevif020edc2015-03-16 19:31:241356
[email protected]b9b651f2013-11-09 04:32:221357 if (rv >= 0) {
David Benjamind3054132023-05-16 00:15:051358 CHECK_LE(rv, user_write_buf_len_);
mikecirone8b85c432016-09-08 19:11:001359 net_log_.AddByteTransferEvent(NetLogEventType::SSL_SOCKET_BYTES_SENT, rv,
[email protected]b9b651f2013-11-09 04:32:221360 user_write_buf_->data());
Adam Langley68df3af2019-01-19 00:37:101361 if (first_post_handshake_write_ && SSL_is_init_finished(ssl_.get())) {
1362 if (base::FeatureList::IsEnabled(features::kTLS13KeyUpdate) &&
1363 SSL_version(ssl_.get()) == TLS1_3_VERSION) {
1364 const int ok = SSL_key_update(ssl_.get(), SSL_KEY_UPDATE_REQUESTED);
1365 DCHECK(ok);
1366 }
1367 first_post_handshake_write_ = false;
1368 }
[email protected]b9b651f2013-11-09 04:32:221369 return rv;
1370 }
1371
davidbend80c12c2016-10-11 00:13:491372 int ssl_error = SSL_get_error(ssl_.get(), rv);
davidben1d489522015-07-01 18:48:461373 if (ssl_error == SSL_ERROR_WANT_PRIVATE_KEY_OPERATION)
1374 return ERR_IO_PENDING;
davidbenb8c23212014-10-28 00:12:161375 OpenSSLErrorInfo error_info;
davidbenfe132d92016-09-27 18:07:211376 int net_error = MapLastOpenSSLError(ssl_error, err_tracer, &error_info);
davidbenb8c23212014-10-28 00:12:161377
1378 if (net_error != ERR_IO_PENDING) {
Eric Roman06bd9742019-07-13 15:19:131379 NetLogOpenSSLError(net_log_, NetLogEventType::SSL_WRITE_ERROR, net_error,
1380 ssl_error, error_info);
davidbenb8c23212014-10-28 00:12:161381 }
1382 return net_error;
[email protected]b9b651f2013-11-09 04:32:221383}
1384
David Benjamin43527bf2019-10-04 17:59:401385void SSLClientSocketImpl::DoPeek() {
David Benjamin3b819c4f2020-05-14 18:20:051386 if (!completed_connect_) {
David Benjamin43527bf2019-10-04 17:59:401387 return;
1388 }
1389
1390 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1391
David Benjamin3b819c4f2020-05-14 18:20:051392 if (ssl_config_.early_data_enabled && !handled_early_data_result_) {
David Benjamin421689f2019-10-17 20:01:191393 // |SSL_peek| will implicitly run |SSL_do_handshake| if needed, but run it
1394 // manually to pick up the reject reason.
1395 int rv = SSL_do_handshake(ssl_.get());
1396 int ssl_err = SSL_get_error(ssl_.get(), rv);
David Benjamin3b819c4f2020-05-14 18:20:051397 int err = rv > 0 ? OK : MapOpenSSLError(ssl_err, err_tracer);
1398 if (err == ERR_IO_PENDING) {
David Benjamin421689f2019-10-17 20:01:191399 return;
1400 }
1401
1402 // Since the two-parameter version of the macro (which asks for a max value)
1403 // requires that the max value sentinel be named |kMaxValue|, transform the
1404 // max-value sentinel into a one-past-the-end ("boundary") sentinel by
1405 // adding 1, in order to be able to use the three-parameter macro.
1406 UMA_HISTOGRAM_ENUMERATION("Net.SSLHandshakeEarlyDataReason",
1407 SSL_get_early_data_reason(ssl_.get()),
1408 ssl_early_data_reason_max_value + 1);
David Benjamin924cedad2021-06-21 20:36:351409 if (IsGoogleHost(host_and_port_.host())) {
1410 // Most Google hosts are known to implement 0-RTT, so this gives more
1411 // targeted metrics as we initially roll out client support. See
1412 // https://crbug.com/641225.
1413 UMA_HISTOGRAM_ENUMERATION("Net.SSLHandshakeEarlyDataReason.Google",
1414 SSL_get_early_data_reason(ssl_.get()),
1415 ssl_early_data_reason_max_value + 1);
1416 }
David Benjamin3b819c4f2020-05-14 18:20:051417
1418 // On early data reject, clear early data on any other sessions in the
1419 // cache, so retries do not get stuck attempting 0-RTT. See
1420 // https://crbug.com/1066623.
1421 if (err == ERR_EARLY_DATA_REJECTED ||
1422 err == ERR_WRONG_VERSION_ON_EARLY_DATA) {
1423 context_->ssl_client_session_cache()->ClearEarlyData(
Arthur Sonzogni4787fce2024-02-08 13:42:481424 GetSessionCacheKey(std::nullopt));
David Benjamin3b819c4f2020-05-14 18:20:051425 }
1426
1427 handled_early_data_result_ = true;
1428
1429 if (err != OK) {
David Benjamin421689f2019-10-17 20:01:191430 peek_complete_ = true;
1431 return;
1432 }
1433 }
1434
David Benjamin3b819c4f2020-05-14 18:20:051435 if (ssl_config_.disable_post_handshake_peek_for_testing || peek_complete_) {
1436 return;
1437 }
1438
David Benjamin43527bf2019-10-04 17:59:401439 char byte;
1440 int rv = SSL_peek(ssl_.get(), &byte, 1);
1441 int ssl_err = SSL_get_error(ssl_.get(), rv);
1442 if (ssl_err != SSL_ERROR_WANT_READ && ssl_err != SSL_ERROR_WANT_WRITE) {
1443 peek_complete_ = true;
1444 }
1445}
1446
davidben3418e81f2016-10-19 00:09:451447void SSLClientSocketImpl::RetryAllOperations() {
1448 // SSL_do_handshake, SSL_read, and SSL_write may all be retried when blocked,
1449 // so retry all operations for simplicity. (Otherwise, SSL_get_error for each
1450 // operation may be remembered to retry only the blocked ones.)
1451
Steven Valdez6af02df2018-07-15 21:52:331452 // Performing these callbacks may cause |this| to be deleted. If this
1453 // happens, the other callbacks should not be invoked. Guard against this by
1454 // holding a WeakPtr to |this| and ensuring it's still valid.
1455 base::WeakPtr<SSLClientSocketImpl> guard(weak_factory_.GetWeakPtr());
davidben3418e81f2016-10-19 00:09:451456 if (next_handshake_state_ == STATE_HANDSHAKE) {
1457 // In handshake phase. The parameter to OnHandshakeIOComplete is unused.
1458 OnHandshakeIOComplete(OK);
davidben3418e81f2016-10-19 00:09:451459 }
1460
Steven Valdez6af02df2018-07-15 21:52:331461 if (!guard.get())
1462 return;
1463
David Benjamin43527bf2019-10-04 17:59:401464 DoPeek();
1465
davidben1d489522015-07-01 18:48:461466 int rv_read = ERR_IO_PENDING;
1467 int rv_write = ERR_IO_PENDING;
xunjieli321a96f32017-03-07 19:42:171468 if (user_read_buf_) {
1469 rv_read = DoPayloadRead(user_read_buf_.get(), user_read_buf_len_);
1470 } else if (!user_read_callback_.is_null()) {
1471 // ReadIfReady() is called by the user. Skip DoPayloadRead() and just let
1472 // the user know that read can be retried.
1473 rv_read = OK;
1474 }
1475
davidben3418e81f2016-10-19 00:09:451476 if (user_write_buf_)
1477 rv_write = DoPayloadWrite();
davidben1d489522015-07-01 18:48:461478
davidben3418e81f2016-10-19 00:09:451479 if (rv_read != ERR_IO_PENDING)
davidben1d489522015-07-01 18:48:461480 DoReadCallback(rv_read);
1481
1482 if (!guard.get())
1483 return;
1484
davidben3418e81f2016-10-19 00:09:451485 if (rv_write != ERR_IO_PENDING)
davidben1d489522015-07-01 18:48:461486 DoWriteCallback(rv_write);
1487}
1488
svaldeze83af292016-04-26 14:33:371489int SSLClientSocketImpl::ClientCertRequestCallback(SSL* ssl) {
davidbend80c12c2016-10-11 00:13:491490 DCHECK(ssl == ssl_.get());
[email protected]82c59022014-08-15 09:38:271491
mikecirone8b85c432016-09-08 19:11:001492 net_log_.AddEvent(NetLogEventType::SSL_CLIENT_CERT_REQUESTED);
davidbenfe132d92016-09-27 18:07:211493 certificate_requested_ = true;
davidbenaf42cbe2014-11-13 03:27:461494
[email protected]82c59022014-08-15 09:38:271495 // Clear any currently configured certificates.
davidbend80c12c2016-10-11 00:13:491496 SSL_certs_clear(ssl_.get());
[email protected]97a854f2014-07-29 07:51:361497
Ian Vollick41446862023-07-14 19:51:261498#if !BUILDFLAG(ENABLE_CLIENT_CERTIFICATES)
[email protected]97a854f2014-07-29 07:51:361499 LOG(WARNING) << "Client auth is not supported";
Ian Vollick41446862023-07-14 19:51:261500#else // BUILDFLAG(ENABLE_CLIENT_CERTIFICATES)
David Benjaminbac8dff2019-08-07 01:30:411501 if (!send_client_cert_) {
[email protected]515adc22013-01-09 16:01:231502 // First pass: we know that a client certificate is needed, but we do not
davidbenb11fd212017-01-12 17:08:031503 // have one at hand. Suspend the handshake. SSL_get_error will return
1504 // SSL_ERROR_WANT_X509_LOOKUP.
davidbenced4aa9b2015-05-12 21:22:351505 return -1;
[email protected]5ac981e182010-12-06 17:56:271506 }
1507
1508 // Second pass: a client certificate should have been selected.
David Benjaminbac8dff2019-08-07 01:30:411509 if (client_cert_.get()) {
1510 if (!client_private_key_) {
svaldez7872fd02015-11-19 21:10:541511 // The caller supplied a null private key. Fail the handshake and surface
1512 // an appropriate error to the caller.
davidben1d489522015-07-01 18:48:461513 LOG(WARNING) << "Client cert found without private key";
1514 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1515 return -1;
1516 }
1517
David Benjaminbac8dff2019-08-07 01:30:411518 if (!SetSSLChainAndKey(ssl_.get(), client_cert_.get(), nullptr,
David Benjaminb8ab3852017-08-04 00:17:321519 &SSLContext::kPrivateKeyMethod)) {
davidbena35b40c32017-03-09 17:33:451520 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1521 return -1;
1522 }
svaldezf3db006f2015-09-29 16:43:581523
David Benjaminb9bafbe2017-11-07 21:41:381524 std::vector<uint16_t> preferences =
David Benjaminbac8dff2019-08-07 01:30:411525 client_private_key_->GetAlgorithmPreferences();
David Benjaminb9bafbe2017-11-07 21:41:381526 SSL_set_signing_algorithm_prefs(ssl_.get(), preferences.data(),
1527 preferences.size());
davidbenaf42cbe2014-11-13 03:27:461528
Eric Roman06bd9742019-07-13 15:19:131529 net_log_.AddEventWithIntParams(
1530 NetLogEventType::SSL_CLIENT_CERT_PROVIDED, "cert_count",
David Benjaminbac8dff2019-08-07 01:30:411531 base::checked_cast<int>(1 +
1532 client_cert_->intermediate_buffers().size()));
[email protected]6bad5052014-07-12 01:25:131533 return 1;
[email protected]c0787702014-05-20 21:51:441534 }
Ian Vollick41446862023-07-14 19:51:261535#endif // !BUILDFLAG(ENABLE_CLIENT_CERTIFICATES)
[email protected]5ac981e182010-12-06 17:56:271536
1537 // Send no client certificate.
Eric Roman06bd9742019-07-13 15:19:131538 net_log_.AddEventWithIntParams(NetLogEventType::SSL_CLIENT_CERT_PROVIDED,
1539 "cert_count", 0);
[email protected]82c59022014-08-15 09:38:271540 return 1;
[email protected]5ac981e182010-12-06 17:56:271541}
1542
svaldeze83af292016-04-26 14:33:371543int SSLClientSocketImpl::NewSessionCallback(SSL_SESSION* session) {
Daniel McArdle3a663d62019-01-31 00:48:471544 if (!IsCachingEnabled())
David Benjaminb3840f42017-08-03 15:50:161545 return 0;
1546
Arthur Sonzogni4787fce2024-02-08 13:42:481547 std::optional<IPAddress> ip_addr;
Adam Langley26cf55a2019-07-01 21:14:571548 if (SSL_CIPHER_get_kx_nid(SSL_SESSION_get0_cipher(session)) == NID_kx_rsa) {
1549 // If RSA key exchange was used, additionally key the cache with the
1550 // destination IP address. Of course, if a proxy is being used, the
1551 // semantics of this are a little complex, but we're doing our best. See
1552 // https://crbug.com/969684
1553 IPEndPoint ip_endpoint;
1554 if (stream_socket_->GetPeerAddress(&ip_endpoint) != OK) {
1555 return 0;
1556 }
1557 ip_addr = ip_endpoint.address();
1558 }
1559
David Benjamin6617c392019-02-12 18:08:571560 // OpenSSL optionally passes ownership of |session|. Returning one signals
1561 // that this function has claimed it.
David Benjamin24725be2019-07-24 20:57:181562 context_->ssl_client_session_cache()->Insert(
1563 GetSessionCacheKey(ip_addr), bssl::UniquePtr<SSL_SESSION>(session));
David Benjamin6617c392019-02-12 18:08:571564 return 1;
davidbendafe4e52015-04-08 22:53:521565}
1566
David Benjamin79d85bd32019-08-02 23:27:571567SSLClientSessionCache::Key SSLClientSocketImpl::GetSessionCacheKey(
Arthur Sonzogni4787fce2024-02-08 13:42:481568 std::optional<IPAddress> dest_ip_addr) const {
David Benjamin79d85bd32019-08-02 23:27:571569 SSLClientSessionCache::Key key;
1570 key.server = host_and_port_;
1571 key.dest_ip_addr = dest_ip_addr;
Dustin J. Mitchell5624da42023-04-20 18:26:171572 if (NetworkAnonymizationKey::IsPartitioningEnabled()) {
Brianna Goldstein92b34452022-09-28 13:45:371573 key.network_anonymization_key = ssl_config_.network_anonymization_key;
David Benjamin6f2da652019-06-26 23:36:351574 }
David Benjamin79d85bd32019-08-02 23:27:571575 key.privacy_mode = ssl_config_.privacy_mode;
1576 return key;
rsleevif020edc2015-03-16 19:31:241577}
1578
svaldeze83af292016-04-26 14:33:371579bool SSLClientSocketImpl::IsRenegotiationAllowed() const {
bncce6ea242016-09-15 20:22:321580 if (negotiated_protocol_ == kProtoUnknown)
davidben421116c2015-05-12 19:56:511581 return ssl_config_.renego_allowed_default;
1582
davidben421116c2015-05-12 19:56:511583 for (NextProto allowed : ssl_config_.renego_allowed_for_protos) {
bnc3cf2a592016-08-11 14:48:361584 if (negotiated_protocol_ == allowed)
davidben421116c2015-05-12 19:56:511585 return true;
1586 }
1587 return false;
1588}
1589
Daniel McArdle3a663d62019-01-31 00:48:471590bool SSLClientSocketImpl::IsCachingEnabled() const {
David Benjamin24725be2019-07-24 20:57:181591 return context_->ssl_client_session_cache() != nullptr;
Daniel McArdle3a663d62019-01-31 00:48:471592}
1593
David Benjaminb9bafbe2017-11-07 21:41:381594ssl_private_key_result_t SSLClientSocketImpl::PrivateKeySignCallback(
davidben1d489522015-07-01 18:48:461595 uint8_t* out,
1596 size_t* out_len,
1597 size_t max_out,
David Benjaminb9bafbe2017-11-07 21:41:381598 uint16_t algorithm,
davidben1d489522015-07-01 18:48:461599 const uint8_t* in,
1600 size_t in_len) {
Oscar Johanssond49464e2018-07-02 09:35:451601 DCHECK_EQ(kSSLClientSocketNoPendingResult, signature_result_);
davidben1d489522015-07-01 18:48:461602 DCHECK(signature_.empty());
David Benjaminbac8dff2019-08-07 01:30:411603 DCHECK(client_private_key_);
davidben1d489522015-07-01 18:48:461604
Eric Roman06bd9742019-07-13 15:19:131605 net_log_.BeginEvent(NetLogEventType::SSL_PRIVATE_KEY_OP, [&] {
1606 return NetLogPrivateKeyOperationParams(
1607 algorithm,
1608 // Pass the SSLPrivateKey pointer to avoid making copies of the
1609 // provider name in the common case with logging disabled.
David Benjaminbac8dff2019-08-07 01:30:411610 client_private_key_.get());
Eric Roman06bd9742019-07-13 15:19:131611 });
David Benjaminb9bafbe2017-11-07 21:41:381612
David Benjamin7f45ed92022-01-12 23:10:211613 base::UmaHistogramSparse("Net.SSLClientCertSignatureAlgorithm", algorithm);
davidben1d489522015-07-01 18:48:461614 signature_result_ = ERR_IO_PENDING;
David Benjaminbac8dff2019-08-07 01:30:411615 client_private_key_->Sign(
David Benjamin9ba36b02017-11-10 19:01:531616 algorithm, base::make_span(in, in_len),
David Benjamin8f2d2c12018-02-27 00:08:261617 base::BindOnce(&SSLClientSocketImpl::OnPrivateKeyComplete,
1618 weak_factory_.GetWeakPtr()));
davidben1d489522015-07-01 18:48:461619 return ssl_private_key_retry;
1620}
1621
davidben0bca07fd2016-07-18 15:12:031622ssl_private_key_result_t SSLClientSocketImpl::PrivateKeyCompleteCallback(
davidben1d489522015-07-01 18:48:461623 uint8_t* out,
1624 size_t* out_len,
1625 size_t max_out) {
Oscar Johanssond49464e2018-07-02 09:35:451626 DCHECK_NE(kSSLClientSocketNoPendingResult, signature_result_);
David Benjaminbac8dff2019-08-07 01:30:411627 DCHECK(client_private_key_);
davidben1d489522015-07-01 18:48:461628
1629 if (signature_result_ == ERR_IO_PENDING)
1630 return ssl_private_key_retry;
1631 if (signature_result_ != OK) {
1632 OpenSSLPutNetError(FROM_HERE, signature_result_);
1633 return ssl_private_key_failure;
1634 }
1635 if (signature_.size() > max_out) {
1636 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
1637 return ssl_private_key_failure;
1638 }
davidben5f8b6bc2015-11-25 03:19:541639 memcpy(out, signature_.data(), signature_.size());
davidben1d489522015-07-01 18:48:461640 *out_len = signature_.size();
1641 signature_.clear();
1642 return ssl_private_key_success;
1643}
1644
davidben0bca07fd2016-07-18 15:12:031645void SSLClientSocketImpl::OnPrivateKeyComplete(
davidben1d489522015-07-01 18:48:461646 Error error,
1647 const std::vector<uint8_t>& signature) {
1648 DCHECK_EQ(ERR_IO_PENDING, signature_result_);
1649 DCHECK(signature_.empty());
David Benjaminbac8dff2019-08-07 01:30:411650 DCHECK(client_private_key_);
davidben1d489522015-07-01 18:48:461651
mikecirone8b85c432016-09-08 19:11:001652 net_log_.EndEventWithNetErrorCode(NetLogEventType::SSL_PRIVATE_KEY_OP, error);
davidben1d489522015-07-01 18:48:461653
1654 signature_result_ = error;
1655 if (signature_result_ == OK)
1656 signature_ = signature;
1657
davidben1d489522015-07-01 18:48:461658 // During a renegotiation, either Read or Write calls may be blocked on an
1659 // asynchronous private key operation.
davidben3418e81f2016-10-19 00:09:451660 RetryAllOperations();
davidben1d489522015-07-01 18:48:461661}
1662
davidbencef9e212017-04-19 15:00:101663void SSLClientSocketImpl::MessageCallback(int is_write,
1664 int content_type,
1665 const void* buf,
1666 size_t len) {
1667 switch (content_type) {
1668 case SSL3_RT_ALERT:
1669 net_log_.AddEvent(is_write ? NetLogEventType::SSL_ALERT_SENT
1670 : NetLogEventType::SSL_ALERT_RECEIVED,
Eric Roman06bd9742019-07-13 15:19:131671 [&] { return NetLogSSLAlertParams(buf, len); });
davidbencef9e212017-04-19 15:00:101672 break;
1673 case SSL3_RT_HANDSHAKE:
1674 net_log_.AddEvent(
1675 is_write ? NetLogEventType::SSL_HANDSHAKE_MESSAGE_SENT
1676 : NetLogEventType::SSL_HANDSHAKE_MESSAGE_RECEIVED,
Eric Roman06bd9742019-07-13 15:19:131677 [&](NetLogCaptureMode capture_mode) {
1678 return NetLogSSLMessageParams(!!is_write, buf, len, capture_mode);
1679 });
davidbencef9e212017-04-19 15:00:101680 break;
David Benjamindf6feebe2022-02-01 07:50:281681 case SSL3_RT_CLIENT_HELLO_INNER:
1682 DCHECK(is_write);
David Benjamin90a6d772023-05-17 01:43:391683 net_log_.AddEvent(NetLogEventType::SSL_ENCRYPTED_CLIENT_HELLO,
David Benjamindf6feebe2022-02-01 07:50:281684 [&](NetLogCaptureMode capture_mode) {
1685 return NetLogSSLMessageParams(!!is_write, buf, len,
1686 capture_mode);
1687 });
1688 break;
davidbencef9e212017-04-19 15:00:101689 }
1690}
1691
davidben281d13f02016-04-27 20:43:281692void SSLClientSocketImpl::LogConnectEndEvent(int rv) {
1693 if (rv != OK) {
mikecirone8b85c432016-09-08 19:11:001694 net_log_.EndEventWithNetErrorCode(NetLogEventType::SSL_CONNECT, rv);
davidben281d13f02016-04-27 20:43:281695 return;
1696 }
1697
mikecirone8b85c432016-09-08 19:11:001698 net_log_.EndEvent(NetLogEventType::SSL_CONNECT,
Eric Roman06bd9742019-07-13 15:19:131699 [&] { return NetLogSSLInfoParams(this); });
davidben281d13f02016-04-27 20:43:281700}
1701
bncbd442c22016-09-14 20:49:161702void SSLClientSocketImpl::RecordNegotiatedProtocol() const {
1703 UMA_HISTOGRAM_ENUMERATION("Net.SSLNegotiatedAlpnProtocol",
1704 negotiated_protocol_, kProtoLast + 1);
bnc3cf2a592016-08-11 14:48:361705}
1706
davidbenfe132d92016-09-27 18:07:211707int SSLClientSocketImpl::MapLastOpenSSLError(
1708 int ssl_error,
1709 const crypto::OpenSSLErrStackTracer& tracer,
1710 OpenSSLErrorInfo* info) {
1711 int net_error = MapOpenSSLErrorWithDetails(ssl_error, tracer, info);
1712
1713 if (ssl_error == SSL_ERROR_SSL &&
1714 ERR_GET_LIB(info->error_code) == ERR_LIB_SSL) {
1715 // TLS does not provide an alert for missing client certificates, so most
1716 // servers send a generic handshake_failure alert. Detect this case by
1717 // checking if we have received a CertificateRequest but sent no
1718 // certificate. See https://crbug.com/646567.
1719 if (ERR_GET_REASON(info->error_code) ==
1720 SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE &&
David Benjaminbac8dff2019-08-07 01:30:411721 certificate_requested_ && send_client_cert_ && !client_cert_) {
davidbenfe132d92016-09-27 18:07:211722 net_error = ERR_BAD_SSL_CLIENT_AUTH_CERT;
1723 }
1724
1725 // Per spec, access_denied is only for client-certificate-based access
1726 // control, but some buggy firewalls use it when blocking a page. To avoid a
1727 // confusing error, map it to a generic protocol error if no
1728 // CertificateRequest was sent. See https://crbug.com/630883.
1729 if (ERR_GET_REASON(info->error_code) == SSL_R_TLSV1_ALERT_ACCESS_DENIED &&
1730 !certificate_requested_) {
1731 net_error = ERR_SSL_PROTOCOL_ERROR;
1732 }
David Benjamin5b4410e2017-11-10 21:50:231733
1734 // This error is specific to the client, so map it here.
1735 if (ERR_GET_REASON(info->error_code) ==
1736 SSL_R_NO_COMMON_SIGNATURE_ALGORITHMS) {
1737 net_error = ERR_SSL_CLIENT_AUTH_NO_COMMON_ALGORITHMS;
1738 }
davidbenfe132d92016-09-27 18:07:211739 }
1740
1741 return net_error;
1742}
1743
Md Hasibul Hasan7495cd72024-03-26 01:02:321744std::string_view SSLClientSocketImpl::GetECHNameOverride() const {
David Benjamin2cd5f6092021-10-18 18:54:491745 const char* data;
1746 size_t len;
1747 SSL_get0_ech_name_override(ssl_.get(), &data, &len);
Md Hasibul Hasan7495cd72024-03-26 01:02:321748 return std::string_view(data, len);
David Benjamin2cd5f6092021-10-18 18:54:491749}
1750
1751bool SSLClientSocketImpl::IsAllowedBadCert(X509Certificate* cert,
1752 CertStatus* cert_status) const {
1753 if (!GetECHNameOverride().empty()) {
1754 // Certificate exceptions are only applicable for the origin name. For
1755 // simplicity, we do not allow certificate exceptions for the public name.
1756 return false;
1757 }
1758 return ssl_config_.IsAllowedBadCert(cert, cert_status);
1759}
1760
[email protected]7e5dd49f2010-12-08 18:33:491761} // namespace net