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-2007 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 */
110 /* ====================================================================
111 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
112 *
113 * Portions of the attached software ("Contribution") are developed by
114 * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
115 *
116 * The Contribution is licensed pursuant to the OpenSSL open source
117 * license provided above.
118 *
119 * ECC cipher suite support in OpenSSL originally written by
120 * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
121 *
122 */
123 /* ====================================================================
124 * Copyright 2005 Nokia. All rights reserved.
125 *
126 * The portions of the attached software ("Contribution") is developed by
127 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
128 * license.
129 *
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.
133 *
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.
137 *
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.
142 *
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
147 * OTHERWISE.
148 */
149
150 #include <openssl/ssl.h>
151
152 #include <assert.h>
153 #include <limits.h>
154 #include <string.h>
155
156 #include <utility>
157
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>
169 #include <openssl/sha.h>
170
171 #include "../crypto/internal.h"
172 #include "internal.h"
173
174
175 BSSL_NAMESPACE_BEGIN
176
177 enum ssl_client_hs_state_t {
178 state_start_connect = 0,
179 state_enter_early_data,
180 state_early_reverify_server_certificate,
181 state_read_hello_verify_request,
182 state_read_server_hello,
183 state_tls13,
184 state_read_server_certificate,
185 state_read_certificate_status,
186 state_verify_server_certificate,
187 state_reverify_server_certificate,
188 state_read_server_key_exchange,
189 state_read_certificate_request,
190 state_read_server_hello_done,
191 state_send_client_certificate,
192 state_send_client_key_exchange,
193 state_send_client_certificate_verify,
194 state_send_client_finished,
195 state_finish_flight,
196 state_read_session_ticket,
197 state_process_change_cipher_spec,
198 state_read_server_finished,
199 state_finish_client_handshake,
200 state_done,
201 };
202
203 // ssl_get_client_disabled sets |*out_mask_a| and |*out_mask_k| to masks of
204 // disabled algorithms.
ssl_get_client_disabled(SSL_HANDSHAKE * hs,uint32_t * out_mask_a,uint32_t * out_mask_k)205 static void ssl_get_client_disabled(SSL_HANDSHAKE *hs, uint32_t *out_mask_a,
206 uint32_t *out_mask_k) {
207 *out_mask_a = 0;
208 *out_mask_k = 0;
209
210 // PSK requires a client callback.
211 if (hs->config->psk_client_callback == NULL) {
212 *out_mask_a |= SSL_aPSK;
213 *out_mask_k |= SSL_kPSK;
214 }
215 }
216
ssl_write_client_cipher_list(SSL_HANDSHAKE * hs,CBB * out)217 static bool ssl_write_client_cipher_list(SSL_HANDSHAKE *hs, CBB *out) {
218 SSL *const ssl = hs->ssl;
219 uint32_t mask_a, mask_k;
220 ssl_get_client_disabled(hs, &mask_a, &mask_k);
221
222 CBB child;
223 if (!CBB_add_u16_length_prefixed(out, &child)) {
224 return false;
225 }
226
227 // Add a fake cipher suite. See draft-davidben-tls-grease-01.
228 if (ssl->ctx->grease_enabled &&
229 !CBB_add_u16(&child, ssl_get_grease_value(hs, ssl_grease_cipher))) {
230 return false;
231 }
232
233 // Add TLS 1.3 ciphers. Order ChaCha20-Poly1305 relative to AES-GCM based on
234 // hardware support.
235 if (hs->max_version >= TLS1_3_VERSION) {
236 if (!EVP_has_aes_hardware() &&
237 !CBB_add_u16(&child, TLS1_CK_CHACHA20_POLY1305_SHA256 & 0xffff)) {
238 return false;
239 }
240 if (!CBB_add_u16(&child, TLS1_CK_AES_128_GCM_SHA256 & 0xffff) ||
241 !CBB_add_u16(&child, TLS1_CK_AES_256_GCM_SHA384 & 0xffff)) {
242 return false;
243 }
244 if (EVP_has_aes_hardware() &&
245 !CBB_add_u16(&child, TLS1_CK_CHACHA20_POLY1305_SHA256 & 0xffff)) {
246 return false;
247 }
248 }
249
250 if (hs->min_version < TLS1_3_VERSION) {
251 bool any_enabled = false;
252 for (const SSL_CIPHER *cipher : SSL_get_ciphers(ssl)) {
253 // Skip disabled ciphers
254 if ((cipher->algorithm_mkey & mask_k) ||
255 (cipher->algorithm_auth & mask_a)) {
256 continue;
257 }
258 if (SSL_CIPHER_get_min_version(cipher) > hs->max_version ||
259 SSL_CIPHER_get_max_version(cipher) < hs->min_version) {
260 continue;
261 }
262 any_enabled = true;
263 if (!CBB_add_u16(&child, ssl_cipher_get_value(cipher))) {
264 return false;
265 }
266 }
267
268 // If all ciphers were disabled, return the error to the caller.
269 if (!any_enabled && hs->max_version < TLS1_3_VERSION) {
270 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CIPHERS_AVAILABLE);
271 return false;
272 }
273 }
274
275 if (ssl->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
276 if (!CBB_add_u16(&child, SSL3_CK_FALLBACK_SCSV & 0xffff)) {
277 return false;
278 }
279 }
280
281 return CBB_flush(out);
282 }
283
ssl_write_client_hello(SSL_HANDSHAKE * hs)284 bool ssl_write_client_hello(SSL_HANDSHAKE *hs) {
285 SSL *const ssl = hs->ssl;
286 ScopedCBB cbb;
287 CBB body;
288 if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_CLIENT_HELLO)) {
289 return false;
290 }
291
292 CBB child;
293 if (!CBB_add_u16(&body, hs->client_version) ||
294 !CBB_add_bytes(&body, ssl->s3->client_random, SSL3_RANDOM_SIZE) ||
295 !CBB_add_u8_length_prefixed(&body, &child)) {
296 return false;
297 }
298
299 // Do not send a session ID on renegotiation.
300 if (!ssl->s3->initial_handshake_complete &&
301 !CBB_add_bytes(&child, hs->session_id, hs->session_id_len)) {
302 return false;
303 }
304
305 if (SSL_is_dtls(ssl)) {
306 if (!CBB_add_u8_length_prefixed(&body, &child) ||
307 !CBB_add_bytes(&child, ssl->d1->cookie, ssl->d1->cookie_len)) {
308 return false;
309 }
310 }
311
312 size_t header_len =
313 SSL_is_dtls(ssl) ? DTLS1_HM_HEADER_LENGTH : SSL3_HM_HEADER_LENGTH;
314 if (!ssl_write_client_cipher_list(hs, &body) ||
315 !CBB_add_u8(&body, 1 /* one compression method */) ||
316 !CBB_add_u8(&body, 0 /* null compression */) ||
317 !ssl_add_clienthello_tlsext(hs, &body, header_len + CBB_len(&body))) {
318 return false;
319 }
320
321 Array<uint8_t> msg;
322 if (!ssl->method->finish_message(ssl, cbb.get(), &msg)) {
323 return false;
324 }
325
326 // Now that the length prefixes have been computed, fill in the placeholder
327 // PSK binder.
328 if (hs->needs_psk_binder &&
329 !tls13_write_psk_binder(hs, msg.data(), msg.size())) {
330 return false;
331 }
332
333 return ssl->method->add_message(ssl, std::move(msg));
334 }
335
parse_supported_versions(SSL_HANDSHAKE * hs,uint16_t * version,const CBS * in)336 static bool parse_supported_versions(SSL_HANDSHAKE *hs, uint16_t *version,
337 const CBS *in) {
338 // If the outer version is not TLS 1.2, or there is no extensions block, use
339 // the outer version.
340 if (*version != TLS1_2_VERSION || CBS_len(in) == 0) {
341 return true;
342 }
343
344 SSL *const ssl = hs->ssl;
345 CBS copy = *in, extensions;
346 if (!CBS_get_u16_length_prefixed(©, &extensions) ||
347 CBS_len(©) != 0) {
348 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
349 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
350 return false;
351 }
352
353 bool have_supported_versions;
354 CBS supported_versions;
355 const SSL_EXTENSION_TYPE ext_types[] = {
356 {TLSEXT_TYPE_supported_versions, &have_supported_versions,
357 &supported_versions},
358 };
359
360 uint8_t alert = SSL_AD_DECODE_ERROR;
361 if (!ssl_parse_extensions(&extensions, &alert, ext_types,
362 OPENSSL_ARRAY_SIZE(ext_types),
363 1 /* ignore unknown */)) {
364 ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
365 return false;
366 }
367
368 // Override the outer version with the extension, if present.
369 if (have_supported_versions &&
370 (!CBS_get_u16(&supported_versions, version) ||
371 CBS_len(&supported_versions) != 0)) {
372 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
373 return false;
374 }
375
376 return true;
377 }
378
do_start_connect(SSL_HANDSHAKE * hs)379 static enum ssl_hs_wait_t do_start_connect(SSL_HANDSHAKE *hs) {
380 SSL *const ssl = hs->ssl;
381
382 ssl_do_info_callback(ssl, SSL_CB_HANDSHAKE_START, 1);
383 // |session_reused| must be reset in case this is a renegotiation.
384 ssl->s3->session_reused = false;
385
386 // Freeze the version range.
387 if (!ssl_get_version_range(hs, &hs->min_version, &hs->max_version)) {
388 return ssl_hs_error;
389 }
390
391 // Always advertise the ClientHello version from the original maximum version,
392 // even on renegotiation. The static RSA key exchange uses this field, and
393 // some servers fail when it changes across handshakes.
394 if (SSL_is_dtls(hs->ssl)) {
395 hs->client_version =
396 hs->max_version >= TLS1_2_VERSION ? DTLS1_2_VERSION : DTLS1_VERSION;
397 } else {
398 hs->client_version =
399 hs->max_version >= TLS1_2_VERSION ? TLS1_2_VERSION : hs->max_version;
400 }
401
402 // If the configured session has expired or was created at a disabled
403 // version, drop it.
404 if (ssl->session != NULL) {
405 if (ssl->session->is_server ||
406 !ssl_supports_version(hs, ssl->session->ssl_version) ||
407 (ssl->session->session_id_length == 0 &&
408 ssl->session->ticket.empty()) ||
409 ssl->session->not_resumable ||
410 !ssl_session_is_time_valid(ssl, ssl->session.get())) {
411 ssl_set_session(ssl, NULL);
412 }
413 }
414
415 if (!RAND_bytes(ssl->s3->client_random, sizeof(ssl->s3->client_random))) {
416 return ssl_hs_error;
417 }
418
419 if (ssl->session != nullptr &&
420 !ssl->s3->initial_handshake_complete &&
421 ssl->session->session_id_length > 0) {
422 hs->session_id_len = ssl->session->session_id_length;
423 OPENSSL_memcpy(hs->session_id, ssl->session->session_id,
424 hs->session_id_len);
425 } else if (hs->max_version >= TLS1_3_VERSION) {
426 // Initialize a random session ID.
427 hs->session_id_len = sizeof(hs->session_id);
428 if (!RAND_bytes(hs->session_id, hs->session_id_len)) {
429 return ssl_hs_error;
430 }
431 }
432
433 if (!ssl_write_client_hello(hs)) {
434 return ssl_hs_error;
435 }
436
437 hs->state = state_enter_early_data;
438 return ssl_hs_flush;
439 }
440
do_enter_early_data(SSL_HANDSHAKE * hs)441 static enum ssl_hs_wait_t do_enter_early_data(SSL_HANDSHAKE *hs) {
442 SSL *const ssl = hs->ssl;
443
444 if (SSL_is_dtls(ssl)) {
445 hs->state = state_read_hello_verify_request;
446 return ssl_hs_ok;
447 }
448
449 if (!hs->early_data_offered) {
450 hs->state = state_read_server_hello;
451 return ssl_hs_ok;
452 }
453
454 ssl->s3->aead_write_ctx->SetVersionIfNullCipher(ssl->session->ssl_version);
455 if (!ssl->method->add_change_cipher_spec(ssl)) {
456 return ssl_hs_error;
457 }
458
459 if (!tls13_init_early_key_schedule(hs, ssl->session->master_key,
460 ssl->session->master_key_length) ||
461 !tls13_derive_early_secrets(hs) ||
462 !tls13_set_traffic_key(ssl, ssl_encryption_early_data, evp_aead_seal,
463 hs->early_traffic_secret, hs->hash_len)) {
464 return ssl_hs_error;
465 }
466
467 // Stash the early data session, so connection properties may be queried out
468 // of it.
469 hs->early_session = UpRef(ssl->session);
470 hs->state = state_early_reverify_server_certificate;
471 return ssl_hs_ok;
472 }
473
do_early_reverify_server_certificate(SSL_HANDSHAKE * hs)474 static enum ssl_hs_wait_t do_early_reverify_server_certificate(SSL_HANDSHAKE *hs) {
475 if (hs->ssl->ctx->reverify_on_resume) {
476 switch (ssl_reverify_peer_cert(hs)) {
477 case ssl_verify_ok:
478 break;
479 case ssl_verify_invalid:
480 return ssl_hs_error;
481 case ssl_verify_retry:
482 hs->state = state_early_reverify_server_certificate;
483 return ssl_hs_certificate_verify;
484 }
485 }
486
487 hs->in_early_data = true;
488 hs->can_early_write = true;
489 hs->state = state_read_server_hello;
490 return ssl_hs_early_return;
491 }
492
do_read_hello_verify_request(SSL_HANDSHAKE * hs)493 static enum ssl_hs_wait_t do_read_hello_verify_request(SSL_HANDSHAKE *hs) {
494 SSL *const ssl = hs->ssl;
495
496 assert(SSL_is_dtls(ssl));
497
498 SSLMessage msg;
499 if (!ssl->method->get_message(ssl, &msg)) {
500 return ssl_hs_read_message;
501 }
502
503 if (msg.type != DTLS1_MT_HELLO_VERIFY_REQUEST) {
504 hs->state = state_read_server_hello;
505 return ssl_hs_ok;
506 }
507
508 CBS hello_verify_request = msg.body, cookie;
509 uint16_t server_version;
510 if (!CBS_get_u16(&hello_verify_request, &server_version) ||
511 !CBS_get_u8_length_prefixed(&hello_verify_request, &cookie) ||
512 CBS_len(&cookie) > sizeof(ssl->d1->cookie) ||
513 CBS_len(&hello_verify_request) != 0) {
514 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
515 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
516 return ssl_hs_error;
517 }
518
519 OPENSSL_memcpy(ssl->d1->cookie, CBS_data(&cookie), CBS_len(&cookie));
520 ssl->d1->cookie_len = CBS_len(&cookie);
521
522 ssl->method->next_message(ssl);
523
524 // DTLS resets the handshake buffer after HelloVerifyRequest.
525 if (!hs->transcript.Init()) {
526 return ssl_hs_error;
527 }
528
529 if (!ssl_write_client_hello(hs)) {
530 return ssl_hs_error;
531 }
532
533 hs->state = state_read_server_hello;
534 return ssl_hs_flush;
535 }
536
do_read_server_hello(SSL_HANDSHAKE * hs)537 static enum ssl_hs_wait_t do_read_server_hello(SSL_HANDSHAKE *hs) {
538 SSL *const ssl = hs->ssl;
539 SSLMessage msg;
540 if (!ssl->method->get_message(ssl, &msg)) {
541 return ssl_hs_read_server_hello;
542 }
543
544 if (!ssl_check_message_type(ssl, msg, SSL3_MT_SERVER_HELLO)) {
545 return ssl_hs_error;
546 }
547
548 CBS server_hello = msg.body, server_random, session_id;
549 uint16_t server_version, cipher_suite;
550 uint8_t compression_method;
551 if (!CBS_get_u16(&server_hello, &server_version) ||
552 !CBS_get_bytes(&server_hello, &server_random, SSL3_RANDOM_SIZE) ||
553 !CBS_get_u8_length_prefixed(&server_hello, &session_id) ||
554 CBS_len(&session_id) > SSL3_SESSION_ID_SIZE ||
555 !CBS_get_u16(&server_hello, &cipher_suite) ||
556 !CBS_get_u8(&server_hello, &compression_method)) {
557 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
558 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
559 return ssl_hs_error;
560 }
561
562 // Use the supported_versions extension if applicable.
563 if (!parse_supported_versions(hs, &server_version, &server_hello)) {
564 return ssl_hs_error;
565 }
566
567 if (!ssl_supports_version(hs, server_version)) {
568 OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL);
569 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
570 return ssl_hs_error;
571 }
572
573 assert(ssl->s3->have_version == ssl->s3->initial_handshake_complete);
574 if (!ssl->s3->have_version) {
575 ssl->version = server_version;
576 // At this point, the connection's version is known and ssl->version is
577 // fixed. Begin enforcing the record-layer version.
578 ssl->s3->have_version = true;
579 ssl->s3->aead_write_ctx->SetVersionIfNullCipher(ssl->version);
580 } else if (server_version != ssl->version) {
581 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION);
582 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
583 return ssl_hs_error;
584 }
585
586 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
587 hs->state = state_tls13;
588 return ssl_hs_ok;
589 }
590
591 // Clear some TLS 1.3 state that no longer needs to be retained.
592 hs->key_shares[0].reset();
593 hs->key_shares[1].reset();
594 hs->key_share_bytes.Reset();
595
596 // A TLS 1.2 server would not know to skip the early data we offered. Report
597 // an error code sooner. The caller may use this error code to implement the
598 // fallback described in RFC 8446 appendix D.3.
599 if (hs->early_data_offered) {
600 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_VERSION_ON_EARLY_DATA);
601 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
602 return ssl_hs_error;
603 }
604
605 // Copy over the server random.
606 OPENSSL_memcpy(ssl->s3->server_random, CBS_data(&server_random),
607 SSL3_RANDOM_SIZE);
608
609 // Enforce the TLS 1.3 anti-downgrade feature.
610 if (!ssl->s3->initial_handshake_complete &&
611 ssl_supports_version(hs, TLS1_3_VERSION)) {
612 static_assert(
613 sizeof(kTLS12DowngradeRandom) == sizeof(kTLS13DowngradeRandom),
614 "downgrade signals have different size");
615 static_assert(
616 sizeof(kJDK11DowngradeRandom) == sizeof(kTLS13DowngradeRandom),
617 "downgrade signals have different size");
618 auto suffix =
619 MakeConstSpan(ssl->s3->server_random, sizeof(ssl->s3->server_random))
620 .subspan(SSL3_RANDOM_SIZE - sizeof(kTLS13DowngradeRandom));
621 if (suffix == kTLS12DowngradeRandom || suffix == kTLS13DowngradeRandom ||
622 suffix == kJDK11DowngradeRandom) {
623 ssl->s3->tls13_downgrade = true;
624 if (!hs->config->ignore_tls13_downgrade) {
625 OPENSSL_PUT_ERROR(SSL, SSL_R_TLS13_DOWNGRADE);
626 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
627 return ssl_hs_error;
628 }
629 }
630 }
631
632 if (!ssl->s3->initial_handshake_complete && ssl->session != nullptr &&
633 ssl->session->session_id_length != 0 &&
634 CBS_mem_equal(&session_id, ssl->session->session_id,
635 ssl->session->session_id_length)) {
636 ssl->s3->session_reused = true;
637 } else {
638 // The server may also have echoed back the TLS 1.3 compatibility mode
639 // session ID. As we know this is not a session the server knows about, any
640 // server resuming it is in error. Reject the first connection
641 // deterministicly, rather than installing an invalid session into the
642 // session cache. https://crbug.com/796910
643 if (hs->session_id_len != 0 &&
644 CBS_mem_equal(&session_id, hs->session_id, hs->session_id_len)) {
645 OPENSSL_PUT_ERROR(SSL, SSL_R_SERVER_ECHOED_INVALID_SESSION_ID);
646 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
647 return ssl_hs_error;
648 }
649
650 // The session wasn't resumed. Create a fresh SSL_SESSION to
651 // fill out.
652 ssl_set_session(ssl, NULL);
653 if (!ssl_get_new_session(hs, 0 /* client */)) {
654 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
655 return ssl_hs_error;
656 }
657 // Note: session_id could be empty.
658 hs->new_session->session_id_length = CBS_len(&session_id);
659 OPENSSL_memcpy(hs->new_session->session_id, CBS_data(&session_id),
660 CBS_len(&session_id));
661 }
662
663 const SSL_CIPHER *cipher = SSL_get_cipher_by_value(cipher_suite);
664 if (cipher == NULL) {
665 // unknown cipher
666 OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CIPHER_RETURNED);
667 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
668 return ssl_hs_error;
669 }
670
671 // The cipher must be allowed in the selected version and enabled.
672 uint32_t mask_a, mask_k;
673 ssl_get_client_disabled(hs, &mask_a, &mask_k);
674 if ((cipher->algorithm_mkey & mask_k) || (cipher->algorithm_auth & mask_a) ||
675 SSL_CIPHER_get_min_version(cipher) > ssl_protocol_version(ssl) ||
676 SSL_CIPHER_get_max_version(cipher) < ssl_protocol_version(ssl) ||
677 !sk_SSL_CIPHER_find(SSL_get_ciphers(ssl), NULL, cipher)) {
678 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
679 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
680 return ssl_hs_error;
681 }
682
683 if (ssl->session != NULL) {
684 if (ssl->session->ssl_version != ssl->version) {
685 OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_VERSION_NOT_RETURNED);
686 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
687 return ssl_hs_error;
688 }
689 if (ssl->session->cipher != cipher) {
690 OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
691 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
692 return ssl_hs_error;
693 }
694 if (!ssl_session_is_context_valid(hs, ssl->session.get())) {
695 // This is actually a client application bug.
696 OPENSSL_PUT_ERROR(SSL,
697 SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
698 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
699 return ssl_hs_error;
700 }
701 } else {
702 hs->new_session->cipher = cipher;
703 }
704 hs->new_cipher = cipher;
705
706 // Now that the cipher is known, initialize the handshake hash and hash the
707 // ServerHello.
708 if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher) ||
709 !ssl_hash_message(hs, msg)) {
710 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
711 return ssl_hs_error;
712 }
713
714 // If doing a full handshake, the server may request a client certificate
715 // which requires hashing the handshake transcript. Otherwise, the handshake
716 // buffer may be released.
717 if (ssl->session != NULL ||
718 !ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
719 hs->transcript.FreeBuffer();
720 }
721
722 // Only the NULL compression algorithm is supported.
723 if (compression_method != 0) {
724 OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
725 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
726 return ssl_hs_error;
727 }
728
729 // TLS extensions
730 if (!ssl_parse_serverhello_tlsext(hs, &server_hello)) {
731 OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
732 return ssl_hs_error;
733 }
734
735 // There should be nothing left over in the record.
736 if (CBS_len(&server_hello) != 0) {
737 // wrong packet length
738 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
739 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
740 return ssl_hs_error;
741 }
742
743 if (ssl->session != NULL &&
744 hs->extended_master_secret != ssl->session->extended_master_secret) {
745 if (ssl->session->extended_master_secret) {
746 OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
747 } else {
748 OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_NON_EMS_SESSION_WITH_EMS_EXTENSION);
749 }
750 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
751 return ssl_hs_error;
752 }
753
754 if (ssl->s3->token_binding_negotiated &&
755 (!hs->extended_master_secret || !ssl->s3->send_connection_binding)) {
756 OPENSSL_PUT_ERROR(SSL, SSL_R_NEGOTIATED_TB_WITHOUT_EMS_OR_RI);
757 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_EXTENSION);
758 return ssl_hs_error;
759 }
760
761 ssl->method->next_message(ssl);
762
763 if (ssl->session != NULL) {
764 if (ssl->ctx->reverify_on_resume &&
765 ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
766 hs->state = state_reverify_server_certificate;
767 } else {
768 hs->state = state_read_session_ticket;
769 }
770 return ssl_hs_ok;
771 }
772
773 hs->state = state_read_server_certificate;
774 return ssl_hs_ok;
775 }
776
do_tls13(SSL_HANDSHAKE * hs)777 static enum ssl_hs_wait_t do_tls13(SSL_HANDSHAKE *hs) {
778 enum ssl_hs_wait_t wait = tls13_client_handshake(hs);
779 if (wait == ssl_hs_ok) {
780 hs->state = state_finish_client_handshake;
781 return ssl_hs_ok;
782 }
783
784 return wait;
785 }
786
do_read_server_certificate(SSL_HANDSHAKE * hs)787 static enum ssl_hs_wait_t do_read_server_certificate(SSL_HANDSHAKE *hs) {
788 SSL *const ssl = hs->ssl;
789
790 if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
791 hs->state = state_read_certificate_status;
792 return ssl_hs_ok;
793 }
794
795 SSLMessage msg;
796 if (!ssl->method->get_message(ssl, &msg)) {
797 return ssl_hs_read_message;
798 }
799
800 if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE) ||
801 !ssl_hash_message(hs, msg)) {
802 return ssl_hs_error;
803 }
804
805 CBS body = msg.body;
806 uint8_t alert = SSL_AD_DECODE_ERROR;
807 if (!ssl_parse_cert_chain(&alert, &hs->new_session->certs, &hs->peer_pubkey,
808 NULL, &body, ssl->ctx->pool)) {
809 ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
810 return ssl_hs_error;
811 }
812
813 if (sk_CRYPTO_BUFFER_num(hs->new_session->certs.get()) == 0 ||
814 CBS_len(&body) != 0 ||
815 !ssl->ctx->x509_method->session_cache_objects(hs->new_session.get())) {
816 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
817 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
818 return ssl_hs_error;
819 }
820
821 if (!ssl_check_leaf_certificate(
822 hs, hs->peer_pubkey.get(),
823 sk_CRYPTO_BUFFER_value(hs->new_session->certs.get(), 0))) {
824 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
825 return ssl_hs_error;
826 }
827
828 ssl->method->next_message(ssl);
829
830 hs->state = state_read_certificate_status;
831 return ssl_hs_ok;
832 }
833
do_read_certificate_status(SSL_HANDSHAKE * hs)834 static enum ssl_hs_wait_t do_read_certificate_status(SSL_HANDSHAKE *hs) {
835 SSL *const ssl = hs->ssl;
836
837 if (!hs->certificate_status_expected) {
838 hs->state = state_verify_server_certificate;
839 return ssl_hs_ok;
840 }
841
842 SSLMessage msg;
843 if (!ssl->method->get_message(ssl, &msg)) {
844 return ssl_hs_read_message;
845 }
846
847 if (msg.type != SSL3_MT_CERTIFICATE_STATUS) {
848 // A server may send status_request in ServerHello and then change its mind
849 // about sending CertificateStatus.
850 hs->state = state_verify_server_certificate;
851 return ssl_hs_ok;
852 }
853
854 if (!ssl_hash_message(hs, msg)) {
855 return ssl_hs_error;
856 }
857
858 CBS certificate_status = msg.body, ocsp_response;
859 uint8_t status_type;
860 if (!CBS_get_u8(&certificate_status, &status_type) ||
861 status_type != TLSEXT_STATUSTYPE_ocsp ||
862 !CBS_get_u24_length_prefixed(&certificate_status, &ocsp_response) ||
863 CBS_len(&ocsp_response) == 0 ||
864 CBS_len(&certificate_status) != 0) {
865 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
866 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
867 return ssl_hs_error;
868 }
869
870 hs->new_session->ocsp_response.reset(
871 CRYPTO_BUFFER_new_from_CBS(&ocsp_response, ssl->ctx->pool));
872 if (hs->new_session->ocsp_response == nullptr) {
873 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
874 return ssl_hs_error;
875 }
876
877 ssl->method->next_message(ssl);
878
879 hs->state = state_verify_server_certificate;
880 return ssl_hs_ok;
881 }
882
do_verify_server_certificate(SSL_HANDSHAKE * hs)883 static enum ssl_hs_wait_t do_verify_server_certificate(SSL_HANDSHAKE *hs) {
884 if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
885 hs->state = state_read_server_key_exchange;
886 return ssl_hs_ok;
887 }
888
889 switch (ssl_verify_peer_cert(hs)) {
890 case ssl_verify_ok:
891 break;
892 case ssl_verify_invalid:
893 return ssl_hs_error;
894 case ssl_verify_retry:
895 hs->state = state_verify_server_certificate;
896 return ssl_hs_certificate_verify;
897 }
898
899 hs->state = state_read_server_key_exchange;
900 return ssl_hs_ok;
901 }
902
do_reverify_server_certificate(SSL_HANDSHAKE * hs)903 static enum ssl_hs_wait_t do_reverify_server_certificate(SSL_HANDSHAKE *hs) {
904 assert(hs->ssl->ctx->reverify_on_resume);
905
906 switch (ssl_reverify_peer_cert(hs)) {
907 case ssl_verify_ok:
908 break;
909 case ssl_verify_invalid:
910 return ssl_hs_error;
911 case ssl_verify_retry:
912 hs->state = state_reverify_server_certificate;
913 return ssl_hs_certificate_verify;
914 }
915
916 hs->state = state_read_session_ticket;
917 return ssl_hs_ok;
918 }
919
do_read_server_key_exchange(SSL_HANDSHAKE * hs)920 static enum ssl_hs_wait_t do_read_server_key_exchange(SSL_HANDSHAKE *hs) {
921 SSL *const ssl = hs->ssl;
922 SSLMessage msg;
923 if (!ssl->method->get_message(ssl, &msg)) {
924 return ssl_hs_read_message;
925 }
926
927 if (msg.type != SSL3_MT_SERVER_KEY_EXCHANGE) {
928 // Some ciphers (pure PSK) have an optional ServerKeyExchange message.
929 if (ssl_cipher_requires_server_key_exchange(hs->new_cipher)) {
930 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
931 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
932 return ssl_hs_error;
933 }
934
935 hs->state = state_read_certificate_request;
936 return ssl_hs_ok;
937 }
938
939 if (!ssl_hash_message(hs, msg)) {
940 return ssl_hs_error;
941 }
942
943 uint32_t alg_k = hs->new_cipher->algorithm_mkey;
944 uint32_t alg_a = hs->new_cipher->algorithm_auth;
945 CBS server_key_exchange = msg.body;
946 if (alg_a & SSL_aPSK) {
947 CBS psk_identity_hint;
948
949 // Each of the PSK key exchanges begins with a psk_identity_hint.
950 if (!CBS_get_u16_length_prefixed(&server_key_exchange,
951 &psk_identity_hint)) {
952 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
953 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
954 return ssl_hs_error;
955 }
956
957 // Store the PSK identity hint for the ClientKeyExchange. Assume that the
958 // maximum length of a PSK identity hint can be as long as the maximum
959 // length of a PSK identity. Also do not allow NULL characters; identities
960 // are saved as C strings.
961 //
962 // TODO(davidben): Should invalid hints be ignored? It's a hint rather than
963 // a specific identity.
964 if (CBS_len(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN ||
965 CBS_contains_zero_byte(&psk_identity_hint)) {
966 OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
967 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
968 return ssl_hs_error;
969 }
970
971 // Save non-empty identity hints as a C string. Empty identity hints we
972 // treat as missing. Plain PSK makes it possible to send either no hint
973 // (omit ServerKeyExchange) or an empty hint, while ECDHE_PSK can only spell
974 // empty hint. Having different capabilities is odd, so we interpret empty
975 // and missing as identical.
976 char *raw = nullptr;
977 if (CBS_len(&psk_identity_hint) != 0 &&
978 !CBS_strdup(&psk_identity_hint, &raw)) {
979 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
980 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
981 return ssl_hs_error;
982 }
983 hs->peer_psk_identity_hint.reset(raw);
984 }
985
986 if (alg_k & SSL_kECDHE) {
987 // Parse the server parameters.
988 uint8_t group_type;
989 uint16_t group_id;
990 CBS point;
991 if (!CBS_get_u8(&server_key_exchange, &group_type) ||
992 group_type != NAMED_CURVE_TYPE ||
993 !CBS_get_u16(&server_key_exchange, &group_id) ||
994 !CBS_get_u8_length_prefixed(&server_key_exchange, &point)) {
995 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
996 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
997 return ssl_hs_error;
998 }
999 hs->new_session->group_id = group_id;
1000
1001 // Ensure the group is consistent with preferences.
1002 if (!tls1_check_group_id(hs, group_id)) {
1003 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
1004 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
1005 return ssl_hs_error;
1006 }
1007
1008 // Initialize ECDH and save the peer public key for later.
1009 hs->key_shares[0] = SSLKeyShare::Create(group_id);
1010 if (!hs->key_shares[0] ||
1011 !hs->peer_key.CopyFrom(point)) {
1012 return ssl_hs_error;
1013 }
1014 } else if (!(alg_k & SSL_kPSK)) {
1015 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
1016 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1017 return ssl_hs_error;
1018 }
1019
1020 // At this point, |server_key_exchange| contains the signature, if any, while
1021 // |msg.body| contains the entire message. From that, derive a CBS containing
1022 // just the parameter.
1023 CBS parameter;
1024 CBS_init(¶meter, CBS_data(&msg.body),
1025 CBS_len(&msg.body) - CBS_len(&server_key_exchange));
1026
1027 // ServerKeyExchange should be signed by the server's public key.
1028 if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1029 uint16_t signature_algorithm = 0;
1030 if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1031 if (!CBS_get_u16(&server_key_exchange, &signature_algorithm)) {
1032 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1033 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1034 return ssl_hs_error;
1035 }
1036 uint8_t alert = SSL_AD_DECODE_ERROR;
1037 if (!tls12_check_peer_sigalg(ssl, &alert, signature_algorithm)) {
1038 ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1039 return ssl_hs_error;
1040 }
1041 hs->new_session->peer_signature_algorithm = signature_algorithm;
1042 } else if (!tls1_get_legacy_signature_algorithm(&signature_algorithm,
1043 hs->peer_pubkey.get())) {
1044 OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
1045 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_CERTIFICATE);
1046 return ssl_hs_error;
1047 }
1048
1049 // The last field in |server_key_exchange| is the signature.
1050 CBS signature;
1051 if (!CBS_get_u16_length_prefixed(&server_key_exchange, &signature) ||
1052 CBS_len(&server_key_exchange) != 0) {
1053 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1054 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1055 return ssl_hs_error;
1056 }
1057
1058 ScopedCBB transcript;
1059 Array<uint8_t> transcript_data;
1060 if (!CBB_init(transcript.get(),
1061 2 * SSL3_RANDOM_SIZE + CBS_len(¶meter)) ||
1062 !CBB_add_bytes(transcript.get(), ssl->s3->client_random,
1063 SSL3_RANDOM_SIZE) ||
1064 !CBB_add_bytes(transcript.get(), ssl->s3->server_random,
1065 SSL3_RANDOM_SIZE) ||
1066 !CBB_add_bytes(transcript.get(), CBS_data(¶meter),
1067 CBS_len(¶meter)) ||
1068 !CBBFinishArray(transcript.get(), &transcript_data)) {
1069 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1070 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1071 return ssl_hs_error;
1072 }
1073
1074 bool sig_ok = ssl_public_key_verify(ssl, signature, signature_algorithm,
1075 hs->peer_pubkey.get(), transcript_data);
1076 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
1077 sig_ok = true;
1078 ERR_clear_error();
1079 #endif
1080 if (!sig_ok) {
1081 // bad signature
1082 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
1083 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
1084 return ssl_hs_error;
1085 }
1086 } else {
1087 // PSK ciphers are the only supported certificate-less ciphers.
1088 assert(alg_a == SSL_aPSK);
1089
1090 if (CBS_len(&server_key_exchange) > 0) {
1091 OPENSSL_PUT_ERROR(SSL, SSL_R_EXTRA_DATA_IN_MESSAGE);
1092 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1093 return ssl_hs_error;
1094 }
1095 }
1096
1097 ssl->method->next_message(ssl);
1098 hs->state = state_read_certificate_request;
1099 return ssl_hs_ok;
1100 }
1101
do_read_certificate_request(SSL_HANDSHAKE * hs)1102 static enum ssl_hs_wait_t do_read_certificate_request(SSL_HANDSHAKE *hs) {
1103 SSL *const ssl = hs->ssl;
1104
1105 if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1106 hs->state = state_read_server_hello_done;
1107 return ssl_hs_ok;
1108 }
1109
1110 SSLMessage msg;
1111 if (!ssl->method->get_message(ssl, &msg)) {
1112 return ssl_hs_read_message;
1113 }
1114
1115 if (msg.type == SSL3_MT_SERVER_HELLO_DONE) {
1116 // If we get here we don't need the handshake buffer as we won't be doing
1117 // client auth.
1118 hs->transcript.FreeBuffer();
1119 hs->state = state_read_server_hello_done;
1120 return ssl_hs_ok;
1121 }
1122
1123 if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_REQUEST) ||
1124 !ssl_hash_message(hs, msg)) {
1125 return ssl_hs_error;
1126 }
1127
1128 // Get the certificate types.
1129 CBS body = msg.body, certificate_types;
1130 if (!CBS_get_u8_length_prefixed(&body, &certificate_types)) {
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;
1134 }
1135
1136 if (!hs->certificate_types.CopyFrom(certificate_types)) {
1137 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1138 return ssl_hs_error;
1139 }
1140
1141 if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1142 CBS supported_signature_algorithms;
1143 if (!CBS_get_u16_length_prefixed(&body, &supported_signature_algorithms) ||
1144 !tls1_parse_peer_sigalgs(hs, &supported_signature_algorithms)) {
1145 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1146 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1147 return ssl_hs_error;
1148 }
1149 }
1150
1151 uint8_t alert = SSL_AD_DECODE_ERROR;
1152 UniquePtr<STACK_OF(CRYPTO_BUFFER)> ca_names =
1153 ssl_parse_client_CA_list(ssl, &alert, &body);
1154 if (!ca_names) {
1155 ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1156 return ssl_hs_error;
1157 }
1158
1159 if (CBS_len(&body) != 0) {
1160 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1161 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1162 return ssl_hs_error;
1163 }
1164
1165 hs->cert_request = true;
1166 hs->ca_names = std::move(ca_names);
1167 ssl->ctx->x509_method->hs_flush_cached_ca_names(hs);
1168
1169 ssl->method->next_message(ssl);
1170 hs->state = state_read_server_hello_done;
1171 return ssl_hs_ok;
1172 }
1173
do_read_server_hello_done(SSL_HANDSHAKE * hs)1174 static enum ssl_hs_wait_t do_read_server_hello_done(SSL_HANDSHAKE *hs) {
1175 SSL *const ssl = hs->ssl;
1176 SSLMessage msg;
1177 if (!ssl->method->get_message(ssl, &msg)) {
1178 return ssl_hs_read_message;
1179 }
1180
1181 if (!ssl_check_message_type(ssl, msg, SSL3_MT_SERVER_HELLO_DONE) ||
1182 !ssl_hash_message(hs, msg)) {
1183 return ssl_hs_error;
1184 }
1185
1186 // ServerHelloDone is empty.
1187 if (CBS_len(&msg.body) != 0) {
1188 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1189 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1190 return ssl_hs_error;
1191 }
1192
1193 ssl->method->next_message(ssl);
1194 hs->state = state_send_client_certificate;
1195 return ssl_hs_ok;
1196 }
1197
do_send_client_certificate(SSL_HANDSHAKE * hs)1198 static enum ssl_hs_wait_t do_send_client_certificate(SSL_HANDSHAKE *hs) {
1199 SSL *const ssl = hs->ssl;
1200
1201 // The peer didn't request a certificate.
1202 if (!hs->cert_request) {
1203 hs->state = state_send_client_key_exchange;
1204 return ssl_hs_ok;
1205 }
1206
1207 // Call cert_cb to update the certificate.
1208 if (hs->config->cert->cert_cb != NULL) {
1209 int rv = hs->config->cert->cert_cb(ssl, hs->config->cert->cert_cb_arg);
1210 if (rv == 0) {
1211 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1212 OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
1213 return ssl_hs_error;
1214 }
1215 if (rv < 0) {
1216 hs->state = state_send_client_certificate;
1217 return ssl_hs_x509_lookup;
1218 }
1219 }
1220
1221 if (!ssl_has_certificate(hs)) {
1222 // Without a client certificate, the handshake buffer may be released.
1223 hs->transcript.FreeBuffer();
1224 }
1225
1226 if (!ssl_on_certificate_selected(hs) ||
1227 !ssl_output_cert_chain(hs)) {
1228 return ssl_hs_error;
1229 }
1230
1231
1232 hs->state = state_send_client_key_exchange;
1233 return ssl_hs_ok;
1234 }
1235
1236 static_assert(sizeof(size_t) >= sizeof(unsigned),
1237 "size_t is smaller than unsigned");
1238
do_send_client_key_exchange(SSL_HANDSHAKE * hs)1239 static enum ssl_hs_wait_t do_send_client_key_exchange(SSL_HANDSHAKE *hs) {
1240 SSL *const ssl = hs->ssl;
1241 ScopedCBB cbb;
1242 CBB body;
1243 if (!ssl->method->init_message(ssl, cbb.get(), &body,
1244 SSL3_MT_CLIENT_KEY_EXCHANGE)) {
1245 return ssl_hs_error;
1246 }
1247
1248 Array<uint8_t> pms;
1249 uint32_t alg_k = hs->new_cipher->algorithm_mkey;
1250 uint32_t alg_a = hs->new_cipher->algorithm_auth;
1251 if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1252 CRYPTO_BUFFER *leaf =
1253 sk_CRYPTO_BUFFER_value(hs->new_session->certs.get(), 0);
1254 CBS leaf_cbs;
1255 CBS_init(&leaf_cbs, CRYPTO_BUFFER_data(leaf), CRYPTO_BUFFER_len(leaf));
1256
1257 // Check the key usage matches the cipher suite. We do this unconditionally
1258 // for non-RSA certificates. In particular, it's needed to distinguish ECDH
1259 // certificates, which we do not support, from ECDSA certificates.
1260 // Historically, we have not checked RSA key usages, so it is controlled by
1261 // a flag for now. See https://crbug.com/795089.
1262 ssl_key_usage_t intended_use = (alg_k & SSL_kRSA)
1263 ? key_usage_encipherment
1264 : key_usage_digital_signature;
1265 if (ssl->config->enforce_rsa_key_usage ||
1266 EVP_PKEY_id(hs->peer_pubkey.get()) != EVP_PKEY_RSA) {
1267 if (!ssl_cert_check_key_usage(&leaf_cbs, intended_use)) {
1268 return ssl_hs_error;
1269 }
1270 }
1271 }
1272
1273 // If using a PSK key exchange, prepare the pre-shared key.
1274 unsigned psk_len = 0;
1275 uint8_t psk[PSK_MAX_PSK_LEN];
1276 if (alg_a & SSL_aPSK) {
1277 if (hs->config->psk_client_callback == NULL) {
1278 OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_NO_CLIENT_CB);
1279 return ssl_hs_error;
1280 }
1281
1282 char identity[PSK_MAX_IDENTITY_LEN + 1];
1283 OPENSSL_memset(identity, 0, sizeof(identity));
1284 psk_len = hs->config->psk_client_callback(
1285 ssl, hs->peer_psk_identity_hint.get(), identity, sizeof(identity), psk,
1286 sizeof(psk));
1287 if (psk_len == 0) {
1288 OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
1289 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1290 return ssl_hs_error;
1291 }
1292 assert(psk_len <= PSK_MAX_PSK_LEN);
1293
1294 hs->new_session->psk_identity.reset(BUF_strdup(identity));
1295 if (hs->new_session->psk_identity == nullptr) {
1296 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1297 return ssl_hs_error;
1298 }
1299
1300 // Write out psk_identity.
1301 CBB child;
1302 if (!CBB_add_u16_length_prefixed(&body, &child) ||
1303 !CBB_add_bytes(&child, (const uint8_t *)identity,
1304 OPENSSL_strnlen(identity, sizeof(identity))) ||
1305 !CBB_flush(&body)) {
1306 return ssl_hs_error;
1307 }
1308 }
1309
1310 // Depending on the key exchange method, compute |pms|.
1311 if (alg_k & SSL_kRSA) {
1312 if (!pms.Init(SSL_MAX_MASTER_KEY_LENGTH)) {
1313 return ssl_hs_error;
1314 }
1315
1316 RSA *rsa = EVP_PKEY_get0_RSA(hs->peer_pubkey.get());
1317 if (rsa == NULL) {
1318 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1319 return ssl_hs_error;
1320 }
1321
1322 pms[0] = hs->client_version >> 8;
1323 pms[1] = hs->client_version & 0xff;
1324 if (!RAND_bytes(&pms[2], SSL_MAX_MASTER_KEY_LENGTH - 2)) {
1325 return ssl_hs_error;
1326 }
1327
1328 CBB enc_pms;
1329 uint8_t *ptr;
1330 size_t enc_pms_len;
1331 if (!CBB_add_u16_length_prefixed(&body, &enc_pms) ||
1332 !CBB_reserve(&enc_pms, &ptr, RSA_size(rsa)) ||
1333 !RSA_encrypt(rsa, &enc_pms_len, ptr, RSA_size(rsa), pms.data(),
1334 pms.size(), RSA_PKCS1_PADDING) ||
1335 !CBB_did_write(&enc_pms, enc_pms_len) ||
1336 !CBB_flush(&body)) {
1337 return ssl_hs_error;
1338 }
1339 } else if (alg_k & SSL_kECDHE) {
1340 // Generate a keypair and serialize the public half.
1341 CBB child;
1342 if (!CBB_add_u8_length_prefixed(&body, &child)) {
1343 return ssl_hs_error;
1344 }
1345
1346 // Compute the premaster.
1347 uint8_t alert = SSL_AD_DECODE_ERROR;
1348 if (!hs->key_shares[0]->Accept(&child, &pms, &alert, hs->peer_key)) {
1349 ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1350 return ssl_hs_error;
1351 }
1352 if (!CBB_flush(&body)) {
1353 return ssl_hs_error;
1354 }
1355
1356 // The key exchange state may now be discarded.
1357 hs->key_shares[0].reset();
1358 hs->key_shares[1].reset();
1359 hs->peer_key.Reset();
1360 } else if (alg_k & SSL_kPSK) {
1361 // For plain PSK, other_secret is a block of 0s with the same length as
1362 // the pre-shared key.
1363 if (!pms.Init(psk_len)) {
1364 return ssl_hs_error;
1365 }
1366 OPENSSL_memset(pms.data(), 0, pms.size());
1367 } else {
1368 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1369 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1370 return ssl_hs_error;
1371 }
1372
1373 // For a PSK cipher suite, other_secret is combined with the pre-shared
1374 // key.
1375 if (alg_a & SSL_aPSK) {
1376 ScopedCBB pms_cbb;
1377 CBB child;
1378 if (!CBB_init(pms_cbb.get(), 2 + psk_len + 2 + pms.size()) ||
1379 !CBB_add_u16_length_prefixed(pms_cbb.get(), &child) ||
1380 !CBB_add_bytes(&child, pms.data(), pms.size()) ||
1381 !CBB_add_u16_length_prefixed(pms_cbb.get(), &child) ||
1382 !CBB_add_bytes(&child, psk, psk_len) ||
1383 !CBBFinishArray(pms_cbb.get(), &pms)) {
1384 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1385 return ssl_hs_error;
1386 }
1387 }
1388
1389 // The message must be added to the finished hash before calculating the
1390 // master secret.
1391 if (!ssl_add_message_cbb(ssl, cbb.get())) {
1392 return ssl_hs_error;
1393 }
1394
1395 hs->new_session->master_key_length =
1396 tls1_generate_master_secret(hs, hs->new_session->master_key, pms);
1397 if (hs->new_session->master_key_length == 0) {
1398 return ssl_hs_error;
1399 }
1400 hs->new_session->extended_master_secret = hs->extended_master_secret;
1401
1402 hs->state = state_send_client_certificate_verify;
1403 return ssl_hs_ok;
1404 }
1405
do_send_client_certificate_verify(SSL_HANDSHAKE * hs)1406 static enum ssl_hs_wait_t do_send_client_certificate_verify(SSL_HANDSHAKE *hs) {
1407 SSL *const ssl = hs->ssl;
1408
1409 if (!hs->cert_request || !ssl_has_certificate(hs)) {
1410 hs->state = state_send_client_finished;
1411 return ssl_hs_ok;
1412 }
1413
1414 assert(ssl_has_private_key(hs));
1415 ScopedCBB cbb;
1416 CBB body, child;
1417 if (!ssl->method->init_message(ssl, cbb.get(), &body,
1418 SSL3_MT_CERTIFICATE_VERIFY)) {
1419 return ssl_hs_error;
1420 }
1421
1422 uint16_t signature_algorithm;
1423 if (!tls1_choose_signature_algorithm(hs, &signature_algorithm)) {
1424 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1425 return ssl_hs_error;
1426 }
1427 if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1428 // Write out the digest type in TLS 1.2.
1429 if (!CBB_add_u16(&body, signature_algorithm)) {
1430 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1431 return ssl_hs_error;
1432 }
1433 }
1434
1435 // Set aside space for the signature.
1436 const size_t max_sig_len = EVP_PKEY_size(hs->local_pubkey.get());
1437 uint8_t *ptr;
1438 if (!CBB_add_u16_length_prefixed(&body, &child) ||
1439 !CBB_reserve(&child, &ptr, max_sig_len)) {
1440 return ssl_hs_error;
1441 }
1442
1443 size_t sig_len = max_sig_len;
1444 switch (ssl_private_key_sign(hs, ptr, &sig_len, max_sig_len,
1445 signature_algorithm,
1446 hs->transcript.buffer())) {
1447 case ssl_private_key_success:
1448 break;
1449 case ssl_private_key_failure:
1450 return ssl_hs_error;
1451 case ssl_private_key_retry:
1452 hs->state = state_send_client_certificate_verify;
1453 return ssl_hs_private_key_operation;
1454 }
1455
1456 if (!CBB_did_write(&child, sig_len) ||
1457 !ssl_add_message_cbb(ssl, cbb.get())) {
1458 return ssl_hs_error;
1459 }
1460
1461 // The handshake buffer is no longer necessary.
1462 hs->transcript.FreeBuffer();
1463
1464 hs->state = state_send_client_finished;
1465 return ssl_hs_ok;
1466 }
1467
do_send_client_finished(SSL_HANDSHAKE * hs)1468 static enum ssl_hs_wait_t do_send_client_finished(SSL_HANDSHAKE *hs) {
1469 SSL *const ssl = hs->ssl;
1470 // Resolve Channel ID first, before any non-idempotent operations.
1471 if (ssl->s3->channel_id_valid) {
1472 if (!ssl_do_channel_id_callback(hs)) {
1473 return ssl_hs_error;
1474 }
1475
1476 if (hs->config->channel_id_private == NULL) {
1477 hs->state = state_send_client_finished;
1478 return ssl_hs_channel_id_lookup;
1479 }
1480 }
1481
1482 if (!ssl->method->add_change_cipher_spec(ssl) ||
1483 !tls1_change_cipher_state(hs, evp_aead_seal)) {
1484 return ssl_hs_error;
1485 }
1486
1487 if (hs->next_proto_neg_seen) {
1488 static const uint8_t kZero[32] = {0};
1489 size_t padding_len =
1490 32 - ((ssl->s3->next_proto_negotiated.size() + 2) % 32);
1491
1492 ScopedCBB cbb;
1493 CBB body, child;
1494 if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_NEXT_PROTO) ||
1495 !CBB_add_u8_length_prefixed(&body, &child) ||
1496 !CBB_add_bytes(&child, ssl->s3->next_proto_negotiated.data(),
1497 ssl->s3->next_proto_negotiated.size()) ||
1498 !CBB_add_u8_length_prefixed(&body, &child) ||
1499 !CBB_add_bytes(&child, kZero, padding_len) ||
1500 !ssl_add_message_cbb(ssl, cbb.get())) {
1501 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1502 return ssl_hs_error;
1503 }
1504 }
1505
1506 if (ssl->s3->channel_id_valid) {
1507 ScopedCBB cbb;
1508 CBB body;
1509 if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_CHANNEL_ID) ||
1510 !tls1_write_channel_id(hs, &body) ||
1511 !ssl_add_message_cbb(ssl, cbb.get())) {
1512 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1513 return ssl_hs_error;
1514 }
1515 }
1516
1517 if (!ssl_send_finished(hs)) {
1518 return ssl_hs_error;
1519 }
1520
1521 hs->state = state_finish_flight;
1522 return ssl_hs_flush;
1523 }
1524
can_false_start(const SSL_HANDSHAKE * hs)1525 static bool can_false_start(const SSL_HANDSHAKE *hs) {
1526 SSL *const ssl = hs->ssl;
1527
1528 // False Start bypasses the Finished check's downgrade protection. This can
1529 // enable attacks where we send data under weaker settings than supported
1530 // (e.g. the Logjam attack). Thus we require TLS 1.2 with an ECDHE+AEAD
1531 // cipher, our strongest settings before TLS 1.3.
1532 //
1533 // Now that TLS 1.3 exists, we would like to avoid similar attacks between
1534 // TLS 1.2 and TLS 1.3, but there are too many TLS 1.2 deployments to
1535 // sacrifice False Start on them. TLS 1.3's downgrade signal fixes this, but
1536 // |SSL_CTX_set_ignore_tls13_downgrade| can disable it due to compatibility
1537 // issues.
1538 //
1539 // |SSL_CTX_set_ignore_tls13_downgrade| normally still retains Finished-based
1540 // downgrade protection, but False Start bypasses that. Thus, we disable False
1541 // Start based on the TLS 1.3 downgrade signal, even if otherwise unenforced.
1542 if (SSL_is_dtls(ssl) ||
1543 SSL_version(ssl) != TLS1_2_VERSION ||
1544 hs->new_cipher->algorithm_mkey != SSL_kECDHE ||
1545 hs->new_cipher->algorithm_mac != SSL_AEAD ||
1546 ssl->s3->tls13_downgrade) {
1547 return false;
1548 }
1549
1550 // Additionally require ALPN or NPN by default.
1551 //
1552 // TODO(davidben): Can this constraint be relaxed globally now that cipher
1553 // suite requirements have been tightened?
1554 if (!ssl->ctx->false_start_allowed_without_alpn &&
1555 ssl->s3->alpn_selected.empty() &&
1556 ssl->s3->next_proto_negotiated.empty()) {
1557 return false;
1558 }
1559
1560 return true;
1561 }
1562
do_finish_flight(SSL_HANDSHAKE * hs)1563 static enum ssl_hs_wait_t do_finish_flight(SSL_HANDSHAKE *hs) {
1564 SSL *const ssl = hs->ssl;
1565 if (ssl->session != NULL) {
1566 hs->state = state_finish_client_handshake;
1567 return ssl_hs_ok;
1568 }
1569
1570 // This is a full handshake. If it involves ChannelID, then record the
1571 // handshake hashes at this point in the session so that any resumption of
1572 // this session with ChannelID can sign those hashes.
1573 if (!tls1_record_handshake_hashes_for_channel_id(hs)) {
1574 return ssl_hs_error;
1575 }
1576
1577 hs->state = state_read_session_ticket;
1578
1579 if ((SSL_get_mode(ssl) & SSL_MODE_ENABLE_FALSE_START) &&
1580 can_false_start(hs) &&
1581 // No False Start on renegotiation (would complicate the state machine).
1582 !ssl->s3->initial_handshake_complete) {
1583 hs->in_false_start = true;
1584 hs->can_early_write = true;
1585 return ssl_hs_early_return;
1586 }
1587
1588 return ssl_hs_ok;
1589 }
1590
do_read_session_ticket(SSL_HANDSHAKE * hs)1591 static enum ssl_hs_wait_t do_read_session_ticket(SSL_HANDSHAKE *hs) {
1592 SSL *const ssl = hs->ssl;
1593
1594 if (!hs->ticket_expected) {
1595 hs->state = state_process_change_cipher_spec;
1596 return ssl_hs_read_change_cipher_spec;
1597 }
1598
1599 SSLMessage msg;
1600 if (!ssl->method->get_message(ssl, &msg)) {
1601 return ssl_hs_read_message;
1602 }
1603
1604 if (!ssl_check_message_type(ssl, msg, SSL3_MT_NEW_SESSION_TICKET) ||
1605 !ssl_hash_message(hs, msg)) {
1606 return ssl_hs_error;
1607 }
1608
1609 CBS new_session_ticket = msg.body, ticket;
1610 uint32_t ticket_lifetime_hint;
1611 if (!CBS_get_u32(&new_session_ticket, &ticket_lifetime_hint) ||
1612 !CBS_get_u16_length_prefixed(&new_session_ticket, &ticket) ||
1613 CBS_len(&new_session_ticket) != 0) {
1614 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1615 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1616 return ssl_hs_error;
1617 }
1618
1619 if (CBS_len(&ticket) == 0) {
1620 // RFC 5077 allows a server to change its mind and send no ticket after
1621 // negotiating the extension. The value of |ticket_expected| is checked in
1622 // |ssl_update_cache| so is cleared here to avoid an unnecessary update.
1623 hs->ticket_expected = false;
1624 ssl->method->next_message(ssl);
1625 hs->state = state_process_change_cipher_spec;
1626 return ssl_hs_read_change_cipher_spec;
1627 }
1628
1629 SSL_SESSION *session = hs->new_session.get();
1630 UniquePtr<SSL_SESSION> renewed_session;
1631 if (ssl->session != NULL) {
1632 // The server is sending a new ticket for an existing session. Sessions are
1633 // immutable once established, so duplicate all but the ticket of the
1634 // existing session.
1635 renewed_session =
1636 SSL_SESSION_dup(ssl->session.get(), SSL_SESSION_INCLUDE_NONAUTH);
1637 if (!renewed_session) {
1638 // This should never happen.
1639 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1640 return ssl_hs_error;
1641 }
1642 session = renewed_session.get();
1643 }
1644
1645 // |ticket_lifetime_hint| is measured from when the ticket was issued.
1646 ssl_session_rebase_time(ssl, session);
1647
1648 if (!session->ticket.CopyFrom(ticket)) {
1649 return ssl_hs_error;
1650 }
1651 session->ticket_lifetime_hint = ticket_lifetime_hint;
1652
1653 // Generate a session ID for this session. Some callers expect all sessions to
1654 // have a session ID. Additionally, it acts as the session ID to signal
1655 // resumption.
1656 SHA256(CBS_data(&ticket), CBS_len(&ticket), session->session_id);
1657 session->session_id_length = SHA256_DIGEST_LENGTH;
1658
1659 if (renewed_session) {
1660 session->not_resumable = false;
1661 ssl->session = std::move(renewed_session);
1662 }
1663
1664 ssl->method->next_message(ssl);
1665 hs->state = state_process_change_cipher_spec;
1666 return ssl_hs_read_change_cipher_spec;
1667 }
1668
do_process_change_cipher_spec(SSL_HANDSHAKE * hs)1669 static enum ssl_hs_wait_t do_process_change_cipher_spec(SSL_HANDSHAKE *hs) {
1670 if (!tls1_change_cipher_state(hs, evp_aead_open)) {
1671 return ssl_hs_error;
1672 }
1673
1674 hs->state = state_read_server_finished;
1675 return ssl_hs_ok;
1676 }
1677
do_read_server_finished(SSL_HANDSHAKE * hs)1678 static enum ssl_hs_wait_t do_read_server_finished(SSL_HANDSHAKE *hs) {
1679 SSL *const ssl = hs->ssl;
1680 enum ssl_hs_wait_t wait = ssl_get_finished(hs);
1681 if (wait != ssl_hs_ok) {
1682 return wait;
1683 }
1684
1685 if (ssl->session != NULL) {
1686 hs->state = state_send_client_finished;
1687 return ssl_hs_ok;
1688 }
1689
1690 hs->state = state_finish_client_handshake;
1691 return ssl_hs_ok;
1692 }
1693
do_finish_client_handshake(SSL_HANDSHAKE * hs)1694 static enum ssl_hs_wait_t do_finish_client_handshake(SSL_HANDSHAKE *hs) {
1695 SSL *const ssl = hs->ssl;
1696
1697 ssl->method->on_handshake_complete(ssl);
1698
1699 if (ssl->session != NULL) {
1700 ssl->s3->established_session = UpRef(ssl->session);
1701 } else {
1702 // We make a copy of the session in order to maintain the immutability
1703 // of the new established_session due to False Start. The caller may
1704 // have taken a reference to the temporary session.
1705 ssl->s3->established_session =
1706 SSL_SESSION_dup(hs->new_session.get(), SSL_SESSION_DUP_ALL);
1707 if (!ssl->s3->established_session) {
1708 return ssl_hs_error;
1709 }
1710 // Renegotiations do not participate in session resumption.
1711 if (!ssl->s3->initial_handshake_complete) {
1712 ssl->s3->established_session->not_resumable = false;
1713 }
1714
1715 hs->new_session.reset();
1716 }
1717
1718 hs->handshake_finalized = true;
1719 ssl->s3->initial_handshake_complete = true;
1720 ssl_update_cache(hs, SSL_SESS_CACHE_CLIENT);
1721
1722 hs->state = state_done;
1723 return ssl_hs_ok;
1724 }
1725
ssl_client_handshake(SSL_HANDSHAKE * hs)1726 enum ssl_hs_wait_t ssl_client_handshake(SSL_HANDSHAKE *hs) {
1727 while (hs->state != state_done) {
1728 enum ssl_hs_wait_t ret = ssl_hs_error;
1729 enum ssl_client_hs_state_t state =
1730 static_cast<enum ssl_client_hs_state_t>(hs->state);
1731 switch (state) {
1732 case state_start_connect:
1733 ret = do_start_connect(hs);
1734 break;
1735 case state_enter_early_data:
1736 ret = do_enter_early_data(hs);
1737 break;
1738 case state_early_reverify_server_certificate:
1739 ret = do_early_reverify_server_certificate(hs);
1740 break;
1741 case state_read_hello_verify_request:
1742 ret = do_read_hello_verify_request(hs);
1743 break;
1744 case state_read_server_hello:
1745 ret = do_read_server_hello(hs);
1746 break;
1747 case state_tls13:
1748 ret = do_tls13(hs);
1749 break;
1750 case state_read_server_certificate:
1751 ret = do_read_server_certificate(hs);
1752 break;
1753 case state_read_certificate_status:
1754 ret = do_read_certificate_status(hs);
1755 break;
1756 case state_verify_server_certificate:
1757 ret = do_verify_server_certificate(hs);
1758 break;
1759 case state_reverify_server_certificate:
1760 ret = do_reverify_server_certificate(hs);
1761 break;
1762 case state_read_server_key_exchange:
1763 ret = do_read_server_key_exchange(hs);
1764 break;
1765 case state_read_certificate_request:
1766 ret = do_read_certificate_request(hs);
1767 break;
1768 case state_read_server_hello_done:
1769 ret = do_read_server_hello_done(hs);
1770 break;
1771 case state_send_client_certificate:
1772 ret = do_send_client_certificate(hs);
1773 break;
1774 case state_send_client_key_exchange:
1775 ret = do_send_client_key_exchange(hs);
1776 break;
1777 case state_send_client_certificate_verify:
1778 ret = do_send_client_certificate_verify(hs);
1779 break;
1780 case state_send_client_finished:
1781 ret = do_send_client_finished(hs);
1782 break;
1783 case state_finish_flight:
1784 ret = do_finish_flight(hs);
1785 break;
1786 case state_read_session_ticket:
1787 ret = do_read_session_ticket(hs);
1788 break;
1789 case state_process_change_cipher_spec:
1790 ret = do_process_change_cipher_spec(hs);
1791 break;
1792 case state_read_server_finished:
1793 ret = do_read_server_finished(hs);
1794 break;
1795 case state_finish_client_handshake:
1796 ret = do_finish_client_handshake(hs);
1797 break;
1798 case state_done:
1799 ret = ssl_hs_ok;
1800 break;
1801 }
1802
1803 if (hs->state != state) {
1804 ssl_do_info_callback(hs->ssl, SSL_CB_CONNECT_LOOP, 1);
1805 }
1806
1807 if (ret != ssl_hs_ok) {
1808 return ret;
1809 }
1810 }
1811
1812 ssl_do_info_callback(hs->ssl, SSL_CB_HANDSHAKE_DONE, 1);
1813 return ssl_hs_ok;
1814 }
1815
ssl_client_handshake_state(SSL_HANDSHAKE * hs)1816 const char *ssl_client_handshake_state(SSL_HANDSHAKE *hs) {
1817 enum ssl_client_hs_state_t state =
1818 static_cast<enum ssl_client_hs_state_t>(hs->state);
1819 switch (state) {
1820 case state_start_connect:
1821 return "TLS client start_connect";
1822 case state_enter_early_data:
1823 return "TLS client enter_early_data";
1824 case state_early_reverify_server_certificate:
1825 return "TLS client early_reverify_server_certificate";
1826 case state_read_hello_verify_request:
1827 return "TLS client read_hello_verify_request";
1828 case state_read_server_hello:
1829 return "TLS client read_server_hello";
1830 case state_tls13:
1831 return tls13_client_handshake_state(hs);
1832 case state_read_server_certificate:
1833 return "TLS client read_server_certificate";
1834 case state_read_certificate_status:
1835 return "TLS client read_certificate_status";
1836 case state_verify_server_certificate:
1837 return "TLS client verify_server_certificate";
1838 case state_reverify_server_certificate:
1839 return "TLS client reverify_server_certificate";
1840 case state_read_server_key_exchange:
1841 return "TLS client read_server_key_exchange";
1842 case state_read_certificate_request:
1843 return "TLS client read_certificate_request";
1844 case state_read_server_hello_done:
1845 return "TLS client read_server_hello_done";
1846 case state_send_client_certificate:
1847 return "TLS client send_client_certificate";
1848 case state_send_client_key_exchange:
1849 return "TLS client send_client_key_exchange";
1850 case state_send_client_certificate_verify:
1851 return "TLS client send_client_certificate_verify";
1852 case state_send_client_finished:
1853 return "TLS client send_client_finished";
1854 case state_finish_flight:
1855 return "TLS client finish_flight";
1856 case state_read_session_ticket:
1857 return "TLS client read_session_ticket";
1858 case state_process_change_cipher_spec:
1859 return "TLS client process_change_cipher_spec";
1860 case state_read_server_finished:
1861 return "TLS client read_server_finished";
1862 case state_finish_client_handshake:
1863 return "TLS client finish_client_handshake";
1864 case state_done:
1865 return "TLS client done";
1866 }
1867
1868 return "TLS client unknown";
1869 }
1870
1871 BSSL_NAMESPACE_END
1872