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 scts_requested(false),
130 needs_psk_binder(false),
131 handshake_finalized(false),
132 accept_psk_mode(false),
133 cert_request(false),
134 certificate_status_expected(false),
135 ocsp_stapling_requested(false),
136 delegated_credential_requested(false),
137 should_ack_sni(false),
138 in_false_start(false),
139 in_early_data(false),
140 early_data_offered(false),
141 can_early_read(false),
142 can_early_write(false),
143 next_proto_neg_seen(false),
144 ticket_expected(false),
145 extended_master_secret(false),
146 pending_private_key_op(false),
147 grease_seeded(false),
148 handback(false),
149 cert_compression_negotiated(false),
150 apply_jdk11_workaround(false) {
151 assert(ssl);
152 }
153
~SSL_HANDSHAKE()154 SSL_HANDSHAKE::~SSL_HANDSHAKE() {
155 ssl->ctx->x509_method->hs_flush_cached_ca_names(this);
156 }
157
ResizeSecrets(size_t hash_len)158 void SSL_HANDSHAKE::ResizeSecrets(size_t hash_len) {
159 if (hash_len > SSL_MAX_MD_SIZE) {
160 abort();
161 }
162 hash_len_ = hash_len;
163 }
164
ssl_handshake_new(SSL * ssl)165 UniquePtr<SSL_HANDSHAKE> ssl_handshake_new(SSL *ssl) {
166 UniquePtr<SSL_HANDSHAKE> hs = MakeUnique<SSL_HANDSHAKE>(ssl);
167 if (!hs || !hs->transcript.Init()) {
168 return nullptr;
169 }
170 hs->config = ssl->config.get();
171 if (!hs->config) {
172 assert(hs->config);
173 return nullptr;
174 }
175 return hs;
176 }
177
ssl_check_message_type(SSL * ssl,const SSLMessage & msg,int type)178 bool ssl_check_message_type(SSL *ssl, const SSLMessage &msg, int type) {
179 if (msg.type != type) {
180 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
181 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
182 ERR_add_error_dataf("got type %d, wanted type %d", msg.type, type);
183 return false;
184 }
185
186 return true;
187 }
188
ssl_add_message_cbb(SSL * ssl,CBB * cbb)189 bool ssl_add_message_cbb(SSL *ssl, CBB *cbb) {
190 Array<uint8_t> msg;
191 if (!ssl->method->finish_message(ssl, cbb, &msg) ||
192 !ssl->method->add_message(ssl, std::move(msg))) {
193 return false;
194 }
195
196 return true;
197 }
198
ssl_max_handshake_message_len(const SSL * ssl)199 size_t ssl_max_handshake_message_len(const SSL *ssl) {
200 // kMaxMessageLen is the default maximum message size for handshakes which do
201 // not accept peer certificate chains.
202 static const size_t kMaxMessageLen = 16384;
203
204 if (SSL_in_init(ssl)) {
205 SSL_CONFIG *config = ssl->config.get(); // SSL_in_init() implies not NULL.
206 if ((!ssl->server || (config->verify_mode & SSL_VERIFY_PEER)) &&
207 kMaxMessageLen < ssl->max_cert_list) {
208 return ssl->max_cert_list;
209 }
210 return kMaxMessageLen;
211 }
212
213 if (ssl_protocol_version(ssl) < TLS1_3_VERSION) {
214 // In TLS 1.2 and below, the largest acceptable post-handshake message is
215 // a HelloRequest.
216 return 0;
217 }
218
219 if (ssl->server) {
220 // The largest acceptable post-handshake message for a server is a
221 // KeyUpdate. We will never initiate post-handshake auth.
222 return 1;
223 }
224
225 // Clients must accept NewSessionTicket, so allow the default size.
226 return kMaxMessageLen;
227 }
228
ssl_hash_message(SSL_HANDSHAKE * hs,const SSLMessage & msg)229 bool ssl_hash_message(SSL_HANDSHAKE *hs, const SSLMessage &msg) {
230 // V2ClientHello messages are pre-hashed.
231 if (msg.is_v2_hello) {
232 return true;
233 }
234
235 return hs->transcript.Update(msg.raw);
236 }
237
ssl_parse_extensions(const CBS * cbs,uint8_t * out_alert,Span<const SSL_EXTENSION_TYPE> ext_types,bool ignore_unknown)238 bool ssl_parse_extensions(const CBS *cbs, uint8_t *out_alert,
239 Span<const SSL_EXTENSION_TYPE> ext_types,
240 bool ignore_unknown) {
241 // Reset everything.
242 for (const SSL_EXTENSION_TYPE &ext_type : ext_types) {
243 *ext_type.out_present = false;
244 CBS_init(ext_type.out_data, nullptr, 0);
245 }
246
247 CBS copy = *cbs;
248 while (CBS_len(©) != 0) {
249 uint16_t type;
250 CBS data;
251 if (!CBS_get_u16(©, &type) ||
252 !CBS_get_u16_length_prefixed(©, &data)) {
253 OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
254 *out_alert = SSL_AD_DECODE_ERROR;
255 return false;
256 }
257
258 const SSL_EXTENSION_TYPE *found = nullptr;
259 for (const SSL_EXTENSION_TYPE &ext_type : ext_types) {
260 if (type == ext_type.type) {
261 found = &ext_type;
262 break;
263 }
264 }
265
266 if (found == nullptr) {
267 if (ignore_unknown) {
268 continue;
269 }
270 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
271 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
272 return false;
273 }
274
275 // Duplicate ext_types are forbidden.
276 if (*found->out_present) {
277 OPENSSL_PUT_ERROR(SSL, SSL_R_DUPLICATE_EXTENSION);
278 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
279 return false;
280 }
281
282 *found->out_present = 1;
283 *found->out_data = data;
284 }
285
286 return true;
287 }
288
ssl_verify_peer_cert(SSL_HANDSHAKE * hs)289 enum ssl_verify_result_t ssl_verify_peer_cert(SSL_HANDSHAKE *hs) {
290 SSL *const ssl = hs->ssl;
291 const SSL_SESSION *prev_session = ssl->s3->established_session.get();
292 if (prev_session != NULL) {
293 // If renegotiating, the server must not change the server certificate. See
294 // https://mitls.org/pages/attacks/3SHAKE. We never resume on renegotiation,
295 // so this check is sufficient to ensure the reported peer certificate never
296 // changes on renegotiation.
297 assert(!ssl->server);
298 if (sk_CRYPTO_BUFFER_num(prev_session->certs.get()) !=
299 sk_CRYPTO_BUFFER_num(hs->new_session->certs.get())) {
300 OPENSSL_PUT_ERROR(SSL, SSL_R_SERVER_CERT_CHANGED);
301 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
302 return ssl_verify_invalid;
303 }
304
305 for (size_t i = 0; i < sk_CRYPTO_BUFFER_num(hs->new_session->certs.get());
306 i++) {
307 const CRYPTO_BUFFER *old_cert =
308 sk_CRYPTO_BUFFER_value(prev_session->certs.get(), i);
309 const CRYPTO_BUFFER *new_cert =
310 sk_CRYPTO_BUFFER_value(hs->new_session->certs.get(), i);
311 if (CRYPTO_BUFFER_len(old_cert) != CRYPTO_BUFFER_len(new_cert) ||
312 OPENSSL_memcmp(CRYPTO_BUFFER_data(old_cert),
313 CRYPTO_BUFFER_data(new_cert),
314 CRYPTO_BUFFER_len(old_cert)) != 0) {
315 OPENSSL_PUT_ERROR(SSL, SSL_R_SERVER_CERT_CHANGED);
316 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
317 return ssl_verify_invalid;
318 }
319 }
320
321 // The certificate is identical, so we may skip re-verifying the
322 // certificate. Since we only authenticated the previous one, copy other
323 // authentication from the established session and ignore what was newly
324 // received.
325 hs->new_session->ocsp_response = UpRef(prev_session->ocsp_response);
326 hs->new_session->signed_cert_timestamp_list =
327 UpRef(prev_session->signed_cert_timestamp_list);
328 hs->new_session->verify_result = prev_session->verify_result;
329 return ssl_verify_ok;
330 }
331
332 uint8_t alert = SSL_AD_CERTIFICATE_UNKNOWN;
333 enum ssl_verify_result_t ret;
334 if (hs->config->custom_verify_callback != nullptr) {
335 ret = hs->config->custom_verify_callback(ssl, &alert);
336 switch (ret) {
337 case ssl_verify_ok:
338 hs->new_session->verify_result = X509_V_OK;
339 break;
340 case ssl_verify_invalid:
341 // If |SSL_VERIFY_NONE|, the error is non-fatal, but we keep the result.
342 if (hs->config->verify_mode == SSL_VERIFY_NONE) {
343 ERR_clear_error();
344 ret = ssl_verify_ok;
345 }
346 hs->new_session->verify_result = X509_V_ERR_APPLICATION_VERIFICATION;
347 break;
348 case ssl_verify_retry:
349 break;
350 }
351 } else {
352 ret = ssl->ctx->x509_method->session_verify_cert_chain(
353 hs->new_session.get(), hs, &alert)
354 ? ssl_verify_ok
355 : ssl_verify_invalid;
356 }
357
358 if (ret == ssl_verify_invalid) {
359 OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_VERIFY_FAILED);
360 ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
361 }
362
363 // Emulate OpenSSL's client OCSP callback. OpenSSL verifies certificates
364 // before it receives the OCSP, so it needs a second callback for OCSP.
365 if (ret == ssl_verify_ok && !ssl->server &&
366 hs->config->ocsp_stapling_enabled &&
367 ssl->ctx->legacy_ocsp_callback != nullptr) {
368 int cb_ret =
369 ssl->ctx->legacy_ocsp_callback(ssl, ssl->ctx->legacy_ocsp_callback_arg);
370 if (cb_ret <= 0) {
371 OPENSSL_PUT_ERROR(SSL, SSL_R_OCSP_CB_ERROR);
372 ssl_send_alert(ssl, SSL3_AL_FATAL,
373 cb_ret == 0 ? SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
374 : SSL_AD_INTERNAL_ERROR);
375 ret = ssl_verify_invalid;
376 }
377 }
378
379 return ret;
380 }
381
382 // Verifies a stored certificate when resuming a session. A few things are
383 // different from verify_peer_cert:
384 // 1. We can't be renegotiating if we're resuming a session.
385 // 2. The session is immutable, so we don't support verify_mode ==
386 // SSL_VERIFY_NONE
387 // 3. We don't call the OCSP callback.
388 // 4. We only support custom verify callbacks.
ssl_reverify_peer_cert(SSL_HANDSHAKE * hs,bool send_alert)389 enum ssl_verify_result_t ssl_reverify_peer_cert(SSL_HANDSHAKE *hs,
390 bool send_alert) {
391 SSL *const ssl = hs->ssl;
392 assert(ssl->s3->established_session == nullptr);
393 assert(hs->config->verify_mode != SSL_VERIFY_NONE);
394
395 uint8_t alert = SSL_AD_CERTIFICATE_UNKNOWN;
396 enum ssl_verify_result_t ret = ssl_verify_invalid;
397 if (hs->config->custom_verify_callback != nullptr) {
398 ret = hs->config->custom_verify_callback(ssl, &alert);
399 }
400
401 if (ret == ssl_verify_invalid) {
402 OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_VERIFY_FAILED);
403 if (send_alert) {
404 ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
405 }
406 }
407
408 return ret;
409 }
410
ssl_get_grease_value(SSL_HANDSHAKE * hs,enum ssl_grease_index_t index)411 uint16_t ssl_get_grease_value(SSL_HANDSHAKE *hs,
412 enum ssl_grease_index_t index) {
413 // Draw entropy for all GREASE values at once. This avoids calling
414 // |RAND_bytes| repeatedly and makes the values consistent within a
415 // connection. The latter is so the second ClientHello matches after
416 // HelloRetryRequest and so supported_groups and key_shares are consistent.
417 if (!hs->grease_seeded) {
418 RAND_bytes(hs->grease_seed, sizeof(hs->grease_seed));
419 hs->grease_seeded = true;
420 }
421
422 // This generates a random value of the form 0xωaωa, for all 0 ≤ ω < 16.
423 uint16_t ret = hs->grease_seed[index];
424 ret = (ret & 0xf0) | 0x0a;
425 ret |= ret << 8;
426 return ret;
427 }
428
ssl_get_finished(SSL_HANDSHAKE * hs)429 enum ssl_hs_wait_t ssl_get_finished(SSL_HANDSHAKE *hs) {
430 SSL *const ssl = hs->ssl;
431 SSLMessage msg;
432 if (!ssl->method->get_message(ssl, &msg)) {
433 return ssl_hs_read_message;
434 }
435
436 if (!ssl_check_message_type(ssl, msg, SSL3_MT_FINISHED)) {
437 return ssl_hs_error;
438 }
439
440 // Snapshot the finished hash before incorporating the new message.
441 uint8_t finished[EVP_MAX_MD_SIZE];
442 size_t finished_len;
443 if (!hs->transcript.GetFinishedMAC(finished, &finished_len,
444 ssl_handshake_session(hs), !ssl->server) ||
445 !ssl_hash_message(hs, msg)) {
446 return ssl_hs_error;
447 }
448
449 int finished_ok = CBS_mem_equal(&msg.body, finished, finished_len);
450 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
451 finished_ok = 1;
452 #endif
453 if (!finished_ok) {
454 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
455 OPENSSL_PUT_ERROR(SSL, SSL_R_DIGEST_CHECK_FAILED);
456 return ssl_hs_error;
457 }
458
459 // Copy the Finished so we can use it for renegotiation checks.
460 if (finished_len > sizeof(ssl->s3->previous_client_finished) ||
461 finished_len > sizeof(ssl->s3->previous_server_finished)) {
462 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
463 return ssl_hs_error;
464 }
465
466 if (ssl->server) {
467 OPENSSL_memcpy(ssl->s3->previous_client_finished, finished, finished_len);
468 ssl->s3->previous_client_finished_len = finished_len;
469 } else {
470 OPENSSL_memcpy(ssl->s3->previous_server_finished, finished, finished_len);
471 ssl->s3->previous_server_finished_len = finished_len;
472 }
473
474 // The Finished message should be the end of a flight.
475 if (ssl->method->has_unprocessed_handshake_data(ssl)) {
476 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
477 OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESS_HANDSHAKE_DATA);
478 return ssl_hs_error;
479 }
480
481 ssl->method->next_message(ssl);
482 return ssl_hs_ok;
483 }
484
ssl_send_finished(SSL_HANDSHAKE * hs)485 bool ssl_send_finished(SSL_HANDSHAKE *hs) {
486 SSL *const ssl = hs->ssl;
487 const SSL_SESSION *session = ssl_handshake_session(hs);
488
489 uint8_t finished[EVP_MAX_MD_SIZE];
490 size_t finished_len;
491 if (!hs->transcript.GetFinishedMAC(finished, &finished_len, session,
492 ssl->server)) {
493 return 0;
494 }
495
496 // Log the master secret, if logging is enabled.
497 if (!ssl_log_secret(
498 ssl, "CLIENT_RANDOM",
499 MakeConstSpan(session->master_key, session->master_key_length))) {
500 return 0;
501 }
502
503 // Copy the Finished so we can use it for renegotiation checks.
504 if (finished_len > sizeof(ssl->s3->previous_client_finished) ||
505 finished_len > sizeof(ssl->s3->previous_server_finished)) {
506 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
507 return 0;
508 }
509
510 if (ssl->server) {
511 OPENSSL_memcpy(ssl->s3->previous_server_finished, finished, finished_len);
512 ssl->s3->previous_server_finished_len = finished_len;
513 } else {
514 OPENSSL_memcpy(ssl->s3->previous_client_finished, finished, finished_len);
515 ssl->s3->previous_client_finished_len = finished_len;
516 }
517
518 ScopedCBB cbb;
519 CBB body;
520 if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_FINISHED) ||
521 !CBB_add_bytes(&body, finished, finished_len) ||
522 !ssl_add_message_cbb(ssl, cbb.get())) {
523 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
524 return 0;
525 }
526
527 return 1;
528 }
529
ssl_output_cert_chain(SSL_HANDSHAKE * hs)530 bool ssl_output_cert_chain(SSL_HANDSHAKE *hs) {
531 ScopedCBB cbb;
532 CBB body;
533 if (!hs->ssl->method->init_message(hs->ssl, cbb.get(), &body,
534 SSL3_MT_CERTIFICATE) ||
535 !ssl_add_cert_chain(hs, &body) ||
536 !ssl_add_message_cbb(hs->ssl, cbb.get())) {
537 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
538 return false;
539 }
540
541 return true;
542 }
543
ssl_handshake_session(const SSL_HANDSHAKE * hs)544 const SSL_SESSION *ssl_handshake_session(const SSL_HANDSHAKE *hs) {
545 if (hs->new_session) {
546 return hs->new_session.get();
547 }
548 return hs->ssl->session.get();
549 }
550
ssl_run_handshake(SSL_HANDSHAKE * hs,bool * out_early_return)551 int ssl_run_handshake(SSL_HANDSHAKE *hs, bool *out_early_return) {
552 SSL *const ssl = hs->ssl;
553 for (;;) {
554 // Resolve the operation the handshake was waiting on.
555 switch (hs->wait) {
556 case ssl_hs_error:
557 ERR_restore_state(hs->error.get());
558 return -1;
559
560 case ssl_hs_flush: {
561 int ret = ssl->method->flush_flight(ssl);
562 if (ret <= 0) {
563 return ret;
564 }
565 break;
566 }
567
568 case ssl_hs_read_server_hello:
569 case ssl_hs_read_message:
570 case ssl_hs_read_change_cipher_spec: {
571 if (ssl->quic_method) {
572 hs->wait = ssl_hs_ok;
573 // The change cipher spec is omitted in QUIC.
574 if (hs->wait != ssl_hs_read_change_cipher_spec) {
575 ssl->s3->rwstate = SSL_ERROR_WANT_READ;
576 return -1;
577 }
578 break;
579 }
580
581 uint8_t alert = SSL_AD_DECODE_ERROR;
582 size_t consumed = 0;
583 ssl_open_record_t ret;
584 if (hs->wait == ssl_hs_read_change_cipher_spec) {
585 ret = ssl_open_change_cipher_spec(ssl, &consumed, &alert,
586 ssl->s3->read_buffer.span());
587 } else {
588 ret = ssl_open_handshake(ssl, &consumed, &alert,
589 ssl->s3->read_buffer.span());
590 }
591 if (ret == ssl_open_record_error &&
592 hs->wait == ssl_hs_read_server_hello) {
593 uint32_t err = ERR_peek_error();
594 if (ERR_GET_LIB(err) == ERR_LIB_SSL &&
595 ERR_GET_REASON(err) == SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE) {
596 // Add a dedicated error code to the queue for a handshake_failure
597 // alert in response to ClientHello. This matches NSS's client
598 // behavior and gives a better error on a (probable) failure to
599 // negotiate initial parameters. Note: this error code comes after
600 // the original one.
601 //
602 // See https://crbug.com/446505.
603 OPENSSL_PUT_ERROR(SSL, SSL_R_HANDSHAKE_FAILURE_ON_CLIENT_HELLO);
604 }
605 }
606 bool retry;
607 int bio_ret = ssl_handle_open_record(ssl, &retry, ret, consumed, alert);
608 if (bio_ret <= 0) {
609 return bio_ret;
610 }
611 if (retry) {
612 continue;
613 }
614 ssl->s3->read_buffer.DiscardConsumed();
615 break;
616 }
617
618 case ssl_hs_read_end_of_early_data: {
619 if (ssl->s3->hs->can_early_read) {
620 // While we are processing early data, the handshake returns early.
621 *out_early_return = true;
622 return 1;
623 }
624 hs->wait = ssl_hs_ok;
625 break;
626 }
627
628 case ssl_hs_certificate_selection_pending:
629 ssl->s3->rwstate = SSL_ERROR_PENDING_CERTIFICATE;
630 hs->wait = ssl_hs_ok;
631 return -1;
632
633 case ssl_hs_handoff:
634 ssl->s3->rwstate = SSL_ERROR_HANDOFF;
635 hs->wait = ssl_hs_ok;
636 return -1;
637
638 case ssl_hs_handback: {
639 int ret = ssl->method->flush_flight(ssl);
640 if (ret <= 0) {
641 return ret;
642 }
643 ssl->s3->rwstate = SSL_ERROR_HANDBACK;
644 hs->wait = ssl_hs_handback;
645 return -1;
646 }
647
648 case ssl_hs_x509_lookup:
649 ssl->s3->rwstate = SSL_ERROR_WANT_X509_LOOKUP;
650 hs->wait = ssl_hs_ok;
651 return -1;
652
653 case ssl_hs_channel_id_lookup:
654 ssl->s3->rwstate = SSL_ERROR_WANT_CHANNEL_ID_LOOKUP;
655 hs->wait = ssl_hs_ok;
656 return -1;
657
658 case ssl_hs_private_key_operation:
659 ssl->s3->rwstate = SSL_ERROR_WANT_PRIVATE_KEY_OPERATION;
660 hs->wait = ssl_hs_ok;
661 return -1;
662
663 case ssl_hs_pending_session:
664 ssl->s3->rwstate = SSL_ERROR_PENDING_SESSION;
665 hs->wait = ssl_hs_ok;
666 return -1;
667
668 case ssl_hs_pending_ticket:
669 ssl->s3->rwstate = SSL_ERROR_PENDING_TICKET;
670 hs->wait = ssl_hs_ok;
671 return -1;
672
673 case ssl_hs_certificate_verify:
674 ssl->s3->rwstate = SSL_ERROR_WANT_CERTIFICATE_VERIFY;
675 hs->wait = ssl_hs_ok;
676 return -1;
677
678 case ssl_hs_early_data_rejected:
679 assert(ssl->s3->early_data_reason != ssl_early_data_unknown);
680 assert(!hs->can_early_write);
681 ssl->s3->rwstate = SSL_ERROR_EARLY_DATA_REJECTED;
682 return -1;
683
684 case ssl_hs_early_return:
685 *out_early_return = true;
686 hs->wait = ssl_hs_ok;
687 return 1;
688
689 case ssl_hs_ok:
690 break;
691 }
692
693 // Run the state machine again.
694 hs->wait = ssl->do_handshake(hs);
695 if (hs->wait == ssl_hs_error) {
696 hs->error.reset(ERR_save_state());
697 return -1;
698 }
699 if (hs->wait == ssl_hs_ok) {
700 // The handshake has completed.
701 *out_early_return = false;
702 return 1;
703 }
704
705 // Otherwise, loop to the beginning and resolve what was blocking the
706 // handshake.
707 }
708 }
709
710 BSSL_NAMESPACE_END
711