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