2 * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
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
10 #if !defined(__STDC_FORMAT_MACROS)
11 #define __STDC_FORMAT_MACROS
14 #include "packeted_bio.h"
15 #include <openssl/e_os2.h>
17 #if !defined(OPENSSL_SYS_WINDOWS)
18 #include <arpa/inet.h>
19 #include <netinet/in.h>
20 #include <netinet/tcp.h>
22 #include <sys/socket.h>
27 OPENSSL_MSVC_PRAGMA(warning(push, 3))
30 OPENSSL_MSVC_PRAGMA(warning(pop))
32 OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
39 #include <openssl/bio.h>
40 #include <openssl/buffer.h>
41 #include <openssl/bn.h>
42 #include <openssl/crypto.h>
43 #include <openssl/dh.h>
44 #include <openssl/err.h>
45 #include <openssl/evp.h>
46 #include <openssl/hmac.h>
47 #include <openssl/objects.h>
48 #include <openssl/rand.h>
49 #include <openssl/ssl.h>
50 #include <openssl/x509.h>
56 #include "async_bio.h"
57 #include "test_config.h"
61 #if !defined(OPENSSL_SYS_WINDOWS)
62 static int closesocket(int sock) {
66 static void PrintSocketError(const char *func) {
70 static void PrintSocketError(const char *func) {
71 fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
75 static int Usage(const char *program) {
76 fprintf(stderr, "Usage: %s [flags...]\n", program);
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;
95 static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
96 int index, long argl, void *argp) {
97 delete ((TestState *)ptr);
100 static int g_config_index = 0;
101 static int g_state_index = 0;
103 static bool SetTestConfig(SSL *ssl, const TestConfig *config) {
104 return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
107 static const TestConfig *GetTestConfig(const SSL *ssl) {
108 return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
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) {
120 static TestState *GetTestState(const SSL *ssl) {
121 return (TestState *)SSL_get_ex_data(ssl, g_state_index);
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())) {
129 return bssl::UniquePtr<X509>(PEM_read_bio_X509(bio.get(), NULL, NULL, NULL));
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())) {
137 return bssl::UniquePtr<EVP_PKEY>(
138 PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
143 void operator()(T *buf) {
148 static bool GetCertificate(SSL *ssl, bssl::UniquePtr<X509> *out_x509,
149 bssl::UniquePtr<EVP_PKEY> *out_pkey) {
150 const TestConfig *config = GetTestConfig(ssl);
152 if (!config->key_file.empty()) {
153 *out_pkey = LoadPrivateKey(config->key_file.c_str());
158 if (!config->cert_file.empty()) {
159 *out_x509 = LoadCertificate(config->cert_file.c_str());
167 static bool InstallCertificate(SSL *ssl) {
168 bssl::UniquePtr<X509> x509;
169 bssl::UniquePtr<EVP_PKEY> pkey;
170 if (!GetCertificate(ssl, &x509, &pkey)) {
174 if (pkey && !SSL_use_PrivateKey(ssl, pkey.get())) {
178 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
185 static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
186 if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
190 bssl::UniquePtr<X509> x509;
191 bssl::UniquePtr<EVP_PKEY> pkey;
192 if (!GetCertificate(ssl, &x509, &pkey)) {
196 // Return zero for no certificate.
201 // Asynchronous private keys are not supported with client_cert_cb.
202 *out_x509 = x509.release();
203 *out_pkey = pkey.release();
207 static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
211 static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
212 X509_STORE_CTX_set_error(store_ctx, X509_V_ERR_APPLICATION_VERIFICATION);
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;
223 *out = (const uint8_t*)config->advertise_npn.data();
224 *out_len = config->advertise_npn.size();
225 return SSL_TLSEXT_ERR_OK;
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;
235 *out = (uint8_t*)config->select_next_proto.data();
236 *outlen = config->select_next_proto.size();
237 return SSL_TLSEXT_ERR_OK;
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");
247 GetTestState(ssl)->alpn_select_done = true;
249 const TestConfig *config = GetTestConfig(ssl);
250 if (config->decline_alpn) {
251 return SSL_TLSEXT_ERR_NOACK;
254 if (!config->expected_advertised_alpn.empty() &&
255 (config->expected_advertised_alpn.size() != inlen ||
256 memcmp(config->expected_advertised_alpn.data(),
258 fprintf(stderr, "bad ALPN select callback inputs\n");
262 *out = (const uint8_t*)config->select_alpn.data();
263 *outlen = config->select_alpn.size();
264 return SSL_TLSEXT_ERR_OK;
267 static unsigned PskClientCallback(SSL *ssl, const char *hint,
269 unsigned max_identity_len,
270 uint8_t *out_psk, unsigned max_psk_len) {
271 const TestConfig *config = GetTestConfig(ssl);
273 if (config->psk_identity.empty()) {
274 if (hint != nullptr) {
275 fprintf(stderr, "Server PSK hint was non-null.\n");
278 } else if (hint == nullptr ||
279 strcmp(hint, config->psk_identity.c_str()) != 0) {
280 fprintf(stderr, "Server PSK hint did not match.\n");
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");
291 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
293 memcpy(out_psk, config->psk.data(), config->psk.size());
294 return config->psk.size();
297 static unsigned PskServerCallback(SSL *ssl, const char *identity,
298 uint8_t *out_psk, unsigned max_psk_len) {
299 const TestConfig *config = GetTestConfig(ssl);
301 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
302 fprintf(stderr, "Client PSK identity did not match.\n");
306 if (config->psk.size() > max_psk_len) {
307 fprintf(stderr, "PSK buffers too small\n");
311 memcpy(out_psk, config->psk.data(), config->psk.size());
312 return config->psk.size();
315 static int CertCallback(SSL *ssl, void *arg) {
316 const TestConfig *config = GetTestConfig(ssl);
318 // Check the CertificateRequest metadata is as expected.
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");
335 // The certificate will be installed via other means.
336 if (!config->async ||
337 config->use_old_client_cert_callback) {
341 if (!GetTestState(ssl)->cert_ready) {
344 if (!InstallCertificate(ssl)) {
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
358 GetTestState(ssl)->handshake_done = true;
360 // Callbacks may be called again on a new handshake.
361 GetTestState(ssl)->ticket_decrypt_done = false;
362 GetTestState(ssl)->alpn_select_done = false;
366 static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
367 GetTestState(ssl)->got_new_session = true;
368 GetTestState(ssl)->new_session.reset(session);
372 static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
373 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
376 if (GetTestState(ssl)->ticket_decrypt_done) {
377 fprintf(stderr, "TicketKeyCallback called after completion.\n");
381 GetTestState(ssl)->ticket_decrypt_done = true;
384 // This is just test code, so use the all-zeros key.
385 static const uint8_t kZeros[16] = {0};
388 memcpy(key_name, kZeros, sizeof(kZeros));
390 } else if (memcmp(key_name, kZeros, 16) != 0) {
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)) {
400 return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
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";
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) {
422 if (GetTestConfig(ssl)->custom_extension_skip) {
425 if (GetTestConfig(ssl)->custom_extension_fail_add) {
429 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
430 *out_len = sizeof(kCustomExtensionContents) - 1;
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)) {
444 static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
445 const uint8_t *contents,
447 int *out_alert_value, void *parse_arg) {
448 if (extension_value != kCustomExtensionValue ||
449 parse_arg != kCustomExtensionParseArg) {
453 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
454 memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
455 *out_alert_value = SSL_AD_DECODE_ERROR;
462 // Connect returns a new socket connected to localhost on |port| or -1 on
464 static int Connect(uint16_t port) {
465 int sock = socket(AF_INET, SOCK_STREAM, 0);
467 PrintSocketError("socket");
471 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
472 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
473 PrintSocketError("setsockopt");
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");
486 if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
488 PrintSocketError("connect");
497 explicit SocketCloser(int sock) : sock_(sock) {}
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);
505 shutdown(sock_, SHUT_WR);
509 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
520 static bssl::UniquePtr<SSL_CTX> SetupCtx(const TestConfig *config) {
521 const char sess_id_ctx[] = "ossl_shim";
522 bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(
523 config->is_dtls ? DTLS_method() : TLS_method()));
528 SSL_CTX_set_security_level(ssl_ctx.get(), 0);
530 /* Disabled for now until we have some TLS1.3 support */
531 // Enable TLS 1.3 for tests.
532 if (!config->is_dtls &&
533 !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION)) {
538 std::string cipher_list = "ALL";
539 if (!config->cipher.empty()) {
540 cipher_list = config->cipher;
541 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
543 if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
549 if (config->use_sparse_dh_prime) {
554 if (p == NULL || g == NULL || tmpdh == NULL) {
560 // This prime number is 2^1024 + 643 – a value just above a power of two.
561 // Because of its form, values modulo it are essentially certain to be one
562 // byte shorter. This is used to test padding of these values.
565 "1000000000000000000000000000000000000000000000000000000000000000"
566 "0000000000000000000000000000000000000000000000000000000000000000"
567 "0000000000000000000000000000000000000000000000000000000000000000"
568 "0000000000000000000000000000000000000000000000000000000000000028"
570 !BN_set_word(g, 2)) {
576 DH_set0_pqg(tmpdh, p, NULL, g);
578 tmpdh = DH_get_2048_256();
581 bssl::UniquePtr<DH> dh(tmpdh);
583 if (!dh || !SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
587 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
589 if (config->use_old_client_cert_callback) {
590 SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
593 SSL_CTX_set_npn_advertised_cb(
594 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
595 if (!config->select_next_proto.empty()) {
596 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
600 if (!config->select_alpn.empty() || config->decline_alpn) {
601 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
604 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
605 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
607 if (config->use_ticket_callback) {
608 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
611 if (config->enable_client_custom_extension &&
612 !SSL_CTX_add_client_custom_ext(
613 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
614 CustomExtensionFreeCallback, kCustomExtensionAddArg,
615 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
619 if (config->enable_server_custom_extension &&
620 !SSL_CTX_add_server_custom_ext(
621 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
622 CustomExtensionFreeCallback, kCustomExtensionAddArg,
623 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
627 if (config->verify_fail) {
628 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
630 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
633 if (config->use_null_client_ca_list) {
634 SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
637 if (!SSL_CTX_set_session_id_context(ssl_ctx.get(),
638 (const unsigned char *)sess_id_ctx,
639 sizeof(sess_id_ctx) - 1))
645 // RetryAsync is called after a failed operation on |ssl| with return code
646 // |ret|. If the operation should be retried, it simulates one asynchronous
647 // event and returns true. Otherwise it returns false.
648 static bool RetryAsync(SSL *ssl, int ret) {
649 // No error; don't retry.
654 TestState *test_state = GetTestState(ssl);
655 assert(GetTestConfig(ssl)->async);
657 if (test_state->packeted_bio != nullptr &&
658 PacketedBioAdvanceClock(test_state->packeted_bio)) {
659 // The DTLS retransmit logic silently ignores write failures. So the test
660 // may progress, allow writes through synchronously.
661 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
662 int timeout_ret = DTLSv1_handle_timeout(ssl);
663 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
665 if (timeout_ret < 0) {
666 fprintf(stderr, "Error retransmitting.\n");
672 // See if we needed to read or write more. If so, allow one byte through on
673 // the appropriate end to maximally stress the state machine.
674 switch (SSL_get_error(ssl, ret)) {
675 case SSL_ERROR_WANT_READ:
676 AsyncBioAllowRead(test_state->async_bio, 1);
678 case SSL_ERROR_WANT_WRITE:
679 AsyncBioAllowWrite(test_state->async_bio, 1);
681 case SSL_ERROR_WANT_X509_LOOKUP:
682 test_state->cert_ready = true;
689 // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
690 // the result value of the final |SSL_read| call.
691 static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
692 const TestConfig *config = GetTestConfig(ssl);
693 TestState *test_state = GetTestState(ssl);
697 // The DTLS retransmit logic silently ignores write failures. So the test
698 // may progress, allow writes through synchronously. |SSL_read| may
699 // trigger a retransmit, so disconnect the write quota.
700 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
702 ret = config->peek_then_read ? SSL_peek(ssl, out, max_out)
703 : SSL_read(ssl, out, max_out);
705 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
707 } while (config->async && RetryAsync(ssl, ret));
709 if (config->peek_then_read && ret > 0) {
710 std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
712 // SSL_peek should synchronously return the same data.
713 int ret2 = SSL_peek(ssl, buf.get(), ret);
715 memcmp(buf.get(), out, ret) != 0) {
716 fprintf(stderr, "First and second SSL_peek did not match.\n");
720 // SSL_read should synchronously return the same data and consume it.
721 ret2 = SSL_read(ssl, buf.get(), ret);
723 memcmp(buf.get(), out, ret) != 0) {
724 fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
732 // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
733 // operations. It returns the result of the final |SSL_write| call.
734 static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
735 const TestConfig *config = GetTestConfig(ssl);
738 ret = SSL_write(ssl, in, in_len);
743 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
747 // DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
748 // returns the result of the final |SSL_shutdown| call.
749 static int DoShutdown(SSL *ssl) {
750 const TestConfig *config = GetTestConfig(ssl);
753 ret = SSL_shutdown(ssl);
754 } while (config->async && RetryAsync(ssl, ret));
758 static uint16_t GetProtocolVersion(const SSL *ssl) {
759 uint16_t version = SSL_version(ssl);
760 if (!SSL_is_dtls(ssl)) {
763 return 0x0201 + ~version;
766 // CheckHandshakeProperties checks, immediately after |ssl| completes its
767 // initial handshake (or False Starts), whether all the properties are
768 // consistent with the test configuration and invariants.
769 static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
770 const TestConfig *config = GetTestConfig(ssl);
772 if (SSL_get_current_cipher(ssl) == nullptr) {
773 fprintf(stderr, "null cipher after handshake\n");
778 (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
779 fprintf(stderr, "session was%s reused\n",
780 SSL_session_reused(ssl) ? "" : " not");
784 if (!GetTestState(ssl)->handshake_done) {
785 fprintf(stderr, "handshake was not completed\n");
789 if (!config->is_server) {
790 bool expect_new_session =
791 !config->expect_no_session &&
792 (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
793 // Session tickets are sent post-handshake in TLS 1.3.
794 GetProtocolVersion(ssl) < TLS1_3_VERSION;
795 if (expect_new_session != GetTestState(ssl)->got_new_session) {
797 "new session was%s cached, but we expected the opposite\n",
798 GetTestState(ssl)->got_new_session ? "" : " not");
803 if (!config->expected_server_name.empty()) {
804 const char *server_name =
805 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
806 if (server_name != config->expected_server_name) {
807 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
808 server_name, config->expected_server_name.c_str());
813 if (!config->expected_next_proto.empty()) {
814 const uint8_t *next_proto;
815 unsigned next_proto_len;
816 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
817 if (next_proto_len != config->expected_next_proto.size() ||
818 memcmp(next_proto, config->expected_next_proto.data(),
819 next_proto_len) != 0) {
820 fprintf(stderr, "negotiated next proto mismatch\n");
825 if (!config->expected_alpn.empty()) {
826 const uint8_t *alpn_proto;
827 unsigned alpn_proto_len;
828 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
829 if (alpn_proto_len != config->expected_alpn.size() ||
830 memcmp(alpn_proto, config->expected_alpn.data(),
831 alpn_proto_len) != 0) {
832 fprintf(stderr, "negotiated alpn proto mismatch\n");
837 if (config->expect_extended_master_secret) {
838 if (!SSL_get_extms_support(ssl)) {
839 fprintf(stderr, "No EMS for connection when expected");
844 if (config->expect_verify_result) {
845 int expected_verify_result = config->verify_fail ?
846 X509_V_ERR_APPLICATION_VERIFICATION :
849 if (SSL_get_verify_result(ssl) != expected_verify_result) {
850 fprintf(stderr, "Wrong certificate verification result\n");
855 if (!config->psk.empty()) {
856 if (SSL_get_peer_cert_chain(ssl) != nullptr) {
857 fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
860 } else if (!config->is_server || config->require_any_client_certificate) {
861 if (SSL_get_peer_certificate(ssl) == nullptr) {
862 fprintf(stderr, "Received no peer certificate but expected one.\n");
870 // DoExchange runs a test SSL exchange against the peer. On success, it returns
871 // true and sets |*out_session| to the negotiated SSL session. If the test is a
872 // resumption attempt, |is_resume| is true and |session| is the session from the
873 // previous exchange.
874 static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
875 SSL_CTX *ssl_ctx, const TestConfig *config,
876 bool is_resume, SSL_SESSION *session) {
877 bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
882 if (!SetTestConfig(ssl.get(), config) ||
883 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
887 if (config->fallback_scsv &&
888 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
891 // Install the certificate synchronously if nothing else will handle it.
892 if (!config->use_old_client_cert_callback &&
894 !InstallCertificate(ssl.get())) {
897 SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
898 if (config->require_any_client_certificate) {
899 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
902 if (config->verify_peer) {
903 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
905 if (config->partial_write) {
906 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
908 if (config->no_tls13) {
909 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
911 if (config->no_tls12) {
912 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
914 if (config->no_tls11) {
915 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
917 if (config->no_tls1) {
918 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
920 if (config->no_ssl3) {
921 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
923 if (!config->host_name.empty() &&
924 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
927 if (!config->advertise_alpn.empty() &&
928 SSL_set_alpn_protos(ssl.get(),
929 (const uint8_t *)config->advertise_alpn.data(),
930 config->advertise_alpn.size()) != 0) {
933 if (!config->psk.empty()) {
934 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
935 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
937 if (!config->psk_identity.empty() &&
938 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
941 if (!config->srtp_profiles.empty() &&
942 SSL_set_tlsext_use_srtp(ssl.get(), config->srtp_profiles.c_str())) {
945 if (config->min_version != 0 &&
946 !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) {
949 if (config->max_version != 0 &&
950 !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) {
953 if (config->mtu != 0) {
954 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
955 SSL_set_mtu(ssl.get(), config->mtu);
957 if (config->renegotiate_freely) {
958 // This is always on for OpenSSL.
960 if (!config->check_close_notify) {
961 SSL_set_quiet_shutdown(ssl.get(), 1);
963 if (config->p384_only) {
964 int nid = NID_secp384r1;
965 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
969 if (config->enable_all_curves) {
970 static const int kAllCurves[] = {
971 NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_X25519,
973 if (!SSL_set1_curves(ssl.get(), kAllCurves,
974 OPENSSL_ARRAY_SIZE(kAllCurves))) {
978 if (config->max_cert_list > 0) {
979 SSL_set_max_cert_list(ssl.get(), config->max_cert_list);
982 int sock = Connect(config->port);
986 SocketCloser closer(sock);
988 bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
992 if (config->is_dtls) {
993 bssl::UniquePtr<BIO> packeted = PacketedBioCreate(!config->async);
997 GetTestState(ssl.get())->packeted_bio = packeted.get();
998 BIO_push(packeted.get(), bio.release());
999 bio = std::move(packeted);
1001 if (config->async) {
1002 bssl::UniquePtr<BIO> async_scoped =
1003 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
1004 if (!async_scoped) {
1007 BIO_push(async_scoped.get(), bio.release());
1008 GetTestState(ssl.get())->async_bio = async_scoped.get();
1009 bio = std::move(async_scoped);
1011 SSL_set_bio(ssl.get(), bio.get(), bio.get());
1012 bio.release(); // SSL_set_bio takes ownership.
1014 if (session != NULL) {
1015 if (!config->is_server) {
1016 if (SSL_set_session(ssl.get(), session) != 1) {
1023 // KNOWN BUG: OpenSSL's SSL_get_current_cipher behaves incorrectly when
1024 // offering resumption.
1025 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1026 fprintf(stderr, "non-null cipher before handshake\n");
1032 if (config->implicit_handshake) {
1033 if (config->is_server) {
1034 SSL_set_accept_state(ssl.get());
1036 SSL_set_connect_state(ssl.get());
1040 if (config->is_server) {
1041 ret = SSL_accept(ssl.get());
1043 ret = SSL_connect(ssl.get());
1045 } while (config->async && RetryAsync(ssl.get(), ret));
1047 !CheckHandshakeProperties(ssl.get(), is_resume)) {
1051 // Reset the state to assert later that the callback isn't called in
1053 GetTestState(ssl.get())->got_new_session = false;
1056 if (config->export_keying_material > 0) {
1057 std::vector<uint8_t> result(
1058 static_cast<size_t>(config->export_keying_material));
1059 if (SSL_export_keying_material(
1060 ssl.get(), result.data(), result.size(),
1061 config->export_label.data(), config->export_label.size(),
1062 reinterpret_cast<const uint8_t*>(config->export_context.data()),
1063 config->export_context.size(), config->use_export_context) != 1) {
1064 fprintf(stderr, "failed to export keying material\n");
1067 if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1072 if (config->write_different_record_sizes) {
1073 if (config->is_dtls) {
1074 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
1077 // This mode writes a number of different record sizes in an attempt to
1078 // trip up the CBC record splitting code.
1079 static const size_t kBufLen = 32769;
1080 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1081 memset(buf.get(), 0x42, kBufLen);
1082 static const size_t kRecordSizes[] = {
1083 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
1084 for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
1085 const size_t len = kRecordSizes[i];
1086 if (len > kBufLen) {
1087 fprintf(stderr, "Bad kRecordSizes value.\n");
1090 if (WriteAll(ssl.get(), buf.get(), len) < 0) {
1095 if (config->shim_writes_first) {
1096 if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1101 if (!config->shim_shuts_down) {
1103 static const size_t kBufLen = 16384;
1104 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1106 // Read only 512 bytes at a time in TLS to ensure records may be
1107 // returned in multiple reads.
1108 int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
1109 int err = SSL_get_error(ssl.get(), n);
1110 if (err == SSL_ERROR_ZERO_RETURN ||
1111 (n == 0 && err == SSL_ERROR_SYSCALL)) {
1113 fprintf(stderr, "Invalid SSL_get_error output\n");
1116 // Stop on either clean or unclean shutdown.
1118 } else if (err != SSL_ERROR_NONE) {
1120 fprintf(stderr, "Invalid SSL_get_error output\n");
1125 // Successfully read data.
1127 fprintf(stderr, "Invalid SSL_get_error output\n");
1131 // After a successful read, with or without False Start, the handshake
1132 // must be complete.
1133 if (!GetTestState(ssl.get())->handshake_done) {
1134 fprintf(stderr, "handshake was not completed after SSL_read\n");
1138 for (int i = 0; i < n; i++) {
1141 if (WriteAll(ssl.get(), buf.get(), n) < 0) {
1148 if (!config->is_server &&
1149 !config->implicit_handshake &&
1150 // Session tickets are sent post-handshake in TLS 1.3.
1151 GetProtocolVersion(ssl.get()) < TLS1_3_VERSION &&
1152 GetTestState(ssl.get())->got_new_session) {
1153 fprintf(stderr, "new session was established after the handshake\n");
1157 if (GetProtocolVersion(ssl.get()) >= TLS1_3_VERSION && !config->is_server) {
1158 bool expect_new_session =
1159 !config->expect_no_session && !config->shim_shuts_down;
1160 if (expect_new_session != GetTestState(ssl.get())->got_new_session) {
1162 "new session was%s cached, but we expected the opposite\n",
1163 GetTestState(ssl.get())->got_new_session ? "" : " not");
1169 *out_session = std::move(GetTestState(ssl.get())->new_session);
1172 ret = DoShutdown(ssl.get());
1174 if (config->shim_shuts_down && config->check_close_notify) {
1175 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1176 // it returns zero when our close_notify is sent, then one when the peer's
1179 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1182 ret = DoShutdown(ssl.get());
1186 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1190 if (SSL_total_renegotiations(ssl.get()) !=
1191 config->expect_total_renegotiations) {
1192 fprintf(stderr, "Expected %d renegotiations, got %ld\n",
1193 config->expect_total_renegotiations,
1194 SSL_total_renegotiations(ssl.get()));
1201 class StderrDelimiter {
1203 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
1206 static int Main(int argc, char **argv) {
1207 // To distinguish ASan's output from ours, add a trailing message to stderr.
1208 // Anything following this line will be considered an error.
1209 StderrDelimiter delimiter;
1211 #if defined(OPENSSL_SYS_WINDOWS)
1212 /* Initialize Winsock. */
1213 WORD wsa_version = MAKEWORD(2, 2);
1215 int wsa_err = WSAStartup(wsa_version, &wsa_data);
1217 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1220 if (wsa_data.wVersion != wsa_version) {
1221 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1225 signal(SIGPIPE, SIG_IGN);
1228 OPENSSL_init_crypto(0, NULL);
1229 OPENSSL_init_ssl(0, NULL);
1230 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
1231 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
1232 if (g_config_index < 0 || g_state_index < 0) {
1237 if (!ParseConfig(argc - 1, argv + 1, &config)) {
1238 return Usage(argv[0]);
1241 bssl::UniquePtr<SSL_CTX> ssl_ctx = SetupCtx(&config);
1243 ERR_print_errors_fp(stderr);
1247 bssl::UniquePtr<SSL_SESSION> session;
1248 for (int i = 0; i < config.resume_count + 1; i++) {
1249 bool is_resume = i > 0;
1250 if (is_resume && !config.is_server && !session) {
1251 fprintf(stderr, "No session to offer.\n");
1255 bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
1256 if (!DoExchange(&session, ssl_ctx.get(), &config, is_resume,
1257 offer_session.get())) {
1258 fprintf(stderr, "Connection %d failed.\n", i + 1);
1259 ERR_print_errors_fp(stderr);
1269 int main(int argc, char **argv) {
1270 return bssl::Main(argc, argv);