• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110 /* ====================================================================
111  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
112  *
113  * Portions of the attached software ("Contribution") are developed by
114  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
115  *
116  * The Contribution is licensed pursuant to the OpenSSL open source
117  * license provided above.
118  *
119  * ECC cipher suite support in OpenSSL originally written by
120  * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
121  *
122  */
123 /* ====================================================================
124  * Copyright 2005 Nokia. All rights reserved.
125  *
126  * The portions of the attached software ("Contribution") is developed by
127  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
128  * license.
129  *
130  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
131  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
132  * support (see RFC 4279) to OpenSSL.
133  *
134  * No patent licenses or other rights except those expressly stated in
135  * the OpenSSL open source license shall be deemed granted or received
136  * expressly, by implication, estoppel, or otherwise.
137  *
138  * No assurances are provided by Nokia that the Contribution does not
139  * infringe the patent or other intellectual property rights of any third
140  * party or that the license provides you with all the necessary rights
141  * to make use of the Contribution.
142  *
143  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
144  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
145  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
146  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
147  * OTHERWISE. */
148 
149 #include <openssl/ssl.h>
150 
151 #include <assert.h>
152 #include <string.h>
153 
154 #include <openssl/bn.h>
155 #include <openssl/bytestring.h>
156 #include <openssl/cipher.h>
157 #include <openssl/curve25519.h>
158 #include <openssl/digest.h>
159 #include <openssl/ec.h>
160 #include <openssl/ecdsa.h>
161 #include <openssl/err.h>
162 #include <openssl/evp.h>
163 #include <openssl/hmac.h>
164 #include <openssl/md5.h>
165 #include <openssl/mem.h>
166 #include <openssl/nid.h>
167 #include <openssl/rand.h>
168 #include <openssl/x509.h>
169 
170 #include "internal.h"
171 #include "../crypto/internal.h"
172 
173 
174 BSSL_NAMESPACE_BEGIN
175 
ssl_client_cipher_list_contains_cipher(const SSL_CLIENT_HELLO * client_hello,uint16_t id)176 bool ssl_client_cipher_list_contains_cipher(
177     const SSL_CLIENT_HELLO *client_hello, uint16_t id) {
178   CBS cipher_suites;
179   CBS_init(&cipher_suites, client_hello->cipher_suites,
180            client_hello->cipher_suites_len);
181 
182   while (CBS_len(&cipher_suites) > 0) {
183     uint16_t got_id;
184     if (!CBS_get_u16(&cipher_suites, &got_id)) {
185       return false;
186     }
187 
188     if (got_id == id) {
189       return true;
190     }
191   }
192 
193   return false;
194 }
195 
negotiate_version(SSL_HANDSHAKE * hs,uint8_t * out_alert,const SSL_CLIENT_HELLO * client_hello)196 static bool negotiate_version(SSL_HANDSHAKE *hs, uint8_t *out_alert,
197                               const SSL_CLIENT_HELLO *client_hello) {
198   SSL *const ssl = hs->ssl;
199   assert(!ssl->s3->have_version);
200   CBS supported_versions, versions;
201   if (ssl_client_hello_get_extension(client_hello, &supported_versions,
202                                      TLSEXT_TYPE_supported_versions)) {
203     if (!CBS_get_u8_length_prefixed(&supported_versions, &versions) ||
204         CBS_len(&supported_versions) != 0 ||
205         CBS_len(&versions) == 0) {
206       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
207       *out_alert = SSL_AD_DECODE_ERROR;
208       return false;
209     }
210   } else {
211     // Convert the ClientHello version to an equivalent supported_versions
212     // extension.
213     static const uint8_t kTLSVersions[] = {
214         0x03, 0x03,  // TLS 1.2
215         0x03, 0x02,  // TLS 1.1
216         0x03, 0x01,  // TLS 1
217     };
218 
219     static const uint8_t kDTLSVersions[] = {
220         0xfe, 0xfd,  // DTLS 1.2
221         0xfe, 0xff,  // DTLS 1.0
222     };
223 
224     size_t versions_len = 0;
225     if (SSL_is_dtls(ssl)) {
226       if (client_hello->version <= DTLS1_2_VERSION) {
227         versions_len = 4;
228       } else if (client_hello->version <= DTLS1_VERSION) {
229         versions_len = 2;
230       }
231       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     return true;
617   }
618 
619   CBS server_name_list, host_name;
620   uint8_t name_type;
621   if (!CBS_get_u16_length_prefixed(&sni, &server_name_list) ||
622       !CBS_get_u8(&server_name_list, &name_type) ||
623       // Although the server_name extension was intended to be extensible to
624       // new name types and multiple names, OpenSSL 1.0.x had a bug which meant
625       // different name types will cause an error. Further, RFC 4366 originally
626       // defined syntax inextensibly. RFC 6066 corrected this mistake, but
627       // adding new name types is no longer feasible.
628       //
629       // Act as if the extensibility does not exist to simplify parsing.
630       !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
631       CBS_len(&server_name_list) != 0 ||
632       CBS_len(&sni) != 0) {
633     *out_alert = SSL_AD_DECODE_ERROR;
634     return false;
635   }
636 
637   if (name_type != TLSEXT_NAMETYPE_host_name ||
638       CBS_len(&host_name) == 0 ||
639       CBS_len(&host_name) > TLSEXT_MAXLEN_host_name ||
640       CBS_contains_zero_byte(&host_name)) {
641     *out_alert = SSL_AD_UNRECOGNIZED_NAME;
642     return false;
643   }
644 
645   // Copy the hostname as a string.
646   char *raw = nullptr;
647   if (!CBS_strdup(&host_name, &raw)) {
648     *out_alert = SSL_AD_INTERNAL_ERROR;
649     return false;
650   }
651   ssl->s3->hostname.reset(raw);
652 
653   hs->should_ack_sni = true;
654   return true;
655 }
656 
do_read_client_hello(SSL_HANDSHAKE * hs)657 static enum ssl_hs_wait_t do_read_client_hello(SSL_HANDSHAKE *hs) {
658   SSL *const ssl = hs->ssl;
659 
660   SSLMessage msg;
661   if (!ssl->method->get_message(ssl, &msg)) {
662     return ssl_hs_read_message;
663   }
664 
665   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CLIENT_HELLO)) {
666     return ssl_hs_error;
667   }
668 
669   SSL_CLIENT_HELLO client_hello;
670   if (!ssl_client_hello_init(ssl, &client_hello, msg.body)) {
671     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
672     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
673     return ssl_hs_error;
674   }
675 
676   // ClientHello should be the end of the flight. We check this early to cover
677   // all protocol versions.
678   if (ssl->method->has_unprocessed_handshake_data(ssl)) {
679     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
680     OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESS_HANDSHAKE_DATA);
681     return ssl_hs_error;
682   }
683 
684   if (hs->config->handoff) {
685     return ssl_hs_handoff;
686   }
687 
688   uint8_t alert = SSL_AD_DECODE_ERROR;
689   if (!decrypt_ech(hs, &alert, &client_hello)) {
690     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
691     return ssl_hs_error;
692   }
693 
694   // ECH may have changed which ClientHello we process. Update |msg| and
695   // |client_hello| in case.
696   if (!hs->GetClientHello(&msg, &client_hello)) {
697     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
698     return ssl_hs_error;
699   }
700 
701   if (!extract_sni(hs, &alert, &client_hello)) {
702     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
703     return ssl_hs_error;
704   }
705 
706   hs->state = state12_read_client_hello_after_ech;
707   return ssl_hs_ok;
708 }
709 
do_read_client_hello_after_ech(SSL_HANDSHAKE * hs)710 static enum ssl_hs_wait_t do_read_client_hello_after_ech(SSL_HANDSHAKE *hs) {
711   SSL *const ssl = hs->ssl;
712 
713   SSLMessage msg_unused;
714   SSL_CLIENT_HELLO client_hello;
715   if (!hs->GetClientHello(&msg_unused, &client_hello)) {
716     return ssl_hs_error;
717   }
718 
719   // Run the early callback.
720   if (ssl->ctx->select_certificate_cb != NULL) {
721     switch (ssl->ctx->select_certificate_cb(&client_hello)) {
722       case ssl_select_cert_retry:
723         return ssl_hs_certificate_selection_pending;
724 
725       case ssl_select_cert_error:
726         // Connection rejected.
727         OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
728         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
729         return ssl_hs_error;
730 
731       default:
732         /* fallthrough */;
733     }
734   }
735 
736   // Freeze the version range after the early callback.
737   if (!ssl_get_version_range(hs, &hs->min_version, &hs->max_version)) {
738     return ssl_hs_error;
739   }
740 
741   if (hs->config->jdk11_workaround &&
742       is_probably_jdk11_with_tls13(&client_hello)) {
743     hs->apply_jdk11_workaround = true;
744   }
745 
746   uint8_t alert = SSL_AD_DECODE_ERROR;
747   if (!negotiate_version(hs, &alert, &client_hello)) {
748     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
749     return ssl_hs_error;
750   }
751 
752   hs->client_version = client_hello.version;
753   if (client_hello.random_len != SSL3_RANDOM_SIZE) {
754     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
755     return ssl_hs_error;
756   }
757   OPENSSL_memcpy(ssl->s3->client_random, client_hello.random,
758                  client_hello.random_len);
759 
760   // Only null compression is supported. TLS 1.3 further requires the peer
761   // advertise no other compression.
762   if (OPENSSL_memchr(client_hello.compression_methods, 0,
763                      client_hello.compression_methods_len) == NULL ||
764       (ssl_protocol_version(ssl) >= TLS1_3_VERSION &&
765        client_hello.compression_methods_len != 1)) {
766     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_COMPRESSION_LIST);
767     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
768     return ssl_hs_error;
769   }
770 
771   // TLS extensions.
772   if (!ssl_parse_clienthello_tlsext(hs, &client_hello)) {
773     OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
774     return ssl_hs_error;
775   }
776 
777   hs->state = state12_cert_callback;
778   return ssl_hs_ok;
779 }
780 
do_cert_callback(SSL_HANDSHAKE * hs)781 static enum ssl_hs_wait_t do_cert_callback(SSL_HANDSHAKE *hs) {
782   SSL *const ssl = hs->ssl;
783 
784   // Call |cert_cb| to update server certificates if required.
785   if (hs->config->cert->cert_cb != NULL) {
786     int rv = hs->config->cert->cert_cb(ssl, hs->config->cert->cert_cb_arg);
787     if (rv == 0) {
788       OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
789       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
790       return ssl_hs_error;
791     }
792     if (rv < 0) {
793       return ssl_hs_x509_lookup;
794     }
795   }
796 
797   if (hs->ocsp_stapling_requested &&
798       ssl->ctx->legacy_ocsp_callback != nullptr) {
799     switch (ssl->ctx->legacy_ocsp_callback(
800         ssl, ssl->ctx->legacy_ocsp_callback_arg)) {
801       case SSL_TLSEXT_ERR_OK:
802         break;
803       case SSL_TLSEXT_ERR_NOACK:
804         hs->ocsp_stapling_requested = false;
805         break;
806       default:
807         OPENSSL_PUT_ERROR(SSL, SSL_R_OCSP_CB_ERROR);
808         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
809         return ssl_hs_error;
810     }
811   }
812 
813   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
814     // Jump to the TLS 1.3 state machine.
815     hs->state = state12_tls13;
816     return ssl_hs_ok;
817   }
818 
819   // It should not be possible to negotiate TLS 1.2 with ECH. The
820   // ClientHelloInner decoding function rejects ClientHellos which offer TLS 1.2
821   // or below.
822   assert(ssl->s3->ech_status != ssl_ech_accepted);
823 
824   ssl->s3->early_data_reason = ssl_early_data_protocol_version;
825 
826   hs->state = state12_select_parameters;
827   return ssl_hs_ok;
828 }
829 
do_tls13(SSL_HANDSHAKE * hs)830 static enum ssl_hs_wait_t do_tls13(SSL_HANDSHAKE *hs) {
831   enum ssl_hs_wait_t wait = tls13_server_handshake(hs);
832   if (wait == ssl_hs_ok) {
833     hs->state = state12_finish_server_handshake;
834     return ssl_hs_ok;
835   }
836 
837   return wait;
838 }
839 
do_select_parameters(SSL_HANDSHAKE * hs)840 static enum ssl_hs_wait_t do_select_parameters(SSL_HANDSHAKE *hs) {
841   SSL *const ssl = hs->ssl;
842   SSLMessage msg;
843   SSL_CLIENT_HELLO client_hello;
844   if (!hs->GetClientHello(&msg, &client_hello)) {
845     return ssl_hs_error;
846   }
847 
848   // Determine the ECDHE group to use, if we are to use ECDHE.
849   uint16_t group_id = 0;
850   bool has_ecdhe_group = tls1_get_shared_group(hs, &group_id);
851 
852   // Select the credential and cipher suite. This must be done after |cert_cb|
853   // runs, so the final credential list is known.
854   //
855   // TODO(davidben): In the course of picking these, we also pick the ECDHE
856   // group and signature algorithm. It would be tidier if we saved that decision
857   // and avoided redoing it later.
858   UniquePtr<STACK_OF(SSL_CIPHER)> client_pref =
859       ssl_parse_client_cipher_list(&client_hello);
860   if (client_pref == nullptr) {
861     return ssl_hs_error;
862   }
863   Array<SSL_CREDENTIAL *> creds;
864   if (!ssl_get_credential_list(hs, &creds)) {
865     return ssl_hs_error;
866   }
867   TLS12ServerParams params;
868   if (creds.empty()) {
869     // The caller may have configured no credentials, but set a PSK callback.
870     params =
871         choose_params(hs, /*cred=*/nullptr, client_pref.get(), has_ecdhe_group);
872   } else {
873     // Select the first credential which works.
874     for (SSL_CREDENTIAL *cred : creds) {
875       ERR_clear_error();
876       params = choose_params(hs, cred, client_pref.get(), has_ecdhe_group);
877       if (params.ok()) {
878         hs->credential = UpRef(cred);
879         break;
880       }
881     }
882   }
883   if (!params.ok()) {
884     // The error from the last attempt is in the error queue.
885     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
886     return ssl_hs_error;
887   }
888   hs->new_cipher = params.cipher;
889   hs->signature_algorithm = params.signature_algorithm;
890 
891   hs->session_id_len = client_hello.session_id_len;
892   // This is checked in |ssl_client_hello_init|.
893   assert(hs->session_id_len <= sizeof(hs->session_id));
894   OPENSSL_memcpy(hs->session_id, client_hello.session_id, hs->session_id_len);
895 
896   // Determine whether we are doing session resumption.
897   UniquePtr<SSL_SESSION> session;
898   bool tickets_supported = false, renew_ticket = false;
899   enum ssl_hs_wait_t wait = ssl_get_prev_session(
900       hs, &session, &tickets_supported, &renew_ticket, &client_hello);
901   if (wait != ssl_hs_ok) {
902     return wait;
903   }
904 
905   if (session) {
906     if (session->extended_master_secret && !hs->extended_master_secret) {
907       // A ClientHello without EMS that attempts to resume a session with EMS
908       // is fatal to the connection.
909       OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
910       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
911       return ssl_hs_error;
912     }
913 
914     if (!ssl_session_is_resumable(hs, session.get()) ||
915         // If the client offers the EMS extension, but the previous session
916         // didn't use it, then negotiate a new session.
917         hs->extended_master_secret != session->extended_master_secret) {
918       session.reset();
919     }
920   }
921 
922   if (session) {
923     // Use the old session.
924     hs->ticket_expected = renew_ticket;
925     ssl->session = std::move(session);
926     ssl->s3->session_reused = true;
927     hs->can_release_private_key = true;
928   } else {
929     hs->ticket_expected = tickets_supported;
930     ssl_set_session(ssl, nullptr);
931     if (!ssl_get_new_session(hs)) {
932       return ssl_hs_error;
933     }
934 
935     // Assign a session ID if not using session tickets.
936     if (!hs->ticket_expected &&
937         (ssl->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)) {
938       hs->new_session->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
939       RAND_bytes(hs->new_session->session_id,
940                  hs->new_session->session_id_length);
941     }
942   }
943 
944   if (ssl->ctx->dos_protection_cb != NULL &&
945       ssl->ctx->dos_protection_cb(&client_hello) == 0) {
946     // Connection rejected for DOS reasons.
947     OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
948     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
949     return ssl_hs_error;
950   }
951 
952   if (ssl->session == NULL) {
953     hs->new_session->cipher = hs->new_cipher;
954     if (hs->new_session->cipher->algorithm_mkey & SSL_kECDHE) {
955       assert(has_ecdhe_group);
956       hs->new_session->group_id = group_id;
957     }
958 
959     // Determine whether to request a client certificate.
960     hs->cert_request = !!(hs->config->verify_mode & SSL_VERIFY_PEER);
961     // Only request a certificate if Channel ID isn't negotiated.
962     if ((hs->config->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
963         hs->channel_id_negotiated) {
964       hs->cert_request = false;
965     }
966     // CertificateRequest may only be sent in certificate-based ciphers.
967     if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
968       hs->cert_request = false;
969     }
970 
971     if (!hs->cert_request) {
972       // OpenSSL returns X509_V_OK when no certificates are requested. This is
973       // classed by them as a bug, but it's assumed by at least NGINX.
974       hs->new_session->verify_result = X509_V_OK;
975     }
976   }
977 
978   // HTTP/2 negotiation depends on the cipher suite, so ALPN negotiation was
979   // deferred. Complete it now.
980   uint8_t alert = SSL_AD_DECODE_ERROR;
981   if (!ssl_negotiate_alpn(hs, &alert, &client_hello)) {
982     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
983     return ssl_hs_error;
984   }
985 
986   // Now that all parameters are known, initialize the handshake hash and hash
987   // the ClientHello.
988   if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher) ||
989       !ssl_hash_message(hs, msg)) {
990     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
991     return ssl_hs_error;
992   }
993 
994   // Handback includes the whole handshake transcript, so we cannot free the
995   // transcript buffer in the handback case.
996   if (!hs->cert_request && !hs->handback) {
997     hs->transcript.FreeBuffer();
998   }
999 
1000   ssl->method->next_message(ssl);
1001 
1002   hs->state = state12_send_server_hello;
1003   return ssl_hs_ok;
1004 }
1005 
copy_suffix(Span<uint8_t> out,Span<const uint8_t> in)1006 static void copy_suffix(Span<uint8_t> out, Span<const uint8_t> in) {
1007   out = out.last(in.size());
1008   OPENSSL_memcpy(out.data(), in.data(), in.size());
1009 }
1010 
do_send_server_hello(SSL_HANDSHAKE * hs)1011 static enum ssl_hs_wait_t do_send_server_hello(SSL_HANDSHAKE *hs) {
1012   SSL *const ssl = hs->ssl;
1013 
1014   // We only accept ChannelIDs on connections with ECDHE in order to avoid a
1015   // known attack while we fix ChannelID itself.
1016   if (hs->channel_id_negotiated &&
1017       (hs->new_cipher->algorithm_mkey & SSL_kECDHE) == 0) {
1018     hs->channel_id_negotiated = false;
1019   }
1020 
1021   // If this is a resumption and the original handshake didn't support
1022   // ChannelID then we didn't record the original handshake hashes in the
1023   // session and so cannot resume with ChannelIDs.
1024   if (ssl->session != NULL &&
1025       ssl->session->original_handshake_hash_len == 0) {
1026     hs->channel_id_negotiated = false;
1027   }
1028 
1029   SSL_HANDSHAKE_HINTS *const hints = hs->hints.get();
1030   if (hints && !hs->hints_requested &&
1031       hints->server_random_tls12.size() == SSL3_RANDOM_SIZE) {
1032     OPENSSL_memcpy(ssl->s3->server_random, hints->server_random_tls12.data(),
1033                    SSL3_RANDOM_SIZE);
1034   } else {
1035     struct OPENSSL_timeval now;
1036     ssl_get_current_time(ssl, &now);
1037     CRYPTO_store_u32_be(ssl->s3->server_random,
1038                         static_cast<uint32_t>(now.tv_sec));
1039     if (!RAND_bytes(ssl->s3->server_random + 4, SSL3_RANDOM_SIZE - 4)) {
1040       return ssl_hs_error;
1041     }
1042     if (hints && hs->hints_requested &&
1043         !hints->server_random_tls12.CopyFrom(ssl->s3->server_random)) {
1044       return ssl_hs_error;
1045     }
1046   }
1047 
1048   // Implement the TLS 1.3 anti-downgrade feature.
1049   if (ssl_supports_version(hs, TLS1_3_VERSION)) {
1050     if (ssl_protocol_version(ssl) == TLS1_2_VERSION) {
1051       if (hs->apply_jdk11_workaround) {
1052         // JDK 11 implements the TLS 1.3 downgrade signal, so we cannot send it
1053         // here. However, the signal is only effective if all TLS 1.2
1054         // ServerHellos produced by the server are marked. Thus we send a
1055         // different non-standard signal for the time being, until JDK 11.0.2 is
1056         // released and clients have updated.
1057         copy_suffix(ssl->s3->server_random, kJDK11DowngradeRandom);
1058       } else {
1059         copy_suffix(ssl->s3->server_random, kTLS13DowngradeRandom);
1060       }
1061     } else {
1062       copy_suffix(ssl->s3->server_random, kTLS12DowngradeRandom);
1063     }
1064   }
1065 
1066   Span<const uint8_t> session_id;
1067   if (ssl->session != nullptr) {
1068     // Echo the session ID from the ClientHello to indicate resumption.
1069     session_id = MakeConstSpan(hs->session_id, hs->session_id_len);
1070   } else {
1071     session_id = MakeConstSpan(hs->new_session->session_id,
1072                                hs->new_session->session_id_length);
1073   }
1074 
1075   ScopedCBB cbb;
1076   CBB body, session_id_bytes;
1077   if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_SERVER_HELLO) ||
1078       !CBB_add_u16(&body, ssl->version) ||
1079       !CBB_add_bytes(&body, ssl->s3->server_random, SSL3_RANDOM_SIZE) ||
1080       !CBB_add_u8_length_prefixed(&body, &session_id_bytes) ||
1081       !CBB_add_bytes(&session_id_bytes, session_id.data(), session_id.size()) ||
1082       !CBB_add_u16(&body, SSL_CIPHER_get_protocol_id(hs->new_cipher)) ||
1083       !CBB_add_u8(&body, 0 /* no compression */) ||
1084       !ssl_add_serverhello_tlsext(hs, &body) ||
1085       !ssl_add_message_cbb(ssl, cbb.get())) {
1086     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1087     return ssl_hs_error;
1088   }
1089 
1090   if (ssl->session != nullptr) {
1091     // No additional hints to generate in resumption.
1092     if (hs->hints_requested) {
1093       return ssl_hs_hints_ready;
1094     }
1095     hs->state = state12_send_server_finished;
1096   } else {
1097     hs->state = state12_send_server_certificate;
1098   }
1099   return ssl_hs_ok;
1100 }
1101 
do_send_server_certificate(SSL_HANDSHAKE * hs)1102 static enum ssl_hs_wait_t do_send_server_certificate(SSL_HANDSHAKE *hs) {
1103   SSL *const ssl = hs->ssl;
1104   ScopedCBB cbb;
1105 
1106   if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1107     assert(hs->credential != nullptr);
1108     if (!ssl_send_tls12_certificate(hs)) {
1109       return ssl_hs_error;
1110     }
1111 
1112     if (hs->certificate_status_expected) {
1113       CBB body, ocsp_response;
1114       if (!ssl->method->init_message(ssl, cbb.get(), &body,
1115                                      SSL3_MT_CERTIFICATE_STATUS) ||
1116           !CBB_add_u8(&body, TLSEXT_STATUSTYPE_ocsp) ||
1117           !CBB_add_u24_length_prefixed(&body, &ocsp_response) ||
1118           !CBB_add_bytes(
1119               &ocsp_response,
1120               CRYPTO_BUFFER_data(hs->credential->ocsp_response.get()),
1121               CRYPTO_BUFFER_len(hs->credential->ocsp_response.get())) ||
1122           !ssl_add_message_cbb(ssl, cbb.get())) {
1123         OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1124         return ssl_hs_error;
1125       }
1126     }
1127   }
1128 
1129   // Assemble ServerKeyExchange parameters if needed.
1130   uint32_t alg_k = hs->new_cipher->algorithm_mkey;
1131   uint32_t alg_a = hs->new_cipher->algorithm_auth;
1132   if (ssl_cipher_requires_server_key_exchange(hs->new_cipher) ||
1133       ((alg_a & SSL_aPSK) && hs->config->psk_identity_hint)) {
1134     // Pre-allocate enough room to comfortably fit an ECDHE public key. Prepend
1135     // the client and server randoms for the signing transcript.
1136     CBB child;
1137     if (!CBB_init(cbb.get(), SSL3_RANDOM_SIZE * 2 + 128) ||
1138         !CBB_add_bytes(cbb.get(), ssl->s3->client_random, SSL3_RANDOM_SIZE) ||
1139         !CBB_add_bytes(cbb.get(), ssl->s3->server_random, SSL3_RANDOM_SIZE)) {
1140       return ssl_hs_error;
1141     }
1142 
1143     // PSK ciphers begin with an identity hint.
1144     if (alg_a & SSL_aPSK) {
1145       size_t len = hs->config->psk_identity_hint == nullptr
1146                        ? 0
1147                        : strlen(hs->config->psk_identity_hint.get());
1148       if (!CBB_add_u16_length_prefixed(cbb.get(), &child) ||
1149           !CBB_add_bytes(&child,
1150                          (const uint8_t *)hs->config->psk_identity_hint.get(),
1151                          len)) {
1152         return ssl_hs_error;
1153       }
1154     }
1155 
1156     if (alg_k & SSL_kECDHE) {
1157       assert(hs->new_session->group_id != 0);
1158       hs->key_shares[0] = SSLKeyShare::Create(hs->new_session->group_id);
1159       if (!hs->key_shares[0] ||
1160           !CBB_add_u8(cbb.get(), NAMED_CURVE_TYPE) ||
1161           !CBB_add_u16(cbb.get(), hs->new_session->group_id) ||
1162           !CBB_add_u8_length_prefixed(cbb.get(), &child)) {
1163         return ssl_hs_error;
1164       }
1165 
1166       SSL_HANDSHAKE_HINTS *const hints = hs->hints.get();
1167       bool hint_ok = false;
1168       if (hints && !hs->hints_requested &&
1169           hints->ecdhe_group_id == hs->new_session->group_id &&
1170           !hints->ecdhe_public_key.empty() &&
1171           !hints->ecdhe_private_key.empty()) {
1172         CBS cbs = MakeConstSpan(hints->ecdhe_private_key);
1173         hint_ok = hs->key_shares[0]->DeserializePrivateKey(&cbs);
1174       }
1175       if (hint_ok) {
1176         // Reuse the ECDH key from handshake hints.
1177         if (!CBB_add_bytes(&child, hints->ecdhe_public_key.data(),
1178                            hints->ecdhe_public_key.size())) {
1179           return ssl_hs_error;
1180         }
1181       } else {
1182         // Generate a key, and emit the public half.
1183         if (!hs->key_shares[0]->Generate(&child)) {
1184           return ssl_hs_error;
1185         }
1186         // If generating hints, save the ECDHE key.
1187         if (hints && hs->hints_requested) {
1188           bssl::ScopedCBB private_key_cbb;
1189           if (!hints->ecdhe_public_key.CopyFrom(
1190                   MakeConstSpan(CBB_data(&child), CBB_len(&child))) ||
1191               !CBB_init(private_key_cbb.get(), 32) ||
1192               !hs->key_shares[0]->SerializePrivateKey(private_key_cbb.get()) ||
1193               !CBBFinishArray(private_key_cbb.get(),
1194                               &hints->ecdhe_private_key)) {
1195             return ssl_hs_error;
1196           }
1197           hints->ecdhe_group_id = hs->new_session->group_id;
1198         }
1199       }
1200     } else {
1201       assert(alg_k & SSL_kPSK);
1202     }
1203 
1204     if (!CBBFinishArray(cbb.get(), &hs->server_params)) {
1205       return ssl_hs_error;
1206     }
1207   }
1208 
1209   hs->state = state12_send_server_key_exchange;
1210   return ssl_hs_ok;
1211 }
1212 
do_send_server_key_exchange(SSL_HANDSHAKE * hs)1213 static enum ssl_hs_wait_t do_send_server_key_exchange(SSL_HANDSHAKE *hs) {
1214   SSL *const ssl = hs->ssl;
1215 
1216   if (hs->server_params.size() == 0) {
1217     hs->state = state12_send_server_hello_done;
1218     return ssl_hs_ok;
1219   }
1220 
1221   ScopedCBB cbb;
1222   CBB body, child;
1223   if (!ssl->method->init_message(ssl, cbb.get(), &body,
1224                                  SSL3_MT_SERVER_KEY_EXCHANGE) ||
1225       // |hs->server_params| contains a prefix for signing.
1226       hs->server_params.size() < 2 * SSL3_RANDOM_SIZE ||
1227       !CBB_add_bytes(&body, hs->server_params.data() + 2 * SSL3_RANDOM_SIZE,
1228                      hs->server_params.size() - 2 * SSL3_RANDOM_SIZE)) {
1229     return ssl_hs_error;
1230   }
1231 
1232   // Add a signature.
1233   if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1234     // Determine the signature algorithm.
1235     uint16_t signature_algorithm;
1236     if (!tls1_choose_signature_algorithm(hs, hs->credential.get(),
1237                                          &signature_algorithm)) {
1238       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1239       return ssl_hs_error;
1240     }
1241     if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1242       if (!CBB_add_u16(&body, signature_algorithm)) {
1243         OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1244         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1245         return ssl_hs_error;
1246       }
1247     }
1248 
1249     // Add space for the signature.
1250     const size_t max_sig_len = EVP_PKEY_size(hs->credential->pubkey.get());
1251     uint8_t *ptr;
1252     if (!CBB_add_u16_length_prefixed(&body, &child) ||
1253         !CBB_reserve(&child, &ptr, max_sig_len)) {
1254       return ssl_hs_error;
1255     }
1256 
1257     size_t sig_len;
1258     switch (ssl_private_key_sign(hs, ptr, &sig_len, max_sig_len,
1259                                  signature_algorithm, hs->server_params)) {
1260       case ssl_private_key_success:
1261         if (!CBB_did_write(&child, sig_len)) {
1262           return ssl_hs_error;
1263         }
1264         break;
1265       case ssl_private_key_failure:
1266         return ssl_hs_error;
1267       case ssl_private_key_retry:
1268         return ssl_hs_private_key_operation;
1269     }
1270   }
1271 
1272   hs->can_release_private_key = true;
1273   if (!ssl_add_message_cbb(ssl, cbb.get())) {
1274     return ssl_hs_error;
1275   }
1276 
1277   hs->server_params.Reset();
1278 
1279   hs->state = state12_send_server_hello_done;
1280   return ssl_hs_ok;
1281 }
1282 
do_send_server_hello_done(SSL_HANDSHAKE * hs)1283 static enum ssl_hs_wait_t do_send_server_hello_done(SSL_HANDSHAKE *hs) {
1284   SSL *const ssl = hs->ssl;
1285   if (hs->hints_requested) {
1286     return ssl_hs_hints_ready;
1287   }
1288 
1289   ScopedCBB cbb;
1290   CBB body;
1291 
1292   if (hs->cert_request) {
1293     CBB cert_types, sigalgs_cbb;
1294     if (!ssl->method->init_message(ssl, cbb.get(), &body,
1295                                    SSL3_MT_CERTIFICATE_REQUEST) ||
1296         !CBB_add_u8_length_prefixed(&body, &cert_types) ||
1297         !CBB_add_u8(&cert_types, SSL3_CT_RSA_SIGN) ||
1298         !CBB_add_u8(&cert_types, TLS_CT_ECDSA_SIGN) ||
1299         (ssl_protocol_version(ssl) >= TLS1_2_VERSION &&
1300          (!CBB_add_u16_length_prefixed(&body, &sigalgs_cbb) ||
1301           !tls12_add_verify_sigalgs(hs, &sigalgs_cbb))) ||
1302         !ssl_add_client_CA_list(hs, &body) ||
1303         !ssl_add_message_cbb(ssl, cbb.get())) {
1304       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1305       return ssl_hs_error;
1306     }
1307   }
1308 
1309   if (!ssl->method->init_message(ssl, cbb.get(), &body,
1310                                  SSL3_MT_SERVER_HELLO_DONE) ||
1311       !ssl_add_message_cbb(ssl, cbb.get())) {
1312     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1313     return ssl_hs_error;
1314   }
1315 
1316   hs->state = state12_read_client_certificate;
1317   return ssl_hs_flush;
1318 }
1319 
do_read_client_certificate(SSL_HANDSHAKE * hs)1320 static enum ssl_hs_wait_t do_read_client_certificate(SSL_HANDSHAKE *hs) {
1321   SSL *const ssl = hs->ssl;
1322 
1323   if (hs->handback && hs->new_cipher->algorithm_mkey == SSL_kECDHE) {
1324     return ssl_hs_handback;
1325   }
1326   if (!hs->cert_request) {
1327     hs->state = state12_verify_client_certificate;
1328     return ssl_hs_ok;
1329   }
1330 
1331   SSLMessage msg;
1332   if (!ssl->method->get_message(ssl, &msg)) {
1333     return ssl_hs_read_message;
1334   }
1335 
1336   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE)) {
1337     return ssl_hs_error;
1338   }
1339 
1340   if (!ssl_hash_message(hs, msg)) {
1341     return ssl_hs_error;
1342   }
1343 
1344   CBS certificate_msg = msg.body;
1345   uint8_t alert = SSL_AD_DECODE_ERROR;
1346   if (!ssl_parse_cert_chain(&alert, &hs->new_session->certs, &hs->peer_pubkey,
1347                             hs->config->retain_only_sha256_of_client_certs
1348                                 ? hs->new_session->peer_sha256
1349                                 : nullptr,
1350                             &certificate_msg, ssl->ctx->pool)) {
1351     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1352     return ssl_hs_error;
1353   }
1354 
1355   if (CBS_len(&certificate_msg) != 0 ||
1356       !ssl->ctx->x509_method->session_cache_objects(hs->new_session.get())) {
1357     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1358     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1359     return ssl_hs_error;
1360   }
1361 
1362   if (sk_CRYPTO_BUFFER_num(hs->new_session->certs.get()) == 0) {
1363     // No client certificate so the handshake buffer may be discarded.
1364     hs->transcript.FreeBuffer();
1365 
1366     if (hs->config->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
1367       // Fail for TLS only if we required a certificate
1368       OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
1369       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1370       return ssl_hs_error;
1371     }
1372 
1373     // OpenSSL returns X509_V_OK when no certificates are received. This is
1374     // classed by them as a bug, but it's assumed by at least NGINX.
1375     hs->new_session->verify_result = X509_V_OK;
1376   } else if (hs->config->retain_only_sha256_of_client_certs) {
1377     // The hash will have been filled in.
1378     hs->new_session->peer_sha256_valid = true;
1379   }
1380 
1381   ssl->method->next_message(ssl);
1382   hs->state = state12_verify_client_certificate;
1383   return ssl_hs_ok;
1384 }
1385 
do_verify_client_certificate(SSL_HANDSHAKE * hs)1386 static enum ssl_hs_wait_t do_verify_client_certificate(SSL_HANDSHAKE *hs) {
1387   if (sk_CRYPTO_BUFFER_num(hs->new_session->certs.get()) > 0) {
1388     switch (ssl_verify_peer_cert(hs)) {
1389       case ssl_verify_ok:
1390         break;
1391       case ssl_verify_invalid:
1392         return ssl_hs_error;
1393       case ssl_verify_retry:
1394         return ssl_hs_certificate_verify;
1395     }
1396   }
1397 
1398   hs->state = state12_read_client_key_exchange;
1399   return ssl_hs_ok;
1400 }
1401 
do_read_client_key_exchange(SSL_HANDSHAKE * hs)1402 static enum ssl_hs_wait_t do_read_client_key_exchange(SSL_HANDSHAKE *hs) {
1403   SSL *const ssl = hs->ssl;
1404   SSLMessage msg;
1405   if (!ssl->method->get_message(ssl, &msg)) {
1406     return ssl_hs_read_message;
1407   }
1408 
1409   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CLIENT_KEY_EXCHANGE)) {
1410     return ssl_hs_error;
1411   }
1412 
1413   CBS client_key_exchange = msg.body;
1414   uint32_t alg_k = hs->new_cipher->algorithm_mkey;
1415   uint32_t alg_a = hs->new_cipher->algorithm_auth;
1416 
1417   // If using a PSK key exchange, parse the PSK identity.
1418   if (alg_a & SSL_aPSK) {
1419     CBS psk_identity;
1420 
1421     // If using PSK, the ClientKeyExchange contains a psk_identity. If PSK,
1422     // then this is the only field in the message.
1423     if (!CBS_get_u16_length_prefixed(&client_key_exchange, &psk_identity) ||
1424         ((alg_k & SSL_kPSK) && CBS_len(&client_key_exchange) != 0)) {
1425       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1426       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1427       return ssl_hs_error;
1428     }
1429 
1430     if (CBS_len(&psk_identity) > PSK_MAX_IDENTITY_LEN ||
1431         CBS_contains_zero_byte(&psk_identity)) {
1432       OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
1433       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
1434       return ssl_hs_error;
1435     }
1436     char *raw = nullptr;
1437     if (!CBS_strdup(&psk_identity, &raw)) {
1438       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1439       return ssl_hs_error;
1440     }
1441     hs->new_session->psk_identity.reset(raw);
1442   }
1443 
1444   // Depending on the key exchange method, compute |premaster_secret|.
1445   Array<uint8_t> premaster_secret;
1446   if (alg_k & SSL_kRSA) {
1447     CBS encrypted_premaster_secret;
1448     if (!CBS_get_u16_length_prefixed(&client_key_exchange,
1449                                      &encrypted_premaster_secret) ||
1450         CBS_len(&client_key_exchange) != 0) {
1451       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1452       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1453       return ssl_hs_error;
1454     }
1455 
1456     // Allocate a buffer large enough for an RSA decryption.
1457     Array<uint8_t> decrypt_buf;
1458     if (!decrypt_buf.Init(EVP_PKEY_size(hs->credential->pubkey.get()))) {
1459       return ssl_hs_error;
1460     }
1461 
1462     // Decrypt with no padding. PKCS#1 padding will be removed as part of the
1463     // timing-sensitive code below.
1464     size_t decrypt_len;
1465     switch (ssl_private_key_decrypt(hs, decrypt_buf.data(), &decrypt_len,
1466                                     decrypt_buf.size(),
1467                                     encrypted_premaster_secret)) {
1468       case ssl_private_key_success:
1469         break;
1470       case ssl_private_key_failure:
1471         return ssl_hs_error;
1472       case ssl_private_key_retry:
1473         return ssl_hs_private_key_operation;
1474     }
1475 
1476     if (decrypt_len != decrypt_buf.size()) {
1477       OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
1478       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
1479       return ssl_hs_error;
1480     }
1481 
1482     CONSTTIME_SECRET(decrypt_buf.data(), decrypt_len);
1483 
1484     // Prepare a random premaster, to be used on invalid padding. See RFC 5246,
1485     // section 7.4.7.1.
1486     if (!premaster_secret.Init(SSL_MAX_MASTER_KEY_LENGTH) ||
1487         !RAND_bytes(premaster_secret.data(), premaster_secret.size())) {
1488       return ssl_hs_error;
1489     }
1490 
1491     // The smallest padded premaster is 11 bytes of overhead. Small keys are
1492     // publicly invalid.
1493     if (decrypt_len < 11 + premaster_secret.size()) {
1494       OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
1495       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
1496       return ssl_hs_error;
1497     }
1498 
1499     // Check the padding. See RFC 3447, section 7.2.2.
1500     size_t padding_len = decrypt_len - premaster_secret.size();
1501     uint8_t good = constant_time_eq_int_8(decrypt_buf[0], 0) &
1502                    constant_time_eq_int_8(decrypt_buf[1], 2);
1503     for (size_t i = 2; i < padding_len - 1; i++) {
1504       good &= ~constant_time_is_zero_8(decrypt_buf[i]);
1505     }
1506     good &= constant_time_is_zero_8(decrypt_buf[padding_len - 1]);
1507 
1508     // The premaster secret must begin with |client_version|. This too must be
1509     // checked in constant time (http://eprint.iacr.org/2003/052/).
1510     good &= constant_time_eq_8(decrypt_buf[padding_len],
1511                                (unsigned)(hs->client_version >> 8));
1512     good &= constant_time_eq_8(decrypt_buf[padding_len + 1],
1513                                (unsigned)(hs->client_version & 0xff));
1514 
1515     // Select, in constant time, either the decrypted premaster or the random
1516     // premaster based on |good|.
1517     for (size_t i = 0; i < premaster_secret.size(); i++) {
1518       premaster_secret[i] = constant_time_select_8(
1519           good, decrypt_buf[padding_len + i], premaster_secret[i]);
1520     }
1521   } else if (alg_k & SSL_kECDHE) {
1522     // Parse the ClientKeyExchange.
1523     CBS ciphertext;
1524     if (!CBS_get_u8_length_prefixed(&client_key_exchange, &ciphertext) ||
1525         CBS_len(&client_key_exchange) != 0) {
1526       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1527       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1528       return ssl_hs_error;
1529     }
1530 
1531     // Decapsulate the premaster secret.
1532     uint8_t alert = SSL_AD_DECODE_ERROR;
1533     if (!hs->key_shares[0]->Decap(&premaster_secret, &alert, ciphertext)) {
1534       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1535       return ssl_hs_error;
1536     }
1537 
1538     // The key exchange state may now be discarded.
1539     hs->key_shares[0].reset();
1540     hs->key_shares[1].reset();
1541   } else if (!(alg_k & SSL_kPSK)) {
1542     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1543     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1544     return ssl_hs_error;
1545   }
1546 
1547   // For a PSK cipher suite, the actual pre-master secret is combined with the
1548   // pre-shared key.
1549   if (alg_a & SSL_aPSK) {
1550     if (hs->config->psk_server_callback == NULL) {
1551       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1552       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1553       return ssl_hs_error;
1554     }
1555 
1556     // Look up the key for the identity.
1557     uint8_t psk[PSK_MAX_PSK_LEN];
1558     unsigned psk_len = hs->config->psk_server_callback(
1559         ssl, hs->new_session->psk_identity.get(), psk, sizeof(psk));
1560     if (psk_len > PSK_MAX_PSK_LEN) {
1561       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1562       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1563       return ssl_hs_error;
1564     } else if (psk_len == 0) {
1565       // PSK related to the given identity not found.
1566       OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
1567       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNKNOWN_PSK_IDENTITY);
1568       return ssl_hs_error;
1569     }
1570 
1571     if (alg_k & SSL_kPSK) {
1572       // In plain PSK, other_secret is a block of 0s with the same length as the
1573       // pre-shared key.
1574       if (!premaster_secret.Init(psk_len)) {
1575         return ssl_hs_error;
1576       }
1577       OPENSSL_memset(premaster_secret.data(), 0, premaster_secret.size());
1578     }
1579 
1580     ScopedCBB new_premaster;
1581     CBB child;
1582     if (!CBB_init(new_premaster.get(),
1583                   2 + psk_len + 2 + premaster_secret.size()) ||
1584         !CBB_add_u16_length_prefixed(new_premaster.get(), &child) ||
1585         !CBB_add_bytes(&child, premaster_secret.data(),
1586                        premaster_secret.size()) ||
1587         !CBB_add_u16_length_prefixed(new_premaster.get(), &child) ||
1588         !CBB_add_bytes(&child, psk, psk_len) ||
1589         !CBBFinishArray(new_premaster.get(), &premaster_secret)) {
1590       return ssl_hs_error;
1591     }
1592   }
1593 
1594   if (!ssl_hash_message(hs, msg)) {
1595     return ssl_hs_error;
1596   }
1597 
1598   // Compute the master secret.
1599   hs->new_session->secret_length = tls1_generate_master_secret(
1600       hs, hs->new_session->secret, premaster_secret);
1601   if (hs->new_session->secret_length == 0) {
1602     return ssl_hs_error;
1603   }
1604   hs->new_session->extended_master_secret = hs->extended_master_secret;
1605   CONSTTIME_DECLASSIFY(hs->new_session->secret, hs->new_session->secret_length);
1606   hs->can_release_private_key = true;
1607 
1608   ssl->method->next_message(ssl);
1609   hs->state = state12_read_client_certificate_verify;
1610   return ssl_hs_ok;
1611 }
1612 
do_read_client_certificate_verify(SSL_HANDSHAKE * hs)1613 static enum ssl_hs_wait_t do_read_client_certificate_verify(SSL_HANDSHAKE *hs) {
1614   SSL *const ssl = hs->ssl;
1615 
1616   // Only RSA and ECDSA client certificates are supported, so a
1617   // CertificateVerify is required if and only if there's a client certificate.
1618   if (!hs->peer_pubkey) {
1619     hs->transcript.FreeBuffer();
1620     hs->state = state12_read_change_cipher_spec;
1621     return ssl_hs_ok;
1622   }
1623 
1624   SSLMessage msg;
1625   if (!ssl->method->get_message(ssl, &msg)) {
1626     return ssl_hs_read_message;
1627   }
1628 
1629   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_VERIFY)) {
1630     return ssl_hs_error;
1631   }
1632 
1633   // The peer certificate must be valid for signing.
1634   const CRYPTO_BUFFER *leaf =
1635       sk_CRYPTO_BUFFER_value(hs->new_session->certs.get(), 0);
1636   CBS leaf_cbs;
1637   CRYPTO_BUFFER_init_CBS(leaf, &leaf_cbs);
1638   if (!ssl_cert_check_key_usage(&leaf_cbs, key_usage_digital_signature)) {
1639     return ssl_hs_error;
1640   }
1641 
1642   CBS certificate_verify = msg.body, signature;
1643 
1644   // Determine the signature algorithm.
1645   uint16_t signature_algorithm = 0;
1646   if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1647     if (!CBS_get_u16(&certificate_verify, &signature_algorithm)) {
1648       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1649       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1650       return ssl_hs_error;
1651     }
1652     uint8_t alert = SSL_AD_DECODE_ERROR;
1653     if (!tls12_check_peer_sigalg(hs, &alert, signature_algorithm)) {
1654       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1655       return ssl_hs_error;
1656     }
1657     hs->new_session->peer_signature_algorithm = signature_algorithm;
1658   } else if (!tls1_get_legacy_signature_algorithm(&signature_algorithm,
1659                                                   hs->peer_pubkey.get())) {
1660     OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
1661     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_CERTIFICATE);
1662     return ssl_hs_error;
1663   }
1664 
1665   // Parse and verify the signature.
1666   if (!CBS_get_u16_length_prefixed(&certificate_verify, &signature) ||
1667       CBS_len(&certificate_verify) != 0) {
1668     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1669     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1670     return ssl_hs_error;
1671   }
1672 
1673   if (!ssl_public_key_verify(ssl, signature, signature_algorithm,
1674                              hs->peer_pubkey.get(), hs->transcript.buffer())) {
1675     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
1676     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
1677     return ssl_hs_error;
1678   }
1679 
1680   // The handshake buffer is no longer necessary, and we may hash the current
1681   // message.
1682   hs->transcript.FreeBuffer();
1683   if (!ssl_hash_message(hs, msg)) {
1684     return ssl_hs_error;
1685   }
1686 
1687   ssl->method->next_message(ssl);
1688   hs->state = state12_read_change_cipher_spec;
1689   return ssl_hs_ok;
1690 }
1691 
do_read_change_cipher_spec(SSL_HANDSHAKE * hs)1692 static enum ssl_hs_wait_t do_read_change_cipher_spec(SSL_HANDSHAKE *hs) {
1693   if (hs->handback && hs->ssl->session != NULL) {
1694     return ssl_hs_handback;
1695   }
1696   hs->state = state12_process_change_cipher_spec;
1697   return ssl_hs_read_change_cipher_spec;
1698 }
1699 
do_process_change_cipher_spec(SSL_HANDSHAKE * hs)1700 static enum ssl_hs_wait_t do_process_change_cipher_spec(SSL_HANDSHAKE *hs) {
1701   if (!tls1_change_cipher_state(hs, evp_aead_open)) {
1702     return ssl_hs_error;
1703   }
1704 
1705   hs->state = state12_read_next_proto;
1706   return ssl_hs_ok;
1707 }
1708 
do_read_next_proto(SSL_HANDSHAKE * hs)1709 static enum ssl_hs_wait_t do_read_next_proto(SSL_HANDSHAKE *hs) {
1710   SSL *const ssl = hs->ssl;
1711 
1712   if (!hs->next_proto_neg_seen) {
1713     hs->state = state12_read_channel_id;
1714     return ssl_hs_ok;
1715   }
1716 
1717   SSLMessage msg;
1718   if (!ssl->method->get_message(ssl, &msg)) {
1719     return ssl_hs_read_message;
1720   }
1721 
1722   if (!ssl_check_message_type(ssl, msg, SSL3_MT_NEXT_PROTO) ||
1723       !ssl_hash_message(hs, msg)) {
1724     return ssl_hs_error;
1725   }
1726 
1727   CBS next_protocol = msg.body, selected_protocol, padding;
1728   if (!CBS_get_u8_length_prefixed(&next_protocol, &selected_protocol) ||
1729       !CBS_get_u8_length_prefixed(&next_protocol, &padding) ||
1730       CBS_len(&next_protocol) != 0) {
1731     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1732     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1733     return ssl_hs_error;
1734   }
1735 
1736   if (!ssl->s3->next_proto_negotiated.CopyFrom(selected_protocol)) {
1737     return ssl_hs_error;
1738   }
1739 
1740   ssl->method->next_message(ssl);
1741   hs->state = state12_read_channel_id;
1742   return ssl_hs_ok;
1743 }
1744 
do_read_channel_id(SSL_HANDSHAKE * hs)1745 static enum ssl_hs_wait_t do_read_channel_id(SSL_HANDSHAKE *hs) {
1746   SSL *const ssl = hs->ssl;
1747 
1748   if (!hs->channel_id_negotiated) {
1749     hs->state = state12_read_client_finished;
1750     return ssl_hs_ok;
1751   }
1752 
1753   SSLMessage msg;
1754   if (!ssl->method->get_message(ssl, &msg)) {
1755     return ssl_hs_read_message;
1756   }
1757 
1758   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CHANNEL_ID) ||
1759       !tls1_verify_channel_id(hs, msg) ||
1760       !ssl_hash_message(hs, msg)) {
1761     return ssl_hs_error;
1762   }
1763 
1764   ssl->method->next_message(ssl);
1765   hs->state = state12_read_client_finished;
1766   return ssl_hs_ok;
1767 }
1768 
do_read_client_finished(SSL_HANDSHAKE * hs)1769 static enum ssl_hs_wait_t do_read_client_finished(SSL_HANDSHAKE *hs) {
1770   SSL *const ssl = hs->ssl;
1771   enum ssl_hs_wait_t wait = ssl_get_finished(hs);
1772   if (wait != ssl_hs_ok) {
1773     return wait;
1774   }
1775 
1776   if (ssl->session != NULL) {
1777     hs->state = state12_finish_server_handshake;
1778   } else {
1779     hs->state = state12_send_server_finished;
1780   }
1781 
1782   // If this is a full handshake with ChannelID then record the handshake
1783   // hashes in |hs->new_session| in case we need them to verify a
1784   // ChannelID signature on a resumption of this session in the future.
1785   if (ssl->session == NULL && ssl->s3->channel_id_valid &&
1786       !tls1_record_handshake_hashes_for_channel_id(hs)) {
1787     return ssl_hs_error;
1788   }
1789 
1790   return ssl_hs_ok;
1791 }
1792 
do_send_server_finished(SSL_HANDSHAKE * hs)1793 static enum ssl_hs_wait_t do_send_server_finished(SSL_HANDSHAKE *hs) {
1794   SSL *const ssl = hs->ssl;
1795 
1796   if (hs->ticket_expected) {
1797     const SSL_SESSION *session;
1798     UniquePtr<SSL_SESSION> session_copy;
1799     if (ssl->session == NULL) {
1800       // Fix the timeout to measure from the ticket issuance time.
1801       ssl_session_rebase_time(ssl, hs->new_session.get());
1802       session = hs->new_session.get();
1803     } else {
1804       // We are renewing an existing session. Duplicate the session to adjust
1805       // the timeout.
1806       session_copy =
1807           SSL_SESSION_dup(ssl->session.get(), SSL_SESSION_INCLUDE_NONAUTH);
1808       if (!session_copy) {
1809         return ssl_hs_error;
1810       }
1811 
1812       ssl_session_rebase_time(ssl, session_copy.get());
1813       session = session_copy.get();
1814     }
1815 
1816     ScopedCBB cbb;
1817     CBB body, ticket;
1818     if (!ssl->method->init_message(ssl, cbb.get(), &body,
1819                                    SSL3_MT_NEW_SESSION_TICKET) ||
1820         !CBB_add_u32(&body, session->timeout) ||
1821         !CBB_add_u16_length_prefixed(&body, &ticket) ||
1822         !ssl_encrypt_ticket(hs, &ticket, session) ||
1823         !ssl_add_message_cbb(ssl, cbb.get())) {
1824       return ssl_hs_error;
1825     }
1826   }
1827 
1828   if (!ssl->method->add_change_cipher_spec(ssl) ||
1829       !tls1_change_cipher_state(hs, evp_aead_seal) ||
1830       !ssl_send_finished(hs)) {
1831     return ssl_hs_error;
1832   }
1833 
1834   if (ssl->session != NULL) {
1835     hs->state = state12_read_change_cipher_spec;
1836   } else {
1837     hs->state = state12_finish_server_handshake;
1838   }
1839   return ssl_hs_flush;
1840 }
1841 
do_finish_server_handshake(SSL_HANDSHAKE * hs)1842 static enum ssl_hs_wait_t do_finish_server_handshake(SSL_HANDSHAKE *hs) {
1843   SSL *const ssl = hs->ssl;
1844 
1845   if (hs->handback) {
1846     return ssl_hs_handback;
1847   }
1848 
1849   ssl->method->on_handshake_complete(ssl);
1850 
1851   // If we aren't retaining peer certificates then we can discard it now.
1852   if (hs->new_session != NULL &&
1853       hs->config->retain_only_sha256_of_client_certs) {
1854     hs->new_session->certs.reset();
1855     ssl->ctx->x509_method->session_clear(hs->new_session.get());
1856   }
1857 
1858   bool has_new_session = hs->new_session != nullptr;
1859   if (has_new_session) {
1860     assert(ssl->session == nullptr);
1861     ssl->s3->established_session = std::move(hs->new_session);
1862     ssl->s3->established_session->not_resumable = false;
1863   } else {
1864     assert(ssl->session != nullptr);
1865     ssl->s3->established_session = UpRef(ssl->session);
1866   }
1867 
1868   hs->handshake_finalized = true;
1869   ssl->s3->initial_handshake_complete = true;
1870   if (has_new_session) {
1871     ssl_update_cache(ssl);
1872   }
1873 
1874   hs->state = state12_done;
1875   return ssl_hs_ok;
1876 }
1877 
ssl_server_handshake(SSL_HANDSHAKE * hs)1878 enum ssl_hs_wait_t ssl_server_handshake(SSL_HANDSHAKE *hs) {
1879   while (hs->state != state12_done) {
1880     enum ssl_hs_wait_t ret = ssl_hs_error;
1881     enum tls12_server_hs_state_t state =
1882         static_cast<enum tls12_server_hs_state_t>(hs->state);
1883     switch (state) {
1884       case state12_start_accept:
1885         ret = do_start_accept(hs);
1886         break;
1887       case state12_read_client_hello:
1888         ret = do_read_client_hello(hs);
1889         break;
1890       case state12_read_client_hello_after_ech:
1891         ret = do_read_client_hello_after_ech(hs);
1892         break;
1893       case state12_cert_callback:
1894         ret = do_cert_callback(hs);
1895         break;
1896       case state12_tls13:
1897         ret = do_tls13(hs);
1898         break;
1899       case state12_select_parameters:
1900         ret = do_select_parameters(hs);
1901         break;
1902       case state12_send_server_hello:
1903         ret = do_send_server_hello(hs);
1904         break;
1905       case state12_send_server_certificate:
1906         ret = do_send_server_certificate(hs);
1907         break;
1908       case state12_send_server_key_exchange:
1909         ret = do_send_server_key_exchange(hs);
1910         break;
1911       case state12_send_server_hello_done:
1912         ret = do_send_server_hello_done(hs);
1913         break;
1914       case state12_read_client_certificate:
1915         ret = do_read_client_certificate(hs);
1916         break;
1917       case state12_verify_client_certificate:
1918         ret = do_verify_client_certificate(hs);
1919         break;
1920       case state12_read_client_key_exchange:
1921         ret = do_read_client_key_exchange(hs);
1922         break;
1923       case state12_read_client_certificate_verify:
1924         ret = do_read_client_certificate_verify(hs);
1925         break;
1926       case state12_read_change_cipher_spec:
1927         ret = do_read_change_cipher_spec(hs);
1928         break;
1929       case state12_process_change_cipher_spec:
1930         ret = do_process_change_cipher_spec(hs);
1931         break;
1932       case state12_read_next_proto:
1933         ret = do_read_next_proto(hs);
1934         break;
1935       case state12_read_channel_id:
1936         ret = do_read_channel_id(hs);
1937         break;
1938       case state12_read_client_finished:
1939         ret = do_read_client_finished(hs);
1940         break;
1941       case state12_send_server_finished:
1942         ret = do_send_server_finished(hs);
1943         break;
1944       case state12_finish_server_handshake:
1945         ret = do_finish_server_handshake(hs);
1946         break;
1947       case state12_done:
1948         ret = ssl_hs_ok;
1949         break;
1950     }
1951 
1952     if (hs->state != state) {
1953       ssl_do_info_callback(hs->ssl, SSL_CB_ACCEPT_LOOP, 1);
1954     }
1955 
1956     if (ret != ssl_hs_ok) {
1957       return ret;
1958     }
1959   }
1960 
1961   ssl_do_info_callback(hs->ssl, SSL_CB_HANDSHAKE_DONE, 1);
1962   return ssl_hs_ok;
1963 }
1964 
ssl_server_handshake_state(SSL_HANDSHAKE * hs)1965 const char *ssl_server_handshake_state(SSL_HANDSHAKE *hs) {
1966   enum tls12_server_hs_state_t state =
1967       static_cast<enum tls12_server_hs_state_t>(hs->state);
1968   switch (state) {
1969     case state12_start_accept:
1970       return "TLS server start_accept";
1971     case state12_read_client_hello:
1972       return "TLS server read_client_hello";
1973     case state12_read_client_hello_after_ech:
1974       return "TLS server read_client_hello_after_ech";
1975     case state12_cert_callback:
1976       return "TLS server cert_callback";
1977     case state12_tls13:
1978       return tls13_server_handshake_state(hs);
1979     case state12_select_parameters:
1980       return "TLS server select_parameters";
1981     case state12_send_server_hello:
1982       return "TLS server send_server_hello";
1983     case state12_send_server_certificate:
1984       return "TLS server send_server_certificate";
1985     case state12_send_server_key_exchange:
1986       return "TLS server send_server_key_exchange";
1987     case state12_send_server_hello_done:
1988       return "TLS server send_server_hello_done";
1989     case state12_read_client_certificate:
1990       return "TLS server read_client_certificate";
1991     case state12_verify_client_certificate:
1992       return "TLS server verify_client_certificate";
1993     case state12_read_client_key_exchange:
1994       return "TLS server read_client_key_exchange";
1995     case state12_read_client_certificate_verify:
1996       return "TLS server read_client_certificate_verify";
1997     case state12_read_change_cipher_spec:
1998       return "TLS server read_change_cipher_spec";
1999     case state12_process_change_cipher_spec:
2000       return "TLS server process_change_cipher_spec";
2001     case state12_read_next_proto:
2002       return "TLS server read_next_proto";
2003     case state12_read_channel_id:
2004       return "TLS server read_channel_id";
2005     case state12_read_client_finished:
2006       return "TLS server read_client_finished";
2007     case state12_send_server_finished:
2008       return "TLS server send_server_finished";
2009     case state12_finish_server_handshake:
2010       return "TLS server finish_server_handshake";
2011     case state12_done:
2012       return "TLS server done";
2013   }
2014 
2015   return "TLS server unknown";
2016 }
2017 
2018 BSSL_NAMESPACE_END
2019