1 // Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
2 // Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //     https://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 
16 #include <openssl/ssl.h>
17 
18 #include <assert.h>
19 
20 #include <algorithm>
21 #include <utility>
22 
23 #include <openssl/rand.h>
24 
25 #include "../crypto/internal.h"
26 #include "internal.h"
27 
28 
29 BSSL_NAMESPACE_BEGIN
30 
SSL_HANDSHAKE(SSL * ssl_arg)31 SSL_HANDSHAKE::SSL_HANDSHAKE(SSL *ssl_arg)
32     : ssl(ssl_arg),
33       transcript(SSL_is_dtls(ssl_arg)),
34       inner_transcript(SSL_is_dtls(ssl_arg)),
35       ech_is_inner(false),
36       ech_authenticated_reject(false),
37       scts_requested(false),
38       handshake_finalized(false),
39       accept_psk_mode(false),
40       cert_request(false),
41       certificate_status_expected(false),
42       ocsp_stapling_requested(false),
43       should_ack_sni(false),
44       in_false_start(false),
45       in_early_data(false),
46       early_data_offered(false),
47       can_early_read(false),
48       can_early_write(false),
49       is_early_version(false),
50       next_proto_neg_seen(false),
51       ticket_expected(false),
52       extended_master_secret(false),
53       pending_private_key_op(false),
54       handback(false),
55       hints_requested(false),
56       cert_compression_negotiated(false),
57       apply_jdk11_workaround(false),
58       can_release_private_key(false),
59       channel_id_negotiated(false),
60       received_hello_verify_request(false),
61       matched_peer_trust_anchor(false),
62       peer_matched_trust_anchor(false) {
63   assert(ssl);
64 
65   // Draw entropy for all GREASE values at once. This avoids calling
66   // |RAND_bytes| repeatedly and makes the values consistent within a
67   // connection. The latter is so the second ClientHello matches after
68   // HelloRetryRequest and so supported_groups and key_shares are consistent.
69   RAND_bytes(grease_seed, sizeof(grease_seed));
70 }
71 
~SSL_HANDSHAKE()72 SSL_HANDSHAKE::~SSL_HANDSHAKE() {
73   ssl->ctx->x509_method->hs_flush_cached_ca_names(this);
74 }
75 
GetClientHello(SSLMessage * out_msg,SSL_CLIENT_HELLO * out_client_hello)76 bool SSL_HANDSHAKE::GetClientHello(SSLMessage *out_msg,
77                                    SSL_CLIENT_HELLO *out_client_hello) {
78   if (!ech_client_hello_buf.empty()) {
79     // If the backing buffer is non-empty, the ClientHelloInner has been set.
80     out_msg->is_v2_hello = false;
81     out_msg->type = SSL3_MT_CLIENT_HELLO;
82     out_msg->raw = CBS(ech_client_hello_buf);
83     size_t header_len =
84         SSL_is_dtls(ssl) ? DTLS1_HM_HEADER_LENGTH : SSL3_HM_HEADER_LENGTH;
85     out_msg->body = CBS(Span(ech_client_hello_buf).subspan(header_len));
86   } else if (!ssl->method->get_message(ssl, out_msg)) {
87     // The message has already been read, so this cannot fail.
88     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
89     return false;
90   }
91 
92   if (!SSL_parse_client_hello(ssl, out_client_hello, CBS_data(&out_msg->body),
93                               CBS_len(&out_msg->body))) {
94     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
95     return false;
96   }
97   return true;
98 }
99 
ssl_handshake_new(SSL * ssl)100 UniquePtr<SSL_HANDSHAKE> ssl_handshake_new(SSL *ssl) {
101   UniquePtr<SSL_HANDSHAKE> hs = MakeUnique<SSL_HANDSHAKE>(ssl);
102   if (!hs || !hs->transcript.Init()) {
103     return nullptr;
104   }
105   hs->config = ssl->config.get();
106   if (!hs->config) {
107     assert(hs->config);
108     return nullptr;
109   }
110   return hs;
111 }
112 
ssl_check_message_type(SSL * ssl,const SSLMessage & msg,int type)113 bool ssl_check_message_type(SSL *ssl, const SSLMessage &msg, int type) {
114   if (msg.type != type) {
115     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
116     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
117     ERR_add_error_dataf("got type %d, wanted type %d", msg.type, type);
118     return false;
119   }
120 
121   return true;
122 }
123 
ssl_add_message_cbb(SSL * ssl,CBB * cbb)124 bool ssl_add_message_cbb(SSL *ssl, CBB *cbb) {
125   Array<uint8_t> msg;
126   if (!ssl->method->finish_message(ssl, cbb, &msg) ||
127       !ssl->method->add_message(ssl, std::move(msg))) {
128     return false;
129   }
130 
131   return true;
132 }
133 
ssl_max_handshake_message_len(const SSL * ssl)134 size_t ssl_max_handshake_message_len(const SSL *ssl) {
135   // kMaxMessageLen is the default maximum message size for handshakes which do
136   // not accept peer certificate chains.
137   static const size_t kMaxMessageLen = 16384;
138 
139   if (SSL_in_init(ssl)) {
140     SSL_CONFIG *config = ssl->config.get();  // SSL_in_init() implies not NULL.
141     if ((!ssl->server || (config->verify_mode & SSL_VERIFY_PEER)) &&
142         kMaxMessageLen < ssl->max_cert_list) {
143       return ssl->max_cert_list;
144     }
145     return kMaxMessageLen;
146   }
147 
148   if (ssl_protocol_version(ssl) < TLS1_3_VERSION) {
149     // In TLS 1.2 and below, the largest acceptable post-handshake message is
150     // a HelloRequest.
151     return 0;
152   }
153 
154   if (ssl->server) {
155     // The largest acceptable post-handshake message for a server is a
156     // KeyUpdate. We will never initiate post-handshake auth.
157     return 1;
158   }
159 
160   // Clients must accept NewSessionTicket, so allow the default size or
161   // max_cert_list, whichever is greater.
162   return std::max(kMaxMessageLen, size_t{ssl->max_cert_list});
163 }
164 
ssl_hash_message(SSL_HANDSHAKE * hs,const SSLMessage & msg)165 bool ssl_hash_message(SSL_HANDSHAKE *hs, const SSLMessage &msg) {
166   // V2ClientHello messages are pre-hashed.
167   if (msg.is_v2_hello) {
168     return true;
169   }
170 
171   return hs->transcript.Update(msg.raw);
172 }
173 
ssl_parse_extensions(const CBS * cbs,uint8_t * out_alert,std::initializer_list<SSLExtension * > extensions,bool ignore_unknown)174 bool ssl_parse_extensions(const CBS *cbs, uint8_t *out_alert,
175                           std::initializer_list<SSLExtension *> extensions,
176                           bool ignore_unknown) {
177   // Reset everything.
178   for (SSLExtension *ext : extensions) {
179     ext->present = false;
180     CBS_init(&ext->data, nullptr, 0);
181     if (!ext->allowed) {
182       assert(!ignore_unknown);
183     }
184   }
185 
186   CBS copy = *cbs;
187   while (CBS_len(&copy) != 0) {
188     uint16_t type;
189     CBS data;
190     if (!CBS_get_u16(&copy, &type) ||
191         !CBS_get_u16_length_prefixed(&copy, &data)) {
192       OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
193       *out_alert = SSL_AD_DECODE_ERROR;
194       return false;
195     }
196 
197     SSLExtension *found = nullptr;
198     for (SSLExtension *ext : extensions) {
199       if (type == ext->type && ext->allowed) {
200         found = ext;
201         break;
202       }
203     }
204 
205     if (found == nullptr) {
206       if (ignore_unknown) {
207         continue;
208       }
209       OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
210       ERR_add_error_dataf("extension %u", unsigned{type});
211       *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
212       return false;
213     }
214 
215     // Duplicate ext_types are forbidden.
216     if (found->present) {
217       OPENSSL_PUT_ERROR(SSL, SSL_R_DUPLICATE_EXTENSION);
218       *out_alert = SSL_AD_ILLEGAL_PARAMETER;
219       return false;
220     }
221 
222     found->present = true;
223     found->data = data;
224   }
225 
226   return true;
227 }
228 
ssl_verify_peer_cert(SSL_HANDSHAKE * hs)229 enum ssl_verify_result_t ssl_verify_peer_cert(SSL_HANDSHAKE *hs) {
230   SSL *const ssl = hs->ssl;
231   const SSL_SESSION *prev_session = ssl->s3->established_session.get();
232   if (prev_session != NULL) {
233     // If renegotiating, the server must not change the server certificate. See
234     // https://mitls.org/pages/attacks/3SHAKE. We never resume on renegotiation,
235     // so this check is sufficient to ensure the reported peer certificate never
236     // changes on renegotiation.
237     assert(!ssl->server);
238     if (sk_CRYPTO_BUFFER_num(prev_session->certs.get()) !=
239         sk_CRYPTO_BUFFER_num(hs->new_session->certs.get())) {
240       OPENSSL_PUT_ERROR(SSL, SSL_R_SERVER_CERT_CHANGED);
241       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
242       return ssl_verify_invalid;
243     }
244 
245     for (size_t i = 0; i < sk_CRYPTO_BUFFER_num(hs->new_session->certs.get());
246          i++) {
247       const CRYPTO_BUFFER *old_cert =
248           sk_CRYPTO_BUFFER_value(prev_session->certs.get(), i);
249       const CRYPTO_BUFFER *new_cert =
250           sk_CRYPTO_BUFFER_value(hs->new_session->certs.get(), i);
251       if (Span(CRYPTO_BUFFER_data(old_cert), CRYPTO_BUFFER_len(old_cert)) !=
252           Span(CRYPTO_BUFFER_data(new_cert), CRYPTO_BUFFER_len(new_cert))) {
253         OPENSSL_PUT_ERROR(SSL, SSL_R_SERVER_CERT_CHANGED);
254         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
255         return ssl_verify_invalid;
256       }
257     }
258 
259     // The certificate is identical, so we may skip re-verifying the
260     // certificate. Since we only authenticated the previous one, copy other
261     // authentication from the established session and ignore what was newly
262     // received.
263     hs->new_session->ocsp_response = UpRef(prev_session->ocsp_response);
264     hs->new_session->signed_cert_timestamp_list =
265         UpRef(prev_session->signed_cert_timestamp_list);
266     hs->new_session->verify_result = prev_session->verify_result;
267     return ssl_verify_ok;
268   }
269 
270   uint8_t alert = SSL_AD_CERTIFICATE_UNKNOWN;
271   enum ssl_verify_result_t ret;
272   if (hs->config->custom_verify_callback != nullptr) {
273     ret = hs->config->custom_verify_callback(ssl, &alert);
274     switch (ret) {
275       case ssl_verify_ok:
276         hs->new_session->verify_result = X509_V_OK;
277         break;
278       case ssl_verify_invalid:
279         // If |SSL_VERIFY_NONE|, the error is non-fatal, but we keep the result.
280         if (hs->config->verify_mode == SSL_VERIFY_NONE) {
281           ERR_clear_error();
282           ret = ssl_verify_ok;
283         }
284         hs->new_session->verify_result = X509_V_ERR_APPLICATION_VERIFICATION;
285         break;
286       case ssl_verify_retry:
287         break;
288     }
289   } else {
290     ret = ssl->ctx->x509_method->session_verify_cert_chain(
291               hs->new_session.get(), hs, &alert)
292               ? ssl_verify_ok
293               : ssl_verify_invalid;
294   }
295 
296   if (ret == ssl_verify_invalid) {
297     OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_VERIFY_FAILED);
298     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
299   }
300 
301   // Emulate OpenSSL's client OCSP callback. OpenSSL verifies certificates
302   // before it receives the OCSP, so it needs a second callback for OCSP.
303   if (ret == ssl_verify_ok && !ssl->server &&
304       hs->config->ocsp_stapling_enabled &&
305       ssl->ctx->legacy_ocsp_callback != nullptr) {
306     int cb_ret =
307         ssl->ctx->legacy_ocsp_callback(ssl, ssl->ctx->legacy_ocsp_callback_arg);
308     if (cb_ret <= 0) {
309       OPENSSL_PUT_ERROR(SSL, SSL_R_OCSP_CB_ERROR);
310       ssl_send_alert(ssl, SSL3_AL_FATAL,
311                      cb_ret == 0 ? SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
312                                  : SSL_AD_INTERNAL_ERROR);
313       ret = ssl_verify_invalid;
314     }
315   }
316 
317   return ret;
318 }
319 
320 // Verifies a stored certificate when resuming a session. A few things are
321 // different from verify_peer_cert:
322 // 1. We can't be renegotiating if we're resuming a session.
323 // 2. The session is immutable, so we don't support verify_mode ==
324 // SSL_VERIFY_NONE
325 // 3. We don't call the OCSP callback.
326 // 4. We only support custom verify callbacks.
ssl_reverify_peer_cert(SSL_HANDSHAKE * hs,bool send_alert)327 enum ssl_verify_result_t ssl_reverify_peer_cert(SSL_HANDSHAKE *hs,
328                                                 bool send_alert) {
329   SSL *const ssl = hs->ssl;
330   assert(ssl->s3->established_session == nullptr);
331   assert(hs->config->verify_mode != SSL_VERIFY_NONE);
332 
333   uint8_t alert = SSL_AD_CERTIFICATE_UNKNOWN;
334   enum ssl_verify_result_t ret = ssl_verify_invalid;
335   if (hs->config->custom_verify_callback != nullptr) {
336     ret = hs->config->custom_verify_callback(ssl, &alert);
337   }
338 
339   if (ret == ssl_verify_invalid) {
340     OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_VERIFY_FAILED);
341     if (send_alert) {
342       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
343     }
344   }
345 
346   return ret;
347 }
348 
grease_index_to_value(const SSL_HANDSHAKE * hs,enum ssl_grease_index_t index)349 static uint16_t grease_index_to_value(const SSL_HANDSHAKE *hs,
350                                       enum ssl_grease_index_t index) {
351   // This generates a random value of the form 0xωaωa, for all 0 ≤ ω < 16.
352   uint16_t ret = hs->grease_seed[index];
353   ret = (ret & 0xf0) | 0x0a;
354   ret |= ret << 8;
355   return ret;
356 }
357 
ssl_get_grease_value(const SSL_HANDSHAKE * hs,enum ssl_grease_index_t index)358 uint16_t ssl_get_grease_value(const SSL_HANDSHAKE *hs,
359                               enum ssl_grease_index_t index) {
360   uint16_t ret = grease_index_to_value(hs, index);
361   if (index == ssl_grease_extension2 &&
362       ret == grease_index_to_value(hs, ssl_grease_extension1)) {
363     // The two fake extensions must not have the same value. GREASE values are
364     // of the form 0x1a1a, 0x2a2a, 0x3a3a, etc., so XOR to generate a different
365     // one.
366     ret ^= 0x1010;
367   }
368   return ret;
369 }
370 
ssl_get_finished(SSL_HANDSHAKE * hs)371 enum ssl_hs_wait_t ssl_get_finished(SSL_HANDSHAKE *hs) {
372   SSL *const ssl = hs->ssl;
373   SSLMessage msg;
374   if (!ssl->method->get_message(ssl, &msg)) {
375     return ssl_hs_read_message;
376   }
377 
378   if (!ssl_check_message_type(ssl, msg, SSL3_MT_FINISHED)) {
379     return ssl_hs_error;
380   }
381 
382   // Snapshot the finished hash before incorporating the new message.
383   uint8_t finished[EVP_MAX_MD_SIZE];
384   size_t finished_len;
385   if (!hs->transcript.GetFinishedMAC(finished, &finished_len,
386                                      ssl_handshake_session(hs), !ssl->server) ||
387       !ssl_hash_message(hs, msg)) {
388     return ssl_hs_error;
389   }
390 
391   bool finished_ok = CBS_mem_equal(&msg.body, finished, finished_len);
392   if (CRYPTO_fuzzer_mode_enabled()) {
393     finished_ok = true;
394   }
395   if (!finished_ok) {
396     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
397     OPENSSL_PUT_ERROR(SSL, SSL_R_DIGEST_CHECK_FAILED);
398     return ssl_hs_error;
399   }
400 
401   // Copy the Finished so we can use it for renegotiation checks.
402   if (finished_len > ssl->s3->previous_client_finished.capacity() ||
403       finished_len > ssl->s3->previous_server_finished.capacity()) {
404     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
405     return ssl_hs_error;
406   }
407 
408   if (ssl->server) {
409     ssl->s3->previous_client_finished.CopyFrom(Span(finished, finished_len));
410   } else {
411     ssl->s3->previous_server_finished.CopyFrom(Span(finished, finished_len));
412   }
413 
414   // The Finished message should be the end of a flight.
415   if (ssl->method->has_unprocessed_handshake_data(ssl)) {
416     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
417     OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESS_HANDSHAKE_DATA);
418     return ssl_hs_error;
419   }
420 
421   ssl->method->next_message(ssl);
422   return ssl_hs_ok;
423 }
424 
ssl_send_finished(SSL_HANDSHAKE * hs)425 bool ssl_send_finished(SSL_HANDSHAKE *hs) {
426   SSL *const ssl = hs->ssl;
427   const SSL_SESSION *session = ssl_handshake_session(hs);
428 
429   uint8_t finished_buf[EVP_MAX_MD_SIZE];
430   size_t finished_len;
431   if (!hs->transcript.GetFinishedMAC(finished_buf, &finished_len, session,
432                                      ssl->server)) {
433     return false;
434   }
435   auto finished = Span(finished_buf, finished_len);
436 
437   // Log the master secret, if logging is enabled.
438   if (!ssl_log_secret(ssl, "CLIENT_RANDOM", session->secret)) {
439     return false;
440   }
441 
442   // Copy the Finished so we can use it for renegotiation checks.
443   bool ok = ssl->server
444                 ? ssl->s3->previous_server_finished.TryCopyFrom(finished)
445                 : ssl->s3->previous_client_finished.TryCopyFrom(finished);
446   if (!ok) {
447     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
448     return ssl_hs_error;
449   }
450 
451   ScopedCBB cbb;
452   CBB body;
453   if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_FINISHED) ||
454       !CBB_add_bytes(&body, finished.data(), finished.size()) ||
455       !ssl_add_message_cbb(ssl, cbb.get())) {
456     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
457     return false;
458   }
459 
460   return true;
461 }
462 
ssl_send_tls12_certificate(SSL_HANDSHAKE * hs)463 bool ssl_send_tls12_certificate(SSL_HANDSHAKE *hs) {
464   ScopedCBB cbb;
465   CBB body, certs, cert;
466   if (!hs->ssl->method->init_message(hs->ssl, cbb.get(), &body,
467                                      SSL3_MT_CERTIFICATE) ||
468       !CBB_add_u24_length_prefixed(&body, &certs)) {
469     return false;
470   }
471 
472   if (hs->credential != nullptr) {
473     assert(hs->credential->type == SSLCredentialType::kX509);
474     STACK_OF(CRYPTO_BUFFER) *chain = hs->credential->chain.get();
475     for (size_t i = 0; i < sk_CRYPTO_BUFFER_num(chain); i++) {
476       CRYPTO_BUFFER *buffer = sk_CRYPTO_BUFFER_value(chain, i);
477       if (!CBB_add_u24_length_prefixed(&certs, &cert) ||
478           !CBB_add_bytes(&cert, CRYPTO_BUFFER_data(buffer),
479                          CRYPTO_BUFFER_len(buffer))) {
480         return false;
481       }
482     }
483   }
484 
485   return ssl_add_message_cbb(hs->ssl, cbb.get());
486 }
487 
ssl_handshake_session(const SSL_HANDSHAKE * hs)488 const SSL_SESSION *ssl_handshake_session(const SSL_HANDSHAKE *hs) {
489   if (hs->new_session) {
490     return hs->new_session.get();
491   }
492   return hs->ssl->session.get();
493 }
494 
ssl_run_handshake(SSL_HANDSHAKE * hs,bool * out_early_return)495 int ssl_run_handshake(SSL_HANDSHAKE *hs, bool *out_early_return) {
496   SSL *const ssl = hs->ssl;
497   for (;;) {
498     // If a timeout during the handshake triggered a DTLS ACK or retransmit, we
499     // resolve that first. E.g., if |ssl_hs_private_key_operation| is slow, the
500     // ACK timer may fire.
501     if (hs->wait != ssl_hs_error && SSL_is_dtls(ssl)) {
502       int ret = ssl->method->flush(ssl);
503       if (ret <= 0) {
504         return ret;
505       }
506     }
507 
508     // Resolve the operation the handshake was waiting on. Each condition may
509     // halt the handshake by returning, or continue executing if the handshake
510     // may immediately proceed. Cases which halt the handshake can clear
511     // |hs->wait| to re-enter the state machine on the next iteration, or leave
512     // it set to keep the condition sticky.
513     switch (hs->wait) {
514       case ssl_hs_error:
515         ERR_restore_state(hs->error.get());
516         return -1;
517 
518       case ssl_hs_flush: {
519         int ret = ssl->method->flush(ssl);
520         if (ret <= 0) {
521           return ret;
522         }
523         break;
524       }
525 
526       case ssl_hs_read_server_hello:
527       case ssl_hs_read_message:
528       case ssl_hs_read_change_cipher_spec: {
529         if (SSL_is_quic(ssl)) {
530           // QUIC has no ChangeCipherSpec messages.
531           assert(hs->wait != ssl_hs_read_change_cipher_spec);
532           // The caller should call |SSL_provide_quic_data|. Clear |hs->wait| so
533           // the handshake can check if there is sufficient data next iteration.
534           ssl->s3->rwstate = SSL_ERROR_WANT_READ;
535           hs->wait = ssl_hs_ok;
536           return -1;
537         }
538 
539         uint8_t alert = SSL_AD_DECODE_ERROR;
540         size_t consumed = 0;
541         ssl_open_record_t ret;
542         if (hs->wait == ssl_hs_read_change_cipher_spec) {
543           ret = ssl_open_change_cipher_spec(ssl, &consumed, &alert,
544                                             ssl->s3->read_buffer.span());
545         } else {
546           ret = ssl_open_handshake(ssl, &consumed, &alert,
547                                    ssl->s3->read_buffer.span());
548         }
549         if (ret == ssl_open_record_error &&
550             hs->wait == ssl_hs_read_server_hello) {
551           uint32_t err = ERR_peek_error();
552           if (ERR_GET_LIB(err) == ERR_LIB_SSL &&
553               ERR_GET_REASON(err) == SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE) {
554             // Add a dedicated error code to the queue for a handshake_failure
555             // alert in response to ClientHello. This matches NSS's client
556             // behavior and gives a better error on a (probable) failure to
557             // negotiate initial parameters. Note: this error code comes after
558             // the original one.
559             //
560             // See https://crbug.com/446505.
561             OPENSSL_PUT_ERROR(SSL, SSL_R_HANDSHAKE_FAILURE_ON_CLIENT_HELLO);
562           }
563         }
564         bool retry;
565         int bio_ret = ssl_handle_open_record(ssl, &retry, ret, consumed, alert);
566         if (bio_ret <= 0) {
567           return bio_ret;
568         }
569         if (retry) {
570           continue;
571         }
572         ssl->s3->read_buffer.DiscardConsumed();
573         break;
574       }
575 
576       case ssl_hs_read_end_of_early_data: {
577         if (ssl->s3->hs->can_early_read) {
578           // While we are processing early data, the handshake returns early.
579           *out_early_return = true;
580           return 1;
581         }
582         hs->wait = ssl_hs_ok;
583         break;
584       }
585 
586       case ssl_hs_certificate_selection_pending:
587         ssl->s3->rwstate = SSL_ERROR_PENDING_CERTIFICATE;
588         hs->wait = ssl_hs_ok;
589         return -1;
590 
591       case ssl_hs_handoff:
592         ssl->s3->rwstate = SSL_ERROR_HANDOFF;
593         hs->wait = ssl_hs_ok;
594         return -1;
595 
596       case ssl_hs_handback: {
597         int ret = ssl->method->flush(ssl);
598         if (ret <= 0) {
599           return ret;
600         }
601         ssl->s3->rwstate = SSL_ERROR_HANDBACK;
602         hs->wait = ssl_hs_handback;
603         return -1;
604       }
605 
606         // The following cases are associated with callback APIs which expect to
607         // be called each time the state machine runs. Thus they set |hs->wait|
608         // to |ssl_hs_ok| so that, next time, we re-enter the state machine and
609         // call the callback again.
610       case ssl_hs_x509_lookup:
611         ssl->s3->rwstate = SSL_ERROR_WANT_X509_LOOKUP;
612         hs->wait = ssl_hs_ok;
613         return -1;
614       case ssl_hs_private_key_operation:
615         ssl->s3->rwstate = SSL_ERROR_WANT_PRIVATE_KEY_OPERATION;
616         hs->wait = ssl_hs_ok;
617         return -1;
618       case ssl_hs_pending_session:
619         ssl->s3->rwstate = SSL_ERROR_PENDING_SESSION;
620         hs->wait = ssl_hs_ok;
621         return -1;
622       case ssl_hs_pending_ticket:
623         ssl->s3->rwstate = SSL_ERROR_PENDING_TICKET;
624         hs->wait = ssl_hs_ok;
625         return -1;
626       case ssl_hs_certificate_verify:
627         ssl->s3->rwstate = SSL_ERROR_WANT_CERTIFICATE_VERIFY;
628         hs->wait = ssl_hs_ok;
629         return -1;
630 
631       case ssl_hs_early_data_rejected:
632         assert(ssl->s3->early_data_reason != ssl_early_data_unknown);
633         assert(!hs->can_early_write);
634         ssl->s3->rwstate = SSL_ERROR_EARLY_DATA_REJECTED;
635         return -1;
636 
637       case ssl_hs_early_return:
638         if (!ssl->server) {
639           // On ECH reject, the handshake should never complete.
640           assert(ssl->s3->ech_status != ssl_ech_rejected);
641         }
642         *out_early_return = true;
643         hs->wait = ssl_hs_ok;
644         return 1;
645 
646       case ssl_hs_hints_ready:
647         ssl->s3->rwstate = SSL_ERROR_HANDSHAKE_HINTS_READY;
648         return -1;
649 
650       case ssl_hs_ok:
651         break;
652     }
653 
654     // Run the state machine again.
655     hs->wait = ssl->do_handshake(hs);
656     if (hs->wait == ssl_hs_error) {
657       hs->error.reset(ERR_save_state());
658       return -1;
659     }
660     if (hs->wait == ssl_hs_ok) {
661       if (!ssl->server) {
662         // On ECH reject, the handshake should never complete.
663         assert(ssl->s3->ech_status != ssl_ech_rejected);
664       }
665       // The handshake has completed.
666       *out_early_return = false;
667       return 1;
668     }
669     // If the handshake returns |ssl_hs_flush|, implicitly finish the flight.
670     // This is a convenience so we do not need to manually insert this
671     // throughout the handshake.
672     if (hs->wait == ssl_hs_flush) {
673       ssl->method->finish_flight(ssl);
674     }
675 
676     // Loop to the beginning and resolve what was blocking the handshake.
677   }
678 }
679 
680 BSSL_NAMESPACE_END
681