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