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