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