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