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