• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2016, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14 
15 #include <openssl/ssl.h>
16 
17 #include <assert.h>
18 #include <string.h>
19 
20 #include <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 enum server_hs_state_t {
37   state_select_parameters = 0,
38   state_select_session,
39   state_send_hello_retry_request,
40   state_read_second_client_hello,
41   state_send_server_hello,
42   state_send_server_certificate_verify,
43   state_send_server_finished,
44   state_read_second_client_flight,
45   state_process_end_of_early_data,
46   state_read_client_certificate,
47   state_read_client_certificate_verify,
48   state_read_channel_id,
49   state_read_client_finished,
50   state_send_new_session_ticket,
51   state_done,
52 };
53 
54 static const uint8_t kZeroes[EVP_MAX_MD_SIZE] = {0};
55 
56 // Allow a minute of ticket age skew in either direction. This covers
57 // transmission delays in ClientHello and NewSessionTicket, as well as
58 // drift between client and server clock rate since the ticket was issued.
59 // See RFC 8446, section 8.3.
60 static const int32_t kMaxTicketAgeSkewSeconds = 60;
61 
resolve_ecdhe_secret(SSL_HANDSHAKE * hs,bool * out_need_retry,SSL_CLIENT_HELLO * client_hello)62 static int resolve_ecdhe_secret(SSL_HANDSHAKE *hs, bool *out_need_retry,
63                                 SSL_CLIENT_HELLO *client_hello) {
64   SSL *const ssl = hs->ssl;
65   *out_need_retry = false;
66 
67   // We only support connections that include an ECDHE key exchange.
68   CBS key_share;
69   if (!ssl_client_hello_get_extension(client_hello, &key_share,
70                                       TLSEXT_TYPE_key_share)) {
71     OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_KEY_SHARE);
72     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_MISSING_EXTENSION);
73     return 0;
74   }
75 
76   bool found_key_share;
77   Array<uint8_t> dhe_secret;
78   uint8_t alert = SSL_AD_DECODE_ERROR;
79   if (!ssl_ext_key_share_parse_clienthello(hs, &found_key_share, &dhe_secret,
80                                            &alert, &key_share)) {
81     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
82     return 0;
83   }
84 
85   if (!found_key_share) {
86     *out_need_retry = true;
87     return 0;
88   }
89 
90   return tls13_advance_key_schedule(hs, dhe_secret);
91 }
92 
ssl_ext_supported_versions_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)93 static int ssl_ext_supported_versions_add_serverhello(SSL_HANDSHAKE *hs,
94                                                       CBB *out) {
95   CBB contents;
96   if (!CBB_add_u16(out, TLSEXT_TYPE_supported_versions) ||
97       !CBB_add_u16_length_prefixed(out, &contents) ||
98       !CBB_add_u16(&contents, hs->ssl->version) ||
99       !CBB_flush(out)) {
100     return 0;
101   }
102 
103   return 1;
104 }
105 
choose_tls13_cipher(const SSL * ssl,const SSL_CLIENT_HELLO * client_hello,uint16_t group_id)106 static const SSL_CIPHER *choose_tls13_cipher(
107     const SSL *ssl, const SSL_CLIENT_HELLO *client_hello, uint16_t group_id) {
108   CBS cipher_suites;
109   CBS_init(&cipher_suites, client_hello->cipher_suites,
110            client_hello->cipher_suites_len);
111 
112   const uint16_t version = ssl_protocol_version(ssl);
113 
114   return ssl_choose_tls13_cipher(cipher_suites, version, group_id);
115 }
116 
add_new_session_tickets(SSL_HANDSHAKE * hs,bool * out_sent_tickets)117 static bool add_new_session_tickets(SSL_HANDSHAKE *hs, bool *out_sent_tickets) {
118   SSL *const ssl = hs->ssl;
119   if (// If the client doesn't accept resumption with PSK_DHE_KE, don't send a
120       // session ticket.
121       !hs->accept_psk_mode ||
122       // We only implement stateless resumption in TLS 1.3, so skip sending
123       // tickets if disabled.
124       (SSL_get_options(ssl) & SSL_OP_NO_TICKET)) {
125     *out_sent_tickets = false;
126     return true;
127   }
128 
129   // TLS 1.3 recommends single-use tickets, so issue multiple tickets in case
130   // the client makes several connections before getting a renewal.
131   static const int kNumTickets = 2;
132 
133   // Rebase the session timestamp so that it is measured from ticket
134   // issuance.
135   ssl_session_rebase_time(ssl, hs->new_session.get());
136 
137   for (int i = 0; i < kNumTickets; i++) {
138     UniquePtr<SSL_SESSION> session(
139         SSL_SESSION_dup(hs->new_session.get(), SSL_SESSION_INCLUDE_NONAUTH));
140     if (!session) {
141       return false;
142     }
143 
144     if (!RAND_bytes((uint8_t *)&session->ticket_age_add, 4)) {
145       return false;
146     }
147     session->ticket_age_add_valid = true;
148     if (ssl->enable_early_data) {
149       // QUIC does not use the max_early_data_size parameter and always sets it
150       // to a fixed value. See draft-ietf-quic-tls-22, section 4.5.
151       session->ticket_max_early_data =
152           ssl->quic_method != nullptr ? 0xffffffff : kMaxEarlyDataAccepted;
153     }
154 
155     static_assert(kNumTickets < 256, "Too many tickets");
156     uint8_t nonce[] = {static_cast<uint8_t>(i)};
157 
158     ScopedCBB cbb;
159     CBB body, nonce_cbb, ticket, extensions;
160     if (!ssl->method->init_message(ssl, cbb.get(), &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_u8_length_prefixed(&body, &nonce_cbb) ||
165         !CBB_add_bytes(&nonce_cbb, nonce, sizeof(nonce)) ||
166         !CBB_add_u16_length_prefixed(&body, &ticket) ||
167         !tls13_derive_session_psk(session.get(), nonce) ||
168         !ssl_encrypt_ticket(hs, &ticket, session.get()) ||
169         !CBB_add_u16_length_prefixed(&body, &extensions)) {
170       return false;
171     }
172 
173     if (ssl->enable_early_data) {
174       CBB early_data;
175       if (!CBB_add_u16(&extensions, TLSEXT_TYPE_early_data) ||
176           !CBB_add_u16_length_prefixed(&extensions, &early_data) ||
177           !CBB_add_u32(&early_data, session->ticket_max_early_data) ||
178           !CBB_flush(&extensions)) {
179         return false;
180       }
181     }
182 
183     // Add a fake extension. See draft-davidben-tls-grease-01.
184     if (!CBB_add_u16(&extensions,
185                      ssl_get_grease_value(hs, ssl_grease_ticket_extension)) ||
186         !CBB_add_u16(&extensions, 0 /* empty */)) {
187       return false;
188     }
189 
190     if (!ssl_add_message_cbb(ssl, cbb.get())) {
191       return false;
192     }
193   }
194 
195   *out_sent_tickets = true;
196   return true;
197 }
198 
do_select_parameters(SSL_HANDSHAKE * hs)199 static enum ssl_hs_wait_t do_select_parameters(SSL_HANDSHAKE *hs) {
200   // At this point, most ClientHello extensions have already been processed by
201   // the common handshake logic. Resolve the remaining non-PSK parameters.
202   SSL *const ssl = hs->ssl;
203   SSLMessage msg;
204   if (!ssl->method->get_message(ssl, &msg)) {
205     return ssl_hs_read_message;
206   }
207   SSL_CLIENT_HELLO client_hello;
208   if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
209     OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_PARSE_FAILED);
210     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
211     return ssl_hs_error;
212   }
213 
214   OPENSSL_memcpy(hs->session_id, client_hello.session_id,
215                  client_hello.session_id_len);
216   hs->session_id_len = client_hello.session_id_len;
217 
218   uint16_t group_id;
219   if (!tls1_get_shared_group(hs, &group_id)) {
220     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_GROUP);
221     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
222     return ssl_hs_error;
223   }
224 
225   // Negotiate the cipher suite.
226   hs->new_cipher = choose_tls13_cipher(ssl, &client_hello, group_id);
227   if (hs->new_cipher == NULL) {
228     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_CIPHER);
229     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
230     return ssl_hs_error;
231   }
232 
233   // HTTP/2 negotiation depends on the cipher suite, so ALPN negotiation was
234   // deferred. Complete it now.
235   uint8_t alert = SSL_AD_DECODE_ERROR;
236   if (!ssl_negotiate_alpn(hs, &alert, &client_hello)) {
237     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
238     return ssl_hs_error;
239   }
240 
241   // The PRF hash is now known. Set up the key schedule and hash the
242   // ClientHello.
243   if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher)) {
244     return ssl_hs_error;
245   }
246 
247   hs->tls13_state = state_select_session;
248   return ssl_hs_ok;
249 }
250 
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)251 static enum ssl_ticket_aead_result_t select_session(
252     SSL_HANDSHAKE *hs, uint8_t *out_alert, UniquePtr<SSL_SESSION> *out_session,
253     int32_t *out_ticket_age_skew, bool *out_offered_ticket,
254     const SSLMessage &msg, const SSL_CLIENT_HELLO *client_hello) {
255   SSL *const ssl = hs->ssl;
256   *out_session = nullptr;
257 
258   CBS pre_shared_key;
259   *out_offered_ticket = ssl_client_hello_get_extension(
260       client_hello, &pre_shared_key, TLSEXT_TYPE_pre_shared_key);
261   if (!*out_offered_ticket) {
262     return ssl_ticket_aead_ignore_ticket;
263   }
264 
265   CBS ticket, binders;
266   uint32_t client_ticket_age;
267   if (!ssl_ext_pre_shared_key_parse_clienthello(
268           hs, &ticket, &binders, &client_ticket_age, out_alert, client_hello,
269           &pre_shared_key)) {
270     return ssl_ticket_aead_error;
271   }
272 
273   // If the peer did not offer psk_dhe, ignore the resumption.
274   if (!hs->accept_psk_mode) {
275     return ssl_ticket_aead_ignore_ticket;
276   }
277 
278   // TLS 1.3 session tickets are renewed separately as part of the
279   // NewSessionTicket.
280   bool unused_renew;
281   UniquePtr<SSL_SESSION> session;
282   enum ssl_ticket_aead_result_t ret =
283       ssl_process_ticket(hs, &session, &unused_renew, ticket, {});
284   switch (ret) {
285     case ssl_ticket_aead_success:
286       break;
287     case ssl_ticket_aead_error:
288       *out_alert = SSL_AD_INTERNAL_ERROR;
289       return ret;
290     default:
291       return ret;
292   }
293 
294   if (!ssl_session_is_resumable(hs, session.get()) ||
295       // Historically, some TLS 1.3 tickets were missing ticket_age_add.
296       !session->ticket_age_add_valid) {
297     return ssl_ticket_aead_ignore_ticket;
298   }
299 
300   // Recover the client ticket age and convert to seconds.
301   client_ticket_age -= session->ticket_age_add;
302   client_ticket_age /= 1000;
303 
304   struct OPENSSL_timeval now;
305   ssl_get_current_time(ssl, &now);
306 
307   // Compute the server ticket age in seconds.
308   assert(now.tv_sec >= session->time);
309   uint64_t server_ticket_age = now.tv_sec - session->time;
310 
311   // To avoid overflowing |hs->ticket_age_skew|, we will not resume
312   // 68-year-old sessions.
313   if (server_ticket_age > INT32_MAX) {
314     return ssl_ticket_aead_ignore_ticket;
315   }
316 
317   *out_ticket_age_skew = static_cast<int32_t>(client_ticket_age) -
318                          static_cast<int32_t>(server_ticket_age);
319 
320   // Check the PSK binder.
321   if (!tls13_verify_psk_binder(hs, session.get(), msg, &binders)) {
322     *out_alert = SSL_AD_DECRYPT_ERROR;
323     return ssl_ticket_aead_error;
324   }
325 
326   *out_session = std::move(session);
327   return ssl_ticket_aead_success;
328 }
329 
do_select_session(SSL_HANDSHAKE * hs)330 static enum ssl_hs_wait_t do_select_session(SSL_HANDSHAKE *hs) {
331   SSL *const ssl = hs->ssl;
332   SSLMessage msg;
333   if (!ssl->method->get_message(ssl, &msg)) {
334     return ssl_hs_read_message;
335   }
336   SSL_CLIENT_HELLO client_hello;
337   if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
338     OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_PARSE_FAILED);
339     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
340     return ssl_hs_error;
341   }
342 
343   uint8_t alert = SSL_AD_DECODE_ERROR;
344   UniquePtr<SSL_SESSION> session;
345   bool offered_ticket = false;
346   switch (select_session(hs, &alert, &session, &ssl->s3->ticket_age_skew,
347                          &offered_ticket, msg, &client_hello)) {
348     case ssl_ticket_aead_ignore_ticket:
349       assert(!session);
350       if (!ssl->enable_early_data) {
351         ssl->s3->early_data_reason = ssl_early_data_disabled;
352       } else if (!offered_ticket) {
353         ssl->s3->early_data_reason = ssl_early_data_no_session_offered;
354       } else {
355         ssl->s3->early_data_reason = ssl_early_data_session_not_resumed;
356       }
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       if (!ssl->enable_early_data) {
374         ssl->s3->early_data_reason = ssl_early_data_disabled;
375       } else if (session->ticket_max_early_data == 0) {
376         ssl->s3->early_data_reason = ssl_early_data_unsupported_for_session;
377       } else if (!hs->early_data_offered) {
378         ssl->s3->early_data_reason = ssl_early_data_peer_declined;
379       } else if (ssl->s3->channel_id_valid) {
380           // Channel ID is incompatible with 0-RTT.
381         ssl->s3->early_data_reason = ssl_early_data_channel_id;
382       } else if (ssl->s3->token_binding_negotiated) {
383           // Token Binding is incompatible with 0-RTT.
384         ssl->s3->early_data_reason = ssl_early_data_token_binding;
385       } else if (MakeConstSpan(ssl->s3->alpn_selected) != session->early_alpn) {
386         // The negotiated ALPN must match the one in the ticket.
387         ssl->s3->early_data_reason = ssl_early_data_alpn_mismatch;
388       } else if (ssl->s3->ticket_age_skew < -kMaxTicketAgeSkewSeconds ||
389                  kMaxTicketAgeSkewSeconds < ssl->s3->ticket_age_skew) {
390         ssl->s3->early_data_reason = ssl_early_data_ticket_age_skew;
391       } else {
392         ssl->s3->early_data_reason = ssl_early_data_accepted;
393         ssl->s3->early_data_accepted = true;
394       }
395 
396       ssl->s3->session_reused = true;
397 
398       // Resumption incorporates fresh key material, so refresh the timeout.
399       ssl_session_renew_timeout(ssl, hs->new_session.get(),
400                                 ssl->session_ctx->session_psk_dhe_timeout);
401       break;
402 
403     case ssl_ticket_aead_error:
404       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
405       return ssl_hs_error;
406 
407     case ssl_ticket_aead_retry:
408       hs->tls13_state = state_select_session;
409       return ssl_hs_pending_ticket;
410   }
411 
412   // Record connection properties in the new session.
413   hs->new_session->cipher = hs->new_cipher;
414 
415   // Store the initial negotiated ALPN in the session.
416   if (!hs->new_session->early_alpn.CopyFrom(ssl->s3->alpn_selected)) {
417     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
418     return ssl_hs_error;
419   }
420 
421   if (ssl->ctx->dos_protection_cb != NULL &&
422       ssl->ctx->dos_protection_cb(&client_hello) == 0) {
423     // Connection rejected for DOS reasons.
424     OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
425     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
426     return ssl_hs_error;
427   }
428 
429   size_t hash_len = EVP_MD_size(
430       ssl_get_handshake_digest(ssl_protocol_version(ssl), hs->new_cipher));
431 
432   // Set up the key schedule and incorporate the PSK into the running secret.
433   if (ssl->s3->session_reused) {
434     if (!tls13_init_key_schedule(
435             hs, MakeConstSpan(hs->new_session->master_key,
436                               hs->new_session->master_key_length))) {
437       return ssl_hs_error;
438     }
439   } else if (!tls13_init_key_schedule(hs, MakeConstSpan(kZeroes, hash_len))) {
440     return ssl_hs_error;
441   }
442 
443   if (!ssl_hash_message(hs, msg)) {
444     return ssl_hs_error;
445   }
446 
447   if (ssl->s3->early_data_accepted) {
448     if (!tls13_derive_early_secret(hs)) {
449       return ssl_hs_error;
450     }
451   } else if (hs->early_data_offered) {
452     ssl->s3->skip_early_data = true;
453   }
454 
455   // Resolve ECDHE and incorporate it into the secret.
456   bool need_retry;
457   if (!resolve_ecdhe_secret(hs, &need_retry, &client_hello)) {
458     if (need_retry) {
459       if (ssl->s3->early_data_accepted) {
460         ssl->s3->early_data_reason = ssl_early_data_hello_retry_request;
461         ssl->s3->early_data_accepted = false;
462       }
463       ssl->s3->skip_early_data = true;
464       ssl->method->next_message(ssl);
465       if (!hs->transcript.UpdateForHelloRetryRequest()) {
466         return ssl_hs_error;
467       }
468       hs->tls13_state = state_send_hello_retry_request;
469       return ssl_hs_ok;
470     }
471     return ssl_hs_error;
472   }
473 
474   // Note we defer releasing the early traffic secret to QUIC until after ECDHE
475   // is resolved. The early traffic secret should be derived before the key
476   // schedule incorporates ECDHE, but doing so may reject 0-RTT. To avoid
477   // confusing the caller, we split derivation and releasing the secret to QUIC.
478   if (ssl->s3->early_data_accepted &&
479       !tls13_set_early_secret_for_quic(hs)) {
480     return ssl_hs_error;
481   }
482 
483   ssl->method->next_message(ssl);
484   hs->tls13_state = state_send_server_hello;
485   return ssl_hs_ok;
486 }
487 
do_send_hello_retry_request(SSL_HANDSHAKE * hs)488 static enum ssl_hs_wait_t do_send_hello_retry_request(SSL_HANDSHAKE *hs) {
489   SSL *const ssl = hs->ssl;
490 
491 
492   ScopedCBB cbb;
493   CBB body, session_id, extensions;
494   uint16_t group_id;
495   if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_SERVER_HELLO) ||
496       !CBB_add_u16(&body, TLS1_2_VERSION) ||
497       !CBB_add_bytes(&body, kHelloRetryRequest, SSL3_RANDOM_SIZE) ||
498       !CBB_add_u8_length_prefixed(&body, &session_id) ||
499       !CBB_add_bytes(&session_id, hs->session_id, hs->session_id_len) ||
500       !CBB_add_u16(&body, ssl_cipher_get_value(hs->new_cipher)) ||
501       !CBB_add_u8(&body, 0 /* no compression */) ||
502       !tls1_get_shared_group(hs, &group_id) ||
503       !CBB_add_u16_length_prefixed(&body, &extensions) ||
504       !CBB_add_u16(&extensions, TLSEXT_TYPE_supported_versions) ||
505       !CBB_add_u16(&extensions, 2 /* length */) ||
506       !CBB_add_u16(&extensions, ssl->version) ||
507       !CBB_add_u16(&extensions, TLSEXT_TYPE_key_share) ||
508       !CBB_add_u16(&extensions, 2 /* length */) ||
509       !CBB_add_u16(&extensions, group_id) ||
510       !ssl_add_message_cbb(ssl, cbb.get())) {
511     return ssl_hs_error;
512   }
513 
514   if (!ssl->method->add_change_cipher_spec(ssl)) {
515     return ssl_hs_error;
516   }
517 
518   hs->sent_hello_retry_request = true;
519   hs->tls13_state = state_read_second_client_hello;
520   return ssl_hs_flush;
521 }
522 
do_read_second_client_hello(SSL_HANDSHAKE * hs)523 static enum ssl_hs_wait_t do_read_second_client_hello(SSL_HANDSHAKE *hs) {
524   SSL *const ssl = hs->ssl;
525   SSLMessage msg;
526   if (!ssl->method->get_message(ssl, &msg)) {
527     return ssl_hs_read_message;
528   }
529   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CLIENT_HELLO)) {
530     return ssl_hs_error;
531   }
532   SSL_CLIENT_HELLO client_hello;
533   if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
534     OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_PARSE_FAILED);
535     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
536     return ssl_hs_error;
537   }
538 
539   // We perform all our negotiation based on the first ClientHello (for
540   // consistency with what |select_certificate_cb| observed), which is in the
541   // transcript, so we can ignore most of this second one.
542   //
543   // We do, however, check the second PSK binder. This covers the client key
544   // share, in case we ever send half-RTT data (we currently do not). It is also
545   // a tricky computation, so we enforce the peer handled it correctly.
546   if (ssl->s3->session_reused) {
547     CBS pre_shared_key;
548     if (!ssl_client_hello_get_extension(&client_hello, &pre_shared_key,
549                                         TLSEXT_TYPE_pre_shared_key)) {
550       OPENSSL_PUT_ERROR(SSL, SSL_R_INCONSISTENT_CLIENT_HELLO);
551       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
552       return ssl_hs_error;
553     }
554 
555     CBS ticket, binders;
556     uint32_t client_ticket_age;
557     uint8_t alert = SSL_AD_DECODE_ERROR;
558     if (!ssl_ext_pre_shared_key_parse_clienthello(
559             hs, &ticket, &binders, &client_ticket_age, &alert, &client_hello,
560             &pre_shared_key)) {
561       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
562       return ssl_hs_error;
563     }
564 
565     // Note it is important that we do not obtain a new |SSL_SESSION| from
566     // |ticket|. We have already selected parameters based on the first
567     // ClientHello (in the transcript) and must not switch partway through.
568     if (!tls13_verify_psk_binder(hs, hs->new_session.get(), msg, &binders)) {
569       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
570       return ssl_hs_error;
571     }
572   }
573 
574   bool need_retry;
575   if (!resolve_ecdhe_secret(hs, &need_retry, &client_hello)) {
576     if (need_retry) {
577       // Only send one HelloRetryRequest.
578       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
579       OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
580     }
581     return ssl_hs_error;
582   }
583 
584   if (!ssl_hash_message(hs, msg)) {
585     return ssl_hs_error;
586   }
587 
588   ssl->method->next_message(ssl);
589   hs->tls13_state = state_send_server_hello;
590   return ssl_hs_ok;
591 }
592 
do_send_server_hello(SSL_HANDSHAKE * hs)593 static enum ssl_hs_wait_t do_send_server_hello(SSL_HANDSHAKE *hs) {
594   SSL *const ssl = hs->ssl;
595 
596   // Send a ServerHello.
597   ScopedCBB cbb;
598   CBB body, extensions, session_id;
599   if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_SERVER_HELLO) ||
600       !CBB_add_u16(&body, TLS1_2_VERSION) ||
601       !RAND_bytes(ssl->s3->server_random, sizeof(ssl->s3->server_random)) ||
602       !CBB_add_bytes(&body, ssl->s3->server_random, SSL3_RANDOM_SIZE) ||
603       !CBB_add_u8_length_prefixed(&body, &session_id) ||
604       !CBB_add_bytes(&session_id, hs->session_id, hs->session_id_len) ||
605       !CBB_add_u16(&body, ssl_cipher_get_value(hs->new_cipher)) ||
606       !CBB_add_u8(&body, 0) ||
607       !CBB_add_u16_length_prefixed(&body, &extensions) ||
608       !ssl_ext_pre_shared_key_add_serverhello(hs, &extensions) ||
609       !ssl_ext_key_share_add_serverhello(hs, &extensions) ||
610       !ssl_ext_supported_versions_add_serverhello(hs, &extensions) ||
611       !ssl_add_message_cbb(ssl, cbb.get())) {
612     return ssl_hs_error;
613   }
614 
615   if (!hs->sent_hello_retry_request &&
616       !ssl->method->add_change_cipher_spec(ssl)) {
617     return ssl_hs_error;
618   }
619 
620   // Derive and enable the handshake traffic secrets.
621   if (!tls13_derive_handshake_secrets(hs) ||
622       !tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_seal,
623                              hs->server_handshake_secret())) {
624     return ssl_hs_error;
625   }
626 
627   // Send EncryptedExtensions.
628   if (!ssl->method->init_message(ssl, cbb.get(), &body,
629                                  SSL3_MT_ENCRYPTED_EXTENSIONS) ||
630       !ssl_add_serverhello_tlsext(hs, &body) ||
631       !ssl_add_message_cbb(ssl, cbb.get())) {
632     return ssl_hs_error;
633   }
634 
635   if (!ssl->s3->session_reused) {
636     // Determine whether to request a client certificate.
637     hs->cert_request = !!(hs->config->verify_mode & SSL_VERIFY_PEER);
638     // Only request a certificate if Channel ID isn't negotiated.
639     if ((hs->config->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
640         ssl->s3->channel_id_valid) {
641       hs->cert_request = false;
642     }
643   }
644 
645   // Send a CertificateRequest, if necessary.
646   if (hs->cert_request) {
647     CBB cert_request_extensions, sigalg_contents, sigalgs_cbb;
648     if (!ssl->method->init_message(ssl, cbb.get(), &body,
649                                    SSL3_MT_CERTIFICATE_REQUEST) ||
650         !CBB_add_u8(&body, 0 /* no certificate_request_context. */) ||
651         !CBB_add_u16_length_prefixed(&body, &cert_request_extensions) ||
652         !CBB_add_u16(&cert_request_extensions,
653                      TLSEXT_TYPE_signature_algorithms) ||
654         !CBB_add_u16_length_prefixed(&cert_request_extensions,
655                                      &sigalg_contents) ||
656         !CBB_add_u16_length_prefixed(&sigalg_contents, &sigalgs_cbb) ||
657         !tls12_add_verify_sigalgs(ssl, &sigalgs_cbb,
658                                   false /* online signature */)) {
659       return ssl_hs_error;
660     }
661 
662     if (tls12_has_different_verify_sigalgs_for_certs(ssl)) {
663       if (!CBB_add_u16(&cert_request_extensions,
664                        TLSEXT_TYPE_signature_algorithms_cert) ||
665           !CBB_add_u16_length_prefixed(&cert_request_extensions,
666                                        &sigalg_contents) ||
667           !CBB_add_u16_length_prefixed(&sigalg_contents, &sigalgs_cbb) ||
668           !tls12_add_verify_sigalgs(ssl, &sigalgs_cbb, true /* certs */)) {
669         return ssl_hs_error;
670       }
671     }
672 
673     if (ssl_has_client_CAs(hs->config)) {
674       CBB ca_contents;
675       if (!CBB_add_u16(&cert_request_extensions,
676                        TLSEXT_TYPE_certificate_authorities) ||
677           !CBB_add_u16_length_prefixed(&cert_request_extensions,
678                                        &ca_contents) ||
679           !ssl_add_client_CA_list(hs, &ca_contents) ||
680           !CBB_flush(&cert_request_extensions)) {
681         return ssl_hs_error;
682       }
683     }
684 
685     if (!ssl_add_message_cbb(ssl, cbb.get())) {
686       return ssl_hs_error;
687     }
688   }
689 
690   // Send the server Certificate message, if necessary.
691   if (!ssl->s3->session_reused) {
692     if (!ssl_has_certificate(hs)) {
693       OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATE_SET);
694       return ssl_hs_error;
695     }
696 
697     if (!tls13_add_certificate(hs)) {
698       return ssl_hs_error;
699     }
700 
701     hs->tls13_state = state_send_server_certificate_verify;
702     return ssl_hs_ok;
703   }
704 
705   hs->tls13_state = state_send_server_finished;
706   return ssl_hs_ok;
707 }
708 
do_send_server_certificate_verify(SSL_HANDSHAKE * hs)709 static enum ssl_hs_wait_t do_send_server_certificate_verify(SSL_HANDSHAKE *hs) {
710   switch (tls13_add_certificate_verify(hs)) {
711     case ssl_private_key_success:
712       hs->tls13_state = state_send_server_finished;
713       return ssl_hs_ok;
714 
715     case ssl_private_key_retry:
716       hs->tls13_state = state_send_server_certificate_verify;
717       return ssl_hs_private_key_operation;
718 
719     case ssl_private_key_failure:
720       return ssl_hs_error;
721   }
722 
723   assert(0);
724   return ssl_hs_error;
725 }
726 
do_send_server_finished(SSL_HANDSHAKE * hs)727 static enum ssl_hs_wait_t do_send_server_finished(SSL_HANDSHAKE *hs) {
728   SSL *const ssl = hs->ssl;
729   if (!tls13_add_finished(hs) ||
730       // Update the secret to the master secret and derive traffic keys.
731       !tls13_advance_key_schedule(
732           hs, MakeConstSpan(kZeroes, hs->transcript.DigestLen())) ||
733       !tls13_derive_application_secrets(hs) ||
734       !tls13_set_traffic_key(ssl, ssl_encryption_application, evp_aead_seal,
735                              hs->server_traffic_secret_0())) {
736     return ssl_hs_error;
737   }
738 
739   if (ssl->s3->early_data_accepted) {
740     // If accepting 0-RTT, we send tickets half-RTT. This gets the tickets on
741     // the wire sooner and also avoids triggering a write on |SSL_read| when
742     // processing the client Finished. This requires computing the client
743     // Finished early. See RFC 8446, section 4.6.1.
744     static const uint8_t kEndOfEarlyData[4] = {SSL3_MT_END_OF_EARLY_DATA, 0,
745                                                0, 0};
746     if (ssl->quic_method == nullptr &&
747         !hs->transcript.Update(kEndOfEarlyData)) {
748       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
749       return ssl_hs_error;
750     }
751 
752     size_t finished_len;
753     if (!tls13_finished_mac(hs, hs->expected_client_finished().data(),
754                             &finished_len, false /* client */)) {
755       return ssl_hs_error;
756     }
757 
758     if (finished_len != hs->expected_client_finished().size()) {
759       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
760       return ssl_hs_error;
761     }
762 
763     // Feed the predicted Finished into the transcript. This allows us to derive
764     // the resumption secret early and send half-RTT tickets.
765     //
766     // TODO(davidben): This will need to be updated for DTLS 1.3.
767     assert(!SSL_is_dtls(hs->ssl));
768     assert(hs->expected_client_finished().size() <= 0xff);
769     uint8_t header[4] = {
770         SSL3_MT_FINISHED, 0, 0,
771         static_cast<uint8_t>(hs->expected_client_finished().size())};
772     bool unused_sent_tickets;
773     if (!hs->transcript.Update(header) ||
774         !hs->transcript.Update(hs->expected_client_finished()) ||
775         !tls13_derive_resumption_secret(hs) ||
776         !add_new_session_tickets(hs, &unused_sent_tickets)) {
777       return ssl_hs_error;
778     }
779   }
780 
781   hs->tls13_state = state_read_second_client_flight;
782   return ssl_hs_flush;
783 }
784 
do_read_second_client_flight(SSL_HANDSHAKE * hs)785 static enum ssl_hs_wait_t do_read_second_client_flight(SSL_HANDSHAKE *hs) {
786   SSL *const ssl = hs->ssl;
787   if (ssl->s3->early_data_accepted) {
788     // QUIC never receives handshake messages under 0-RTT keys.
789     if (ssl->quic_method == nullptr &&
790         !tls13_set_traffic_key(ssl, ssl_encryption_early_data, evp_aead_open,
791                                hs->early_traffic_secret())) {
792       return ssl_hs_error;
793     }
794     hs->can_early_write = true;
795     hs->can_early_read = true;
796     hs->in_early_data = true;
797   }
798 
799   // QUIC doesn't use an EndOfEarlyData message (draft-ietf-quic-tls-22,
800   // section 8.3), so we switch to client_handshake_secret before the early
801   // return.
802   if (ssl->quic_method != nullptr) {
803     if (!tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_open,
804                                hs->client_handshake_secret())) {
805       return ssl_hs_error;
806     }
807     hs->tls13_state = state_read_client_certificate;
808     return ssl->s3->early_data_accepted ? ssl_hs_early_return : ssl_hs_ok;
809   }
810 
811   hs->tls13_state = state_process_end_of_early_data;
812   return ssl->s3->early_data_accepted ? ssl_hs_read_end_of_early_data
813                                       : ssl_hs_ok;
814 }
815 
do_process_end_of_early_data(SSL_HANDSHAKE * hs)816 static enum ssl_hs_wait_t do_process_end_of_early_data(SSL_HANDSHAKE *hs) {
817   SSL *const ssl = hs->ssl;
818   // If early data was not accepted, the EndOfEarlyData will be in the discarded
819   // early data.
820   if (hs->ssl->s3->early_data_accepted) {
821     SSLMessage msg;
822     if (!ssl->method->get_message(ssl, &msg)) {
823       return ssl_hs_read_message;
824     }
825     if (!ssl_check_message_type(ssl, msg, SSL3_MT_END_OF_EARLY_DATA)) {
826       return ssl_hs_error;
827     }
828     if (CBS_len(&msg.body) != 0) {
829       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
830       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
831       return ssl_hs_error;
832     }
833     ssl->method->next_message(ssl);
834   }
835   if (!tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_open,
836                              hs->client_handshake_secret())) {
837     return ssl_hs_error;
838   }
839   hs->tls13_state = state_read_client_certificate;
840   return ssl_hs_ok;
841 }
842 
do_read_client_certificate(SSL_HANDSHAKE * hs)843 static enum ssl_hs_wait_t do_read_client_certificate(SSL_HANDSHAKE *hs) {
844   SSL *const ssl = hs->ssl;
845   if (!hs->cert_request) {
846     if (!ssl->s3->session_reused) {
847       // OpenSSL returns X509_V_OK when no certificates are requested. This is
848       // classed by them as a bug, but it's assumed by at least NGINX. (Only do
849       // this in full handshakes as resumptions should carry over the previous
850       // |verify_result|, though this is a no-op because servers do not
851       // implement the client's odd soft-fail mode.)
852       hs->new_session->verify_result = X509_V_OK;
853     }
854 
855     // Skip this state.
856     hs->tls13_state = state_read_channel_id;
857     return ssl_hs_ok;
858   }
859 
860   const bool allow_anonymous =
861       (hs->config->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) == 0;
862   SSLMessage msg;
863   if (!ssl->method->get_message(ssl, &msg)) {
864     return ssl_hs_read_message;
865   }
866   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE) ||
867       !tls13_process_certificate(hs, msg, allow_anonymous) ||
868       !ssl_hash_message(hs, msg)) {
869     return ssl_hs_error;
870   }
871 
872   ssl->method->next_message(ssl);
873   hs->tls13_state = state_read_client_certificate_verify;
874   return ssl_hs_ok;
875 }
876 
do_read_client_certificate_verify(SSL_HANDSHAKE * hs)877 static enum ssl_hs_wait_t do_read_client_certificate_verify(
878     SSL_HANDSHAKE *hs) {
879   SSL *const ssl = hs->ssl;
880   if (sk_CRYPTO_BUFFER_num(hs->new_session->certs.get()) == 0) {
881     // Skip this state.
882     hs->tls13_state = state_read_channel_id;
883     return ssl_hs_ok;
884   }
885 
886   SSLMessage msg;
887   if (!ssl->method->get_message(ssl, &msg)) {
888     return ssl_hs_read_message;
889   }
890 
891   switch (ssl_verify_peer_cert(hs)) {
892     case ssl_verify_ok:
893       break;
894     case ssl_verify_invalid:
895       return ssl_hs_error;
896     case ssl_verify_retry:
897       hs->tls13_state = state_read_client_certificate_verify;
898       return ssl_hs_certificate_verify;
899   }
900 
901   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_VERIFY) ||
902       !tls13_process_certificate_verify(hs, msg) ||
903       !ssl_hash_message(hs, msg)) {
904     return ssl_hs_error;
905   }
906 
907   ssl->method->next_message(ssl);
908   hs->tls13_state = state_read_channel_id;
909   return ssl_hs_ok;
910 }
911 
do_read_channel_id(SSL_HANDSHAKE * hs)912 static enum ssl_hs_wait_t do_read_channel_id(SSL_HANDSHAKE *hs) {
913   SSL *const ssl = hs->ssl;
914   if (!ssl->s3->channel_id_valid) {
915     hs->tls13_state = state_read_client_finished;
916     return ssl_hs_ok;
917   }
918 
919   SSLMessage msg;
920   if (!ssl->method->get_message(ssl, &msg)) {
921     return ssl_hs_read_message;
922   }
923   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CHANNEL_ID) ||
924       !tls1_verify_channel_id(hs, msg) ||
925       !ssl_hash_message(hs, msg)) {
926     return ssl_hs_error;
927   }
928 
929   ssl->method->next_message(ssl);
930   hs->tls13_state = state_read_client_finished;
931   return ssl_hs_ok;
932 }
933 
do_read_client_finished(SSL_HANDSHAKE * hs)934 static enum ssl_hs_wait_t do_read_client_finished(SSL_HANDSHAKE *hs) {
935   SSL *const ssl = hs->ssl;
936   SSLMessage msg;
937   if (!ssl->method->get_message(ssl, &msg)) {
938     return ssl_hs_read_message;
939   }
940   if (!ssl_check_message_type(ssl, msg, SSL3_MT_FINISHED) ||
941       // If early data was accepted, we've already computed the client Finished
942       // and derived the resumption secret.
943       !tls13_process_finished(hs, msg, ssl->s3->early_data_accepted) ||
944       // evp_aead_seal keys have already been switched.
945       !tls13_set_traffic_key(ssl, ssl_encryption_application, evp_aead_open,
946                              hs->client_traffic_secret_0())) {
947     return ssl_hs_error;
948   }
949 
950   if (!ssl->s3->early_data_accepted) {
951     if (!ssl_hash_message(hs, msg) ||
952         !tls13_derive_resumption_secret(hs)) {
953       return ssl_hs_error;
954     }
955 
956     // We send post-handshake tickets as part of the handshake in 1-RTT.
957     hs->tls13_state = state_send_new_session_ticket;
958   } else {
959     // We already sent half-RTT tickets.
960     hs->tls13_state = state_done;
961   }
962 
963   ssl->method->next_message(ssl);
964   return ssl_hs_ok;
965 }
966 
do_send_new_session_ticket(SSL_HANDSHAKE * hs)967 static enum ssl_hs_wait_t do_send_new_session_ticket(SSL_HANDSHAKE *hs) {
968   bool sent_tickets;
969   if (!add_new_session_tickets(hs, &sent_tickets)) {
970     return ssl_hs_error;
971   }
972 
973   hs->tls13_state = state_done;
974   // In TLS 1.3, the NewSessionTicket isn't flushed until the server performs a
975   // write, to prevent a non-reading client from causing the server to hang in
976   // the case of a small server write buffer. Consumers which don't write data
977   // to the client will need to do a zero-byte write if they wish to flush the
978   // tickets.
979   if (hs->ssl->quic_method != nullptr && sent_tickets) {
980     return ssl_hs_flush;
981   }
982   return ssl_hs_ok;
983 }
984 
tls13_server_handshake(SSL_HANDSHAKE * hs)985 enum ssl_hs_wait_t tls13_server_handshake(SSL_HANDSHAKE *hs) {
986   while (hs->tls13_state != state_done) {
987     enum ssl_hs_wait_t ret = ssl_hs_error;
988     enum server_hs_state_t state =
989         static_cast<enum server_hs_state_t>(hs->tls13_state);
990     switch (state) {
991       case state_select_parameters:
992         ret = do_select_parameters(hs);
993         break;
994       case state_select_session:
995         ret = do_select_session(hs);
996         break;
997       case state_send_hello_retry_request:
998         ret = do_send_hello_retry_request(hs);
999         break;
1000       case state_read_second_client_hello:
1001         ret = do_read_second_client_hello(hs);
1002         break;
1003       case state_send_server_hello:
1004         ret = do_send_server_hello(hs);
1005         break;
1006       case state_send_server_certificate_verify:
1007         ret = do_send_server_certificate_verify(hs);
1008         break;
1009       case state_send_server_finished:
1010         ret = do_send_server_finished(hs);
1011         break;
1012       case state_read_second_client_flight:
1013         ret = do_read_second_client_flight(hs);
1014         break;
1015       case state_process_end_of_early_data:
1016         ret = do_process_end_of_early_data(hs);
1017         break;
1018       case state_read_client_certificate:
1019         ret = do_read_client_certificate(hs);
1020         break;
1021       case state_read_client_certificate_verify:
1022         ret = do_read_client_certificate_verify(hs);
1023         break;
1024       case state_read_channel_id:
1025         ret = do_read_channel_id(hs);
1026         break;
1027       case state_read_client_finished:
1028         ret = do_read_client_finished(hs);
1029         break;
1030       case state_send_new_session_ticket:
1031         ret = do_send_new_session_ticket(hs);
1032         break;
1033       case state_done:
1034         ret = ssl_hs_ok;
1035         break;
1036     }
1037 
1038     if (hs->tls13_state != state) {
1039       ssl_do_info_callback(hs->ssl, SSL_CB_ACCEPT_LOOP, 1);
1040     }
1041 
1042     if (ret != ssl_hs_ok) {
1043       return ret;
1044     }
1045   }
1046 
1047   return ssl_hs_ok;
1048 }
1049 
tls13_server_handshake_state(SSL_HANDSHAKE * hs)1050 const char *tls13_server_handshake_state(SSL_HANDSHAKE *hs) {
1051   enum server_hs_state_t state =
1052       static_cast<enum server_hs_state_t>(hs->tls13_state);
1053   switch (state) {
1054     case state_select_parameters:
1055       return "TLS 1.3 server select_parameters";
1056     case state_select_session:
1057       return "TLS 1.3 server select_session";
1058     case state_send_hello_retry_request:
1059       return "TLS 1.3 server send_hello_retry_request";
1060     case state_read_second_client_hello:
1061       return "TLS 1.3 server read_second_client_hello";
1062     case state_send_server_hello:
1063       return "TLS 1.3 server send_server_hello";
1064     case state_send_server_certificate_verify:
1065       return "TLS 1.3 server send_server_certificate_verify";
1066     case state_send_server_finished:
1067       return "TLS 1.3 server send_server_finished";
1068     case state_read_second_client_flight:
1069       return "TLS 1.3 server read_second_client_flight";
1070     case state_process_end_of_early_data:
1071       return "TLS 1.3 server process_end_of_early_data";
1072     case state_read_client_certificate:
1073       return "TLS 1.3 server read_client_certificate";
1074     case state_read_client_certificate_verify:
1075       return "TLS 1.3 server read_client_certificate_verify";
1076     case state_read_channel_id:
1077       return "TLS 1.3 server read_channel_id";
1078     case state_read_client_finished:
1079       return "TLS 1.3 server read_client_finished";
1080     case state_send_new_session_ticket:
1081       return "TLS 1.3 server send_new_session_ticket";
1082     case state_done:
1083       return "TLS 1.3 server done";
1084   }
1085 
1086   return "TLS 1.3 server unknown";
1087 }
1088 
1089 BSSL_NAMESPACE_END
1090