1 // Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
2 // Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
3 // Copyright 2005 Nokia. All rights reserved.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //     https://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 
17 #include <openssl/ssl.h>
18 
19 #include <assert.h>
20 #include <limits.h>
21 #include <string.h>
22 
23 #include <algorithm>
24 #include <utility>
25 
26 #include <openssl/aead.h>
27 #include <openssl/bn.h>
28 #include <openssl/bytestring.h>
29 #include <openssl/ec_key.h>
30 #include <openssl/ecdsa.h>
31 #include <openssl/err.h>
32 #include <openssl/evp.h>
33 #include <openssl/hpke.h>
34 #include <openssl/md5.h>
35 #include <openssl/mem.h>
36 #include <openssl/rand.h>
37 #include <openssl/sha2.h>
38 
39 #include "../crypto/internal.h"
40 #include "internal.h"
41 
42 
43 BSSL_NAMESPACE_BEGIN
44 
45 enum ssl_client_hs_state_t {
46   state_start_connect = 0,
47   state_enter_early_data,
48   state_early_reverify_server_certificate,
49   state_read_server_hello,
50   state_tls13,
51   state_read_server_certificate,
52   state_read_certificate_status,
53   state_verify_server_certificate,
54   state_reverify_server_certificate,
55   state_read_server_key_exchange,
56   state_read_certificate_request,
57   state_read_server_hello_done,
58   state_send_client_certificate,
59   state_send_client_key_exchange,
60   state_send_client_certificate_verify,
61   state_send_client_finished,
62   state_finish_flight,
63   state_read_session_ticket,
64   state_process_change_cipher_spec,
65   state_read_server_finished,
66   state_finish_client_handshake,
67   state_done,
68 };
69 
70 // ssl_get_client_disabled sets |*out_mask_a| and |*out_mask_k| to masks of
71 // disabled algorithms.
ssl_get_client_disabled(const SSL_HANDSHAKE * hs,uint32_t * out_mask_a,uint32_t * out_mask_k)72 static void ssl_get_client_disabled(const SSL_HANDSHAKE *hs,
73                                     uint32_t *out_mask_a,
74                                     uint32_t *out_mask_k) {
75   *out_mask_a = 0;
76   *out_mask_k = 0;
77 
78   // PSK requires a client callback.
79   if (hs->config->psk_client_callback == NULL) {
80     *out_mask_a |= SSL_aPSK;
81     *out_mask_k |= SSL_kPSK;
82   }
83 }
84 
ssl_add_tls13_cipher(CBB * cbb,uint16_t cipher_id,ssl_compliance_policy_t policy)85 static bool ssl_add_tls13_cipher(CBB *cbb, uint16_t cipher_id,
86                                  ssl_compliance_policy_t policy) {
87   if (ssl_tls13_cipher_meets_policy(cipher_id, policy)) {
88     return CBB_add_u16(cbb, cipher_id);
89   }
90   return true;
91 }
92 
ssl_write_client_cipher_list(const SSL_HANDSHAKE * hs,CBB * out,ssl_client_hello_type_t type)93 static bool ssl_write_client_cipher_list(const SSL_HANDSHAKE *hs, CBB *out,
94                                          ssl_client_hello_type_t type) {
95   const SSL *const ssl = hs->ssl;
96   uint32_t mask_a, mask_k;
97   ssl_get_client_disabled(hs, &mask_a, &mask_k);
98 
99   CBB child;
100   if (!CBB_add_u16_length_prefixed(out, &child)) {
101     return false;
102   }
103 
104   // Add a fake cipher suite. See RFC 8701.
105   if (ssl->ctx->grease_enabled &&
106       !CBB_add_u16(&child, ssl_get_grease_value(hs, ssl_grease_cipher))) {
107     return false;
108   }
109 
110   // Add TLS 1.3 ciphers. Order ChaCha20-Poly1305 relative to AES-GCM based on
111   // hardware support.
112   if (hs->max_version >= TLS1_3_VERSION) {
113     static const uint16_t kCiphersNoAESHardware[] = {
114         TLS1_3_CK_CHACHA20_POLY1305_SHA256 & 0xffff,
115         TLS1_3_CK_AES_128_GCM_SHA256 & 0xffff,
116         TLS1_3_CK_AES_256_GCM_SHA384 & 0xffff,
117     };
118     static const uint16_t kCiphersAESHardware[] = {
119         TLS1_3_CK_AES_128_GCM_SHA256 & 0xffff,
120         TLS1_3_CK_AES_256_GCM_SHA384 & 0xffff,
121         TLS1_3_CK_CHACHA20_POLY1305_SHA256 & 0xffff,
122     };
123     static const uint16_t kCiphersCNSA[] = {
124         TLS1_3_CK_AES_256_GCM_SHA384 & 0xffff,
125         TLS1_3_CK_AES_128_GCM_SHA256 & 0xffff,
126         TLS1_3_CK_CHACHA20_POLY1305_SHA256 & 0xffff,
127     };
128 
129     const bool has_aes_hw = ssl->config->aes_hw_override
130                                 ? ssl->config->aes_hw_override_value
131                                 : EVP_has_aes_hardware();
132     const bssl::Span<const uint16_t> ciphers =
133         ssl->config->compliance_policy == ssl_compliance_policy_cnsa_202407
134             ? bssl::Span<const uint16_t>(kCiphersCNSA)
135             : (has_aes_hw ? bssl::Span<const uint16_t>(kCiphersAESHardware)
136                           : bssl::Span<const uint16_t>(kCiphersNoAESHardware));
137 
138     for (auto cipher : ciphers) {
139       if (!ssl_add_tls13_cipher(&child, cipher,
140                                 ssl->config->compliance_policy)) {
141         return false;
142       }
143     }
144   }
145 
146   if (hs->min_version < TLS1_3_VERSION && type != ssl_client_hello_inner) {
147     bool any_enabled = false;
148     for (const SSL_CIPHER *cipher : SSL_get_ciphers(ssl)) {
149       // Skip disabled ciphers
150       if ((cipher->algorithm_mkey & mask_k) ||
151           (cipher->algorithm_auth & mask_a)) {
152         continue;
153       }
154       if (SSL_CIPHER_get_min_version(cipher) > hs->max_version ||
155           SSL_CIPHER_get_max_version(cipher) < hs->min_version) {
156         continue;
157       }
158       any_enabled = true;
159       if (!CBB_add_u16(&child, SSL_CIPHER_get_protocol_id(cipher))) {
160         return false;
161       }
162     }
163 
164     // If all ciphers were disabled, return the error to the caller.
165     if (!any_enabled && hs->max_version < TLS1_3_VERSION) {
166       OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CIPHERS_AVAILABLE);
167       return false;
168     }
169   }
170 
171   if (ssl->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
172     if (!CBB_add_u16(&child, SSL3_CK_FALLBACK_SCSV & 0xffff)) {
173       return false;
174     }
175   }
176 
177   return CBB_flush(out);
178 }
179 
ssl_write_client_hello_without_extensions(const SSL_HANDSHAKE * hs,CBB * cbb,ssl_client_hello_type_t type,bool empty_session_id)180 bool ssl_write_client_hello_without_extensions(const SSL_HANDSHAKE *hs,
181                                                CBB *cbb,
182                                                ssl_client_hello_type_t type,
183                                                bool empty_session_id) {
184   const SSL *const ssl = hs->ssl;
185   CBB child;
186   if (!CBB_add_u16(cbb, hs->client_version) ||
187       !CBB_add_bytes(cbb,
188                      type == ssl_client_hello_inner ? hs->inner_client_random
189                                                     : ssl->s3->client_random,
190                      SSL3_RANDOM_SIZE) ||
191       !CBB_add_u8_length_prefixed(cbb, &child)) {
192     return false;
193   }
194 
195   // Do not send a session ID on renegotiation.
196   if (!ssl->s3->initial_handshake_complete &&  //
197       !empty_session_id &&                     //
198       !CBB_add_bytes(&child, hs->session_id.data(), hs->session_id.size())) {
199     return false;
200   }
201 
202   if (SSL_is_dtls(ssl)) {
203     if (!CBB_add_u8_length_prefixed(cbb, &child) ||
204         !CBB_add_bytes(&child, hs->dtls_cookie.data(),
205                        hs->dtls_cookie.size())) {
206       return false;
207     }
208   }
209 
210   if (!ssl_write_client_cipher_list(hs, cbb, type) ||
211       !CBB_add_u8(cbb, 1 /* one compression method */) ||
212       !CBB_add_u8(cbb, 0 /* null compression */)) {
213     return false;
214   }
215   return true;
216 }
217 
ssl_add_client_hello(SSL_HANDSHAKE * hs)218 bool ssl_add_client_hello(SSL_HANDSHAKE *hs) {
219   SSL *const ssl = hs->ssl;
220   ScopedCBB cbb;
221   CBB body;
222   ssl_client_hello_type_t type = hs->selected_ech_config
223                                      ? ssl_client_hello_outer
224                                      : ssl_client_hello_unencrypted;
225   bool needs_psk_binder;
226   Array<uint8_t> msg;
227   if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_CLIENT_HELLO) ||
228       !ssl_write_client_hello_without_extensions(hs, &body, type,
229                                                  /*empty_session_id=*/false) ||
230       !ssl_add_clienthello_tlsext(hs, &body, /*out_encoded=*/nullptr,
231                                   &needs_psk_binder, type, CBB_len(&body)) ||
232       !ssl->method->finish_message(ssl, cbb.get(), &msg)) {
233     return false;
234   }
235 
236   // Now that the length prefixes have been computed, fill in the placeholder
237   // PSK binder.
238   if (needs_psk_binder) {
239     // ClientHelloOuter cannot have a PSK binder. Otherwise the
240     // ClientHellOuterAAD computation would break.
241     assert(type != ssl_client_hello_outer);
242     if (!tls13_write_psk_binder(hs, hs->transcript, Span(msg),
243                                 /*out_binder_len=*/0)) {
244       return false;
245     }
246   }
247 
248   return ssl->method->add_message(ssl, std::move(msg));
249 }
250 
parse_server_version(const SSL_HANDSHAKE * hs,uint16_t * out_version,uint8_t * out_alert,const ParsedServerHello & server_hello)251 static bool parse_server_version(const SSL_HANDSHAKE *hs, uint16_t *out_version,
252                                  uint8_t *out_alert,
253                                  const ParsedServerHello &server_hello) {
254   uint16_t legacy_version = TLS1_2_VERSION;
255   if (SSL_is_dtls(hs->ssl)) {
256     legacy_version = DTLS1_2_VERSION;
257   }
258   // If the outer version is not TLS 1.2, use it.
259   // TODO(davidben): This function doesn't quite match the RFC8446 formulation.
260   if (server_hello.legacy_version != legacy_version) {
261     *out_version = server_hello.legacy_version;
262     return true;
263   }
264 
265   SSLExtension supported_versions(TLSEXT_TYPE_supported_versions);
266   CBS extensions = server_hello.extensions;
267   if (!ssl_parse_extensions(&extensions, out_alert, {&supported_versions},
268                             /*ignore_unknown=*/true)) {
269     return false;
270   }
271 
272   if (!supported_versions.present) {
273     *out_version = server_hello.legacy_version;
274     return true;
275   }
276 
277   if (!CBS_get_u16(&supported_versions.data, out_version) ||  //
278       CBS_len(&supported_versions.data) != 0) {
279     *out_alert = SSL_AD_DECODE_ERROR;
280     return false;
281   }
282 
283   return true;
284 }
285 
286 // should_offer_early_data returns |ssl_early_data_accepted| if |hs| should
287 // offer early data, and some other reason code otherwise.
should_offer_early_data(const SSL_HANDSHAKE * hs)288 static ssl_early_data_reason_t should_offer_early_data(
289     const SSL_HANDSHAKE *hs) {
290   const SSL *const ssl = hs->ssl;
291   assert(!ssl->server);
292   if (!ssl->enable_early_data) {
293     return ssl_early_data_disabled;
294   }
295 
296   if (hs->max_version < TLS1_3_VERSION || SSL_is_dtls(ssl)) {
297     // We discard inapplicable sessions, so this is redundant with the session
298     // checks below, but reporting that TLS 1.3 was disabled is more useful.
299     //
300     // TODO(crbug.com/381113363): Support early data in DTLS 1.3.
301     return ssl_early_data_protocol_version;
302   }
303 
304   if (ssl->session == nullptr) {
305     return ssl_early_data_no_session_offered;
306   }
307 
308   if (ssl_session_protocol_version(ssl->session.get()) < TLS1_3_VERSION ||
309       ssl->session->ticket_max_early_data == 0) {
310     return ssl_early_data_unsupported_for_session;
311   }
312 
313   if (!ssl->session->early_alpn.empty()) {
314     if (!ssl_is_alpn_protocol_allowed(hs, ssl->session->early_alpn)) {
315       // Avoid reporting a confusing value in |SSL_get0_alpn_selected|.
316       return ssl_early_data_alpn_mismatch;
317     }
318 
319     // If the previous connection negotiated ALPS, only offer 0-RTT when the
320     // local are settings are consistent with what we'd offer for this
321     // connection.
322     if (ssl->session->has_application_settings) {
323       Span<const uint8_t> settings;
324       if (!ssl_get_local_application_settings(hs, &settings,
325                                               ssl->session->early_alpn) ||
326           settings != ssl->session->local_application_settings) {
327         return ssl_early_data_alps_mismatch;
328       }
329     }
330   }
331 
332   // Early data has not yet been accepted, but we use it as a success code.
333   return ssl_early_data_accepted;
334 }
335 
ssl_done_writing_client_hello(SSL_HANDSHAKE * hs)336 void ssl_done_writing_client_hello(SSL_HANDSHAKE *hs) {
337   hs->ech_client_outer.Reset();
338   hs->cookie.Reset();
339   hs->key_share_bytes.Reset();
340   hs->pake_share_bytes.Reset();
341 }
342 
do_start_connect(SSL_HANDSHAKE * hs)343 static enum ssl_hs_wait_t do_start_connect(SSL_HANDSHAKE *hs) {
344   SSL *const ssl = hs->ssl;
345 
346   ssl_do_info_callback(ssl, SSL_CB_HANDSHAKE_START, 1);
347   // |session_reused| must be reset in case this is a renegotiation.
348   ssl->s3->session_reused = false;
349 
350   // Freeze the version range.
351   if (!ssl_get_version_range(hs, &hs->min_version, &hs->max_version)) {
352     return ssl_hs_error;
353   }
354 
355   uint8_t ech_enc[EVP_HPKE_MAX_ENC_LENGTH];
356   size_t ech_enc_len;
357   if (!ssl_select_ech_config(hs, ech_enc, &ech_enc_len)) {
358     return ssl_hs_error;
359   }
360 
361   // Always advertise the ClientHello version from the original maximum version,
362   // even on renegotiation. The static RSA key exchange uses this field, and
363   // some servers fail when it changes across handshakes.
364   if (SSL_is_dtls(hs->ssl)) {
365     hs->client_version =
366         hs->max_version >= TLS1_2_VERSION ? DTLS1_2_VERSION : DTLS1_VERSION;
367   } else {
368     hs->client_version =
369         hs->max_version >= TLS1_2_VERSION ? TLS1_2_VERSION : hs->max_version;
370   }
371 
372   if (!ssl_setup_pake_shares(hs)) {
373     return ssl_hs_error;
374   }
375 
376   // If the configured session has expired or is not usable, drop it. We also do
377   // not offer sessions on renegotiation.
378   SSLSessionType session_type = SSLSessionType::kNotResumable;
379   if (ssl->session != nullptr) {
380     session_type = ssl_session_get_type(ssl->session.get());
381     if (ssl->session->is_server ||
382         !ssl_supports_version(hs, ssl->session->ssl_version) ||
383         // Do not offer TLS 1.2 sessions with ECH. ClientHelloInner does not
384         // offer TLS 1.2, and the cleartext session ID may leak the server
385         // identity.
386         (hs->selected_ech_config &&
387          ssl_session_protocol_version(ssl->session.get()) < TLS1_3_VERSION) ||
388         session_type == SSLSessionType::kNotResumable ||
389         // Don't offer TLS 1.2 tickets if disabled.
390         (session_type == SSLSessionType::kTicket &&
391          (SSL_get_options(ssl) & SSL_OP_NO_TICKET)) ||
392         // Don't offer sessions and PAKEs at the same time. We do not currently
393         // support resumption with PAKEs. (Offering both together would need
394         // more logic to conditionally send the key_share extension.)
395         hs->pake_prover != nullptr ||
396         !ssl_session_is_time_valid(ssl, ssl->session.get()) ||
397         SSL_is_quic(ssl) != int{ssl->session->is_quic} ||
398         ssl->s3->initial_handshake_complete) {
399       ssl_set_session(ssl, nullptr);
400       session_type = SSLSessionType::kNotResumable;
401     }
402   }
403 
404   if (!RAND_bytes(ssl->s3->client_random, sizeof(ssl->s3->client_random))) {
405     return ssl_hs_error;
406   }
407   if (hs->selected_ech_config &&
408       !RAND_bytes(hs->inner_client_random, sizeof(hs->inner_client_random))) {
409     return ssl_hs_error;
410   }
411 
412   // Compatibility mode sends a random session ID. Compatibility mode is
413   // enabled for TLS 1.3, but not when it's run over QUIC or DTLS.
414   const bool enable_compatibility_mode = hs->max_version >= TLS1_3_VERSION &&
415                                          !SSL_is_quic(ssl) && !SSL_is_dtls(ssl);
416   if (session_type == SSLSessionType::kID) {
417     hs->session_id = ssl->session->session_id;
418   } else if (session_type == SSLSessionType::kTicket ||
419              enable_compatibility_mode) {
420     // TLS 1.2 session tickets require a placeholder value to signal resumption.
421     hs->session_id.ResizeForOverwrite(SSL_MAX_SSL_SESSION_ID_LENGTH);
422     if (!RAND_bytes(hs->session_id.data(), hs->session_id.size())) {
423       return ssl_hs_error;
424     }
425   }
426 
427   ssl_early_data_reason_t reason = should_offer_early_data(hs);
428   if (reason != ssl_early_data_accepted) {
429     ssl->s3->early_data_reason = reason;
430   } else {
431     hs->early_data_offered = true;
432   }
433 
434   if (!ssl_setup_key_shares(hs, /*override_group_id=*/0) ||
435       !ssl_setup_extension_permutation(hs) ||
436       !ssl_encrypt_client_hello(hs, Span(ech_enc, ech_enc_len)) ||
437       !ssl_add_client_hello(hs)) {
438     return ssl_hs_error;
439   }
440 
441   hs->state = state_enter_early_data;
442   return ssl_hs_flush;
443 }
444 
do_enter_early_data(SSL_HANDSHAKE * hs)445 static enum ssl_hs_wait_t do_enter_early_data(SSL_HANDSHAKE *hs) {
446   SSL *const ssl = hs->ssl;
447   if (!hs->early_data_offered) {
448     hs->state = state_read_server_hello;
449     return ssl_hs_ok;
450   }
451 
452   // Stash the early data session and activate the early version. This must
453   // happen before |do_early_reverify_server_certificate|, so early connection
454   // properties are available to the callback. Note the early version may be
455   // overwritten later by the final version.
456   hs->early_session = UpRef(ssl->session);
457   ssl->s3->version = hs->early_session->ssl_version;
458   hs->is_early_version = true;
459   hs->state = state_early_reverify_server_certificate;
460   return ssl_hs_ok;
461 }
462 
do_early_reverify_server_certificate(SSL_HANDSHAKE * hs)463 static enum ssl_hs_wait_t do_early_reverify_server_certificate(
464     SSL_HANDSHAKE *hs) {
465   SSL *const ssl = hs->ssl;
466   if (ssl->ctx->reverify_on_resume) {
467     // Don't send an alert on error. The alert would be in the clear, which the
468     // server is not expecting anyway. Alerts in between ClientHello and
469     // ServerHello cannot usefully be delivered in TLS 1.3.
470     //
471     // TODO(davidben): The client behavior should be to verify the certificate
472     // before deciding whether to offer the session and, if invalid, decline to
473     // send the session.
474     switch (ssl_reverify_peer_cert(hs, /*send_alert=*/false)) {
475       case ssl_verify_ok:
476         break;
477       case ssl_verify_invalid:
478         return ssl_hs_error;
479       case ssl_verify_retry:
480         hs->state = state_early_reverify_server_certificate;
481         return ssl_hs_certificate_verify;
482     }
483   }
484 
485   if (!ssl->method->add_change_cipher_spec(ssl)) {
486     return ssl_hs_error;
487   }
488 
489   // Defer releasing the 0-RTT key to after certificate reverification, so the
490   // QUIC implementation does not accidentally write data too early.
491   if (!tls13_init_early_key_schedule(hs, hs->early_session.get()) ||
492       !tls13_derive_early_secret(hs) ||
493       !tls13_set_traffic_key(hs->ssl, ssl_encryption_early_data, evp_aead_seal,
494                              hs->early_session.get(),
495                              hs->early_traffic_secret)) {
496     return ssl_hs_error;
497   }
498 
499   hs->in_early_data = true;
500   hs->can_early_write = true;
501   hs->state = state_read_server_hello;
502   return ssl_hs_early_return;
503 }
504 
handle_hello_verify_request(SSL_HANDSHAKE * hs,const SSLMessage & msg)505 static bool handle_hello_verify_request(SSL_HANDSHAKE *hs,
506                                         const SSLMessage &msg) {
507   SSL *const ssl = hs->ssl;
508   assert(SSL_is_dtls(ssl));
509   assert(msg.type == DTLS1_MT_HELLO_VERIFY_REQUEST);
510   assert(!hs->received_hello_verify_request);
511 
512   CBS hello_verify_request = msg.body, cookie;
513   uint16_t server_version;
514   if (!CBS_get_u16(&hello_verify_request, &server_version) ||
515       !CBS_get_u8_length_prefixed(&hello_verify_request, &cookie) ||
516       CBS_len(&hello_verify_request) != 0) {
517     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
518     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
519     return false;
520   }
521 
522   if (!hs->dtls_cookie.CopyFrom(cookie)) {
523     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
524     return false;
525   }
526   hs->received_hello_verify_request = true;
527 
528   ssl->method->next_message(ssl);
529 
530   // DTLS resets the handshake buffer after HelloVerifyRequest.
531   if (!hs->transcript.Init()) {
532     return false;
533   }
534 
535   return ssl_add_client_hello(hs);
536 }
537 
ssl_parse_server_hello(ParsedServerHello * out,uint8_t * out_alert,const SSLMessage & msg)538 bool ssl_parse_server_hello(ParsedServerHello *out, uint8_t *out_alert,
539                             const SSLMessage &msg) {
540   if (msg.type != SSL3_MT_SERVER_HELLO) {
541     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
542     *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
543     return false;
544   }
545   out->raw = msg.raw;
546   CBS body = msg.body;
547   if (!CBS_get_u16(&body, &out->legacy_version) ||
548       !CBS_get_bytes(&body, &out->random, SSL3_RANDOM_SIZE) ||
549       !CBS_get_u8_length_prefixed(&body, &out->session_id) ||
550       CBS_len(&out->session_id) > SSL3_SESSION_ID_SIZE ||
551       !CBS_get_u16(&body, &out->cipher_suite) ||
552       !CBS_get_u8(&body, &out->compression_method)) {
553     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
554     *out_alert = SSL_AD_DECODE_ERROR;
555     return false;
556   }
557   // In TLS 1.2 and below, empty extensions blocks may be omitted. In TLS 1.3,
558   // ServerHellos always have extensions, so this can be applied generically.
559   CBS_init(&out->extensions, nullptr, 0);
560   if ((CBS_len(&body) != 0 &&
561        !CBS_get_u16_length_prefixed(&body, &out->extensions)) ||
562       CBS_len(&body) != 0) {
563     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
564     *out_alert = SSL_AD_DECODE_ERROR;
565     return false;
566   }
567   return true;
568 }
569 
do_read_server_hello(SSL_HANDSHAKE * hs)570 static enum ssl_hs_wait_t do_read_server_hello(SSL_HANDSHAKE *hs) {
571   SSL *const ssl = hs->ssl;
572   SSLMessage msg;
573   if (!ssl->method->get_message(ssl, &msg)) {
574     return ssl_hs_read_server_hello;
575   }
576 
577   if (SSL_is_dtls(ssl) && !hs->received_hello_verify_request &&
578       msg.type == DTLS1_MT_HELLO_VERIFY_REQUEST) {
579     if (!handle_hello_verify_request(hs, msg)) {
580       return ssl_hs_error;
581     }
582     hs->received_hello_verify_request = true;
583     hs->state = state_read_server_hello;
584     return ssl_hs_flush;
585   }
586 
587   ParsedServerHello server_hello;
588   uint16_t server_version;
589   uint8_t alert = SSL_AD_DECODE_ERROR;
590   if (!ssl_parse_server_hello(&server_hello, &alert, msg) ||
591       !parse_server_version(hs, &server_version, &alert, server_hello)) {
592     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
593     return ssl_hs_error;
594   }
595 
596   if (!ssl_supports_version(hs, server_version)) {
597     OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL);
598     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
599     return ssl_hs_error;
600   }
601 
602   if (!ssl->s3->initial_handshake_complete) {
603     // |ssl->s3->version| may be set due to 0-RTT. If it was to a different
604     // value, the check below will fire.
605     assert(ssl->s3->version == 0 ||
606            (hs->is_early_version &&
607             ssl->s3->version == hs->early_session->ssl_version));
608     ssl->s3->version = server_version;
609     hs->is_early_version = false;
610   } else if (server_version != ssl->s3->version) {
611     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION);
612     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
613     return ssl_hs_error;
614   }
615 
616   // If the version did not match, stop sending 0-RTT data.
617   if (hs->early_data_offered &&
618       ssl->s3->version != hs->early_session->ssl_version) {
619     // This is currently only possible by reading a TLS 1.2 (or earlier)
620     // ServerHello in response to TLS 1.3. If there is ever a TLS 1.4, or
621     // another variant of TLS 1.3, the fatal error below will need to be a clean
622     // 0-RTT reject.
623     assert(ssl_protocol_version(ssl) < TLS1_3_VERSION);
624     assert(ssl_session_protocol_version(hs->early_session.get()) >=
625            TLS1_3_VERSION);
626 
627     // A TLS 1.2 server would not know to skip the early data we offered, so
628     // there is no point in continuing the handshake. Report an error code as
629     // soon as we detect this. The caller may use this error code to implement
630     // the fallback described in RFC 8446 appendix D.3.
631     //
632     // Disconnect early writes. This ensures subsequent |SSL_write| calls query
633     // the handshake which, in turn, will replay the error code rather than fail
634     // at the |write_shutdown| check. See https://crbug.com/1078515.
635     // TODO(davidben): Should all handshake errors do this? What about record
636     // decryption failures?
637     //
638     // TODO(crbug.com/381113363): Although missing from the spec, a DTLS 1.2
639     // server will already naturally skip 0-RTT data. If we implement DTLS 1.3
640     // 0-RTT, we may want a clean reject.
641     assert(!SSL_is_dtls(ssl));
642     hs->can_early_write = false;
643     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_VERSION_ON_EARLY_DATA);
644     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
645     return ssl_hs_error;
646   }
647 
648   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
649     if (hs->received_hello_verify_request) {
650       OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_MESSAGE);
651       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
652       return ssl_hs_error;
653     }
654 
655     hs->state = state_tls13;
656     return ssl_hs_ok;
657   }
658 
659   // If this client is configured to use a PAKE, then the server must support
660   // TLS 1.3.
661   if (hs->pake_prover) {
662     OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL);
663     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
664     return ssl_hs_error;
665   }
666 
667   // Clear some TLS 1.3 state that no longer needs to be retained.
668   hs->key_shares[0].reset();
669   hs->key_shares[1].reset();
670   ssl_done_writing_client_hello(hs);
671 
672   // TLS 1.2 handshakes cannot accept ECH.
673   if (hs->selected_ech_config) {
674     ssl->s3->ech_status = ssl_ech_rejected;
675   }
676 
677   // Copy over the server random.
678   OPENSSL_memcpy(ssl->s3->server_random, CBS_data(&server_hello.random),
679                  SSL3_RANDOM_SIZE);
680 
681   // Enforce the TLS 1.3 anti-downgrade feature.
682   if (!ssl->s3->initial_handshake_complete &&
683       hs->max_version >= TLS1_3_VERSION) {
684     static_assert(
685         sizeof(kTLS12DowngradeRandom) == sizeof(kTLS13DowngradeRandom),
686         "downgrade signals have different size");
687     static_assert(
688         sizeof(kJDK11DowngradeRandom) == sizeof(kTLS13DowngradeRandom),
689         "downgrade signals have different size");
690     auto suffix =
691         Span(ssl->s3->server_random).last(sizeof(kTLS13DowngradeRandom));
692     if (suffix == kTLS12DowngradeRandom || suffix == kTLS13DowngradeRandom ||
693         suffix == kJDK11DowngradeRandom) {
694       OPENSSL_PUT_ERROR(SSL, SSL_R_TLS13_DOWNGRADE);
695       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
696       return ssl_hs_error;
697     }
698   }
699 
700   // The cipher must be allowed in the selected version and enabled.
701   const SSL_CIPHER *cipher = SSL_get_cipher_by_value(server_hello.cipher_suite);
702   uint32_t mask_a, mask_k;
703   ssl_get_client_disabled(hs, &mask_a, &mask_k);
704   if (cipher == nullptr ||                                               //
705       (cipher->algorithm_mkey & mask_k) ||                               //
706       (cipher->algorithm_auth & mask_a) ||                               //
707       SSL_CIPHER_get_min_version(cipher) > ssl_protocol_version(ssl) ||  //
708       SSL_CIPHER_get_max_version(cipher) < ssl_protocol_version(ssl) ||  //
709       !sk_SSL_CIPHER_find(SSL_get_ciphers(ssl), nullptr, cipher)) {
710     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
711     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
712     return ssl_hs_error;
713   }
714 
715   hs->new_cipher = cipher;
716 
717   if (!hs->session_id.empty() &&
718       Span<const uint8_t>(server_hello.session_id) == hs->session_id) {
719     // Echoing the ClientHello session ID in TLS 1.2, whether from the session
720     // or a synthetic one, indicates resumption. If there was no session (or if
721     // the session was only offered in ECH ClientHelloInner), this was the
722     // TLS 1.3 compatibility mode session ID. As we know this is not a session
723     // the server knows about, any server resuming it is in error. Reject the
724     // first connection deterministicly, rather than installing an invalid
725     // session into the session cache. https://crbug.com/796910
726     if (ssl->session == nullptr || ssl->s3->ech_status == ssl_ech_rejected) {
727       OPENSSL_PUT_ERROR(SSL, SSL_R_SERVER_ECHOED_INVALID_SESSION_ID);
728       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
729       return ssl_hs_error;
730     }
731     if (ssl->session->ssl_version != ssl->s3->version) {
732       OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_VERSION_NOT_RETURNED);
733       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
734       return ssl_hs_error;
735     }
736     if (ssl->session->cipher != hs->new_cipher) {
737       OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
738       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
739       return ssl_hs_error;
740     }
741     if (!ssl_session_is_context_valid(hs, ssl->session.get())) {
742       // This is actually a client application bug.
743       OPENSSL_PUT_ERROR(SSL,
744                         SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
745       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
746       return ssl_hs_error;
747     }
748     // We never offer sessions on renegotiation.
749     assert(!ssl->s3->initial_handshake_complete);
750     ssl->s3->session_reused = true;
751   } else {
752     // The session wasn't resumed. Create a fresh SSL_SESSION to fill out.
753     ssl_set_session(ssl, NULL);
754     if (!ssl_get_new_session(hs)) {
755       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
756       return ssl_hs_error;
757     }
758 
759     // Save the session ID from the server. This may be empty if the session
760     // isn't resumable, or if we'll receive a session ticket later. The
761     // ServerHello parser ensures |server_hello.session_id| is within bounds.
762     hs->new_session->session_id.CopyFrom(server_hello.session_id);
763     hs->new_session->cipher = hs->new_cipher;
764   }
765 
766   // Now that the cipher is known, initialize the handshake hash and hash the
767   // ServerHello.
768   if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher) ||
769       !ssl_hash_message(hs, msg)) {
770     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
771     return ssl_hs_error;
772   }
773 
774   // If doing a full handshake, the server may request a client certificate
775   // which requires hashing the handshake transcript. Otherwise, the handshake
776   // buffer may be released.
777   if (ssl->session != NULL ||
778       !ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
779     hs->transcript.FreeBuffer();
780   }
781 
782   // Only the NULL compression algorithm is supported.
783   if (server_hello.compression_method != 0) {
784     OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
785     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
786     return ssl_hs_error;
787   }
788 
789   if (!ssl_parse_serverhello_tlsext(hs, &server_hello.extensions)) {
790     OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
791     return ssl_hs_error;
792   }
793 
794   if (ssl->session != NULL &&
795       hs->extended_master_secret != ssl->session->extended_master_secret) {
796     if (ssl->session->extended_master_secret) {
797       OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
798     } else {
799       OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_NON_EMS_SESSION_WITH_EMS_EXTENSION);
800     }
801     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
802     return ssl_hs_error;
803   }
804 
805   ssl->method->next_message(ssl);
806 
807   if (ssl->session != NULL) {
808     if (ssl->ctx->reverify_on_resume &&
809         ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
810       hs->state = state_reverify_server_certificate;
811     } else {
812       hs->state = state_read_session_ticket;
813     }
814     return ssl_hs_ok;
815   }
816 
817   hs->state = state_read_server_certificate;
818   return ssl_hs_ok;
819 }
820 
do_tls13(SSL_HANDSHAKE * hs)821 static enum ssl_hs_wait_t do_tls13(SSL_HANDSHAKE *hs) {
822   enum ssl_hs_wait_t wait = tls13_client_handshake(hs);
823   if (wait == ssl_hs_ok) {
824     hs->state = state_finish_client_handshake;
825     return ssl_hs_ok;
826   }
827 
828   return wait;
829 }
830 
do_read_server_certificate(SSL_HANDSHAKE * hs)831 static enum ssl_hs_wait_t do_read_server_certificate(SSL_HANDSHAKE *hs) {
832   SSL *const ssl = hs->ssl;
833 
834   if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
835     hs->state = state_read_certificate_status;
836     return ssl_hs_ok;
837   }
838 
839   SSLMessage msg;
840   if (!ssl->method->get_message(ssl, &msg)) {
841     return ssl_hs_read_message;
842   }
843 
844   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE) ||
845       !ssl_hash_message(hs, msg)) {
846     return ssl_hs_error;
847   }
848 
849   CBS body = msg.body;
850   uint8_t alert = SSL_AD_DECODE_ERROR;
851   if (!ssl_parse_cert_chain(&alert, &hs->new_session->certs, &hs->peer_pubkey,
852                             NULL, &body, ssl->ctx->pool)) {
853     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
854     return ssl_hs_error;
855   }
856 
857   if (sk_CRYPTO_BUFFER_num(hs->new_session->certs.get()) == 0 ||
858       CBS_len(&body) != 0 ||
859       !ssl->ctx->x509_method->session_cache_objects(hs->new_session.get())) {
860     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
861     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
862     return ssl_hs_error;
863   }
864 
865   if (!ssl_check_leaf_certificate(
866           hs, hs->peer_pubkey.get(),
867           sk_CRYPTO_BUFFER_value(hs->new_session->certs.get(), 0))) {
868     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
869     return ssl_hs_error;
870   }
871 
872   ssl->method->next_message(ssl);
873 
874   hs->state = state_read_certificate_status;
875   return ssl_hs_ok;
876 }
877 
do_read_certificate_status(SSL_HANDSHAKE * hs)878 static enum ssl_hs_wait_t do_read_certificate_status(SSL_HANDSHAKE *hs) {
879   SSL *const ssl = hs->ssl;
880 
881   if (!hs->certificate_status_expected) {
882     hs->state = state_verify_server_certificate;
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   if (msg.type != SSL3_MT_CERTIFICATE_STATUS) {
892     // A server may send status_request in ServerHello and then change its mind
893     // about sending CertificateStatus.
894     hs->state = state_verify_server_certificate;
895     return ssl_hs_ok;
896   }
897 
898   if (!ssl_hash_message(hs, msg)) {
899     return ssl_hs_error;
900   }
901 
902   CBS certificate_status = msg.body, ocsp_response;
903   uint8_t status_type;
904   if (!CBS_get_u8(&certificate_status, &status_type) ||                     //
905       status_type != TLSEXT_STATUSTYPE_ocsp ||                              //
906       !CBS_get_u24_length_prefixed(&certificate_status, &ocsp_response) ||  //
907       CBS_len(&ocsp_response) == 0 ||                                       //
908       CBS_len(&certificate_status) != 0) {
909     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
910     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
911     return ssl_hs_error;
912   }
913 
914   hs->new_session->ocsp_response.reset(
915       CRYPTO_BUFFER_new_from_CBS(&ocsp_response, ssl->ctx->pool));
916   if (hs->new_session->ocsp_response == nullptr) {
917     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
918     return ssl_hs_error;
919   }
920 
921   ssl->method->next_message(ssl);
922 
923   hs->state = state_verify_server_certificate;
924   return ssl_hs_ok;
925 }
926 
do_verify_server_certificate(SSL_HANDSHAKE * hs)927 static enum ssl_hs_wait_t do_verify_server_certificate(SSL_HANDSHAKE *hs) {
928   if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
929     hs->state = state_read_server_key_exchange;
930     return ssl_hs_ok;
931   }
932 
933   switch (ssl_verify_peer_cert(hs)) {
934     case ssl_verify_ok:
935       break;
936     case ssl_verify_invalid:
937       return ssl_hs_error;
938     case ssl_verify_retry:
939       hs->state = state_verify_server_certificate;
940       return ssl_hs_certificate_verify;
941   }
942 
943   hs->state = state_read_server_key_exchange;
944   return ssl_hs_ok;
945 }
946 
do_reverify_server_certificate(SSL_HANDSHAKE * hs)947 static enum ssl_hs_wait_t do_reverify_server_certificate(SSL_HANDSHAKE *hs) {
948   assert(hs->ssl->ctx->reverify_on_resume);
949 
950   switch (ssl_reverify_peer_cert(hs, /*send_alert=*/true)) {
951     case ssl_verify_ok:
952       break;
953     case ssl_verify_invalid:
954       return ssl_hs_error;
955     case ssl_verify_retry:
956       hs->state = state_reverify_server_certificate;
957       return ssl_hs_certificate_verify;
958   }
959 
960   hs->state = state_read_session_ticket;
961   return ssl_hs_ok;
962 }
963 
do_read_server_key_exchange(SSL_HANDSHAKE * hs)964 static enum ssl_hs_wait_t do_read_server_key_exchange(SSL_HANDSHAKE *hs) {
965   SSL *const ssl = hs->ssl;
966   SSLMessage msg;
967   if (!ssl->method->get_message(ssl, &msg)) {
968     return ssl_hs_read_message;
969   }
970 
971   if (msg.type != SSL3_MT_SERVER_KEY_EXCHANGE) {
972     // Some ciphers (pure PSK) have an optional ServerKeyExchange message.
973     if (ssl_cipher_requires_server_key_exchange(hs->new_cipher)) {
974       OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
975       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
976       return ssl_hs_error;
977     }
978 
979     hs->state = state_read_certificate_request;
980     return ssl_hs_ok;
981   }
982 
983   if (!ssl_hash_message(hs, msg)) {
984     return ssl_hs_error;
985   }
986 
987   uint32_t alg_k = hs->new_cipher->algorithm_mkey;
988   uint32_t alg_a = hs->new_cipher->algorithm_auth;
989   CBS server_key_exchange = msg.body;
990   if (alg_a & SSL_aPSK) {
991     CBS psk_identity_hint;
992 
993     // Each of the PSK key exchanges begins with a psk_identity_hint.
994     if (!CBS_get_u16_length_prefixed(&server_key_exchange,
995                                      &psk_identity_hint)) {
996       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
997       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
998       return ssl_hs_error;
999     }
1000 
1001     // Store the PSK identity hint for the ClientKeyExchange. Assume that the
1002     // maximum length of a PSK identity hint can be as long as the maximum
1003     // length of a PSK identity. Also do not allow NULL characters; identities
1004     // are saved as C strings.
1005     //
1006     // TODO(davidben): Should invalid hints be ignored? It's a hint rather than
1007     // a specific identity.
1008     if (CBS_len(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN ||
1009         CBS_contains_zero_byte(&psk_identity_hint)) {
1010       OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
1011       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1012       return ssl_hs_error;
1013     }
1014 
1015     // Save non-empty identity hints as a C string. Empty identity hints we
1016     // treat as missing. Plain PSK makes it possible to send either no hint
1017     // (omit ServerKeyExchange) or an empty hint, while ECDHE_PSK can only spell
1018     // empty hint. Having different capabilities is odd, so we interpret empty
1019     // and missing as identical.
1020     char *raw = nullptr;
1021     if (CBS_len(&psk_identity_hint) != 0 &&
1022         !CBS_strdup(&psk_identity_hint, &raw)) {
1023       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1024       return ssl_hs_error;
1025     }
1026     hs->peer_psk_identity_hint.reset(raw);
1027   }
1028 
1029   if (alg_k & SSL_kECDHE) {
1030     // Parse the server parameters.
1031     uint8_t group_type;
1032     uint16_t group_id;
1033     CBS point;
1034     if (!CBS_get_u8(&server_key_exchange, &group_type) ||
1035         group_type != NAMED_CURVE_TYPE ||
1036         !CBS_get_u16(&server_key_exchange, &group_id) ||
1037         !CBS_get_u8_length_prefixed(&server_key_exchange, &point)) {
1038       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1039       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1040       return ssl_hs_error;
1041     }
1042 
1043     // Ensure the group is consistent with preferences.
1044     if (!tls1_check_group_id(hs, group_id)) {
1045       OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
1046       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
1047       return ssl_hs_error;
1048     }
1049 
1050     // Save the group and peer public key for later.
1051     hs->new_session->group_id = group_id;
1052     if (!hs->peer_key.CopyFrom(point)) {
1053       return ssl_hs_error;
1054     }
1055   } else if (!(alg_k & SSL_kPSK)) {
1056     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
1057     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1058     return ssl_hs_error;
1059   }
1060 
1061   // At this point, |server_key_exchange| contains the signature, if any, while
1062   // |msg.body| contains the entire message. From that, derive a CBS containing
1063   // just the parameter.
1064   CBS parameter;
1065   CBS_init(&parameter, CBS_data(&msg.body),
1066            CBS_len(&msg.body) - CBS_len(&server_key_exchange));
1067 
1068   // ServerKeyExchange should be signed by the server's public key.
1069   if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1070     uint16_t signature_algorithm = 0;
1071     if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1072       if (!CBS_get_u16(&server_key_exchange, &signature_algorithm)) {
1073         OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1074         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1075         return ssl_hs_error;
1076       }
1077       uint8_t alert = SSL_AD_DECODE_ERROR;
1078       if (!tls12_check_peer_sigalg(hs, &alert, signature_algorithm,
1079                                    hs->peer_pubkey.get())) {
1080         ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1081         return ssl_hs_error;
1082       }
1083       hs->new_session->peer_signature_algorithm = signature_algorithm;
1084     } else if (!tls1_get_legacy_signature_algorithm(&signature_algorithm,
1085                                                     hs->peer_pubkey.get())) {
1086       OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
1087       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_CERTIFICATE);
1088       return ssl_hs_error;
1089     }
1090 
1091     // The last field in |server_key_exchange| is the signature.
1092     CBS signature;
1093     if (!CBS_get_u16_length_prefixed(&server_key_exchange, &signature) ||
1094         CBS_len(&server_key_exchange) != 0) {
1095       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1096       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1097       return ssl_hs_error;
1098     }
1099 
1100     ScopedCBB transcript;
1101     Array<uint8_t> transcript_data;
1102     if (!CBB_init(transcript.get(),
1103                   2 * SSL3_RANDOM_SIZE + CBS_len(&parameter)) ||
1104         !CBB_add_bytes(transcript.get(), ssl->s3->client_random,
1105                        SSL3_RANDOM_SIZE) ||
1106         !CBB_add_bytes(transcript.get(), ssl->s3->server_random,
1107                        SSL3_RANDOM_SIZE) ||
1108         !CBB_add_bytes(transcript.get(), CBS_data(&parameter),
1109                        CBS_len(&parameter)) ||
1110         !CBBFinishArray(transcript.get(), &transcript_data)) {
1111       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1112       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1113       return ssl_hs_error;
1114     }
1115 
1116     if (!ssl_public_key_verify(ssl, signature, signature_algorithm,
1117                                hs->peer_pubkey.get(), transcript_data)) {
1118       // bad signature
1119       OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
1120       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
1121       return ssl_hs_error;
1122     }
1123   } else {
1124     // PSK ciphers are the only supported certificate-less ciphers.
1125     assert(alg_a == SSL_aPSK);
1126 
1127     if (CBS_len(&server_key_exchange) > 0) {
1128       OPENSSL_PUT_ERROR(SSL, SSL_R_EXTRA_DATA_IN_MESSAGE);
1129       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1130       return ssl_hs_error;
1131     }
1132   }
1133 
1134   ssl->method->next_message(ssl);
1135   hs->state = state_read_certificate_request;
1136   return ssl_hs_ok;
1137 }
1138 
do_read_certificate_request(SSL_HANDSHAKE * hs)1139 static enum ssl_hs_wait_t do_read_certificate_request(SSL_HANDSHAKE *hs) {
1140   SSL *const ssl = hs->ssl;
1141 
1142   if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1143     hs->state = state_read_server_hello_done;
1144     return ssl_hs_ok;
1145   }
1146 
1147   SSLMessage msg;
1148   if (!ssl->method->get_message(ssl, &msg)) {
1149     return ssl_hs_read_message;
1150   }
1151 
1152   if (msg.type == SSL3_MT_SERVER_HELLO_DONE) {
1153     // If we get here we don't need the handshake buffer as we won't be doing
1154     // client auth.
1155     hs->transcript.FreeBuffer();
1156     hs->state = state_read_server_hello_done;
1157     return ssl_hs_ok;
1158   }
1159 
1160   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_REQUEST) ||
1161       !ssl_hash_message(hs, msg)) {
1162     return ssl_hs_error;
1163   }
1164 
1165   // Get the certificate types.
1166   CBS body = msg.body, certificate_types;
1167   if (!CBS_get_u8_length_prefixed(&body, &certificate_types)) {
1168     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1169     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1170     return ssl_hs_error;
1171   }
1172 
1173   if (!hs->certificate_types.CopyFrom(certificate_types)) {
1174     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1175     return ssl_hs_error;
1176   }
1177 
1178   if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1179     CBS supported_signature_algorithms;
1180     if (!CBS_get_u16_length_prefixed(&body, &supported_signature_algorithms) ||
1181         !tls1_parse_peer_sigalgs(hs, &supported_signature_algorithms)) {
1182       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1183       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1184       return ssl_hs_error;
1185     }
1186   }
1187 
1188   uint8_t alert = SSL_AD_DECODE_ERROR;
1189   UniquePtr<STACK_OF(CRYPTO_BUFFER)> ca_names =
1190       SSL_parse_CA_list(ssl, &alert, &body);
1191   if (!ca_names) {
1192     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1193     return ssl_hs_error;
1194   }
1195 
1196   if (CBS_len(&body) != 0) {
1197     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1198     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1199     return ssl_hs_error;
1200   }
1201 
1202   hs->cert_request = true;
1203   hs->ca_names = std::move(ca_names);
1204   ssl->ctx->x509_method->hs_flush_cached_ca_names(hs);
1205 
1206   ssl->method->next_message(ssl);
1207   hs->state = state_read_server_hello_done;
1208   return ssl_hs_ok;
1209 }
1210 
do_read_server_hello_done(SSL_HANDSHAKE * hs)1211 static enum ssl_hs_wait_t do_read_server_hello_done(SSL_HANDSHAKE *hs) {
1212   SSL *const ssl = hs->ssl;
1213   SSLMessage msg;
1214   if (!ssl->method->get_message(ssl, &msg)) {
1215     return ssl_hs_read_message;
1216   }
1217 
1218   if (!ssl_check_message_type(ssl, msg, SSL3_MT_SERVER_HELLO_DONE) ||
1219       !ssl_hash_message(hs, msg)) {
1220     return ssl_hs_error;
1221   }
1222 
1223   // ServerHelloDone is empty.
1224   if (CBS_len(&msg.body) != 0) {
1225     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1226     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1227     return ssl_hs_error;
1228   }
1229 
1230   // ServerHelloDone should be the end of the flight.
1231   if (ssl->method->has_unprocessed_handshake_data(ssl)) {
1232     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1233     OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESS_HANDSHAKE_DATA);
1234     return ssl_hs_error;
1235   }
1236 
1237   ssl->method->next_message(ssl);
1238   hs->state = state_send_client_certificate;
1239   return ssl_hs_ok;
1240 }
1241 
check_credential(SSL_HANDSHAKE * hs,const SSL_CREDENTIAL * cred,uint16_t * out_sigalg)1242 static bool check_credential(SSL_HANDSHAKE *hs, const SSL_CREDENTIAL *cred,
1243                              uint16_t *out_sigalg) {
1244   if (cred->type != SSLCredentialType::kX509) {
1245     OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1246     return false;
1247   }
1248 
1249   // Check the certificate types advertised by the peer.
1250   uint8_t cert_type;
1251   switch (EVP_PKEY_id(cred->pubkey.get())) {
1252     case EVP_PKEY_RSA:
1253       cert_type = SSL3_CT_RSA_SIGN;
1254       break;
1255     case EVP_PKEY_EC:
1256     case EVP_PKEY_ED25519:
1257       cert_type = TLS_CT_ECDSA_SIGN;
1258       break;
1259     default:
1260       OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1261       return false;
1262   }
1263   if (std::find(hs->certificate_types.begin(), hs->certificate_types.end(),
1264                 cert_type) == hs->certificate_types.end()) {
1265     OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1266     return false;
1267   }
1268 
1269   // All currently supported credentials require a signature. Note this does not
1270   // check the ECDSA curve. Prior to TLS 1.3, there is no way to determine which
1271   // ECDSA curves are supported by the peer, so we must assume all curves are
1272   // supported.
1273   return tls1_choose_signature_algorithm(hs, cred, out_sigalg) &&
1274          ssl_credential_matches_requested_issuers(hs, cred);
1275 }
1276 
do_send_client_certificate(SSL_HANDSHAKE * hs)1277 static enum ssl_hs_wait_t do_send_client_certificate(SSL_HANDSHAKE *hs) {
1278   SSL *const ssl = hs->ssl;
1279 
1280   // The peer didn't request a certificate.
1281   if (!hs->cert_request) {
1282     hs->state = state_send_client_key_exchange;
1283     return ssl_hs_ok;
1284   }
1285 
1286   if (ssl->s3->ech_status == ssl_ech_rejected) {
1287     // Do not send client certificates on ECH reject. We have not authenticated
1288     // the server for the name that can learn the certificate.
1289     SSL_certs_clear(ssl);
1290   } else if (hs->config->cert->cert_cb != nullptr) {
1291     // Call cert_cb to update the certificate.
1292     int rv = hs->config->cert->cert_cb(ssl, hs->config->cert->cert_cb_arg);
1293     if (rv == 0) {
1294       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1295       OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
1296       return ssl_hs_error;
1297     }
1298     if (rv < 0) {
1299       hs->state = state_send_client_certificate;
1300       return ssl_hs_x509_lookup;
1301     }
1302   }
1303 
1304   Array<SSL_CREDENTIAL *> creds;
1305   if (!ssl_get_full_credential_list(hs, &creds)) {
1306     return ssl_hs_error;
1307   }
1308 
1309   if (creds.empty()) {
1310     // If there were no credentials, proceed without a client certificate. In
1311     // this case, the handshake buffer may be released early.
1312     hs->transcript.FreeBuffer();
1313   } else {
1314     // Select the credential to use.
1315     for (SSL_CREDENTIAL *cred : creds) {
1316       ERR_clear_error();
1317       uint16_t sigalg;
1318       if (check_credential(hs, cred, &sigalg)) {
1319         hs->credential = UpRef(cred);
1320         hs->signature_algorithm = sigalg;
1321         break;
1322       }
1323     }
1324     if (hs->credential == nullptr) {
1325       // The error from the last attempt is in the error queue.
1326       assert(ERR_peek_error() != 0);
1327       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1328       return ssl_hs_error;
1329     }
1330   }
1331 
1332   if (!ssl_send_tls12_certificate(hs)) {
1333     return ssl_hs_error;
1334   }
1335 
1336   hs->state = state_send_client_key_exchange;
1337   return ssl_hs_ok;
1338 }
1339 
1340 static_assert(sizeof(size_t) >= sizeof(unsigned),
1341               "size_t is smaller than unsigned");
1342 
do_send_client_key_exchange(SSL_HANDSHAKE * hs)1343 static enum ssl_hs_wait_t do_send_client_key_exchange(SSL_HANDSHAKE *hs) {
1344   SSL *const ssl = hs->ssl;
1345   ScopedCBB cbb;
1346   CBB body;
1347   if (!ssl->method->init_message(ssl, cbb.get(), &body,
1348                                  SSL3_MT_CLIENT_KEY_EXCHANGE)) {
1349     return ssl_hs_error;
1350   }
1351 
1352   Array<uint8_t> pms;
1353   uint32_t alg_k = hs->new_cipher->algorithm_mkey;
1354   uint32_t alg_a = hs->new_cipher->algorithm_auth;
1355   if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1356     const CRYPTO_BUFFER *leaf =
1357         sk_CRYPTO_BUFFER_value(hs->new_session->certs.get(), 0);
1358     CBS leaf_cbs;
1359     CRYPTO_BUFFER_init_CBS(leaf, &leaf_cbs);
1360 
1361     // Check the key usage matches the cipher suite. We do this unconditionally
1362     // for non-RSA certificates. In particular, it's needed to distinguish ECDH
1363     // certificates, which we do not support, from ECDSA certificates.
1364     // Historically, we have not checked RSA key usages, so it is controlled by
1365     // a flag for now. See https://crbug.com/795089.
1366     ssl_key_usage_t intended_use = (alg_k & SSL_kRSA)
1367                                        ? key_usage_encipherment
1368                                        : key_usage_digital_signature;
1369     if (!ssl_cert_check_key_usage(&leaf_cbs, intended_use)) {
1370       if (hs->config->enforce_rsa_key_usage ||
1371           EVP_PKEY_id(hs->peer_pubkey.get()) != EVP_PKEY_RSA) {
1372         return ssl_hs_error;
1373       }
1374       ERR_clear_error();
1375       ssl->s3->was_key_usage_invalid = true;
1376     }
1377   }
1378 
1379   // If using a PSK key exchange, prepare the pre-shared key.
1380   unsigned psk_len = 0;
1381   uint8_t psk[PSK_MAX_PSK_LEN];
1382   if (alg_a & SSL_aPSK) {
1383     if (hs->config->psk_client_callback == NULL) {
1384       OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_NO_CLIENT_CB);
1385       return ssl_hs_error;
1386     }
1387 
1388     char identity[PSK_MAX_IDENTITY_LEN + 1];
1389     OPENSSL_memset(identity, 0, sizeof(identity));
1390     psk_len = hs->config->psk_client_callback(
1391         ssl, hs->peer_psk_identity_hint.get(), identity, sizeof(identity), psk,
1392         sizeof(psk));
1393     if (psk_len == 0) {
1394       OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
1395       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1396       return ssl_hs_error;
1397     }
1398     assert(psk_len <= PSK_MAX_PSK_LEN);
1399 
1400     hs->new_session->psk_identity.reset(OPENSSL_strdup(identity));
1401     if (hs->new_session->psk_identity == nullptr) {
1402       return ssl_hs_error;
1403     }
1404 
1405     // Write out psk_identity.
1406     CBB child;
1407     if (!CBB_add_u16_length_prefixed(&body, &child) ||
1408         !CBB_add_bytes(&child, (const uint8_t *)identity,
1409                        OPENSSL_strnlen(identity, sizeof(identity))) ||
1410         !CBB_flush(&body)) {
1411       return ssl_hs_error;
1412     }
1413   }
1414 
1415   // Depending on the key exchange method, compute |pms|.
1416   if (alg_k & SSL_kRSA) {
1417     RSA *rsa = EVP_PKEY_get0_RSA(hs->peer_pubkey.get());
1418     if (rsa == NULL) {
1419       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1420       return ssl_hs_error;
1421     }
1422 
1423     if (!pms.InitForOverwrite(SSL_MAX_MASTER_KEY_LENGTH)) {
1424       return ssl_hs_error;
1425     }
1426     pms[0] = hs->client_version >> 8;
1427     pms[1] = hs->client_version & 0xff;
1428     if (!RAND_bytes(&pms[2], SSL_MAX_MASTER_KEY_LENGTH - 2)) {
1429       return ssl_hs_error;
1430     }
1431 
1432     CBB enc_pms;
1433     uint8_t *ptr;
1434     size_t enc_pms_len;
1435     if (!CBB_add_u16_length_prefixed(&body, &enc_pms) ||  //
1436         !CBB_reserve(&enc_pms, &ptr, RSA_size(rsa)) ||    //
1437         !RSA_encrypt(rsa, &enc_pms_len, ptr, RSA_size(rsa), pms.data(),
1438                      pms.size(), RSA_PKCS1_PADDING) ||  //
1439         !CBB_did_write(&enc_pms, enc_pms_len) ||        //
1440         !CBB_flush(&body)) {
1441       return ssl_hs_error;
1442     }
1443   } else if (alg_k & SSL_kECDHE) {
1444     CBB child;
1445     if (!CBB_add_u8_length_prefixed(&body, &child)) {
1446       return ssl_hs_error;
1447     }
1448 
1449     // Generate a premaster secret and encapsulate it.
1450     bssl::UniquePtr<SSLKeyShare> kem =
1451         SSLKeyShare::Create(hs->new_session->group_id);
1452     uint8_t alert = SSL_AD_DECODE_ERROR;
1453     if (!kem || !kem->Encap(&child, &pms, &alert, hs->peer_key)) {
1454       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1455       return ssl_hs_error;
1456     }
1457     if (!CBB_flush(&body)) {
1458       return ssl_hs_error;
1459     }
1460 
1461     // The peer key can now be discarded.
1462     hs->peer_key.Reset();
1463   } else if (alg_k & SSL_kPSK) {
1464     // For plain PSK, other_secret is a block of 0s with the same length as
1465     // the pre-shared key.
1466     if (!pms.Init(psk_len)) {
1467       return ssl_hs_error;
1468     }
1469   } else {
1470     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1471     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1472     return ssl_hs_error;
1473   }
1474 
1475   // For a PSK cipher suite, other_secret is combined with the pre-shared
1476   // key.
1477   if (alg_a & SSL_aPSK) {
1478     ScopedCBB pms_cbb;
1479     CBB child;
1480     if (!CBB_init(pms_cbb.get(), 2 + psk_len + 2 + pms.size()) ||
1481         !CBB_add_u16_length_prefixed(pms_cbb.get(), &child) ||
1482         !CBB_add_bytes(&child, pms.data(), pms.size()) ||
1483         !CBB_add_u16_length_prefixed(pms_cbb.get(), &child) ||
1484         !CBB_add_bytes(&child, psk, psk_len) ||
1485         !CBBFinishArray(pms_cbb.get(), &pms)) {
1486       return ssl_hs_error;
1487     }
1488   }
1489 
1490   // The message must be added to the finished hash before calculating the
1491   // master secret.
1492   if (!ssl_add_message_cbb(ssl, cbb.get())) {
1493     return ssl_hs_error;
1494   }
1495 
1496   hs->new_session->secret.ResizeForOverwrite(SSL3_MASTER_SECRET_SIZE);
1497   if (!tls1_generate_master_secret(hs, Span(hs->new_session->secret), pms)) {
1498     return ssl_hs_error;
1499   }
1500 
1501   hs->new_session->extended_master_secret = hs->extended_master_secret;
1502   hs->state = state_send_client_certificate_verify;
1503   return ssl_hs_ok;
1504 }
1505 
do_send_client_certificate_verify(SSL_HANDSHAKE * hs)1506 static enum ssl_hs_wait_t do_send_client_certificate_verify(SSL_HANDSHAKE *hs) {
1507   SSL *const ssl = hs->ssl;
1508 
1509   if (!hs->cert_request || hs->credential == nullptr) {
1510     hs->state = state_send_client_finished;
1511     return ssl_hs_ok;
1512   }
1513 
1514   ScopedCBB cbb;
1515   CBB body, child;
1516   if (!ssl->method->init_message(ssl, cbb.get(), &body,
1517                                  SSL3_MT_CERTIFICATE_VERIFY)) {
1518     return ssl_hs_error;
1519   }
1520 
1521   assert(hs->signature_algorithm != 0);
1522   if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1523     // Write out the digest type in TLS 1.2.
1524     if (!CBB_add_u16(&body, hs->signature_algorithm)) {
1525       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1526       return ssl_hs_error;
1527     }
1528   }
1529 
1530   // Set aside space for the signature.
1531   const size_t max_sig_len = EVP_PKEY_size(hs->credential->pubkey.get());
1532   uint8_t *ptr;
1533   if (!CBB_add_u16_length_prefixed(&body, &child) ||
1534       !CBB_reserve(&child, &ptr, max_sig_len)) {
1535     return ssl_hs_error;
1536   }
1537 
1538   size_t sig_len = max_sig_len;
1539   switch (ssl_private_key_sign(hs, ptr, &sig_len, max_sig_len,
1540                                hs->signature_algorithm,
1541                                hs->transcript.buffer())) {
1542     case ssl_private_key_success:
1543       break;
1544     case ssl_private_key_failure:
1545       return ssl_hs_error;
1546     case ssl_private_key_retry:
1547       hs->state = state_send_client_certificate_verify;
1548       return ssl_hs_private_key_operation;
1549   }
1550 
1551   if (!CBB_did_write(&child, sig_len) ||  //
1552       !ssl_add_message_cbb(ssl, cbb.get())) {
1553     return ssl_hs_error;
1554   }
1555 
1556   // The handshake buffer is no longer necessary.
1557   hs->transcript.FreeBuffer();
1558 
1559   hs->state = state_send_client_finished;
1560   return ssl_hs_ok;
1561 }
1562 
do_send_client_finished(SSL_HANDSHAKE * hs)1563 static enum ssl_hs_wait_t do_send_client_finished(SSL_HANDSHAKE *hs) {
1564   SSL *const ssl = hs->ssl;
1565   hs->can_release_private_key = true;
1566   if (!ssl->method->add_change_cipher_spec(ssl) ||
1567       !tls1_change_cipher_state(hs, evp_aead_seal)) {
1568     return ssl_hs_error;
1569   }
1570 
1571   if (hs->next_proto_neg_seen) {
1572     static const uint8_t kZero[32] = {0};
1573     size_t padding_len =
1574         32 - ((ssl->s3->next_proto_negotiated.size() + 2) % 32);
1575 
1576     ScopedCBB cbb;
1577     CBB body, child;
1578     if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_NEXT_PROTO) ||
1579         !CBB_add_u8_length_prefixed(&body, &child) ||
1580         !CBB_add_bytes(&child, ssl->s3->next_proto_negotiated.data(),
1581                        ssl->s3->next_proto_negotiated.size()) ||
1582         !CBB_add_u8_length_prefixed(&body, &child) ||
1583         !CBB_add_bytes(&child, kZero, padding_len) ||
1584         !ssl_add_message_cbb(ssl, cbb.get())) {
1585       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1586       return ssl_hs_error;
1587     }
1588   }
1589 
1590   if (hs->channel_id_negotiated) {
1591     ScopedCBB cbb;
1592     CBB body;
1593     if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_CHANNEL_ID) ||
1594         !tls1_write_channel_id(hs, &body) ||
1595         !ssl_add_message_cbb(ssl, cbb.get())) {
1596       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1597       return ssl_hs_error;
1598     }
1599   }
1600 
1601   if (!ssl_send_finished(hs)) {
1602     return ssl_hs_error;
1603   }
1604 
1605   hs->state = state_finish_flight;
1606   return ssl_hs_flush;
1607 }
1608 
can_false_start(const SSL_HANDSHAKE * hs)1609 static bool can_false_start(const SSL_HANDSHAKE *hs) {
1610   const SSL *const ssl = hs->ssl;
1611 
1612   // False Start bypasses the Finished check's downgrade protection. This can
1613   // enable attacks where we send data under weaker settings than supported
1614   // (e.g. the Logjam attack). Thus we require TLS 1.2 with an ECDHE+AEAD
1615   // cipher, our strongest settings before TLS 1.3.
1616   //
1617   // Now that TLS 1.3 exists, we would like to avoid similar attacks between
1618   // TLS 1.2 and TLS 1.3, but there are too many TLS 1.2 deployments to
1619   // sacrifice False Start on them. Instead, we rely on the ServerHello.random
1620   // downgrade signal, which we unconditionally enforce.
1621   if (SSL_is_dtls(ssl) ||                              //
1622       SSL_version(ssl) != TLS1_2_VERSION ||            //
1623       hs->new_cipher->algorithm_mkey != SSL_kECDHE ||  //
1624       hs->new_cipher->algorithm_mac != SSL_AEAD) {
1625     return false;
1626   }
1627 
1628   // If ECH was rejected, disable False Start. We run the handshake to
1629   // completion, including the Finished downgrade check, to authenticate the
1630   // recovery flow.
1631   if (ssl->s3->ech_status == ssl_ech_rejected) {
1632     return false;
1633   }
1634 
1635   // Additionally require ALPN or NPN by default.
1636   //
1637   // TODO(davidben): Can this constraint be relaxed globally now that cipher
1638   // suite requirements have been tightened?
1639   if (!ssl->ctx->false_start_allowed_without_alpn &&
1640       ssl->s3->alpn_selected.empty() &&
1641       ssl->s3->next_proto_negotiated.empty()) {
1642     return false;
1643   }
1644 
1645   return true;
1646 }
1647 
do_finish_flight(SSL_HANDSHAKE * hs)1648 static enum ssl_hs_wait_t do_finish_flight(SSL_HANDSHAKE *hs) {
1649   SSL *const ssl = hs->ssl;
1650   if (ssl->session != NULL) {
1651     hs->state = state_finish_client_handshake;
1652     return ssl_hs_ok;
1653   }
1654 
1655   // This is a full handshake. If it involves ChannelID, then record the
1656   // handshake hashes at this point in the session so that any resumption of
1657   // this session with ChannelID can sign those hashes.
1658   if (!tls1_record_handshake_hashes_for_channel_id(hs)) {
1659     return ssl_hs_error;
1660   }
1661 
1662   hs->state = state_read_session_ticket;
1663 
1664   if ((SSL_get_mode(ssl) & SSL_MODE_ENABLE_FALSE_START) &&
1665       can_false_start(hs) &&
1666       // No False Start on renegotiation (would complicate the state machine).
1667       !ssl->s3->initial_handshake_complete) {
1668     hs->in_false_start = true;
1669     hs->can_early_write = true;
1670     return ssl_hs_early_return;
1671   }
1672 
1673   return ssl_hs_ok;
1674 }
1675 
do_read_session_ticket(SSL_HANDSHAKE * hs)1676 static enum ssl_hs_wait_t do_read_session_ticket(SSL_HANDSHAKE *hs) {
1677   SSL *const ssl = hs->ssl;
1678 
1679   if (!hs->ticket_expected) {
1680     hs->state = state_process_change_cipher_spec;
1681     return ssl_hs_read_change_cipher_spec;
1682   }
1683 
1684   SSLMessage msg;
1685   if (!ssl->method->get_message(ssl, &msg)) {
1686     return ssl_hs_read_message;
1687   }
1688 
1689   if (!ssl_check_message_type(ssl, msg, SSL3_MT_NEW_SESSION_TICKET) ||
1690       !ssl_hash_message(hs, msg)) {
1691     return ssl_hs_error;
1692   }
1693 
1694   CBS new_session_ticket = msg.body, ticket;
1695   uint32_t ticket_lifetime_hint;
1696   if (!CBS_get_u32(&new_session_ticket, &ticket_lifetime_hint) ||
1697       !CBS_get_u16_length_prefixed(&new_session_ticket, &ticket) ||
1698       CBS_len(&new_session_ticket) != 0) {
1699     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1700     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1701     return ssl_hs_error;
1702   }
1703 
1704   if (CBS_len(&ticket) == 0) {
1705     // RFC 5077 allows a server to change its mind and send no ticket after
1706     // negotiating the extension. The value of |ticket_expected| is checked in
1707     // |ssl_update_cache| so is cleared here to avoid an unnecessary update.
1708     hs->ticket_expected = false;
1709     ssl->method->next_message(ssl);
1710     hs->state = state_process_change_cipher_spec;
1711     return ssl_hs_read_change_cipher_spec;
1712   }
1713 
1714   if (ssl->session != nullptr) {
1715     // The server is sending a new ticket for an existing session. Sessions are
1716     // immutable once established, so duplicate all but the ticket of the
1717     // existing session.
1718     assert(!hs->new_session);
1719     hs->new_session =
1720         SSL_SESSION_dup(ssl->session.get(), SSL_SESSION_INCLUDE_NONAUTH);
1721     if (!hs->new_session) {
1722       return ssl_hs_error;
1723     }
1724   }
1725 
1726   // |ticket_lifetime_hint| is measured from when the ticket was issued.
1727   ssl_session_rebase_time(ssl, hs->new_session.get());
1728 
1729   if (!hs->new_session->ticket.CopyFrom(ticket)) {
1730     return ssl_hs_error;
1731   }
1732   hs->new_session->ticket_lifetime_hint = ticket_lifetime_hint;
1733 
1734   // Historically, OpenSSL filled in fake session IDs for ticket-based sessions.
1735   // TODO(davidben): Are external callers relying on this? Try removing this.
1736   hs->new_session->session_id.ResizeForOverwrite(SHA256_DIGEST_LENGTH);
1737   SHA256(CBS_data(&ticket), CBS_len(&ticket),
1738          hs->new_session->session_id.data());
1739 
1740   ssl->method->next_message(ssl);
1741   hs->state = state_process_change_cipher_spec;
1742   return ssl_hs_read_change_cipher_spec;
1743 }
1744 
do_process_change_cipher_spec(SSL_HANDSHAKE * hs)1745 static enum ssl_hs_wait_t do_process_change_cipher_spec(SSL_HANDSHAKE *hs) {
1746   if (!tls1_change_cipher_state(hs, evp_aead_open)) {
1747     return ssl_hs_error;
1748   }
1749 
1750   hs->state = state_read_server_finished;
1751   return ssl_hs_ok;
1752 }
1753 
do_read_server_finished(SSL_HANDSHAKE * hs)1754 static enum ssl_hs_wait_t do_read_server_finished(SSL_HANDSHAKE *hs) {
1755   SSL *const ssl = hs->ssl;
1756   enum ssl_hs_wait_t wait = ssl_get_finished(hs);
1757   if (wait != ssl_hs_ok) {
1758     return wait;
1759   }
1760 
1761   if (ssl->session != NULL) {
1762     hs->state = state_send_client_finished;
1763     return ssl_hs_ok;
1764   }
1765 
1766   hs->state = state_finish_client_handshake;
1767   return ssl_hs_ok;
1768 }
1769 
do_finish_client_handshake(SSL_HANDSHAKE * hs)1770 static enum ssl_hs_wait_t do_finish_client_handshake(SSL_HANDSHAKE *hs) {
1771   SSL *const ssl = hs->ssl;
1772   if (ssl->s3->ech_status == ssl_ech_rejected) {
1773     // Release the retry configs.
1774     hs->ech_authenticated_reject = true;
1775     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ECH_REQUIRED);
1776     OPENSSL_PUT_ERROR(SSL, SSL_R_ECH_REJECTED);
1777     return ssl_hs_error;
1778   }
1779 
1780   ssl->method->on_handshake_complete(ssl);
1781 
1782   // Note TLS 1.2 resumptions with ticket renewal have both |ssl->session| (the
1783   // resumed session) and |hs->new_session| (the session with the new ticket).
1784   bool has_new_session = hs->new_session != nullptr;
1785   if (has_new_session) {
1786     // When False Start is enabled, the handshake reports completion early. The
1787     // caller may then have passed the (then unresuable) |hs->new_session| to
1788     // another thread via |SSL_get0_session| for resumption. To avoid potential
1789     // race conditions in such callers, we duplicate the session before
1790     // clearing |not_resumable|.
1791     ssl->s3->established_session =
1792         SSL_SESSION_dup(hs->new_session.get(), SSL_SESSION_DUP_ALL);
1793     if (!ssl->s3->established_session) {
1794       return ssl_hs_error;
1795     }
1796     // Renegotiations do not participate in session resumption.
1797     if (!ssl->s3->initial_handshake_complete) {
1798       ssl->s3->established_session->not_resumable = false;
1799     }
1800 
1801     hs->new_session.reset();
1802   } else {
1803     assert(ssl->session != nullptr);
1804     ssl->s3->established_session = UpRef(ssl->session);
1805   }
1806 
1807   hs->handshake_finalized = true;
1808   ssl->s3->initial_handshake_complete = true;
1809   if (has_new_session) {
1810     ssl_update_cache(ssl);
1811   }
1812 
1813   hs->state = state_done;
1814   return ssl_hs_ok;
1815 }
1816 
ssl_client_handshake(SSL_HANDSHAKE * hs)1817 enum ssl_hs_wait_t ssl_client_handshake(SSL_HANDSHAKE *hs) {
1818   while (hs->state != state_done) {
1819     enum ssl_hs_wait_t ret = ssl_hs_error;
1820     enum ssl_client_hs_state_t state =
1821         static_cast<enum ssl_client_hs_state_t>(hs->state);
1822     switch (state) {
1823       case state_start_connect:
1824         ret = do_start_connect(hs);
1825         break;
1826       case state_enter_early_data:
1827         ret = do_enter_early_data(hs);
1828         break;
1829       case state_early_reverify_server_certificate:
1830         ret = do_early_reverify_server_certificate(hs);
1831         break;
1832       case state_read_server_hello:
1833         ret = do_read_server_hello(hs);
1834         break;
1835       case state_tls13:
1836         ret = do_tls13(hs);
1837         break;
1838       case state_read_server_certificate:
1839         ret = do_read_server_certificate(hs);
1840         break;
1841       case state_read_certificate_status:
1842         ret = do_read_certificate_status(hs);
1843         break;
1844       case state_verify_server_certificate:
1845         ret = do_verify_server_certificate(hs);
1846         break;
1847       case state_reverify_server_certificate:
1848         ret = do_reverify_server_certificate(hs);
1849         break;
1850       case state_read_server_key_exchange:
1851         ret = do_read_server_key_exchange(hs);
1852         break;
1853       case state_read_certificate_request:
1854         ret = do_read_certificate_request(hs);
1855         break;
1856       case state_read_server_hello_done:
1857         ret = do_read_server_hello_done(hs);
1858         break;
1859       case state_send_client_certificate:
1860         ret = do_send_client_certificate(hs);
1861         break;
1862       case state_send_client_key_exchange:
1863         ret = do_send_client_key_exchange(hs);
1864         break;
1865       case state_send_client_certificate_verify:
1866         ret = do_send_client_certificate_verify(hs);
1867         break;
1868       case state_send_client_finished:
1869         ret = do_send_client_finished(hs);
1870         break;
1871       case state_finish_flight:
1872         ret = do_finish_flight(hs);
1873         break;
1874       case state_read_session_ticket:
1875         ret = do_read_session_ticket(hs);
1876         break;
1877       case state_process_change_cipher_spec:
1878         ret = do_process_change_cipher_spec(hs);
1879         break;
1880       case state_read_server_finished:
1881         ret = do_read_server_finished(hs);
1882         break;
1883       case state_finish_client_handshake:
1884         ret = do_finish_client_handshake(hs);
1885         break;
1886       case state_done:
1887         ret = ssl_hs_ok;
1888         break;
1889     }
1890 
1891     if (hs->state != state) {
1892       ssl_do_info_callback(hs->ssl, SSL_CB_CONNECT_LOOP, 1);
1893     }
1894 
1895     if (ret != ssl_hs_ok) {
1896       return ret;
1897     }
1898   }
1899 
1900   ssl_do_info_callback(hs->ssl, SSL_CB_HANDSHAKE_DONE, 1);
1901   return ssl_hs_ok;
1902 }
1903 
ssl_client_handshake_state(SSL_HANDSHAKE * hs)1904 const char *ssl_client_handshake_state(SSL_HANDSHAKE *hs) {
1905   enum ssl_client_hs_state_t state =
1906       static_cast<enum ssl_client_hs_state_t>(hs->state);
1907   switch (state) {
1908     case state_start_connect:
1909       return "TLS client start_connect";
1910     case state_enter_early_data:
1911       return "TLS client enter_early_data";
1912     case state_early_reverify_server_certificate:
1913       return "TLS client early_reverify_server_certificate";
1914     case state_read_server_hello:
1915       return "TLS client read_server_hello";
1916     case state_tls13:
1917       return tls13_client_handshake_state(hs);
1918     case state_read_server_certificate:
1919       return "TLS client read_server_certificate";
1920     case state_read_certificate_status:
1921       return "TLS client read_certificate_status";
1922     case state_verify_server_certificate:
1923       return "TLS client verify_server_certificate";
1924     case state_reverify_server_certificate:
1925       return "TLS client reverify_server_certificate";
1926     case state_read_server_key_exchange:
1927       return "TLS client read_server_key_exchange";
1928     case state_read_certificate_request:
1929       return "TLS client read_certificate_request";
1930     case state_read_server_hello_done:
1931       return "TLS client read_server_hello_done";
1932     case state_send_client_certificate:
1933       return "TLS client send_client_certificate";
1934     case state_send_client_key_exchange:
1935       return "TLS client send_client_key_exchange";
1936     case state_send_client_certificate_verify:
1937       return "TLS client send_client_certificate_verify";
1938     case state_send_client_finished:
1939       return "TLS client send_client_finished";
1940     case state_finish_flight:
1941       return "TLS client finish_flight";
1942     case state_read_session_ticket:
1943       return "TLS client read_session_ticket";
1944     case state_process_change_cipher_spec:
1945       return "TLS client process_change_cipher_spec";
1946     case state_read_server_finished:
1947       return "TLS client read_server_finished";
1948     case state_finish_client_handshake:
1949       return "TLS client finish_client_handshake";
1950     case state_done:
1951       return "TLS client done";
1952   }
1953 
1954   return "TLS client unknown";
1955 }
1956 
1957 BSSL_NAMESPACE_END
1958