• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2016, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14 
15 #include <openssl/ssl.h>
16 
17 #include <assert.h>
18 #include <string.h>
19 
20 #include <algorithm>
21 #include <tuple>
22 
23 #include <openssl/aead.h>
24 #include <openssl/bytestring.h>
25 #include <openssl/digest.h>
26 #include <openssl/err.h>
27 #include <openssl/hpke.h>
28 #include <openssl/mem.h>
29 #include <openssl/rand.h>
30 #include <openssl/stack.h>
31 
32 #include "../crypto/internal.h"
33 #include "internal.h"
34 
35 
36 BSSL_NAMESPACE_BEGIN
37 
38 static const uint8_t kZeroes[EVP_MAX_MD_SIZE] = {0};
39 
40 // Allow a minute of ticket age skew in either direction. This covers
41 // transmission delays in ClientHello and NewSessionTicket, as well as
42 // drift between client and server clock rate since the ticket was issued.
43 // See RFC 8446, section 8.3.
44 static const int32_t kMaxTicketAgeSkewSeconds = 60;
45 
resolve_ecdhe_secret(SSL_HANDSHAKE * hs,const SSL_CLIENT_HELLO * client_hello)46 static bool resolve_ecdhe_secret(SSL_HANDSHAKE *hs,
47                                  const SSL_CLIENT_HELLO *client_hello) {
48   SSL *const ssl = hs->ssl;
49   const uint16_t group_id = hs->new_session->group_id;
50 
51   bool found_key_share;
52   Span<const uint8_t> peer_key;
53   uint8_t alert = SSL_AD_DECODE_ERROR;
54   if (!ssl_ext_key_share_parse_clienthello(hs, &found_key_share, &peer_key,
55                                            &alert, client_hello)) {
56     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
57     return false;
58   }
59 
60   if (!found_key_share) {
61     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
62     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
63     return false;
64   }
65 
66   Array<uint8_t> secret;
67   SSL_HANDSHAKE_HINTS *const hints = hs->hints.get();
68   if (hints && !hs->hints_requested && hints->key_share_group_id == group_id &&
69       !hints->key_share_secret.empty()) {
70     // Copy the key_share secret from hints.
71     if (!hs->key_share_ciphertext.CopyFrom(hints->key_share_ciphertext) ||
72         !secret.CopyFrom(hints->key_share_secret)) {
73       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
74       return false;
75     }
76   } else {
77     ScopedCBB ciphertext;
78     UniquePtr<SSLKeyShare> key_share = SSLKeyShare::Create(group_id);
79     if (!key_share ||  //
80         !CBB_init(ciphertext.get(), 32) ||
81         !key_share->Encap(ciphertext.get(), &secret, &alert, peer_key) ||
82         !CBBFinishArray(ciphertext.get(), &hs->key_share_ciphertext)) {
83       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
84       return false;
85     }
86     if (hints && hs->hints_requested) {
87       hints->key_share_group_id = group_id;
88       if (!hints->key_share_ciphertext.CopyFrom(hs->key_share_ciphertext) ||
89           !hints->key_share_secret.CopyFrom(secret)) {
90         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
91         return false;
92       }
93     }
94   }
95 
96   return tls13_advance_key_schedule(hs, secret);
97 }
98 
ssl_ext_supported_versions_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)99 static int ssl_ext_supported_versions_add_serverhello(SSL_HANDSHAKE *hs,
100                                                       CBB *out) {
101   CBB contents;
102   if (!CBB_add_u16(out, TLSEXT_TYPE_supported_versions) ||  //
103       !CBB_add_u16_length_prefixed(out, &contents) ||       //
104       !CBB_add_u16(&contents, hs->ssl->s3->version) ||      //
105       !CBB_flush(out)) {
106     return 0;
107   }
108 
109   return 1;
110 }
111 
choose_tls13_cipher(const SSL * ssl,const SSL_CLIENT_HELLO * client_hello)112 static const SSL_CIPHER *choose_tls13_cipher(
113     const SSL *ssl, const SSL_CLIENT_HELLO *client_hello) {
114   CBS cipher_suites;
115   CBS_init(&cipher_suites, client_hello->cipher_suites,
116            client_hello->cipher_suites_len);
117 
118   const uint16_t version = ssl_protocol_version(ssl);
119 
120   return ssl_choose_tls13_cipher(cipher_suites,
121                                  ssl->config->aes_hw_override
122                                      ? ssl->config->aes_hw_override_value
123                                      : EVP_has_aes_hardware(),
124                                  version, ssl->config->tls13_cipher_policy);
125 }
126 
add_new_session_tickets(SSL_HANDSHAKE * hs,bool * out_sent_tickets)127 static bool add_new_session_tickets(SSL_HANDSHAKE *hs, bool *out_sent_tickets) {
128   SSL *const ssl = hs->ssl;
129   if (  // If the client doesn't accept resumption with PSK_DHE_KE, don't send a
130         // session ticket.
131       !hs->accept_psk_mode ||
132       // We only implement stateless resumption in TLS 1.3, so skip sending
133       // tickets if disabled.
134       (SSL_get_options(ssl) & SSL_OP_NO_TICKET)) {
135     *out_sent_tickets = false;
136     return true;
137   }
138 
139   // Rebase the session timestamp so that it is measured from ticket
140   // issuance.
141   ssl_session_rebase_time(ssl, hs->new_session.get());
142 
143   assert(ssl->session_ctx->num_tickets <= kMaxTickets);
144   bool sent_tickets = false;
145   for (size_t i = 0; i < ssl->session_ctx->num_tickets; i++) {
146     UniquePtr<SSL_SESSION> session(
147         SSL_SESSION_dup(hs->new_session.get(), SSL_SESSION_INCLUDE_NONAUTH));
148     if (!session) {
149       return false;
150     }
151 
152     if (!RAND_bytes((uint8_t *)&session->ticket_age_add, 4)) {
153       return false;
154     }
155     session->ticket_age_add_valid = true;
156     // TODO(crbug.com/42290594): Remove the SSL_is_dtls check once we support
157     // 0-RTT for DTLS 1.3.
158     bool enable_early_data =
159         ssl->enable_early_data &&
160         (!ssl->quic_method || !ssl->config->quic_early_data_context.empty()) &&
161         !SSL_is_dtls(ssl);
162     if (enable_early_data) {
163       // QUIC does not use the max_early_data_size parameter and always sets it
164       // to a fixed value. See RFC 9001, section 4.6.1.
165       session->ticket_max_early_data =
166           ssl->quic_method != nullptr ? 0xffffffff : kMaxEarlyDataAccepted;
167     }
168 
169     static_assert(kMaxTickets < 256, "Too many tickets");
170     assert(i < 256);
171     uint8_t nonce[] = {static_cast<uint8_t>(i)};
172 
173     ScopedCBB cbb;
174     CBB body, nonce_cbb, ticket, extensions;
175     if (!ssl->method->init_message(ssl, cbb.get(), &body,
176                                    SSL3_MT_NEW_SESSION_TICKET) ||
177         !CBB_add_u32(&body, session->timeout) ||
178         !CBB_add_u32(&body, session->ticket_age_add) ||
179         !CBB_add_u8_length_prefixed(&body, &nonce_cbb) ||
180         !CBB_add_bytes(&nonce_cbb, nonce, sizeof(nonce)) ||
181         !tls13_derive_session_psk(session.get(), nonce, SSL_is_dtls(ssl)) ||
182         !CBB_add_u16_length_prefixed(&body, &ticket) ||
183         !ssl_encrypt_ticket(hs, &ticket, session.get())) {
184       return false;
185     }
186 
187     if (CBB_len(&ticket) == 0) {
188       // The caller decided not to encrypt a ticket. Skip the message.
189       continue;
190     }
191 
192     if (!CBB_add_u16_length_prefixed(&body, &extensions)) {
193       return false;
194     }
195 
196     if (enable_early_data) {
197       CBB early_data;
198       if (!CBB_add_u16(&extensions, TLSEXT_TYPE_early_data) ||
199           !CBB_add_u16_length_prefixed(&extensions, &early_data) ||
200           !CBB_add_u32(&early_data, session->ticket_max_early_data) ||
201           !CBB_flush(&extensions)) {
202         return false;
203       }
204     }
205 
206     // Add a fake extension. See RFC 8701.
207     if (!CBB_add_u16(&extensions,
208                      ssl_get_grease_value(hs, ssl_grease_ticket_extension)) ||
209         !CBB_add_u16(&extensions, 0 /* empty */)) {
210       return false;
211     }
212 
213     if (!ssl_add_message_cbb(ssl, cbb.get())) {
214       return false;
215     }
216     sent_tickets = true;
217   }
218 
219   *out_sent_tickets = sent_tickets;
220   return true;
221 }
222 
check_credential(SSL_HANDSHAKE * hs,const SSL_CREDENTIAL * cred,uint16_t * out_sigalg)223 static bool check_credential(SSL_HANDSHAKE *hs, const SSL_CREDENTIAL *cred,
224                              uint16_t *out_sigalg) {
225   switch (cred->type) {
226     case SSLCredentialType::kX509:
227       break;
228     case SSLCredentialType::kDelegated:
229       // Check that the peer supports the signature over the delegated
230       // credential.
231       if (std::find(hs->peer_sigalgs.begin(), hs->peer_sigalgs.end(),
232                     cred->dc_algorithm) == hs->peer_sigalgs.end()) {
233         OPENSSL_PUT_ERROR(SSL, SSL_R_NO_COMMON_SIGNATURE_ALGORITHMS);
234         return false;
235       }
236       break;
237   }
238 
239   // All currently supported credentials require a signature. If |cred| is a
240   // delegated credential, this also checks that the peer supports delegated
241   // credentials and matched |dc_cert_verify_algorithm|.
242   if (!tls1_choose_signature_algorithm(hs, cred, out_sigalg)) {
243     return false;
244   }
245   // Use this credential if it either matches a requested issuer,
246   // or does not require issuer matching.
247   return ssl_credential_matches_requested_issuers(hs, cred);
248 }
249 
do_select_parameters(SSL_HANDSHAKE * hs)250 static enum ssl_hs_wait_t do_select_parameters(SSL_HANDSHAKE *hs) {
251   // At this point, most ClientHello extensions have already been processed by
252   // the common handshake logic. Resolve the remaining non-PSK parameters.
253   SSL *const ssl = hs->ssl;
254   SSLMessage msg;
255   SSL_CLIENT_HELLO client_hello;
256   if (!hs->GetClientHello(&msg, &client_hello)) {
257     return ssl_hs_error;
258   }
259 
260   if (ssl->quic_method != nullptr && client_hello.session_id_len > 0) {
261     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_COMPATIBILITY_MODE);
262     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
263     return ssl_hs_error;
264   }
265   // DTLS 1.3 disables compatibility mode, and even if the client advertised a
266   // session ID (for resumption in DTLS 1.2), the server "MUST NOT echo the
267   // 'legacy_session_id' value from the client" (RFC 9147, section 5) as it
268   // would in a TLS 1.3 handshake.
269   if (!SSL_is_dtls(ssl)) {
270     hs->session_id.CopyFrom(
271         MakeConstSpan(client_hello.session_id, client_hello.session_id_len));
272   }
273 
274   Array<SSL_CREDENTIAL *> creds;
275   if (!ssl_get_credential_list(hs, &creds)) {
276     return ssl_hs_error;
277   }
278   if (creds.empty()) {
279     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATE_SET);
280     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
281     return ssl_hs_error;
282   }
283 
284   // Select the credential to use.
285   for (SSL_CREDENTIAL *cred : creds) {
286     ERR_clear_error();
287     uint16_t sigalg;
288     if (check_credential(hs, cred, &sigalg)) {
289       hs->credential = UpRef(cred);
290       hs->signature_algorithm = sigalg;
291       break;
292     }
293   }
294   if (hs->credential == nullptr) {
295     // The error from the last attempt is in the error queue.
296     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
297     return ssl_hs_error;
298   }
299 
300   // Negotiate the cipher suite.
301   hs->new_cipher = choose_tls13_cipher(ssl, &client_hello);
302   if (hs->new_cipher == NULL) {
303     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_CIPHER);
304     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
305     return ssl_hs_error;
306   }
307 
308   // HTTP/2 negotiation depends on the cipher suite, so ALPN negotiation was
309   // deferred. Complete it now.
310   uint8_t alert = SSL_AD_DECODE_ERROR;
311   if (!ssl_negotiate_alpn(hs, &alert, &client_hello)) {
312     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
313     return ssl_hs_error;
314   }
315 
316   // The PRF hash is now known.
317   if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher)) {
318     return ssl_hs_error;
319   }
320 
321   hs->tls13_state = state13_select_session;
322   return ssl_hs_ok;
323 }
324 
select_session(SSL_HANDSHAKE * hs,uint8_t * out_alert,UniquePtr<SSL_SESSION> * out_session,int32_t * out_ticket_age_skew,bool * out_offered_ticket,const SSLMessage & msg,const SSL_CLIENT_HELLO * client_hello)325 static enum ssl_ticket_aead_result_t select_session(
326     SSL_HANDSHAKE *hs, uint8_t *out_alert, UniquePtr<SSL_SESSION> *out_session,
327     int32_t *out_ticket_age_skew, bool *out_offered_ticket,
328     const SSLMessage &msg, const SSL_CLIENT_HELLO *client_hello) {
329   SSL *const ssl = hs->ssl;
330   *out_session = nullptr;
331 
332   CBS pre_shared_key;
333   *out_offered_ticket = ssl_client_hello_get_extension(
334       client_hello, &pre_shared_key, TLSEXT_TYPE_pre_shared_key);
335   if (!*out_offered_ticket) {
336     return ssl_ticket_aead_ignore_ticket;
337   }
338 
339   // Per RFC 8446, section 4.2.9, servers MUST abort the handshake if the client
340   // sends pre_shared_key without psk_key_exchange_modes.
341   CBS unused;
342   if (!ssl_client_hello_get_extension(client_hello, &unused,
343                                       TLSEXT_TYPE_psk_key_exchange_modes)) {
344     *out_alert = SSL_AD_MISSING_EXTENSION;
345     OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
346     return ssl_ticket_aead_error;
347   }
348 
349   CBS ticket, binders;
350   uint32_t client_ticket_age;
351   if (!ssl_ext_pre_shared_key_parse_clienthello(
352           hs, &ticket, &binders, &client_ticket_age, out_alert, client_hello,
353           &pre_shared_key)) {
354     return ssl_ticket_aead_error;
355   }
356 
357   // If the peer did not offer psk_dhe, ignore the resumption.
358   if (!hs->accept_psk_mode) {
359     return ssl_ticket_aead_ignore_ticket;
360   }
361 
362   // TLS 1.3 session tickets are renewed separately as part of the
363   // NewSessionTicket.
364   bool unused_renew;
365   UniquePtr<SSL_SESSION> session;
366   enum ssl_ticket_aead_result_t ret =
367       ssl_process_ticket(hs, &session, &unused_renew, ticket, {});
368   switch (ret) {
369     case ssl_ticket_aead_success:
370       break;
371     case ssl_ticket_aead_error:
372       *out_alert = SSL_AD_INTERNAL_ERROR;
373       return ret;
374     default:
375       return ret;
376   }
377 
378   if (!ssl_session_is_resumable(hs, session.get()) ||
379       // Historically, some TLS 1.3 tickets were missing ticket_age_add.
380       !session->ticket_age_add_valid) {
381     return ssl_ticket_aead_ignore_ticket;
382   }
383 
384   // Recover the client ticket age and convert to seconds.
385   client_ticket_age -= session->ticket_age_add;
386   client_ticket_age /= 1000;
387 
388   OPENSSL_timeval now = ssl_ctx_get_current_time(ssl->ctx.get());
389 
390   // Compute the server ticket age in seconds.
391   assert(now.tv_sec >= session->time);
392   uint64_t server_ticket_age = now.tv_sec - session->time;
393 
394   // To avoid overflowing |hs->ticket_age_skew|, we will not resume
395   // 68-year-old sessions.
396   if (server_ticket_age > INT32_MAX) {
397     return ssl_ticket_aead_ignore_ticket;
398   }
399 
400   *out_ticket_age_skew = static_cast<int32_t>(client_ticket_age) -
401                          static_cast<int32_t>(server_ticket_age);
402 
403   // Check the PSK binder.
404   if (!tls13_verify_psk_binder(hs, session.get(), msg, &binders)) {
405     *out_alert = SSL_AD_DECRYPT_ERROR;
406     return ssl_ticket_aead_error;
407   }
408 
409   *out_session = std::move(session);
410   return ssl_ticket_aead_success;
411 }
412 
quic_ticket_compatible(const SSL_SESSION * session,const SSL_CONFIG * config)413 static bool quic_ticket_compatible(const SSL_SESSION *session,
414                                    const SSL_CONFIG *config) {
415   if (!session->is_quic) {
416     return true;
417   }
418 
419   if (session->quic_early_data_context.empty() ||
420       config->quic_early_data_context.size() !=
421           session->quic_early_data_context.size() ||
422       CRYPTO_memcmp(config->quic_early_data_context.data(),
423                     session->quic_early_data_context.data(),
424                     session->quic_early_data_context.size()) != 0) {
425     return false;
426   }
427   return true;
428 }
429 
do_select_session(SSL_HANDSHAKE * hs)430 static enum ssl_hs_wait_t do_select_session(SSL_HANDSHAKE *hs) {
431   SSL *const ssl = hs->ssl;
432   SSLMessage msg;
433   SSL_CLIENT_HELLO client_hello;
434   if (!hs->GetClientHello(&msg, &client_hello)) {
435     return ssl_hs_error;
436   }
437 
438   uint8_t alert = SSL_AD_DECODE_ERROR;
439   UniquePtr<SSL_SESSION> session;
440   bool offered_ticket = false;
441   switch (select_session(hs, &alert, &session, &ssl->s3->ticket_age_skew,
442                          &offered_ticket, msg, &client_hello)) {
443     case ssl_ticket_aead_ignore_ticket:
444       assert(!session);
445       if (!ssl_get_new_session(hs)) {
446         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
447         return ssl_hs_error;
448       }
449       break;
450 
451     case ssl_ticket_aead_success:
452       // Carry over authentication information from the previous handshake into
453       // a fresh session.
454       hs->new_session =
455           SSL_SESSION_dup(session.get(), SSL_SESSION_DUP_AUTH_ONLY);
456       if (hs->new_session == nullptr) {
457         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
458         return ssl_hs_error;
459       }
460 
461       ssl->s3->session_reused = true;
462       hs->can_release_private_key = true;
463 
464       // Resumption incorporates fresh key material, so refresh the timeout.
465       ssl_session_renew_timeout(ssl, hs->new_session.get(),
466                                 ssl->session_ctx->session_psk_dhe_timeout);
467       break;
468 
469     case ssl_ticket_aead_error:
470       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
471       return ssl_hs_error;
472 
473     case ssl_ticket_aead_retry:
474       hs->tls13_state = state13_select_session;
475       return ssl_hs_pending_ticket;
476   }
477 
478   // Negotiate ALPS now, after ALPN is negotiated and |hs->new_session| is
479   // initialized.
480   if (!ssl_negotiate_alps(hs, &alert, &client_hello)) {
481     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
482     return ssl_hs_error;
483   }
484 
485   // Record connection properties in the new session.
486   hs->new_session->cipher = hs->new_cipher;
487   if (!tls1_get_shared_group(hs, &hs->new_session->group_id)) {
488     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_GROUP);
489     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
490     return ssl_hs_error;
491   }
492 
493   // Determine if we need HelloRetryRequest.
494   bool found_key_share;
495   if (!ssl_ext_key_share_parse_clienthello(hs, &found_key_share,
496                                            /*out_key_share=*/nullptr, &alert,
497                                            &client_hello)) {
498     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
499     return ssl_hs_error;
500   }
501 
502   // Determine if we're negotiating 0-RTT.
503   if (!ssl->enable_early_data) {
504     ssl->s3->early_data_reason = ssl_early_data_disabled;
505   } else if (!offered_ticket) {
506     ssl->s3->early_data_reason = ssl_early_data_no_session_offered;
507   } else if (!session) {
508     ssl->s3->early_data_reason = ssl_early_data_session_not_resumed;
509   } else if (session->ticket_max_early_data == 0) {
510     ssl->s3->early_data_reason = ssl_early_data_unsupported_for_session;
511   } else if (!hs->early_data_offered) {
512     ssl->s3->early_data_reason = ssl_early_data_peer_declined;
513   } else if (hs->channel_id_negotiated) {
514     // Channel ID is incompatible with 0-RTT.
515     ssl->s3->early_data_reason = ssl_early_data_channel_id;
516   } else if (MakeConstSpan(ssl->s3->alpn_selected) != session->early_alpn) {
517     // The negotiated ALPN must match the one in the ticket.
518     ssl->s3->early_data_reason = ssl_early_data_alpn_mismatch;
519   } else if (hs->new_session->has_application_settings !=
520                  session->has_application_settings ||
521              MakeConstSpan(hs->new_session->local_application_settings) !=
522                  session->local_application_settings) {
523     ssl->s3->early_data_reason = ssl_early_data_alps_mismatch;
524   } else if (ssl->s3->ticket_age_skew < -kMaxTicketAgeSkewSeconds ||
525              kMaxTicketAgeSkewSeconds < ssl->s3->ticket_age_skew) {
526     ssl->s3->early_data_reason = ssl_early_data_ticket_age_skew;
527   } else if (!quic_ticket_compatible(session.get(), hs->config)) {
528     ssl->s3->early_data_reason = ssl_early_data_quic_parameter_mismatch;
529   } else if (!found_key_share) {
530     ssl->s3->early_data_reason = ssl_early_data_hello_retry_request;
531   } else {
532     // |ssl_session_is_resumable| forbids cross-cipher resumptions even if the
533     // PRF hashes match.
534     assert(hs->new_cipher == session->cipher);
535 
536     ssl->s3->early_data_reason = ssl_early_data_accepted;
537     ssl->s3->early_data_accepted = true;
538   }
539 
540   // Store the ALPN and ALPS values in the session for 0-RTT. Note the peer
541   // applications settings are not generally known until client
542   // EncryptedExtensions.
543   if (!hs->new_session->early_alpn.CopyFrom(ssl->s3->alpn_selected)) {
544     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
545     return ssl_hs_error;
546   }
547 
548   // The peer applications settings are usually received later, in
549   // EncryptedExtensions. But, in 0-RTT handshakes, we carry over the
550   // values from |session|. Do this now, before |session| is discarded.
551   if (ssl->s3->early_data_accepted &&
552       hs->new_session->has_application_settings &&
553       !hs->new_session->peer_application_settings.CopyFrom(
554           session->peer_application_settings)) {
555     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
556     return ssl_hs_error;
557   }
558 
559   // Copy the QUIC early data context to the session.
560   if (ssl->enable_early_data && ssl->quic_method) {
561     if (!hs->new_session->quic_early_data_context.CopyFrom(
562             hs->config->quic_early_data_context)) {
563       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
564       return ssl_hs_error;
565     }
566   }
567 
568   if (ssl->ctx->dos_protection_cb != NULL &&
569       ssl->ctx->dos_protection_cb(&client_hello) == 0) {
570     // Connection rejected for DOS reasons.
571     OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
572     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
573     return ssl_hs_error;
574   }
575 
576   size_t hash_len = EVP_MD_size(
577       ssl_get_handshake_digest(ssl_protocol_version(ssl), hs->new_cipher));
578 
579   // Set up the key schedule and incorporate the PSK into the running secret.
580   if (!tls13_init_key_schedule(hs, ssl->s3->session_reused
581                                        ? MakeConstSpan(hs->new_session->secret)
582                                        : MakeConstSpan(kZeroes, hash_len)) ||
583       !ssl_hash_message(hs, msg)) {
584     return ssl_hs_error;
585   }
586 
587   if (ssl->s3->early_data_accepted) {
588     if (!tls13_derive_early_secret(hs)) {
589       return ssl_hs_error;
590     }
591   } else if (hs->early_data_offered) {
592     ssl->s3->skip_early_data = true;
593   }
594 
595   if (!found_key_share) {
596     ssl->method->next_message(ssl);
597     if (!hs->transcript.UpdateForHelloRetryRequest()) {
598       return ssl_hs_error;
599     }
600     hs->tls13_state = state13_send_hello_retry_request;
601     return ssl_hs_ok;
602   }
603 
604   if (!resolve_ecdhe_secret(hs, &client_hello)) {
605     return ssl_hs_error;
606   }
607 
608   ssl->method->next_message(ssl);
609   hs->ech_client_hello_buf.Reset();
610   hs->tls13_state = state13_send_server_hello;
611   return ssl_hs_ok;
612 }
613 
do_send_hello_retry_request(SSL_HANDSHAKE * hs)614 static enum ssl_hs_wait_t do_send_hello_retry_request(SSL_HANDSHAKE *hs) {
615   SSL *const ssl = hs->ssl;
616   if (hs->hints_requested) {
617     return ssl_hs_hints_ready;
618   }
619 
620   ScopedCBB cbb;
621   CBB body, session_id, extensions;
622   if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_SERVER_HELLO) ||
623       !CBB_add_u16(&body, TLS1_2_VERSION) ||
624       !CBB_add_bytes(&body, kHelloRetryRequest, SSL3_RANDOM_SIZE) ||
625       !CBB_add_u8_length_prefixed(&body, &session_id) ||
626       !CBB_add_bytes(&session_id, hs->session_id.data(),
627                      hs->session_id.size()) ||
628       !CBB_add_u16(&body, SSL_CIPHER_get_protocol_id(hs->new_cipher)) ||
629       !CBB_add_u8(&body, 0 /* no compression */) ||
630       !CBB_add_u16_length_prefixed(&body, &extensions) ||
631       !CBB_add_u16(&extensions, TLSEXT_TYPE_supported_versions) ||
632       !CBB_add_u16(&extensions, 2 /* length */) ||
633       !CBB_add_u16(&extensions, ssl->s3->version) ||
634       !CBB_add_u16(&extensions, TLSEXT_TYPE_key_share) ||
635       !CBB_add_u16(&extensions, 2 /* length */) ||
636       !CBB_add_u16(&extensions, hs->new_session->group_id)) {
637     return ssl_hs_error;
638   }
639   if (hs->ech_is_inner) {
640     // Fill a placeholder for the ECH confirmation value.
641     if (!CBB_add_u16(&extensions, TLSEXT_TYPE_encrypted_client_hello) ||
642         !CBB_add_u16(&extensions, ECH_CONFIRMATION_SIGNAL_LEN) ||
643         !CBB_add_zeros(&extensions, ECH_CONFIRMATION_SIGNAL_LEN)) {
644       return ssl_hs_error;
645     }
646   }
647   Array<uint8_t> hrr;
648   if (!ssl->method->finish_message(ssl, cbb.get(), &hrr)) {
649     return ssl_hs_error;
650   }
651   if (hs->ech_is_inner) {
652     // Now that the message is encoded, fill in the whole value.
653     size_t offset = hrr.size() - ECH_CONFIRMATION_SIGNAL_LEN;
654     if (!ssl_ech_accept_confirmation(
655             hs, MakeSpan(hrr).last(ECH_CONFIRMATION_SIGNAL_LEN),
656             ssl->s3->client_random, hs->transcript, /*is_hrr=*/true, hrr,
657             offset)) {
658       return ssl_hs_error;
659     }
660   }
661 
662   if (!ssl->method->add_message(ssl, std::move(hrr)) ||
663       !ssl->method->add_change_cipher_spec(ssl)) {
664     return ssl_hs_error;
665   }
666 
667   ssl->s3->used_hello_retry_request = true;
668   hs->tls13_state = state13_read_second_client_hello;
669   return ssl_hs_flush;
670 }
671 
do_read_second_client_hello(SSL_HANDSHAKE * hs)672 static enum ssl_hs_wait_t do_read_second_client_hello(SSL_HANDSHAKE *hs) {
673   SSL *const ssl = hs->ssl;
674   SSLMessage msg;
675   if (!ssl->method->get_message(ssl, &msg)) {
676     return ssl_hs_read_message;
677   }
678   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CLIENT_HELLO)) {
679     return ssl_hs_error;
680   }
681   SSL_CLIENT_HELLO client_hello;
682   if (!ssl_client_hello_init(ssl, &client_hello, msg.body)) {
683     OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_PARSE_FAILED);
684     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
685     return ssl_hs_error;
686   }
687 
688   if (ssl->s3->ech_status == ssl_ech_accepted) {
689     // If we previously accepted the ClientHelloInner, the second ClientHello
690     // must contain an outer encrypted_client_hello extension.
691     CBS ech_body;
692     if (!ssl_client_hello_get_extension(&client_hello, &ech_body,
693                                         TLSEXT_TYPE_encrypted_client_hello)) {
694       OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
695       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_MISSING_EXTENSION);
696       return ssl_hs_error;
697     }
698     uint16_t kdf_id, aead_id;
699     uint8_t type, config_id;
700     CBS enc, payload;
701     if (!CBS_get_u8(&ech_body, &type) ||     //
702         type != ECH_CLIENT_OUTER ||          //
703         !CBS_get_u16(&ech_body, &kdf_id) ||  //
704         !CBS_get_u16(&ech_body, &aead_id) ||
705         !CBS_get_u8(&ech_body, &config_id) ||
706         !CBS_get_u16_length_prefixed(&ech_body, &enc) ||
707         !CBS_get_u16_length_prefixed(&ech_body, &payload) ||
708         CBS_len(&ech_body) != 0) {
709       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
710       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
711       return ssl_hs_error;
712     }
713 
714     if (kdf_id != EVP_HPKE_KDF_id(EVP_HPKE_CTX_kdf(hs->ech_hpke_ctx.get())) ||
715         aead_id !=
716             EVP_HPKE_AEAD_id(EVP_HPKE_CTX_aead(hs->ech_hpke_ctx.get())) ||
717         config_id != hs->ech_config_id || CBS_len(&enc) > 0) {
718       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
719       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
720       return ssl_hs_error;
721     }
722 
723     // Decrypt the payload with the HPKE context from the first ClientHello.
724     uint8_t alert = SSL_AD_DECODE_ERROR;
725     bool unused;
726     if (!ssl_client_hello_decrypt(hs, &alert, &unused,
727                                   &hs->ech_client_hello_buf, &client_hello,
728                                   payload)) {
729       // Decryption failure is fatal in the second ClientHello.
730       OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
731       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
732       return ssl_hs_error;
733     }
734 
735     // Reparse |client_hello| from the buffer owned by |hs|.
736     if (!hs->GetClientHello(&msg, &client_hello)) {
737       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
738       return ssl_hs_error;
739     }
740   }
741 
742   // We perform all our negotiation based on the first ClientHello (for
743   // consistency with what |select_certificate_cb| observed), which is in the
744   // transcript, so we can ignore most of this second one.
745   //
746   // We do, however, check the second PSK binder. This covers the client key
747   // share, in case we ever send half-RTT data (we currently do not). It is also
748   // a tricky computation, so we enforce the peer handled it correctly.
749   if (ssl->s3->session_reused) {
750     CBS pre_shared_key;
751     if (!ssl_client_hello_get_extension(&client_hello, &pre_shared_key,
752                                         TLSEXT_TYPE_pre_shared_key)) {
753       OPENSSL_PUT_ERROR(SSL, SSL_R_INCONSISTENT_CLIENT_HELLO);
754       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
755       return ssl_hs_error;
756     }
757 
758     CBS ticket, binders;
759     uint32_t client_ticket_age;
760     uint8_t alert = SSL_AD_DECODE_ERROR;
761     if (!ssl_ext_pre_shared_key_parse_clienthello(
762             hs, &ticket, &binders, &client_ticket_age, &alert, &client_hello,
763             &pre_shared_key)) {
764       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
765       return ssl_hs_error;
766     }
767 
768     // Note it is important that we do not obtain a new |SSL_SESSION| from
769     // |ticket|. We have already selected parameters based on the first
770     // ClientHello (in the transcript) and must not switch partway through.
771     if (!tls13_verify_psk_binder(hs, hs->new_session.get(), msg, &binders)) {
772       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
773       return ssl_hs_error;
774     }
775   }
776 
777   if (!resolve_ecdhe_secret(hs, &client_hello)) {
778     return ssl_hs_error;
779   }
780 
781   if (!ssl_hash_message(hs, msg)) {
782     return ssl_hs_error;
783   }
784 
785   // ClientHello should be the end of the flight.
786   if (ssl->method->has_unprocessed_handshake_data(ssl)) {
787     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
788     OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESS_HANDSHAKE_DATA);
789     return ssl_hs_error;
790   }
791 
792   ssl->method->next_message(ssl);
793   hs->ech_client_hello_buf.Reset();
794   hs->tls13_state = state13_send_server_hello;
795   return ssl_hs_ok;
796 }
797 
do_send_server_hello(SSL_HANDSHAKE * hs)798 static enum ssl_hs_wait_t do_send_server_hello(SSL_HANDSHAKE *hs) {
799   SSL *const ssl = hs->ssl;
800 
801   Span<uint8_t> random(ssl->s3->server_random);
802 
803   SSL_HANDSHAKE_HINTS *const hints = hs->hints.get();
804   if (hints && !hs->hints_requested &&
805       hints->server_random_tls13.size() == random.size()) {
806     OPENSSL_memcpy(random.data(), hints->server_random_tls13.data(),
807                    random.size());
808   } else {
809     RAND_bytes(random.data(), random.size());
810     if (hints && hs->hints_requested &&
811         !hints->server_random_tls13.CopyFrom(random)) {
812       return ssl_hs_error;
813     }
814   }
815 
816   uint16_t server_hello_version = TLS1_2_VERSION;
817   if (SSL_is_dtls(ssl)) {
818     server_hello_version = DTLS1_2_VERSION;
819   }
820   Array<uint8_t> server_hello;
821   ScopedCBB cbb;
822   CBB body, extensions, session_id;
823   if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_SERVER_HELLO) ||
824       !CBB_add_u16(&body, server_hello_version) ||
825       !CBB_add_bytes(&body, ssl->s3->server_random,
826                      sizeof(ssl->s3->server_random)) ||
827       !CBB_add_u8_length_prefixed(&body, &session_id) ||
828       !CBB_add_bytes(&session_id, hs->session_id.data(),
829                      hs->session_id.size()) ||
830       !CBB_add_u16(&body, SSL_CIPHER_get_protocol_id(hs->new_cipher)) ||
831       !CBB_add_u8(&body, 0) ||
832       !CBB_add_u16_length_prefixed(&body, &extensions) ||
833       !ssl_ext_pre_shared_key_add_serverhello(hs, &extensions) ||
834       !ssl_ext_key_share_add_serverhello(hs, &extensions) ||
835       !ssl_ext_supported_versions_add_serverhello(hs, &extensions) ||
836       !ssl->method->finish_message(ssl, cbb.get(), &server_hello)) {
837     return ssl_hs_error;
838   }
839 
840   assert(ssl->s3->ech_status != ssl_ech_accepted || hs->ech_is_inner);
841   if (hs->ech_is_inner) {
842     // Fill in the ECH confirmation signal.
843     const size_t offset = ssl_ech_confirmation_signal_hello_offset(ssl);
844     Span<uint8_t> random_suffix = random.last(ECH_CONFIRMATION_SIGNAL_LEN);
845     if (!ssl_ech_accept_confirmation(hs, random_suffix, ssl->s3->client_random,
846                                      hs->transcript,
847                                      /*is_hrr=*/false, server_hello, offset)) {
848       return ssl_hs_error;
849     }
850 
851     // Update |server_hello|.
852     Span<uint8_t> server_hello_out =
853         MakeSpan(server_hello).subspan(offset, ECH_CONFIRMATION_SIGNAL_LEN);
854     OPENSSL_memcpy(server_hello_out.data(), random_suffix.data(),
855                    ECH_CONFIRMATION_SIGNAL_LEN);
856   }
857 
858   if (!ssl->method->add_message(ssl, std::move(server_hello))) {
859     return ssl_hs_error;
860   }
861 
862   hs->key_share_ciphertext.Reset();  // No longer needed.
863   if (!ssl->s3->used_hello_retry_request &&
864       !ssl->method->add_change_cipher_spec(ssl)) {
865     return ssl_hs_error;
866   }
867 
868   // Derive and enable the handshake traffic secrets.
869   if (!tls13_derive_handshake_secrets(hs) ||
870       !tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_seal,
871                              hs->new_session.get(),
872                              hs->server_handshake_secret)) {
873     return ssl_hs_error;
874   }
875 
876   // Send EncryptedExtensions.
877   if (!ssl->method->init_message(ssl, cbb.get(), &body,
878                                  SSL3_MT_ENCRYPTED_EXTENSIONS) ||
879       !ssl_add_serverhello_tlsext(hs, &body) ||
880       !ssl_add_message_cbb(ssl, cbb.get())) {
881     return ssl_hs_error;
882   }
883 
884   if (!ssl->s3->session_reused) {
885     // Determine whether to request a client certificate.
886     hs->cert_request = !!(hs->config->verify_mode & SSL_VERIFY_PEER);
887     // Only request a certificate if Channel ID isn't negotiated.
888     if ((hs->config->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
889         hs->channel_id_negotiated) {
890       hs->cert_request = false;
891     }
892   }
893 
894   // Send a CertificateRequest, if necessary.
895   if (hs->cert_request) {
896     CBB cert_request_extensions, sigalg_contents, sigalgs_cbb;
897     if (!ssl->method->init_message(ssl, cbb.get(), &body,
898                                    SSL3_MT_CERTIFICATE_REQUEST) ||
899         !CBB_add_u8(&body, 0 /* no certificate_request_context. */) ||
900         !CBB_add_u16_length_prefixed(&body, &cert_request_extensions) ||
901         !CBB_add_u16(&cert_request_extensions,
902                      TLSEXT_TYPE_signature_algorithms) ||
903         !CBB_add_u16_length_prefixed(&cert_request_extensions,
904                                      &sigalg_contents) ||
905         !CBB_add_u16_length_prefixed(&sigalg_contents, &sigalgs_cbb) ||
906         !tls12_add_verify_sigalgs(hs, &sigalgs_cbb)) {
907       return ssl_hs_error;
908     }
909 
910     if (ssl_has_client_CAs(hs->config)) {
911       CBB ca_contents;
912       if (!CBB_add_u16(&cert_request_extensions,
913                        TLSEXT_TYPE_certificate_authorities) ||
914           !CBB_add_u16_length_prefixed(&cert_request_extensions,
915                                        &ca_contents) ||
916           !ssl_add_client_CA_list(hs, &ca_contents) ||
917           !CBB_flush(&cert_request_extensions)) {
918         return ssl_hs_error;
919       }
920     }
921 
922     if (!ssl_add_message_cbb(ssl, cbb.get())) {
923       return ssl_hs_error;
924     }
925   }
926 
927   // Send the server Certificate message, if necessary.
928   if (!ssl->s3->session_reused) {
929     if (!tls13_add_certificate(hs)) {
930       return ssl_hs_error;
931     }
932 
933     hs->tls13_state = state13_send_server_certificate_verify;
934     return ssl_hs_ok;
935   }
936 
937   hs->tls13_state = state13_send_server_finished;
938   return ssl_hs_ok;
939 }
940 
do_send_server_certificate_verify(SSL_HANDSHAKE * hs)941 static enum ssl_hs_wait_t do_send_server_certificate_verify(SSL_HANDSHAKE *hs) {
942   switch (tls13_add_certificate_verify(hs)) {
943     case ssl_private_key_success:
944       hs->tls13_state = state13_send_server_finished;
945       return ssl_hs_ok;
946 
947     case ssl_private_key_retry:
948       hs->tls13_state = state13_send_server_certificate_verify;
949       return ssl_hs_private_key_operation;
950 
951     case ssl_private_key_failure:
952       return ssl_hs_error;
953   }
954 
955   assert(0);
956   return ssl_hs_error;
957 }
958 
do_send_server_finished(SSL_HANDSHAKE * hs)959 static enum ssl_hs_wait_t do_send_server_finished(SSL_HANDSHAKE *hs) {
960   SSL *const ssl = hs->ssl;
961   if (hs->hints_requested) {
962     return ssl_hs_hints_ready;
963   }
964 
965   hs->can_release_private_key = true;
966   if (!tls13_add_finished(hs) ||
967       // Update the secret to the master secret and derive traffic keys.
968       !tls13_advance_key_schedule(
969           hs, MakeConstSpan(kZeroes, hs->transcript.DigestLen())) ||
970       !tls13_derive_application_secrets(hs) ||
971       !tls13_set_traffic_key(ssl, ssl_encryption_application, evp_aead_seal,
972                              hs->new_session.get(),
973                              hs->server_traffic_secret_0)) {
974     return ssl_hs_error;
975   }
976 
977   hs->tls13_state = state13_send_half_rtt_ticket;
978   return hs->handback ? ssl_hs_handback : ssl_hs_ok;
979 }
980 
do_send_half_rtt_ticket(SSL_HANDSHAKE * hs)981 static enum ssl_hs_wait_t do_send_half_rtt_ticket(SSL_HANDSHAKE *hs) {
982   SSL *const ssl = hs->ssl;
983 
984   if (ssl->s3->early_data_accepted) {
985     // If accepting 0-RTT, we send tickets half-RTT. This gets the tickets on
986     // the wire sooner and also avoids triggering a write on |SSL_read| when
987     // processing the client Finished. This requires computing the client
988     // Finished early. See RFC 8446, section 4.6.1.
989     static const uint8_t kEndOfEarlyData[4] = {SSL3_MT_END_OF_EARLY_DATA, 0, 0,
990                                                0};
991     if (ssl->quic_method == nullptr &&
992         !hs->transcript.Update(kEndOfEarlyData)) {
993       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
994       return ssl_hs_error;
995     }
996 
997     size_t finished_len;
998     hs->expected_client_finished.Resize(hs->transcript.DigestLen());
999     if (!tls13_finished_mac(hs, hs->expected_client_finished.data(),
1000                             &finished_len, false /* client */)) {
1001       return ssl_hs_error;
1002     }
1003 
1004     if (finished_len != hs->expected_client_finished.size()) {
1005       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1006       return ssl_hs_error;
1007     }
1008 
1009     // Feed the predicted Finished into the transcript. This allows us to derive
1010     // the resumption secret early and send half-RTT tickets.
1011     //
1012     // TODO(crbug.com/42290594): Queuing up half-RTT tickets with DTLS will also
1013     // make implicit ACKing more subtle.
1014     assert(!SSL_is_dtls(hs->ssl));
1015     assert(hs->expected_client_finished.size() <= 0xff);
1016     uint8_t header[4] = {
1017         SSL3_MT_FINISHED, 0, 0,
1018         static_cast<uint8_t>(hs->expected_client_finished.size())};
1019     bool unused_sent_tickets;
1020     if (!hs->transcript.Update(header) ||
1021         !hs->transcript.Update(hs->expected_client_finished) ||
1022         !tls13_derive_resumption_secret(hs) ||
1023         !add_new_session_tickets(hs, &unused_sent_tickets)) {
1024       return ssl_hs_error;
1025     }
1026   }
1027 
1028   hs->tls13_state = state13_read_second_client_flight;
1029   return ssl_hs_flush;
1030 }
1031 
uses_end_of_early_data(const SSL * ssl)1032 static bool uses_end_of_early_data(const SSL *ssl) {
1033   // DTLS and QUIC omit the EndOfEarlyData message. See RFC 9001, section 8.3,
1034   // and RFC 9147, section 5.6.
1035   return ssl->quic_method == nullptr && !SSL_is_dtls(ssl);
1036 }
1037 
do_read_second_client_flight(SSL_HANDSHAKE * hs)1038 static enum ssl_hs_wait_t do_read_second_client_flight(SSL_HANDSHAKE *hs) {
1039   SSL *const ssl = hs->ssl;
1040   if (ssl->s3->early_data_accepted) {
1041     if (!tls13_set_traffic_key(ssl, ssl_encryption_early_data, evp_aead_open,
1042                                hs->new_session.get(),
1043                                hs->early_traffic_secret)) {
1044       return ssl_hs_error;
1045     }
1046     hs->can_early_write = true;
1047     hs->can_early_read = true;
1048     hs->in_early_data = true;
1049   }
1050 
1051   // If the EndOfEarlyData message is not used, switch to
1052   // client_handshake_secret before the early return.
1053   if (!uses_end_of_early_data(ssl)) {
1054     if (!tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_open,
1055                                hs->new_session.get(),
1056                                hs->client_handshake_secret)) {
1057       return ssl_hs_error;
1058     }
1059     hs->tls13_state = state13_process_end_of_early_data;
1060     return ssl->s3->early_data_accepted ? ssl_hs_early_return : ssl_hs_ok;
1061   }
1062 
1063   hs->tls13_state = state13_process_end_of_early_data;
1064   return ssl->s3->early_data_accepted ? ssl_hs_read_end_of_early_data
1065                                       : ssl_hs_ok;
1066 }
1067 
do_process_end_of_early_data(SSL_HANDSHAKE * hs)1068 static enum ssl_hs_wait_t do_process_end_of_early_data(SSL_HANDSHAKE *hs) {
1069   SSL *const ssl = hs->ssl;
1070   // In protocols that use EndOfEarlyData, we must consume the extra message and
1071   // switch to client_handshake_secret after the early return.
1072   if (uses_end_of_early_data(ssl)) {
1073     // If early data was not accepted, the EndOfEarlyData will be in the
1074     // discarded early data.
1075     if (hs->ssl->s3->early_data_accepted) {
1076       SSLMessage msg;
1077       if (!ssl->method->get_message(ssl, &msg)) {
1078         return ssl_hs_read_message;
1079       }
1080       if (!ssl_check_message_type(ssl, msg, SSL3_MT_END_OF_EARLY_DATA)) {
1081         return ssl_hs_error;
1082       }
1083       if (CBS_len(&msg.body) != 0) {
1084         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1085         OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1086         return ssl_hs_error;
1087       }
1088       ssl->method->next_message(ssl);
1089     }
1090     if (!tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_open,
1091                                hs->new_session.get(),
1092                                hs->client_handshake_secret)) {
1093       return ssl_hs_error;
1094     }
1095   }
1096   hs->tls13_state = state13_read_client_encrypted_extensions;
1097   return ssl_hs_ok;
1098 }
1099 
do_read_client_encrypted_extensions(SSL_HANDSHAKE * hs)1100 static enum ssl_hs_wait_t do_read_client_encrypted_extensions(
1101     SSL_HANDSHAKE *hs) {
1102   SSL *const ssl = hs->ssl;
1103   // For now, only one extension uses client EncryptedExtensions. This function
1104   // may be generalized if others use it in the future.
1105   if (hs->new_session->has_application_settings &&
1106       !ssl->s3->early_data_accepted) {
1107     SSLMessage msg;
1108     if (!ssl->method->get_message(ssl, &msg)) {
1109       return ssl_hs_read_message;
1110     }
1111     if (!ssl_check_message_type(ssl, msg, SSL3_MT_ENCRYPTED_EXTENSIONS)) {
1112       return ssl_hs_error;
1113     }
1114 
1115     CBS body = msg.body, extensions;
1116     if (!CBS_get_u16_length_prefixed(&body, &extensions) ||
1117         CBS_len(&body) != 0) {
1118       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1119       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1120       return ssl_hs_error;
1121     }
1122 
1123     uint16_t extension_type = TLSEXT_TYPE_application_settings_old;
1124     if (hs->config->alps_use_new_codepoint) {
1125       extension_type = TLSEXT_TYPE_application_settings;
1126     }
1127     SSLExtension application_settings(extension_type);
1128     uint8_t alert = SSL_AD_DECODE_ERROR;
1129     if (!ssl_parse_extensions(&extensions, &alert, {&application_settings},
1130                               /*ignore_unknown=*/false)) {
1131       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1132       return ssl_hs_error;
1133     }
1134 
1135     if (!application_settings.present) {
1136       OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
1137       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_MISSING_EXTENSION);
1138       return ssl_hs_error;
1139     }
1140 
1141     // Note that, if 0-RTT was accepted, these values will already have been
1142     // initialized earlier.
1143     if (!hs->new_session->peer_application_settings.CopyFrom(
1144             application_settings.data) ||
1145         !ssl_hash_message(hs, msg)) {
1146       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1147       return ssl_hs_error;
1148     }
1149 
1150     ssl->method->next_message(ssl);
1151   }
1152 
1153   hs->tls13_state = state13_read_client_certificate;
1154   return ssl_hs_ok;
1155 }
1156 
do_read_client_certificate(SSL_HANDSHAKE * hs)1157 static enum ssl_hs_wait_t do_read_client_certificate(SSL_HANDSHAKE *hs) {
1158   SSL *const ssl = hs->ssl;
1159   if (!hs->cert_request) {
1160     if (!ssl->s3->session_reused) {
1161       // OpenSSL returns X509_V_OK when no certificates are requested. This is
1162       // classed by them as a bug, but it's assumed by at least NGINX. (Only do
1163       // this in full handshakes as resumptions should carry over the previous
1164       // |verify_result|, though this is a no-op because servers do not
1165       // implement the client's odd soft-fail mode.)
1166       hs->new_session->verify_result = X509_V_OK;
1167     }
1168 
1169     // Skip this state.
1170     hs->tls13_state = state13_read_channel_id;
1171     return ssl_hs_ok;
1172   }
1173 
1174   const bool allow_anonymous =
1175       (hs->config->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) == 0;
1176   SSLMessage msg;
1177   if (!ssl->method->get_message(ssl, &msg)) {
1178     return ssl_hs_read_message;
1179   }
1180   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE) ||
1181       !tls13_process_certificate(hs, msg, allow_anonymous) ||
1182       !ssl_hash_message(hs, msg)) {
1183     return ssl_hs_error;
1184   }
1185 
1186   ssl->method->next_message(ssl);
1187   hs->tls13_state = state13_read_client_certificate_verify;
1188   return ssl_hs_ok;
1189 }
1190 
do_read_client_certificate_verify(SSL_HANDSHAKE * hs)1191 static enum ssl_hs_wait_t do_read_client_certificate_verify(SSL_HANDSHAKE *hs) {
1192   SSL *const ssl = hs->ssl;
1193   if (sk_CRYPTO_BUFFER_num(hs->new_session->certs.get()) == 0) {
1194     // Skip this state.
1195     hs->tls13_state = state13_read_channel_id;
1196     return ssl_hs_ok;
1197   }
1198 
1199   SSLMessage msg;
1200   if (!ssl->method->get_message(ssl, &msg)) {
1201     return ssl_hs_read_message;
1202   }
1203 
1204   switch (ssl_verify_peer_cert(hs)) {
1205     case ssl_verify_ok:
1206       break;
1207     case ssl_verify_invalid:
1208       return ssl_hs_error;
1209     case ssl_verify_retry:
1210       hs->tls13_state = state13_read_client_certificate_verify;
1211       return ssl_hs_certificate_verify;
1212   }
1213 
1214   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_VERIFY) ||
1215       !tls13_process_certificate_verify(hs, msg) ||
1216       !ssl_hash_message(hs, msg)) {
1217     return ssl_hs_error;
1218   }
1219 
1220   ssl->method->next_message(ssl);
1221   hs->tls13_state = state13_read_channel_id;
1222   return ssl_hs_ok;
1223 }
1224 
do_read_channel_id(SSL_HANDSHAKE * hs)1225 static enum ssl_hs_wait_t do_read_channel_id(SSL_HANDSHAKE *hs) {
1226   SSL *const ssl = hs->ssl;
1227   if (!hs->channel_id_negotiated) {
1228     hs->tls13_state = state13_read_client_finished;
1229     return ssl_hs_ok;
1230   }
1231 
1232   SSLMessage msg;
1233   if (!ssl->method->get_message(ssl, &msg)) {
1234     return ssl_hs_read_message;
1235   }
1236   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CHANNEL_ID) ||  //
1237       !tls1_verify_channel_id(hs, msg) ||                       //
1238       !ssl_hash_message(hs, msg)) {
1239     return ssl_hs_error;
1240   }
1241 
1242   ssl->method->next_message(ssl);
1243   hs->tls13_state = state13_read_client_finished;
1244   return ssl_hs_ok;
1245 }
1246 
do_read_client_finished(SSL_HANDSHAKE * hs)1247 static enum ssl_hs_wait_t do_read_client_finished(SSL_HANDSHAKE *hs) {
1248   SSL *const ssl = hs->ssl;
1249   SSLMessage msg;
1250   if (!ssl->method->get_message(ssl, &msg)) {
1251     return ssl_hs_read_message;
1252   }
1253   if (!ssl_check_message_type(ssl, msg, SSL3_MT_FINISHED) ||
1254       // If early data was accepted, we've already computed the client Finished
1255       // and derived the resumption secret.
1256       !tls13_process_finished(hs, msg, ssl->s3->early_data_accepted) ||
1257       // evp_aead_seal keys have already been switched.
1258       !tls13_set_traffic_key(ssl, ssl_encryption_application, evp_aead_open,
1259                              hs->new_session.get(),
1260                              hs->client_traffic_secret_0)) {
1261     return ssl_hs_error;
1262   }
1263 
1264   if (!ssl->s3->early_data_accepted) {
1265     if (!ssl_hash_message(hs, msg) ||  //
1266         !tls13_derive_resumption_secret(hs)) {
1267       return ssl_hs_error;
1268     }
1269 
1270     // We send post-handshake tickets as part of the handshake in 1-RTT.
1271     hs->tls13_state = state13_send_new_session_ticket;
1272   } else {
1273     // We already sent half-RTT tickets.
1274     hs->tls13_state = state13_done;
1275   }
1276 
1277   ssl->method->next_message(ssl);
1278   return ssl_hs_ack;
1279 }
1280 
do_send_new_session_ticket(SSL_HANDSHAKE * hs)1281 static enum ssl_hs_wait_t do_send_new_session_ticket(SSL_HANDSHAKE *hs) {
1282   bool sent_tickets;
1283   if (!add_new_session_tickets(hs, &sent_tickets)) {
1284     return ssl_hs_error;
1285   }
1286 
1287   hs->tls13_state = state13_done;
1288   return sent_tickets ? ssl_hs_flush_post_handshake : ssl_hs_ok;
1289 }
1290 
tls13_server_handshake(SSL_HANDSHAKE * hs)1291 enum ssl_hs_wait_t tls13_server_handshake(SSL_HANDSHAKE *hs) {
1292   while (hs->tls13_state != state13_done) {
1293     enum ssl_hs_wait_t ret = ssl_hs_error;
1294     enum tls13_server_hs_state_t state =
1295         static_cast<enum tls13_server_hs_state_t>(hs->tls13_state);
1296     switch (state) {
1297       case state13_select_parameters:
1298         ret = do_select_parameters(hs);
1299         break;
1300       case state13_select_session:
1301         ret = do_select_session(hs);
1302         break;
1303       case state13_send_hello_retry_request:
1304         ret = do_send_hello_retry_request(hs);
1305         break;
1306       case state13_read_second_client_hello:
1307         ret = do_read_second_client_hello(hs);
1308         break;
1309       case state13_send_server_hello:
1310         ret = do_send_server_hello(hs);
1311         break;
1312       case state13_send_server_certificate_verify:
1313         ret = do_send_server_certificate_verify(hs);
1314         break;
1315       case state13_send_server_finished:
1316         ret = do_send_server_finished(hs);
1317         break;
1318       case state13_send_half_rtt_ticket:
1319         ret = do_send_half_rtt_ticket(hs);
1320         break;
1321       case state13_read_second_client_flight:
1322         ret = do_read_second_client_flight(hs);
1323         break;
1324       case state13_process_end_of_early_data:
1325         ret = do_process_end_of_early_data(hs);
1326         break;
1327       case state13_read_client_encrypted_extensions:
1328         ret = do_read_client_encrypted_extensions(hs);
1329         break;
1330       case state13_read_client_certificate:
1331         ret = do_read_client_certificate(hs);
1332         break;
1333       case state13_read_client_certificate_verify:
1334         ret = do_read_client_certificate_verify(hs);
1335         break;
1336       case state13_read_channel_id:
1337         ret = do_read_channel_id(hs);
1338         break;
1339       case state13_read_client_finished:
1340         ret = do_read_client_finished(hs);
1341         break;
1342       case state13_send_new_session_ticket:
1343         ret = do_send_new_session_ticket(hs);
1344         break;
1345       case state13_done:
1346         ret = ssl_hs_ok;
1347         break;
1348     }
1349 
1350     if (hs->tls13_state != state) {
1351       ssl_do_info_callback(hs->ssl, SSL_CB_ACCEPT_LOOP, 1);
1352     }
1353 
1354     if (ret != ssl_hs_ok) {
1355       return ret;
1356     }
1357   }
1358 
1359   return ssl_hs_ok;
1360 }
1361 
tls13_server_handshake_state(SSL_HANDSHAKE * hs)1362 const char *tls13_server_handshake_state(SSL_HANDSHAKE *hs) {
1363   enum tls13_server_hs_state_t state =
1364       static_cast<enum tls13_server_hs_state_t>(hs->tls13_state);
1365   switch (state) {
1366     case state13_select_parameters:
1367       return "TLS 1.3 server select_parameters";
1368     case state13_select_session:
1369       return "TLS 1.3 server select_session";
1370     case state13_send_hello_retry_request:
1371       return "TLS 1.3 server send_hello_retry_request";
1372     case state13_read_second_client_hello:
1373       return "TLS 1.3 server read_second_client_hello";
1374     case state13_send_server_hello:
1375       return "TLS 1.3 server send_server_hello";
1376     case state13_send_server_certificate_verify:
1377       return "TLS 1.3 server send_server_certificate_verify";
1378     case state13_send_half_rtt_ticket:
1379       return "TLS 1.3 server send_half_rtt_ticket";
1380     case state13_send_server_finished:
1381       return "TLS 1.3 server send_server_finished";
1382     case state13_read_second_client_flight:
1383       return "TLS 1.3 server read_second_client_flight";
1384     case state13_process_end_of_early_data:
1385       return "TLS 1.3 server process_end_of_early_data";
1386     case state13_read_client_encrypted_extensions:
1387       return "TLS 1.3 server read_client_encrypted_extensions";
1388     case state13_read_client_certificate:
1389       return "TLS 1.3 server read_client_certificate";
1390     case state13_read_client_certificate_verify:
1391       return "TLS 1.3 server read_client_certificate_verify";
1392     case state13_read_channel_id:
1393       return "TLS 1.3 server read_channel_id";
1394     case state13_read_client_finished:
1395       return "TLS 1.3 server read_client_finished";
1396     case state13_send_new_session_ticket:
1397       return "TLS 1.3 server send_new_session_ticket";
1398     case state13_done:
1399       return "TLS 1.3 server done";
1400   }
1401 
1402   return "TLS 1.3 server unknown";
1403 }
1404 
1405 BSSL_NAMESPACE_END
1406