Coverage Report

Created: 2023-06-07 07:11

/src/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
0
static bool is_post_quantum_group(uint16_t id) {
208
0
  switch (id) {
209
0
    case SSL_GROUP_X25519_KYBER768_DRAFT00:
210
0
      return true;
211
0
    default:
212
0
      return false;
213
0
  }
214
0
}
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
0
Span<const uint16_t> tls1_get_grouplist(const SSL_HANDSHAKE *hs) {
316
0
  if (!hs->config->supported_group_list.empty()) {
317
0
    return hs->config->supported_group_list;
318
0
  }
319
0
  return Span<const uint16_t>(kDefaultGroups);
320
0
}
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
0
static Span<const uint16_t> tls12_get_verify_sigalgs(const SSL_HANDSHAKE *hs) {
428
0
  if (hs->config->verify_sigalgs.empty()) {
429
0
    return Span<const uint16_t>(kVerifySignatureAlgorithms);
430
0
  }
431
0
  return hs->config->verify_sigalgs;
432
0
}
433
434
0
bool tls12_add_verify_sigalgs(const SSL_HANDSHAKE *hs, CBB *out) {
435
0
  for (uint16_t sigalg : tls12_get_verify_sigalgs(hs)) {
436
0
    if (!CBB_add_u16(out, sigalg)) {
437
0
      return false;
438
0
    }
439
0
  }
440
0
  return true;
441
0
}
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
0
                                    ssl_client_hello_type_t type) {
524
0
  const SSL *const ssl = hs->ssl;
525
  // If offering ECH, send the public name instead of the configured name.
526
0
  Span<const uint8_t> hostname;
527
0
  if (type == ssl_client_hello_outer) {
528
0
    hostname = hs->selected_ech_config->public_name;
529
0
  } else {
530
0
    if (ssl->hostname == nullptr) {
531
0
      return true;
532
0
    }
533
0
    hostname =
534
0
        MakeConstSpan(reinterpret_cast<const uint8_t *>(ssl->hostname.get()),
535
0
                      strlen(ssl->hostname.get()));
536
0
  }
537
538
0
  CBB contents, server_name_list, name;
539
0
  if (!CBB_add_u16(out, TLSEXT_TYPE_server_name) ||
540
0
      !CBB_add_u16_length_prefixed(out, &contents) ||
541
0
      !CBB_add_u16_length_prefixed(&contents, &server_name_list) ||
542
0
      !CBB_add_u8(&server_name_list, TLSEXT_NAMETYPE_host_name) ||
543
0
      !CBB_add_u16_length_prefixed(&server_name_list, &name) ||
544
0
      !CBB_add_bytes(&name, hostname.data(), hostname.size()) ||
545
0
      !CBB_flush(out)) {
546
0
    return false;
547
0
  }
548
549
0
  return true;
550
0
}
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
0
                                    ssl_client_hello_type_t type) {
587
0
  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
0
  if (hs->ech_client_outer.empty()) {
597
0
    return true;
598
0
  }
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
0
                                   ssl_client_hello_type_t type) {
701
0
  const SSL *const ssl = hs->ssl;
702
  // Renegotiation indication is not necessary in TLS 1.3.
703
0
  if (hs->min_version >= TLS1_3_VERSION ||
704
0
     type == ssl_client_hello_inner) {
705
0
    return true;
706
0
  }
707
708
0
  assert(ssl->s3->initial_handshake_complete ==
709
0
         (ssl->s3->previous_client_finished_len != 0));
710
711
0
  CBB contents, prev_finished;
712
0
  if (!CBB_add_u16(out, TLSEXT_TYPE_renegotiate) ||
713
0
      !CBB_add_u16_length_prefixed(out, &contents) ||
714
0
      !CBB_add_u8_length_prefixed(&contents, &prev_finished) ||
715
0
      !CBB_add_bytes(&prev_finished, ssl->s3->previous_client_finished,
716
0
                     ssl->s3->previous_client_finished_len) ||
717
0
      !CBB_flush(out)) {
718
0
    return false;
719
0
  }
720
721
0
  return true;
722
0
}
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
0
#if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
783
0
  ok = true;
784
0
#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
0
#if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
795
0
  ok = true;
796
0
#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
0
                                    ssl_client_hello_type_t type) {
869
  // Extended master secret is not necessary in TLS 1.3.
870
0
  if (hs->min_version >= TLS1_3_VERSION || type == ssl_client_hello_inner) {
871
0
    return true;
872
0
  }
873
874
0
  if (!CBB_add_u16(out, TLSEXT_TYPE_extended_master_secret) ||
875
0
      !CBB_add_u16(out, 0 /* length */)) {
876
0
    return false;
877
0
  }
878
879
0
  return true;
880
0
}
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
0
                                       ssl_client_hello_type_t type) {
946
0
  const SSL *const ssl = hs->ssl;
947
  // TLS 1.3 uses a different ticket extension.
948
0
  if (hs->min_version >= TLS1_3_VERSION || type == ssl_client_hello_inner ||
949
0
      SSL_get_options(ssl) & SSL_OP_NO_TICKET) {
950
0
    return true;
951
0
  }
952
953
0
  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
0
  if (!ssl->s3->initial_handshake_complete &&
960
0
      ssl->session != nullptr &&
961
0
      !ssl->session->ticket.empty() &&
962
      // Don't send TLS 1.3 session tickets in the ticket extension.
963
0
      ssl_session_protocol_version(ssl->session.get()) < TLS1_3_VERSION) {
964
0
    ticket = ssl->session->ticket;
965
0
  }
966
967
0
  CBB ticket_cbb;
968
0
  if (!CBB_add_u16(out, TLSEXT_TYPE_session_ticket) ||
969
0
      !CBB_add_u16_length_prefixed(out, &ticket_cbb) ||
970
0
      !CBB_add_bytes(&ticket_cbb, ticket.data(), ticket.size()) ||
971
0
      !CBB_flush(out)) {
972
0
    return false;
973
0
  }
974
975
0
  return true;
976
0
}
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
0
                                        ssl_client_hello_type_t type) {
1026
0
  if (hs->max_version < TLS1_2_VERSION) {
1027
0
    return true;
1028
0
  }
1029
1030
0
  CBB contents, sigalgs_cbb;
1031
0
  if (!CBB_add_u16(out_compressible, TLSEXT_TYPE_signature_algorithms) ||
1032
0
      !CBB_add_u16_length_prefixed(out_compressible, &contents) ||
1033
0
      !CBB_add_u16_length_prefixed(&contents, &sigalgs_cbb) ||
1034
0
      !tls12_add_verify_sigalgs(hs, &sigalgs_cbb) ||
1035
0
      !CBB_flush(out_compressible)) {
1036
0
    return false;
1037
0
  }
1038
1039
0
  return true;
1040
0
}
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
0
                                     ssl_client_hello_type_t type) {
1067
0
  if (!hs->config->ocsp_stapling_enabled) {
1068
0
    return true;
1069
0
  }
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 || hs->config->cert->ocsp_response == NULL ||
1132
0
      ssl->s3->session_reused ||
1133
0
      !ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
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
0
                                    ssl_client_hello_type_t type) {
1151
0
  const SSL *const ssl = hs->ssl;
1152
0
  if (ssl->ctx->next_proto_select_cb == NULL ||
1153
      // Do not allow NPN to change on renegotiation.
1154
0
      ssl->s3->initial_handshake_complete ||
1155
      // NPN is not defined in DTLS or TLS 1.3.
1156
0
      SSL_is_dtls(ssl) || hs->min_version >= TLS1_3_VERSION ||
1157
0
      type == ssl_client_hello_inner) {
1158
0
    return true;
1159
0
  }
1160
1161
0
  if (!CBB_add_u16(out, TLSEXT_TYPE_next_proto_neg) ||
1162
0
      !CBB_add_u16(out, 0 /* length */)) {
1163
0
    return false;
1164
0
  }
1165
1166
0
  return true;
1167
0
}
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
0
                                    ssl_client_hello_type_t type) {
1281
0
  if (!hs->config->signed_cert_timestamps_enabled) {
1282
0
    return true;
1283
0
  }
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
  // The extension shouldn't be sent when resuming sessions.
1349
0
  if (ssl_protocol_version(ssl) >= TLS1_3_VERSION || ssl->s3->session_reused ||
1350
0
      hs->config->cert->signed_cert_timestamp_list == NULL) {
1351
0
    return true;
1352
0
  }
1353
1354
0
  CBB contents;
1355
0
  return CBB_add_u16(out, TLSEXT_TYPE_certificate_timestamp) &&
1356
0
         CBB_add_u16_length_prefixed(out, &contents) &&
1357
0
         CBB_add_bytes(
1358
0
             &contents,
1359
0
             CRYPTO_BUFFER_data(
1360
0
                 hs->config->cert->signed_cert_timestamp_list.get()),
1361
0
             CRYPTO_BUFFER_len(
1362
0
                 hs->config->cert->signed_cert_timestamp_list.get())) &&
1363
0
         CBB_flush(out);
1364
0
}
1365
1366
1367
// Application-level Protocol Negotiation.
1368
//
1369
// https://tools.ietf.org/html/rfc7301
1370
1371
static bool ext_alpn_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1372
                                     CBB *out_compressible,
1373
0
                                     ssl_client_hello_type_t type) {
1374
0
  const SSL *const ssl = hs->ssl;
1375
0
  if (hs->config->alpn_client_proto_list.empty() && ssl->quic_method) {
1376
    // ALPN MUST be used with QUIC.
1377
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_NO_APPLICATION_PROTOCOL);
1378
0
    return false;
1379
0
  }
1380
1381
0
  if (hs->config->alpn_client_proto_list.empty() ||
1382
0
      ssl->s3->initial_handshake_complete) {
1383
0
    return true;
1384
0
  }
1385
1386
0
  CBB contents, proto_list;
1387
0
  if (!CBB_add_u16(out_compressible,
1388
0
                   TLSEXT_TYPE_application_layer_protocol_negotiation) ||
1389
0
      !CBB_add_u16_length_prefixed(out_compressible, &contents) ||
1390
0
      !CBB_add_u16_length_prefixed(&contents, &proto_list) ||
1391
0
      !CBB_add_bytes(&proto_list, hs->config->alpn_client_proto_list.data(),
1392
0
                     hs->config->alpn_client_proto_list.size()) ||
1393
0
      !CBB_flush(out_compressible)) {
1394
0
    return false;
1395
0
  }
1396
1397
0
  return true;
1398
0
}
1399
1400
static bool ext_alpn_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1401
0
                                       CBS *contents) {
1402
0
  SSL *const ssl = hs->ssl;
1403
0
  if (contents == NULL) {
1404
0
    if (ssl->quic_method) {
1405
      // ALPN is required when QUIC is used.
1406
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_NO_APPLICATION_PROTOCOL);
1407
0
      *out_alert = SSL_AD_NO_APPLICATION_PROTOCOL;
1408
0
      return false;
1409
0
    }
1410
0
    return true;
1411
0
  }
1412
1413
0
  assert(!ssl->s3->initial_handshake_complete);
1414
0
  assert(!hs->config->alpn_client_proto_list.empty());
1415
1416
0
  if (hs->next_proto_neg_seen) {
1417
    // NPN and ALPN may not be negotiated in the same connection.
1418
0
    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1419
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_NEGOTIATED_BOTH_NPN_AND_ALPN);
1420
0
    return false;
1421
0
  }
1422
1423
  // The extension data consists of a ProtocolNameList which must have
1424
  // exactly one ProtocolName. Each of these is length-prefixed.
1425
0
  CBS protocol_name_list, protocol_name;
1426
0
  if (!CBS_get_u16_length_prefixed(contents, &protocol_name_list) ||
1427
0
      CBS_len(contents) != 0 ||
1428
0
      !CBS_get_u8_length_prefixed(&protocol_name_list, &protocol_name) ||
1429
      // Empty protocol names are forbidden.
1430
0
      CBS_len(&protocol_name) == 0 ||
1431
0
      CBS_len(&protocol_name_list) != 0) {
1432
0
    return false;
1433
0
  }
1434
1435
0
  if (!ssl_is_alpn_protocol_allowed(hs, protocol_name)) {
1436
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_ALPN_PROTOCOL);
1437
0
    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1438
0
    return false;
1439
0
  }
1440
1441
0
  if (!ssl->s3->alpn_selected.CopyFrom(protocol_name)) {
1442
0
    *out_alert = SSL_AD_INTERNAL_ERROR;
1443
0
    return false;
1444
0
  }
1445
1446
0
  return true;
1447
0
}
1448
1449
0
bool ssl_is_valid_alpn_list(Span<const uint8_t> in) {
1450
0
  CBS protocol_name_list = in;
1451
0
  if (CBS_len(&protocol_name_list) == 0) {
1452
0
    return false;
1453
0
  }
1454
0
  while (CBS_len(&protocol_name_list) > 0) {
1455
0
    CBS protocol_name;
1456
0
    if (!CBS_get_u8_length_prefixed(&protocol_name_list, &protocol_name) ||
1457
        // Empty protocol names are forbidden.
1458
0
        CBS_len(&protocol_name) == 0) {
1459
0
      return false;
1460
0
    }
1461
0
  }
1462
0
  return true;
1463
0
}
1464
1465
bool ssl_is_alpn_protocol_allowed(const SSL_HANDSHAKE *hs,
1466
0
                                  Span<const uint8_t> protocol) {
1467
0
  if (hs->config->alpn_client_proto_list.empty()) {
1468
0
    return false;
1469
0
  }
1470
1471
0
  if (hs->ssl->ctx->allow_unknown_alpn_protos) {
1472
0
    return true;
1473
0
  }
1474
1475
  // Check that the protocol name is one of the ones we advertised.
1476
0
  CBS client_protocol_name_list =
1477
0
          MakeConstSpan(hs->config->alpn_client_proto_list),
1478
0
      client_protocol_name;
1479
0
  while (CBS_len(&client_protocol_name_list) > 0) {
1480
0
    if (!CBS_get_u8_length_prefixed(&client_protocol_name_list,
1481
0
                                    &client_protocol_name)) {
1482
0
      return false;
1483
0
    }
1484
1485
0
    if (client_protocol_name == protocol) {
1486
0
      return true;
1487
0
    }
1488
0
  }
1489
1490
0
  return false;
1491
0
}
1492
1493
bool ssl_negotiate_alpn(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1494
0
                        const SSL_CLIENT_HELLO *client_hello) {
1495
0
  SSL *const ssl = hs->ssl;
1496
0
  CBS contents;
1497
0
  if (ssl->ctx->alpn_select_cb == NULL ||
1498
0
      !ssl_client_hello_get_extension(
1499
0
          client_hello, &contents,
1500
0
          TLSEXT_TYPE_application_layer_protocol_negotiation)) {
1501
0
    if (ssl->quic_method) {
1502
      // ALPN is required when QUIC is used.
1503
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_NO_APPLICATION_PROTOCOL);
1504
0
      *out_alert = SSL_AD_NO_APPLICATION_PROTOCOL;
1505
0
      return false;
1506
0
    }
1507
    // Ignore ALPN if not configured or no extension was supplied.
1508
0
    return true;
1509
0
  }
1510
1511
  // ALPN takes precedence over NPN.
1512
0
  hs->next_proto_neg_seen = false;
1513
1514
0
  CBS protocol_name_list;
1515
0
  if (!CBS_get_u16_length_prefixed(&contents, &protocol_name_list) ||
1516
0
      CBS_len(&contents) != 0 ||
1517
0
      !ssl_is_valid_alpn_list(protocol_name_list)) {
1518
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
1519
0
    *out_alert = SSL_AD_DECODE_ERROR;
1520
0
    return false;
1521
0
  }
1522
1523
  // |protocol_name_list| fits in |unsigned| because TLS extensions use 16-bit
1524
  // lengths.
1525
0
  const uint8_t *selected;
1526
0
  uint8_t selected_len;
1527
0
  int ret = ssl->ctx->alpn_select_cb(
1528
0
      ssl, &selected, &selected_len, CBS_data(&protocol_name_list),
1529
0
      static_cast<unsigned>(CBS_len(&protocol_name_list)),
1530
0
      ssl->ctx->alpn_select_cb_arg);
1531
  // ALPN is required when QUIC is used.
1532
0
  if (ssl->quic_method &&
1533
0
      (ret == SSL_TLSEXT_ERR_NOACK || ret == SSL_TLSEXT_ERR_ALERT_WARNING)) {
1534
0
    ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1535
0
  }
1536
0
  switch (ret) {
1537
0
    case SSL_TLSEXT_ERR_OK:
1538
0
      if (selected_len == 0) {
1539
0
        OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_ALPN_PROTOCOL);
1540
0
        *out_alert = SSL_AD_INTERNAL_ERROR;
1541
0
        return false;
1542
0
      }
1543
0
      if (!ssl->s3->alpn_selected.CopyFrom(
1544
0
              MakeConstSpan(selected, selected_len))) {
1545
0
        *out_alert = SSL_AD_INTERNAL_ERROR;
1546
0
        return false;
1547
0
      }
1548
0
      break;
1549
0
    case SSL_TLSEXT_ERR_NOACK:
1550
0
    case SSL_TLSEXT_ERR_ALERT_WARNING:
1551
0
      break;
1552
0
    case SSL_TLSEXT_ERR_ALERT_FATAL:
1553
0
      *out_alert = SSL_AD_NO_APPLICATION_PROTOCOL;
1554
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_NO_APPLICATION_PROTOCOL);
1555
0
      return false;
1556
0
    default:
1557
      // Invalid return value.
1558
0
      *out_alert = SSL_AD_INTERNAL_ERROR;
1559
0
      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1560
0
      return false;
1561
0
  }
1562
1563
0
  return true;
1564
0
}
1565
1566
0
static bool ext_alpn_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1567
0
  SSL *const ssl = hs->ssl;
1568
0
  if (ssl->s3->alpn_selected.empty()) {
1569
0
    return true;
1570
0
  }
1571
1572
0
  CBB contents, proto_list, proto;
1573
0
  if (!CBB_add_u16(out, TLSEXT_TYPE_application_layer_protocol_negotiation) ||
1574
0
      !CBB_add_u16_length_prefixed(out, &contents) ||
1575
0
      !CBB_add_u16_length_prefixed(&contents, &proto_list) ||
1576
0
      !CBB_add_u8_length_prefixed(&proto_list, &proto) ||
1577
0
      !CBB_add_bytes(&proto, ssl->s3->alpn_selected.data(),
1578
0
                     ssl->s3->alpn_selected.size()) ||
1579
0
      !CBB_flush(out)) {
1580
0
    return false;
1581
0
  }
1582
1583
0
  return true;
1584
0
}
1585
1586
1587
// Channel ID.
1588
//
1589
// https://tools.ietf.org/html/draft-balfanz-tls-channelid-01
1590
1591
static bool ext_channel_id_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1592
                                           CBB *out_compressible,
1593
0
                                           ssl_client_hello_type_t type) {
1594
0
  const SSL *const ssl = hs->ssl;
1595
0
  if (!hs->config->channel_id_private || SSL_is_dtls(ssl) ||
1596
      // Don't offer Channel ID in ClientHelloOuter. ClientHelloOuter handshakes
1597
      // are not authenticated for the name that can learn the Channel ID.
1598
      //
1599
      // We could alternatively offer the extension but sign with a random key.
1600
      // For other extensions, we try to align |ssl_client_hello_outer| and
1601
      // |ssl_client_hello_unencrypted|, to improve the effectiveness of ECH
1602
      // GREASE. However, Channel ID is deprecated and unlikely to be used with
1603
      // ECH, so do the simplest thing.
1604
0
      type == ssl_client_hello_outer) {
1605
0
    return true;
1606
0
  }
1607
1608
0
  if (!CBB_add_u16(out, TLSEXT_TYPE_channel_id) ||
1609
0
      !CBB_add_u16(out, 0 /* length */)) {
1610
0
    return false;
1611
0
  }
1612
1613
0
  return true;
1614
0
}
1615
1616
static bool ext_channel_id_parse_serverhello(SSL_HANDSHAKE *hs,
1617
                                             uint8_t *out_alert,
1618
0
                                             CBS *contents) {
1619
0
  if (contents == NULL) {
1620
0
    return true;
1621
0
  }
1622
1623
0
  assert(!SSL_is_dtls(hs->ssl));
1624
0
  assert(hs->config->channel_id_private);
1625
1626
0
  if (CBS_len(contents) != 0) {
1627
0
    return false;
1628
0
  }
1629
1630
0
  hs->channel_id_negotiated = true;
1631
0
  return true;
1632
0
}
1633
1634
static bool ext_channel_id_parse_clienthello(SSL_HANDSHAKE *hs,
1635
                                             uint8_t *out_alert,
1636
0
                                             CBS *contents) {
1637
0
  SSL *const ssl = hs->ssl;
1638
0
  if (contents == NULL || !hs->config->channel_id_enabled || SSL_is_dtls(ssl)) {
1639
0
    return true;
1640
0
  }
1641
1642
0
  if (CBS_len(contents) != 0) {
1643
0
    return false;
1644
0
  }
1645
1646
0
  hs->channel_id_negotiated = true;
1647
0
  return true;
1648
0
}
1649
1650
0
static bool ext_channel_id_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1651
0
  if (!hs->channel_id_negotiated) {
1652
0
    return true;
1653
0
  }
1654
1655
0
  if (!CBB_add_u16(out, TLSEXT_TYPE_channel_id) ||
1656
0
      !CBB_add_u16(out, 0 /* length */)) {
1657
0
    return false;
1658
0
  }
1659
1660
0
  return true;
1661
0
}
1662
1663
1664
// Secure Real-time Transport Protocol (SRTP) extension.
1665
//
1666
// https://tools.ietf.org/html/rfc5764
1667
1668
static bool ext_srtp_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1669
                                     CBB *out_compressible,
1670
0
                                     ssl_client_hello_type_t type) {
1671
0
  const SSL *const ssl = hs->ssl;
1672
0
  const STACK_OF(SRTP_PROTECTION_PROFILE) *profiles =
1673
0
      SSL_get_srtp_profiles(ssl);
1674
0
  if (profiles == NULL ||
1675
0
      sk_SRTP_PROTECTION_PROFILE_num(profiles) == 0 ||
1676
0
      !SSL_is_dtls(ssl)) {
1677
0
    return true;
1678
0
  }
1679
1680
0
  CBB contents, profile_ids;
1681
0
  if (!CBB_add_u16(out_compressible, TLSEXT_TYPE_srtp) ||
1682
0
      !CBB_add_u16_length_prefixed(out_compressible, &contents) ||
1683
0
      !CBB_add_u16_length_prefixed(&contents, &profile_ids)) {
1684
0
    return false;
1685
0
  }
1686
1687
0
  for (const SRTP_PROTECTION_PROFILE *profile : profiles) {
1688
0
    if (!CBB_add_u16(&profile_ids, profile->id)) {
1689
0
      return false;
1690
0
    }
1691
0
  }
1692
1693
0
  if (!CBB_add_u8(&contents, 0 /* empty use_mki value */) ||
1694
0
      !CBB_flush(out_compressible)) {
1695
0
    return false;
1696
0
  }
1697
1698
0
  return true;
1699
0
}
1700
1701
static bool ext_srtp_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1702
0
                                       CBS *contents) {
1703
0
  SSL *const ssl = hs->ssl;
1704
0
  if (contents == NULL) {
1705
0
    return true;
1706
0
  }
1707
1708
  // The extension consists of a u16-prefixed profile ID list containing a
1709
  // single uint16_t profile ID, then followed by a u8-prefixed srtp_mki field.
1710
  //
1711
  // See https://tools.ietf.org/html/rfc5764#section-4.1.1
1712
0
  assert(SSL_is_dtls(ssl));
1713
0
  CBS profile_ids, srtp_mki;
1714
0
  uint16_t profile_id;
1715
0
  if (!CBS_get_u16_length_prefixed(contents, &profile_ids) ||
1716
0
      !CBS_get_u16(&profile_ids, &profile_id) ||
1717
0
      CBS_len(&profile_ids) != 0 ||
1718
0
      !CBS_get_u8_length_prefixed(contents, &srtp_mki) ||
1719
0
      CBS_len(contents) != 0) {
1720
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
1721
0
    return false;
1722
0
  }
1723
1724
0
  if (CBS_len(&srtp_mki) != 0) {
1725
    // Must be no MKI, since we never offer one.
1726
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_MKI_VALUE);
1727
0
    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1728
0
    return false;
1729
0
  }
1730
1731
  // Check to see if the server gave us something we support and offered.
1732
0
  for (const SRTP_PROTECTION_PROFILE *profile : SSL_get_srtp_profiles(ssl)) {
1733
0
    if (profile->id == profile_id) {
1734
0
      ssl->s3->srtp_profile = profile;
1735
0
      return true;
1736
0
    }
1737
0
  }
1738
1739
0
  OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
1740
0
  *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1741
0
  return false;
1742
0
}
1743
1744
static bool ext_srtp_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1745
0
                                       CBS *contents) {
1746
0
  SSL *const ssl = hs->ssl;
1747
  // DTLS-SRTP is only defined for DTLS.
1748
0
  if (contents == NULL || !SSL_is_dtls(ssl)) {
1749
0
    return true;
1750
0
  }
1751
1752
0
  CBS profile_ids, srtp_mki;
1753
0
  if (!CBS_get_u16_length_prefixed(contents, &profile_ids) ||
1754
0
      CBS_len(&profile_ids) < 2 ||
1755
0
      !CBS_get_u8_length_prefixed(contents, &srtp_mki) ||
1756
0
      CBS_len(contents) != 0) {
1757
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
1758
0
    return false;
1759
0
  }
1760
  // Discard the MKI value for now.
1761
1762
0
  const STACK_OF(SRTP_PROTECTION_PROFILE) *server_profiles =
1763
0
      SSL_get_srtp_profiles(ssl);
1764
1765
  // Pick the server's most preferred profile.
1766
0
  for (const SRTP_PROTECTION_PROFILE *server_profile : server_profiles) {
1767
0
    CBS profile_ids_tmp;
1768
0
    CBS_init(&profile_ids_tmp, CBS_data(&profile_ids), CBS_len(&profile_ids));
1769
1770
0
    while (CBS_len(&profile_ids_tmp) > 0) {
1771
0
      uint16_t profile_id;
1772
0
      if (!CBS_get_u16(&profile_ids_tmp, &profile_id)) {
1773
0
        return false;
1774
0
      }
1775
1776
0
      if (server_profile->id == profile_id) {
1777
0
        ssl->s3->srtp_profile = server_profile;
1778
0
        return true;
1779
0
      }
1780
0
    }
1781
0
  }
1782
1783
0
  return true;
1784
0
}
1785
1786
0
static bool ext_srtp_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1787
0
  SSL *const ssl = hs->ssl;
1788
0
  if (ssl->s3->srtp_profile == NULL) {
1789
0
    return true;
1790
0
  }
1791
1792
0
  assert(SSL_is_dtls(ssl));
1793
0
  CBB contents, profile_ids;
1794
0
  if (!CBB_add_u16(out, TLSEXT_TYPE_srtp) ||
1795
0
      !CBB_add_u16_length_prefixed(out, &contents) ||
1796
0
      !CBB_add_u16_length_prefixed(&contents, &profile_ids) ||
1797
0
      !CBB_add_u16(&profile_ids, ssl->s3->srtp_profile->id) ||
1798
0
      !CBB_add_u8(&contents, 0 /* empty MKI */) ||
1799
0
      !CBB_flush(out)) {
1800
0
    return false;
1801
0
  }
1802
1803
0
  return true;
1804
0
}
1805
1806
1807
// EC point formats.
1808
//
1809
// https://tools.ietf.org/html/rfc4492#section-5.1.2
1810
1811
0
static bool ext_ec_point_add_extension(const SSL_HANDSHAKE *hs, CBB *out) {
1812
0
  CBB contents, formats;
1813
0
  if (!CBB_add_u16(out, TLSEXT_TYPE_ec_point_formats) ||
1814
0
      !CBB_add_u16_length_prefixed(out, &contents) ||
1815
0
      !CBB_add_u8_length_prefixed(&contents, &formats) ||
1816
0
      !CBB_add_u8(&formats, TLSEXT_ECPOINTFORMAT_uncompressed) ||
1817
0
      !CBB_flush(out)) {
1818
0
    return false;
1819
0
  }
1820
1821
0
  return true;
1822
0
}
1823
1824
static bool ext_ec_point_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
1825
                                         CBB *out_compressible,
1826
0
                                         ssl_client_hello_type_t type) {
1827
  // The point format extension is unnecessary in TLS 1.3.
1828
0
  if (hs->min_version >= TLS1_3_VERSION || type == ssl_client_hello_inner) {
1829
0
    return true;
1830
0
  }
1831
1832
0
  return ext_ec_point_add_extension(hs, out);
1833
0
}
1834
1835
static bool ext_ec_point_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1836
0
                                           CBS *contents) {
1837
0
  if (contents == NULL) {
1838
0
    return true;
1839
0
  }
1840
1841
0
  if (ssl_protocol_version(hs->ssl) >= TLS1_3_VERSION) {
1842
0
    return false;
1843
0
  }
1844
1845
0
  CBS ec_point_format_list;
1846
0
  if (!CBS_get_u8_length_prefixed(contents, &ec_point_format_list) ||
1847
0
      CBS_len(contents) != 0) {
1848
0
    return false;
1849
0
  }
1850
1851
  // Per RFC 4492, section 5.1.2, implementations MUST support the uncompressed
1852
  // point format.
1853
0
  if (OPENSSL_memchr(CBS_data(&ec_point_format_list),
1854
0
                     TLSEXT_ECPOINTFORMAT_uncompressed,
1855
0
                     CBS_len(&ec_point_format_list)) == NULL) {
1856
0
    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1857
0
    return false;
1858
0
  }
1859
1860
0
  return true;
1861
0
}
1862
1863
static bool ext_ec_point_parse_clienthello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1864
0
                                          CBS *contents) {
1865
0
  if (ssl_protocol_version(hs->ssl) >= TLS1_3_VERSION) {
1866
0
    return true;
1867
0
  }
1868
1869
0
  return ext_ec_point_parse_serverhello(hs, out_alert, contents);
1870
0
}
1871
1872
0
static bool ext_ec_point_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
1873
0
  SSL *const ssl = hs->ssl;
1874
0
  if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1875
0
    return true;
1876
0
  }
1877
1878
0
  const uint32_t alg_k = hs->new_cipher->algorithm_mkey;
1879
0
  const uint32_t alg_a = hs->new_cipher->algorithm_auth;
1880
0
  const bool using_ecc = (alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA);
1881
1882
0
  if (!using_ecc) {
1883
0
    return true;
1884
0
  }
1885
1886
0
  return ext_ec_point_add_extension(hs, out);
1887
0
}
1888
1889
1890
// Pre Shared Key
1891
//
1892
// https://tools.ietf.org/html/rfc8446#section-4.2.11
1893
1894
static bool should_offer_psk(const SSL_HANDSHAKE *hs,
1895
0
                             ssl_client_hello_type_t type) {
1896
0
  const SSL *const ssl = hs->ssl;
1897
0
  if (hs->max_version < TLS1_3_VERSION || ssl->session == nullptr ||
1898
0
      ssl_session_protocol_version(ssl->session.get()) < TLS1_3_VERSION ||
1899
      // TODO(https://crbug.com/boringssl/275): Should we synthesize a
1900
      // placeholder PSK, at least when we offer early data? Otherwise
1901
      // ClientHelloOuter will contain an early_data extension without a
1902
      // pre_shared_key extension and potentially break the recovery flow.
1903
0
      type == ssl_client_hello_outer) {
1904
0
    return false;
1905
0
  }
1906
1907
  // Per RFC 8446 section 4.1.4, skip offering the session if the selected
1908
  // cipher in HelloRetryRequest does not match. This avoids performing the
1909
  // transcript hash transformation for multiple hashes.
1910
0
  if (ssl->s3->used_hello_retry_request &&
1911
0
      ssl->session->cipher->algorithm_prf != hs->new_cipher->algorithm_prf) {
1912
0
    return false;
1913
0
  }
1914
1915
0
  return true;
1916
0
}
1917
1918
static size_t ext_pre_shared_key_clienthello_length(
1919
0
    const SSL_HANDSHAKE *hs, ssl_client_hello_type_t type) {
1920
0
  const SSL *const ssl = hs->ssl;
1921
0
  if (!should_offer_psk(hs, type)) {
1922
0
    return 0;
1923
0
  }
1924
1925
0
  size_t binder_len = EVP_MD_size(ssl_session_get_digest(ssl->session.get()));
1926
0
  return 15 + ssl->session->ticket.size() + binder_len;
1927
0
}
1928
1929
static bool ext_pre_shared_key_add_clienthello(const SSL_HANDSHAKE *hs,
1930
                                               CBB *out, bool *out_needs_binder,
1931
0
                                               ssl_client_hello_type_t type) {
1932
0
  const SSL *const ssl = hs->ssl;
1933
0
  *out_needs_binder = false;
1934
0
  if (!should_offer_psk(hs, type)) {
1935
0
    return true;
1936
0
  }
1937
1938
0
  struct OPENSSL_timeval now;
1939
0
  ssl_get_current_time(ssl, &now);
1940
0
  uint32_t ticket_age = 1000 * (now.tv_sec - ssl->session->time);
1941
0
  uint32_t obfuscated_ticket_age = ticket_age + ssl->session->ticket_age_add;
1942
1943
  // Fill in a placeholder zero binder of the appropriate length. It will be
1944
  // computed and filled in later after length prefixes are computed.
1945
0
  size_t binder_len = EVP_MD_size(ssl_session_get_digest(ssl->session.get()));
1946
1947
0
  CBB contents, identity, ticket, binders, binder;
1948
0
  if (!CBB_add_u16(out, TLSEXT_TYPE_pre_shared_key) ||
1949
0
      !CBB_add_u16_length_prefixed(out, &contents) ||
1950
0
      !CBB_add_u16_length_prefixed(&contents, &identity) ||
1951
0
      !CBB_add_u16_length_prefixed(&identity, &ticket) ||
1952
0
      !CBB_add_bytes(&ticket, ssl->session->ticket.data(),
1953
0
                     ssl->session->ticket.size()) ||
1954
0
      !CBB_add_u32(&identity, obfuscated_ticket_age) ||
1955
0
      !CBB_add_u16_length_prefixed(&contents, &binders) ||
1956
0
      !CBB_add_u8_length_prefixed(&binders, &binder) ||
1957
0
      !CBB_add_zeros(&binder, binder_len)) {
1958
0
    return false;
1959
0
  }
1960
1961
0
  *out_needs_binder = true;
1962
0
  return CBB_flush(out);
1963
0
}
1964
1965
bool ssl_ext_pre_shared_key_parse_serverhello(SSL_HANDSHAKE *hs,
1966
                                              uint8_t *out_alert,
1967
0
                                              CBS *contents) {
1968
0
  uint16_t psk_id;
1969
0
  if (!CBS_get_u16(contents, &psk_id) ||
1970
0
      CBS_len(contents) != 0) {
1971
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1972
0
    *out_alert = SSL_AD_DECODE_ERROR;
1973
0
    return false;
1974
0
  }
1975
1976
  // We only advertise one PSK identity, so the only legal index is zero.
1977
0
  if (psk_id != 0) {
1978
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
1979
0
    *out_alert = SSL_AD_UNKNOWN_PSK_IDENTITY;
1980
0
    return false;
1981
0
  }
1982
1983
0
  return true;
1984
0
}
1985
1986
bool ssl_ext_pre_shared_key_parse_clienthello(
1987
    SSL_HANDSHAKE *hs, CBS *out_ticket, CBS *out_binders,
1988
    uint32_t *out_obfuscated_ticket_age, uint8_t *out_alert,
1989
0
    const SSL_CLIENT_HELLO *client_hello, CBS *contents) {
1990
  // Verify that the pre_shared_key extension is the last extension in
1991
  // ClientHello.
1992
0
  if (CBS_data(contents) + CBS_len(contents) !=
1993
0
      client_hello->extensions + client_hello->extensions_len) {
1994
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_PRE_SHARED_KEY_MUST_BE_LAST);
1995
0
    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
1996
0
    return false;
1997
0
  }
1998
1999
  // We only process the first PSK identity since we don't support pure PSK.
2000
0
  CBS identities, binders;
2001
0
  if (!CBS_get_u16_length_prefixed(contents, &identities) ||
2002
0
      !CBS_get_u16_length_prefixed(&identities, out_ticket) ||
2003
0
      !CBS_get_u32(&identities, out_obfuscated_ticket_age) ||
2004
0
      !CBS_get_u16_length_prefixed(contents, &binders) ||
2005
0
      CBS_len(&binders) == 0 ||
2006
0
      CBS_len(contents) != 0) {
2007
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2008
0
    *out_alert = SSL_AD_DECODE_ERROR;
2009
0
    return false;
2010
0
  }
2011
2012
0
  *out_binders = binders;
2013
2014
  // Check the syntax of the remaining identities, but do not process them.
2015
0
  size_t num_identities = 1;
2016
0
  while (CBS_len(&identities) != 0) {
2017
0
    CBS unused_ticket;
2018
0
    uint32_t unused_obfuscated_ticket_age;
2019
0
    if (!CBS_get_u16_length_prefixed(&identities, &unused_ticket) ||
2020
0
        !CBS_get_u32(&identities, &unused_obfuscated_ticket_age)) {
2021
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2022
0
      *out_alert = SSL_AD_DECODE_ERROR;
2023
0
      return false;
2024
0
    }
2025
2026
0
    num_identities++;
2027
0
  }
2028
2029
  // Check the syntax of the binders. The value will be checked later if
2030
  // resuming.
2031
0
  size_t num_binders = 0;
2032
0
  while (CBS_len(&binders) != 0) {
2033
0
    CBS binder;
2034
0
    if (!CBS_get_u8_length_prefixed(&binders, &binder)) {
2035
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2036
0
      *out_alert = SSL_AD_DECODE_ERROR;
2037
0
      return false;
2038
0
    }
2039
2040
0
    num_binders++;
2041
0
  }
2042
2043
0
  if (num_identities != num_binders) {
2044
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_BINDER_COUNT_MISMATCH);
2045
0
    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
2046
0
    return false;
2047
0
  }
2048
2049
0
  return true;
2050
0
}
2051
2052
0
bool ssl_ext_pre_shared_key_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
2053
0
  if (!hs->ssl->s3->session_reused) {
2054
0
    return true;
2055
0
  }
2056
2057
0
  CBB contents;
2058
0
  if (!CBB_add_u16(out, TLSEXT_TYPE_pre_shared_key) ||
2059
0
      !CBB_add_u16_length_prefixed(out, &contents) ||
2060
      // We only consider the first identity for resumption
2061
0
      !CBB_add_u16(&contents, 0) ||
2062
0
      !CBB_flush(out)) {
2063
0
    return false;
2064
0
  }
2065
2066
0
  return true;
2067
0
}
2068
2069
2070
// Pre-Shared Key Exchange Modes
2071
//
2072
// https://tools.ietf.org/html/rfc8446#section-4.2.9
2073
2074
static bool ext_psk_key_exchange_modes_add_clienthello(
2075
    const SSL_HANDSHAKE *hs, CBB *out, CBB *out_compressible,
2076
0
    ssl_client_hello_type_t type) {
2077
0
  if (hs->max_version < TLS1_3_VERSION) {
2078
0
    return true;
2079
0
  }
2080
2081
0
  CBB contents, ke_modes;
2082
0
  if (!CBB_add_u16(out_compressible, TLSEXT_TYPE_psk_key_exchange_modes) ||
2083
0
      !CBB_add_u16_length_prefixed(out_compressible, &contents) ||
2084
0
      !CBB_add_u8_length_prefixed(&contents, &ke_modes) ||
2085
0
      !CBB_add_u8(&ke_modes, SSL_PSK_DHE_KE)) {
2086
0
    return false;
2087
0
  }
2088
2089
0
  return CBB_flush(out_compressible);
2090
0
}
2091
2092
static bool ext_psk_key_exchange_modes_parse_clienthello(SSL_HANDSHAKE *hs,
2093
                                                         uint8_t *out_alert,
2094
0
                                                         CBS *contents) {
2095
0
  if (contents == NULL) {
2096
0
    return true;
2097
0
  }
2098
2099
0
  CBS ke_modes;
2100
0
  if (!CBS_get_u8_length_prefixed(contents, &ke_modes) ||
2101
0
      CBS_len(&ke_modes) == 0 ||
2102
0
      CBS_len(contents) != 0) {
2103
0
    *out_alert = SSL_AD_DECODE_ERROR;
2104
0
    return false;
2105
0
  }
2106
2107
  // We only support tickets with PSK_DHE_KE.
2108
0
  hs->accept_psk_mode = OPENSSL_memchr(CBS_data(&ke_modes), SSL_PSK_DHE_KE,
2109
0
                                       CBS_len(&ke_modes)) != NULL;
2110
2111
0
  return true;
2112
0
}
2113
2114
2115
// Early Data Indication
2116
//
2117
// https://tools.ietf.org/html/rfc8446#section-4.2.10
2118
2119
static bool ext_early_data_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
2120
                                           CBB *out_compressible,
2121
0
                                           ssl_client_hello_type_t type) {
2122
0
  const SSL *const ssl = hs->ssl;
2123
  // The second ClientHello never offers early data, and we must have already
2124
  // filled in |early_data_reason| by this point.
2125
0
  if (ssl->s3->used_hello_retry_request) {
2126
0
    assert(ssl->s3->early_data_reason != ssl_early_data_unknown);
2127
0
    return true;
2128
0
  }
2129
2130
0
  if (!hs->early_data_offered) {
2131
0
    return true;
2132
0
  }
2133
2134
  // If offering ECH, the extension only applies to ClientHelloInner, but we
2135
  // send the extension in both ClientHellos. This ensures that, if the server
2136
  // handshakes with ClientHelloOuter, it can skip past early data. See
2137
  // draft-ietf-tls-esni-13, section 6.1.
2138
0
  if (!CBB_add_u16(out_compressible, TLSEXT_TYPE_early_data) ||
2139
0
      !CBB_add_u16(out_compressible, 0) ||
2140
0
      !CBB_flush(out_compressible)) {
2141
0
    return false;
2142
0
  }
2143
2144
0
  return true;
2145
0
}
2146
2147
static bool ext_early_data_parse_serverhello(SSL_HANDSHAKE *hs,
2148
                                             uint8_t *out_alert,
2149
0
                                             CBS *contents) {
2150
0
  SSL *const ssl = hs->ssl;
2151
0
  if (contents == NULL) {
2152
0
    if (hs->early_data_offered && !ssl->s3->used_hello_retry_request) {
2153
0
      ssl->s3->early_data_reason = ssl->s3->session_reused
2154
0
                                       ? ssl_early_data_peer_declined
2155
0
                                       : ssl_early_data_session_not_resumed;
2156
0
    } else {
2157
      // We already filled in |early_data_reason| when declining to offer 0-RTT
2158
      // or handling the implicit HelloRetryRequest reject.
2159
0
      assert(ssl->s3->early_data_reason != ssl_early_data_unknown);
2160
0
    }
2161
0
    return true;
2162
0
  }
2163
2164
  // If we received an HRR, the second ClientHello never offers early data, so
2165
  // the extensions logic will automatically reject early data extensions as
2166
  // unsolicited. This covered by the ServerAcceptsEarlyDataOnHRR test.
2167
0
  assert(!ssl->s3->used_hello_retry_request);
2168
2169
0
  if (CBS_len(contents) != 0) {
2170
0
    *out_alert = SSL_AD_DECODE_ERROR;
2171
0
    return false;
2172
0
  }
2173
2174
0
  if (!ssl->s3->session_reused) {
2175
0
    *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
2176
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
2177
0
    return false;
2178
0
  }
2179
2180
0
  ssl->s3->early_data_reason = ssl_early_data_accepted;
2181
0
  ssl->s3->early_data_accepted = true;
2182
0
  return true;
2183
0
}
2184
2185
static bool ext_early_data_parse_clienthello(SSL_HANDSHAKE *hs,
2186
0
                                             uint8_t *out_alert, CBS *contents) {
2187
0
  SSL *const ssl = hs->ssl;
2188
0
  if (contents == NULL ||
2189
0
      ssl_protocol_version(ssl) < TLS1_3_VERSION) {
2190
0
    return true;
2191
0
  }
2192
2193
0
  if (CBS_len(contents) != 0) {
2194
0
    *out_alert = SSL_AD_DECODE_ERROR;
2195
0
    return false;
2196
0
  }
2197
2198
0
  hs->early_data_offered = true;
2199
0
  return true;
2200
0
}
2201
2202
0
static bool ext_early_data_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
2203
0
  if (!hs->ssl->s3->early_data_accepted) {
2204
0
    return true;
2205
0
  }
2206
2207
0
  if (!CBB_add_u16(out, TLSEXT_TYPE_early_data) ||
2208
0
      !CBB_add_u16(out, 0) ||
2209
0
      !CBB_flush(out)) {
2210
0
    return false;
2211
0
  }
2212
2213
0
  return true;
2214
0
}
2215
2216
2217
// Key Share
2218
//
2219
// https://tools.ietf.org/html/rfc8446#section-4.2.8
2220
2221
0
bool ssl_setup_key_shares(SSL_HANDSHAKE *hs, uint16_t override_group_id) {
2222
0
  SSL *const ssl = hs->ssl;
2223
0
  hs->key_shares[0].reset();
2224
0
  hs->key_shares[1].reset();
2225
0
  hs->key_share_bytes.Reset();
2226
2227
0
  if (hs->max_version < TLS1_3_VERSION) {
2228
0
    return true;
2229
0
  }
2230
2231
0
  bssl::ScopedCBB cbb;
2232
0
  if (!CBB_init(cbb.get(), 64)) {
2233
0
    return false;
2234
0
  }
2235
2236
0
  if (override_group_id == 0 && ssl->ctx->grease_enabled) {
2237
    // Add a fake group. See RFC 8701.
2238
0
    if (!CBB_add_u16(cbb.get(), ssl_get_grease_value(hs, ssl_grease_group)) ||
2239
0
        !CBB_add_u16(cbb.get(), 1 /* length */) ||
2240
0
        !CBB_add_u8(cbb.get(), 0 /* one byte key share */)) {
2241
0
      return false;
2242
0
    }
2243
0
  }
2244
2245
0
  uint16_t group_id = override_group_id;
2246
0
  uint16_t second_group_id = 0;
2247
0
  if (override_group_id == 0) {
2248
    // Predict the most preferred group.
2249
0
    Span<const uint16_t> groups = tls1_get_grouplist(hs);
2250
0
    if (groups.empty()) {
2251
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_NO_GROUPS_SPECIFIED);
2252
0
      return false;
2253
0
    }
2254
2255
0
    group_id = groups[0];
2256
2257
    // We'll try to include one post-quantum and one classical initial key
2258
    // share.
2259
0
    for (size_t i = 1; i < groups.size() && second_group_id == 0; i++) {
2260
0
      if (is_post_quantum_group(group_id) != is_post_quantum_group(groups[i])) {
2261
0
        second_group_id = groups[i];
2262
0
        assert(second_group_id != group_id);
2263
0
      }
2264
0
    }
2265
0
  }
2266
2267
0
  CBB key_exchange;
2268
0
  hs->key_shares[0] = SSLKeyShare::Create(group_id);
2269
0
  if (!hs->key_shares[0] ||  //
2270
0
      !CBB_add_u16(cbb.get(), group_id) ||
2271
0
      !CBB_add_u16_length_prefixed(cbb.get(), &key_exchange) ||
2272
0
      !hs->key_shares[0]->Generate(&key_exchange)) {
2273
0
    return false;
2274
0
  }
2275
2276
0
  if (second_group_id != 0) {
2277
0
    hs->key_shares[1] = SSLKeyShare::Create(second_group_id);
2278
0
    if (!hs->key_shares[1] ||  //
2279
0
        !CBB_add_u16(cbb.get(), second_group_id) ||
2280
0
        !CBB_add_u16_length_prefixed(cbb.get(), &key_exchange) ||
2281
0
        !hs->key_shares[1]->Generate(&key_exchange)) {
2282
0
      return false;
2283
0
    }
2284
0
  }
2285
2286
0
  return CBBFinishArray(cbb.get(), &hs->key_share_bytes);
2287
0
}
2288
2289
static bool ext_key_share_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
2290
                                          CBB *out_compressible,
2291
0
                                          ssl_client_hello_type_t type) {
2292
0
  if (hs->max_version < TLS1_3_VERSION) {
2293
0
    return true;
2294
0
  }
2295
2296
0
  assert(!hs->key_share_bytes.empty());
2297
0
  CBB contents, kse_bytes;
2298
0
  if (!CBB_add_u16(out_compressible, TLSEXT_TYPE_key_share) ||
2299
0
      !CBB_add_u16_length_prefixed(out_compressible, &contents) ||
2300
0
      !CBB_add_u16_length_prefixed(&contents, &kse_bytes) ||
2301
0
      !CBB_add_bytes(&kse_bytes, hs->key_share_bytes.data(),
2302
0
                     hs->key_share_bytes.size()) ||
2303
0
      !CBB_flush(out_compressible)) {
2304
0
    return false;
2305
0
  }
2306
2307
0
  return true;
2308
0
}
2309
2310
bool ssl_ext_key_share_parse_serverhello(SSL_HANDSHAKE *hs,
2311
                                         Array<uint8_t> *out_secret,
2312
0
                                         uint8_t *out_alert, CBS *contents) {
2313
0
  CBS ciphertext;
2314
0
  uint16_t group_id;
2315
0
  if (!CBS_get_u16(contents, &group_id) ||
2316
0
      !CBS_get_u16_length_prefixed(contents, &ciphertext) ||
2317
0
      CBS_len(contents) != 0) {
2318
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2319
0
    *out_alert = SSL_AD_DECODE_ERROR;
2320
0
    return false;
2321
0
  }
2322
2323
0
  SSLKeyShare *key_share = hs->key_shares[0].get();
2324
0
  if (key_share->GroupID() != group_id) {
2325
0
    if (!hs->key_shares[1] || hs->key_shares[1]->GroupID() != group_id) {
2326
0
      *out_alert = SSL_AD_ILLEGAL_PARAMETER;
2327
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
2328
0
      return false;
2329
0
    }
2330
0
    key_share = hs->key_shares[1].get();
2331
0
  }
2332
2333
0
  if (!key_share->Decap(out_secret, out_alert, ciphertext)) {
2334
0
    *out_alert = SSL_AD_INTERNAL_ERROR;
2335
0
    return false;
2336
0
  }
2337
2338
0
  hs->new_session->group_id = group_id;
2339
0
  hs->key_shares[0].reset();
2340
0
  hs->key_shares[1].reset();
2341
0
  return true;
2342
0
}
2343
2344
bool ssl_ext_key_share_parse_clienthello(SSL_HANDSHAKE *hs, bool *out_found,
2345
                                         Span<const uint8_t> *out_peer_key,
2346
                                         uint8_t *out_alert,
2347
0
                                         const SSL_CLIENT_HELLO *client_hello) {
2348
  // We only support connections that include an ECDHE key exchange.
2349
0
  CBS contents;
2350
0
  if (!ssl_client_hello_get_extension(client_hello, &contents,
2351
0
                                      TLSEXT_TYPE_key_share)) {
2352
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_KEY_SHARE);
2353
0
    *out_alert = SSL_AD_MISSING_EXTENSION;
2354
0
    return false;
2355
0
  }
2356
2357
0
  CBS key_shares;
2358
0
  if (!CBS_get_u16_length_prefixed(&contents, &key_shares) ||
2359
0
      CBS_len(&contents) != 0) {
2360
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2361
0
    return false;
2362
0
  }
2363
2364
  // Find the corresponding key share.
2365
0
  const uint16_t group_id = hs->new_session->group_id;
2366
0
  CBS peer_key;
2367
0
  CBS_init(&peer_key, nullptr, 0);
2368
0
  while (CBS_len(&key_shares) > 0) {
2369
0
    uint16_t id;
2370
0
    CBS peer_key_tmp;
2371
0
    if (!CBS_get_u16(&key_shares, &id) ||
2372
0
        !CBS_get_u16_length_prefixed(&key_shares, &peer_key_tmp) ||
2373
0
        CBS_len(&peer_key_tmp) == 0) {
2374
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2375
0
      return false;
2376
0
    }
2377
2378
0
    if (id == group_id) {
2379
0
      if (CBS_len(&peer_key) != 0) {
2380
0
        OPENSSL_PUT_ERROR(SSL, SSL_R_DUPLICATE_KEY_SHARE);
2381
0
        *out_alert = SSL_AD_ILLEGAL_PARAMETER;
2382
0
        return false;
2383
0
      }
2384
2385
0
      peer_key = peer_key_tmp;
2386
      // Continue parsing the structure to keep peers honest.
2387
0
    }
2388
0
  }
2389
2390
0
  if (out_peer_key != nullptr) {
2391
0
    *out_peer_key = peer_key;
2392
0
  }
2393
0
  *out_found = CBS_len(&peer_key) != 0;
2394
0
  return true;
2395
0
}
2396
2397
0
bool ssl_ext_key_share_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
2398
0
  CBB entry, ciphertext;
2399
0
  if (!CBB_add_u16(out, TLSEXT_TYPE_key_share) ||
2400
0
      !CBB_add_u16_length_prefixed(out, &entry) ||
2401
0
      !CBB_add_u16(&entry, hs->new_session->group_id) ||
2402
0
      !CBB_add_u16_length_prefixed(&entry, &ciphertext) ||
2403
0
      !CBB_add_bytes(&ciphertext, hs->key_share_ciphertext.data(),
2404
0
                     hs->key_share_ciphertext.size()) ||
2405
0
      !CBB_flush(out)) {
2406
0
    return false;
2407
0
  }
2408
0
  return true;
2409
0
}
2410
2411
2412
// Supported Versions
2413
//
2414
// https://tools.ietf.org/html/rfc8446#section-4.2.1
2415
2416
static bool ext_supported_versions_add_clienthello(
2417
    const SSL_HANDSHAKE *hs, CBB *out, CBB *out_compressible,
2418
0
    ssl_client_hello_type_t type) {
2419
0
  const SSL *const ssl = hs->ssl;
2420
0
  if (hs->max_version <= TLS1_2_VERSION) {
2421
0
    return true;
2422
0
  }
2423
2424
  // supported_versions is compressible in ECH if ClientHelloOuter already
2425
  // requires TLS 1.3. Otherwise the extensions differ in the older versions.
2426
0
  if (hs->min_version >= TLS1_3_VERSION) {
2427
0
    out = out_compressible;
2428
0
  }
2429
2430
0
  CBB contents, versions;
2431
0
  if (!CBB_add_u16(out, TLSEXT_TYPE_supported_versions) ||
2432
0
      !CBB_add_u16_length_prefixed(out, &contents) ||
2433
0
      !CBB_add_u8_length_prefixed(&contents, &versions)) {
2434
0
    return false;
2435
0
  }
2436
2437
  // Add a fake version. See RFC 8701.
2438
0
  if (ssl->ctx->grease_enabled &&
2439
0
      !CBB_add_u16(&versions, ssl_get_grease_value(hs, ssl_grease_version))) {
2440
0
    return false;
2441
0
  }
2442
2443
  // Encrypted ClientHellos requires TLS 1.3 or later.
2444
0
  uint16_t extra_min_version =
2445
0
      type == ssl_client_hello_inner ? TLS1_3_VERSION : 0;
2446
0
  if (!ssl_add_supported_versions(hs, &versions, extra_min_version) ||
2447
0
      !CBB_flush(out)) {
2448
0
    return false;
2449
0
  }
2450
2451
0
  return true;
2452
0
}
2453
2454
2455
// Cookie
2456
//
2457
// https://tools.ietf.org/html/rfc8446#section-4.2.2
2458
2459
static bool ext_cookie_add_clienthello(const SSL_HANDSHAKE *hs, CBB *out,
2460
                                       CBB *out_compressible,
2461
0
                                       ssl_client_hello_type_t type) {
2462
0
  if (hs->cookie.empty()) {
2463
0
    return true;
2464
0
  }
2465
2466
0
  CBB contents, cookie;
2467
0
  if (!CBB_add_u16(out_compressible, TLSEXT_TYPE_cookie) ||
2468
0
      !CBB_add_u16_length_prefixed(out_compressible, &contents) ||
2469
0
      !CBB_add_u16_length_prefixed(&contents, &cookie) ||
2470
0
      !CBB_add_bytes(&cookie, hs->cookie.data(), hs->cookie.size()) ||
2471
0
      !CBB_flush(out_compressible)) {
2472
0
    return false;
2473
0
  }
2474
2475
0
  return true;
2476
0
}
2477
2478
2479
// Supported Groups
2480
//
2481
// https://tools.ietf.org/html/rfc4492#section-5.1.1
2482
// https://tools.ietf.org/html/rfc8446#section-4.2.7
2483
2484
static bool ext_supported_groups_add_clienthello(const SSL_HANDSHAKE *hs,
2485
                                                 CBB *out,
2486
                                                 CBB *out_compressible,
2487
0
                                                 ssl_client_hello_type_t type) {
2488
0
  const SSL *const ssl = hs->ssl;
2489
0
  CBB contents, groups_bytes;
2490
0
  if (!CBB_add_u16(out_compressible, TLSEXT_TYPE_supported_groups) ||
2491
0
      !CBB_add_u16_length_prefixed(out_compressible, &contents) ||
2492
0
      !CBB_add_u16_length_prefixed(&contents, &groups_bytes)) {
2493
0
    return false;
2494
0
  }
2495
2496
  // Add a fake group. See RFC 8701.
2497
0
  if (ssl->ctx->grease_enabled &&
2498
0
      !CBB_add_u16(&groups_bytes,
2499
0
                   ssl_get_grease_value(hs, ssl_grease_group))) {
2500
0
    return false;
2501
0
  }
2502
2503
0
  for (uint16_t group : tls1_get_grouplist(hs)) {
2504
0
    if (is_post_quantum_group(group) &&
2505
0
        hs->max_version < TLS1_3_VERSION) {
2506
0
      continue;
2507
0
    }
2508
0
    if (!CBB_add_u16(&groups_bytes, group)) {
2509
0
      return false;
2510
0
    }
2511
0
  }
2512
2513
0
  return CBB_flush(out_compressible);
2514
0
}
2515
2516
static bool ext_supported_groups_parse_serverhello(SSL_HANDSHAKE *hs,
2517
                                                   uint8_t *out_alert,
2518
0
                                                   CBS *contents) {
2519
  // This extension is not expected to be echoed by servers in TLS 1.2, but some
2520
  // BigIP servers send it nonetheless, so do not enforce this.
2521
0
  return true;
2522
0
}
2523
2524
0
static bool parse_u16_array(const CBS *cbs, Array<uint16_t> *out) {
2525
0
  CBS copy = *cbs;
2526
0
  if ((CBS_len(&copy) & 1) != 0) {
2527
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
2528
0
    return false;
2529
0
  }
2530
2531
0
  Array<uint16_t> ret;
2532
0
  if (!ret.Init(CBS_len(&copy) / 2)) {
2533
0
    return false;
2534
0
  }
2535
0
  for (size_t i = 0; i < ret.size(); i++) {
2536
0
    if (!CBS_get_u16(&copy, &ret[i])) {
2537
0
      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
2538
0
      return false;
2539
0
    }
2540
0
  }
2541
2542
0
  assert(CBS_len(&copy) == 0);
2543
0
  *out = std::move(ret);
2544
0
  return true;
2545
0
}
2546
2547
static bool ext_supported_groups_parse_clienthello(SSL_HANDSHAKE *hs,
2548
                                                  uint8_t *out_alert,
2549
0
                                                   CBS *contents) {
2550
0
  if (contents == NULL) {
2551
0
    return true;
2552
0
  }
2553
2554
0
  CBS supported_group_list;
2555
0
  if (!CBS_get_u16_length_prefixed(contents, &supported_group_list) ||
2556
0
      CBS_len(&supported_group_list) == 0 ||
2557
0
      CBS_len(contents) != 0 ||
2558
0
      !parse_u16_array(&supported_group_list, &hs->peer_supported_group_list)) {
2559
0
    return false;
2560
0
  }
2561
2562
0
  return true;
2563
0
}
2564
2565
2566
// QUIC Transport Parameters
2567
2568
static bool ext_quic_transport_params_add_clienthello_impl(
2569
0
    const SSL_HANDSHAKE *hs, CBB *out, bool use_legacy_codepoint) {
2570
0
  if (hs->config->quic_transport_params.empty() && !hs->ssl->quic_method) {
2571
0
    return true;
2572
0
  }
2573
0
  if (hs->config->quic_transport_params.empty() || !hs->ssl->quic_method) {
2574
    // QUIC Transport Parameters must be sent over QUIC, and they must not be
2575
    // sent over non-QUIC transports. If transport params are set, then
2576
    // SSL(_CTX)_set_quic_method must also be called.
2577
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_QUIC_TRANSPORT_PARAMETERS_MISCONFIGURED);
2578
0
    return false;
2579
0
  }
2580
0
  assert(hs->min_version > TLS1_2_VERSION);
2581
0
  if (use_legacy_codepoint != hs->config->quic_use_legacy_codepoint) {
2582
    // Do nothing, we'll send the other codepoint.
2583
0
    return true;
2584
0
  }
2585
2586
0
  uint16_t extension_type = TLSEXT_TYPE_quic_transport_parameters;
2587
0
  if (hs->config->quic_use_legacy_codepoint) {
2588
0
    extension_type = TLSEXT_TYPE_quic_transport_parameters_legacy;
2589
0
  }
2590
2591
0
  CBB contents;
2592
0
  if (!CBB_add_u16(out, extension_type) ||
2593
0
      !CBB_add_u16_length_prefixed(out, &contents) ||
2594
0
      !CBB_add_bytes(&contents, hs->config->quic_transport_params.data(),
2595
0
                     hs->config->quic_transport_params.size()) ||
2596
0
      !CBB_flush(out)) {
2597
0
    return false;
2598
0
  }
2599
0
  return true;
2600
0
}
2601
2602
static bool ext_quic_transport_params_add_clienthello(
2603
    const SSL_HANDSHAKE *hs, CBB *out, CBB *out_compressible,
2604
0
    ssl_client_hello_type_t type) {
2605
0
  return ext_quic_transport_params_add_clienthello_impl(
2606
0
      hs, out_compressible, /*use_legacy_codepoint=*/false);
2607
0
}
2608
2609
static bool ext_quic_transport_params_add_clienthello_legacy(
2610
    const SSL_HANDSHAKE *hs, CBB *out, CBB *out_compressible,
2611
0
    ssl_client_hello_type_t type) {
2612
0
  return ext_quic_transport_params_add_clienthello_impl(
2613
0
      hs, out_compressible, /*use_legacy_codepoint=*/true);
2614
0
}
2615
2616
static bool ext_quic_transport_params_parse_serverhello_impl(
2617
    SSL_HANDSHAKE *hs, uint8_t *out_alert, CBS *contents,
2618
0
    bool used_legacy_codepoint) {
2619
0
  SSL *const ssl = hs->ssl;
2620
0
  if (contents == nullptr) {
2621
0
    if (used_legacy_codepoint != hs->config->quic_use_legacy_codepoint) {
2622
      // Silently ignore because we expect the other QUIC codepoint.
2623
0
      return true;
2624
0
    }
2625
0
    if (!ssl->quic_method) {
2626
0
      return true;
2627
0
    }
2628
0
    *out_alert = SSL_AD_MISSING_EXTENSION;
2629
0
    return false;
2630
0
  }
2631
  // The extensions parser will check for unsolicited extensions before
2632
  // calling the callback.
2633
0
  assert(ssl->quic_method != nullptr);
2634
0
  assert(ssl_protocol_version(ssl) == TLS1_3_VERSION);
2635
0
  assert(used_legacy_codepoint == hs->config->quic_use_legacy_codepoint);
2636
0
  return ssl->s3->peer_quic_transport_params.CopyFrom(*contents);
2637
0
}
2638
2639
static bool ext_quic_transport_params_parse_serverhello(SSL_HANDSHAKE *hs,
2640
                                                        uint8_t *out_alert,
2641
0
                                                        CBS *contents) {
2642
0
  return ext_quic_transport_params_parse_serverhello_impl(
2643
0
      hs, out_alert, contents, /*used_legacy_codepoint=*/false);
2644
0
}
2645
2646
static bool ext_quic_transport_params_parse_serverhello_legacy(
2647
0
    SSL_HANDSHAKE *hs, uint8_t *out_alert, CBS *contents) {
2648
0
  return ext_quic_transport_params_parse_serverhello_impl(
2649
0
      hs, out_alert, contents, /*used_legacy_codepoint=*/true);
2650
0
}
2651
2652
static bool ext_quic_transport_params_parse_clienthello_impl(
2653
    SSL_HANDSHAKE *hs, uint8_t *out_alert, CBS *contents,
2654
0
    bool used_legacy_codepoint) {
2655
0
  SSL *const ssl = hs->ssl;
2656
0
  if (!contents) {
2657
0
    if (!ssl->quic_method) {
2658
0
      if (hs->config->quic_transport_params.empty()) {
2659
0
        return true;
2660
0
      }
2661
      // QUIC transport parameters must not be set if |ssl| is not configured
2662
      // for QUIC.
2663
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_QUIC_TRANSPORT_PARAMETERS_MISCONFIGURED);
2664
0
      *out_alert = SSL_AD_INTERNAL_ERROR;
2665
0
      return false;
2666
0
    }
2667
0
    if (used_legacy_codepoint != hs->config->quic_use_legacy_codepoint) {
2668
      // Silently ignore because we expect the other QUIC codepoint.
2669
0
      return true;
2670
0
    }
2671
0
    *out_alert = SSL_AD_MISSING_EXTENSION;
2672
0
    return false;
2673
0
  }
2674
0
  if (!ssl->quic_method) {
2675
0
    if (used_legacy_codepoint) {
2676
      // Ignore the legacy private-use codepoint because that could be sent
2677
      // to mean something else than QUIC transport parameters.
2678
0
      return true;
2679
0
    }
2680
    // Fail if we received the codepoint registered with IANA for QUIC
2681
    // because that is not allowed outside of QUIC.
2682
0
    *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
2683
0
    return false;
2684
0
  }
2685
0
  assert(ssl_protocol_version(ssl) == TLS1_3_VERSION);
2686
0
  if (used_legacy_codepoint != hs->config->quic_use_legacy_codepoint) {
2687
    // Silently ignore because we expect the other QUIC codepoint.
2688
0
    return true;
2689
0
  }
2690
0
  return ssl->s3->peer_quic_transport_params.CopyFrom(*contents);
2691
0
}
2692
2693
static bool ext_quic_transport_params_parse_clienthello(SSL_HANDSHAKE *hs,
2694
                                                        uint8_t *out_alert,
2695
0
                                                        CBS *contents) {
2696
0
  return ext_quic_transport_params_parse_clienthello_impl(
2697
0
      hs, out_alert, contents, /*used_legacy_codepoint=*/false);
2698
0
}
2699
2700
static bool ext_quic_transport_params_parse_clienthello_legacy(
2701
0
    SSL_HANDSHAKE *hs, uint8_t *out_alert, CBS *contents) {
2702
0
  return ext_quic_transport_params_parse_clienthello_impl(
2703
0
      hs, out_alert, contents, /*used_legacy_codepoint=*/true);
2704
0
}
2705
2706
static bool ext_quic_transport_params_add_serverhello_impl(
2707
0
    SSL_HANDSHAKE *hs, CBB *out, bool use_legacy_codepoint) {
2708
0
  if (hs->ssl->quic_method == nullptr && use_legacy_codepoint) {
2709
    // Ignore the legacy private-use codepoint because that could be sent
2710
    // to mean something else than QUIC transport parameters.
2711
0
    return true;
2712
0
  }
2713
0
  assert(hs->ssl->quic_method != nullptr);
2714
0
  if (hs->config->quic_transport_params.empty()) {
2715
    // Transport parameters must be set when using QUIC.
2716
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_QUIC_TRANSPORT_PARAMETERS_MISCONFIGURED);
2717
0
    return false;
2718
0
  }
2719
0
  if (use_legacy_codepoint != hs->config->quic_use_legacy_codepoint) {
2720
    // Do nothing, we'll send the other codepoint.
2721
0
    return true;
2722
0
  }
2723
2724
0
  uint16_t extension_type = TLSEXT_TYPE_quic_transport_parameters;
2725
0
  if (hs->config->quic_use_legacy_codepoint) {
2726
0
    extension_type = TLSEXT_TYPE_quic_transport_parameters_legacy;
2727
0
  }
2728
2729
0
  CBB contents;
2730
0
  if (!CBB_add_u16(out, extension_type) ||
2731
0
      !CBB_add_u16_length_prefixed(out, &contents) ||
2732
0
      !CBB_add_bytes(&contents, hs->config->quic_transport_params.data(),
2733
0
                     hs->config->quic_transport_params.size()) ||
2734
0
      !CBB_flush(out)) {
2735
0
    return false;
2736
0
  }
2737
2738
0
  return true;
2739
0
}
2740
2741
static bool ext_quic_transport_params_add_serverhello(SSL_HANDSHAKE *hs,
2742
0
                                                      CBB *out) {
2743
0
  return ext_quic_transport_params_add_serverhello_impl(
2744
0
      hs, out, /*use_legacy_codepoint=*/false);
2745
0
}
2746
2747
static bool ext_quic_transport_params_add_serverhello_legacy(SSL_HANDSHAKE *hs,
2748
0
                                                             CBB *out) {
2749
0
  return ext_quic_transport_params_add_serverhello_impl(
2750
0
      hs, out, /*use_legacy_codepoint=*/true);
2751
0
}
2752
2753
// Delegated credentials.
2754
//
2755
// https://tools.ietf.org/html/draft-ietf-tls-subcerts
2756
2757
static bool ext_delegated_credential_add_clienthello(
2758
    const SSL_HANDSHAKE *hs, CBB *out, CBB *out_compressible,
2759
0
    ssl_client_hello_type_t type) {
2760
0
  return true;
2761
0
}
2762
2763
static bool ext_delegated_credential_parse_clienthello(SSL_HANDSHAKE *hs,
2764
                                                       uint8_t *out_alert,
2765
0
                                                       CBS *contents) {
2766
0
  if (contents == nullptr || ssl_protocol_version(hs->ssl) < TLS1_3_VERSION) {
2767
    // Don't use delegated credentials unless we're negotiating TLS 1.3 or
2768
    // higher.
2769
0
    return true;
2770
0
  }
2771
2772
  // The contents of the extension are the signature algorithms the client will
2773
  // accept for a delegated credential.
2774
0
  CBS sigalg_list;
2775
0
  if (!CBS_get_u16_length_prefixed(contents, &sigalg_list) ||
2776
0
      CBS_len(&sigalg_list) == 0 ||
2777
0
      CBS_len(contents) != 0 ||
2778
0
      !parse_u16_array(&sigalg_list, &hs->peer_delegated_credential_sigalgs)) {
2779
0
    return false;
2780
0
  }
2781
2782
0
  hs->delegated_credential_requested = true;
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
0
                                             ssl_client_hello_type_t type) {
2791
0
  bool first = true;
2792
0
  CBB contents, algs;
2793
2794
0
  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
0
  return first || CBB_flush(out_compressible);
2812
0
}
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(const SSL_HANDSHAKE *hs, CBB *out,
2910
                                     CBB *out_compressible,
2911
0
                                     ssl_client_hello_type_t type) {
2912
0
  const SSL *const ssl = hs->ssl;
2913
0
  if (// ALPS requires TLS 1.3.
2914
0
      hs->max_version < TLS1_3_VERSION ||
2915
      // Do not offer ALPS without ALPN.
2916
0
      hs->config->alpn_client_proto_list.empty() ||
2917
      // Do not offer ALPS if not configured.
2918
0
      hs->config->alps_configs.empty() ||
2919
      // Do not offer ALPS on renegotiation handshakes.
2920
0
      ssl->s3->initial_handshake_complete) {
2921
0
    return true;
2922
0
  }
2923
2924
0
  CBB contents, proto_list, proto;
2925
0
  if (!CBB_add_u16(out_compressible, TLSEXT_TYPE_application_settings) ||
2926
0
      !CBB_add_u16_length_prefixed(out_compressible, &contents) ||
2927
0
      !CBB_add_u16_length_prefixed(&contents, &proto_list)) {
2928
0
    return false;
2929
0
  }
2930
2931
0
  for (const ALPSConfig &config : hs->config->alps_configs) {
2932
0
    if (!CBB_add_u8_length_prefixed(&proto_list, &proto) ||
2933
0
        !CBB_add_bytes(&proto, config.protocol.data(),
2934
0
                       config.protocol.size())) {
2935
0
      return false;
2936
0
    }
2937
0
  }
2938
2939
0
  return CBB_flush(out_compressible);
2940
0
}
2941
2942
static bool ext_alps_parse_serverhello(SSL_HANDSHAKE *hs, uint8_t *out_alert,
2943
0
                                       CBS *contents) {
2944
0
  SSL *const ssl = hs->ssl;
2945
0
  if (contents == nullptr) {
2946
0
    return true;
2947
0
  }
2948
2949
0
  assert(!ssl->s3->initial_handshake_complete);
2950
0
  assert(!hs->config->alpn_client_proto_list.empty());
2951
0
  assert(!hs->config->alps_configs.empty());
2952
2953
  // ALPS requires TLS 1.3.
2954
0
  if (ssl_protocol_version(ssl) < TLS1_3_VERSION) {
2955
0
    *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
2956
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
2957
0
    return false;
2958
0
  }
2959
2960
  // Note extension callbacks may run in any order, so we defer checking
2961
  // consistency with ALPN to |ssl_check_serverhello_tlsext|.
2962
0
  if (!hs->new_session->peer_application_settings.CopyFrom(*contents)) {
2963
0
    *out_alert = SSL_AD_INTERNAL_ERROR;
2964
0
    return false;
2965
0
  }
2966
2967
0
  hs->new_session->has_application_settings = true;
2968
0
  return true;
2969
0
}
2970
2971
0
static bool ext_alps_add_serverhello(SSL_HANDSHAKE *hs, CBB *out) {
2972
0
  SSL *const ssl = hs->ssl;
2973
  // If early data is accepted, we omit the ALPS extension. It is implicitly
2974
  // carried over from the previous connection.
2975
0
  if (hs->new_session == nullptr ||
2976
0
      !hs->new_session->has_application_settings ||
2977
0
      ssl->s3->early_data_accepted) {
2978
0
    return true;
2979
0
  }
2980
2981
0
  CBB contents;
2982
0
  if (!CBB_add_u16(out, TLSEXT_TYPE_application_settings) ||
2983
0
      !CBB_add_u16_length_prefixed(out, &contents) ||
2984
0
      !CBB_add_bytes(&contents,
2985
0
                     hs->new_session->local_application_settings.data(),
2986
0
                     hs->new_session->local_application_settings.size()) ||
2987
0
      !CBB_flush(out)) {
2988
0
    return false;
2989
0
  }
2990
2991
0
  return true;
2992
0
}
2993
2994
bool ssl_negotiate_alps(SSL_HANDSHAKE *hs, uint8_t *out_alert,
2995
0
                        const SSL_CLIENT_HELLO *client_hello) {
2996
0
  SSL *const ssl = hs->ssl;
2997
0
  if (ssl->s3->alpn_selected.empty()) {
2998
0
    return true;
2999
0
  }
3000
3001
  // If we negotiate ALPN over TLS 1.3, try to negotiate ALPS.
3002
0
  CBS alps_contents;
3003
0
  Span<const uint8_t> settings;
3004
0
  if (ssl_protocol_version(ssl) >= TLS1_3_VERSION &&
3005
0
      ssl_get_local_application_settings(hs, &settings,
3006
0
                                         ssl->s3->alpn_selected) &&
3007
0
      ssl_client_hello_get_extension(client_hello, &alps_contents,
3008
0
                                     TLSEXT_TYPE_application_settings)) {
3009
    // Check if the client supports ALPS with the selected ALPN.
3010
0
    bool found = false;
3011
0
    CBS alps_list;
3012
0
    if (!CBS_get_u16_length_prefixed(&alps_contents, &alps_list) ||
3013
0
        CBS_len(&alps_contents) != 0 ||
3014
0
        CBS_len(&alps_list) == 0) {
3015
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
3016
0
      *out_alert = SSL_AD_DECODE_ERROR;
3017
0
      return false;
3018
0
    }
3019
0
    while (CBS_len(&alps_list) > 0) {
3020
0
      CBS protocol_name;
3021
0
      if (!CBS_get_u8_length_prefixed(&alps_list, &protocol_name) ||
3022
          // Empty protocol names are forbidden.
3023
0
          CBS_len(&protocol_name) == 0) {
3024
0
        OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
3025
0
        *out_alert = SSL_AD_DECODE_ERROR;
3026
0
        return false;
3027
0
      }
3028
0
      if (protocol_name == MakeConstSpan(ssl->s3->alpn_selected)) {
3029
0
        found = true;
3030
0
      }
3031
0
    }
3032
3033
    // Negotiate ALPS if both client also supports ALPS for this protocol.
3034
0
    if (found) {
3035
0
      hs->new_session->has_application_settings = true;
3036
0
      if (!hs->new_session->local_application_settings.CopyFrom(settings)) {
3037
0
        *out_alert = SSL_AD_INTERNAL_ERROR;
3038
0
        return false;
3039
0
      }
3040
0
    }
3041
0
  }
3042
3043
0
  return true;
3044
0
}
3045
3046
// kExtensions contains all the supported extensions.
3047
static const struct tls_extension kExtensions[] = {
3048
  {
3049
    TLSEXT_TYPE_server_name,
3050
    ext_sni_add_clienthello,
3051
    ext_sni_parse_serverhello,
3052
    ext_sni_parse_clienthello,
3053
    ext_sni_add_serverhello,
3054
  },
3055
  {
3056
    TLSEXT_TYPE_encrypted_client_hello,
3057
    ext_ech_add_clienthello,
3058
    ext_ech_parse_serverhello,
3059
    ext_ech_parse_clienthello,
3060
    ext_ech_add_serverhello,
3061
  },
3062
  {
3063
    TLSEXT_TYPE_extended_master_secret,
3064
    ext_ems_add_clienthello,
3065
    ext_ems_parse_serverhello,
3066
    ext_ems_parse_clienthello,
3067
    ext_ems_add_serverhello,
3068
  },
3069
  {
3070
    TLSEXT_TYPE_renegotiate,
3071
    ext_ri_add_clienthello,
3072
    ext_ri_parse_serverhello,
3073
    ext_ri_parse_clienthello,
3074
    ext_ri_add_serverhello,
3075
  },
3076
  {
3077
    TLSEXT_TYPE_supported_groups,
3078
    ext_supported_groups_add_clienthello,
3079
    ext_supported_groups_parse_serverhello,
3080
    ext_supported_groups_parse_clienthello,
3081
    dont_add_serverhello,
3082
  },
3083
  {
3084
    TLSEXT_TYPE_ec_point_formats,
3085
    ext_ec_point_add_clienthello,
3086
    ext_ec_point_parse_serverhello,
3087
    ext_ec_point_parse_clienthello,
3088
    ext_ec_point_add_serverhello,
3089
  },
3090
  {
3091
    TLSEXT_TYPE_session_ticket,
3092
    ext_ticket_add_clienthello,
3093
    ext_ticket_parse_serverhello,
3094
    // Ticket extension client parsing is handled in ssl_session.c
3095
    ignore_parse_clienthello,
3096
    ext_ticket_add_serverhello,
3097
  },
3098
  {
3099
    TLSEXT_TYPE_application_layer_protocol_negotiation,
3100
    ext_alpn_add_clienthello,
3101
    ext_alpn_parse_serverhello,
3102
    // ALPN is negotiated late in |ssl_negotiate_alpn|.
3103
    ignore_parse_clienthello,
3104
    ext_alpn_add_serverhello,
3105
  },
3106
  {
3107
    TLSEXT_TYPE_status_request,
3108
    ext_ocsp_add_clienthello,
3109
    ext_ocsp_parse_serverhello,
3110
    ext_ocsp_parse_clienthello,
3111
    ext_ocsp_add_serverhello,
3112
  },
3113
  {
3114
    TLSEXT_TYPE_signature_algorithms,
3115
    ext_sigalgs_add_clienthello,
3116
    forbid_parse_serverhello,
3117
    ext_sigalgs_parse_clienthello,
3118
    dont_add_serverhello,
3119
  },
3120
  {
3121
    TLSEXT_TYPE_next_proto_neg,
3122
    ext_npn_add_clienthello,
3123
    ext_npn_parse_serverhello,
3124
    ext_npn_parse_clienthello,
3125
    ext_npn_add_serverhello,
3126
  },
3127
  {
3128
    TLSEXT_TYPE_certificate_timestamp,
3129
    ext_sct_add_clienthello,
3130
    ext_sct_parse_serverhello,
3131
    ext_sct_parse_clienthello,
3132
    ext_sct_add_serverhello,
3133
  },
3134
  {
3135
    TLSEXT_TYPE_channel_id,
3136
    ext_channel_id_add_clienthello,
3137
    ext_channel_id_parse_serverhello,
3138
    ext_channel_id_parse_clienthello,
3139
    ext_channel_id_add_serverhello,
3140
  },
3141
  {
3142
    TLSEXT_TYPE_srtp,
3143
    ext_srtp_add_clienthello,
3144
    ext_srtp_parse_serverhello,
3145
    ext_srtp_parse_clienthello,
3146
    ext_srtp_add_serverhello,
3147
  },
3148
  {
3149
    TLSEXT_TYPE_key_share,
3150
    ext_key_share_add_clienthello,
3151
    forbid_parse_serverhello,
3152
    ignore_parse_clienthello,
3153
    dont_add_serverhello,
3154
  },
3155
  {
3156
    TLSEXT_TYPE_psk_key_exchange_modes,
3157
    ext_psk_key_exchange_modes_add_clienthello,
3158
    forbid_parse_serverhello,
3159
    ext_psk_key_exchange_modes_parse_clienthello,
3160
    dont_add_serverhello,
3161
  },
3162
  {
3163
    TLSEXT_TYPE_early_data,
3164
    ext_early_data_add_clienthello,
3165
    ext_early_data_parse_serverhello,
3166
    ext_early_data_parse_clienthello,
3167
    ext_early_data_add_serverhello,
3168
  },
3169
  {
3170
    TLSEXT_TYPE_supported_versions,
3171
    ext_supported_versions_add_clienthello,
3172
    forbid_parse_serverhello,
3173
    ignore_parse_clienthello,
3174
    dont_add_serverhello,
3175
  },
3176
  {
3177
    TLSEXT_TYPE_cookie,
3178
    ext_cookie_add_clienthello,
3179
    forbid_parse_serverhello,
3180
    ignore_parse_clienthello,
3181
    dont_add_serverhello,
3182
  },
3183
  {
3184
    TLSEXT_TYPE_quic_transport_parameters,
3185
    ext_quic_transport_params_add_clienthello,
3186
    ext_quic_transport_params_parse_serverhello,
3187
    ext_quic_transport_params_parse_clienthello,
3188
    ext_quic_transport_params_add_serverhello,
3189
  },
3190
  {
3191
    TLSEXT_TYPE_quic_transport_parameters_legacy,
3192
    ext_quic_transport_params_add_clienthello_legacy,
3193
    ext_quic_transport_params_parse_serverhello_legacy,
3194
    ext_quic_transport_params_parse_clienthello_legacy,
3195
    ext_quic_transport_params_add_serverhello_legacy,
3196
  },
3197
  {
3198
    TLSEXT_TYPE_cert_compression,
3199
    cert_compression_add_clienthello,
3200
    cert_compression_parse_serverhello,
3201
    cert_compression_parse_clienthello,
3202
    cert_compression_add_serverhello,
3203
  },
3204
  {
3205
    TLSEXT_TYPE_delegated_credential,
3206
    ext_delegated_credential_add_clienthello,
3207
    forbid_parse_serverhello,
3208
    ext_delegated_credential_parse_clienthello,
3209
    dont_add_serverhello,
3210
  },
3211
  {
3212
    TLSEXT_TYPE_application_settings,
3213
    ext_alps_add_clienthello,
3214
    ext_alps_parse_serverhello,
3215
    // ALPS is negotiated late in |ssl_negotiate_alpn|.
3216
    ignore_parse_clienthello,
3217
    ext_alps_add_serverhello,
3218
  },
3219
};
3220
3221
0
#define kNumExtensions (sizeof(kExtensions) / sizeof(struct tls_extension))
3222
3223
static_assert(kNumExtensions <=
3224
                  sizeof(((SSL_HANDSHAKE *)NULL)->extensions.sent) * 8,
3225
              "too many extensions for sent bitset");
3226
static_assert(kNumExtensions <=
3227
                  sizeof(((SSL_HANDSHAKE *)NULL)->extensions.received) * 8,
3228
              "too many extensions for received bitset");
3229
3230
0
bool ssl_setup_extension_permutation(SSL_HANDSHAKE *hs) {
3231
0
  if (!hs->config->permute_extensions) {
3232
0
    return true;
3233
0
  }
3234
3235
0
  static_assert(kNumExtensions <= UINT8_MAX,
3236
0
                "extensions_permutation type is too small");
3237
0
  uint32_t seeds[kNumExtensions - 1];
3238
0
  Array<uint8_t> permutation;
3239
0
  if (!RAND_bytes(reinterpret_cast<uint8_t *>(seeds), sizeof(seeds)) ||
3240
0
      !permutation.Init(kNumExtensions)) {
3241
0
    return false;
3242
0
  }
3243
0
  for (size_t i = 0; i < kNumExtensions; i++) {
3244
0
    permutation[i] = i;
3245
0
  }
3246
0
  for (size_t i = kNumExtensions - 1; i > 0; i--) {
3247
    // Set element |i| to a randomly-selected element 0 <= j <= i.
3248
0
    std::swap(permutation[i], permutation[seeds[i - 1] % (i + 1)]);
3249
0
  }
3250
0
  hs->extension_permutation = std::move(permutation);
3251
0
  return true;
3252
0
}
3253
3254
static const struct tls_extension *tls_extension_find(uint32_t *out_index,
3255
0
                                                      uint16_t value) {
3256
0
  unsigned i;
3257
0
  for (i = 0; i < kNumExtensions; i++) {
3258
0
    if (kExtensions[i].value == value) {
3259
0
      *out_index = i;
3260
0
      return &kExtensions[i];
3261
0
    }
3262
0
  }
3263
3264
0
  return NULL;
3265
0
}
3266
3267
0
static bool add_padding_extension(CBB *cbb, uint16_t ext, size_t len) {
3268
0
  CBB child;
3269
0
  if (!CBB_add_u16(cbb, ext) ||  //
3270
0
      !CBB_add_u16_length_prefixed(cbb, &child) ||
3271
0
      !CBB_add_zeros(&child, len)) {
3272
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
3273
0
    return false;
3274
0
  }
3275
0
  return CBB_flush(cbb);
3276
0
}
3277
3278
static bool ssl_add_clienthello_tlsext_inner(SSL_HANDSHAKE *hs, CBB *out,
3279
                                             CBB *out_encoded,
3280
0
                                             bool *out_needs_psk_binder) {
3281
  // When writing ClientHelloInner, we construct the real and encoded
3282
  // ClientHellos concurrently, to handle compression. Uncompressed extensions
3283
  // are written to |extensions| and copied to |extensions_encoded|. Compressed
3284
  // extensions are buffered in |compressed| and written to the end. (ECH can
3285
  // only compress continguous extensions.)
3286
0
  SSL *const ssl = hs->ssl;
3287
0
  bssl::ScopedCBB compressed, outer_extensions;
3288
0
  CBB extensions, extensions_encoded;
3289
0
  if (!CBB_add_u16_length_prefixed(out, &extensions) ||
3290
0
      !CBB_add_u16_length_prefixed(out_encoded, &extensions_encoded) ||
3291
0
      !CBB_init(compressed.get(), 64) ||
3292
0
      !CBB_init(outer_extensions.get(), 64)) {
3293
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
3294
0
    return false;
3295
0
  }
3296
3297
0
  hs->inner_extensions_sent = 0;
3298
3299
0
  if (ssl->ctx->grease_enabled) {
3300
    // Add a fake empty extension. See RFC 8701. This always matches
3301
    // |ssl_add_clienthello_tlsext|, so compress it.
3302
0
    uint16_t grease_ext = ssl_get_grease_value(hs, ssl_grease_extension1);
3303
0
    if (!add_padding_extension(compressed.get(), grease_ext, 0) ||
3304
0
        !CBB_add_u16(outer_extensions.get(), grease_ext)) {
3305
0
      return false;
3306
0
    }
3307
0
  }
3308
3309
0
  for (size_t unpermuted = 0; unpermuted < kNumExtensions; unpermuted++) {
3310
0
    size_t i = hs->extension_permutation.empty()
3311
0
                   ? unpermuted
3312
0
                   : hs->extension_permutation[unpermuted];
3313
0
    const size_t len_before = CBB_len(&extensions);
3314
0
    const size_t len_compressed_before = CBB_len(compressed.get());
3315
0
    if (!kExtensions[i].add_clienthello(hs, &extensions, compressed.get(),
3316
0
                                        ssl_client_hello_inner)) {
3317
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_ADDING_EXTENSION);
3318
0
      ERR_add_error_dataf("extension %u", (unsigned)kExtensions[i].value);
3319
0
      return false;
3320
0
    }
3321
3322
0
    const size_t bytes_written = CBB_len(&extensions) - len_before;
3323
0
    const size_t bytes_written_compressed =
3324
0
        CBB_len(compressed.get()) - len_compressed_before;
3325
    // The callback may write to at most one output.
3326
0
    assert(bytes_written == 0 || bytes_written_compressed == 0);
3327
0
    if (bytes_written != 0 || bytes_written_compressed != 0) {
3328
0
      hs->inner_extensions_sent |= (1u << i);
3329
0
    }
3330
    // If compressed, update the running ech_outer_extensions extension.
3331
0
    if (bytes_written_compressed != 0 &&
3332
0
        !CBB_add_u16(outer_extensions.get(), kExtensions[i].value)) {
3333
0
      return false;
3334
0
    }
3335
0
  }
3336
3337
0
  if (ssl->ctx->grease_enabled) {
3338
    // Add a fake non-empty extension. See RFC 8701. This always matches
3339
    // |ssl_add_clienthello_tlsext|, so compress it.
3340
0
    uint16_t grease_ext = ssl_get_grease_value(hs, ssl_grease_extension2);
3341
0
    if (!add_padding_extension(compressed.get(), grease_ext, 1) ||
3342
0
        !CBB_add_u16(outer_extensions.get(), grease_ext)) {
3343
0
      return false;
3344
0
    }
3345
0
  }
3346
3347
  // Uncompressed extensions are encoded as-is.
3348
0
  if (!CBB_add_bytes(&extensions_encoded, CBB_data(&extensions),
3349
0
                     CBB_len(&extensions))) {
3350
0
    return false;
3351
0
  }
3352
3353
  // Flush all the compressed extensions.
3354
0
  if (CBB_len(compressed.get()) != 0) {
3355
0
    CBB extension, child;
3356
    // Copy them as-is in the real ClientHelloInner.
3357
0
    if (!CBB_add_bytes(&extensions, CBB_data(compressed.get()),
3358
0
                       CBB_len(compressed.get())) ||
3359
        // Replace with ech_outer_extensions in the encoded form.
3360
0
        !CBB_add_u16(&extensions_encoded, TLSEXT_TYPE_ech_outer_extensions) ||
3361
0
        !CBB_add_u16_length_prefixed(&extensions_encoded, &extension) ||
3362
0
        !CBB_add_u8_length_prefixed(&extension, &child) ||
3363
0
        !CBB_add_bytes(&child, CBB_data(outer_extensions.get()),
3364
0
                       CBB_len(outer_extensions.get())) ||
3365
0
        !CBB_flush(&extensions_encoded)) {
3366
0
      return false;
3367
0
    }
3368
0
  }
3369
3370
  // The PSK extension must be last. It is never compressed. Note, if there is a
3371
  // binder, the caller will need to update both ClientHelloInner and
3372
  // EncodedClientHelloInner after computing it.
3373
0
  const size_t len_before = CBB_len(&extensions);
3374
0
  if (!ext_pre_shared_key_add_clienthello(hs, &extensions, out_needs_psk_binder,
3375
0
                                          ssl_client_hello_inner) ||
3376
0
      !CBB_add_bytes(&extensions_encoded, CBB_data(&extensions) + len_before,
3377
0
                     CBB_len(&extensions) - len_before) ||
3378
0
      !CBB_flush(out) ||  //
3379
0
      !CBB_flush(out_encoded)) {
3380
0
    return false;
3381
0
  }
3382
3383
0
  return true;
3384
0
}
3385
3386
bool ssl_add_clienthello_tlsext(SSL_HANDSHAKE *hs, CBB *out, CBB *out_encoded,
3387
                                bool *out_needs_psk_binder,
3388
                                ssl_client_hello_type_t type,
3389
0
                                size_t header_len) {
3390
0
  *out_needs_psk_binder = false;
3391
3392
0
  if (type == ssl_client_hello_inner) {
3393
0
    return ssl_add_clienthello_tlsext_inner(hs, out, out_encoded,
3394
0
                                            out_needs_psk_binder);
3395
0
  }
3396
3397
0
  assert(out_encoded == nullptr);  // Only ClientHelloInner needs two outputs.
3398
0
  SSL *const ssl = hs->ssl;
3399
0
  CBB extensions;
3400
0
  if (!CBB_add_u16_length_prefixed(out, &extensions)) {
3401
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
3402
0
    return false;
3403
0
  }
3404
3405
  // Note we may send multiple ClientHellos for DTLS HelloVerifyRequest and TLS
3406
  // 1.3 HelloRetryRequest. For the latter, the extensions may change, so it is
3407
  // important to reset this value.
3408
0
  hs->extensions.sent = 0;
3409
3410
  // Add a fake empty extension. See RFC 8701.
3411
0
  if (ssl->ctx->grease_enabled &&
3412
0
      !add_padding_extension(
3413
0
          &extensions, ssl_get_grease_value(hs, ssl_grease_extension1), 0)) {
3414
0
    return false;
3415
0
  }
3416
3417
0
  bool last_was_empty = false;
3418
0
  for (size_t unpermuted = 0; unpermuted < kNumExtensions; unpermuted++) {
3419
0
    size_t i = hs->extension_permutation.empty()
3420
0
                   ? unpermuted
3421
0
                   : hs->extension_permutation[unpermuted];
3422
0
    const size_t len_before = CBB_len(&extensions);
3423
0
    if (!kExtensions[i].add_clienthello(hs, &extensions, &extensions, type)) {
3424
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_ADDING_EXTENSION);
3425
0
      ERR_add_error_dataf("extension %u", (unsigned)kExtensions[i].value);
3426
0
      return false;
3427
0
    }
3428
3429
0
    const size_t bytes_written = CBB_len(&extensions) - len_before;
3430
0
    if (bytes_written != 0) {
3431
0
      hs->extensions.sent |= (1u << i);
3432
0
    }
3433
    // If the difference in lengths is only four bytes then the extension had
3434
    // an empty body.
3435
0
    last_was_empty = (bytes_written == 4);
3436
0
  }
3437
3438
0
  if (ssl->ctx->grease_enabled) {
3439
    // Add a fake non-empty extension. See RFC 8701.
3440
0
    if (!add_padding_extension(
3441
0
            &extensions, ssl_get_grease_value(hs, ssl_grease_extension2), 1)) {
3442
0
      return false;
3443
0
    }
3444
0
    last_was_empty = false;
3445
0
  }
3446
3447
  // In cleartext ClientHellos, we add the padding extension to work around
3448
  // bugs. We also apply this padding to ClientHelloOuter, to keep the wire
3449
  // images aligned.
3450
0
  size_t psk_extension_len = ext_pre_shared_key_clienthello_length(hs, type);
3451
0
  if (!SSL_is_dtls(ssl) && !ssl->quic_method &&
3452
0
      !ssl->s3->used_hello_retry_request) {
3453
0
    header_len +=
3454
0
        SSL3_HM_HEADER_LENGTH + 2 + CBB_len(&extensions) + psk_extension_len;
3455
0
    size_t padding_len = 0;
3456
3457
    // The final extension must be non-empty. WebSphere Application
3458
    // Server 7.0 is intolerant to the last extension being zero-length. See
3459
    // https://crbug.com/363583.
3460
0
    if (last_was_empty && psk_extension_len == 0) {
3461
0
      padding_len = 1;
3462
      // The addition of the padding extension may push us into the F5 bug.
3463
0
      header_len += 4 + padding_len;
3464
0
    }
3465
3466
    // Add padding to workaround bugs in F5 terminators. See RFC 7685.
3467
    //
3468
    // NB: because this code works out the length of all existing extensions
3469
    // it MUST always appear last (save for any PSK extension).
3470
0
    if (header_len > 0xff && header_len < 0x200) {
3471
      // If our calculations already included a padding extension, remove that
3472
      // factor because we're about to change its length.
3473
0
      if (padding_len != 0) {
3474
0
        header_len -= 4 + padding_len;
3475
0
      }
3476
0
      padding_len = 0x200 - header_len;
3477
      // Extensions take at least four bytes to encode. Always include at least
3478
      // one byte of data if including the extension. WebSphere Application
3479
      // Server 7.0 is intolerant to the last extension being zero-length. See
3480
      // https://crbug.com/363583.
3481
0
      if (padding_len >= 4 + 1) {
3482
0
        padding_len -= 4;
3483
0
      } else {
3484
0
        padding_len = 1;
3485
0
      }
3486
0
    }
3487
3488
0
    if (padding_len != 0 &&
3489
0
        !add_padding_extension(&extensions, TLSEXT_TYPE_padding, padding_len)) {
3490
0
      return false;
3491
0
    }
3492
0
  }
3493
3494
  // The PSK extension must be last, including after the padding.
3495
0
  const size_t len_before = CBB_len(&extensions);
3496
0
  if (!ext_pre_shared_key_add_clienthello(hs, &extensions, out_needs_psk_binder,
3497
0
                                          type)) {
3498
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
3499
0
    return false;
3500
0
  }
3501
0
  assert(psk_extension_len == CBB_len(&extensions) - len_before);
3502
0
  (void)len_before;  // |assert| is omitted in release builds.
3503
3504
  // Discard empty extensions blocks.
3505
0
  if (CBB_len(&extensions) == 0) {
3506
0
    CBB_discard_child(out);
3507
0
  }
3508
3509
0
  return CBB_flush(out);
3510
0
}
3511
3512
0
bool ssl_add_serverhello_tlsext(SSL_HANDSHAKE *hs, CBB *out) {
3513
0
  SSL *const ssl = hs->ssl;
3514
0
  CBB extensions;
3515
0
  if (!CBB_add_u16_length_prefixed(out, &extensions)) {
3516
0
    goto err;
3517
0
  }
3518
3519
0
  for (unsigned i = 0; i < kNumExtensions; i++) {
3520
0
    if (!(hs->extensions.received & (1u << i))) {
3521
      // Don't send extensions that were not received.
3522
0
      continue;
3523
0
    }
3524
3525
0
    if (!kExtensions[i].add_serverhello(hs, &extensions)) {
3526
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_ADDING_EXTENSION);
3527
0
      ERR_add_error_dataf("extension %u", (unsigned)kExtensions[i].value);
3528
0
      goto err;
3529
0
    }
3530
0
  }
3531
3532
  // Discard empty extensions blocks before TLS 1.3.
3533
0
  if (ssl_protocol_version(ssl) < TLS1_3_VERSION &&
3534
0
      CBB_len(&extensions) == 0) {
3535
0
    CBB_discard_child(out);
3536
0
  }
3537
3538
0
  return CBB_flush(out);
3539
3540
0
err:
3541
0
  OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
3542
0
  return false;
3543
0
}
3544
3545
static bool ssl_scan_clienthello_tlsext(SSL_HANDSHAKE *hs,
3546
                                        const SSL_CLIENT_HELLO *client_hello,
3547
0
                                        int *out_alert) {
3548
0
  hs->extensions.received = 0;
3549
0
  CBS extensions;
3550
0
  CBS_init(&extensions, client_hello->extensions, client_hello->extensions_len);
3551
0
  while (CBS_len(&extensions) != 0) {
3552
0
    uint16_t type;
3553
0
    CBS extension;
3554
3555
    // Decode the next extension.
3556
0
    if (!CBS_get_u16(&extensions, &type) ||
3557
0
        !CBS_get_u16_length_prefixed(&extensions, &extension)) {
3558
0
      *out_alert = SSL_AD_DECODE_ERROR;
3559
0
      return false;
3560
0
    }
3561
3562
0
    unsigned ext_index;
3563
0
    const struct tls_extension *const ext =
3564
0
        tls_extension_find(&ext_index, type);
3565
0
    if (ext == NULL) {
3566
0
      continue;
3567
0
    }
3568
3569
0
    hs->extensions.received |= (1u << ext_index);
3570
0
    uint8_t alert = SSL_AD_DECODE_ERROR;
3571
0
    if (!ext->parse_clienthello(hs, &alert, &extension)) {
3572
0
      *out_alert = alert;
3573
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_PARSING_EXTENSION);
3574
0
      ERR_add_error_dataf("extension %u", (unsigned)type);
3575
0
      return false;
3576
0
    }
3577
0
  }
3578
3579
0
  for (size_t i = 0; i < kNumExtensions; i++) {
3580
0
    if (hs->extensions.received & (1u << i)) {
3581
0
      continue;
3582
0
    }
3583
3584
0
    CBS *contents = NULL, fake_contents;
3585
0
    static const uint8_t kFakeRenegotiateExtension[] = {0};
3586
0
    if (kExtensions[i].value == TLSEXT_TYPE_renegotiate &&
3587
0
        ssl_client_cipher_list_contains_cipher(client_hello,
3588
0
                                               SSL3_CK_SCSV & 0xffff)) {
3589
      // The renegotiation SCSV was received so pretend that we received a
3590
      // renegotiation extension.
3591
0
      CBS_init(&fake_contents, kFakeRenegotiateExtension,
3592
0
               sizeof(kFakeRenegotiateExtension));
3593
0
      contents = &fake_contents;
3594
0
      hs->extensions.received |= (1u << i);
3595
0
    }
3596
3597
    // Extension wasn't observed so call the callback with a NULL
3598
    // parameter.
3599
0
    uint8_t alert = SSL_AD_DECODE_ERROR;
3600
0
    if (!kExtensions[i].parse_clienthello(hs, &alert, contents)) {
3601
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
3602
0
      ERR_add_error_dataf("extension %u", (unsigned)kExtensions[i].value);
3603
0
      *out_alert = alert;
3604
0
      return false;
3605
0
    }
3606
0
  }
3607
3608
0
  return true;
3609
0
}
3610
3611
bool ssl_parse_clienthello_tlsext(SSL_HANDSHAKE *hs,
3612
0
                                  const SSL_CLIENT_HELLO *client_hello) {
3613
0
  SSL *const ssl = hs->ssl;
3614
0
  int alert = SSL_AD_DECODE_ERROR;
3615
0
  if (!ssl_scan_clienthello_tlsext(hs, client_hello, &alert)) {
3616
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
3617
0
    return false;
3618
0
  }
3619
3620
0
  if (!ssl_check_clienthello_tlsext(hs)) {
3621
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_TLSEXT);
3622
0
    return false;
3623
0
  }
3624
3625
0
  return true;
3626
0
}
3627
3628
static bool ssl_scan_serverhello_tlsext(SSL_HANDSHAKE *hs, const CBS *cbs,
3629
0
                                        int *out_alert) {
3630
0
  CBS extensions = *cbs;
3631
0
  if (!tls1_check_duplicate_extensions(&extensions)) {
3632
0
    *out_alert = SSL_AD_DECODE_ERROR;
3633
0
    return false;
3634
0
  }
3635
3636
0
  uint32_t received = 0;
3637
0
  while (CBS_len(&extensions) != 0) {
3638
0
    uint16_t type;
3639
0
    CBS extension;
3640
3641
    // Decode the next extension.
3642
0
    if (!CBS_get_u16(&extensions, &type) ||
3643
0
        !CBS_get_u16_length_prefixed(&extensions, &extension)) {
3644
0
      *out_alert = SSL_AD_DECODE_ERROR;
3645
0
      return false;
3646
0
    }
3647
3648
0
    unsigned ext_index;
3649
0
    const struct tls_extension *const ext =
3650
0
        tls_extension_find(&ext_index, type);
3651
3652
0
    if (ext == NULL) {
3653
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
3654
0
      ERR_add_error_dataf("extension %u", (unsigned)type);
3655
0
      *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
3656
0
      return false;
3657
0
    }
3658
3659
0
    static_assert(kNumExtensions <= sizeof(hs->extensions.sent) * 8,
3660
0
                  "too many bits");
3661
3662
0
    if (!(hs->extensions.sent & (1u << ext_index))) {
3663
      // If the extension was never sent then it is illegal.
3664
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
3665
0
      ERR_add_error_dataf("extension :%u", (unsigned)type);
3666
0
      *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
3667
0
      return false;
3668
0
    }
3669
3670
0
    received |= (1u << ext_index);
3671
3672
0
    uint8_t alert = SSL_AD_DECODE_ERROR;
3673
0
    if (!ext->parse_serverhello(hs, &alert, &extension)) {
3674
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_PARSING_EXTENSION);
3675
0
      ERR_add_error_dataf("extension %u", (unsigned)type);
3676
0
      *out_alert = alert;
3677
0
      return false;
3678
0
    }
3679
0
  }
3680
3681
0
  for (size_t i = 0; i < kNumExtensions; i++) {
3682
0
    if (!(received & (1u << i))) {
3683
      // Extension wasn't observed so call the callback with a NULL
3684
      // parameter.
3685
0
      uint8_t alert = SSL_AD_DECODE_ERROR;
3686
0
      if (!kExtensions[i].parse_serverhello(hs, &alert, NULL)) {
3687
0
        OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
3688
0
        ERR_add_error_dataf("extension %u", (unsigned)kExtensions[i].value);
3689
0
        *out_alert = alert;
3690
0
        return false;
3691
0
      }
3692
0
    }
3693
0
  }
3694
3695
0
  return true;
3696
0
}
3697
3698
0
static bool ssl_check_clienthello_tlsext(SSL_HANDSHAKE *hs) {
3699
0
  SSL *const ssl = hs->ssl;
3700
0
  int ret = SSL_TLSEXT_ERR_NOACK;
3701
0
  int al = SSL_AD_UNRECOGNIZED_NAME;
3702
0
  if (ssl->ctx->servername_callback != 0) {
3703
0
    ret = ssl->ctx->servername_callback(ssl, &al, ssl->ctx->servername_arg);
3704
0
  } else if (ssl->session_ctx->servername_callback != 0) {
3705
0
    ret = ssl->session_ctx->servername_callback(
3706
0
        ssl, &al, ssl->session_ctx->servername_arg);
3707
0
  }
3708
3709
0
  switch (ret) {
3710
0
    case SSL_TLSEXT_ERR_ALERT_FATAL:
3711
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, al);
3712
0
      return false;
3713
3714
0
    case SSL_TLSEXT_ERR_NOACK:
3715
0
      hs->should_ack_sni = false;
3716
0
      return true;
3717
3718
0
    default:
3719
0
      return true;
3720
0
  }
3721
0
}
3722
3723
0
static bool ssl_check_serverhello_tlsext(SSL_HANDSHAKE *hs) {
3724
0
  SSL *const ssl = hs->ssl;
3725
  // ALPS and ALPN have a dependency between each other, so we defer checking
3726
  // consistency to after the callbacks run.
3727
0
  if (hs->new_session != nullptr && hs->new_session->has_application_settings) {
3728
    // ALPN must be negotiated.
3729
0
    if (ssl->s3->alpn_selected.empty()) {
3730
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_NEGOTIATED_ALPS_WITHOUT_ALPN);
3731
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
3732
0
      return false;
3733
0
    }
3734
3735
    // The negotiated protocol must be one of the ones we advertised for ALPS.
3736
0
    Span<const uint8_t> settings;
3737
0
    if (!ssl_get_local_application_settings(hs, &settings,
3738
0
                                            ssl->s3->alpn_selected)) {
3739
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_ALPN_PROTOCOL);
3740
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
3741
0
      return false;
3742
0
    }
3743
3744
0
    if (!hs->new_session->local_application_settings.CopyFrom(settings)) {
3745
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3746
0
      return false;
3747
0
    }
3748
0
  }
3749
3750
0
  return true;
3751
0
}
3752
3753
0
bool ssl_parse_serverhello_tlsext(SSL_HANDSHAKE *hs, const CBS *cbs) {
3754
0
  SSL *const ssl = hs->ssl;
3755
0
  int alert = SSL_AD_DECODE_ERROR;
3756
0
  if (!ssl_scan_serverhello_tlsext(hs, cbs, &alert)) {
3757
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
3758
0
    return false;
3759
0
  }
3760
3761
0
  if (!ssl_check_serverhello_tlsext(hs)) {
3762
0
    return false;
3763
0
  }
3764
3765
0
  return true;
3766
0
}
3767
3768
static enum ssl_ticket_aead_result_t decrypt_ticket_with_cipher_ctx(
3769
    Array<uint8_t> *out, EVP_CIPHER_CTX *cipher_ctx, HMAC_CTX *hmac_ctx,
3770
0
    Span<const uint8_t> ticket) {
3771
0
  size_t iv_len = EVP_CIPHER_CTX_iv_length(cipher_ctx);
3772
3773
  // Check the MAC at the end of the ticket.
3774
0
  uint8_t mac[EVP_MAX_MD_SIZE];
3775
0
  size_t mac_len = HMAC_size(hmac_ctx);
3776
0
  if (ticket.size() < SSL_TICKET_KEY_NAME_LEN + iv_len + 1 + mac_len) {
3777
    // The ticket must be large enough for key name, IV, data, and MAC.
3778
0
    return ssl_ticket_aead_ignore_ticket;
3779
0
  }
3780
  // Split the ticket into the ticket and the MAC.
3781
0
  auto ticket_mac = ticket.last(mac_len);
3782
0
  ticket = ticket.first(ticket.size() - mac_len);
3783
0
  HMAC_Update(hmac_ctx, ticket.data(), ticket.size());
3784
0
  HMAC_Final(hmac_ctx, mac, NULL);
3785
0
  assert(mac_len == ticket_mac.size());
3786
0
  bool mac_ok = CRYPTO_memcmp(mac, ticket_mac.data(), mac_len) == 0;
3787
0
#if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
3788
0
  mac_ok = true;
3789
0
#endif
3790
0
  if (!mac_ok) {
3791
0
    return ssl_ticket_aead_ignore_ticket;
3792
0
  }
3793
3794
  // Decrypt the session data.
3795
0
  auto ciphertext = ticket.subspan(SSL_TICKET_KEY_NAME_LEN + iv_len);
3796
0
  Array<uint8_t> plaintext;
3797
0
#if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
3798
0
  if (!plaintext.CopyFrom(ciphertext)) {
3799
0
    return ssl_ticket_aead_error;
3800
0
  }
3801
#else
3802
  if (ciphertext.size() >= INT_MAX) {
3803
    return ssl_ticket_aead_ignore_ticket;
3804
  }
3805
  if (!plaintext.Init(ciphertext.size())) {
3806
    return ssl_ticket_aead_error;
3807
  }
3808
  int len1, len2;
3809
  if (!EVP_DecryptUpdate(cipher_ctx, plaintext.data(), &len1, ciphertext.data(),
3810
                         (int)ciphertext.size()) ||
3811
      !EVP_DecryptFinal_ex(cipher_ctx, plaintext.data() + len1, &len2)) {
3812
    ERR_clear_error();
3813
    return ssl_ticket_aead_ignore_ticket;
3814
  }
3815
  plaintext.Shrink(static_cast<size_t>(len1) + len2);
3816
#endif
3817
3818
0
  *out = std::move(plaintext);
3819
0
  return ssl_ticket_aead_success;
3820
0
}
3821
3822
static enum ssl_ticket_aead_result_t ssl_decrypt_ticket_with_cb(
3823
    SSL_HANDSHAKE *hs, Array<uint8_t> *out, bool *out_renew_ticket,
3824
0
    Span<const uint8_t> ticket) {
3825
0
  assert(ticket.size() >= SSL_TICKET_KEY_NAME_LEN + EVP_MAX_IV_LENGTH);
3826
0
  ScopedEVP_CIPHER_CTX cipher_ctx;
3827
0
  ScopedHMAC_CTX hmac_ctx;
3828
0
  auto name = ticket.subspan(0, SSL_TICKET_KEY_NAME_LEN);
3829
  // The actual IV is shorter, but the length is determined by the callback's
3830
  // chosen cipher. Instead we pass in |EVP_MAX_IV_LENGTH| worth of IV to ensure
3831
  // the callback has enough.
3832
0
  auto iv = ticket.subspan(SSL_TICKET_KEY_NAME_LEN, EVP_MAX_IV_LENGTH);
3833
0
  int cb_ret = hs->ssl->session_ctx->ticket_key_cb(
3834
0
      hs->ssl, const_cast<uint8_t *>(name.data()),
3835
0
      const_cast<uint8_t *>(iv.data()), cipher_ctx.get(), hmac_ctx.get(),
3836
0
      0 /* decrypt */);
3837
0
  if (cb_ret < 0) {
3838
0
    return ssl_ticket_aead_error;
3839
0
  } else if (cb_ret == 0) {
3840
0
    return ssl_ticket_aead_ignore_ticket;
3841
0
  } else if (cb_ret == 2) {
3842
0
    *out_renew_ticket = true;
3843
0
  } else {
3844
0
    assert(cb_ret == 1);
3845
0
  }
3846
0
  return decrypt_ticket_with_cipher_ctx(out, cipher_ctx.get(), hmac_ctx.get(),
3847
0
                                        ticket);
3848
0
}
3849
3850
static enum ssl_ticket_aead_result_t ssl_decrypt_ticket_with_ticket_keys(
3851
0
    SSL_HANDSHAKE *hs, Array<uint8_t> *out, Span<const uint8_t> ticket) {
3852
0
  assert(ticket.size() >= SSL_TICKET_KEY_NAME_LEN + EVP_MAX_IV_LENGTH);
3853
0
  SSL_CTX *ctx = hs->ssl->session_ctx.get();
3854
3855
  // Rotate the ticket key if necessary.
3856
0
  if (!ssl_ctx_rotate_ticket_encryption_key(ctx)) {
3857
0
    return ssl_ticket_aead_error;
3858
0
  }
3859
3860
0
  const EVP_CIPHER *cipher = EVP_aes_128_cbc();
3861
0
  auto name = ticket.subspan(0, SSL_TICKET_KEY_NAME_LEN);
3862
0
  auto iv =
3863
0
      ticket.subspan(SSL_TICKET_KEY_NAME_LEN, EVP_CIPHER_iv_length(cipher));
3864
3865
  // Pick the matching ticket key and decrypt.
3866
0
  ScopedEVP_CIPHER_CTX cipher_ctx;
3867
0
  ScopedHMAC_CTX hmac_ctx;
3868
0
  {
3869
0
    MutexReadLock lock(&ctx->lock);
3870
0
    const TicketKey *key;
3871
0
    if (ctx->ticket_key_current && name == ctx->ticket_key_current->name) {
3872
0
      key = ctx->ticket_key_current.get();
3873
0
    } else if (ctx->ticket_key_prev && name == ctx->ticket_key_prev->name) {
3874
0
      key = ctx->ticket_key_prev.get();
3875
0
    } else {
3876
0
      return ssl_ticket_aead_ignore_ticket;
3877
0
    }
3878
0
    if (!HMAC_Init_ex(hmac_ctx.get(), key->hmac_key, sizeof(key->hmac_key),
3879
0
                      tlsext_tick_md(), NULL) ||
3880
0
        !EVP_DecryptInit_ex(cipher_ctx.get(), cipher, NULL,
3881
0
                            key->aes_key, iv.data())) {
3882
0
      return ssl_ticket_aead_error;
3883
0
    }
3884
0
  }
3885
0
  return decrypt_ticket_with_cipher_ctx(out, cipher_ctx.get(), hmac_ctx.get(),
3886
0
                                        ticket);
3887
0
}
3888
3889
static enum ssl_ticket_aead_result_t ssl_decrypt_ticket_with_method(
3890
    SSL_HANDSHAKE *hs, Array<uint8_t> *out, bool *out_renew_ticket,
3891
0
    Span<const uint8_t> ticket) {
3892
0
  Array<uint8_t> plaintext;
3893
0
  if (!plaintext.Init(ticket.size())) {
3894
0
    return ssl_ticket_aead_error;
3895
0
  }
3896
3897
0
  size_t plaintext_len;
3898
0
  const enum ssl_ticket_aead_result_t result =
3899
0
      hs->ssl->session_ctx->ticket_aead_method->open(
3900
0
          hs->ssl, plaintext.data(), &plaintext_len, ticket.size(),
3901
0
          ticket.data(), ticket.size());
3902
0
  if (result != ssl_ticket_aead_success) {
3903
0
    return result;
3904
0
  }
3905
3906
0
  plaintext.Shrink(plaintext_len);
3907
0
  *out = std::move(plaintext);
3908
0
  return ssl_ticket_aead_success;
3909
0
}
3910
3911
enum ssl_ticket_aead_result_t ssl_process_ticket(
3912
    SSL_HANDSHAKE *hs, UniquePtr<SSL_SESSION> *out_session,
3913
    bool *out_renew_ticket, Span<const uint8_t> ticket,
3914
0
    Span<const uint8_t> session_id) {
3915
0
  SSL *const ssl = hs->ssl;
3916
0
  *out_renew_ticket = false;
3917
0
  out_session->reset();
3918
3919
0
  if ((SSL_get_options(hs->ssl) & SSL_OP_NO_TICKET) ||
3920
0
      session_id.size() > SSL_MAX_SSL_SESSION_ID_LENGTH) {
3921
0
    return ssl_ticket_aead_ignore_ticket;
3922
0
  }
3923
3924
  // Tickets in TLS 1.3 are tied into pre-shared keys (PSKs), unlike in TLS 1.2
3925
  // where that concept doesn't exist. The |decrypted_psk| and |ignore_psk|
3926
  // hints only apply to PSKs. We check the version to determine which this is.
3927
0
  const bool is_psk = ssl_protocol_version(ssl) >= TLS1_3_VERSION;
3928
3929
0
  Array<uint8_t> plaintext;
3930
0
  enum ssl_ticket_aead_result_t result;
3931
0
  SSL_HANDSHAKE_HINTS *const hints = hs->hints.get();
3932
0
  if (is_psk && hints && !hs->hints_requested &&
3933
0
      !hints->decrypted_psk.empty()) {
3934
0
    result = plaintext.CopyFrom(hints->decrypted_psk) ? ssl_ticket_aead_success
3935
0
                                                      : ssl_ticket_aead_error;
3936
0
  } else if (is_psk && hints && !hs->hints_requested && hints->ignore_psk) {
3937
0
    result = ssl_ticket_aead_ignore_ticket;
3938
0
  } else if (!is_psk && hints && !hs->hints_requested &&
3939
0
             !hints->decrypted_ticket.empty()) {
3940
0
    if (plaintext.CopyFrom(hints->decrypted_ticket)) {
3941
0
      result = ssl_ticket_aead_success;
3942
0
      *out_renew_ticket = hints->renew_ticket;
3943
0
    } else {
3944
0
      result = ssl_ticket_aead_error;
3945
0
    }
3946
0
  } else if (!is_psk && hints && !hs->hints_requested && hints->ignore_ticket) {
3947
0
    result = ssl_ticket_aead_ignore_ticket;
3948
0
  } else if (ssl->session_ctx->ticket_aead_method != NULL) {
3949
0
    result = ssl_decrypt_ticket_with_method(hs, &plaintext, out_renew_ticket,
3950
0
                                            ticket);
3951
0
  } else {
3952
    // Ensure there is room for the key name and the largest IV |ticket_key_cb|
3953
    // may try to consume. The real limit may be lower, but the maximum IV
3954
    // length should be well under the minimum size for the session material and
3955
    // HMAC.
3956
0
    if (ticket.size() < SSL_TICKET_KEY_NAME_LEN + EVP_MAX_IV_LENGTH) {
3957
0
      result = ssl_ticket_aead_ignore_ticket;
3958
0
    } else if (ssl->session_ctx->ticket_key_cb != NULL) {
3959
0
      result =
3960
0
          ssl_decrypt_ticket_with_cb(hs, &plaintext, out_renew_ticket, ticket);
3961
0
    } else {
3962
0
      result = ssl_decrypt_ticket_with_ticket_keys(hs, &plaintext, ticket);
3963
0
    }
3964
0
  }
3965
3966
0
  if (hints && hs->hints_requested) {
3967
0
    if (result == ssl_ticket_aead_ignore_ticket) {
3968
0
      if (is_psk) {
3969
0
        hints->ignore_psk = true;
3970
0
      } else {
3971
0
        hints->ignore_ticket = true;
3972
0
      }
3973
0
    } else if (result == ssl_ticket_aead_success) {
3974
0
      if (is_psk) {
3975
0
        if (!hints->decrypted_psk.CopyFrom(plaintext)) {
3976
0
          return ssl_ticket_aead_error;
3977
0
        }
3978
0
      } else {
3979
0
        if (!hints->decrypted_ticket.CopyFrom(plaintext)) {
3980
0
          return ssl_ticket_aead_error;
3981
0
        }
3982
0
        hints->renew_ticket = *out_renew_ticket;
3983
0
      }
3984
0
    }
3985
0
  }
3986
3987
0
  if (result != ssl_ticket_aead_success) {
3988
0
    return result;
3989
0
  }
3990
3991
  // Decode the session.
3992
0
  UniquePtr<SSL_SESSION> session(SSL_SESSION_from_bytes(
3993
0
      plaintext.data(), plaintext.size(), ssl->ctx.get()));
3994
0
  if (!session) {
3995
0
    ERR_clear_error();  // Don't leave an error on the queue.
3996
0
    return ssl_ticket_aead_ignore_ticket;
3997
0
  }
3998
3999
  // Envoy's tests expect the session to have a session ID that matches the
4000
  // placeholder used by the client. It's unclear whether this is a good idea,
4001
  // but we maintain it for now.
4002
0
  SHA256(ticket.data(), ticket.size(), session->session_id);
4003
  // Other consumers may expect a non-empty session ID to indicate resumption.
4004
0
  session->session_id_length = SHA256_DIGEST_LENGTH;
4005
4006
0
  *out_session = std::move(session);
4007
0
  return ssl_ticket_aead_success;
4008
0
}
4009
4010
0
bool tls1_parse_peer_sigalgs(SSL_HANDSHAKE *hs, const CBS *in_sigalgs) {
4011
  // Extension ignored for inappropriate versions
4012
0
  if (ssl_protocol_version(hs->ssl) < TLS1_2_VERSION) {
4013
0
    return true;
4014
0
  }
4015
4016
  // In all contexts, the signature algorithms list may not be empty. (It may be
4017
  // omitted by clients in TLS 1.2, but then the entire extension is omitted.)
4018
0
  return CBS_len(in_sigalgs) != 0 &&
4019
0
         parse_u16_array(in_sigalgs, &hs->peer_sigalgs);
4020
0
}
4021
4022
0
bool tls1_get_legacy_signature_algorithm(uint16_t *out, const EVP_PKEY *pkey) {
4023
0
  switch (EVP_PKEY_id(pkey)) {
4024
0
    case EVP_PKEY_RSA:
4025
0
      *out = SSL_SIGN_RSA_PKCS1_MD5_SHA1;
4026
0
      return true;
4027
0
    case EVP_PKEY_EC:
4028
0
      *out = SSL_SIGN_ECDSA_SHA1;
4029
0
      return true;
4030
0
    default:
4031
0
      return false;
4032
0
  }
4033
0
}
4034
4035
0
bool tls1_choose_signature_algorithm(SSL_HANDSHAKE *hs, uint16_t *out) {
4036
0
  SSL *const ssl = hs->ssl;
4037
0
  CERT *cert = hs->config->cert.get();
4038
0
  DC *dc = cert->dc.get();
4039
4040
  // Before TLS 1.2, the signature algorithm isn't negotiated as part of the
4041
  // handshake.
4042
0
  if (ssl_protocol_version(ssl) < TLS1_2_VERSION) {
4043
0
    if (!tls1_get_legacy_signature_algorithm(out, hs->local_pubkey.get())) {
4044
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_NO_COMMON_SIGNATURE_ALGORITHMS);
4045
0
      return false;
4046
0
    }
4047
0
    return true;
4048
0
  }
4049
4050
0
  Span<const uint16_t> sigalgs = kSignSignatureAlgorithms;
4051
0
  if (ssl_signing_with_dc(hs)) {
4052
0
    sigalgs = MakeConstSpan(&dc->expected_cert_verify_algorithm, 1);
4053
0
  } else if (!cert->sigalgs.empty()) {
4054
0
    sigalgs = cert->sigalgs;
4055
0
  }
4056
4057
0
  Span<const uint16_t> peer_sigalgs = tls1_get_peer_verify_algorithms(hs);
4058
4059
0
  for (uint16_t sigalg : sigalgs) {
4060
0
    if (!ssl_private_key_supports_signature_algorithm(hs, sigalg)) {
4061
0
      continue;
4062
0
    }
4063
4064
0
    for (uint16_t peer_sigalg : peer_sigalgs) {
4065
0
      if (sigalg == peer_sigalg) {
4066
0
        *out = sigalg;
4067
0
        return true;
4068
0
      }
4069
0
    }
4070
0
  }
4071
4072
0
  OPENSSL_PUT_ERROR(SSL, SSL_R_NO_COMMON_SIGNATURE_ALGORITHMS);
4073
0
  return false;
4074
0
}
4075
4076
0
Span<const uint16_t> tls1_get_peer_verify_algorithms(const SSL_HANDSHAKE *hs) {
4077
0
  Span<const uint16_t> peer_sigalgs = hs->peer_sigalgs;
4078
0
  if (peer_sigalgs.empty() && ssl_protocol_version(hs->ssl) < TLS1_3_VERSION) {
4079
    // If the client didn't specify any signature_algorithms extension then
4080
    // we can assume that it supports SHA1. See
4081
    // http://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
4082
0
    static const uint16_t kDefaultPeerAlgorithms[] = {SSL_SIGN_RSA_PKCS1_SHA1,
4083
0
                                                      SSL_SIGN_ECDSA_SHA1};
4084
0
    peer_sigalgs = kDefaultPeerAlgorithms;
4085
0
  }
4086
0
  return peer_sigalgs;
4087
0
}
4088
4089
0
bool tls1_verify_channel_id(SSL_HANDSHAKE *hs, const SSLMessage &msg) {
4090
0
  SSL *const ssl = hs->ssl;
4091
  // A Channel ID handshake message is structured to contain multiple
4092
  // extensions, but the only one that can be present is Channel ID.
4093
0
  uint16_t extension_type;
4094
0
  CBS channel_id = msg.body, extension;
4095
0
  if (!CBS_get_u16(&channel_id, &extension_type) ||
4096
0
      !CBS_get_u16_length_prefixed(&channel_id, &extension) ||
4097
0
      CBS_len(&channel_id) != 0 ||
4098
0
      extension_type != TLSEXT_TYPE_channel_id ||
4099
0
      CBS_len(&extension) != TLSEXT_CHANNEL_ID_SIZE) {
4100
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
4101
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
4102
0
    return false;
4103
0
  }
4104
4105
0
  UniquePtr<EC_GROUP> p256(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
4106
0
  if (!p256) {
4107
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_NO_P256_SUPPORT);
4108
0
    return false;
4109
0
  }
4110
4111
0
  UniquePtr<ECDSA_SIG> sig(ECDSA_SIG_new());
4112
0
  UniquePtr<BIGNUM> x(BN_new()), y(BN_new());
4113
0
  if (!sig || !x || !y) {
4114
0
    return false;
4115
0
  }
4116
4117
0
  const uint8_t *p = CBS_data(&extension);
4118
0
  if (BN_bin2bn(p + 0, 32, x.get()) == NULL ||
4119
0
      BN_bin2bn(p + 32, 32, y.get()) == NULL ||
4120
0
      BN_bin2bn(p + 64, 32, sig->r) == NULL ||
4121
0
      BN_bin2bn(p + 96, 32, sig->s) == NULL) {
4122
0
    return false;
4123
0
  }
4124
4125
0
  UniquePtr<EC_KEY> key(EC_KEY_new());
4126
0
  UniquePtr<EC_POINT> point(EC_POINT_new(p256.get()));
4127
0
  if (!key || !point ||
4128
0
      !EC_POINT_set_affine_coordinates_GFp(p256.get(), point.get(), x.get(),
4129
0
                                           y.get(), nullptr) ||
4130
0
      !EC_KEY_set_group(key.get(), p256.get()) ||
4131
0
      !EC_KEY_set_public_key(key.get(), point.get())) {
4132
0
    return false;
4133
0
  }
4134
4135
0
  uint8_t digest[EVP_MAX_MD_SIZE];
4136
0
  size_t digest_len;
4137
0
  if (!tls1_channel_id_hash(hs, digest, &digest_len)) {
4138
0
    return false;
4139
0
  }
4140
4141
0
  bool sig_ok = ECDSA_do_verify(digest, digest_len, sig.get(), key.get());
4142
0
#if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
4143
0
  sig_ok = true;
4144
0
  ERR_clear_error();
4145
0
#endif
4146
0
  if (!sig_ok) {
4147
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_CHANNEL_ID_SIGNATURE_INVALID);
4148
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
4149
0
    return false;
4150
0
  }
4151
4152
0
  OPENSSL_memcpy(ssl->s3->channel_id, p, 64);
4153
0
  ssl->s3->channel_id_valid = true;
4154
0
  return true;
4155
0
}
4156
4157
0
bool tls1_write_channel_id(SSL_HANDSHAKE *hs, CBB *cbb) {
4158
0
  uint8_t digest[EVP_MAX_MD_SIZE];
4159
0
  size_t digest_len;
4160
0
  if (!tls1_channel_id_hash(hs, digest, &digest_len)) {
4161
0
    return false;
4162
0
  }
4163
4164
0
  EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(hs->config->channel_id_private.get());
4165
0
  if (ec_key == nullptr) {
4166
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
4167
0
    return false;
4168
0
  }
4169
4170
0
  UniquePtr<BIGNUM> x(BN_new()), y(BN_new());
4171
0
  if (!x || !y ||
4172
0
      !EC_POINT_get_affine_coordinates_GFp(EC_KEY_get0_group(ec_key),
4173
0
                                           EC_KEY_get0_public_key(ec_key),
4174
0
                                           x.get(), y.get(), nullptr)) {
4175
0
    return false;
4176
0
  }
4177
4178
0
  UniquePtr<ECDSA_SIG> sig(ECDSA_do_sign(digest, digest_len, ec_key));
4179
0
  if (!sig) {
4180
0
    return false;
4181
0
  }
4182
4183
0
  CBB child;
4184
0
  if (!CBB_add_u16(cbb, TLSEXT_TYPE_channel_id) ||
4185
0
      !CBB_add_u16_length_prefixed(cbb, &child) ||
4186
0
      !BN_bn2cbb_padded(&child, 32, x.get()) ||
4187
0
      !BN_bn2cbb_padded(&child, 32, y.get()) ||
4188
0
      !BN_bn2cbb_padded(&child, 32, sig->r) ||
4189
0
      !BN_bn2cbb_padded(&child, 32, sig->s) ||
4190
0
      !CBB_flush(cbb)) {
4191
0
    return false;
4192
0
  }
4193
4194
0
  return true;
4195
0
}
4196
4197
0
bool tls1_channel_id_hash(SSL_HANDSHAKE *hs, uint8_t *out, size_t *out_len) {
4198
0
  SSL *const ssl = hs->ssl;
4199
0
  if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
4200
0
    Array<uint8_t> msg;
4201
0
    if (!tls13_get_cert_verify_signature_input(hs, &msg,
4202
0
                                               ssl_cert_verify_channel_id)) {
4203
0
      return false;
4204
0
    }
4205
0
    SHA256(msg.data(), msg.size(), out);
4206
0
    *out_len = SHA256_DIGEST_LENGTH;
4207
0
    return true;
4208
0
  }
4209
4210
0
  SHA256_CTX ctx;
4211
4212
0
  SHA256_Init(&ctx);
4213
0
  static const char kClientIDMagic[] = "TLS Channel ID signature";
4214
0
  SHA256_Update(&ctx, kClientIDMagic, sizeof(kClientIDMagic));
4215
4216
0
  if (ssl->session != NULL) {
4217
0
    static const char kResumptionMagic[] = "Resumption";
4218
0
    SHA256_Update(&ctx, kResumptionMagic, sizeof(kResumptionMagic));
4219
0
    if (ssl->session->original_handshake_hash_len == 0) {
4220
0
      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
4221
0
      return false;
4222
0
    }
4223
0
    SHA256_Update(&ctx, ssl->session->original_handshake_hash,
4224
0
                  ssl->session->original_handshake_hash_len);
4225
0
  }
4226
4227
0
  uint8_t hs_hash[EVP_MAX_MD_SIZE];
4228
0
  size_t hs_hash_len;
4229
0
  if (!hs->transcript.GetHash(hs_hash, &hs_hash_len)) {
4230
0
    return false;
4231
0
  }
4232
0
  SHA256_Update(&ctx, hs_hash, (size_t)hs_hash_len);
4233
0
  SHA256_Final(out, &ctx);
4234
0
  *out_len = SHA256_DIGEST_LENGTH;
4235
0
  return true;
4236
0
}
4237
4238
0
bool tls1_record_handshake_hashes_for_channel_id(SSL_HANDSHAKE *hs) {
4239
0
  SSL *const ssl = hs->ssl;
4240
  // This function should never be called for a resumed session because the
4241
  // handshake hashes that we wish to record are for the original, full
4242
  // handshake.
4243
0
  if (ssl->session != NULL) {
4244
0
    return false;
4245
0
  }
4246
4247
0
  static_assert(
4248
0
      sizeof(hs->new_session->original_handshake_hash) == EVP_MAX_MD_SIZE,
4249
0
      "original_handshake_hash is too small");
4250
4251
0
  size_t digest_len;
4252
0
  if (!hs->transcript.GetHash(hs->new_session->original_handshake_hash,
4253
0
                              &digest_len)) {
4254
0
    return false;
4255
0
  }
4256
4257
0
  static_assert(EVP_MAX_MD_SIZE <= 0xff,
4258
0
                "EVP_MAX_MD_SIZE does not fit in uint8_t");
4259
0
  hs->new_session->original_handshake_hash_len = (uint8_t)digest_len;
4260
4261
0
  return true;
4262
0
}
4263
4264
0
bool ssl_is_sct_list_valid(const CBS *contents) {
4265
  // Shallow parse the SCT list for sanity. By the RFC
4266
  // (https://tools.ietf.org/html/rfc6962#section-3.3) neither the list nor any
4267
  // of the SCTs may be empty.
4268
0
  CBS copy = *contents;
4269
0
  CBS sct_list;
4270
0
  if (!CBS_get_u16_length_prefixed(&copy, &sct_list) ||
4271
0
      CBS_len(&copy) != 0 ||
4272
0
      CBS_len(&sct_list) == 0) {
4273
0
    return false;
4274
0
  }
4275
4276
0
  while (CBS_len(&sct_list) > 0) {
4277
0
    CBS sct;
4278
0
    if (!CBS_get_u16_length_prefixed(&sct_list, &sct) ||
4279
0
        CBS_len(&sct) == 0) {
4280
0
      return false;
4281
0
    }
4282
0
  }
4283
4284
0
  return true;
4285
0
}
4286
4287
BSSL_NAMESPACE_END
4288
4289
using namespace bssl;
4290
4291
int SSL_early_callback_ctx_extension_get(const SSL_CLIENT_HELLO *client_hello,
4292
                                         uint16_t extension_type,
4293
                                         const uint8_t **out_data,
4294
0
                                         size_t *out_len) {
4295
0
  CBS cbs;
4296
0
  if (!ssl_client_hello_get_extension(client_hello, &cbs, extension_type)) {
4297
0
    return 0;
4298
0
  }
4299
4300
0
  *out_data = CBS_data(&cbs);
4301
0
  *out_len = CBS_len(&cbs);
4302
0
  return 1;
4303
0
}