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