Debian Codegraph @

debian/rust-vendor/aws-lc-sys/aws-lc/ssl/test/test_config.cc

raw
1 // Copyright (c) 2014, Google Inc.
2 // SPDX-License-Identifier: ISC
3
4 #include "test_config.h"
5
6 #include <assert.h>
7 #include <ctype.h>
8 #include <errno.h>
9 #include <limits.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13
14 #include <algorithm>
15 #include <functional>
16 #include <limits>
17 #include <memory>
18 #include <type_traits>
19
20 #include <openssl/base64.h>
21 #include <openssl/hmac.h>
22 #include <openssl/hpke.h>
23 #include <openssl/rand.h>
24 #include <openssl/span.h>
25 #include <openssl/ssl.h>
26
27 #include "../../crypto/internal.h"
28 #include "../internal.h"
29 #include "handshake_util.h"
30 #include "mock_quic_transport.h"
31 #include "test_state.h"
32
33 namespace {
34
35 struct Flag {
36 const char *name;
37 bool has_param;
38 // skip_handshaker, if true, causes this flag to be skipped when
39 // forwarding flags to the handshaker. This should be used with flags
40 // that only impact connecting to the runner.
41 bool skip_handshaker;
42 // If |has_param| is false, |param| will be nullptr.
43 std::function<bool(TestConfig *config, const char *param)> set_param;
44 };
45
46 Flag BoolFlag(const char *name, bool TestConfig::*field,
47 bool skip_handshaker = false) {
48 return Flag{name, false, skip_handshaker,
49 [=](TestConfig *config, const char *) -> bool {
50 config->*field = true;
51 return true;
52 }};
53 }
54
55 template <typename T>
56 bool StringToInt(T *out, const char *str) {
57 static_assert(std::is_integral<T>::value, "not an integral type");
58
59 // |strtoull| allows leading '-' with wraparound. Additionally, both
60 // functions accept empty strings and leading whitespace.
61 if (!OPENSSL_isdigit(static_cast<unsigned char>(*str)) &&
62 (!std::is_signed<T>::value || *str != '-')) {
63 return false;
64 }
65
66 errno = 0;
67 char *end;
68 if (std::is_signed<T>::value) {
69 static_assert(sizeof(T) <= sizeof(long long),
70 "type too large for long long");
71 long long value = strtoll(str, &end, 10);
72 if (value < static_cast<long long>(std::numeric_limits<T>::min()) ||
73 value > static_cast<long long>(std::numeric_limits<T>::max())) {
74 return false;
75 }
76 *out = static_cast<T>(value);
77 } else {
78 static_assert(sizeof(T) <= sizeof(unsigned long long),
79 "type too large for unsigned long long");
80 unsigned long long value = strtoull(str, &end, 10);
81 if (value >
82 static_cast<unsigned long long>(std::numeric_limits<T>::max())) {
83 return false;
84 }
85 *out = static_cast<T>(value);
86 }
87
88 // Check for overflow and that the whole input was consumed.
89 return errno != ERANGE && *end == '\0';
90 }
91
92 template <typename T>
93 Flag IntFlag(const char *name, T TestConfig::*field,
94 bool skip_handshaker = false) {
95 return Flag{name, true, skip_handshaker,
96 [=](TestConfig *config, const char *param) -> bool {
97 return StringToInt(&(config->*field), param);
98 }};
99 }
100
101 template <typename T>
102 Flag IntVectorFlag(const char *name, std::vector<T> TestConfig::*field,
103 bool skip_handshaker = false) {
104 return Flag{name, true, skip_handshaker,
105 [=](TestConfig *config, const char *param) -> bool {
106 T value;
107 if (!StringToInt(&value, param)) {
108 return false;
109 }
110 (config->*field).push_back(value);
111 return true;
112 }};
113 }
114
115 Flag StringFlag(const char *name, std::string TestConfig::*field,
116 bool skip_handshaker = false) {
117 return Flag{name, true, skip_handshaker,
118 [=](TestConfig *config, const char *param) -> bool {
119 config->*field = param;
120 return true;
121 }};
122 }
123
124 // TODO(davidben): When we can depend on C++17 or Abseil, switch this to
125 // std::optional or absl::optional.
126 Flag OptionalStringFlag(const char *name,
127 std::unique_ptr<std::string> TestConfig::*field,
128 bool skip_handshaker = false) {
129 return Flag{name, true, skip_handshaker,
130 [=](TestConfig *config, const char *param) -> bool {
131 (config->*field).reset(new std::string(param));
132 return true;
133 }};
134 }
135
136 bool DecodeBase64(std::string *out, const std::string &in) {
137 size_t len;
138 if (!EVP_DecodedLength(&len, in.size())) {
139 fprintf(stderr, "Invalid base64: %s.\n", in.c_str());
140 return false;
141 }
142 std::vector<uint8_t> buf(len);
143 if (!EVP_DecodeBase64(buf.data(), &len, buf.size(),
144 reinterpret_cast<const uint8_t *>(in.data()),
145 in.size())) {
146 fprintf(stderr, "Invalid base64: %s.\n", in.c_str());
147 return false;
148 }
149 out->assign(reinterpret_cast<const char *>(buf.data()), len);
150 return true;
151 }
152
153 Flag Base64Flag(const char *name, std::string TestConfig::*field,
154 bool skip_handshaker = false) {
155 return Flag{name, true, skip_handshaker,
156 [=](TestConfig *config, const char *param) -> bool {
157 return DecodeBase64(&(config->*field), param);
158 }};
159 }
160
161 Flag Base64VectorFlag(const char *name,
162 std::vector<std::string> TestConfig::*field,
163 bool skip_handshaker = false) {
164 return Flag{name, true, skip_handshaker,
165 [=](TestConfig *config, const char *param) -> bool {
166 std::string value;
167 if (!DecodeBase64(&value, param)) {
168 return false;
169 }
170 (config->*field).push_back(std::move(value));
171 return true;
172 }};
173 }
174
175 Flag StringPairVectorFlag(
176 const char *name,
177 std::vector<std::pair<std::string, std::string>> TestConfig::*field,
178 bool skip_handshaker = false) {
179 return Flag{name, true, skip_handshaker,
180 [=](TestConfig *config, const char *param) -> bool {
181 const char *comma = strchr(param, ',');
182 if (!comma) {
183 return false;
184 }
185 (config->*field)
186 .push_back(std::make_pair(std::string(param, comma - param),
187 std::string(comma + 1)));
188 return true;
189 }};
190 }
191
192 std::vector<Flag> SortedFlags() {
193 std::vector<Flag> flags = {
194 IntFlag("-port", &TestConfig::port, /*skip_handshaker=*/true),
195 BoolFlag("-ipv6", &TestConfig::ipv6, /*skip_handshaker=*/true),
196 IntFlag("-shim-id", &TestConfig::shim_id, /*skip_handshaker=*/true),
197 BoolFlag("-server", &TestConfig::is_server),
198 BoolFlag("-dtls", &TestConfig::is_dtls),
199 BoolFlag("-quic", &TestConfig::is_quic),
200 IntFlag("-resume-count", &TestConfig::resume_count),
201 StringFlag("-write-settings", &TestConfig::write_settings),
202 BoolFlag("-fallback-scsv", &TestConfig::fallback_scsv),
203 IntVectorFlag("-signing-prefs", &TestConfig::signing_prefs),
204 IntVectorFlag("-verify-prefs", &TestConfig::verify_prefs),
205 IntVectorFlag("-expect-peer-verify-pref",
206 &TestConfig::expect_peer_verify_prefs),
207 IntVectorFlag("-curves", &TestConfig::curves),
208 StringFlag("-key-file", &TestConfig::key_file),
209 StringFlag("-cert-file", &TestConfig::cert_file),
210 StringFlag("-trust-cert", &TestConfig::trust_cert),
211 StringFlag("-expect-server-name", &TestConfig::expect_server_name),
212 BoolFlag("-enable-ech-grease", &TestConfig::enable_ech_grease),
213 Base64VectorFlag("-ech-server-config", &TestConfig::ech_server_configs),
214 Base64VectorFlag("-ech-server-key", &TestConfig::ech_server_keys),
215 IntVectorFlag("-ech-is-retry-config", &TestConfig::ech_is_retry_config),
216 BoolFlag("-expect-ech-accept", &TestConfig::expect_ech_accept),
217 StringFlag("-expect-ech-name-override",
218 &TestConfig::expect_ech_name_override),
219 BoolFlag("-expect-no-ech-name-override",
220 &TestConfig::expect_no_ech_name_override),
221 Base64Flag("-expect-ech-retry-configs",
222 &TestConfig::expect_ech_retry_configs),
223 BoolFlag("-expect-no-ech-retry-configs",
224 &TestConfig::expect_no_ech_retry_configs),
225 Base64Flag("-ech-config-list", &TestConfig::ech_config_list),
226 Base64Flag("-expect-certificate-types",
227 &TestConfig::expect_certificate_types),
228 BoolFlag("-require-any-client-certificate",
229 &TestConfig::require_any_client_certificate),
230 StringFlag("-advertise-npn", &TestConfig::advertise_npn),
231 StringFlag("-expect-next-proto", &TestConfig::expect_next_proto),
232 BoolFlag("-false-start", &TestConfig::false_start),
233 StringFlag("-select-next-proto", &TestConfig::select_next_proto),
234 BoolFlag("-async", &TestConfig::async),
235 BoolFlag("-write-different-record-sizes",
236 &TestConfig::write_different_record_sizes),
237 BoolFlag("-cbc-record-splitting", &TestConfig::cbc_record_splitting),
238 BoolFlag("-partial-write", &TestConfig::partial_write),
239 BoolFlag("-no-tls13", &TestConfig::no_tls13),
240 BoolFlag("-no-tls12", &TestConfig::no_tls12),
241 BoolFlag("-no-tls11", &TestConfig::no_tls11),
242 BoolFlag("-no-tls1", &TestConfig::no_tls1),
243 BoolFlag("-no-ticket", &TestConfig::no_ticket),
244 Base64Flag("-expect-channel-id", &TestConfig::expect_channel_id),
245 BoolFlag("-enable-channel-id", &TestConfig::enable_channel_id),
246 StringFlag("-send-channel-id", &TestConfig::send_channel_id),
247 BoolFlag("-shim-writes-first", &TestConfig::shim_writes_first),
248 StringFlag("-host-name", &TestConfig::host_name),
249 StringFlag("-advertise-alpn", &TestConfig::advertise_alpn),
250 StringFlag("-expect-alpn", &TestConfig::expect_alpn),
251 StringFlag("-expect-advertised-alpn",
252 &TestConfig::expect_advertised_alpn),
253 StringFlag("-select-alpn", &TestConfig::select_alpn),
254 BoolFlag("-decline-alpn", &TestConfig::decline_alpn),
255 BoolFlag("-reject-alpn", &TestConfig::reject_alpn),
256 BoolFlag("-select-empty-alpn", &TestConfig::select_empty_alpn),
257 BoolFlag("-defer-alps", &TestConfig::defer_alps),
258 StringPairVectorFlag("-application-settings",
259 &TestConfig::application_settings),
260 OptionalStringFlag("-expect-peer-application-settings",
261 &TestConfig::expect_peer_application_settings),
262 BoolFlag("-alps-use-new-codepoint", &TestConfig::alps_use_new_codepoint),
263 Base64Flag("-quic-transport-params", &TestConfig::quic_transport_params),
264 Base64Flag("-expect-quic-transport-params",
265 &TestConfig::expect_quic_transport_params),
266 IntFlag("-quic-use-legacy-codepoint",
267 &TestConfig::quic_use_legacy_codepoint),
268 BoolFlag("-expect-session-miss", &TestConfig::expect_session_miss),
269 BoolFlag("-expect-extended-master-secret",
270 &TestConfig::expect_extended_master_secret),
271 StringFlag("-psk", &TestConfig::psk),
272 StringFlag("-psk-identity", &TestConfig::psk_identity),
273 StringFlag("-srtp-profiles", &TestConfig::srtp_profiles),
274 BoolFlag("-enable-ocsp-stapling", &TestConfig::enable_ocsp_stapling),
275 BoolFlag("-enable-signed-cert-timestamps",
276 &TestConfig::enable_signed_cert_timestamps),
277 Base64Flag("-expect-signed-cert-timestamps",
278 &TestConfig::expect_signed_cert_timestamps),
279 IntFlag("-min-version", &TestConfig::min_version),
280 IntFlag("-max-version", &TestConfig::max_version),
281 IntFlag("-expect-version", &TestConfig::expect_version),
282 IntFlag("-mtu", &TestConfig::mtu),
283 BoolFlag("-implicit-handshake", &TestConfig::implicit_handshake),
284 BoolFlag("-use-early-callback", &TestConfig::use_early_callback),
285 BoolFlag("-fail-early-callback", &TestConfig::fail_early_callback),
286 BoolFlag("-install-ddos-callback", &TestConfig::install_ddos_callback),
287 BoolFlag("-fail-ddos-callback", &TestConfig::fail_ddos_callback),
288 BoolFlag("-fail-cert-callback", &TestConfig::fail_cert_callback),
289 StringFlag("-cipher", &TestConfig::cipher),
290 BoolFlag("-handshake-never-done", &TestConfig::handshake_never_done),
291 IntFlag("-export-keying-material", &TestConfig::export_keying_material),
292 StringFlag("-export-label", &TestConfig::export_label),
293 StringFlag("-export-context", &TestConfig::export_context),
294 BoolFlag("-use-export-context", &TestConfig::use_export_context),
295 BoolFlag("-tls-unique", &TestConfig::tls_unique),
296 BoolFlag("-expect-ticket-renewal", &TestConfig::expect_ticket_renewal),
297 BoolFlag("-expect-no-session", &TestConfig::expect_no_session),
298 BoolFlag("-expect-ticket-supports-early-data",
299 &TestConfig::expect_ticket_supports_early_data),
300 BoolFlag("-expect-accept-early-data",
301 &TestConfig::expect_accept_early_data),
302 BoolFlag("-expect-reject-early-data",
303 &TestConfig::expect_reject_early_data),
304 BoolFlag("-expect-no-offer-early-data",
305 &TestConfig::expect_no_offer_early_data),
306 BoolFlag("-use-ticket-callback", &TestConfig::use_ticket_callback),
307 BoolFlag("-renew-ticket", &TestConfig::renew_ticket),
308 BoolFlag("-enable-early-data", &TestConfig::enable_early_data),
309 BoolFlag("-enable-client-custom-extension", &TestConfig::enable_client_custom_extension),
310 BoolFlag("-enable-server-custom-extension", &TestConfig::enable_server_custom_extension),
311 BoolFlag("-custom-extension-skip", &TestConfig::custom_extension_skip),
312 BoolFlag("-custom-extension-fail-add", &TestConfig::custom_extension_fail_add),
313 Base64Flag("-ocsp-response", &TestConfig::ocsp_response),
314 Base64Flag("-expect-ocsp-response", &TestConfig::expect_ocsp_response),
315 BoolFlag("-check-close-notify", &TestConfig::check_close_notify),
316 BoolFlag("-shim-shuts-down", &TestConfig::shim_shuts_down),
317 BoolFlag("-verify-fail", &TestConfig::verify_fail),
318 BoolFlag("-verify-peer", &TestConfig::verify_peer),
319 BoolFlag("-verify-peer-if-no-obc", &TestConfig::verify_peer_if_no_obc),
320 BoolFlag("-expect-verify-result", &TestConfig::expect_verify_result),
321 Base64Flag("-signed-cert-timestamps",
322 &TestConfig::signed_cert_timestamps),
323 IntFlag("-expect-total-renegotiations",
324 &TestConfig::expect_total_renegotiations),
325 BoolFlag("-renegotiate-once", &TestConfig::renegotiate_once),
326 BoolFlag("-renegotiate-freely", &TestConfig::renegotiate_freely),
327 BoolFlag("-renegotiate-ignore", &TestConfig::renegotiate_ignore),
328 BoolFlag("-renegotiate-explicit", &TestConfig::renegotiate_explicit),
329 BoolFlag("-forbid-renegotiation-after-handshake",
330 &TestConfig::forbid_renegotiation_after_handshake),
331 IntFlag("-expect-peer-signature-algorithm",
332 &TestConfig::expect_peer_signature_algorithm),
333 IntFlag("-expect-curve-id", &TestConfig::expect_curve_id),
334 BoolFlag("-use-old-client-cert-callback",
335 &TestConfig::use_old_client_cert_callback),
336 IntFlag("-initial-timeout-duration-ms",
337 &TestConfig::initial_timeout_duration_ms),
338 StringFlag("-use-client-ca-list", &TestConfig::use_client_ca_list),
339 StringFlag("-expect-client-ca-list", &TestConfig::expect_client_ca_list),
340 BoolFlag("-send-alert", &TestConfig::send_alert),
341 BoolFlag("-peek-then-read", &TestConfig::peek_then_read),
342 BoolFlag("-enable-grease", &TestConfig::enable_grease),
343 BoolFlag("-permute-extensions", &TestConfig::permute_extensions),
344 IntFlag("-max-cert-list", &TestConfig::max_cert_list),
345 Base64Flag("-ticket-key", &TestConfig::ticket_key),
346 BoolFlag("-use-exporter-between-reads",
347 &TestConfig::use_exporter_between_reads),
348 IntFlag("-expect-cipher-aes", &TestConfig::expect_cipher_aes),
349 IntFlag("-expect-cipher-no-aes", &TestConfig::expect_cipher_no_aes),
350 IntFlag("-expect-cipher", &TestConfig::expect_cipher),
351 StringFlag("-expect-peer-cert-file", &TestConfig::expect_peer_cert_file),
352 IntFlag("-resumption-delay", &TestConfig::resumption_delay),
353 BoolFlag("-retain-only-sha256-client-cert",
354 &TestConfig::retain_only_sha256_client_cert),
355 BoolFlag("-expect-sha256-client-cert",
356 &TestConfig::expect_sha256_client_cert),
357 BoolFlag("-read-with-unfinished-write",
358 &TestConfig::read_with_unfinished_write),
359 BoolFlag("-expect-secure-renegotiation",
360 &TestConfig::expect_secure_renegotiation),
361 BoolFlag("-expect-no-secure-renegotiation",
362 &TestConfig::expect_no_secure_renegotiation),
363 IntFlag("-max-send-fragment", &TestConfig::max_send_fragment),
364 IntFlag("-read-size", &TestConfig::read_size),
365 BoolFlag("-expect-session-id", &TestConfig::expect_session_id),
366 BoolFlag("-expect-no-session-id", &TestConfig::expect_no_session_id),
367 IntFlag("-expect-ticket-age-skew", &TestConfig::expect_ticket_age_skew),
368 BoolFlag("-no-op-extra-handshake", &TestConfig::no_op_extra_handshake),
369 BoolFlag("-handshake-twice", &TestConfig::handshake_twice),
370 BoolFlag("-allow-unknown-alpn-protos",
371 &TestConfig::allow_unknown_alpn_protos),
372 BoolFlag("-use-custom-verify-callback",
373 &TestConfig::use_custom_verify_callback),
374 StringFlag("-expect-msg-callback", &TestConfig::expect_msg_callback),
375 BoolFlag("-allow-false-start-without-alpn",
376 &TestConfig::allow_false_start_without_alpn),
377 BoolFlag("-handoff", &TestConfig::handoff),
378 BoolFlag("-handshake-hints", &TestConfig::handshake_hints),
379 BoolFlag("-allow-hint-mismatch", &TestConfig::allow_hint_mismatch),
380 BoolFlag("-use-ocsp-callback", &TestConfig::use_ocsp_callback),
381 BoolFlag("-set-ocsp-in-callback", &TestConfig::set_ocsp_in_callback),
382 BoolFlag("-decline-ocsp-callback", &TestConfig::decline_ocsp_callback),
383 BoolFlag("-fail-ocsp-callback", &TestConfig::fail_ocsp_callback),
384 BoolFlag("-install-cert-compression-algs",
385 &TestConfig::install_cert_compression_algs),
386 IntFlag("-install-one-cert-compression-alg",
387 &TestConfig::install_one_cert_compression_alg),
388 BoolFlag("-reverify-on-resume", &TestConfig::reverify_on_resume),
389 BoolFlag("-enforce-rsa-key-usage", &TestConfig::enforce_rsa_key_usage),
390 BoolFlag("-expect-key-usage-invalid",
391 &TestConfig::expect_key_usage_invalid),
392 BoolFlag("-is-handshaker-supported",
393 &TestConfig::is_handshaker_supported),
394 BoolFlag("-handshaker-resume", &TestConfig::handshaker_resume),
395 StringFlag("-handshaker-path", &TestConfig::handshaker_path),
396 BoolFlag("-jdk11-workaround", &TestConfig::jdk11_workaround),
397 BoolFlag("-server-preference", &TestConfig::server_preference),
398 BoolFlag("-export-traffic-secrets", &TestConfig::export_traffic_secrets),
399 BoolFlag("-key-update", &TestConfig::key_update),
400 BoolFlag("-expect-delegated-credential-used",
401 &TestConfig::expect_delegated_credential_used),
402 StringFlag("-delegated-credential", &TestConfig::delegated_credential),
403 StringFlag("-expect-early-data-reason",
404 &TestConfig::expect_early_data_reason),
405 BoolFlag("-expect-hrr", &TestConfig::expect_hrr),
406 BoolFlag("-expect-no-hrr", &TestConfig::expect_no_hrr),
407 BoolFlag("-wait-for-debugger", &TestConfig::wait_for_debugger),
408 StringFlag("-quic-early-data-context",
409 &TestConfig::quic_early_data_context),
410 IntFlag("-early-write-after-message",
411 &TestConfig::early_write_after_message),
412 BoolFlag("-check-ssl-transfer", &TestConfig::check_ssl_transfer),
413 BoolFlag("-do-ssl-transfer", &TestConfig::do_ssl_transfer),
414 IntFlag("-read-ahead-buffer-size",
415 &TestConfig::read_ahead_buffer_size),
416 StringFlag("-ssl-fuzz-seed-path-prefix", &TestConfig::ssl_fuzz_seed_path_prefix),
417 StringFlag("-tls13-ciphersuites", &TestConfig::tls13_ciphersuites),
418 StringPairVectorFlag("-multiple-certs-slot", &TestConfig::multiple_certs_slot),
419 BoolFlag("-no-check-client-certificate-type",
420 &TestConfig::no_check_client_certificate_type),
421 };
422 std::sort(flags.begin(), flags.end(), [](const Flag &a, const Flag &b) {
423 return strcmp(a.name, b.name) < 0;
424 });
425 return flags;
426 }
427
428 const Flag *FindFlag(const char *name) {
429 static const std::vector<Flag> kSortedFlags = SortedFlags();
430 auto iter = std::lower_bound(kSortedFlags.begin(), kSortedFlags.end(), name,
431 [](const Flag &flag, const char *key) {
432 return strcmp(flag.name, key) < 0;
433 });
434 if (iter == kSortedFlags.end() || strcmp(iter->name, name) != 0) {
435 return nullptr;
436 }
437 return &*iter;
438 }
439
440 // RemovePrefix checks if |*str| begins with |prefix| + "-". If so, it advances
441 // |*str| past |prefix| (but not past the "-") and returns true. Otherwise, it
442 // returns false and leaves |*str| unmodified.
443 bool RemovePrefix(const char **str, const char *prefix) {
444 size_t prefix_len = strlen(prefix);
445 if (strncmp(*str, prefix, strlen(prefix)) == 0 && (*str)[prefix_len] == '-') {
446 *str += strlen(prefix);
447 return true;
448 }
449 return false;
450 }
451
452 } // namespace
453
454 bool ParseConfig(int argc, char **argv, bool is_shim,
455 TestConfig *out_initial,
456 TestConfig *out_resume,
457 TestConfig *out_retry) {
458 for (int i = 0; i < argc; i++) {
459 bool skip = false;
460 const char *arg = argv[i];
461 const char *name = arg;
462
463 // -on-shim and -on-handshaker prefixes enable flags only on the shim or
464 // handshaker.
465 if (RemovePrefix(&name, "-on-shim")) {
466 if (!is_shim) {
467 skip = true;
468 }
469 } else if (RemovePrefix(&name, "-on-handshaker")) {
470 if (is_shim) {
471 skip = true;
472 }
473 }
474
475 // The following prefixes allow different configurations for each of the
476 // initial, resumption, and 0-RTT retry handshakes.
477 TestConfig *out = nullptr;
478 if (RemovePrefix(&name, "-on-initial")) {
479 out = out_initial;
480 } else if (RemovePrefix(&name, "-on-resume")) {
481 out = out_resume;
482 } else if (RemovePrefix(&name, "-on-retry")) {
483 out = out_retry;
484 }
485
486 const Flag *flag = FindFlag(name);
487 if (flag == nullptr) {
488 fprintf(stderr, "Unrecognized flag: %s\n", name);
489 return false;
490 }
491
492 const char *param = nullptr;
493 if (flag->has_param) {
494 if (i >= argc) {
495 fprintf(stderr, "Missing parameter for %s\n", name);
496 return false;
497 }
498 i++;
499 param = argv[i];
500 }
501
502 if (!flag->skip_handshaker) {
503 out_initial->handshaker_args.push_back(arg);
504 if (flag->has_param) {
505 out_initial->handshaker_args.push_back(param);
506 }
507 }
508
509 if (!skip) {
510 if (out != nullptr) {
511 if (!flag->set_param(out, param)) {
512 fprintf(stderr, "Invalid parameter for %s: %s\n", name, param);
513 return false;
514 }
515 } else {
516 // Unprefixed flags apply to all three.
517 if (!flag->set_param(out_initial, param) ||
518 !flag->set_param(out_resume, param) ||
519 !flag->set_param(out_retry, param)) {
520 fprintf(stderr, "Invalid parameter for %s: %s\n", name, param);
521 return false;
522 }
523 }
524 }
525 }
526
527 out_resume->handshaker_args = std::vector<const char*>(out_initial->handshaker_args);
528 out_retry->handshaker_args = std::vector<const char*>(out_initial->handshaker_args);
529 return true;
530 }
531
532 static CRYPTO_once_t once = CRYPTO_ONCE_INIT;
533 static int g_config_index = 0;
534 static CRYPTO_BUFFER_POOL *g_pool = nullptr;
535
536 static void init_once() {
537 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
538 if (g_config_index < 0) {
539 abort();
540 }
541 g_pool = CRYPTO_BUFFER_POOL_new();
542 if (!g_pool) {
543 abort();
544 }
545 }
546
547 bool SetTestConfig(SSL *ssl, const TestConfig *config) {
548 CRYPTO_once(&once, init_once);
549 return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
550 }
551
552 const TestConfig *GetTestConfig(const SSL *ssl) {
553 CRYPTO_once(&once, init_once);
554 return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
555 }
556
557 static int LegacyOCSPCallback(SSL *ssl, void *arg) {
558 const TestConfig *config = GetTestConfig(ssl);
559 if (!SSL_is_server(ssl)) {
560 return !config->fail_ocsp_callback;
561 }
562
563 if (!config->ocsp_response.empty() && config->set_ocsp_in_callback &&
564 !SSL_set_ocsp_response(ssl, (const uint8_t *)config->ocsp_response.data(),
565 config->ocsp_response.size())) {
566 return SSL_TLSEXT_ERR_ALERT_FATAL;
567 }
568 if (config->fail_ocsp_callback) {
569 return SSL_TLSEXT_ERR_ALERT_FATAL;
570 }
571 if (config->decline_ocsp_callback) {
572 return SSL_TLSEXT_ERR_NOACK;
573 }
574 return SSL_TLSEXT_ERR_OK;
575 }
576
577 // kCustomExtensionValue is the extension value that the custom extension
578 // callbacks will add.
579 static const uint16_t kCustomExtensionValue = 1234;
580 static void *const kCustomExtensionAddArg =
581 reinterpret_cast<void *>(kCustomExtensionValue);
582 static void *const kCustomExtensionParseArg =
583 reinterpret_cast<void *>(kCustomExtensionValue + 1);
584 static const char kCustomExtensionContents[] = "custom extension";
585
586 static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
587 const uint8_t **out, size_t *out_len,
588 int *out_alert_value, void *add_arg) {
589 if (extension_value != kCustomExtensionValue ||
590 add_arg != kCustomExtensionAddArg) {
591 abort();
592 }
593
594 if (GetTestConfig(ssl)->custom_extension_skip) {
595 return 0;
596 }
597 if (GetTestConfig(ssl)->custom_extension_fail_add) {
598 return -1;
599 }
600
601 *out = reinterpret_cast<const uint8_t *>(kCustomExtensionContents);
602 *out_len = sizeof(kCustomExtensionContents) - 1;
603
604 return 1;
605 }
606
607 static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
608 const uint8_t *out, void *add_arg) {
609 if (extension_value != kCustomExtensionValue ||
610 add_arg != kCustomExtensionAddArg ||
611 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
612 abort();
613 }
614 }
615
616 static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
617 const uint8_t *contents,
618 size_t contents_len,
619 int *out_alert_value, void *parse_arg) {
620 if (extension_value != kCustomExtensionValue ||
621 parse_arg != kCustomExtensionParseArg) {
622 abort();
623 }
624
625 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
626 OPENSSL_memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
627 *out_alert_value = SSL_AD_DECODE_ERROR;
628 return 0;
629 }
630
631 return 1;
632 }
633
634 static int ServerNameCallback(SSL *ssl, int *out_alert, void *arg) {
635 // SNI must be accessible from the SNI callback.
636 const TestConfig *config = GetTestConfig(ssl);
637 const char *server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
638 if (server_name == nullptr ||
639 std::string(server_name) != config->expect_server_name) {
640 fprintf(stderr, "servername mismatch (got %s; want %s).\n", server_name,
641 config->expect_server_name.c_str());
642 return SSL_TLSEXT_ERR_ALERT_FATAL;
643 }
644
645 return SSL_TLSEXT_ERR_OK;
646 }
647
648 static int NextProtoSelectCallback(SSL *ssl, uint8_t **out, uint8_t *outlen,
649 const uint8_t *in, unsigned inlen,
650 void *arg) {
651 const TestConfig *config = GetTestConfig(ssl);
652 if (config->select_next_proto.empty()) {
653 return SSL_TLSEXT_ERR_NOACK;
654 }
655
656 *out = (uint8_t *)config->select_next_proto.data();
657 *outlen = config->select_next_proto.size();
658 return SSL_TLSEXT_ERR_OK;
659 }
660
661 static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
662 unsigned int *out_len, void *arg) {
663 const TestConfig *config = GetTestConfig(ssl);
664 if (config->advertise_npn.empty()) {
665 return SSL_TLSEXT_ERR_NOACK;
666 }
667
668 if (config->advertise_npn.size() > UINT_MAX) {
669 fprintf(stderr, "NPN value too large.\n");
670 return SSL_TLSEXT_ERR_ALERT_FATAL;
671 }
672
673 *out = reinterpret_cast<const uint8_t *>(config->advertise_npn.data());
674 *out_len = static_cast<unsigned>(config->advertise_npn.size());
675 return SSL_TLSEXT_ERR_OK;
676 }
677
678 static void MessageCallback(int is_write, int version, int content_type,
679 const void *buf, size_t len, SSL *ssl, void *arg) {
680 const uint8_t *buf_u8 = reinterpret_cast<const uint8_t *>(buf);
681 const TestConfig *config = GetTestConfig(ssl);
682 TestState *state = GetTestState(ssl);
683 if (!state->msg_callback_ok) {
684 return;
685 }
686
687 if (content_type == SSL3_RT_HEADER) {
688 if (len !=
689 (config->is_dtls ? DTLS1_RT_HEADER_LENGTH : SSL3_RT_HEADER_LENGTH)) {
690 fprintf(stderr, "Incorrect length for record header: %zu.\n", len);
691 state->msg_callback_ok = false;
692 }
693 return;
694 }
695
696 state->msg_callback_text += is_write ? "write " : "read ";
697 switch (content_type) {
698 case 0:
699 if (version != SSL2_VERSION) {
700 fprintf(stderr, "Incorrect version for V2ClientHello: %x.\n",
701 static_cast<unsigned>(version));
702 state->msg_callback_ok = false;
703 return;
704 }
705 state->msg_callback_text += "v2clienthello\n";
706 return;
707
708 case SSL3_RT_CLIENT_HELLO_INNER:
709 case SSL3_RT_HANDSHAKE: {
710 CBS cbs;
711 CBS_init(&cbs, buf_u8, len);
712 uint8_t type;
713 uint32_t msg_len;
714 if (!CBS_get_u8(&cbs, &type) ||
715 // TODO(davidben): Reporting on entire messages would be more
716 // consistent than fragments.
717 (config->is_dtls &&
718 !CBS_skip(&cbs, 3 /* total */ + 2 /* seq */ + 3 /* frag_off */)) ||
719 !CBS_get_u24(&cbs, &msg_len) || !CBS_skip(&cbs, msg_len) ||
720 CBS_len(&cbs) != 0) {
721 fprintf(stderr, "Could not parse handshake message.\n");
722 state->msg_callback_ok = false;
723 return;
724 }
725 char text[16];
726 if (content_type == SSL3_RT_CLIENT_HELLO_INNER) {
727 if (type != SSL3_MT_CLIENT_HELLO) {
728 fprintf(stderr, "Invalid header for ClientHelloInner.\n");
729 state->msg_callback_ok = false;
730 return;
731 }
732 state->msg_callback_text += "clienthelloinner\n";
733 } else {
734 snprintf(text, sizeof(text), "hs %d\n", type);
735 state->msg_callback_text += text;
736 if (!is_write) {
737 state->last_message_received = type;
738 }
739 }
740 return;
741 }
742
743 case SSL3_RT_CHANGE_CIPHER_SPEC:
744 if (len != 1 || buf_u8[0] != 1) {
745 fprintf(stderr, "Invalid ChangeCipherSpec.\n");
746 state->msg_callback_ok = false;
747 return;
748 }
749 state->msg_callback_text += "ccs\n";
750 return;
751
752 case SSL3_RT_ALERT:
753 if (len != 2) {
754 fprintf(stderr, "Invalid alert.\n");
755 state->msg_callback_ok = false;
756 return;
757 }
758 char text[16];
759 snprintf(text, sizeof(text), "alert %d %d\n", buf_u8[0], buf_u8[1]);
760 state->msg_callback_text += text;
761 return;
762
763 default:
764 fprintf(stderr, "Invalid content_type: %d.\n", content_type);
765 state->msg_callback_ok = false;
766 }
767 }
768
769 static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
770 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
771 int encrypt) {
772 if (!encrypt) {
773 if (GetTestState(ssl)->ticket_decrypt_done) {
774 fprintf(stderr, "TicketKeyCallback called after completion.\n");
775 return -1;
776 }
777
778 GetTestState(ssl)->ticket_decrypt_done = true;
779 }
780
781 // This is just test code, so use the all-zeros key.
782 static const uint8_t kZeros[16] = {0};
783
784 if (encrypt) {
785 OPENSSL_memcpy(key_name, kZeros, sizeof(kZeros));
786 RAND_bytes(iv, 16);
787 } else if (OPENSSL_memcmp(key_name, kZeros, 16) != 0) {
788 return 0;
789 }
790
791 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
792 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
793 return -1;
794 }
795
796 if (!encrypt) {
797 return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
798 }
799 return 1;
800 }
801
802 static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
803 // This callback is called as the handshake completes. |SSL_get_session|
804 // must continue to work and, historically, |SSL_in_init| returned false at
805 // this point.
806 if (SSL_in_init(ssl) || SSL_get_session(ssl) == nullptr) {
807 fprintf(stderr, "Invalid state for NewSessionCallback.\n");
808 abort();
809 }
810
811 GetTestState(ssl)->got_new_session = true;
812 GetTestState(ssl)->new_session.reset(session);
813 return 1;
814 }
815
816 static void InfoCallback(const SSL *ssl, int type, int val) {
817 if (type == SSL_CB_HANDSHAKE_DONE) {
818 if (GetTestConfig(ssl)->handshake_never_done) {
819 fprintf(stderr, "Handshake unexpectedly completed.\n");
820 // Abort before any expected error code is printed, to ensure the overall
821 // test fails.
822 abort();
823 }
824 // This callback is called when the handshake completes. |SSL_get_session|
825 // must continue to work and |SSL_in_init| must return false.
826 if (SSL_in_init(ssl) || SSL_get_session(ssl) == nullptr) {
827 fprintf(stderr, "Invalid state for SSL_CB_HANDSHAKE_DONE.\n");
828 abort();
829 }
830 GetTestState(ssl)->handshake_done = true;
831 }
832 }
833
834 static SSL_SESSION *GetSessionCallback(SSL *ssl, const uint8_t *data, int len,
835 int *copy) {
836 TestState *async_state = GetTestState(ssl);
837 if (async_state->session) {
838 *copy = 0;
839 return async_state->session.release();
840 } else if (async_state->pending_session) {
841 return SSL_magic_pending_session_ptr();
842 } else {
843 return NULL;
844 }
845 }
846
847 static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
848 *out_clock = *GetClock();
849 }
850
851 static int AlpnSelectCallback(SSL *ssl, const uint8_t **out, uint8_t *outlen,
852 const uint8_t *in, unsigned inlen, void *arg) {
853 if (GetTestState(ssl)->alpn_select_done) {
854 fprintf(stderr, "AlpnSelectCallback called after completion.\n");
855 exit(1);
856 }
857
858 GetTestState(ssl)->alpn_select_done = true;
859
860 const TestConfig *config = GetTestConfig(ssl);
861 if (config->decline_alpn) {
862 return SSL_TLSEXT_ERR_NOACK;
863 }
864 if (config->reject_alpn) {
865 return SSL_TLSEXT_ERR_ALERT_FATAL;
866 }
867
868 if (!config->expect_advertised_alpn.empty() &&
869 (config->expect_advertised_alpn.size() != inlen ||
870 OPENSSL_memcmp(config->expect_advertised_alpn.data(), in, inlen) !=
871 0)) {
872 fprintf(stderr, "bad ALPN select callback inputs.\n");
873 exit(1);
874 }
875
876 if (config->defer_alps) {
877 for (const auto &pair : config->application_settings) {
878 if (!SSL_add_application_settings(
879 ssl, reinterpret_cast<const uint8_t *>(pair.first.data()),
880 pair.first.size(),
881 reinterpret_cast<const uint8_t *>(pair.second.data()),
882 pair.second.size())) {
883 fprintf(stderr, "error configuring ALPS.\n");
884 exit(1);
885 }
886 }
887 }
888
889 assert(config->select_alpn.empty() || !config->select_empty_alpn);
890 *out = (const uint8_t *)config->select_alpn.data();
891 *outlen = config->select_alpn.size();
892 return SSL_TLSEXT_ERR_OK;
893 }
894
895 static bool CheckVerifyCallback(SSL *ssl) {
896 const TestConfig *config = GetTestConfig(ssl);
897 if (!config->expect_ocsp_response.empty()) {
898 const uint8_t *data;
899 size_t len;
900 SSL_get0_ocsp_response(ssl, &data, &len);
901 if (len == 0) {
902 fprintf(stderr, "OCSP response not available in verify callback.\n");
903 return false;
904 }
905 }
906
907 const char *name_override;
908 size_t name_override_len;
909 SSL_get0_ech_name_override(ssl, &name_override, &name_override_len);
910 if (config->expect_no_ech_name_override && name_override_len != 0) {
911 fprintf(stderr, "Unexpected ECH name override.\n");
912 return false;
913 }
914 if (!config->expect_ech_name_override.empty() &&
915 config->expect_ech_name_override !=
916 std::string(name_override, name_override_len)) {
917 fprintf(stderr, "ECH name did not match expected value.\n");
918 return false;
919 }
920
921 if (GetTestState(ssl)->cert_verified) {
922 fprintf(stderr, "Certificate verified twice.\n");
923 return false;
924 }
925
926 return true;
927 }
928
929 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
930 SSL *ssl = (SSL *)X509_STORE_CTX_get_ex_data(
931 store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
932 const TestConfig *config = GetTestConfig(ssl);
933 if (!CheckVerifyCallback(ssl)) {
934 return 0;
935 }
936
937 GetTestState(ssl)->cert_verified = true;
938 if (config->verify_fail) {
939 X509_STORE_CTX_set_error(store_ctx, X509_V_ERR_APPLICATION_VERIFICATION);
940 return 0;
941 }
942
943 return 1;
944 }
945
946 bool LoadCertificate(bssl::UniquePtr<X509> *out_x509,
947 bssl::UniquePtr<STACK_OF(X509)> *out_chain,
948 const std::string &file) {
949 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
950 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
951 return false;
952 }
953
954 out_x509->reset(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
955 if (!*out_x509) {
956 return false;
957 }
958
959 out_chain->reset(sk_X509_new_null());
960 if (!*out_chain) {
961 return false;
962 }
963
964 // Keep reading the certificate chain.
965 for (;;) {
966 bssl::UniquePtr<X509> cert(
967 PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
968 if (!cert) {
969 break;
970 }
971
972 if (!bssl::PushToStack(out_chain->get(), std::move(cert))) {
973 return false;
974 }
975 }
976
977 uint32_t err = ERR_peek_last_error();
978 if (ERR_GET_LIB(err) != ERR_LIB_PEM ||
979 ERR_GET_REASON(err) != PEM_R_NO_START_LINE) {
980 return false;
981 }
982
983 ERR_clear_error();
984 return true;
985 }
986
987 bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
988 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
989 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
990 return nullptr;
991 }
992 return bssl::UniquePtr<EVP_PKEY>(
993 PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
994 }
995
996 static bool GetCertificate(SSL *ssl, bssl::UniquePtr<X509> *out_x509,
997 bssl::UniquePtr<STACK_OF(X509)> *out_chain,
998 bssl::UniquePtr<EVP_PKEY> *out_pkey) {
999 const TestConfig *config = GetTestConfig(ssl);
1000
1001 if (!config->signing_prefs.empty()) {
1002 if (!SSL_set_signing_algorithm_prefs(ssl, config->signing_prefs.data(),
1003 config->signing_prefs.size())) {
1004 return false;
1005 }
1006 }
1007
1008 if (!config->key_file.empty()) {
1009 *out_pkey = LoadPrivateKey(config->key_file.c_str());
1010 if (!*out_pkey) {
1011 return false;
1012 }
1013 }
1014 if (!config->cert_file.empty() &&
1015 !LoadCertificate(out_x509, out_chain, config->cert_file.c_str())) {
1016 return false;
1017 }
1018 if (!config->ocsp_response.empty() && !config->set_ocsp_in_callback &&
1019 !SSL_set_ocsp_response(ssl, (const uint8_t *)config->ocsp_response.data(),
1020 config->ocsp_response.size())) {
1021 return false;
1022 }
1023 return true;
1024 }
1025
1026 static bool HexDecode(std::string *out, const std::string &in) {
1027 if ((in.size() & 1) != 0) {
1028 return false;
1029 }
1030
1031 std::unique_ptr<uint8_t[]> buf(new uint8_t[in.size() / 2]);
1032 for (size_t i = 0; i < in.size() / 2; i++) {
1033 uint8_t high, low;
1034 if (!OPENSSL_fromxdigit(&high, in[i * 2]) ||
1035 !OPENSSL_fromxdigit(&low, in[i * 2 + 1])) {
1036 return false;
1037 }
1038 buf[i] = (high << 4) | low;
1039 }
1040
1041 out->assign(reinterpret_cast<const char *>(buf.get()), in.size() / 2);
1042 return true;
1043 }
1044
1045 static std::vector<std::string> SplitParts(const std::string &in,
1046 const char delim) {
1047 std::vector<std::string> ret;
1048 size_t start = 0;
1049
1050 for (size_t i = 0; i < in.size(); i++) {
1051 if (in[i] == delim) {
1052 ret.push_back(in.substr(start, i - start));
1053 start = i + 1;
1054 }
1055 }
1056
1057 ret.push_back(in.substr(start, std::string::npos));
1058 return ret;
1059 }
1060
1061 static std::vector<std::string> DecodeHexStrings(
1062 const std::string &hex_strings) {
1063 std::vector<std::string> ret;
1064 const std::vector<std::string> parts = SplitParts(hex_strings, ',');
1065
1066 for (const auto &part : parts) {
1067 std::string binary;
1068 if (!HexDecode(&binary, part)) {
1069 fprintf(stderr, "Bad hex string: %s.\n", part.c_str());
1070 return ret;
1071 }
1072
1073 ret.push_back(std::move(binary));
1074 }
1075
1076 return ret;
1077 }
1078
1079 static bssl::UniquePtr<STACK_OF(X509_NAME)> DecodeHexX509Names(
1080 const std::string &hex_names) {
1081 const std::vector<std::string> der_names = DecodeHexStrings(hex_names);
1082 bssl::UniquePtr<STACK_OF(X509_NAME)> ret(sk_X509_NAME_new_null());
1083 if (!ret) {
1084 return nullptr;
1085 }
1086
1087 for (const auto &der_name : der_names) {
1088 const uint8_t *const data =
1089 reinterpret_cast<const uint8_t *>(der_name.data());
1090 const uint8_t *derp = data;
1091 bssl::UniquePtr<X509_NAME> name(
1092 d2i_X509_NAME(nullptr, &derp, der_name.size()));
1093 if (!name || derp != data + der_name.size()) {
1094 fprintf(stderr, "Failed to parse X509_NAME.\n");
1095 return nullptr;
1096 }
1097
1098 if (!bssl::PushToStack(ret.get(), std::move(name))) {
1099 return nullptr;
1100 }
1101 }
1102
1103 return ret;
1104 }
1105
1106 static bool CheckPeerVerifyPrefs(SSL *ssl) {
1107 const TestConfig *config = GetTestConfig(ssl);
1108 if (!config->expect_peer_verify_prefs.empty()) {
1109 const uint16_t *peer_sigalgs;
1110 size_t num_peer_sigalgs =
1111 SSL_get0_peer_verify_algorithms(ssl, &peer_sigalgs);
1112 if (config->expect_peer_verify_prefs.size() != num_peer_sigalgs) {
1113 fprintf(stderr,
1114 "peer verify preferences length mismatch (got %zu, wanted %zu)\n",
1115 num_peer_sigalgs, config->expect_peer_verify_prefs.size());
1116 return false;
1117 }
1118 for (size_t i = 0; i < num_peer_sigalgs; i++) {
1119 if (peer_sigalgs[i] != config->expect_peer_verify_prefs[i]) {
1120 fprintf(stderr,
1121 "peer verify preference %zu mismatch (got %04x, wanted %04x\n",
1122 i, peer_sigalgs[i], config->expect_peer_verify_prefs[i]);
1123 return false;
1124 }
1125 }
1126 }
1127 return true;
1128 }
1129
1130 static bool CheckCertificateRequest(SSL *ssl) {
1131 const TestConfig *config = GetTestConfig(ssl);
1132
1133 if (!CheckPeerVerifyPrefs(ssl)) {
1134 return false;
1135 }
1136
1137 if (!config->expect_certificate_types.empty()) {
1138 const uint8_t *certificate_types;
1139 size_t certificate_types_len =
1140 SSL_get0_certificate_types(ssl, &certificate_types);
1141 if (certificate_types_len != config->expect_certificate_types.size() ||
1142 OPENSSL_memcmp(certificate_types,
1143 config->expect_certificate_types.data(),
1144 certificate_types_len) != 0) {
1145 fprintf(stderr, "certificate types mismatch.\n");
1146 return false;
1147 }
1148 }
1149
1150 if (!config->expect_client_ca_list.empty()) {
1151 bssl::UniquePtr<STACK_OF(X509_NAME)> expected =
1152 DecodeHexX509Names(config->expect_client_ca_list);
1153 const size_t num_expected = sk_X509_NAME_num(expected.get());
1154
1155 const STACK_OF(X509_NAME) *received = SSL_get_client_CA_list(ssl);
1156 const size_t num_received = sk_X509_NAME_num(received);
1157
1158 if (num_received != num_expected) {
1159 fprintf(stderr, "expected %zu names in CertificateRequest but got %zu.\n",
1160 num_expected, num_received);
1161 return false;
1162 }
1163
1164 for (size_t i = 0; i < num_received; i++) {
1165 if (X509_NAME_cmp(sk_X509_NAME_value(received, i),
1166 sk_X509_NAME_value(expected.get(), i)) != 0) {
1167 fprintf(stderr, "names in CertificateRequest differ at index #%zu.\n",
1168 i);
1169 return false;
1170 }
1171 }
1172
1173 const STACK_OF(CRYPTO_BUFFER) *buffers = SSL_get0_server_requested_CAs(ssl);
1174 if (sk_CRYPTO_BUFFER_num(buffers) != num_received) {
1175 fprintf(stderr,
1176 "Mismatch between SSL_get_server_requested_CAs and "
1177 "SSL_get_client_CA_list.\n");
1178 return false;
1179 }
1180 }
1181
1182 return true;
1183 }
1184
1185 static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
1186 if (!CheckCertificateRequest(ssl)) {
1187 return -1;
1188 }
1189
1190 if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
1191 return -1;
1192 }
1193
1194 bssl::UniquePtr<X509> x509;
1195 bssl::UniquePtr<STACK_OF(X509)> chain;
1196 bssl::UniquePtr<EVP_PKEY> pkey;
1197 if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
1198 return -1;
1199 }
1200
1201 // Return zero for no certificate.
1202 if (!x509) {
1203 return 0;
1204 }
1205
1206 // Chains and asynchronous private keys are not supported with client_cert_cb.
1207 *out_x509 = x509.release();
1208 *out_pkey = pkey.release();
1209 return 1;
1210 }
1211
1212 static ssl_private_key_result_t AsyncPrivateKeyComplete(SSL *ssl, uint8_t *out,
1213 size_t *out_len,
1214 size_t max_out);
1215
1216 static ssl_private_key_result_t AsyncPrivateKeySign(
1217 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
1218 uint16_t signature_algorithm, const uint8_t *in, size_t in_len) {
1219 TestState *test_state = GetTestState(ssl);
1220 test_state->used_private_key = true;
1221 if (!test_state->private_key_result.empty()) {
1222 fprintf(stderr, "AsyncPrivateKeySign called with operation pending.\n");
1223 abort();
1224 }
1225
1226 if (EVP_PKEY_id(test_state->private_key.get()) !=
1227 SSL_get_signature_algorithm_key_type(signature_algorithm)) {
1228 fprintf(stderr, "Key type does not match signature algorithm.\n");
1229 abort();
1230 }
1231
1232 // Determine the hash.
1233 const EVP_MD *md = SSL_get_signature_algorithm_digest(signature_algorithm);
1234 bssl::ScopedEVP_MD_CTX ctx;
1235 EVP_PKEY_CTX *pctx;
1236 if (!EVP_DigestSignInit(ctx.get(), &pctx, md, nullptr,
1237 test_state->private_key.get())) {
1238 return ssl_private_key_failure;
1239 }
1240
1241 // Configure additional signature parameters.
1242 if (SSL_is_signature_algorithm_rsa_pss(signature_algorithm)) {
1243 if (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) ||
1244 !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1 /* salt len = hash len */)) {
1245 return ssl_private_key_failure;
1246 }
1247 }
1248
1249 // Write the signature into |test_state|.
1250 size_t len = 0;
1251 if (!EVP_DigestSign(ctx.get(), nullptr, &len, in, in_len)) {
1252 return ssl_private_key_failure;
1253 }
1254 test_state->private_key_result.resize(len);
1255 if (!EVP_DigestSign(ctx.get(), test_state->private_key_result.data(), &len,
1256 in, in_len)) {
1257 return ssl_private_key_failure;
1258 }
1259 test_state->private_key_result.resize(len);
1260
1261 return AsyncPrivateKeyComplete(ssl, out, out_len, max_out);
1262 }
1263
1264 static ssl_private_key_result_t AsyncPrivateKeyDecrypt(SSL *ssl, uint8_t *out,
1265 size_t *out_len,
1266 size_t max_out,
1267 const uint8_t *in,
1268 size_t in_len) {
1269 TestState *test_state = GetTestState(ssl);
1270 test_state->used_private_key = true;
1271 if (!test_state->private_key_result.empty()) {
1272 fprintf(stderr, "AsyncPrivateKeyDecrypt called with operation pending.\n");
1273 abort();
1274 }
1275
1276 RSA *rsa = EVP_PKEY_get0_RSA(test_state->private_key.get());
1277 if (rsa == NULL) {
1278 fprintf(stderr, "AsyncPrivateKeyDecrypt called with incorrect key type.\n");
1279 abort();
1280 }
1281 test_state->private_key_result.resize(RSA_size(rsa));
1282 if (!RSA_decrypt(rsa, out_len, test_state->private_key_result.data(),
1283 RSA_size(rsa), in, in_len, RSA_NO_PADDING)) {
1284 return ssl_private_key_failure;
1285 }
1286
1287 test_state->private_key_result.resize(*out_len);
1288
1289 return AsyncPrivateKeyComplete(ssl, out, out_len, max_out);
1290 }
1291
1292 static ssl_private_key_result_t AsyncPrivateKeyComplete(SSL *ssl, uint8_t *out,
1293 size_t *out_len,
1294 size_t max_out) {
1295 TestState *test_state = GetTestState(ssl);
1296 if (test_state->private_key_result.empty()) {
1297 fprintf(stderr,
1298 "AsyncPrivateKeyComplete called without operation pending.\n");
1299 abort();
1300 }
1301
1302 if (GetTestConfig(ssl)->async && test_state->private_key_retries < 2) {
1303 // Only return the decryption on the second attempt, to test both incomplete
1304 // |sign|/|decrypt| and |complete|.
1305 return ssl_private_key_retry;
1306 }
1307
1308 if (max_out < test_state->private_key_result.size()) {
1309 fprintf(stderr, "Output buffer too small.\n");
1310 return ssl_private_key_failure;
1311 }
1312 OPENSSL_memcpy(out, test_state->private_key_result.data(),
1313 test_state->private_key_result.size());
1314 *out_len = test_state->private_key_result.size();
1315
1316 test_state->private_key_result.clear();
1317 test_state->private_key_retries = 0;
1318 return ssl_private_key_success;
1319 }
1320
1321 static const SSL_PRIVATE_KEY_METHOD g_async_private_key_method = {
1322 AsyncPrivateKeySign,
1323 AsyncPrivateKeyDecrypt,
1324 AsyncPrivateKeyComplete,
1325 };
1326
1327 static bool InstallCertificate(SSL *ssl) {
1328 bssl::UniquePtr<X509> x509;
1329 bssl::UniquePtr<STACK_OF(X509)> chain;
1330 bssl::UniquePtr<EVP_PKEY> pkey;
1331 if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
1332 return false;
1333 }
1334
1335 if (pkey) {
1336 TestState *test_state = GetTestState(ssl);
1337 const TestConfig *config = GetTestConfig(ssl);
1338 if (config->async || config->handshake_hints) {
1339 // Install a custom private key if testing asynchronous callbacks, or if
1340 // testing handshake hints. In the handshake hints case, we wish to check
1341 // that hints only mismatch when allowed.
1342 test_state->private_key = std::move(pkey);
1343 SSL_set_private_key_method(ssl, &g_async_private_key_method);
1344 } else if (!SSL_use_PrivateKey(ssl, pkey.get())) {
1345 return false;
1346 }
1347 }
1348
1349 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
1350 return false;
1351 }
1352
1353 if (sk_X509_num(chain.get()) > 0 && !SSL_set1_chain(ssl, chain.get())) {
1354 return false;
1355 }
1356
1357 return true;
1358 }
1359
1360 static bool InstallMultipleCertificates(SSL *ssl) {
1361 const TestConfig *config = GetTestConfig(ssl);
1362 if (config->multiple_certs_slot.empty()) {
1363 return false;
1364 }
1365
1366 if (!config->signing_prefs.empty()) {
1367 if (!SSL_set_signing_algorithm_prefs(ssl, config->signing_prefs.data(),
1368 config->signing_prefs.size())) {
1369 return false;
1370 }
1371 }
1372
1373 for (const auto &cert_key_pair : config->multiple_certs_slot) {
1374 bssl::UniquePtr<X509> x509;
1375 bssl::UniquePtr<STACK_OF(X509)> chain;
1376 bssl::UniquePtr<EVP_PKEY> pkey;
1377
1378 if (!LoadCertificate(&x509, &chain, cert_key_pair.first)) {
1379 return false;
1380 }
1381 pkey = LoadPrivateKey(cert_key_pair.second);
1382 if (pkey && !SSL_use_PrivateKey(ssl, pkey.get())) {
1383 return false;
1384 }
1385 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
1386 return false;
1387 }
1388 if (sk_X509_num(chain.get()) > 0 && !SSL_set1_chain(ssl, chain.get())) {
1389 return false;
1390 }
1391 }
1392 return true;
1393 }
1394
1395
1396 static enum ssl_select_cert_result_t SelectCertificateCallback(
1397 const SSL_CLIENT_HELLO *client_hello) {
1398 SSL *ssl = client_hello->ssl;
1399 const TestConfig *config = GetTestConfig(ssl);
1400 TestState *test_state = GetTestState(ssl);
1401 test_state->early_callback_called = true;
1402
1403 if (!config->expect_server_name.empty()) {
1404 const char *server_name =
1405 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1406 if (server_name == nullptr ||
1407 std::string(server_name) != config->expect_server_name) {
1408 fprintf(stderr,
1409 "Server name mismatch in early callback (got %s; want %s).\n",
1410 server_name, config->expect_server_name.c_str());
1411 return ssl_select_cert_error;
1412 }
1413 }
1414
1415 if (config->fail_early_callback) {
1416 return ssl_select_cert_error;
1417 }
1418
1419 // Simulate some asynchronous work in the early callback.
1420 if ((config->use_early_callback || test_state->get_handshake_hints_cb) &&
1421 config->async && !test_state->early_callback_ready) {
1422 return ssl_select_cert_retry;
1423 }
1424
1425 if (test_state->get_handshake_hints_cb &&
1426 !test_state->get_handshake_hints_cb(client_hello)) {
1427 return ssl_select_cert_error;
1428 }
1429
1430 if (config->use_early_callback &&
1431 !InstallMultipleCertificates(ssl) &&
1432 !InstallCertificate(ssl)) {
1433 return ssl_select_cert_error;
1434 }
1435
1436 return ssl_select_cert_success;
1437 }
1438
1439 static int SetQuicReadSecret(SSL *ssl, enum ssl_encryption_level_t level,
1440 const SSL_CIPHER *cipher, const uint8_t *secret,
1441 size_t secret_len) {
1442 MockQuicTransport *quic_transport = GetTestState(ssl)->quic_transport.get();
1443 if (quic_transport == nullptr) {
1444 fprintf(stderr, "No QUIC transport.\n");
1445 return 0;
1446 }
1447 return quic_transport->SetReadSecret(level, cipher, secret, secret_len);
1448 }
1449
1450 static int SetQuicWriteSecret(SSL *ssl, enum ssl_encryption_level_t level,
1451 const SSL_CIPHER *cipher, const uint8_t *secret,
1452 size_t secret_len) {
1453 MockQuicTransport *quic_transport = GetTestState(ssl)->quic_transport.get();
1454 if (quic_transport == nullptr) {
1455 fprintf(stderr, "No QUIC transport.\n");
1456 return 0;
1457 }
1458 return quic_transport->SetWriteSecret(level, cipher, secret, secret_len);
1459 }
1460
1461 static int AddQuicHandshakeData(SSL *ssl, enum ssl_encryption_level_t level,
1462 const uint8_t *data, size_t len) {
1463 MockQuicTransport *quic_transport = GetTestState(ssl)->quic_transport.get();
1464 if (quic_transport == nullptr) {
1465 fprintf(stderr, "No QUIC transport.\n");
1466 return 0;
1467 }
1468 return quic_transport->WriteHandshakeData(level, data, len);
1469 }
1470
1471 static int FlushQuicFlight(SSL *ssl) {
1472 MockQuicTransport *quic_transport = GetTestState(ssl)->quic_transport.get();
1473 if (quic_transport == nullptr) {
1474 fprintf(stderr, "No QUIC transport.\n");
1475 return 0;
1476 }
1477 return quic_transport->Flush();
1478 }
1479
1480 static int SendQuicAlert(SSL *ssl, enum ssl_encryption_level_t level,
1481 uint8_t alert) {
1482 MockQuicTransport *quic_transport = GetTestState(ssl)->quic_transport.get();
1483 if (quic_transport == nullptr) {
1484 fprintf(stderr, "No QUIC transport.\n");
1485 return 0;
1486 }
1487 return quic_transport->SendAlert(level, alert);
1488 }
1489
1490 static const SSL_QUIC_METHOD g_quic_method = {
1491 SetQuicReadSecret,
1492 SetQuicWriteSecret,
1493 AddQuicHandshakeData,
1494 FlushQuicFlight,
1495 SendQuicAlert,
1496 };
1497
1498 static bool MaybeInstallCertCompressionAlg(
1499 const TestConfig *config, SSL_CTX *ssl_ctx, uint16_t alg,
1500 ssl_cert_compression_func_t compress,
1501 ssl_cert_decompression_func_t decompress) {
1502 if (!config->install_cert_compression_algs &&
1503 config->install_one_cert_compression_alg != alg) {
1504 return true;
1505 }
1506 return SSL_CTX_add_cert_compression_alg(ssl_ctx, alg, compress, decompress);
1507 }
1508
1509 bssl::UniquePtr<SSL_CTX> TestConfig::SetupCtx(SSL_CTX *old_ctx) const {
1510 bssl::UniquePtr<SSL_CTX> ssl_ctx(
1511 SSL_CTX_new(is_dtls ? DTLS_method() : TLS_method()));
1512 if (!ssl_ctx) {
1513 return nullptr;
1514 }
1515
1516 CRYPTO_once(&once, init_once);
1517 SSL_CTX_set0_buffer_pool(ssl_ctx.get(), g_pool);
1518
1519 std::string cipher_list = "ALL";
1520 if (!cipher.empty()) {
1521 cipher_list = cipher;
1522 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
1523 }
1524 if (!SSL_CTX_set_strict_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
1525 return nullptr;
1526 }
1527 if (!tls13_ciphersuites.empty()
1528 && !SSL_CTX_set_ciphersuites(ssl_ctx.get(), tls13_ciphersuites.c_str())) {
1529 return nullptr;
1530 }
1531
1532 if (async && is_server) {
1533 // Disable the internal session cache. To test asynchronous session lookup,
1534 // we use an external session cache.
1535 SSL_CTX_set_session_cache_mode(
1536 ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
1537 SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
1538 } else {
1539 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
1540 }
1541
1542 SSL_CTX_set_select_certificate_cb(ssl_ctx.get(), SelectCertificateCallback);
1543
1544 if (use_old_client_cert_callback) {
1545 SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
1546 }
1547
1548 SSL_CTX_set_next_protos_advertised_cb(ssl_ctx.get(),
1549 NextProtosAdvertisedCallback, NULL);
1550 if (!select_next_proto.empty()) {
1551 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
1552 NULL);
1553 }
1554
1555 if (!select_alpn.empty() || decline_alpn || reject_alpn ||
1556 select_empty_alpn) {
1557 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
1558 }
1559
1560 SSL_CTX_set_current_time_cb(ssl_ctx.get(), CurrentTimeCallback);
1561
1562 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
1563 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
1564
1565 if (use_ticket_callback || handshake_hints) {
1566 // If using handshake hints, always enable the ticket callback, so we can
1567 // check that hints only mismatch when allowed. The ticket callback also
1568 // uses a constant key, which simplifies the test.
1569 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
1570 }
1571
1572 if (enable_client_custom_extension &&
1573 !SSL_CTX_add_client_custom_ext(
1574 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
1575 CustomExtensionFreeCallback, kCustomExtensionAddArg,
1576 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1577 return nullptr;
1578 }
1579
1580 if (enable_server_custom_extension &&
1581 !SSL_CTX_add_server_custom_ext(
1582 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
1583 CustomExtensionFreeCallback, kCustomExtensionAddArg,
1584 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1585 return nullptr;
1586 }
1587
1588 if (!use_custom_verify_callback) {
1589 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), CertVerifyCallback, NULL);
1590 }
1591
1592 if (!signed_cert_timestamps.empty() &&
1593 !SSL_CTX_set_signed_cert_timestamp_list(
1594 ssl_ctx.get(), (const uint8_t *)signed_cert_timestamps.data(),
1595 signed_cert_timestamps.size())) {
1596 return nullptr;
1597 }
1598
1599 if (!use_client_ca_list.empty()) {
1600 if (use_client_ca_list == "<NULL>") {
1601 SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
1602 } else if (use_client_ca_list == "<EMPTY>") {
1603 bssl::UniquePtr<STACK_OF(X509_NAME)> names;
1604 SSL_CTX_set_client_CA_list(ssl_ctx.get(), names.release());
1605 } else {
1606 bssl::UniquePtr<STACK_OF(X509_NAME)> names =
1607 DecodeHexX509Names(use_client_ca_list);
1608 SSL_CTX_set_client_CA_list(ssl_ctx.get(), names.release());
1609 }
1610 }
1611
1612 if (enable_grease) {
1613 SSL_CTX_set_grease_enabled(ssl_ctx.get(), 1);
1614 }
1615
1616 if (permute_extensions) {
1617 SSL_CTX_set_permute_extensions(ssl_ctx.get(), 1);
1618 }
1619
1620 if (!expect_server_name.empty()) {
1621 SSL_CTX_set_tlsext_servername_callback(ssl_ctx.get(), ServerNameCallback);
1622 }
1623
1624 if (enable_early_data) {
1625 SSL_CTX_set_early_data_enabled(ssl_ctx.get(), 1);
1626 }
1627
1628 if (allow_unknown_alpn_protos) {
1629 SSL_CTX_set_allow_unknown_alpn_protos(ssl_ctx.get(), 1);
1630 }
1631
1632 if (!verify_prefs.empty()) {
1633 if (!SSL_CTX_set_verify_algorithm_prefs(ssl_ctx.get(), verify_prefs.data(),
1634 verify_prefs.size())) {
1635 return nullptr;
1636 }
1637 }
1638
1639 SSL_CTX_set_msg_callback(ssl_ctx.get(), MessageCallback);
1640
1641 if (allow_false_start_without_alpn) {
1642 SSL_CTX_set_false_start_allowed_without_alpn(ssl_ctx.get(), 1);
1643 }
1644
1645 if (use_ocsp_callback) {
1646 SSL_CTX_set_tlsext_status_cb(ssl_ctx.get(), LegacyOCSPCallback);
1647 int (*cb)(SSL *, void *) = nullptr;
1648 if(!SSL_CTX_get_tlsext_status_cb(ssl_ctx.get(), &cb) ||
1649 cb != LegacyOCSPCallback){
1650 return nullptr;
1651 }
1652 }
1653
1654 if (old_ctx) {
1655 uint8_t keys[48];
1656 if (!SSL_CTX_get_tlsext_ticket_keys(old_ctx, &keys, sizeof(keys)) ||
1657 !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), keys, sizeof(keys))) {
1658 return nullptr;
1659 }
1660 CopySessions(ssl_ctx.get(), old_ctx);
1661 } else if (!ticket_key.empty() &&
1662 !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), ticket_key.data(),
1663 ticket_key.size())) {
1664 return nullptr;
1665 }
1666
1667 // These mock compression algorithms match the corresponding ones in
1668 // |addCertCompressionTests|.
1669 if (!MaybeInstallCertCompressionAlg(
1670 this, ssl_ctx.get(), 0xff02,
1671 [](SSL *ssl, CBB *out, const uint8_t *in, size_t in_len) -> int {
1672 if (!CBB_add_u8(out, 1) || !CBB_add_u8(out, 2) ||
1673 !CBB_add_u8(out, 3) || !CBB_add_u8(out, 4) ||
1674 !CBB_add_bytes(out, in, in_len)) {
1675 return 0;
1676 }
1677 return 1;
1678 },
1679 [](SSL *ssl, CRYPTO_BUFFER **out, size_t uncompressed_len,
1680 const uint8_t *in, size_t in_len) -> int {
1681 if (in_len < 4 || in[0] != 1 || in[1] != 2 || in[2] != 3 ||
1682 in[3] != 4 || uncompressed_len != in_len - 4) {
1683 return 0;
1684 }
1685 const bssl::Span<const uint8_t> uncompressed(in + 4, in_len - 4);
1686 *out = CRYPTO_BUFFER_new(uncompressed.data(), uncompressed.size(),
1687 nullptr);
1688 return *out != nullptr;
1689 }) ||
1690 !MaybeInstallCertCompressionAlg(
1691 this, ssl_ctx.get(), 0xff01,
1692 [](SSL *ssl, CBB *out, const uint8_t *in, size_t in_len) -> int {
1693 if (in_len < 2 || in[0] != 0 || in[1] != 0) {
1694 return 0;
1695 }
1696 return CBB_add_bytes(out, in + 2, in_len - 2);
1697 },
1698 [](SSL *ssl, CRYPTO_BUFFER **out, size_t uncompressed_len,
1699 const uint8_t *in, size_t in_len) -> int {
1700 if (uncompressed_len != 2 + in_len) {
1701 return 0;
1702 }
1703 std::unique_ptr<uint8_t[]> buf(new uint8_t[2 + in_len]);
1704 buf[0] = 0;
1705 buf[1] = 0;
1706 OPENSSL_memcpy(&buf[2], in, in_len);
1707 *out = CRYPTO_BUFFER_new(buf.get(), 2 + in_len, nullptr);
1708 return *out != nullptr;
1709 }) ||
1710 !MaybeInstallCertCompressionAlg(
1711 this, ssl_ctx.get(), 0xff03,
1712 [](SSL *ssl, CBB *out, const uint8_t *in, size_t in_len) -> int {
1713 uint8_t byte;
1714 return RAND_bytes(&byte, 1) && //
1715 CBB_add_u8(out, byte) && //
1716 CBB_add_bytes(out, in, in_len);
1717 },
1718 [](SSL *ssl, CRYPTO_BUFFER **out, size_t uncompressed_len,
1719 const uint8_t *in, size_t in_len) -> int {
1720 if (uncompressed_len + 1 != in_len) {
1721 return 0;
1722 }
1723 *out = CRYPTO_BUFFER_new(in + 1, in_len - 1, nullptr);
1724 return *out != nullptr;
1725 })) {
1726 fprintf(stderr, "SSL_CTX_add_cert_compression_alg failed.\n");
1727 abort();
1728 }
1729
1730 if (server_preference) {
1731 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
1732 }
1733
1734 if (is_quic) {
1735 SSL_CTX_set_quic_method(ssl_ctx.get(), &g_quic_method);
1736 }
1737
1738 return ssl_ctx;
1739 }
1740
1741 static int DDoSCallback(const SSL_CLIENT_HELLO *client_hello) {
1742 const TestConfig *config = GetTestConfig(client_hello->ssl);
1743 return config->fail_ddos_callback ? 0 : 1;
1744 }
1745
1746 static unsigned PskClientCallback(SSL *ssl, const char *hint,
1747 char *out_identity, unsigned max_identity_len,
1748 uint8_t *out_psk, unsigned max_psk_len) {
1749 const TestConfig *config = GetTestConfig(ssl);
1750
1751 if (config->psk_identity.empty()) {
1752 if (hint != nullptr) {
1753 fprintf(stderr, "Server PSK hint was non-null.\n");
1754 return 0;
1755 }
1756 } else if (hint == nullptr ||
1757 strcmp(hint, config->psk_identity.c_str()) != 0) {
1758 fprintf(stderr, "Server PSK hint did not match.\n");
1759 return 0;
1760 }
1761
1762 // Account for the trailing '\0' for the identity.
1763 if (config->psk_identity.size() >= max_identity_len ||
1764 config->psk.size() > max_psk_len) {
1765 fprintf(stderr, "PSK buffers too small.\n");
1766 return 0;
1767 }
1768
1769 OPENSSL_strlcpy(out_identity, config->psk_identity.c_str(), max_identity_len);
1770 OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size());
1771 return static_cast<unsigned>(config->psk.size());
1772 }
1773
1774 static unsigned PskServerCallback(SSL *ssl, const char *identity,
1775 uint8_t *out_psk, unsigned max_psk_len) {
1776 const TestConfig *config = GetTestConfig(ssl);
1777
1778 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
1779 fprintf(stderr, "Client PSK identity did not match.\n");
1780 return 0;
1781 }
1782
1783 if (config->psk.size() > max_psk_len) {
1784 fprintf(stderr, "PSK buffers too small.\n");
1785 return 0;
1786 }
1787
1788 OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size());
1789 return static_cast<unsigned>(config->psk.size());
1790 }
1791
1792 static ssl_verify_result_t CustomVerifyCallback(SSL *ssl, uint8_t *out_alert) {
1793 const TestConfig *config = GetTestConfig(ssl);
1794 if (!CheckVerifyCallback(ssl)) {
1795 return ssl_verify_invalid;
1796 }
1797
1798 if (config->async && !GetTestState(ssl)->custom_verify_ready) {
1799 return ssl_verify_retry;
1800 }
1801
1802 GetTestState(ssl)->cert_verified = true;
1803 if (config->verify_fail) {
1804 return ssl_verify_invalid;
1805 }
1806
1807 return ssl_verify_ok;
1808 }
1809
1810 static int CertCallback(SSL *ssl, void *arg) {
1811 const TestConfig *config = GetTestConfig(ssl);
1812
1813 // Check the peer certificate metadata is as expected.
1814 if ((!SSL_is_server(ssl) && !CheckCertificateRequest(ssl)) ||
1815 !CheckPeerVerifyPrefs(ssl)) {
1816 return -1;
1817 }
1818
1819 if (config->fail_cert_callback) {
1820 return 0;
1821 }
1822
1823 // The certificate will be installed via other means.
1824 if (!config->async || config->use_early_callback) {
1825 return 1;
1826 }
1827
1828 if (!GetTestState(ssl)->cert_ready) {
1829 return -1;
1830 }
1831 if (!InstallCertificate(ssl)) {
1832 return 0;
1833 }
1834 return 1;
1835 }
1836
1837 bssl::UniquePtr<SSL> TestConfig::NewSSL(
1838 SSL_CTX *ssl_ctx, SSL_SESSION *session,
1839 std::unique_ptr<TestState> test_state) const {
1840 bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
1841 if (!ssl) {
1842 return nullptr;
1843 }
1844
1845 if (!SetTestConfig(ssl.get(), this)) {
1846 return nullptr;
1847 }
1848 if (test_state != nullptr) {
1849 if (!SetTestState(ssl.get(), std::move(test_state))) {
1850 return nullptr;
1851 }
1852 }
1853
1854 if (fallback_scsv && !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
1855 return nullptr;
1856 }
1857 // Install the certificate synchronously if nothing else will handle it.
1858 if (!use_early_callback && !use_old_client_cert_callback && !async &&
1859 !InstallMultipleCertificates(ssl.get()) &&
1860 !InstallCertificate(ssl.get())) {
1861 return nullptr;
1862 }
1863 if (!use_old_client_cert_callback) {
1864 SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
1865 }
1866 int mode = SSL_VERIFY_NONE;
1867 if (require_any_client_certificate) {
1868 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1869 }
1870 if (verify_peer) {
1871 mode = SSL_VERIFY_PEER;
1872 }
1873 if (verify_peer_if_no_obc) {
1874 // Set SSL_VERIFY_FAIL_IF_NO_PEER_CERT so testing whether client
1875 // certificates were requested is easy.
1876 mode = SSL_VERIFY_PEER | SSL_VERIFY_PEER_IF_NO_OBC |
1877 SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1878 }
1879 if (use_custom_verify_callback) {
1880 SSL_set_custom_verify(ssl.get(), mode, CustomVerifyCallback);
1881 } else if (mode != SSL_VERIFY_NONE) {
1882 SSL_set_verify(ssl.get(), mode, NULL);
1883 }
1884 if (false_start) {
1885 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
1886 }
1887 if (cbc_record_splitting) {
1888 SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
1889 }
1890 if (partial_write) {
1891 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
1892 }
1893 if (reverify_on_resume) {
1894 SSL_CTX_set_reverify_on_resume(ssl_ctx, 1);
1895 }
1896 if (enforce_rsa_key_usage) {
1897 SSL_set_enforce_rsa_key_usage(ssl.get(), 1);
1898 }
1899 if (no_check_client_certificate_type) {
1900 SSL_set_check_client_certificate_type(ssl.get(), 0);
1901 }
1902 if (no_tls13) {
1903 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
1904 }
1905 if (no_tls12) {
1906 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
1907 }
1908 if (no_tls11) {
1909 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
1910 }
1911 if (no_tls1) {
1912 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
1913 }
1914 if (no_ticket) {
1915 SSL_set_options(ssl.get(), SSL_OP_NO_TICKET);
1916 }
1917 if (!expect_channel_id.empty() || enable_channel_id) {
1918 SSL_set_tls_channel_id_enabled(ssl.get(), 1);
1919 }
1920 if (enable_ech_grease) {
1921 SSL_set_enable_ech_grease(ssl.get(), 1);
1922 }
1923 if (!ech_config_list.empty() &&
1924 !SSL_set1_ech_config_list(
1925 ssl.get(), reinterpret_cast<const uint8_t *>(ech_config_list.data()),
1926 ech_config_list.size())) {
1927 return nullptr;
1928 }
1929 if (ech_server_configs.size() != ech_server_keys.size() ||
1930 ech_server_configs.size() != ech_is_retry_config.size()) {
1931 fprintf(stderr,
1932 "-ech-server-config, -ech-server-key, and -ech-is-retry-config "
1933 "flags must match.\n");
1934 return nullptr;
1935 }
1936 if (!ech_server_configs.empty()) {
1937 bssl::UniquePtr<SSL_ECH_KEYS> keys(SSL_ECH_KEYS_new());
1938 if (!keys) {
1939 return nullptr;
1940 }
1941 for (size_t i = 0; i < ech_server_configs.size(); i++) {
1942 const std::string &ech_config = ech_server_configs[i];
1943 const std::string &ech_private_key = ech_server_keys[i];
1944 const int is_retry_config = ech_is_retry_config[i];
1945 bssl::ScopedEVP_HPKE_KEY key;
1946 if (!EVP_HPKE_KEY_init(
1947 key.get(), EVP_hpke_x25519_hkdf_sha256(),
1948 reinterpret_cast<const uint8_t *>(ech_private_key.data()),
1949 ech_private_key.size()) ||
1950 !SSL_ECH_KEYS_add(
1951 keys.get(), is_retry_config,
1952 reinterpret_cast<const uint8_t *>(ech_config.data()),
1953 ech_config.size(), key.get())) {
1954 return nullptr;
1955 }
1956 }
1957 if (!SSL_CTX_set1_ech_keys(ssl_ctx, keys.get())) {
1958 return nullptr;
1959 }
1960 }
1961 if (!send_channel_id.empty()) {
1962 bssl::UniquePtr<EVP_PKEY> pkey = LoadPrivateKey(send_channel_id);
1963 if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
1964 return nullptr;
1965 }
1966 }
1967 if (!host_name.empty() &&
1968 !SSL_set_tlsext_host_name(ssl.get(), host_name.c_str())) {
1969 return nullptr;
1970 }
1971 if (!advertise_alpn.empty() &&
1972 SSL_set_alpn_protos(
1973 ssl.get(), reinterpret_cast<const uint8_t *>(advertise_alpn.data()),
1974 advertise_alpn.size()) != 0) {
1975 return nullptr;
1976 }
1977 if (!defer_alps) {
1978 for (const auto &pair : application_settings) {
1979 if (!SSL_add_application_settings(
1980 ssl.get(), reinterpret_cast<const uint8_t *>(pair.first.data()),
1981 pair.first.size(),
1982 reinterpret_cast<const uint8_t *>(pair.second.data()),
1983 pair.second.size())) {
1984 return nullptr;
1985 }
1986 }
1987 }
1988 if (!psk.empty()) {
1989 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
1990 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
1991 }
1992 if (!psk_identity.empty() &&
1993 !SSL_use_psk_identity_hint(ssl.get(), psk_identity.c_str())) {
1994 return nullptr;
1995 }
1996 if (!srtp_profiles.empty() &&
1997 !SSL_set_srtp_profiles(ssl.get(), srtp_profiles.c_str())) {
1998 return nullptr;
1999 }
2000 if (enable_ocsp_stapling) {
2001 SSL_enable_ocsp_stapling(ssl.get());
2002 }
2003 if (enable_signed_cert_timestamps) {
2004 SSL_enable_signed_cert_timestamps(ssl.get());
2005 }
2006 if (min_version != 0 &&
2007 !SSL_set_min_proto_version(ssl.get(), min_version)) {
2008 return nullptr;
2009 }
2010 if (max_version != 0 &&
2011 !SSL_set_max_proto_version(ssl.get(), max_version)) {
2012 return nullptr;
2013 }
2014 if (mtu != 0) {
2015 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
2016 SSL_set_mtu(ssl.get(), mtu);
2017 }
2018 if (install_ddos_callback) {
2019 SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
2020 }
2021 SSL_set_shed_handshake_config(ssl.get(), true);
2022 if (renegotiate_once) {
2023 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_once);
2024 }
2025 if (renegotiate_freely || forbid_renegotiation_after_handshake) {
2026 // |forbid_renegotiation_after_handshake| will disable renegotiation later.
2027 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
2028 }
2029 if (renegotiate_ignore) {
2030 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_ignore);
2031 }
2032 if (renegotiate_explicit) {
2033 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_explicit);
2034 }
2035 if (!check_close_notify) {
2036 SSL_set_quiet_shutdown(ssl.get(), 1);
2037 }
2038 if (!curves.empty()) {
2039 std::vector<int> nids;
2040 for (auto curve : curves) {
2041 switch (curve) {
2042 case SSL_GROUP_SECP224R1:
2043 nids.push_back(NID_secp224r1);
2044 break;
2045
2046 case SSL_GROUP_SECP256R1:
2047 nids.push_back(NID_X9_62_prime256v1);
2048 break;
2049
2050 case SSL_GROUP_SECP384R1:
2051 nids.push_back(NID_secp384r1);
2052 break;
2053
2054 case SSL_GROUP_SECP521R1:
2055 nids.push_back(NID_secp521r1);
2056 break;
2057
2058 case SSL_GROUP_X25519:
2059 nids.push_back(NID_X25519);
2060 break;
2061 }
2062 if (!SSL_set1_curves(ssl.get(), &nids[0], nids.size())) {
2063 return nullptr;
2064 }
2065 }
2066 }
2067 if (initial_timeout_duration_ms > 0) {
2068 DTLSv1_set_initial_timeout_duration(ssl.get(), initial_timeout_duration_ms);
2069 }
2070 if (max_cert_list > 0) {
2071 SSL_set_max_cert_list(ssl.get(), max_cert_list);
2072 }
2073 if (retain_only_sha256_client_cert) {
2074 SSL_set_retain_only_sha256_of_client_certs(ssl.get(), 1);
2075 }
2076 if (max_send_fragment > 0) {
2077 SSL_set_max_send_fragment(ssl.get(), max_send_fragment);
2078 }
2079 if (alps_use_new_codepoint) {
2080 SSL_set_alps_use_new_codepoint(ssl.get(), 1);
2081 }
2082 if (quic_use_legacy_codepoint != -1) {
2083 SSL_set_quic_use_legacy_codepoint(ssl.get(), quic_use_legacy_codepoint);
2084 }
2085 if (!quic_transport_params.empty()) {
2086 if (!SSL_set_quic_transport_params(
2087 ssl.get(),
2088 reinterpret_cast<const uint8_t *>(quic_transport_params.data()),
2089 quic_transport_params.size())) {
2090 return nullptr;
2091 }
2092 }
2093 if (jdk11_workaround) {
2094 SSL_set_jdk11_workaround(ssl.get(), 1);
2095 }
2096
2097 if (session != NULL) {
2098 if (!is_server) {
2099 if (SSL_set_session(ssl.get(), session) != 1) {
2100 return nullptr;
2101 }
2102 } else if (async) {
2103 // The internal session cache is disabled, so install the session
2104 // manually.
2105 SSL_SESSION_up_ref(session);
2106 GetTestState(ssl.get())->pending_session.reset(session);
2107 }
2108 }
2109
2110 if (!delegated_credential.empty()) {
2111 std::string::size_type comma = delegated_credential.find(',');
2112 if (comma == std::string::npos) {
2113 fprintf(stderr,
2114 "failed to find comma in delegated credential argument.\n");
2115 return nullptr;
2116 }
2117
2118 const std::string dc_hex = delegated_credential.substr(0, comma);
2119 const std::string pkcs8_hex = delegated_credential.substr(comma + 1);
2120 std::string dc, pkcs8;
2121 if (!HexDecode(&dc, dc_hex) || !HexDecode(&pkcs8, pkcs8_hex)) {
2122 fprintf(stderr, "failed to hex decode delegated credential argument.\n");
2123 return nullptr;
2124 }
2125
2126 CBS dc_cbs(bssl::Span<const uint8_t>(
2127 reinterpret_cast<const uint8_t *>(dc.data()), dc.size()));
2128 CBS pkcs8_cbs(bssl::Span<const uint8_t>(
2129 reinterpret_cast<const uint8_t *>(pkcs8.data()), pkcs8.size()));
2130
2131 bssl::UniquePtr<EVP_PKEY> priv(EVP_parse_private_key(&pkcs8_cbs));
2132 if (!priv) {
2133 fprintf(stderr, "failed to parse delegated credential private key.\n");
2134 return nullptr;
2135 }
2136
2137 bssl::UniquePtr<CRYPTO_BUFFER> dc_buf(
2138 CRYPTO_BUFFER_new_from_CBS(&dc_cbs, nullptr));
2139 if (!SSL_set1_delegated_credential(ssl.get(), dc_buf.get(),
2140 priv.get(), nullptr)) {
2141 fprintf(stderr, "SSL_set1_delegated_credential failed.\n");
2142 return nullptr;
2143 }
2144 }
2145
2146 if (!quic_early_data_context.empty() &&
2147 !SSL_set_quic_early_data_context(
2148 ssl.get(),
2149 reinterpret_cast<const uint8_t *>(quic_early_data_context.data()),
2150 quic_early_data_context.size())) {
2151 return nullptr;
2152 }
2153
2154 return ssl;
2155 }