• 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 #if !defined(__STDC_FORMAT_MACROS)
16 #define __STDC_FORMAT_MACROS
17 #endif
18 
19 #include <openssl/base.h>
20 
21 #if !defined(OPENSSL_WINDOWS)
22 #include <arpa/inet.h>
23 #include <netinet/in.h>
24 #include <netinet/tcp.h>
25 #include <signal.h>
26 #include <sys/socket.h>
27 #include <sys/time.h>
28 #include <unistd.h>
29 #else
30 #include <io.h>
31 OPENSSL_MSVC_PRAGMA(warning(push, 3))
32 #include <winsock2.h>
33 #include <ws2tcpip.h>
34 OPENSSL_MSVC_PRAGMA(warning(pop))
35 
36 OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
37 #endif
38 
39 #include <assert.h>
40 #include <inttypes.h>
41 #include <string.h>
42 #include <time.h>
43 
44 #include <openssl/aead.h>
45 #include <openssl/bio.h>
46 #include <openssl/buf.h>
47 #include <openssl/bytestring.h>
48 #include <openssl/cipher.h>
49 #include <openssl/crypto.h>
50 #include <openssl/digest.h>
51 #include <openssl/err.h>
52 #include <openssl/evp.h>
53 #include <openssl/hmac.h>
54 #include <openssl/nid.h>
55 #include <openssl/rand.h>
56 #include <openssl/ssl.h>
57 #include <openssl/x509.h>
58 
59 #include <functional>
60 #include <memory>
61 #include <string>
62 #include <vector>
63 
64 #include "../../crypto/internal.h"
65 #include "../internal.h"
66 #include "async_bio.h"
67 #include "fuzzer_tags.h"
68 #include "packeted_bio.h"
69 #include "test_config.h"
70 
71 
72 static CRYPTO_BUFFER_POOL *g_pool = nullptr;
73 
74 #if !defined(OPENSSL_WINDOWS)
closesocket(int sock)75 static int closesocket(int sock) {
76   return close(sock);
77 }
78 
PrintSocketError(const char * func)79 static void PrintSocketError(const char *func) {
80   perror(func);
81 }
82 #else
PrintSocketError(const char * func)83 static void PrintSocketError(const char *func) {
84   fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
85 }
86 #endif
87 
Usage(const char * program)88 static int Usage(const char *program) {
89   fprintf(stderr, "Usage: %s [flags...]\n", program);
90   return 1;
91 }
92 
93 struct TestState {
94   // async_bio is async BIO which pauses reads and writes.
95   BIO *async_bio = nullptr;
96   // packeted_bio is the packeted BIO which simulates read timeouts.
97   BIO *packeted_bio = nullptr;
98   bssl::UniquePtr<EVP_PKEY> channel_id;
99   bool cert_ready = false;
100   bssl::UniquePtr<SSL_SESSION> session;
101   bssl::UniquePtr<SSL_SESSION> pending_session;
102   bool early_callback_called = false;
103   bool handshake_done = false;
104   // private_key is the underlying private key used when testing custom keys.
105   bssl::UniquePtr<EVP_PKEY> private_key;
106   std::vector<uint8_t> private_key_result;
107   // private_key_retries is the number of times an asynchronous private key
108   // operation has been retried.
109   unsigned private_key_retries = 0;
110   bool got_new_session = false;
111   bssl::UniquePtr<SSL_SESSION> new_session;
112   bool ticket_decrypt_done = false;
113   bool alpn_select_done = false;
114   bool is_resume = false;
115   bool early_callback_ready = false;
116   bool custom_verify_ready = false;
117   std::string msg_callback_text;
118   bool msg_callback_ok = true;
119   // cert_verified is true if certificate verification has been driven to
120   // completion. This tests that the callback is not called again after this.
121   bool cert_verified = false;
122 };
123 
TestStateExFree(void * parent,void * ptr,CRYPTO_EX_DATA * ad,int index,long argl,void * argp)124 static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
125                             int index, long argl, void *argp) {
126   delete ((TestState *)ptr);
127 }
128 
129 static int g_config_index = 0;
130 static int g_state_index = 0;
131 
SetTestConfig(SSL * ssl,const TestConfig * config)132 static bool SetTestConfig(SSL *ssl, const TestConfig *config) {
133   return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
134 }
135 
GetTestConfig(const SSL * ssl)136 static const TestConfig *GetTestConfig(const SSL *ssl) {
137   return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
138 }
139 
SetTestState(SSL * ssl,std::unique_ptr<TestState> state)140 static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
141   // |SSL_set_ex_data| takes ownership of |state| only on success.
142   if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
143     state.release();
144     return true;
145   }
146   return false;
147 }
148 
GetTestState(const SSL * ssl)149 static TestState *GetTestState(const SSL *ssl) {
150   return (TestState *)SSL_get_ex_data(ssl, g_state_index);
151 }
152 
MoveExData(SSL * dest,SSL * src)153 static bool MoveExData(SSL *dest, SSL *src) {
154   TestState *state = GetTestState(src);
155   const TestConfig *config = GetTestConfig(src);
156   if (!SSL_set_ex_data(src, g_state_index, nullptr) ||
157       !SSL_set_ex_data(dest, g_state_index, state) ||
158       !SSL_set_ex_data(src, g_config_index, nullptr) ||
159       !SSL_set_ex_data(dest, g_config_index, (void *) config)) {
160     return false;
161   }
162 
163   return true;
164 }
165 
MoveBIOs(SSL * dest,SSL * src)166 static void MoveBIOs(SSL *dest, SSL *src) {
167   BIO *rbio = SSL_get_rbio(src);
168   BIO_up_ref(rbio);
169   SSL_set0_rbio(dest, rbio);
170 
171   BIO *wbio = SSL_get_wbio(src);
172   BIO_up_ref(wbio);
173   SSL_set0_wbio(dest, wbio);
174 
175   SSL_set0_rbio(src, nullptr);
176   SSL_set0_wbio(src, nullptr);
177 }
178 
LoadCertificate(bssl::UniquePtr<X509> * out_x509,bssl::UniquePtr<STACK_OF (X509)> * out_chain,const std::string & file)179 static bool LoadCertificate(bssl::UniquePtr<X509> *out_x509,
180                             bssl::UniquePtr<STACK_OF(X509)> *out_chain,
181                             const std::string &file) {
182   bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
183   if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
184     return false;
185   }
186 
187   out_x509->reset(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
188   if (!*out_x509) {
189     return false;
190   }
191 
192   out_chain->reset(sk_X509_new_null());
193   if (!*out_chain) {
194     return false;
195   }
196 
197   // Keep reading the certificate chain.
198   for (;;) {
199     bssl::UniquePtr<X509> cert(
200         PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
201     if (!cert) {
202       break;
203     }
204 
205     if (!sk_X509_push(out_chain->get(), cert.get())) {
206       return false;
207     }
208     cert.release();  // sk_X509_push takes ownership.
209   }
210 
211   uint32_t err = ERR_peek_last_error();
212   if (ERR_GET_LIB(err) != ERR_LIB_PEM ||
213       ERR_GET_REASON(err) != PEM_R_NO_START_LINE) {
214     return false;
215 }
216 
217   ERR_clear_error();
218   return true;
219 }
220 
LoadPrivateKey(const std::string & file)221 static bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
222   bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
223   if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
224     return nullptr;
225   }
226   return bssl::UniquePtr<EVP_PKEY>(
227       PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
228 }
229 
FromHexDigit(uint8_t * out,char c)230 static bool FromHexDigit(uint8_t *out, char c) {
231   if ('0' <= c && c <= '9') {
232     *out = c - '0';
233     return true;
234   }
235   if ('a' <= c && c <= 'f') {
236     *out = c - 'a' + 10;
237     return true;
238   }
239   if ('A' <= c && c <= 'F') {
240     *out = c - 'A' + 10;
241     return true;
242   }
243   return false;
244 }
245 
HexDecode(std::string * out,const std::string & in)246 static bool HexDecode(std::string *out, const std::string &in) {
247   if ((in.size() & 1) != 0) {
248     return false;
249   }
250 
251   std::unique_ptr<uint8_t[]> buf(new uint8_t[in.size() / 2]);
252   for (size_t i = 0; i < in.size() / 2; i++) {
253     uint8_t high, low;
254     if (!FromHexDigit(&high, in[i*2]) ||
255         !FromHexDigit(&low, in[i*2+1])) {
256       return false;
257     }
258     buf[i] = (high << 4) | low;
259   }
260 
261   out->assign(reinterpret_cast<const char *>(buf.get()), in.size() / 2);
262   return true;
263 }
264 
SplitParts(const std::string & in,const char delim)265 static std::vector<std::string> SplitParts(const std::string &in,
266                                            const char delim) {
267   std::vector<std::string> ret;
268   size_t start = 0;
269 
270   for (size_t i = 0; i < in.size(); i++) {
271     if (in[i] == delim) {
272       ret.push_back(in.substr(start, i - start));
273       start = i + 1;
274     }
275   }
276 
277   ret.push_back(in.substr(start, std::string::npos));
278   return ret;
279 }
280 
DecodeHexStrings(const std::string & hex_strings)281 static std::vector<std::string> DecodeHexStrings(
282     const std::string &hex_strings) {
283   std::vector<std::string> ret;
284   const std::vector<std::string> parts = SplitParts(hex_strings, ',');
285 
286   for (const auto &part : parts) {
287     std::string binary;
288     if (!HexDecode(&binary, part)) {
289       fprintf(stderr, "Bad hex string: %s\n", part.c_str());
290       return ret;
291     }
292 
293     ret.push_back(binary);
294   }
295 
296   return ret;
297 }
298 
DecodeHexX509Names(const std::string & hex_names)299 static bssl::UniquePtr<STACK_OF(X509_NAME)> DecodeHexX509Names(
300     const std::string &hex_names) {
301   const std::vector<std::string> der_names = DecodeHexStrings(hex_names);
302   bssl::UniquePtr<STACK_OF(X509_NAME)> ret(sk_X509_NAME_new_null());
303   if (!ret) {
304     return nullptr;
305   }
306 
307   for (const auto &der_name : der_names) {
308     const uint8_t *const data =
309         reinterpret_cast<const uint8_t *>(der_name.data());
310     const uint8_t *derp = data;
311     bssl::UniquePtr<X509_NAME> name(
312         d2i_X509_NAME(nullptr, &derp, der_name.size()));
313     if (!name || derp != data + der_name.size()) {
314       fprintf(stderr, "Failed to parse X509_NAME.\n");
315       return nullptr;
316     }
317 
318     if (!sk_X509_NAME_push(ret.get(), name.get())) {
319       return nullptr;
320     }
321     name.release();
322   }
323 
324   return ret;
325 }
326 
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)327 static ssl_private_key_result_t AsyncPrivateKeySign(
328     SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
329     uint16_t signature_algorithm, const uint8_t *in, size_t in_len) {
330   TestState *test_state = GetTestState(ssl);
331   if (!test_state->private_key_result.empty()) {
332     fprintf(stderr, "AsyncPrivateKeySign called with operation pending.\n");
333     abort();
334   }
335 
336   // Determine the hash.
337   const EVP_MD *md;
338   switch (signature_algorithm) {
339     case SSL_SIGN_RSA_PKCS1_SHA1:
340     case SSL_SIGN_ECDSA_SHA1:
341       md = EVP_sha1();
342       break;
343     case SSL_SIGN_RSA_PKCS1_SHA256:
344     case SSL_SIGN_ECDSA_SECP256R1_SHA256:
345     case SSL_SIGN_RSA_PSS_SHA256:
346       md = EVP_sha256();
347       break;
348     case SSL_SIGN_RSA_PKCS1_SHA384:
349     case SSL_SIGN_ECDSA_SECP384R1_SHA384:
350     case SSL_SIGN_RSA_PSS_SHA384:
351       md = EVP_sha384();
352       break;
353     case SSL_SIGN_RSA_PKCS1_SHA512:
354     case SSL_SIGN_ECDSA_SECP521R1_SHA512:
355     case SSL_SIGN_RSA_PSS_SHA512:
356       md = EVP_sha512();
357       break;
358     case SSL_SIGN_RSA_PKCS1_MD5_SHA1:
359       md = EVP_md5_sha1();
360       break;
361     case SSL_SIGN_ED25519:
362       md = nullptr;
363       break;
364     default:
365       fprintf(stderr, "Unknown signature algorithm %04x.\n",
366               signature_algorithm);
367       return ssl_private_key_failure;
368   }
369 
370   bssl::ScopedEVP_MD_CTX ctx;
371   EVP_PKEY_CTX *pctx;
372   if (!EVP_DigestSignInit(ctx.get(), &pctx, md, nullptr,
373                           test_state->private_key.get())) {
374     return ssl_private_key_failure;
375   }
376 
377   // Configure additional signature parameters.
378   switch (signature_algorithm) {
379     case SSL_SIGN_RSA_PSS_SHA256:
380     case SSL_SIGN_RSA_PSS_SHA384:
381     case SSL_SIGN_RSA_PSS_SHA512:
382       if (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) ||
383           !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
384                                             -1 /* salt len = hash len */)) {
385         return ssl_private_key_failure;
386       }
387   }
388 
389   // Write the signature into |test_state|.
390   size_t len = 0;
391   if (!EVP_DigestSign(ctx.get(), nullptr, &len, in, in_len)) {
392     return ssl_private_key_failure;
393   }
394   test_state->private_key_result.resize(len);
395   if (!EVP_DigestSign(ctx.get(), test_state->private_key_result.data(), &len,
396                       in, in_len)) {
397     return ssl_private_key_failure;
398   }
399   test_state->private_key_result.resize(len);
400 
401   // The signature will be released asynchronously in |AsyncPrivateKeyComplete|.
402   return ssl_private_key_retry;
403 }
404 
AsyncPrivateKeyDecrypt(SSL * ssl,uint8_t * out,size_t * out_len,size_t max_out,const uint8_t * in,size_t in_len)405 static ssl_private_key_result_t AsyncPrivateKeyDecrypt(
406     SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
407     const uint8_t *in, size_t in_len) {
408   TestState *test_state = GetTestState(ssl);
409   if (!test_state->private_key_result.empty()) {
410     fprintf(stderr,
411             "AsyncPrivateKeyDecrypt called with operation pending.\n");
412     abort();
413   }
414 
415   RSA *rsa = EVP_PKEY_get0_RSA(test_state->private_key.get());
416   if (rsa == NULL) {
417     fprintf(stderr,
418             "AsyncPrivateKeyDecrypt called with incorrect key type.\n");
419     abort();
420   }
421   test_state->private_key_result.resize(RSA_size(rsa));
422   if (!RSA_decrypt(rsa, out_len, test_state->private_key_result.data(),
423                    RSA_size(rsa), in, in_len, RSA_NO_PADDING)) {
424     return ssl_private_key_failure;
425   }
426 
427   test_state->private_key_result.resize(*out_len);
428 
429   // The decryption will be released asynchronously in |AsyncPrivateComplete|.
430   return ssl_private_key_retry;
431 }
432 
AsyncPrivateKeyComplete(SSL * ssl,uint8_t * out,size_t * out_len,size_t max_out)433 static ssl_private_key_result_t AsyncPrivateKeyComplete(
434     SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
435   TestState *test_state = GetTestState(ssl);
436   if (test_state->private_key_result.empty()) {
437     fprintf(stderr,
438             "AsyncPrivateKeyComplete called without operation pending.\n");
439     abort();
440   }
441 
442   if (test_state->private_key_retries < 2) {
443     // Only return the decryption on the second attempt, to test both incomplete
444     // |decrypt| and |decrypt_complete|.
445     return ssl_private_key_retry;
446   }
447 
448   if (max_out < test_state->private_key_result.size()) {
449     fprintf(stderr, "Output buffer too small.\n");
450     return ssl_private_key_failure;
451   }
452   OPENSSL_memcpy(out, test_state->private_key_result.data(),
453                  test_state->private_key_result.size());
454   *out_len = test_state->private_key_result.size();
455 
456   test_state->private_key_result.clear();
457   test_state->private_key_retries = 0;
458   return ssl_private_key_success;
459 }
460 
461 static const SSL_PRIVATE_KEY_METHOD g_async_private_key_method = {
462     AsyncPrivateKeySign,
463     AsyncPrivateKeyDecrypt,
464     AsyncPrivateKeyComplete,
465 };
466 
467 template<typename T>
468 struct Free {
operator ()Free469   void operator()(T *buf) {
470     free(buf);
471   }
472 };
473 
GetCertificate(SSL * ssl,bssl::UniquePtr<X509> * out_x509,bssl::UniquePtr<STACK_OF (X509)> * out_chain,bssl::UniquePtr<EVP_PKEY> * out_pkey)474 static bool GetCertificate(SSL *ssl, bssl::UniquePtr<X509> *out_x509,
475                            bssl::UniquePtr<STACK_OF(X509)> *out_chain,
476                            bssl::UniquePtr<EVP_PKEY> *out_pkey) {
477   const TestConfig *config = GetTestConfig(ssl);
478 
479   if (!config->signing_prefs.empty()) {
480     std::vector<uint16_t> u16s(config->signing_prefs.begin(),
481                                config->signing_prefs.end());
482     if (!SSL_set_signing_algorithm_prefs(ssl, u16s.data(), u16s.size())) {
483       return false;
484     }
485   }
486 
487   if (!config->key_file.empty()) {
488     *out_pkey = LoadPrivateKey(config->key_file.c_str());
489     if (!*out_pkey) {
490       return false;
491     }
492   }
493   if (!config->cert_file.empty() &&
494       !LoadCertificate(out_x509, out_chain, config->cert_file.c_str())) {
495     return false;
496   }
497   if (!config->ocsp_response.empty() &&
498       !SSL_set_ocsp_response(ssl, (const uint8_t *)config->ocsp_response.data(),
499                              config->ocsp_response.size())) {
500     return false;
501   }
502   return true;
503 }
504 
InstallCertificate(SSL * ssl)505 static bool InstallCertificate(SSL *ssl) {
506   bssl::UniquePtr<X509> x509;
507   bssl::UniquePtr<STACK_OF(X509)> chain;
508   bssl::UniquePtr<EVP_PKEY> pkey;
509   if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
510     return false;
511   }
512 
513   if (pkey) {
514     TestState *test_state = GetTestState(ssl);
515     const TestConfig *config = GetTestConfig(ssl);
516     if (config->async) {
517       test_state->private_key = std::move(pkey);
518       SSL_set_private_key_method(ssl, &g_async_private_key_method);
519     } else if (!SSL_use_PrivateKey(ssl, pkey.get())) {
520       return false;
521     }
522   }
523 
524   if (x509 && !SSL_use_certificate(ssl, x509.get())) {
525     return false;
526   }
527 
528   if (sk_X509_num(chain.get()) > 0 &&
529       !SSL_set1_chain(ssl, chain.get())) {
530     return false;
531   }
532 
533   return true;
534 }
535 
SelectCertificateCallback(const SSL_CLIENT_HELLO * client_hello)536 static enum ssl_select_cert_result_t SelectCertificateCallback(
537     const SSL_CLIENT_HELLO *client_hello) {
538   const TestConfig *config = GetTestConfig(client_hello->ssl);
539   GetTestState(client_hello->ssl)->early_callback_called = true;
540 
541   if (!config->expected_server_name.empty()) {
542     const uint8_t *extension_data;
543     size_t extension_len;
544     CBS extension, server_name_list, host_name;
545     uint8_t name_type;
546 
547     if (!SSL_early_callback_ctx_extension_get(
548             client_hello, TLSEXT_TYPE_server_name, &extension_data,
549             &extension_len)) {
550       fprintf(stderr, "Could not find server_name extension.\n");
551       return ssl_select_cert_error;
552     }
553 
554     CBS_init(&extension, extension_data, extension_len);
555     if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
556         CBS_len(&extension) != 0 ||
557         !CBS_get_u8(&server_name_list, &name_type) ||
558         name_type != TLSEXT_NAMETYPE_host_name ||
559         !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
560         CBS_len(&server_name_list) != 0) {
561       fprintf(stderr, "Could not decode server_name extension.\n");
562       return ssl_select_cert_error;
563     }
564 
565     if (!CBS_mem_equal(&host_name,
566                        (const uint8_t*)config->expected_server_name.data(),
567                        config->expected_server_name.size())) {
568       fprintf(stderr, "Server name mismatch.\n");
569     }
570   }
571 
572   if (config->fail_early_callback) {
573     return ssl_select_cert_error;
574   }
575 
576   // Install the certificate in the early callback.
577   if (config->use_early_callback) {
578     bool early_callback_ready =
579         GetTestState(client_hello->ssl)->early_callback_ready;
580     if (config->async && !early_callback_ready) {
581       // Install the certificate asynchronously.
582       return ssl_select_cert_retry;
583     }
584     if (!InstallCertificate(client_hello->ssl)) {
585       return ssl_select_cert_error;
586     }
587   }
588   return ssl_select_cert_success;
589 }
590 
CheckCertificateRequest(SSL * ssl)591 static bool CheckCertificateRequest(SSL *ssl) {
592   const TestConfig *config = GetTestConfig(ssl);
593 
594   if (!config->expected_certificate_types.empty()) {
595     const uint8_t *certificate_types;
596     size_t certificate_types_len =
597         SSL_get0_certificate_types(ssl, &certificate_types);
598     if (certificate_types_len != config->expected_certificate_types.size() ||
599         OPENSSL_memcmp(certificate_types,
600                        config->expected_certificate_types.data(),
601                        certificate_types_len) != 0) {
602       fprintf(stderr, "certificate types mismatch\n");
603       return false;
604     }
605   }
606 
607   if (!config->expected_client_ca_list.empty()) {
608     bssl::UniquePtr<STACK_OF(X509_NAME)> expected =
609         DecodeHexX509Names(config->expected_client_ca_list);
610     const size_t num_expected = sk_X509_NAME_num(expected.get());
611 
612     const STACK_OF(X509_NAME) *received = SSL_get_client_CA_list(ssl);
613     const size_t num_received = sk_X509_NAME_num(received);
614 
615     if (num_received != num_expected) {
616       fprintf(stderr, "expected %u names in CertificateRequest but got %u\n",
617               static_cast<unsigned>(num_expected),
618               static_cast<unsigned>(num_received));
619       return false;
620     }
621 
622     for (size_t i = 0; i < num_received; i++) {
623       if (X509_NAME_cmp(sk_X509_NAME_value(received, i),
624                         sk_X509_NAME_value(expected.get(), i)) != 0) {
625         fprintf(stderr, "names in CertificateRequest differ at index #%d\n",
626                 static_cast<unsigned>(i));
627         return false;
628       }
629     }
630 
631     STACK_OF(CRYPTO_BUFFER) *buffers = SSL_get0_server_requested_CAs(ssl);
632     if (sk_CRYPTO_BUFFER_num(buffers) != num_received) {
633       fprintf(stderr,
634               "Mismatch between SSL_get_server_requested_CAs and "
635               "SSL_get_client_CA_list.\n");
636       return false;
637     }
638   }
639 
640   return true;
641 }
642 
ClientCertCallback(SSL * ssl,X509 ** out_x509,EVP_PKEY ** out_pkey)643 static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
644   if (!CheckCertificateRequest(ssl)) {
645     return -1;
646   }
647 
648   if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
649     return -1;
650   }
651 
652   bssl::UniquePtr<X509> x509;
653   bssl::UniquePtr<STACK_OF(X509)> chain;
654   bssl::UniquePtr<EVP_PKEY> pkey;
655   if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
656     return -1;
657   }
658 
659   // Return zero for no certificate.
660   if (!x509) {
661     return 0;
662   }
663 
664   // Chains and asynchronous private keys are not supported with client_cert_cb.
665   *out_x509 = x509.release();
666   *out_pkey = pkey.release();
667   return 1;
668 }
669 
CertCallback(SSL * ssl,void * arg)670 static int CertCallback(SSL *ssl, void *arg) {
671   const TestConfig *config = GetTestConfig(ssl);
672 
673   // Check the CertificateRequest metadata is as expected.
674   if (!SSL_is_server(ssl) && !CheckCertificateRequest(ssl)) {
675     return -1;
676   }
677 
678   if (config->fail_cert_callback) {
679     return 0;
680   }
681 
682   // The certificate will be installed via other means.
683   if (!config->async || config->use_early_callback) {
684     return 1;
685   }
686 
687   if (!GetTestState(ssl)->cert_ready) {
688     return -1;
689   }
690   if (!InstallCertificate(ssl)) {
691     return 0;
692   }
693   return 1;
694 }
695 
CheckVerifyCallback(SSL * ssl)696 static bool CheckVerifyCallback(SSL *ssl) {
697   const TestConfig *config = GetTestConfig(ssl);
698   if (!config->expected_ocsp_response.empty()) {
699     const uint8_t *data;
700     size_t len;
701     SSL_get0_ocsp_response(ssl, &data, &len);
702     if (len == 0) {
703       fprintf(stderr, "OCSP response not available in verify callback\n");
704       return false;
705     }
706   }
707 
708   if (GetTestState(ssl)->cert_verified) {
709     fprintf(stderr, "Certificate verified twice.\n");
710     return false;
711   }
712 
713   return true;
714 }
715 
CertVerifyCallback(X509_STORE_CTX * store_ctx,void * arg)716 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
717   SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data(store_ctx,
718       SSL_get_ex_data_X509_STORE_CTX_idx());
719   const TestConfig *config = GetTestConfig(ssl);
720   if (!CheckVerifyCallback(ssl)) {
721     return 0;
722   }
723 
724   GetTestState(ssl)->cert_verified = true;
725   if (config->verify_fail) {
726     store_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION;
727     return 0;
728   }
729 
730   return 1;
731 }
732 
CustomVerifyCallback(SSL * ssl,uint8_t * out_alert)733 static ssl_verify_result_t CustomVerifyCallback(SSL *ssl, uint8_t *out_alert) {
734   const TestConfig *config = GetTestConfig(ssl);
735   if (!CheckVerifyCallback(ssl)) {
736     return ssl_verify_invalid;
737   }
738 
739   if (config->async && !GetTestState(ssl)->custom_verify_ready) {
740     return ssl_verify_retry;
741   }
742 
743   GetTestState(ssl)->cert_verified = true;
744   if (config->verify_fail) {
745     return ssl_verify_invalid;
746   }
747 
748   return ssl_verify_ok;
749 }
750 
NextProtosAdvertisedCallback(SSL * ssl,const uint8_t ** out,unsigned int * out_len,void * arg)751 static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
752                                         unsigned int *out_len, void *arg) {
753   const TestConfig *config = GetTestConfig(ssl);
754   if (config->advertise_npn.empty()) {
755     return SSL_TLSEXT_ERR_NOACK;
756   }
757 
758   *out = (const uint8_t*)config->advertise_npn.data();
759   *out_len = config->advertise_npn.size();
760   return SSL_TLSEXT_ERR_OK;
761 }
762 
NextProtoSelectCallback(SSL * ssl,uint8_t ** out,uint8_t * outlen,const uint8_t * in,unsigned inlen,void * arg)763 static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
764                                    const uint8_t* in, unsigned inlen, void* arg) {
765   const TestConfig *config = GetTestConfig(ssl);
766   if (config->select_next_proto.empty()) {
767     return SSL_TLSEXT_ERR_NOACK;
768   }
769 
770   *out = (uint8_t*)config->select_next_proto.data();
771   *outlen = config->select_next_proto.size();
772   return SSL_TLSEXT_ERR_OK;
773 }
774 
AlpnSelectCallback(SSL * ssl,const uint8_t ** out,uint8_t * outlen,const uint8_t * in,unsigned inlen,void * arg)775 static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
776                               const uint8_t* in, unsigned inlen, void* arg) {
777   if (GetTestState(ssl)->alpn_select_done) {
778     fprintf(stderr, "AlpnSelectCallback called after completion.\n");
779     exit(1);
780   }
781 
782   GetTestState(ssl)->alpn_select_done = true;
783 
784   const TestConfig *config = GetTestConfig(ssl);
785   if (config->decline_alpn) {
786     return SSL_TLSEXT_ERR_NOACK;
787   }
788 
789   if (!config->expected_advertised_alpn.empty() &&
790       (config->expected_advertised_alpn.size() != inlen ||
791        OPENSSL_memcmp(config->expected_advertised_alpn.data(), in, inlen) !=
792            0)) {
793     fprintf(stderr, "bad ALPN select callback inputs\n");
794     exit(1);
795   }
796 
797   *out = (const uint8_t*)config->select_alpn.data();
798   *outlen = config->select_alpn.size();
799   return SSL_TLSEXT_ERR_OK;
800 }
801 
PskClientCallback(SSL * ssl,const char * hint,char * out_identity,unsigned max_identity_len,uint8_t * out_psk,unsigned max_psk_len)802 static unsigned PskClientCallback(SSL *ssl, const char *hint,
803                                   char *out_identity,
804                                   unsigned max_identity_len,
805                                   uint8_t *out_psk, unsigned max_psk_len) {
806   const TestConfig *config = GetTestConfig(ssl);
807 
808   if (config->psk_identity.empty()) {
809     if (hint != nullptr) {
810       fprintf(stderr, "Server PSK hint was non-null.\n");
811       return 0;
812     }
813   } else if (hint == nullptr ||
814              strcmp(hint, config->psk_identity.c_str()) != 0) {
815     fprintf(stderr, "Server PSK hint did not match.\n");
816     return 0;
817   }
818 
819   // Account for the trailing '\0' for the identity.
820   if (config->psk_identity.size() >= max_identity_len ||
821       config->psk.size() > max_psk_len) {
822     fprintf(stderr, "PSK buffers too small\n");
823     return 0;
824   }
825 
826   BUF_strlcpy(out_identity, config->psk_identity.c_str(),
827               max_identity_len);
828   OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size());
829   return config->psk.size();
830 }
831 
PskServerCallback(SSL * ssl,const char * identity,uint8_t * out_psk,unsigned max_psk_len)832 static unsigned PskServerCallback(SSL *ssl, const char *identity,
833                                   uint8_t *out_psk, unsigned max_psk_len) {
834   const TestConfig *config = GetTestConfig(ssl);
835 
836   if (strcmp(identity, config->psk_identity.c_str()) != 0) {
837     fprintf(stderr, "Client PSK identity did not match.\n");
838     return 0;
839   }
840 
841   if (config->psk.size() > max_psk_len) {
842     fprintf(stderr, "PSK buffers too small\n");
843     return 0;
844   }
845 
846   OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size());
847   return config->psk.size();
848 }
849 
850 static timeval g_clock;
851 
CurrentTimeCallback(const SSL * ssl,timeval * out_clock)852 static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
853   *out_clock = g_clock;
854 }
855 
ChannelIdCallback(SSL * ssl,EVP_PKEY ** out_pkey)856 static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
857   *out_pkey = GetTestState(ssl)->channel_id.release();
858 }
859 
GetSessionCallback(SSL * ssl,const uint8_t * data,int len,int * copy)860 static SSL_SESSION *GetSessionCallback(SSL *ssl, const uint8_t *data, int len,
861                                        int *copy) {
862   TestState *async_state = GetTestState(ssl);
863   if (async_state->session) {
864     *copy = 0;
865     return async_state->session.release();
866   } else if (async_state->pending_session) {
867     return SSL_magic_pending_session_ptr();
868   } else {
869     return NULL;
870   }
871 }
872 
DDoSCallback(const SSL_CLIENT_HELLO * client_hello)873 static int DDoSCallback(const SSL_CLIENT_HELLO *client_hello) {
874   const TestConfig *config = GetTestConfig(client_hello->ssl);
875   static int callback_num = 0;
876 
877   callback_num++;
878   if (config->fail_ddos_callback ||
879       (config->fail_second_ddos_callback && callback_num == 2)) {
880     return 0;
881   }
882   return 1;
883 }
884 
InfoCallback(const SSL * ssl,int type,int val)885 static void InfoCallback(const SSL *ssl, int type, int val) {
886   if (type == SSL_CB_HANDSHAKE_DONE) {
887     if (GetTestConfig(ssl)->handshake_never_done) {
888       fprintf(stderr, "Handshake unexpectedly completed.\n");
889       // Abort before any expected error code is printed, to ensure the overall
890       // test fails.
891       abort();
892     }
893     // This callback is called when the handshake completes. |SSL_get_session|
894     // must continue to work and |SSL_in_init| must return false.
895     if (SSL_in_init(ssl) || SSL_get_session(ssl) == nullptr) {
896       fprintf(stderr, "Invalid state for SSL_CB_HANDSHAKE_DONE.\n");
897       abort();
898     }
899     GetTestState(ssl)->handshake_done = true;
900 
901     // Callbacks may be called again on a new handshake.
902     GetTestState(ssl)->ticket_decrypt_done = false;
903     GetTestState(ssl)->alpn_select_done = false;
904   }
905 }
906 
NewSessionCallback(SSL * ssl,SSL_SESSION * session)907 static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
908   // This callback is called as the handshake completes. |SSL_get_session|
909   // must continue to work and, historically, |SSL_in_init| returned false at
910   // this point.
911   if (SSL_in_init(ssl) || SSL_get_session(ssl) == nullptr) {
912     fprintf(stderr, "Invalid state for NewSessionCallback.\n");
913     abort();
914   }
915 
916   GetTestState(ssl)->got_new_session = true;
917   GetTestState(ssl)->new_session.reset(session);
918   return 1;
919 }
920 
TicketKeyCallback(SSL * ssl,uint8_t * key_name,uint8_t * iv,EVP_CIPHER_CTX * ctx,HMAC_CTX * hmac_ctx,int encrypt)921 static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
922                              EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
923                              int encrypt) {
924   if (!encrypt) {
925     if (GetTestState(ssl)->ticket_decrypt_done) {
926       fprintf(stderr, "TicketKeyCallback called after completion.\n");
927       return -1;
928     }
929 
930     GetTestState(ssl)->ticket_decrypt_done = true;
931   }
932 
933   // This is just test code, so use the all-zeros key.
934   static const uint8_t kZeros[16] = {0};
935 
936   if (encrypt) {
937     OPENSSL_memcpy(key_name, kZeros, sizeof(kZeros));
938     RAND_bytes(iv, 16);
939   } else if (OPENSSL_memcmp(key_name, kZeros, 16) != 0) {
940     return 0;
941   }
942 
943   if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
944       !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
945     return -1;
946   }
947 
948   if (!encrypt) {
949     return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
950   }
951   return 1;
952 }
953 
954 // kCustomExtensionValue is the extension value that the custom extension
955 // callbacks will add.
956 static const uint16_t kCustomExtensionValue = 1234;
957 static void *const kCustomExtensionAddArg =
958     reinterpret_cast<void *>(kCustomExtensionValue);
959 static void *const kCustomExtensionParseArg =
960     reinterpret_cast<void *>(kCustomExtensionValue + 1);
961 static const char kCustomExtensionContents[] = "custom extension";
962 
CustomExtensionAddCallback(SSL * ssl,unsigned extension_value,const uint8_t ** out,size_t * out_len,int * out_alert_value,void * add_arg)963 static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
964                                       const uint8_t **out, size_t *out_len,
965                                       int *out_alert_value, void *add_arg) {
966   if (extension_value != kCustomExtensionValue ||
967       add_arg != kCustomExtensionAddArg) {
968     abort();
969   }
970 
971   if (GetTestConfig(ssl)->custom_extension_skip) {
972     return 0;
973   }
974   if (GetTestConfig(ssl)->custom_extension_fail_add) {
975     return -1;
976   }
977 
978   *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
979   *out_len = sizeof(kCustomExtensionContents) - 1;
980 
981   return 1;
982 }
983 
CustomExtensionFreeCallback(SSL * ssl,unsigned extension_value,const uint8_t * out,void * add_arg)984 static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
985                                         const uint8_t *out, void *add_arg) {
986   if (extension_value != kCustomExtensionValue ||
987       add_arg != kCustomExtensionAddArg ||
988       out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
989     abort();
990   }
991 }
992 
CustomExtensionParseCallback(SSL * ssl,unsigned extension_value,const uint8_t * contents,size_t contents_len,int * out_alert_value,void * parse_arg)993 static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
994                                         const uint8_t *contents,
995                                         size_t contents_len,
996                                         int *out_alert_value, void *parse_arg) {
997   if (extension_value != kCustomExtensionValue ||
998       parse_arg != kCustomExtensionParseArg) {
999     abort();
1000   }
1001 
1002   if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
1003       OPENSSL_memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
1004     *out_alert_value = SSL_AD_DECODE_ERROR;
1005     return 0;
1006   }
1007 
1008   return 1;
1009 }
1010 
ServerNameCallback(SSL * ssl,int * out_alert,void * arg)1011 static int ServerNameCallback(SSL *ssl, int *out_alert, void *arg) {
1012   // SNI must be accessible from the SNI callback.
1013   const TestConfig *config = GetTestConfig(ssl);
1014   const char *server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1015   if (server_name == nullptr ||
1016       std::string(server_name) != config->expected_server_name) {
1017     fprintf(stderr, "servername mismatch (got %s; want %s)\n", server_name,
1018             config->expected_server_name.c_str());
1019     return SSL_TLSEXT_ERR_ALERT_FATAL;
1020   }
1021 
1022   return SSL_TLSEXT_ERR_OK;
1023 }
1024 
MessageCallback(int is_write,int version,int content_type,const void * buf,size_t len,SSL * ssl,void * arg)1025 static void MessageCallback(int is_write, int version, int content_type,
1026                             const void *buf, size_t len, SSL *ssl, void *arg) {
1027   const uint8_t *buf_u8 = reinterpret_cast<const uint8_t *>(buf);
1028   const TestConfig *config = GetTestConfig(ssl);
1029   TestState *state = GetTestState(ssl);
1030   if (!state->msg_callback_ok) {
1031     return;
1032   }
1033 
1034   if (content_type == SSL3_RT_HEADER) {
1035     if (len !=
1036         (config->is_dtls ? DTLS1_RT_HEADER_LENGTH : SSL3_RT_HEADER_LENGTH)) {
1037       fprintf(stderr, "Incorrect length for record header: %zu\n", len);
1038       state->msg_callback_ok = false;
1039     }
1040     return;
1041   }
1042 
1043   state->msg_callback_text += is_write ? "write " : "read ";
1044   switch (content_type) {
1045     case 0:
1046       if (version != SSL2_VERSION) {
1047         fprintf(stderr, "Incorrect version for V2ClientHello: %x\n", version);
1048         state->msg_callback_ok = false;
1049         return;
1050       }
1051       state->msg_callback_text += "v2clienthello\n";
1052       return;
1053 
1054     case SSL3_RT_HANDSHAKE: {
1055       CBS cbs;
1056       CBS_init(&cbs, buf_u8, len);
1057       uint8_t type;
1058       uint32_t msg_len;
1059       if (!CBS_get_u8(&cbs, &type) ||
1060           // TODO(davidben): Reporting on entire messages would be more
1061           // consistent than fragments.
1062           (config->is_dtls &&
1063            !CBS_skip(&cbs, 3 /* total */ + 2 /* seq */ + 3 /* frag_off */)) ||
1064           !CBS_get_u24(&cbs, &msg_len) ||
1065           !CBS_skip(&cbs, msg_len) ||
1066           CBS_len(&cbs) != 0) {
1067         fprintf(stderr, "Could not parse handshake message.\n");
1068         state->msg_callback_ok = false;
1069         return;
1070       }
1071       char text[16];
1072       snprintf(text, sizeof(text), "hs %d\n", type);
1073       state->msg_callback_text += text;
1074       return;
1075     }
1076 
1077     case SSL3_RT_CHANGE_CIPHER_SPEC:
1078       if (len != 1 || buf_u8[0] != 1) {
1079         fprintf(stderr, "Invalid ChangeCipherSpec.\n");
1080         state->msg_callback_ok = false;
1081         return;
1082       }
1083       state->msg_callback_text += "ccs\n";
1084       return;
1085 
1086     case SSL3_RT_ALERT:
1087       if (len != 2) {
1088         fprintf(stderr, "Invalid alert.\n");
1089         state->msg_callback_ok = false;
1090         return;
1091       }
1092       char text[16];
1093       snprintf(text, sizeof(text), "alert %d %d\n", buf_u8[0], buf_u8[1]);
1094       state->msg_callback_text += text;
1095       return;
1096 
1097     default:
1098       fprintf(stderr, "Invalid content_type: %d\n", content_type);
1099       state->msg_callback_ok = false;
1100   }
1101 }
1102 
1103 // Connect returns a new socket connected to localhost on |port| or -1 on
1104 // error.
Connect(uint16_t port)1105 static int Connect(uint16_t port) {
1106   for (int af : { AF_INET6, AF_INET }) {
1107     int sock = socket(af, SOCK_STREAM, 0);
1108     if (sock == -1) {
1109       PrintSocketError("socket");
1110       return -1;
1111     }
1112     int nodelay = 1;
1113     if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
1114             reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
1115       PrintSocketError("setsockopt");
1116       closesocket(sock);
1117       return -1;
1118     }
1119 
1120     sockaddr_storage ss;
1121     OPENSSL_memset(&ss, 0, sizeof(ss));
1122     ss.ss_family = af;
1123     socklen_t len = 0;
1124 
1125     if (af == AF_INET6) {
1126       sockaddr_in6 *sin6 = (sockaddr_in6 *) &ss;
1127       len = sizeof(*sin6);
1128       sin6->sin6_port = htons(port);
1129       if (!inet_pton(AF_INET6, "::1", &sin6->sin6_addr)) {
1130         PrintSocketError("inet_pton");
1131         closesocket(sock);
1132         return -1;
1133       }
1134     } else if (af == AF_INET) {
1135       sockaddr_in *sin = (sockaddr_in *) &ss;
1136       len = sizeof(*sin);
1137       sin->sin_port = htons(port);
1138       if (!inet_pton(AF_INET, "127.0.0.1", &sin->sin_addr)) {
1139         PrintSocketError("inet_pton");
1140         closesocket(sock);
1141         return -1;
1142       }
1143     }
1144 
1145     if (connect(sock, reinterpret_cast<const sockaddr*>(&ss), len) == 0) {
1146       return sock;
1147     }
1148     closesocket(sock);
1149   }
1150 
1151   PrintSocketError("connect");
1152   return -1;
1153 }
1154 
1155 class SocketCloser {
1156  public:
SocketCloser(int sock)1157   explicit SocketCloser(int sock) : sock_(sock) {}
~SocketCloser()1158   ~SocketCloser() {
1159     // Half-close and drain the socket before releasing it. This seems to be
1160     // necessary for graceful shutdown on Windows. It will also avoid write
1161     // failures in the test runner.
1162 #if defined(OPENSSL_WINDOWS)
1163     shutdown(sock_, SD_SEND);
1164 #else
1165     shutdown(sock_, SHUT_WR);
1166 #endif
1167     while (true) {
1168       char buf[1024];
1169       if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
1170         break;
1171       }
1172     }
1173     closesocket(sock_);
1174   }
1175 
1176  private:
1177   const int sock_;
1178 };
1179 
ssl_ctx_add_session(SSL_SESSION * session,void * void_param)1180 static void ssl_ctx_add_session(SSL_SESSION *session, void *void_param) {
1181   SSL_CTX *ctx = reinterpret_cast<SSL_CTX *>(void_param);
1182   bssl::UniquePtr<SSL_SESSION> new_session = bssl::SSL_SESSION_dup(
1183       session, SSL_SESSION_INCLUDE_NONAUTH | SSL_SESSION_INCLUDE_TICKET);
1184   if (new_session != nullptr) {
1185     SSL_CTX_add_session(ctx, new_session.get());
1186   }
1187 }
1188 
SetupCtx(SSL_CTX * old_ctx,const TestConfig * config)1189 static bssl::UniquePtr<SSL_CTX> SetupCtx(SSL_CTX *old_ctx,
1190                                          const TestConfig *config) {
1191   bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(
1192       config->is_dtls ? DTLS_method() : TLS_method()));
1193   if (!ssl_ctx) {
1194     return nullptr;
1195   }
1196 
1197   SSL_CTX_set0_buffer_pool(ssl_ctx.get(), g_pool);
1198 
1199   // Enable SSL 3.0 and TLS 1.3 for tests.
1200   if (!config->is_dtls &&
1201       (!SSL_CTX_set_min_proto_version(ssl_ctx.get(), SSL3_VERSION) ||
1202        !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION))) {
1203     return nullptr;
1204   }
1205 
1206   std::string cipher_list = "ALL";
1207   if (!config->cipher.empty()) {
1208     cipher_list = config->cipher;
1209     SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
1210   }
1211   if (!SSL_CTX_set_strict_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
1212     return nullptr;
1213   }
1214 
1215   if (config->async && config->is_server) {
1216     // Disable the internal session cache. To test asynchronous session lookup,
1217     // we use an external session cache.
1218     SSL_CTX_set_session_cache_mode(
1219         ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
1220     SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
1221   } else {
1222     SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
1223   }
1224 
1225   SSL_CTX_set_select_certificate_cb(ssl_ctx.get(), SelectCertificateCallback);
1226 
1227   if (config->use_old_client_cert_callback) {
1228     SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
1229   }
1230 
1231   SSL_CTX_set_next_protos_advertised_cb(
1232       ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
1233   if (!config->select_next_proto.empty()) {
1234     SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
1235                                      NULL);
1236   }
1237 
1238   if (!config->select_alpn.empty() || config->decline_alpn) {
1239     SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
1240   }
1241 
1242   SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
1243 
1244   SSL_CTX_set_current_time_cb(ssl_ctx.get(), CurrentTimeCallback);
1245 
1246   SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
1247   SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
1248 
1249   if (config->use_ticket_callback) {
1250     SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
1251   }
1252 
1253   if (config->enable_client_custom_extension &&
1254       !SSL_CTX_add_client_custom_ext(
1255           ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
1256           CustomExtensionFreeCallback, kCustomExtensionAddArg,
1257           CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1258     return nullptr;
1259   }
1260 
1261   if (config->enable_server_custom_extension &&
1262       !SSL_CTX_add_server_custom_ext(
1263           ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
1264           CustomExtensionFreeCallback, kCustomExtensionAddArg,
1265           CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1266     return nullptr;
1267   }
1268 
1269   if (!config->use_custom_verify_callback) {
1270     SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), CertVerifyCallback, NULL);
1271   }
1272 
1273   if (!config->signed_cert_timestamps.empty() &&
1274       !SSL_CTX_set_signed_cert_timestamp_list(
1275           ssl_ctx.get(), (const uint8_t *)config->signed_cert_timestamps.data(),
1276           config->signed_cert_timestamps.size())) {
1277     return nullptr;
1278   }
1279 
1280   if (!config->use_client_ca_list.empty()) {
1281     if (config->use_client_ca_list == "<NULL>") {
1282       SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
1283     } else if (config->use_client_ca_list == "<EMPTY>") {
1284       bssl::UniquePtr<STACK_OF(X509_NAME)> names;
1285       SSL_CTX_set_client_CA_list(ssl_ctx.get(), names.release());
1286     } else {
1287       bssl::UniquePtr<STACK_OF(X509_NAME)> names =
1288           DecodeHexX509Names(config->use_client_ca_list);
1289       SSL_CTX_set_client_CA_list(ssl_ctx.get(), names.release());
1290     }
1291   }
1292 
1293   if (config->enable_grease) {
1294     SSL_CTX_set_grease_enabled(ssl_ctx.get(), 1);
1295   }
1296 
1297   if (!config->expected_server_name.empty()) {
1298     SSL_CTX_set_tlsext_servername_callback(ssl_ctx.get(), ServerNameCallback);
1299   }
1300 
1301   if (!config->ticket_key.empty() &&
1302       !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), config->ticket_key.data(),
1303                                       config->ticket_key.size())) {
1304     return nullptr;
1305   }
1306 
1307   if (config->enable_early_data) {
1308     SSL_CTX_set_early_data_enabled(ssl_ctx.get(), 1);
1309   }
1310 
1311   SSL_CTX_set_tls13_variant(
1312       ssl_ctx.get(), static_cast<enum tls13_variant_t>(config->tls13_variant));
1313 
1314   if (config->allow_unknown_alpn_protos) {
1315     SSL_CTX_set_allow_unknown_alpn_protos(ssl_ctx.get(), 1);
1316   }
1317 
1318   if (config->enable_ed25519) {
1319     SSL_CTX_set_ed25519_enabled(ssl_ctx.get(), 1);
1320   }
1321 
1322   if (!config->verify_prefs.empty()) {
1323     std::vector<uint16_t> u16s(config->verify_prefs.begin(),
1324                                config->verify_prefs.end());
1325     if (!SSL_CTX_set_verify_algorithm_prefs(ssl_ctx.get(), u16s.data(),
1326                                             u16s.size())) {
1327       return nullptr;
1328     }
1329   }
1330 
1331   SSL_CTX_set_msg_callback(ssl_ctx.get(), MessageCallback);
1332 
1333   if (config->allow_false_start_without_alpn) {
1334     SSL_CTX_set_false_start_allowed_without_alpn(ssl_ctx.get(), 1);
1335   }
1336 
1337   if (old_ctx) {
1338     uint8_t keys[48];
1339     if (!SSL_CTX_get_tlsext_ticket_keys(old_ctx, &keys, sizeof(keys)) ||
1340         !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), keys, sizeof(keys))) {
1341       return nullptr;
1342     }
1343     lh_SSL_SESSION_doall_arg(old_ctx->sessions, ssl_ctx_add_session,
1344                              ssl_ctx.get());
1345   }
1346 
1347   return ssl_ctx;
1348 }
1349 
1350 // RetryAsync is called after a failed operation on |ssl| with return code
1351 // |ret|. If the operation should be retried, it simulates one asynchronous
1352 // event and returns true. Otherwise it returns false.
RetryAsync(SSL * ssl,int ret)1353 static bool RetryAsync(SSL *ssl, int ret) {
1354   // No error; don't retry.
1355   if (ret >= 0) {
1356     return false;
1357   }
1358 
1359   TestState *test_state = GetTestState(ssl);
1360   assert(GetTestConfig(ssl)->async);
1361 
1362   if (test_state->packeted_bio != nullptr &&
1363       PacketedBioAdvanceClock(test_state->packeted_bio)) {
1364     // The DTLS retransmit logic silently ignores write failures. So the test
1365     // may progress, allow writes through synchronously.
1366     AsyncBioEnforceWriteQuota(test_state->async_bio, false);
1367     int timeout_ret = DTLSv1_handle_timeout(ssl);
1368     AsyncBioEnforceWriteQuota(test_state->async_bio, true);
1369 
1370     if (timeout_ret < 0) {
1371       fprintf(stderr, "Error retransmitting.\n");
1372       return false;
1373     }
1374     return true;
1375   }
1376 
1377   // See if we needed to read or write more. If so, allow one byte through on
1378   // the appropriate end to maximally stress the state machine.
1379   switch (SSL_get_error(ssl, ret)) {
1380     case SSL_ERROR_WANT_READ:
1381       AsyncBioAllowRead(test_state->async_bio, 1);
1382       return true;
1383     case SSL_ERROR_WANT_WRITE:
1384       AsyncBioAllowWrite(test_state->async_bio, 1);
1385       return true;
1386     case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
1387       bssl::UniquePtr<EVP_PKEY> pkey =
1388           LoadPrivateKey(GetTestConfig(ssl)->send_channel_id);
1389       if (!pkey) {
1390         return false;
1391       }
1392       test_state->channel_id = std::move(pkey);
1393       return true;
1394     }
1395     case SSL_ERROR_WANT_X509_LOOKUP:
1396       test_state->cert_ready = true;
1397       return true;
1398     case SSL_ERROR_PENDING_SESSION:
1399       test_state->session = std::move(test_state->pending_session);
1400       return true;
1401     case SSL_ERROR_PENDING_CERTIFICATE:
1402       test_state->early_callback_ready = true;
1403       return true;
1404     case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
1405       test_state->private_key_retries++;
1406       return true;
1407     case SSL_ERROR_WANT_CERTIFICATE_VERIFY:
1408       test_state->custom_verify_ready = true;
1409       return true;
1410     default:
1411       return false;
1412   }
1413 }
1414 
1415 // CheckIdempotentError runs |func|, an operation on |ssl|, ensuring that
1416 // errors are idempotent.
CheckIdempotentError(const char * name,SSL * ssl,std::function<int ()> func)1417 static int CheckIdempotentError(const char *name, SSL *ssl,
1418                                 std::function<int()> func) {
1419   int ret = func();
1420   int ssl_err = SSL_get_error(ssl, ret);
1421   uint32_t err = ERR_peek_error();
1422   if (ssl_err == SSL_ERROR_SSL || ssl_err == SSL_ERROR_ZERO_RETURN) {
1423     int ret2 = func();
1424     int ssl_err2 = SSL_get_error(ssl, ret2);
1425     uint32_t err2 = ERR_peek_error();
1426     if (ret != ret2 || ssl_err != ssl_err2 || err != err2) {
1427       fprintf(stderr, "Repeating %s did not replay the error.\n", name);
1428       char buf[256];
1429       ERR_error_string_n(err, buf, sizeof(buf));
1430       fprintf(stderr, "Wanted: %d %d %s\n", ret, ssl_err, buf);
1431       ERR_error_string_n(err2, buf, sizeof(buf));
1432       fprintf(stderr, "Got:    %d %d %s\n", ret2, ssl_err2, buf);
1433       // runner treats exit code 90 as always failing. Otherwise, it may
1434       // accidentally consider the result an expected protocol failure.
1435       exit(90);
1436     }
1437   }
1438   return ret;
1439 }
1440 
1441 // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
1442 // the result value of the final |SSL_read| call.
DoRead(SSL * ssl,uint8_t * out,size_t max_out)1443 static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
1444   const TestConfig *config = GetTestConfig(ssl);
1445   TestState *test_state = GetTestState(ssl);
1446   int ret;
1447   do {
1448     if (config->async) {
1449       // The DTLS retransmit logic silently ignores write failures. So the test
1450       // may progress, allow writes through synchronously. |SSL_read| may
1451       // trigger a retransmit, so disconnect the write quota.
1452       AsyncBioEnforceWriteQuota(test_state->async_bio, false);
1453     }
1454     ret = CheckIdempotentError("SSL_peek/SSL_read", ssl, [&]() -> int {
1455       return config->peek_then_read ? SSL_peek(ssl, out, max_out)
1456                                     : SSL_read(ssl, out, max_out);
1457     });
1458     if (config->async) {
1459       AsyncBioEnforceWriteQuota(test_state->async_bio, true);
1460     }
1461 
1462     // Run the exporter after each read. This is to test that the exporter fails
1463     // during a renegotiation.
1464     if (config->use_exporter_between_reads) {
1465       uint8_t buf;
1466       if (!SSL_export_keying_material(ssl, &buf, 1, NULL, 0, NULL, 0, 0)) {
1467         fprintf(stderr, "failed to export keying material\n");
1468         return -1;
1469       }
1470     }
1471   } while (config->async && RetryAsync(ssl, ret));
1472 
1473   if (config->peek_then_read && ret > 0) {
1474     std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
1475 
1476     // SSL_peek should synchronously return the same data.
1477     int ret2 = SSL_peek(ssl, buf.get(), ret);
1478     if (ret2 != ret ||
1479         OPENSSL_memcmp(buf.get(), out, ret) != 0) {
1480       fprintf(stderr, "First and second SSL_peek did not match.\n");
1481       return -1;
1482     }
1483 
1484     // SSL_read should synchronously return the same data and consume it.
1485     ret2 = SSL_read(ssl, buf.get(), ret);
1486     if (ret2 != ret ||
1487         OPENSSL_memcmp(buf.get(), out, ret) != 0) {
1488       fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
1489       return -1;
1490     }
1491   }
1492 
1493   return ret;
1494 }
1495 
1496 // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
1497 // operations. It returns the result of the final |SSL_write| call.
WriteAll(SSL * ssl,const void * in_,size_t in_len)1498 static int WriteAll(SSL *ssl, const void *in_, size_t in_len) {
1499   const uint8_t *in = reinterpret_cast<const uint8_t *>(in_);
1500   const TestConfig *config = GetTestConfig(ssl);
1501   int ret;
1502   do {
1503     ret = SSL_write(ssl, in, in_len);
1504     if (ret > 0) {
1505       in += ret;
1506       in_len -= ret;
1507     }
1508   } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
1509   return ret;
1510 }
1511 
1512 // DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
1513 // returns the result of the final |SSL_shutdown| call.
DoShutdown(SSL * ssl)1514 static int DoShutdown(SSL *ssl) {
1515   const TestConfig *config = GetTestConfig(ssl);
1516   int ret;
1517   do {
1518     ret = SSL_shutdown(ssl);
1519   } while (config->async && RetryAsync(ssl, ret));
1520   return ret;
1521 }
1522 
1523 // DoSendFatalAlert calls |SSL_send_fatal_alert|, resolving any asynchronous
1524 // operations. It returns the result of the final |SSL_send_fatal_alert| call.
DoSendFatalAlert(SSL * ssl,uint8_t alert)1525 static int DoSendFatalAlert(SSL *ssl, uint8_t alert) {
1526   const TestConfig *config = GetTestConfig(ssl);
1527   int ret;
1528   do {
1529     ret = SSL_send_fatal_alert(ssl, alert);
1530   } while (config->async && RetryAsync(ssl, ret));
1531   return ret;
1532 }
1533 
GetProtocolVersion(const SSL * ssl)1534 static uint16_t GetProtocolVersion(const SSL *ssl) {
1535   uint16_t version = SSL_version(ssl);
1536   if (!SSL_is_dtls(ssl)) {
1537     return version;
1538   }
1539   return 0x0201 + ~version;
1540 }
1541 
1542 // CheckAuthProperties checks, after the initial handshake is completed or
1543 // after a renegotiation, that authentication-related properties match |config|.
CheckAuthProperties(SSL * ssl,bool is_resume,const TestConfig * config)1544 static bool CheckAuthProperties(SSL *ssl, bool is_resume,
1545                                 const TestConfig *config) {
1546   if (!config->expected_ocsp_response.empty()) {
1547     const uint8_t *data;
1548     size_t len;
1549     SSL_get0_ocsp_response(ssl, &data, &len);
1550     if (config->expected_ocsp_response.size() != len ||
1551         OPENSSL_memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
1552       fprintf(stderr, "OCSP response mismatch\n");
1553       return false;
1554     }
1555   }
1556 
1557   if (!config->expected_signed_cert_timestamps.empty()) {
1558     const uint8_t *data;
1559     size_t len;
1560     SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
1561     if (config->expected_signed_cert_timestamps.size() != len ||
1562         OPENSSL_memcmp(config->expected_signed_cert_timestamps.data(), data,
1563                        len) != 0) {
1564       fprintf(stderr, "SCT list mismatch\n");
1565       return false;
1566     }
1567   }
1568 
1569   if (config->expect_verify_result) {
1570     int expected_verify_result = config->verify_fail ?
1571       X509_V_ERR_APPLICATION_VERIFICATION :
1572       X509_V_OK;
1573 
1574     if (SSL_get_verify_result(ssl) != expected_verify_result) {
1575       fprintf(stderr, "Wrong certificate verification result\n");
1576       return false;
1577     }
1578   }
1579 
1580   if (!config->expect_peer_cert_file.empty()) {
1581     bssl::UniquePtr<X509> expect_leaf;
1582     bssl::UniquePtr<STACK_OF(X509)> expect_chain;
1583     if (!LoadCertificate(&expect_leaf, &expect_chain,
1584                          config->expect_peer_cert_file)) {
1585       return false;
1586     }
1587 
1588     // For historical reasons, clients report a chain with a leaf and servers
1589     // without.
1590     if (!config->is_server) {
1591       if (!sk_X509_insert(expect_chain.get(), expect_leaf.get(), 0)) {
1592         return false;
1593       }
1594       X509_up_ref(expect_leaf.get());  // sk_X509_push takes ownership.
1595     }
1596 
1597     bssl::UniquePtr<X509> leaf(SSL_get_peer_certificate(ssl));
1598     STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl);
1599     if (X509_cmp(leaf.get(), expect_leaf.get()) != 0) {
1600       fprintf(stderr, "Received a different leaf certificate than expected.\n");
1601       return false;
1602     }
1603 
1604     if (sk_X509_num(chain) != sk_X509_num(expect_chain.get())) {
1605       fprintf(stderr, "Received a chain of length %zu instead of %zu.\n",
1606               sk_X509_num(chain), sk_X509_num(expect_chain.get()));
1607       return false;
1608     }
1609 
1610     for (size_t i = 0; i < sk_X509_num(chain); i++) {
1611       if (X509_cmp(sk_X509_value(chain, i),
1612                    sk_X509_value(expect_chain.get(), i)) != 0) {
1613         fprintf(stderr, "Chain certificate %zu did not match.\n",
1614                 i + 1);
1615         return false;
1616       }
1617     }
1618   }
1619 
1620   if (SSL_get_session(ssl)->peer_sha256_valid !=
1621       config->expect_sha256_client_cert) {
1622     fprintf(stderr,
1623             "Unexpected SHA-256 client cert state: expected:%d is_resume:%d.\n",
1624             config->expect_sha256_client_cert, is_resume);
1625     return false;
1626   }
1627 
1628   if (config->expect_sha256_client_cert &&
1629       SSL_get_session(ssl)->certs != nullptr) {
1630     fprintf(stderr, "Have both client cert and SHA-256 hash: is_resume:%d.\n",
1631             is_resume);
1632     return false;
1633   }
1634 
1635   return true;
1636 }
1637 
1638 // CheckHandshakeProperties checks, immediately after |ssl| completes its
1639 // initial handshake (or False Starts), whether all the properties are
1640 // consistent with the test configuration and invariants.
CheckHandshakeProperties(SSL * ssl,bool is_resume,const TestConfig * config)1641 static bool CheckHandshakeProperties(SSL *ssl, bool is_resume,
1642                                      const TestConfig *config) {
1643   if (!CheckAuthProperties(ssl, is_resume, config)) {
1644     return false;
1645   }
1646 
1647   if (SSL_get_current_cipher(ssl) == nullptr) {
1648     fprintf(stderr, "null cipher after handshake\n");
1649     return false;
1650   }
1651 
1652   if (config->expect_version != 0 &&
1653       SSL_version(ssl) != config->expect_version) {
1654     fprintf(stderr, "want version %04x, got %04x\n", config->expect_version,
1655             SSL_version(ssl));
1656     return false;
1657   }
1658 
1659   bool expect_resume =
1660       is_resume && (!config->expect_session_miss || SSL_in_early_data(ssl));
1661   if (!!SSL_session_reused(ssl) != expect_resume) {
1662     fprintf(stderr, "session unexpectedly was%s reused\n",
1663             SSL_session_reused(ssl) ? "" : " not");
1664     return false;
1665   }
1666 
1667   bool expect_handshake_done =
1668       (is_resume || !config->false_start) && !SSL_in_early_data(ssl);
1669   if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
1670     fprintf(stderr, "handshake was%s completed\n",
1671             GetTestState(ssl)->handshake_done ? "" : " not");
1672     return false;
1673   }
1674 
1675   if (expect_handshake_done && !config->is_server) {
1676     bool expect_new_session =
1677         !config->expect_no_session &&
1678         (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
1679         // Session tickets are sent post-handshake in TLS 1.3.
1680         GetProtocolVersion(ssl) < TLS1_3_VERSION;
1681     if (expect_new_session != GetTestState(ssl)->got_new_session) {
1682       fprintf(stderr,
1683               "new session was%s cached, but we expected the opposite\n",
1684               GetTestState(ssl)->got_new_session ? "" : " not");
1685       return false;
1686     }
1687   }
1688 
1689   if (!is_resume) {
1690     if (config->expect_session_id && !GetTestState(ssl)->got_new_session) {
1691       fprintf(stderr, "session was not cached on the server.\n");
1692       return false;
1693     }
1694     if (config->expect_no_session_id && GetTestState(ssl)->got_new_session) {
1695       fprintf(stderr, "session was unexpectedly cached on the server.\n");
1696       return false;
1697     }
1698   }
1699 
1700   if (config->is_server && !GetTestState(ssl)->early_callback_called) {
1701     fprintf(stderr, "early callback not called\n");
1702     return false;
1703   }
1704 
1705   if (!config->expected_server_name.empty()) {
1706     const char *server_name =
1707         SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1708     if (server_name == nullptr ||
1709         server_name != config->expected_server_name) {
1710       fprintf(stderr, "servername mismatch (got %s; want %s)\n",
1711               server_name, config->expected_server_name.c_str());
1712       return false;
1713     }
1714   }
1715 
1716   if (!config->expected_next_proto.empty()) {
1717     const uint8_t *next_proto;
1718     unsigned next_proto_len;
1719     SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
1720     if (next_proto_len != config->expected_next_proto.size() ||
1721         OPENSSL_memcmp(next_proto, config->expected_next_proto.data(),
1722                        next_proto_len) != 0) {
1723       fprintf(stderr, "negotiated next proto mismatch\n");
1724       return false;
1725     }
1726   }
1727 
1728   if (!config->is_server) {
1729     const uint8_t *alpn_proto;
1730     unsigned alpn_proto_len;
1731     SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
1732     if (alpn_proto_len != config->expected_alpn.size() ||
1733         OPENSSL_memcmp(alpn_proto, config->expected_alpn.data(),
1734                        alpn_proto_len) != 0) {
1735       fprintf(stderr, "negotiated alpn proto mismatch\n");
1736       return false;
1737     }
1738   }
1739 
1740   if (!config->expected_quic_transport_params.empty()) {
1741     const uint8_t *peer_params;
1742     size_t peer_params_len;
1743     SSL_get_peer_quic_transport_params(ssl, &peer_params, &peer_params_len);
1744     if (peer_params_len != config->expected_quic_transport_params.size() ||
1745         OPENSSL_memcmp(peer_params,
1746                        config->expected_quic_transport_params.data(),
1747                        peer_params_len) != 0) {
1748       fprintf(stderr, "QUIC transport params mismatch\n");
1749       return false;
1750     }
1751   }
1752 
1753   if (!config->expected_channel_id.empty()) {
1754     uint8_t channel_id[64];
1755     if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
1756       fprintf(stderr, "no channel id negotiated\n");
1757       return false;
1758     }
1759     if (config->expected_channel_id.size() != 64 ||
1760         OPENSSL_memcmp(config->expected_channel_id.data(), channel_id, 64) !=
1761             0) {
1762       fprintf(stderr, "channel id mismatch\n");
1763       return false;
1764     }
1765   }
1766 
1767   if (config->expected_token_binding_param != -1) {
1768     if (!SSL_is_token_binding_negotiated(ssl)) {
1769       fprintf(stderr, "no Token Binding negotiated\n");
1770       return false;
1771     }
1772     if (SSL_get_negotiated_token_binding_param(ssl) !=
1773         static_cast<uint8_t>(config->expected_token_binding_param)) {
1774       fprintf(stderr, "Token Binding param mismatch\n");
1775       return false;
1776     }
1777   }
1778 
1779   if (config->expect_extended_master_secret && !SSL_get_extms_support(ssl)) {
1780     fprintf(stderr, "No EMS for connection when expected\n");
1781     return false;
1782   }
1783 
1784   if (config->expect_secure_renegotiation &&
1785       !SSL_get_secure_renegotiation_support(ssl)) {
1786     fprintf(stderr, "No secure renegotiation for connection when expected\n");
1787     return false;
1788   }
1789 
1790   if (config->expect_no_secure_renegotiation &&
1791       SSL_get_secure_renegotiation_support(ssl)) {
1792     fprintf(stderr,
1793             "Secure renegotiation unexpectedly negotiated for connection\n");
1794     return false;
1795   }
1796 
1797   if (config->expect_peer_signature_algorithm != 0 &&
1798       config->expect_peer_signature_algorithm !=
1799           SSL_get_peer_signature_algorithm(ssl)) {
1800     fprintf(stderr, "Peer signature algorithm was %04x, wanted %04x.\n",
1801             SSL_get_peer_signature_algorithm(ssl),
1802             config->expect_peer_signature_algorithm);
1803     return false;
1804   }
1805 
1806   if (config->expect_curve_id != 0) {
1807     uint16_t curve_id = SSL_get_curve_id(ssl);
1808     if (static_cast<uint16_t>(config->expect_curve_id) != curve_id) {
1809       fprintf(stderr, "curve_id was %04x, wanted %04x\n", curve_id,
1810               static_cast<uint16_t>(config->expect_curve_id));
1811       return false;
1812     }
1813   }
1814 
1815   uint16_t cipher_id =
1816       static_cast<uint16_t>(SSL_CIPHER_get_id(SSL_get_current_cipher(ssl)));
1817   if (config->expect_cipher_aes != 0 &&
1818       EVP_has_aes_hardware() &&
1819       static_cast<uint16_t>(config->expect_cipher_aes) != cipher_id) {
1820     fprintf(stderr, "Cipher ID was %04x, wanted %04x (has AES hardware)\n",
1821             cipher_id, static_cast<uint16_t>(config->expect_cipher_aes));
1822     return false;
1823   }
1824 
1825   if (config->expect_cipher_no_aes != 0 &&
1826       !EVP_has_aes_hardware() &&
1827       static_cast<uint16_t>(config->expect_cipher_no_aes) != cipher_id) {
1828     fprintf(stderr, "Cipher ID was %04x, wanted %04x (no AES hardware)\n",
1829             cipher_id, static_cast<uint16_t>(config->expect_cipher_no_aes));
1830     return false;
1831   }
1832 
1833   if (is_resume && !SSL_in_early_data(ssl)) {
1834     if ((config->expect_accept_early_data && !SSL_early_data_accepted(ssl)) ||
1835         (config->expect_reject_early_data && SSL_early_data_accepted(ssl))) {
1836       fprintf(stderr,
1837               "Early data was%s accepted, but we expected the opposite\n",
1838               SSL_early_data_accepted(ssl) ? "" : " not");
1839       return false;
1840     }
1841   }
1842 
1843   if (!config->psk.empty()) {
1844     if (SSL_get_peer_cert_chain(ssl) != nullptr) {
1845       fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
1846       return false;
1847     }
1848   } else if (!config->is_server || config->require_any_client_certificate) {
1849     if (SSL_get_peer_cert_chain(ssl) == nullptr) {
1850       fprintf(stderr, "Received no peer certificate but expected one.\n");
1851       return false;
1852     }
1853   }
1854 
1855   if (is_resume && config->expect_ticket_age_skew != 0 &&
1856       SSL_get_ticket_age_skew(ssl) != config->expect_ticket_age_skew) {
1857     fprintf(stderr, "Ticket age skew was %" PRId32 ", wanted %d\n",
1858             SSL_get_ticket_age_skew(ssl), config->expect_ticket_age_skew);
1859     return false;
1860   }
1861 
1862   if (config->expect_draft_downgrade != !!SSL_is_draft_downgrade(ssl)) {
1863     fprintf(stderr, "Got %sdraft downgrade signal, but wanted the opposite.\n",
1864             SSL_is_draft_downgrade(ssl) ? "" : "no ");
1865   }
1866 
1867   return true;
1868 }
1869 
WriteSettings(int i,const TestConfig * config,const SSL_SESSION * session)1870 static bool WriteSettings(int i, const TestConfig *config,
1871                           const SSL_SESSION *session) {
1872   if (config->write_settings.empty()) {
1873     return true;
1874   }
1875 
1876   // Treat write_settings as a path prefix for each connection in the run.
1877   char buf[DECIMAL_SIZE(int)];
1878   snprintf(buf, sizeof(buf), "%d", i);
1879   std::string path = config->write_settings + buf;
1880 
1881   bssl::ScopedCBB cbb;
1882   if (!CBB_init(cbb.get(), 64)) {
1883     return false;
1884   }
1885 
1886   if (session != nullptr) {
1887     uint8_t *data;
1888     size_t len;
1889     if (!SSL_SESSION_to_bytes(session, &data, &len)) {
1890       return false;
1891     }
1892     bssl::UniquePtr<uint8_t> free_data(data);
1893     CBB child;
1894     if (!CBB_add_u16(cbb.get(), kSessionTag) ||
1895         !CBB_add_u24_length_prefixed(cbb.get(), &child) ||
1896         !CBB_add_bytes(&child, data, len) ||
1897         !CBB_flush(cbb.get())) {
1898       return false;
1899     }
1900   }
1901 
1902   if (config->is_server &&
1903       (config->require_any_client_certificate || config->verify_peer) &&
1904       !CBB_add_u16(cbb.get(), kRequestClientCert)) {
1905     return false;
1906   }
1907 
1908   if (config->tls13_variant != 0 &&
1909       (!CBB_add_u16(cbb.get(), kTLS13Variant) ||
1910        !CBB_add_u8(cbb.get(), static_cast<uint8_t>(config->tls13_variant)))) {
1911     return false;
1912   }
1913 
1914   uint8_t *settings;
1915   size_t settings_len;
1916   if (!CBB_add_u16(cbb.get(), kDataTag) ||
1917       !CBB_finish(cbb.get(), &settings, &settings_len)) {
1918     return false;
1919   }
1920   bssl::UniquePtr<uint8_t> free_settings(settings);
1921 
1922   using ScopedFILE = std::unique_ptr<FILE, decltype(&fclose)>;
1923   ScopedFILE file(fopen(path.c_str(), "w"), fclose);
1924   if (!file) {
1925     return false;
1926   }
1927 
1928   return fwrite(settings, settings_len, 1, file.get()) == 1;
1929 }
1930 
1931 static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
1932                        bssl::UniquePtr<SSL> *ssl_uniqueptr,
1933                        const TestConfig *config, bool is_resume, bool is_retry);
1934 
1935 // DoConnection tests an SSL connection against the peer. On success, it returns
1936 // true and sets |*out_session| to the negotiated SSL session. If the test is a
1937 // resumption attempt, |is_resume| is true and |session| is the session from the
1938 // previous exchange.
DoConnection(bssl::UniquePtr<SSL_SESSION> * out_session,SSL_CTX * ssl_ctx,const TestConfig * config,const TestConfig * retry_config,bool is_resume,SSL_SESSION * session)1939 static bool DoConnection(bssl::UniquePtr<SSL_SESSION> *out_session,
1940                          SSL_CTX *ssl_ctx, const TestConfig *config,
1941                          const TestConfig *retry_config, bool is_resume,
1942                          SSL_SESSION *session) {
1943   bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
1944   if (!ssl) {
1945     return false;
1946   }
1947 
1948   if (!SetTestConfig(ssl.get(), config) ||
1949       !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
1950     return false;
1951   }
1952 
1953   GetTestState(ssl.get())->is_resume = is_resume;
1954 
1955   if (config->fallback_scsv &&
1956       !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
1957     return false;
1958   }
1959   // Install the certificate synchronously if nothing else will handle it.
1960   if (!config->use_early_callback &&
1961       !config->use_old_client_cert_callback &&
1962       !config->async &&
1963       !InstallCertificate(ssl.get())) {
1964     return false;
1965   }
1966   if (!config->use_old_client_cert_callback) {
1967     SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
1968   }
1969   int mode = SSL_VERIFY_NONE;
1970   if (config->require_any_client_certificate) {
1971     mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1972   }
1973   if (config->verify_peer) {
1974     mode = SSL_VERIFY_PEER;
1975   }
1976   if (config->verify_peer_if_no_obc) {
1977     // Set SSL_VERIFY_FAIL_IF_NO_PEER_CERT so testing whether client
1978     // certificates were requested is easy.
1979     mode = SSL_VERIFY_PEER | SSL_VERIFY_PEER_IF_NO_OBC |
1980            SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1981   }
1982   if (config->use_custom_verify_callback) {
1983     SSL_set_custom_verify(ssl.get(), mode, CustomVerifyCallback);
1984   } else if (mode != SSL_VERIFY_NONE) {
1985     SSL_set_verify(ssl.get(), mode, NULL);
1986   }
1987   if (config->false_start) {
1988     SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
1989   }
1990   if (config->cbc_record_splitting) {
1991     SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
1992   }
1993   if (config->partial_write) {
1994     SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
1995   }
1996   if (config->no_tls13) {
1997     SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
1998   }
1999   if (config->no_tls12) {
2000     SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
2001   }
2002   if (config->no_tls11) {
2003     SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
2004   }
2005   if (config->no_tls1) {
2006     SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
2007   }
2008   if (config->no_ssl3) {
2009     SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
2010   }
2011   if (!config->expected_channel_id.empty() ||
2012       config->enable_channel_id) {
2013     SSL_set_tls_channel_id_enabled(ssl.get(), 1);
2014   }
2015   if (!config->send_channel_id.empty()) {
2016     SSL_set_tls_channel_id_enabled(ssl.get(), 1);
2017     if (!config->async) {
2018       // The async case will be supplied by |ChannelIdCallback|.
2019       bssl::UniquePtr<EVP_PKEY> pkey = LoadPrivateKey(config->send_channel_id);
2020       if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
2021         return false;
2022       }
2023     }
2024   }
2025   if (!config->send_token_binding_params.empty()) {
2026     SSL_set_token_binding_params(ssl.get(),
2027                                  reinterpret_cast<const uint8_t *>(
2028                                      config->send_token_binding_params.data()),
2029                                  config->send_token_binding_params.length());
2030   }
2031   if (!config->host_name.empty() &&
2032       !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
2033     return false;
2034   }
2035   if (!config->advertise_alpn.empty() &&
2036       SSL_set_alpn_protos(ssl.get(),
2037                           (const uint8_t *)config->advertise_alpn.data(),
2038                           config->advertise_alpn.size()) != 0) {
2039     return false;
2040   }
2041   if (!config->psk.empty()) {
2042     SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
2043     SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
2044   }
2045   if (!config->psk_identity.empty() &&
2046       !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
2047     return false;
2048   }
2049   if (!config->srtp_profiles.empty() &&
2050       !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
2051     return false;
2052   }
2053   if (config->enable_ocsp_stapling) {
2054     SSL_enable_ocsp_stapling(ssl.get());
2055   }
2056   if (config->enable_signed_cert_timestamps) {
2057     SSL_enable_signed_cert_timestamps(ssl.get());
2058   }
2059   if (config->min_version != 0 &&
2060       !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) {
2061     return false;
2062   }
2063   if (config->max_version != 0 &&
2064       !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) {
2065     return false;
2066   }
2067   if (config->mtu != 0) {
2068     SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
2069     SSL_set_mtu(ssl.get(), config->mtu);
2070   }
2071   if (config->install_ddos_callback) {
2072     SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
2073   }
2074   if (config->renegotiate_once) {
2075     SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_once);
2076   }
2077   if (config->renegotiate_freely) {
2078     SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
2079   }
2080   if (config->renegotiate_ignore) {
2081     SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_ignore);
2082   }
2083   if (!config->check_close_notify) {
2084     SSL_set_quiet_shutdown(ssl.get(), 1);
2085   }
2086   if (config->p384_only) {
2087     int nid = NID_secp384r1;
2088     if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
2089       return false;
2090     }
2091   }
2092   if (config->enable_all_curves) {
2093     static const int kAllCurves[] = {
2094         NID_secp224r1, NID_X9_62_prime256v1, NID_secp384r1,
2095         NID_secp521r1, NID_X25519,
2096     };
2097     if (!SSL_set1_curves(ssl.get(), kAllCurves,
2098                          OPENSSL_ARRAY_SIZE(kAllCurves))) {
2099       return false;
2100     }
2101   }
2102   if (config->initial_timeout_duration_ms > 0) {
2103     DTLSv1_set_initial_timeout_duration(ssl.get(),
2104                                         config->initial_timeout_duration_ms);
2105   }
2106   if (config->max_cert_list > 0) {
2107     SSL_set_max_cert_list(ssl.get(), config->max_cert_list);
2108   }
2109   if (config->retain_only_sha256_client_cert) {
2110     SSL_set_retain_only_sha256_of_client_certs(ssl.get(), 1);
2111   }
2112   if (config->max_send_fragment > 0) {
2113     SSL_set_max_send_fragment(ssl.get(), config->max_send_fragment);
2114   }
2115   if (config->dummy_pq_padding_len > 0 &&
2116       !SSL_set_dummy_pq_padding_size(ssl.get(), config->dummy_pq_padding_len)) {
2117     return false;
2118   }
2119   if (!config->quic_transport_params.empty()) {
2120     if (!SSL_set_quic_transport_params(
2121             ssl.get(),
2122             reinterpret_cast<const uint8_t *>(
2123                 config->quic_transport_params.data()),
2124             config->quic_transport_params.size())) {
2125       return false;
2126     }
2127   }
2128 
2129   int sock = Connect(config->port);
2130   if (sock == -1) {
2131     return false;
2132   }
2133   SocketCloser closer(sock);
2134 
2135   bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
2136   if (!bio) {
2137     return false;
2138   }
2139   if (config->is_dtls) {
2140     bssl::UniquePtr<BIO> packeted = PacketedBioCreate(&g_clock);
2141     if (!packeted) {
2142       return false;
2143     }
2144     GetTestState(ssl.get())->packeted_bio = packeted.get();
2145     BIO_push(packeted.get(), bio.release());
2146     bio = std::move(packeted);
2147   }
2148   if (config->async) {
2149     bssl::UniquePtr<BIO> async_scoped =
2150         config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
2151     if (!async_scoped) {
2152       return false;
2153     }
2154     BIO_push(async_scoped.get(), bio.release());
2155     GetTestState(ssl.get())->async_bio = async_scoped.get();
2156     bio = std::move(async_scoped);
2157   }
2158   SSL_set_bio(ssl.get(), bio.get(), bio.get());
2159   bio.release();  // SSL_set_bio takes ownership.
2160 
2161   if (session != NULL) {
2162     if (!config->is_server) {
2163       if (SSL_set_session(ssl.get(), session) != 1) {
2164         return false;
2165       }
2166     } else if (config->async) {
2167       // The internal session cache is disabled, so install the session
2168       // manually.
2169       SSL_SESSION_up_ref(session);
2170       GetTestState(ssl.get())->pending_session.reset(session);
2171     }
2172   }
2173 
2174   if (SSL_get_current_cipher(ssl.get()) != nullptr) {
2175     fprintf(stderr, "non-null cipher before handshake\n");
2176     return false;
2177   }
2178 
2179   if (config->is_server) {
2180     SSL_set_accept_state(ssl.get());
2181   } else {
2182     SSL_set_connect_state(ssl.get());
2183   }
2184 
2185   bool ret = DoExchange(out_session, &ssl, config, is_resume, false);
2186   if (!config->is_server && is_resume && config->expect_reject_early_data) {
2187     // We must have failed due to an early data rejection.
2188     if (ret) {
2189       fprintf(stderr, "0-RTT exchange unexpected succeeded.\n");
2190       return false;
2191     }
2192     if (SSL_get_error(ssl.get(), -1) != SSL_ERROR_EARLY_DATA_REJECTED) {
2193       fprintf(stderr,
2194               "SSL_get_error did not signal SSL_ERROR_EARLY_DATA_REJECTED.\n");
2195       return false;
2196     }
2197 
2198     // Before reseting, early state should still be available.
2199     if (!SSL_in_early_data(ssl.get()) ||
2200         !CheckHandshakeProperties(ssl.get(), is_resume, config)) {
2201       fprintf(stderr, "SSL_in_early_data returned false before reset.\n");
2202       return false;
2203     }
2204 
2205     // Reset the connection and try again at 1-RTT.
2206     SSL_reset_early_data_reject(ssl.get());
2207 
2208     // After reseting, the socket should report it is no longer in an early data
2209     // state.
2210     if (SSL_in_early_data(ssl.get())) {
2211       fprintf(stderr, "SSL_in_early_data returned true after reset.\n");
2212       return false;
2213     }
2214 
2215     if (!SetTestConfig(ssl.get(), retry_config)) {
2216       return false;
2217     }
2218 
2219     assert(!config->handoff);
2220     ret = DoExchange(out_session, &ssl, retry_config, is_resume, true);
2221   }
2222 
2223   if (!ret) {
2224     return false;
2225   }
2226 
2227   if (!GetTestState(ssl.get())->msg_callback_ok) {
2228     return false;
2229   }
2230 
2231   if (!config->expect_msg_callback.empty() &&
2232       GetTestState(ssl.get())->msg_callback_text !=
2233           config->expect_msg_callback) {
2234     fprintf(stderr, "Bad message callback trace. Wanted:\n%s\nGot:\n%s\n",
2235             config->expect_msg_callback.c_str(),
2236             GetTestState(ssl.get())->msg_callback_text.c_str());
2237     return false;
2238   }
2239 
2240   return true;
2241 }
2242 
HandoffReady(SSL * ssl,int ret)2243 static bool HandoffReady(SSL *ssl, int ret) {
2244   return ret < 0 && SSL_get_error(ssl, ret) == SSL_ERROR_HANDOFF;
2245 }
2246 
DoExchange(bssl::UniquePtr<SSL_SESSION> * out_session,bssl::UniquePtr<SSL> * ssl_uniqueptr,const TestConfig * config,bool is_resume,bool is_retry)2247 static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
2248                        bssl::UniquePtr<SSL> *ssl_uniqueptr,
2249                        const TestConfig *config, bool is_resume,
2250                        bool is_retry) {
2251   int ret;
2252   SSL *ssl = ssl_uniqueptr->get();
2253 
2254   if (!config->implicit_handshake) {
2255     if (config->handoff) {
2256       bssl::UniquePtr<SSL_CTX> ctx_handoff(SSL_CTX_new(TLSv1_method()));
2257       if (!ctx_handoff) {
2258         return false;
2259       }
2260       SSL_CTX_set_handoff_mode(ctx_handoff.get(), 1);
2261 
2262       bssl::UniquePtr<SSL> ssl_handoff(SSL_new(ctx_handoff.get()));
2263       if (!ssl_handoff) {
2264         return false;
2265       }
2266       SSL_set_accept_state(ssl_handoff.get());
2267       if (!MoveExData(ssl_handoff.get(), ssl)) {
2268         return false;
2269       }
2270       MoveBIOs(ssl_handoff.get(), ssl);
2271 
2272       do {
2273         ret = CheckIdempotentError("SSL_do_handshake", ssl_handoff.get(),
2274                                    [&]() -> int {
2275           return SSL_do_handshake(ssl_handoff.get());
2276         });
2277       } while (!HandoffReady(ssl_handoff.get(), ret) &&
2278                config->async &&
2279                RetryAsync(ssl_handoff.get(), ret));
2280 
2281       if (!HandoffReady(ssl_handoff.get(), ret)) {
2282         fprintf(stderr, "Handshake failed while waiting for handoff.\n");
2283         return false;
2284       }
2285 
2286       bssl::ScopedCBB cbb;
2287       bssl::Array<uint8_t> handoff;
2288       if (!CBB_init(cbb.get(), 512) ||
2289           !SSL_serialize_handoff(ssl_handoff.get(), cbb.get()) ||
2290           !CBBFinishArray(cbb.get(), &handoff)) {
2291         fprintf(stderr, "Handoff serialisation failed.\n");
2292         return false;
2293       }
2294 
2295       MoveBIOs(ssl, ssl_handoff.get());
2296       if (!MoveExData(ssl, ssl_handoff.get())) {
2297         return false;
2298       }
2299 
2300       if (!SSL_apply_handoff(ssl, handoff)) {
2301         fprintf(stderr, "Handoff application failed.\n");
2302         return false;
2303       }
2304     }
2305 
2306     do {
2307       ret = CheckIdempotentError("SSL_do_handshake", ssl, [&]() -> int {
2308         return SSL_do_handshake(ssl);
2309       });
2310     } while (config->async && RetryAsync(ssl, ret));
2311 
2312     if (ret != 1 ||
2313         !CheckHandshakeProperties(ssl, is_resume, config)) {
2314       return false;
2315     }
2316 
2317     if (config->handoff) {
2318       bssl::ScopedCBB cbb;
2319       bssl::Array<uint8_t> handback;
2320       if (!CBB_init(cbb.get(), 512) ||
2321           !SSL_serialize_handback(ssl, cbb.get()) ||
2322           !CBBFinishArray(cbb.get(), &handback)) {
2323         fprintf(stderr, "Handback serialisation failed.\n");
2324         return false;
2325       }
2326 
2327       bssl::UniquePtr<SSL_CTX> ctx_handback(SSL_CTX_new(TLSv1_method()));
2328       SSL_CTX_set_msg_callback(ctx_handback.get(), MessageCallback);
2329       bssl::UniquePtr<SSL> ssl_handback(SSL_new(ctx_handback.get()));
2330       if (!ssl_handback) {
2331         return false;
2332       }
2333       if (!SSL_apply_handback(ssl_handback.get(), handback)) {
2334         fprintf(stderr, "Applying handback failed.\n");
2335         return false;
2336       }
2337 
2338       MoveBIOs(ssl_handback.get(), ssl);
2339       if (!MoveExData(ssl_handback.get(), ssl)) {
2340         return false;
2341       }
2342 
2343       *ssl_uniqueptr = std::move(ssl_handback);
2344       ssl = ssl_uniqueptr->get();
2345     }
2346 
2347     if (is_resume && !is_retry && !config->is_server &&
2348         config->expect_no_offer_early_data && SSL_in_early_data(ssl)) {
2349       fprintf(stderr, "Client unexpectedly offered early data.\n");
2350       return false;
2351     }
2352 
2353     if (config->handshake_twice) {
2354       do {
2355         ret = SSL_do_handshake(ssl);
2356       } while (config->async && RetryAsync(ssl, ret));
2357       if (ret != 1) {
2358         return false;
2359       }
2360     }
2361 
2362     // Skip the |config->async| logic as this should be a no-op.
2363     if (config->no_op_extra_handshake &&
2364         SSL_do_handshake(ssl) != 1) {
2365       fprintf(stderr, "Extra SSL_do_handshake was not a no-op.\n");
2366       return false;
2367     }
2368 
2369     // Reset the state to assert later that the callback isn't called in
2370     // renegotations.
2371     GetTestState(ssl)->got_new_session = false;
2372   }
2373 
2374   if (config->export_early_keying_material > 0) {
2375     std::vector<uint8_t> result(
2376         static_cast<size_t>(config->export_early_keying_material));
2377     if (!SSL_export_early_keying_material(
2378             ssl, result.data(), result.size(), config->export_label.data(),
2379             config->export_label.size(),
2380             reinterpret_cast<const uint8_t *>(config->export_context.data()),
2381             config->export_context.size())) {
2382       fprintf(stderr, "failed to export keying material\n");
2383       return false;
2384     }
2385     if (WriteAll(ssl, result.data(), result.size()) < 0) {
2386       return false;
2387     }
2388   }
2389 
2390   if (config->export_keying_material > 0) {
2391     std::vector<uint8_t> result(
2392         static_cast<size_t>(config->export_keying_material));
2393     if (!SSL_export_keying_material(
2394             ssl, result.data(), result.size(), config->export_label.data(),
2395             config->export_label.size(),
2396             reinterpret_cast<const uint8_t *>(config->export_context.data()),
2397             config->export_context.size(), config->use_export_context)) {
2398       fprintf(stderr, "failed to export keying material\n");
2399       return false;
2400     }
2401     if (WriteAll(ssl, result.data(), result.size()) < 0) {
2402       return false;
2403     }
2404   }
2405 
2406   if (config->tls_unique) {
2407     uint8_t tls_unique[16];
2408     size_t tls_unique_len;
2409     if (!SSL_get_tls_unique(ssl, tls_unique, &tls_unique_len,
2410                             sizeof(tls_unique))) {
2411       fprintf(stderr, "failed to get tls-unique\n");
2412       return false;
2413     }
2414 
2415     if (tls_unique_len != 12) {
2416       fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
2417               static_cast<unsigned>(tls_unique_len));
2418       return false;
2419     }
2420 
2421     if (WriteAll(ssl, tls_unique, tls_unique_len) < 0) {
2422       return false;
2423     }
2424   }
2425 
2426   if (config->send_alert) {
2427     if (DoSendFatalAlert(ssl, SSL_AD_DECOMPRESSION_FAILURE) < 0) {
2428       return false;
2429     }
2430     return true;
2431   }
2432 
2433   if (config->write_different_record_sizes) {
2434     if (config->is_dtls) {
2435       fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
2436       return false;
2437     }
2438     // This mode writes a number of different record sizes in an attempt to
2439     // trip up the CBC record splitting code.
2440     static const size_t kBufLen = 32769;
2441     std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
2442     OPENSSL_memset(buf.get(), 0x42, kBufLen);
2443     static const size_t kRecordSizes[] = {
2444         0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
2445     for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
2446       const size_t len = kRecordSizes[i];
2447       if (len > kBufLen) {
2448         fprintf(stderr, "Bad kRecordSizes value.\n");
2449         return false;
2450       }
2451       if (WriteAll(ssl, buf.get(), len) < 0) {
2452         return false;
2453       }
2454     }
2455   } else {
2456     static const char kInitialWrite[] = "hello";
2457     bool pending_initial_write = false;
2458     if (config->read_with_unfinished_write) {
2459       if (!config->async) {
2460         fprintf(stderr, "-read-with-unfinished-write requires -async.\n");
2461         return false;
2462       }
2463 
2464       // Let only one byte of the record through.
2465       AsyncBioAllowWrite(GetTestState(ssl)->async_bio, 1);
2466       int write_ret =
2467           SSL_write(ssl, kInitialWrite, strlen(kInitialWrite));
2468       if (SSL_get_error(ssl, write_ret) != SSL_ERROR_WANT_WRITE) {
2469         fprintf(stderr, "Failed to leave unfinished write.\n");
2470         return false;
2471       }
2472       pending_initial_write = true;
2473     } else if (config->shim_writes_first) {
2474       if (WriteAll(ssl, kInitialWrite, strlen(kInitialWrite)) < 0) {
2475         return false;
2476       }
2477     }
2478     if (!config->shim_shuts_down) {
2479       for (;;) {
2480         // Read only 512 bytes at a time in TLS to ensure records may be
2481         // returned in multiple reads.
2482         size_t read_size = config->is_dtls ? 16384 : 512;
2483         if (config->read_size > 0) {
2484           read_size = config->read_size;
2485         }
2486         std::unique_ptr<uint8_t[]> buf(new uint8_t[read_size]);
2487 
2488         int n = DoRead(ssl, buf.get(), read_size);
2489         int err = SSL_get_error(ssl, n);
2490         if (err == SSL_ERROR_ZERO_RETURN ||
2491             (n == 0 && err == SSL_ERROR_SYSCALL)) {
2492           if (n != 0) {
2493             fprintf(stderr, "Invalid SSL_get_error output\n");
2494             return false;
2495           }
2496           // Stop on either clean or unclean shutdown.
2497           break;
2498         } else if (err != SSL_ERROR_NONE) {
2499           if (n > 0) {
2500             fprintf(stderr, "Invalid SSL_get_error output\n");
2501             return false;
2502           }
2503           return false;
2504         }
2505         // Successfully read data.
2506         if (n <= 0) {
2507           fprintf(stderr, "Invalid SSL_get_error output\n");
2508           return false;
2509         }
2510 
2511         if (!config->is_server && is_resume && !is_retry &&
2512             config->expect_reject_early_data) {
2513           fprintf(stderr,
2514                   "Unexpectedly received data instead of 0-RTT reject.\n");
2515           return false;
2516         }
2517 
2518         // After a successful read, with or without False Start, the handshake
2519         // must be complete unless we are doing early data.
2520         if (!GetTestState(ssl)->handshake_done &&
2521             !SSL_early_data_accepted(ssl)) {
2522           fprintf(stderr, "handshake was not completed after SSL_read\n");
2523           return false;
2524         }
2525 
2526         // Clear the initial write, if unfinished.
2527         if (pending_initial_write) {
2528           if (WriteAll(ssl, kInitialWrite, strlen(kInitialWrite)) < 0) {
2529             return false;
2530           }
2531           pending_initial_write = false;
2532         }
2533 
2534         for (int i = 0; i < n; i++) {
2535           buf[i] ^= 0xff;
2536         }
2537         if (WriteAll(ssl, buf.get(), n) < 0) {
2538           return false;
2539         }
2540       }
2541     }
2542   }
2543 
2544   if (!config->is_server && !config->false_start &&
2545       !config->implicit_handshake &&
2546       // Session tickets are sent post-handshake in TLS 1.3.
2547       GetProtocolVersion(ssl) < TLS1_3_VERSION &&
2548       GetTestState(ssl)->got_new_session) {
2549     fprintf(stderr, "new session was established after the handshake\n");
2550     return false;
2551   }
2552 
2553   if (GetProtocolVersion(ssl) >= TLS1_3_VERSION && !config->is_server) {
2554     bool expect_new_session =
2555         !config->expect_no_session && !config->shim_shuts_down;
2556     if (expect_new_session != GetTestState(ssl)->got_new_session) {
2557       fprintf(stderr,
2558               "new session was%s cached, but we expected the opposite\n",
2559               GetTestState(ssl)->got_new_session ? "" : " not");
2560       return false;
2561     }
2562 
2563     if (expect_new_session) {
2564       bool got_early_data =
2565           GetTestState(ssl)->new_session->ticket_max_early_data != 0;
2566       if (config->expect_ticket_supports_early_data != got_early_data) {
2567         fprintf(stderr,
2568                 "new session did%s support early data, but we expected the "
2569                 "opposite\n",
2570                 got_early_data ? "" : " not");
2571         return false;
2572       }
2573     }
2574   }
2575 
2576   if (out_session) {
2577     *out_session = std::move(GetTestState(ssl)->new_session);
2578   }
2579 
2580   ret = DoShutdown(ssl);
2581 
2582   if (config->shim_shuts_down && config->check_close_notify) {
2583     // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
2584     // it returns zero when our close_notify is sent, then one when the peer's
2585     // is received.
2586     if (ret != 0) {
2587       fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
2588       return false;
2589     }
2590     ret = DoShutdown(ssl);
2591   }
2592 
2593   if (ret != 1) {
2594     fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
2595     return false;
2596   }
2597 
2598   if (SSL_total_renegotiations(ssl) > 0) {
2599     if (!SSL_get_session(ssl)->not_resumable) {
2600       fprintf(stderr,
2601               "Renegotiations should never produce resumable sessions.\n");
2602       return false;
2603     }
2604 
2605     if (SSL_session_reused(ssl)) {
2606       fprintf(stderr, "Renegotiations should never resume sessions.\n");
2607       return false;
2608     }
2609 
2610     // Re-check authentication properties after a renegotiation. The reported
2611     // values should remain unchanged even if the server sent different SCT
2612     // lists.
2613     if (!CheckAuthProperties(ssl, is_resume, config)) {
2614       return false;
2615     }
2616   }
2617 
2618   if (SSL_total_renegotiations(ssl) != config->expect_total_renegotiations) {
2619     fprintf(stderr, "Expected %d renegotiations, got %d\n",
2620             config->expect_total_renegotiations, SSL_total_renegotiations(ssl));
2621     return false;
2622   }
2623 
2624   return true;
2625 }
2626 
2627 class StderrDelimiter {
2628  public:
~StderrDelimiter()2629   ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
2630 };
2631 
main(int argc,char ** argv)2632 int main(int argc, char **argv) {
2633   // To distinguish ASan's output from ours, add a trailing message to stderr.
2634   // Anything following this line will be considered an error.
2635   StderrDelimiter delimiter;
2636 
2637 #if defined(OPENSSL_WINDOWS)
2638   // Initialize Winsock.
2639   WORD wsa_version = MAKEWORD(2, 2);
2640   WSADATA wsa_data;
2641   int wsa_err = WSAStartup(wsa_version, &wsa_data);
2642   if (wsa_err != 0) {
2643     fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
2644     return 1;
2645   }
2646   if (wsa_data.wVersion != wsa_version) {
2647     fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
2648     return 1;
2649   }
2650 #else
2651   signal(SIGPIPE, SIG_IGN);
2652 #endif
2653 
2654   CRYPTO_library_init();
2655   g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
2656   g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
2657   if (g_config_index < 0 || g_state_index < 0) {
2658     return 1;
2659   }
2660 
2661   TestConfig initial_config, resume_config, retry_config;
2662   if (!ParseConfig(argc - 1, argv + 1, &initial_config, &resume_config,
2663                    &retry_config)) {
2664     return Usage(argv[0]);
2665   }
2666 
2667   g_pool = CRYPTO_BUFFER_POOL_new();
2668 
2669   // Some code treats the zero time special, so initialize the clock to a
2670   // non-zero time.
2671   g_clock.tv_sec = 1234;
2672   g_clock.tv_usec = 1234;
2673 
2674   bssl::UniquePtr<SSL_CTX> ssl_ctx;
2675 
2676   bssl::UniquePtr<SSL_SESSION> session;
2677   for (int i = 0; i < initial_config.resume_count + 1; i++) {
2678     bool is_resume = i > 0;
2679     TestConfig *config = is_resume ? &resume_config : &initial_config;
2680     ssl_ctx = SetupCtx(ssl_ctx.get(), config);
2681     if (!ssl_ctx) {
2682       ERR_print_errors_fp(stderr);
2683       return 1;
2684     }
2685 
2686     if (is_resume && !initial_config.is_server && !session) {
2687       fprintf(stderr, "No session to offer.\n");
2688       return 1;
2689     }
2690 
2691     bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
2692     if (!WriteSettings(i, config, offer_session.get())) {
2693       fprintf(stderr, "Error writing settings.\n");
2694       return 1;
2695     }
2696     if (!DoConnection(&session, ssl_ctx.get(), config, &retry_config, is_resume,
2697                       offer_session.get())) {
2698       fprintf(stderr, "Connection %d failed.\n", i + 1);
2699       ERR_print_errors_fp(stderr);
2700       return 1;
2701     }
2702 
2703     if (config->resumption_delay != 0) {
2704       g_clock.tv_sec += config->resumption_delay;
2705     }
2706   }
2707 
2708   return 0;
2709 }
2710