xref: /aosp_15_r20/external/cronet/net/third_party/quiche/src/quiche/quic/core/tls_server_handshaker.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright (c) 2017 The Chromium Authors. All rights reserved.
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 QUICHE_QUIC_CORE_TLS_SERVER_HANDSHAKER_H_
6 #define QUICHE_QUIC_CORE_TLS_SERVER_HANDSHAKER_H_
7 
8 #include <cstddef>
9 #include <cstdint>
10 #include <memory>
11 #include <optional>
12 #include <string>
13 #include <utility>
14 #include <vector>
15 
16 #include "absl/strings/string_view.h"
17 #include "absl/types/span.h"
18 #include "openssl/base.h"
19 #include "openssl/ssl.h"
20 #include "quiche/quic/core/crypto/crypto_handshake.h"
21 #include "quiche/quic/core/crypto/crypto_message_parser.h"
22 #include "quiche/quic/core/crypto/proof_source.h"
23 #include "quiche/quic/core/crypto/proof_verifier.h"
24 #include "quiche/quic/core/crypto/quic_crypto_server_config.h"
25 #include "quiche/quic/core/crypto/quic_decrypter.h"
26 #include "quiche/quic/core/crypto/quic_encrypter.h"
27 #include "quiche/quic/core/crypto/tls_connection.h"
28 #include "quiche/quic/core/crypto/tls_server_connection.h"
29 #include "quiche/quic/core/crypto/transport_parameters.h"
30 #include "quiche/quic/core/quic_config.h"
31 #include "quiche/quic/core/quic_connection_context.h"
32 #include "quiche/quic/core/quic_connection_id.h"
33 #include "quiche/quic/core/quic_connection_stats.h"
34 #include "quiche/quic/core/quic_crypto_server_stream_base.h"
35 #include "quiche/quic/core/quic_crypto_stream.h"
36 #include "quiche/quic/core/quic_error_codes.h"
37 #include "quiche/quic/core/quic_time.h"
38 #include "quiche/quic/core/quic_time_accumulator.h"
39 #include "quiche/quic/core/quic_types.h"
40 #include "quiche/quic/core/tls_handshaker.h"
41 #include "quiche/quic/platform/api/quic_socket_address.h"
42 
43 namespace quic {
44 
45 // An implementation of QuicCryptoServerStreamBase which uses
46 // TLS 1.3 for the crypto handshake protocol.
47 class QUICHE_EXPORT TlsServerHandshaker : public TlsHandshaker,
48                                           public TlsServerConnection::Delegate,
49                                           public ProofSourceHandleCallback,
50                                           public QuicCryptoServerStreamBase {
51  public:
52   // |crypto_config| must outlive TlsServerHandshaker.
53   TlsServerHandshaker(QuicSession* session,
54                       const QuicCryptoServerConfig* crypto_config);
55   TlsServerHandshaker(const TlsServerHandshaker&) = delete;
56   TlsServerHandshaker& operator=(const TlsServerHandshaker&) = delete;
57 
58   ~TlsServerHandshaker() override;
59 
60   // From QuicCryptoServerStreamBase
61   void CancelOutstandingCallbacks() override;
62   bool GetBase64SHA256ClientChannelID(std::string* output) const override;
63   void SendServerConfigUpdate(
64       const CachedNetworkParameters* cached_network_params) override;
65   bool DisableResumption() override;
66   bool IsZeroRtt() const override;
67   bool IsResumption() const override;
68   bool ResumptionAttempted() const override;
69   // Must be called after EarlySelectCertCallback is started.
70   bool EarlyDataAttempted() const override;
71   int NumServerConfigUpdateMessagesSent() const override;
72   const CachedNetworkParameters* PreviousCachedNetworkParams() const override;
73   void SetPreviousCachedNetworkParams(
74       CachedNetworkParameters cached_network_params) override;
75   void OnPacketDecrypted(EncryptionLevel level) override;
OnOneRttPacketAcknowledged()76   void OnOneRttPacketAcknowledged() override {}
OnHandshakePacketSent()77   void OnHandshakePacketSent() override {}
78   void OnConnectionClosed(QuicErrorCode error,
79                           ConnectionCloseSource source) override;
80   void OnHandshakeDoneReceived() override;
81   std::string GetAddressToken(
82       const CachedNetworkParameters* cached_network_params) const override;
83   bool ValidateAddressToken(absl::string_view token) const override;
84   void OnNewTokenReceived(absl::string_view token) override;
85   bool ShouldSendExpectCTHeader() const override;
86   bool DidCertMatchSni() const override;
87   const ProofSource::Details* ProofSourceDetails() const override;
88   bool ExportKeyingMaterial(absl::string_view label, absl::string_view context,
89                             size_t result_len, std::string* result) override;
90   SSL* GetSsl() const override;
91   bool IsCryptoFrameExpectedForEncryptionLevel(
92       EncryptionLevel level) const override;
93   EncryptionLevel GetEncryptionLevelToSendCryptoDataOfSpace(
94       PacketNumberSpace space) const override;
95 
96   // From QuicCryptoServerStreamBase and TlsHandshaker
97   ssl_early_data_reason_t EarlyDataReason() const override;
98   bool encryption_established() const override;
99   bool one_rtt_keys_available() const override;
100   const QuicCryptoNegotiatedParameters& crypto_negotiated_params()
101       const override;
102   CryptoMessageParser* crypto_message_parser() override;
103   HandshakeState GetHandshakeState() const override;
104   void SetServerApplicationStateForResumption(
105       std::unique_ptr<ApplicationState> state) override;
106   size_t BufferSizeLimitForLevel(EncryptionLevel level) const override;
107   std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter()
108       override;
109   std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override;
110   void SetWriteSecret(EncryptionLevel level, const SSL_CIPHER* cipher,
111                       absl::Span<const uint8_t> write_secret) override;
112 
113   // Called with normalized SNI hostname as |hostname|.  Return value will be
114   // sent in an ACCEPT_CH frame in the TLS ALPS extension, unless empty.
115   virtual std::string GetAcceptChValueForHostname(
116       const std::string& hostname) const;
117 
118   // Returns whether server uses new ALPS codepoint to negotiate application
119   // settings. If client sends new ALPS codepoint in ClientHello, return true.
120   bool UseAlpsNewCodepoint() const;
121 
122   // Get the ClientCertMode that is currently in effect on this handshaker.
client_cert_mode()123   ClientCertMode client_cert_mode() const {
124     return tls_connection_.ssl_config().client_cert_mode;
125   }
126 
127  protected:
128   // Override for tracing.
129   void InfoCallback(int type, int value) override;
130 
131   // Creates a proof source handle for selecting cert and computing signature.
132   virtual std::unique_ptr<ProofSourceHandle> MaybeCreateProofSourceHandle();
133 
134   // Hook to allow the server to override parts of the QuicConfig based on SNI
135   // before we generate transport parameters.
136   virtual void OverrideQuicConfigDefaults(QuicConfig* config);
137 
138   virtual bool ValidateHostname(const std::string& hostname) const;
139 
tls_connection()140   const TlsConnection* tls_connection() const override {
141     return &tls_connection_;
142   }
143 
144   // Returns true if the handshake should continue. If false is returned, the
145   // caller should fail the handshake.
ProcessAdditionalTransportParameters(const TransportParameters &)146   virtual bool ProcessAdditionalTransportParameters(
147       const TransportParameters& /*params*/) {
148     return true;
149   }
150 
151   // Called when a potentially async operation is done and the done callback
152   // needs to advance the handshake.
153   void AdvanceHandshakeFromCallback();
154 
155   // TlsHandshaker implementation:
156   void FinishHandshake() override;
ProcessPostHandshakeMessage()157   void ProcessPostHandshakeMessage() override {}
158   QuicAsyncStatus VerifyCertChain(
159       const std::vector<std::string>& certs, std::string* error_details,
160       std::unique_ptr<ProofVerifyDetails>* details, uint8_t* out_alert,
161       std::unique_ptr<ProofVerifierCallback> callback) override;
162   void OnProofVerifyDetailsAvailable(
163       const ProofVerifyDetails& verify_details) override;
164 
165   // TlsServerConnection::Delegate implementation:
166   // Used to select certificates and process transport parameters.
167   ssl_select_cert_result_t EarlySelectCertCallback(
168       const SSL_CLIENT_HELLO* client_hello) override;
169   int TlsExtServernameCallback(int* out_alert) override;
170   int SelectAlpn(const uint8_t** out, uint8_t* out_len, const uint8_t* in,
171                  unsigned in_len) override;
172   ssl_private_key_result_t PrivateKeySign(uint8_t* out, size_t* out_len,
173                                           size_t max_out, uint16_t sig_alg,
174                                           absl::string_view in) override;
175   ssl_private_key_result_t PrivateKeyComplete(uint8_t* out, size_t* out_len,
176                                               size_t max_out) override;
177   size_t SessionTicketMaxOverhead() override;
178   int SessionTicketSeal(uint8_t* out, size_t* out_len, size_t max_out_len,
179                         absl::string_view in) override;
180   ssl_ticket_aead_result_t SessionTicketOpen(uint8_t* out, size_t* out_len,
181                                              size_t max_out_len,
182                                              absl::string_view in) override;
183   // Called when ticket_decryption_callback_ is done to determine a final
184   // decryption result.
185   ssl_ticket_aead_result_t FinalizeSessionTicketOpen(uint8_t* out,
186                                                      size_t* out_len,
187                                                      size_t max_out_len);
ConnectionDelegate()188   TlsConnection::Delegate* ConnectionDelegate() override { return this; }
189 
190   // The status of cert selection. nullopt means it hasn't started.
select_cert_status()191   const std::optional<QuicAsyncStatus>& select_cert_status() const {
192     return select_cert_status_;
193   }
194   // Whether |cert_verify_sig_| contains a valid signature.
195   // NOTE: BoringSSL queries the result of a async signature operation using
196   // PrivateKeyComplete(), a successful PrivateKeyComplete() will clear the
197   // content of |cert_verify_sig_|, this function should not be called after
198   // that.
199   bool HasValidSignature(size_t max_signature_size) const;
200 
201   // ProofSourceHandleCallback implementation:
202   void OnSelectCertificateDone(bool ok, bool is_sync, SSLConfig ssl_config,
203                                absl::string_view ticket_encryption_key,
204                                bool cert_matched_sni) override;
205 
206   void OnComputeSignatureDone(
207       bool ok, bool is_sync, std::string signature,
208       std::unique_ptr<ProofSource::Details> details) override;
209 
set_encryption_established(bool encryption_established)210   void set_encryption_established(bool encryption_established) {
211     encryption_established_ = encryption_established;
212   }
213 
214   bool WillNotCallComputeSignature() const override;
215 
SetIgnoreTicketOpen(bool value)216   void SetIgnoreTicketOpen(bool value) { ignore_ticket_open_ = value; }
217 
218  private:
219   class QUICHE_EXPORT DecryptCallback : public ProofSource::DecryptCallback {
220    public:
221     explicit DecryptCallback(TlsServerHandshaker* handshaker);
222     void Run(std::vector<uint8_t> plaintext) override;
223 
224     // If called, Cancel causes the pending callback to be a no-op.
225     void Cancel();
226 
227     // Return true if either
228     // - Cancel() has been called.
229     // - Run() has been called, or is in the middle of it.
IsDone()230     bool IsDone() const { return handshaker_ == nullptr; }
231 
232    private:
233     TlsServerHandshaker* handshaker_;
234   };
235 
236   // DefaultProofSourceHandle delegates all operations to the shared proof
237   // source.
238   class QUICHE_EXPORT DefaultProofSourceHandle : public ProofSourceHandle {
239    public:
240     DefaultProofSourceHandle(TlsServerHandshaker* handshaker,
241                              ProofSource* proof_source);
242 
243     ~DefaultProofSourceHandle() override;
244 
245     // Close the handle. Cancel the pending signature operation, if any.
246     void CloseHandle() override;
247 
248     // Delegates to proof_source_->GetCertChain.
249     // Returns QUIC_SUCCESS or QUIC_FAILURE. Never returns QUIC_PENDING.
250     QuicAsyncStatus SelectCertificate(
251         const QuicSocketAddress& server_address,
252         const QuicSocketAddress& client_address,
253         const QuicConnectionId& original_connection_id,
254         absl::string_view ssl_capabilities, const std::string& hostname,
255         absl::string_view client_hello, const std::string& alpn,
256         std::optional<std::string> alps,
257         const std::vector<uint8_t>& quic_transport_params,
258         const std::optional<std::vector<uint8_t>>& early_data_context,
259         const QuicSSLConfig& ssl_config) override;
260 
261     // Delegates to proof_source_->ComputeTlsSignature.
262     // Returns QUIC_SUCCESS, QUIC_FAILURE or QUIC_PENDING.
263     QuicAsyncStatus ComputeSignature(const QuicSocketAddress& server_address,
264                                      const QuicSocketAddress& client_address,
265                                      const std::string& hostname,
266                                      uint16_t signature_algorithm,
267                                      absl::string_view in,
268                                      size_t max_signature_size) override;
269 
270    protected:
callback()271     ProofSourceHandleCallback* callback() override { return handshaker_; }
272 
273    private:
274     class QUICHE_EXPORT DefaultSignatureCallback
275         : public ProofSource::SignatureCallback {
276      public:
DefaultSignatureCallback(DefaultProofSourceHandle * handle)277       explicit DefaultSignatureCallback(DefaultProofSourceHandle* handle)
278           : handle_(handle) {}
279 
Run(bool ok,std::string signature,std::unique_ptr<ProofSource::Details> details)280       void Run(bool ok, std::string signature,
281                std::unique_ptr<ProofSource::Details> details) override {
282         if (handle_ == nullptr) {
283           // Operation has been canceled, or Run has been called.
284           return;
285         }
286 
287         DefaultProofSourceHandle* handle = handle_;
288         handle_ = nullptr;
289 
290         handle->signature_callback_ = nullptr;
291         if (handle->handshaker_ != nullptr) {
292           handle->handshaker_->OnComputeSignatureDone(
293               ok, is_sync_, std::move(signature), std::move(details));
294         }
295       }
296 
297       // If called, Cancel causes the pending callback to be a no-op.
Cancel()298       void Cancel() { handle_ = nullptr; }
299 
set_is_sync(bool is_sync)300       void set_is_sync(bool is_sync) { is_sync_ = is_sync; }
301 
302      private:
303       DefaultProofSourceHandle* handle_;
304       // Set to false if handle_->ComputeSignature returns QUIC_PENDING.
305       bool is_sync_ = true;
306     };
307 
308     // Not nullptr on construction. Set to nullptr when cancelled.
309     TlsServerHandshaker* handshaker_;  // Not owned.
310     ProofSource* proof_source_;        // Not owned.
311     DefaultSignatureCallback* signature_callback_ = nullptr;
312   };
313 
314   struct QUICHE_EXPORT SetTransportParametersResult {
315     bool success = false;
316     // Empty vector if QUIC transport params are not set successfully.
317     std::vector<uint8_t> quic_transport_params;
318     // std::nullopt if there is no application state to begin with.
319     // Empty vector if application state is not set successfully.
320     std::optional<std::vector<uint8_t>> early_data_context;
321   };
322 
323   SetTransportParametersResult SetTransportParameters();
324   bool ProcessTransportParameters(const SSL_CLIENT_HELLO* client_hello,
325                                   std::string* error_details);
326   // Compares |serialized_params| with |server_params_|.
327   // Returns true if handshaker serialization is equivalent.
328   bool TransportParametersMatch(
329       absl::Span<const uint8_t> serialized_params) const;
330 
331   struct QUICHE_EXPORT SetApplicationSettingsResult {
332     bool success = false;
333     // TODO(b/239676439): Change type to std::optional<std::string> and make
334     // sure SetApplicationSettings() returns nullopt if no ALPS data.
335     std::string alps_buffer;
336   };
337   SetApplicationSettingsResult SetApplicationSettings(absl::string_view alpn);
338 
connection_stats()339   QuicConnectionStats& connection_stats() {
340     return session()->connection()->mutable_stats();
341   }
now()342   QuicTime now() const { return session()->GetClock()->Now(); }
343 
connection_context()344   QuicConnectionContext* connection_context() {
345     return session()->connection()->context();
346   }
347 
348   std::unique_ptr<ProofSourceHandle> proof_source_handle_;
349   ProofSource* proof_source_;
350 
351   // State to handle potentially asynchronous session ticket decryption.
352   // |ticket_decryption_callback_| points to the non-owned callback that was
353   // passed to ProofSource::TicketCrypter::Decrypt but hasn't finished running
354   // yet.
355   std::shared_ptr<DecryptCallback> ticket_decryption_callback_;
356   // |decrypted_session_ticket_| contains the decrypted session ticket after the
357   // callback has run but before it is passed to BoringSSL.
358   std::vector<uint8_t> decrypted_session_ticket_;
359   // |ticket_received_| tracks whether we received a resumption ticket from the
360   // client. It does not matter whether we were able to decrypt said ticket or
361   // if we actually resumed a session with it - the presence of this ticket
362   // indicates that the client attempted a resumption.
363   bool ticket_received_ = false;
364 
365   // True if the "early_data" extension is in the client hello.
366   bool early_data_attempted_ = false;
367 
368   // Force SessionTicketOpen to return ssl_ticket_aead_ignore_ticket if called.
369   bool ignore_ticket_open_ = false;
370 
371   // True if new ALPS codepoint in the ClientHello.
372   bool alps_new_codepoint_received_ = false;
373 
374   // nullopt means select cert hasn't started.
375   std::optional<QuicAsyncStatus> select_cert_status_;
376 
377   std::string cert_verify_sig_;
378   std::unique_ptr<ProofSource::Details> proof_source_details_;
379 
380   // Count the duration of the current async operation, if any.
381   std::optional<QuicTimeAccumulator> async_op_timer_;
382 
383   std::unique_ptr<ApplicationState> application_state_;
384 
385   // Pre-shared key used during the handshake.
386   std::string pre_shared_key_;
387 
388   // (optional) Key to use for encrypting TLS resumption tickets.
389   std::string ticket_encryption_key_;
390 
391   HandshakeState state_ = HANDSHAKE_START;
392   bool encryption_established_ = false;
393   bool valid_alpn_received_ = false;
394   bool can_disable_resumption_ = true;
395   quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters>
396       crypto_negotiated_params_;
397   TlsServerConnection tls_connection_;
398   const QuicCryptoServerConfig* crypto_config_;  // Unowned.
399   // The last received CachedNetworkParameters from a validated address token.
400   mutable std::unique_ptr<CachedNetworkParameters>
401       last_received_cached_network_params_;
402 
403   bool cert_matched_sni_ = false;
404   TransportParameters server_params_;
405 };
406 
407 }  // namespace quic
408 
409 #endif  // QUICHE_QUIC_CORE_TLS_SERVER_HANDSHAKER_H_
410