1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2002 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com). */
108 /* ====================================================================
109  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
110  * ECC cipher suite support in OpenSSL originally developed by
111  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. */
112 
113 #include <openssl/ssl.h>
114 
115 #include <assert.h>
116 
117 #include <utility>
118 
119 #include <openssl/rand.h>
120 
121 #include "../crypto/internal.h"
122 #include "internal.h"
123 
124 
125 BSSL_NAMESPACE_BEGIN
126 
SSL_HANDSHAKE(SSL * ssl_arg)127 SSL_HANDSHAKE::SSL_HANDSHAKE(SSL *ssl_arg)
128     : ssl(ssl_arg),
129       ech_present(false),
130       ech_is_inner_present(false),
131       scts_requested(false),
132       needs_psk_binder(false),
133       handshake_finalized(false),
134       accept_psk_mode(false),
135       cert_request(false),
136       certificate_status_expected(false),
137       ocsp_stapling_requested(false),
138       delegated_credential_requested(false),
139       should_ack_sni(false),
140       in_false_start(false),
141       in_early_data(false),
142       early_data_offered(false),
143       can_early_read(false),
144       can_early_write(false),
145       next_proto_neg_seen(false),
146       ticket_expected(false),
147       extended_master_secret(false),
148       pending_private_key_op(false),
149       grease_seeded(false),
150       handback(false),
151       cert_compression_negotiated(false),
152       apply_jdk11_workaround(false) {
153   assert(ssl);
154 }
155 
~SSL_HANDSHAKE()156 SSL_HANDSHAKE::~SSL_HANDSHAKE() {
157   ssl->ctx->x509_method->hs_flush_cached_ca_names(this);
158 }
159 
ResizeSecrets(size_t hash_len)160 void SSL_HANDSHAKE::ResizeSecrets(size_t hash_len) {
161   if (hash_len > SSL_MAX_MD_SIZE) {
162     abort();
163   }
164   hash_len_ = hash_len;
165 }
166 
ssl_handshake_new(SSL * ssl)167 UniquePtr<SSL_HANDSHAKE> ssl_handshake_new(SSL *ssl) {
168   UniquePtr<SSL_HANDSHAKE> hs = MakeUnique<SSL_HANDSHAKE>(ssl);
169   if (!hs || !hs->transcript.Init()) {
170     return nullptr;
171   }
172   hs->config = ssl->config.get();
173   if (!hs->config) {
174     assert(hs->config);
175     return nullptr;
176   }
177   return hs;
178 }
179 
ssl_check_message_type(SSL * ssl,const SSLMessage & msg,int type)180 bool ssl_check_message_type(SSL *ssl, const SSLMessage &msg, int type) {
181   if (msg.type != type) {
182     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
183     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
184     ERR_add_error_dataf("got type %d, wanted type %d", msg.type, type);
185     return false;
186   }
187 
188   return true;
189 }
190 
ssl_add_message_cbb(SSL * ssl,CBB * cbb)191 bool ssl_add_message_cbb(SSL *ssl, CBB *cbb) {
192   Array<uint8_t> msg;
193   if (!ssl->method->finish_message(ssl, cbb, &msg) ||
194       !ssl->method->add_message(ssl, std::move(msg))) {
195     return false;
196   }
197 
198   return true;
199 }
200 
ssl_max_handshake_message_len(const SSL * ssl)201 size_t ssl_max_handshake_message_len(const SSL *ssl) {
202   // kMaxMessageLen is the default maximum message size for handshakes which do
203   // not accept peer certificate chains.
204   static const size_t kMaxMessageLen = 16384;
205 
206   if (SSL_in_init(ssl)) {
207     SSL_CONFIG *config = ssl->config.get();  // SSL_in_init() implies not NULL.
208     if ((!ssl->server || (config->verify_mode & SSL_VERIFY_PEER)) &&
209         kMaxMessageLen < ssl->max_cert_list) {
210       return ssl->max_cert_list;
211     }
212     return kMaxMessageLen;
213   }
214 
215   if (ssl_protocol_version(ssl) < TLS1_3_VERSION) {
216     // In TLS 1.2 and below, the largest acceptable post-handshake message is
217     // a HelloRequest.
218     return 0;
219   }
220 
221   if (ssl->server) {
222     // The largest acceptable post-handshake message for a server is a
223     // KeyUpdate. We will never initiate post-handshake auth.
224     return 1;
225   }
226 
227   // Clients must accept NewSessionTicket, so allow the default size.
228   return kMaxMessageLen;
229 }
230 
ssl_hash_message(SSL_HANDSHAKE * hs,const SSLMessage & msg)231 bool ssl_hash_message(SSL_HANDSHAKE *hs, const SSLMessage &msg) {
232   // V2ClientHello messages are pre-hashed.
233   if (msg.is_v2_hello) {
234     return true;
235   }
236 
237   return hs->transcript.Update(msg.raw);
238 }
239 
ssl_parse_extensions(const CBS * cbs,uint8_t * out_alert,Span<const SSL_EXTENSION_TYPE> ext_types,bool ignore_unknown)240 bool ssl_parse_extensions(const CBS *cbs, uint8_t *out_alert,
241                           Span<const SSL_EXTENSION_TYPE> ext_types,
242                           bool ignore_unknown) {
243   // Reset everything.
244   for (const SSL_EXTENSION_TYPE &ext_type : ext_types) {
245     *ext_type.out_present = false;
246     CBS_init(ext_type.out_data, nullptr, 0);
247   }
248 
249   CBS copy = *cbs;
250   while (CBS_len(&copy) != 0) {
251     uint16_t type;
252     CBS data;
253     if (!CBS_get_u16(&copy, &type) ||
254         !CBS_get_u16_length_prefixed(&copy, &data)) {
255       OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
256       *out_alert = SSL_AD_DECODE_ERROR;
257       return false;
258     }
259 
260     const SSL_EXTENSION_TYPE *found = nullptr;
261     for (const SSL_EXTENSION_TYPE &ext_type : ext_types) {
262       if (type == ext_type.type) {
263         found = &ext_type;
264         break;
265       }
266     }
267 
268     if (found == nullptr) {
269       if (ignore_unknown) {
270         continue;
271       }
272       OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
273       *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
274       return false;
275     }
276 
277     // Duplicate ext_types are forbidden.
278     if (*found->out_present) {
279       OPENSSL_PUT_ERROR(SSL, SSL_R_DUPLICATE_EXTENSION);
280       *out_alert = SSL_AD_ILLEGAL_PARAMETER;
281       return false;
282     }
283 
284     *found->out_present = 1;
285     *found->out_data = data;
286   }
287 
288   return true;
289 }
290 
ssl_verify_peer_cert(SSL_HANDSHAKE * hs)291 enum ssl_verify_result_t ssl_verify_peer_cert(SSL_HANDSHAKE *hs) {
292   SSL *const ssl = hs->ssl;
293   const SSL_SESSION *prev_session = ssl->s3->established_session.get();
294   if (prev_session != NULL) {
295     // If renegotiating, the server must not change the server certificate. See
296     // https://mitls.org/pages/attacks/3SHAKE. We never resume on renegotiation,
297     // so this check is sufficient to ensure the reported peer certificate never
298     // changes on renegotiation.
299     assert(!ssl->server);
300     if (sk_CRYPTO_BUFFER_num(prev_session->certs.get()) !=
301         sk_CRYPTO_BUFFER_num(hs->new_session->certs.get())) {
302       OPENSSL_PUT_ERROR(SSL, SSL_R_SERVER_CERT_CHANGED);
303       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
304       return ssl_verify_invalid;
305     }
306 
307     for (size_t i = 0; i < sk_CRYPTO_BUFFER_num(hs->new_session->certs.get());
308          i++) {
309       const CRYPTO_BUFFER *old_cert =
310           sk_CRYPTO_BUFFER_value(prev_session->certs.get(), i);
311       const CRYPTO_BUFFER *new_cert =
312           sk_CRYPTO_BUFFER_value(hs->new_session->certs.get(), i);
313       if (CRYPTO_BUFFER_len(old_cert) != CRYPTO_BUFFER_len(new_cert) ||
314           OPENSSL_memcmp(CRYPTO_BUFFER_data(old_cert),
315                          CRYPTO_BUFFER_data(new_cert),
316                          CRYPTO_BUFFER_len(old_cert)) != 0) {
317         OPENSSL_PUT_ERROR(SSL, SSL_R_SERVER_CERT_CHANGED);
318         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
319         return ssl_verify_invalid;
320       }
321     }
322 
323     // The certificate is identical, so we may skip re-verifying the
324     // certificate. Since we only authenticated the previous one, copy other
325     // authentication from the established session and ignore what was newly
326     // received.
327     hs->new_session->ocsp_response = UpRef(prev_session->ocsp_response);
328     hs->new_session->signed_cert_timestamp_list =
329         UpRef(prev_session->signed_cert_timestamp_list);
330     hs->new_session->verify_result = prev_session->verify_result;
331     return ssl_verify_ok;
332   }
333 
334   uint8_t alert = SSL_AD_CERTIFICATE_UNKNOWN;
335   enum ssl_verify_result_t ret;
336   if (hs->config->custom_verify_callback != nullptr) {
337     ret = hs->config->custom_verify_callback(ssl, &alert);
338     switch (ret) {
339       case ssl_verify_ok:
340         hs->new_session->verify_result = X509_V_OK;
341         break;
342       case ssl_verify_invalid:
343         // If |SSL_VERIFY_NONE|, the error is non-fatal, but we keep the result.
344         if (hs->config->verify_mode == SSL_VERIFY_NONE) {
345           ERR_clear_error();
346           ret = ssl_verify_ok;
347         }
348         hs->new_session->verify_result = X509_V_ERR_APPLICATION_VERIFICATION;
349         break;
350       case ssl_verify_retry:
351         break;
352     }
353   } else {
354     ret = ssl->ctx->x509_method->session_verify_cert_chain(
355               hs->new_session.get(), hs, &alert)
356               ? ssl_verify_ok
357               : ssl_verify_invalid;
358   }
359 
360   if (ret == ssl_verify_invalid) {
361     OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_VERIFY_FAILED);
362     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
363   }
364 
365   // Emulate OpenSSL's client OCSP callback. OpenSSL verifies certificates
366   // before it receives the OCSP, so it needs a second callback for OCSP.
367   if (ret == ssl_verify_ok && !ssl->server &&
368       hs->config->ocsp_stapling_enabled &&
369       ssl->ctx->legacy_ocsp_callback != nullptr) {
370     int cb_ret =
371         ssl->ctx->legacy_ocsp_callback(ssl, ssl->ctx->legacy_ocsp_callback_arg);
372     if (cb_ret <= 0) {
373       OPENSSL_PUT_ERROR(SSL, SSL_R_OCSP_CB_ERROR);
374       ssl_send_alert(ssl, SSL3_AL_FATAL,
375                      cb_ret == 0 ? SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
376                                  : SSL_AD_INTERNAL_ERROR);
377       ret = ssl_verify_invalid;
378     }
379   }
380 
381   return ret;
382 }
383 
384 // Verifies a stored certificate when resuming a session. A few things are
385 // different from verify_peer_cert:
386 // 1. We can't be renegotiating if we're resuming a session.
387 // 2. The session is immutable, so we don't support verify_mode ==
388 // SSL_VERIFY_NONE
389 // 3. We don't call the OCSP callback.
390 // 4. We only support custom verify callbacks.
ssl_reverify_peer_cert(SSL_HANDSHAKE * hs,bool send_alert)391 enum ssl_verify_result_t ssl_reverify_peer_cert(SSL_HANDSHAKE *hs,
392                                                 bool send_alert) {
393   SSL *const ssl = hs->ssl;
394   assert(ssl->s3->established_session == nullptr);
395   assert(hs->config->verify_mode != SSL_VERIFY_NONE);
396 
397   uint8_t alert = SSL_AD_CERTIFICATE_UNKNOWN;
398   enum ssl_verify_result_t ret = ssl_verify_invalid;
399   if (hs->config->custom_verify_callback != nullptr) {
400     ret = hs->config->custom_verify_callback(ssl, &alert);
401   }
402 
403   if (ret == ssl_verify_invalid) {
404     OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_VERIFY_FAILED);
405     if (send_alert) {
406       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
407     }
408   }
409 
410   return ret;
411 }
412 
ssl_get_grease_value(SSL_HANDSHAKE * hs,enum ssl_grease_index_t index)413 uint16_t ssl_get_grease_value(SSL_HANDSHAKE *hs,
414                               enum ssl_grease_index_t index) {
415   // Draw entropy for all GREASE values at once. This avoids calling
416   // |RAND_bytes| repeatedly and makes the values consistent within a
417   // connection. The latter is so the second ClientHello matches after
418   // HelloRetryRequest and so supported_groups and key_shares are consistent.
419   if (!hs->grease_seeded) {
420     RAND_bytes(hs->grease_seed, sizeof(hs->grease_seed));
421     hs->grease_seeded = true;
422   }
423 
424   // This generates a random value of the form 0xωaωa, for all 0 ≤ ω < 16.
425   uint16_t ret = hs->grease_seed[index];
426   ret = (ret & 0xf0) | 0x0a;
427   ret |= ret << 8;
428   return ret;
429 }
430 
ssl_get_finished(SSL_HANDSHAKE * hs)431 enum ssl_hs_wait_t ssl_get_finished(SSL_HANDSHAKE *hs) {
432   SSL *const ssl = hs->ssl;
433   SSLMessage msg;
434   if (!ssl->method->get_message(ssl, &msg)) {
435     return ssl_hs_read_message;
436   }
437 
438   if (!ssl_check_message_type(ssl, msg, SSL3_MT_FINISHED)) {
439     return ssl_hs_error;
440   }
441 
442   // Snapshot the finished hash before incorporating the new message.
443   uint8_t finished[EVP_MAX_MD_SIZE];
444   size_t finished_len;
445   if (!hs->transcript.GetFinishedMAC(finished, &finished_len,
446                                      ssl_handshake_session(hs), !ssl->server) ||
447       !ssl_hash_message(hs, msg)) {
448     return ssl_hs_error;
449   }
450 
451   int finished_ok = CBS_mem_equal(&msg.body, finished, finished_len);
452 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
453   finished_ok = 1;
454 #endif
455   if (!finished_ok) {
456     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
457     OPENSSL_PUT_ERROR(SSL, SSL_R_DIGEST_CHECK_FAILED);
458     return ssl_hs_error;
459   }
460 
461   // Copy the Finished so we can use it for renegotiation checks.
462   if (finished_len > sizeof(ssl->s3->previous_client_finished) ||
463       finished_len > sizeof(ssl->s3->previous_server_finished)) {
464     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
465     return ssl_hs_error;
466   }
467 
468   if (ssl->server) {
469     OPENSSL_memcpy(ssl->s3->previous_client_finished, finished, finished_len);
470     ssl->s3->previous_client_finished_len = finished_len;
471   } else {
472     OPENSSL_memcpy(ssl->s3->previous_server_finished, finished, finished_len);
473     ssl->s3->previous_server_finished_len = finished_len;
474   }
475 
476   // The Finished message should be the end of a flight.
477   if (ssl->method->has_unprocessed_handshake_data(ssl)) {
478     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
479     OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESS_HANDSHAKE_DATA);
480     return ssl_hs_error;
481   }
482 
483   ssl->method->next_message(ssl);
484   return ssl_hs_ok;
485 }
486 
ssl_send_finished(SSL_HANDSHAKE * hs)487 bool ssl_send_finished(SSL_HANDSHAKE *hs) {
488   SSL *const ssl = hs->ssl;
489   const SSL_SESSION *session = ssl_handshake_session(hs);
490 
491   uint8_t finished[EVP_MAX_MD_SIZE];
492   size_t finished_len;
493   if (!hs->transcript.GetFinishedMAC(finished, &finished_len, session,
494                                      ssl->server)) {
495     return 0;
496   }
497 
498   // Log the master secret, if logging is enabled.
499   if (!ssl_log_secret(ssl, "CLIENT_RANDOM",
500                       MakeConstSpan(session->secret, session->secret_length))) {
501     return 0;
502   }
503 
504   // Copy the Finished so we can use it for renegotiation checks.
505   if (finished_len > sizeof(ssl->s3->previous_client_finished) ||
506       finished_len > sizeof(ssl->s3->previous_server_finished)) {
507     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
508     return 0;
509   }
510 
511   if (ssl->server) {
512     OPENSSL_memcpy(ssl->s3->previous_server_finished, finished, finished_len);
513     ssl->s3->previous_server_finished_len = finished_len;
514   } else {
515     OPENSSL_memcpy(ssl->s3->previous_client_finished, finished, finished_len);
516     ssl->s3->previous_client_finished_len = finished_len;
517   }
518 
519   ScopedCBB cbb;
520   CBB body;
521   if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_FINISHED) ||
522       !CBB_add_bytes(&body, finished, finished_len) ||
523       !ssl_add_message_cbb(ssl, cbb.get())) {
524     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
525     return 0;
526   }
527 
528   return 1;
529 }
530 
ssl_output_cert_chain(SSL_HANDSHAKE * hs)531 bool ssl_output_cert_chain(SSL_HANDSHAKE *hs) {
532   ScopedCBB cbb;
533   CBB body;
534   if (!hs->ssl->method->init_message(hs->ssl, cbb.get(), &body,
535                                      SSL3_MT_CERTIFICATE) ||
536       !ssl_add_cert_chain(hs, &body) ||
537       !ssl_add_message_cbb(hs->ssl, cbb.get())) {
538     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
539     return false;
540   }
541 
542   return true;
543 }
544 
ssl_handshake_session(const SSL_HANDSHAKE * hs)545 const SSL_SESSION *ssl_handshake_session(const SSL_HANDSHAKE *hs) {
546   if (hs->new_session) {
547     return hs->new_session.get();
548   }
549   return hs->ssl->session.get();
550 }
551 
ssl_run_handshake(SSL_HANDSHAKE * hs,bool * out_early_return)552 int ssl_run_handshake(SSL_HANDSHAKE *hs, bool *out_early_return) {
553   SSL *const ssl = hs->ssl;
554   for (;;) {
555     // Resolve the operation the handshake was waiting on.
556     switch (hs->wait) {
557       case ssl_hs_error:
558         ERR_restore_state(hs->error.get());
559         return -1;
560 
561       case ssl_hs_flush: {
562         int ret = ssl->method->flush_flight(ssl);
563         if (ret <= 0) {
564           return ret;
565         }
566         break;
567       }
568 
569       case ssl_hs_read_server_hello:
570       case ssl_hs_read_message:
571       case ssl_hs_read_change_cipher_spec: {
572         if (ssl->quic_method) {
573           hs->wait = ssl_hs_ok;
574           // The change cipher spec is omitted in QUIC.
575           if (hs->wait != ssl_hs_read_change_cipher_spec) {
576             ssl->s3->rwstate = SSL_ERROR_WANT_READ;
577             return -1;
578           }
579           break;
580         }
581 
582         uint8_t alert = SSL_AD_DECODE_ERROR;
583         size_t consumed = 0;
584         ssl_open_record_t ret;
585         if (hs->wait == ssl_hs_read_change_cipher_spec) {
586           ret = ssl_open_change_cipher_spec(ssl, &consumed, &alert,
587                                             ssl->s3->read_buffer.span());
588         } else {
589           ret = ssl_open_handshake(ssl, &consumed, &alert,
590                                    ssl->s3->read_buffer.span());
591         }
592         if (ret == ssl_open_record_error &&
593             hs->wait == ssl_hs_read_server_hello) {
594           uint32_t err = ERR_peek_error();
595           if (ERR_GET_LIB(err) == ERR_LIB_SSL &&
596               ERR_GET_REASON(err) == SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE) {
597             // Add a dedicated error code to the queue for a handshake_failure
598             // alert in response to ClientHello. This matches NSS's client
599             // behavior and gives a better error on a (probable) failure to
600             // negotiate initial parameters. Note: this error code comes after
601             // the original one.
602             //
603             // See https://crbug.com/446505.
604             OPENSSL_PUT_ERROR(SSL, SSL_R_HANDSHAKE_FAILURE_ON_CLIENT_HELLO);
605           }
606         }
607         bool retry;
608         int bio_ret = ssl_handle_open_record(ssl, &retry, ret, consumed, alert);
609         if (bio_ret <= 0) {
610           return bio_ret;
611         }
612         if (retry) {
613           continue;
614         }
615         ssl->s3->read_buffer.DiscardConsumed();
616         break;
617       }
618 
619       case ssl_hs_read_end_of_early_data: {
620         if (ssl->s3->hs->can_early_read) {
621           // While we are processing early data, the handshake returns early.
622           *out_early_return = true;
623           return 1;
624         }
625         hs->wait = ssl_hs_ok;
626         break;
627       }
628 
629       case ssl_hs_certificate_selection_pending:
630         ssl->s3->rwstate = SSL_ERROR_PENDING_CERTIFICATE;
631         hs->wait = ssl_hs_ok;
632         return -1;
633 
634       case ssl_hs_handoff:
635         ssl->s3->rwstate = SSL_ERROR_HANDOFF;
636         hs->wait = ssl_hs_ok;
637         return -1;
638 
639       case ssl_hs_handback: {
640         int ret = ssl->method->flush_flight(ssl);
641         if (ret <= 0) {
642           return ret;
643         }
644         ssl->s3->rwstate = SSL_ERROR_HANDBACK;
645         hs->wait = ssl_hs_handback;
646         return -1;
647       }
648 
649       case ssl_hs_x509_lookup:
650         ssl->s3->rwstate = SSL_ERROR_WANT_X509_LOOKUP;
651         hs->wait = ssl_hs_ok;
652         return -1;
653 
654       case ssl_hs_channel_id_lookup:
655         ssl->s3->rwstate = SSL_ERROR_WANT_CHANNEL_ID_LOOKUP;
656         hs->wait = ssl_hs_ok;
657         return -1;
658 
659       case ssl_hs_private_key_operation:
660         ssl->s3->rwstate = SSL_ERROR_WANT_PRIVATE_KEY_OPERATION;
661         hs->wait = ssl_hs_ok;
662         return -1;
663 
664       case ssl_hs_pending_session:
665         ssl->s3->rwstate = SSL_ERROR_PENDING_SESSION;
666         hs->wait = ssl_hs_ok;
667         return -1;
668 
669       case ssl_hs_pending_ticket:
670         ssl->s3->rwstate = SSL_ERROR_PENDING_TICKET;
671         hs->wait = ssl_hs_ok;
672         return -1;
673 
674       case ssl_hs_certificate_verify:
675         ssl->s3->rwstate = SSL_ERROR_WANT_CERTIFICATE_VERIFY;
676         hs->wait = ssl_hs_ok;
677         return -1;
678 
679       case ssl_hs_early_data_rejected:
680         assert(ssl->s3->early_data_reason != ssl_early_data_unknown);
681         assert(!hs->can_early_write);
682         ssl->s3->rwstate = SSL_ERROR_EARLY_DATA_REJECTED;
683         return -1;
684 
685       case ssl_hs_early_return:
686         *out_early_return = true;
687         hs->wait = ssl_hs_ok;
688         return 1;
689 
690       case ssl_hs_ok:
691         break;
692     }
693 
694     // Run the state machine again.
695     hs->wait = ssl->do_handshake(hs);
696     if (hs->wait == ssl_hs_error) {
697       hs->error.reset(ERR_save_state());
698       return -1;
699     }
700     if (hs->wait == ssl_hs_ok) {
701       // The handshake has completed.
702       *out_early_return = false;
703       return 1;
704     }
705 
706     // Otherwise, loop to the beginning and resolve what was blocking the
707     // handshake.
708   }
709 }
710 
711 BSSL_NAMESPACE_END
712