• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <openssl/ssl.h>
150 
151 #include <assert.h>
152 #include <string.h>
153 
154 #include <openssl/bn.h>
155 #include <openssl/buf.h>
156 #include <openssl/bytestring.h>
157 #include <openssl/cipher.h>
158 #include <openssl/ec.h>
159 #include <openssl/ecdsa.h>
160 #include <openssl/err.h>
161 #include <openssl/evp.h>
162 #include <openssl/hmac.h>
163 #include <openssl/md5.h>
164 #include <openssl/mem.h>
165 #include <openssl/nid.h>
166 #include <openssl/rand.h>
167 #include <openssl/x509.h>
168 
169 #include "internal.h"
170 #include "../crypto/internal.h"
171 
172 
173 BSSL_NAMESPACE_BEGIN
174 
ssl_client_cipher_list_contains_cipher(const SSL_CLIENT_HELLO * client_hello,uint16_t id)175 bool ssl_client_cipher_list_contains_cipher(
176     const SSL_CLIENT_HELLO *client_hello, uint16_t id) {
177   CBS cipher_suites;
178   CBS_init(&cipher_suites, client_hello->cipher_suites,
179            client_hello->cipher_suites_len);
180 
181   while (CBS_len(&cipher_suites) > 0) {
182     uint16_t got_id;
183     if (!CBS_get_u16(&cipher_suites, &got_id)) {
184       return false;
185     }
186 
187     if (got_id == id) {
188       return true;
189     }
190   }
191 
192   return false;
193 }
194 
negotiate_version(SSL_HANDSHAKE * hs,uint8_t * out_alert,const SSL_CLIENT_HELLO * client_hello)195 static bool negotiate_version(SSL_HANDSHAKE *hs, uint8_t *out_alert,
196                               const SSL_CLIENT_HELLO *client_hello) {
197   SSL *const ssl = hs->ssl;
198   assert(!ssl->s3->have_version);
199   CBS supported_versions, versions;
200   if (ssl_client_hello_get_extension(client_hello, &supported_versions,
201                                      TLSEXT_TYPE_supported_versions)) {
202     if (!CBS_get_u8_length_prefixed(&supported_versions, &versions) ||
203         CBS_len(&supported_versions) != 0 ||
204         CBS_len(&versions) == 0) {
205       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
206       *out_alert = SSL_AD_DECODE_ERROR;
207       return false;
208     }
209   } else {
210     // Convert the ClientHello version to an equivalent supported_versions
211     // extension.
212     static const uint8_t kTLSVersions[] = {
213         0x03, 0x03,  // TLS 1.2
214         0x03, 0x02,  // TLS 1.1
215         0x03, 0x01,  // TLS 1
216     };
217 
218     static const uint8_t kDTLSVersions[] = {
219         0xfe, 0xfd,  // DTLS 1.2
220         0xfe, 0xff,  // DTLS 1.0
221     };
222 
223     size_t versions_len = 0;
224     if (SSL_is_dtls(ssl)) {
225       if (client_hello->version <= DTLS1_2_VERSION) {
226         versions_len = 4;
227       } else if (client_hello->version <= DTLS1_VERSION) {
228         versions_len = 2;
229       }
230       CBS_init(&versions, kDTLSVersions + sizeof(kDTLSVersions) - versions_len,
231                versions_len);
232     } else {
233       if (client_hello->version >= TLS1_2_VERSION) {
234         versions_len = 6;
235       } else if (client_hello->version >= TLS1_1_VERSION) {
236         versions_len = 4;
237       } else if (client_hello->version >= TLS1_VERSION) {
238         versions_len = 2;
239       }
240       CBS_init(&versions, kTLSVersions + sizeof(kTLSVersions) - versions_len,
241                versions_len);
242     }
243   }
244 
245   if (!ssl_negotiate_version(hs, out_alert, &ssl->version, &versions)) {
246     return false;
247   }
248 
249   // At this point, the connection's version is known and |ssl->version| is
250   // fixed. Begin enforcing the record-layer version.
251   ssl->s3->have_version = true;
252   ssl->s3->aead_write_ctx->SetVersionIfNullCipher(ssl->version);
253 
254   // Handle FALLBACK_SCSV.
255   if (ssl_client_cipher_list_contains_cipher(client_hello,
256                                              SSL3_CK_FALLBACK_SCSV & 0xffff) &&
257       ssl_protocol_version(ssl) < hs->max_version) {
258     OPENSSL_PUT_ERROR(SSL, SSL_R_INAPPROPRIATE_FALLBACK);
259     *out_alert = SSL3_AD_INAPPROPRIATE_FALLBACK;
260     return false;
261   }
262 
263   return true;
264 }
265 
ssl_parse_client_cipher_list(const SSL_CLIENT_HELLO * client_hello)266 static UniquePtr<STACK_OF(SSL_CIPHER)> ssl_parse_client_cipher_list(
267     const SSL_CLIENT_HELLO *client_hello) {
268   CBS cipher_suites;
269   CBS_init(&cipher_suites, client_hello->cipher_suites,
270            client_hello->cipher_suites_len);
271 
272   UniquePtr<STACK_OF(SSL_CIPHER)> sk(sk_SSL_CIPHER_new_null());
273   if (!sk) {
274     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
275     return nullptr;
276   }
277 
278   while (CBS_len(&cipher_suites) > 0) {
279     uint16_t cipher_suite;
280 
281     if (!CBS_get_u16(&cipher_suites, &cipher_suite)) {
282       OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
283       return nullptr;
284     }
285 
286     const SSL_CIPHER *c = SSL_get_cipher_by_value(cipher_suite);
287     if (c != NULL && !sk_SSL_CIPHER_push(sk.get(), c)) {
288       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
289       return nullptr;
290     }
291   }
292 
293   return sk;
294 }
295 
296 // ssl_get_compatible_server_ciphers determines the key exchange and
297 // authentication cipher suite masks compatible with the server configuration
298 // and current ClientHello parameters of |hs|. It sets |*out_mask_k| to the key
299 // exchange mask and |*out_mask_a| to the authentication mask.
ssl_get_compatible_server_ciphers(SSL_HANDSHAKE * hs,uint32_t * out_mask_k,uint32_t * out_mask_a)300 static void ssl_get_compatible_server_ciphers(SSL_HANDSHAKE *hs,
301                                               uint32_t *out_mask_k,
302                                               uint32_t *out_mask_a) {
303   uint32_t mask_k = 0;
304   uint32_t mask_a = 0;
305 
306   if (ssl_has_certificate(hs)) {
307     mask_a |= ssl_cipher_auth_mask_for_key(hs->local_pubkey.get());
308     if (EVP_PKEY_id(hs->local_pubkey.get()) == EVP_PKEY_RSA) {
309       mask_k |= SSL_kRSA;
310     }
311   }
312 
313   // Check for a shared group to consider ECDHE ciphers.
314   uint16_t unused;
315   if (tls1_get_shared_group(hs, &unused)) {
316     mask_k |= SSL_kECDHE;
317   }
318 
319   // PSK requires a server callback.
320   if (hs->config->psk_server_callback != NULL) {
321     mask_k |= SSL_kPSK;
322     mask_a |= SSL_aPSK;
323   }
324 
325   *out_mask_k = mask_k;
326   *out_mask_a = mask_a;
327 }
328 
ssl3_choose_cipher(SSL_HANDSHAKE * hs,const SSL_CLIENT_HELLO * client_hello,const SSLCipherPreferenceList * server_pref)329 static const SSL_CIPHER *ssl3_choose_cipher(
330     SSL_HANDSHAKE *hs, const SSL_CLIENT_HELLO *client_hello,
331     const SSLCipherPreferenceList *server_pref) {
332   SSL *const ssl = hs->ssl;
333   const STACK_OF(SSL_CIPHER) *prio, *allow;
334   // in_group_flags will either be NULL, or will point to an array of bytes
335   // which indicate equal-preference groups in the |prio| stack. See the
336   // comment about |in_group_flags| in the |SSLCipherPreferenceList|
337   // struct.
338   const bool *in_group_flags;
339   // group_min contains the minimal index so far found in a group, or -1 if no
340   // such value exists yet.
341   int group_min = -1;
342 
343   UniquePtr<STACK_OF(SSL_CIPHER)> client_pref =
344       ssl_parse_client_cipher_list(client_hello);
345   if (!client_pref) {
346     return nullptr;
347   }
348 
349   if (ssl->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
350     prio = server_pref->ciphers.get();
351     in_group_flags = server_pref->in_group_flags;
352     allow = client_pref.get();
353   } else {
354     prio = client_pref.get();
355     in_group_flags = NULL;
356     allow = server_pref->ciphers.get();
357   }
358 
359   uint32_t mask_k, mask_a;
360   ssl_get_compatible_server_ciphers(hs, &mask_k, &mask_a);
361 
362   for (size_t i = 0; i < sk_SSL_CIPHER_num(prio); i++) {
363     const SSL_CIPHER *c = sk_SSL_CIPHER_value(prio, i);
364 
365     size_t cipher_index;
366     if (// Check if the cipher is supported for the current version.
367         SSL_CIPHER_get_min_version(c) <= ssl_protocol_version(ssl) &&
368         ssl_protocol_version(ssl) <= SSL_CIPHER_get_max_version(c) &&
369         // Check the cipher is supported for the server configuration.
370         (c->algorithm_mkey & mask_k) &&
371         (c->algorithm_auth & mask_a) &&
372         // Check the cipher is in the |allow| list.
373         sk_SSL_CIPHER_find(allow, &cipher_index, c)) {
374       if (in_group_flags != NULL && in_group_flags[i]) {
375         // This element of |prio| is in a group. Update the minimum index found
376         // so far and continue looking.
377         if (group_min == -1 || (size_t)group_min > cipher_index) {
378           group_min = cipher_index;
379         }
380       } else {
381         if (group_min != -1 && (size_t)group_min < cipher_index) {
382           cipher_index = group_min;
383         }
384         return sk_SSL_CIPHER_value(allow, cipher_index);
385       }
386     }
387 
388     if (in_group_flags != NULL && !in_group_flags[i] && group_min != -1) {
389       // We are about to leave a group, but we found a match in it, so that's
390       // our answer.
391       return sk_SSL_CIPHER_value(allow, group_min);
392     }
393   }
394 
395   return nullptr;
396 }
397 
do_start_accept(SSL_HANDSHAKE * hs)398 static enum ssl_hs_wait_t do_start_accept(SSL_HANDSHAKE *hs) {
399   ssl_do_info_callback(hs->ssl, SSL_CB_HANDSHAKE_START, 1);
400   hs->state = state12_read_client_hello;
401   return ssl_hs_ok;
402 }
403 
404 // is_probably_jdk11_with_tls13 returns whether |client_hello| was probably sent
405 // from a JDK 11 client with both TLS 1.3 and a prior version enabled.
is_probably_jdk11_with_tls13(const SSL_CLIENT_HELLO * client_hello)406 static bool is_probably_jdk11_with_tls13(const SSL_CLIENT_HELLO *client_hello) {
407   // JDK 11 ClientHellos contain a number of unusual properties which should
408   // limit false positives.
409 
410   // JDK 11 does not support ChaCha20-Poly1305. This is unusual: many modern
411   // clients implement ChaCha20-Poly1305.
412   if (ssl_client_cipher_list_contains_cipher(
413           client_hello, TLS1_CK_CHACHA20_POLY1305_SHA256 & 0xffff)) {
414     return false;
415   }
416 
417   // JDK 11 always sends extensions in a particular order.
418   constexpr uint16_t kMaxFragmentLength = 0x0001;
419   constexpr uint16_t kStatusRequestV2 = 0x0011;
420   static CONSTEXPR_ARRAY struct {
421     uint16_t id;
422     bool required;
423   } kJavaExtensions[] = {
424       {TLSEXT_TYPE_server_name, false},
425       {kMaxFragmentLength, false},
426       {TLSEXT_TYPE_status_request, false},
427       {TLSEXT_TYPE_supported_groups, true},
428       {TLSEXT_TYPE_ec_point_formats, false},
429       {TLSEXT_TYPE_signature_algorithms, true},
430       // Java always sends signature_algorithms_cert.
431       {TLSEXT_TYPE_signature_algorithms_cert, true},
432       {TLSEXT_TYPE_application_layer_protocol_negotiation, false},
433       {kStatusRequestV2, false},
434       {TLSEXT_TYPE_extended_master_secret, false},
435       {TLSEXT_TYPE_supported_versions, true},
436       {TLSEXT_TYPE_cookie, false},
437       {TLSEXT_TYPE_psk_key_exchange_modes, true},
438       {TLSEXT_TYPE_key_share, true},
439       {TLSEXT_TYPE_renegotiate, false},
440       {TLSEXT_TYPE_pre_shared_key, false},
441   };
442   Span<const uint8_t> sigalgs, sigalgs_cert;
443   bool has_status_request = false, has_status_request_v2 = false;
444   CBS extensions, supported_groups;
445   CBS_init(&extensions, client_hello->extensions, client_hello->extensions_len);
446   for (const auto &java_extension : kJavaExtensions) {
447     CBS copy = extensions;
448     uint16_t id;
449     if (CBS_get_u16(&copy, &id) && id == java_extension.id) {
450       // The next extension is the one we expected.
451       extensions = copy;
452       CBS body;
453       if (!CBS_get_u16_length_prefixed(&extensions, &body)) {
454         return false;
455       }
456       switch (id) {
457         case TLSEXT_TYPE_status_request:
458           has_status_request = true;
459           break;
460         case kStatusRequestV2:
461           has_status_request_v2 = true;
462           break;
463         case TLSEXT_TYPE_signature_algorithms:
464           sigalgs = body;
465           break;
466         case TLSEXT_TYPE_signature_algorithms_cert:
467           sigalgs_cert = body;
468           break;
469         case TLSEXT_TYPE_supported_groups:
470           supported_groups = body;
471           break;
472       }
473     } else if (java_extension.required) {
474       return false;
475     }
476   }
477   if (CBS_len(&extensions) != 0) {
478     return false;
479   }
480 
481   // JDK 11 never advertises X25519. It is not offered by default, and
482   // -Djdk.tls.namedGroups=x25519 does not work. This is unusual: many modern
483   // clients implement X25519.
484   while (CBS_len(&supported_groups) > 0) {
485     uint16_t group;
486     if (!CBS_get_u16(&supported_groups, &group) ||
487         group == SSL_CURVE_X25519) {
488       return false;
489     }
490   }
491 
492   if (// JDK 11 always sends the same contents in signature_algorithms and
493       // signature_algorithms_cert. This is unusual: signature_algorithms_cert,
494       // if omitted, is treated as if it were signature_algorithms.
495       sigalgs != sigalgs_cert ||
496       // When TLS 1.2 or below is enabled, JDK 11 sends status_request_v2 iff it
497       // sends status_request. This is unusual: status_request_v2 is not widely
498       // implemented.
499       has_status_request != has_status_request_v2) {
500     return false;
501   }
502 
503   return true;
504 }
505 
extract_sni(SSL_HANDSHAKE * hs,uint8_t * out_alert,const SSL_CLIENT_HELLO * client_hello)506 static bool extract_sni(SSL_HANDSHAKE *hs, uint8_t *out_alert,
507                         const SSL_CLIENT_HELLO *client_hello) {
508   SSL *const ssl = hs->ssl;
509   CBS sni;
510   if (!ssl_client_hello_get_extension(client_hello, &sni,
511                                       TLSEXT_TYPE_server_name)) {
512     // No SNI extension to parse.
513     return true;
514   }
515 
516   CBS server_name_list, host_name;
517   uint8_t name_type;
518   if (!CBS_get_u16_length_prefixed(&sni, &server_name_list) ||
519       !CBS_get_u8(&server_name_list, &name_type) ||
520       // Although the server_name extension was intended to be extensible to
521       // new name types and multiple names, OpenSSL 1.0.x had a bug which meant
522       // different name types will cause an error. Further, RFC 4366 originally
523       // defined syntax inextensibly. RFC 6066 corrected this mistake, but
524       // adding new name types is no longer feasible.
525       //
526       // Act as if the extensibility does not exist to simplify parsing.
527       !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
528       CBS_len(&server_name_list) != 0 ||
529       CBS_len(&sni) != 0) {
530     *out_alert = SSL_AD_DECODE_ERROR;
531     return false;
532   }
533 
534   if (name_type != TLSEXT_NAMETYPE_host_name ||
535       CBS_len(&host_name) == 0 ||
536       CBS_len(&host_name) > TLSEXT_MAXLEN_host_name ||
537       CBS_contains_zero_byte(&host_name)) {
538     *out_alert = SSL_AD_UNRECOGNIZED_NAME;
539     return false;
540   }
541 
542   // Copy the hostname as a string.
543   char *raw = nullptr;
544   if (!CBS_strdup(&host_name, &raw)) {
545     *out_alert = SSL_AD_INTERNAL_ERROR;
546     return false;
547   }
548   ssl->s3->hostname.reset(raw);
549 
550   hs->should_ack_sni = true;
551   return true;
552 }
553 
do_read_client_hello(SSL_HANDSHAKE * hs)554 static enum ssl_hs_wait_t do_read_client_hello(SSL_HANDSHAKE *hs) {
555   SSL *const ssl = hs->ssl;
556 
557   SSLMessage msg;
558   if (!ssl->method->get_message(ssl, &msg)) {
559     return ssl_hs_read_message;
560   }
561 
562   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CLIENT_HELLO)) {
563     return ssl_hs_error;
564   }
565 
566   SSL_CLIENT_HELLO client_hello;
567   if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
568     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
569     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
570     return ssl_hs_error;
571   }
572 
573   if (hs->config->handoff) {
574     return ssl_hs_handoff;
575   }
576 
577   uint8_t alert = SSL_AD_DECODE_ERROR;
578   if (!extract_sni(hs, &alert, &client_hello)) {
579     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
580     return ssl_hs_error;
581   }
582 
583   // Run the early callback.
584   if (ssl->ctx->select_certificate_cb != NULL) {
585     switch (ssl->ctx->select_certificate_cb(&client_hello)) {
586       case ssl_select_cert_retry:
587         return ssl_hs_certificate_selection_pending;
588 
589       case ssl_select_cert_error:
590         // Connection rejected.
591         OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
592         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
593         return ssl_hs_error;
594 
595       default:
596         /* fallthrough */;
597     }
598   }
599 
600   // Freeze the version range after the early callback.
601   if (!ssl_get_version_range(hs, &hs->min_version, &hs->max_version)) {
602     return ssl_hs_error;
603   }
604 
605   if (hs->config->jdk11_workaround &&
606       is_probably_jdk11_with_tls13(&client_hello)) {
607     hs->apply_jdk11_workaround = true;
608   }
609 
610   if (!negotiate_version(hs, &alert, &client_hello)) {
611     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
612     return ssl_hs_error;
613   }
614 
615   hs->client_version = client_hello.version;
616   if (client_hello.random_len != SSL3_RANDOM_SIZE) {
617     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
618     return ssl_hs_error;
619   }
620   OPENSSL_memcpy(ssl->s3->client_random, client_hello.random,
621                  client_hello.random_len);
622 
623   // Only null compression is supported. TLS 1.3 further requires the peer
624   // advertise no other compression.
625   if (OPENSSL_memchr(client_hello.compression_methods, 0,
626                      client_hello.compression_methods_len) == NULL ||
627       (ssl_protocol_version(ssl) >= TLS1_3_VERSION &&
628        client_hello.compression_methods_len != 1)) {
629     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_COMPRESSION_LIST);
630     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
631     return ssl_hs_error;
632   }
633 
634   // TLS extensions.
635   if (!ssl_parse_clienthello_tlsext(hs, &client_hello)) {
636     OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
637     return ssl_hs_error;
638   }
639 
640   hs->state = state12_select_certificate;
641   return ssl_hs_ok;
642 }
643 
do_select_certificate(SSL_HANDSHAKE * hs)644 static enum ssl_hs_wait_t do_select_certificate(SSL_HANDSHAKE *hs) {
645   SSL *const ssl = hs->ssl;
646 
647   SSLMessage msg;
648   if (!ssl->method->get_message(ssl, &msg)) {
649     return ssl_hs_read_message;
650   }
651 
652   // Call |cert_cb| to update server certificates if required.
653   if (hs->config->cert->cert_cb != NULL) {
654     int rv = hs->config->cert->cert_cb(ssl, hs->config->cert->cert_cb_arg);
655     if (rv == 0) {
656       OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
657       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
658       return ssl_hs_error;
659     }
660     if (rv < 0) {
661       return ssl_hs_x509_lookup;
662     }
663   }
664 
665   if (!ssl_on_certificate_selected(hs)) {
666     return ssl_hs_error;
667   }
668 
669   if (hs->ocsp_stapling_requested &&
670       ssl->ctx->legacy_ocsp_callback != nullptr) {
671     switch (ssl->ctx->legacy_ocsp_callback(
672         ssl, ssl->ctx->legacy_ocsp_callback_arg)) {
673       case SSL_TLSEXT_ERR_OK:
674         break;
675       case SSL_TLSEXT_ERR_NOACK:
676         hs->ocsp_stapling_requested = false;
677         break;
678       default:
679         OPENSSL_PUT_ERROR(SSL, SSL_R_OCSP_CB_ERROR);
680         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
681         return ssl_hs_error;
682     }
683   }
684 
685   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
686     // Jump to the TLS 1.3 state machine.
687     hs->state = state12_tls13;
688     return ssl_hs_ok;
689   }
690 
691   ssl->s3->early_data_reason = ssl_early_data_protocol_version;
692 
693   SSL_CLIENT_HELLO client_hello;
694   if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
695     return ssl_hs_error;
696   }
697 
698   // Negotiate the cipher suite. This must be done after |cert_cb| so the
699   // certificate is finalized.
700   SSLCipherPreferenceList *prefs = hs->config->cipher_list
701                                        ? hs->config->cipher_list.get()
702                                        : ssl->ctx->cipher_list.get();
703   hs->new_cipher = ssl3_choose_cipher(hs, &client_hello, prefs);
704   if (hs->new_cipher == NULL) {
705     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_CIPHER);
706     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
707     return ssl_hs_error;
708   }
709 
710   hs->state = state12_select_parameters;
711   return ssl_hs_ok;
712 }
713 
do_tls13(SSL_HANDSHAKE * hs)714 static enum ssl_hs_wait_t do_tls13(SSL_HANDSHAKE *hs) {
715   enum ssl_hs_wait_t wait = tls13_server_handshake(hs);
716   if (wait == ssl_hs_ok) {
717     hs->state = state12_finish_server_handshake;
718     return ssl_hs_ok;
719   }
720 
721   return wait;
722 }
723 
do_select_parameters(SSL_HANDSHAKE * hs)724 static enum ssl_hs_wait_t do_select_parameters(SSL_HANDSHAKE *hs) {
725   SSL *const ssl = hs->ssl;
726 
727   SSLMessage msg;
728   if (!ssl->method->get_message(ssl, &msg)) {
729     return ssl_hs_read_message;
730   }
731 
732   SSL_CLIENT_HELLO client_hello;
733   if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
734     return ssl_hs_error;
735   }
736 
737   // Determine whether we are doing session resumption.
738   UniquePtr<SSL_SESSION> session;
739   bool tickets_supported = false, renew_ticket = false;
740   enum ssl_hs_wait_t wait = ssl_get_prev_session(
741       hs, &session, &tickets_supported, &renew_ticket, &client_hello);
742   if (wait != ssl_hs_ok) {
743     return wait;
744   }
745 
746   if (session) {
747     if (session->extended_master_secret && !hs->extended_master_secret) {
748       // A ClientHello without EMS that attempts to resume a session with EMS
749       // is fatal to the connection.
750       OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
751       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
752       return ssl_hs_error;
753     }
754 
755     if (!ssl_session_is_resumable(hs, session.get()) ||
756         // If the client offers the EMS extension, but the previous session
757         // didn't use it, then negotiate a new session.
758         hs->extended_master_secret != session->extended_master_secret) {
759       session.reset();
760     }
761   }
762 
763   if (session) {
764     // Use the old session.
765     hs->ticket_expected = renew_ticket;
766     ssl->session = std::move(session);
767     ssl->s3->session_reused = true;
768   } else {
769     hs->ticket_expected = tickets_supported;
770     ssl_set_session(ssl, NULL);
771     if (!ssl_get_new_session(hs, 1 /* server */)) {
772       return ssl_hs_error;
773     }
774 
775     // Clear the session ID if we want the session to be single-use.
776     if (!(ssl->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)) {
777       hs->new_session->session_id_length = 0;
778     }
779   }
780 
781   if (ssl->ctx->dos_protection_cb != NULL &&
782       ssl->ctx->dos_protection_cb(&client_hello) == 0) {
783     // Connection rejected for DOS reasons.
784     OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
785     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
786     return ssl_hs_error;
787   }
788 
789   if (ssl->session == NULL) {
790     hs->new_session->cipher = hs->new_cipher;
791 
792     // Determine whether to request a client certificate.
793     hs->cert_request = !!(hs->config->verify_mode & SSL_VERIFY_PEER);
794     // Only request a certificate if Channel ID isn't negotiated.
795     if ((hs->config->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
796         ssl->s3->channel_id_valid) {
797       hs->cert_request = false;
798     }
799     // CertificateRequest may only be sent in certificate-based ciphers.
800     if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
801       hs->cert_request = false;
802     }
803 
804     if (!hs->cert_request) {
805       // OpenSSL returns X509_V_OK when no certificates are requested. This is
806       // classed by them as a bug, but it's assumed by at least NGINX.
807       hs->new_session->verify_result = X509_V_OK;
808     }
809   }
810 
811   // HTTP/2 negotiation depends on the cipher suite, so ALPN negotiation was
812   // deferred. Complete it now.
813   uint8_t alert = SSL_AD_DECODE_ERROR;
814   if (!ssl_negotiate_alpn(hs, &alert, &client_hello)) {
815     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
816     return ssl_hs_error;
817   }
818 
819   // Now that all parameters are known, initialize the handshake hash and hash
820   // the ClientHello.
821   if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher) ||
822       !ssl_hash_message(hs, msg)) {
823     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
824     return ssl_hs_error;
825   }
826 
827   // Handback includes the whole handshake transcript, so we cannot free the
828   // transcript buffer in the handback case.
829   if (!hs->cert_request && !hs->handback) {
830     hs->transcript.FreeBuffer();
831   }
832 
833   ssl->method->next_message(ssl);
834 
835   hs->state = state12_send_server_hello;
836   return ssl_hs_ok;
837 }
838 
copy_suffix(Span<uint8_t> out,Span<const uint8_t> in)839 static void copy_suffix(Span<uint8_t> out, Span<const uint8_t> in) {
840   out = out.subspan(out.size() - in.size());
841   assert(out.size() == in.size());
842   OPENSSL_memcpy(out.data(), in.data(), in.size());
843 }
844 
do_send_server_hello(SSL_HANDSHAKE * hs)845 static enum ssl_hs_wait_t do_send_server_hello(SSL_HANDSHAKE *hs) {
846   SSL *const ssl = hs->ssl;
847 
848   // We only accept ChannelIDs on connections with ECDHE in order to avoid a
849   // known attack while we fix ChannelID itself.
850   if (ssl->s3->channel_id_valid &&
851       (hs->new_cipher->algorithm_mkey & SSL_kECDHE) == 0) {
852     ssl->s3->channel_id_valid = false;
853   }
854 
855   // If this is a resumption and the original handshake didn't support
856   // ChannelID then we didn't record the original handshake hashes in the
857   // session and so cannot resume with ChannelIDs.
858   if (ssl->session != NULL &&
859       ssl->session->original_handshake_hash_len == 0) {
860     ssl->s3->channel_id_valid = false;
861   }
862 
863   struct OPENSSL_timeval now;
864   ssl_get_current_time(ssl, &now);
865   ssl->s3->server_random[0] = now.tv_sec >> 24;
866   ssl->s3->server_random[1] = now.tv_sec >> 16;
867   ssl->s3->server_random[2] = now.tv_sec >> 8;
868   ssl->s3->server_random[3] = now.tv_sec;
869   if (!RAND_bytes(ssl->s3->server_random + 4, SSL3_RANDOM_SIZE - 4)) {
870     return ssl_hs_error;
871   }
872 
873   // Implement the TLS 1.3 anti-downgrade feature.
874   if (ssl_supports_version(hs, TLS1_3_VERSION)) {
875     if (ssl_protocol_version(ssl) == TLS1_2_VERSION) {
876       if (hs->apply_jdk11_workaround) {
877         // JDK 11 implements the TLS 1.3 downgrade signal, so we cannot send it
878         // here. However, the signal is only effective if all TLS 1.2
879         // ServerHellos produced by the server are marked. Thus we send a
880         // different non-standard signal for the time being, until JDK 11.0.2 is
881         // released and clients have updated.
882         copy_suffix(ssl->s3->server_random, kJDK11DowngradeRandom);
883       } else {
884         copy_suffix(ssl->s3->server_random, kTLS13DowngradeRandom);
885       }
886     } else {
887       copy_suffix(ssl->s3->server_random, kTLS12DowngradeRandom);
888     }
889   }
890 
891   const SSL_SESSION *session = hs->new_session.get();
892   if (ssl->session != nullptr) {
893     session = ssl->session.get();
894   }
895 
896   ScopedCBB cbb;
897   CBB body, session_id;
898   if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_SERVER_HELLO) ||
899       !CBB_add_u16(&body, ssl->version) ||
900       !CBB_add_bytes(&body, ssl->s3->server_random, SSL3_RANDOM_SIZE) ||
901       !CBB_add_u8_length_prefixed(&body, &session_id) ||
902       !CBB_add_bytes(&session_id, session->session_id,
903                      session->session_id_length) ||
904       !CBB_add_u16(&body, ssl_cipher_get_value(hs->new_cipher)) ||
905       !CBB_add_u8(&body, 0 /* no compression */) ||
906       !ssl_add_serverhello_tlsext(hs, &body) ||
907       !ssl_add_message_cbb(ssl, cbb.get())) {
908     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
909     return ssl_hs_error;
910   }
911 
912   if (ssl->session != NULL) {
913     hs->state = state12_send_server_finished;
914   } else {
915     hs->state = state12_send_server_certificate;
916   }
917   return ssl_hs_ok;
918 }
919 
do_send_server_certificate(SSL_HANDSHAKE * hs)920 static enum ssl_hs_wait_t do_send_server_certificate(SSL_HANDSHAKE *hs) {
921   SSL *const ssl = hs->ssl;
922   ScopedCBB cbb;
923 
924   if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
925     if (!ssl_has_certificate(hs)) {
926       OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATE_SET);
927       return ssl_hs_error;
928     }
929 
930     if (!ssl_output_cert_chain(hs)) {
931       return ssl_hs_error;
932     }
933 
934     if (hs->certificate_status_expected) {
935       CBB body, ocsp_response;
936       if (!ssl->method->init_message(ssl, cbb.get(), &body,
937                                      SSL3_MT_CERTIFICATE_STATUS) ||
938           !CBB_add_u8(&body, TLSEXT_STATUSTYPE_ocsp) ||
939           !CBB_add_u24_length_prefixed(&body, &ocsp_response) ||
940           !CBB_add_bytes(
941               &ocsp_response,
942               CRYPTO_BUFFER_data(hs->config->cert->ocsp_response.get()),
943               CRYPTO_BUFFER_len(hs->config->cert->ocsp_response.get())) ||
944           !ssl_add_message_cbb(ssl, cbb.get())) {
945         OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
946         return ssl_hs_error;
947       }
948     }
949   }
950 
951   // Assemble ServerKeyExchange parameters if needed.
952   uint32_t alg_k = hs->new_cipher->algorithm_mkey;
953   uint32_t alg_a = hs->new_cipher->algorithm_auth;
954   if (ssl_cipher_requires_server_key_exchange(hs->new_cipher) ||
955       ((alg_a & SSL_aPSK) && hs->config->psk_identity_hint)) {
956     // Pre-allocate enough room to comfortably fit an ECDHE public key. Prepend
957     // the client and server randoms for the signing transcript.
958     CBB child;
959     if (!CBB_init(cbb.get(), SSL3_RANDOM_SIZE * 2 + 128) ||
960         !CBB_add_bytes(cbb.get(), ssl->s3->client_random, SSL3_RANDOM_SIZE) ||
961         !CBB_add_bytes(cbb.get(), ssl->s3->server_random, SSL3_RANDOM_SIZE)) {
962       return ssl_hs_error;
963     }
964 
965     // PSK ciphers begin with an identity hint.
966     if (alg_a & SSL_aPSK) {
967       size_t len = hs->config->psk_identity_hint == nullptr
968                        ? 0
969                        : strlen(hs->config->psk_identity_hint.get());
970       if (!CBB_add_u16_length_prefixed(cbb.get(), &child) ||
971           !CBB_add_bytes(&child,
972                          (const uint8_t *)hs->config->psk_identity_hint.get(),
973                          len)) {
974         return ssl_hs_error;
975       }
976     }
977 
978     if (alg_k & SSL_kECDHE) {
979       // Determine the group to use.
980       uint16_t group_id;
981       if (!tls1_get_shared_group(hs, &group_id)) {
982         OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
983         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
984         return ssl_hs_error;
985        }
986       hs->new_session->group_id = group_id;
987 
988       // Set up ECDH, generate a key, and emit the public half.
989       hs->key_shares[0] = SSLKeyShare::Create(group_id);
990       if (!hs->key_shares[0] ||
991           !CBB_add_u8(cbb.get(), NAMED_CURVE_TYPE) ||
992           !CBB_add_u16(cbb.get(), group_id) ||
993           !CBB_add_u8_length_prefixed(cbb.get(), &child) ||
994           !hs->key_shares[0]->Offer(&child)) {
995         return ssl_hs_error;
996       }
997     } else {
998       assert(alg_k & SSL_kPSK);
999     }
1000 
1001     if (!CBBFinishArray(cbb.get(), &hs->server_params)) {
1002       return ssl_hs_error;
1003     }
1004   }
1005 
1006   hs->state = state12_send_server_key_exchange;
1007   return ssl_hs_ok;
1008 }
1009 
do_send_server_key_exchange(SSL_HANDSHAKE * hs)1010 static enum ssl_hs_wait_t do_send_server_key_exchange(SSL_HANDSHAKE *hs) {
1011   SSL *const ssl = hs->ssl;
1012 
1013   if (hs->server_params.size() == 0) {
1014     hs->state = state12_send_server_hello_done;
1015     return ssl_hs_ok;
1016   }
1017 
1018   ScopedCBB cbb;
1019   CBB body, child;
1020   if (!ssl->method->init_message(ssl, cbb.get(), &body,
1021                                  SSL3_MT_SERVER_KEY_EXCHANGE) ||
1022       // |hs->server_params| contains a prefix for signing.
1023       hs->server_params.size() < 2 * SSL3_RANDOM_SIZE ||
1024       !CBB_add_bytes(&body, hs->server_params.data() + 2 * SSL3_RANDOM_SIZE,
1025                      hs->server_params.size() - 2 * SSL3_RANDOM_SIZE)) {
1026     return ssl_hs_error;
1027   }
1028 
1029   // Add a signature.
1030   if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1031     if (!ssl_has_private_key(hs)) {
1032       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1033       return ssl_hs_error;
1034     }
1035 
1036     // Determine the signature algorithm.
1037     uint16_t signature_algorithm;
1038     if (!tls1_choose_signature_algorithm(hs, &signature_algorithm)) {
1039       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1040       return ssl_hs_error;
1041     }
1042     if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1043       if (!CBB_add_u16(&body, signature_algorithm)) {
1044         OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1045         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1046         return ssl_hs_error;
1047       }
1048     }
1049 
1050     // Add space for the signature.
1051     const size_t max_sig_len = EVP_PKEY_size(hs->local_pubkey.get());
1052     uint8_t *ptr;
1053     if (!CBB_add_u16_length_prefixed(&body, &child) ||
1054         !CBB_reserve(&child, &ptr, max_sig_len)) {
1055       return ssl_hs_error;
1056     }
1057 
1058     size_t sig_len;
1059     switch (ssl_private_key_sign(hs, ptr, &sig_len, max_sig_len,
1060                                  signature_algorithm, hs->server_params)) {
1061       case ssl_private_key_success:
1062         if (!CBB_did_write(&child, sig_len)) {
1063           return ssl_hs_error;
1064         }
1065         break;
1066       case ssl_private_key_failure:
1067         return ssl_hs_error;
1068       case ssl_private_key_retry:
1069         return ssl_hs_private_key_operation;
1070     }
1071   }
1072 
1073   if (!ssl_add_message_cbb(ssl, cbb.get())) {
1074     return ssl_hs_error;
1075   }
1076 
1077   hs->server_params.Reset();
1078 
1079   hs->state = state12_send_server_hello_done;
1080   return ssl_hs_ok;
1081 }
1082 
do_send_server_hello_done(SSL_HANDSHAKE * hs)1083 static enum ssl_hs_wait_t do_send_server_hello_done(SSL_HANDSHAKE *hs) {
1084   SSL *const ssl = hs->ssl;
1085 
1086   ScopedCBB cbb;
1087   CBB body;
1088 
1089   if (hs->cert_request) {
1090     CBB cert_types, sigalgs_cbb;
1091     if (!ssl->method->init_message(ssl, cbb.get(), &body,
1092                                    SSL3_MT_CERTIFICATE_REQUEST) ||
1093         !CBB_add_u8_length_prefixed(&body, &cert_types) ||
1094         !CBB_add_u8(&cert_types, SSL3_CT_RSA_SIGN) ||
1095         !CBB_add_u8(&cert_types, TLS_CT_ECDSA_SIGN) ||
1096         // TLS 1.2 has no way to specify different signature algorithms for
1097         // certificates and the online signature, so emit the more restrictive
1098         // certificate list.
1099         (ssl_protocol_version(ssl) >= TLS1_2_VERSION &&
1100          (!CBB_add_u16_length_prefixed(&body, &sigalgs_cbb) ||
1101           !tls12_add_verify_sigalgs(ssl, &sigalgs_cbb, true /* certs */))) ||
1102         !ssl_add_client_CA_list(hs, &body) ||
1103         !ssl_add_message_cbb(ssl, cbb.get())) {
1104       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1105       return ssl_hs_error;
1106     }
1107   }
1108 
1109   if (!ssl->method->init_message(ssl, cbb.get(), &body,
1110                                  SSL3_MT_SERVER_HELLO_DONE) ||
1111       !ssl_add_message_cbb(ssl, cbb.get())) {
1112     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1113     return ssl_hs_error;
1114   }
1115 
1116   hs->state = state12_read_client_certificate;
1117   return ssl_hs_flush;
1118 }
1119 
do_read_client_certificate(SSL_HANDSHAKE * hs)1120 static enum ssl_hs_wait_t do_read_client_certificate(SSL_HANDSHAKE *hs) {
1121   SSL *const ssl = hs->ssl;
1122 
1123   if (hs->handback && hs->new_cipher->algorithm_mkey == SSL_kECDHE) {
1124     return ssl_hs_handback;
1125   }
1126   if (!hs->cert_request) {
1127     hs->state = state12_verify_client_certificate;
1128     return ssl_hs_ok;
1129   }
1130 
1131   SSLMessage msg;
1132   if (!ssl->method->get_message(ssl, &msg)) {
1133     return ssl_hs_read_message;
1134   }
1135 
1136   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE)) {
1137     return ssl_hs_error;
1138   }
1139 
1140   if (!ssl_hash_message(hs, msg)) {
1141     return ssl_hs_error;
1142   }
1143 
1144   CBS certificate_msg = msg.body;
1145   uint8_t alert = SSL_AD_DECODE_ERROR;
1146   if (!ssl_parse_cert_chain(&alert, &hs->new_session->certs, &hs->peer_pubkey,
1147                             hs->config->retain_only_sha256_of_client_certs
1148                                 ? hs->new_session->peer_sha256
1149                                 : nullptr,
1150                             &certificate_msg, ssl->ctx->pool)) {
1151     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1152     return ssl_hs_error;
1153   }
1154 
1155   if (CBS_len(&certificate_msg) != 0 ||
1156       !ssl->ctx->x509_method->session_cache_objects(hs->new_session.get())) {
1157     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1158     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1159     return ssl_hs_error;
1160   }
1161 
1162   if (sk_CRYPTO_BUFFER_num(hs->new_session->certs.get()) == 0) {
1163     // No client certificate so the handshake buffer may be discarded.
1164     hs->transcript.FreeBuffer();
1165 
1166     if (hs->config->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
1167       // Fail for TLS only if we required a certificate
1168       OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
1169       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1170       return ssl_hs_error;
1171     }
1172 
1173     // OpenSSL returns X509_V_OK when no certificates are received. This is
1174     // classed by them as a bug, but it's assumed by at least NGINX.
1175     hs->new_session->verify_result = X509_V_OK;
1176   } else if (hs->config->retain_only_sha256_of_client_certs) {
1177     // The hash will have been filled in.
1178     hs->new_session->peer_sha256_valid = 1;
1179   }
1180 
1181   ssl->method->next_message(ssl);
1182   hs->state = state12_verify_client_certificate;
1183   return ssl_hs_ok;
1184 }
1185 
do_verify_client_certificate(SSL_HANDSHAKE * hs)1186 static enum ssl_hs_wait_t do_verify_client_certificate(SSL_HANDSHAKE *hs) {
1187   if (sk_CRYPTO_BUFFER_num(hs->new_session->certs.get()) > 0) {
1188     switch (ssl_verify_peer_cert(hs)) {
1189       case ssl_verify_ok:
1190         break;
1191       case ssl_verify_invalid:
1192         return ssl_hs_error;
1193       case ssl_verify_retry:
1194         return ssl_hs_certificate_verify;
1195     }
1196   }
1197 
1198   hs->state = state12_read_client_key_exchange;
1199   return ssl_hs_ok;
1200 }
1201 
do_read_client_key_exchange(SSL_HANDSHAKE * hs)1202 static enum ssl_hs_wait_t do_read_client_key_exchange(SSL_HANDSHAKE *hs) {
1203   SSL *const ssl = hs->ssl;
1204   SSLMessage msg;
1205   if (!ssl->method->get_message(ssl, &msg)) {
1206     return ssl_hs_read_message;
1207   }
1208 
1209   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CLIENT_KEY_EXCHANGE)) {
1210     return ssl_hs_error;
1211   }
1212 
1213   CBS client_key_exchange = msg.body;
1214   uint32_t alg_k = hs->new_cipher->algorithm_mkey;
1215   uint32_t alg_a = hs->new_cipher->algorithm_auth;
1216 
1217   // If using a PSK key exchange, parse the PSK identity.
1218   if (alg_a & SSL_aPSK) {
1219     CBS psk_identity;
1220 
1221     // If using PSK, the ClientKeyExchange contains a psk_identity. If PSK,
1222     // then this is the only field in the message.
1223     if (!CBS_get_u16_length_prefixed(&client_key_exchange, &psk_identity) ||
1224         ((alg_k & SSL_kPSK) && CBS_len(&client_key_exchange) != 0)) {
1225       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1226       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1227       return ssl_hs_error;
1228     }
1229 
1230     if (CBS_len(&psk_identity) > PSK_MAX_IDENTITY_LEN ||
1231         CBS_contains_zero_byte(&psk_identity)) {
1232       OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
1233       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
1234       return ssl_hs_error;
1235     }
1236     char *raw = nullptr;
1237     if (!CBS_strdup(&psk_identity, &raw)) {
1238       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1239       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1240       return ssl_hs_error;
1241     }
1242     hs->new_session->psk_identity.reset(raw);
1243   }
1244 
1245   // Depending on the key exchange method, compute |premaster_secret|.
1246   Array<uint8_t> premaster_secret;
1247   if (alg_k & SSL_kRSA) {
1248     CBS encrypted_premaster_secret;
1249     if (!CBS_get_u16_length_prefixed(&client_key_exchange,
1250                                      &encrypted_premaster_secret) ||
1251         CBS_len(&client_key_exchange) != 0) {
1252       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1253       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1254       return ssl_hs_error;
1255     }
1256 
1257     // Allocate a buffer large enough for an RSA decryption.
1258     Array<uint8_t> decrypt_buf;
1259     if (!decrypt_buf.Init(EVP_PKEY_size(hs->local_pubkey.get()))) {
1260       return ssl_hs_error;
1261     }
1262 
1263     // Decrypt with no padding. PKCS#1 padding will be removed as part of the
1264     // timing-sensitive code below.
1265     size_t decrypt_len;
1266     switch (ssl_private_key_decrypt(hs, decrypt_buf.data(), &decrypt_len,
1267                                     decrypt_buf.size(),
1268                                     encrypted_premaster_secret)) {
1269       case ssl_private_key_success:
1270         break;
1271       case ssl_private_key_failure:
1272         return ssl_hs_error;
1273       case ssl_private_key_retry:
1274         return ssl_hs_private_key_operation;
1275     }
1276 
1277     if (decrypt_len != decrypt_buf.size()) {
1278       OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
1279       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
1280       return ssl_hs_error;
1281     }
1282 
1283     CONSTTIME_SECRET(decrypt_buf.data(), decrypt_len);
1284 
1285     // Prepare a random premaster, to be used on invalid padding. See RFC 5246,
1286     // section 7.4.7.1.
1287     if (!premaster_secret.Init(SSL_MAX_MASTER_KEY_LENGTH) ||
1288         !RAND_bytes(premaster_secret.data(), premaster_secret.size())) {
1289       return ssl_hs_error;
1290     }
1291 
1292     // The smallest padded premaster is 11 bytes of overhead. Small keys are
1293     // publicly invalid.
1294     if (decrypt_len < 11 + premaster_secret.size()) {
1295       OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
1296       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
1297       return ssl_hs_error;
1298     }
1299 
1300     // Check the padding. See RFC 3447, section 7.2.2.
1301     size_t padding_len = decrypt_len - premaster_secret.size();
1302     uint8_t good = constant_time_eq_int_8(decrypt_buf[0], 0) &
1303                    constant_time_eq_int_8(decrypt_buf[1], 2);
1304     for (size_t i = 2; i < padding_len - 1; i++) {
1305       good &= ~constant_time_is_zero_8(decrypt_buf[i]);
1306     }
1307     good &= constant_time_is_zero_8(decrypt_buf[padding_len - 1]);
1308 
1309     // The premaster secret must begin with |client_version|. This too must be
1310     // checked in constant time (http://eprint.iacr.org/2003/052/).
1311     good &= constant_time_eq_8(decrypt_buf[padding_len],
1312                                (unsigned)(hs->client_version >> 8));
1313     good &= constant_time_eq_8(decrypt_buf[padding_len + 1],
1314                                (unsigned)(hs->client_version & 0xff));
1315 
1316     // Select, in constant time, either the decrypted premaster or the random
1317     // premaster based on |good|.
1318     for (size_t i = 0; i < premaster_secret.size(); i++) {
1319       premaster_secret[i] = constant_time_select_8(
1320           good, decrypt_buf[padding_len + i], premaster_secret[i]);
1321     }
1322   } else if (alg_k & SSL_kECDHE) {
1323     // Parse the ClientKeyExchange.
1324     CBS peer_key;
1325     if (!CBS_get_u8_length_prefixed(&client_key_exchange, &peer_key) ||
1326         CBS_len(&client_key_exchange) != 0) {
1327       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1328       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1329       return ssl_hs_error;
1330     }
1331 
1332     // Compute the premaster.
1333     uint8_t alert = SSL_AD_DECODE_ERROR;
1334     if (!hs->key_shares[0]->Finish(&premaster_secret, &alert, peer_key)) {
1335       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1336       return ssl_hs_error;
1337     }
1338 
1339     // The key exchange state may now be discarded.
1340     hs->key_shares[0].reset();
1341     hs->key_shares[1].reset();
1342   } else if (!(alg_k & SSL_kPSK)) {
1343     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1344     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1345     return ssl_hs_error;
1346   }
1347 
1348   // For a PSK cipher suite, the actual pre-master secret is combined with the
1349   // pre-shared key.
1350   if (alg_a & SSL_aPSK) {
1351     if (hs->config->psk_server_callback == NULL) {
1352       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1353       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1354       return ssl_hs_error;
1355     }
1356 
1357     // Look up the key for the identity.
1358     uint8_t psk[PSK_MAX_PSK_LEN];
1359     unsigned psk_len = hs->config->psk_server_callback(
1360         ssl, hs->new_session->psk_identity.get(), psk, sizeof(psk));
1361     if (psk_len > PSK_MAX_PSK_LEN) {
1362       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1363       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1364       return ssl_hs_error;
1365     } else if (psk_len == 0) {
1366       // PSK related to the given identity not found.
1367       OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
1368       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNKNOWN_PSK_IDENTITY);
1369       return ssl_hs_error;
1370     }
1371 
1372     if (alg_k & SSL_kPSK) {
1373       // In plain PSK, other_secret is a block of 0s with the same length as the
1374       // pre-shared key.
1375       if (!premaster_secret.Init(psk_len)) {
1376         return ssl_hs_error;
1377       }
1378       OPENSSL_memset(premaster_secret.data(), 0, premaster_secret.size());
1379     }
1380 
1381     ScopedCBB new_premaster;
1382     CBB child;
1383     if (!CBB_init(new_premaster.get(),
1384                   2 + psk_len + 2 + premaster_secret.size()) ||
1385         !CBB_add_u16_length_prefixed(new_premaster.get(), &child) ||
1386         !CBB_add_bytes(&child, premaster_secret.data(),
1387                        premaster_secret.size()) ||
1388         !CBB_add_u16_length_prefixed(new_premaster.get(), &child) ||
1389         !CBB_add_bytes(&child, psk, psk_len) ||
1390         !CBBFinishArray(new_premaster.get(), &premaster_secret)) {
1391       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1392       return ssl_hs_error;
1393     }
1394   }
1395 
1396   if (!ssl_hash_message(hs, msg)) {
1397     return ssl_hs_error;
1398   }
1399 
1400   // Compute the master secret.
1401   hs->new_session->master_key_length = tls1_generate_master_secret(
1402       hs, hs->new_session->master_key, premaster_secret);
1403   if (hs->new_session->master_key_length == 0) {
1404     return ssl_hs_error;
1405   }
1406   hs->new_session->extended_master_secret = hs->extended_master_secret;
1407   CONSTTIME_DECLASSIFY(hs->new_session->master_key,
1408                        hs->new_session->master_key_length);
1409 
1410   ssl->method->next_message(ssl);
1411   hs->state = state12_read_client_certificate_verify;
1412   return ssl_hs_ok;
1413 }
1414 
do_read_client_certificate_verify(SSL_HANDSHAKE * hs)1415 static enum ssl_hs_wait_t do_read_client_certificate_verify(SSL_HANDSHAKE *hs) {
1416   SSL *const ssl = hs->ssl;
1417 
1418   // Only RSA and ECDSA client certificates are supported, so a
1419   // CertificateVerify is required if and only if there's a client certificate.
1420   if (!hs->peer_pubkey) {
1421     hs->transcript.FreeBuffer();
1422     hs->state = state12_read_change_cipher_spec;
1423     return ssl_hs_ok;
1424   }
1425 
1426   SSLMessage msg;
1427   if (!ssl->method->get_message(ssl, &msg)) {
1428     return ssl_hs_read_message;
1429   }
1430 
1431   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_VERIFY)) {
1432     return ssl_hs_error;
1433   }
1434 
1435   CBS certificate_verify = msg.body, signature;
1436 
1437   // Determine the signature algorithm.
1438   uint16_t signature_algorithm = 0;
1439   if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1440     if (!CBS_get_u16(&certificate_verify, &signature_algorithm)) {
1441       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1442       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1443       return ssl_hs_error;
1444     }
1445     uint8_t alert = SSL_AD_DECODE_ERROR;
1446     if (!tls12_check_peer_sigalg(ssl, &alert, signature_algorithm)) {
1447       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1448       return ssl_hs_error;
1449     }
1450     hs->new_session->peer_signature_algorithm = signature_algorithm;
1451   } else if (!tls1_get_legacy_signature_algorithm(&signature_algorithm,
1452                                                   hs->peer_pubkey.get())) {
1453     OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
1454     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_CERTIFICATE);
1455     return ssl_hs_error;
1456   }
1457 
1458   // Parse and verify the signature.
1459   if (!CBS_get_u16_length_prefixed(&certificate_verify, &signature) ||
1460       CBS_len(&certificate_verify) != 0) {
1461     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1462     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1463     return ssl_hs_error;
1464   }
1465 
1466   if (!ssl_public_key_verify(ssl, signature, signature_algorithm,
1467                              hs->peer_pubkey.get(), hs->transcript.buffer())) {
1468     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
1469     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
1470     return ssl_hs_error;
1471   }
1472 
1473   // The handshake buffer is no longer necessary, and we may hash the current
1474   // message.
1475   hs->transcript.FreeBuffer();
1476   if (!ssl_hash_message(hs, msg)) {
1477     return ssl_hs_error;
1478   }
1479 
1480   ssl->method->next_message(ssl);
1481   hs->state = state12_read_change_cipher_spec;
1482   return ssl_hs_ok;
1483 }
1484 
do_read_change_cipher_spec(SSL_HANDSHAKE * hs)1485 static enum ssl_hs_wait_t do_read_change_cipher_spec(SSL_HANDSHAKE *hs) {
1486   if (hs->handback && hs->ssl->session != NULL) {
1487     return ssl_hs_handback;
1488   }
1489   hs->state = state12_process_change_cipher_spec;
1490   return ssl_hs_read_change_cipher_spec;
1491 }
1492 
do_process_change_cipher_spec(SSL_HANDSHAKE * hs)1493 static enum ssl_hs_wait_t do_process_change_cipher_spec(SSL_HANDSHAKE *hs) {
1494   if (!tls1_change_cipher_state(hs, evp_aead_open)) {
1495     return ssl_hs_error;
1496   }
1497 
1498   hs->state = state12_read_next_proto;
1499   return ssl_hs_ok;
1500 }
1501 
do_read_next_proto(SSL_HANDSHAKE * hs)1502 static enum ssl_hs_wait_t do_read_next_proto(SSL_HANDSHAKE *hs) {
1503   SSL *const ssl = hs->ssl;
1504 
1505   if (!hs->next_proto_neg_seen) {
1506     hs->state = state12_read_channel_id;
1507     return ssl_hs_ok;
1508   }
1509 
1510   SSLMessage msg;
1511   if (!ssl->method->get_message(ssl, &msg)) {
1512     return ssl_hs_read_message;
1513   }
1514 
1515   if (!ssl_check_message_type(ssl, msg, SSL3_MT_NEXT_PROTO) ||
1516       !ssl_hash_message(hs, msg)) {
1517     return ssl_hs_error;
1518   }
1519 
1520   CBS next_protocol = msg.body, selected_protocol, padding;
1521   if (!CBS_get_u8_length_prefixed(&next_protocol, &selected_protocol) ||
1522       !CBS_get_u8_length_prefixed(&next_protocol, &padding) ||
1523       CBS_len(&next_protocol) != 0) {
1524     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1525     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1526     return ssl_hs_error;
1527   }
1528 
1529   if (!ssl->s3->next_proto_negotiated.CopyFrom(selected_protocol)) {
1530     return ssl_hs_error;
1531   }
1532 
1533   ssl->method->next_message(ssl);
1534   hs->state = state12_read_channel_id;
1535   return ssl_hs_ok;
1536 }
1537 
do_read_channel_id(SSL_HANDSHAKE * hs)1538 static enum ssl_hs_wait_t do_read_channel_id(SSL_HANDSHAKE *hs) {
1539   SSL *const ssl = hs->ssl;
1540 
1541   if (!ssl->s3->channel_id_valid) {
1542     hs->state = state12_read_client_finished;
1543     return ssl_hs_ok;
1544   }
1545 
1546   SSLMessage msg;
1547   if (!ssl->method->get_message(ssl, &msg)) {
1548     return ssl_hs_read_message;
1549   }
1550 
1551   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CHANNEL_ID) ||
1552       !tls1_verify_channel_id(hs, msg) ||
1553       !ssl_hash_message(hs, msg)) {
1554     return ssl_hs_error;
1555   }
1556 
1557   ssl->method->next_message(ssl);
1558   hs->state = state12_read_client_finished;
1559   return ssl_hs_ok;
1560 }
1561 
do_read_client_finished(SSL_HANDSHAKE * hs)1562 static enum ssl_hs_wait_t do_read_client_finished(SSL_HANDSHAKE *hs) {
1563   SSL *const ssl = hs->ssl;
1564   enum ssl_hs_wait_t wait = ssl_get_finished(hs);
1565   if (wait != ssl_hs_ok) {
1566     return wait;
1567   }
1568 
1569   if (ssl->session != NULL) {
1570     hs->state = state12_finish_server_handshake;
1571   } else {
1572     hs->state = state12_send_server_finished;
1573   }
1574 
1575   // If this is a full handshake with ChannelID then record the handshake
1576   // hashes in |hs->new_session| in case we need them to verify a
1577   // ChannelID signature on a resumption of this session in the future.
1578   if (ssl->session == NULL && ssl->s3->channel_id_valid &&
1579       !tls1_record_handshake_hashes_for_channel_id(hs)) {
1580     return ssl_hs_error;
1581   }
1582 
1583   return ssl_hs_ok;
1584 }
1585 
do_send_server_finished(SSL_HANDSHAKE * hs)1586 static enum ssl_hs_wait_t do_send_server_finished(SSL_HANDSHAKE *hs) {
1587   SSL *const ssl = hs->ssl;
1588 
1589   if (hs->ticket_expected) {
1590     const SSL_SESSION *session;
1591     UniquePtr<SSL_SESSION> session_copy;
1592     if (ssl->session == NULL) {
1593       // Fix the timeout to measure from the ticket issuance time.
1594       ssl_session_rebase_time(ssl, hs->new_session.get());
1595       session = hs->new_session.get();
1596     } else {
1597       // We are renewing an existing session. Duplicate the session to adjust
1598       // the timeout.
1599       session_copy =
1600           SSL_SESSION_dup(ssl->session.get(), SSL_SESSION_INCLUDE_NONAUTH);
1601       if (!session_copy) {
1602         return ssl_hs_error;
1603       }
1604 
1605       ssl_session_rebase_time(ssl, session_copy.get());
1606       session = session_copy.get();
1607     }
1608 
1609     ScopedCBB cbb;
1610     CBB body, ticket;
1611     if (!ssl->method->init_message(ssl, cbb.get(), &body,
1612                                    SSL3_MT_NEW_SESSION_TICKET) ||
1613         !CBB_add_u32(&body, session->timeout) ||
1614         !CBB_add_u16_length_prefixed(&body, &ticket) ||
1615         !ssl_encrypt_ticket(hs, &ticket, session) ||
1616         !ssl_add_message_cbb(ssl, cbb.get())) {
1617       return ssl_hs_error;
1618     }
1619   }
1620 
1621   if (!ssl->method->add_change_cipher_spec(ssl) ||
1622       !tls1_change_cipher_state(hs, evp_aead_seal) ||
1623       !ssl_send_finished(hs)) {
1624     return ssl_hs_error;
1625   }
1626 
1627   if (ssl->session != NULL) {
1628     hs->state = state12_read_change_cipher_spec;
1629   } else {
1630     hs->state = state12_finish_server_handshake;
1631   }
1632   return ssl_hs_flush;
1633 }
1634 
do_finish_server_handshake(SSL_HANDSHAKE * hs)1635 static enum ssl_hs_wait_t do_finish_server_handshake(SSL_HANDSHAKE *hs) {
1636   SSL *const ssl = hs->ssl;
1637 
1638   if (hs->handback) {
1639     return ssl_hs_handback;
1640   }
1641 
1642   ssl->method->on_handshake_complete(ssl);
1643 
1644   // If we aren't retaining peer certificates then we can discard it now.
1645   if (hs->new_session != NULL &&
1646       hs->config->retain_only_sha256_of_client_certs) {
1647     hs->new_session->certs.reset();
1648     ssl->ctx->x509_method->session_clear(hs->new_session.get());
1649   }
1650 
1651   if (ssl->session != NULL) {
1652     ssl->s3->established_session = UpRef(ssl->session);
1653   } else {
1654     ssl->s3->established_session = std::move(hs->new_session);
1655     ssl->s3->established_session->not_resumable = false;
1656   }
1657 
1658   hs->handshake_finalized = true;
1659   ssl->s3->initial_handshake_complete = true;
1660   ssl_update_cache(hs, SSL_SESS_CACHE_SERVER);
1661 
1662   hs->state = state12_done;
1663   return ssl_hs_ok;
1664 }
1665 
ssl_server_handshake(SSL_HANDSHAKE * hs)1666 enum ssl_hs_wait_t ssl_server_handshake(SSL_HANDSHAKE *hs) {
1667   while (hs->state != state12_done) {
1668     enum ssl_hs_wait_t ret = ssl_hs_error;
1669     enum tls12_server_hs_state_t state =
1670         static_cast<enum tls12_server_hs_state_t>(hs->state);
1671     switch (state) {
1672       case state12_start_accept:
1673         ret = do_start_accept(hs);
1674         break;
1675       case state12_read_client_hello:
1676         ret = do_read_client_hello(hs);
1677         break;
1678       case state12_select_certificate:
1679         ret = do_select_certificate(hs);
1680         break;
1681       case state12_tls13:
1682         ret = do_tls13(hs);
1683         break;
1684       case state12_select_parameters:
1685         ret = do_select_parameters(hs);
1686         break;
1687       case state12_send_server_hello:
1688         ret = do_send_server_hello(hs);
1689         break;
1690       case state12_send_server_certificate:
1691         ret = do_send_server_certificate(hs);
1692         break;
1693       case state12_send_server_key_exchange:
1694         ret = do_send_server_key_exchange(hs);
1695         break;
1696       case state12_send_server_hello_done:
1697         ret = do_send_server_hello_done(hs);
1698         break;
1699       case state12_read_client_certificate:
1700         ret = do_read_client_certificate(hs);
1701         break;
1702       case state12_verify_client_certificate:
1703         ret = do_verify_client_certificate(hs);
1704         break;
1705       case state12_read_client_key_exchange:
1706         ret = do_read_client_key_exchange(hs);
1707         break;
1708       case state12_read_client_certificate_verify:
1709         ret = do_read_client_certificate_verify(hs);
1710         break;
1711       case state12_read_change_cipher_spec:
1712         ret = do_read_change_cipher_spec(hs);
1713         break;
1714       case state12_process_change_cipher_spec:
1715         ret = do_process_change_cipher_spec(hs);
1716         break;
1717       case state12_read_next_proto:
1718         ret = do_read_next_proto(hs);
1719         break;
1720       case state12_read_channel_id:
1721         ret = do_read_channel_id(hs);
1722         break;
1723       case state12_read_client_finished:
1724         ret = do_read_client_finished(hs);
1725         break;
1726       case state12_send_server_finished:
1727         ret = do_send_server_finished(hs);
1728         break;
1729       case state12_finish_server_handshake:
1730         ret = do_finish_server_handshake(hs);
1731         break;
1732       case state12_done:
1733         ret = ssl_hs_ok;
1734         break;
1735     }
1736 
1737     if (hs->state != state) {
1738       ssl_do_info_callback(hs->ssl, SSL_CB_ACCEPT_LOOP, 1);
1739     }
1740 
1741     if (ret != ssl_hs_ok) {
1742       return ret;
1743     }
1744   }
1745 
1746   ssl_do_info_callback(hs->ssl, SSL_CB_HANDSHAKE_DONE, 1);
1747   return ssl_hs_ok;
1748 }
1749 
ssl_server_handshake_state(SSL_HANDSHAKE * hs)1750 const char *ssl_server_handshake_state(SSL_HANDSHAKE *hs) {
1751   enum tls12_server_hs_state_t state =
1752       static_cast<enum tls12_server_hs_state_t>(hs->state);
1753   switch (state) {
1754     case state12_start_accept:
1755       return "TLS server start_accept";
1756     case state12_read_client_hello:
1757       return "TLS server read_client_hello";
1758     case state12_select_certificate:
1759       return "TLS server select_certificate";
1760     case state12_tls13:
1761       return tls13_server_handshake_state(hs);
1762     case state12_select_parameters:
1763       return "TLS server select_parameters";
1764     case state12_send_server_hello:
1765       return "TLS server send_server_hello";
1766     case state12_send_server_certificate:
1767       return "TLS server send_server_certificate";
1768     case state12_send_server_key_exchange:
1769       return "TLS server send_server_key_exchange";
1770     case state12_send_server_hello_done:
1771       return "TLS server send_server_hello_done";
1772     case state12_read_client_certificate:
1773       return "TLS server read_client_certificate";
1774     case state12_verify_client_certificate:
1775       return "TLS server verify_client_certificate";
1776     case state12_read_client_key_exchange:
1777       return "TLS server read_client_key_exchange";
1778     case state12_read_client_certificate_verify:
1779       return "TLS server read_client_certificate_verify";
1780     case state12_read_change_cipher_spec:
1781       return "TLS server read_change_cipher_spec";
1782     case state12_process_change_cipher_spec:
1783       return "TLS server process_change_cipher_spec";
1784     case state12_read_next_proto:
1785       return "TLS server read_next_proto";
1786     case state12_read_channel_id:
1787       return "TLS server read_channel_id";
1788     case state12_read_client_finished:
1789       return "TLS server read_client_finished";
1790     case state12_send_server_finished:
1791       return "TLS server send_server_finished";
1792     case state12_finish_server_handshake:
1793       return "TLS server finish_server_handshake";
1794     case state12_done:
1795       return "TLS server done";
1796   }
1797 
1798   return "TLS server unknown";
1799 }
1800 
1801 BSSL_NAMESPACE_END
1802