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