1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
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.
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).
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.
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
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)"
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
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.]
57 /* ====================================================================
58 * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
64 * 1. Redistributions of source code must retain the above copyright
65 * notice, this list of conditions and the following disclaimer.
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
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/)"
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.
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.
86 * 6. Redistributions of any form whatsoever must retain the following
88 * "This product includes software developed by the OpenSSL Project
89 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
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 * ====================================================================
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).
110 /* ====================================================================
111 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113 * Portions of the attached software ("Contribution") are developed by
114 * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
116 * The Contribution is licensed pursuant to the OpenSSL open source
117 * license provided above.
119 * ECC cipher suite support in OpenSSL originally written by
120 * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
123 /* ====================================================================
124 * Copyright 2005 Nokia. All rights reserved.
126 * The portions of the attached software ("Contribution") is developed by
127 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
130 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
131 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
132 * support (see RFC 4279) to OpenSSL.
134 * No patent licenses or other rights except those expressly stated in
135 * the OpenSSL open source license shall be deemed granted or received
136 * expressly, by implication, estoppel, or otherwise.
138 * No assurances are provided by Nokia that the Contribution does not
139 * infringe the patent or other intellectual property rights of any third
140 * party or that the license provides you with all the necessary rights
141 * to make use of the Contribution.
143 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
144 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
145 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
146 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
150 #include <openssl/ssl.h>
158 #include <openssl/aead.h>
159 #include <openssl/bn.h>
160 #include <openssl/buf.h>
161 #include <openssl/bytestring.h>
162 #include <openssl/ec_key.h>
163 #include <openssl/ecdsa.h>
164 #include <openssl/err.h>
165 #include <openssl/evp.h>
166 #include <openssl/md5.h>
167 #include <openssl/mem.h>
168 #include <openssl/rand.h>
170 #include "../crypto/internal.h"
171 #include "internal.h"
176 enum ssl_client_hs_state_t {
177 state_start_connect = 0,
178 state_enter_early_data,
179 state_read_hello_verify_request,
180 state_read_server_hello,
182 state_read_server_certificate,
183 state_read_certificate_status,
184 state_verify_server_certificate,
185 state_read_server_key_exchange,
186 state_read_certificate_request,
187 state_read_server_hello_done,
188 state_send_client_certificate,
189 state_send_client_key_exchange,
190 state_send_client_certificate_verify,
191 state_send_client_finished,
193 state_read_session_ticket,
194 state_process_change_cipher_spec,
195 state_read_server_finished,
196 state_finish_client_handshake,
200 // ssl_get_client_disabled sets |*out_mask_a| and |*out_mask_k| to masks of
201 // disabled algorithms.
202 static void ssl_get_client_disabled(SSL *ssl, uint32_t *out_mask_a,
203 uint32_t *out_mask_k) {
207 // PSK requires a client callback.
208 if (ssl->psk_client_callback == NULL) {
209 *out_mask_a |= SSL_aPSK;
210 *out_mask_k |= SSL_kPSK;
214 static int ssl_write_client_cipher_list(SSL_HANDSHAKE *hs, CBB *out) {
215 SSL *const ssl = hs->ssl;
216 uint32_t mask_a, mask_k;
217 ssl_get_client_disabled(ssl, &mask_a, &mask_k);
220 if (!CBB_add_u16_length_prefixed(out, &child)) {
224 // Add a fake cipher suite. See draft-davidben-tls-grease-01.
225 if (ssl->ctx->grease_enabled &&
226 !CBB_add_u16(&child, ssl_get_grease_value(hs, ssl_grease_cipher))) {
230 // Add TLS 1.3 ciphers. Order ChaCha20-Poly1305 relative to AES-GCM based on
232 if (hs->max_version >= TLS1_3_VERSION) {
233 if (!EVP_has_aes_hardware() &&
234 !CBB_add_u16(&child, TLS1_CK_CHACHA20_POLY1305_SHA256 & 0xffff)) {
237 if (!CBB_add_u16(&child, TLS1_CK_AES_128_GCM_SHA256 & 0xffff) ||
238 !CBB_add_u16(&child, TLS1_CK_AES_256_GCM_SHA384 & 0xffff)) {
241 if (EVP_has_aes_hardware() &&
242 !CBB_add_u16(&child, TLS1_CK_CHACHA20_POLY1305_SHA256 & 0xffff)) {
247 if (hs->min_version < TLS1_3_VERSION) {
249 for (const SSL_CIPHER *cipher : SSL_get_ciphers(ssl)) {
250 // Skip disabled ciphers
251 if ((cipher->algorithm_mkey & mask_k) ||
252 (cipher->algorithm_auth & mask_a)) {
255 if (SSL_CIPHER_get_min_version(cipher) > hs->max_version ||
256 SSL_CIPHER_get_max_version(cipher) < hs->min_version) {
260 if (!CBB_add_u16(&child, ssl_cipher_get_value(cipher))) {
265 // If all ciphers were disabled, return the error to the caller.
266 if (!any_enabled && hs->max_version < TLS1_3_VERSION) {
267 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CIPHERS_AVAILABLE);
272 // For SSLv3, the SCSV is added. Otherwise the renegotiation extension is
274 if (hs->max_version == SSL3_VERSION &&
275 !ssl->s3->initial_handshake_complete) {
276 if (!CBB_add_u16(&child, SSL3_CK_SCSV & 0xffff)) {
281 if (ssl->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
282 if (!CBB_add_u16(&child, SSL3_CK_FALLBACK_SCSV & 0xffff)) {
287 return CBB_flush(out);
290 int ssl_write_client_hello(SSL_HANDSHAKE *hs) {
291 SSL *const ssl = hs->ssl;
294 if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_CLIENT_HELLO)) {
299 if (!CBB_add_u16(&body, hs->client_version) ||
300 !CBB_add_bytes(&body, ssl->s3->client_random, SSL3_RANDOM_SIZE) ||
301 !CBB_add_u8_length_prefixed(&body, &child)) {
305 // Do not send a session ID on renegotiation.
306 if (!ssl->s3->initial_handshake_complete &&
307 !CBB_add_bytes(&child, hs->session_id, hs->session_id_len)) {
311 if (SSL_is_dtls(ssl)) {
312 if (!CBB_add_u8_length_prefixed(&body, &child) ||
313 !CBB_add_bytes(&child, ssl->d1->cookie, ssl->d1->cookie_len)) {
319 SSL_is_dtls(ssl) ? DTLS1_HM_HEADER_LENGTH : SSL3_HM_HEADER_LENGTH;
320 if (!ssl_write_client_cipher_list(hs, &body) ||
321 !CBB_add_u8(&body, 1 /* one compression method */) ||
322 !CBB_add_u8(&body, 0 /* null compression */) ||
323 !ssl_add_clienthello_tlsext(hs, &body, header_len + CBB_len(&body))) {
328 if (!ssl->method->finish_message(ssl, cbb.get(), &msg)) {
332 // Now that the length prefixes have been computed, fill in the placeholder
334 if (hs->needs_psk_binder &&
335 !tls13_write_psk_binder(hs, msg.data(), msg.size())) {
339 return ssl->method->add_message(ssl, std::move(msg));
342 static bool parse_supported_versions(SSL_HANDSHAKE *hs, uint16_t *version,
344 // If the outer version is not TLS 1.2, or there is no extensions block, use
345 // the outer version.
346 if (*version != TLS1_2_VERSION || CBS_len(in) == 0) {
350 SSL *const ssl = hs->ssl;
351 CBS copy = *in, extensions;
352 if (!CBS_get_u16_length_prefixed(©, &extensions) ||
353 CBS_len(©) != 0) {
354 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
355 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
359 bool have_supported_versions;
360 CBS supported_versions;
361 const SSL_EXTENSION_TYPE ext_types[] = {
362 {TLSEXT_TYPE_supported_versions, &have_supported_versions,
363 &supported_versions},
366 uint8_t alert = SSL_AD_DECODE_ERROR;
367 if (!ssl_parse_extensions(&extensions, &alert, ext_types,
368 OPENSSL_ARRAY_SIZE(ext_types),
369 1 /* ignore unknown */)) {
370 ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
374 // Override the outer version with the extension, if present.
375 if (have_supported_versions &&
376 (!CBS_get_u16(&supported_versions, version) ||
377 CBS_len(&supported_versions) != 0)) {
378 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
385 static enum ssl_hs_wait_t do_start_connect(SSL_HANDSHAKE *hs) {
386 SSL *const ssl = hs->ssl;
388 ssl_do_info_callback(ssl, SSL_CB_HANDSHAKE_START, 1);
389 // |session_reused| must be reset in case this is a renegotiation.
390 ssl->s3->session_reused = false;
392 // Freeze the version range.
393 if (!ssl_get_version_range(ssl, &hs->min_version, &hs->max_version)) {
397 // SSL 3.0 ClientHellos should use SSL 3.0 not TLS 1.0, for the record-layer
399 if (hs->max_version == SSL3_VERSION) {
400 ssl->s3->aead_write_ctx->SetVersionIfNullCipher(SSL3_VERSION);
403 // Always advertise the ClientHello version from the original maximum version,
404 // even on renegotiation. The static RSA key exchange uses this field, and
405 // some servers fail when it changes across handshakes.
406 if (SSL_is_dtls(hs->ssl)) {
408 hs->max_version >= TLS1_2_VERSION ? DTLS1_2_VERSION : DTLS1_VERSION;
411 hs->max_version >= TLS1_2_VERSION ? TLS1_2_VERSION : hs->max_version;
414 // If the configured session has expired or was created at a disabled
416 if (ssl->session != NULL) {
417 if (ssl->session->is_server ||
418 !ssl_supports_version(hs, ssl->session->ssl_version) ||
419 (ssl->session->session_id_length == 0 &&
420 ssl->session->tlsext_ticklen == 0) ||
421 ssl->session->not_resumable ||
422 !ssl_session_is_time_valid(ssl, ssl->session)) {
423 ssl_set_session(ssl, NULL);
427 if (!RAND_bytes(ssl->s3->client_random, sizeof(ssl->s3->client_random))) {
431 // Initialize a random session ID for the experimental TLS 1.3 variant
432 // requiring a session id.
433 if (ssl->session != nullptr &&
434 !ssl->s3->initial_handshake_complete &&
435 ssl->session->session_id_length > 0) {
436 hs->session_id_len = ssl->session->session_id_length;
437 OPENSSL_memcpy(hs->session_id, ssl->session->session_id,
439 } else if (hs->max_version >= TLS1_3_VERSION) {
440 hs->session_id_len = sizeof(hs->session_id);
441 if (!RAND_bytes(hs->session_id, hs->session_id_len)) {
446 if (!ssl_write_client_hello(hs)) {
450 hs->state = state_enter_early_data;
454 static enum ssl_hs_wait_t do_enter_early_data(SSL_HANDSHAKE *hs) {
455 SSL *const ssl = hs->ssl;
457 if (SSL_is_dtls(ssl)) {
458 hs->state = state_read_hello_verify_request;
462 if (!hs->early_data_offered) {
463 hs->state = state_read_server_hello;
467 ssl->s3->aead_write_ctx->SetVersionIfNullCipher(ssl->session->ssl_version);
468 if (!ssl->method->add_change_cipher_spec(ssl)) {
472 if (!tls13_init_early_key_schedule(hs, ssl->session->master_key,
473 ssl->session->master_key_length) ||
474 !tls13_derive_early_secrets(hs) ||
475 !tls13_set_traffic_key(ssl, evp_aead_seal, hs->early_traffic_secret,
480 // Stash the early data session, so connection properties may be queried out
482 hs->in_early_data = true;
483 SSL_SESSION_up_ref(ssl->session);
484 hs->early_session.reset(ssl->session);
485 hs->can_early_write = true;
487 hs->state = state_read_server_hello;
488 return ssl_hs_early_return;
491 static enum ssl_hs_wait_t do_read_hello_verify_request(SSL_HANDSHAKE *hs) {
492 SSL *const ssl = hs->ssl;
494 assert(SSL_is_dtls(ssl));
497 if (!ssl->method->get_message(ssl, &msg)) {
498 return ssl_hs_read_message;
501 if (msg.type != DTLS1_MT_HELLO_VERIFY_REQUEST) {
502 hs->state = state_read_server_hello;
506 CBS hello_verify_request = msg.body, cookie;
507 uint16_t server_version;
508 if (!CBS_get_u16(&hello_verify_request, &server_version) ||
509 !CBS_get_u8_length_prefixed(&hello_verify_request, &cookie) ||
510 CBS_len(&cookie) > sizeof(ssl->d1->cookie) ||
511 CBS_len(&hello_verify_request) != 0) {
512 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
513 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
517 OPENSSL_memcpy(ssl->d1->cookie, CBS_data(&cookie), CBS_len(&cookie));
518 ssl->d1->cookie_len = CBS_len(&cookie);
520 ssl->method->next_message(ssl);
522 // DTLS resets the handshake buffer after HelloVerifyRequest.
523 if (!hs->transcript.Init()) {
527 if (!ssl_write_client_hello(hs)) {
531 hs->state = state_read_server_hello;
535 static enum ssl_hs_wait_t do_read_server_hello(SSL_HANDSHAKE *hs) {
536 SSL *const ssl = hs->ssl;
538 if (!ssl->method->get_message(ssl, &msg)) {
539 return ssl_hs_read_server_hello;
542 if (!ssl_check_message_type(ssl, msg, SSL3_MT_SERVER_HELLO)) {
546 CBS server_hello = msg.body, server_random, session_id;
547 uint16_t server_version, cipher_suite;
548 uint8_t compression_method;
549 if (!CBS_get_u16(&server_hello, &server_version) ||
550 !CBS_get_bytes(&server_hello, &server_random, SSL3_RANDOM_SIZE) ||
551 !CBS_get_u8_length_prefixed(&server_hello, &session_id) ||
552 CBS_len(&session_id) > SSL3_SESSION_ID_SIZE ||
553 !CBS_get_u16(&server_hello, &cipher_suite) ||
554 !CBS_get_u8(&server_hello, &compression_method)) {
555 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
556 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
560 // Use the supported_versions extension if applicable.
561 if (!parse_supported_versions(hs, &server_version, &server_hello)) {
565 if (!ssl_supports_version(hs, server_version)) {
566 OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL);
567 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
571 assert(ssl->s3->have_version == ssl->s3->initial_handshake_complete);
572 if (!ssl->s3->have_version) {
573 ssl->version = server_version;
574 // At this point, the connection's version is known and ssl->version is
575 // fixed. Begin enforcing the record-layer version.
576 ssl->s3->have_version = true;
577 ssl->s3->aead_write_ctx->SetVersionIfNullCipher(ssl->version);
578 } else if (server_version != ssl->version) {
579 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION);
580 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
584 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
585 hs->state = state_tls13;
589 // Clear some TLS 1.3 state that no longer needs to be retained.
590 hs->key_share.reset();
591 hs->key_share_bytes.Reset();
593 // A TLS 1.2 server would not know to skip the early data we offered. Report
594 // an error code sooner. The caller may use this error code to implement the
595 // fallback described in draft-ietf-tls-tls13-18 appendix C.3.
596 if (hs->early_data_offered) {
597 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_VERSION_ON_EARLY_DATA);
598 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
602 // Copy over the server random.
603 OPENSSL_memcpy(ssl->s3->server_random, CBS_data(&server_random),
606 // Measure, but do not enforce, the TLS 1.3 anti-downgrade feature, with a
609 // For draft TLS 1.3 versions, it is not safe to deploy this feature. However,
610 // some TLS terminators are non-compliant and copy the origin server's value,
611 // so we wish to measure eventual compatibility impact.
612 if (!ssl->s3->initial_handshake_complete &&
613 hs->max_version >= TLS1_3_VERSION &&
614 OPENSSL_memcmp(ssl->s3->server_random + SSL3_RANDOM_SIZE -
615 sizeof(kDraftDowngradeRandom),
616 kDraftDowngradeRandom,
617 sizeof(kDraftDowngradeRandom)) == 0) {
618 ssl->s3->draft_downgrade = true;
621 if (!ssl->s3->initial_handshake_complete && ssl->session != NULL &&
622 ssl->session->session_id_length != 0 &&
623 CBS_mem_equal(&session_id, ssl->session->session_id,
624 ssl->session->session_id_length)) {
625 ssl->s3->session_reused = true;
627 // The server may also have echoed back the TLS 1.3 compatibility mode
628 // session ID. As we know this is not a session the server knows about, any
629 // server resuming it is in error. Reject the first connection
630 // deterministicly, rather than installing an invalid session into the
631 // session cache. https://crbug.com/796910
632 if (hs->session_id_len != 0 &&
633 CBS_mem_equal(&session_id, hs->session_id, hs->session_id_len)) {
634 OPENSSL_PUT_ERROR(SSL, SSL_R_SERVER_ECHOED_INVALID_SESSION_ID);
635 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
639 // The session wasn't resumed. Create a fresh SSL_SESSION to
641 ssl_set_session(ssl, NULL);
642 if (!ssl_get_new_session(hs, 0 /* client */)) {
643 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
646 // Note: session_id could be empty.
647 hs->new_session->session_id_length = CBS_len(&session_id);
648 OPENSSL_memcpy(hs->new_session->session_id, CBS_data(&session_id),
649 CBS_len(&session_id));
652 const SSL_CIPHER *cipher = SSL_get_cipher_by_value(cipher_suite);
653 if (cipher == NULL) {
655 OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CIPHER_RETURNED);
656 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
660 // The cipher must be allowed in the selected version and enabled.
661 uint32_t mask_a, mask_k;
662 ssl_get_client_disabled(ssl, &mask_a, &mask_k);
663 if ((cipher->algorithm_mkey & mask_k) || (cipher->algorithm_auth & mask_a) ||
664 SSL_CIPHER_get_min_version(cipher) > ssl_protocol_version(ssl) ||
665 SSL_CIPHER_get_max_version(cipher) < ssl_protocol_version(ssl) ||
666 !sk_SSL_CIPHER_find(SSL_get_ciphers(ssl), NULL, cipher)) {
667 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
668 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
672 if (ssl->session != NULL) {
673 if (ssl->session->ssl_version != ssl->version) {
674 OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_VERSION_NOT_RETURNED);
675 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
678 if (ssl->session->cipher != cipher) {
679 OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
680 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
683 if (!ssl_session_is_context_valid(ssl, ssl->session)) {
684 // This is actually a client application bug.
685 OPENSSL_PUT_ERROR(SSL,
686 SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
687 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
691 hs->new_session->cipher = cipher;
693 hs->new_cipher = cipher;
695 // Now that the cipher is known, initialize the handshake hash and hash the
697 if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher) ||
698 !ssl_hash_message(hs, msg)) {
699 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
703 // If doing a full handshake, the server may request a client certificate
704 // which requires hashing the handshake transcript. Otherwise, the handshake
705 // buffer may be released.
706 if (ssl->session != NULL ||
707 !ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
708 hs->transcript.FreeBuffer();
711 // Only the NULL compression algorithm is supported.
712 if (compression_method != 0) {
713 OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
714 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
719 if (!ssl_parse_serverhello_tlsext(hs, &server_hello)) {
720 OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
724 // There should be nothing left over in the record.
725 if (CBS_len(&server_hello) != 0) {
726 // wrong packet length
727 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
728 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
732 if (ssl->session != NULL &&
733 hs->extended_master_secret != ssl->session->extended_master_secret) {
734 if (ssl->session->extended_master_secret) {
735 OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
737 OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_NON_EMS_SESSION_WITH_EMS_EXTENSION);
739 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
743 if (ssl->token_binding_negotiated &&
744 (!hs->extended_master_secret || !ssl->s3->send_connection_binding)) {
745 OPENSSL_PUT_ERROR(SSL, SSL_R_NEGOTIATED_TB_WITHOUT_EMS_OR_RI);
746 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_EXTENSION);
750 ssl->method->next_message(ssl);
752 if (ssl->session != NULL) {
753 hs->state = state_read_session_ticket;
757 hs->state = state_read_server_certificate;
761 static enum ssl_hs_wait_t do_tls13(SSL_HANDSHAKE *hs) {
762 enum ssl_hs_wait_t wait = tls13_client_handshake(hs);
763 if (wait == ssl_hs_ok) {
764 hs->state = state_finish_client_handshake;
771 static enum ssl_hs_wait_t do_read_server_certificate(SSL_HANDSHAKE *hs) {
772 SSL *const ssl = hs->ssl;
774 if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
775 hs->state = state_read_certificate_status;
780 if (!ssl->method->get_message(ssl, &msg)) {
781 return ssl_hs_read_message;
784 if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE) ||
785 !ssl_hash_message(hs, msg)) {
790 uint8_t alert = SSL_AD_DECODE_ERROR;
791 UniquePtr<STACK_OF(CRYPTO_BUFFER)> chain;
792 if (!ssl_parse_cert_chain(&alert, &chain, &hs->peer_pubkey, NULL, &body,
794 ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
797 sk_CRYPTO_BUFFER_pop_free(hs->new_session->certs, CRYPTO_BUFFER_free);
798 hs->new_session->certs = chain.release();
800 if (sk_CRYPTO_BUFFER_num(hs->new_session->certs) == 0 ||
801 CBS_len(&body) != 0 ||
802 !ssl->ctx->x509_method->session_cache_objects(hs->new_session.get())) {
803 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
804 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
808 if (!ssl_check_leaf_certificate(
809 hs, hs->peer_pubkey.get(),
810 sk_CRYPTO_BUFFER_value(hs->new_session->certs, 0))) {
811 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
815 ssl->method->next_message(ssl);
817 hs->state = state_read_certificate_status;
821 static enum ssl_hs_wait_t do_read_certificate_status(SSL_HANDSHAKE *hs) {
822 SSL *const ssl = hs->ssl;
824 if (!hs->certificate_status_expected) {
825 hs->state = state_verify_server_certificate;
830 if (!ssl->method->get_message(ssl, &msg)) {
831 return ssl_hs_read_message;
834 if (msg.type != SSL3_MT_CERTIFICATE_STATUS) {
835 // A server may send status_request in ServerHello and then change its mind
836 // about sending CertificateStatus.
837 hs->state = state_verify_server_certificate;
841 if (!ssl_hash_message(hs, msg)) {
845 CBS certificate_status = msg.body, ocsp_response;
847 if (!CBS_get_u8(&certificate_status, &status_type) ||
848 status_type != TLSEXT_STATUSTYPE_ocsp ||
849 !CBS_get_u24_length_prefixed(&certificate_status, &ocsp_response) ||
850 CBS_len(&ocsp_response) == 0 ||
851 CBS_len(&certificate_status) != 0) {
852 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
853 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
857 CRYPTO_BUFFER_free(hs->new_session->ocsp_response);
858 hs->new_session->ocsp_response =
859 CRYPTO_BUFFER_new_from_CBS(&ocsp_response, ssl->ctx->pool);
860 if (hs->new_session->ocsp_response == nullptr) {
861 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
865 ssl->method->next_message(ssl);
867 hs->state = state_verify_server_certificate;
871 static enum ssl_hs_wait_t do_verify_server_certificate(SSL_HANDSHAKE *hs) {
872 if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
873 hs->state = state_read_server_key_exchange;
877 switch (ssl_verify_peer_cert(hs)) {
880 case ssl_verify_invalid:
882 case ssl_verify_retry:
883 hs->state = state_verify_server_certificate;
884 return ssl_hs_certificate_verify;
887 hs->state = state_read_server_key_exchange;
891 static enum ssl_hs_wait_t do_read_server_key_exchange(SSL_HANDSHAKE *hs) {
892 SSL *const ssl = hs->ssl;
894 if (!ssl->method->get_message(ssl, &msg)) {
895 return ssl_hs_read_message;
898 if (msg.type != SSL3_MT_SERVER_KEY_EXCHANGE) {
899 // Some ciphers (pure PSK) have an optional ServerKeyExchange message.
900 if (ssl_cipher_requires_server_key_exchange(hs->new_cipher)) {
901 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
902 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
906 hs->state = state_read_certificate_request;
910 if (!ssl_hash_message(hs, msg)) {
914 uint32_t alg_k = hs->new_cipher->algorithm_mkey;
915 uint32_t alg_a = hs->new_cipher->algorithm_auth;
916 CBS server_key_exchange = msg.body;
917 if (alg_a & SSL_aPSK) {
918 CBS psk_identity_hint;
920 // Each of the PSK key exchanges begins with a psk_identity_hint.
921 if (!CBS_get_u16_length_prefixed(&server_key_exchange,
922 &psk_identity_hint)) {
923 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
924 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
928 // Store the PSK identity hint for the ClientKeyExchange. Assume that the
929 // maximum length of a PSK identity hint can be as long as the maximum
930 // length of a PSK identity. Also do not allow NULL characters; identities
931 // are saved as C strings.
933 // TODO(davidben): Should invalid hints be ignored? It's a hint rather than
934 // a specific identity.
935 if (CBS_len(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN ||
936 CBS_contains_zero_byte(&psk_identity_hint)) {
937 OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
938 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
942 // Save non-empty identity hints as a C string. Empty identity hints we
943 // treat as missing. Plain PSK makes it possible to send either no hint
944 // (omit ServerKeyExchange) or an empty hint, while ECDHE_PSK can only spell
945 // empty hint. Having different capabilities is odd, so we interpret empty
946 // and missing as identical.
948 if (CBS_len(&psk_identity_hint) != 0 &&
949 !CBS_strdup(&psk_identity_hint, &raw)) {
950 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
951 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
954 hs->peer_psk_identity_hint.reset(raw);
957 if (alg_k & SSL_kECDHE) {
958 // Parse the server parameters.
962 if (!CBS_get_u8(&server_key_exchange, &group_type) ||
963 group_type != NAMED_CURVE_TYPE ||
964 !CBS_get_u16(&server_key_exchange, &group_id) ||
965 !CBS_get_u8_length_prefixed(&server_key_exchange, &point)) {
966 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
967 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
970 hs->new_session->group_id = group_id;
972 // Ensure the group is consistent with preferences.
973 if (!tls1_check_group_id(ssl, group_id)) {
974 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
975 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
979 // Initialize ECDH and save the peer public key for later.
980 hs->key_share = SSLKeyShare::Create(group_id);
981 if (!hs->key_share ||
982 !hs->peer_key.CopyFrom(point)) {
985 } else if (!(alg_k & SSL_kPSK)) {
986 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
987 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
991 // At this point, |server_key_exchange| contains the signature, if any, while
992 // |msg.body| contains the entire message. From that, derive a CBS containing
993 // just the parameter.
995 CBS_init(¶meter, CBS_data(&msg.body),
996 CBS_len(&msg.body) - CBS_len(&server_key_exchange));
998 // ServerKeyExchange should be signed by the server's public key.
999 if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1000 uint16_t signature_algorithm = 0;
1001 if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1002 if (!CBS_get_u16(&server_key_exchange, &signature_algorithm)) {
1003 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1004 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1005 return ssl_hs_error;
1007 uint8_t alert = SSL_AD_DECODE_ERROR;
1008 if (!tls12_check_peer_sigalg(ssl, &alert, signature_algorithm)) {
1009 ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1010 return ssl_hs_error;
1012 hs->new_session->peer_signature_algorithm = signature_algorithm;
1013 } else if (!tls1_get_legacy_signature_algorithm(&signature_algorithm,
1014 hs->peer_pubkey.get())) {
1015 OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
1016 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_CERTIFICATE);
1017 return ssl_hs_error;
1020 // The last field in |server_key_exchange| is the signature.
1022 if (!CBS_get_u16_length_prefixed(&server_key_exchange, &signature) ||
1023 CBS_len(&server_key_exchange) != 0) {
1024 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1025 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1026 return ssl_hs_error;
1029 ScopedCBB transcript;
1030 Array<uint8_t> transcript_data;
1031 if (!CBB_init(transcript.get(),
1032 2 * SSL3_RANDOM_SIZE + CBS_len(¶meter)) ||
1033 !CBB_add_bytes(transcript.get(), ssl->s3->client_random,
1034 SSL3_RANDOM_SIZE) ||
1035 !CBB_add_bytes(transcript.get(), ssl->s3->server_random,
1036 SSL3_RANDOM_SIZE) ||
1037 !CBB_add_bytes(transcript.get(), CBS_data(¶meter),
1038 CBS_len(¶meter)) ||
1039 !CBBFinishArray(transcript.get(), &transcript_data)) {
1040 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1041 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1042 return ssl_hs_error;
1045 bool sig_ok = ssl_public_key_verify(ssl, signature, signature_algorithm,
1046 hs->peer_pubkey.get(), transcript_data);
1047 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
1053 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
1054 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
1055 return ssl_hs_error;
1058 // PSK ciphers are the only supported certificate-less ciphers.
1059 assert(alg_a == SSL_aPSK);
1061 if (CBS_len(&server_key_exchange) > 0) {
1062 OPENSSL_PUT_ERROR(SSL, SSL_R_EXTRA_DATA_IN_MESSAGE);
1063 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1064 return ssl_hs_error;
1068 ssl->method->next_message(ssl);
1069 hs->state = state_read_certificate_request;
1073 static enum ssl_hs_wait_t do_read_certificate_request(SSL_HANDSHAKE *hs) {
1074 SSL *const ssl = hs->ssl;
1076 if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1077 hs->state = state_read_server_hello_done;
1082 if (!ssl->method->get_message(ssl, &msg)) {
1083 return ssl_hs_read_message;
1086 if (msg.type == SSL3_MT_SERVER_HELLO_DONE) {
1087 // If we get here we don't need the handshake buffer as we won't be doing
1089 hs->transcript.FreeBuffer();
1090 hs->state = state_read_server_hello_done;
1094 if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_REQUEST) ||
1095 !ssl_hash_message(hs, msg)) {
1096 return ssl_hs_error;
1099 // Get the certificate types.
1100 CBS body = msg.body, certificate_types;
1101 if (!CBS_get_u8_length_prefixed(&body, &certificate_types)) {
1102 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1103 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1104 return ssl_hs_error;
1107 if (!hs->certificate_types.CopyFrom(certificate_types)) {
1108 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1109 return ssl_hs_error;
1112 if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1113 CBS supported_signature_algorithms;
1114 if (!CBS_get_u16_length_prefixed(&body, &supported_signature_algorithms) ||
1115 !tls1_parse_peer_sigalgs(hs, &supported_signature_algorithms)) {
1116 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1117 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1118 return ssl_hs_error;
1122 uint8_t alert = SSL_AD_DECODE_ERROR;
1123 UniquePtr<STACK_OF(CRYPTO_BUFFER)> ca_names =
1124 ssl_parse_client_CA_list(ssl, &alert, &body);
1126 ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1127 return ssl_hs_error;
1130 if (CBS_len(&body) != 0) {
1131 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1132 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1133 return ssl_hs_error;
1136 hs->cert_request = true;
1137 hs->ca_names = std::move(ca_names);
1138 ssl->ctx->x509_method->hs_flush_cached_ca_names(hs);
1140 ssl->method->next_message(ssl);
1141 hs->state = state_read_server_hello_done;
1145 static enum ssl_hs_wait_t do_read_server_hello_done(SSL_HANDSHAKE *hs) {
1146 SSL *const ssl = hs->ssl;
1148 if (!ssl->method->get_message(ssl, &msg)) {
1149 return ssl_hs_read_message;
1152 if (!ssl_check_message_type(ssl, msg, SSL3_MT_SERVER_HELLO_DONE) ||
1153 !ssl_hash_message(hs, msg)) {
1154 return ssl_hs_error;
1157 // ServerHelloDone is empty.
1158 if (CBS_len(&msg.body) != 0) {
1159 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1160 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1161 return ssl_hs_error;
1164 ssl->method->next_message(ssl);
1165 hs->state = state_send_client_certificate;
1169 static enum ssl_hs_wait_t do_send_client_certificate(SSL_HANDSHAKE *hs) {
1170 SSL *const ssl = hs->ssl;
1172 // The peer didn't request a certificate.
1173 if (!hs->cert_request) {
1174 hs->state = state_send_client_key_exchange;
1178 // Call cert_cb to update the certificate.
1179 if (ssl->cert->cert_cb != NULL) {
1180 int rv = ssl->cert->cert_cb(ssl, ssl->cert->cert_cb_arg);
1182 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1183 OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
1184 return ssl_hs_error;
1187 hs->state = state_send_client_certificate;
1188 return ssl_hs_x509_lookup;
1192 if (!ssl_has_certificate(ssl)) {
1193 // Without a client certificate, the handshake buffer may be released.
1194 hs->transcript.FreeBuffer();
1196 // In SSL 3.0, the Certificate message is replaced with a warning alert.
1197 if (ssl->version == SSL3_VERSION) {
1198 if (!ssl->method->add_alert(ssl, SSL3_AL_WARNING,
1199 SSL_AD_NO_CERTIFICATE)) {
1200 return ssl_hs_error;
1202 hs->state = state_send_client_key_exchange;
1207 if (!ssl_on_certificate_selected(hs) ||
1208 !ssl_output_cert_chain(ssl)) {
1209 return ssl_hs_error;
1213 hs->state = state_send_client_key_exchange;
1217 static_assert(sizeof(size_t) >= sizeof(unsigned),
1218 "size_t is smaller than unsigned");
1220 static enum ssl_hs_wait_t do_send_client_key_exchange(SSL_HANDSHAKE *hs) {
1221 SSL *const ssl = hs->ssl;
1224 if (!ssl->method->init_message(ssl, cbb.get(), &body,
1225 SSL3_MT_CLIENT_KEY_EXCHANGE)) {
1226 return ssl_hs_error;
1230 uint32_t alg_k = hs->new_cipher->algorithm_mkey;
1231 uint32_t alg_a = hs->new_cipher->algorithm_auth;
1233 // If using a PSK key exchange, prepare the pre-shared key.
1234 unsigned psk_len = 0;
1235 uint8_t psk[PSK_MAX_PSK_LEN];
1236 if (alg_a & SSL_aPSK) {
1237 if (ssl->psk_client_callback == NULL) {
1238 OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_NO_CLIENT_CB);
1239 return ssl_hs_error;
1242 char identity[PSK_MAX_IDENTITY_LEN + 1];
1243 OPENSSL_memset(identity, 0, sizeof(identity));
1245 ssl->psk_client_callback(ssl, hs->peer_psk_identity_hint.get(),
1246 identity, sizeof(identity), psk, sizeof(psk));
1248 OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
1249 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1250 return ssl_hs_error;
1252 assert(psk_len <= PSK_MAX_PSK_LEN);
1254 OPENSSL_free(hs->new_session->psk_identity);
1255 hs->new_session->psk_identity = BUF_strdup(identity);
1256 if (hs->new_session->psk_identity == NULL) {
1257 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1258 return ssl_hs_error;
1261 // Write out psk_identity.
1263 if (!CBB_add_u16_length_prefixed(&body, &child) ||
1264 !CBB_add_bytes(&child, (const uint8_t *)identity,
1265 OPENSSL_strnlen(identity, sizeof(identity))) ||
1266 !CBB_flush(&body)) {
1267 return ssl_hs_error;
1271 // Depending on the key exchange method, compute |pms|.
1272 if (alg_k & SSL_kRSA) {
1273 if (!pms.Init(SSL_MAX_MASTER_KEY_LENGTH)) {
1274 return ssl_hs_error;
1277 RSA *rsa = EVP_PKEY_get0_RSA(hs->peer_pubkey.get());
1279 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1280 return ssl_hs_error;
1283 pms[0] = hs->client_version >> 8;
1284 pms[1] = hs->client_version & 0xff;
1285 if (!RAND_bytes(&pms[2], SSL_MAX_MASTER_KEY_LENGTH - 2)) {
1286 return ssl_hs_error;
1289 CBB child, *enc_pms = &body;
1291 // In TLS, there is a length prefix.
1292 if (ssl->version > SSL3_VERSION) {
1293 if (!CBB_add_u16_length_prefixed(&body, &child)) {
1294 return ssl_hs_error;
1300 if (!CBB_reserve(enc_pms, &ptr, RSA_size(rsa)) ||
1301 !RSA_encrypt(rsa, &enc_pms_len, ptr, RSA_size(rsa), pms.data(),
1302 pms.size(), RSA_PKCS1_PADDING) ||
1303 !CBB_did_write(enc_pms, enc_pms_len) ||
1304 !CBB_flush(&body)) {
1305 return ssl_hs_error;
1307 } else if (alg_k & SSL_kECDHE) {
1308 // Generate a keypair and serialize the public half.
1310 if (!CBB_add_u8_length_prefixed(&body, &child)) {
1311 return ssl_hs_error;
1314 // Compute the premaster.
1315 uint8_t alert = SSL_AD_DECODE_ERROR;
1316 if (!hs->key_share->Accept(&child, &pms, &alert, hs->peer_key)) {
1317 ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1318 return ssl_hs_error;
1320 if (!CBB_flush(&body)) {
1321 return ssl_hs_error;
1324 // The key exchange state may now be discarded.
1325 hs->key_share.reset();
1326 hs->peer_key.Reset();
1327 } else if (alg_k & SSL_kPSK) {
1328 // For plain PSK, other_secret is a block of 0s with the same length as
1329 // the pre-shared key.
1330 if (!pms.Init(psk_len)) {
1331 return ssl_hs_error;
1333 OPENSSL_memset(pms.data(), 0, pms.size());
1335 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1336 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1337 return ssl_hs_error;
1340 // For a PSK cipher suite, other_secret is combined with the pre-shared
1342 if (alg_a & SSL_aPSK) {
1345 if (!CBB_init(pms_cbb.get(), 2 + psk_len + 2 + pms.size()) ||
1346 !CBB_add_u16_length_prefixed(pms_cbb.get(), &child) ||
1347 !CBB_add_bytes(&child, pms.data(), pms.size()) ||
1348 !CBB_add_u16_length_prefixed(pms_cbb.get(), &child) ||
1349 !CBB_add_bytes(&child, psk, psk_len) ||
1350 !CBBFinishArray(pms_cbb.get(), &pms)) {
1351 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1352 return ssl_hs_error;
1356 // The message must be added to the finished hash before calculating the
1358 if (!ssl_add_message_cbb(ssl, cbb.get())) {
1359 return ssl_hs_error;
1362 hs->new_session->master_key_length =
1363 tls1_generate_master_secret(hs, hs->new_session->master_key, pms);
1364 if (hs->new_session->master_key_length == 0) {
1365 return ssl_hs_error;
1367 hs->new_session->extended_master_secret = hs->extended_master_secret;
1369 hs->state = state_send_client_certificate_verify;
1373 static enum ssl_hs_wait_t do_send_client_certificate_verify(SSL_HANDSHAKE *hs) {
1374 SSL *const ssl = hs->ssl;
1376 if (!hs->cert_request || !ssl_has_certificate(ssl)) {
1377 hs->state = state_send_client_finished;
1381 assert(ssl_has_private_key(ssl));
1384 if (!ssl->method->init_message(ssl, cbb.get(), &body,
1385 SSL3_MT_CERTIFICATE_VERIFY)) {
1386 return ssl_hs_error;
1389 uint16_t signature_algorithm;
1390 if (!tls1_choose_signature_algorithm(hs, &signature_algorithm)) {
1391 return ssl_hs_error;
1393 if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1394 // Write out the digest type in TLS 1.2.
1395 if (!CBB_add_u16(&body, signature_algorithm)) {
1396 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1397 return ssl_hs_error;
1401 // Set aside space for the signature.
1402 const size_t max_sig_len = EVP_PKEY_size(hs->local_pubkey.get());
1404 if (!CBB_add_u16_length_prefixed(&body, &child) ||
1405 !CBB_reserve(&child, &ptr, max_sig_len)) {
1406 return ssl_hs_error;
1409 size_t sig_len = max_sig_len;
1410 // The SSL3 construction for CertificateVerify does not decompose into a
1411 // single final digest and signature, and must be special-cased.
1412 if (ssl_protocol_version(ssl) == SSL3_VERSION) {
1413 if (ssl->cert->key_method != NULL) {
1414 OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL_FOR_CUSTOM_KEY);
1415 return ssl_hs_error;
1418 uint8_t digest[EVP_MAX_MD_SIZE];
1420 if (!hs->transcript.GetSSL3CertVerifyHash(
1421 digest, &digest_len, hs->new_session.get(), signature_algorithm)) {
1422 return ssl_hs_error;
1425 UniquePtr<EVP_PKEY_CTX> pctx(EVP_PKEY_CTX_new(ssl->cert->privatekey, NULL));
1427 !EVP_PKEY_sign_init(pctx.get()) ||
1428 !EVP_PKEY_sign(pctx.get(), ptr, &sig_len, digest, digest_len)) {
1429 return ssl_hs_error;
1432 switch (ssl_private_key_sign(hs, ptr, &sig_len, max_sig_len,
1433 signature_algorithm,
1434 hs->transcript.buffer())) {
1435 case ssl_private_key_success:
1437 case ssl_private_key_failure:
1438 return ssl_hs_error;
1439 case ssl_private_key_retry:
1440 hs->state = state_send_client_certificate_verify;
1441 return ssl_hs_private_key_operation;
1445 if (!CBB_did_write(&child, sig_len) ||
1446 !ssl_add_message_cbb(ssl, cbb.get())) {
1447 return ssl_hs_error;
1450 // The handshake buffer is no longer necessary.
1451 hs->transcript.FreeBuffer();
1453 hs->state = state_send_client_finished;
1457 static enum ssl_hs_wait_t do_send_client_finished(SSL_HANDSHAKE *hs) {
1458 SSL *const ssl = hs->ssl;
1459 // Resolve Channel ID first, before any non-idempotent operations.
1460 if (ssl->s3->tlsext_channel_id_valid) {
1461 if (!ssl_do_channel_id_callback(ssl)) {
1462 return ssl_hs_error;
1465 if (ssl->tlsext_channel_id_private == NULL) {
1466 hs->state = state_send_client_finished;
1467 return ssl_hs_channel_id_lookup;
1471 if (!ssl->method->add_change_cipher_spec(ssl) ||
1472 !tls1_change_cipher_state(hs, evp_aead_seal)) {
1473 return ssl_hs_error;
1476 if (hs->next_proto_neg_seen) {
1477 static const uint8_t kZero[32] = {0};
1478 size_t padding_len =
1479 32 - ((ssl->s3->next_proto_negotiated.size() + 2) % 32);
1483 if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_NEXT_PROTO) ||
1484 !CBB_add_u8_length_prefixed(&body, &child) ||
1485 !CBB_add_bytes(&child, ssl->s3->next_proto_negotiated.data(),
1486 ssl->s3->next_proto_negotiated.size()) ||
1487 !CBB_add_u8_length_prefixed(&body, &child) ||
1488 !CBB_add_bytes(&child, kZero, padding_len) ||
1489 !ssl_add_message_cbb(ssl, cbb.get())) {
1490 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1491 return ssl_hs_error;
1495 if (ssl->s3->tlsext_channel_id_valid) {
1498 if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_CHANNEL_ID) ||
1499 !tls1_write_channel_id(hs, &body) ||
1500 !ssl_add_message_cbb(ssl, cbb.get())) {
1501 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1502 return ssl_hs_error;
1506 if (!ssl_send_finished(hs)) {
1507 return ssl_hs_error;
1510 hs->state = state_finish_flight;
1511 return ssl_hs_flush;
1514 static bool can_false_start(const SSL_HANDSHAKE *hs) {
1515 SSL *const ssl = hs->ssl;
1517 // False Start only for TLS 1.2 with an ECDHE+AEAD cipher.
1518 if (SSL_is_dtls(ssl) ||
1519 SSL_version(ssl) != TLS1_2_VERSION ||
1520 hs->new_cipher->algorithm_mkey != SSL_kECDHE ||
1521 hs->new_cipher->algorithm_mac != SSL_AEAD) {
1525 // Additionally require ALPN or NPN by default.
1527 // TODO(davidben): Can this constraint be relaxed globally now that cipher
1528 // suite requirements have been relaxed?
1529 if (!ssl->ctx->false_start_allowed_without_alpn &&
1530 ssl->s3->alpn_selected.empty() &&
1531 ssl->s3->next_proto_negotiated.empty()) {
1538 static enum ssl_hs_wait_t do_finish_flight(SSL_HANDSHAKE *hs) {
1539 SSL *const ssl = hs->ssl;
1540 if (ssl->session != NULL) {
1541 hs->state = state_finish_client_handshake;
1545 // This is a full handshake. If it involves ChannelID, then record the
1546 // handshake hashes at this point in the session so that any resumption of
1547 // this session with ChannelID can sign those hashes.
1548 if (!tls1_record_handshake_hashes_for_channel_id(hs)) {
1549 return ssl_hs_error;
1552 hs->state = state_read_session_ticket;
1554 if ((SSL_get_mode(ssl) & SSL_MODE_ENABLE_FALSE_START) &&
1555 can_false_start(hs) &&
1556 // No False Start on renegotiation (would complicate the state machine).
1557 !ssl->s3->initial_handshake_complete) {
1558 hs->in_false_start = true;
1559 hs->can_early_write = true;
1560 return ssl_hs_early_return;
1566 static enum ssl_hs_wait_t do_read_session_ticket(SSL_HANDSHAKE *hs) {
1567 SSL *const ssl = hs->ssl;
1569 if (!hs->ticket_expected) {
1570 hs->state = state_process_change_cipher_spec;
1571 return ssl_hs_read_change_cipher_spec;
1575 if (!ssl->method->get_message(ssl, &msg)) {
1576 return ssl_hs_read_message;
1579 if (!ssl_check_message_type(ssl, msg, SSL3_MT_NEW_SESSION_TICKET) ||
1580 !ssl_hash_message(hs, msg)) {
1581 return ssl_hs_error;
1584 CBS new_session_ticket = msg.body, ticket;
1585 uint32_t tlsext_tick_lifetime_hint;
1586 if (!CBS_get_u32(&new_session_ticket, &tlsext_tick_lifetime_hint) ||
1587 !CBS_get_u16_length_prefixed(&new_session_ticket, &ticket) ||
1588 CBS_len(&new_session_ticket) != 0) {
1589 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1590 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1591 return ssl_hs_error;
1594 if (CBS_len(&ticket) == 0) {
1595 // RFC 5077 allows a server to change its mind and send no ticket after
1596 // negotiating the extension. The value of |ticket_expected| is checked in
1597 // |ssl_update_cache| so is cleared here to avoid an unnecessary update.
1598 hs->ticket_expected = false;
1599 ssl->method->next_message(ssl);
1600 hs->state = state_process_change_cipher_spec;
1601 return ssl_hs_read_change_cipher_spec;
1604 SSL_SESSION *session = hs->new_session.get();
1605 UniquePtr<SSL_SESSION> renewed_session;
1606 if (ssl->session != NULL) {
1607 // The server is sending a new ticket for an existing session. Sessions are
1608 // immutable once established, so duplicate all but the ticket of the
1609 // existing session.
1611 SSL_SESSION_dup(ssl->session, SSL_SESSION_INCLUDE_NONAUTH);
1612 if (!renewed_session) {
1613 // This should never happen.
1614 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1615 return ssl_hs_error;
1617 session = renewed_session.get();
1620 // |tlsext_tick_lifetime_hint| is measured from when the ticket was issued.
1621 ssl_session_rebase_time(ssl, session);
1623 if (!CBS_stow(&ticket, &session->tlsext_tick, &session->tlsext_ticklen)) {
1624 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1625 return ssl_hs_error;
1627 session->tlsext_tick_lifetime_hint = tlsext_tick_lifetime_hint;
1629 // Generate a session ID for this session based on the session ticket. We use
1630 // the session ID mechanism for detecting ticket resumption. This also fits in
1631 // with assumptions elsewhere in OpenSSL.
1632 if (!EVP_Digest(CBS_data(&ticket), CBS_len(&ticket),
1633 session->session_id, &session->session_id_length,
1634 EVP_sha256(), NULL)) {
1635 return ssl_hs_error;
1638 if (renewed_session) {
1639 session->not_resumable = 0;
1640 SSL_SESSION_free(ssl->session);
1641 ssl->session = renewed_session.release();
1644 ssl->method->next_message(ssl);
1645 hs->state = state_process_change_cipher_spec;
1646 return ssl_hs_read_change_cipher_spec;
1649 static enum ssl_hs_wait_t do_process_change_cipher_spec(SSL_HANDSHAKE *hs) {
1650 if (!tls1_change_cipher_state(hs, evp_aead_open)) {
1651 return ssl_hs_error;
1654 hs->state = state_read_server_finished;
1658 static enum ssl_hs_wait_t do_read_server_finished(SSL_HANDSHAKE *hs) {
1659 SSL *const ssl = hs->ssl;
1660 enum ssl_hs_wait_t wait = ssl_get_finished(hs);
1661 if (wait != ssl_hs_ok) {
1665 if (ssl->session != NULL) {
1666 hs->state = state_send_client_finished;
1670 hs->state = state_finish_client_handshake;
1674 static enum ssl_hs_wait_t do_finish_client_handshake(SSL_HANDSHAKE *hs) {
1675 SSL *const ssl = hs->ssl;
1677 ssl->method->on_handshake_complete(ssl);
1679 if (ssl->session != NULL) {
1680 SSL_SESSION_up_ref(ssl->session);
1681 ssl->s3->established_session.reset(ssl->session);
1683 // We make a copy of the session in order to maintain the immutability
1684 // of the new established_session due to False Start. The caller may
1685 // have taken a reference to the temporary session.
1686 ssl->s3->established_session =
1687 SSL_SESSION_dup(hs->new_session.get(), SSL_SESSION_DUP_ALL);
1688 if (!ssl->s3->established_session) {
1689 return ssl_hs_error;
1691 // Renegotiations do not participate in session resumption.
1692 if (!ssl->s3->initial_handshake_complete) {
1693 ssl->s3->established_session->not_resumable = 0;
1696 hs->new_session.reset();
1699 hs->handshake_finalized = true;
1700 ssl->s3->initial_handshake_complete = true;
1701 ssl_update_cache(hs, SSL_SESS_CACHE_CLIENT);
1703 hs->state = state_done;
1707 enum ssl_hs_wait_t ssl_client_handshake(SSL_HANDSHAKE *hs) {
1708 while (hs->state != state_done) {
1709 enum ssl_hs_wait_t ret = ssl_hs_error;
1710 enum ssl_client_hs_state_t state =
1711 static_cast<enum ssl_client_hs_state_t>(hs->state);
1713 case state_start_connect:
1714 ret = do_start_connect(hs);
1716 case state_enter_early_data:
1717 ret = do_enter_early_data(hs);
1719 case state_read_hello_verify_request:
1720 ret = do_read_hello_verify_request(hs);
1722 case state_read_server_hello:
1723 ret = do_read_server_hello(hs);
1728 case state_read_server_certificate:
1729 ret = do_read_server_certificate(hs);
1731 case state_read_certificate_status:
1732 ret = do_read_certificate_status(hs);
1734 case state_verify_server_certificate:
1735 ret = do_verify_server_certificate(hs);
1737 case state_read_server_key_exchange:
1738 ret = do_read_server_key_exchange(hs);
1740 case state_read_certificate_request:
1741 ret = do_read_certificate_request(hs);
1743 case state_read_server_hello_done:
1744 ret = do_read_server_hello_done(hs);
1746 case state_send_client_certificate:
1747 ret = do_send_client_certificate(hs);
1749 case state_send_client_key_exchange:
1750 ret = do_send_client_key_exchange(hs);
1752 case state_send_client_certificate_verify:
1753 ret = do_send_client_certificate_verify(hs);
1755 case state_send_client_finished:
1756 ret = do_send_client_finished(hs);
1758 case state_finish_flight:
1759 ret = do_finish_flight(hs);
1761 case state_read_session_ticket:
1762 ret = do_read_session_ticket(hs);
1764 case state_process_change_cipher_spec:
1765 ret = do_process_change_cipher_spec(hs);
1767 case state_read_server_finished:
1768 ret = do_read_server_finished(hs);
1770 case state_finish_client_handshake:
1771 ret = do_finish_client_handshake(hs);
1778 if (hs->state != state) {
1779 ssl_do_info_callback(hs->ssl, SSL_CB_CONNECT_LOOP, 1);
1782 if (ret != ssl_hs_ok) {
1787 ssl_do_info_callback(hs->ssl, SSL_CB_HANDSHAKE_DONE, 1);
1791 const char *ssl_client_handshake_state(SSL_HANDSHAKE *hs) {
1792 enum ssl_client_hs_state_t state =
1793 static_cast<enum ssl_client_hs_state_t>(hs->state);
1795 case state_start_connect:
1796 return "TLS client start_connect";
1797 case state_enter_early_data:
1798 return "TLS client enter_early_data";
1799 case state_read_hello_verify_request:
1800 return "TLS client read_hello_verify_request";
1801 case state_read_server_hello:
1802 return "TLS client read_server_hello";
1804 return tls13_client_handshake_state(hs);
1805 case state_read_server_certificate:
1806 return "TLS client read_server_certificate";
1807 case state_read_certificate_status:
1808 return "TLS client read_certificate_status";
1809 case state_verify_server_certificate:
1810 return "TLS client verify_server_certificate";
1811 case state_read_server_key_exchange:
1812 return "TLS client read_server_key_exchange";
1813 case state_read_certificate_request:
1814 return "TLS client read_certificate_request";
1815 case state_read_server_hello_done:
1816 return "TLS client read_server_hello_done";
1817 case state_send_client_certificate:
1818 return "TLS client send_client_certificate";
1819 case state_send_client_key_exchange:
1820 return "TLS client send_client_key_exchange";
1821 case state_send_client_certificate_verify:
1822 return "TLS client send_client_certificate_verify";
1823 case state_send_client_finished:
1824 return "TLS client send_client_finished";
1825 case state_finish_flight:
1826 return "TLS client finish_flight";
1827 case state_read_session_ticket:
1828 return "TLS client read_session_ticket";
1829 case state_process_change_cipher_spec:
1830 return "TLS client process_change_cipher_spec";
1831 case state_read_server_finished:
1832 return "TLS client read_server_finished";
1833 case state_finish_client_handshake:
1834 return "TLS client finish_client_handshake";
1836 return "TLS client done";
1839 return "TLS client unknown";