1 /* Copyright (c) 2014, Google Inc.
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.
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. */
15 #if !defined(__STDC_FORMAT_MACROS)
16 #define __STDC_FORMAT_MACROS
19 #include <openssl/e_os2.h>
21 #if !defined(OPENSSL_SYS_WINDOWS)
22 #include <arpa/inet.h>
23 #include <netinet/in.h>
24 #include <netinet/tcp.h>
26 #include <sys/socket.h>
31 OPENSSL_MSVC_PRAGMA(warning(push, 3))
34 OPENSSL_MSVC_PRAGMA(warning(pop))
36 OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
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>
59 #include "async_bio.h"
60 #include "packeted_bio.h"
61 #include "test_config.h"
65 #if !defined(OPENSSL_SYS_WINDOWS)
66 static int closesocket(int sock) {
70 static void PrintSocketError(const char *func) {
74 static void PrintSocketError(const char *func) {
75 fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
79 static int Usage(const char *program) {
80 fprintf(stderr, "Usage: %s [flags...]\n", program);
85 // async_bio is async BIO which pauses reads and writes.
86 BIO *async_bio = nullptr;
87 // packeted_bio is the packeted BIO which simulates read timeouts.
88 BIO *packeted_bio = nullptr;
89 bssl::UniquePtr<EVP_PKEY> channel_id;
90 bool cert_ready = false;
91 bssl::UniquePtr<SSL_SESSION> session;
92 bssl::UniquePtr<SSL_SESSION> pending_session;
93 bool early_callback_called = false;
94 bool handshake_done = false;
95 // private_key is the underlying private key used when testing custom keys.
96 bssl::UniquePtr<EVP_PKEY> private_key;
97 std::vector<uint8_t> private_key_result;
98 // private_key_retries is the number of times an asynchronous private key
99 // operation has been retried.
100 unsigned private_key_retries = 0;
101 bool got_new_session = false;
102 bssl::UniquePtr<SSL_SESSION> new_session;
103 bool ticket_decrypt_done = false;
104 bool alpn_select_done = false;
107 static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
108 int index, long argl, void *argp) {
109 delete ((TestState *)ptr);
112 static int g_config_index = 0;
113 static int g_state_index = 0;
115 static bool SetTestConfig(SSL *ssl, const TestConfig *config) {
116 return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
119 static const TestConfig *GetTestConfig(const SSL *ssl) {
120 return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
123 static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
124 // |SSL_set_ex_data| takes ownership of |state| only on success.
125 if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
132 static TestState *GetTestState(const SSL *ssl) {
133 return (TestState *)SSL_get_ex_data(ssl, g_state_index);
136 static bssl::UniquePtr<X509> LoadCertificate(const std::string &file) {
137 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
138 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
141 return bssl::UniquePtr<X509>(PEM_read_bio_X509(bio.get(), NULL, NULL, NULL));
144 static bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
145 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
146 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
149 return bssl::UniquePtr<EVP_PKEY>(
150 PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
155 void operator()(T *buf) {
160 static bool GetCertificate(SSL *ssl, bssl::UniquePtr<X509> *out_x509,
161 bssl::UniquePtr<EVP_PKEY> *out_pkey) {
162 const TestConfig *config = GetTestConfig(ssl);
164 if (!config->digest_prefs.empty()) {
165 fprintf(stderr, "Digest prefs not supported.\n");
169 if (!config->signing_prefs.empty()) {
170 fprintf(stderr, "Set signing algorithm prefs not supported\n");
174 if (!config->key_file.empty()) {
175 *out_pkey = LoadPrivateKey(config->key_file.c_str());
180 if (!config->cert_file.empty()) {
181 *out_x509 = LoadCertificate(config->cert_file.c_str());
186 if (!config->ocsp_response.empty()) {
187 fprintf(stderr, "OCSP response not supported.\n");
193 static bool InstallCertificate(SSL *ssl) {
194 bssl::UniquePtr<X509> x509;
195 bssl::UniquePtr<EVP_PKEY> pkey;
196 if (!GetCertificate(ssl, &x509, &pkey)) {
201 if (!SSL_use_PrivateKey(ssl, pkey.get())) {
206 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
213 static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
214 if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
218 bssl::UniquePtr<X509> x509;
219 bssl::UniquePtr<EVP_PKEY> pkey;
220 if (!GetCertificate(ssl, &x509, &pkey)) {
224 // Return zero for no certificate.
229 // Asynchronous private keys are not supported with client_cert_cb.
230 *out_x509 = x509.release();
231 *out_pkey = pkey.release();
235 static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
239 static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
240 X509_STORE_CTX_set_error(store_ctx, X509_V_ERR_APPLICATION_VERIFICATION);
244 static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
245 unsigned int *out_len, void *arg) {
246 const TestConfig *config = GetTestConfig(ssl);
247 if (config->advertise_npn.empty()) {
248 return SSL_TLSEXT_ERR_NOACK;
251 *out = (const uint8_t*)config->advertise_npn.data();
252 *out_len = config->advertise_npn.size();
253 return SSL_TLSEXT_ERR_OK;
256 static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
257 const uint8_t* in, unsigned inlen, void* arg) {
258 const TestConfig *config = GetTestConfig(ssl);
259 if (config->select_next_proto.empty()) {
260 return SSL_TLSEXT_ERR_NOACK;
263 *out = (uint8_t*)config->select_next_proto.data();
264 *outlen = config->select_next_proto.size();
265 return SSL_TLSEXT_ERR_OK;
268 static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
269 const uint8_t* in, unsigned inlen, void* arg) {
270 if (GetTestState(ssl)->alpn_select_done) {
271 fprintf(stderr, "AlpnSelectCallback called after completion.\n");
275 GetTestState(ssl)->alpn_select_done = true;
277 const TestConfig *config = GetTestConfig(ssl);
278 if (config->decline_alpn) {
279 return SSL_TLSEXT_ERR_NOACK;
282 if (!config->expected_advertised_alpn.empty() &&
283 (config->expected_advertised_alpn.size() != inlen ||
284 memcmp(config->expected_advertised_alpn.data(),
286 fprintf(stderr, "bad ALPN select callback inputs\n");
290 *out = (const uint8_t*)config->select_alpn.data();
291 *outlen = config->select_alpn.size();
292 return SSL_TLSEXT_ERR_OK;
295 static unsigned PskClientCallback(SSL *ssl, const char *hint,
297 unsigned max_identity_len,
298 uint8_t *out_psk, unsigned max_psk_len) {
299 const TestConfig *config = GetTestConfig(ssl);
301 if (config->psk_identity.empty()) {
302 if (hint != nullptr) {
303 fprintf(stderr, "Server PSK hint was non-null.\n");
306 } else if (hint == nullptr ||
307 strcmp(hint, config->psk_identity.c_str()) != 0) {
308 fprintf(stderr, "Server PSK hint did not match.\n");
312 // Account for the trailing '\0' for the identity.
313 if (config->psk_identity.size() >= max_identity_len ||
314 config->psk.size() > max_psk_len) {
315 fprintf(stderr, "PSK buffers too small\n");
319 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
321 memcpy(out_psk, config->psk.data(), config->psk.size());
322 return config->psk.size();
325 static unsigned PskServerCallback(SSL *ssl, const char *identity,
326 uint8_t *out_psk, unsigned max_psk_len) {
327 const TestConfig *config = GetTestConfig(ssl);
329 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
330 fprintf(stderr, "Client PSK identity did not match.\n");
334 if (config->psk.size() > max_psk_len) {
335 fprintf(stderr, "PSK buffers too small\n");
339 memcpy(out_psk, config->psk.data(), config->psk.size());
340 return config->psk.size();
343 static int CertCallback(SSL *ssl, void *arg) {
344 const TestConfig *config = GetTestConfig(ssl);
346 // Check the CertificateRequest metadata is as expected.
348 // TODO(davidben): Test |SSL_get_client_CA_list|.
349 if (!SSL_is_server(ssl) &&
350 !config->expected_certificate_types.empty()) {
351 const uint8_t *certificate_types;
352 size_t certificate_types_len =
353 SSL_get0_certificate_types(ssl, &certificate_types);
354 if (certificate_types_len != config->expected_certificate_types.size() ||
355 memcmp(certificate_types,
356 config->expected_certificate_types.data(),
357 certificate_types_len) != 0) {
358 fprintf(stderr, "certificate types mismatch\n");
363 // The certificate will be installed via other means.
364 if (!config->async || config->use_early_callback ||
365 config->use_old_client_cert_callback) {
369 if (!GetTestState(ssl)->cert_ready) {
372 if (!InstallCertificate(ssl)) {
378 static void InfoCallback(const SSL *ssl, int type, int val) {
379 if (type == SSL_CB_HANDSHAKE_DONE) {
380 if (GetTestConfig(ssl)->handshake_never_done) {
381 fprintf(stderr, "Handshake unexpectedly completed.\n");
382 // Abort before any expected error code is printed, to ensure the overall
386 GetTestState(ssl)->handshake_done = true;
388 // Callbacks may be called again on a new handshake.
389 GetTestState(ssl)->ticket_decrypt_done = false;
390 GetTestState(ssl)->alpn_select_done = false;
394 static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
395 GetTestState(ssl)->got_new_session = true;
396 GetTestState(ssl)->new_session.reset(session);
400 static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
401 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
404 if (GetTestState(ssl)->ticket_decrypt_done) {
405 fprintf(stderr, "TicketKeyCallback called after completion.\n");
409 GetTestState(ssl)->ticket_decrypt_done = true;
412 // This is just test code, so use the all-zeros key.
413 static const uint8_t kZeros[16] = {0};
416 memcpy(key_name, kZeros, sizeof(kZeros));
418 } else if (memcmp(key_name, kZeros, 16) != 0) {
422 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
423 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
428 return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
433 // kCustomExtensionValue is the extension value that the custom extension
434 // callbacks will add.
435 static const uint16_t kCustomExtensionValue = 1234;
436 static void *const kCustomExtensionAddArg =
437 reinterpret_cast<void *>(kCustomExtensionValue);
438 static void *const kCustomExtensionParseArg =
439 reinterpret_cast<void *>(kCustomExtensionValue + 1);
440 static const char kCustomExtensionContents[] = "custom extension";
442 static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
443 const uint8_t **out, size_t *out_len,
444 int *out_alert_value, void *add_arg) {
445 if (extension_value != kCustomExtensionValue ||
446 add_arg != kCustomExtensionAddArg) {
450 if (GetTestConfig(ssl)->custom_extension_skip) {
453 if (GetTestConfig(ssl)->custom_extension_fail_add) {
457 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
458 *out_len = sizeof(kCustomExtensionContents) - 1;
463 static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
464 const uint8_t *out, void *add_arg) {
465 if (extension_value != kCustomExtensionValue ||
466 add_arg != kCustomExtensionAddArg ||
467 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
472 static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
473 const uint8_t *contents,
475 int *out_alert_value, void *parse_arg) {
476 if (extension_value != kCustomExtensionValue ||
477 parse_arg != kCustomExtensionParseArg) {
481 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
482 memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
483 *out_alert_value = SSL_AD_DECODE_ERROR;
490 // Connect returns a new socket connected to localhost on |port| or -1 on
492 static int Connect(uint16_t port) {
493 int sock = socket(AF_INET, SOCK_STREAM, 0);
495 PrintSocketError("socket");
499 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
500 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
501 PrintSocketError("setsockopt");
506 memset(&sin, 0, sizeof(sin));
507 sin.sin_family = AF_INET;
508 sin.sin_port = htons(port);
509 if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
510 PrintSocketError("inet_pton");
514 if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
516 PrintSocketError("connect");
525 explicit SocketCloser(int sock) : sock_(sock) {}
527 // Half-close and drain the socket before releasing it. This seems to be
528 // necessary for graceful shutdown on Windows. It will also avoid write
529 // failures in the test runner.
530 #if defined(OPENSSL_WINDOWS)
531 shutdown(sock_, SD_SEND);
533 shutdown(sock_, SHUT_WR);
537 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
548 static bssl::UniquePtr<SSL_CTX> SetupCtx(const TestConfig *config) {
549 bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(
550 config->is_dtls ? DTLS_method() : TLS_method()));
555 SSL_CTX_set_security_level(ssl_ctx.get(), 0);
557 /* Disabled for now until we have some TLS1.3 support */
558 // Enable TLS 1.3 for tests.
559 if (!config->is_dtls &&
560 !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION)) {
565 std::string cipher_list = "ALL";
566 if (!config->cipher.empty()) {
567 cipher_list = config->cipher;
568 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
570 if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
574 if (!config->cipher_tls10.empty() || !config->cipher_tls11.empty()) {
575 fprintf(stderr, "version-specific cipher lists not supported.\n");
581 if (config->use_sparse_dh_prime) {
586 if (p == NULL || g == NULL || tmpdh == NULL) {
592 // This prime number is 2^1024 + 643 – a value just above a power of two.
593 // Because of its form, values modulo it are essentially certain to be one
594 // byte shorter. This is used to test padding of these values.
597 "1000000000000000000000000000000000000000000000000000000000000000"
598 "0000000000000000000000000000000000000000000000000000000000000000"
599 "0000000000000000000000000000000000000000000000000000000000000000"
600 "0000000000000000000000000000000000000000000000000000000000000028"
602 !BN_set_word(g, 2)) {
608 DH_set0_pqg(tmpdh, p, NULL, g);
610 tmpdh = DH_get_2048_256();
613 bssl::UniquePtr<DH> dh(tmpdh);
615 if (!dh || !SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
619 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
621 if (config->use_old_client_cert_callback) {
622 SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
625 SSL_CTX_set_next_protos_advertised_cb(
626 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
627 if (!config->select_next_proto.empty()) {
628 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
632 if (!config->select_alpn.empty() || config->decline_alpn) {
633 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
636 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
637 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
639 if (config->use_ticket_callback) {
640 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
643 if (config->enable_client_custom_extension &&
644 !SSL_CTX_add_client_custom_ext(
645 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
646 CustomExtensionFreeCallback, kCustomExtensionAddArg,
647 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
651 if (config->enable_server_custom_extension &&
652 !SSL_CTX_add_server_custom_ext(
653 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
654 CustomExtensionFreeCallback, kCustomExtensionAddArg,
655 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
659 if (config->verify_fail) {
660 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
662 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
665 if (!config->signed_cert_timestamps.empty()) {
666 fprintf(stderr, "SCTs not supported.\n");
670 if (config->use_null_client_ca_list) {
671 SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
677 // RetryAsync is called after a failed operation on |ssl| with return code
678 // |ret|. If the operation should be retried, it simulates one asynchronous
679 // event and returns true. Otherwise it returns false.
680 static bool RetryAsync(SSL *ssl, int ret) {
681 // No error; don't retry.
686 TestState *test_state = GetTestState(ssl);
687 assert(GetTestConfig(ssl)->async);
689 if (test_state->packeted_bio != nullptr &&
690 PacketedBioAdvanceClock(test_state->packeted_bio)) {
691 // The DTLS retransmit logic silently ignores write failures. So the test
692 // may progress, allow writes through synchronously.
693 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
694 int timeout_ret = DTLSv1_handle_timeout(ssl);
695 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
697 if (timeout_ret < 0) {
698 fprintf(stderr, "Error retransmitting.\n");
704 // See if we needed to read or write more. If so, allow one byte through on
705 // the appropriate end to maximally stress the state machine.
706 switch (SSL_get_error(ssl, ret)) {
707 case SSL_ERROR_WANT_READ:
708 AsyncBioAllowRead(test_state->async_bio, 1);
710 case SSL_ERROR_WANT_WRITE:
711 AsyncBioAllowWrite(test_state->async_bio, 1);
713 case SSL_ERROR_WANT_X509_LOOKUP:
714 test_state->cert_ready = true;
721 // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
722 // the result value of the final |SSL_read| call.
723 static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
724 const TestConfig *config = GetTestConfig(ssl);
725 TestState *test_state = GetTestState(ssl);
729 // The DTLS retransmit logic silently ignores write failures. So the test
730 // may progress, allow writes through synchronously. |SSL_read| may
731 // trigger a retransmit, so disconnect the write quota.
732 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
734 ret = config->peek_then_read ? SSL_peek(ssl, out, max_out)
735 : SSL_read(ssl, out, max_out);
737 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
739 } while (config->async && RetryAsync(ssl, ret));
741 if (config->peek_then_read && ret > 0) {
742 std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
744 // SSL_peek should synchronously return the same data.
745 int ret2 = SSL_peek(ssl, buf.get(), ret);
747 memcmp(buf.get(), out, ret) != 0) {
748 fprintf(stderr, "First and second SSL_peek did not match.\n");
752 // SSL_read should synchronously return the same data and consume it.
753 ret2 = SSL_read(ssl, buf.get(), ret);
755 memcmp(buf.get(), out, ret) != 0) {
756 fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
764 // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
765 // operations. It returns the result of the final |SSL_write| call.
766 static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
767 const TestConfig *config = GetTestConfig(ssl);
770 ret = SSL_write(ssl, in, in_len);
775 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
779 // DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
780 // returns the result of the final |SSL_shutdown| call.
781 static int DoShutdown(SSL *ssl) {
782 const TestConfig *config = GetTestConfig(ssl);
785 ret = SSL_shutdown(ssl);
786 } while (config->async && RetryAsync(ssl, ret));
790 static uint16_t GetProtocolVersion(const SSL *ssl) {
791 uint16_t version = SSL_version(ssl);
792 if (!SSL_is_dtls(ssl)) {
795 return 0x0201 + ~version;
798 // CheckHandshakeProperties checks, immediately after |ssl| completes its
799 // initial handshake (or False Starts), whether all the properties are
800 // consistent with the test configuration and invariants.
801 static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
802 const TestConfig *config = GetTestConfig(ssl);
804 if (SSL_get_current_cipher(ssl) == nullptr) {
805 fprintf(stderr, "null cipher after handshake\n");
810 (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
811 fprintf(stderr, "session was%s reused\n",
812 SSL_session_reused(ssl) ? "" : " not");
816 bool expect_handshake_done = is_resume || !config->false_start;
817 if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
818 fprintf(stderr, "handshake was%s completed\n",
819 GetTestState(ssl)->handshake_done ? "" : " not");
823 if (expect_handshake_done && !config->is_server) {
824 bool expect_new_session =
825 !config->expect_no_session &&
826 (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
827 // Session tickets are sent post-handshake in TLS 1.3.
828 GetProtocolVersion(ssl) < TLS1_3_VERSION;
829 if (expect_new_session != GetTestState(ssl)->got_new_session) {
831 "new session was%s cached, but we expected the opposite\n",
832 GetTestState(ssl)->got_new_session ? "" : " not");
837 if (!config->expected_server_name.empty()) {
838 const char *server_name =
839 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
840 if (server_name != config->expected_server_name) {
841 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
842 server_name, config->expected_server_name.c_str());
847 if (!config->expected_next_proto.empty()) {
848 const uint8_t *next_proto;
849 unsigned next_proto_len;
850 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
851 if (next_proto_len != config->expected_next_proto.size() ||
852 memcmp(next_proto, config->expected_next_proto.data(),
853 next_proto_len) != 0) {
854 fprintf(stderr, "negotiated next proto mismatch\n");
859 if (!config->expected_alpn.empty()) {
860 const uint8_t *alpn_proto;
861 unsigned alpn_proto_len;
862 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
863 if (alpn_proto_len != config->expected_alpn.size() ||
864 memcmp(alpn_proto, config->expected_alpn.data(),
865 alpn_proto_len) != 0) {
866 fprintf(stderr, "negotiated alpn proto mismatch\n");
871 if (config->expect_extended_master_secret) {
872 if (!SSL_get_extms_support(ssl)) {
873 fprintf(stderr, "No EMS for connection when expected");
878 if (config->expect_verify_result) {
879 int expected_verify_result = config->verify_fail ?
880 X509_V_ERR_APPLICATION_VERIFICATION :
883 if (SSL_get_verify_result(ssl) != expected_verify_result) {
884 fprintf(stderr, "Wrong certificate verification result\n");
889 if (!config->psk.empty()) {
890 if (SSL_get_peer_cert_chain(ssl) != nullptr) {
891 fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
894 } else if (!config->is_server || config->require_any_client_certificate) {
895 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
896 fprintf(stderr, "Received no peer certificate but expected one.\n");
904 // DoExchange runs a test SSL exchange against the peer. On success, it returns
905 // true and sets |*out_session| to the negotiated SSL session. If the test is a
906 // resumption attempt, |is_resume| is true and |session| is the session from the
907 // previous exchange.
908 static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
909 SSL_CTX *ssl_ctx, const TestConfig *config,
910 bool is_resume, SSL_SESSION *session) {
911 bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
916 if (!SetTestConfig(ssl.get(), config) ||
917 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
921 if (config->fallback_scsv &&
922 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
925 // Install the certificate synchronously if nothing else will handle it.
926 if (!config->use_early_callback &&
927 !config->use_old_client_cert_callback &&
929 !InstallCertificate(ssl.get())) {
932 SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
933 if (config->require_any_client_certificate) {
934 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
937 if (config->verify_peer) {
938 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
940 if (config->false_start) {
941 fprintf(stderr, "False Start not supported\n");
944 if (config->partial_write) {
945 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
947 if (config->no_tls13) {
948 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
950 if (config->no_tls12) {
951 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
953 if (config->no_tls11) {
954 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
956 if (config->no_tls1) {
957 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
959 if (config->no_ssl3) {
960 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
962 if (!config->expected_channel_id.empty()) {
963 fprintf(stderr, "Channel ID not supported\n");
966 if (!config->send_channel_id.empty()) {
967 fprintf(stderr, "Channel ID not supported\n");
970 if (!config->host_name.empty() &&
971 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
974 if (!config->advertise_alpn.empty() &&
975 SSL_set_alpn_protos(ssl.get(),
976 (const uint8_t *)config->advertise_alpn.data(),
977 config->advertise_alpn.size()) != 0) {
980 if (!config->psk.empty()) {
981 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
982 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
984 if (!config->psk_identity.empty() &&
985 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
988 if (!config->srtp_profiles.empty() &&
989 SSL_set_tlsext_use_srtp(ssl.get(), config->srtp_profiles.c_str())) {
992 if (config->enable_ocsp_stapling) {
993 fprintf(stderr, "OCSP stapling not supported (with the same API).\n");
996 if (config->enable_signed_cert_timestamps) {
997 fprintf(stderr, "SCTs not supported (with the same API).\n");
1000 if (config->min_version != 0 &&
1001 !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) {
1004 if (config->max_version != 0 &&
1005 !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) {
1008 if (config->mtu != 0) {
1009 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
1010 SSL_set_mtu(ssl.get(), config->mtu);
1012 if (config->install_ddos_callback) {
1013 fprintf(stderr, "DDoS callback not supported.\n");
1016 if (config->renegotiate_once) {
1017 fprintf(stderr, "renegotiate_once not supported.\n");
1020 if (config->renegotiate_freely) {
1021 // This is always on for OpenSSL.
1023 if (config->renegotiate_ignore) {
1024 fprintf(stderr, "renegotiate_ignore not supported.\n");
1027 if (!config->check_close_notify) {
1028 SSL_set_quiet_shutdown(ssl.get(), 1);
1030 if (config->disable_npn) {
1031 fprintf(stderr, "SSL_OP_DISABLE_NPN not supported.\n");
1034 if (config->p384_only) {
1035 int nid = NID_secp384r1;
1036 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
1040 if (config->enable_all_curves) {
1041 static const int kAllCurves[] = {
1042 NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_X25519,
1044 if (!SSL_set1_curves(ssl.get(), kAllCurves,
1045 OPENSSL_ARRAY_SIZE(kAllCurves))) {
1049 if (config->initial_timeout_duration_ms > 0) {
1050 fprintf(stderr, "Setting DTLS initial timeout duration not supported.\n");
1053 if (config->max_cert_list > 0) {
1054 SSL_set_max_cert_list(ssl.get(), config->max_cert_list);
1057 int sock = Connect(config->port);
1061 SocketCloser closer(sock);
1063 bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
1067 if (config->is_dtls) {
1068 bssl::UniquePtr<BIO> packeted = PacketedBioCreate(!config->async);
1072 GetTestState(ssl.get())->packeted_bio = packeted.get();
1073 BIO_push(packeted.get(), bio.release());
1074 bio = std::move(packeted);
1076 if (config->async) {
1077 bssl::UniquePtr<BIO> async_scoped =
1078 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
1079 if (!async_scoped) {
1082 BIO_push(async_scoped.get(), bio.release());
1083 GetTestState(ssl.get())->async_bio = async_scoped.get();
1084 bio = std::move(async_scoped);
1086 SSL_set_bio(ssl.get(), bio.get(), bio.get());
1087 bio.release(); // SSL_set_bio takes ownership.
1089 if (session != NULL) {
1090 if (!config->is_server) {
1091 if (SSL_set_session(ssl.get(), session) != 1) {
1098 // KNOWN BUG: OpenSSL's SSL_get_current_cipher behaves incorrectly when
1099 // offering resumption.
1100 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1101 fprintf(stderr, "non-null cipher before handshake\n");
1107 if (config->implicit_handshake) {
1108 if (config->is_server) {
1109 SSL_set_accept_state(ssl.get());
1111 SSL_set_connect_state(ssl.get());
1115 if (config->is_server) {
1116 ret = SSL_accept(ssl.get());
1118 ret = SSL_connect(ssl.get());
1120 } while (config->async && RetryAsync(ssl.get(), ret));
1122 !CheckHandshakeProperties(ssl.get(), is_resume)) {
1126 // Reset the state to assert later that the callback isn't called in
1128 GetTestState(ssl.get())->got_new_session = false;
1131 if (config->export_keying_material > 0) {
1132 std::vector<uint8_t> result(
1133 static_cast<size_t>(config->export_keying_material));
1134 if (SSL_export_keying_material(
1135 ssl.get(), result.data(), result.size(),
1136 config->export_label.data(), config->export_label.size(),
1137 reinterpret_cast<const uint8_t*>(config->export_context.data()),
1138 config->export_context.size(), config->use_export_context) != 1) {
1139 fprintf(stderr, "failed to export keying material\n");
1142 if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1147 if (config->tls_unique) {
1148 fprintf(stderr, "tls_unique not supported\n");
1152 if (config->send_alert) {
1153 fprintf(stderr, "Sending an alert not supported\n");
1157 if (config->write_different_record_sizes) {
1158 if (config->is_dtls) {
1159 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
1162 // This mode writes a number of different record sizes in an attempt to
1163 // trip up the CBC record splitting code.
1164 static const size_t kBufLen = 32769;
1165 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1166 memset(buf.get(), 0x42, kBufLen);
1167 static const size_t kRecordSizes[] = {
1168 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
1169 for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
1170 const size_t len = kRecordSizes[i];
1171 if (len > kBufLen) {
1172 fprintf(stderr, "Bad kRecordSizes value.\n");
1175 if (WriteAll(ssl.get(), buf.get(), len) < 0) {
1180 if (config->shim_writes_first) {
1181 if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1186 if (!config->shim_shuts_down) {
1188 static const size_t kBufLen = 16384;
1189 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1191 // Read only 512 bytes at a time in TLS to ensure records may be
1192 // returned in multiple reads.
1193 int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
1194 int err = SSL_get_error(ssl.get(), n);
1195 if (err == SSL_ERROR_ZERO_RETURN ||
1196 (n == 0 && err == SSL_ERROR_SYSCALL)) {
1198 fprintf(stderr, "Invalid SSL_get_error output\n");
1201 // Stop on either clean or unclean shutdown.
1203 } else if (err != SSL_ERROR_NONE) {
1205 fprintf(stderr, "Invalid SSL_get_error output\n");
1210 // Successfully read data.
1212 fprintf(stderr, "Invalid SSL_get_error output\n");
1216 // After a successful read, with or without False Start, the handshake
1217 // must be complete.
1218 if (!GetTestState(ssl.get())->handshake_done) {
1219 fprintf(stderr, "handshake was not completed after SSL_read\n");
1223 for (int i = 0; i < n; i++) {
1226 if (WriteAll(ssl.get(), buf.get(), n) < 0) {
1233 if (!config->is_server && !config->false_start &&
1234 !config->implicit_handshake &&
1235 // Session tickets are sent post-handshake in TLS 1.3.
1236 GetProtocolVersion(ssl.get()) < TLS1_3_VERSION &&
1237 GetTestState(ssl.get())->got_new_session) {
1238 fprintf(stderr, "new session was established after the handshake\n");
1242 if (GetProtocolVersion(ssl.get()) >= TLS1_3_VERSION && !config->is_server) {
1243 bool expect_new_session =
1244 !config->expect_no_session && !config->shim_shuts_down;
1245 if (expect_new_session != GetTestState(ssl.get())->got_new_session) {
1247 "new session was%s cached, but we expected the opposite\n",
1248 GetTestState(ssl.get())->got_new_session ? "" : " not");
1254 *out_session = std::move(GetTestState(ssl.get())->new_session);
1257 ret = DoShutdown(ssl.get());
1259 if (config->shim_shuts_down && config->check_close_notify) {
1260 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1261 // it returns zero when our close_notify is sent, then one when the peer's
1264 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1267 ret = DoShutdown(ssl.get());
1271 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1275 if (SSL_total_renegotiations(ssl.get()) !=
1276 config->expect_total_renegotiations) {
1277 fprintf(stderr, "Expected %d renegotiations, got %ld\n",
1278 config->expect_total_renegotiations,
1279 SSL_total_renegotiations(ssl.get()));
1286 class StderrDelimiter {
1288 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
1291 static int Main(int argc, char **argv) {
1292 // To distinguish ASan's output from ours, add a trailing message to stderr.
1293 // Anything following this line will be considered an error.
1294 StderrDelimiter delimiter;
1296 #if defined(OPENSSL_WINDOWS)
1297 /* Initialize Winsock. */
1298 WORD wsa_version = MAKEWORD(2, 2);
1300 int wsa_err = WSAStartup(wsa_version, &wsa_data);
1302 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1305 if (wsa_data.wVersion != wsa_version) {
1306 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1310 signal(SIGPIPE, SIG_IGN);
1313 OPENSSL_init_crypto(0, NULL);
1314 OPENSSL_init_ssl(0, NULL);
1315 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
1316 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
1317 if (g_config_index < 0 || g_state_index < 0) {
1322 if (!ParseConfig(argc - 1, argv + 1, &config)) {
1323 return Usage(argv[0]);
1326 bssl::UniquePtr<SSL_CTX> ssl_ctx = SetupCtx(&config);
1328 ERR_print_errors_fp(stderr);
1332 bssl::UniquePtr<SSL_SESSION> session;
1333 for (int i = 0; i < config.resume_count + 1; i++) {
1334 bool is_resume = i > 0;
1335 if (is_resume && !config.is_server && !session) {
1336 fprintf(stderr, "No session to offer.\n");
1340 bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
1341 if (!DoExchange(&session, ssl_ctx.get(), &config, is_resume,
1342 offer_session.get())) {
1343 fprintf(stderr, "Connection %d failed.\n", i + 1);
1344 ERR_print_errors_fp(stderr);
1354 int main(int argc, char **argv) {
1355 return bssl::Main(argc, argv);