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 #ifndef NET_SOCKET_SSL_CLIENT_SOCKET_IMPL_H_ 6 #define NET_SOCKET_SSL_CLIENT_SOCKET_IMPL_H_ 7 8 #include <stddef.h> 9 #include <stdint.h> 10 11 #include <memory> 12 #include <optional> 13 #include <string> 14 #include <string_view> 15 #include <vector> 16 17 #include "base/compiler_specific.h" 18 #include "base/containers/lru_cache.h" 19 #include "base/memory/raw_ptr.h" 20 #include "base/memory/scoped_refptr.h" 21 #include "base/memory/weak_ptr.h" 22 #include "net/base/completion_once_callback.h" 23 #include "net/base/host_port_pair.h" 24 #include "net/base/io_buffer.h" 25 #include "net/cert/cert_verifier.h" 26 #include "net/cert/cert_verify_result.h" 27 #include "net/log/net_log_with_source.h" 28 #include "net/socket/next_proto.h" 29 #include "net/socket/socket_bio_adapter.h" 30 #include "net/socket/ssl_client_socket.h" 31 #include "net/socket/stream_socket.h" 32 #include "net/ssl/openssl_ssl_util.h" 33 #include "net/ssl/ssl_client_session_cache.h" 34 #include "net/ssl/ssl_config.h" 35 #include "net/traffic_annotation/network_traffic_annotation.h" 36 #include "third_party/boringssl/src/include/openssl/base.h" 37 #include "third_party/boringssl/src/include/openssl/ssl.h" 38 39 namespace crypto { 40 class OpenSSLErrStackTracer; 41 } 42 43 namespace net { 44 45 class SSLCertRequestInfo; 46 class SSLInfo; 47 class SSLPrivateKey; 48 class SSLKeyLogger; 49 class X509Certificate; 50 51 class SSLClientSocketImpl : public SSLClientSocket, 52 public SocketBIOAdapter::Delegate { 53 public: 54 // Takes ownership of |stream_socket|, which may already be connected. 55 // The given hostname will be compared with the name(s) in the server's 56 // certificate during the SSL handshake. |ssl_config| specifies the SSL 57 // settings. The resulting socket may not outlive |context|. 58 SSLClientSocketImpl(SSLClientContext* context, 59 std::unique_ptr<StreamSocket> stream_socket, 60 const HostPortPair& host_and_port, 61 const SSLConfig& ssl_config); 62 63 SSLClientSocketImpl(const SSLClientSocketImpl&) = delete; 64 SSLClientSocketImpl& operator=(const SSLClientSocketImpl&) = delete; 65 66 ~SSLClientSocketImpl() override; 67 host_and_port()68 const HostPortPair& host_and_port() const { return host_and_port_; } 69 70 // Log SSL key material to |logger|. Must be called before any 71 // SSLClientSockets are created. 72 static void SetSSLKeyLogger(std::unique_ptr<SSLKeyLogger> logger); 73 74 // SSLClientSocket implementation. 75 std::vector<uint8_t> GetECHRetryConfigs() override; 76 77 // SSLSocket implementation. 78 int ExportKeyingMaterial(std::string_view label, 79 bool has_context, 80 std::string_view context, 81 unsigned char* out, 82 unsigned int outlen) override; 83 84 // StreamSocket implementation. 85 int Connect(CompletionOnceCallback callback) override; 86 void Disconnect() override; 87 int ConfirmHandshake(CompletionOnceCallback callback) override; 88 bool IsConnected() const override; 89 bool IsConnectedAndIdle() const override; 90 int GetPeerAddress(IPEndPoint* address) const override; 91 int GetLocalAddress(IPEndPoint* address) const override; 92 const NetLogWithSource& NetLog() const override; 93 bool WasEverUsed() const override; 94 NextProto GetNegotiatedProtocol() const override; 95 std::optional<std::string_view> GetPeerApplicationSettings() const override; 96 bool GetSSLInfo(SSLInfo* ssl_info) override; 97 int64_t GetTotalReceivedBytes() const override; 98 void GetSSLCertRequestInfo( 99 SSLCertRequestInfo* cert_request_info) const override; 100 101 void ApplySocketTag(const SocketTag& tag) override; 102 103 // Socket implementation. 104 int Read(IOBuffer* buf, 105 int buf_len, 106 CompletionOnceCallback callback) override; 107 int ReadIfReady(IOBuffer* buf, 108 int buf_len, 109 CompletionOnceCallback callback) override; 110 int CancelReadIfReady() override; 111 int Write(IOBuffer* buf, 112 int buf_len, 113 CompletionOnceCallback callback, 114 const NetworkTrafficAnnotationTag& traffic_annotation) override; 115 int SetReceiveBufferSize(int32_t size) override; 116 int SetSendBufferSize(int32_t size) override; 117 118 // SocketBIOAdapter implementation: 119 void OnReadReady() override; 120 void OnWriteReady() override; 121 122 private: 123 class PeerCertificateChain; 124 class SSLContext; 125 friend class SSLClientSocket; 126 friend class SSLContext; 127 128 int Init(); 129 void DoReadCallback(int result); 130 void DoWriteCallback(int result); 131 132 int DoHandshake(); 133 int DoHandshakeComplete(int result); 134 void DoConnectCallback(int result); 135 136 void OnVerifyComplete(int result); 137 void OnHandshakeIOComplete(int result); 138 139 int DoHandshakeLoop(int last_io_result); 140 int DoPayloadRead(IOBuffer* buf, int buf_len); 141 int DoPayloadWrite(); 142 void DoPeek(); 143 144 // Called when an asynchronous event completes which may have blocked the 145 // pending Connect, Read or Write calls, if any. Retries all state machines 146 // and, if complete, runs the respective callbacks. 147 void RetryAllOperations(); 148 149 // Callback from the SSL layer when a certificate needs to be verified. This 150 // is called when establishing new (fresh) connections and when evaluating 151 // whether an existing session can be resumed. 152 static ssl_verify_result_t VerifyCertCallback(SSL* ssl, uint8_t* out_alert); 153 ssl_verify_result_t VerifyCert(); 154 ssl_verify_result_t HandleVerifyResult(); 155 int CheckCTRequirements(); 156 157 // Callback from the SSL layer that indicates the remote server is requesting 158 // a certificate for this client. 159 int ClientCertRequestCallback(SSL* ssl); 160 161 // Called from the SSL layer whenever a new session is established. 162 int NewSessionCallback(SSL_SESSION* session); 163 164 // Returns a session cache key for this socket. 165 SSLClientSessionCache::Key GetSessionCacheKey( 166 std::optional<IPAddress> dest_ip_addr) const; 167 168 // Returns true if renegotiations are allowed. 169 bool IsRenegotiationAllowed() const; 170 171 // Returns true when we should be using the ssl_client_session_cache_ 172 bool IsCachingEnabled() const; 173 174 // Callbacks for operations with the private key. 175 ssl_private_key_result_t PrivateKeySignCallback(uint8_t* out, 176 size_t* out_len, 177 size_t max_out, 178 uint16_t algorithm, 179 const uint8_t* in, 180 size_t in_len); 181 ssl_private_key_result_t PrivateKeyCompleteCallback(uint8_t* out, 182 size_t* out_len, 183 size_t max_out); 184 185 void OnPrivateKeyComplete(Error error, const std::vector<uint8_t>& signature); 186 187 // Called whenever BoringSSL processes a protocol message. 188 void MessageCallback(int is_write, 189 int content_type, 190 const void* buf, 191 size_t len); 192 193 void LogConnectEndEvent(int rv); 194 195 // Record whether ALPN was used, and if so, the negotiated protocol, 196 // in a UMA histogram. 197 void RecordNegotiatedProtocol() const; 198 199 // Returns the net error corresponding to the most recent OpenSSL 200 // error. ssl_error is the output of SSL_get_error. 201 int MapLastOpenSSLError(int ssl_error, 202 const crypto::OpenSSLErrStackTracer& tracer, 203 OpenSSLErrorInfo* info); 204 205 // Wraps SSL_get0_ech_name_override. See documentation for that function. 206 std::string_view GetECHNameOverride() const; 207 208 // Returns true if |cert| is one of the certs in |allowed_bad_certs|. 209 // The expected cert status is written to |cert_status|. |*cert_status| can 210 // be nullptr if user doesn't care about the cert status. This method checks 211 // handshake state, so it may only be called during certificate verification. 212 bool IsAllowedBadCert(X509Certificate* cert, CertStatus* cert_status) const; 213 214 CompletionOnceCallback user_connect_callback_; 215 CompletionOnceCallback user_read_callback_; 216 CompletionOnceCallback user_write_callback_; 217 218 // Used by Read function. 219 scoped_refptr<IOBuffer> user_read_buf_; 220 int user_read_buf_len_; 221 222 // Used by Write function. 223 scoped_refptr<IOBuffer> user_write_buf_; 224 int user_write_buf_len_; 225 bool first_post_handshake_write_ = true; 226 227 // True if we've already handled the result of our attempt to use early data. 228 bool handled_early_data_result_ = false; 229 230 // Used by DoPayloadRead() when attempting to fill the caller's buffer with 231 // as much data as possible without blocking. 232 // If DoPayloadRead() encounters an error after having read some data, stores 233 // the result to return on the *next* call to DoPayloadRead(). A value > 0 234 // indicates there is no pending result, otherwise 0 indicates EOF and < 0 235 // indicates an error. 236 int pending_read_error_; 237 238 // If there is a pending read result, the OpenSSL result code (output of 239 // SSL_get_error) associated with it. 240 int pending_read_ssl_error_ = SSL_ERROR_NONE; 241 242 // If there is a pending read result, the OpenSSLErrorInfo associated with it. 243 OpenSSLErrorInfo pending_read_error_info_; 244 245 // Set when Connect finishes. 246 scoped_refptr<X509Certificate> server_cert_; 247 CertVerifyResult server_cert_verify_result_; 248 bool completed_connect_ = false; 249 250 // Set when Read() or Write() successfully reads or writes data to or from the 251 // network. 252 bool was_ever_used_ = false; 253 254 const raw_ptr<SSLClientContext> context_; 255 256 std::unique_ptr<CertVerifier::Request> cert_verifier_request_; 257 258 // Result from Cert Verifier. 259 int cert_verification_result_; 260 261 // OpenSSL stuff 262 bssl::UniquePtr<SSL> ssl_; 263 264 std::unique_ptr<StreamSocket> stream_socket_; 265 std::unique_ptr<SocketBIOAdapter> transport_adapter_; 266 const HostPortPair host_and_port_; 267 SSLConfig ssl_config_; 268 269 enum State { 270 STATE_NONE, 271 STATE_HANDSHAKE, 272 STATE_HANDSHAKE_COMPLETE, 273 }; 274 State next_handshake_state_ = STATE_NONE; 275 276 // True if we are currently confirming the handshake. 277 bool in_confirm_handshake_ = false; 278 279 // True if the post-handshake SSL_peek has completed. 280 bool peek_complete_ = false; 281 282 // True if the socket has been disconnected. 283 bool disconnected_ = false; 284 285 // True if certificate verification used an ECH name override. 286 bool used_ech_name_override_ = false; 287 288 NextProto negotiated_protocol_ = kProtoUnknown; 289 290 // Set to true if a CertificateRequest was received. 291 bool certificate_requested_ = false; 292 293 int signature_result_; 294 std::vector<uint8_t> signature_; 295 296 // True if PKP is bypassed due to a local trust anchor. 297 bool pkp_bypassed_ = false; 298 299 // True if there was a certificate error which should be treated as fatal, 300 // and false otherwise. 301 bool is_fatal_cert_error_ = false; 302 303 // True if the socket should respond to client certificate requests with 304 // |client_cert_| and |client_private_key_|, which may be null to continue 305 // with no certificate. If false, client certificate requests will result in 306 // ERR_SSL_CLIENT_AUTH_CERT_NEEDED. 307 bool send_client_cert_; 308 scoped_refptr<X509Certificate> client_cert_; 309 scoped_refptr<SSLPrivateKey> client_private_key_; 310 311 NetLogWithSource net_log_; 312 base::WeakPtrFactory<SSLClientSocketImpl> weak_factory_{this}; 313 }; 314 315 } // namespace net 316 317 #endif // NET_SOCKET_SSL_CLIENT_SOCKET_IMPL_H_ 318