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