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