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 <tuple>
21 
22 #include <openssl/aead.h>
23 #include <openssl/bytestring.h>
24 #include <openssl/digest.h>
25 #include <openssl/err.h>
26 #include <openssl/mem.h>
27 #include <openssl/rand.h>
28 #include <openssl/stack.h>
29 
30 #include "../crypto/internal.h"
31 #include "internal.h"
32 
33 
34 BSSL_NAMESPACE_BEGIN
35 
36 static const uint8_t kZeroes[EVP_MAX_MD_SIZE] = {0};
37 
38 // Allow a minute of ticket age skew in either direction. This covers
39 // transmission delays in ClientHello and NewSessionTicket, as well as
40 // drift between client and server clock rate since the ticket was issued.
41 // See RFC 8446, section 8.3.
42 static const int32_t kMaxTicketAgeSkewSeconds = 60;
43 
resolve_ecdhe_secret(SSL_HANDSHAKE * hs,bool * out_need_retry,SSL_CLIENT_HELLO * client_hello)44 static int resolve_ecdhe_secret(SSL_HANDSHAKE *hs, bool *out_need_retry,
45                                 SSL_CLIENT_HELLO *client_hello) {
46   SSL *const ssl = hs->ssl;
47   *out_need_retry = false;
48 
49   // We only support connections that include an ECDHE key exchange.
50   CBS key_share;
51   if (!ssl_client_hello_get_extension(client_hello, &key_share,
52                                       TLSEXT_TYPE_key_share)) {
53     OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_KEY_SHARE);
54     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_MISSING_EXTENSION);
55     return 0;
56   }
57 
58   bool found_key_share;
59   Array<uint8_t> dhe_secret;
60   uint8_t alert = SSL_AD_DECODE_ERROR;
61   if (!ssl_ext_key_share_parse_clienthello(hs, &found_key_share, &dhe_secret,
62                                            &alert, &key_share)) {
63     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
64     return 0;
65   }
66 
67   if (!found_key_share) {
68     *out_need_retry = true;
69     return 0;
70   }
71 
72   return tls13_advance_key_schedule(hs, dhe_secret);
73 }
74 
ssl_ext_supported_versions_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)75 static int ssl_ext_supported_versions_add_serverhello(SSL_HANDSHAKE *hs,
76                                                       CBB *out) {
77   CBB contents;
78   if (!CBB_add_u16(out, TLSEXT_TYPE_supported_versions) ||
79       !CBB_add_u16_length_prefixed(out, &contents) ||
80       !CBB_add_u16(&contents, hs->ssl->version) ||
81       !CBB_flush(out)) {
82     return 0;
83   }
84 
85   return 1;
86 }
87 
choose_tls13_cipher(const SSL * ssl,const SSL_CLIENT_HELLO * client_hello,uint16_t group_id)88 static const SSL_CIPHER *choose_tls13_cipher(
89     const SSL *ssl, const SSL_CLIENT_HELLO *client_hello, uint16_t group_id) {
90   CBS cipher_suites;
91   CBS_init(&cipher_suites, client_hello->cipher_suites,
92            client_hello->cipher_suites_len);
93 
94   const uint16_t version = ssl_protocol_version(ssl);
95 
96   return ssl_choose_tls13_cipher(cipher_suites, version, group_id);
97 }
98 
add_new_session_tickets(SSL_HANDSHAKE * hs,bool * out_sent_tickets)99 static bool add_new_session_tickets(SSL_HANDSHAKE *hs, bool *out_sent_tickets) {
100   SSL *const ssl = hs->ssl;
101   if (// If the client doesn't accept resumption with PSK_DHE_KE, don't send a
102       // session ticket.
103       !hs->accept_psk_mode ||
104       // We only implement stateless resumption in TLS 1.3, so skip sending
105       // tickets if disabled.
106       (SSL_get_options(ssl) & SSL_OP_NO_TICKET)) {
107     *out_sent_tickets = false;
108     return true;
109   }
110 
111   // TLS 1.3 recommends single-use tickets, so issue multiple tickets in case
112   // the client makes several connections before getting a renewal.
113   static const int kNumTickets = 2;
114 
115   // Rebase the session timestamp so that it is measured from ticket
116   // issuance.
117   ssl_session_rebase_time(ssl, hs->new_session.get());
118 
119   for (int i = 0; i < kNumTickets; i++) {
120     UniquePtr<SSL_SESSION> session(
121         SSL_SESSION_dup(hs->new_session.get(), SSL_SESSION_INCLUDE_NONAUTH));
122     if (!session) {
123       return false;
124     }
125 
126     if (!RAND_bytes((uint8_t *)&session->ticket_age_add, 4)) {
127       return false;
128     }
129     session->ticket_age_add_valid = true;
130     bool enable_early_data =
131         ssl->enable_early_data &&
132         (!ssl->quic_method || !ssl->config->quic_early_data_context.empty());
133     if (enable_early_data) {
134       // QUIC does not use the max_early_data_size parameter and always sets it
135       // to a fixed value. See draft-ietf-quic-tls-22, section 4.5.
136       session->ticket_max_early_data =
137           ssl->quic_method != nullptr ? 0xffffffff : kMaxEarlyDataAccepted;
138     }
139 
140     static_assert(kNumTickets < 256, "Too many tickets");
141     uint8_t nonce[] = {static_cast<uint8_t>(i)};
142 
143     ScopedCBB cbb;
144     CBB body, nonce_cbb, ticket, extensions;
145     if (!ssl->method->init_message(ssl, cbb.get(), &body,
146                                    SSL3_MT_NEW_SESSION_TICKET) ||
147         !CBB_add_u32(&body, session->timeout) ||
148         !CBB_add_u32(&body, session->ticket_age_add) ||
149         !CBB_add_u8_length_prefixed(&body, &nonce_cbb) ||
150         !CBB_add_bytes(&nonce_cbb, nonce, sizeof(nonce)) ||
151         !CBB_add_u16_length_prefixed(&body, &ticket) ||
152         !tls13_derive_session_psk(session.get(), nonce) ||
153         !ssl_encrypt_ticket(hs, &ticket, session.get()) ||
154         !CBB_add_u16_length_prefixed(&body, &extensions)) {
155       return false;
156     }
157 
158     if (enable_early_data) {
159       CBB early_data;
160       if (!CBB_add_u16(&extensions, TLSEXT_TYPE_early_data) ||
161           !CBB_add_u16_length_prefixed(&extensions, &early_data) ||
162           !CBB_add_u32(&early_data, session->ticket_max_early_data) ||
163           !CBB_flush(&extensions)) {
164         return false;
165       }
166     }
167 
168     // Add a fake extension. See draft-davidben-tls-grease-01.
169     if (!CBB_add_u16(&extensions,
170                      ssl_get_grease_value(hs, ssl_grease_ticket_extension)) ||
171         !CBB_add_u16(&extensions, 0 /* empty */)) {
172       return false;
173     }
174 
175     if (!ssl_add_message_cbb(ssl, cbb.get())) {
176       return false;
177     }
178   }
179 
180   *out_sent_tickets = true;
181   return true;
182 }
183 
do_select_parameters(SSL_HANDSHAKE * hs)184 static enum ssl_hs_wait_t do_select_parameters(SSL_HANDSHAKE *hs) {
185   // At this point, most ClientHello extensions have already been processed by
186   // the common handshake logic. Resolve the remaining non-PSK parameters.
187   SSL *const ssl = hs->ssl;
188   SSLMessage msg;
189   if (!ssl->method->get_message(ssl, &msg)) {
190     return ssl_hs_read_message;
191   }
192   SSL_CLIENT_HELLO client_hello;
193   if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
194     OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_PARSE_FAILED);
195     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
196     return ssl_hs_error;
197   }
198 
199   if (ssl->quic_method != nullptr && client_hello.session_id_len > 0) {
200     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_COMPATIBILITY_MODE);
201     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
202     return ssl_hs_error;
203   }
204   OPENSSL_memcpy(hs->session_id, client_hello.session_id,
205                  client_hello.session_id_len);
206   hs->session_id_len = client_hello.session_id_len;
207 
208   uint16_t group_id;
209   if (!tls1_get_shared_group(hs, &group_id)) {
210     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_GROUP);
211     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
212     return ssl_hs_error;
213   }
214 
215   // Negotiate the cipher suite.
216   hs->new_cipher = choose_tls13_cipher(ssl, &client_hello, group_id);
217   if (hs->new_cipher == NULL) {
218     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_CIPHER);
219     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
220     return ssl_hs_error;
221   }
222 
223   // HTTP/2 negotiation depends on the cipher suite, so ALPN negotiation was
224   // deferred. Complete it now.
225   uint8_t alert = SSL_AD_DECODE_ERROR;
226   if (!ssl_negotiate_alpn(hs, &alert, &client_hello)) {
227     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
228     return ssl_hs_error;
229   }
230 
231   // The PRF hash is now known. Set up the key schedule and hash the
232   // ClientHello.
233   if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher)) {
234     return ssl_hs_error;
235   }
236 
237   hs->tls13_state = state13_select_session;
238   return ssl_hs_ok;
239 }
240 
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)241 static enum ssl_ticket_aead_result_t select_session(
242     SSL_HANDSHAKE *hs, uint8_t *out_alert, UniquePtr<SSL_SESSION> *out_session,
243     int32_t *out_ticket_age_skew, bool *out_offered_ticket,
244     const SSLMessage &msg, const SSL_CLIENT_HELLO *client_hello) {
245   SSL *const ssl = hs->ssl;
246   *out_session = nullptr;
247 
248   CBS pre_shared_key;
249   *out_offered_ticket = ssl_client_hello_get_extension(
250       client_hello, &pre_shared_key, TLSEXT_TYPE_pre_shared_key);
251   if (!*out_offered_ticket) {
252     return ssl_ticket_aead_ignore_ticket;
253   }
254 
255   CBS ticket, binders;
256   uint32_t client_ticket_age;
257   if (!ssl_ext_pre_shared_key_parse_clienthello(
258           hs, &ticket, &binders, &client_ticket_age, out_alert, client_hello,
259           &pre_shared_key)) {
260     return ssl_ticket_aead_error;
261   }
262 
263   // If the peer did not offer psk_dhe, ignore the resumption.
264   if (!hs->accept_psk_mode) {
265     return ssl_ticket_aead_ignore_ticket;
266   }
267 
268   // TLS 1.3 session tickets are renewed separately as part of the
269   // NewSessionTicket.
270   bool unused_renew;
271   UniquePtr<SSL_SESSION> session;
272   enum ssl_ticket_aead_result_t ret =
273       ssl_process_ticket(hs, &session, &unused_renew, ticket, {});
274   switch (ret) {
275     case ssl_ticket_aead_success:
276       break;
277     case ssl_ticket_aead_error:
278       *out_alert = SSL_AD_INTERNAL_ERROR;
279       return ret;
280     default:
281       return ret;
282   }
283 
284   if (!ssl_session_is_resumable(hs, session.get()) ||
285       // Historically, some TLS 1.3 tickets were missing ticket_age_add.
286       !session->ticket_age_add_valid) {
287     return ssl_ticket_aead_ignore_ticket;
288   }
289 
290   // Recover the client ticket age and convert to seconds.
291   client_ticket_age -= session->ticket_age_add;
292   client_ticket_age /= 1000;
293 
294   struct OPENSSL_timeval now;
295   ssl_get_current_time(ssl, &now);
296 
297   // Compute the server ticket age in seconds.
298   assert(now.tv_sec >= session->time);
299   uint64_t server_ticket_age = now.tv_sec - session->time;
300 
301   // To avoid overflowing |hs->ticket_age_skew|, we will not resume
302   // 68-year-old sessions.
303   if (server_ticket_age > INT32_MAX) {
304     return ssl_ticket_aead_ignore_ticket;
305   }
306 
307   *out_ticket_age_skew = static_cast<int32_t>(client_ticket_age) -
308                          static_cast<int32_t>(server_ticket_age);
309 
310   // Check the PSK binder.
311   if (!tls13_verify_psk_binder(hs, session.get(), msg, &binders)) {
312     *out_alert = SSL_AD_DECRYPT_ERROR;
313     return ssl_ticket_aead_error;
314   }
315 
316   *out_session = std::move(session);
317   return ssl_ticket_aead_success;
318 }
319 
quic_ticket_compatible(const SSL_SESSION * session,const SSL_CONFIG * config)320 static bool quic_ticket_compatible(const SSL_SESSION *session,
321                                    const SSL_CONFIG *config) {
322   if (!session->is_quic) {
323     return true;
324   }
325 
326   if (session->quic_early_data_context.empty() ||
327       config->quic_early_data_context.size() !=
328           session->quic_early_data_context.size() ||
329       CRYPTO_memcmp(config->quic_early_data_context.data(),
330                     session->quic_early_data_context.data(),
331                     session->quic_early_data_context.size()) != 0) {
332     return false;
333   }
334   return true;
335 }
336 
do_select_session(SSL_HANDSHAKE * hs)337 static enum ssl_hs_wait_t do_select_session(SSL_HANDSHAKE *hs) {
338   SSL *const ssl = hs->ssl;
339   SSLMessage msg;
340   if (!ssl->method->get_message(ssl, &msg)) {
341     return ssl_hs_read_message;
342   }
343   SSL_CLIENT_HELLO client_hello;
344   if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
345     OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_PARSE_FAILED);
346     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
347     return ssl_hs_error;
348   }
349 
350   uint8_t alert = SSL_AD_DECODE_ERROR;
351   UniquePtr<SSL_SESSION> session;
352   bool offered_ticket = false;
353   switch (select_session(hs, &alert, &session, &ssl->s3->ticket_age_skew,
354                          &offered_ticket, msg, &client_hello)) {
355     case ssl_ticket_aead_ignore_ticket:
356       assert(!session);
357       if (!ssl_get_new_session(hs, 1 /* server */)) {
358         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
359         return ssl_hs_error;
360       }
361       break;
362 
363     case ssl_ticket_aead_success:
364       // Carry over authentication information from the previous handshake into
365       // a fresh session.
366       hs->new_session =
367           SSL_SESSION_dup(session.get(), SSL_SESSION_DUP_AUTH_ONLY);
368       if (hs->new_session == nullptr) {
369         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
370         return ssl_hs_error;
371       }
372 
373       ssl->s3->session_reused = true;
374 
375       // Resumption incorporates fresh key material, so refresh the timeout.
376       ssl_session_renew_timeout(ssl, hs->new_session.get(),
377                                 ssl->session_ctx->session_psk_dhe_timeout);
378       break;
379 
380     case ssl_ticket_aead_error:
381       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
382       return ssl_hs_error;
383 
384     case ssl_ticket_aead_retry:
385       hs->tls13_state = state13_select_session;
386       return ssl_hs_pending_ticket;
387   }
388 
389   // Negotiate ALPS now, after ALPN is negotiated and |hs->new_session| is
390   // initialized.
391   if (!ssl_negotiate_alps(hs, &alert, &client_hello)) {
392     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
393     return ssl_hs_error;
394   }
395 
396   // Determine if we're negotiating 0-RTT.
397   if (!ssl->enable_early_data) {
398     ssl->s3->early_data_reason = ssl_early_data_disabled;
399   } else if (!offered_ticket) {
400     ssl->s3->early_data_reason = ssl_early_data_no_session_offered;
401   } else if (!session) {
402     ssl->s3->early_data_reason = ssl_early_data_session_not_resumed;
403   } else if (session->ticket_max_early_data == 0) {
404     ssl->s3->early_data_reason = ssl_early_data_unsupported_for_session;
405   } else if (!hs->early_data_offered) {
406     ssl->s3->early_data_reason = ssl_early_data_peer_declined;
407   } else if (ssl->s3->channel_id_valid) {
408     // Channel ID is incompatible with 0-RTT.
409     ssl->s3->early_data_reason = ssl_early_data_channel_id;
410   } else if (ssl->s3->token_binding_negotiated) {
411     // Token Binding is incompatible with 0-RTT.
412     ssl->s3->early_data_reason = ssl_early_data_token_binding;
413   } else if (MakeConstSpan(ssl->s3->alpn_selected) != session->early_alpn) {
414     // The negotiated ALPN must match the one in the ticket.
415     ssl->s3->early_data_reason = ssl_early_data_alpn_mismatch;
416   } else if (hs->new_session->has_application_settings !=
417                  session->has_application_settings ||
418              MakeConstSpan(hs->new_session->local_application_settings) !=
419                  session->local_application_settings) {
420     ssl->s3->early_data_reason = ssl_early_data_alps_mismatch;
421   } else if (ssl->s3->ticket_age_skew < -kMaxTicketAgeSkewSeconds ||
422              kMaxTicketAgeSkewSeconds < ssl->s3->ticket_age_skew) {
423     ssl->s3->early_data_reason = ssl_early_data_ticket_age_skew;
424   } else if (!quic_ticket_compatible(session.get(), hs->config)) {
425     ssl->s3->early_data_reason = ssl_early_data_quic_parameter_mismatch;
426   } else {
427     // |ssl_session_is_resumable| forbids cross-cipher resumptions even if the
428     // PRF hashes match.
429     assert(hs->new_cipher == session->cipher);
430 
431     ssl->s3->early_data_reason = ssl_early_data_accepted;
432     ssl->s3->early_data_accepted = true;
433   }
434 
435   // Record connection properties in the new session.
436   hs->new_session->cipher = hs->new_cipher;
437 
438   // Store the ALPN and ALPS values in the session for 0-RTT. Note the peer
439   // applications settings are not generally known until client
440   // EncryptedExtensions.
441   if (!hs->new_session->early_alpn.CopyFrom(ssl->s3->alpn_selected)) {
442     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
443     return ssl_hs_error;
444   }
445 
446   // The peer applications settings are usually received later, in
447   // EncryptedExtensions. But, in 0-RTT handshakes, we carry over the
448   // values from |session|. Do this now, before |session| is discarded.
449   if (ssl->s3->early_data_accepted &&
450       hs->new_session->has_application_settings &&
451       !hs->new_session->peer_application_settings.CopyFrom(
452           session->peer_application_settings)) {
453     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
454     return ssl_hs_error;
455   }
456 
457   // Copy the QUIC early data context to the session.
458   if (ssl->enable_early_data && ssl->quic_method) {
459     if (!hs->new_session->quic_early_data_context.CopyFrom(
460             hs->config->quic_early_data_context)) {
461       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
462       return ssl_hs_error;
463     }
464   }
465 
466   if (ssl->ctx->dos_protection_cb != NULL &&
467       ssl->ctx->dos_protection_cb(&client_hello) == 0) {
468     // Connection rejected for DOS reasons.
469     OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
470     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
471     return ssl_hs_error;
472   }
473 
474   size_t hash_len = EVP_MD_size(
475       ssl_get_handshake_digest(ssl_protocol_version(ssl), hs->new_cipher));
476 
477   // Set up the key schedule and incorporate the PSK into the running secret.
478   if (ssl->s3->session_reused) {
479     if (!tls13_init_key_schedule(
480             hs, MakeConstSpan(hs->new_session->secret,
481                               hs->new_session->secret_length))) {
482       return ssl_hs_error;
483     }
484   } else if (!tls13_init_key_schedule(hs, MakeConstSpan(kZeroes, hash_len))) {
485     return ssl_hs_error;
486   }
487 
488   if (!ssl_hash_message(hs, msg)) {
489     return ssl_hs_error;
490   }
491 
492   if (ssl->s3->early_data_accepted) {
493     if (!tls13_derive_early_secret(hs)) {
494       return ssl_hs_error;
495     }
496   } else if (hs->early_data_offered) {
497     ssl->s3->skip_early_data = true;
498   }
499 
500   // Resolve ECDHE and incorporate it into the secret.
501   bool need_retry;
502   if (!resolve_ecdhe_secret(hs, &need_retry, &client_hello)) {
503     if (need_retry) {
504       if (ssl->s3->early_data_accepted) {
505         ssl->s3->early_data_reason = ssl_early_data_hello_retry_request;
506         ssl->s3->early_data_accepted = false;
507       }
508       ssl->s3->skip_early_data = true;
509       ssl->method->next_message(ssl);
510       if (!hs->transcript.UpdateForHelloRetryRequest()) {
511         return ssl_hs_error;
512       }
513       hs->tls13_state = state13_send_hello_retry_request;
514       return ssl_hs_ok;
515     }
516     return ssl_hs_error;
517   }
518 
519   ssl->method->next_message(ssl);
520   hs->tls13_state = state13_send_server_hello;
521   return ssl_hs_ok;
522 }
523 
do_send_hello_retry_request(SSL_HANDSHAKE * hs)524 static enum ssl_hs_wait_t do_send_hello_retry_request(SSL_HANDSHAKE *hs) {
525   SSL *const ssl = hs->ssl;
526 
527 
528   ScopedCBB cbb;
529   CBB body, session_id, extensions;
530   uint16_t group_id;
531   if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_SERVER_HELLO) ||
532       !CBB_add_u16(&body, TLS1_2_VERSION) ||
533       !CBB_add_bytes(&body, kHelloRetryRequest, SSL3_RANDOM_SIZE) ||
534       !CBB_add_u8_length_prefixed(&body, &session_id) ||
535       !CBB_add_bytes(&session_id, hs->session_id, hs->session_id_len) ||
536       !CBB_add_u16(&body, SSL_CIPHER_get_protocol_id(hs->new_cipher)) ||
537       !CBB_add_u8(&body, 0 /* no compression */) ||
538       !tls1_get_shared_group(hs, &group_id) ||
539       !CBB_add_u16_length_prefixed(&body, &extensions) ||
540       !CBB_add_u16(&extensions, TLSEXT_TYPE_supported_versions) ||
541       !CBB_add_u16(&extensions, 2 /* length */) ||
542       !CBB_add_u16(&extensions, ssl->version) ||
543       !CBB_add_u16(&extensions, TLSEXT_TYPE_key_share) ||
544       !CBB_add_u16(&extensions, 2 /* length */) ||
545       !CBB_add_u16(&extensions, group_id) ||
546       !ssl_add_message_cbb(ssl, cbb.get())) {
547     return ssl_hs_error;
548   }
549 
550   if (!ssl->method->add_change_cipher_spec(ssl)) {
551     return ssl_hs_error;
552   }
553 
554   ssl->s3->used_hello_retry_request = true;
555   hs->tls13_state = state13_read_second_client_hello;
556   return ssl_hs_flush;
557 }
558 
do_read_second_client_hello(SSL_HANDSHAKE * hs)559 static enum ssl_hs_wait_t do_read_second_client_hello(SSL_HANDSHAKE *hs) {
560   SSL *const ssl = hs->ssl;
561   SSLMessage msg;
562   if (!ssl->method->get_message(ssl, &msg)) {
563     return ssl_hs_read_message;
564   }
565   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CLIENT_HELLO)) {
566     return ssl_hs_error;
567   }
568   SSL_CLIENT_HELLO client_hello;
569   if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
570     OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_PARSE_FAILED);
571     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
572     return ssl_hs_error;
573   }
574 
575   // We perform all our negotiation based on the first ClientHello (for
576   // consistency with what |select_certificate_cb| observed), which is in the
577   // transcript, so we can ignore most of this second one.
578   //
579   // We do, however, check the second PSK binder. This covers the client key
580   // share, in case we ever send half-RTT data (we currently do not). It is also
581   // a tricky computation, so we enforce the peer handled it correctly.
582   if (ssl->s3->session_reused) {
583     CBS pre_shared_key;
584     if (!ssl_client_hello_get_extension(&client_hello, &pre_shared_key,
585                                         TLSEXT_TYPE_pre_shared_key)) {
586       OPENSSL_PUT_ERROR(SSL, SSL_R_INCONSISTENT_CLIENT_HELLO);
587       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
588       return ssl_hs_error;
589     }
590 
591     CBS ticket, binders;
592     uint32_t client_ticket_age;
593     uint8_t alert = SSL_AD_DECODE_ERROR;
594     if (!ssl_ext_pre_shared_key_parse_clienthello(
595             hs, &ticket, &binders, &client_ticket_age, &alert, &client_hello,
596             &pre_shared_key)) {
597       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
598       return ssl_hs_error;
599     }
600 
601     // Note it is important that we do not obtain a new |SSL_SESSION| from
602     // |ticket|. We have already selected parameters based on the first
603     // ClientHello (in the transcript) and must not switch partway through.
604     if (!tls13_verify_psk_binder(hs, hs->new_session.get(), msg, &binders)) {
605       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
606       return ssl_hs_error;
607     }
608   }
609 
610   bool need_retry;
611   if (!resolve_ecdhe_secret(hs, &need_retry, &client_hello)) {
612     if (need_retry) {
613       // Only send one HelloRetryRequest.
614       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
615       OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
616     }
617     return ssl_hs_error;
618   }
619 
620   if (!ssl_hash_message(hs, msg)) {
621     return ssl_hs_error;
622   }
623 
624   // ClientHello should be the end of the flight.
625   if (ssl->method->has_unprocessed_handshake_data(ssl)) {
626     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
627     OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESS_HANDSHAKE_DATA);
628     return ssl_hs_error;
629   }
630 
631   ssl->method->next_message(ssl);
632   hs->tls13_state = state13_send_server_hello;
633   return ssl_hs_ok;
634 }
635 
do_send_server_hello(SSL_HANDSHAKE * hs)636 static enum ssl_hs_wait_t do_send_server_hello(SSL_HANDSHAKE *hs) {
637   SSL *const ssl = hs->ssl;
638 
639   Span<uint8_t> random(ssl->s3->server_random);
640   RAND_bytes(random.data(), random.size());
641 
642   // If the ClientHello has an ech_is_inner extension, we must be the ECH
643   // backend server. In response to ech_is_inner, we will overwrite part of the
644   // ServerHello.random with the ECH acceptance confirmation.
645   if (hs->ech_is_inner_present) {
646     // Construct the ServerHelloECHConf message, which is the same as
647     // ServerHello, except the last 8 bytes of its random field are zeroed out.
648     Span<uint8_t> random_suffix = random.subspan(24);
649     OPENSSL_memset(random_suffix.data(), 0, random_suffix.size());
650 
651     ScopedCBB cbb;
652     CBB body, extensions, session_id;
653     if (!ssl->method->init_message(ssl, cbb.get(), &body,
654                                    SSL3_MT_SERVER_HELLO) ||
655         !CBB_add_u16(&body, TLS1_2_VERSION) ||
656         !CBB_add_bytes(&body, random.data(), random.size()) ||
657         !CBB_add_u8_length_prefixed(&body, &session_id) ||
658         !CBB_add_bytes(&session_id, hs->session_id, hs->session_id_len) ||
659         !CBB_add_u16(&body, SSL_CIPHER_get_protocol_id(hs->new_cipher)) ||
660         !CBB_add_u8(&body, 0) ||
661         !CBB_add_u16_length_prefixed(&body, &extensions) ||
662         !ssl_ext_pre_shared_key_add_serverhello(hs, &extensions) ||
663         !ssl_ext_key_share_add_serverhello(hs, &extensions, /*dry_run=*/true) ||
664         !ssl_ext_supported_versions_add_serverhello(hs, &extensions) ||
665         !CBB_flush(cbb.get())) {
666       return ssl_hs_error;
667     }
668 
669     // Note that |cbb| includes the message type and length fields, but not the
670     // record layer header.
671     if (!tls13_ech_accept_confirmation(
672             hs, random_suffix,
673             bssl::MakeConstSpan(CBB_data(cbb.get()), CBB_len(cbb.get())))) {
674       return ssl_hs_error;
675     }
676   }
677 
678   // Send a ServerHello.
679   ScopedCBB cbb;
680   CBB body, extensions, session_id;
681   if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_SERVER_HELLO) ||
682       !CBB_add_u16(&body, TLS1_2_VERSION) ||
683       !CBB_add_bytes(&body, random.data(), random.size()) ||
684       !CBB_add_u8_length_prefixed(&body, &session_id) ||
685       !CBB_add_bytes(&session_id, hs->session_id, hs->session_id_len) ||
686       !CBB_add_u16(&body, SSL_CIPHER_get_protocol_id(hs->new_cipher)) ||
687       !CBB_add_u8(&body, 0) ||
688       !CBB_add_u16_length_prefixed(&body, &extensions) ||
689       !ssl_ext_pre_shared_key_add_serverhello(hs, &extensions) ||
690       !ssl_ext_key_share_add_serverhello(hs, &extensions, /*dry_run=*/false) ||
691       !ssl_ext_supported_versions_add_serverhello(hs, &extensions) ||
692       !ssl_add_message_cbb(ssl, cbb.get())) {
693     return ssl_hs_error;
694   }
695 
696   if (!ssl->s3->used_hello_retry_request &&
697       !ssl->method->add_change_cipher_spec(ssl)) {
698     return ssl_hs_error;
699   }
700 
701   // Derive and enable the handshake traffic secrets.
702   if (!tls13_derive_handshake_secrets(hs) ||
703       !tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_seal,
704                              hs->new_session.get(),
705                              hs->server_handshake_secret())) {
706     return ssl_hs_error;
707   }
708 
709   // Send EncryptedExtensions.
710   if (!ssl->method->init_message(ssl, cbb.get(), &body,
711                                  SSL3_MT_ENCRYPTED_EXTENSIONS) ||
712       !ssl_add_serverhello_tlsext(hs, &body) ||
713       !ssl_add_message_cbb(ssl, cbb.get())) {
714     return ssl_hs_error;
715   }
716 
717   if (!ssl->s3->session_reused) {
718     // Determine whether to request a client certificate.
719     hs->cert_request = !!(hs->config->verify_mode & SSL_VERIFY_PEER);
720     // Only request a certificate if Channel ID isn't negotiated.
721     if ((hs->config->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
722         ssl->s3->channel_id_valid) {
723       hs->cert_request = false;
724     }
725   }
726 
727   // Send a CertificateRequest, if necessary.
728   if (hs->cert_request) {
729     CBB cert_request_extensions, sigalg_contents, sigalgs_cbb;
730     if (!ssl->method->init_message(ssl, cbb.get(), &body,
731                                    SSL3_MT_CERTIFICATE_REQUEST) ||
732         !CBB_add_u8(&body, 0 /* no certificate_request_context. */) ||
733         !CBB_add_u16_length_prefixed(&body, &cert_request_extensions) ||
734         !CBB_add_u16(&cert_request_extensions,
735                      TLSEXT_TYPE_signature_algorithms) ||
736         !CBB_add_u16_length_prefixed(&cert_request_extensions,
737                                      &sigalg_contents) ||
738         !CBB_add_u16_length_prefixed(&sigalg_contents, &sigalgs_cbb) ||
739         !tls12_add_verify_sigalgs(hs, &sigalgs_cbb)) {
740       return ssl_hs_error;
741     }
742 
743     if (ssl_has_client_CAs(hs->config)) {
744       CBB ca_contents;
745       if (!CBB_add_u16(&cert_request_extensions,
746                        TLSEXT_TYPE_certificate_authorities) ||
747           !CBB_add_u16_length_prefixed(&cert_request_extensions,
748                                        &ca_contents) ||
749           !ssl_add_client_CA_list(hs, &ca_contents) ||
750           !CBB_flush(&cert_request_extensions)) {
751         return ssl_hs_error;
752       }
753     }
754 
755     if (!ssl_add_message_cbb(ssl, cbb.get())) {
756       return ssl_hs_error;
757     }
758   }
759 
760   // Send the server Certificate message, if necessary.
761   if (!ssl->s3->session_reused) {
762     if (!ssl_has_certificate(hs)) {
763       OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATE_SET);
764       return ssl_hs_error;
765     }
766 
767     if (!tls13_add_certificate(hs)) {
768       return ssl_hs_error;
769     }
770 
771     hs->tls13_state = state13_send_server_certificate_verify;
772     return ssl_hs_ok;
773   }
774 
775   hs->tls13_state = state13_send_server_finished;
776   return ssl_hs_ok;
777 }
778 
do_send_server_certificate_verify(SSL_HANDSHAKE * hs)779 static enum ssl_hs_wait_t do_send_server_certificate_verify(SSL_HANDSHAKE *hs) {
780   switch (tls13_add_certificate_verify(hs)) {
781     case ssl_private_key_success:
782       hs->tls13_state = state13_send_server_finished;
783       return ssl_hs_ok;
784 
785     case ssl_private_key_retry:
786       hs->tls13_state = state13_send_server_certificate_verify;
787       return ssl_hs_private_key_operation;
788 
789     case ssl_private_key_failure:
790       return ssl_hs_error;
791   }
792 
793   assert(0);
794   return ssl_hs_error;
795 }
796 
do_send_server_finished(SSL_HANDSHAKE * hs)797 static enum ssl_hs_wait_t do_send_server_finished(SSL_HANDSHAKE *hs) {
798   SSL *const ssl = hs->ssl;
799   if (!tls13_add_finished(hs) ||
800       // Update the secret to the master secret and derive traffic keys.
801       !tls13_advance_key_schedule(
802           hs, MakeConstSpan(kZeroes, hs->transcript.DigestLen())) ||
803       !tls13_derive_application_secrets(hs) ||
804       !tls13_set_traffic_key(ssl, ssl_encryption_application, evp_aead_seal,
805                              hs->new_session.get(),
806                              hs->server_traffic_secret_0())) {
807     return ssl_hs_error;
808   }
809 
810   hs->tls13_state = state13_send_half_rtt_ticket;
811   return hs->handback ? ssl_hs_handback : ssl_hs_ok;
812 }
813 
do_send_half_rtt_ticket(SSL_HANDSHAKE * hs)814 static enum ssl_hs_wait_t do_send_half_rtt_ticket(SSL_HANDSHAKE *hs) {
815   SSL *const ssl = hs->ssl;
816 
817   if (ssl->s3->early_data_accepted) {
818     // If accepting 0-RTT, we send tickets half-RTT. This gets the tickets on
819     // the wire sooner and also avoids triggering a write on |SSL_read| when
820     // processing the client Finished. This requires computing the client
821     // Finished early. See RFC 8446, section 4.6.1.
822     static const uint8_t kEndOfEarlyData[4] = {SSL3_MT_END_OF_EARLY_DATA, 0,
823                                                0, 0};
824     if (ssl->quic_method == nullptr &&
825         !hs->transcript.Update(kEndOfEarlyData)) {
826       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
827       return ssl_hs_error;
828     }
829 
830     size_t finished_len;
831     if (!tls13_finished_mac(hs, hs->expected_client_finished().data(),
832                             &finished_len, false /* client */)) {
833       return ssl_hs_error;
834     }
835 
836     if (finished_len != hs->expected_client_finished().size()) {
837       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
838       return ssl_hs_error;
839     }
840 
841     // Feed the predicted Finished into the transcript. This allows us to derive
842     // the resumption secret early and send half-RTT tickets.
843     //
844     // TODO(davidben): This will need to be updated for DTLS 1.3.
845     assert(!SSL_is_dtls(hs->ssl));
846     assert(hs->expected_client_finished().size() <= 0xff);
847     uint8_t header[4] = {
848         SSL3_MT_FINISHED, 0, 0,
849         static_cast<uint8_t>(hs->expected_client_finished().size())};
850     bool unused_sent_tickets;
851     if (!hs->transcript.Update(header) ||
852         !hs->transcript.Update(hs->expected_client_finished()) ||
853         !tls13_derive_resumption_secret(hs) ||
854         !add_new_session_tickets(hs, &unused_sent_tickets)) {
855       return ssl_hs_error;
856     }
857   }
858 
859   hs->tls13_state = state13_read_second_client_flight;
860   return ssl_hs_flush;
861 }
862 
do_read_second_client_flight(SSL_HANDSHAKE * hs)863 static enum ssl_hs_wait_t do_read_second_client_flight(SSL_HANDSHAKE *hs) {
864   SSL *const ssl = hs->ssl;
865   if (ssl->s3->early_data_accepted) {
866     if (!tls13_set_traffic_key(ssl, ssl_encryption_early_data, evp_aead_open,
867                                hs->new_session.get(),
868                                hs->early_traffic_secret())) {
869       return ssl_hs_error;
870     }
871     hs->can_early_write = true;
872     hs->can_early_read = true;
873     hs->in_early_data = true;
874   }
875 
876   // QUIC doesn't use an EndOfEarlyData message (draft-ietf-quic-tls-22,
877   // section 8.3), so we switch to client_handshake_secret before the early
878   // return.
879   if (ssl->quic_method != nullptr) {
880     if (!tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_open,
881                                hs->new_session.get(),
882                                hs->client_handshake_secret())) {
883       return ssl_hs_error;
884     }
885     hs->tls13_state = state13_process_end_of_early_data;
886     return ssl->s3->early_data_accepted ? ssl_hs_early_return : ssl_hs_ok;
887   }
888 
889   hs->tls13_state = state13_process_end_of_early_data;
890   return ssl->s3->early_data_accepted ? ssl_hs_read_end_of_early_data
891                                       : ssl_hs_ok;
892 }
893 
do_process_end_of_early_data(SSL_HANDSHAKE * hs)894 static enum ssl_hs_wait_t do_process_end_of_early_data(SSL_HANDSHAKE *hs) {
895   SSL *const ssl = hs->ssl;
896   // In protocols that use EndOfEarlyData, we must consume the extra message and
897   // switch to client_handshake_secret after the early return.
898   if (ssl->quic_method == nullptr) {
899     // If early data was not accepted, the EndOfEarlyData will be in the
900     // discarded early data.
901     if (hs->ssl->s3->early_data_accepted) {
902       SSLMessage msg;
903       if (!ssl->method->get_message(ssl, &msg)) {
904         return ssl_hs_read_message;
905       }
906       if (!ssl_check_message_type(ssl, msg, SSL3_MT_END_OF_EARLY_DATA)) {
907         return ssl_hs_error;
908       }
909       if (CBS_len(&msg.body) != 0) {
910         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
911         OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
912         return ssl_hs_error;
913       }
914       ssl->method->next_message(ssl);
915     }
916     if (!tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_open,
917                                hs->new_session.get(),
918                                hs->client_handshake_secret())) {
919       return ssl_hs_error;
920     }
921   }
922   hs->tls13_state = state13_read_client_encrypted_extensions;
923   return ssl_hs_ok;
924 }
925 
do_read_client_encrypted_extensions(SSL_HANDSHAKE * hs)926 static enum ssl_hs_wait_t do_read_client_encrypted_extensions(
927     SSL_HANDSHAKE *hs) {
928   SSL *const ssl = hs->ssl;
929   // For now, only one extension uses client EncryptedExtensions. This function
930   // may be generalized if others use it in the future.
931   if (hs->new_session->has_application_settings &&
932       !ssl->s3->early_data_accepted) {
933     SSLMessage msg;
934     if (!ssl->method->get_message(ssl, &msg)) {
935       return ssl_hs_read_message;
936     }
937     if (!ssl_check_message_type(ssl, msg, SSL3_MT_ENCRYPTED_EXTENSIONS)) {
938       return ssl_hs_error;
939     }
940 
941     CBS body = msg.body, extensions;
942     if (!CBS_get_u16_length_prefixed(&body, &extensions) ||
943         CBS_len(&body) != 0) {
944       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
945       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
946       return ssl_hs_error;
947     }
948 
949     // Parse out the extensions.
950     bool have_application_settings = false;
951     CBS application_settings;
952     SSL_EXTENSION_TYPE ext_types[] = {{TLSEXT_TYPE_application_settings,
953                                        &have_application_settings,
954                                        &application_settings}};
955     uint8_t alert = SSL_AD_DECODE_ERROR;
956     if (!ssl_parse_extensions(&extensions, &alert, ext_types,
957                               /*ignore_unknown=*/false)) {
958       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
959       return ssl_hs_error;
960     }
961 
962     if (!have_application_settings) {
963       OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
964       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_MISSING_EXTENSION);
965       return ssl_hs_error;
966     }
967 
968     // Note that, if 0-RTT was accepted, these values will already have been
969     // initialized earlier.
970     if (!hs->new_session->peer_application_settings.CopyFrom(
971             application_settings) ||
972         !ssl_hash_message(hs, msg)) {
973       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
974       return ssl_hs_error;
975     }
976 
977     ssl->method->next_message(ssl);
978   }
979 
980   hs->tls13_state = state13_read_client_certificate;
981   return ssl_hs_ok;
982 }
983 
do_read_client_certificate(SSL_HANDSHAKE * hs)984 static enum ssl_hs_wait_t do_read_client_certificate(SSL_HANDSHAKE *hs) {
985   SSL *const ssl = hs->ssl;
986   if (!hs->cert_request) {
987     if (!ssl->s3->session_reused) {
988       // OpenSSL returns X509_V_OK when no certificates are requested. This is
989       // classed by them as a bug, but it's assumed by at least NGINX. (Only do
990       // this in full handshakes as resumptions should carry over the previous
991       // |verify_result|, though this is a no-op because servers do not
992       // implement the client's odd soft-fail mode.)
993       hs->new_session->verify_result = X509_V_OK;
994     }
995 
996     // Skip this state.
997     hs->tls13_state = state13_read_channel_id;
998     return ssl_hs_ok;
999   }
1000 
1001   const bool allow_anonymous =
1002       (hs->config->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) == 0;
1003   SSLMessage msg;
1004   if (!ssl->method->get_message(ssl, &msg)) {
1005     return ssl_hs_read_message;
1006   }
1007   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE) ||
1008       !tls13_process_certificate(hs, msg, allow_anonymous) ||
1009       !ssl_hash_message(hs, msg)) {
1010     return ssl_hs_error;
1011   }
1012 
1013   ssl->method->next_message(ssl);
1014   hs->tls13_state = state13_read_client_certificate_verify;
1015   return ssl_hs_ok;
1016 }
1017 
do_read_client_certificate_verify(SSL_HANDSHAKE * hs)1018 static enum ssl_hs_wait_t do_read_client_certificate_verify(SSL_HANDSHAKE *hs) {
1019   SSL *const ssl = hs->ssl;
1020   if (sk_CRYPTO_BUFFER_num(hs->new_session->certs.get()) == 0) {
1021     // Skip this state.
1022     hs->tls13_state = state13_read_channel_id;
1023     return ssl_hs_ok;
1024   }
1025 
1026   SSLMessage msg;
1027   if (!ssl->method->get_message(ssl, &msg)) {
1028     return ssl_hs_read_message;
1029   }
1030 
1031   switch (ssl_verify_peer_cert(hs)) {
1032     case ssl_verify_ok:
1033       break;
1034     case ssl_verify_invalid:
1035       return ssl_hs_error;
1036     case ssl_verify_retry:
1037       hs->tls13_state = state13_read_client_certificate_verify;
1038       return ssl_hs_certificate_verify;
1039   }
1040 
1041   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_VERIFY) ||
1042       !tls13_process_certificate_verify(hs, msg) ||
1043       !ssl_hash_message(hs, msg)) {
1044     return ssl_hs_error;
1045   }
1046 
1047   ssl->method->next_message(ssl);
1048   hs->tls13_state = state13_read_channel_id;
1049   return ssl_hs_ok;
1050 }
1051 
do_read_channel_id(SSL_HANDSHAKE * hs)1052 static enum ssl_hs_wait_t do_read_channel_id(SSL_HANDSHAKE *hs) {
1053   SSL *const ssl = hs->ssl;
1054   if (!ssl->s3->channel_id_valid) {
1055     hs->tls13_state = state13_read_client_finished;
1056     return ssl_hs_ok;
1057   }
1058 
1059   SSLMessage msg;
1060   if (!ssl->method->get_message(ssl, &msg)) {
1061     return ssl_hs_read_message;
1062   }
1063   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CHANNEL_ID) ||
1064       !tls1_verify_channel_id(hs, msg) ||
1065       !ssl_hash_message(hs, msg)) {
1066     return ssl_hs_error;
1067   }
1068 
1069   ssl->method->next_message(ssl);
1070   hs->tls13_state = state13_read_client_finished;
1071   return ssl_hs_ok;
1072 }
1073 
do_read_client_finished(SSL_HANDSHAKE * hs)1074 static enum ssl_hs_wait_t do_read_client_finished(SSL_HANDSHAKE *hs) {
1075   SSL *const ssl = hs->ssl;
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_FINISHED) ||
1081       // If early data was accepted, we've already computed the client Finished
1082       // and derived the resumption secret.
1083       !tls13_process_finished(hs, msg, ssl->s3->early_data_accepted) ||
1084       // evp_aead_seal keys have already been switched.
1085       !tls13_set_traffic_key(ssl, ssl_encryption_application, evp_aead_open,
1086                              hs->new_session.get(),
1087                              hs->client_traffic_secret_0())) {
1088     return ssl_hs_error;
1089   }
1090 
1091   if (!ssl->s3->early_data_accepted) {
1092     if (!ssl_hash_message(hs, msg) ||
1093         !tls13_derive_resumption_secret(hs)) {
1094       return ssl_hs_error;
1095     }
1096 
1097     // We send post-handshake tickets as part of the handshake in 1-RTT.
1098     hs->tls13_state = state13_send_new_session_ticket;
1099   } else {
1100     // We already sent half-RTT tickets.
1101     hs->tls13_state = state13_done;
1102   }
1103 
1104   ssl->method->next_message(ssl);
1105   return ssl_hs_ok;
1106 }
1107 
do_send_new_session_ticket(SSL_HANDSHAKE * hs)1108 static enum ssl_hs_wait_t do_send_new_session_ticket(SSL_HANDSHAKE *hs) {
1109   bool sent_tickets;
1110   if (!add_new_session_tickets(hs, &sent_tickets)) {
1111     return ssl_hs_error;
1112   }
1113 
1114   hs->tls13_state = state13_done;
1115   // In TLS 1.3, the NewSessionTicket isn't flushed until the server performs a
1116   // write, to prevent a non-reading client from causing the server to hang in
1117   // the case of a small server write buffer. Consumers which don't write data
1118   // to the client will need to do a zero-byte write if they wish to flush the
1119   // tickets.
1120   if (hs->ssl->quic_method != nullptr && sent_tickets) {
1121     return ssl_hs_flush;
1122   }
1123   return ssl_hs_ok;
1124 }
1125 
tls13_server_handshake(SSL_HANDSHAKE * hs)1126 enum ssl_hs_wait_t tls13_server_handshake(SSL_HANDSHAKE *hs) {
1127   while (hs->tls13_state != state13_done) {
1128     enum ssl_hs_wait_t ret = ssl_hs_error;
1129     enum tls13_server_hs_state_t state =
1130         static_cast<enum tls13_server_hs_state_t>(hs->tls13_state);
1131     switch (state) {
1132       case state13_select_parameters:
1133         ret = do_select_parameters(hs);
1134         break;
1135       case state13_select_session:
1136         ret = do_select_session(hs);
1137         break;
1138       case state13_send_hello_retry_request:
1139         ret = do_send_hello_retry_request(hs);
1140         break;
1141       case state13_read_second_client_hello:
1142         ret = do_read_second_client_hello(hs);
1143         break;
1144       case state13_send_server_hello:
1145         ret = do_send_server_hello(hs);
1146         break;
1147       case state13_send_server_certificate_verify:
1148         ret = do_send_server_certificate_verify(hs);
1149         break;
1150       case state13_send_server_finished:
1151         ret = do_send_server_finished(hs);
1152         break;
1153       case state13_send_half_rtt_ticket:
1154         ret = do_send_half_rtt_ticket(hs);
1155         break;
1156       case state13_read_second_client_flight:
1157         ret = do_read_second_client_flight(hs);
1158         break;
1159       case state13_process_end_of_early_data:
1160         ret = do_process_end_of_early_data(hs);
1161         break;
1162       case state13_read_client_encrypted_extensions:
1163         ret = do_read_client_encrypted_extensions(hs);
1164         break;
1165       case state13_read_client_certificate:
1166         ret = do_read_client_certificate(hs);
1167         break;
1168       case state13_read_client_certificate_verify:
1169         ret = do_read_client_certificate_verify(hs);
1170         break;
1171       case state13_read_channel_id:
1172         ret = do_read_channel_id(hs);
1173         break;
1174       case state13_read_client_finished:
1175         ret = do_read_client_finished(hs);
1176         break;
1177       case state13_send_new_session_ticket:
1178         ret = do_send_new_session_ticket(hs);
1179         break;
1180       case state13_done:
1181         ret = ssl_hs_ok;
1182         break;
1183     }
1184 
1185     if (hs->tls13_state != state) {
1186       ssl_do_info_callback(hs->ssl, SSL_CB_ACCEPT_LOOP, 1);
1187     }
1188 
1189     if (ret != ssl_hs_ok) {
1190       return ret;
1191     }
1192   }
1193 
1194   return ssl_hs_ok;
1195 }
1196 
tls13_server_handshake_state(SSL_HANDSHAKE * hs)1197 const char *tls13_server_handshake_state(SSL_HANDSHAKE *hs) {
1198   enum tls13_server_hs_state_t state =
1199       static_cast<enum tls13_server_hs_state_t>(hs->tls13_state);
1200   switch (state) {
1201     case state13_select_parameters:
1202       return "TLS 1.3 server select_parameters";
1203     case state13_select_session:
1204       return "TLS 1.3 server select_session";
1205     case state13_send_hello_retry_request:
1206       return "TLS 1.3 server send_hello_retry_request";
1207     case state13_read_second_client_hello:
1208       return "TLS 1.3 server read_second_client_hello";
1209     case state13_send_server_hello:
1210       return "TLS 1.3 server send_server_hello";
1211     case state13_send_server_certificate_verify:
1212       return "TLS 1.3 server send_server_certificate_verify";
1213     case state13_send_half_rtt_ticket:
1214       return "TLS 1.3 server send_half_rtt_ticket";
1215     case state13_send_server_finished:
1216       return "TLS 1.3 server send_server_finished";
1217     case state13_read_second_client_flight:
1218       return "TLS 1.3 server read_second_client_flight";
1219     case state13_process_end_of_early_data:
1220       return "TLS 1.3 server process_end_of_early_data";
1221     case state13_read_client_encrypted_extensions:
1222       return "TLS 1.3 server read_client_encrypted_extensions";
1223     case state13_read_client_certificate:
1224       return "TLS 1.3 server read_client_certificate";
1225     case state13_read_client_certificate_verify:
1226       return "TLS 1.3 server read_client_certificate_verify";
1227     case state13_read_channel_id:
1228       return "TLS 1.3 server read_channel_id";
1229     case state13_read_client_finished:
1230       return "TLS 1.3 server read_client_finished";
1231     case state13_send_new_session_ticket:
1232       return "TLS 1.3 server send_new_session_ticket";
1233     case state13_done:
1234       return "TLS 1.3 server done";
1235   }
1236 
1237   return "TLS 1.3 server unknown";
1238 }
1239 
1240 BSSL_NAMESPACE_END
1241