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