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