Coverage Report

Created: 2024-09-19 09:45

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