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