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