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 TestState *test_state = GetTestState(ssl);
202 const TestConfig *config = GetTestConfig(ssl);
203 if (!SSL_use_PrivateKey(ssl, pkey.get())) {
208 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
215 static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
216 if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
220 bssl::UniquePtr<X509> x509;
221 bssl::UniquePtr<EVP_PKEY> pkey;
222 if (!GetCertificate(ssl, &x509, &pkey)) {
226 // Return zero for no certificate.
231 // Asynchronous private keys are not supported with client_cert_cb.
232 *out_x509 = x509.release();
233 *out_pkey = pkey.release();
237 static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
241 static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
242 X509_STORE_CTX_set_error(store_ctx, X509_V_ERR_APPLICATION_VERIFICATION);
246 static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
247 unsigned int *out_len, void *arg) {
248 const TestConfig *config = GetTestConfig(ssl);
249 if (config->advertise_npn.empty()) {
250 return SSL_TLSEXT_ERR_NOACK;
253 *out = (const uint8_t*)config->advertise_npn.data();
254 *out_len = config->advertise_npn.size();
255 return SSL_TLSEXT_ERR_OK;
258 static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
259 const uint8_t* in, unsigned inlen, void* arg) {
260 const TestConfig *config = GetTestConfig(ssl);
261 if (config->select_next_proto.empty()) {
262 return SSL_TLSEXT_ERR_NOACK;
265 *out = (uint8_t*)config->select_next_proto.data();
266 *outlen = config->select_next_proto.size();
267 return SSL_TLSEXT_ERR_OK;
270 static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
271 const uint8_t* in, unsigned inlen, void* arg) {
272 if (GetTestState(ssl)->alpn_select_done) {
273 fprintf(stderr, "AlpnSelectCallback called after completion.\n");
277 GetTestState(ssl)->alpn_select_done = true;
279 const TestConfig *config = GetTestConfig(ssl);
280 if (config->decline_alpn) {
281 return SSL_TLSEXT_ERR_NOACK;
284 if (!config->expected_advertised_alpn.empty() &&
285 (config->expected_advertised_alpn.size() != inlen ||
286 memcmp(config->expected_advertised_alpn.data(),
288 fprintf(stderr, "bad ALPN select callback inputs\n");
292 *out = (const uint8_t*)config->select_alpn.data();
293 *outlen = config->select_alpn.size();
294 return SSL_TLSEXT_ERR_OK;
297 static unsigned PskClientCallback(SSL *ssl, const char *hint,
299 unsigned max_identity_len,
300 uint8_t *out_psk, unsigned max_psk_len) {
301 const TestConfig *config = GetTestConfig(ssl);
303 if (config->psk_identity.empty()) {
304 if (hint != nullptr) {
305 fprintf(stderr, "Server PSK hint was non-null.\n");
308 } else if (hint == nullptr ||
309 strcmp(hint, config->psk_identity.c_str()) != 0) {
310 fprintf(stderr, "Server PSK hint did not match.\n");
314 // Account for the trailing '\0' for the identity.
315 if (config->psk_identity.size() >= max_identity_len ||
316 config->psk.size() > max_psk_len) {
317 fprintf(stderr, "PSK buffers too small\n");
321 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
323 memcpy(out_psk, config->psk.data(), config->psk.size());
324 return config->psk.size();
327 static unsigned PskServerCallback(SSL *ssl, const char *identity,
328 uint8_t *out_psk, unsigned max_psk_len) {
329 const TestConfig *config = GetTestConfig(ssl);
331 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
332 fprintf(stderr, "Client PSK identity did not match.\n");
336 if (config->psk.size() > max_psk_len) {
337 fprintf(stderr, "PSK buffers too small\n");
341 memcpy(out_psk, config->psk.data(), config->psk.size());
342 return config->psk.size();
345 static int CertCallback(SSL *ssl, void *arg) {
346 const TestConfig *config = GetTestConfig(ssl);
348 // Check the CertificateRequest metadata is as expected.
350 // TODO(davidben): Test |SSL_get_client_CA_list|.
351 if (!SSL_is_server(ssl) &&
352 !config->expected_certificate_types.empty()) {
353 const uint8_t *certificate_types;
354 size_t certificate_types_len =
355 SSL_get0_certificate_types(ssl, &certificate_types);
356 if (certificate_types_len != config->expected_certificate_types.size() ||
357 memcmp(certificate_types,
358 config->expected_certificate_types.data(),
359 certificate_types_len) != 0) {
360 fprintf(stderr, "certificate types mismatch\n");
365 // The certificate will be installed via other means.
366 if (!config->async || config->use_early_callback ||
367 config->use_old_client_cert_callback) {
371 if (!GetTestState(ssl)->cert_ready) {
374 if (!InstallCertificate(ssl)) {
380 static void InfoCallback(const SSL *ssl, int type, int val) {
381 if (type == SSL_CB_HANDSHAKE_DONE) {
382 if (GetTestConfig(ssl)->handshake_never_done) {
383 fprintf(stderr, "Handshake unexpectedly completed.\n");
384 // Abort before any expected error code is printed, to ensure the overall
388 GetTestState(ssl)->handshake_done = true;
390 // Callbacks may be called again on a new handshake.
391 GetTestState(ssl)->ticket_decrypt_done = false;
392 GetTestState(ssl)->alpn_select_done = false;
396 static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
397 GetTestState(ssl)->got_new_session = true;
398 GetTestState(ssl)->new_session.reset(session);
402 static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
403 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
406 if (GetTestState(ssl)->ticket_decrypt_done) {
407 fprintf(stderr, "TicketKeyCallback called after completion.\n");
411 GetTestState(ssl)->ticket_decrypt_done = true;
414 // This is just test code, so use the all-zeros key.
415 static const uint8_t kZeros[16] = {0};
418 memcpy(key_name, kZeros, sizeof(kZeros));
420 } else if (memcmp(key_name, kZeros, 16) != 0) {
424 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
425 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
430 return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
435 // kCustomExtensionValue is the extension value that the custom extension
436 // callbacks will add.
437 static const uint16_t kCustomExtensionValue = 1234;
438 static void *const kCustomExtensionAddArg =
439 reinterpret_cast<void *>(kCustomExtensionValue);
440 static void *const kCustomExtensionParseArg =
441 reinterpret_cast<void *>(kCustomExtensionValue + 1);
442 static const char kCustomExtensionContents[] = "custom extension";
444 static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
445 const uint8_t **out, size_t *out_len,
446 int *out_alert_value, void *add_arg) {
447 if (extension_value != kCustomExtensionValue ||
448 add_arg != kCustomExtensionAddArg) {
452 if (GetTestConfig(ssl)->custom_extension_skip) {
455 if (GetTestConfig(ssl)->custom_extension_fail_add) {
459 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
460 *out_len = sizeof(kCustomExtensionContents) - 1;
465 static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
466 const uint8_t *out, void *add_arg) {
467 if (extension_value != kCustomExtensionValue ||
468 add_arg != kCustomExtensionAddArg ||
469 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
474 static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
475 const uint8_t *contents,
477 int *out_alert_value, void *parse_arg) {
478 if (extension_value != kCustomExtensionValue ||
479 parse_arg != kCustomExtensionParseArg) {
483 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
484 memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
485 *out_alert_value = SSL_AD_DECODE_ERROR;
492 // Connect returns a new socket connected to localhost on |port| or -1 on
494 static int Connect(uint16_t port) {
495 int sock = socket(AF_INET, SOCK_STREAM, 0);
497 PrintSocketError("socket");
501 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
502 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
503 PrintSocketError("setsockopt");
508 memset(&sin, 0, sizeof(sin));
509 sin.sin_family = AF_INET;
510 sin.sin_port = htons(port);
511 if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
512 PrintSocketError("inet_pton");
516 if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
518 PrintSocketError("connect");
527 explicit SocketCloser(int sock) : sock_(sock) {}
529 // Half-close and drain the socket before releasing it. This seems to be
530 // necessary for graceful shutdown on Windows. It will also avoid write
531 // failures in the test runner.
532 #if defined(OPENSSL_WINDOWS)
533 shutdown(sock_, SD_SEND);
535 shutdown(sock_, SHUT_WR);
539 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
550 static bssl::UniquePtr<SSL_CTX> SetupCtx(const TestConfig *config) {
551 bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(
552 config->is_dtls ? DTLS_method() : TLS_method()));
557 SSL_CTX_set_security_level(ssl_ctx.get(), 0);
559 /* Disabled for now until we have some TLS1.3 support */
560 // Enable TLS 1.3 for tests.
561 if (!config->is_dtls &&
562 !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION)) {
567 std::string cipher_list = "ALL";
568 if (!config->cipher.empty()) {
569 cipher_list = config->cipher;
570 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
572 if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
576 if (!config->cipher_tls10.empty() || !config->cipher_tls11.empty()) {
577 fprintf(stderr, "version-specific cipher lists not supported.\n");
583 if (config->use_sparse_dh_prime) {
588 if (p == NULL || g == NULL || tmpdh == NULL) {
594 // This prime number is 2^1024 + 643 – a value just above a power of two.
595 // Because of its form, values modulo it are essentially certain to be one
596 // byte shorter. This is used to test padding of these values.
599 "1000000000000000000000000000000000000000000000000000000000000000"
600 "0000000000000000000000000000000000000000000000000000000000000000"
601 "0000000000000000000000000000000000000000000000000000000000000000"
602 "0000000000000000000000000000000000000000000000000000000000000028"
604 !BN_set_word(g, 2)) {
610 DH_set0_pqg(tmpdh, p, NULL, g);
612 tmpdh = DH_get_2048_256();
615 bssl::UniquePtr<DH> dh(tmpdh);
617 if (!dh || !SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
621 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
623 if (config->use_old_client_cert_callback) {
624 SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
627 SSL_CTX_set_next_protos_advertised_cb(
628 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
629 if (!config->select_next_proto.empty()) {
630 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
634 if (!config->select_alpn.empty() || config->decline_alpn) {
635 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
638 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
639 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
641 if (config->use_ticket_callback) {
642 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
645 if (config->enable_client_custom_extension &&
646 !SSL_CTX_add_client_custom_ext(
647 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
648 CustomExtensionFreeCallback, kCustomExtensionAddArg,
649 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
653 if (config->enable_server_custom_extension &&
654 !SSL_CTX_add_server_custom_ext(
655 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
656 CustomExtensionFreeCallback, kCustomExtensionAddArg,
657 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
661 if (config->verify_fail) {
662 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
664 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
667 if (!config->signed_cert_timestamps.empty()) {
668 fprintf(stderr, "SCTs not supported.\n");
672 if (config->use_null_client_ca_list) {
673 SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
679 // RetryAsync is called after a failed operation on |ssl| with return code
680 // |ret|. If the operation should be retried, it simulates one asynchronous
681 // event and returns true. Otherwise it returns false.
682 static bool RetryAsync(SSL *ssl, int ret) {
683 // No error; don't retry.
688 TestState *test_state = GetTestState(ssl);
689 assert(GetTestConfig(ssl)->async);
691 if (test_state->packeted_bio != nullptr &&
692 PacketedBioAdvanceClock(test_state->packeted_bio)) {
693 // The DTLS retransmit logic silently ignores write failures. So the test
694 // may progress, allow writes through synchronously.
695 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
696 int timeout_ret = DTLSv1_handle_timeout(ssl);
697 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
699 if (timeout_ret < 0) {
700 fprintf(stderr, "Error retransmitting.\n");
706 // See if we needed to read or write more. If so, allow one byte through on
707 // the appropriate end to maximally stress the state machine.
708 switch (SSL_get_error(ssl, ret)) {
709 case SSL_ERROR_WANT_READ:
710 AsyncBioAllowRead(test_state->async_bio, 1);
712 case SSL_ERROR_WANT_WRITE:
713 AsyncBioAllowWrite(test_state->async_bio, 1);
715 case SSL_ERROR_WANT_X509_LOOKUP:
716 test_state->cert_ready = true;
723 // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
724 // the result value of the final |SSL_read| call.
725 static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
726 const TestConfig *config = GetTestConfig(ssl);
727 TestState *test_state = GetTestState(ssl);
731 // The DTLS retransmit logic silently ignores write failures. So the test
732 // may progress, allow writes through synchronously. |SSL_read| may
733 // trigger a retransmit, so disconnect the write quota.
734 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
736 ret = config->peek_then_read ? SSL_peek(ssl, out, max_out)
737 : SSL_read(ssl, out, max_out);
739 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
741 } while (config->async && RetryAsync(ssl, ret));
743 if (config->peek_then_read && ret > 0) {
744 std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
746 // SSL_peek should synchronously return the same data.
747 int ret2 = SSL_peek(ssl, buf.get(), ret);
749 memcmp(buf.get(), out, ret) != 0) {
750 fprintf(stderr, "First and second SSL_peek did not match.\n");
754 // SSL_read should synchronously return the same data and consume it.
755 ret2 = SSL_read(ssl, buf.get(), ret);
757 memcmp(buf.get(), out, ret) != 0) {
758 fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
766 // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
767 // operations. It returns the result of the final |SSL_write| call.
768 static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
769 const TestConfig *config = GetTestConfig(ssl);
772 ret = SSL_write(ssl, in, in_len);
777 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
781 // DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
782 // returns the result of the final |SSL_shutdown| call.
783 static int DoShutdown(SSL *ssl) {
784 const TestConfig *config = GetTestConfig(ssl);
787 ret = SSL_shutdown(ssl);
788 } while (config->async && RetryAsync(ssl, ret));
792 static uint16_t GetProtocolVersion(const SSL *ssl) {
793 uint16_t version = SSL_version(ssl);
794 if (!SSL_is_dtls(ssl)) {
797 return 0x0201 + ~version;
800 // CheckHandshakeProperties checks, immediately after |ssl| completes its
801 // initial handshake (or False Starts), whether all the properties are
802 // consistent with the test configuration and invariants.
803 static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
804 const TestConfig *config = GetTestConfig(ssl);
806 if (SSL_get_current_cipher(ssl) == nullptr) {
807 fprintf(stderr, "null cipher after handshake\n");
812 (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
813 fprintf(stderr, "session was%s reused\n",
814 SSL_session_reused(ssl) ? "" : " not");
818 bool expect_handshake_done = is_resume || !config->false_start;
819 if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
820 fprintf(stderr, "handshake was%s completed\n",
821 GetTestState(ssl)->handshake_done ? "" : " not");
825 if (expect_handshake_done && !config->is_server) {
826 bool expect_new_session =
827 !config->expect_no_session &&
828 (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
829 // Session tickets are sent post-handshake in TLS 1.3.
830 GetProtocolVersion(ssl) < TLS1_3_VERSION;
831 if (expect_new_session != GetTestState(ssl)->got_new_session) {
833 "new session was%s cached, but we expected the opposite\n",
834 GetTestState(ssl)->got_new_session ? "" : " not");
839 if (!config->expected_server_name.empty()) {
840 const char *server_name =
841 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
842 if (server_name != config->expected_server_name) {
843 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
844 server_name, config->expected_server_name.c_str());
849 if (!config->expected_next_proto.empty()) {
850 const uint8_t *next_proto;
851 unsigned next_proto_len;
852 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
853 if (next_proto_len != config->expected_next_proto.size() ||
854 memcmp(next_proto, config->expected_next_proto.data(),
855 next_proto_len) != 0) {
856 fprintf(stderr, "negotiated next proto mismatch\n");
861 if (!config->expected_alpn.empty()) {
862 const uint8_t *alpn_proto;
863 unsigned alpn_proto_len;
864 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
865 if (alpn_proto_len != config->expected_alpn.size() ||
866 memcmp(alpn_proto, config->expected_alpn.data(),
867 alpn_proto_len) != 0) {
868 fprintf(stderr, "negotiated alpn proto mismatch\n");
873 if (config->expect_extended_master_secret) {
874 if (!SSL_get_extms_support(ssl)) {
875 fprintf(stderr, "No EMS for connection when expected");
880 if (config->expect_verify_result) {
881 int expected_verify_result = config->verify_fail ?
882 X509_V_ERR_APPLICATION_VERIFICATION :
885 if (SSL_get_verify_result(ssl) != expected_verify_result) {
886 fprintf(stderr, "Wrong certificate verification result\n");
891 if (!config->psk.empty()) {
892 if (SSL_get_peer_cert_chain(ssl) != nullptr) {
893 fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
896 } else if (!config->is_server || config->require_any_client_certificate) {
897 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
898 fprintf(stderr, "Received no peer certificate but expected one.\n");
906 // DoExchange runs a test SSL exchange against the peer. On success, it returns
907 // true and sets |*out_session| to the negotiated SSL session. If the test is a
908 // resumption attempt, |is_resume| is true and |session| is the session from the
909 // previous exchange.
910 static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
911 SSL_CTX *ssl_ctx, const TestConfig *config,
912 bool is_resume, SSL_SESSION *session) {
913 bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
918 if (!SetTestConfig(ssl.get(), config) ||
919 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
923 if (config->fallback_scsv &&
924 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
927 // Install the certificate synchronously if nothing else will handle it.
928 if (!config->use_early_callback &&
929 !config->use_old_client_cert_callback &&
931 !InstallCertificate(ssl.get())) {
934 SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
935 if (config->require_any_client_certificate) {
936 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
939 if (config->verify_peer) {
940 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
942 if (config->false_start) {
943 fprintf(stderr, "False Start not supported\n");
946 if (config->partial_write) {
947 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
949 if (config->no_tls13) {
950 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
952 if (config->no_tls12) {
953 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
955 if (config->no_tls11) {
956 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
958 if (config->no_tls1) {
959 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
961 if (config->no_ssl3) {
962 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
964 if (!config->expected_channel_id.empty()) {
965 fprintf(stderr, "Channel ID not supported\n");
968 if (!config->send_channel_id.empty()) {
969 fprintf(stderr, "Channel ID not supported\n");
972 if (!config->host_name.empty() &&
973 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
976 if (!config->advertise_alpn.empty() &&
977 SSL_set_alpn_protos(ssl.get(),
978 (const uint8_t *)config->advertise_alpn.data(),
979 config->advertise_alpn.size()) != 0) {
982 if (!config->psk.empty()) {
983 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
984 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
986 if (!config->psk_identity.empty() &&
987 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
990 if (!config->srtp_profiles.empty() &&
991 SSL_set_tlsext_use_srtp(ssl.get(), config->srtp_profiles.c_str())) {
994 if (config->enable_ocsp_stapling) {
995 fprintf(stderr, "OCSP stapling not supported (with the same API).\n");
998 if (config->enable_signed_cert_timestamps) {
999 fprintf(stderr, "SCTs not supported (with the same API).\n");
1002 if (config->min_version != 0 &&
1003 !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) {
1006 if (config->max_version != 0 &&
1007 !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) {
1010 if (config->mtu != 0) {
1011 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
1012 SSL_set_mtu(ssl.get(), config->mtu);
1014 if (config->install_ddos_callback) {
1015 fprintf(stderr, "DDoS callback not supported.\n");
1018 if (config->renegotiate_once) {
1019 fprintf(stderr, "renegotiate_once not supported.\n");
1022 if (config->renegotiate_freely) {
1023 // This is always on for OpenSSL.
1025 if (config->renegotiate_ignore) {
1026 fprintf(stderr, "renegotiate_ignore not supported.\n");
1029 if (!config->check_close_notify) {
1030 SSL_set_quiet_shutdown(ssl.get(), 1);
1032 if (config->disable_npn) {
1033 fprintf(stderr, "SSL_OP_DISABLE_NPN not supported.\n");
1036 if (config->p384_only) {
1037 int nid = NID_secp384r1;
1038 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
1042 if (config->enable_all_curves) {
1043 static const int kAllCurves[] = {
1044 NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_X25519,
1046 if (!SSL_set1_curves(ssl.get(), kAllCurves,
1047 OPENSSL_ARRAY_SIZE(kAllCurves))) {
1051 if (config->initial_timeout_duration_ms > 0) {
1052 fprintf(stderr, "Setting DTLS initial timeout duration not supported.\n");
1055 if (config->max_cert_list > 0) {
1056 SSL_set_max_cert_list(ssl.get(), config->max_cert_list);
1059 int sock = Connect(config->port);
1063 SocketCloser closer(sock);
1065 bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
1069 if (config->is_dtls) {
1070 bssl::UniquePtr<BIO> packeted = PacketedBioCreate(!config->async);
1074 GetTestState(ssl.get())->packeted_bio = packeted.get();
1075 BIO_push(packeted.get(), bio.release());
1076 bio = std::move(packeted);
1078 if (config->async) {
1079 bssl::UniquePtr<BIO> async_scoped =
1080 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
1081 if (!async_scoped) {
1084 BIO_push(async_scoped.get(), bio.release());
1085 GetTestState(ssl.get())->async_bio = async_scoped.get();
1086 bio = std::move(async_scoped);
1088 SSL_set_bio(ssl.get(), bio.get(), bio.get());
1089 bio.release(); // SSL_set_bio takes ownership.
1091 if (session != NULL) {
1092 if (!config->is_server) {
1093 if (SSL_set_session(ssl.get(), session) != 1) {
1100 // KNOWN BUG: OpenSSL's SSL_get_current_cipher behaves incorrectly when
1101 // offering resumption.
1102 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1103 fprintf(stderr, "non-null cipher before handshake\n");
1109 if (config->implicit_handshake) {
1110 if (config->is_server) {
1111 SSL_set_accept_state(ssl.get());
1113 SSL_set_connect_state(ssl.get());
1117 if (config->is_server) {
1118 ret = SSL_accept(ssl.get());
1120 ret = SSL_connect(ssl.get());
1122 } while (config->async && RetryAsync(ssl.get(), ret));
1124 !CheckHandshakeProperties(ssl.get(), is_resume)) {
1128 // Reset the state to assert later that the callback isn't called in
1130 GetTestState(ssl.get())->got_new_session = false;
1133 if (config->export_keying_material > 0) {
1134 std::vector<uint8_t> result(
1135 static_cast<size_t>(config->export_keying_material));
1136 if (SSL_export_keying_material(
1137 ssl.get(), result.data(), result.size(),
1138 config->export_label.data(), config->export_label.size(),
1139 reinterpret_cast<const uint8_t*>(config->export_context.data()),
1140 config->export_context.size(), config->use_export_context) != 1) {
1141 fprintf(stderr, "failed to export keying material\n");
1144 if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1149 if (config->tls_unique) {
1150 fprintf(stderr, "tls_unique not supported\n");
1154 if (config->send_alert) {
1155 fprintf(stderr, "Sending an alert not supported\n");
1159 if (config->write_different_record_sizes) {
1160 if (config->is_dtls) {
1161 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
1164 // This mode writes a number of different record sizes in an attempt to
1165 // trip up the CBC record splitting code.
1166 static const size_t kBufLen = 32769;
1167 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1168 memset(buf.get(), 0x42, kBufLen);
1169 static const size_t kRecordSizes[] = {
1170 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
1171 for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
1172 const size_t len = kRecordSizes[i];
1173 if (len > kBufLen) {
1174 fprintf(stderr, "Bad kRecordSizes value.\n");
1177 if (WriteAll(ssl.get(), buf.get(), len) < 0) {
1182 if (config->shim_writes_first) {
1183 if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1188 if (!config->shim_shuts_down) {
1190 static const size_t kBufLen = 16384;
1191 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1193 // Read only 512 bytes at a time in TLS to ensure records may be
1194 // returned in multiple reads.
1195 int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
1196 int err = SSL_get_error(ssl.get(), n);
1197 if (err == SSL_ERROR_ZERO_RETURN ||
1198 (n == 0 && err == SSL_ERROR_SYSCALL)) {
1200 fprintf(stderr, "Invalid SSL_get_error output\n");
1203 // Stop on either clean or unclean shutdown.
1205 } else if (err != SSL_ERROR_NONE) {
1207 fprintf(stderr, "Invalid SSL_get_error output\n");
1212 // Successfully read data.
1214 fprintf(stderr, "Invalid SSL_get_error output\n");
1218 // After a successful read, with or without False Start, the handshake
1219 // must be complete.
1220 if (!GetTestState(ssl.get())->handshake_done) {
1221 fprintf(stderr, "handshake was not completed after SSL_read\n");
1225 for (int i = 0; i < n; i++) {
1228 if (WriteAll(ssl.get(), buf.get(), n) < 0) {
1235 if (!config->is_server && !config->false_start &&
1236 !config->implicit_handshake &&
1237 // Session tickets are sent post-handshake in TLS 1.3.
1238 GetProtocolVersion(ssl.get()) < TLS1_3_VERSION &&
1239 GetTestState(ssl.get())->got_new_session) {
1240 fprintf(stderr, "new session was established after the handshake\n");
1244 if (GetProtocolVersion(ssl.get()) >= TLS1_3_VERSION && !config->is_server) {
1245 bool expect_new_session =
1246 !config->expect_no_session && !config->shim_shuts_down;
1247 if (expect_new_session != GetTestState(ssl.get())->got_new_session) {
1249 "new session was%s cached, but we expected the opposite\n",
1250 GetTestState(ssl.get())->got_new_session ? "" : " not");
1256 *out_session = std::move(GetTestState(ssl.get())->new_session);
1259 ret = DoShutdown(ssl.get());
1261 if (config->shim_shuts_down && config->check_close_notify) {
1262 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1263 // it returns zero when our close_notify is sent, then one when the peer's
1266 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1269 ret = DoShutdown(ssl.get());
1273 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1277 if (SSL_total_renegotiations(ssl.get()) !=
1278 config->expect_total_renegotiations) {
1279 fprintf(stderr, "Expected %d renegotiations, got %ld\n",
1280 config->expect_total_renegotiations,
1281 SSL_total_renegotiations(ssl.get()));
1288 class StderrDelimiter {
1290 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
1293 static int Main(int argc, char **argv) {
1294 // To distinguish ASan's output from ours, add a trailing message to stderr.
1295 // Anything following this line will be considered an error.
1296 StderrDelimiter delimiter;
1298 #if defined(OPENSSL_WINDOWS)
1299 /* Initialize Winsock. */
1300 WORD wsa_version = MAKEWORD(2, 2);
1302 int wsa_err = WSAStartup(wsa_version, &wsa_data);
1304 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1307 if (wsa_data.wVersion != wsa_version) {
1308 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1312 signal(SIGPIPE, SIG_IGN);
1315 OPENSSL_init_crypto(0, NULL);
1316 OPENSSL_init_ssl(0, NULL);
1317 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
1318 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
1319 if (g_config_index < 0 || g_state_index < 0) {
1324 if (!ParseConfig(argc - 1, argv + 1, &config)) {
1325 return Usage(argv[0]);
1328 bssl::UniquePtr<SSL_CTX> ssl_ctx = SetupCtx(&config);
1330 ERR_print_errors_fp(stderr);
1334 bssl::UniquePtr<SSL_SESSION> session;
1335 for (int i = 0; i < config.resume_count + 1; i++) {
1336 bool is_resume = i > 0;
1337 if (is_resume && !config.is_server && !session) {
1338 fprintf(stderr, "No session to offer.\n");
1342 bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
1343 if (!DoExchange(&session, ssl_ctx.get(), &config, is_resume,
1344 offer_session.get())) {
1345 fprintf(stderr, "Connection %d failed.\n", i + 1);
1346 ERR_print_errors_fp(stderr);
1356 int main(int argc, char **argv) {
1357 return bssl::Main(argc, argv);