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