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 #include <openssl/ssl.h>
110
111 #include <assert.h>
112 #include <limits.h>
113 #include <stdlib.h>
114 #include <string.h>
115
116 #include <algorithm>
117 #include <utility>
118
119 #include <openssl/aead.h>
120 #include <openssl/bytestring.h>
121 #include <openssl/chacha.h>
122 #include <openssl/curve25519.h>
123 #include <openssl/digest.h>
124 #include <openssl/err.h>
125 #include <openssl/evp.h>
126 #include <openssl/hmac.h>
127 #include <openssl/hpke.h>
128 #include <openssl/mem.h>
129 #include <openssl/nid.h>
130 #include <openssl/rand.h>
131
132 #include "../crypto/internal.h"
133 #include "internal.h"
134
135
136 BSSL_NAMESPACE_BEGIN
137
138 static bool ssl_check_clienthello_tlsext(SSL_HANDSHAKE *hs);
139 static bool ssl_check_serverhello_tlsext(SSL_HANDSHAKE *hs);
140
compare_uint16_t(const void * p1,const void * p2)141 static int compare_uint16_t(const void *p1, const void *p2) {
142 uint16_t u1 = *((const uint16_t *)p1);
143 uint16_t u2 = *((const uint16_t *)p2);
144 if (u1 < u2) {
145 return -1;
146 } else if (u1 > u2) {
147 return 1;
148 } else {
149 return 0;
150 }
151 }
152
153 // Per http://tools.ietf.org/html/rfc5246#section-7.4.1.4, there may not be
154 // more than one extension of the same type in a ClientHello or ServerHello.
155 // This function does an initial scan over the extensions block to filter those
156 // out.
tls1_check_duplicate_extensions(const CBS * cbs)157 static bool tls1_check_duplicate_extensions(const CBS *cbs) {
158 // First pass: count the extensions.
159 size_t num_extensions = 0;
160 CBS extensions = *cbs;
161 while (CBS_len(&extensions) > 0) {
162 uint16_t type;
163 CBS extension;
164
165 if (!CBS_get_u16(&extensions, &type) ||
166 !CBS_get_u16_length_prefixed(&extensions, &extension)) {
167 return false;
168 }
169
170 num_extensions++;
171 }
172
173 if (num_extensions == 0) {
174 return true;
175 }
176
177 Array<uint16_t> extension_types;
178 if (!extension_types.Init(num_extensions)) {
179 return false;
180 }
181
182 // Second pass: gather the extension types.
183 extensions = *cbs;
184 for (size_t i = 0; i < extension_types.size(); i++) {
185 CBS extension;
186
187 if (!CBS_get_u16(&extensions, &extension_types[i]) ||
188 !CBS_get_u16_length_prefixed(&extensions, &extension)) {
189 // This should not happen.
190 return false;
191 }
192 }
193 assert(CBS_len(&extensions) == 0);
194
195 // Sort the extensions and make sure there are no duplicates.
196 qsort(extension_types.data(), extension_types.size(), sizeof(uint16_t),
197 compare_uint16_t);
198 for (size_t i = 1; i < num_extensions; i++) {
199 if (extension_types[i - 1] == extension_types[i]) {
200 return false;
201 }
202 }
203
204 return true;
205 }
206
is_post_quantum_group(uint16_t id)207 static bool is_post_quantum_group(uint16_t id) {
208 return id == SSL_CURVE_CECPQ2;
209 }
210
ssl_client_hello_init(const SSL * ssl,SSL_CLIENT_HELLO * out,Span<const uint8_t> body)211 bool ssl_client_hello_init(const SSL *ssl, SSL_CLIENT_HELLO *out,
212 Span<const uint8_t> body) {
213 CBS cbs = body;
214 if (!ssl_parse_client_hello_with_trailing_data(ssl, &cbs, out) ||
215 CBS_len(&cbs) != 0) {
216 return false;
217 }
218 return true;
219 }
220
ssl_parse_client_hello_with_trailing_data(const SSL * ssl,CBS * cbs,SSL_CLIENT_HELLO * out)221 bool ssl_parse_client_hello_with_trailing_data(const SSL *ssl, CBS *cbs,
222 SSL_CLIENT_HELLO *out) {
223 OPENSSL_memset(out, 0, sizeof(*out));
224 out->ssl = const_cast<SSL *>(ssl);
225
226 CBS copy = *cbs;
227 CBS random, session_id;
228 if (!CBS_get_u16(cbs, &out->version) ||
229 !CBS_get_bytes(cbs, &random, SSL3_RANDOM_SIZE) ||
230 !CBS_get_u8_length_prefixed(cbs, &session_id) ||
231 CBS_len(&session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH) {
232 return false;
233 }
234
235 out->random = CBS_data(&random);
236 out->random_len = CBS_len(&random);
237 out->session_id = CBS_data(&session_id);
238 out->session_id_len = CBS_len(&session_id);
239
240 // Skip past DTLS cookie
241 if (SSL_is_dtls(out->ssl)) {
242 CBS cookie;
243 if (!CBS_get_u8_length_prefixed(cbs, &cookie) ||
244 CBS_len(&cookie) > DTLS1_COOKIE_LENGTH) {
245 return false;
246 }
247 }
248
249 CBS cipher_suites, compression_methods;
250 if (!CBS_get_u16_length_prefixed(cbs, &cipher_suites) ||
251 CBS_len(&cipher_suites) < 2 || (CBS_len(&cipher_suites) & 1) != 0 ||
252 !CBS_get_u8_length_prefixed(cbs, &compression_methods) ||
253 CBS_len(&compression_methods) < 1) {
254 return false;
255 }
256
257 out->cipher_suites = CBS_data(&cipher_suites);
258 out->cipher_suites_len = CBS_len(&cipher_suites);
259 out->compression_methods = CBS_data(&compression_methods);
260 out->compression_methods_len = CBS_len(&compression_methods);
261
262 // If the ClientHello ends here then it's valid, but doesn't have any
263 // extensions.
264 if (CBS_len(cbs) == 0) {
265 out->extensions = nullptr;
266 out->extensions_len = 0;
267 } else {
268 // Extract extensions and check it is valid.
269 CBS extensions;
270 if (!CBS_get_u16_length_prefixed(cbs, &extensions) ||
271 !tls1_check_duplicate_extensions(&extensions)) {
272 return false;
273 }
274 out->extensions = CBS_data(&extensions);
275 out->extensions_len = CBS_len(&extensions);
276 }
277
278 out->client_hello = CBS_data(©);
279 out->client_hello_len = CBS_len(©) - CBS_len(cbs);
280 return true;
281 }
282
ssl_client_hello_get_extension(const SSL_CLIENT_HELLO * client_hello,CBS * out,uint16_t extension_type)283 bool ssl_client_hello_get_extension(const SSL_CLIENT_HELLO *client_hello,
284 CBS *out, uint16_t extension_type) {
285 CBS extensions;
286 CBS_init(&extensions, client_hello->extensions, client_hello->extensions_len);
287 while (CBS_len(&extensions) != 0) {
288 // Decode the next extension.
289 uint16_t type;
290 CBS extension;
291 if (!CBS_get_u16(&extensions, &type) ||
292 !CBS_get_u16_length_prefixed(&extensions, &extension)) {
293 return false;
294 }
295
296 if (type == extension_type) {
297 *out = extension;
298 return true;
299 }
300 }
301
302 return false;
303 }
304
305 static const uint16_t kDefaultGroups[] = {
306 SSL_CURVE_X25519,
307 SSL_CURVE_SECP256R1,
308 SSL_CURVE_SECP384R1,
309 };
310
tls1_get_grouplist(const SSL_HANDSHAKE * hs)311 Span<const uint16_t> tls1_get_grouplist(const SSL_HANDSHAKE *hs) {
312 if (!hs->config->supported_group_list.empty()) {
313 return hs->config->supported_group_list;
314 }
315 return Span<const uint16_t>(kDefaultGroups);
316 }
317
tls1_get_shared_group(SSL_HANDSHAKE * hs,uint16_t * out_group_id)318 bool tls1_get_shared_group(SSL_HANDSHAKE *hs, uint16_t *out_group_id) {
319 SSL *const ssl = hs->ssl;
320 assert(ssl->server);
321
322 // Clients are not required to send a supported_groups extension. In this
323 // case, the server is free to pick any group it likes. See RFC 4492,
324 // section 4, paragraph 3.
325 //
326 // However, in the interests of compatibility, we will skip ECDH if the
327 // client didn't send an extension because we can't be sure that they'll
328 // support our favoured group. Thus we do not special-case an emtpy
329 // |peer_supported_group_list|.
330
331 Span<const uint16_t> groups = tls1_get_grouplist(hs);
332 Span<const uint16_t> pref, supp;
333 if (ssl->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
334 pref = groups;
335 supp = hs->peer_supported_group_list;
336 } else {
337 pref = hs->peer_supported_group_list;
338 supp = groups;
339 }
340
341 for (uint16_t pref_group : pref) {
342 for (uint16_t supp_group : supp) {
343 if (pref_group == supp_group &&
344 // CECPQ2(b) doesn't fit in the u8-length-prefixed ECPoint field in
345 // TLS 1.2 and below.
346 (ssl_protocol_version(ssl) >= TLS1_3_VERSION ||
347 !is_post_quantum_group(pref_group))) {
348 *out_group_id = pref_group;
349 return true;
350 }
351 }
352 }
353
354 return false;
355 }
356
tls1_set_curves(Array<uint16_t> * out_group_ids,Span<const int> curves)357 bool tls1_set_curves(Array<uint16_t> *out_group_ids, Span<const int> curves) {
358 Array<uint16_t> group_ids;
359 if (!group_ids.Init(curves.size())) {
360 return false;
361 }
362
363 for (size_t i = 0; i < curves.size(); i++) {
364 if (!ssl_nid_to_group_id(&group_ids[i], curves[i])) {
365 return false;
366 }
367 }
368
369 *out_group_ids = std::move(group_ids);
370 return true;
371 }
372
tls1_set_curves_list(Array<uint16_t> * out_group_ids,const char * curves)373 bool tls1_set_curves_list(Array<uint16_t> *out_group_ids, const char *curves) {
374 // Count the number of curves in the list.
375 size_t count = 0;
376 const char *ptr = curves, *col;
377 do {
378 col = strchr(ptr, ':');
379 count++;
380 if (col) {
381 ptr = col + 1;
382 }
383 } while (col);
384
385 Array<uint16_t> group_ids;
386 if (!group_ids.Init(count)) {
387 return false;
388 }
389
390 size_t i = 0;
391 ptr = curves;
392 do {
393 col = strchr(ptr, ':');
394 if (!ssl_name_to_group_id(&group_ids[i++], ptr,
395 col ? (size_t)(col - ptr) : strlen(ptr))) {
396 return false;
397 }
398 if (col) {
399 ptr = col + 1;
400 }
401 } while (col);
402
403 assert(i == count);
404 *out_group_ids = std::move(group_ids);
405 return true;
406 }
407
tls1_check_group_id(const SSL_HANDSHAKE * hs,uint16_t group_id)408 bool tls1_check_group_id(const SSL_HANDSHAKE *hs, uint16_t group_id) {
409 if (is_post_quantum_group(group_id) &&
410 ssl_protocol_version(hs->ssl) < TLS1_3_VERSION) {
411 // CECPQ2(b) requires TLS 1.3.
412 return false;
413 }
414
415 // We internally assume zero is never allocated as a group ID.
416 if (group_id == 0) {
417 return false;
418 }
419
420 for (uint16_t supported : tls1_get_grouplist(hs)) {
421 if (supported == group_id) {
422 return true;
423 }
424 }
425
426 return false;
427 }
428
429 // kVerifySignatureAlgorithms is the default list of accepted signature
430 // algorithms for verifying.
431 static const uint16_t kVerifySignatureAlgorithms[] = {
432 // List our preferred algorithms first.
433 SSL_SIGN_ECDSA_SECP256R1_SHA256,
434 SSL_SIGN_RSA_PSS_RSAE_SHA256,
435 SSL_SIGN_RSA_PKCS1_SHA256,
436
437 // Larger hashes are acceptable.
438 SSL_SIGN_ECDSA_SECP384R1_SHA384,
439 SSL_SIGN_RSA_PSS_RSAE_SHA384,
440 SSL_SIGN_RSA_PKCS1_SHA384,
441
442 SSL_SIGN_RSA_PSS_RSAE_SHA512,
443 SSL_SIGN_RSA_PKCS1_SHA512,
444
445 // For now, SHA-1 is still accepted but least preferable.
446 SSL_SIGN_RSA_PKCS1_SHA1,
447 };
448
449 // kSignSignatureAlgorithms is the default list of supported signature
450 // algorithms for signing.
451 static const uint16_t kSignSignatureAlgorithms[] = {
452 // List our preferred algorithms first.
453 SSL_SIGN_ED25519,
454 SSL_SIGN_ECDSA_SECP256R1_SHA256,
455 SSL_SIGN_RSA_PSS_RSAE_SHA256,
456 SSL_SIGN_RSA_PKCS1_SHA256,
457
458 // If needed, sign larger hashes.
459 //
460 // TODO(davidben): Determine which of these may be pruned.
461 SSL_SIGN_ECDSA_SECP384R1_SHA384,
462 SSL_SIGN_RSA_PSS_RSAE_SHA384,
463 SSL_SIGN_RSA_PKCS1_SHA384,
464
465 SSL_SIGN_ECDSA_SECP521R1_SHA512,
466 SSL_SIGN_RSA_PSS_RSAE_SHA512,
467 SSL_SIGN_RSA_PKCS1_SHA512,
468
469 // If the peer supports nothing else, sign with SHA-1.
470 SSL_SIGN_ECDSA_SHA1,
471 SSL_SIGN_RSA_PKCS1_SHA1,
472 };
473
tls12_get_verify_sigalgs(const SSL_HANDSHAKE * hs)474 static Span<const uint16_t> tls12_get_verify_sigalgs(const SSL_HANDSHAKE *hs) {
475 if (hs->config->verify_sigalgs.empty()) {
476 return Span<const uint16_t>(kVerifySignatureAlgorithms);
477 }
478 return hs->config->verify_sigalgs;
479 }
480
tls12_add_verify_sigalgs(const SSL_HANDSHAKE * hs,CBB * out)481 bool tls12_add_verify_sigalgs(const SSL_HANDSHAKE *hs, CBB *out) {
482 for (uint16_t sigalg : tls12_get_verify_sigalgs(hs)) {
483 if (!CBB_add_u16(out, sigalg)) {
484 return false;
485 }
486 }
487 return true;
488 }
489
tls12_check_peer_sigalg(const SSL_HANDSHAKE * hs,uint8_t * out_alert,uint16_t sigalg)490 bool tls12_check_peer_sigalg(const SSL_HANDSHAKE *hs, uint8_t *out_alert,
491 uint16_t sigalg) {
492 for (uint16_t verify_sigalg : tls12_get_verify_sigalgs(hs)) {
493 if (verify_sigalg == sigalg) {
494 return true;
495 }
496 }
497
498 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SIGNATURE_TYPE);
499 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
500 return false;
501 }
502
503 // tls_extension represents a TLS extension that is handled internally.
504 //
505 // The parse callbacks receive a |CBS| that contains the contents of the
506 // extension (i.e. not including the type and length bytes). If an extension is
507 // not received then the parse callbacks will be called with a NULL CBS so that
508 // they can do any processing needed to handle the absence of an extension.
509 //
510 // The add callbacks receive a |CBB| to which the extension can be appended but
511 // the function is responsible for appending the type and length bytes too.
512 //
513 // |add_clienthello| may be called multiple times and must not mutate |hs|. It
514 // is additionally passed two output |CBB|s. If the extension is the same
515 // independent of the value of |type|, the callback may write to
516 // |out_compressible| instead of |out|. When serializing the ClientHelloInner,
517 // all compressible extensions will be made continguous and replaced with
518 // ech_outer_extensions when encrypted. When serializing the ClientHelloOuter
519 // or not offering ECH, |out| will be equal to |out_compressible|, so writing to
520 // |out_compressible| still works.
521 //
522 // Note the |parse_serverhello| and |add_serverhello| callbacks refer to the
523 // TLS 1.2 ServerHello. In TLS 1.3, these callbacks act on EncryptedExtensions,
524 // with ServerHello extensions handled elsewhere in the handshake.
525 //
526 // All callbacks return true for success and false for error. If a parse
527 // function returns zero then a fatal alert with value |*out_alert| will be
528 // sent. If |*out_alert| isn't set, then a |decode_error| alert will be sent.
529 struct tls_extension {
530 uint16_t value;
531
532 bool (*add_clienthello)(const SSL_HANDSHAKE *hs, CBB *out,
533 CBB *out_compressible, ssl_client_hello_type_t type);
534 bool (*parse_serverhello)(SSL_HANDSHAKE *hs, uint8_t *out_alert,
535 CBS *contents);
536
537 bool (*parse_clienthello)(SSL_HANDSHAKE *hs, uint8_t *out_alert,
538 CBS *contents);
539 bool (*add_serverhello)(SSL_HANDSHAKE *hs, CBB *out);
540 };
541
forbid_parse_serverhello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)542 static bool forbid_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
543 CBS *contents) {
544 if (contents != NULL) {
545 // Servers MUST NOT send this extension.
546 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
547 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
548 return false;
549 }
550
551 return true;
552 }
553
ignore_parse_clienthello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)554 static bool ignore_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
555 CBS *contents) {
556 // This extension from the client is handled elsewhere.
557 return true;
558 }
559
dont_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)560 static bool dont_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
561 return true;
562 }
563
564 // Server name indication (SNI).
565 //
566 // https://tools.ietf.org/html/rfc6066#section-3.
567
ext_sni_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)568 static bool ext_sni_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
569 CBB *out_compressible,
570 ssl_client_hello_type_t type) {
571 const SSL *const ssl = hs->ssl;
572 // If offering ECH, send the public name instead of the configured name.
573 Span<const uint8_t> hostname;
574 if (type == ssl_client_hello_outer) {
575 hostname = hs->selected_ech_config->public_name;
576 } else {
577 if (ssl->hostname == nullptr) {
578 return true;
579 }
580 hostname =
581 MakeConstSpan(reinterpret_cast<const uint8_t *>(ssl->hostname.get()),
582 strlen(ssl->hostname.get()));
583 }
584
585 CBB contents, server_name_list, name;
586 if (!CBB_add_u16(out, TLSEXT_TYPE_server_name) ||
587 !CBB_add_u16_length_prefixed(out, &contents) ||
588 !CBB_add_u16_length_prefixed(&contents, &server_name_list) ||
589 !CBB_add_u8(&server_name_list, TLSEXT_NAMETYPE_host_name) ||
590 !CBB_add_u16_length_prefixed(&server_name_list, &name) ||
591 !CBB_add_bytes(&name, hostname.data(), hostname.size()) ||
592 !CBB_flush(out)) {
593 return false;
594 }
595
596 return true;
597 }
598
ext_sni_parse_serverhello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)599 static bool ext_sni_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
600 CBS *contents) {
601 // The server may acknowledge SNI with an empty extension. We check the syntax
602 // but otherwise ignore this signal.
603 return contents == NULL || CBS_len(contents) == 0;
604 }
605
ext_sni_parse_clienthello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)606 static bool ext_sni_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
607 CBS *contents) {
608 // SNI has already been parsed earlier in the handshake. See |extract_sni|.
609 return true;
610 }
611
ext_sni_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)612 static bool ext_sni_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
613 if (hs->ssl->s3->session_reused ||
614 !hs->should_ack_sni) {
615 return true;
616 }
617
618 if (!CBB_add_u16(out, TLSEXT_TYPE_server_name) ||
619 !CBB_add_u16(out, 0 /* length */)) {
620 return false;
621 }
622
623 return true;
624 }
625
626
627 // Encrypted ClientHello (ECH)
628 //
629 // https://tools.ietf.org/html/draft-ietf-tls-esni-13
630
ext_ech_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)631 static bool ext_ech_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
632 CBB *out_compressible,
633 ssl_client_hello_type_t type) {
634 if (type == ssl_client_hello_inner) {
635 if (!CBB_add_u16(out, TLSEXT_TYPE_encrypted_client_hello) ||
636 !CBB_add_u16(out, /* length */ 1) ||
637 !CBB_add_u8(out, ECH_CLIENT_INNER)) {
638 return false;
639 }
640 return true;
641 }
642
643 if (hs->ech_client_outer.empty()) {
644 return true;
645 }
646
647 CBB ech_body;
648 if (!CBB_add_u16(out, TLSEXT_TYPE_encrypted_client_hello) ||
649 !CBB_add_u16_length_prefixed(out, &ech_body) ||
650 !CBB_add_u8(&ech_body, ECH_CLIENT_OUTER) ||
651 !CBB_add_bytes(&ech_body, hs->ech_client_outer.data(),
652 hs->ech_client_outer.size()) ||
653 !CBB_flush(out)) {
654 return false;
655 }
656 return true;
657 }
658
ext_ech_parse_serverhello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)659 static bool ext_ech_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
660 CBS *contents) {
661 SSL *const ssl = hs->ssl;
662 if (contents == NULL) {
663 return true;
664 }
665
666 // The ECH extension may not be sent in TLS 1.2 ServerHello, only TLS 1.3
667 // EncryptedExtensions. It also may not be sent in response to an inner ECH
668 // extension.
669 if (ssl_protocol_version(ssl) < TLS1_3_VERSION ||
670 ssl->s3->ech_status == ssl_ech_accepted) {
671 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
672 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
673 return false;
674 }
675
676 if (!ssl_is_valid_ech_config_list(*contents)) {
677 *out_alert = SSL_AD_DECODE_ERROR;
678 return false;
679 }
680
681 if (ssl->s3->ech_status == ssl_ech_rejected &&
682 !hs->ech_retry_configs.CopyFrom(*contents)) {
683 *out_alert = SSL_AD_INTERNAL_ERROR;
684 return false;
685 }
686
687 return true;
688 }
689
ext_ech_parse_clienthello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)690 static bool ext_ech_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
691 CBS *contents) {
692 if (contents == nullptr) {
693 return true;
694 }
695
696 uint8_t type;
697 if (!CBS_get_u8(contents, &type)) {
698 return false;
699 }
700 if (type == ECH_CLIENT_OUTER) {
701 // Outer ECH extensions are handled outside the callback.
702 return true;
703 }
704 if (type != ECH_CLIENT_INNER || CBS_len(contents) != 0) {
705 return false;
706 }
707
708 hs->ech_is_inner = true;
709 return true;
710 }
711
ext_ech_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)712 static bool ext_ech_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
713 SSL *const ssl = hs->ssl;
714 if (ssl_protocol_version(ssl) < TLS1_3_VERSION ||
715 ssl->s3->ech_status == ssl_ech_accepted || //
716 hs->ech_keys == nullptr) {
717 return true;
718 }
719
720 // Write the list of retry configs to |out|. Note |SSL_CTX_set1_ech_keys|
721 // ensures |ech_keys| contains at least one retry config.
722 CBB body, retry_configs;
723 if (!CBB_add_u16(out, TLSEXT_TYPE_encrypted_client_hello) ||
724 !CBB_add_u16_length_prefixed(out, &body) ||
725 !CBB_add_u16_length_prefixed(&body, &retry_configs)) {
726 return false;
727 }
728 for (const auto &config : hs->ech_keys->configs) {
729 if (!config->is_retry_config()) {
730 continue;
731 }
732 if (!CBB_add_bytes(&retry_configs, config->ech_config().raw.data(),
733 config->ech_config().raw.size())) {
734 return false;
735 }
736 }
737 return CBB_flush(out);
738 }
739
740
741 // Renegotiation indication.
742 //
743 // https://tools.ietf.org/html/rfc5746
744
ext_ri_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)745 static bool ext_ri_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
746 CBB *out_compressible,
747 ssl_client_hello_type_t type) {
748 const SSL *const ssl = hs->ssl;
749 // Renegotiation indication is not necessary in TLS 1.3.
750 if (hs->min_version >= TLS1_3_VERSION ||
751 type == ssl_client_hello_inner) {
752 return true;
753 }
754
755 assert(ssl->s3->initial_handshake_complete ==
756 (ssl->s3->previous_client_finished_len != 0));
757
758 CBB contents, prev_finished;
759 if (!CBB_add_u16(out, TLSEXT_TYPE_renegotiate) ||
760 !CBB_add_u16_length_prefixed(out, &contents) ||
761 !CBB_add_u8_length_prefixed(&contents, &prev_finished) ||
762 !CBB_add_bytes(&prev_finished, ssl->s3->previous_client_finished,
763 ssl->s3->previous_client_finished_len) ||
764 !CBB_flush(out)) {
765 return false;
766 }
767
768 return true;
769 }
770
ext_ri_parse_serverhello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)771 static bool ext_ri_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
772 CBS *contents) {
773 SSL *const ssl = hs->ssl;
774 if (contents != NULL && ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
775 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
776 return false;
777 }
778
779 // Servers may not switch between omitting the extension and supporting it.
780 // See RFC 5746, sections 3.5 and 4.2.
781 if (ssl->s3->initial_handshake_complete &&
782 (contents != NULL) != ssl->s3->send_connection_binding) {
783 *out_alert = SSL_AD_HANDSHAKE_FAILURE;
784 OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
785 return false;
786 }
787
788 if (contents == NULL) {
789 // Strictly speaking, if we want to avoid an attack we should *always* see
790 // RI even on initial ServerHello because the client doesn't see any
791 // renegotiation during an attack. However this would mean we could not
792 // connect to any server which doesn't support RI.
793 //
794 // OpenSSL has |SSL_OP_LEGACY_SERVER_CONNECT| to control this, but in
795 // practical terms every client sets it so it's just assumed here.
796 return true;
797 }
798
799 const size_t expected_len = ssl->s3->previous_client_finished_len +
800 ssl->s3->previous_server_finished_len;
801
802 // Check for logic errors
803 assert(!expected_len || ssl->s3->previous_client_finished_len);
804 assert(!expected_len || ssl->s3->previous_server_finished_len);
805 assert(ssl->s3->initial_handshake_complete ==
806 (ssl->s3->previous_client_finished_len != 0));
807 assert(ssl->s3->initial_handshake_complete ==
808 (ssl->s3->previous_server_finished_len != 0));
809
810 // Parse out the extension contents.
811 CBS renegotiated_connection;
812 if (!CBS_get_u8_length_prefixed(contents, &renegotiated_connection) ||
813 CBS_len(contents) != 0) {
814 OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_ENCODING_ERR);
815 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
816 return false;
817 }
818
819 // Check that the extension matches.
820 if (CBS_len(&renegotiated_connection) != expected_len) {
821 OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
822 *out_alert = SSL_AD_HANDSHAKE_FAILURE;
823 return false;
824 }
825
826 const uint8_t *d = CBS_data(&renegotiated_connection);
827 bool ok = CRYPTO_memcmp(d, ssl->s3->previous_client_finished,
828 ssl->s3->previous_client_finished_len) == 0;
829 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
830 ok = true;
831 #endif
832 if (!ok) {
833 OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
834 *out_alert = SSL_AD_HANDSHAKE_FAILURE;
835 return false;
836 }
837 d += ssl->s3->previous_client_finished_len;
838
839 ok = CRYPTO_memcmp(d, ssl->s3->previous_server_finished,
840 ssl->s3->previous_server_finished_len) == 0;
841 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
842 ok = true;
843 #endif
844 if (!ok) {
845 OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
846 *out_alert = SSL_AD_HANDSHAKE_FAILURE;
847 return false;
848 }
849 ssl->s3->send_connection_binding = true;
850
851 return true;
852 }
853
ext_ri_parse_clienthello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)854 static bool ext_ri_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
855 CBS *contents) {
856 SSL *const ssl = hs->ssl;
857 // Renegotiation isn't supported as a server so this function should never be
858 // called after the initial handshake.
859 assert(!ssl->s3->initial_handshake_complete);
860
861 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
862 return true;
863 }
864
865 if (contents == NULL) {
866 return true;
867 }
868
869 CBS renegotiated_connection;
870 if (!CBS_get_u8_length_prefixed(contents, &renegotiated_connection) ||
871 CBS_len(contents) != 0) {
872 OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_ENCODING_ERR);
873 return false;
874 }
875
876 // Check that the extension matches. We do not support renegotiation as a
877 // server, so this must be empty.
878 if (CBS_len(&renegotiated_connection) != 0) {
879 OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_MISMATCH);
880 *out_alert = SSL_AD_HANDSHAKE_FAILURE;
881 return false;
882 }
883
884 ssl->s3->send_connection_binding = true;
885
886 return true;
887 }
888
ext_ri_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)889 static bool ext_ri_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
890 SSL *const ssl = hs->ssl;
891 // Renegotiation isn't supported as a server so this function should never be
892 // called after the initial handshake.
893 assert(!ssl->s3->initial_handshake_complete);
894
895 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
896 return true;
897 }
898
899 if (!CBB_add_u16(out, TLSEXT_TYPE_renegotiate) ||
900 !CBB_add_u16(out, 1 /* length */) ||
901 !CBB_add_u8(out, 0 /* empty renegotiation info */)) {
902 return false;
903 }
904
905 return true;
906 }
907
908
909 // Extended Master Secret.
910 //
911 // https://tools.ietf.org/html/rfc7627
912
ext_ems_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)913 static bool ext_ems_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
914 CBB *out_compressible,
915 ssl_client_hello_type_t type) {
916 // Extended master secret is not necessary in TLS 1.3.
917 if (hs->min_version >= TLS1_3_VERSION || type == ssl_client_hello_inner) {
918 return true;
919 }
920
921 if (!CBB_add_u16(out, TLSEXT_TYPE_extended_master_secret) ||
922 !CBB_add_u16(out, 0 /* length */)) {
923 return false;
924 }
925
926 return true;
927 }
928
ext_ems_parse_serverhello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)929 static bool ext_ems_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
930 CBS *contents) {
931 SSL *const ssl = hs->ssl;
932
933 if (contents != NULL) {
934 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION ||
935 CBS_len(contents) != 0) {
936 return false;
937 }
938
939 hs->extended_master_secret = true;
940 }
941
942 // Whether EMS is negotiated may not change on renegotiation.
943 if (ssl->s3->established_session != nullptr &&
944 hs->extended_master_secret !=
945 !!ssl->s3->established_session->extended_master_secret) {
946 OPENSSL_PUT_ERROR(SSL, SSL_R_RENEGOTIATION_EMS_MISMATCH);
947 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
948 return false;
949 }
950
951 return true;
952 }
953
ext_ems_parse_clienthello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)954 static bool ext_ems_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
955 CBS *contents) {
956 if (ssl_protocol_version(hs->ssl) >= TLS1_3_VERSION) {
957 return true;
958 }
959
960 if (contents == NULL) {
961 return true;
962 }
963
964 if (CBS_len(contents) != 0) {
965 return false;
966 }
967
968 hs->extended_master_secret = true;
969 return true;
970 }
971
ext_ems_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)972 static bool ext_ems_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
973 if (!hs->extended_master_secret) {
974 return true;
975 }
976
977 if (!CBB_add_u16(out, TLSEXT_TYPE_extended_master_secret) ||
978 !CBB_add_u16(out, 0 /* length */)) {
979 return false;
980 }
981
982 return true;
983 }
984
985
986 // Session tickets.
987 //
988 // https://tools.ietf.org/html/rfc5077
989
ext_ticket_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)990 static bool ext_ticket_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
991 CBB *out_compressible,
992 ssl_client_hello_type_t type) {
993 const SSL *const ssl = hs->ssl;
994 // TLS 1.3 uses a different ticket extension.
995 if (hs->min_version >= TLS1_3_VERSION || type == ssl_client_hello_inner ||
996 SSL_get_options(ssl) & SSL_OP_NO_TICKET) {
997 return true;
998 }
999
1000 Span<const uint8_t> ticket;
1001
1002 // Renegotiation does not participate in session resumption. However, still
1003 // advertise the extension to avoid potentially breaking servers which carry
1004 // over the state from the previous handshake, such as OpenSSL servers
1005 // without upstream's 3c3f0259238594d77264a78944d409f2127642c4.
1006 if (!ssl->s3->initial_handshake_complete &&
1007 ssl->session != nullptr &&
1008 !ssl->session->ticket.empty() &&
1009 // Don't send TLS 1.3 session tickets in the ticket extension.
1010 ssl_session_protocol_version(ssl->session.get()) < TLS1_3_VERSION) {
1011 ticket = ssl->session->ticket;
1012 }
1013
1014 CBB ticket_cbb;
1015 if (!CBB_add_u16(out, TLSEXT_TYPE_session_ticket) ||
1016 !CBB_add_u16_length_prefixed(out, &ticket_cbb) ||
1017 !CBB_add_bytes(&ticket_cbb, ticket.data(), ticket.size()) ||
1018 !CBB_flush(out)) {
1019 return false;
1020 }
1021
1022 return true;
1023 }
1024
ext_ticket_parse_serverhello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)1025 static bool ext_ticket_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1026 CBS *contents) {
1027 SSL *const ssl = hs->ssl;
1028 if (contents == NULL) {
1029 return true;
1030 }
1031
1032 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1033 return false;
1034 }
1035
1036 // If |SSL_OP_NO_TICKET| is set then no extension will have been sent and
1037 // this function should never be called, even if the server tries to send the
1038 // extension.
1039 assert((SSL_get_options(ssl) & SSL_OP_NO_TICKET) == 0);
1040
1041 if (CBS_len(contents) != 0) {
1042 return false;
1043 }
1044
1045 hs->ticket_expected = true;
1046 return true;
1047 }
1048
ext_ticket_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)1049 static bool ext_ticket_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1050 if (!hs->ticket_expected) {
1051 return true;
1052 }
1053
1054 // If |SSL_OP_NO_TICKET| is set, |ticket_expected| should never be true.
1055 assert((SSL_get_options(hs->ssl) & SSL_OP_NO_TICKET) == 0);
1056
1057 if (!CBB_add_u16(out, TLSEXT_TYPE_session_ticket) ||
1058 !CBB_add_u16(out, 0 /* length */)) {
1059 return false;
1060 }
1061
1062 return true;
1063 }
1064
1065
1066 // Signature Algorithms.
1067 //
1068 // https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
1069
ext_sigalgs_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)1070 static bool ext_sigalgs_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1071 CBB *out_compressible,
1072 ssl_client_hello_type_t type) {
1073 if (hs->max_version < TLS1_2_VERSION) {
1074 return true;
1075 }
1076
1077 CBB contents, sigalgs_cbb;
1078 if (!CBB_add_u16(out_compressible, TLSEXT_TYPE_signature_algorithms) ||
1079 !CBB_add_u16_length_prefixed(out_compressible, &contents) ||
1080 !CBB_add_u16_length_prefixed(&contents, &sigalgs_cbb) ||
1081 !tls12_add_verify_sigalgs(hs, &sigalgs_cbb) ||
1082 !CBB_flush(out_compressible)) {
1083 return false;
1084 }
1085
1086 return true;
1087 }
1088
ext_sigalgs_parse_clienthello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)1089 static bool ext_sigalgs_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1090 CBS *contents) {
1091 hs->peer_sigalgs.Reset();
1092 if (contents == NULL) {
1093 return true;
1094 }
1095
1096 CBS supported_signature_algorithms;
1097 if (!CBS_get_u16_length_prefixed(contents, &supported_signature_algorithms) ||
1098 CBS_len(contents) != 0 ||
1099 !tls1_parse_peer_sigalgs(hs, &supported_signature_algorithms)) {
1100 return false;
1101 }
1102
1103 return true;
1104 }
1105
1106
1107 // OCSP Stapling.
1108 //
1109 // https://tools.ietf.org/html/rfc6066#section-8
1110
ext_ocsp_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)1111 static bool ext_ocsp_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1112 CBB *out_compressible,
1113 ssl_client_hello_type_t type) {
1114 if (!hs->config->ocsp_stapling_enabled) {
1115 return true;
1116 }
1117
1118 CBB contents;
1119 if (!CBB_add_u16(out_compressible, TLSEXT_TYPE_status_request) ||
1120 !CBB_add_u16_length_prefixed(out_compressible, &contents) ||
1121 !CBB_add_u8(&contents, TLSEXT_STATUSTYPE_ocsp) ||
1122 !CBB_add_u16(&contents, 0 /* empty responder ID list */) ||
1123 !CBB_add_u16(&contents, 0 /* empty request extensions */) ||
1124 !CBB_flush(out_compressible)) {
1125 return false;
1126 }
1127
1128 return true;
1129 }
1130
ext_ocsp_parse_serverhello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)1131 static bool ext_ocsp_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1132 CBS *contents) {
1133 SSL *const ssl = hs->ssl;
1134 if (contents == NULL) {
1135 return true;
1136 }
1137
1138 // TLS 1.3 OCSP responses are included in the Certificate extensions.
1139 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1140 return false;
1141 }
1142
1143 // OCSP stapling is forbidden on non-certificate ciphers.
1144 if (CBS_len(contents) != 0 ||
1145 !ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1146 return false;
1147 }
1148
1149 // Note this does not check for resumption in TLS 1.2. Sending
1150 // status_request here does not make sense, but OpenSSL does so and the
1151 // specification does not say anything. Tolerate it but ignore it.
1152
1153 hs->certificate_status_expected = true;
1154 return true;
1155 }
1156
ext_ocsp_parse_clienthello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)1157 static bool ext_ocsp_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1158 CBS *contents) {
1159 if (contents == NULL) {
1160 return true;
1161 }
1162
1163 uint8_t status_type;
1164 if (!CBS_get_u8(contents, &status_type)) {
1165 return false;
1166 }
1167
1168 // We cannot decide whether OCSP stapling will occur yet because the correct
1169 // SSL_CTX might not have been selected.
1170 hs->ocsp_stapling_requested = status_type == TLSEXT_STATUSTYPE_ocsp;
1171
1172 return true;
1173 }
1174
ext_ocsp_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)1175 static bool ext_ocsp_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1176 SSL *const ssl = hs->ssl;
1177 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION ||
1178 !hs->ocsp_stapling_requested || hs->config->cert->ocsp_response == NULL ||
1179 ssl->s3->session_reused ||
1180 !ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1181 return true;
1182 }
1183
1184 hs->certificate_status_expected = true;
1185
1186 return CBB_add_u16(out, TLSEXT_TYPE_status_request) &&
1187 CBB_add_u16(out, 0 /* length */);
1188 }
1189
1190
1191 // Next protocol negotiation.
1192 //
1193 // https://htmlpreview.github.io/?https://github.com/agl/technotes/blob/master/nextprotoneg.html
1194
ext_npn_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)1195 static bool ext_npn_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1196 CBB *out_compressible,
1197 ssl_client_hello_type_t type) {
1198 const SSL *const ssl = hs->ssl;
1199 if (ssl->ctx->next_proto_select_cb == NULL ||
1200 // Do not allow NPN to change on renegotiation.
1201 ssl->s3->initial_handshake_complete ||
1202 // NPN is not defined in DTLS or TLS 1.3.
1203 SSL_is_dtls(ssl) || hs->min_version >= TLS1_3_VERSION ||
1204 type == ssl_client_hello_inner) {
1205 return true;
1206 }
1207
1208 if (!CBB_add_u16(out, TLSEXT_TYPE_next_proto_neg) ||
1209 !CBB_add_u16(out, 0 /* length */)) {
1210 return false;
1211 }
1212
1213 return true;
1214 }
1215
ext_npn_parse_serverhello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)1216 static bool ext_npn_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1217 CBS *contents) {
1218 SSL *const ssl = hs->ssl;
1219 if (contents == NULL) {
1220 return true;
1221 }
1222
1223 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1224 return false;
1225 }
1226
1227 // If any of these are false then we should never have sent the NPN
1228 // extension in the ClientHello and thus this function should never have been
1229 // called.
1230 assert(!ssl->s3->initial_handshake_complete);
1231 assert(!SSL_is_dtls(ssl));
1232 assert(ssl->ctx->next_proto_select_cb != NULL);
1233
1234 if (!ssl->s3->alpn_selected.empty()) {
1235 // NPN and ALPN may not be negotiated in the same connection.
1236 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1237 OPENSSL_PUT_ERROR(SSL, SSL_R_NEGOTIATED_BOTH_NPN_AND_ALPN);
1238 return false;
1239 }
1240
1241 const uint8_t *const orig_contents = CBS_data(contents);
1242 const size_t orig_len = CBS_len(contents);
1243
1244 while (CBS_len(contents) != 0) {
1245 CBS proto;
1246 if (!CBS_get_u8_length_prefixed(contents, &proto) ||
1247 CBS_len(&proto) == 0) {
1248 return false;
1249 }
1250 }
1251
1252 uint8_t *selected;
1253 uint8_t selected_len;
1254 if (ssl->ctx->next_proto_select_cb(
1255 ssl, &selected, &selected_len, orig_contents, orig_len,
1256 ssl->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK ||
1257 !ssl->s3->next_proto_negotiated.CopyFrom(
1258 MakeConstSpan(selected, selected_len))) {
1259 *out_alert = SSL_AD_INTERNAL_ERROR;
1260 return false;
1261 }
1262
1263 hs->next_proto_neg_seen = true;
1264 return true;
1265 }
1266
ext_npn_parse_clienthello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)1267 static bool ext_npn_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1268 CBS *contents) {
1269 SSL *const ssl = hs->ssl;
1270 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1271 return true;
1272 }
1273
1274 if (contents != NULL && CBS_len(contents) != 0) {
1275 return false;
1276 }
1277
1278 if (contents == NULL ||
1279 ssl->s3->initial_handshake_complete ||
1280 ssl->ctx->next_protos_advertised_cb == NULL ||
1281 SSL_is_dtls(ssl)) {
1282 return true;
1283 }
1284
1285 hs->next_proto_neg_seen = true;
1286 return true;
1287 }
1288
ext_npn_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)1289 static bool ext_npn_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1290 SSL *const ssl = hs->ssl;
1291 // |next_proto_neg_seen| might have been cleared when an ALPN extension was
1292 // parsed.
1293 if (!hs->next_proto_neg_seen) {
1294 return true;
1295 }
1296
1297 const uint8_t *npa;
1298 unsigned npa_len;
1299
1300 if (ssl->ctx->next_protos_advertised_cb(
1301 ssl, &npa, &npa_len, ssl->ctx->next_protos_advertised_cb_arg) !=
1302 SSL_TLSEXT_ERR_OK) {
1303 hs->next_proto_neg_seen = false;
1304 return true;
1305 }
1306
1307 CBB contents;
1308 if (!CBB_add_u16(out, TLSEXT_TYPE_next_proto_neg) ||
1309 !CBB_add_u16_length_prefixed(out, &contents) ||
1310 !CBB_add_bytes(&contents, npa, npa_len) ||
1311 !CBB_flush(out)) {
1312 return false;
1313 }
1314
1315 return true;
1316 }
1317
1318
1319 // Signed certificate timestamps.
1320 //
1321 // https://tools.ietf.org/html/rfc6962#section-3.3.1
1322
ext_sct_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)1323 static bool ext_sct_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1324 CBB *out_compressible,
1325 ssl_client_hello_type_t type) {
1326 if (!hs->config->signed_cert_timestamps_enabled) {
1327 return true;
1328 }
1329
1330 if (!CBB_add_u16(out_compressible, TLSEXT_TYPE_certificate_timestamp) ||
1331 !CBB_add_u16(out_compressible, 0 /* length */)) {
1332 return false;
1333 }
1334
1335 return true;
1336 }
1337
ext_sct_parse_serverhello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)1338 static bool ext_sct_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1339 CBS *contents) {
1340 SSL *const ssl = hs->ssl;
1341 if (contents == NULL) {
1342 return true;
1343 }
1344
1345 // TLS 1.3 SCTs are included in the Certificate extensions.
1346 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1347 *out_alert = SSL_AD_DECODE_ERROR;
1348 return false;
1349 }
1350
1351 // If this is false then we should never have sent the SCT extension in the
1352 // ClientHello and thus this function should never have been called.
1353 assert(hs->config->signed_cert_timestamps_enabled);
1354
1355 if (!ssl_is_sct_list_valid(contents)) {
1356 *out_alert = SSL_AD_DECODE_ERROR;
1357 return false;
1358 }
1359
1360 // Session resumption uses the original session information. The extension
1361 // should not be sent on resumption, but RFC 6962 did not make it a
1362 // requirement, so tolerate this.
1363 //
1364 // TODO(davidben): Enforce this anyway.
1365 if (!ssl->s3->session_reused) {
1366 hs->new_session->signed_cert_timestamp_list.reset(
1367 CRYPTO_BUFFER_new_from_CBS(contents, ssl->ctx->pool));
1368 if (hs->new_session->signed_cert_timestamp_list == nullptr) {
1369 *out_alert = SSL_AD_INTERNAL_ERROR;
1370 return false;
1371 }
1372 }
1373
1374 return true;
1375 }
1376
ext_sct_parse_clienthello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)1377 static bool ext_sct_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1378 CBS *contents) {
1379 if (contents == NULL) {
1380 return true;
1381 }
1382
1383 if (CBS_len(contents) != 0) {
1384 return false;
1385 }
1386
1387 hs->scts_requested = true;
1388 return true;
1389 }
1390
ext_sct_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)1391 static bool ext_sct_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1392 SSL *const ssl = hs->ssl;
1393 // The extension shouldn't be sent when resuming sessions.
1394 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION || ssl->s3->session_reused ||
1395 hs->config->cert->signed_cert_timestamp_list == NULL) {
1396 return true;
1397 }
1398
1399 CBB contents;
1400 return CBB_add_u16(out, TLSEXT_TYPE_certificate_timestamp) &&
1401 CBB_add_u16_length_prefixed(out, &contents) &&
1402 CBB_add_bytes(
1403 &contents,
1404 CRYPTO_BUFFER_data(
1405 hs->config->cert->signed_cert_timestamp_list.get()),
1406 CRYPTO_BUFFER_len(
1407 hs->config->cert->signed_cert_timestamp_list.get())) &&
1408 CBB_flush(out);
1409 }
1410
1411
1412 // Application-level Protocol Negotiation.
1413 //
1414 // https://tools.ietf.org/html/rfc7301
1415
ext_alpn_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)1416 static bool ext_alpn_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1417 CBB *out_compressible,
1418 ssl_client_hello_type_t type) {
1419 const SSL *const ssl = hs->ssl;
1420 if (hs->config->alpn_client_proto_list.empty() && ssl->quic_method) {
1421 // ALPN MUST be used with QUIC.
1422 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_APPLICATION_PROTOCOL);
1423 return false;
1424 }
1425
1426 if (hs->config->alpn_client_proto_list.empty() ||
1427 ssl->s3->initial_handshake_complete) {
1428 return true;
1429 }
1430
1431 CBB contents, proto_list;
1432 if (!CBB_add_u16(out_compressible,
1433 TLSEXT_TYPE_application_layer_protocol_negotiation) ||
1434 !CBB_add_u16_length_prefixed(out_compressible, &contents) ||
1435 !CBB_add_u16_length_prefixed(&contents, &proto_list) ||
1436 !CBB_add_bytes(&proto_list, hs->config->alpn_client_proto_list.data(),
1437 hs->config->alpn_client_proto_list.size()) ||
1438 !CBB_flush(out_compressible)) {
1439 return false;
1440 }
1441
1442 return true;
1443 }
1444
ext_alpn_parse_serverhello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)1445 static bool ext_alpn_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1446 CBS *contents) {
1447 SSL *const ssl = hs->ssl;
1448 if (contents == NULL) {
1449 if (ssl->quic_method) {
1450 // ALPN is required when QUIC is used.
1451 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_APPLICATION_PROTOCOL);
1452 *out_alert = SSL_AD_NO_APPLICATION_PROTOCOL;
1453 return false;
1454 }
1455 return true;
1456 }
1457
1458 assert(!ssl->s3->initial_handshake_complete);
1459 assert(!hs->config->alpn_client_proto_list.empty());
1460
1461 if (hs->next_proto_neg_seen) {
1462 // NPN and ALPN may not be negotiated in the same connection.
1463 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1464 OPENSSL_PUT_ERROR(SSL, SSL_R_NEGOTIATED_BOTH_NPN_AND_ALPN);
1465 return false;
1466 }
1467
1468 // The extension data consists of a ProtocolNameList which must have
1469 // exactly one ProtocolName. Each of these is length-prefixed.
1470 CBS protocol_name_list, protocol_name;
1471 if (!CBS_get_u16_length_prefixed(contents, &protocol_name_list) ||
1472 CBS_len(contents) != 0 ||
1473 !CBS_get_u8_length_prefixed(&protocol_name_list, &protocol_name) ||
1474 // Empty protocol names are forbidden.
1475 CBS_len(&protocol_name) == 0 ||
1476 CBS_len(&protocol_name_list) != 0) {
1477 return false;
1478 }
1479
1480 if (!ssl_is_alpn_protocol_allowed(hs, protocol_name)) {
1481 OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_ALPN_PROTOCOL);
1482 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1483 return false;
1484 }
1485
1486 if (!ssl->s3->alpn_selected.CopyFrom(protocol_name)) {
1487 *out_alert = SSL_AD_INTERNAL_ERROR;
1488 return false;
1489 }
1490
1491 return true;
1492 }
1493
ssl_is_valid_alpn_list(Span<const uint8_t> in)1494 bool ssl_is_valid_alpn_list(Span<const uint8_t> in) {
1495 CBS protocol_name_list = in;
1496 if (CBS_len(&protocol_name_list) == 0) {
1497 return false;
1498 }
1499 while (CBS_len(&protocol_name_list) > 0) {
1500 CBS protocol_name;
1501 if (!CBS_get_u8_length_prefixed(&protocol_name_list, &protocol_name) ||
1502 // Empty protocol names are forbidden.
1503 CBS_len(&protocol_name) == 0) {
1504 return false;
1505 }
1506 }
1507 return true;
1508 }
1509
ssl_is_alpn_protocol_allowed(const SSL_HANDSHAKE * hs,Span<const uint8_t> protocol)1510 bool ssl_is_alpn_protocol_allowed(const SSL_HANDSHAKE *hs,
1511 Span<const uint8_t> protocol) {
1512 if (hs->config->alpn_client_proto_list.empty()) {
1513 return false;
1514 }
1515
1516 if (hs->ssl->ctx->allow_unknown_alpn_protos) {
1517 return true;
1518 }
1519
1520 // Check that the protocol name is one of the ones we advertised.
1521 CBS client_protocol_name_list =
1522 MakeConstSpan(hs->config->alpn_client_proto_list),
1523 client_protocol_name;
1524 while (CBS_len(&client_protocol_name_list) > 0) {
1525 if (!CBS_get_u8_length_prefixed(&client_protocol_name_list,
1526 &client_protocol_name)) {
1527 return false;
1528 }
1529
1530 if (client_protocol_name == protocol) {
1531 return true;
1532 }
1533 }
1534
1535 return false;
1536 }
1537
ssl_negotiate_alpn(SSL_HANDSHAKE * hs,uint8_t * out_alert,const SSL_CLIENT_HELLO * client_hello)1538 bool ssl_negotiate_alpn(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1539 const SSL_CLIENT_HELLO *client_hello) {
1540 SSL *const ssl = hs->ssl;
1541 CBS contents;
1542 if (ssl->ctx->alpn_select_cb == NULL ||
1543 !ssl_client_hello_get_extension(
1544 client_hello, &contents,
1545 TLSEXT_TYPE_application_layer_protocol_negotiation)) {
1546 if (ssl->quic_method) {
1547 // ALPN is required when QUIC is used.
1548 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_APPLICATION_PROTOCOL);
1549 *out_alert = SSL_AD_NO_APPLICATION_PROTOCOL;
1550 return false;
1551 }
1552 // Ignore ALPN if not configured or no extension was supplied.
1553 return true;
1554 }
1555
1556 // ALPN takes precedence over NPN.
1557 hs->next_proto_neg_seen = false;
1558
1559 CBS protocol_name_list;
1560 if (!CBS_get_u16_length_prefixed(&contents, &protocol_name_list) ||
1561 CBS_len(&contents) != 0 ||
1562 !ssl_is_valid_alpn_list(protocol_name_list)) {
1563 OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
1564 *out_alert = SSL_AD_DECODE_ERROR;
1565 return false;
1566 }
1567
1568 const uint8_t *selected;
1569 uint8_t selected_len;
1570 int ret = ssl->ctx->alpn_select_cb(
1571 ssl, &selected, &selected_len, CBS_data(&protocol_name_list),
1572 CBS_len(&protocol_name_list), ssl->ctx->alpn_select_cb_arg);
1573 // ALPN is required when QUIC is used.
1574 if (ssl->quic_method &&
1575 (ret == SSL_TLSEXT_ERR_NOACK || ret == SSL_TLSEXT_ERR_ALERT_WARNING)) {
1576 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1577 }
1578 switch (ret) {
1579 case SSL_TLSEXT_ERR_OK:
1580 if (selected_len == 0) {
1581 OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_ALPN_PROTOCOL);
1582 *out_alert = SSL_AD_INTERNAL_ERROR;
1583 return false;
1584 }
1585 if (!ssl->s3->alpn_selected.CopyFrom(
1586 MakeConstSpan(selected, selected_len))) {
1587 *out_alert = SSL_AD_INTERNAL_ERROR;
1588 return false;
1589 }
1590 break;
1591 case SSL_TLSEXT_ERR_NOACK:
1592 case SSL_TLSEXT_ERR_ALERT_WARNING:
1593 break;
1594 case SSL_TLSEXT_ERR_ALERT_FATAL:
1595 *out_alert = SSL_AD_NO_APPLICATION_PROTOCOL;
1596 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_APPLICATION_PROTOCOL);
1597 return false;
1598 default:
1599 // Invalid return value.
1600 *out_alert = SSL_AD_INTERNAL_ERROR;
1601 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1602 return false;
1603 }
1604
1605 return true;
1606 }
1607
ext_alpn_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)1608 static bool ext_alpn_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1609 SSL *const ssl = hs->ssl;
1610 if (ssl->s3->alpn_selected.empty()) {
1611 return true;
1612 }
1613
1614 CBB contents, proto_list, proto;
1615 if (!CBB_add_u16(out, TLSEXT_TYPE_application_layer_protocol_negotiation) ||
1616 !CBB_add_u16_length_prefixed(out, &contents) ||
1617 !CBB_add_u16_length_prefixed(&contents, &proto_list) ||
1618 !CBB_add_u8_length_prefixed(&proto_list, &proto) ||
1619 !CBB_add_bytes(&proto, ssl->s3->alpn_selected.data(),
1620 ssl->s3->alpn_selected.size()) ||
1621 !CBB_flush(out)) {
1622 return false;
1623 }
1624
1625 return true;
1626 }
1627
1628
1629 // Channel ID.
1630 //
1631 // https://tools.ietf.org/html/draft-balfanz-tls-channelid-01
1632
ext_channel_id_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)1633 static bool ext_channel_id_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1634 CBB *out_compressible,
1635 ssl_client_hello_type_t type) {
1636 const SSL *const ssl = hs->ssl;
1637 if (!hs->config->channel_id_private || SSL_is_dtls(ssl) ||
1638 // Don't offer Channel ID in ClientHelloOuter. ClientHelloOuter handshakes
1639 // are not authenticated for the name that can learn the Channel ID.
1640 //
1641 // We could alternatively offer the extension but sign with a random key.
1642 // For other extensions, we try to align |ssl_client_hello_outer| and
1643 // |ssl_client_hello_unencrypted|, to improve the effectiveness of ECH
1644 // GREASE. However, Channel ID is deprecated and unlikely to be used with
1645 // ECH, so do the simplest thing.
1646 type == ssl_client_hello_outer) {
1647 return true;
1648 }
1649
1650 if (!CBB_add_u16(out, TLSEXT_TYPE_channel_id) ||
1651 !CBB_add_u16(out, 0 /* length */)) {
1652 return false;
1653 }
1654
1655 return true;
1656 }
1657
ext_channel_id_parse_serverhello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)1658 static bool ext_channel_id_parse_serverhello(SSL_HANDSHAKE *hs,
1659 uint8_t *out_alert,
1660 CBS *contents) {
1661 if (contents == NULL) {
1662 return true;
1663 }
1664
1665 assert(!SSL_is_dtls(hs->ssl));
1666 assert(hs->config->channel_id_private);
1667
1668 if (CBS_len(contents) != 0) {
1669 return false;
1670 }
1671
1672 hs->channel_id_negotiated = true;
1673 return true;
1674 }
1675
ext_channel_id_parse_clienthello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)1676 static bool ext_channel_id_parse_clienthello(SSL_HANDSHAKE *hs,
1677 uint8_t *out_alert,
1678 CBS *contents) {
1679 SSL *const ssl = hs->ssl;
1680 if (contents == NULL || !hs->config->channel_id_enabled || SSL_is_dtls(ssl)) {
1681 return true;
1682 }
1683
1684 if (CBS_len(contents) != 0) {
1685 return false;
1686 }
1687
1688 hs->channel_id_negotiated = true;
1689 return true;
1690 }
1691
ext_channel_id_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)1692 static bool ext_channel_id_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1693 if (!hs->channel_id_negotiated) {
1694 return true;
1695 }
1696
1697 if (!CBB_add_u16(out, TLSEXT_TYPE_channel_id) ||
1698 !CBB_add_u16(out, 0 /* length */)) {
1699 return false;
1700 }
1701
1702 return true;
1703 }
1704
1705
1706 // Secure Real-time Transport Protocol (SRTP) extension.
1707 //
1708 // https://tools.ietf.org/html/rfc5764
1709
ext_srtp_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)1710 static bool ext_srtp_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1711 CBB *out_compressible,
1712 ssl_client_hello_type_t type) {
1713 const SSL *const ssl = hs->ssl;
1714 const STACK_OF(SRTP_PROTECTION_PROFILE) *profiles =
1715 SSL_get_srtp_profiles(ssl);
1716 if (profiles == NULL ||
1717 sk_SRTP_PROTECTION_PROFILE_num(profiles) == 0 ||
1718 !SSL_is_dtls(ssl)) {
1719 return true;
1720 }
1721
1722 CBB contents, profile_ids;
1723 if (!CBB_add_u16(out_compressible, TLSEXT_TYPE_srtp) ||
1724 !CBB_add_u16_length_prefixed(out_compressible, &contents) ||
1725 !CBB_add_u16_length_prefixed(&contents, &profile_ids)) {
1726 return false;
1727 }
1728
1729 for (const SRTP_PROTECTION_PROFILE *profile : profiles) {
1730 if (!CBB_add_u16(&profile_ids, profile->id)) {
1731 return false;
1732 }
1733 }
1734
1735 if (!CBB_add_u8(&contents, 0 /* empty use_mki value */) ||
1736 !CBB_flush(out_compressible)) {
1737 return false;
1738 }
1739
1740 return true;
1741 }
1742
ext_srtp_parse_serverhello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)1743 static bool ext_srtp_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1744 CBS *contents) {
1745 SSL *const ssl = hs->ssl;
1746 if (contents == NULL) {
1747 return true;
1748 }
1749
1750 // The extension consists of a u16-prefixed profile ID list containing a
1751 // single uint16_t profile ID, then followed by a u8-prefixed srtp_mki field.
1752 //
1753 // See https://tools.ietf.org/html/rfc5764#section-4.1.1
1754 assert(SSL_is_dtls(ssl));
1755 CBS profile_ids, srtp_mki;
1756 uint16_t profile_id;
1757 if (!CBS_get_u16_length_prefixed(contents, &profile_ids) ||
1758 !CBS_get_u16(&profile_ids, &profile_id) ||
1759 CBS_len(&profile_ids) != 0 ||
1760 !CBS_get_u8_length_prefixed(contents, &srtp_mki) ||
1761 CBS_len(contents) != 0) {
1762 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
1763 return false;
1764 }
1765
1766 if (CBS_len(&srtp_mki) != 0) {
1767 // Must be no MKI, since we never offer one.
1768 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_MKI_VALUE);
1769 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1770 return false;
1771 }
1772
1773 // Check to see if the server gave us something we support and offered.
1774 for (const SRTP_PROTECTION_PROFILE *profile : SSL_get_srtp_profiles(ssl)) {
1775 if (profile->id == profile_id) {
1776 ssl->s3->srtp_profile = profile;
1777 return true;
1778 }
1779 }
1780
1781 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
1782 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1783 return false;
1784 }
1785
ext_srtp_parse_clienthello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)1786 static bool ext_srtp_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1787 CBS *contents) {
1788 SSL *const ssl = hs->ssl;
1789 // DTLS-SRTP is only defined for DTLS.
1790 if (contents == NULL || !SSL_is_dtls(ssl)) {
1791 return true;
1792 }
1793
1794 CBS profile_ids, srtp_mki;
1795 if (!CBS_get_u16_length_prefixed(contents, &profile_ids) ||
1796 CBS_len(&profile_ids) < 2 ||
1797 !CBS_get_u8_length_prefixed(contents, &srtp_mki) ||
1798 CBS_len(contents) != 0) {
1799 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
1800 return false;
1801 }
1802 // Discard the MKI value for now.
1803
1804 const STACK_OF(SRTP_PROTECTION_PROFILE) *server_profiles =
1805 SSL_get_srtp_profiles(ssl);
1806
1807 // Pick the server's most preferred profile.
1808 for (const SRTP_PROTECTION_PROFILE *server_profile : server_profiles) {
1809 CBS profile_ids_tmp;
1810 CBS_init(&profile_ids_tmp, CBS_data(&profile_ids), CBS_len(&profile_ids));
1811
1812 while (CBS_len(&profile_ids_tmp) > 0) {
1813 uint16_t profile_id;
1814 if (!CBS_get_u16(&profile_ids_tmp, &profile_id)) {
1815 return false;
1816 }
1817
1818 if (server_profile->id == profile_id) {
1819 ssl->s3->srtp_profile = server_profile;
1820 return true;
1821 }
1822 }
1823 }
1824
1825 return true;
1826 }
1827
ext_srtp_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)1828 static bool ext_srtp_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1829 SSL *const ssl = hs->ssl;
1830 if (ssl->s3->srtp_profile == NULL) {
1831 return true;
1832 }
1833
1834 assert(SSL_is_dtls(ssl));
1835 CBB contents, profile_ids;
1836 if (!CBB_add_u16(out, TLSEXT_TYPE_srtp) ||
1837 !CBB_add_u16_length_prefixed(out, &contents) ||
1838 !CBB_add_u16_length_prefixed(&contents, &profile_ids) ||
1839 !CBB_add_u16(&profile_ids, ssl->s3->srtp_profile->id) ||
1840 !CBB_add_u8(&contents, 0 /* empty MKI */) ||
1841 !CBB_flush(out)) {
1842 return false;
1843 }
1844
1845 return true;
1846 }
1847
1848
1849 // EC point formats.
1850 //
1851 // https://tools.ietf.org/html/rfc4492#section-5.1.2
1852
ext_ec_point_add_extension(const SSL_HANDSHAKE * hs,CBB * out)1853 static bool ext_ec_point_add_extension(const SSL_HANDSHAKE *hs, CBB *out) {
1854 CBB contents, formats;
1855 if (!CBB_add_u16(out, TLSEXT_TYPE_ec_point_formats) ||
1856 !CBB_add_u16_length_prefixed(out, &contents) ||
1857 !CBB_add_u8_length_prefixed(&contents, &formats) ||
1858 !CBB_add_u8(&formats, TLSEXT_ECPOINTFORMAT_uncompressed) ||
1859 !CBB_flush(out)) {
1860 return false;
1861 }
1862
1863 return true;
1864 }
1865
ext_ec_point_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)1866 static bool ext_ec_point_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1867 CBB *out_compressible,
1868 ssl_client_hello_type_t type) {
1869 // The point format extension is unnecessary in TLS 1.3.
1870 if (hs->min_version >= TLS1_3_VERSION || type == ssl_client_hello_inner) {
1871 return true;
1872 }
1873
1874 return ext_ec_point_add_extension(hs, out);
1875 }
1876
ext_ec_point_parse_serverhello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)1877 static bool ext_ec_point_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1878 CBS *contents) {
1879 if (contents == NULL) {
1880 return true;
1881 }
1882
1883 if (ssl_protocol_version(hs->ssl) >= TLS1_3_VERSION) {
1884 return false;
1885 }
1886
1887 CBS ec_point_format_list;
1888 if (!CBS_get_u8_length_prefixed(contents, &ec_point_format_list) ||
1889 CBS_len(contents) != 0) {
1890 return false;
1891 }
1892
1893 // Per RFC 4492, section 5.1.2, implementations MUST support the uncompressed
1894 // point format.
1895 if (OPENSSL_memchr(CBS_data(&ec_point_format_list),
1896 TLSEXT_ECPOINTFORMAT_uncompressed,
1897 CBS_len(&ec_point_format_list)) == NULL) {
1898 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1899 return false;
1900 }
1901
1902 return true;
1903 }
1904
ext_ec_point_parse_clienthello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)1905 static bool ext_ec_point_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1906 CBS *contents) {
1907 if (ssl_protocol_version(hs->ssl) >= TLS1_3_VERSION) {
1908 return true;
1909 }
1910
1911 return ext_ec_point_parse_serverhello(hs, out_alert, contents);
1912 }
1913
ext_ec_point_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)1914 static bool ext_ec_point_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1915 SSL *const ssl = hs->ssl;
1916 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1917 return true;
1918 }
1919
1920 const uint32_t alg_k = hs->new_cipher->algorithm_mkey;
1921 const uint32_t alg_a = hs->new_cipher->algorithm_auth;
1922 const bool using_ecc = (alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA);
1923
1924 if (!using_ecc) {
1925 return true;
1926 }
1927
1928 return ext_ec_point_add_extension(hs, out);
1929 }
1930
1931
1932 // Pre Shared Key
1933 //
1934 // https://tools.ietf.org/html/rfc8446#section-4.2.11
1935
should_offer_psk(const SSL_HANDSHAKE * hs,ssl_client_hello_type_t type)1936 static bool should_offer_psk(const SSL_HANDSHAKE *hs,
1937 ssl_client_hello_type_t type) {
1938 const SSL *const ssl = hs->ssl;
1939 if (hs->max_version < TLS1_3_VERSION || ssl->session == nullptr ||
1940 ssl_session_protocol_version(ssl->session.get()) < TLS1_3_VERSION ||
1941 // TODO(https://crbug.com/boringssl/275): Should we synthesize a
1942 // placeholder PSK, at least when we offer early data? Otherwise
1943 // ClientHelloOuter will contain an early_data extension without a
1944 // pre_shared_key extension and potentially break the recovery flow.
1945 type == ssl_client_hello_outer) {
1946 return false;
1947 }
1948
1949 // Per RFC 8446 section 4.1.4, skip offering the session if the selected
1950 // cipher in HelloRetryRequest does not match. This avoids performing the
1951 // transcript hash transformation for multiple hashes.
1952 if (ssl->s3->used_hello_retry_request &&
1953 ssl->session->cipher->algorithm_prf != hs->new_cipher->algorithm_prf) {
1954 return false;
1955 }
1956
1957 return true;
1958 }
1959
ext_pre_shared_key_clienthello_length(const SSL_HANDSHAKE * hs,ssl_client_hello_type_t type)1960 static size_t ext_pre_shared_key_clienthello_length(
1961 const SSL_HANDSHAKE *hs, ssl_client_hello_type_t type) {
1962 const SSL *const ssl = hs->ssl;
1963 if (!should_offer_psk(hs, type)) {
1964 return 0;
1965 }
1966
1967 size_t binder_len = EVP_MD_size(ssl_session_get_digest(ssl->session.get()));
1968 return 15 + ssl->session->ticket.size() + binder_len;
1969 }
1970
ext_pre_shared_key_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,bool * out_needs_binder,ssl_client_hello_type_t type)1971 static bool ext_pre_shared_key_add_clienthello(const SSL_HANDSHAKE *hs,
1972 CBB *out, bool *out_needs_binder,
1973 ssl_client_hello_type_t type) {
1974 const SSL *const ssl = hs->ssl;
1975 *out_needs_binder = false;
1976 if (!should_offer_psk(hs, type)) {
1977 return true;
1978 }
1979
1980 struct OPENSSL_timeval now;
1981 ssl_get_current_time(ssl, &now);
1982 uint32_t ticket_age = 1000 * (now.tv_sec - ssl->session->time);
1983 uint32_t obfuscated_ticket_age = ticket_age + ssl->session->ticket_age_add;
1984
1985 // Fill in a placeholder zero binder of the appropriate length. It will be
1986 // computed and filled in later after length prefixes are computed.
1987 size_t binder_len = EVP_MD_size(ssl_session_get_digest(ssl->session.get()));
1988
1989 CBB contents, identity, ticket, binders, binder;
1990 if (!CBB_add_u16(out, TLSEXT_TYPE_pre_shared_key) ||
1991 !CBB_add_u16_length_prefixed(out, &contents) ||
1992 !CBB_add_u16_length_prefixed(&contents, &identity) ||
1993 !CBB_add_u16_length_prefixed(&identity, &ticket) ||
1994 !CBB_add_bytes(&ticket, ssl->session->ticket.data(),
1995 ssl->session->ticket.size()) ||
1996 !CBB_add_u32(&identity, obfuscated_ticket_age) ||
1997 !CBB_add_u16_length_prefixed(&contents, &binders) ||
1998 !CBB_add_u8_length_prefixed(&binders, &binder) ||
1999 !CBB_add_zeros(&binder, binder_len)) {
2000 return false;
2001 }
2002
2003 *out_needs_binder = true;
2004 return CBB_flush(out);
2005 }
2006
ssl_ext_pre_shared_key_parse_serverhello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)2007 bool ssl_ext_pre_shared_key_parse_serverhello(SSL_HANDSHAKE *hs,
2008 uint8_t *out_alert,
2009 CBS *contents) {
2010 uint16_t psk_id;
2011 if (!CBS_get_u16(contents, &psk_id) ||
2012 CBS_len(contents) != 0) {
2013 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2014 *out_alert = SSL_AD_DECODE_ERROR;
2015 return false;
2016 }
2017
2018 // We only advertise one PSK identity, so the only legal index is zero.
2019 if (psk_id != 0) {
2020 OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
2021 *out_alert = SSL_AD_UNKNOWN_PSK_IDENTITY;
2022 return false;
2023 }
2024
2025 return true;
2026 }
2027
ssl_ext_pre_shared_key_parse_clienthello(SSL_HANDSHAKE * hs,CBS * out_ticket,CBS * out_binders,uint32_t * out_obfuscated_ticket_age,uint8_t * out_alert,const SSL_CLIENT_HELLO * client_hello,CBS * contents)2028 bool ssl_ext_pre_shared_key_parse_clienthello(
2029 SSL_HANDSHAKE *hs, CBS *out_ticket, CBS *out_binders,
2030 uint32_t *out_obfuscated_ticket_age, uint8_t *out_alert,
2031 const SSL_CLIENT_HELLO *client_hello, CBS *contents) {
2032 // Verify that the pre_shared_key extension is the last extension in
2033 // ClientHello.
2034 if (CBS_data(contents) + CBS_len(contents) !=
2035 client_hello->extensions + client_hello->extensions_len) {
2036 OPENSSL_PUT_ERROR(SSL, SSL_R_PRE_SHARED_KEY_MUST_BE_LAST);
2037 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
2038 return false;
2039 }
2040
2041 // We only process the first PSK identity since we don't support pure PSK.
2042 CBS identities, binders;
2043 if (!CBS_get_u16_length_prefixed(contents, &identities) ||
2044 !CBS_get_u16_length_prefixed(&identities, out_ticket) ||
2045 !CBS_get_u32(&identities, out_obfuscated_ticket_age) ||
2046 !CBS_get_u16_length_prefixed(contents, &binders) ||
2047 CBS_len(&binders) == 0 ||
2048 CBS_len(contents) != 0) {
2049 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2050 *out_alert = SSL_AD_DECODE_ERROR;
2051 return false;
2052 }
2053
2054 *out_binders = binders;
2055
2056 // Check the syntax of the remaining identities, but do not process them.
2057 size_t num_identities = 1;
2058 while (CBS_len(&identities) != 0) {
2059 CBS unused_ticket;
2060 uint32_t unused_obfuscated_ticket_age;
2061 if (!CBS_get_u16_length_prefixed(&identities, &unused_ticket) ||
2062 !CBS_get_u32(&identities, &unused_obfuscated_ticket_age)) {
2063 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2064 *out_alert = SSL_AD_DECODE_ERROR;
2065 return false;
2066 }
2067
2068 num_identities++;
2069 }
2070
2071 // Check the syntax of the binders. The value will be checked later if
2072 // resuming.
2073 size_t num_binders = 0;
2074 while (CBS_len(&binders) != 0) {
2075 CBS binder;
2076 if (!CBS_get_u8_length_prefixed(&binders, &binder)) {
2077 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2078 *out_alert = SSL_AD_DECODE_ERROR;
2079 return false;
2080 }
2081
2082 num_binders++;
2083 }
2084
2085 if (num_identities != num_binders) {
2086 OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_BINDER_COUNT_MISMATCH);
2087 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
2088 return false;
2089 }
2090
2091 return true;
2092 }
2093
ssl_ext_pre_shared_key_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)2094 bool ssl_ext_pre_shared_key_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
2095 if (!hs->ssl->s3->session_reused) {
2096 return true;
2097 }
2098
2099 CBB contents;
2100 if (!CBB_add_u16(out, TLSEXT_TYPE_pre_shared_key) ||
2101 !CBB_add_u16_length_prefixed(out, &contents) ||
2102 // We only consider the first identity for resumption
2103 !CBB_add_u16(&contents, 0) ||
2104 !CBB_flush(out)) {
2105 return false;
2106 }
2107
2108 return true;
2109 }
2110
2111
2112 // Pre-Shared Key Exchange Modes
2113 //
2114 // https://tools.ietf.org/html/rfc8446#section-4.2.9
2115
ext_psk_key_exchange_modes_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)2116 static bool ext_psk_key_exchange_modes_add_clienthello(
2117 const SSL_HANDSHAKE *hs, CBB *out, CBB *out_compressible,
2118 ssl_client_hello_type_t type) {
2119 if (hs->max_version < TLS1_3_VERSION) {
2120 return true;
2121 }
2122
2123 CBB contents, ke_modes;
2124 if (!CBB_add_u16(out_compressible, TLSEXT_TYPE_psk_key_exchange_modes) ||
2125 !CBB_add_u16_length_prefixed(out_compressible, &contents) ||
2126 !CBB_add_u8_length_prefixed(&contents, &ke_modes) ||
2127 !CBB_add_u8(&ke_modes, SSL_PSK_DHE_KE)) {
2128 return false;
2129 }
2130
2131 return CBB_flush(out_compressible);
2132 }
2133
ext_psk_key_exchange_modes_parse_clienthello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)2134 static bool ext_psk_key_exchange_modes_parse_clienthello(SSL_HANDSHAKE *hs,
2135 uint8_t *out_alert,
2136 CBS *contents) {
2137 if (contents == NULL) {
2138 return true;
2139 }
2140
2141 CBS ke_modes;
2142 if (!CBS_get_u8_length_prefixed(contents, &ke_modes) ||
2143 CBS_len(&ke_modes) == 0 ||
2144 CBS_len(contents) != 0) {
2145 *out_alert = SSL_AD_DECODE_ERROR;
2146 return false;
2147 }
2148
2149 // We only support tickets with PSK_DHE_KE.
2150 hs->accept_psk_mode = OPENSSL_memchr(CBS_data(&ke_modes), SSL_PSK_DHE_KE,
2151 CBS_len(&ke_modes)) != NULL;
2152
2153 return true;
2154 }
2155
2156
2157 // Early Data Indication
2158 //
2159 // https://tools.ietf.org/html/rfc8446#section-4.2.10
2160
ext_early_data_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)2161 static bool ext_early_data_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
2162 CBB *out_compressible,
2163 ssl_client_hello_type_t type) {
2164 const SSL *const ssl = hs->ssl;
2165 // The second ClientHello never offers early data, and we must have already
2166 // filled in |early_data_reason| by this point.
2167 if (ssl->s3->used_hello_retry_request) {
2168 assert(ssl->s3->early_data_reason != ssl_early_data_unknown);
2169 return true;
2170 }
2171
2172 if (!hs->early_data_offered) {
2173 return true;
2174 }
2175
2176 // If offering ECH, the extension only applies to ClientHelloInner, but we
2177 // send the extension in both ClientHellos. This ensures that, if the server
2178 // handshakes with ClientHelloOuter, it can skip past early data. See
2179 // https://github.com/tlswg/draft-ietf-tls-esni/pull/415
2180 //
2181 // TODO(https://crbug.com/boringssl/275): Replace this with a reference to the
2182 // right section in the next draft.
2183 if (!CBB_add_u16(out_compressible, TLSEXT_TYPE_early_data) ||
2184 !CBB_add_u16(out_compressible, 0) ||
2185 !CBB_flush(out_compressible)) {
2186 return false;
2187 }
2188
2189 return true;
2190 }
2191
ext_early_data_parse_serverhello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)2192 static bool ext_early_data_parse_serverhello(SSL_HANDSHAKE *hs,
2193 uint8_t *out_alert,
2194 CBS *contents) {
2195 SSL *const ssl = hs->ssl;
2196 if (contents == NULL) {
2197 if (hs->early_data_offered && !ssl->s3->used_hello_retry_request) {
2198 ssl->s3->early_data_reason = ssl->s3->session_reused
2199 ? ssl_early_data_peer_declined
2200 : ssl_early_data_session_not_resumed;
2201 } else {
2202 // We already filled in |early_data_reason| when declining to offer 0-RTT
2203 // or handling the implicit HelloRetryRequest reject.
2204 assert(ssl->s3->early_data_reason != ssl_early_data_unknown);
2205 }
2206 return true;
2207 }
2208
2209 // If we received an HRR, the second ClientHello never offers early data, so
2210 // the extensions logic will automatically reject early data extensions as
2211 // unsolicited. This covered by the ServerAcceptsEarlyDataOnHRR test.
2212 assert(!ssl->s3->used_hello_retry_request);
2213
2214 if (CBS_len(contents) != 0) {
2215 *out_alert = SSL_AD_DECODE_ERROR;
2216 return false;
2217 }
2218
2219 if (!ssl->s3->session_reused) {
2220 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
2221 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
2222 return false;
2223 }
2224
2225 ssl->s3->early_data_reason = ssl_early_data_accepted;
2226 ssl->s3->early_data_accepted = true;
2227 return true;
2228 }
2229
ext_early_data_parse_clienthello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)2230 static bool ext_early_data_parse_clienthello(SSL_HANDSHAKE *hs,
2231 uint8_t *out_alert, CBS *contents) {
2232 SSL *const ssl = hs->ssl;
2233 if (contents == NULL ||
2234 ssl_protocol_version(ssl) < TLS1_3_VERSION) {
2235 return true;
2236 }
2237
2238 if (CBS_len(contents) != 0) {
2239 *out_alert = SSL_AD_DECODE_ERROR;
2240 return false;
2241 }
2242
2243 hs->early_data_offered = true;
2244 return true;
2245 }
2246
ext_early_data_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)2247 static bool ext_early_data_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
2248 if (!hs->ssl->s3->early_data_accepted) {
2249 return true;
2250 }
2251
2252 if (!CBB_add_u16(out, TLSEXT_TYPE_early_data) ||
2253 !CBB_add_u16(out, 0) ||
2254 !CBB_flush(out)) {
2255 return false;
2256 }
2257
2258 return true;
2259 }
2260
2261
2262 // Key Share
2263 //
2264 // https://tools.ietf.org/html/rfc8446#section-4.2.8
2265
ssl_setup_key_shares(SSL_HANDSHAKE * hs,uint16_t override_group_id)2266 bool ssl_setup_key_shares(SSL_HANDSHAKE *hs, uint16_t override_group_id) {
2267 SSL *const ssl = hs->ssl;
2268 hs->key_shares[0].reset();
2269 hs->key_shares[1].reset();
2270 hs->key_share_bytes.Reset();
2271
2272 if (hs->max_version < TLS1_3_VERSION) {
2273 return true;
2274 }
2275
2276 bssl::ScopedCBB cbb;
2277 if (!CBB_init(cbb.get(), 64)) {
2278 return false;
2279 }
2280
2281 if (override_group_id == 0 && ssl->ctx->grease_enabled) {
2282 // Add a fake group. See RFC 8701.
2283 if (!CBB_add_u16(cbb.get(), ssl_get_grease_value(hs, ssl_grease_group)) ||
2284 !CBB_add_u16(cbb.get(), 1 /* length */) ||
2285 !CBB_add_u8(cbb.get(), 0 /* one byte key share */)) {
2286 return false;
2287 }
2288 }
2289
2290 uint16_t group_id = override_group_id;
2291 uint16_t second_group_id = 0;
2292 if (override_group_id == 0) {
2293 // Predict the most preferred group.
2294 Span<const uint16_t> groups = tls1_get_grouplist(hs);
2295 if (groups.empty()) {
2296 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_GROUPS_SPECIFIED);
2297 return false;
2298 }
2299
2300 group_id = groups[0];
2301
2302 if (is_post_quantum_group(group_id) && groups.size() >= 2) {
2303 // CECPQ2(b) is not sent as the only initial key share. We'll include the
2304 // 2nd preference group too to avoid round-trips.
2305 second_group_id = groups[1];
2306 assert(second_group_id != group_id);
2307 }
2308 }
2309
2310 CBB key_exchange;
2311 hs->key_shares[0] = SSLKeyShare::Create(group_id);
2312 if (!hs->key_shares[0] || //
2313 !CBB_add_u16(cbb.get(), group_id) ||
2314 !CBB_add_u16_length_prefixed(cbb.get(), &key_exchange) ||
2315 !hs->key_shares[0]->Offer(&key_exchange)) {
2316 return false;
2317 }
2318
2319 if (second_group_id != 0) {
2320 hs->key_shares[1] = SSLKeyShare::Create(second_group_id);
2321 if (!hs->key_shares[1] || //
2322 !CBB_add_u16(cbb.get(), second_group_id) ||
2323 !CBB_add_u16_length_prefixed(cbb.get(), &key_exchange) ||
2324 !hs->key_shares[1]->Offer(&key_exchange)) {
2325 return false;
2326 }
2327 }
2328
2329 return CBBFinishArray(cbb.get(), &hs->key_share_bytes);
2330 }
2331
ext_key_share_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)2332 static bool ext_key_share_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
2333 CBB *out_compressible,
2334 ssl_client_hello_type_t type) {
2335 if (hs->max_version < TLS1_3_VERSION) {
2336 return true;
2337 }
2338
2339 assert(!hs->key_share_bytes.empty());
2340 CBB contents, kse_bytes;
2341 if (!CBB_add_u16(out_compressible, TLSEXT_TYPE_key_share) ||
2342 !CBB_add_u16_length_prefixed(out_compressible, &contents) ||
2343 !CBB_add_u16_length_prefixed(&contents, &kse_bytes) ||
2344 !CBB_add_bytes(&kse_bytes, hs->key_share_bytes.data(),
2345 hs->key_share_bytes.size()) ||
2346 !CBB_flush(out_compressible)) {
2347 return false;
2348 }
2349
2350 return true;
2351 }
2352
ssl_ext_key_share_parse_serverhello(SSL_HANDSHAKE * hs,Array<uint8_t> * out_secret,uint8_t * out_alert,CBS * contents)2353 bool ssl_ext_key_share_parse_serverhello(SSL_HANDSHAKE *hs,
2354 Array<uint8_t> *out_secret,
2355 uint8_t *out_alert, CBS *contents) {
2356 CBS peer_key;
2357 uint16_t group_id;
2358 if (!CBS_get_u16(contents, &group_id) ||
2359 !CBS_get_u16_length_prefixed(contents, &peer_key) ||
2360 CBS_len(contents) != 0) {
2361 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2362 *out_alert = SSL_AD_DECODE_ERROR;
2363 return false;
2364 }
2365
2366 SSLKeyShare *key_share = hs->key_shares[0].get();
2367 if (key_share->GroupID() != group_id) {
2368 if (!hs->key_shares[1] || hs->key_shares[1]->GroupID() != group_id) {
2369 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
2370 OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
2371 return false;
2372 }
2373 key_share = hs->key_shares[1].get();
2374 }
2375
2376 if (!key_share->Finish(out_secret, out_alert, peer_key)) {
2377 *out_alert = SSL_AD_INTERNAL_ERROR;
2378 return false;
2379 }
2380
2381 hs->new_session->group_id = group_id;
2382 hs->key_shares[0].reset();
2383 hs->key_shares[1].reset();
2384 return true;
2385 }
2386
ssl_ext_key_share_parse_clienthello(SSL_HANDSHAKE * hs,bool * out_found,Span<const uint8_t> * out_peer_key,uint8_t * out_alert,const SSL_CLIENT_HELLO * client_hello)2387 bool ssl_ext_key_share_parse_clienthello(SSL_HANDSHAKE *hs, bool *out_found,
2388 Span<const uint8_t> *out_peer_key,
2389 uint8_t *out_alert,
2390 const SSL_CLIENT_HELLO *client_hello) {
2391 // We only support connections that include an ECDHE key exchange.
2392 CBS contents;
2393 if (!ssl_client_hello_get_extension(client_hello, &contents,
2394 TLSEXT_TYPE_key_share)) {
2395 OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_KEY_SHARE);
2396 *out_alert = SSL_AD_MISSING_EXTENSION;
2397 return false;
2398 }
2399
2400 CBS key_shares;
2401 if (!CBS_get_u16_length_prefixed(&contents, &key_shares) ||
2402 CBS_len(&contents) != 0) {
2403 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2404 return false;
2405 }
2406
2407 // Find the corresponding key share.
2408 const uint16_t group_id = hs->new_session->group_id;
2409 CBS peer_key;
2410 CBS_init(&peer_key, nullptr, 0);
2411 while (CBS_len(&key_shares) > 0) {
2412 uint16_t id;
2413 CBS peer_key_tmp;
2414 if (!CBS_get_u16(&key_shares, &id) ||
2415 !CBS_get_u16_length_prefixed(&key_shares, &peer_key_tmp) ||
2416 CBS_len(&peer_key_tmp) == 0) {
2417 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2418 return false;
2419 }
2420
2421 if (id == group_id) {
2422 if (CBS_len(&peer_key) != 0) {
2423 OPENSSL_PUT_ERROR(SSL, SSL_R_DUPLICATE_KEY_SHARE);
2424 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
2425 return false;
2426 }
2427
2428 peer_key = peer_key_tmp;
2429 // Continue parsing the structure to keep peers honest.
2430 }
2431 }
2432
2433 if (out_peer_key != nullptr) {
2434 *out_peer_key = peer_key;
2435 }
2436 *out_found = CBS_len(&peer_key) != 0;
2437 return true;
2438 }
2439
ssl_ext_key_share_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)2440 bool ssl_ext_key_share_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
2441 CBB kse_bytes, public_key;
2442 if (!CBB_add_u16(out, TLSEXT_TYPE_key_share) ||
2443 !CBB_add_u16_length_prefixed(out, &kse_bytes) ||
2444 !CBB_add_u16(&kse_bytes, hs->new_session->group_id) ||
2445 !CBB_add_u16_length_prefixed(&kse_bytes, &public_key) ||
2446 !CBB_add_bytes(&public_key, hs->ecdh_public_key.data(),
2447 hs->ecdh_public_key.size()) ||
2448 !CBB_flush(out)) {
2449 return false;
2450 }
2451 return true;
2452 }
2453
2454
2455 // Supported Versions
2456 //
2457 // https://tools.ietf.org/html/rfc8446#section-4.2.1
2458
ext_supported_versions_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)2459 static bool ext_supported_versions_add_clienthello(
2460 const SSL_HANDSHAKE *hs, CBB *out, CBB *out_compressible,
2461 ssl_client_hello_type_t type) {
2462 const SSL *const ssl = hs->ssl;
2463 if (hs->max_version <= TLS1_2_VERSION) {
2464 return true;
2465 }
2466
2467 // supported_versions is compressible in ECH if ClientHelloOuter already
2468 // requires TLS 1.3. Otherwise the extensions differ in the older versions.
2469 if (hs->min_version >= TLS1_3_VERSION) {
2470 out = out_compressible;
2471 }
2472
2473 CBB contents, versions;
2474 if (!CBB_add_u16(out, TLSEXT_TYPE_supported_versions) ||
2475 !CBB_add_u16_length_prefixed(out, &contents) ||
2476 !CBB_add_u8_length_prefixed(&contents, &versions)) {
2477 return false;
2478 }
2479
2480 // Add a fake version. See RFC 8701.
2481 if (ssl->ctx->grease_enabled &&
2482 !CBB_add_u16(&versions, ssl_get_grease_value(hs, ssl_grease_version))) {
2483 return false;
2484 }
2485
2486 // Encrypted ClientHellos requires TLS 1.3 or later.
2487 uint16_t extra_min_version =
2488 type == ssl_client_hello_inner ? TLS1_3_VERSION : 0;
2489 if (!ssl_add_supported_versions(hs, &versions, extra_min_version) ||
2490 !CBB_flush(out)) {
2491 return false;
2492 }
2493
2494 return true;
2495 }
2496
2497
2498 // Cookie
2499 //
2500 // https://tools.ietf.org/html/rfc8446#section-4.2.2
2501
ext_cookie_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)2502 static bool ext_cookie_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
2503 CBB *out_compressible,
2504 ssl_client_hello_type_t type) {
2505 if (hs->cookie.empty()) {
2506 return true;
2507 }
2508
2509 CBB contents, cookie;
2510 if (!CBB_add_u16(out_compressible, TLSEXT_TYPE_cookie) ||
2511 !CBB_add_u16_length_prefixed(out_compressible, &contents) ||
2512 !CBB_add_u16_length_prefixed(&contents, &cookie) ||
2513 !CBB_add_bytes(&cookie, hs->cookie.data(), hs->cookie.size()) ||
2514 !CBB_flush(out_compressible)) {
2515 return false;
2516 }
2517
2518 return true;
2519 }
2520
2521
2522 // Supported Groups
2523 //
2524 // https://tools.ietf.org/html/rfc4492#section-5.1.1
2525 // https://tools.ietf.org/html/rfc8446#section-4.2.7
2526
ext_supported_groups_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)2527 static bool ext_supported_groups_add_clienthello(const SSL_HANDSHAKE *hs,
2528 CBB *out,
2529 CBB *out_compressible,
2530 ssl_client_hello_type_t type) {
2531 const SSL *const ssl = hs->ssl;
2532 CBB contents, groups_bytes;
2533 if (!CBB_add_u16(out_compressible, TLSEXT_TYPE_supported_groups) ||
2534 !CBB_add_u16_length_prefixed(out_compressible, &contents) ||
2535 !CBB_add_u16_length_prefixed(&contents, &groups_bytes)) {
2536 return false;
2537 }
2538
2539 // Add a fake group. See RFC 8701.
2540 if (ssl->ctx->grease_enabled &&
2541 !CBB_add_u16(&groups_bytes,
2542 ssl_get_grease_value(hs, ssl_grease_group))) {
2543 return false;
2544 }
2545
2546 for (uint16_t group : tls1_get_grouplist(hs)) {
2547 if (is_post_quantum_group(group) &&
2548 hs->max_version < TLS1_3_VERSION) {
2549 continue;
2550 }
2551 if (!CBB_add_u16(&groups_bytes, group)) {
2552 return false;
2553 }
2554 }
2555
2556 return CBB_flush(out_compressible);
2557 }
2558
ext_supported_groups_parse_serverhello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)2559 static bool ext_supported_groups_parse_serverhello(SSL_HANDSHAKE *hs,
2560 uint8_t *out_alert,
2561 CBS *contents) {
2562 // This extension is not expected to be echoed by servers in TLS 1.2, but some
2563 // BigIP servers send it nonetheless, so do not enforce this.
2564 return true;
2565 }
2566
parse_u16_array(const CBS * cbs,Array<uint16_t> * out)2567 static bool parse_u16_array(const CBS *cbs, Array<uint16_t> *out) {
2568 CBS copy = *cbs;
2569 if ((CBS_len(©) & 1) != 0) {
2570 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2571 return false;
2572 }
2573
2574 Array<uint16_t> ret;
2575 if (!ret.Init(CBS_len(©) / 2)) {
2576 return false;
2577 }
2578 for (size_t i = 0; i < ret.size(); i++) {
2579 if (!CBS_get_u16(©, &ret[i])) {
2580 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
2581 return false;
2582 }
2583 }
2584
2585 assert(CBS_len(©) == 0);
2586 *out = std::move(ret);
2587 return 1;
2588 }
2589
ext_supported_groups_parse_clienthello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)2590 static bool ext_supported_groups_parse_clienthello(SSL_HANDSHAKE *hs,
2591 uint8_t *out_alert,
2592 CBS *contents) {
2593 if (contents == NULL) {
2594 return true;
2595 }
2596
2597 CBS supported_group_list;
2598 if (!CBS_get_u16_length_prefixed(contents, &supported_group_list) ||
2599 CBS_len(&supported_group_list) == 0 ||
2600 CBS_len(contents) != 0 ||
2601 !parse_u16_array(&supported_group_list, &hs->peer_supported_group_list)) {
2602 return false;
2603 }
2604
2605 return true;
2606 }
2607
2608
2609 // QUIC Transport Parameters
2610
ext_quic_transport_params_add_clienthello_impl(const SSL_HANDSHAKE * hs,CBB * out,bool use_legacy_codepoint)2611 static bool ext_quic_transport_params_add_clienthello_impl(
2612 const SSL_HANDSHAKE *hs, CBB *out, bool use_legacy_codepoint) {
2613 if (hs->config->quic_transport_params.empty() && !hs->ssl->quic_method) {
2614 return true;
2615 }
2616 if (hs->config->quic_transport_params.empty() || !hs->ssl->quic_method) {
2617 // QUIC Transport Parameters must be sent over QUIC, and they must not be
2618 // sent over non-QUIC transports. If transport params are set, then
2619 // SSL(_CTX)_set_quic_method must also be called.
2620 OPENSSL_PUT_ERROR(SSL, SSL_R_QUIC_TRANSPORT_PARAMETERS_MISCONFIGURED);
2621 return false;
2622 }
2623 assert(hs->min_version > TLS1_2_VERSION);
2624 if (use_legacy_codepoint != hs->config->quic_use_legacy_codepoint) {
2625 // Do nothing, we'll send the other codepoint.
2626 return true;
2627 }
2628
2629 uint16_t extension_type = TLSEXT_TYPE_quic_transport_parameters;
2630 if (hs->config->quic_use_legacy_codepoint) {
2631 extension_type = TLSEXT_TYPE_quic_transport_parameters_legacy;
2632 }
2633
2634 CBB contents;
2635 if (!CBB_add_u16(out, extension_type) ||
2636 !CBB_add_u16_length_prefixed(out, &contents) ||
2637 !CBB_add_bytes(&contents, hs->config->quic_transport_params.data(),
2638 hs->config->quic_transport_params.size()) ||
2639 !CBB_flush(out)) {
2640 return false;
2641 }
2642 return true;
2643 }
2644
ext_quic_transport_params_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)2645 static bool ext_quic_transport_params_add_clienthello(
2646 const SSL_HANDSHAKE *hs, CBB *out, CBB *out_compressible,
2647 ssl_client_hello_type_t type) {
2648 return ext_quic_transport_params_add_clienthello_impl(
2649 hs, out_compressible, /*use_legacy_codepoint=*/false);
2650 }
2651
ext_quic_transport_params_add_clienthello_legacy(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)2652 static bool ext_quic_transport_params_add_clienthello_legacy(
2653 const SSL_HANDSHAKE *hs, CBB *out, CBB *out_compressible,
2654 ssl_client_hello_type_t type) {
2655 return ext_quic_transport_params_add_clienthello_impl(
2656 hs, out_compressible, /*use_legacy_codepoint=*/true);
2657 }
2658
ext_quic_transport_params_parse_serverhello_impl(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents,bool used_legacy_codepoint)2659 static bool ext_quic_transport_params_parse_serverhello_impl(
2660 SSL_HANDSHAKE *hs, uint8_t *out_alert, CBS *contents,
2661 bool used_legacy_codepoint) {
2662 SSL *const ssl = hs->ssl;
2663 if (contents == nullptr) {
2664 if (used_legacy_codepoint != hs->config->quic_use_legacy_codepoint) {
2665 // Silently ignore because we expect the other QUIC codepoint.
2666 return true;
2667 }
2668 if (!ssl->quic_method) {
2669 return true;
2670 }
2671 *out_alert = SSL_AD_MISSING_EXTENSION;
2672 return false;
2673 }
2674 // The extensions parser will check for unsolicited extensions before
2675 // calling the callback.
2676 assert(ssl->quic_method != nullptr);
2677 assert(ssl_protocol_version(ssl) == TLS1_3_VERSION);
2678 assert(used_legacy_codepoint == hs->config->quic_use_legacy_codepoint);
2679 return ssl->s3->peer_quic_transport_params.CopyFrom(*contents);
2680 }
2681
ext_quic_transport_params_parse_serverhello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)2682 static bool ext_quic_transport_params_parse_serverhello(SSL_HANDSHAKE *hs,
2683 uint8_t *out_alert,
2684 CBS *contents) {
2685 return ext_quic_transport_params_parse_serverhello_impl(
2686 hs, out_alert, contents, /*used_legacy_codepoint=*/false);
2687 }
2688
ext_quic_transport_params_parse_serverhello_legacy(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)2689 static bool ext_quic_transport_params_parse_serverhello_legacy(
2690 SSL_HANDSHAKE *hs, uint8_t *out_alert, CBS *contents) {
2691 return ext_quic_transport_params_parse_serverhello_impl(
2692 hs, out_alert, contents, /*used_legacy_codepoint=*/true);
2693 }
2694
ext_quic_transport_params_parse_clienthello_impl(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents,bool used_legacy_codepoint)2695 static bool ext_quic_transport_params_parse_clienthello_impl(
2696 SSL_HANDSHAKE *hs, uint8_t *out_alert, CBS *contents,
2697 bool used_legacy_codepoint) {
2698 SSL *const ssl = hs->ssl;
2699 if (!contents) {
2700 if (!ssl->quic_method) {
2701 if (hs->config->quic_transport_params.empty()) {
2702 return true;
2703 }
2704 // QUIC transport parameters must not be set if |ssl| is not configured
2705 // for QUIC.
2706 OPENSSL_PUT_ERROR(SSL, SSL_R_QUIC_TRANSPORT_PARAMETERS_MISCONFIGURED);
2707 *out_alert = SSL_AD_INTERNAL_ERROR;
2708 return false;
2709 }
2710 if (used_legacy_codepoint != hs->config->quic_use_legacy_codepoint) {
2711 // Silently ignore because we expect the other QUIC codepoint.
2712 return true;
2713 }
2714 *out_alert = SSL_AD_MISSING_EXTENSION;
2715 return false;
2716 }
2717 if (!ssl->quic_method) {
2718 if (used_legacy_codepoint) {
2719 // Ignore the legacy private-use codepoint because that could be sent
2720 // to mean something else than QUIC transport parameters.
2721 return true;
2722 }
2723 // Fail if we received the codepoint registered with IANA for QUIC
2724 // because that is not allowed outside of QUIC.
2725 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
2726 return false;
2727 }
2728 assert(ssl_protocol_version(ssl) == TLS1_3_VERSION);
2729 if (used_legacy_codepoint != hs->config->quic_use_legacy_codepoint) {
2730 // Silently ignore because we expect the other QUIC codepoint.
2731 return true;
2732 }
2733 return ssl->s3->peer_quic_transport_params.CopyFrom(*contents);
2734 }
2735
ext_quic_transport_params_parse_clienthello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)2736 static bool ext_quic_transport_params_parse_clienthello(SSL_HANDSHAKE *hs,
2737 uint8_t *out_alert,
2738 CBS *contents) {
2739 return ext_quic_transport_params_parse_clienthello_impl(
2740 hs, out_alert, contents, /*used_legacy_codepoint=*/false);
2741 }
2742
ext_quic_transport_params_parse_clienthello_legacy(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)2743 static bool ext_quic_transport_params_parse_clienthello_legacy(
2744 SSL_HANDSHAKE *hs, uint8_t *out_alert, CBS *contents) {
2745 return ext_quic_transport_params_parse_clienthello_impl(
2746 hs, out_alert, contents, /*used_legacy_codepoint=*/true);
2747 }
2748
ext_quic_transport_params_add_serverhello_impl(SSL_HANDSHAKE * hs,CBB * out,bool use_legacy_codepoint)2749 static bool ext_quic_transport_params_add_serverhello_impl(
2750 SSL_HANDSHAKE *hs, CBB *out, bool use_legacy_codepoint) {
2751 if (hs->ssl->quic_method == nullptr && use_legacy_codepoint) {
2752 // Ignore the legacy private-use codepoint because that could be sent
2753 // to mean something else than QUIC transport parameters.
2754 return true;
2755 }
2756 assert(hs->ssl->quic_method != nullptr);
2757 if (hs->config->quic_transport_params.empty()) {
2758 // Transport parameters must be set when using QUIC.
2759 OPENSSL_PUT_ERROR(SSL, SSL_R_QUIC_TRANSPORT_PARAMETERS_MISCONFIGURED);
2760 return false;
2761 }
2762 if (use_legacy_codepoint != hs->config->quic_use_legacy_codepoint) {
2763 // Do nothing, we'll send the other codepoint.
2764 return true;
2765 }
2766
2767 uint16_t extension_type = TLSEXT_TYPE_quic_transport_parameters;
2768 if (hs->config->quic_use_legacy_codepoint) {
2769 extension_type = TLSEXT_TYPE_quic_transport_parameters_legacy;
2770 }
2771
2772 CBB contents;
2773 if (!CBB_add_u16(out, extension_type) ||
2774 !CBB_add_u16_length_prefixed(out, &contents) ||
2775 !CBB_add_bytes(&contents, hs->config->quic_transport_params.data(),
2776 hs->config->quic_transport_params.size()) ||
2777 !CBB_flush(out)) {
2778 return false;
2779 }
2780
2781 return true;
2782 }
2783
ext_quic_transport_params_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)2784 static bool ext_quic_transport_params_add_serverhello(SSL_HANDSHAKE *hs,
2785 CBB *out) {
2786 return ext_quic_transport_params_add_serverhello_impl(
2787 hs, out, /*use_legacy_codepoint=*/false);
2788 }
2789
ext_quic_transport_params_add_serverhello_legacy(SSL_HANDSHAKE * hs,CBB * out)2790 static bool ext_quic_transport_params_add_serverhello_legacy(SSL_HANDSHAKE *hs,
2791 CBB *out) {
2792 return ext_quic_transport_params_add_serverhello_impl(
2793 hs, out, /*use_legacy_codepoint=*/true);
2794 }
2795
2796 // Delegated credentials.
2797 //
2798 // https://tools.ietf.org/html/draft-ietf-tls-subcerts
2799
ext_delegated_credential_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)2800 static bool ext_delegated_credential_add_clienthello(
2801 const SSL_HANDSHAKE *hs, CBB *out, CBB *out_compressible,
2802 ssl_client_hello_type_t type) {
2803 return true;
2804 }
2805
ext_delegated_credential_parse_clienthello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)2806 static bool ext_delegated_credential_parse_clienthello(SSL_HANDSHAKE *hs,
2807 uint8_t *out_alert,
2808 CBS *contents) {
2809 if (contents == nullptr || ssl_protocol_version(hs->ssl) < TLS1_3_VERSION) {
2810 // Don't use delegated credentials unless we're negotiating TLS 1.3 or
2811 // higher.
2812 return true;
2813 }
2814
2815 // The contents of the extension are the signature algorithms the client will
2816 // accept for a delegated credential.
2817 CBS sigalg_list;
2818 if (!CBS_get_u16_length_prefixed(contents, &sigalg_list) ||
2819 CBS_len(&sigalg_list) == 0 ||
2820 CBS_len(contents) != 0 ||
2821 !parse_u16_array(&sigalg_list, &hs->peer_delegated_credential_sigalgs)) {
2822 return false;
2823 }
2824
2825 hs->delegated_credential_requested = true;
2826 return true;
2827 }
2828
2829 // Certificate compression
2830
cert_compression_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)2831 static bool cert_compression_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
2832 CBB *out_compressible,
2833 ssl_client_hello_type_t type) {
2834 bool first = true;
2835 CBB contents, algs;
2836
2837 for (const auto &alg : hs->ssl->ctx->cert_compression_algs) {
2838 if (alg.decompress == nullptr) {
2839 continue;
2840 }
2841
2842 if (first &&
2843 (!CBB_add_u16(out_compressible, TLSEXT_TYPE_cert_compression) ||
2844 !CBB_add_u16_length_prefixed(out_compressible, &contents) ||
2845 !CBB_add_u8_length_prefixed(&contents, &algs))) {
2846 return false;
2847 }
2848 first = false;
2849 if (!CBB_add_u16(&algs, alg.alg_id)) {
2850 return false;
2851 }
2852 }
2853
2854 return first || CBB_flush(out_compressible);
2855 }
2856
cert_compression_parse_serverhello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)2857 static bool cert_compression_parse_serverhello(SSL_HANDSHAKE *hs,
2858 uint8_t *out_alert,
2859 CBS *contents) {
2860 if (contents == nullptr) {
2861 return true;
2862 }
2863
2864 // The server may not echo this extension. Any server to client negotiation is
2865 // advertised in the CertificateRequest message.
2866 return false;
2867 }
2868
cert_compression_parse_clienthello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)2869 static bool cert_compression_parse_clienthello(SSL_HANDSHAKE *hs,
2870 uint8_t *out_alert,
2871 CBS *contents) {
2872 if (contents == nullptr) {
2873 return true;
2874 }
2875
2876 const SSL_CTX *ctx = hs->ssl->ctx.get();
2877 const size_t num_algs = ctx->cert_compression_algs.size();
2878
2879 CBS alg_ids;
2880 if (!CBS_get_u8_length_prefixed(contents, &alg_ids) ||
2881 CBS_len(contents) != 0 ||
2882 CBS_len(&alg_ids) == 0 ||
2883 CBS_len(&alg_ids) % 2 == 1) {
2884 return false;
2885 }
2886
2887 const size_t num_given_alg_ids = CBS_len(&alg_ids) / 2;
2888 Array<uint16_t> given_alg_ids;
2889 if (!given_alg_ids.Init(num_given_alg_ids)) {
2890 return false;
2891 }
2892
2893 size_t best_index = num_algs;
2894 size_t given_alg_idx = 0;
2895
2896 while (CBS_len(&alg_ids) > 0) {
2897 uint16_t alg_id;
2898 if (!CBS_get_u16(&alg_ids, &alg_id)) {
2899 return false;
2900 }
2901
2902 given_alg_ids[given_alg_idx++] = alg_id;
2903
2904 for (size_t i = 0; i < num_algs; i++) {
2905 const auto &alg = ctx->cert_compression_algs[i];
2906 if (alg.alg_id == alg_id && alg.compress != nullptr) {
2907 if (i < best_index) {
2908 best_index = i;
2909 }
2910 break;
2911 }
2912 }
2913 }
2914
2915 qsort(given_alg_ids.data(), given_alg_ids.size(), sizeof(uint16_t),
2916 compare_uint16_t);
2917 for (size_t i = 1; i < num_given_alg_ids; i++) {
2918 if (given_alg_ids[i - 1] == given_alg_ids[i]) {
2919 return false;
2920 }
2921 }
2922
2923 if (best_index < num_algs &&
2924 ssl_protocol_version(hs->ssl) >= TLS1_3_VERSION) {
2925 hs->cert_compression_negotiated = true;
2926 hs->cert_compression_alg_id = ctx->cert_compression_algs[best_index].alg_id;
2927 }
2928
2929 return true;
2930 }
2931
cert_compression_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)2932 static bool cert_compression_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
2933 return true;
2934 }
2935
2936 // Application-level Protocol Settings
2937 //
2938 // https://tools.ietf.org/html/draft-vvv-tls-alps-01
2939
ssl_get_local_application_settings(const SSL_HANDSHAKE * hs,Span<const uint8_t> * out_settings,Span<const uint8_t> protocol)2940 bool ssl_get_local_application_settings(const SSL_HANDSHAKE *hs,
2941 Span<const uint8_t> *out_settings,
2942 Span<const uint8_t> protocol) {
2943 for (const ALPSConfig &config : hs->config->alps_configs) {
2944 if (protocol == config.protocol) {
2945 *out_settings = config.settings;
2946 return true;
2947 }
2948 }
2949 return false;
2950 }
2951
ext_alps_add_clienthello(const SSL_HANDSHAKE * hs,CBB * out,CBB * out_compressible,ssl_client_hello_type_t type)2952 static bool ext_alps_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
2953 CBB *out_compressible,
2954 ssl_client_hello_type_t type) {
2955 const SSL *const ssl = hs->ssl;
2956 if (// ALPS requires TLS 1.3.
2957 hs->max_version < TLS1_3_VERSION ||
2958 // Do not offer ALPS without ALPN.
2959 hs->config->alpn_client_proto_list.empty() ||
2960 // Do not offer ALPS if not configured.
2961 hs->config->alps_configs.empty() ||
2962 // Do not offer ALPS on renegotiation handshakes.
2963 ssl->s3->initial_handshake_complete) {
2964 return true;
2965 }
2966
2967 CBB contents, proto_list, proto;
2968 if (!CBB_add_u16(out_compressible, TLSEXT_TYPE_application_settings) ||
2969 !CBB_add_u16_length_prefixed(out_compressible, &contents) ||
2970 !CBB_add_u16_length_prefixed(&contents, &proto_list)) {
2971 return false;
2972 }
2973
2974 for (const ALPSConfig &config : hs->config->alps_configs) {
2975 if (!CBB_add_u8_length_prefixed(&proto_list, &proto) ||
2976 !CBB_add_bytes(&proto, config.protocol.data(),
2977 config.protocol.size())) {
2978 return false;
2979 }
2980 }
2981
2982 return CBB_flush(out_compressible);
2983 }
2984
ext_alps_parse_serverhello(SSL_HANDSHAKE * hs,uint8_t * out_alert,CBS * contents)2985 static bool ext_alps_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
2986 CBS *contents) {
2987 SSL *const ssl = hs->ssl;
2988 if (contents == nullptr) {
2989 return true;
2990 }
2991
2992 assert(!ssl->s3->initial_handshake_complete);
2993 assert(!hs->config->alpn_client_proto_list.empty());
2994 assert(!hs->config->alps_configs.empty());
2995
2996 // ALPS requires TLS 1.3.
2997 if (ssl_protocol_version(ssl) < TLS1_3_VERSION) {
2998 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
2999 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
3000 return false;
3001 }
3002
3003 // Note extension callbacks may run in any order, so we defer checking
3004 // consistency with ALPN to |ssl_check_serverhello_tlsext|.
3005 if (!hs->new_session->peer_application_settings.CopyFrom(*contents)) {
3006 *out_alert = SSL_AD_INTERNAL_ERROR;
3007 return false;
3008 }
3009
3010 hs->new_session->has_application_settings = true;
3011 return true;
3012 }
3013
ext_alps_add_serverhello(SSL_HANDSHAKE * hs,CBB * out)3014 static bool ext_alps_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
3015 SSL *const ssl = hs->ssl;
3016 // If early data is accepted, we omit the ALPS extension. It is implicitly
3017 // carried over from the previous connection.
3018 if (hs->new_session == nullptr ||
3019 !hs->new_session->has_application_settings ||
3020 ssl->s3->early_data_accepted) {
3021 return true;
3022 }
3023
3024 CBB contents;
3025 if (!CBB_add_u16(out, TLSEXT_TYPE_application_settings) ||
3026 !CBB_add_u16_length_prefixed(out, &contents) ||
3027 !CBB_add_bytes(&contents,
3028 hs->new_session->local_application_settings.data(),
3029 hs->new_session->local_application_settings.size()) ||
3030 !CBB_flush(out)) {
3031 return false;
3032 }
3033
3034 return true;
3035 }
3036
ssl_negotiate_alps(SSL_HANDSHAKE * hs,uint8_t * out_alert,const SSL_CLIENT_HELLO * client_hello)3037 bool ssl_negotiate_alps(SSL_HANDSHAKE *hs, uint8_t *out_alert,
3038 const SSL_CLIENT_HELLO *client_hello) {
3039 SSL *const ssl = hs->ssl;
3040 if (ssl->s3->alpn_selected.empty()) {
3041 return true;
3042 }
3043
3044 // If we negotiate ALPN over TLS 1.3, try to negotiate ALPS.
3045 CBS alps_contents;
3046 Span<const uint8_t> settings;
3047 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION &&
3048 ssl_get_local_application_settings(hs, &settings,
3049 ssl->s3->alpn_selected) &&
3050 ssl_client_hello_get_extension(client_hello, &alps_contents,
3051 TLSEXT_TYPE_application_settings)) {
3052 // Check if the client supports ALPS with the selected ALPN.
3053 bool found = false;
3054 CBS alps_list;
3055 if (!CBS_get_u16_length_prefixed(&alps_contents, &alps_list) ||
3056 CBS_len(&alps_contents) != 0 ||
3057 CBS_len(&alps_list) == 0) {
3058 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
3059 *out_alert = SSL_AD_DECODE_ERROR;
3060 return false;
3061 }
3062 while (CBS_len(&alps_list) > 0) {
3063 CBS protocol_name;
3064 if (!CBS_get_u8_length_prefixed(&alps_list, &protocol_name) ||
3065 // Empty protocol names are forbidden.
3066 CBS_len(&protocol_name) == 0) {
3067 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
3068 *out_alert = SSL_AD_DECODE_ERROR;
3069 return false;
3070 }
3071 if (protocol_name == MakeConstSpan(ssl->s3->alpn_selected)) {
3072 found = true;
3073 }
3074 }
3075
3076 // Negotiate ALPS if both client also supports ALPS for this protocol.
3077 if (found) {
3078 hs->new_session->has_application_settings = true;
3079 if (!hs->new_session->local_application_settings.CopyFrom(settings)) {
3080 *out_alert = SSL_AD_INTERNAL_ERROR;
3081 return false;
3082 }
3083 }
3084 }
3085
3086 return true;
3087 }
3088
3089 // kExtensions contains all the supported extensions.
3090 static const struct tls_extension kExtensions[] = {
3091 {
3092 TLSEXT_TYPE_server_name,
3093 ext_sni_add_clienthello,
3094 ext_sni_parse_serverhello,
3095 ext_sni_parse_clienthello,
3096 ext_sni_add_serverhello,
3097 },
3098 {
3099 TLSEXT_TYPE_encrypted_client_hello,
3100 ext_ech_add_clienthello,
3101 ext_ech_parse_serverhello,
3102 ext_ech_parse_clienthello,
3103 ext_ech_add_serverhello,
3104 },
3105 {
3106 TLSEXT_TYPE_extended_master_secret,
3107 ext_ems_add_clienthello,
3108 ext_ems_parse_serverhello,
3109 ext_ems_parse_clienthello,
3110 ext_ems_add_serverhello,
3111 },
3112 {
3113 TLSEXT_TYPE_renegotiate,
3114 ext_ri_add_clienthello,
3115 ext_ri_parse_serverhello,
3116 ext_ri_parse_clienthello,
3117 ext_ri_add_serverhello,
3118 },
3119 {
3120 TLSEXT_TYPE_supported_groups,
3121 ext_supported_groups_add_clienthello,
3122 ext_supported_groups_parse_serverhello,
3123 ext_supported_groups_parse_clienthello,
3124 dont_add_serverhello,
3125 },
3126 {
3127 TLSEXT_TYPE_ec_point_formats,
3128 ext_ec_point_add_clienthello,
3129 ext_ec_point_parse_serverhello,
3130 ext_ec_point_parse_clienthello,
3131 ext_ec_point_add_serverhello,
3132 },
3133 {
3134 TLSEXT_TYPE_session_ticket,
3135 ext_ticket_add_clienthello,
3136 ext_ticket_parse_serverhello,
3137 // Ticket extension client parsing is handled in ssl_session.c
3138 ignore_parse_clienthello,
3139 ext_ticket_add_serverhello,
3140 },
3141 {
3142 TLSEXT_TYPE_application_layer_protocol_negotiation,
3143 ext_alpn_add_clienthello,
3144 ext_alpn_parse_serverhello,
3145 // ALPN is negotiated late in |ssl_negotiate_alpn|.
3146 ignore_parse_clienthello,
3147 ext_alpn_add_serverhello,
3148 },
3149 {
3150 TLSEXT_TYPE_status_request,
3151 ext_ocsp_add_clienthello,
3152 ext_ocsp_parse_serverhello,
3153 ext_ocsp_parse_clienthello,
3154 ext_ocsp_add_serverhello,
3155 },
3156 {
3157 TLSEXT_TYPE_signature_algorithms,
3158 ext_sigalgs_add_clienthello,
3159 forbid_parse_serverhello,
3160 ext_sigalgs_parse_clienthello,
3161 dont_add_serverhello,
3162 },
3163 {
3164 TLSEXT_TYPE_next_proto_neg,
3165 ext_npn_add_clienthello,
3166 ext_npn_parse_serverhello,
3167 ext_npn_parse_clienthello,
3168 ext_npn_add_serverhello,
3169 },
3170 {
3171 TLSEXT_TYPE_certificate_timestamp,
3172 ext_sct_add_clienthello,
3173 ext_sct_parse_serverhello,
3174 ext_sct_parse_clienthello,
3175 ext_sct_add_serverhello,
3176 },
3177 {
3178 TLSEXT_TYPE_channel_id,
3179 ext_channel_id_add_clienthello,
3180 ext_channel_id_parse_serverhello,
3181 ext_channel_id_parse_clienthello,
3182 ext_channel_id_add_serverhello,
3183 },
3184 {
3185 TLSEXT_TYPE_srtp,
3186 ext_srtp_add_clienthello,
3187 ext_srtp_parse_serverhello,
3188 ext_srtp_parse_clienthello,
3189 ext_srtp_add_serverhello,
3190 },
3191 {
3192 TLSEXT_TYPE_key_share,
3193 ext_key_share_add_clienthello,
3194 forbid_parse_serverhello,
3195 ignore_parse_clienthello,
3196 dont_add_serverhello,
3197 },
3198 {
3199 TLSEXT_TYPE_psk_key_exchange_modes,
3200 ext_psk_key_exchange_modes_add_clienthello,
3201 forbid_parse_serverhello,
3202 ext_psk_key_exchange_modes_parse_clienthello,
3203 dont_add_serverhello,
3204 },
3205 {
3206 TLSEXT_TYPE_early_data,
3207 ext_early_data_add_clienthello,
3208 ext_early_data_parse_serverhello,
3209 ext_early_data_parse_clienthello,
3210 ext_early_data_add_serverhello,
3211 },
3212 {
3213 TLSEXT_TYPE_supported_versions,
3214 ext_supported_versions_add_clienthello,
3215 forbid_parse_serverhello,
3216 ignore_parse_clienthello,
3217 dont_add_serverhello,
3218 },
3219 {
3220 TLSEXT_TYPE_cookie,
3221 ext_cookie_add_clienthello,
3222 forbid_parse_serverhello,
3223 ignore_parse_clienthello,
3224 dont_add_serverhello,
3225 },
3226 {
3227 TLSEXT_TYPE_quic_transport_parameters,
3228 ext_quic_transport_params_add_clienthello,
3229 ext_quic_transport_params_parse_serverhello,
3230 ext_quic_transport_params_parse_clienthello,
3231 ext_quic_transport_params_add_serverhello,
3232 },
3233 {
3234 TLSEXT_TYPE_quic_transport_parameters_legacy,
3235 ext_quic_transport_params_add_clienthello_legacy,
3236 ext_quic_transport_params_parse_serverhello_legacy,
3237 ext_quic_transport_params_parse_clienthello_legacy,
3238 ext_quic_transport_params_add_serverhello_legacy,
3239 },
3240 {
3241 TLSEXT_TYPE_cert_compression,
3242 cert_compression_add_clienthello,
3243 cert_compression_parse_serverhello,
3244 cert_compression_parse_clienthello,
3245 cert_compression_add_serverhello,
3246 },
3247 {
3248 TLSEXT_TYPE_delegated_credential,
3249 ext_delegated_credential_add_clienthello,
3250 forbid_parse_serverhello,
3251 ext_delegated_credential_parse_clienthello,
3252 dont_add_serverhello,
3253 },
3254 {
3255 TLSEXT_TYPE_application_settings,
3256 ext_alps_add_clienthello,
3257 ext_alps_parse_serverhello,
3258 // ALPS is negotiated late in |ssl_negotiate_alpn|.
3259 ignore_parse_clienthello,
3260 ext_alps_add_serverhello,
3261 },
3262 };
3263
3264 #define kNumExtensions (sizeof(kExtensions) / sizeof(struct tls_extension))
3265
3266 static_assert(kNumExtensions <=
3267 sizeof(((SSL_HANDSHAKE *)NULL)->extensions.sent) * 8,
3268 "too many extensions for sent bitset");
3269 static_assert(kNumExtensions <=
3270 sizeof(((SSL_HANDSHAKE *)NULL)->extensions.received) * 8,
3271 "too many extensions for received bitset");
3272
ssl_setup_extension_permutation(SSL_HANDSHAKE * hs)3273 bool ssl_setup_extension_permutation(SSL_HANDSHAKE *hs) {
3274 if (!hs->config->permute_extensions) {
3275 return true;
3276 }
3277
3278 static_assert(kNumExtensions <= UINT8_MAX,
3279 "extensions_permutation type is too small");
3280 uint32_t seeds[kNumExtensions - 1];
3281 Array<uint8_t> permutation;
3282 if (!RAND_bytes(reinterpret_cast<uint8_t *>(seeds), sizeof(seeds)) ||
3283 !permutation.Init(kNumExtensions)) {
3284 return false;
3285 }
3286 for (size_t i = 0; i < kNumExtensions; i++) {
3287 permutation[i] = i;
3288 }
3289 for (size_t i = kNumExtensions - 1; i > 0; i--) {
3290 // Set element |i| to a randomly-selected element 0 <= j <= i.
3291 std::swap(permutation[i], permutation[seeds[i - 1] % (i + 1)]);
3292 }
3293 hs->extension_permutation = std::move(permutation);
3294 return true;
3295 }
3296
tls_extension_find(uint32_t * out_index,uint16_t value)3297 static const struct tls_extension *tls_extension_find(uint32_t *out_index,
3298 uint16_t value) {
3299 unsigned i;
3300 for (i = 0; i < kNumExtensions; i++) {
3301 if (kExtensions[i].value == value) {
3302 *out_index = i;
3303 return &kExtensions[i];
3304 }
3305 }
3306
3307 return NULL;
3308 }
3309
add_padding_extension(CBB * cbb,uint16_t ext,size_t len)3310 static bool add_padding_extension(CBB *cbb, uint16_t ext, size_t len) {
3311 CBB child;
3312 if (!CBB_add_u16(cbb, ext) || //
3313 !CBB_add_u16_length_prefixed(cbb, &child) ||
3314 !CBB_add_zeros(&child, len)) {
3315 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
3316 return false;
3317 }
3318 return CBB_flush(cbb);
3319 }
3320
ssl_add_clienthello_tlsext_inner(SSL_HANDSHAKE * hs,CBB * out,CBB * out_encoded,bool * out_needs_psk_binder)3321 static bool ssl_add_clienthello_tlsext_inner(SSL_HANDSHAKE *hs, CBB *out,
3322 CBB *out_encoded,
3323 bool *out_needs_psk_binder) {
3324 // When writing ClientHelloInner, we construct the real and encoded
3325 // ClientHellos concurrently, to handle compression. Uncompressed extensions
3326 // are written to |extensions| and copied to |extensions_encoded|. Compressed
3327 // extensions are buffered in |compressed| and written to the end. (ECH can
3328 // only compress continguous extensions.)
3329 SSL *const ssl = hs->ssl;
3330 bssl::ScopedCBB compressed, outer_extensions;
3331 CBB extensions, extensions_encoded;
3332 if (!CBB_add_u16_length_prefixed(out, &extensions) ||
3333 !CBB_add_u16_length_prefixed(out_encoded, &extensions_encoded) ||
3334 !CBB_init(compressed.get(), 64) ||
3335 !CBB_init(outer_extensions.get(), 64)) {
3336 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
3337 return false;
3338 }
3339
3340 hs->inner_extensions_sent = 0;
3341
3342 if (ssl->ctx->grease_enabled) {
3343 // Add a fake empty extension. See RFC 8701. This always matches
3344 // |ssl_add_clienthello_tlsext|, so compress it.
3345 uint16_t grease_ext = ssl_get_grease_value(hs, ssl_grease_extension1);
3346 if (!add_padding_extension(compressed.get(), grease_ext, 0) ||
3347 !CBB_add_u16(outer_extensions.get(), grease_ext)) {
3348 return false;
3349 }
3350 }
3351
3352 for (size_t unpermuted = 0; unpermuted < kNumExtensions; unpermuted++) {
3353 size_t i = hs->extension_permutation.empty()
3354 ? unpermuted
3355 : hs->extension_permutation[unpermuted];
3356 const size_t len_before = CBB_len(&extensions);
3357 const size_t len_compressed_before = CBB_len(compressed.get());
3358 if (!kExtensions[i].add_clienthello(hs, &extensions, compressed.get(),
3359 ssl_client_hello_inner)) {
3360 OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_ADDING_EXTENSION);
3361 ERR_add_error_dataf("extension %u", (unsigned)kExtensions[i].value);
3362 return false;
3363 }
3364
3365 const size_t bytes_written = CBB_len(&extensions) - len_before;
3366 const size_t bytes_written_compressed =
3367 CBB_len(compressed.get()) - len_compressed_before;
3368 // The callback may write to at most one output.
3369 assert(bytes_written == 0 || bytes_written_compressed == 0);
3370 if (bytes_written != 0 || bytes_written_compressed != 0) {
3371 hs->inner_extensions_sent |= (1u << i);
3372 }
3373 // If compressed, update the running ech_outer_extensions extension.
3374 if (bytes_written_compressed != 0 &&
3375 !CBB_add_u16(outer_extensions.get(), kExtensions[i].value)) {
3376 return false;
3377 }
3378 }
3379
3380 if (ssl->ctx->grease_enabled) {
3381 // Add a fake non-empty extension. See RFC 8701. This always matches
3382 // |ssl_add_clienthello_tlsext|, so compress it.
3383 uint16_t grease_ext = ssl_get_grease_value(hs, ssl_grease_extension2);
3384 if (!add_padding_extension(compressed.get(), grease_ext, 1) ||
3385 !CBB_add_u16(outer_extensions.get(), grease_ext)) {
3386 return false;
3387 }
3388 }
3389
3390 // Uncompressed extensions are encoded as-is.
3391 if (!CBB_add_bytes(&extensions_encoded, CBB_data(&extensions),
3392 CBB_len(&extensions))) {
3393 return false;
3394 }
3395
3396 // Flush all the compressed extensions.
3397 if (CBB_len(compressed.get()) != 0) {
3398 CBB extension, child;
3399 // Copy them as-is in the real ClientHelloInner.
3400 if (!CBB_add_bytes(&extensions, CBB_data(compressed.get()),
3401 CBB_len(compressed.get())) ||
3402 // Replace with ech_outer_extensions in the encoded form.
3403 !CBB_add_u16(&extensions_encoded, TLSEXT_TYPE_ech_outer_extensions) ||
3404 !CBB_add_u16_length_prefixed(&extensions_encoded, &extension) ||
3405 !CBB_add_u8_length_prefixed(&extension, &child) ||
3406 !CBB_add_bytes(&child, CBB_data(outer_extensions.get()),
3407 CBB_len(outer_extensions.get())) ||
3408 !CBB_flush(&extensions_encoded)) {
3409 return false;
3410 }
3411 }
3412
3413 // The PSK extension must be last. It is never compressed. Note, if there is a
3414 // binder, the caller will need to update both ClientHelloInner and
3415 // EncodedClientHelloInner after computing it.
3416 const size_t len_before = CBB_len(&extensions);
3417 if (!ext_pre_shared_key_add_clienthello(hs, &extensions, out_needs_psk_binder,
3418 ssl_client_hello_inner) ||
3419 !CBB_add_bytes(&extensions_encoded, CBB_data(&extensions) + len_before,
3420 CBB_len(&extensions) - len_before) ||
3421 !CBB_flush(out) || //
3422 !CBB_flush(out_encoded)) {
3423 return false;
3424 }
3425
3426 return true;
3427 }
3428
ssl_add_clienthello_tlsext(SSL_HANDSHAKE * hs,CBB * out,CBB * out_encoded,bool * out_needs_psk_binder,ssl_client_hello_type_t type,size_t header_len)3429 bool ssl_add_clienthello_tlsext(SSL_HANDSHAKE *hs, CBB *out, CBB *out_encoded,
3430 bool *out_needs_psk_binder,
3431 ssl_client_hello_type_t type,
3432 size_t header_len) {
3433 *out_needs_psk_binder = false;
3434
3435 if (type == ssl_client_hello_inner) {
3436 return ssl_add_clienthello_tlsext_inner(hs, out, out_encoded,
3437 out_needs_psk_binder);
3438 }
3439
3440 assert(out_encoded == nullptr); // Only ClientHelloInner needs two outputs.
3441 SSL *const ssl = hs->ssl;
3442 CBB extensions;
3443 if (!CBB_add_u16_length_prefixed(out, &extensions)) {
3444 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
3445 return false;
3446 }
3447
3448 // Note we may send multiple ClientHellos for DTLS HelloVerifyRequest and TLS
3449 // 1.3 HelloRetryRequest. For the latter, the extensions may change, so it is
3450 // important to reset this value.
3451 hs->extensions.sent = 0;
3452
3453 // Add a fake empty extension. See RFC 8701.
3454 if (ssl->ctx->grease_enabled &&
3455 !add_padding_extension(
3456 &extensions, ssl_get_grease_value(hs, ssl_grease_extension1), 0)) {
3457 return false;
3458 }
3459
3460 bool last_was_empty = false;
3461 for (size_t unpermuted = 0; unpermuted < kNumExtensions; unpermuted++) {
3462 size_t i = hs->extension_permutation.empty()
3463 ? unpermuted
3464 : hs->extension_permutation[unpermuted];
3465 const size_t len_before = CBB_len(&extensions);
3466 if (!kExtensions[i].add_clienthello(hs, &extensions, &extensions, type)) {
3467 OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_ADDING_EXTENSION);
3468 ERR_add_error_dataf("extension %u", (unsigned)kExtensions[i].value);
3469 return false;
3470 }
3471
3472 const size_t bytes_written = CBB_len(&extensions) - len_before;
3473 if (bytes_written != 0) {
3474 hs->extensions.sent |= (1u << i);
3475 }
3476 // If the difference in lengths is only four bytes then the extension had
3477 // an empty body.
3478 last_was_empty = (bytes_written == 4);
3479 }
3480
3481 if (ssl->ctx->grease_enabled) {
3482 // Add a fake non-empty extension. See RFC 8701.
3483 if (!add_padding_extension(
3484 &extensions, ssl_get_grease_value(hs, ssl_grease_extension2), 1)) {
3485 return false;
3486 }
3487 last_was_empty = false;
3488 }
3489
3490 // In cleartext ClientHellos, we add the padding extension to work around
3491 // bugs. We also apply this padding to ClientHelloOuter, to keep the wire
3492 // images aligned.
3493 size_t psk_extension_len = ext_pre_shared_key_clienthello_length(hs, type);
3494 if (!SSL_is_dtls(ssl) && !ssl->quic_method &&
3495 !ssl->s3->used_hello_retry_request) {
3496 header_len +=
3497 SSL3_HM_HEADER_LENGTH + 2 + CBB_len(&extensions) + psk_extension_len;
3498 size_t padding_len = 0;
3499
3500 // The final extension must be non-empty. WebSphere Application
3501 // Server 7.0 is intolerant to the last extension being zero-length. See
3502 // https://crbug.com/363583.
3503 if (last_was_empty && psk_extension_len == 0) {
3504 padding_len = 1;
3505 // The addition of the padding extension may push us into the F5 bug.
3506 header_len += 4 + padding_len;
3507 }
3508
3509 // Add padding to workaround bugs in F5 terminators. See RFC 7685.
3510 //
3511 // NB: because this code works out the length of all existing extensions
3512 // it MUST always appear last (save for any PSK extension).
3513 if (header_len > 0xff && header_len < 0x200) {
3514 // If our calculations already included a padding extension, remove that
3515 // factor because we're about to change its length.
3516 if (padding_len != 0) {
3517 header_len -= 4 + padding_len;
3518 }
3519 padding_len = 0x200 - header_len;
3520 // Extensions take at least four bytes to encode. Always include at least
3521 // one byte of data if including the extension. WebSphere Application
3522 // Server 7.0 is intolerant to the last extension being zero-length. See
3523 // https://crbug.com/363583.
3524 if (padding_len >= 4 + 1) {
3525 padding_len -= 4;
3526 } else {
3527 padding_len = 1;
3528 }
3529 }
3530
3531 if (padding_len != 0 &&
3532 !add_padding_extension(&extensions, TLSEXT_TYPE_padding, padding_len)) {
3533 return false;
3534 }
3535 }
3536
3537 // The PSK extension must be last, including after the padding.
3538 const size_t len_before = CBB_len(&extensions);
3539 if (!ext_pre_shared_key_add_clienthello(hs, &extensions, out_needs_psk_binder,
3540 type)) {
3541 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
3542 return false;
3543 }
3544 assert(psk_extension_len == CBB_len(&extensions) - len_before);
3545 (void)len_before; // |assert| is omitted in release builds.
3546
3547 // Discard empty extensions blocks.
3548 if (CBB_len(&extensions) == 0) {
3549 CBB_discard_child(out);
3550 }
3551
3552 return CBB_flush(out);
3553 }
3554
ssl_add_serverhello_tlsext(SSL_HANDSHAKE * hs,CBB * out)3555 bool ssl_add_serverhello_tlsext(SSL_HANDSHAKE *hs, CBB *out) {
3556 SSL *const ssl = hs->ssl;
3557 CBB extensions;
3558 if (!CBB_add_u16_length_prefixed(out, &extensions)) {
3559 goto err;
3560 }
3561
3562 for (unsigned i = 0; i < kNumExtensions; i++) {
3563 if (!(hs->extensions.received & (1u << i))) {
3564 // Don't send extensions that were not received.
3565 continue;
3566 }
3567
3568 if (!kExtensions[i].add_serverhello(hs, &extensions)) {
3569 OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_ADDING_EXTENSION);
3570 ERR_add_error_dataf("extension %u", (unsigned)kExtensions[i].value);
3571 goto err;
3572 }
3573 }
3574
3575 // Discard empty extensions blocks before TLS 1.3.
3576 if (ssl_protocol_version(ssl) < TLS1_3_VERSION &&
3577 CBB_len(&extensions) == 0) {
3578 CBB_discard_child(out);
3579 }
3580
3581 return CBB_flush(out);
3582
3583 err:
3584 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
3585 return false;
3586 }
3587
ssl_scan_clienthello_tlsext(SSL_HANDSHAKE * hs,const SSL_CLIENT_HELLO * client_hello,int * out_alert)3588 static bool ssl_scan_clienthello_tlsext(SSL_HANDSHAKE *hs,
3589 const SSL_CLIENT_HELLO *client_hello,
3590 int *out_alert) {
3591 hs->extensions.received = 0;
3592 CBS extensions;
3593 CBS_init(&extensions, client_hello->extensions, client_hello->extensions_len);
3594 while (CBS_len(&extensions) != 0) {
3595 uint16_t type;
3596 CBS extension;
3597
3598 // Decode the next extension.
3599 if (!CBS_get_u16(&extensions, &type) ||
3600 !CBS_get_u16_length_prefixed(&extensions, &extension)) {
3601 *out_alert = SSL_AD_DECODE_ERROR;
3602 return false;
3603 }
3604
3605 unsigned ext_index;
3606 const struct tls_extension *const ext =
3607 tls_extension_find(&ext_index, type);
3608 if (ext == NULL) {
3609 continue;
3610 }
3611
3612 hs->extensions.received |= (1u << ext_index);
3613 uint8_t alert = SSL_AD_DECODE_ERROR;
3614 if (!ext->parse_clienthello(hs, &alert, &extension)) {
3615 *out_alert = alert;
3616 OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_PARSING_EXTENSION);
3617 ERR_add_error_dataf("extension %u", (unsigned)type);
3618 return false;
3619 }
3620 }
3621
3622 for (size_t i = 0; i < kNumExtensions; i++) {
3623 if (hs->extensions.received & (1u << i)) {
3624 continue;
3625 }
3626
3627 CBS *contents = NULL, fake_contents;
3628 static const uint8_t kFakeRenegotiateExtension[] = {0};
3629 if (kExtensions[i].value == TLSEXT_TYPE_renegotiate &&
3630 ssl_client_cipher_list_contains_cipher(client_hello,
3631 SSL3_CK_SCSV & 0xffff)) {
3632 // The renegotiation SCSV was received so pretend that we received a
3633 // renegotiation extension.
3634 CBS_init(&fake_contents, kFakeRenegotiateExtension,
3635 sizeof(kFakeRenegotiateExtension));
3636 contents = &fake_contents;
3637 hs->extensions.received |= (1u << i);
3638 }
3639
3640 // Extension wasn't observed so call the callback with a NULL
3641 // parameter.
3642 uint8_t alert = SSL_AD_DECODE_ERROR;
3643 if (!kExtensions[i].parse_clienthello(hs, &alert, contents)) {
3644 OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
3645 ERR_add_error_dataf("extension %u", (unsigned)kExtensions[i].value);
3646 *out_alert = alert;
3647 return false;
3648 }
3649 }
3650
3651 return true;
3652 }
3653
ssl_parse_clienthello_tlsext(SSL_HANDSHAKE * hs,const SSL_CLIENT_HELLO * client_hello)3654 bool ssl_parse_clienthello_tlsext(SSL_HANDSHAKE *hs,
3655 const SSL_CLIENT_HELLO *client_hello) {
3656 SSL *const ssl = hs->ssl;
3657 int alert = SSL_AD_DECODE_ERROR;
3658 if (!ssl_scan_clienthello_tlsext(hs, client_hello, &alert)) {
3659 ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
3660 return false;
3661 }
3662
3663 if (!ssl_check_clienthello_tlsext(hs)) {
3664 OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_TLSEXT);
3665 return false;
3666 }
3667
3668 return true;
3669 }
3670
ssl_scan_serverhello_tlsext(SSL_HANDSHAKE * hs,const CBS * cbs,int * out_alert)3671 static bool ssl_scan_serverhello_tlsext(SSL_HANDSHAKE *hs, const CBS *cbs,
3672 int *out_alert) {
3673 CBS extensions = *cbs;
3674 if (!tls1_check_duplicate_extensions(&extensions)) {
3675 *out_alert = SSL_AD_DECODE_ERROR;
3676 return false;
3677 }
3678
3679 uint32_t received = 0;
3680 while (CBS_len(&extensions) != 0) {
3681 uint16_t type;
3682 CBS extension;
3683
3684 // Decode the next extension.
3685 if (!CBS_get_u16(&extensions, &type) ||
3686 !CBS_get_u16_length_prefixed(&extensions, &extension)) {
3687 *out_alert = SSL_AD_DECODE_ERROR;
3688 return false;
3689 }
3690
3691 unsigned ext_index;
3692 const struct tls_extension *const ext =
3693 tls_extension_find(&ext_index, type);
3694
3695 if (ext == NULL) {
3696 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
3697 ERR_add_error_dataf("extension %u", (unsigned)type);
3698 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
3699 return false;
3700 }
3701
3702 static_assert(kNumExtensions <= sizeof(hs->extensions.sent) * 8,
3703 "too many bits");
3704
3705 if (!(hs->extensions.sent & (1u << ext_index))) {
3706 // If the extension was never sent then it is illegal.
3707 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
3708 ERR_add_error_dataf("extension :%u", (unsigned)type);
3709 *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
3710 return false;
3711 }
3712
3713 received |= (1u << ext_index);
3714
3715 uint8_t alert = SSL_AD_DECODE_ERROR;
3716 if (!ext->parse_serverhello(hs, &alert, &extension)) {
3717 OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_PARSING_EXTENSION);
3718 ERR_add_error_dataf("extension %u", (unsigned)type);
3719 *out_alert = alert;
3720 return false;
3721 }
3722 }
3723
3724 for (size_t i = 0; i < kNumExtensions; i++) {
3725 if (!(received & (1u << i))) {
3726 // Extension wasn't observed so call the callback with a NULL
3727 // parameter.
3728 uint8_t alert = SSL_AD_DECODE_ERROR;
3729 if (!kExtensions[i].parse_serverhello(hs, &alert, NULL)) {
3730 OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
3731 ERR_add_error_dataf("extension %u", (unsigned)kExtensions[i].value);
3732 *out_alert = alert;
3733 return false;
3734 }
3735 }
3736 }
3737
3738 return true;
3739 }
3740
ssl_check_clienthello_tlsext(SSL_HANDSHAKE * hs)3741 static bool ssl_check_clienthello_tlsext(SSL_HANDSHAKE *hs) {
3742 SSL *const ssl = hs->ssl;
3743 int ret = SSL_TLSEXT_ERR_NOACK;
3744 int al = SSL_AD_UNRECOGNIZED_NAME;
3745 if (ssl->ctx->servername_callback != 0) {
3746 ret = ssl->ctx->servername_callback(ssl, &al, ssl->ctx->servername_arg);
3747 } else if (ssl->session_ctx->servername_callback != 0) {
3748 ret = ssl->session_ctx->servername_callback(
3749 ssl, &al, ssl->session_ctx->servername_arg);
3750 }
3751
3752 switch (ret) {
3753 case SSL_TLSEXT_ERR_ALERT_FATAL:
3754 ssl_send_alert(ssl, SSL3_AL_FATAL, al);
3755 return false;
3756
3757 case SSL_TLSEXT_ERR_NOACK:
3758 hs->should_ack_sni = false;
3759 return true;
3760
3761 default:
3762 return true;
3763 }
3764 }
3765
ssl_check_serverhello_tlsext(SSL_HANDSHAKE * hs)3766 static bool ssl_check_serverhello_tlsext(SSL_HANDSHAKE *hs) {
3767 SSL *const ssl = hs->ssl;
3768 // ALPS and ALPN have a dependency between each other, so we defer checking
3769 // consistency to after the callbacks run.
3770 if (hs->new_session != nullptr && hs->new_session->has_application_settings) {
3771 // ALPN must be negotiated.
3772 if (ssl->s3->alpn_selected.empty()) {
3773 OPENSSL_PUT_ERROR(SSL, SSL_R_NEGOTIATED_ALPS_WITHOUT_ALPN);
3774 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
3775 return false;
3776 }
3777
3778 // The negotiated protocol must be one of the ones we advertised for ALPS.
3779 Span<const uint8_t> settings;
3780 if (!ssl_get_local_application_settings(hs, &settings,
3781 ssl->s3->alpn_selected)) {
3782 OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_ALPN_PROTOCOL);
3783 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
3784 return false;
3785 }
3786
3787 if (!hs->new_session->local_application_settings.CopyFrom(settings)) {
3788 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3789 return false;
3790 }
3791 }
3792
3793 return true;
3794 }
3795
ssl_parse_serverhello_tlsext(SSL_HANDSHAKE * hs,const CBS * cbs)3796 bool ssl_parse_serverhello_tlsext(SSL_HANDSHAKE *hs, const CBS *cbs) {
3797 SSL *const ssl = hs->ssl;
3798 int alert = SSL_AD_DECODE_ERROR;
3799 if (!ssl_scan_serverhello_tlsext(hs, cbs, &alert)) {
3800 ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
3801 return false;
3802 }
3803
3804 if (!ssl_check_serverhello_tlsext(hs)) {
3805 return false;
3806 }
3807
3808 return true;
3809 }
3810
decrypt_ticket_with_cipher_ctx(Array<uint8_t> * out,EVP_CIPHER_CTX * cipher_ctx,HMAC_CTX * hmac_ctx,Span<const uint8_t> ticket)3811 static enum ssl_ticket_aead_result_t decrypt_ticket_with_cipher_ctx(
3812 Array<uint8_t> *out, EVP_CIPHER_CTX *cipher_ctx, HMAC_CTX *hmac_ctx,
3813 Span<const uint8_t> ticket) {
3814 size_t iv_len = EVP_CIPHER_CTX_iv_length(cipher_ctx);
3815
3816 // Check the MAC at the end of the ticket.
3817 uint8_t mac[EVP_MAX_MD_SIZE];
3818 size_t mac_len = HMAC_size(hmac_ctx);
3819 if (ticket.size() < SSL_TICKET_KEY_NAME_LEN + iv_len + 1 + mac_len) {
3820 // The ticket must be large enough for key name, IV, data, and MAC.
3821 return ssl_ticket_aead_ignore_ticket;
3822 }
3823 // Split the ticket into the ticket and the MAC.
3824 auto ticket_mac = ticket.last(mac_len);
3825 ticket = ticket.first(ticket.size() - mac_len);
3826 HMAC_Update(hmac_ctx, ticket.data(), ticket.size());
3827 HMAC_Final(hmac_ctx, mac, NULL);
3828 assert(mac_len == ticket_mac.size());
3829 bool mac_ok = CRYPTO_memcmp(mac, ticket_mac.data(), mac_len) == 0;
3830 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
3831 mac_ok = true;
3832 #endif
3833 if (!mac_ok) {
3834 return ssl_ticket_aead_ignore_ticket;
3835 }
3836
3837 // Decrypt the session data.
3838 auto ciphertext = ticket.subspan(SSL_TICKET_KEY_NAME_LEN + iv_len);
3839 Array<uint8_t> plaintext;
3840 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
3841 if (!plaintext.CopyFrom(ciphertext)) {
3842 return ssl_ticket_aead_error;
3843 }
3844 #else
3845 if (ciphertext.size() >= INT_MAX) {
3846 return ssl_ticket_aead_ignore_ticket;
3847 }
3848 if (!plaintext.Init(ciphertext.size())) {
3849 return ssl_ticket_aead_error;
3850 }
3851 int len1, len2;
3852 if (!EVP_DecryptUpdate(cipher_ctx, plaintext.data(), &len1, ciphertext.data(),
3853 (int)ciphertext.size()) ||
3854 !EVP_DecryptFinal_ex(cipher_ctx, plaintext.data() + len1, &len2)) {
3855 ERR_clear_error();
3856 return ssl_ticket_aead_ignore_ticket;
3857 }
3858 plaintext.Shrink(static_cast<size_t>(len1) + len2);
3859 #endif
3860
3861 *out = std::move(plaintext);
3862 return ssl_ticket_aead_success;
3863 }
3864
ssl_decrypt_ticket_with_cb(SSL_HANDSHAKE * hs,Array<uint8_t> * out,bool * out_renew_ticket,Span<const uint8_t> ticket)3865 static enum ssl_ticket_aead_result_t ssl_decrypt_ticket_with_cb(
3866 SSL_HANDSHAKE *hs, Array<uint8_t> *out, bool *out_renew_ticket,
3867 Span<const uint8_t> ticket) {
3868 assert(ticket.size() >= SSL_TICKET_KEY_NAME_LEN + EVP_MAX_IV_LENGTH);
3869 ScopedEVP_CIPHER_CTX cipher_ctx;
3870 ScopedHMAC_CTX hmac_ctx;
3871 auto name = ticket.subspan(0, SSL_TICKET_KEY_NAME_LEN);
3872 // The actual IV is shorter, but the length is determined by the callback's
3873 // chosen cipher. Instead we pass in |EVP_MAX_IV_LENGTH| worth of IV to ensure
3874 // the callback has enough.
3875 auto iv = ticket.subspan(SSL_TICKET_KEY_NAME_LEN, EVP_MAX_IV_LENGTH);
3876 int cb_ret = hs->ssl->session_ctx->ticket_key_cb(
3877 hs->ssl, const_cast<uint8_t *>(name.data()),
3878 const_cast<uint8_t *>(iv.data()), cipher_ctx.get(), hmac_ctx.get(),
3879 0 /* decrypt */);
3880 if (cb_ret < 0) {
3881 return ssl_ticket_aead_error;
3882 } else if (cb_ret == 0) {
3883 return ssl_ticket_aead_ignore_ticket;
3884 } else if (cb_ret == 2) {
3885 *out_renew_ticket = true;
3886 } else {
3887 assert(cb_ret == 1);
3888 }
3889 return decrypt_ticket_with_cipher_ctx(out, cipher_ctx.get(), hmac_ctx.get(),
3890 ticket);
3891 }
3892
ssl_decrypt_ticket_with_ticket_keys(SSL_HANDSHAKE * hs,Array<uint8_t> * out,Span<const uint8_t> ticket)3893 static enum ssl_ticket_aead_result_t ssl_decrypt_ticket_with_ticket_keys(
3894 SSL_HANDSHAKE *hs, Array<uint8_t> *out, Span<const uint8_t> ticket) {
3895 assert(ticket.size() >= SSL_TICKET_KEY_NAME_LEN + EVP_MAX_IV_LENGTH);
3896 SSL_CTX *ctx = hs->ssl->session_ctx.get();
3897
3898 // Rotate the ticket key if necessary.
3899 if (!ssl_ctx_rotate_ticket_encryption_key(ctx)) {
3900 return ssl_ticket_aead_error;
3901 }
3902
3903 const EVP_CIPHER *cipher = EVP_aes_128_cbc();
3904 auto name = ticket.subspan(0, SSL_TICKET_KEY_NAME_LEN);
3905 auto iv =
3906 ticket.subspan(SSL_TICKET_KEY_NAME_LEN, EVP_CIPHER_iv_length(cipher));
3907
3908 // Pick the matching ticket key and decrypt.
3909 ScopedEVP_CIPHER_CTX cipher_ctx;
3910 ScopedHMAC_CTX hmac_ctx;
3911 {
3912 MutexReadLock lock(&ctx->lock);
3913 const TicketKey *key;
3914 if (ctx->ticket_key_current && name == ctx->ticket_key_current->name) {
3915 key = ctx->ticket_key_current.get();
3916 } else if (ctx->ticket_key_prev && name == ctx->ticket_key_prev->name) {
3917 key = ctx->ticket_key_prev.get();
3918 } else {
3919 return ssl_ticket_aead_ignore_ticket;
3920 }
3921 if (!HMAC_Init_ex(hmac_ctx.get(), key->hmac_key, sizeof(key->hmac_key),
3922 tlsext_tick_md(), NULL) ||
3923 !EVP_DecryptInit_ex(cipher_ctx.get(), cipher, NULL,
3924 key->aes_key, iv.data())) {
3925 return ssl_ticket_aead_error;
3926 }
3927 }
3928 return decrypt_ticket_with_cipher_ctx(out, cipher_ctx.get(), hmac_ctx.get(),
3929 ticket);
3930 }
3931
ssl_decrypt_ticket_with_method(SSL_HANDSHAKE * hs,Array<uint8_t> * out,bool * out_renew_ticket,Span<const uint8_t> ticket)3932 static enum ssl_ticket_aead_result_t ssl_decrypt_ticket_with_method(
3933 SSL_HANDSHAKE *hs, Array<uint8_t> *out, bool *out_renew_ticket,
3934 Span<const uint8_t> ticket) {
3935 Array<uint8_t> plaintext;
3936 if (!plaintext.Init(ticket.size())) {
3937 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
3938 return ssl_ticket_aead_error;
3939 }
3940
3941 size_t plaintext_len;
3942 const enum ssl_ticket_aead_result_t result =
3943 hs->ssl->session_ctx->ticket_aead_method->open(
3944 hs->ssl, plaintext.data(), &plaintext_len, ticket.size(),
3945 ticket.data(), ticket.size());
3946 if (result != ssl_ticket_aead_success) {
3947 return result;
3948 }
3949
3950 plaintext.Shrink(plaintext_len);
3951 *out = std::move(plaintext);
3952 return ssl_ticket_aead_success;
3953 }
3954
ssl_process_ticket(SSL_HANDSHAKE * hs,UniquePtr<SSL_SESSION> * out_session,bool * out_renew_ticket,Span<const uint8_t> ticket,Span<const uint8_t> session_id)3955 enum ssl_ticket_aead_result_t ssl_process_ticket(
3956 SSL_HANDSHAKE *hs, UniquePtr<SSL_SESSION> *out_session,
3957 bool *out_renew_ticket, Span<const uint8_t> ticket,
3958 Span<const uint8_t> session_id) {
3959 SSL *const ssl = hs->ssl;
3960 *out_renew_ticket = false;
3961 out_session->reset();
3962
3963 if ((SSL_get_options(hs->ssl) & SSL_OP_NO_TICKET) ||
3964 session_id.size() > SSL_MAX_SSL_SESSION_ID_LENGTH) {
3965 return ssl_ticket_aead_ignore_ticket;
3966 }
3967
3968 // Tickets in TLS 1.3 are tied into pre-shared keys (PSKs), unlike in TLS 1.2
3969 // where that concept doesn't exist. The |decrypted_psk| and |ignore_psk|
3970 // hints only apply to PSKs. We check the version to determine which this is.
3971 const bool is_psk = ssl_protocol_version(ssl) >= TLS1_3_VERSION;
3972
3973 Array<uint8_t> plaintext;
3974 enum ssl_ticket_aead_result_t result;
3975 SSL_HANDSHAKE_HINTS *const hints = hs->hints.get();
3976 if (is_psk && hints && !hs->hints_requested &&
3977 !hints->decrypted_psk.empty()) {
3978 result = plaintext.CopyFrom(hints->decrypted_psk) ? ssl_ticket_aead_success
3979 : ssl_ticket_aead_error;
3980 } else if (is_psk && hints && !hs->hints_requested && hints->ignore_psk) {
3981 result = ssl_ticket_aead_ignore_ticket;
3982 } else if (ssl->session_ctx->ticket_aead_method != NULL) {
3983 result = ssl_decrypt_ticket_with_method(hs, &plaintext, out_renew_ticket,
3984 ticket);
3985 } else {
3986 // Ensure there is room for the key name and the largest IV |ticket_key_cb|
3987 // may try to consume. The real limit may be lower, but the maximum IV
3988 // length should be well under the minimum size for the session material and
3989 // HMAC.
3990 if (ticket.size() < SSL_TICKET_KEY_NAME_LEN + EVP_MAX_IV_LENGTH) {
3991 result = ssl_ticket_aead_ignore_ticket;
3992 } else if (ssl->session_ctx->ticket_key_cb != NULL) {
3993 result =
3994 ssl_decrypt_ticket_with_cb(hs, &plaintext, out_renew_ticket, ticket);
3995 } else {
3996 result = ssl_decrypt_ticket_with_ticket_keys(hs, &plaintext, ticket);
3997 }
3998 }
3999
4000 if (is_psk && hints && hs->hints_requested) {
4001 if (result == ssl_ticket_aead_ignore_ticket) {
4002 hints->ignore_psk = true;
4003 } else if (result == ssl_ticket_aead_success &&
4004 !hints->decrypted_psk.CopyFrom(plaintext)) {
4005 return ssl_ticket_aead_error;
4006 }
4007 }
4008
4009 if (result != ssl_ticket_aead_success) {
4010 return result;
4011 }
4012
4013 // Decode the session.
4014 UniquePtr<SSL_SESSION> session(SSL_SESSION_from_bytes(
4015 plaintext.data(), plaintext.size(), ssl->ctx.get()));
4016 if (!session) {
4017 ERR_clear_error(); // Don't leave an error on the queue.
4018 return ssl_ticket_aead_ignore_ticket;
4019 }
4020
4021 // Envoy's tests expect the session to have a session ID that matches the
4022 // placeholder used by the client. It's unclear whether this is a good idea,
4023 // but we maintain it for now.
4024 SHA256(ticket.data(), ticket.size(), session->session_id);
4025 // Other consumers may expect a non-empty session ID to indicate resumption.
4026 session->session_id_length = SHA256_DIGEST_LENGTH;
4027
4028 *out_session = std::move(session);
4029 return ssl_ticket_aead_success;
4030 }
4031
tls1_parse_peer_sigalgs(SSL_HANDSHAKE * hs,const CBS * in_sigalgs)4032 bool tls1_parse_peer_sigalgs(SSL_HANDSHAKE *hs, const CBS *in_sigalgs) {
4033 // Extension ignored for inappropriate versions
4034 if (ssl_protocol_version(hs->ssl) < TLS1_2_VERSION) {
4035 return true;
4036 }
4037
4038 // In all contexts, the signature algorithms list may not be empty. (It may be
4039 // omitted by clients in TLS 1.2, but then the entire extension is omitted.)
4040 return CBS_len(in_sigalgs) != 0 &&
4041 parse_u16_array(in_sigalgs, &hs->peer_sigalgs);
4042 }
4043
tls1_get_legacy_signature_algorithm(uint16_t * out,const EVP_PKEY * pkey)4044 bool tls1_get_legacy_signature_algorithm(uint16_t *out, const EVP_PKEY *pkey) {
4045 switch (EVP_PKEY_id(pkey)) {
4046 case EVP_PKEY_RSA:
4047 *out = SSL_SIGN_RSA_PKCS1_MD5_SHA1;
4048 return true;
4049 case EVP_PKEY_EC:
4050 *out = SSL_SIGN_ECDSA_SHA1;
4051 return true;
4052 default:
4053 return false;
4054 }
4055 }
4056
tls1_choose_signature_algorithm(SSL_HANDSHAKE * hs,uint16_t * out)4057 bool tls1_choose_signature_algorithm(SSL_HANDSHAKE *hs, uint16_t *out) {
4058 SSL *const ssl = hs->ssl;
4059 CERT *cert = hs->config->cert.get();
4060 DC *dc = cert->dc.get();
4061
4062 // Before TLS 1.2, the signature algorithm isn't negotiated as part of the
4063 // handshake.
4064 if (ssl_protocol_version(ssl) < TLS1_2_VERSION) {
4065 if (!tls1_get_legacy_signature_algorithm(out, hs->local_pubkey.get())) {
4066 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_COMMON_SIGNATURE_ALGORITHMS);
4067 return false;
4068 }
4069 return true;
4070 }
4071
4072 Span<const uint16_t> sigalgs = kSignSignatureAlgorithms;
4073 if (ssl_signing_with_dc(hs)) {
4074 sigalgs = MakeConstSpan(&dc->expected_cert_verify_algorithm, 1);
4075 } else if (!cert->sigalgs.empty()) {
4076 sigalgs = cert->sigalgs;
4077 }
4078
4079 Span<const uint16_t> peer_sigalgs = tls1_get_peer_verify_algorithms(hs);
4080
4081 for (uint16_t sigalg : sigalgs) {
4082 // SSL_SIGN_RSA_PKCS1_MD5_SHA1 is an internal value and should never be
4083 // negotiated.
4084 if (sigalg == SSL_SIGN_RSA_PKCS1_MD5_SHA1 ||
4085 !ssl_private_key_supports_signature_algorithm(hs, sigalg)) {
4086 continue;
4087 }
4088
4089 for (uint16_t peer_sigalg : peer_sigalgs) {
4090 if (sigalg == peer_sigalg) {
4091 *out = sigalg;
4092 return true;
4093 }
4094 }
4095 }
4096
4097 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_COMMON_SIGNATURE_ALGORITHMS);
4098 return false;
4099 }
4100
tls1_get_peer_verify_algorithms(const SSL_HANDSHAKE * hs)4101 Span<const uint16_t> tls1_get_peer_verify_algorithms(const SSL_HANDSHAKE *hs) {
4102 Span<const uint16_t> peer_sigalgs = hs->peer_sigalgs;
4103 if (peer_sigalgs.empty() && ssl_protocol_version(hs->ssl) < TLS1_3_VERSION) {
4104 // If the client didn't specify any signature_algorithms extension then
4105 // we can assume that it supports SHA1. See
4106 // http://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
4107 static const uint16_t kDefaultPeerAlgorithms[] = {SSL_SIGN_RSA_PKCS1_SHA1,
4108 SSL_SIGN_ECDSA_SHA1};
4109 peer_sigalgs = kDefaultPeerAlgorithms;
4110 }
4111 return peer_sigalgs;
4112 }
4113
tls1_verify_channel_id(SSL_HANDSHAKE * hs,const SSLMessage & msg)4114 bool tls1_verify_channel_id(SSL_HANDSHAKE *hs, const SSLMessage &msg) {
4115 SSL *const ssl = hs->ssl;
4116 // A Channel ID handshake message is structured to contain multiple
4117 // extensions, but the only one that can be present is Channel ID.
4118 uint16_t extension_type;
4119 CBS channel_id = msg.body, extension;
4120 if (!CBS_get_u16(&channel_id, &extension_type) ||
4121 !CBS_get_u16_length_prefixed(&channel_id, &extension) ||
4122 CBS_len(&channel_id) != 0 ||
4123 extension_type != TLSEXT_TYPE_channel_id ||
4124 CBS_len(&extension) != TLSEXT_CHANNEL_ID_SIZE) {
4125 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
4126 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
4127 return false;
4128 }
4129
4130 UniquePtr<EC_GROUP> p256(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
4131 if (!p256) {
4132 OPENSSL_PUT_ERROR(SSL, SSL_R_NO_P256_SUPPORT);
4133 return false;
4134 }
4135
4136 UniquePtr<ECDSA_SIG> sig(ECDSA_SIG_new());
4137 UniquePtr<BIGNUM> x(BN_new()), y(BN_new());
4138 if (!sig || !x || !y) {
4139 return false;
4140 }
4141
4142 const uint8_t *p = CBS_data(&extension);
4143 if (BN_bin2bn(p + 0, 32, x.get()) == NULL ||
4144 BN_bin2bn(p + 32, 32, y.get()) == NULL ||
4145 BN_bin2bn(p + 64, 32, sig->r) == NULL ||
4146 BN_bin2bn(p + 96, 32, sig->s) == NULL) {
4147 return false;
4148 }
4149
4150 UniquePtr<EC_KEY> key(EC_KEY_new());
4151 UniquePtr<EC_POINT> point(EC_POINT_new(p256.get()));
4152 if (!key || !point ||
4153 !EC_POINT_set_affine_coordinates_GFp(p256.get(), point.get(), x.get(),
4154 y.get(), nullptr) ||
4155 !EC_KEY_set_group(key.get(), p256.get()) ||
4156 !EC_KEY_set_public_key(key.get(), point.get())) {
4157 return false;
4158 }
4159
4160 uint8_t digest[EVP_MAX_MD_SIZE];
4161 size_t digest_len;
4162 if (!tls1_channel_id_hash(hs, digest, &digest_len)) {
4163 return false;
4164 }
4165
4166 bool sig_ok = ECDSA_do_verify(digest, digest_len, sig.get(), key.get());
4167 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
4168 sig_ok = true;
4169 ERR_clear_error();
4170 #endif
4171 if (!sig_ok) {
4172 OPENSSL_PUT_ERROR(SSL, SSL_R_CHANNEL_ID_SIGNATURE_INVALID);
4173 ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
4174 return false;
4175 }
4176
4177 OPENSSL_memcpy(ssl->s3->channel_id, p, 64);
4178 ssl->s3->channel_id_valid = true;
4179 return true;
4180 }
4181
tls1_write_channel_id(SSL_HANDSHAKE * hs,CBB * cbb)4182 bool tls1_write_channel_id(SSL_HANDSHAKE *hs, CBB *cbb) {
4183 uint8_t digest[EVP_MAX_MD_SIZE];
4184 size_t digest_len;
4185 if (!tls1_channel_id_hash(hs, digest, &digest_len)) {
4186 return false;
4187 }
4188
4189 EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(hs->config->channel_id_private.get());
4190 if (ec_key == nullptr) {
4191 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
4192 return false;
4193 }
4194
4195 UniquePtr<BIGNUM> x(BN_new()), y(BN_new());
4196 if (!x || !y ||
4197 !EC_POINT_get_affine_coordinates_GFp(EC_KEY_get0_group(ec_key),
4198 EC_KEY_get0_public_key(ec_key),
4199 x.get(), y.get(), nullptr)) {
4200 return false;
4201 }
4202
4203 UniquePtr<ECDSA_SIG> sig(ECDSA_do_sign(digest, digest_len, ec_key));
4204 if (!sig) {
4205 return false;
4206 }
4207
4208 CBB child;
4209 if (!CBB_add_u16(cbb, TLSEXT_TYPE_channel_id) ||
4210 !CBB_add_u16_length_prefixed(cbb, &child) ||
4211 !BN_bn2cbb_padded(&child, 32, x.get()) ||
4212 !BN_bn2cbb_padded(&child, 32, y.get()) ||
4213 !BN_bn2cbb_padded(&child, 32, sig->r) ||
4214 !BN_bn2cbb_padded(&child, 32, sig->s) ||
4215 !CBB_flush(cbb)) {
4216 return false;
4217 }
4218
4219 return true;
4220 }
4221
tls1_channel_id_hash(SSL_HANDSHAKE * hs,uint8_t * out,size_t * out_len)4222 bool tls1_channel_id_hash(SSL_HANDSHAKE *hs, uint8_t *out, size_t *out_len) {
4223 SSL *const ssl = hs->ssl;
4224 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
4225 Array<uint8_t> msg;
4226 if (!tls13_get_cert_verify_signature_input(hs, &msg,
4227 ssl_cert_verify_channel_id)) {
4228 return false;
4229 }
4230 SHA256(msg.data(), msg.size(), out);
4231 *out_len = SHA256_DIGEST_LENGTH;
4232 return true;
4233 }
4234
4235 SHA256_CTX ctx;
4236
4237 SHA256_Init(&ctx);
4238 static const char kClientIDMagic[] = "TLS Channel ID signature";
4239 SHA256_Update(&ctx, kClientIDMagic, sizeof(kClientIDMagic));
4240
4241 if (ssl->session != NULL) {
4242 static const char kResumptionMagic[] = "Resumption";
4243 SHA256_Update(&ctx, kResumptionMagic, sizeof(kResumptionMagic));
4244 if (ssl->session->original_handshake_hash_len == 0) {
4245 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
4246 return false;
4247 }
4248 SHA256_Update(&ctx, ssl->session->original_handshake_hash,
4249 ssl->session->original_handshake_hash_len);
4250 }
4251
4252 uint8_t hs_hash[EVP_MAX_MD_SIZE];
4253 size_t hs_hash_len;
4254 if (!hs->transcript.GetHash(hs_hash, &hs_hash_len)) {
4255 return false;
4256 }
4257 SHA256_Update(&ctx, hs_hash, (size_t)hs_hash_len);
4258 SHA256_Final(out, &ctx);
4259 *out_len = SHA256_DIGEST_LENGTH;
4260 return true;
4261 }
4262
tls1_record_handshake_hashes_for_channel_id(SSL_HANDSHAKE * hs)4263 bool tls1_record_handshake_hashes_for_channel_id(SSL_HANDSHAKE *hs) {
4264 SSL *const ssl = hs->ssl;
4265 // This function should never be called for a resumed session because the
4266 // handshake hashes that we wish to record are for the original, full
4267 // handshake.
4268 if (ssl->session != NULL) {
4269 return false;
4270 }
4271
4272 static_assert(
4273 sizeof(hs->new_session->original_handshake_hash) == EVP_MAX_MD_SIZE,
4274 "original_handshake_hash is too small");
4275
4276 size_t digest_len;
4277 if (!hs->transcript.GetHash(hs->new_session->original_handshake_hash,
4278 &digest_len)) {
4279 return false;
4280 }
4281
4282 static_assert(EVP_MAX_MD_SIZE <= 0xff,
4283 "EVP_MAX_MD_SIZE does not fit in uint8_t");
4284 hs->new_session->original_handshake_hash_len = (uint8_t)digest_len;
4285
4286 return true;
4287 }
4288
ssl_is_sct_list_valid(const CBS * contents)4289 bool ssl_is_sct_list_valid(const CBS *contents) {
4290 // Shallow parse the SCT list for sanity. By the RFC
4291 // (https://tools.ietf.org/html/rfc6962#section-3.3) neither the list nor any
4292 // of the SCTs may be empty.
4293 CBS copy = *contents;
4294 CBS sct_list;
4295 if (!CBS_get_u16_length_prefixed(©, &sct_list) ||
4296 CBS_len(©) != 0 ||
4297 CBS_len(&sct_list) == 0) {
4298 return false;
4299 }
4300
4301 while (CBS_len(&sct_list) > 0) {
4302 CBS sct;
4303 if (!CBS_get_u16_length_prefixed(&sct_list, &sct) ||
4304 CBS_len(&sct) == 0) {
4305 return false;
4306 }
4307 }
4308
4309 return true;
4310 }
4311
4312 BSSL_NAMESPACE_END
4313
4314 using namespace bssl;
4315
SSL_early_callback_ctx_extension_get(const SSL_CLIENT_HELLO * client_hello,uint16_t extension_type,const uint8_t ** out_data,size_t * out_len)4316 int SSL_early_callback_ctx_extension_get(const SSL_CLIENT_HELLO *client_hello,
4317 uint16_t extension_type,
4318 const uint8_t **out_data,
4319 size_t *out_len) {
4320 CBS cbs;
4321 if (!ssl_client_hello_get_extension(client_hello, &cbs, extension_type)) {
4322 return 0;
4323 }
4324
4325 *out_data = CBS_data(&cbs);
4326 *out_len = CBS_len(&cbs);
4327 return 1;
4328 }
4329