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