1 /* Copyright (c) 2021, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
15 #include <openssl/ssl.h>
16
17 #include <assert.h>
18 #include <string.h>
19
20 #include <algorithm>
21 #include <utility>
22
23 #include <openssl/aead.h>
24 #include <openssl/bytestring.h>
25 #include <openssl/curve25519.h>
26 #include <openssl/err.h>
27 #include <openssl/hkdf.h>
28 #include <openssl/hpke.h>
29 #include <openssl/rand.h>
30
31 #include "internal.h"
32
33
34 BSSL_NAMESPACE_BEGIN
35
36 // ECH reuses the extension code point for the version number.
37 static constexpr uint16_t kECHConfigVersion =
38 TLSEXT_TYPE_encrypted_client_hello;
39
40 static const decltype(&EVP_hpke_aes_128_gcm) kSupportedAEADs[] = {
41 &EVP_hpke_aes_128_gcm,
42 &EVP_hpke_aes_256_gcm,
43 &EVP_hpke_chacha20_poly1305,
44 };
45
get_ech_aead(uint16_t aead_id)46 static const EVP_HPKE_AEAD *get_ech_aead(uint16_t aead_id) {
47 for (const auto aead_func : kSupportedAEADs) {
48 const EVP_HPKE_AEAD *aead = aead_func();
49 if (aead_id == EVP_HPKE_AEAD_id(aead)) {
50 return aead;
51 }
52 }
53 return nullptr;
54 }
55
56 // ssl_client_hello_write_without_extensions serializes |client_hello| into
57 // |out|, omitting the length-prefixed extensions. It serializes individual
58 // fields, starting with |client_hello->version|, and ignores the
59 // |client_hello->client_hello| field. It returns true on success and false on
60 // failure.
ssl_client_hello_write_without_extensions(const SSL_CLIENT_HELLO * client_hello,CBB * out)61 static bool ssl_client_hello_write_without_extensions(
62 const SSL_CLIENT_HELLO *client_hello, CBB *out) {
63 CBB cbb;
64 if (!CBB_add_u16(out, client_hello->version) ||
65 !CBB_add_bytes(out, client_hello->random, client_hello->random_len) ||
66 !CBB_add_u8_length_prefixed(out, &cbb) ||
67 !CBB_add_bytes(&cbb, client_hello->session_id,
68 client_hello->session_id_len) ||
69 !CBB_add_u16_length_prefixed(out, &cbb) ||
70 !CBB_add_bytes(&cbb, client_hello->cipher_suites,
71 client_hello->cipher_suites_len) ||
72 !CBB_add_u8_length_prefixed(out, &cbb) ||
73 !CBB_add_bytes(&cbb, client_hello->compression_methods,
74 client_hello->compression_methods_len) ||
75 !CBB_flush(out)) {
76 return false;
77 }
78 return true;
79 }
80
is_valid_client_hello_inner(SSL * ssl,uint8_t * out_alert,Span<const uint8_t> body)81 static bool is_valid_client_hello_inner(SSL *ssl, uint8_t *out_alert,
82 Span<const uint8_t> body) {
83 // See draft-ietf-tls-esni-13, section 7.1.
84 SSL_CLIENT_HELLO client_hello;
85 CBS extension;
86 if (!ssl_client_hello_init(ssl, &client_hello, body) ||
87 !ssl_client_hello_get_extension(&client_hello, &extension,
88 TLSEXT_TYPE_encrypted_client_hello) ||
89 CBS_len(&extension) != 1 || //
90 CBS_data(&extension)[0] != ECH_CLIENT_INNER ||
91 !ssl_client_hello_get_extension(&client_hello, &extension,
92 TLSEXT_TYPE_supported_versions)) {
93 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
94 OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_CLIENT_HELLO_INNER);
95 return false;
96 }
97 // Parse supported_versions and reject TLS versions prior to TLS 1.3. Older
98 // versions are incompatible with ECH.
99 CBS versions;
100 if (!CBS_get_u8_length_prefixed(&extension, &versions) ||
101 CBS_len(&extension) != 0 || //
102 CBS_len(&versions) == 0) {
103 *out_alert = SSL_AD_DECODE_ERROR;
104 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
105 return false;
106 }
107 while (CBS_len(&versions) != 0) {
108 uint16_t version;
109 if (!CBS_get_u16(&versions, &version)) {
110 *out_alert = SSL_AD_DECODE_ERROR;
111 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
112 return false;
113 }
114 if (version == SSL3_VERSION || version == TLS1_VERSION ||
115 version == TLS1_1_VERSION || version == TLS1_2_VERSION ||
116 version == DTLS1_VERSION || version == DTLS1_2_VERSION) {
117 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
118 OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_CLIENT_HELLO_INNER);
119 return false;
120 }
121 }
122 return true;
123 }
124
ssl_decode_client_hello_inner(SSL * ssl,uint8_t * out_alert,Array<uint8_t> * out_client_hello_inner,Span<const uint8_t> encoded_client_hello_inner,const SSL_CLIENT_HELLO * client_hello_outer)125 bool ssl_decode_client_hello_inner(
126 SSL *ssl, uint8_t *out_alert, Array<uint8_t> *out_client_hello_inner,
127 Span<const uint8_t> encoded_client_hello_inner,
128 const SSL_CLIENT_HELLO *client_hello_outer) {
129 SSL_CLIENT_HELLO client_hello_inner;
130 CBS cbs = encoded_client_hello_inner;
131 if (!ssl_parse_client_hello_with_trailing_data(ssl, &cbs,
132 &client_hello_inner)) {
133 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
134 return false;
135 }
136 // The remaining data is padding.
137 uint8_t padding;
138 while (CBS_get_u8(&cbs, &padding)) {
139 if (padding != 0) {
140 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
141 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
142 return false;
143 }
144 }
145
146 // TLS 1.3 ClientHellos must have extensions, and EncodedClientHelloInners use
147 // ClientHelloOuter's session_id.
148 if (client_hello_inner.extensions_len == 0 ||
149 client_hello_inner.session_id_len != 0) {
150 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
151 return false;
152 }
153 client_hello_inner.session_id = client_hello_outer->session_id;
154 client_hello_inner.session_id_len = client_hello_outer->session_id_len;
155
156 // Begin serializing a message containing the ClientHelloInner in |cbb|.
157 ScopedCBB cbb;
158 CBB body, extensions_cbb;
159 if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_CLIENT_HELLO) ||
160 !ssl_client_hello_write_without_extensions(&client_hello_inner, &body) ||
161 !CBB_add_u16_length_prefixed(&body, &extensions_cbb)) {
162 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
163 return false;
164 }
165
166 auto inner_extensions = MakeConstSpan(client_hello_inner.extensions,
167 client_hello_inner.extensions_len);
168 CBS ext_list_wrapper;
169 if (!ssl_client_hello_get_extension(&client_hello_inner, &ext_list_wrapper,
170 TLSEXT_TYPE_ech_outer_extensions)) {
171 // No ech_outer_extensions. Copy everything.
172 if (!CBB_add_bytes(&extensions_cbb, inner_extensions.data(),
173 inner_extensions.size())) {
174 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
175 return false;
176 }
177 } else {
178 const size_t offset = CBS_data(&ext_list_wrapper) - inner_extensions.data();
179 auto inner_extensions_before =
180 inner_extensions.subspan(0, offset - 4 /* extension header */);
181 auto inner_extensions_after =
182 inner_extensions.subspan(offset + CBS_len(&ext_list_wrapper));
183 if (!CBB_add_bytes(&extensions_cbb, inner_extensions_before.data(),
184 inner_extensions_before.size())) {
185 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
186 return false;
187 }
188
189 // Expand ech_outer_extensions. See draft-ietf-tls-esni-13, Appendix B.
190 CBS ext_list;
191 if (!CBS_get_u8_length_prefixed(&ext_list_wrapper, &ext_list) ||
192 CBS_len(&ext_list) == 0 || CBS_len(&ext_list_wrapper) != 0) {
193 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
194 return false;
195 }
196 CBS outer_extensions;
197 CBS_init(&outer_extensions, client_hello_outer->extensions,
198 client_hello_outer->extensions_len);
199 while (CBS_len(&ext_list) != 0) {
200 // Find the next extension to copy.
201 uint16_t want;
202 if (!CBS_get_u16(&ext_list, &want)) {
203 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
204 return false;
205 }
206 // The ECH extension itself is not in the AAD and may not be referenced.
207 if (want == TLSEXT_TYPE_encrypted_client_hello) {
208 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
209 OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_OUTER_EXTENSION);
210 return false;
211 }
212 // Seek to |want| in |outer_extensions|. |ext_list| is required to match
213 // ClientHelloOuter in order.
214 uint16_t found;
215 CBS ext_body;
216 do {
217 if (CBS_len(&outer_extensions) == 0) {
218 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
219 OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_OUTER_EXTENSION);
220 return false;
221 }
222 if (!CBS_get_u16(&outer_extensions, &found) ||
223 !CBS_get_u16_length_prefixed(&outer_extensions, &ext_body)) {
224 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
225 return false;
226 }
227 } while (found != want);
228 // Copy the extension.
229 if (!CBB_add_u16(&extensions_cbb, found) ||
230 !CBB_add_u16(&extensions_cbb, CBS_len(&ext_body)) ||
231 !CBB_add_bytes(&extensions_cbb, CBS_data(&ext_body),
232 CBS_len(&ext_body))) {
233 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
234 return false;
235 }
236 }
237
238 if (!CBB_add_bytes(&extensions_cbb, inner_extensions_after.data(),
239 inner_extensions_after.size())) {
240 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
241 return false;
242 }
243 }
244 if (!CBB_flush(&body)) {
245 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
246 return false;
247 }
248
249 if (!is_valid_client_hello_inner(
250 ssl, out_alert, MakeConstSpan(CBB_data(&body), CBB_len(&body)))) {
251 return false;
252 }
253
254 if (!ssl->method->finish_message(ssl, cbb.get(), out_client_hello_inner)) {
255 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
256 return false;
257 }
258 return true;
259 }
260
ssl_client_hello_decrypt(SSL_HANDSHAKE * hs,uint8_t * out_alert,bool * out_is_decrypt_error,Array<uint8_t> * out,const SSL_CLIENT_HELLO * client_hello_outer,Span<const uint8_t> payload)261 bool ssl_client_hello_decrypt(SSL_HANDSHAKE *hs, uint8_t *out_alert,
262 bool *out_is_decrypt_error, Array<uint8_t> *out,
263 const SSL_CLIENT_HELLO *client_hello_outer,
264 Span<const uint8_t> payload) {
265 *out_is_decrypt_error = false;
266
267 // The ClientHelloOuterAAD is |client_hello_outer| with |payload| (which must
268 // point within |client_hello_outer->extensions|) replaced with zeros. See
269 // draft-ietf-tls-esni-13, section 5.2.
270 Array<uint8_t> aad;
271 if (!aad.CopyFrom(MakeConstSpan(client_hello_outer->client_hello,
272 client_hello_outer->client_hello_len))) {
273 *out_alert = SSL_AD_INTERNAL_ERROR;
274 return false;
275 }
276
277 // We assert with |uintptr_t| because the comparison would be UB if they
278 // didn't alias.
279 assert(reinterpret_cast<uintptr_t>(client_hello_outer->extensions) <=
280 reinterpret_cast<uintptr_t>(payload.data()));
281 assert(reinterpret_cast<uintptr_t>(client_hello_outer->extensions +
282 client_hello_outer->extensions_len) >=
283 reinterpret_cast<uintptr_t>(payload.data() + payload.size()));
284 Span<uint8_t> payload_aad = MakeSpan(aad).subspan(
285 payload.data() - client_hello_outer->client_hello, payload.size());
286 OPENSSL_memset(payload_aad.data(), 0, payload_aad.size());
287
288 // Decrypt the EncodedClientHelloInner.
289 Array<uint8_t> encoded;
290 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
291 // In fuzzer mode, disable encryption to improve coverage. We reserve a short
292 // input to signal decryption failure, so the fuzzer can explore fallback to
293 // ClientHelloOuter.
294 const uint8_t kBadPayload[] = {0xff};
295 if (payload == kBadPayload) {
296 *out_alert = SSL_AD_DECRYPT_ERROR;
297 *out_is_decrypt_error = true;
298 OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
299 return false;
300 }
301 if (!encoded.CopyFrom(payload)) {
302 *out_alert = SSL_AD_INTERNAL_ERROR;
303 return false;
304 }
305 #else
306 if (!encoded.Init(payload.size())) {
307 *out_alert = SSL_AD_INTERNAL_ERROR;
308 return false;
309 }
310 size_t len;
311 if (!EVP_HPKE_CTX_open(hs->ech_hpke_ctx.get(), encoded.data(), &len,
312 encoded.size(), payload.data(), payload.size(),
313 aad.data(), aad.size())) {
314 *out_alert = SSL_AD_DECRYPT_ERROR;
315 *out_is_decrypt_error = true;
316 OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
317 return false;
318 }
319 encoded.Shrink(len);
320 #endif
321
322 if (!ssl_decode_client_hello_inner(hs->ssl, out_alert, out, encoded,
323 client_hello_outer)) {
324 return false;
325 }
326
327 ssl_do_msg_callback(hs->ssl, /*is_write=*/0, SSL3_RT_CLIENT_HELLO_INNER,
328 *out);
329 return true;
330 }
331
is_hex_component(Span<const uint8_t> in)332 static bool is_hex_component(Span<const uint8_t> in) {
333 if (in.size() < 2 || in[0] != '0' || (in[1] != 'x' && in[1] != 'X')) {
334 return false;
335 }
336 for (uint8_t b : in.subspan(2)) {
337 if (!('0' <= b && b <= '9') && !('a' <= b && b <= 'f') &&
338 !('A' <= b && b <= 'F')) {
339 return false;
340 }
341 }
342 return true;
343 }
344
is_decimal_component(Span<const uint8_t> in)345 static bool is_decimal_component(Span<const uint8_t> in) {
346 if (in.empty()) {
347 return false;
348 }
349 for (uint8_t b : in) {
350 if (!('0' <= b && b <= '9')) {
351 return false;
352 }
353 }
354 return true;
355 }
356
ssl_is_valid_ech_public_name(Span<const uint8_t> public_name)357 bool ssl_is_valid_ech_public_name(Span<const uint8_t> public_name) {
358 // See draft-ietf-tls-esni-13, Section 4 and RFC 5890, Section 2.3.1. The
359 // public name must be a dot-separated sequence of LDH labels and not begin or
360 // end with a dot.
361 auto remaining = public_name;
362 if (remaining.empty()) {
363 return false;
364 }
365 Span<const uint8_t> last;
366 while (!remaining.empty()) {
367 // Find the next dot-separated component.
368 auto dot = std::find(remaining.begin(), remaining.end(), '.');
369 Span<const uint8_t> component;
370 if (dot == remaining.end()) {
371 component = remaining;
372 last = component;
373 remaining = Span<const uint8_t>();
374 } else {
375 component = remaining.subspan(0, dot - remaining.begin());
376 // Skip the dot.
377 remaining = remaining.subspan(dot - remaining.begin() + 1);
378 if (remaining.empty()) {
379 // Trailing dots are not allowed.
380 return false;
381 }
382 }
383 // |component| must be a valid LDH label. Checking for empty components also
384 // rejects leading dots.
385 if (component.empty() || component.size() > 63 ||
386 component.front() == '-' || component.back() == '-') {
387 return false;
388 }
389 for (uint8_t c : component) {
390 if (!('a' <= c && c <= 'z') && !('A' <= c && c <= 'Z') &&
391 !('0' <= c && c <= '9') && c != '-') {
392 return false;
393 }
394 }
395 }
396
397 // The WHATWG URL parser additionally does not allow any DNS names that end in
398 // a numeric component. See:
399 // https://url.spec.whatwg.org/#concept-host-parser
400 // https://url.spec.whatwg.org/#ends-in-a-number-checker
401 //
402 // The WHATWG parser is formulated in terms of parsing decimal, octal, and
403 // hex, along with a separate ASCII digits check. The ASCII digits check
404 // subsumes the decimal and octal check, so we only need to check two cases.
405 return !is_hex_component(last) && !is_decimal_component(last);
406 }
407
parse_ech_config(CBS * cbs,ECHConfig * out,bool * out_supported,bool all_extensions_mandatory)408 static bool parse_ech_config(CBS *cbs, ECHConfig *out, bool *out_supported,
409 bool all_extensions_mandatory) {
410 uint16_t version;
411 CBS orig = *cbs;
412 CBS contents;
413 if (!CBS_get_u16(cbs, &version) ||
414 !CBS_get_u16_length_prefixed(cbs, &contents)) {
415 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
416 return false;
417 }
418
419 if (version != kECHConfigVersion) {
420 *out_supported = false;
421 return true;
422 }
423
424 // Make a copy of the ECHConfig and parse from it, so the results alias into
425 // the saved copy.
426 if (!out->raw.CopyFrom(
427 MakeConstSpan(CBS_data(&orig), CBS_len(&orig) - CBS_len(cbs)))) {
428 return false;
429 }
430
431 CBS ech_config(out->raw);
432 CBS public_name, public_key, cipher_suites, extensions;
433 if (!CBS_skip(&ech_config, 2) || // version
434 !CBS_get_u16_length_prefixed(&ech_config, &contents) ||
435 !CBS_get_u8(&contents, &out->config_id) ||
436 !CBS_get_u16(&contents, &out->kem_id) ||
437 !CBS_get_u16_length_prefixed(&contents, &public_key) ||
438 CBS_len(&public_key) == 0 ||
439 !CBS_get_u16_length_prefixed(&contents, &cipher_suites) ||
440 CBS_len(&cipher_suites) == 0 || CBS_len(&cipher_suites) % 4 != 0 ||
441 !CBS_get_u8(&contents, &out->maximum_name_length) ||
442 !CBS_get_u8_length_prefixed(&contents, &public_name) ||
443 CBS_len(&public_name) == 0 ||
444 !CBS_get_u16_length_prefixed(&contents, &extensions) ||
445 CBS_len(&contents) != 0) {
446 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
447 return false;
448 }
449
450 if (!ssl_is_valid_ech_public_name(public_name)) {
451 // TODO(https://crbug.com/boringssl/275): The draft says ECHConfigs with
452 // invalid public names should be ignored, but LDH syntax failures are
453 // unambiguously invalid.
454 *out_supported = false;
455 return true;
456 }
457
458 out->public_key = public_key;
459 out->public_name = public_name;
460 // This function does not ensure |out->kem_id| and |out->cipher_suites| use
461 // supported algorithms. The caller must do this.
462 out->cipher_suites = cipher_suites;
463
464 bool has_unknown_mandatory_extension = false;
465 while (CBS_len(&extensions) != 0) {
466 uint16_t type;
467 CBS body;
468 if (!CBS_get_u16(&extensions, &type) ||
469 !CBS_get_u16_length_prefixed(&extensions, &body)) {
470 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
471 return false;
472 }
473 // We currently do not support any extensions.
474 if (type & 0x8000 || all_extensions_mandatory) {
475 // Extension numbers with the high bit set are mandatory. Continue parsing
476 // to enforce syntax, but we will ultimately ignore this ECHConfig as a
477 // client and reject it as a server.
478 has_unknown_mandatory_extension = true;
479 }
480 }
481
482 *out_supported = !has_unknown_mandatory_extension;
483 return true;
484 }
485
Init(Span<const uint8_t> ech_config,const EVP_HPKE_KEY * key,bool is_retry_config)486 bool ECHServerConfig::Init(Span<const uint8_t> ech_config,
487 const EVP_HPKE_KEY *key, bool is_retry_config) {
488 is_retry_config_ = is_retry_config;
489
490 // Parse the ECHConfig, rejecting all unsupported parameters and extensions.
491 // Unlike most server options, ECH's server configuration is serialized and
492 // configured in both the server and DNS. If the caller configures an
493 // unsupported parameter, this is a deployment error. To catch these errors,
494 // we fail early.
495 CBS cbs = ech_config;
496 bool supported;
497 if (!parse_ech_config(&cbs, &ech_config_, &supported,
498 /*all_extensions_mandatory=*/true)) {
499 return false;
500 }
501 if (CBS_len(&cbs) != 0) {
502 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
503 return false;
504 }
505 if (!supported) {
506 OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_ECH_SERVER_CONFIG);
507 return false;
508 }
509
510 CBS cipher_suites = ech_config_.cipher_suites;
511 while (CBS_len(&cipher_suites) > 0) {
512 uint16_t kdf_id, aead_id;
513 if (!CBS_get_u16(&cipher_suites, &kdf_id) ||
514 !CBS_get_u16(&cipher_suites, &aead_id)) {
515 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
516 return false;
517 }
518 // The server promises to support every option in the ECHConfig, so reject
519 // any unsupported cipher suites.
520 if (kdf_id != EVP_HPKE_HKDF_SHA256 || get_ech_aead(aead_id) == nullptr) {
521 OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_ECH_SERVER_CONFIG);
522 return false;
523 }
524 }
525
526 // Check the public key in the ECHConfig matches |key|.
527 uint8_t expected_public_key[EVP_HPKE_MAX_PUBLIC_KEY_LENGTH];
528 size_t expected_public_key_len;
529 if (!EVP_HPKE_KEY_public_key(key, expected_public_key,
530 &expected_public_key_len,
531 sizeof(expected_public_key))) {
532 return false;
533 }
534 if (ech_config_.kem_id != EVP_HPKE_KEM_id(EVP_HPKE_KEY_kem(key)) ||
535 MakeConstSpan(expected_public_key, expected_public_key_len) !=
536 ech_config_.public_key) {
537 OPENSSL_PUT_ERROR(SSL, SSL_R_ECH_SERVER_CONFIG_AND_PRIVATE_KEY_MISMATCH);
538 return false;
539 }
540
541 if (!EVP_HPKE_KEY_copy(key_.get(), key)) {
542 return false;
543 }
544
545 return true;
546 }
547
SetupContext(EVP_HPKE_CTX * ctx,uint16_t kdf_id,uint16_t aead_id,Span<const uint8_t> enc) const548 bool ECHServerConfig::SetupContext(EVP_HPKE_CTX *ctx, uint16_t kdf_id,
549 uint16_t aead_id,
550 Span<const uint8_t> enc) const {
551 // Check the cipher suite is supported by this ECHServerConfig.
552 CBS cbs(ech_config_.cipher_suites);
553 bool cipher_ok = false;
554 while (CBS_len(&cbs) != 0) {
555 uint16_t supported_kdf_id, supported_aead_id;
556 if (!CBS_get_u16(&cbs, &supported_kdf_id) ||
557 !CBS_get_u16(&cbs, &supported_aead_id)) {
558 return false;
559 }
560 if (kdf_id == supported_kdf_id && aead_id == supported_aead_id) {
561 cipher_ok = true;
562 break;
563 }
564 }
565 if (!cipher_ok) {
566 return false;
567 }
568
569 static const uint8_t kInfoLabel[] = "tls ech";
570 ScopedCBB info_cbb;
571 if (!CBB_init(info_cbb.get(), sizeof(kInfoLabel) + ech_config_.raw.size()) ||
572 !CBB_add_bytes(info_cbb.get(), kInfoLabel,
573 sizeof(kInfoLabel) /* includes trailing NUL */) ||
574 !CBB_add_bytes(info_cbb.get(), ech_config_.raw.data(),
575 ech_config_.raw.size())) {
576 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
577 return false;
578 }
579
580 assert(kdf_id == EVP_HPKE_HKDF_SHA256);
581 assert(get_ech_aead(aead_id) != NULL);
582 return EVP_HPKE_CTX_setup_recipient(
583 ctx, key_.get(), EVP_hpke_hkdf_sha256(), get_ech_aead(aead_id), enc.data(),
584 enc.size(), CBB_data(info_cbb.get()), CBB_len(info_cbb.get()));
585 }
586
ssl_is_valid_ech_config_list(Span<const uint8_t> ech_config_list)587 bool ssl_is_valid_ech_config_list(Span<const uint8_t> ech_config_list) {
588 CBS cbs = ech_config_list, child;
589 if (!CBS_get_u16_length_prefixed(&cbs, &child) || //
590 CBS_len(&child) == 0 || //
591 CBS_len(&cbs) > 0) {
592 return false;
593 }
594 while (CBS_len(&child) > 0) {
595 ECHConfig ech_config;
596 bool supported;
597 if (!parse_ech_config(&child, &ech_config, &supported,
598 /*all_extensions_mandatory=*/false)) {
599 return false;
600 }
601 }
602 return true;
603 }
604
select_ech_cipher_suite(const EVP_HPKE_KDF ** out_kdf,const EVP_HPKE_AEAD ** out_aead,Span<const uint8_t> cipher_suites)605 static bool select_ech_cipher_suite(const EVP_HPKE_KDF **out_kdf,
606 const EVP_HPKE_AEAD **out_aead,
607 Span<const uint8_t> cipher_suites) {
608 const bool has_aes_hardware = EVP_has_aes_hardware();
609 const EVP_HPKE_AEAD *aead = nullptr;
610 CBS cbs = cipher_suites;
611 while (CBS_len(&cbs) != 0) {
612 uint16_t kdf_id, aead_id;
613 if (!CBS_get_u16(&cbs, &kdf_id) || //
614 !CBS_get_u16(&cbs, &aead_id)) {
615 return false;
616 }
617 // Pick the first common cipher suite, but prefer ChaCha20-Poly1305 if we
618 // don't have AES hardware.
619 const EVP_HPKE_AEAD *candidate = get_ech_aead(aead_id);
620 if (kdf_id != EVP_HPKE_HKDF_SHA256 || candidate == nullptr) {
621 continue;
622 }
623 if (aead == nullptr ||
624 (!has_aes_hardware && aead_id == EVP_HPKE_CHACHA20_POLY1305)) {
625 aead = candidate;
626 }
627 }
628 if (aead == nullptr) {
629 return false;
630 }
631
632 *out_kdf = EVP_hpke_hkdf_sha256();
633 *out_aead = aead;
634 return true;
635 }
636
ssl_select_ech_config(SSL_HANDSHAKE * hs,Span<uint8_t> out_enc,size_t * out_enc_len)637 bool ssl_select_ech_config(SSL_HANDSHAKE *hs, Span<uint8_t> out_enc,
638 size_t *out_enc_len) {
639 *out_enc_len = 0;
640 if (hs->max_version < TLS1_3_VERSION) {
641 // ECH requires TLS 1.3.
642 return true;
643 }
644
645 if (!hs->config->client_ech_config_list.empty()) {
646 CBS cbs = MakeConstSpan(hs->config->client_ech_config_list);
647 CBS child;
648 if (!CBS_get_u16_length_prefixed(&cbs, &child) || //
649 CBS_len(&child) == 0 || //
650 CBS_len(&cbs) > 0) {
651 return false;
652 }
653 // Look for the first ECHConfig with supported parameters.
654 while (CBS_len(&child) > 0) {
655 ECHConfig ech_config;
656 bool supported;
657 if (!parse_ech_config(&child, &ech_config, &supported,
658 /*all_extensions_mandatory=*/false)) {
659 return false;
660 }
661 const EVP_HPKE_KEM *kem = EVP_hpke_x25519_hkdf_sha256();
662 const EVP_HPKE_KDF *kdf;
663 const EVP_HPKE_AEAD *aead;
664 if (supported && //
665 ech_config.kem_id == EVP_HPKE_DHKEM_X25519_HKDF_SHA256 &&
666 select_ech_cipher_suite(&kdf, &aead, ech_config.cipher_suites)) {
667 ScopedCBB info;
668 static const uint8_t kInfoLabel[] = "tls ech"; // includes trailing NUL
669 if (!CBB_init(info.get(), sizeof(kInfoLabel) + ech_config.raw.size()) ||
670 !CBB_add_bytes(info.get(), kInfoLabel, sizeof(kInfoLabel)) ||
671 !CBB_add_bytes(info.get(), ech_config.raw.data(),
672 ech_config.raw.size())) {
673 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
674 return false;
675 }
676
677 if (!EVP_HPKE_CTX_setup_sender(
678 hs->ech_hpke_ctx.get(), out_enc.data(), out_enc_len,
679 out_enc.size(), kem, kdf, aead, ech_config.public_key.data(),
680 ech_config.public_key.size(), CBB_data(info.get()),
681 CBB_len(info.get())) ||
682 !hs->inner_transcript.Init()) {
683 return false;
684 }
685
686 hs->selected_ech_config = MakeUnique<ECHConfig>(std::move(ech_config));
687 return hs->selected_ech_config != nullptr;
688 }
689 }
690 }
691
692 return true;
693 }
694
aead_overhead(const EVP_HPKE_AEAD * aead)695 static size_t aead_overhead(const EVP_HPKE_AEAD *aead) {
696 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
697 // TODO(https://crbug.com/boringssl/275): Having to adjust the overhead
698 // everywhere is tedious. Change fuzzer mode to append a fake tag but still
699 // otherwise be cleartext, refresh corpora, and then inline this function.
700 return 0;
701 #else
702 return EVP_AEAD_max_overhead(EVP_HPKE_AEAD_aead(aead));
703 #endif
704 }
705
706 // random_size returns a random value between |min| and |max|, inclusive.
random_size(size_t min,size_t max)707 static size_t random_size(size_t min, size_t max) {
708 assert(min < max);
709 size_t value;
710 RAND_bytes(reinterpret_cast<uint8_t *>(&value), sizeof(value));
711 return value % (max - min + 1) + min;
712 }
713
setup_ech_grease(SSL_HANDSHAKE * hs)714 static bool setup_ech_grease(SSL_HANDSHAKE *hs) {
715 assert(!hs->selected_ech_config);
716 if (hs->max_version < TLS1_3_VERSION || !hs->config->ech_grease_enabled) {
717 return true;
718 }
719
720 const uint16_t kdf_id = EVP_HPKE_HKDF_SHA256;
721 const EVP_HPKE_AEAD *aead = EVP_has_aes_hardware()
722 ? EVP_hpke_aes_128_gcm()
723 : EVP_hpke_chacha20_poly1305();
724 static_assert(ssl_grease_ech_config_id < sizeof(hs->grease_seed),
725 "hs->grease_seed is too small");
726 uint8_t config_id = hs->grease_seed[ssl_grease_ech_config_id];
727
728 uint8_t enc[X25519_PUBLIC_VALUE_LEN];
729 uint8_t private_key_unused[X25519_PRIVATE_KEY_LEN];
730 X25519_keypair(enc, private_key_unused);
731
732 // To determine a plausible length for the payload, we estimate the size of a
733 // typical EncodedClientHelloInner without resumption:
734 //
735 // 2+32+1+2 version, random, legacy_session_id, legacy_compression_methods
736 // 2+4*2 cipher_suites (three TLS 1.3 ciphers, GREASE)
737 // 2 extensions prefix
738 // 5 inner encrypted_client_hello
739 // 4+1+2*2 supported_versions (TLS 1.3, GREASE)
740 // 4+1+10*2 outer_extensions (key_share, sigalgs, sct, alpn,
741 // supported_groups, status_request, psk_key_exchange_modes,
742 // compress_certificate, GREASE x2)
743 //
744 // The server_name extension has an overhead of 9 bytes. For now, arbitrarily
745 // estimate maximum_name_length to be between 32 and 100 bytes. Then round up
746 // to a multiple of 32, to match draft-ietf-tls-esni-13, section 6.1.3.
747 const size_t payload_len =
748 32 * random_size(128 / 32, 224 / 32) + aead_overhead(aead);
749 bssl::ScopedCBB cbb;
750 CBB enc_cbb, payload_cbb;
751 uint8_t *payload;
752 if (!CBB_init(cbb.get(), 256) ||
753 !CBB_add_u16(cbb.get(), kdf_id) ||
754 !CBB_add_u16(cbb.get(), EVP_HPKE_AEAD_id(aead)) ||
755 !CBB_add_u8(cbb.get(), config_id) ||
756 !CBB_add_u16_length_prefixed(cbb.get(), &enc_cbb) ||
757 !CBB_add_bytes(&enc_cbb, enc, sizeof(enc)) ||
758 !CBB_add_u16_length_prefixed(cbb.get(), &payload_cbb) ||
759 !CBB_add_space(&payload_cbb, &payload, payload_len) ||
760 !RAND_bytes(payload, payload_len) ||
761 !CBBFinishArray(cbb.get(), &hs->ech_client_outer)) {
762 return false;
763 }
764 return true;
765 }
766
ssl_encrypt_client_hello(SSL_HANDSHAKE * hs,Span<const uint8_t> enc)767 bool ssl_encrypt_client_hello(SSL_HANDSHAKE *hs, Span<const uint8_t> enc) {
768 SSL *const ssl = hs->ssl;
769 if (!hs->selected_ech_config) {
770 return setup_ech_grease(hs);
771 }
772
773 // Construct ClientHelloInner and EncodedClientHelloInner. See
774 // draft-ietf-tls-esni-13, sections 5.1 and 6.1.
775 ScopedCBB cbb, encoded_cbb;
776 CBB body;
777 bool needs_psk_binder;
778 Array<uint8_t> hello_inner;
779 if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_CLIENT_HELLO) ||
780 !CBB_init(encoded_cbb.get(), 256) ||
781 !ssl_write_client_hello_without_extensions(hs, &body,
782 ssl_client_hello_inner,
783 /*empty_session_id=*/false) ||
784 !ssl_write_client_hello_without_extensions(hs, encoded_cbb.get(),
785 ssl_client_hello_inner,
786 /*empty_session_id=*/true) ||
787 !ssl_add_clienthello_tlsext(hs, &body, encoded_cbb.get(),
788 &needs_psk_binder, ssl_client_hello_inner,
789 CBB_len(&body)) ||
790 !ssl->method->finish_message(ssl, cbb.get(), &hello_inner)) {
791 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
792 return false;
793 }
794
795 if (needs_psk_binder) {
796 size_t binder_len;
797 if (!tls13_write_psk_binder(hs, hs->inner_transcript, MakeSpan(hello_inner),
798 &binder_len)) {
799 return false;
800 }
801 // Also update the EncodedClientHelloInner.
802 auto encoded_binder =
803 MakeSpan(const_cast<uint8_t *>(CBB_data(encoded_cbb.get())),
804 CBB_len(encoded_cbb.get()))
805 .last(binder_len);
806 auto hello_inner_binder = MakeConstSpan(hello_inner).last(binder_len);
807 OPENSSL_memcpy(encoded_binder.data(), hello_inner_binder.data(),
808 binder_len);
809 }
810
811 ssl_do_msg_callback(ssl, /*is_write=*/1, SSL3_RT_CLIENT_HELLO_INNER,
812 hello_inner);
813 if (!hs->inner_transcript.Update(hello_inner)) {
814 return false;
815 }
816
817 // Pad the EncodedClientHelloInner. See draft-ietf-tls-esni-13, section 6.1.3.
818 size_t padding_len = 0;
819 size_t maximum_name_length = hs->selected_ech_config->maximum_name_length;
820 if (ssl->hostname) {
821 size_t hostname_len = strlen(ssl->hostname.get());
822 if (hostname_len <= maximum_name_length) {
823 padding_len = maximum_name_length - hostname_len;
824 }
825 } else {
826 // No SNI. Pad up to |maximum_name_length|, including server_name extension
827 // overhead.
828 padding_len = 9 + maximum_name_length;
829 }
830 // Pad the whole thing to a multiple of 32 bytes.
831 padding_len += 31 - ((CBB_len(encoded_cbb.get()) + padding_len - 1) % 32);
832 Array<uint8_t> encoded;
833 if (!CBB_add_zeros(encoded_cbb.get(), padding_len) ||
834 !CBBFinishArray(encoded_cbb.get(), &encoded)) {
835 return false;
836 }
837
838 // Encrypt |encoded|. See draft-ietf-tls-esni-13, section 6.1.1. First,
839 // assemble the extension with a placeholder value for ClientHelloOuterAAD.
840 // See draft-ietf-tls-esni-13, section 5.2.
841 const EVP_HPKE_KDF *kdf = EVP_HPKE_CTX_kdf(hs->ech_hpke_ctx.get());
842 const EVP_HPKE_AEAD *aead = EVP_HPKE_CTX_aead(hs->ech_hpke_ctx.get());
843 size_t payload_len = encoded.size() + aead_overhead(aead);
844 CBB enc_cbb, payload_cbb;
845 if (!CBB_init(cbb.get(), 256) ||
846 !CBB_add_u16(cbb.get(), EVP_HPKE_KDF_id(kdf)) ||
847 !CBB_add_u16(cbb.get(), EVP_HPKE_AEAD_id(aead)) ||
848 !CBB_add_u8(cbb.get(), hs->selected_ech_config->config_id) ||
849 !CBB_add_u16_length_prefixed(cbb.get(), &enc_cbb) ||
850 !CBB_add_bytes(&enc_cbb, enc.data(), enc.size()) ||
851 !CBB_add_u16_length_prefixed(cbb.get(), &payload_cbb) ||
852 !CBB_add_zeros(&payload_cbb, payload_len) ||
853 !CBBFinishArray(cbb.get(), &hs->ech_client_outer)) {
854 return false;
855 }
856
857 // Construct ClientHelloOuterAAD.
858 // TODO(https://crbug.com/boringssl/275): This ends up constructing the
859 // ClientHelloOuter twice. Instead, reuse |aad| for the ClientHello, now that
860 // draft-12 made the length prefixes match.
861 bssl::ScopedCBB aad;
862 if (!CBB_init(aad.get(), 256) ||
863 !ssl_write_client_hello_without_extensions(hs, aad.get(),
864 ssl_client_hello_outer,
865 /*empty_session_id=*/false) ||
866 !ssl_add_clienthello_tlsext(hs, aad.get(), /*out_encoded=*/nullptr,
867 &needs_psk_binder, ssl_client_hello_outer,
868 CBB_len(aad.get()))) {
869 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
870 return false;
871 }
872
873 // ClientHelloOuter may not require a PSK binder. Otherwise, we have a
874 // circular dependency.
875 assert(!needs_psk_binder);
876
877 // Replace the payload in |hs->ech_client_outer| with the encrypted value.
878 auto payload_span = MakeSpan(hs->ech_client_outer).last(payload_len);
879 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
880 // In fuzzer mode, the server expects a cleartext payload.
881 assert(payload_span.size() == encoded.size());
882 OPENSSL_memcpy(payload_span.data(), encoded.data(), encoded.size());
883 #else
884 if (!EVP_HPKE_CTX_seal(hs->ech_hpke_ctx.get(), payload_span.data(),
885 &payload_len, payload_span.size(), encoded.data(),
886 encoded.size(), CBB_data(aad.get()),
887 CBB_len(aad.get())) ||
888 payload_len != payload_span.size()) {
889 return false;
890 }
891 #endif // BORINGSSL_UNSAFE_FUZZER_MODE
892
893 return true;
894 }
895
896 BSSL_NAMESPACE_END
897
898 using namespace bssl;
899
SSL_set_enable_ech_grease(SSL * ssl,int enable)900 void SSL_set_enable_ech_grease(SSL *ssl, int enable) {
901 if (!ssl->config) {
902 return;
903 }
904 ssl->config->ech_grease_enabled = !!enable;
905 }
906
SSL_set1_ech_config_list(SSL * ssl,const uint8_t * ech_config_list,size_t ech_config_list_len)907 int SSL_set1_ech_config_list(SSL *ssl, const uint8_t *ech_config_list,
908 size_t ech_config_list_len) {
909 if (!ssl->config) {
910 return 0;
911 }
912
913 auto span = MakeConstSpan(ech_config_list, ech_config_list_len);
914 if (!ssl_is_valid_ech_config_list(span)) {
915 OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_ECH_CONFIG_LIST);
916 return 0;
917 }
918 return ssl->config->client_ech_config_list.CopyFrom(span);
919 }
920
SSL_get0_ech_name_override(const SSL * ssl,const char ** out_name,size_t * out_name_len)921 void SSL_get0_ech_name_override(const SSL *ssl, const char **out_name,
922 size_t *out_name_len) {
923 // When ECH is rejected, we use the public name. Note that, if
924 // |SSL_CTX_set_reverify_on_resume| is enabled, we reverify the certificate
925 // before the 0-RTT point. If also offering ECH, we verify as if
926 // ClientHelloInner was accepted and do not override. This works because, at
927 // this point, |ech_status| will be |ssl_ech_none|. See the
928 // ECH-Client-Reject-EarlyDataReject-OverrideNameOnRetry tests in runner.go.
929 const SSL_HANDSHAKE *hs = ssl->s3->hs.get();
930 if (!ssl->server && hs && ssl->s3->ech_status == ssl_ech_rejected) {
931 *out_name = reinterpret_cast<const char *>(
932 hs->selected_ech_config->public_name.data());
933 *out_name_len = hs->selected_ech_config->public_name.size();
934 } else {
935 *out_name = nullptr;
936 *out_name_len = 0;
937 }
938 }
939
SSL_get0_ech_retry_configs(const SSL * ssl,const uint8_t ** out_retry_configs,size_t * out_retry_configs_len)940 void SSL_get0_ech_retry_configs(
941 const SSL *ssl, const uint8_t **out_retry_configs,
942 size_t *out_retry_configs_len) {
943 const SSL_HANDSHAKE *hs = ssl->s3->hs.get();
944 if (!hs || !hs->ech_authenticated_reject) {
945 // It is an error to call this function except in response to
946 // |SSL_R_ECH_REJECTED|. Returning an empty string risks the caller
947 // mistakenly believing the server has disabled ECH. Instead, return a
948 // non-empty ECHConfigList with a syntax error, so the subsequent
949 // |SSL_set1_ech_config_list| call will fail.
950 assert(0);
951 static const uint8_t kPlaceholder[] = {
952 kECHConfigVersion >> 8, kECHConfigVersion & 0xff, 0xff, 0xff, 0xff};
953 *out_retry_configs = kPlaceholder;
954 *out_retry_configs_len = sizeof(kPlaceholder);
955 return;
956 }
957
958 *out_retry_configs = hs->ech_retry_configs.data();
959 *out_retry_configs_len = hs->ech_retry_configs.size();
960 }
961
SSL_marshal_ech_config(uint8_t ** out,size_t * out_len,uint8_t config_id,const EVP_HPKE_KEY * key,const char * public_name,size_t max_name_len)962 int SSL_marshal_ech_config(uint8_t **out, size_t *out_len, uint8_t config_id,
963 const EVP_HPKE_KEY *key, const char *public_name,
964 size_t max_name_len) {
965 Span<const uint8_t> public_name_u8 = MakeConstSpan(
966 reinterpret_cast<const uint8_t *>(public_name), strlen(public_name));
967 if (!ssl_is_valid_ech_public_name(public_name_u8)) {
968 OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_ECH_PUBLIC_NAME);
969 return 0;
970 }
971
972 // The maximum name length is encoded in one byte.
973 if (max_name_len > 0xff) {
974 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_LENGTH);
975 return 0;
976 }
977
978 // See draft-ietf-tls-esni-13, section 4.
979 ScopedCBB cbb;
980 CBB contents, child;
981 uint8_t *public_key;
982 size_t public_key_len;
983 if (!CBB_init(cbb.get(), 128) || //
984 !CBB_add_u16(cbb.get(), kECHConfigVersion) ||
985 !CBB_add_u16_length_prefixed(cbb.get(), &contents) ||
986 !CBB_add_u8(&contents, config_id) ||
987 !CBB_add_u16(&contents, EVP_HPKE_KEM_id(EVP_HPKE_KEY_kem(key))) ||
988 !CBB_add_u16_length_prefixed(&contents, &child) ||
989 !CBB_reserve(&child, &public_key, EVP_HPKE_MAX_PUBLIC_KEY_LENGTH) ||
990 !EVP_HPKE_KEY_public_key(key, public_key, &public_key_len,
991 EVP_HPKE_MAX_PUBLIC_KEY_LENGTH) ||
992 !CBB_did_write(&child, public_key_len) ||
993 !CBB_add_u16_length_prefixed(&contents, &child) ||
994 // Write a default cipher suite configuration.
995 !CBB_add_u16(&child, EVP_HPKE_HKDF_SHA256) ||
996 !CBB_add_u16(&child, EVP_HPKE_AES_128_GCM) ||
997 !CBB_add_u16(&child, EVP_HPKE_HKDF_SHA256) ||
998 !CBB_add_u16(&child, EVP_HPKE_CHACHA20_POLY1305) ||
999 !CBB_add_u8(&contents, max_name_len) ||
1000 !CBB_add_u8_length_prefixed(&contents, &child) ||
1001 !CBB_add_bytes(&child, public_name_u8.data(), public_name_u8.size()) ||
1002 // TODO(https://crbug.com/boringssl/275): Reserve some GREASE extensions
1003 // and include some.
1004 !CBB_add_u16(&contents, 0 /* no extensions */) ||
1005 !CBB_finish(cbb.get(), out, out_len)) {
1006 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1007 return 0;
1008 }
1009 return 1;
1010 }
1011
SSL_ECH_KEYS_new()1012 SSL_ECH_KEYS *SSL_ECH_KEYS_new() { return New<SSL_ECH_KEYS>(); }
1013
SSL_ECH_KEYS_up_ref(SSL_ECH_KEYS * keys)1014 void SSL_ECH_KEYS_up_ref(SSL_ECH_KEYS *keys) {
1015 CRYPTO_refcount_inc(&keys->references);
1016 }
1017
SSL_ECH_KEYS_free(SSL_ECH_KEYS * keys)1018 void SSL_ECH_KEYS_free(SSL_ECH_KEYS *keys) {
1019 if (keys == nullptr ||
1020 !CRYPTO_refcount_dec_and_test_zero(&keys->references)) {
1021 return;
1022 }
1023
1024 keys->~ssl_ech_keys_st();
1025 OPENSSL_free(keys);
1026 }
1027
SSL_ECH_KEYS_add(SSL_ECH_KEYS * configs,int is_retry_config,const uint8_t * ech_config,size_t ech_config_len,const EVP_HPKE_KEY * key)1028 int SSL_ECH_KEYS_add(SSL_ECH_KEYS *configs, int is_retry_config,
1029 const uint8_t *ech_config, size_t ech_config_len,
1030 const EVP_HPKE_KEY *key) {
1031 UniquePtr<ECHServerConfig> parsed_config = MakeUnique<ECHServerConfig>();
1032 if (!parsed_config) {
1033 return 0;
1034 }
1035 if (!parsed_config->Init(MakeConstSpan(ech_config, ech_config_len), key,
1036 !!is_retry_config)) {
1037 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1038 return 0;
1039 }
1040 if (!configs->configs.Push(std::move(parsed_config))) {
1041 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1042 return 0;
1043 }
1044 return 1;
1045 }
1046
SSL_ECH_KEYS_has_duplicate_config_id(const SSL_ECH_KEYS * keys)1047 int SSL_ECH_KEYS_has_duplicate_config_id(const SSL_ECH_KEYS *keys) {
1048 bool seen[256] = {false};
1049 for (const auto &config : keys->configs) {
1050 if (seen[config->ech_config().config_id]) {
1051 return 1;
1052 }
1053 seen[config->ech_config().config_id] = true;
1054 }
1055 return 0;
1056 }
1057
SSL_ECH_KEYS_marshal_retry_configs(const SSL_ECH_KEYS * keys,uint8_t ** out,size_t * out_len)1058 int SSL_ECH_KEYS_marshal_retry_configs(const SSL_ECH_KEYS *keys, uint8_t **out,
1059 size_t *out_len) {
1060 ScopedCBB cbb;
1061 CBB child;
1062 if (!CBB_init(cbb.get(), 128) ||
1063 !CBB_add_u16_length_prefixed(cbb.get(), &child)) {
1064 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1065 return false;
1066 }
1067 for (const auto &config : keys->configs) {
1068 if (config->is_retry_config() &&
1069 !CBB_add_bytes(&child, config->ech_config().raw.data(),
1070 config->ech_config().raw.size())) {
1071 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
1072 return false;
1073 }
1074 }
1075 return CBB_finish(cbb.get(), out, out_len);
1076 }
1077
SSL_CTX_set1_ech_keys(SSL_CTX * ctx,SSL_ECH_KEYS * keys)1078 int SSL_CTX_set1_ech_keys(SSL_CTX *ctx, SSL_ECH_KEYS *keys) {
1079 bool has_retry_config = false;
1080 for (const auto &config : keys->configs) {
1081 if (config->is_retry_config()) {
1082 has_retry_config = true;
1083 break;
1084 }
1085 }
1086 if (!has_retry_config) {
1087 OPENSSL_PUT_ERROR(SSL, SSL_R_ECH_SERVER_WOULD_HAVE_NO_RETRY_CONFIGS);
1088 return 0;
1089 }
1090 UniquePtr<SSL_ECH_KEYS> owned_keys = UpRef(keys);
1091 MutexWriteLock lock(&ctx->lock);
1092 ctx->ech_keys.swap(owned_keys);
1093 return 1;
1094 }
1095
SSL_ech_accepted(const SSL * ssl)1096 int SSL_ech_accepted(const SSL *ssl) {
1097 if (SSL_in_early_data(ssl) && !ssl->server) {
1098 // In the client early data state, we report properties as if the server
1099 // accepted early data. The server can only accept early data with
1100 // ClientHelloInner.
1101 return ssl->s3->hs->selected_ech_config != nullptr;
1102 }
1103
1104 return ssl->s3->ech_status == ssl_ech_accepted;
1105 }
1106