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