• 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 <limits.h>
19 #include <string.h>
20 
21 #include <utility>
22 
23 #include <openssl/bytestring.h>
24 #include <openssl/digest.h>
25 #include <openssl/err.h>
26 #include <openssl/mem.h>
27 #include <openssl/sha.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 client_hs_state_t {
37   state_read_hello_retry_request = 0,
38   state_send_second_client_hello,
39   state_read_server_hello,
40   state_read_encrypted_extensions,
41   state_read_certificate_request,
42   state_read_server_certificate,
43   state_read_server_certificate_verify,
44   state_server_certificate_reverify,
45   state_read_server_finished,
46   state_send_end_of_early_data,
47   state_send_client_certificate,
48   state_send_client_certificate_verify,
49   state_complete_second_flight,
50   state_done,
51 };
52 
53 static const uint8_t kZeroes[EVP_MAX_MD_SIZE] = {0};
54 
55 // end_of_early_data closes the early data stream for |hs| and switches the
56 // encryption level to |level|. It returns true on success and false on error.
close_early_data(SSL_HANDSHAKE * hs,ssl_encryption_level_t level)57 static bool close_early_data(SSL_HANDSHAKE *hs, ssl_encryption_level_t level) {
58   SSL *const ssl = hs->ssl;
59   assert(hs->in_early_data);
60 
61   // Note |can_early_write| may already be false if |SSL_write| exceeded the
62   // early data write limit.
63   hs->can_early_write = false;
64 
65   // 0-RTT write states on the client differ between TLS 1.3, DTLS 1.3, and
66   // QUIC. TLS 1.3 has one write encryption level at a time. 0-RTT write keys
67   // overwrite the null cipher and defer handshake write keys. While a
68   // HelloRetryRequest can cause us to rewind back to the null cipher, sequence
69   // numbers have no effect, so we can install a "new" null cipher.
70   //
71   // In QUIC and DTLS 1.3, 0-RTT write state cannot override or defer the normal
72   // write state. The two ClientHello sequence numbers must align, and handshake
73   // write keys must be installed early to ACK the EncryptedExtensions.
74   //
75   // We do not currently implement DTLS 1.3 and, in QUIC, the caller handles
76   // 0-RTT data, so we can skip installing 0-RTT keys and act as if there is one
77   // write level. If we implement DTLS 1.3, we'll need to model this better.
78   if (ssl->quic_method == nullptr) {
79     if (level == ssl_encryption_initial) {
80       bssl::UniquePtr<SSLAEADContext> null_ctx =
81           SSLAEADContext::CreateNullCipher(SSL_is_dtls(ssl));
82       if (!null_ctx ||
83           !ssl->method->set_write_state(ssl, ssl_encryption_initial,
84                                         std::move(null_ctx),
85                                         /*secret_for_quic=*/{})) {
86         return false;
87       }
88       ssl->s3->aead_write_ctx->SetVersionIfNullCipher(ssl->version);
89     } else {
90       assert(level == ssl_encryption_handshake);
91       if (!tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_seal,
92                                  hs->new_session.get(),
93                                  hs->client_handshake_secret())) {
94         return false;
95       }
96     }
97   }
98 
99   assert(ssl->s3->write_level == level);
100   return true;
101 }
102 
do_read_hello_retry_request(SSL_HANDSHAKE * hs)103 static enum ssl_hs_wait_t do_read_hello_retry_request(SSL_HANDSHAKE *hs) {
104   SSL *const ssl = hs->ssl;
105   assert(ssl->s3->have_version);
106   SSLMessage msg;
107   if (!ssl->method->get_message(ssl, &msg)) {
108     return ssl_hs_read_message;
109   }
110 
111   // Queue up a ChangeCipherSpec for whenever we next send something. This
112   // will be before the second ClientHello. If we offered early data, this was
113   // already done.
114   if (!hs->early_data_offered &&
115       !ssl->method->add_change_cipher_spec(ssl)) {
116     return ssl_hs_error;
117   }
118 
119   if (!ssl_check_message_type(ssl, msg, SSL3_MT_SERVER_HELLO)) {
120     return ssl_hs_error;
121   }
122 
123   CBS body = msg.body, extensions, server_random, session_id;
124   uint16_t server_version, cipher_suite;
125   uint8_t compression_method;
126   if (!CBS_get_u16(&body, &server_version) ||
127       !CBS_get_bytes(&body, &server_random, SSL3_RANDOM_SIZE) ||
128       !CBS_get_u8_length_prefixed(&body, &session_id) ||
129       !CBS_mem_equal(&session_id, hs->session_id, hs->session_id_len) ||
130       !CBS_get_u16(&body, &cipher_suite) ||
131       !CBS_get_u8(&body, &compression_method) ||
132       compression_method != 0 ||
133       !CBS_get_u16_length_prefixed(&body, &extensions) ||
134       CBS_len(&extensions) == 0 ||
135       CBS_len(&body) != 0) {
136     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
137     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
138     return ssl_hs_error;
139   }
140 
141   if (!CBS_mem_equal(&server_random, kHelloRetryRequest, SSL3_RANDOM_SIZE)) {
142     hs->tls13_state = state_read_server_hello;
143     return ssl_hs_ok;
144   }
145 
146   const SSL_CIPHER *cipher = SSL_get_cipher_by_value(cipher_suite);
147   // Check if the cipher is a TLS 1.3 cipher.
148   if (cipher == NULL ||
149       SSL_CIPHER_get_min_version(cipher) > ssl_protocol_version(ssl) ||
150       SSL_CIPHER_get_max_version(cipher) < ssl_protocol_version(ssl)) {
151     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
152     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
153     return ssl_hs_error;
154   }
155 
156   hs->new_cipher = cipher;
157 
158   if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher) ||
159       !hs->transcript.UpdateForHelloRetryRequest()) {
160     return ssl_hs_error;
161   }
162 
163 
164   bool have_cookie, have_key_share, have_supported_versions;
165   CBS cookie, key_share, supported_versions;
166   SSL_EXTENSION_TYPE ext_types[] = {
167       {TLSEXT_TYPE_key_share, &have_key_share, &key_share},
168       {TLSEXT_TYPE_cookie, &have_cookie, &cookie},
169       {TLSEXT_TYPE_supported_versions, &have_supported_versions,
170        &supported_versions},
171   };
172 
173   uint8_t alert = SSL_AD_DECODE_ERROR;
174   if (!ssl_parse_extensions(&extensions, &alert, ext_types,
175                             OPENSSL_ARRAY_SIZE(ext_types),
176                             0 /* reject unknown */)) {
177     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
178     return ssl_hs_error;
179   }
180 
181   if (!have_cookie && !have_key_share) {
182     OPENSSL_PUT_ERROR(SSL, SSL_R_EMPTY_HELLO_RETRY_REQUEST);
183     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
184     return ssl_hs_error;
185   }
186   if (have_cookie) {
187     CBS cookie_value;
188     if (!CBS_get_u16_length_prefixed(&cookie, &cookie_value) ||
189         CBS_len(&cookie_value) == 0 ||
190         CBS_len(&cookie) != 0) {
191       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
192       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
193       return ssl_hs_error;
194     }
195 
196     if (!hs->cookie.CopyFrom(cookie_value)) {
197       return ssl_hs_error;
198     }
199   }
200 
201   if (have_key_share) {
202     uint16_t group_id;
203     if (!CBS_get_u16(&key_share, &group_id) || CBS_len(&key_share) != 0) {
204       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
205       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
206       return ssl_hs_error;
207     }
208 
209     // The group must be supported.
210     if (!tls1_check_group_id(hs, group_id)) {
211       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
212       OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
213       return ssl_hs_error;
214     }
215 
216     // Check that the HelloRetryRequest does not request a key share that was
217     // provided in the initial ClientHello.
218     if (hs->key_shares[0]->GroupID() == group_id ||
219         (hs->key_shares[1] && hs->key_shares[1]->GroupID() == group_id)) {
220       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
221       OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
222       return ssl_hs_error;
223     }
224 
225     hs->key_shares[0].reset();
226     hs->key_shares[1].reset();
227     hs->retry_group = group_id;
228   }
229 
230   if (!ssl_hash_message(hs, msg)) {
231     return ssl_hs_error;
232   }
233 
234   // HelloRetryRequest should be the end of the flight.
235   if (ssl->method->has_unprocessed_handshake_data(ssl)) {
236     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
237     OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESS_HANDSHAKE_DATA);
238     return ssl_hs_error;
239   }
240 
241   ssl->method->next_message(ssl);
242   ssl->s3->used_hello_retry_request = true;
243   hs->tls13_state = state_send_second_client_hello;
244   // 0-RTT is rejected if we receive a HelloRetryRequest.
245   if (hs->in_early_data) {
246     ssl->s3->early_data_reason = ssl_early_data_hello_retry_request;
247     if (!close_early_data(hs, ssl_encryption_initial)) {
248       return ssl_hs_error;
249     }
250     return ssl_hs_early_data_rejected;
251   }
252   return ssl_hs_ok;
253 }
254 
do_send_second_client_hello(SSL_HANDSHAKE * hs)255 static enum ssl_hs_wait_t do_send_second_client_hello(SSL_HANDSHAKE *hs) {
256   // Any 0-RTT keys must have been discarded.
257   assert(hs->ssl->s3->write_level == ssl_encryption_initial);
258 
259   if (!ssl_write_client_hello(hs)) {
260     return ssl_hs_error;
261   }
262 
263   hs->tls13_state = state_read_server_hello;
264   return ssl_hs_flush;
265 }
266 
do_read_server_hello(SSL_HANDSHAKE * hs)267 static enum ssl_hs_wait_t do_read_server_hello(SSL_HANDSHAKE *hs) {
268   SSL *const ssl = hs->ssl;
269   SSLMessage msg;
270   if (!ssl->method->get_message(ssl, &msg)) {
271     return ssl_hs_read_message;
272   }
273   if (!ssl_check_message_type(ssl, msg, SSL3_MT_SERVER_HELLO)) {
274     return ssl_hs_error;
275   }
276 
277   CBS body = msg.body, server_random, session_id, extensions;
278   uint16_t server_version;
279   uint16_t cipher_suite;
280   uint8_t compression_method;
281   if (!CBS_get_u16(&body, &server_version) ||
282       !CBS_get_bytes(&body, &server_random, SSL3_RANDOM_SIZE) ||
283       !CBS_get_u8_length_prefixed(&body, &session_id) ||
284       !CBS_mem_equal(&session_id, hs->session_id, hs->session_id_len) ||
285       !CBS_get_u16(&body, &cipher_suite) ||
286       !CBS_get_u8(&body, &compression_method) ||
287       compression_method != 0 ||
288       !CBS_get_u16_length_prefixed(&body, &extensions) ||
289       CBS_len(&body) != 0) {
290     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
291     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
292     return ssl_hs_error;
293   }
294 
295   if (server_version != TLS1_2_VERSION) {
296     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
297     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_VERSION_NUMBER);
298     return ssl_hs_error;
299   }
300 
301   // Forbid a second HelloRetryRequest.
302   if (CBS_mem_equal(&server_random, kHelloRetryRequest, SSL3_RANDOM_SIZE)) {
303     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
304     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
305     return ssl_hs_error;
306   }
307 
308   OPENSSL_memcpy(ssl->s3->server_random, CBS_data(&server_random),
309                  SSL3_RANDOM_SIZE);
310 
311   // Check if the cipher is a TLS 1.3 cipher.
312   const SSL_CIPHER *cipher = SSL_get_cipher_by_value(cipher_suite);
313   if (cipher == nullptr ||
314       SSL_CIPHER_get_min_version(cipher) > ssl_protocol_version(ssl) ||
315       SSL_CIPHER_get_max_version(cipher) < ssl_protocol_version(ssl)) {
316     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
317     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
318     return ssl_hs_error;
319   }
320 
321   // Check that the cipher matches the one in the HelloRetryRequest.
322   if (ssl->s3->used_hello_retry_request && hs->new_cipher != cipher) {
323     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
324     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
325     return ssl_hs_error;
326   }
327 
328   // Parse out the extensions.
329   bool have_key_share = false, have_pre_shared_key = false,
330        have_supported_versions = false;
331   CBS key_share, pre_shared_key, supported_versions;
332   SSL_EXTENSION_TYPE ext_types[] = {
333       {TLSEXT_TYPE_key_share, &have_key_share, &key_share},
334       {TLSEXT_TYPE_pre_shared_key, &have_pre_shared_key, &pre_shared_key},
335       {TLSEXT_TYPE_supported_versions, &have_supported_versions,
336        &supported_versions},
337   };
338 
339   uint8_t alert = SSL_AD_DECODE_ERROR;
340   if (!ssl_parse_extensions(&extensions, &alert, ext_types,
341                             OPENSSL_ARRAY_SIZE(ext_types),
342                             0 /* reject unknown */)) {
343     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
344     return ssl_hs_error;
345   }
346 
347   // Recheck supported_versions, in case this is the second ServerHello.
348   uint16_t version;
349   if (!have_supported_versions ||
350       !CBS_get_u16(&supported_versions, &version) ||
351       version != ssl->version) {
352     OPENSSL_PUT_ERROR(SSL, SSL_R_SECOND_SERVERHELLO_VERSION_MISMATCH);
353     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
354     return ssl_hs_error;
355   }
356 
357   alert = SSL_AD_DECODE_ERROR;
358   if (have_pre_shared_key) {
359     if (ssl->session == NULL) {
360       OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
361       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_EXTENSION);
362       return ssl_hs_error;
363     }
364 
365     if (!ssl_ext_pre_shared_key_parse_serverhello(hs, &alert,
366                                                   &pre_shared_key)) {
367       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
368       return ssl_hs_error;
369     }
370 
371     if (ssl->session->ssl_version != ssl->version) {
372       OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_VERSION_NOT_RETURNED);
373       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
374       return ssl_hs_error;
375     }
376 
377     if (ssl->session->cipher->algorithm_prf != cipher->algorithm_prf) {
378       OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_PRF_HASH_MISMATCH);
379       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
380       return ssl_hs_error;
381     }
382 
383     if (!ssl_session_is_context_valid(hs, ssl->session.get())) {
384       // This is actually a client application bug.
385       OPENSSL_PUT_ERROR(SSL,
386                         SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
387       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
388       return ssl_hs_error;
389     }
390 
391     ssl->s3->session_reused = true;
392     // Only authentication information carries over in TLS 1.3.
393     hs->new_session =
394         SSL_SESSION_dup(ssl->session.get(), SSL_SESSION_DUP_AUTH_ONLY);
395     if (!hs->new_session) {
396       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
397       return ssl_hs_error;
398     }
399     ssl_set_session(ssl, NULL);
400 
401     // Resumption incorporates fresh key material, so refresh the timeout.
402     ssl_session_renew_timeout(ssl, hs->new_session.get(),
403                               ssl->session_ctx->session_psk_dhe_timeout);
404   } else if (!ssl_get_new_session(hs, 0)) {
405     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
406     return ssl_hs_error;
407   }
408 
409   hs->new_session->cipher = cipher;
410   hs->new_cipher = cipher;
411 
412   size_t hash_len =
413       EVP_MD_size(ssl_get_handshake_digest(ssl_protocol_version(ssl), cipher));
414 
415   // Set up the key schedule and incorporate the PSK into the running secret.
416   if (ssl->s3->session_reused) {
417     if (!tls13_init_key_schedule(
418             hs, MakeConstSpan(hs->new_session->master_key,
419                               hs->new_session->master_key_length))) {
420       return ssl_hs_error;
421     }
422   } else if (!tls13_init_key_schedule(hs, MakeConstSpan(kZeroes, hash_len))) {
423     return ssl_hs_error;
424   }
425 
426   if (!have_key_share) {
427     // We do not support psk_ke and thus always require a key share.
428     OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_KEY_SHARE);
429     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_MISSING_EXTENSION);
430     return ssl_hs_error;
431   }
432 
433   // Resolve ECDHE and incorporate it into the secret.
434   Array<uint8_t> dhe_secret;
435   alert = SSL_AD_DECODE_ERROR;
436   if (!ssl_ext_key_share_parse_serverhello(hs, &dhe_secret, &alert,
437                                            &key_share)) {
438     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
439     return ssl_hs_error;
440   }
441 
442   if (!tls13_advance_key_schedule(hs, dhe_secret) ||
443       !ssl_hash_message(hs, msg) ||
444       !tls13_derive_handshake_secrets(hs)) {
445     return ssl_hs_error;
446   }
447 
448   // If currently sending early data over TCP, we defer installing client
449   // traffic keys to when the early data stream is closed. See
450   // |close_early_data|. Note if the server has already rejected 0-RTT via
451   // HelloRetryRequest, |in_early_data| is already false.
452   if (!hs->in_early_data || ssl->quic_method != nullptr) {
453     if (!tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_seal,
454                                hs->new_session.get(),
455                                hs->client_handshake_secret())) {
456       return ssl_hs_error;
457     }
458   }
459 
460   if (!tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_open,
461                              hs->new_session.get(),
462                              hs->server_handshake_secret())) {
463     return ssl_hs_error;
464   }
465 
466   ssl->method->next_message(ssl);
467   hs->tls13_state = state_read_encrypted_extensions;
468   return ssl_hs_ok;
469 }
470 
do_read_encrypted_extensions(SSL_HANDSHAKE * hs)471 static enum ssl_hs_wait_t do_read_encrypted_extensions(SSL_HANDSHAKE *hs) {
472   SSL *const ssl = hs->ssl;
473   SSLMessage msg;
474   if (!ssl->method->get_message(ssl, &msg)) {
475     return ssl_hs_read_message;
476   }
477   if (!ssl_check_message_type(ssl, msg, SSL3_MT_ENCRYPTED_EXTENSIONS)) {
478     return ssl_hs_error;
479   }
480 
481   CBS body = msg.body;
482   if (!ssl_parse_serverhello_tlsext(hs, &body)) {
483     OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
484     return ssl_hs_error;
485   }
486   if (CBS_len(&body) != 0) {
487     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
488     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
489     return ssl_hs_error;
490   }
491 
492   // Store the negotiated ALPN in the session.
493   if (!hs->new_session->early_alpn.CopyFrom(ssl->s3->alpn_selected)) {
494     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
495     return ssl_hs_error;
496   }
497 
498   if (ssl->s3->early_data_accepted) {
499     if (hs->early_session->cipher != hs->new_session->cipher) {
500       OPENSSL_PUT_ERROR(SSL, SSL_R_CIPHER_MISMATCH_ON_EARLY_DATA);
501       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
502       return ssl_hs_error;
503     }
504     if (MakeConstSpan(hs->early_session->early_alpn) !=
505         ssl->s3->alpn_selected) {
506       OPENSSL_PUT_ERROR(SSL, SSL_R_ALPN_MISMATCH_ON_EARLY_DATA);
507       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
508       return ssl_hs_error;
509     }
510     if (ssl->s3->channel_id_valid || ssl->s3->token_binding_negotiated) {
511       OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION_ON_EARLY_DATA);
512       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
513       return ssl_hs_error;
514     }
515   }
516 
517   if (!ssl_hash_message(hs, msg)) {
518     return ssl_hs_error;
519   }
520 
521   ssl->method->next_message(ssl);
522   hs->tls13_state = state_read_certificate_request;
523   if (hs->in_early_data && !ssl->s3->early_data_accepted) {
524     if (!close_early_data(hs, ssl_encryption_handshake)) {
525       return ssl_hs_error;
526     }
527     return ssl_hs_early_data_rejected;
528   }
529   return ssl_hs_ok;
530 }
531 
do_read_certificate_request(SSL_HANDSHAKE * hs)532 static enum ssl_hs_wait_t do_read_certificate_request(SSL_HANDSHAKE *hs) {
533   SSL *const ssl = hs->ssl;
534   // CertificateRequest may only be sent in non-resumption handshakes.
535   if (ssl->s3->session_reused) {
536     if (ssl->ctx->reverify_on_resume && !ssl->s3->early_data_accepted) {
537       hs->tls13_state = state_server_certificate_reverify;
538       return ssl_hs_ok;
539     }
540     hs->tls13_state = state_read_server_finished;
541     return ssl_hs_ok;
542   }
543 
544   SSLMessage msg;
545   if (!ssl->method->get_message(ssl, &msg)) {
546     return ssl_hs_read_message;
547   }
548 
549   // CertificateRequest is optional.
550   if (msg.type != SSL3_MT_CERTIFICATE_REQUEST) {
551     hs->tls13_state = state_read_server_certificate;
552     return ssl_hs_ok;
553   }
554 
555 
556   bool have_sigalgs = false, have_ca = false;
557   CBS sigalgs, ca;
558   const SSL_EXTENSION_TYPE ext_types[] = {
559     {TLSEXT_TYPE_signature_algorithms, &have_sigalgs, &sigalgs},
560     {TLSEXT_TYPE_certificate_authorities, &have_ca, &ca},
561   };
562 
563   CBS body = msg.body, context, extensions, supported_signature_algorithms;
564   uint8_t alert = SSL_AD_DECODE_ERROR;
565   if (!CBS_get_u8_length_prefixed(&body, &context) ||
566       // The request context is always empty during the handshake.
567       CBS_len(&context) != 0 ||
568       !CBS_get_u16_length_prefixed(&body, &extensions) ||
569       CBS_len(&body) != 0 ||
570       !ssl_parse_extensions(&extensions, &alert, ext_types,
571                             OPENSSL_ARRAY_SIZE(ext_types),
572                             1 /* accept unknown */) ||
573       (have_ca && CBS_len(&ca) == 0) ||
574       !have_sigalgs ||
575       !CBS_get_u16_length_prefixed(&sigalgs,
576                                    &supported_signature_algorithms) ||
577       !tls1_parse_peer_sigalgs(hs, &supported_signature_algorithms)) {
578     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
579     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
580     return ssl_hs_error;
581   }
582 
583   if (have_ca) {
584     hs->ca_names = ssl_parse_client_CA_list(ssl, &alert, &ca);
585     if (!hs->ca_names) {
586       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
587       return ssl_hs_error;
588     }
589   } else {
590     hs->ca_names.reset(sk_CRYPTO_BUFFER_new_null());
591     if (!hs->ca_names) {
592       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
593       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
594       return ssl_hs_error;
595     }
596   }
597 
598   hs->cert_request = true;
599   ssl->ctx->x509_method->hs_flush_cached_ca_names(hs);
600 
601   if (!ssl_hash_message(hs, msg)) {
602     return ssl_hs_error;
603   }
604 
605   ssl->method->next_message(ssl);
606   hs->tls13_state = state_read_server_certificate;
607   return ssl_hs_ok;
608 }
609 
do_read_server_certificate(SSL_HANDSHAKE * hs)610 static enum ssl_hs_wait_t do_read_server_certificate(SSL_HANDSHAKE *hs) {
611   SSL *const ssl = hs->ssl;
612   SSLMessage msg;
613   if (!ssl->method->get_message(ssl, &msg)) {
614     return ssl_hs_read_message;
615   }
616 
617   if (msg.type != SSL3_MT_COMPRESSED_CERTIFICATE &&
618       !ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE)) {
619     return ssl_hs_error;
620   }
621 
622   if (!tls13_process_certificate(hs, msg, false /* certificate required */) ||
623       !ssl_hash_message(hs, msg)) {
624     return ssl_hs_error;
625   }
626 
627   ssl->method->next_message(ssl);
628   hs->tls13_state = state_read_server_certificate_verify;
629   return ssl_hs_ok;
630 }
631 
do_read_server_certificate_verify(SSL_HANDSHAKE * hs)632 static enum ssl_hs_wait_t do_read_server_certificate_verify(
633     SSL_HANDSHAKE *hs) {
634   SSL *const ssl = hs->ssl;
635   SSLMessage msg;
636   if (!ssl->method->get_message(ssl, &msg)) {
637     return ssl_hs_read_message;
638   }
639   switch (ssl_verify_peer_cert(hs)) {
640     case ssl_verify_ok:
641       break;
642     case ssl_verify_invalid:
643       return ssl_hs_error;
644     case ssl_verify_retry:
645       hs->tls13_state = state_read_server_certificate_verify;
646       return ssl_hs_certificate_verify;
647   }
648 
649   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_VERIFY) ||
650       !tls13_process_certificate_verify(hs, msg) ||
651       !ssl_hash_message(hs, msg)) {
652     return ssl_hs_error;
653   }
654 
655   ssl->method->next_message(ssl);
656   hs->tls13_state = state_read_server_finished;
657   return ssl_hs_ok;
658 }
659 
do_server_certificate_reverify(SSL_HANDSHAKE * hs)660 static enum ssl_hs_wait_t do_server_certificate_reverify(
661     SSL_HANDSHAKE *hs) {
662   switch (ssl_reverify_peer_cert(hs, /*send_alert=*/true)) {
663     case ssl_verify_ok:
664       break;
665     case ssl_verify_invalid:
666       return ssl_hs_error;
667     case ssl_verify_retry:
668       hs->tls13_state = state_server_certificate_reverify;
669       return ssl_hs_certificate_verify;
670   }
671   hs->tls13_state = state_read_server_finished;
672   return ssl_hs_ok;
673 }
674 
do_read_server_finished(SSL_HANDSHAKE * hs)675 static enum ssl_hs_wait_t do_read_server_finished(SSL_HANDSHAKE *hs) {
676   SSL *const ssl = hs->ssl;
677   SSLMessage msg;
678   if (!ssl->method->get_message(ssl, &msg)) {
679     return ssl_hs_read_message;
680   }
681   if (!ssl_check_message_type(ssl, msg, SSL3_MT_FINISHED) ||
682       !tls13_process_finished(hs, msg, false /* don't use saved value */) ||
683       !ssl_hash_message(hs, msg) ||
684       // Update the secret to the master secret and derive traffic keys.
685       !tls13_advance_key_schedule(
686           hs, MakeConstSpan(kZeroes, hs->transcript.DigestLen())) ||
687       !tls13_derive_application_secrets(hs)) {
688     return ssl_hs_error;
689   }
690 
691   // Finished should be the end of the flight.
692   if (ssl->method->has_unprocessed_handshake_data(ssl)) {
693     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
694     OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESS_HANDSHAKE_DATA);
695     return ssl_hs_error;
696   }
697 
698   ssl->method->next_message(ssl);
699   hs->tls13_state = state_send_end_of_early_data;
700   return ssl_hs_ok;
701 }
702 
do_send_end_of_early_data(SSL_HANDSHAKE * hs)703 static enum ssl_hs_wait_t do_send_end_of_early_data(SSL_HANDSHAKE *hs) {
704   SSL *const ssl = hs->ssl;
705 
706   if (ssl->s3->early_data_accepted) {
707     // QUIC omits the EndOfEarlyData message. See draft-ietf-quic-tls-22,
708     // section 8.3.
709     if (ssl->quic_method == nullptr) {
710       ScopedCBB cbb;
711       CBB body;
712       if (!ssl->method->init_message(ssl, cbb.get(), &body,
713                                      SSL3_MT_END_OF_EARLY_DATA) ||
714           !ssl_add_message_cbb(ssl, cbb.get())) {
715         return ssl_hs_error;
716       }
717     }
718 
719     if (!close_early_data(hs, ssl_encryption_handshake)) {
720       return ssl_hs_error;
721     }
722   }
723 
724   hs->tls13_state = state_send_client_certificate;
725   return ssl_hs_ok;
726 }
727 
do_send_client_certificate(SSL_HANDSHAKE * hs)728 static enum ssl_hs_wait_t do_send_client_certificate(SSL_HANDSHAKE *hs) {
729   SSL *const ssl = hs->ssl;
730 
731   // The peer didn't request a certificate.
732   if (!hs->cert_request) {
733     hs->tls13_state = state_complete_second_flight;
734     return ssl_hs_ok;
735   }
736 
737   // Call cert_cb to update the certificate.
738   if (hs->config->cert->cert_cb != NULL) {
739     int rv = hs->config->cert->cert_cb(ssl, hs->config->cert->cert_cb_arg);
740     if (rv == 0) {
741       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
742       OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
743       return ssl_hs_error;
744     }
745     if (rv < 0) {
746       hs->tls13_state = state_send_client_certificate;
747       return ssl_hs_x509_lookup;
748     }
749   }
750 
751   if (!ssl_on_certificate_selected(hs) ||
752       !tls13_add_certificate(hs)) {
753     return ssl_hs_error;
754   }
755 
756   hs->tls13_state = state_send_client_certificate_verify;
757   return ssl_hs_ok;
758 }
759 
do_send_client_certificate_verify(SSL_HANDSHAKE * hs)760 static enum ssl_hs_wait_t do_send_client_certificate_verify(SSL_HANDSHAKE *hs) {
761   // Don't send CertificateVerify if there is no certificate.
762   if (!ssl_has_certificate(hs)) {
763     hs->tls13_state = state_complete_second_flight;
764     return ssl_hs_ok;
765   }
766 
767   switch (tls13_add_certificate_verify(hs)) {
768     case ssl_private_key_success:
769       hs->tls13_state = state_complete_second_flight;
770       return ssl_hs_ok;
771 
772     case ssl_private_key_retry:
773       hs->tls13_state = state_send_client_certificate_verify;
774       return ssl_hs_private_key_operation;
775 
776     case ssl_private_key_failure:
777       return ssl_hs_error;
778   }
779 
780   assert(0);
781   return ssl_hs_error;
782 }
783 
do_complete_second_flight(SSL_HANDSHAKE * hs)784 static enum ssl_hs_wait_t do_complete_second_flight(SSL_HANDSHAKE *hs) {
785   SSL *const ssl = hs->ssl;
786 
787   // Send a Channel ID assertion if necessary.
788   if (ssl->s3->channel_id_valid) {
789     if (!ssl_do_channel_id_callback(hs)) {
790       hs->tls13_state = state_complete_second_flight;
791       return ssl_hs_error;
792     }
793 
794     if (hs->config->channel_id_private == NULL) {
795       return ssl_hs_channel_id_lookup;
796     }
797 
798     ScopedCBB cbb;
799     CBB body;
800     if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_CHANNEL_ID) ||
801         !tls1_write_channel_id(hs, &body) ||
802         !ssl_add_message_cbb(ssl, cbb.get())) {
803       return ssl_hs_error;
804     }
805   }
806 
807   // Send a Finished message.
808   if (!tls13_add_finished(hs)) {
809     return ssl_hs_error;
810   }
811 
812   // Derive the final keys and enable them.
813   if (!tls13_set_traffic_key(ssl, ssl_encryption_application, evp_aead_seal,
814                              hs->new_session.get(),
815                              hs->client_traffic_secret_0()) ||
816       !tls13_set_traffic_key(ssl, ssl_encryption_application, evp_aead_open,
817                              hs->new_session.get(),
818                              hs->server_traffic_secret_0()) ||
819       !tls13_derive_resumption_secret(hs)) {
820     return ssl_hs_error;
821   }
822 
823   hs->tls13_state = state_done;
824   return ssl_hs_flush;
825 }
826 
tls13_client_handshake(SSL_HANDSHAKE * hs)827 enum ssl_hs_wait_t tls13_client_handshake(SSL_HANDSHAKE *hs) {
828   while (hs->tls13_state != state_done) {
829     enum ssl_hs_wait_t ret = ssl_hs_error;
830     enum client_hs_state_t state =
831         static_cast<enum client_hs_state_t>(hs->tls13_state);
832     switch (state) {
833       case state_read_hello_retry_request:
834         ret = do_read_hello_retry_request(hs);
835         break;
836       case state_send_second_client_hello:
837         ret = do_send_second_client_hello(hs);
838         break;
839       case state_read_server_hello:
840         ret = do_read_server_hello(hs);
841         break;
842       case state_read_encrypted_extensions:
843         ret = do_read_encrypted_extensions(hs);
844         break;
845       case state_read_certificate_request:
846         ret = do_read_certificate_request(hs);
847         break;
848       case state_read_server_certificate:
849         ret = do_read_server_certificate(hs);
850         break;
851       case state_read_server_certificate_verify:
852         ret = do_read_server_certificate_verify(hs);
853         break;
854       case state_server_certificate_reverify:
855         ret = do_server_certificate_reverify(hs);
856         break;
857       case state_read_server_finished:
858         ret = do_read_server_finished(hs);
859         break;
860       case state_send_end_of_early_data:
861         ret = do_send_end_of_early_data(hs);
862         break;
863       case state_send_client_certificate:
864         ret = do_send_client_certificate(hs);
865         break;
866       case state_send_client_certificate_verify:
867         ret = do_send_client_certificate_verify(hs);
868         break;
869       case state_complete_second_flight:
870         ret = do_complete_second_flight(hs);
871         break;
872       case state_done:
873         ret = ssl_hs_ok;
874         break;
875     }
876 
877     if (hs->tls13_state != state) {
878       ssl_do_info_callback(hs->ssl, SSL_CB_CONNECT_LOOP, 1);
879     }
880 
881     if (ret != ssl_hs_ok) {
882       return ret;
883     }
884   }
885 
886   return ssl_hs_ok;
887 }
888 
tls13_client_handshake_state(SSL_HANDSHAKE * hs)889 const char *tls13_client_handshake_state(SSL_HANDSHAKE *hs) {
890   enum client_hs_state_t state =
891       static_cast<enum client_hs_state_t>(hs->tls13_state);
892   switch (state) {
893     case state_read_hello_retry_request:
894       return "TLS 1.3 client read_hello_retry_request";
895     case state_send_second_client_hello:
896       return "TLS 1.3 client send_second_client_hello";
897     case state_read_server_hello:
898       return "TLS 1.3 client read_server_hello";
899     case state_read_encrypted_extensions:
900       return "TLS 1.3 client read_encrypted_extensions";
901     case state_read_certificate_request:
902       return "TLS 1.3 client read_certificate_request";
903     case state_read_server_certificate:
904       return "TLS 1.3 client read_server_certificate";
905     case state_read_server_certificate_verify:
906       return "TLS 1.3 client read_server_certificate_verify";
907     case state_server_certificate_reverify:
908       return "TLS 1.3 client server_certificate_reverify";
909     case state_read_server_finished:
910       return "TLS 1.3 client read_server_finished";
911     case state_send_end_of_early_data:
912       return "TLS 1.3 client send_end_of_early_data";
913     case state_send_client_certificate:
914       return "TLS 1.3 client send_client_certificate";
915     case state_send_client_certificate_verify:
916       return "TLS 1.3 client send_client_certificate_verify";
917     case state_complete_second_flight:
918       return "TLS 1.3 client complete_second_flight";
919     case state_done:
920       return "TLS 1.3 client done";
921   }
922 
923   return "TLS 1.3 client unknown";
924 }
925 
tls13_process_new_session_ticket(SSL * ssl,const SSLMessage & msg)926 bool tls13_process_new_session_ticket(SSL *ssl, const SSLMessage &msg) {
927   if (ssl->s3->write_shutdown != ssl_shutdown_none) {
928     // Ignore tickets on shutdown. Callers tend to indiscriminately call
929     // |SSL_shutdown| before destroying an |SSL|, at which point calling the new
930     // session callback may be confusing.
931     return true;
932   }
933 
934   CBS body = msg.body;
935   UniquePtr<SSL_SESSION> session = tls13_create_session_with_ticket(ssl, &body);
936   if (!session) {
937     return false;
938   }
939 
940   if ((ssl->session_ctx->session_cache_mode & SSL_SESS_CACHE_CLIENT) &&
941       ssl->session_ctx->new_session_cb != NULL &&
942       ssl->session_ctx->new_session_cb(ssl, session.get())) {
943     // |new_session_cb|'s return value signals that it took ownership.
944     session.release();
945   }
946 
947   return true;
948 }
949 
tls13_create_session_with_ticket(SSL * ssl,CBS * body)950 UniquePtr<SSL_SESSION> tls13_create_session_with_ticket(SSL *ssl, CBS *body) {
951   UniquePtr<SSL_SESSION> session = SSL_SESSION_dup(
952       ssl->s3->established_session.get(), SSL_SESSION_INCLUDE_NONAUTH);
953   if (!session) {
954     return nullptr;
955   }
956 
957   ssl_session_rebase_time(ssl, session.get());
958 
959   uint32_t server_timeout;
960   CBS ticket_nonce, ticket, extensions;
961   if (!CBS_get_u32(body, &server_timeout) ||
962       !CBS_get_u32(body, &session->ticket_age_add) ||
963       !CBS_get_u8_length_prefixed(body, &ticket_nonce) ||
964       !CBS_get_u16_length_prefixed(body, &ticket) ||
965       !session->ticket.CopyFrom(ticket) ||
966       !CBS_get_u16_length_prefixed(body, &extensions) ||
967       CBS_len(body) != 0) {
968     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
969     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
970     return nullptr;
971   }
972 
973   // Cap the renewable lifetime by the server advertised value. This avoids
974   // wasting bandwidth on 0-RTT when we know the server will reject it.
975   if (session->timeout > server_timeout) {
976     session->timeout = server_timeout;
977   }
978 
979   if (!tls13_derive_session_psk(session.get(), ticket_nonce)) {
980     return nullptr;
981   }
982 
983   // Parse out the extensions.
984   bool have_early_data = false;
985   CBS early_data;
986   const SSL_EXTENSION_TYPE ext_types[] = {
987       {TLSEXT_TYPE_early_data, &have_early_data, &early_data},
988   };
989 
990   uint8_t alert = SSL_AD_DECODE_ERROR;
991   if (!ssl_parse_extensions(&extensions, &alert, ext_types,
992                             OPENSSL_ARRAY_SIZE(ext_types),
993                             1 /* ignore unknown */)) {
994     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
995     return nullptr;
996   }
997 
998   if (have_early_data) {
999     if (!CBS_get_u32(&early_data, &session->ticket_max_early_data) ||
1000         CBS_len(&early_data) != 0) {
1001       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1002       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1003       return nullptr;
1004     }
1005 
1006     // QUIC does not use the max_early_data_size parameter and always sets it to
1007     // a fixed value. See draft-ietf-quic-tls-22, section 4.5.
1008     if (ssl->quic_method != nullptr &&
1009         session->ticket_max_early_data != 0xffffffff) {
1010       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
1011       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1012       return nullptr;
1013     }
1014   }
1015 
1016   // Generate a session ID for this session. Some callers expect all sessions to
1017   // have a session ID.
1018   SHA256(CBS_data(&ticket), CBS_len(&ticket), session->session_id);
1019   session->session_id_length = SHA256_DIGEST_LENGTH;
1020 
1021   session->ticket_age_add_valid = true;
1022   session->not_resumable = false;
1023 
1024   return session;
1025 }
1026 
1027 BSSL_NAMESPACE_END
1028