Fix some unused variable warnings in ossl_shim
[openssl.git] / test / ossl_shim / ossl_shim.cc
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/e_os2.h>
20
21 #if !defined(OPENSSL_SYS_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
43 #include <openssl/bio.h>
44 #include <openssl/buffer.h>
45 #include <openssl/crypto.h>
46 #include <openssl/dh.h>
47 #include <openssl/err.h>
48 #include <openssl/evp.h>
49 #include <openssl/hmac.h>
50 #include <openssl/objects.h>
51 #include <openssl/rand.h>
52 #include <openssl/ssl.h>
53 #include <openssl/x509.h>
54
55 #include <memory>
56 #include <string>
57 #include <vector>
58
59 #include "async_bio.h"
60 #include "packeted_bio.h"
61 #include "test_config.h"
62
63 namespace bssl {
64
65 #if !defined(OPENSSL_SYS_WINDOWS)
66 static int closesocket(int sock) {
67   return close(sock);
68 }
69
70 static void PrintSocketError(const char *func) {
71   perror(func);
72 }
73 #else
74 static void PrintSocketError(const char *func) {
75   fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
76 }
77 #endif
78
79 static int Usage(const char *program) {
80   fprintf(stderr, "Usage: %s [flags...]\n", program);
81   return 1;
82 }
83
84 struct TestState {
85   // async_bio is async BIO which pauses reads and writes.
86   BIO *async_bio = nullptr;
87   // packeted_bio is the packeted BIO which simulates read timeouts.
88   BIO *packeted_bio = nullptr;
89   bssl::UniquePtr<EVP_PKEY> channel_id;
90   bool cert_ready = false;
91   bssl::UniquePtr<SSL_SESSION> session;
92   bssl::UniquePtr<SSL_SESSION> pending_session;
93   bool early_callback_called = false;
94   bool handshake_done = false;
95   // private_key is the underlying private key used when testing custom keys.
96   bssl::UniquePtr<EVP_PKEY> private_key;
97   std::vector<uint8_t> private_key_result;
98   // private_key_retries is the number of times an asynchronous private key
99   // operation has been retried.
100   unsigned private_key_retries = 0;
101   bool got_new_session = false;
102   bssl::UniquePtr<SSL_SESSION> new_session;
103   bool ticket_decrypt_done = false;
104   bool alpn_select_done = false;
105 };
106
107 static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
108                             int index, long argl, void *argp) {
109   delete ((TestState *)ptr);
110 }
111
112 static int g_config_index = 0;
113 static int g_state_index = 0;
114
115 static bool SetTestConfig(SSL *ssl, const TestConfig *config) {
116   return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
117 }
118
119 static const TestConfig *GetTestConfig(const SSL *ssl) {
120   return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
121 }
122
123 static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
124   // |SSL_set_ex_data| takes ownership of |state| only on success.
125   if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
126     state.release();
127     return true;
128   }
129   return false;
130 }
131
132 static TestState *GetTestState(const SSL *ssl) {
133   return (TestState *)SSL_get_ex_data(ssl, g_state_index);
134 }
135
136 static bssl::UniquePtr<X509> LoadCertificate(const std::string &file) {
137   bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
138   if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
139     return nullptr;
140   }
141   return bssl::UniquePtr<X509>(PEM_read_bio_X509(bio.get(), NULL, NULL, NULL));
142 }
143
144 static bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
145   bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
146   if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
147     return nullptr;
148   }
149   return bssl::UniquePtr<EVP_PKEY>(
150       PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
151 }
152
153 template<typename T>
154 struct Free {
155   void operator()(T *buf) {
156     free(buf);
157   }
158 };
159
160 static bool GetCertificate(SSL *ssl, bssl::UniquePtr<X509> *out_x509,
161                            bssl::UniquePtr<EVP_PKEY> *out_pkey) {
162   const TestConfig *config = GetTestConfig(ssl);
163
164   if (!config->digest_prefs.empty()) {
165     fprintf(stderr, "Digest prefs not supported.\n");
166     return false;
167   }
168
169   if (!config->signing_prefs.empty()) {
170     fprintf(stderr, "Set signing algorithm prefs not supported\n");
171     return false;
172   }
173
174   if (!config->key_file.empty()) {
175     *out_pkey = LoadPrivateKey(config->key_file.c_str());
176     if (!*out_pkey) {
177       return false;
178     }
179   }
180   if (!config->cert_file.empty()) {
181     *out_x509 = LoadCertificate(config->cert_file.c_str());
182     if (!*out_x509) {
183       return false;
184     }
185   }
186   if (!config->ocsp_response.empty()) {
187     fprintf(stderr, "OCSP response not supported.\n");
188     return false;
189   }
190   return true;
191 }
192
193 static bool InstallCertificate(SSL *ssl) {
194   bssl::UniquePtr<X509> x509;
195   bssl::UniquePtr<EVP_PKEY> pkey;
196   if (!GetCertificate(ssl, &x509, &pkey)) {
197     return false;
198   }
199
200   if (pkey) {
201     if (!SSL_use_PrivateKey(ssl, pkey.get())) {
202       return false;
203     }
204   }
205
206   if (x509 && !SSL_use_certificate(ssl, x509.get())) {
207     return false;
208   }
209
210   return true;
211 }
212
213 static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
214   if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
215     return -1;
216   }
217
218   bssl::UniquePtr<X509> x509;
219   bssl::UniquePtr<EVP_PKEY> pkey;
220   if (!GetCertificate(ssl, &x509, &pkey)) {
221     return -1;
222   }
223
224   // Return zero for no certificate.
225   if (!x509) {
226     return 0;
227   }
228
229   // Asynchronous private keys are not supported with client_cert_cb.
230   *out_x509 = x509.release();
231   *out_pkey = pkey.release();
232   return 1;
233 }
234
235 static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
236   return 1;
237 }
238
239 static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
240   X509_STORE_CTX_set_error(store_ctx, X509_V_ERR_APPLICATION_VERIFICATION);
241   return 0;
242 }
243
244 static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
245                                         unsigned int *out_len, void *arg) {
246   const TestConfig *config = GetTestConfig(ssl);
247   if (config->advertise_npn.empty()) {
248     return SSL_TLSEXT_ERR_NOACK;
249   }
250
251   *out = (const uint8_t*)config->advertise_npn.data();
252   *out_len = config->advertise_npn.size();
253   return SSL_TLSEXT_ERR_OK;
254 }
255
256 static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
257                                    const uint8_t* in, unsigned inlen, void* arg) {
258   const TestConfig *config = GetTestConfig(ssl);
259   if (config->select_next_proto.empty()) {
260     return SSL_TLSEXT_ERR_NOACK;
261   }
262
263   *out = (uint8_t*)config->select_next_proto.data();
264   *outlen = config->select_next_proto.size();
265   return SSL_TLSEXT_ERR_OK;
266 }
267
268 static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
269                               const uint8_t* in, unsigned inlen, void* arg) {
270   if (GetTestState(ssl)->alpn_select_done) {
271     fprintf(stderr, "AlpnSelectCallback called after completion.\n");
272     exit(1);
273   }
274
275   GetTestState(ssl)->alpn_select_done = true;
276
277   const TestConfig *config = GetTestConfig(ssl);
278   if (config->decline_alpn) {
279     return SSL_TLSEXT_ERR_NOACK;
280   }
281
282   if (!config->expected_advertised_alpn.empty() &&
283       (config->expected_advertised_alpn.size() != inlen ||
284        memcmp(config->expected_advertised_alpn.data(),
285               in, inlen) != 0)) {
286     fprintf(stderr, "bad ALPN select callback inputs\n");
287     exit(1);
288   }
289
290   *out = (const uint8_t*)config->select_alpn.data();
291   *outlen = config->select_alpn.size();
292   return SSL_TLSEXT_ERR_OK;
293 }
294
295 static unsigned PskClientCallback(SSL *ssl, const char *hint,
296                                   char *out_identity,
297                                   unsigned max_identity_len,
298                                   uint8_t *out_psk, unsigned max_psk_len) {
299   const TestConfig *config = GetTestConfig(ssl);
300
301   if (config->psk_identity.empty()) {
302     if (hint != nullptr) {
303       fprintf(stderr, "Server PSK hint was non-null.\n");
304       return 0;
305     }
306   } else if (hint == nullptr ||
307              strcmp(hint, config->psk_identity.c_str()) != 0) {
308     fprintf(stderr, "Server PSK hint did not match.\n");
309     return 0;
310   }
311
312   // Account for the trailing '\0' for the identity.
313   if (config->psk_identity.size() >= max_identity_len ||
314       config->psk.size() > max_psk_len) {
315     fprintf(stderr, "PSK buffers too small\n");
316     return 0;
317   }
318
319   BUF_strlcpy(out_identity, config->psk_identity.c_str(),
320               max_identity_len);
321   memcpy(out_psk, config->psk.data(), config->psk.size());
322   return config->psk.size();
323 }
324
325 static unsigned PskServerCallback(SSL *ssl, const char *identity,
326                                   uint8_t *out_psk, unsigned max_psk_len) {
327   const TestConfig *config = GetTestConfig(ssl);
328
329   if (strcmp(identity, config->psk_identity.c_str()) != 0) {
330     fprintf(stderr, "Client PSK identity did not match.\n");
331     return 0;
332   }
333
334   if (config->psk.size() > max_psk_len) {
335     fprintf(stderr, "PSK buffers too small\n");
336     return 0;
337   }
338
339   memcpy(out_psk, config->psk.data(), config->psk.size());
340   return config->psk.size();
341 }
342
343 static int CertCallback(SSL *ssl, void *arg) {
344   const TestConfig *config = GetTestConfig(ssl);
345
346   // Check the CertificateRequest metadata is as expected.
347   //
348   // TODO(davidben): Test |SSL_get_client_CA_list|.
349   if (!SSL_is_server(ssl) &&
350       !config->expected_certificate_types.empty()) {
351     const uint8_t *certificate_types;
352     size_t certificate_types_len =
353         SSL_get0_certificate_types(ssl, &certificate_types);
354     if (certificate_types_len != config->expected_certificate_types.size() ||
355         memcmp(certificate_types,
356                config->expected_certificate_types.data(),
357                certificate_types_len) != 0) {
358       fprintf(stderr, "certificate types mismatch\n");
359       return 0;
360     }
361   }
362
363   // The certificate will be installed via other means.
364   if (!config->async || config->use_early_callback ||
365       config->use_old_client_cert_callback) {
366     return 1;
367   }
368
369   if (!GetTestState(ssl)->cert_ready) {
370     return -1;
371   }
372   if (!InstallCertificate(ssl)) {
373     return 0;
374   }
375   return 1;
376 }
377
378 static void InfoCallback(const SSL *ssl, int type, int val) {
379   if (type == SSL_CB_HANDSHAKE_DONE) {
380     if (GetTestConfig(ssl)->handshake_never_done) {
381       fprintf(stderr, "Handshake unexpectedly completed.\n");
382       // Abort before any expected error code is printed, to ensure the overall
383       // test fails.
384       abort();
385     }
386     GetTestState(ssl)->handshake_done = true;
387
388     // Callbacks may be called again on a new handshake.
389     GetTestState(ssl)->ticket_decrypt_done = false;
390     GetTestState(ssl)->alpn_select_done = false;
391   }
392 }
393
394 static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
395   GetTestState(ssl)->got_new_session = true;
396   GetTestState(ssl)->new_session.reset(session);
397   return 1;
398 }
399
400 static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
401                              EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
402                              int encrypt) {
403   if (!encrypt) {
404     if (GetTestState(ssl)->ticket_decrypt_done) {
405       fprintf(stderr, "TicketKeyCallback called after completion.\n");
406       return -1;
407     }
408
409     GetTestState(ssl)->ticket_decrypt_done = true;
410   }
411
412   // This is just test code, so use the all-zeros key.
413   static const uint8_t kZeros[16] = {0};
414
415   if (encrypt) {
416     memcpy(key_name, kZeros, sizeof(kZeros));
417     RAND_bytes(iv, 16);
418   } else if (memcmp(key_name, kZeros, 16) != 0) {
419     return 0;
420   }
421
422   if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
423       !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
424     return -1;
425   }
426
427   if (!encrypt) {
428     return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
429   }
430   return 1;
431 }
432
433 // kCustomExtensionValue is the extension value that the custom extension
434 // callbacks will add.
435 static const uint16_t kCustomExtensionValue = 1234;
436 static void *const kCustomExtensionAddArg =
437     reinterpret_cast<void *>(kCustomExtensionValue);
438 static void *const kCustomExtensionParseArg =
439     reinterpret_cast<void *>(kCustomExtensionValue + 1);
440 static const char kCustomExtensionContents[] = "custom extension";
441
442 static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
443                                       const uint8_t **out, size_t *out_len,
444                                       int *out_alert_value, void *add_arg) {
445   if (extension_value != kCustomExtensionValue ||
446       add_arg != kCustomExtensionAddArg) {
447     abort();
448   }
449
450   if (GetTestConfig(ssl)->custom_extension_skip) {
451     return 0;
452   }
453   if (GetTestConfig(ssl)->custom_extension_fail_add) {
454     return -1;
455   }
456
457   *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
458   *out_len = sizeof(kCustomExtensionContents) - 1;
459
460   return 1;
461 }
462
463 static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
464                                         const uint8_t *out, void *add_arg) {
465   if (extension_value != kCustomExtensionValue ||
466       add_arg != kCustomExtensionAddArg ||
467       out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
468     abort();
469   }
470 }
471
472 static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
473                                         const uint8_t *contents,
474                                         size_t contents_len,
475                                         int *out_alert_value, void *parse_arg) {
476   if (extension_value != kCustomExtensionValue ||
477       parse_arg != kCustomExtensionParseArg) {
478     abort();
479   }
480
481   if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
482       memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
483     *out_alert_value = SSL_AD_DECODE_ERROR;
484     return 0;
485   }
486
487   return 1;
488 }
489
490 // Connect returns a new socket connected to localhost on |port| or -1 on
491 // error.
492 static int Connect(uint16_t port) {
493   int sock = socket(AF_INET, SOCK_STREAM, 0);
494   if (sock == -1) {
495     PrintSocketError("socket");
496     return -1;
497   }
498   int nodelay = 1;
499   if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
500           reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
501     PrintSocketError("setsockopt");
502     closesocket(sock);
503     return -1;
504   }
505   sockaddr_in sin;
506   memset(&sin, 0, sizeof(sin));
507   sin.sin_family = AF_INET;
508   sin.sin_port = htons(port);
509   if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
510     PrintSocketError("inet_pton");
511     closesocket(sock);
512     return -1;
513   }
514   if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
515               sizeof(sin)) != 0) {
516     PrintSocketError("connect");
517     closesocket(sock);
518     return -1;
519   }
520   return sock;
521 }
522
523 class SocketCloser {
524  public:
525   explicit SocketCloser(int sock) : sock_(sock) {}
526   ~SocketCloser() {
527     // Half-close and drain the socket before releasing it. This seems to be
528     // necessary for graceful shutdown on Windows. It will also avoid write
529     // failures in the test runner.
530 #if defined(OPENSSL_WINDOWS)
531     shutdown(sock_, SD_SEND);
532 #else
533     shutdown(sock_, SHUT_WR);
534 #endif
535     while (true) {
536       char buf[1024];
537       if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
538         break;
539       }
540     }
541     closesocket(sock_);
542   }
543
544  private:
545   const int sock_;
546 };
547
548 static bssl::UniquePtr<SSL_CTX> SetupCtx(const TestConfig *config) {
549   bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(
550       config->is_dtls ? DTLS_method() : TLS_method()));
551   if (!ssl_ctx) {
552     return nullptr;
553   }
554
555   SSL_CTX_set_security_level(ssl_ctx.get(), 0);
556 #if 0
557   /* Disabled for now until we have some TLS1.3 support */
558   // Enable TLS 1.3 for tests.
559   if (!config->is_dtls &&
560       !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION)) {
561     return nullptr;
562   }
563 #endif
564
565   std::string cipher_list = "ALL";
566   if (!config->cipher.empty()) {
567     cipher_list = config->cipher;
568     SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
569   }
570   if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
571     return nullptr;
572   }
573
574   if (!config->cipher_tls10.empty() || !config->cipher_tls11.empty()) {
575     fprintf(stderr, "version-specific cipher lists not supported.\n");
576     return nullptr;
577   }
578
579   DH *tmpdh;
580
581   if (config->use_sparse_dh_prime) {
582     BIGNUM *p, *g;
583     p = BN_new();
584     g = BN_new();
585     tmpdh = DH_new();
586     if (p == NULL || g == NULL || tmpdh == NULL) {
587         BN_free(p);
588         BN_free(g);
589         DH_free(tmpdh);
590         return nullptr;
591     }
592     // This prime number is 2^1024 + 643 â€“ a value just above a power of two.
593     // Because of its form, values modulo it are essentially certain to be one
594     // byte shorter. This is used to test padding of these values.
595     if (BN_hex2bn(
596             &p,
597             "1000000000000000000000000000000000000000000000000000000000000000"
598             "0000000000000000000000000000000000000000000000000000000000000000"
599             "0000000000000000000000000000000000000000000000000000000000000000"
600             "0000000000000000000000000000000000000000000000000000000000000028"
601             "3") == 0 ||
602         !BN_set_word(g, 2)) {
603       BN_free(p);
604       BN_free(g);
605       DH_free(tmpdh);
606       return nullptr;
607     }
608     DH_set0_pqg(tmpdh, p, NULL, g);
609   } else {
610       tmpdh = DH_get_2048_256();
611   }
612
613   bssl::UniquePtr<DH> dh(tmpdh);
614
615   if (!dh || !SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
616     return nullptr;
617   }
618
619   SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
620
621   if (config->use_old_client_cert_callback) {
622     SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
623   }
624
625   SSL_CTX_set_next_protos_advertised_cb(
626       ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
627   if (!config->select_next_proto.empty()) {
628     SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
629                                      NULL);
630   }
631
632   if (!config->select_alpn.empty() || config->decline_alpn) {
633     SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
634   }
635
636   SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
637   SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
638
639   if (config->use_ticket_callback) {
640     SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
641   }
642
643   if (config->enable_client_custom_extension &&
644       !SSL_CTX_add_client_custom_ext(
645           ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
646           CustomExtensionFreeCallback, kCustomExtensionAddArg,
647           CustomExtensionParseCallback, kCustomExtensionParseArg)) {
648     return nullptr;
649   }
650
651   if (config->enable_server_custom_extension &&
652       !SSL_CTX_add_server_custom_ext(
653           ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
654           CustomExtensionFreeCallback, kCustomExtensionAddArg,
655           CustomExtensionParseCallback, kCustomExtensionParseArg)) {
656     return nullptr;
657   }
658
659   if (config->verify_fail) {
660     SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
661   } else {
662     SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
663   }
664
665   if (!config->signed_cert_timestamps.empty()) {
666     fprintf(stderr, "SCTs not supported.\n");
667     return nullptr;
668   }
669
670   if (config->use_null_client_ca_list) {
671     SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
672   }
673
674   return ssl_ctx;
675 }
676
677 // RetryAsync is called after a failed operation on |ssl| with return code
678 // |ret|. If the operation should be retried, it simulates one asynchronous
679 // event and returns true. Otherwise it returns false.
680 static bool RetryAsync(SSL *ssl, int ret) {
681   // No error; don't retry.
682   if (ret >= 0) {
683     return false;
684   }
685
686   TestState *test_state = GetTestState(ssl);
687   assert(GetTestConfig(ssl)->async);
688
689   if (test_state->packeted_bio != nullptr &&
690       PacketedBioAdvanceClock(test_state->packeted_bio)) {
691     // The DTLS retransmit logic silently ignores write failures. So the test
692     // may progress, allow writes through synchronously.
693     AsyncBioEnforceWriteQuota(test_state->async_bio, false);
694     int timeout_ret = DTLSv1_handle_timeout(ssl);
695     AsyncBioEnforceWriteQuota(test_state->async_bio, true);
696
697     if (timeout_ret < 0) {
698       fprintf(stderr, "Error retransmitting.\n");
699       return false;
700     }
701     return true;
702   }
703
704   // See if we needed to read or write more. If so, allow one byte through on
705   // the appropriate end to maximally stress the state machine.
706   switch (SSL_get_error(ssl, ret)) {
707     case SSL_ERROR_WANT_READ:
708       AsyncBioAllowRead(test_state->async_bio, 1);
709       return true;
710     case SSL_ERROR_WANT_WRITE:
711       AsyncBioAllowWrite(test_state->async_bio, 1);
712       return true;
713     case SSL_ERROR_WANT_X509_LOOKUP:
714       test_state->cert_ready = true;
715       return true;
716     default:
717       return false;
718   }
719 }
720
721 // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
722 // the result value of the final |SSL_read| call.
723 static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
724   const TestConfig *config = GetTestConfig(ssl);
725   TestState *test_state = GetTestState(ssl);
726   int ret;
727   do {
728     if (config->async) {
729       // The DTLS retransmit logic silently ignores write failures. So the test
730       // may progress, allow writes through synchronously. |SSL_read| may
731       // trigger a retransmit, so disconnect the write quota.
732       AsyncBioEnforceWriteQuota(test_state->async_bio, false);
733     }
734     ret = config->peek_then_read ? SSL_peek(ssl, out, max_out)
735                                  : SSL_read(ssl, out, max_out);
736     if (config->async) {
737       AsyncBioEnforceWriteQuota(test_state->async_bio, true);
738     }
739   } while (config->async && RetryAsync(ssl, ret));
740
741   if (config->peek_then_read && ret > 0) {
742     std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
743
744     // SSL_peek should synchronously return the same data.
745     int ret2 = SSL_peek(ssl, buf.get(), ret);
746     if (ret2 != ret ||
747         memcmp(buf.get(), out, ret) != 0) {
748       fprintf(stderr, "First and second SSL_peek did not match.\n");
749       return -1;
750     }
751
752     // SSL_read should synchronously return the same data and consume it.
753     ret2 = SSL_read(ssl, buf.get(), ret);
754     if (ret2 != ret ||
755         memcmp(buf.get(), out, ret) != 0) {
756       fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
757       return -1;
758     }
759   }
760
761   return ret;
762 }
763
764 // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
765 // operations. It returns the result of the final |SSL_write| call.
766 static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
767   const TestConfig *config = GetTestConfig(ssl);
768   int ret;
769   do {
770     ret = SSL_write(ssl, in, in_len);
771     if (ret > 0) {
772       in += ret;
773       in_len -= ret;
774     }
775   } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
776   return ret;
777 }
778
779 // DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
780 // returns the result of the final |SSL_shutdown| call.
781 static int DoShutdown(SSL *ssl) {
782   const TestConfig *config = GetTestConfig(ssl);
783   int ret;
784   do {
785     ret = SSL_shutdown(ssl);
786   } while (config->async && RetryAsync(ssl, ret));
787   return ret;
788 }
789
790 static uint16_t GetProtocolVersion(const SSL *ssl) {
791   uint16_t version = SSL_version(ssl);
792   if (!SSL_is_dtls(ssl)) {
793     return version;
794   }
795   return 0x0201 + ~version;
796 }
797
798 // CheckHandshakeProperties checks, immediately after |ssl| completes its
799 // initial handshake (or False Starts), whether all the properties are
800 // consistent with the test configuration and invariants.
801 static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
802   const TestConfig *config = GetTestConfig(ssl);
803
804   if (SSL_get_current_cipher(ssl) == nullptr) {
805     fprintf(stderr, "null cipher after handshake\n");
806     return false;
807   }
808
809   if (is_resume &&
810       (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
811     fprintf(stderr, "session was%s reused\n",
812             SSL_session_reused(ssl) ? "" : " not");
813     return false;
814   }
815
816   bool expect_handshake_done = is_resume || !config->false_start;
817   if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
818     fprintf(stderr, "handshake was%s completed\n",
819             GetTestState(ssl)->handshake_done ? "" : " not");
820     return false;
821   }
822
823   if (expect_handshake_done && !config->is_server) {
824     bool expect_new_session =
825         !config->expect_no_session &&
826         (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
827         // Session tickets are sent post-handshake in TLS 1.3.
828         GetProtocolVersion(ssl) < TLS1_3_VERSION;
829     if (expect_new_session != GetTestState(ssl)->got_new_session) {
830       fprintf(stderr,
831               "new session was%s cached, but we expected the opposite\n",
832               GetTestState(ssl)->got_new_session ? "" : " not");
833       return false;
834     }
835   }
836
837   if (!config->expected_server_name.empty()) {
838     const char *server_name =
839         SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
840     if (server_name != config->expected_server_name) {
841       fprintf(stderr, "servername mismatch (got %s; want %s)\n",
842               server_name, config->expected_server_name.c_str());
843       return false;
844     }
845   }
846
847   if (!config->expected_next_proto.empty()) {
848     const uint8_t *next_proto;
849     unsigned next_proto_len;
850     SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
851     if (next_proto_len != config->expected_next_proto.size() ||
852         memcmp(next_proto, config->expected_next_proto.data(),
853                next_proto_len) != 0) {
854       fprintf(stderr, "negotiated next proto mismatch\n");
855       return false;
856     }
857   }
858
859   if (!config->expected_alpn.empty()) {
860     const uint8_t *alpn_proto;
861     unsigned alpn_proto_len;
862     SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
863     if (alpn_proto_len != config->expected_alpn.size() ||
864         memcmp(alpn_proto, config->expected_alpn.data(),
865                alpn_proto_len) != 0) {
866       fprintf(stderr, "negotiated alpn proto mismatch\n");
867       return false;
868     }
869   }
870
871   if (config->expect_extended_master_secret) {
872     if (!SSL_get_extms_support(ssl)) {
873       fprintf(stderr, "No EMS for connection when expected");
874       return false;
875     }
876   }
877
878   if (config->expect_verify_result) {
879     int expected_verify_result = config->verify_fail ?
880       X509_V_ERR_APPLICATION_VERIFICATION :
881       X509_V_OK;
882
883     if (SSL_get_verify_result(ssl) != expected_verify_result) {
884       fprintf(stderr, "Wrong certificate verification result\n");
885       return false;
886     }
887   }
888
889   if (!config->psk.empty()) {
890     if (SSL_get_peer_cert_chain(ssl) != nullptr) {
891       fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
892       return false;
893     }
894   } else if (!config->is_server || config->require_any_client_certificate) {
895     if (SSL_get_peer_cert_chain(ssl) == nullptr) {
896       fprintf(stderr, "Received no peer certificate but expected one.\n");
897       return false;
898     }
899   }
900
901   return true;
902 }
903
904 // DoExchange runs a test SSL exchange against the peer. On success, it returns
905 // true and sets |*out_session| to the negotiated SSL session. If the test is a
906 // resumption attempt, |is_resume| is true and |session| is the session from the
907 // previous exchange.
908 static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
909                        SSL_CTX *ssl_ctx, const TestConfig *config,
910                        bool is_resume, SSL_SESSION *session) {
911   bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
912   if (!ssl) {
913     return false;
914   }
915
916   if (!SetTestConfig(ssl.get(), config) ||
917       !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
918     return false;
919   }
920
921   if (config->fallback_scsv &&
922       !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
923     return false;
924   }
925   // Install the certificate synchronously if nothing else will handle it.
926   if (!config->use_early_callback &&
927       !config->use_old_client_cert_callback &&
928       !config->async &&
929       !InstallCertificate(ssl.get())) {
930     return false;
931   }
932   SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
933   if (config->require_any_client_certificate) {
934     SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
935                    NULL);
936   }
937   if (config->verify_peer) {
938     SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
939   }
940   if (config->false_start) {
941     fprintf(stderr, "False Start not supported\n");
942     return false;
943   }
944   if (config->partial_write) {
945     SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
946   }
947   if (config->no_tls13) {
948     SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
949   }
950   if (config->no_tls12) {
951     SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
952   }
953   if (config->no_tls11) {
954     SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
955   }
956   if (config->no_tls1) {
957     SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
958   }
959   if (config->no_ssl3) {
960     SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
961   }
962   if (!config->expected_channel_id.empty()) {
963     fprintf(stderr, "Channel ID not supported\n");
964     return false;
965   }
966   if (!config->send_channel_id.empty()) {
967     fprintf(stderr, "Channel ID not supported\n");
968     return false;
969   }
970   if (!config->host_name.empty() &&
971       !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
972     return false;
973   }
974   if (!config->advertise_alpn.empty() &&
975       SSL_set_alpn_protos(ssl.get(),
976                           (const uint8_t *)config->advertise_alpn.data(),
977                           config->advertise_alpn.size()) != 0) {
978     return false;
979   }
980   if (!config->psk.empty()) {
981     SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
982     SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
983   }
984   if (!config->psk_identity.empty() &&
985       !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
986     return false;
987   }
988   if (!config->srtp_profiles.empty() &&
989       SSL_set_tlsext_use_srtp(ssl.get(), config->srtp_profiles.c_str())) {
990     return false;
991   }
992   if (config->enable_ocsp_stapling) {
993     fprintf(stderr, "OCSP stapling not supported (with the same API).\n");
994     return false;
995   }
996   if (config->enable_signed_cert_timestamps) {
997     fprintf(stderr, "SCTs not supported (with the same API).\n");
998     return false;
999   }
1000   if (config->min_version != 0 &&
1001       !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) {
1002     return false;
1003   }
1004   if (config->max_version != 0 &&
1005       !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) {
1006     return false;
1007   }
1008   if (config->mtu != 0) {
1009     SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
1010     SSL_set_mtu(ssl.get(), config->mtu);
1011   }
1012   if (config->install_ddos_callback) {
1013     fprintf(stderr, "DDoS callback not supported.\n");
1014     return false;
1015   }
1016   if (config->renegotiate_once) {
1017     fprintf(stderr, "renegotiate_once not supported.\n");
1018     return false;
1019   }
1020   if (config->renegotiate_freely) {
1021     // This is always on for OpenSSL.
1022   }
1023   if (config->renegotiate_ignore) {
1024     fprintf(stderr, "renegotiate_ignore not supported.\n");
1025     return false;
1026   }
1027   if (!config->check_close_notify) {
1028     SSL_set_quiet_shutdown(ssl.get(), 1);
1029   }
1030   if (config->disable_npn) {
1031     fprintf(stderr, "SSL_OP_DISABLE_NPN not supported.\n");
1032     return false;
1033   }
1034   if (config->p384_only) {
1035     int nid = NID_secp384r1;
1036     if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
1037       return false;
1038     }
1039   }
1040   if (config->enable_all_curves) {
1041     static const int kAllCurves[] = {
1042       NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_X25519,
1043     };
1044     if (!SSL_set1_curves(ssl.get(), kAllCurves,
1045                          OPENSSL_ARRAY_SIZE(kAllCurves))) {
1046       return false;
1047     }
1048   }
1049   if (config->initial_timeout_duration_ms > 0) {
1050     fprintf(stderr, "Setting DTLS initial timeout duration not supported.\n");
1051     return false;
1052   }
1053   if (config->max_cert_list > 0) {
1054     SSL_set_max_cert_list(ssl.get(), config->max_cert_list);
1055   }
1056
1057   int sock = Connect(config->port);
1058   if (sock == -1) {
1059     return false;
1060   }
1061   SocketCloser closer(sock);
1062
1063   bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
1064   if (!bio) {
1065     return false;
1066   }
1067   if (config->is_dtls) {
1068     bssl::UniquePtr<BIO> packeted = PacketedBioCreate(!config->async);
1069     if (!packeted) {
1070       return false;
1071     }
1072     GetTestState(ssl.get())->packeted_bio = packeted.get();
1073     BIO_push(packeted.get(), bio.release());
1074     bio = std::move(packeted);
1075   }
1076   if (config->async) {
1077     bssl::UniquePtr<BIO> async_scoped =
1078         config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
1079     if (!async_scoped) {
1080       return false;
1081     }
1082     BIO_push(async_scoped.get(), bio.release());
1083     GetTestState(ssl.get())->async_bio = async_scoped.get();
1084     bio = std::move(async_scoped);
1085   }
1086   SSL_set_bio(ssl.get(), bio.get(), bio.get());
1087   bio.release();  // SSL_set_bio takes ownership.
1088
1089   if (session != NULL) {
1090     if (!config->is_server) {
1091       if (SSL_set_session(ssl.get(), session) != 1) {
1092         return false;
1093       }
1094     }
1095   }
1096
1097 #if 0
1098   // KNOWN BUG: OpenSSL's SSL_get_current_cipher behaves incorrectly when
1099   // offering resumption.
1100   if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1101     fprintf(stderr, "non-null cipher before handshake\n");
1102     return false;
1103   }
1104 #endif
1105
1106   int ret;
1107   if (config->implicit_handshake) {
1108     if (config->is_server) {
1109       SSL_set_accept_state(ssl.get());
1110     } else {
1111       SSL_set_connect_state(ssl.get());
1112     }
1113   } else {
1114     do {
1115       if (config->is_server) {
1116         ret = SSL_accept(ssl.get());
1117       } else {
1118         ret = SSL_connect(ssl.get());
1119       }
1120     } while (config->async && RetryAsync(ssl.get(), ret));
1121     if (ret != 1 ||
1122         !CheckHandshakeProperties(ssl.get(), is_resume)) {
1123       return false;
1124     }
1125
1126     // Reset the state to assert later that the callback isn't called in
1127     // renegotations.
1128     GetTestState(ssl.get())->got_new_session = false;
1129   }
1130
1131   if (config->export_keying_material > 0) {
1132     std::vector<uint8_t> result(
1133         static_cast<size_t>(config->export_keying_material));
1134     if (SSL_export_keying_material(
1135             ssl.get(), result.data(), result.size(),
1136             config->export_label.data(), config->export_label.size(),
1137             reinterpret_cast<const uint8_t*>(config->export_context.data()),
1138             config->export_context.size(), config->use_export_context) != 1) {
1139       fprintf(stderr, "failed to export keying material\n");
1140       return false;
1141     }
1142     if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1143       return false;
1144     }
1145   }
1146
1147   if (config->tls_unique) {
1148     fprintf(stderr, "tls_unique not supported\n");
1149     return false;
1150   }
1151
1152   if (config->send_alert) {
1153     fprintf(stderr, "Sending an alert not supported\n");
1154     return false;
1155   }
1156
1157   if (config->write_different_record_sizes) {
1158     if (config->is_dtls) {
1159       fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
1160       return false;
1161     }
1162     // This mode writes a number of different record sizes in an attempt to
1163     // trip up the CBC record splitting code.
1164     static const size_t kBufLen = 32769;
1165     std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1166     memset(buf.get(), 0x42, kBufLen);
1167     static const size_t kRecordSizes[] = {
1168         0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
1169     for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
1170       const size_t len = kRecordSizes[i];
1171       if (len > kBufLen) {
1172         fprintf(stderr, "Bad kRecordSizes value.\n");
1173         return false;
1174       }
1175       if (WriteAll(ssl.get(), buf.get(), len) < 0) {
1176         return false;
1177       }
1178     }
1179   } else {
1180     if (config->shim_writes_first) {
1181       if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1182                    5) < 0) {
1183         return false;
1184       }
1185     }
1186     if (!config->shim_shuts_down) {
1187       for (;;) {
1188         static const size_t kBufLen = 16384;
1189         std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1190
1191         // Read only 512 bytes at a time in TLS to ensure records may be
1192         // returned in multiple reads.
1193         int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
1194         int err = SSL_get_error(ssl.get(), n);
1195         if (err == SSL_ERROR_ZERO_RETURN ||
1196             (n == 0 && err == SSL_ERROR_SYSCALL)) {
1197           if (n != 0) {
1198             fprintf(stderr, "Invalid SSL_get_error output\n");
1199             return false;
1200           }
1201           // Stop on either clean or unclean shutdown.
1202           break;
1203         } else if (err != SSL_ERROR_NONE) {
1204           if (n > 0) {
1205             fprintf(stderr, "Invalid SSL_get_error output\n");
1206             return false;
1207           }
1208           return false;
1209         }
1210         // Successfully read data.
1211         if (n <= 0) {
1212           fprintf(stderr, "Invalid SSL_get_error output\n");
1213           return false;
1214         }
1215
1216         // After a successful read, with or without False Start, the handshake
1217         // must be complete.
1218         if (!GetTestState(ssl.get())->handshake_done) {
1219           fprintf(stderr, "handshake was not completed after SSL_read\n");
1220           return false;
1221         }
1222
1223         for (int i = 0; i < n; i++) {
1224           buf[i] ^= 0xff;
1225         }
1226         if (WriteAll(ssl.get(), buf.get(), n) < 0) {
1227           return false;
1228         }
1229       }
1230     }
1231   }
1232
1233   if (!config->is_server && !config->false_start &&
1234       !config->implicit_handshake &&
1235       // Session tickets are sent post-handshake in TLS 1.3.
1236       GetProtocolVersion(ssl.get()) < TLS1_3_VERSION &&
1237       GetTestState(ssl.get())->got_new_session) {
1238     fprintf(stderr, "new session was established after the handshake\n");
1239     return false;
1240   }
1241
1242   if (GetProtocolVersion(ssl.get()) >= TLS1_3_VERSION && !config->is_server) {
1243     bool expect_new_session =
1244         !config->expect_no_session && !config->shim_shuts_down;
1245     if (expect_new_session != GetTestState(ssl.get())->got_new_session) {
1246       fprintf(stderr,
1247               "new session was%s cached, but we expected the opposite\n",
1248               GetTestState(ssl.get())->got_new_session ? "" : " not");
1249       return false;
1250     }
1251   }
1252
1253   if (out_session) {
1254     *out_session = std::move(GetTestState(ssl.get())->new_session);
1255   }
1256
1257   ret = DoShutdown(ssl.get());
1258
1259   if (config->shim_shuts_down && config->check_close_notify) {
1260     // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1261     // it returns zero when our close_notify is sent, then one when the peer's
1262     // is received.
1263     if (ret != 0) {
1264       fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1265       return false;
1266     }
1267     ret = DoShutdown(ssl.get());
1268   }
1269
1270   if (ret != 1) {
1271     fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1272     return false;
1273   }
1274
1275   if (SSL_total_renegotiations(ssl.get()) !=
1276       config->expect_total_renegotiations) {
1277     fprintf(stderr, "Expected %d renegotiations, got %ld\n",
1278             config->expect_total_renegotiations,
1279             SSL_total_renegotiations(ssl.get()));
1280     return false;
1281   }
1282
1283   return true;
1284 }
1285
1286 class StderrDelimiter {
1287  public:
1288   ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
1289 };
1290
1291 static int Main(int argc, char **argv) {
1292   // To distinguish ASan's output from ours, add a trailing message to stderr.
1293   // Anything following this line will be considered an error.
1294   StderrDelimiter delimiter;
1295
1296 #if defined(OPENSSL_WINDOWS)
1297   /* Initialize Winsock. */
1298   WORD wsa_version = MAKEWORD(2, 2);
1299   WSADATA wsa_data;
1300   int wsa_err = WSAStartup(wsa_version, &wsa_data);
1301   if (wsa_err != 0) {
1302     fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1303     return 1;
1304   }
1305   if (wsa_data.wVersion != wsa_version) {
1306     fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1307     return 1;
1308   }
1309 #else
1310   signal(SIGPIPE, SIG_IGN);
1311 #endif
1312
1313   OPENSSL_init_crypto(0, NULL);
1314   OPENSSL_init_ssl(0, NULL);
1315   g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
1316   g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
1317   if (g_config_index < 0 || g_state_index < 0) {
1318     return 1;
1319   }
1320
1321   TestConfig config;
1322   if (!ParseConfig(argc - 1, argv + 1, &config)) {
1323     return Usage(argv[0]);
1324   }
1325
1326   bssl::UniquePtr<SSL_CTX> ssl_ctx = SetupCtx(&config);
1327   if (!ssl_ctx) {
1328     ERR_print_errors_fp(stderr);
1329     return 1;
1330   }
1331
1332   bssl::UniquePtr<SSL_SESSION> session;
1333   for (int i = 0; i < config.resume_count + 1; i++) {
1334     bool is_resume = i > 0;
1335     if (is_resume && !config.is_server && !session) {
1336       fprintf(stderr, "No session to offer.\n");
1337       return 1;
1338     }
1339
1340     bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
1341     if (!DoExchange(&session, ssl_ctx.get(), &config, is_resume,
1342                     offer_session.get())) {
1343       fprintf(stderr, "Connection %d failed.\n", i + 1);
1344       ERR_print_errors_fp(stderr);
1345       return 1;
1346     }
1347   }
1348
1349   return 0;
1350 }
1351
1352 }  // namespace bssl
1353
1354 int main(int argc, char **argv) {
1355   return bssl::Main(argc, argv);
1356 }