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