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