Home | History | Annotate | Download | only in ssl
      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 <openssl/aead.h>
     21 #include <openssl/bytestring.h>
     22 #include <openssl/digest.h>
     23 #include <openssl/err.h>
     24 #include <openssl/mem.h>
     25 #include <openssl/rand.h>
     26 #include <openssl/stack.h>
     27 
     28 #include "../crypto/internal.h"
     29 #include "internal.h"
     30 
     31 
     32 /* kMaxEarlyDataAccepted is the advertised number of plaintext bytes of early
     33  * data that will be accepted. This value should be slightly below
     34  * kMaxEarlyDataSkipped in tls_record.c, which is measured in ciphertext. */
     35 static const size_t kMaxEarlyDataAccepted = 14336;
     36 
     37 enum server_hs_state_t {
     38   state_select_parameters = 0,
     39   state_select_session,
     40   state_send_hello_retry_request,
     41   state_process_second_client_hello,
     42   state_send_server_hello,
     43   state_send_server_certificate_verify,
     44   state_complete_server_certificate_verify,
     45   state_send_server_finished,
     46   state_read_second_client_flight,
     47   state_process_end_of_early_data,
     48   state_process_client_certificate,
     49   state_process_client_certificate_verify,
     50   state_process_channel_id,
     51   state_process_client_finished,
     52   state_send_new_session_ticket,
     53   state_done,
     54 };
     55 
     56 static const uint8_t kZeroes[EVP_MAX_MD_SIZE] = {0};
     57 
     58 static int resolve_ecdhe_secret(SSL_HANDSHAKE *hs, int *out_need_retry,
     59                                 SSL_CLIENT_HELLO *client_hello) {
     60   SSL *const ssl = hs->ssl;
     61   *out_need_retry = 0;
     62 
     63   /* We only support connections that include an ECDHE key exchange. */
     64   CBS key_share;
     65   if (!ssl_client_hello_get_extension(client_hello, &key_share,
     66                                       TLSEXT_TYPE_key_share)) {
     67     OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_KEY_SHARE);
     68     ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_MISSING_EXTENSION);
     69     return 0;
     70   }
     71 
     72   int found_key_share;
     73   uint8_t *dhe_secret;
     74   size_t dhe_secret_len;
     75   uint8_t alert = SSL_AD_DECODE_ERROR;
     76   if (!ssl_ext_key_share_parse_clienthello(hs, &found_key_share, &dhe_secret,
     77                                            &dhe_secret_len, &alert,
     78                                            &key_share)) {
     79     ssl3_send_alert(ssl, SSL3_AL_FATAL, alert);
     80     return 0;
     81   }
     82 
     83   if (!found_key_share) {
     84     *out_need_retry = 1;
     85     return 0;
     86   }
     87 
     88   int ok = tls13_advance_key_schedule(hs, dhe_secret, dhe_secret_len);
     89   OPENSSL_free(dhe_secret);
     90   return ok;
     91 }
     92 
     93 static const SSL_CIPHER *choose_tls13_cipher(
     94     const SSL *ssl, const SSL_CLIENT_HELLO *client_hello) {
     95   if (client_hello->cipher_suites_len % 2 != 0) {
     96     return NULL;
     97   }
     98 
     99   CBS cipher_suites;
    100   CBS_init(&cipher_suites, client_hello->cipher_suites,
    101            client_hello->cipher_suites_len);
    102 
    103   const int aes_is_fine = EVP_has_aes_hardware();
    104   const uint16_t version = ssl3_protocol_version(ssl);
    105 
    106   const SSL_CIPHER *best = NULL;
    107   while (CBS_len(&cipher_suites) > 0) {
    108     uint16_t cipher_suite;
    109     if (!CBS_get_u16(&cipher_suites, &cipher_suite)) {
    110       return NULL;
    111     }
    112 
    113     /* Limit to TLS 1.3 ciphers we know about. */
    114     const SSL_CIPHER *candidate = SSL_get_cipher_by_value(cipher_suite);
    115     if (candidate == NULL ||
    116         SSL_CIPHER_get_min_version(candidate) > version ||
    117         SSL_CIPHER_get_max_version(candidate) < version) {
    118       continue;
    119     }
    120 
    121     /* TLS 1.3 removes legacy ciphers, so honor the client order, but prefer
    122      * ChaCha20 if we do not have AES hardware. */
    123     if (aes_is_fine) {
    124       return candidate;
    125     }
    126 
    127     if (candidate->algorithm_enc == SSL_CHACHA20POLY1305) {
    128       return candidate;
    129     }
    130 
    131     if (best == NULL) {
    132       best = candidate;
    133     }
    134   }
    135 
    136   return best;
    137 }
    138 
    139 static int add_new_session_tickets(SSL_HANDSHAKE *hs) {
    140   SSL *const ssl = hs->ssl;
    141   /* TLS 1.3 recommends single-use tickets, so issue multiple tickets in case
    142    * the client makes several connections before getting a renewal. */
    143   static const int kNumTickets = 2;
    144 
    145   SSL_SESSION *session = hs->new_session;
    146   CBB cbb;
    147   CBB_zero(&cbb);
    148 
    149   /* Rebase the session timestamp so that it is measured from ticket
    150    * issuance. */
    151   ssl_session_rebase_time(ssl, session);
    152 
    153   for (int i = 0; i < kNumTickets; i++) {
    154     if (!RAND_bytes((uint8_t *)&session->ticket_age_add, 4)) {
    155       goto err;
    156     }
    157     session->ticket_age_add_valid = 1;
    158 
    159     CBB body, ticket, extensions;
    160     if (!ssl->method->init_message(ssl, &cbb, &body,
    161                                    SSL3_MT_NEW_SESSION_TICKET) ||
    162         !CBB_add_u32(&body, session->timeout) ||
    163         !CBB_add_u32(&body, session->ticket_age_add) ||
    164         !CBB_add_u16_length_prefixed(&body, &ticket) ||
    165         !ssl_encrypt_ticket(ssl, &ticket, session) ||
    166         !CBB_add_u16_length_prefixed(&body, &extensions)) {
    167       goto err;
    168     }
    169 
    170     if (ssl->ctx->enable_early_data) {
    171       session->ticket_max_early_data = kMaxEarlyDataAccepted;
    172 
    173       CBB early_data_info;
    174       if (!CBB_add_u16(&extensions, TLSEXT_TYPE_ticket_early_data_info) ||
    175           !CBB_add_u16_length_prefixed(&extensions, &early_data_info) ||
    176           !CBB_add_u32(&early_data_info, session->ticket_max_early_data) ||
    177           !CBB_flush(&extensions)) {
    178         goto err;
    179       }
    180     }
    181 
    182     /* Add a fake extension. See draft-davidben-tls-grease-01. */
    183     if (!CBB_add_u16(&extensions,
    184                      ssl_get_grease_value(ssl, ssl_grease_ticket_extension)) ||
    185         !CBB_add_u16(&extensions, 0 /* empty */)) {
    186       goto err;
    187     }
    188 
    189     if (!ssl_add_message_cbb(ssl, &cbb)) {
    190       goto err;
    191     }
    192   }
    193 
    194   return 1;
    195 
    196 err:
    197   CBB_cleanup(&cbb);
    198   return 0;
    199 }
    200 
    201 static enum ssl_hs_wait_t do_select_parameters(SSL_HANDSHAKE *hs) {
    202   /* At this point, most ClientHello extensions have already been processed by
    203    * the common handshake logic. Resolve the remaining non-PSK parameters. */
    204   SSL *const ssl = hs->ssl;
    205 
    206   SSL_CLIENT_HELLO client_hello;
    207   if (!ssl_client_hello_init(ssl, &client_hello, ssl->init_msg,
    208                              ssl->init_num)) {
    209     OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_PARSE_FAILED);
    210     ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
    211     return ssl_hs_error;
    212   }
    213 
    214   /* Negotiate the cipher suite. */
    215   hs->new_cipher = choose_tls13_cipher(ssl, &client_hello);
    216   if (hs->new_cipher == NULL) {
    217     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_CIPHER);
    218     ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
    219     return ssl_hs_error;
    220   }
    221 
    222   /* HTTP/2 negotiation depends on the cipher suite, so ALPN negotiation was
    223    * deferred. Complete it now. */
    224   uint8_t alert = SSL_AD_DECODE_ERROR;
    225   if (!ssl_negotiate_alpn(hs, &alert, &client_hello)) {
    226     ssl3_send_alert(ssl, SSL3_AL_FATAL, alert);
    227     return ssl_hs_error;
    228   }
    229 
    230   /* The PRF hash is now known. Set up the key schedule and hash the
    231    * ClientHello. */
    232   if (!tls13_init_key_schedule(hs) ||
    233       !ssl_hash_current_message(hs)) {
    234     return ssl_hs_error;
    235   }
    236 
    237   hs->tls13_state = state_select_session;
    238   return ssl_hs_ok;
    239 }
    240 
    241 static enum ssl_ticket_aead_result_t select_session(
    242     SSL_HANDSHAKE *hs, uint8_t *out_alert, SSL_SESSION **out_session,
    243     int32_t *out_ticket_age_skew, const SSL_CLIENT_HELLO *client_hello) {
    244   SSL *const ssl = hs->ssl;
    245   *out_session = NULL;
    246 
    247   /* Decode the ticket if we agreed on a PSK key exchange mode. */
    248   CBS pre_shared_key;
    249   if (!hs->accept_psk_mode ||
    250       !ssl_client_hello_get_extension(client_hello, &pre_shared_key,
    251                                       TLSEXT_TYPE_pre_shared_key)) {
    252     return ssl_ticket_aead_ignore_ticket;
    253   }
    254 
    255   /* Verify that the pre_shared_key extension is the last extension in
    256    * ClientHello. */
    257   if (CBS_data(&pre_shared_key) + CBS_len(&pre_shared_key) !=
    258       client_hello->extensions + client_hello->extensions_len) {
    259     OPENSSL_PUT_ERROR(SSL, SSL_R_PRE_SHARED_KEY_MUST_BE_LAST);
    260     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
    261     return ssl_ticket_aead_error;
    262   }
    263 
    264   CBS ticket, binders;
    265   uint32_t client_ticket_age;
    266   if (!ssl_ext_pre_shared_key_parse_clienthello(hs, &ticket, &binders,
    267                                                 &client_ticket_age, out_alert,
    268                                                 &pre_shared_key)) {
    269     return ssl_ticket_aead_error;
    270   }
    271 
    272   /* TLS 1.3 session tickets are renewed separately as part of the
    273    * NewSessionTicket. */
    274   int unused_renew;
    275   SSL_SESSION *session = NULL;
    276   enum ssl_ticket_aead_result_t ret =
    277       ssl_process_ticket(ssl, &session, &unused_renew, CBS_data(&ticket),
    278                          CBS_len(&ticket), NULL, 0);
    279   switch (ret) {
    280     case ssl_ticket_aead_success:
    281       break;
    282     case ssl_ticket_aead_error:
    283       *out_alert = SSL_AD_INTERNAL_ERROR;
    284       return ret;
    285     default:
    286       return ret;
    287   }
    288 
    289   if (!ssl_session_is_resumable(hs, session) ||
    290       /* Historically, some TLS 1.3 tickets were missing ticket_age_add. */
    291       !session->ticket_age_add_valid) {
    292     SSL_SESSION_free(session);
    293     return ssl_ticket_aead_ignore_ticket;
    294   }
    295 
    296   /* Recover the client ticket age and convert to seconds. */
    297   client_ticket_age -= session->ticket_age_add;
    298   client_ticket_age /= 1000;
    299 
    300   struct OPENSSL_timeval now;
    301   ssl_get_current_time(ssl, &now);
    302 
    303   /* Compute the server ticket age in seconds. */
    304   assert(now.tv_sec >= session->time);
    305   uint64_t server_ticket_age = now.tv_sec - session->time;
    306 
    307   /* To avoid overflowing |hs->ticket_age_skew|, we will not resume
    308    * 68-year-old sessions. */
    309   if (server_ticket_age > INT32_MAX) {
    310     SSL_SESSION_free(session);
    311     return ssl_ticket_aead_ignore_ticket;
    312   }
    313 
    314   /* TODO(davidben,svaldez): Measure this value to decide on tolerance. For
    315    * now, accept all values. https://crbug.com/boringssl/113. */
    316   *out_ticket_age_skew =
    317       (int32_t)client_ticket_age - (int32_t)server_ticket_age;
    318 
    319   /* Check the PSK binder. */
    320   if (!tls13_verify_psk_binder(hs, session, &binders)) {
    321     SSL_SESSION_free(session);
    322     *out_alert = SSL_AD_DECRYPT_ERROR;
    323     return ssl_ticket_aead_error;
    324   }
    325 
    326   *out_session = session;
    327   return ssl_ticket_aead_success;
    328 }
    329 
    330 static enum ssl_hs_wait_t do_select_session(SSL_HANDSHAKE *hs) {
    331   SSL *const ssl = hs->ssl;
    332   SSL_CLIENT_HELLO client_hello;
    333   if (!ssl_client_hello_init(ssl, &client_hello, ssl->init_msg,
    334                              ssl->init_num)) {
    335     OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_PARSE_FAILED);
    336     ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
    337     return ssl_hs_error;
    338   }
    339 
    340   uint8_t alert = SSL_AD_DECODE_ERROR;
    341   SSL_SESSION *session = NULL;
    342   switch (select_session(hs, &alert, &session, &ssl->s3->ticket_age_skew,
    343                          &client_hello)) {
    344     case ssl_ticket_aead_ignore_ticket:
    345       assert(session == NULL);
    346       if (!ssl_get_new_session(hs, 1 /* server */)) {
    347         ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
    348         return ssl_hs_error;
    349       }
    350       break;
    351 
    352     case ssl_ticket_aead_success:
    353       /* Carry over authentication information from the previous handshake into
    354        * a fresh session. */
    355       hs->new_session = SSL_SESSION_dup(session, SSL_SESSION_DUP_AUTH_ONLY);
    356 
    357       if (/* Early data must be acceptable for this ticket. */
    358           ssl->ctx->enable_early_data &&
    359           session->ticket_max_early_data != 0 &&
    360           /* The client must have offered early data. */
    361           hs->early_data_offered &&
    362           /* Channel ID is incompatible with 0-RTT. */
    363           !ssl->s3->tlsext_channel_id_valid &&
    364           /* The negotiated ALPN must match the one in the ticket. */
    365           ssl->s3->alpn_selected_len == session->early_alpn_len &&
    366           OPENSSL_memcmp(ssl->s3->alpn_selected, session->early_alpn,
    367                          ssl->s3->alpn_selected_len) == 0) {
    368         ssl->early_data_accepted = 1;
    369       }
    370 
    371       SSL_SESSION_free(session);
    372       if (hs->new_session == NULL) {
    373         ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
    374         return ssl_hs_error;
    375       }
    376 
    377       ssl->s3->session_reused = 1;
    378 
    379       /* Resumption incorporates fresh key material, so refresh the timeout. */
    380       ssl_session_renew_timeout(ssl, hs->new_session,
    381                                 ssl->session_ctx->session_psk_dhe_timeout);
    382       break;
    383 
    384     case ssl_ticket_aead_error:
    385       ssl3_send_alert(ssl, SSL3_AL_FATAL, alert);
    386       return ssl_hs_error;
    387 
    388     case ssl_ticket_aead_retry:
    389       hs->tls13_state = state_select_session;
    390       return ssl_hs_pending_ticket;
    391   }
    392 
    393   /* Record connection properties in the new session. */
    394   hs->new_session->cipher = hs->new_cipher;
    395 
    396   if (hs->hostname != NULL) {
    397     OPENSSL_free(hs->new_session->tlsext_hostname);
    398     hs->new_session->tlsext_hostname = BUF_strdup(hs->hostname);
    399     if (hs->new_session->tlsext_hostname == NULL) {
    400       ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
    401       return ssl_hs_error;
    402     }
    403   }
    404 
    405   /* Store the initial negotiated ALPN in the session. */
    406   if (ssl->s3->alpn_selected != NULL) {
    407     hs->new_session->early_alpn =
    408         BUF_memdup(ssl->s3->alpn_selected, ssl->s3->alpn_selected_len);
    409     if (hs->new_session->early_alpn == NULL) {
    410       ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
    411       return ssl_hs_error;
    412     }
    413     hs->new_session->early_alpn_len = ssl->s3->alpn_selected_len;
    414   }
    415 
    416   if (ssl->ctx->dos_protection_cb != NULL &&
    417       ssl->ctx->dos_protection_cb(&client_hello) == 0) {
    418     /* Connection rejected for DOS reasons. */
    419     OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
    420     ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
    421     return ssl_hs_error;
    422   }
    423 
    424   /* Incorporate the PSK into the running secret. */
    425   if (ssl->s3->session_reused) {
    426     if (!tls13_advance_key_schedule(hs, hs->new_session->master_key,
    427                                     hs->new_session->master_key_length)) {
    428       return ssl_hs_error;
    429     }
    430   } else if (!tls13_advance_key_schedule(hs, kZeroes, hs->hash_len)) {
    431     return ssl_hs_error;
    432   }
    433 
    434   if (ssl->early_data_accepted) {
    435     if (!tls13_derive_early_secrets(hs)) {
    436       return ssl_hs_error;
    437     }
    438   } else if (hs->early_data_offered) {
    439     ssl->s3->skip_early_data = 1;
    440   }
    441 
    442   ssl->method->received_flight(ssl);
    443 
    444   /* Resolve ECDHE and incorporate it into the secret. */
    445   int need_retry;
    446   if (!resolve_ecdhe_secret(hs, &need_retry, &client_hello)) {
    447     if (need_retry) {
    448       ssl->early_data_accepted = 0;
    449       ssl->s3->skip_early_data = 1;
    450       hs->tls13_state = state_send_hello_retry_request;
    451       return ssl_hs_ok;
    452     }
    453     return ssl_hs_error;
    454   }
    455 
    456   hs->tls13_state = state_send_server_hello;
    457   return ssl_hs_ok;
    458 }
    459 
    460 static enum ssl_hs_wait_t do_send_hello_retry_request(SSL_HANDSHAKE *hs) {
    461   SSL *const ssl = hs->ssl;
    462   CBB cbb, body, extensions;
    463   uint16_t group_id;
    464   if (!ssl->method->init_message(ssl, &cbb, &body,
    465                                  SSL3_MT_HELLO_RETRY_REQUEST) ||
    466       !CBB_add_u16(&body, ssl->version) ||
    467       !tls1_get_shared_group(hs, &group_id) ||
    468       !CBB_add_u16_length_prefixed(&body, &extensions) ||
    469       !CBB_add_u16(&extensions, TLSEXT_TYPE_key_share) ||
    470       !CBB_add_u16(&extensions, 2 /* length */) ||
    471       !CBB_add_u16(&extensions, group_id) ||
    472       !ssl_add_message_cbb(ssl, &cbb)) {
    473     CBB_cleanup(&cbb);
    474     return ssl_hs_error;
    475   }
    476 
    477   hs->tls13_state = state_process_second_client_hello;
    478   return ssl_hs_flush_and_read_message;
    479 }
    480 
    481 static enum ssl_hs_wait_t do_process_second_client_hello(SSL_HANDSHAKE *hs) {
    482   SSL *const ssl = hs->ssl;
    483   if (!ssl_check_message_type(ssl, SSL3_MT_CLIENT_HELLO)) {
    484     return ssl_hs_error;
    485   }
    486 
    487   SSL_CLIENT_HELLO client_hello;
    488   if (!ssl_client_hello_init(ssl, &client_hello, ssl->init_msg,
    489                              ssl->init_num)) {
    490     OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_PARSE_FAILED);
    491     ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
    492     return ssl_hs_error;
    493   }
    494 
    495   int need_retry;
    496   if (!resolve_ecdhe_secret(hs, &need_retry, &client_hello)) {
    497     if (need_retry) {
    498       /* Only send one HelloRetryRequest. */
    499       ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
    500       OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
    501     }
    502     return ssl_hs_error;
    503   }
    504 
    505   if (!ssl_hash_current_message(hs)) {
    506     return ssl_hs_error;
    507   }
    508 
    509   ssl->method->received_flight(ssl);
    510   hs->tls13_state = state_send_server_hello;
    511   return ssl_hs_ok;
    512 }
    513 
    514 static enum ssl_hs_wait_t do_send_server_hello(SSL_HANDSHAKE *hs) {
    515   SSL *const ssl = hs->ssl;
    516 
    517   /* Send a ServerHello. */
    518   CBB cbb, body, extensions;
    519   if (!ssl->method->init_message(ssl, &cbb, &body, SSL3_MT_SERVER_HELLO) ||
    520       !CBB_add_u16(&body, ssl->version) ||
    521       !RAND_bytes(ssl->s3->server_random, sizeof(ssl->s3->server_random)) ||
    522       !CBB_add_bytes(&body, ssl->s3->server_random, SSL3_RANDOM_SIZE) ||
    523       !CBB_add_u16(&body, ssl_cipher_get_value(hs->new_cipher)) ||
    524       !CBB_add_u16_length_prefixed(&body, &extensions) ||
    525       !ssl_ext_pre_shared_key_add_serverhello(hs, &extensions) ||
    526       !ssl_ext_key_share_add_serverhello(hs, &extensions) ||
    527       !ssl_add_message_cbb(ssl, &cbb)) {
    528     goto err;
    529   }
    530 
    531   /* Derive and enable the handshake traffic secrets. */
    532   if (!tls13_derive_handshake_secrets(hs) ||
    533       !tls13_set_traffic_key(ssl, evp_aead_seal, hs->server_handshake_secret,
    534                              hs->hash_len)) {
    535     goto err;
    536   }
    537 
    538   /* Send EncryptedExtensions. */
    539   if (!ssl->method->init_message(ssl, &cbb, &body,
    540                                  SSL3_MT_ENCRYPTED_EXTENSIONS) ||
    541       !ssl_add_serverhello_tlsext(hs, &body) ||
    542       !ssl_add_message_cbb(ssl, &cbb)) {
    543     goto err;
    544   }
    545 
    546   /* Determine whether to request a client certificate. */
    547   hs->cert_request = !!(ssl->verify_mode & SSL_VERIFY_PEER);
    548   /* CertificateRequest may only be sent in non-resumption handshakes. */
    549   if (ssl->s3->session_reused) {
    550     hs->cert_request = 0;
    551   }
    552 
    553   /* Send a CertificateRequest, if necessary. */
    554   if (hs->cert_request) {
    555     CBB sigalgs_cbb;
    556     if (!ssl->method->init_message(ssl, &cbb, &body,
    557                                    SSL3_MT_CERTIFICATE_REQUEST) ||
    558         !CBB_add_u8(&body, 0 /* no certificate_request_context. */)) {
    559       goto err;
    560     }
    561 
    562     const uint16_t *sigalgs;
    563     size_t num_sigalgs = tls12_get_verify_sigalgs(ssl, &sigalgs);
    564     if (!CBB_add_u16_length_prefixed(&body, &sigalgs_cbb)) {
    565       goto err;
    566     }
    567 
    568     for (size_t i = 0; i < num_sigalgs; i++) {
    569       if (!CBB_add_u16(&sigalgs_cbb, sigalgs[i])) {
    570         goto err;
    571       }
    572     }
    573 
    574     if (!ssl_add_client_CA_list(ssl, &body) ||
    575         !CBB_add_u16(&body, 0 /* empty certificate_extensions. */) ||
    576         !ssl_add_message_cbb(ssl, &cbb)) {
    577       goto err;
    578     }
    579   }
    580 
    581   /* Send the server Certificate message, if necessary. */
    582   if (!ssl->s3->session_reused) {
    583     if (!ssl_has_certificate(ssl)) {
    584       OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATE_SET);
    585       goto err;
    586     }
    587 
    588     if (!tls13_add_certificate(hs)) {
    589       goto err;
    590     }
    591 
    592     hs->tls13_state = state_send_server_certificate_verify;
    593     return ssl_hs_ok;
    594   }
    595 
    596   hs->tls13_state = state_send_server_finished;
    597   return ssl_hs_ok;
    598 
    599 err:
    600   CBB_cleanup(&cbb);
    601   return ssl_hs_error;
    602 }
    603 
    604 static enum ssl_hs_wait_t do_send_server_certificate_verify(SSL_HANDSHAKE *hs,
    605                                                             int is_first_run) {
    606   switch (tls13_add_certificate_verify(hs, is_first_run)) {
    607     case ssl_private_key_success:
    608       hs->tls13_state = state_send_server_finished;
    609       return ssl_hs_ok;
    610 
    611     case ssl_private_key_retry:
    612       hs->tls13_state = state_complete_server_certificate_verify;
    613       return ssl_hs_private_key_operation;
    614 
    615     case ssl_private_key_failure:
    616       return ssl_hs_error;
    617   }
    618 
    619   assert(0);
    620   return ssl_hs_error;
    621 }
    622 
    623 static enum ssl_hs_wait_t do_send_server_finished(SSL_HANDSHAKE *hs) {
    624   SSL *const ssl = hs->ssl;
    625   if (!tls13_add_finished(hs) ||
    626       /* Update the secret to the master secret and derive traffic keys. */
    627       !tls13_advance_key_schedule(hs, kZeroes, hs->hash_len) ||
    628       !tls13_derive_application_secrets(hs) ||
    629       !tls13_set_traffic_key(ssl, evp_aead_seal, hs->server_traffic_secret_0,
    630                              hs->hash_len)) {
    631     return ssl_hs_error;
    632   }
    633 
    634   if (ssl->early_data_accepted) {
    635     /* If accepting 0-RTT, we send tickets half-RTT. This gets the tickets on
    636      * the wire sooner and also avoids triggering a write on |SSL_read| when
    637      * processing the client Finished. This requires computing the client
    638      * Finished early. See draft-ietf-tls-tls13-18, section 4.5.1. */
    639     size_t finished_len;
    640     if (!tls13_finished_mac(hs, hs->expected_client_finished, &finished_len,
    641                             0 /* client */)) {
    642       return ssl_hs_error;
    643     }
    644 
    645     if (finished_len != hs->hash_len) {
    646       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
    647       return ssl_hs_error;
    648     }
    649 
    650     /* Feed the predicted Finished into the transcript. This allows us to derive
    651      * the resumption secret early and send half-RTT tickets.
    652      *
    653      * TODO(davidben): This will need to be updated for DTLS 1.3. */
    654     assert(!SSL_is_dtls(hs->ssl));
    655     uint8_t header[4] = {SSL3_MT_FINISHED, 0, 0, hs->hash_len};
    656     if (!SSL_TRANSCRIPT_update(&hs->transcript, header, sizeof(header)) ||
    657         !SSL_TRANSCRIPT_update(&hs->transcript, hs->expected_client_finished,
    658                                hs->hash_len) ||
    659         !tls13_derive_resumption_secret(hs) ||
    660         !add_new_session_tickets(hs)) {
    661       return ssl_hs_error;
    662     }
    663   }
    664 
    665   hs->tls13_state = state_read_second_client_flight;
    666   return ssl_hs_flush;
    667 }
    668 
    669 static enum ssl_hs_wait_t do_read_second_client_flight(SSL_HANDSHAKE *hs) {
    670   SSL *const ssl = hs->ssl;
    671   if (ssl->early_data_accepted) {
    672     if (!tls13_set_traffic_key(ssl, evp_aead_open, hs->early_traffic_secret,
    673                                hs->hash_len)) {
    674       return ssl_hs_error;
    675     }
    676     hs->can_early_write = 1;
    677     hs->can_early_read = 1;
    678     hs->tls13_state = state_process_end_of_early_data;
    679     return ssl_hs_read_end_of_early_data;
    680   }
    681   hs->tls13_state = state_process_end_of_early_data;
    682   return ssl_hs_ok;
    683 }
    684 
    685 static enum ssl_hs_wait_t do_process_end_of_early_data(SSL_HANDSHAKE *hs) {
    686   SSL *const ssl = hs->ssl;
    687   if (!tls13_set_traffic_key(ssl, evp_aead_open, hs->client_handshake_secret,
    688                              hs->hash_len)) {
    689     return ssl_hs_error;
    690   }
    691   hs->tls13_state = ssl->early_data_accepted ? state_process_client_finished
    692                                              : state_process_client_certificate;
    693   return ssl_hs_read_message;
    694 }
    695 
    696 static enum ssl_hs_wait_t do_process_client_certificate(SSL_HANDSHAKE *hs) {
    697   SSL *const ssl = hs->ssl;
    698   if (!hs->cert_request) {
    699     /* OpenSSL returns X509_V_OK when no certificates are requested. This is
    700      * classed by them as a bug, but it's assumed by at least NGINX. */
    701     hs->new_session->verify_result = X509_V_OK;
    702 
    703     /* Skip this state. */
    704     hs->tls13_state = state_process_channel_id;
    705     return ssl_hs_ok;
    706   }
    707 
    708   const int allow_anonymous =
    709       (ssl->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) == 0;
    710 
    711   if (!ssl_check_message_type(ssl, SSL3_MT_CERTIFICATE) ||
    712       !tls13_process_certificate(hs, allow_anonymous) ||
    713       !ssl_hash_current_message(hs)) {
    714     return ssl_hs_error;
    715   }
    716 
    717   hs->tls13_state = state_process_client_certificate_verify;
    718   return ssl_hs_read_message;
    719 }
    720 
    721 static enum ssl_hs_wait_t do_process_client_certificate_verify(
    722     SSL_HANDSHAKE *hs) {
    723   SSL *const ssl = hs->ssl;
    724   if (sk_CRYPTO_BUFFER_num(hs->new_session->certs) == 0) {
    725     /* Skip this state. */
    726     hs->tls13_state = state_process_channel_id;
    727     return ssl_hs_ok;
    728   }
    729 
    730   if (!ssl_check_message_type(ssl, SSL3_MT_CERTIFICATE_VERIFY) ||
    731       !tls13_process_certificate_verify(hs) ||
    732       !ssl_hash_current_message(hs)) {
    733     return ssl_hs_error;
    734   }
    735 
    736   hs->tls13_state = state_process_channel_id;
    737   return ssl_hs_read_message;
    738 }
    739 
    740 static enum ssl_hs_wait_t do_process_channel_id(SSL_HANDSHAKE *hs) {
    741   if (!hs->ssl->s3->tlsext_channel_id_valid) {
    742     hs->tls13_state = state_process_client_finished;
    743     return ssl_hs_ok;
    744   }
    745 
    746   if (!ssl_check_message_type(hs->ssl, SSL3_MT_CHANNEL_ID) ||
    747       !tls1_verify_channel_id(hs) ||
    748       !ssl_hash_current_message(hs)) {
    749     return ssl_hs_error;
    750   }
    751 
    752   hs->tls13_state = state_process_client_finished;
    753   return ssl_hs_read_message;
    754 }
    755 
    756 static enum ssl_hs_wait_t do_process_client_finished(SSL_HANDSHAKE *hs) {
    757   SSL *const ssl = hs->ssl;
    758   if (!ssl_check_message_type(ssl, SSL3_MT_FINISHED) ||
    759       /* If early data was accepted, we've already computed the client Finished
    760        * and derived the resumption secret. */
    761       !tls13_process_finished(hs, ssl->early_data_accepted) ||
    762       /* evp_aead_seal keys have already been switched. */
    763       !tls13_set_traffic_key(ssl, evp_aead_open, hs->client_traffic_secret_0,
    764                              hs->hash_len)) {
    765     return ssl_hs_error;
    766   }
    767 
    768   ssl->method->received_flight(ssl);
    769 
    770   if (!ssl->early_data_accepted) {
    771     if (!ssl_hash_current_message(hs) ||
    772         !tls13_derive_resumption_secret(hs)) {
    773       return ssl_hs_error;
    774     }
    775 
    776     /* We send post-handshake tickets as part of the handshake in 1-RTT. */
    777     hs->tls13_state = state_send_new_session_ticket;
    778     return ssl_hs_ok;
    779   }
    780 
    781   hs->tls13_state = state_done;
    782   return ssl_hs_ok;
    783 }
    784 
    785 static enum ssl_hs_wait_t do_send_new_session_ticket(SSL_HANDSHAKE *hs) {
    786   /* If the client doesn't accept resumption with PSK_DHE_KE, don't send a
    787    * session ticket. */
    788   if (!hs->accept_psk_mode) {
    789     hs->tls13_state = state_done;
    790     return ssl_hs_ok;
    791   }
    792 
    793   if (!add_new_session_tickets(hs)) {
    794     return ssl_hs_error;
    795   }
    796 
    797   hs->tls13_state = state_done;
    798   return ssl_hs_flush;
    799 }
    800 
    801 enum ssl_hs_wait_t tls13_server_handshake(SSL_HANDSHAKE *hs) {
    802   while (hs->tls13_state != state_done) {
    803     enum ssl_hs_wait_t ret = ssl_hs_error;
    804     enum server_hs_state_t state = hs->tls13_state;
    805     switch (state) {
    806       case state_select_parameters:
    807         ret = do_select_parameters(hs);
    808         break;
    809       case state_select_session:
    810         ret = do_select_session(hs);
    811         break;
    812       case state_send_hello_retry_request:
    813         ret = do_send_hello_retry_request(hs);
    814         break;
    815       case state_process_second_client_hello:
    816         ret = do_process_second_client_hello(hs);
    817         break;
    818       case state_send_server_hello:
    819         ret = do_send_server_hello(hs);
    820         break;
    821       case state_send_server_certificate_verify:
    822         ret = do_send_server_certificate_verify(hs, 1 /* first run */);
    823       break;
    824       case state_complete_server_certificate_verify:
    825         ret = do_send_server_certificate_verify(hs, 0 /* complete */);
    826         break;
    827       case state_send_server_finished:
    828         ret = do_send_server_finished(hs);
    829         break;
    830       case state_read_second_client_flight:
    831         ret = do_read_second_client_flight(hs);
    832         break;
    833       case state_process_end_of_early_data:
    834         ret = do_process_end_of_early_data(hs);
    835         break;
    836       case state_process_client_certificate:
    837         ret = do_process_client_certificate(hs);
    838         break;
    839       case state_process_client_certificate_verify:
    840         ret = do_process_client_certificate_verify(hs);
    841         break;
    842       case state_process_channel_id:
    843         ret = do_process_channel_id(hs);
    844         break;
    845       case state_process_client_finished:
    846         ret = do_process_client_finished(hs);
    847         break;
    848       case state_send_new_session_ticket:
    849         ret = do_send_new_session_ticket(hs);
    850         break;
    851       case state_done:
    852         ret = ssl_hs_ok;
    853         break;
    854     }
    855 
    856     if (ret != ssl_hs_ok) {
    857       return ret;
    858     }
    859   }
    860 
    861   return ssl_hs_ok;
    862 }
    863