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, MakeSpan(msg))) {
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(
460 hs, MakeConstSpan(ssl->session->master_key,
461 ssl->session->master_key_length)) ||
462 !tls13_derive_early_secret(hs) ||
463 !tls13_set_early_secret_for_quic(hs)) {
464 return ssl_hs_error;
465 }
466 if (ssl->quic_method == nullptr &&
467 !tls13_set_traffic_key(ssl, ssl_encryption_early_data, evp_aead_seal,
468 hs->early_traffic_secret())) {
469 return ssl_hs_error;
470 }
471
472 // Stash the early data session, so connection properties may be queried out
473 // of it.
474 hs->early_session = UpRef(ssl->session);
475 hs->state = state_early_reverify_server_certificate;
476 return ssl_hs_ok;
477 }
478
do_early_reverify_server_certificate(SSL_HANDSHAKE * hs)479 static enum ssl_hs_wait_t do_early_reverify_server_certificate(SSL_HANDSHAKE *hs) {
480 if (hs->ssl->ctx->reverify_on_resume) {
481 switch (ssl_reverify_peer_cert(hs)) {
482 case ssl_verify_ok:
483 break;
484 case ssl_verify_invalid:
485 return ssl_hs_error;
486 case ssl_verify_retry:
487 hs->state = state_early_reverify_server_certificate;
488 return ssl_hs_certificate_verify;
489 }
490 }
491
492 hs->in_early_data = true;
493 hs->can_early_write = true;
494 hs->state = state_read_server_hello;
495 return ssl_hs_early_return;
496 }
497
do_read_hello_verify_request(SSL_HANDSHAKE * hs)498 static enum ssl_hs_wait_t do_read_hello_verify_request(SSL_HANDSHAKE *hs) {
499 SSL *const ssl = hs->ssl;
500
501 assert(SSL_is_dtls(ssl));
502
503 SSLMessage msg;
504 if (!ssl->method->get_message(ssl, &msg)) {
505 return ssl_hs_read_message;
506 }
507
508 if (msg.type != DTLS1_MT_HELLO_VERIFY_REQUEST) {
509 hs->state = state_read_server_hello;
510 return ssl_hs_ok;
511 }
512
513 CBS hello_verify_request = msg.body, cookie;
514 uint16_t server_version;
515 if (!CBS_get_u16(&hello_verify_request, &server_version) ||
516 !CBS_get_u8_length_prefixed(&hello_verify_request, &cookie) ||
517 CBS_len(&cookie) > sizeof(ssl->d1->cookie) ||
518 CBS_len(&hello_verify_request) != 0) {
519 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
520 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
521 return ssl_hs_error;
522 }
523
524 OPENSSL_memcpy(ssl->d1->cookie, CBS_data(&cookie), CBS_len(&cookie));
525 ssl->d1->cookie_len = CBS_len(&cookie);
526
527 ssl->method->next_message(ssl);
528
529 // DTLS resets the handshake buffer after HelloVerifyRequest.
530 if (!hs->transcript.Init()) {
531 return ssl_hs_error;
532 }
533
534 if (!ssl_write_client_hello(hs)) {
535 return ssl_hs_error;
536 }
537
538 hs->state = state_read_server_hello;
539 return ssl_hs_flush;
540 }
541
do_read_server_hello(SSL_HANDSHAKE * hs)542 static enum ssl_hs_wait_t do_read_server_hello(SSL_HANDSHAKE *hs) {
543 SSL *const ssl = hs->ssl;
544 SSLMessage msg;
545 if (!ssl->method->get_message(ssl, &msg)) {
546 return ssl_hs_read_server_hello;
547 }
548
549 if (!ssl_check_message_type(ssl, msg, SSL3_MT_SERVER_HELLO)) {
550 return ssl_hs_error;
551 }
552
553 CBS server_hello = msg.body, server_random, session_id;
554 uint16_t server_version, cipher_suite;
555 uint8_t compression_method;
556 if (!CBS_get_u16(&server_hello, &server_version) ||
557 !CBS_get_bytes(&server_hello, &server_random, SSL3_RANDOM_SIZE) ||
558 !CBS_get_u8_length_prefixed(&server_hello, &session_id) ||
559 CBS_len(&session_id) > SSL3_SESSION_ID_SIZE ||
560 !CBS_get_u16(&server_hello, &cipher_suite) ||
561 !CBS_get_u8(&server_hello, &compression_method)) {
562 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
563 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
564 return ssl_hs_error;
565 }
566
567 // Use the supported_versions extension if applicable.
568 if (!parse_supported_versions(hs, &server_version, &server_hello)) {
569 return ssl_hs_error;
570 }
571
572 if (!ssl_supports_version(hs, server_version)) {
573 OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL);
574 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
575 return ssl_hs_error;
576 }
577
578 assert(ssl->s3->have_version == ssl->s3->initial_handshake_complete);
579 if (!ssl->s3->have_version) {
580 ssl->version = server_version;
581 // At this point, the connection's version is known and ssl->version is
582 // fixed. Begin enforcing the record-layer version.
583 ssl->s3->have_version = true;
584 ssl->s3->aead_write_ctx->SetVersionIfNullCipher(ssl->version);
585 } else if (server_version != ssl->version) {
586 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION);
587 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
588 return ssl_hs_error;
589 }
590
591 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
592 hs->state = state_tls13;
593 return ssl_hs_ok;
594 }
595
596 // Clear some TLS 1.3 state that no longer needs to be retained.
597 hs->key_shares[0].reset();
598 hs->key_shares[1].reset();
599 hs->key_share_bytes.Reset();
600
601 // A TLS 1.2 server would not know to skip the early data we offered. Report
602 // an error code sooner. The caller may use this error code to implement the
603 // fallback described in RFC 8446 appendix D.3.
604 if (hs->early_data_offered) {
605 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_VERSION_ON_EARLY_DATA);
606 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
607 return ssl_hs_error;
608 }
609
610 // Copy over the server random.
611 OPENSSL_memcpy(ssl->s3->server_random, CBS_data(&server_random),
612 SSL3_RANDOM_SIZE);
613
614 // Enforce the TLS 1.3 anti-downgrade feature.
615 if (!ssl->s3->initial_handshake_complete &&
616 ssl_supports_version(hs, TLS1_3_VERSION)) {
617 static_assert(
618 sizeof(kTLS12DowngradeRandom) == sizeof(kTLS13DowngradeRandom),
619 "downgrade signals have different size");
620 static_assert(
621 sizeof(kJDK11DowngradeRandom) == sizeof(kTLS13DowngradeRandom),
622 "downgrade signals have different size");
623 auto suffix =
624 MakeConstSpan(ssl->s3->server_random, sizeof(ssl->s3->server_random))
625 .subspan(SSL3_RANDOM_SIZE - sizeof(kTLS13DowngradeRandom));
626 if (suffix == kTLS12DowngradeRandom || suffix == kTLS13DowngradeRandom ||
627 suffix == kJDK11DowngradeRandom) {
628 ssl->s3->tls13_downgrade = true;
629 if (!hs->config->ignore_tls13_downgrade) {
630 OPENSSL_PUT_ERROR(SSL, SSL_R_TLS13_DOWNGRADE);
631 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
632 return ssl_hs_error;
633 }
634 }
635 }
636
637 if (!ssl->s3->initial_handshake_complete && ssl->session != nullptr &&
638 ssl->session->session_id_length != 0 &&
639 CBS_mem_equal(&session_id, ssl->session->session_id,
640 ssl->session->session_id_length)) {
641 ssl->s3->session_reused = true;
642 } else {
643 // The server may also have echoed back the TLS 1.3 compatibility mode
644 // session ID. As we know this is not a session the server knows about, any
645 // server resuming it is in error. Reject the first connection
646 // deterministicly, rather than installing an invalid session into the
647 // session cache. https://crbug.com/796910
648 if (hs->session_id_len != 0 &&
649 CBS_mem_equal(&session_id, hs->session_id, hs->session_id_len)) {
650 OPENSSL_PUT_ERROR(SSL, SSL_R_SERVER_ECHOED_INVALID_SESSION_ID);
651 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
652 return ssl_hs_error;
653 }
654
655 // The session wasn't resumed. Create a fresh SSL_SESSION to
656 // fill out.
657 ssl_set_session(ssl, NULL);
658 if (!ssl_get_new_session(hs, 0 /* client */)) {
659 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
660 return ssl_hs_error;
661 }
662 // Note: session_id could be empty.
663 hs->new_session->session_id_length = CBS_len(&session_id);
664 OPENSSL_memcpy(hs->new_session->session_id, CBS_data(&session_id),
665 CBS_len(&session_id));
666 }
667
668 const SSL_CIPHER *cipher = SSL_get_cipher_by_value(cipher_suite);
669 if (cipher == NULL) {
670 // unknown cipher
671 OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CIPHER_RETURNED);
672 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
673 return ssl_hs_error;
674 }
675
676 // The cipher must be allowed in the selected version and enabled.
677 uint32_t mask_a, mask_k;
678 ssl_get_client_disabled(hs, &mask_a, &mask_k);
679 if ((cipher->algorithm_mkey & mask_k) || (cipher->algorithm_auth & mask_a) ||
680 SSL_CIPHER_get_min_version(cipher) > ssl_protocol_version(ssl) ||
681 SSL_CIPHER_get_max_version(cipher) < ssl_protocol_version(ssl) ||
682 !sk_SSL_CIPHER_find(SSL_get_ciphers(ssl), NULL, cipher)) {
683 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
684 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
685 return ssl_hs_error;
686 }
687
688 if (ssl->session != NULL) {
689 if (ssl->session->ssl_version != ssl->version) {
690 OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_VERSION_NOT_RETURNED);
691 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
692 return ssl_hs_error;
693 }
694 if (ssl->session->cipher != cipher) {
695 OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
696 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
697 return ssl_hs_error;
698 }
699 if (!ssl_session_is_context_valid(hs, ssl->session.get())) {
700 // This is actually a client application bug.
701 OPENSSL_PUT_ERROR(SSL,
702 SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
703 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
704 return ssl_hs_error;
705 }
706 } else {
707 hs->new_session->cipher = cipher;
708 }
709 hs->new_cipher = cipher;
710
711 // Now that the cipher is known, initialize the handshake hash and hash the
712 // ServerHello.
713 if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher) ||
714 !ssl_hash_message(hs, msg)) {
715 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
716 return ssl_hs_error;
717 }
718
719 // If doing a full handshake, the server may request a client certificate
720 // which requires hashing the handshake transcript. Otherwise, the handshake
721 // buffer may be released.
722 if (ssl->session != NULL ||
723 !ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
724 hs->transcript.FreeBuffer();
725 }
726
727 // Only the NULL compression algorithm is supported.
728 if (compression_method != 0) {
729 OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
730 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
731 return ssl_hs_error;
732 }
733
734 // TLS extensions
735 if (!ssl_parse_serverhello_tlsext(hs, &server_hello)) {
736 OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
737 return ssl_hs_error;
738 }
739
740 // There should be nothing left over in the record.
741 if (CBS_len(&server_hello) != 0) {
742 // wrong packet length
743 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
744 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
745 return ssl_hs_error;
746 }
747
748 if (ssl->session != NULL &&
749 hs->extended_master_secret != ssl->session->extended_master_secret) {
750 if (ssl->session->extended_master_secret) {
751 OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
752 } else {
753 OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_NON_EMS_SESSION_WITH_EMS_EXTENSION);
754 }
755 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
756 return ssl_hs_error;
757 }
758
759 if (ssl->s3->token_binding_negotiated &&
760 (!hs->extended_master_secret || !ssl->s3->send_connection_binding)) {
761 OPENSSL_PUT_ERROR(SSL, SSL_R_NEGOTIATED_TB_WITHOUT_EMS_OR_RI);
762 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_EXTENSION);
763 return ssl_hs_error;
764 }
765
766 ssl->method->next_message(ssl);
767
768 if (ssl->session != NULL) {
769 if (ssl->ctx->reverify_on_resume &&
770 ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
771 hs->state = state_reverify_server_certificate;
772 } else {
773 hs->state = state_read_session_ticket;
774 }
775 return ssl_hs_ok;
776 }
777
778 hs->state = state_read_server_certificate;
779 return ssl_hs_ok;
780 }
781
do_tls13(SSL_HANDSHAKE * hs)782 static enum ssl_hs_wait_t do_tls13(SSL_HANDSHAKE *hs) {
783 enum ssl_hs_wait_t wait = tls13_client_handshake(hs);
784 if (wait == ssl_hs_ok) {
785 hs->state = state_finish_client_handshake;
786 return ssl_hs_ok;
787 }
788
789 return wait;
790 }
791
do_read_server_certificate(SSL_HANDSHAKE * hs)792 static enum ssl_hs_wait_t do_read_server_certificate(SSL_HANDSHAKE *hs) {
793 SSL *const ssl = hs->ssl;
794
795 if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
796 hs->state = state_read_certificate_status;
797 return ssl_hs_ok;
798 }
799
800 SSLMessage msg;
801 if (!ssl->method->get_message(ssl, &msg)) {
802 return ssl_hs_read_message;
803 }
804
805 if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE) ||
806 !ssl_hash_message(hs, msg)) {
807 return ssl_hs_error;
808 }
809
810 CBS body = msg.body;
811 uint8_t alert = SSL_AD_DECODE_ERROR;
812 if (!ssl_parse_cert_chain(&alert, &hs->new_session->certs, &hs->peer_pubkey,
813 NULL, &body, ssl->ctx->pool)) {
814 ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
815 return ssl_hs_error;
816 }
817
818 if (sk_CRYPTO_BUFFER_num(hs->new_session->certs.get()) == 0 ||
819 CBS_len(&body) != 0 ||
820 !ssl->ctx->x509_method->session_cache_objects(hs->new_session.get())) {
821 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
822 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
823 return ssl_hs_error;
824 }
825
826 if (!ssl_check_leaf_certificate(
827 hs, hs->peer_pubkey.get(),
828 sk_CRYPTO_BUFFER_value(hs->new_session->certs.get(), 0))) {
829 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
830 return ssl_hs_error;
831 }
832
833 ssl->method->next_message(ssl);
834
835 hs->state = state_read_certificate_status;
836 return ssl_hs_ok;
837 }
838
do_read_certificate_status(SSL_HANDSHAKE * hs)839 static enum ssl_hs_wait_t do_read_certificate_status(SSL_HANDSHAKE *hs) {
840 SSL *const ssl = hs->ssl;
841
842 if (!hs->certificate_status_expected) {
843 hs->state = state_verify_server_certificate;
844 return ssl_hs_ok;
845 }
846
847 SSLMessage msg;
848 if (!ssl->method->get_message(ssl, &msg)) {
849 return ssl_hs_read_message;
850 }
851
852 if (msg.type != SSL3_MT_CERTIFICATE_STATUS) {
853 // A server may send status_request in ServerHello and then change its mind
854 // about sending CertificateStatus.
855 hs->state = state_verify_server_certificate;
856 return ssl_hs_ok;
857 }
858
859 if (!ssl_hash_message(hs, msg)) {
860 return ssl_hs_error;
861 }
862
863 CBS certificate_status = msg.body, ocsp_response;
864 uint8_t status_type;
865 if (!CBS_get_u8(&certificate_status, &status_type) ||
866 status_type != TLSEXT_STATUSTYPE_ocsp ||
867 !CBS_get_u24_length_prefixed(&certificate_status, &ocsp_response) ||
868 CBS_len(&ocsp_response) == 0 ||
869 CBS_len(&certificate_status) != 0) {
870 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
871 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
872 return ssl_hs_error;
873 }
874
875 hs->new_session->ocsp_response.reset(
876 CRYPTO_BUFFER_new_from_CBS(&ocsp_response, ssl->ctx->pool));
877 if (hs->new_session->ocsp_response == nullptr) {
878 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
879 return ssl_hs_error;
880 }
881
882 ssl->method->next_message(ssl);
883
884 hs->state = state_verify_server_certificate;
885 return ssl_hs_ok;
886 }
887
do_verify_server_certificate(SSL_HANDSHAKE * hs)888 static enum ssl_hs_wait_t do_verify_server_certificate(SSL_HANDSHAKE *hs) {
889 if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
890 hs->state = state_read_server_key_exchange;
891 return ssl_hs_ok;
892 }
893
894 switch (ssl_verify_peer_cert(hs)) {
895 case ssl_verify_ok:
896 break;
897 case ssl_verify_invalid:
898 return ssl_hs_error;
899 case ssl_verify_retry:
900 hs->state = state_verify_server_certificate;
901 return ssl_hs_certificate_verify;
902 }
903
904 hs->state = state_read_server_key_exchange;
905 return ssl_hs_ok;
906 }
907
do_reverify_server_certificate(SSL_HANDSHAKE * hs)908 static enum ssl_hs_wait_t do_reverify_server_certificate(SSL_HANDSHAKE *hs) {
909 assert(hs->ssl->ctx->reverify_on_resume);
910
911 switch (ssl_reverify_peer_cert(hs)) {
912 case ssl_verify_ok:
913 break;
914 case ssl_verify_invalid:
915 return ssl_hs_error;
916 case ssl_verify_retry:
917 hs->state = state_reverify_server_certificate;
918 return ssl_hs_certificate_verify;
919 }
920
921 hs->state = state_read_session_ticket;
922 return ssl_hs_ok;
923 }
924
do_read_server_key_exchange(SSL_HANDSHAKE * hs)925 static enum ssl_hs_wait_t do_read_server_key_exchange(SSL_HANDSHAKE *hs) {
926 SSL *const ssl = hs->ssl;
927 SSLMessage msg;
928 if (!ssl->method->get_message(ssl, &msg)) {
929 return ssl_hs_read_message;
930 }
931
932 if (msg.type != SSL3_MT_SERVER_KEY_EXCHANGE) {
933 // Some ciphers (pure PSK) have an optional ServerKeyExchange message.
934 if (ssl_cipher_requires_server_key_exchange(hs->new_cipher)) {
935 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
936 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
937 return ssl_hs_error;
938 }
939
940 hs->state = state_read_certificate_request;
941 return ssl_hs_ok;
942 }
943
944 if (!ssl_hash_message(hs, msg)) {
945 return ssl_hs_error;
946 }
947
948 uint32_t alg_k = hs->new_cipher->algorithm_mkey;
949 uint32_t alg_a = hs->new_cipher->algorithm_auth;
950 CBS server_key_exchange = msg.body;
951 if (alg_a & SSL_aPSK) {
952 CBS psk_identity_hint;
953
954 // Each of the PSK key exchanges begins with a psk_identity_hint.
955 if (!CBS_get_u16_length_prefixed(&server_key_exchange,
956 &psk_identity_hint)) {
957 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
958 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
959 return ssl_hs_error;
960 }
961
962 // Store the PSK identity hint for the ClientKeyExchange. Assume that the
963 // maximum length of a PSK identity hint can be as long as the maximum
964 // length of a PSK identity. Also do not allow NULL characters; identities
965 // are saved as C strings.
966 //
967 // TODO(davidben): Should invalid hints be ignored? It's a hint rather than
968 // a specific identity.
969 if (CBS_len(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN ||
970 CBS_contains_zero_byte(&psk_identity_hint)) {
971 OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
972 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
973 return ssl_hs_error;
974 }
975
976 // Save non-empty identity hints as a C string. Empty identity hints we
977 // treat as missing. Plain PSK makes it possible to send either no hint
978 // (omit ServerKeyExchange) or an empty hint, while ECDHE_PSK can only spell
979 // empty hint. Having different capabilities is odd, so we interpret empty
980 // and missing as identical.
981 char *raw = nullptr;
982 if (CBS_len(&psk_identity_hint) != 0 &&
983 !CBS_strdup(&psk_identity_hint, &raw)) {
984 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
985 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
986 return ssl_hs_error;
987 }
988 hs->peer_psk_identity_hint.reset(raw);
989 }
990
991 if (alg_k & SSL_kECDHE) {
992 // Parse the server parameters.
993 uint8_t group_type;
994 uint16_t group_id;
995 CBS point;
996 if (!CBS_get_u8(&server_key_exchange, &group_type) ||
997 group_type != NAMED_CURVE_TYPE ||
998 !CBS_get_u16(&server_key_exchange, &group_id) ||
999 !CBS_get_u8_length_prefixed(&server_key_exchange, &point)) {
1000 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1001 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1002 return ssl_hs_error;
1003 }
1004 hs->new_session->group_id = group_id;
1005
1006 // Ensure the group is consistent with preferences.
1007 if (!tls1_check_group_id(hs, group_id)) {
1008 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
1009 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
1010 return ssl_hs_error;
1011 }
1012
1013 // Initialize ECDH and save the peer public key for later.
1014 hs->key_shares[0] = SSLKeyShare::Create(group_id);
1015 if (!hs->key_shares[0] ||
1016 !hs->peer_key.CopyFrom(point)) {
1017 return ssl_hs_error;
1018 }
1019 } else if (!(alg_k & SSL_kPSK)) {
1020 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
1021 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1022 return ssl_hs_error;
1023 }
1024
1025 // At this point, |server_key_exchange| contains the signature, if any, while
1026 // |msg.body| contains the entire message. From that, derive a CBS containing
1027 // just the parameter.
1028 CBS parameter;
1029 CBS_init(¶meter, CBS_data(&msg.body),
1030 CBS_len(&msg.body) - CBS_len(&server_key_exchange));
1031
1032 // ServerKeyExchange should be signed by the server's public key.
1033 if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1034 uint16_t signature_algorithm = 0;
1035 if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1036 if (!CBS_get_u16(&server_key_exchange, &signature_algorithm)) {
1037 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1038 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1039 return ssl_hs_error;
1040 }
1041 uint8_t alert = SSL_AD_DECODE_ERROR;
1042 if (!tls12_check_peer_sigalg(ssl, &alert, signature_algorithm)) {
1043 ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1044 return ssl_hs_error;
1045 }
1046 hs->new_session->peer_signature_algorithm = signature_algorithm;
1047 } else if (!tls1_get_legacy_signature_algorithm(&signature_algorithm,
1048 hs->peer_pubkey.get())) {
1049 OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
1050 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_CERTIFICATE);
1051 return ssl_hs_error;
1052 }
1053
1054 // The last field in |server_key_exchange| is the signature.
1055 CBS signature;
1056 if (!CBS_get_u16_length_prefixed(&server_key_exchange, &signature) ||
1057 CBS_len(&server_key_exchange) != 0) {
1058 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1059 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1060 return ssl_hs_error;
1061 }
1062
1063 ScopedCBB transcript;
1064 Array<uint8_t> transcript_data;
1065 if (!CBB_init(transcript.get(),
1066 2 * SSL3_RANDOM_SIZE + CBS_len(¶meter)) ||
1067 !CBB_add_bytes(transcript.get(), ssl->s3->client_random,
1068 SSL3_RANDOM_SIZE) ||
1069 !CBB_add_bytes(transcript.get(), ssl->s3->server_random,
1070 SSL3_RANDOM_SIZE) ||
1071 !CBB_add_bytes(transcript.get(), CBS_data(¶meter),
1072 CBS_len(¶meter)) ||
1073 !CBBFinishArray(transcript.get(), &transcript_data)) {
1074 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1075 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1076 return ssl_hs_error;
1077 }
1078
1079 if (!ssl_public_key_verify(ssl, signature, signature_algorithm,
1080 hs->peer_pubkey.get(), transcript_data)) {
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