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