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