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