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