2 * Copyright 1995-2016 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 <openssl/e_os2.h>
16 #if !defined(OPENSSL_SYS_WINDOWS)
17 #include <arpa/inet.h>
18 #include <netinet/in.h>
19 #include <netinet/tcp.h>
21 #include <sys/socket.h>
26 OPENSSL_MSVC_PRAGMA(warning(push, 3))
29 OPENSSL_MSVC_PRAGMA(warning(pop))
31 OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
38 #include <openssl/bio.h>
39 #include <openssl/buffer.h>
40 #include <openssl/bn.h>
41 #include <openssl/crypto.h>
42 #include <openssl/dh.h>
43 #include <openssl/err.h>
44 #include <openssl/evp.h>
45 #include <openssl/hmac.h>
46 #include <openssl/objects.h>
47 #include <openssl/rand.h>
48 #include <openssl/ssl.h>
49 #include <openssl/x509.h>
55 #include "async_bio.h"
56 #include "packeted_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 bssl::UniquePtr<SSL_SESSION> session;
87 bool handshake_done = false;
88 // private_key is the underlying private key used when testing custom keys.
89 bssl::UniquePtr<EVP_PKEY> private_key;
90 bool got_new_session = false;
91 bssl::UniquePtr<SSL_SESSION> new_session;
92 bool ticket_decrypt_done = false;
93 bool alpn_select_done = false;
96 static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
97 int index, long argl, void *argp) {
98 delete ((TestState *)ptr);
101 static int g_config_index = 0;
102 static int g_state_index = 0;
104 static bool SetTestConfig(SSL *ssl, const TestConfig *config) {
105 return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
108 static const TestConfig *GetTestConfig(const SSL *ssl) {
109 return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
112 static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
113 // |SSL_set_ex_data| takes ownership of |state| only on success.
114 if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
121 static TestState *GetTestState(const SSL *ssl) {
122 return (TestState *)SSL_get_ex_data(ssl, g_state_index);
125 static bssl::UniquePtr<X509> LoadCertificate(const std::string &file) {
126 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
127 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
130 return bssl::UniquePtr<X509>(PEM_read_bio_X509(bio.get(), NULL, NULL, NULL));
133 static bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
134 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
135 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
138 return bssl::UniquePtr<EVP_PKEY>(
139 PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
144 void operator()(T *buf) {
149 static bool GetCertificate(SSL *ssl, bssl::UniquePtr<X509> *out_x509,
150 bssl::UniquePtr<EVP_PKEY> *out_pkey) {
151 const TestConfig *config = GetTestConfig(ssl);
153 if (!config->key_file.empty()) {
154 *out_pkey = LoadPrivateKey(config->key_file.c_str());
159 if (!config->cert_file.empty()) {
160 *out_x509 = LoadCertificate(config->cert_file.c_str());
168 static bool InstallCertificate(SSL *ssl) {
169 bssl::UniquePtr<X509> x509;
170 bssl::UniquePtr<EVP_PKEY> pkey;
171 if (!GetCertificate(ssl, &x509, &pkey)) {
175 if (pkey && !SSL_use_PrivateKey(ssl, pkey.get())) {
179 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
186 static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
187 if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
191 bssl::UniquePtr<X509> x509;
192 bssl::UniquePtr<EVP_PKEY> pkey;
193 if (!GetCertificate(ssl, &x509, &pkey)) {
197 // Return zero for no certificate.
202 // Asynchronous private keys are not supported with client_cert_cb.
203 *out_x509 = x509.release();
204 *out_pkey = pkey.release();
208 static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
212 static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
213 X509_STORE_CTX_set_error(store_ctx, X509_V_ERR_APPLICATION_VERIFICATION);
217 static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
218 unsigned int *out_len, void *arg) {
219 const TestConfig *config = GetTestConfig(ssl);
220 if (config->advertise_npn.empty()) {
221 return SSL_TLSEXT_ERR_NOACK;
224 *out = (const uint8_t*)config->advertise_npn.data();
225 *out_len = config->advertise_npn.size();
226 return SSL_TLSEXT_ERR_OK;
229 static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
230 const uint8_t* in, unsigned inlen, void* arg) {
231 const TestConfig *config = GetTestConfig(ssl);
232 if (config->select_next_proto.empty()) {
233 return SSL_TLSEXT_ERR_NOACK;
236 *out = (uint8_t*)config->select_next_proto.data();
237 *outlen = config->select_next_proto.size();
238 return SSL_TLSEXT_ERR_OK;
241 static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
242 const uint8_t* in, unsigned inlen, void* arg) {
243 if (GetTestState(ssl)->alpn_select_done) {
244 fprintf(stderr, "AlpnSelectCallback called after completion.\n");
248 GetTestState(ssl)->alpn_select_done = true;
250 const TestConfig *config = GetTestConfig(ssl);
251 if (config->decline_alpn) {
252 return SSL_TLSEXT_ERR_NOACK;
255 if (!config->expected_advertised_alpn.empty() &&
256 (config->expected_advertised_alpn.size() != inlen ||
257 memcmp(config->expected_advertised_alpn.data(),
259 fprintf(stderr, "bad ALPN select callback inputs\n");
263 *out = (const uint8_t*)config->select_alpn.data();
264 *outlen = config->select_alpn.size();
265 return SSL_TLSEXT_ERR_OK;
268 static unsigned PskClientCallback(SSL *ssl, const char *hint,
270 unsigned max_identity_len,
271 uint8_t *out_psk, unsigned max_psk_len) {
272 const TestConfig *config = GetTestConfig(ssl);
274 if (config->psk_identity.empty()) {
275 if (hint != nullptr) {
276 fprintf(stderr, "Server PSK hint was non-null.\n");
279 } else if (hint == nullptr ||
280 strcmp(hint, config->psk_identity.c_str()) != 0) {
281 fprintf(stderr, "Server PSK hint did not match.\n");
285 // Account for the trailing '\0' for the identity.
286 if (config->psk_identity.size() >= max_identity_len ||
287 config->psk.size() > max_psk_len) {
288 fprintf(stderr, "PSK buffers too small\n");
292 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
294 memcpy(out_psk, config->psk.data(), config->psk.size());
295 return config->psk.size();
298 static unsigned PskServerCallback(SSL *ssl, const char *identity,
299 uint8_t *out_psk, unsigned max_psk_len) {
300 const TestConfig *config = GetTestConfig(ssl);
302 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
303 fprintf(stderr, "Client PSK identity did not match.\n");
307 if (config->psk.size() > max_psk_len) {
308 fprintf(stderr, "PSK buffers too small\n");
312 memcpy(out_psk, config->psk.data(), config->psk.size());
313 return config->psk.size();
316 static int CertCallback(SSL *ssl, void *arg) {
317 const TestConfig *config = GetTestConfig(ssl);
319 // Check the CertificateRequest metadata is as expected.
321 // TODO(davidben): Test |SSL_get_client_CA_list|.
322 if (!SSL_is_server(ssl) &&
323 !config->expected_certificate_types.empty()) {
324 const uint8_t *certificate_types;
325 size_t certificate_types_len =
326 SSL_get0_certificate_types(ssl, &certificate_types);
327 if (certificate_types_len != config->expected_certificate_types.size() ||
328 memcmp(certificate_types,
329 config->expected_certificate_types.data(),
330 certificate_types_len) != 0) {
331 fprintf(stderr, "certificate types mismatch\n");
336 // The certificate will be installed via other means.
337 if (!config->async ||
338 config->use_old_client_cert_callback) {
342 if (!GetTestState(ssl)->cert_ready) {
345 if (!InstallCertificate(ssl)) {
351 static void InfoCallback(const SSL *ssl, int type, int val) {
352 if (type == SSL_CB_HANDSHAKE_DONE) {
353 if (GetTestConfig(ssl)->handshake_never_done) {
354 fprintf(stderr, "Handshake unexpectedly completed.\n");
355 // Abort before any expected error code is printed, to ensure the overall
359 GetTestState(ssl)->handshake_done = true;
361 // Callbacks may be called again on a new handshake.
362 GetTestState(ssl)->ticket_decrypt_done = false;
363 GetTestState(ssl)->alpn_select_done = false;
367 static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
368 GetTestState(ssl)->got_new_session = true;
369 GetTestState(ssl)->new_session.reset(session);
373 static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
374 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
377 if (GetTestState(ssl)->ticket_decrypt_done) {
378 fprintf(stderr, "TicketKeyCallback called after completion.\n");
382 GetTestState(ssl)->ticket_decrypt_done = true;
385 // This is just test code, so use the all-zeros key.
386 static const uint8_t kZeros[16] = {0};
389 memcpy(key_name, kZeros, sizeof(kZeros));
391 } else if (memcmp(key_name, kZeros, 16) != 0) {
395 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
396 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
401 return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
406 // kCustomExtensionValue is the extension value that the custom extension
407 // callbacks will add.
408 static const uint16_t kCustomExtensionValue = 1234;
409 static void *const kCustomExtensionAddArg =
410 reinterpret_cast<void *>(kCustomExtensionValue);
411 static void *const kCustomExtensionParseArg =
412 reinterpret_cast<void *>(kCustomExtensionValue + 1);
413 static const char kCustomExtensionContents[] = "custom extension";
415 static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
416 const uint8_t **out, size_t *out_len,
417 int *out_alert_value, void *add_arg) {
418 if (extension_value != kCustomExtensionValue ||
419 add_arg != kCustomExtensionAddArg) {
423 if (GetTestConfig(ssl)->custom_extension_skip) {
426 if (GetTestConfig(ssl)->custom_extension_fail_add) {
430 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
431 *out_len = sizeof(kCustomExtensionContents) - 1;
436 static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
437 const uint8_t *out, void *add_arg) {
438 if (extension_value != kCustomExtensionValue ||
439 add_arg != kCustomExtensionAddArg ||
440 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
445 static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
446 const uint8_t *contents,
448 int *out_alert_value, void *parse_arg) {
449 if (extension_value != kCustomExtensionValue ||
450 parse_arg != kCustomExtensionParseArg) {
454 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
455 memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
456 *out_alert_value = SSL_AD_DECODE_ERROR;
463 // Connect returns a new socket connected to localhost on |port| or -1 on
465 static int Connect(uint16_t port) {
466 int sock = socket(AF_INET, SOCK_STREAM, 0);
468 PrintSocketError("socket");
472 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
473 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
474 PrintSocketError("setsockopt");
479 memset(&sin, 0, sizeof(sin));
480 sin.sin_family = AF_INET;
481 sin.sin_port = htons(port);
482 if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
483 PrintSocketError("inet_pton");
487 if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
489 PrintSocketError("connect");
498 explicit SocketCloser(int sock) : sock_(sock) {}
500 // Half-close and drain the socket before releasing it. This seems to be
501 // necessary for graceful shutdown on Windows. It will also avoid write
502 // failures in the test runner.
503 #if defined(OPENSSL_SYS_WINDOWS)
504 shutdown(sock_, SD_SEND);
506 shutdown(sock_, SHUT_WR);
510 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
521 static bssl::UniquePtr<SSL_CTX> SetupCtx(const TestConfig *config) {
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_next_protos_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);
640 // RetryAsync is called after a failed operation on |ssl| with return code
641 // |ret|. If the operation should be retried, it simulates one asynchronous
642 // event and returns true. Otherwise it returns false.
643 static bool RetryAsync(SSL *ssl, int ret) {
644 // No error; don't retry.
649 TestState *test_state = GetTestState(ssl);
650 assert(GetTestConfig(ssl)->async);
652 if (test_state->packeted_bio != nullptr &&
653 PacketedBioAdvanceClock(test_state->packeted_bio)) {
654 // The DTLS retransmit logic silently ignores write failures. So the test
655 // may progress, allow writes through synchronously.
656 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
657 int timeout_ret = DTLSv1_handle_timeout(ssl);
658 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
660 if (timeout_ret < 0) {
661 fprintf(stderr, "Error retransmitting.\n");
667 // See if we needed to read or write more. If so, allow one byte through on
668 // the appropriate end to maximally stress the state machine.
669 switch (SSL_get_error(ssl, ret)) {
670 case SSL_ERROR_WANT_READ:
671 AsyncBioAllowRead(test_state->async_bio, 1);
673 case SSL_ERROR_WANT_WRITE:
674 AsyncBioAllowWrite(test_state->async_bio, 1);
676 case SSL_ERROR_WANT_X509_LOOKUP:
677 test_state->cert_ready = true;
684 // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
685 // the result value of the final |SSL_read| call.
686 static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
687 const TestConfig *config = GetTestConfig(ssl);
688 TestState *test_state = GetTestState(ssl);
692 // The DTLS retransmit logic silently ignores write failures. So the test
693 // may progress, allow writes through synchronously. |SSL_read| may
694 // trigger a retransmit, so disconnect the write quota.
695 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
697 ret = config->peek_then_read ? SSL_peek(ssl, out, max_out)
698 : SSL_read(ssl, out, max_out);
700 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
702 } while (config->async && RetryAsync(ssl, ret));
704 if (config->peek_then_read && ret > 0) {
705 std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
707 // SSL_peek should synchronously return the same data.
708 int ret2 = SSL_peek(ssl, buf.get(), ret);
710 memcmp(buf.get(), out, ret) != 0) {
711 fprintf(stderr, "First and second SSL_peek did not match.\n");
715 // SSL_read should synchronously return the same data and consume it.
716 ret2 = SSL_read(ssl, buf.get(), ret);
718 memcmp(buf.get(), out, ret) != 0) {
719 fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
727 // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
728 // operations. It returns the result of the final |SSL_write| call.
729 static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
730 const TestConfig *config = GetTestConfig(ssl);
733 ret = SSL_write(ssl, in, in_len);
738 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
742 // DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
743 // returns the result of the final |SSL_shutdown| call.
744 static int DoShutdown(SSL *ssl) {
745 const TestConfig *config = GetTestConfig(ssl);
748 ret = SSL_shutdown(ssl);
749 } while (config->async && RetryAsync(ssl, ret));
753 static uint16_t GetProtocolVersion(const SSL *ssl) {
754 uint16_t version = SSL_version(ssl);
755 if (!SSL_is_dtls(ssl)) {
758 return 0x0201 + ~version;
761 // CheckHandshakeProperties checks, immediately after |ssl| completes its
762 // initial handshake (or False Starts), whether all the properties are
763 // consistent with the test configuration and invariants.
764 static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
765 const TestConfig *config = GetTestConfig(ssl);
767 if (SSL_get_current_cipher(ssl) == nullptr) {
768 fprintf(stderr, "null cipher after handshake\n");
773 (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
774 fprintf(stderr, "session was%s reused\n",
775 SSL_session_reused(ssl) ? "" : " not");
779 if (!GetTestState(ssl)->handshake_done) {
780 fprintf(stderr, "handshake was not completed\n");
784 if (!config->is_server) {
785 bool expect_new_session =
786 !config->expect_no_session &&
787 (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
788 // Session tickets are sent post-handshake in TLS 1.3.
789 GetProtocolVersion(ssl) < TLS1_3_VERSION;
790 if (expect_new_session != GetTestState(ssl)->got_new_session) {
792 "new session was%s cached, but we expected the opposite\n",
793 GetTestState(ssl)->got_new_session ? "" : " not");
798 if (!config->expected_server_name.empty()) {
799 const char *server_name =
800 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
801 if (server_name != config->expected_server_name) {
802 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
803 server_name, config->expected_server_name.c_str());
808 if (!config->expected_next_proto.empty()) {
809 const uint8_t *next_proto;
810 unsigned next_proto_len;
811 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
812 if (next_proto_len != config->expected_next_proto.size() ||
813 memcmp(next_proto, config->expected_next_proto.data(),
814 next_proto_len) != 0) {
815 fprintf(stderr, "negotiated next proto mismatch\n");
820 if (!config->expected_alpn.empty()) {
821 const uint8_t *alpn_proto;
822 unsigned alpn_proto_len;
823 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
824 if (alpn_proto_len != config->expected_alpn.size() ||
825 memcmp(alpn_proto, config->expected_alpn.data(),
826 alpn_proto_len) != 0) {
827 fprintf(stderr, "negotiated alpn proto mismatch\n");
832 if (config->expect_extended_master_secret) {
833 if (!SSL_get_extms_support(ssl)) {
834 fprintf(stderr, "No EMS for connection when expected");
839 if (config->expect_verify_result) {
840 int expected_verify_result = config->verify_fail ?
841 X509_V_ERR_APPLICATION_VERIFICATION :
844 if (SSL_get_verify_result(ssl) != expected_verify_result) {
845 fprintf(stderr, "Wrong certificate verification result\n");
850 if (!config->psk.empty()) {
851 if (SSL_get_peer_cert_chain(ssl) != nullptr) {
852 fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
855 } else if (!config->is_server || config->require_any_client_certificate) {
856 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
857 fprintf(stderr, "Received no peer certificate but expected one.\n");
865 // DoExchange runs a test SSL exchange against the peer. On success, it returns
866 // true and sets |*out_session| to the negotiated SSL session. If the test is a
867 // resumption attempt, |is_resume| is true and |session| is the session from the
868 // previous exchange.
869 static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
870 SSL_CTX *ssl_ctx, const TestConfig *config,
871 bool is_resume, SSL_SESSION *session) {
872 bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
877 if (!SetTestConfig(ssl.get(), config) ||
878 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
882 if (config->fallback_scsv &&
883 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
886 // Install the certificate synchronously if nothing else will handle it.
887 if (!config->use_old_client_cert_callback &&
889 !InstallCertificate(ssl.get())) {
892 SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
893 if (config->require_any_client_certificate) {
894 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
897 if (config->verify_peer) {
898 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
900 if (config->partial_write) {
901 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
903 if (config->no_tls13) {
904 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
906 if (config->no_tls12) {
907 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
909 if (config->no_tls11) {
910 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
912 if (config->no_tls1) {
913 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
915 if (config->no_ssl3) {
916 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
918 if (!config->host_name.empty() &&
919 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
922 if (!config->advertise_alpn.empty() &&
923 SSL_set_alpn_protos(ssl.get(),
924 (const uint8_t *)config->advertise_alpn.data(),
925 config->advertise_alpn.size()) != 0) {
928 if (!config->psk.empty()) {
929 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
930 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
932 if (!config->psk_identity.empty() &&
933 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
936 if (!config->srtp_profiles.empty() &&
937 SSL_set_tlsext_use_srtp(ssl.get(), config->srtp_profiles.c_str())) {
940 if (config->min_version != 0 &&
941 !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) {
944 if (config->max_version != 0 &&
945 !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) {
948 if (config->mtu != 0) {
949 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
950 SSL_set_mtu(ssl.get(), config->mtu);
952 if (config->renegotiate_freely) {
953 // This is always on for OpenSSL.
955 if (!config->check_close_notify) {
956 SSL_set_quiet_shutdown(ssl.get(), 1);
958 if (config->p384_only) {
959 int nid = NID_secp384r1;
960 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
964 if (config->enable_all_curves) {
965 static const int kAllCurves[] = {
966 NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_X25519,
968 if (!SSL_set1_curves(ssl.get(), kAllCurves,
969 OPENSSL_ARRAY_SIZE(kAllCurves))) {
973 if (config->max_cert_list > 0) {
974 SSL_set_max_cert_list(ssl.get(), config->max_cert_list);
977 int sock = Connect(config->port);
981 SocketCloser closer(sock);
983 bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
987 if (config->is_dtls) {
988 bssl::UniquePtr<BIO> packeted = PacketedBioCreate(!config->async);
992 GetTestState(ssl.get())->packeted_bio = packeted.get();
993 BIO_push(packeted.get(), bio.release());
994 bio = std::move(packeted);
997 bssl::UniquePtr<BIO> async_scoped =
998 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
1002 BIO_push(async_scoped.get(), bio.release());
1003 GetTestState(ssl.get())->async_bio = async_scoped.get();
1004 bio = std::move(async_scoped);
1006 SSL_set_bio(ssl.get(), bio.get(), bio.get());
1007 bio.release(); // SSL_set_bio takes ownership.
1009 if (session != NULL) {
1010 if (!config->is_server) {
1011 if (SSL_set_session(ssl.get(), session) != 1) {
1018 // KNOWN BUG: OpenSSL's SSL_get_current_cipher behaves incorrectly when
1019 // offering resumption.
1020 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1021 fprintf(stderr, "non-null cipher before handshake\n");
1027 if (config->implicit_handshake) {
1028 if (config->is_server) {
1029 SSL_set_accept_state(ssl.get());
1031 SSL_set_connect_state(ssl.get());
1035 if (config->is_server) {
1036 ret = SSL_accept(ssl.get());
1038 ret = SSL_connect(ssl.get());
1040 } while (config->async && RetryAsync(ssl.get(), ret));
1042 !CheckHandshakeProperties(ssl.get(), is_resume)) {
1046 // Reset the state to assert later that the callback isn't called in
1048 GetTestState(ssl.get())->got_new_session = false;
1051 if (config->export_keying_material > 0) {
1052 std::vector<uint8_t> result(
1053 static_cast<size_t>(config->export_keying_material));
1054 if (SSL_export_keying_material(
1055 ssl.get(), result.data(), result.size(),
1056 config->export_label.data(), config->export_label.size(),
1057 reinterpret_cast<const uint8_t*>(config->export_context.data()),
1058 config->export_context.size(), config->use_export_context) != 1) {
1059 fprintf(stderr, "failed to export keying material\n");
1062 if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1067 if (config->write_different_record_sizes) {
1068 if (config->is_dtls) {
1069 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
1072 // This mode writes a number of different record sizes in an attempt to
1073 // trip up the CBC record splitting code.
1074 static const size_t kBufLen = 32769;
1075 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1076 memset(buf.get(), 0x42, kBufLen);
1077 static const size_t kRecordSizes[] = {
1078 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
1079 for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
1080 const size_t len = kRecordSizes[i];
1081 if (len > kBufLen) {
1082 fprintf(stderr, "Bad kRecordSizes value.\n");
1085 if (WriteAll(ssl.get(), buf.get(), len) < 0) {
1090 if (config->shim_writes_first) {
1091 if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1096 if (!config->shim_shuts_down) {
1098 static const size_t kBufLen = 16384;
1099 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1101 // Read only 512 bytes at a time in TLS to ensure records may be
1102 // returned in multiple reads.
1103 int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
1104 int err = SSL_get_error(ssl.get(), n);
1105 if (err == SSL_ERROR_ZERO_RETURN ||
1106 (n == 0 && err == SSL_ERROR_SYSCALL)) {
1108 fprintf(stderr, "Invalid SSL_get_error output\n");
1111 // Stop on either clean or unclean shutdown.
1113 } else if (err != SSL_ERROR_NONE) {
1115 fprintf(stderr, "Invalid SSL_get_error output\n");
1120 // Successfully read data.
1122 fprintf(stderr, "Invalid SSL_get_error output\n");
1126 // After a successful read, with or without False Start, the handshake
1127 // must be complete.
1128 if (!GetTestState(ssl.get())->handshake_done) {
1129 fprintf(stderr, "handshake was not completed after SSL_read\n");
1133 for (int i = 0; i < n; i++) {
1136 if (WriteAll(ssl.get(), buf.get(), n) < 0) {
1143 if (!config->is_server &&
1144 !config->implicit_handshake &&
1145 // Session tickets are sent post-handshake in TLS 1.3.
1146 GetProtocolVersion(ssl.get()) < TLS1_3_VERSION &&
1147 GetTestState(ssl.get())->got_new_session) {
1148 fprintf(stderr, "new session was established after the handshake\n");
1152 if (GetProtocolVersion(ssl.get()) >= TLS1_3_VERSION && !config->is_server) {
1153 bool expect_new_session =
1154 !config->expect_no_session && !config->shim_shuts_down;
1155 if (expect_new_session != GetTestState(ssl.get())->got_new_session) {
1157 "new session was%s cached, but we expected the opposite\n",
1158 GetTestState(ssl.get())->got_new_session ? "" : " not");
1164 *out_session = std::move(GetTestState(ssl.get())->new_session);
1167 ret = DoShutdown(ssl.get());
1169 if (config->shim_shuts_down && config->check_close_notify) {
1170 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1171 // it returns zero when our close_notify is sent, then one when the peer's
1174 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1177 ret = DoShutdown(ssl.get());
1181 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1185 if (SSL_total_renegotiations(ssl.get()) !=
1186 config->expect_total_renegotiations) {
1187 fprintf(stderr, "Expected %d renegotiations, got %ld\n",
1188 config->expect_total_renegotiations,
1189 SSL_total_renegotiations(ssl.get()));
1196 class StderrDelimiter {
1198 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
1201 static int Main(int argc, char **argv) {
1202 // To distinguish ASan's output from ours, add a trailing message to stderr.
1203 // Anything following this line will be considered an error.
1204 StderrDelimiter delimiter;
1206 #if defined(OPENSSL_SYS_WINDOWS)
1207 /* Initialize Winsock. */
1208 WORD wsa_version = MAKEWORD(2, 2);
1210 int wsa_err = WSAStartup(wsa_version, &wsa_data);
1212 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1215 if (wsa_data.wVersion != wsa_version) {
1216 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1220 signal(SIGPIPE, SIG_IGN);
1223 OPENSSL_init_crypto(0, NULL);
1224 OPENSSL_init_ssl(0, NULL);
1225 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
1226 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
1227 if (g_config_index < 0 || g_state_index < 0) {
1232 if (!ParseConfig(argc - 1, argv + 1, &config)) {
1233 return Usage(argv[0]);
1236 bssl::UniquePtr<SSL_CTX> ssl_ctx = SetupCtx(&config);
1238 ERR_print_errors_fp(stderr);
1242 bssl::UniquePtr<SSL_SESSION> session;
1243 for (int i = 0; i < config.resume_count + 1; i++) {
1244 bool is_resume = i > 0;
1245 if (is_resume && !config.is_server && !session) {
1246 fprintf(stderr, "No session to offer.\n");
1250 bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
1251 if (!DoExchange(&session, ssl_ctx.get(), &config, is_resume,
1252 offer_session.get())) {
1253 fprintf(stderr, "Connection %d failed.\n", i + 1);
1254 ERR_print_errors_fp(stderr);
1264 int main(int argc, char **argv) {
1265 return bssl::Main(argc, argv);