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