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