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