From 7b73b7beda88501b9d6e062a5dbf9a72f791dfda Mon Sep 17 00:00:00 2001 From: Matt Caswell Date: Wed, 12 Oct 2016 10:56:29 +0100 Subject: [PATCH] Rebase shim against latest boringssl code Numerous conflicts resolved. rebase was against commit 490469f850. Reviewed-by: Richard Levitte --- test/ossl_shim/Makefile | 2 +- test/ossl_shim/async_bio.cc | 9 +- test/ossl_shim/async_bio.h | 7 +- test/ossl_shim/crypto/scoped_types.h | 102 ------- test/ossl_shim/include/openssl/base.h | 158 +++++++++++ test/ossl_shim/ossl_shim.cc | 395 +++++++++++++++++--------- test/ossl_shim/packeted_bio.cc | 203 ++++++++++--- test/ossl_shim/packeted_bio.h | 33 ++- test/ossl_shim/test_config.cc | 37 ++- test/ossl_shim/test_config.h | 18 +- 10 files changed, 653 insertions(+), 311 deletions(-) delete mode 100644 test/ossl_shim/crypto/scoped_types.h create mode 100644 test/ossl_shim/include/openssl/base.h diff --git a/test/ossl_shim/Makefile b/test/ossl_shim/Makefile index 688317cc79..bab8441646 100644 --- a/test/ossl_shim/Makefile +++ b/test/ossl_shim/Makefile @@ -1,7 +1,7 @@ all: ossl_shim ossl_shim: ../../libssl.a ../../libcrypto.a *.cc - g++ -g -std=c++11 -I. -I../../include *.cc \ + g++ -g -std=c++11 -I. -Iinclude -I../../include *.cc \ ../../libssl.a ../../libcrypto.a -ldl -lpthread \ -o ossl_shim diff --git a/test/ossl_shim/async_bio.cc b/test/ossl_shim/async_bio.cc index 825b22372f..b905a0e697 100644 --- a/test/ossl_shim/async_bio.cc +++ b/test/ossl_shim/async_bio.cc @@ -17,6 +17,7 @@ #include #include +#include #include @@ -158,12 +159,12 @@ static const BIO_METHOD *AsyncMethod(void) } // namespace -ScopedBIO AsyncBioCreate() { - return ScopedBIO(BIO_new(AsyncMethod())); +bssl::UniquePtr AsyncBioCreate() { + return bssl::UniquePtr(BIO_new(AsyncMethod())); } -ScopedBIO AsyncBioCreateDatagram() { - ScopedBIO ret(BIO_new(AsyncMethod())); +bssl::UniquePtr AsyncBioCreateDatagram() { + bssl::UniquePtr ret(BIO_new(AsyncMethod())); if (!ret) { return nullptr; } diff --git a/test/ossl_shim/async_bio.h b/test/ossl_shim/async_bio.h index 9466a8ca3d..8a8ee18fba 100644 --- a/test/ossl_shim/async_bio.h +++ b/test/ossl_shim/async_bio.h @@ -15,22 +15,21 @@ #ifndef HEADER_ASYNC_BIO #define HEADER_ASYNC_BIO +#include #include -#include "crypto/scoped_types.h" - // AsyncBioCreate creates a filter BIO for testing asynchronous state // machines which consume a stream socket. Reads and writes will fail // and return EAGAIN unless explicitly allowed. Each async BIO has a // read quota and a write quota. Initially both are zero. As each is // incremented, bytes are allowed to flow through the BIO. -ScopedBIO AsyncBioCreate(); +bssl::UniquePtr AsyncBioCreate(); // AsyncBioCreateDatagram creates a filter BIO for testing for // asynchronous state machines which consume datagram sockets. The read // and write quota count in packets rather than bytes. -ScopedBIO AsyncBioCreateDatagram(); +bssl::UniquePtr AsyncBioCreateDatagram(); // AsyncBioAllowRead increments |bio|'s read quota by |count|. void AsyncBioAllowRead(BIO *bio, size_t count); diff --git a/test/ossl_shim/crypto/scoped_types.h b/test/ossl_shim/crypto/scoped_types.h deleted file mode 100644 index a1f6851228..0000000000 --- a/test/ossl_shim/crypto/scoped_types.h +++ /dev/null @@ -1,102 +0,0 @@ -/* Copyright (c) 2015, Google Inc. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -#ifndef OPENSSL_HEADER_CRYPTO_TEST_SCOPED_TYPES_H -#define OPENSSL_HEADER_CRYPTO_TEST_SCOPED_TYPES_H - -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -template -struct OpenSSLDeleter { - void operator()(T *obj) { - func(obj); - } -}; - -template -struct OpenSSLStackDeleter { - void operator()(StackType *obj) { - sk_pop_free(reinterpret_cast<_STACK*>(obj), - reinterpret_cast(func)); - } -}; - -template -struct OpenSSLFree { - void operator()(T *buf) { - OPENSSL_free(buf); - } -}; - -struct FileCloser { - void operator()(FILE *file) { - fclose(file); - } -}; - -template -using ScopedOpenSSLType = std::unique_ptr>; - -template -using ScopedOpenSSLStack = - std::unique_ptr>; - -using ScopedASN1_TYPE = ScopedOpenSSLType; -using ScopedBIO = ScopedOpenSSLType; -using ScopedBIGNUM = ScopedOpenSSLType; -using ScopedBN_CTX = ScopedOpenSSLType; -using ScopedBN_MONT_CTX = ScopedOpenSSLType; -using ScopedCMAC_CTX = ScopedOpenSSLType; -using ScopedDH = ScopedOpenSSLType; -using ScopedECDSA_SIG = ScopedOpenSSLType; -using ScopedEC_GROUP = ScopedOpenSSLType; -using ScopedEC_KEY = ScopedOpenSSLType; -using ScopedEC_POINT = ScopedOpenSSLType; -using ScopedEVP_PKEY = ScopedOpenSSLType; -using ScopedEVP_PKEY_CTX = ScopedOpenSSLType; -using ScopedPKCS8_PRIV_KEY_INFO = ScopedOpenSSLType; -using ScopedPKCS12 = ScopedOpenSSLType; -using ScopedRSA = ScopedOpenSSLType; -using ScopedX509 = ScopedOpenSSLType; -using ScopedX509_ALGOR = ScopedOpenSSLType; -using ScopedX509_SIG = ScopedOpenSSLType; -using ScopedX509_STORE_CTX = ScopedOpenSSLType; - -using ScopedX509Stack = ScopedOpenSSLStack; - -using ScopedOpenSSLBytes = std::unique_ptr>; -using ScopedOpenSSLString = std::unique_ptr>; - -using ScopedFILE = std::unique_ptr; - -#endif // OPENSSL_HEADER_CRYPTO_TEST_SCOPED_TYPES_H diff --git a/test/ossl_shim/include/openssl/base.h b/test/ossl_shim/include/openssl/base.h new file mode 100644 index 0000000000..755d520032 --- /dev/null +++ b/test/ossl_shim/include/openssl/base.h @@ -0,0 +1,158 @@ +/* ==================================================================== + * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). */ + +#ifndef OPENSSL_HEADER_BASE_H +#define OPENSSL_HEADER_BASE_H + +/* Needed for BORINGSSL_MAKE_DELETER */ +# include +# include +# include +# include +# include + +# define OPENSSL_ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0])) + +/* Temporary TLS1.3 defines until OpenSSL supports these */ +# define TLS1_3_VERSION 0x0304 +# define SSL_OP_NO_TLSv1_3 0 + +extern "C++" { + +#include + +namespace bssl { + +namespace internal { + +template +struct DeleterImpl {}; + +template +struct Deleter { + void operator()(T *ptr) { + // Rather than specialize Deleter for each type, we specialize + // DeleterImpl. This allows bssl::UniquePtr to be used while only + // including base.h as long as the destructor is not emitted. This matches + // std::unique_ptr's behavior on forward-declared types. + // + // DeleterImpl itself is specialized in the corresponding module's header + // and must be included to release an object. If not included, the compiler + // will error that DeleterImpl does not have a method Free. + DeleterImpl::Free(ptr); + } +}; + +template +class StackAllocated { + public: + StackAllocated() { init(&ctx_); } + ~StackAllocated() { cleanup(&ctx_); } + + StackAllocated(const StackAllocated &) = delete; + T& operator=(const StackAllocated &) = delete; + + T *get() { return &ctx_; } + const T *get() const { return &ctx_; } + + void Reset() { + cleanup(&ctx_); + init(&ctx_); + } + + private: + T ctx_; +}; + +} // namespace internal + +#define BORINGSSL_MAKE_DELETER(type, deleter) \ + namespace internal { \ + template <> \ + struct DeleterImpl { \ + static void Free(type *ptr) { deleter(ptr); } \ + }; \ + } + +// This makes a unique_ptr to STACK_OF(type) that owns all elements on the +// stack, i.e. it uses sk_pop_free() to clean up. +#define BORINGSSL_MAKE_STACK_DELETER(type, deleter) \ + namespace internal { \ + template <> \ + struct DeleterImpl { \ + static void Free(STACK_OF(type) *ptr) { \ + sk_##type##_pop_free(ptr, deleter); \ + } \ + }; \ + } + +// Holds ownership of heap-allocated BoringSSL structures. Sample usage: +// bssl::UniquePtr rsa(RSA_new()); +// bssl::UniquePtr bio(BIO_new(BIO_s_mem())); +template +using UniquePtr = std::unique_ptr>; + +BORINGSSL_MAKE_DELETER(BIO, BIO_free) +BORINGSSL_MAKE_DELETER(EVP_PKEY, EVP_PKEY_free) +BORINGSSL_MAKE_DELETER(DH, DH_free) +BORINGSSL_MAKE_DELETER(X509, X509_free) +BORINGSSL_MAKE_DELETER(SSL, SSL_free) +BORINGSSL_MAKE_DELETER(SSL_CTX, SSL_CTX_free) +BORINGSSL_MAKE_DELETER(SSL_SESSION, SSL_SESSION_free) + +} // namespace bssl + +} /* extern C++ */ + + +#endif /* OPENSSL_HEADER_BASE_H */ diff --git a/test/ossl_shim/ossl_shim.cc b/test/ossl_shim/ossl_shim.cc index b1abcf6d6c..526d614d26 100644 --- a/test/ossl_shim/ossl_shim.cc +++ b/test/ossl_shim/ossl_shim.cc @@ -28,14 +28,15 @@ #include #else #include -#pragma warning(push, 3) +OPENSSL_MSVC_PRAGMA(warning(push, 3)) #include #include -#pragma warning(pop) +OPENSSL_MSVC_PRAGMA(warning(pop)) -#pragma comment(lib, "Ws2_32.lib") +OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib")) #endif +#include #include #include @@ -49,17 +50,17 @@ #include #include #include +#include #include #include #include -#include "crypto/scoped_types.h" #include "async_bio.h" #include "packeted_bio.h" -#include "scoped_types.h" #include "test_config.h" +namespace bssl { #if !defined(OPENSSL_SYS_WINDOWS) static int closesocket(int sock) { @@ -81,31 +82,26 @@ static int Usage(const char *program) { } struct TestState { - TestState() { - // MSVC cannot initialize these inline. - memset(&clock, 0, sizeof(clock)); - memset(&clock_delta, 0, sizeof(clock_delta)); - } - // async_bio is async BIO which pauses reads and writes. BIO *async_bio = nullptr; - // clock is the current time for the SSL connection. - timeval clock; - // clock_delta is how far the clock advanced in the most recent failed - // |BIO_read|. - timeval clock_delta; + // packeted_bio is the packeted BIO which simulates read timeouts. + BIO *packeted_bio = nullptr; + bssl::UniquePtr channel_id; bool cert_ready = false; - ScopedSSL_SESSION session; - ScopedSSL_SESSION pending_session; + bssl::UniquePtr session; + bssl::UniquePtr pending_session; bool early_callback_called = false; bool handshake_done = false; // private_key is the underlying private key used when testing custom keys. - ScopedEVP_PKEY private_key; + bssl::UniquePtr private_key; std::vector private_key_result; // private_key_retries is the number of times an asynchronous private key // operation has been retried. unsigned private_key_retries = 0; bool got_new_session = false; + bssl::UniquePtr new_session; + bool ticket_decrypt_done = false; + bool alpn_select_done = false; }; static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad, @@ -116,11 +112,11 @@ static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad, static int g_config_index = 0; static int g_state_index = 0; -static bool SetConfigPtr(SSL *ssl, const TestConfig *config) { +static bool SetTestConfig(SSL *ssl, const TestConfig *config) { return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1; } -static const TestConfig *GetConfigPtr(const SSL *ssl) { +static const TestConfig *GetTestConfig(const SSL *ssl) { return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index); } @@ -137,20 +133,21 @@ static TestState *GetTestState(const SSL *ssl) { return (TestState *)SSL_get_ex_data(ssl, g_state_index); } -static ScopedX509 LoadCertificate(const std::string &file) { - ScopedBIO bio(BIO_new(BIO_s_file())); +static bssl::UniquePtr LoadCertificate(const std::string &file) { + bssl::UniquePtr bio(BIO_new(BIO_s_file())); if (!bio || !BIO_read_filename(bio.get(), file.c_str())) { return nullptr; } - return ScopedX509(PEM_read_bio_X509(bio.get(), NULL, NULL, NULL)); + return bssl::UniquePtr(PEM_read_bio_X509(bio.get(), NULL, NULL, NULL)); } -static ScopedEVP_PKEY LoadPrivateKey(const std::string &file) { - ScopedBIO bio(BIO_new(BIO_s_file())); +static bssl::UniquePtr LoadPrivateKey(const std::string &file) { + bssl::UniquePtr bio(BIO_new(BIO_s_file())); if (!bio || !BIO_read_filename(bio.get(), file.c_str())) { return nullptr; } - return ScopedEVP_PKEY(PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL)); + return bssl::UniquePtr( + PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL)); } template @@ -160,15 +157,20 @@ struct Free { } }; -static bool GetCertificate(SSL *ssl, ScopedX509 *out_x509, - ScopedEVP_PKEY *out_pkey) { - const TestConfig *config = GetConfigPtr(ssl); +static bool GetCertificate(SSL *ssl, bssl::UniquePtr *out_x509, + bssl::UniquePtr *out_pkey) { + const TestConfig *config = GetTestConfig(ssl); if (!config->digest_prefs.empty()) { fprintf(stderr, "Digest prefs not supported.\n"); return false; } + if (!config->signing_prefs.empty()) { + fprintf(stderr, "Set signing algorithm prefs not supported\n"); + return false; + } + if (!config->key_file.empty()) { *out_pkey = LoadPrivateKey(config->key_file.c_str()); if (!*out_pkey) { @@ -189,15 +191,15 @@ static bool GetCertificate(SSL *ssl, ScopedX509 *out_x509, } static bool InstallCertificate(SSL *ssl) { - ScopedX509 x509; - ScopedEVP_PKEY pkey; + bssl::UniquePtr x509; + bssl::UniquePtr pkey; if (!GetCertificate(ssl, &x509, &pkey)) { return false; } if (pkey) { TestState *test_state = GetTestState(ssl); - const TestConfig *config = GetConfigPtr(ssl); + const TestConfig *config = GetTestConfig(ssl); if (!SSL_use_PrivateKey(ssl, pkey.get())) { return false; } @@ -211,12 +213,12 @@ static bool InstallCertificate(SSL *ssl) { } static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) { - if (GetConfigPtr(ssl)->async && !GetTestState(ssl)->cert_ready) { + if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) { return -1; } - ScopedX509 x509; - ScopedEVP_PKEY pkey; + bssl::UniquePtr x509; + bssl::UniquePtr pkey; if (!GetCertificate(ssl, &x509, &pkey)) { return -1; } @@ -243,7 +245,7 @@ static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) { static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out, unsigned int *out_len, void *arg) { - const TestConfig *config = GetConfigPtr(ssl); + const TestConfig *config = GetTestConfig(ssl); if (config->advertise_npn.empty()) { return SSL_TLSEXT_ERR_NOACK; } @@ -255,7 +257,7 @@ static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out, static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen, const uint8_t* in, unsigned inlen, void* arg) { - const TestConfig *config = GetConfigPtr(ssl); + const TestConfig *config = GetTestConfig(ssl); if (config->select_next_proto.empty()) { return SSL_TLSEXT_ERR_NOACK; } @@ -267,8 +269,15 @@ static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen, static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen, const uint8_t* in, unsigned inlen, void* arg) { - const TestConfig *config = GetConfigPtr(ssl); - if (config->select_alpn.empty()) { + if (GetTestState(ssl)->alpn_select_done) { + fprintf(stderr, "AlpnSelectCallback called after completion.\n"); + exit(1); + } + + GetTestState(ssl)->alpn_select_done = true; + + const TestConfig *config = GetTestConfig(ssl); + if (config->decline_alpn) { return SSL_TLSEXT_ERR_NOACK; } @@ -289,9 +298,15 @@ static unsigned PskClientCallback(SSL *ssl, const char *hint, char *out_identity, unsigned max_identity_len, uint8_t *out_psk, unsigned max_psk_len) { - const TestConfig *config = GetConfigPtr(ssl); + const TestConfig *config = GetTestConfig(ssl); - if (strcmp(hint ? hint : "", config->psk_identity.c_str()) != 0) { + if (config->psk_identity.empty()) { + if (hint != nullptr) { + fprintf(stderr, "Server PSK hint was non-null.\n"); + return 0; + } + } else if (hint == nullptr || + strcmp(hint, config->psk_identity.c_str()) != 0) { fprintf(stderr, "Server PSK hint did not match.\n"); return 0; } @@ -311,7 +326,7 @@ static unsigned PskClientCallback(SSL *ssl, const char *hint, static unsigned PskServerCallback(SSL *ssl, const char *identity, uint8_t *out_psk, unsigned max_psk_len) { - const TestConfig *config = GetConfigPtr(ssl); + const TestConfig *config = GetTestConfig(ssl); if (strcmp(identity, config->psk_identity.c_str()) != 0) { fprintf(stderr, "Client PSK identity did not match.\n"); @@ -328,6 +343,31 @@ static unsigned PskServerCallback(SSL *ssl, const char *identity, } static int CertCallback(SSL *ssl, void *arg) { + const TestConfig *config = GetTestConfig(ssl); + + // Check the CertificateRequest metadata is as expected. + // + // TODO(davidben): Test |SSL_get_client_CA_list|. + if (!SSL_is_server(ssl) && + !config->expected_certificate_types.empty()) { + const uint8_t *certificate_types; + size_t certificate_types_len = + SSL_get0_certificate_types(ssl, &certificate_types); + if (certificate_types_len != config->expected_certificate_types.size() || + memcmp(certificate_types, + config->expected_certificate_types.data(), + certificate_types_len) != 0) { + fprintf(stderr, "certificate types mismatch\n"); + return 0; + } + } + + // The certificate will be installed via other means. + if (!config->async || config->use_early_callback || + config->use_old_client_cert_callback) { + return 1; + } + if (!GetTestState(ssl)->cert_ready) { return -1; } @@ -339,26 +379,38 @@ static int CertCallback(SSL *ssl, void *arg) { static void InfoCallback(const SSL *ssl, int type, int val) { if (type == SSL_CB_HANDSHAKE_DONE) { - if (GetConfigPtr(ssl)->handshake_never_done) { - fprintf(stderr, "handshake completed\n"); + if (GetTestConfig(ssl)->handshake_never_done) { + fprintf(stderr, "Handshake unexpectedly completed.\n"); // Abort before any expected error code is printed, to ensure the overall // test fails. abort(); } GetTestState(ssl)->handshake_done = true; + + // Callbacks may be called again on a new handshake. + GetTestState(ssl)->ticket_decrypt_done = false; + GetTestState(ssl)->alpn_select_done = false; } } static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) { GetTestState(ssl)->got_new_session = true; - // BoringSSL passes a reference to |session|. - SSL_SESSION_free(session); + GetTestState(ssl)->new_session.reset(session); return 1; } static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv, EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx, int encrypt) { + if (!encrypt) { + if (GetTestState(ssl)->ticket_decrypt_done) { + fprintf(stderr, "TicketKeyCallback called after completion.\n"); + return -1; + } + + GetTestState(ssl)->ticket_decrypt_done = true; + } + // This is just test code, so use the all-zeros key. static const uint8_t kZeros[16] = {0}; @@ -375,7 +427,7 @@ static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv, } if (!encrypt) { - return GetConfigPtr(ssl)->renew_ticket ? 2 : 1; + return GetTestConfig(ssl)->renew_ticket ? 2 : 1; } return 1; } @@ -397,10 +449,10 @@ static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value, abort(); } - if (GetConfigPtr(ssl)->custom_extension_skip) { + if (GetTestConfig(ssl)->custom_extension_skip) { return 0; } - if (GetConfigPtr(ssl)->custom_extension_fail_add) { + if (GetTestConfig(ssl)->custom_extension_fail_add) { return -1; } @@ -495,14 +547,22 @@ class SocketCloser { const int sock_; }; -static ScopedSSL_CTX SetupCtx(const TestConfig *config) { - ScopedSSL_CTX ssl_ctx(SSL_CTX_new( +static bssl::UniquePtr SetupCtx(const TestConfig *config) { + bssl::UniquePtr ssl_ctx(SSL_CTX_new( config->is_dtls ? DTLS_method() : TLS_method())); if (!ssl_ctx) { return nullptr; } SSL_CTX_set_security_level(ssl_ctx.get(), 0); +#if 0 + /* Disabled for now until we have some TLS1.3 support */ + // Enable TLS 1.3 for tests. + if (!config->is_dtls && + !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION)) { + return nullptr; + } +#endif std::string cipher_list = "ALL"; if (!config->cipher.empty()) { @@ -552,7 +612,7 @@ static ScopedSSL_CTX SetupCtx(const TestConfig *config) { tmpdh = DH_get_2048_256(); } - ScopedDH dh(tmpdh); + bssl::UniquePtr dh(tmpdh); if (!dh || !SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) { return nullptr; @@ -571,7 +631,7 @@ static ScopedSSL_CTX SetupCtx(const TestConfig *config) { NULL); } - if (!config->select_alpn.empty()) { + if (!config->select_alpn.empty() || config->decline_alpn) { SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL); } @@ -609,6 +669,10 @@ static ScopedSSL_CTX SetupCtx(const TestConfig *config) { return nullptr; } + if (config->use_null_client_ca_list) { + SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr); + } + return ssl_ctx; } @@ -621,26 +685,16 @@ static bool RetryAsync(SSL *ssl, int ret) { return false; } - const TestConfig *config = GetConfigPtr(ssl); TestState *test_state = GetTestState(ssl); - if (test_state->clock_delta.tv_usec != 0 || - test_state->clock_delta.tv_sec != 0) { - // Process the timeout and retry. - test_state->clock.tv_usec += test_state->clock_delta.tv_usec; - test_state->clock.tv_sec += test_state->clock.tv_usec / 1000000; - test_state->clock.tv_usec %= 1000000; - test_state->clock.tv_sec += test_state->clock_delta.tv_sec; - memset(&test_state->clock_delta, 0, sizeof(test_state->clock_delta)); + assert(GetTestConfig(ssl)->async); + if (test_state->packeted_bio != nullptr && + PacketedBioAdvanceClock(test_state->packeted_bio)) { // The DTLS retransmit logic silently ignores write failures. So the test // may progress, allow writes through synchronously. - if (config->async) { - AsyncBioEnforceWriteQuota(test_state->async_bio, false); - } + AsyncBioEnforceWriteQuota(test_state->async_bio, false); int timeout_ret = DTLSv1_handle_timeout(ssl); - if (config->async) { - AsyncBioEnforceWriteQuota(test_state->async_bio, true); - } + AsyncBioEnforceWriteQuota(test_state->async_bio, true); if (timeout_ret < 0) { fprintf(stderr, "Error retransmitting.\n"); @@ -669,7 +723,7 @@ static bool RetryAsync(SSL *ssl, int ret) { // DoRead reads from |ssl|, resolving any asynchronous operations. It returns // the result value of the final |SSL_read| call. static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) { - const TestConfig *config = GetConfigPtr(ssl); + const TestConfig *config = GetTestConfig(ssl); TestState *test_state = GetTestState(ssl); int ret; do { @@ -679,18 +733,40 @@ static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) { // trigger a retransmit, so disconnect the write quota. AsyncBioEnforceWriteQuota(test_state->async_bio, false); } - ret = SSL_read(ssl, out, max_out); + ret = config->peek_then_read ? SSL_peek(ssl, out, max_out) + : SSL_read(ssl, out, max_out); if (config->async) { AsyncBioEnforceWriteQuota(test_state->async_bio, true); } } while (config->async && RetryAsync(ssl, ret)); + + if (config->peek_then_read && ret > 0) { + std::unique_ptr buf(new uint8_t[static_cast(ret)]); + + // SSL_peek should synchronously return the same data. + int ret2 = SSL_peek(ssl, buf.get(), ret); + if (ret2 != ret || + memcmp(buf.get(), out, ret) != 0) { + fprintf(stderr, "First and second SSL_peek did not match.\n"); + return -1; + } + + // SSL_read should synchronously return the same data and consume it. + ret2 = SSL_read(ssl, buf.get(), ret); + if (ret2 != ret || + memcmp(buf.get(), out, ret) != 0) { + fprintf(stderr, "SSL_peek and SSL_read did not match.\n"); + return -1; + } + } + return ret; } // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous // operations. It returns the result of the final |SSL_write| call. static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) { - const TestConfig *config = GetConfigPtr(ssl); + const TestConfig *config = GetTestConfig(ssl); int ret; do { ret = SSL_write(ssl, in, in_len); @@ -705,7 +781,7 @@ static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) { // DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It // returns the result of the final |SSL_shutdown| call. static int DoShutdown(SSL *ssl) { - const TestConfig *config = GetConfigPtr(ssl); + const TestConfig *config = GetTestConfig(ssl); int ret; do { ret = SSL_shutdown(ssl); @@ -713,11 +789,19 @@ static int DoShutdown(SSL *ssl) { return ret; } +static uint16_t GetProtocolVersion(const SSL *ssl) { + uint16_t version = SSL_version(ssl); + if (!SSL_is_dtls(ssl)) { + return version; + } + return 0x0201 + ~version; +} + // CheckHandshakeProperties checks, immediately after |ssl| completes its // initial handshake (or False Starts), whether all the properties are // consistent with the test configuration and invariants. static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) { - const TestConfig *config = GetConfigPtr(ssl); + const TestConfig *config = GetTestConfig(ssl); if (SSL_get_current_cipher(ssl) == nullptr) { fprintf(stderr, "null cipher after handshake\n"); @@ -741,7 +825,9 @@ static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) { if (expect_handshake_done && !config->is_server) { bool expect_new_session = !config->expect_no_session && - (!SSL_session_reused(ssl) || config->expect_ticket_renewal); + (!SSL_session_reused(ssl) || config->expect_ticket_renewal) && + // Session tickets are sent post-handshake in TLS 1.3. + GetProtocolVersion(ssl) < TLS1_3_VERSION; if (expect_new_session != GetTestState(ssl)->got_new_session) { fprintf(stderr, "new session was%s cached, but we expected the opposite\n", @@ -760,19 +846,6 @@ static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) { } } - if (!config->expected_certificate_types.empty()) { - const uint8_t *certificate_types; - size_t certificate_types_len = - SSL_get0_certificate_types(ssl, &certificate_types); - if (certificate_types_len != config->expected_certificate_types.size() || - memcmp(certificate_types, - config->expected_certificate_types.data(), - certificate_types_len) != 0) { - fprintf(stderr, "certificate types mismatch\n"); - return false; - } - } - if (!config->expected_next_proto.empty()) { const uint8_t *next_proto; unsigned next_proto_len; @@ -797,6 +870,13 @@ static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) { } } + if (config->expect_extended_master_secret) { + if (!SSL_get_extms_support(ssl)) { + fprintf(stderr, "No EMS for connection when expected"); + return false; + } + } + if (config->expect_verify_result) { int expected_verify_result = config->verify_fail ? X509_V_ERR_APPLICATION_VERIFICATION : @@ -808,19 +888,18 @@ static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) { } } - if (!config->is_server) { - /* Clients should expect a peer certificate chain iff this was not a PSK - * cipher suite. */ - if (config->psk.empty()) { - if (SSL_get_peer_cert_chain(ssl) == nullptr) { - fprintf(stderr, "Missing peer certificate chain!\n"); - return false; - } - } else if (SSL_get_peer_cert_chain(ssl) != nullptr) { - fprintf(stderr, "Unexpected peer certificate chain!\n"); + if (!config->psk.empty()) { + if (SSL_get_peer_cert_chain(ssl) != nullptr) { + fprintf(stderr, "Received peer certificate on a PSK cipher.\n"); + return false; + } + } else if (!config->is_server || config->require_any_client_certificate) { + if (SSL_get_peer_cert_chain(ssl) == nullptr) { + fprintf(stderr, "Received no peer certificate but expected one.\n"); return false; } } + return true; } @@ -828,15 +907,15 @@ static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) { // true and sets |*out_session| to the negotiated SSL session. If the test is a // resumption attempt, |is_resume| is true and |session| is the session from the // previous exchange. -static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx, - const TestConfig *config, bool is_resume, - SSL_SESSION *session) { - ScopedSSL ssl(SSL_new(ssl_ctx)); +static bool DoExchange(bssl::UniquePtr *out_session, + SSL_CTX *ssl_ctx, const TestConfig *config, + bool is_resume, SSL_SESSION *session) { + bssl::UniquePtr ssl(SSL_new(ssl_ctx)); if (!ssl) { return false; } - if (!SetConfigPtr(ssl.get(), config) || + if (!SetTestConfig(ssl.get(), config) || !SetTestState(ssl.get(), std::unique_ptr(new TestState))) { return false; } @@ -845,16 +924,14 @@ static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx, !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) { return false; } - if (!config->use_early_callback && !config->use_old_client_cert_callback) { - if (config->async) { - SSL_set_cert_cb(ssl.get(), CertCallback, NULL); - } else if (!InstallCertificate(ssl.get())) { - return false; - } - } else { - fprintf(stderr, "Early callback not supported.\n"); + // Install the certificate synchronously if nothing else will handle it. + if (!config->use_early_callback && + !config->use_old_client_cert_callback && + !config->async && + !InstallCertificate(ssl.get())) { return false; } + SSL_set_cert_cb(ssl.get(), CertCallback, nullptr); if (config->require_any_client_certificate) { SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL); @@ -869,6 +946,9 @@ static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx, if (config->partial_write) { SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE); } + if (config->no_tls13) { + SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3); + } if (config->no_tls12) { SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2); } @@ -919,11 +999,13 @@ static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx, fprintf(stderr, "SCTs not supported (with the same API).\n"); return false; } - if (config->min_version != 0) { - SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version); + if (config->min_version != 0 && + !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) { + return false; } - if (config->max_version != 0) { - SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version); + if (config->max_version != 0 && + !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) { + return false; } if (config->mtu != 0) { SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU); @@ -959,13 +1041,20 @@ static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx, } if (config->enable_all_curves) { static const int kAllCurves[] = { - NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_X25519, + NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_X25519, }; if (!SSL_set1_curves(ssl.get(), kAllCurves, - sizeof(kAllCurves) / sizeof(kAllCurves[0]))) { + OPENSSL_ARRAY_SIZE(kAllCurves))) { return false; } } + if (config->initial_timeout_duration_ms > 0) { + fprintf(stderr, "Setting DTLS initial timeout duration not supported.\n"); + return false; + } + if (config->max_cert_list > 0) { + SSL_set_max_cert_list(ssl.get(), config->max_cert_list); + } int sock = Connect(config->port); if (sock == -1) { @@ -973,19 +1062,25 @@ static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx, } SocketCloser closer(sock); - ScopedBIO bio(BIO_new_socket(sock, BIO_NOCLOSE)); + bssl::UniquePtr bio(BIO_new_socket(sock, BIO_NOCLOSE)); if (!bio) { return false; } if (config->is_dtls) { - ScopedBIO packeted = - PacketedBioCreate(&GetTestState(ssl.get())->clock_delta); + bssl::UniquePtr packeted = PacketedBioCreate(!config->async); + if (!packeted) { + return false; + } + GetTestState(ssl.get())->packeted_bio = packeted.get(); BIO_push(packeted.get(), bio.release()); bio = std::move(packeted); } if (config->async) { - ScopedBIO async_scoped = + bssl::UniquePtr async_scoped = config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate(); + if (!async_scoped) { + return false; + } BIO_push(async_scoped.get(), bio.release()); GetTestState(ssl.get())->async_bio = async_scoped.get(); bio = std::move(async_scoped); @@ -1056,6 +1151,11 @@ static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx, return false; } + if (config->send_alert) { + fprintf(stderr, "Sending an alert not supported\n"); + return false; + } + if (config->write_different_record_sizes) { if (config->is_dtls) { fprintf(stderr, "write_different_record_sizes not supported for DTLS\n"); @@ -1068,8 +1168,7 @@ static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx, memset(buf.get(), 0x42, kBufLen); static const size_t kRecordSizes[] = { 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769}; - for (size_t i = 0; i < sizeof(kRecordSizes) / sizeof(kRecordSizes[0]); - i++) { + for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) { const size_t len = kRecordSizes[i]; if (len > kBufLen) { fprintf(stderr, "Bad kRecordSizes value.\n"); @@ -1135,13 +1234,26 @@ static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx, if (!config->is_server && !config->false_start && !config->implicit_handshake && + // Session tickets are sent post-handshake in TLS 1.3. + GetProtocolVersion(ssl.get()) < TLS1_3_VERSION && GetTestState(ssl.get())->got_new_session) { fprintf(stderr, "new session was established after the handshake\n"); return false; } + if (GetProtocolVersion(ssl.get()) >= TLS1_3_VERSION && !config->is_server) { + bool expect_new_session = + !config->expect_no_session && !config->shim_shuts_down; + if (expect_new_session != GetTestState(ssl.get())->got_new_session) { + fprintf(stderr, + "new session was%s cached, but we expected the opposite\n", + GetTestState(ssl.get())->got_new_session ? "" : " not"); + return false; + } + } + if (out_session) { - out_session->reset(SSL_get1_session(ssl.get())); + *out_session = std::move(GetTestState(ssl.get())->new_session); } ret = DoShutdown(ssl.get()); @@ -1178,7 +1290,7 @@ class StderrDelimiter { ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); } }; -int main(int argc, char **argv) { +static int Main(int argc, char **argv) { // To distinguish ASan's output from ours, add a trailing message to stderr. // Anything following this line will be considered an error. StderrDelimiter delimiter; @@ -1213,25 +1325,34 @@ int main(int argc, char **argv) { return Usage(argv[0]); } - ScopedSSL_CTX ssl_ctx = SetupCtx(&config); + bssl::UniquePtr ssl_ctx = SetupCtx(&config); if (!ssl_ctx) { ERR_print_errors_fp(stderr); return 1; } - ScopedSSL_SESSION session; - if (!DoExchange(&session, ssl_ctx.get(), &config, false /* is_resume */, - NULL /* session */)) { - ERR_print_errors_fp(stderr); - return 1; - } + bssl::UniquePtr session; + for (int i = 0; i < config.resume_count + 1; i++) { + bool is_resume = i > 0; + if (is_resume && !config.is_server && !session) { + fprintf(stderr, "No session to offer.\n"); + return 1; + } - if (config.resume && - !DoExchange(NULL, ssl_ctx.get(), &config, true /* is_resume */, - session.get())) { - ERR_print_errors_fp(stderr); - return 1; + bssl::UniquePtr offer_session = std::move(session); + if (!DoExchange(&session, ssl_ctx.get(), &config, is_resume, + offer_session.get())) { + fprintf(stderr, "Connection %d failed.\n", i + 1); + ERR_print_errors_fp(stderr); + return 1; + } } return 0; } + +} // namespace bssl + +int main(int argc, char **argv) { + return bssl::Main(argc, argv); +} diff --git a/test/ossl_shim/packeted_bio.cc b/test/ossl_shim/packeted_bio.cc index 824c4275c5..23fc47a33b 100644 --- a/test/ossl_shim/packeted_bio.cc +++ b/test/ossl_shim/packeted_bio.cc @@ -26,6 +26,50 @@ namespace { const uint8_t kOpcodePacket = 'P'; const uint8_t kOpcodeTimeout = 'T'; +const uint8_t kOpcodeTimeoutAck = 't'; + +struct PacketedBio { + explicit PacketedBio(bool advance_clock_arg) + : advance_clock(advance_clock_arg) { + memset(&timeout, 0, sizeof(timeout)); + memset(&clock, 0, sizeof(clock)); + memset(&read_deadline, 0, sizeof(read_deadline)); + } + + bool HasTimeout() const { + return timeout.tv_sec != 0 || timeout.tv_usec != 0; + } + + bool CanRead() const { + if (read_deadline.tv_sec == 0 && read_deadline.tv_usec == 0) { + return true; + } + + if (clock.tv_sec == read_deadline.tv_sec) { + return clock.tv_usec < read_deadline.tv_usec; + } + return clock.tv_sec < read_deadline.tv_sec; + } + + timeval timeout; + timeval clock; + timeval read_deadline; + bool advance_clock; +}; + +PacketedBio *GetData(BIO *bio) { +#if 0 + /* Missing accessor BIO_get_method()?? Disabled for now */ + if (bio->method != &g_packeted_bio_method) { + return NULL; + } +#endif + return (PacketedBio *)BIO_get_data(bio); +} + +const PacketedBio *GetData(const BIO *bio) { + return GetData(const_cast(bio)); +} // ReadAll reads |len| bytes from |bio| into |out|. It returns 1 on success and // 0 or -1 on error. @@ -76,59 +120,113 @@ static int PacketedWrite(BIO *bio, const char *in, int inl) { } static int PacketedRead(BIO *bio, char *out, int outl) { + PacketedBio *data = GetData(bio); if (BIO_next(bio) == NULL) { return 0; } BIO_clear_retry_flags(bio); - // Read the opcode. - uint8_t opcode; - int ret = ReadAll(BIO_next(bio), &opcode, sizeof(opcode)); - if (ret <= 0) { - BIO_copy_next_retry(bio); - return ret; - } + for (;;) { + // Check if the read deadline has passed. + if (!data->CanRead()) { + BIO_set_retry_read(bio); + return -1; + } - if (opcode == kOpcodeTimeout) { - fprintf(stderr, "Timeout simulation not supported.\n"); - return -1; - } + // Read the opcode. + uint8_t opcode; + int ret = ReadAll(BIO_next(bio), &opcode, sizeof(opcode)); + if (ret <= 0) { + BIO_copy_next_retry(bio); + return ret; + } - if (opcode != kOpcodePacket) { - fprintf(stderr, "Unknown opcode, %u\n", opcode); - return -1; - } + if (opcode == kOpcodeTimeout) { + // The caller is required to advance any pending timeouts before + // continuing. + if (data->HasTimeout()) { + fprintf(stderr, "Unprocessed timeout!\n"); + return -1; + } - // Read the length prefix. - uint8_t len_bytes[4]; - ret = ReadAll(BIO_next(bio), len_bytes, sizeof(len_bytes)); - if (ret <= 0) { - BIO_copy_next_retry(bio); - return ret; - } + // Process the timeout. + uint8_t buf[8]; + ret = ReadAll(BIO_next(bio), buf, sizeof(buf)); + if (ret <= 0) { + BIO_copy_next_retry(bio); + return ret; + } + uint64_t timeout = (static_cast(buf[0]) << 56) | + (static_cast(buf[1]) << 48) | + (static_cast(buf[2]) << 40) | + (static_cast(buf[3]) << 32) | + (static_cast(buf[4]) << 24) | + (static_cast(buf[5]) << 16) | + (static_cast(buf[6]) << 8) | + static_cast(buf[7]); + timeout /= 1000; // Convert nanoseconds to microseconds. - uint32_t len = (len_bytes[0] << 24) | (len_bytes[1] << 16) | - (len_bytes[2] << 8) | len_bytes[3]; - uint8_t *buf = (uint8_t *)OPENSSL_malloc(len); - if (buf == NULL) { - return -1; - } - ret = ReadAll(BIO_next(bio), buf, len); - if (ret <= 0) { - fprintf(stderr, "Packeted BIO was truncated\n"); - return -1; - } + data->timeout.tv_usec = timeout % 1000000; + data->timeout.tv_sec = timeout / 1000000; + + // Send an ACK to the peer. + ret = BIO_write(BIO_next(bio), &kOpcodeTimeoutAck, 1); + if (ret <= 0) { + return ret; + } + assert(ret == 1); + + if (!data->advance_clock) { + // Signal to the caller to retry the read, after advancing the clock. + BIO_set_retry_read(bio); + return -1; + } + + PacketedBioAdvanceClock(bio); + continue; + } - if (outl > (int)len) { - outl = len; + if (opcode != kOpcodePacket) { + fprintf(stderr, "Unknown opcode, %u\n", opcode); + return -1; + } + + // Read the length prefix. + uint8_t len_bytes[4]; + ret = ReadAll(BIO_next(bio), len_bytes, sizeof(len_bytes)); + if (ret <= 0) { + BIO_copy_next_retry(bio); + return ret; + } + + uint32_t len = (len_bytes[0] << 24) | (len_bytes[1] << 16) | + (len_bytes[2] << 8) | len_bytes[3]; + uint8_t *buf = (uint8_t *)OPENSSL_malloc(len); + if (buf == NULL) { + return -1; + } + ret = ReadAll(BIO_next(bio), buf, len); + if (ret <= 0) { + fprintf(stderr, "Packeted BIO was truncated\n"); + return -1; + } + + if (outl > (int)len) { + outl = len; + } + memcpy(out, buf, outl); + OPENSSL_free(buf); + return outl; } - memcpy(out, buf, outl); - OPENSSL_free(buf); - return outl; } static long PacketedCtrl(BIO *bio, int cmd, long num, void *ptr) { + if (cmd == BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT) { + memcpy(&GetData(bio)->read_deadline, ptr, sizeof(timeval)); + return 1; + } + if (BIO_next(bio) == NULL) { return 0; } @@ -148,6 +246,7 @@ static int PacketedFree(BIO *bio) { return 0; } + delete GetData(bio); BIO_set_init(bio, 0); return 1; } @@ -179,11 +278,33 @@ static const BIO_METHOD *PacketedMethod(void) } } // namespace -ScopedBIO PacketedBioCreate(timeval *out_timeout) { - ScopedBIO bio(BIO_new(PacketedMethod())); +bssl::UniquePtr PacketedBioCreate(bool advance_clock) { + bssl::UniquePtr bio(BIO_new(PacketedMethod())); if (!bio) { return nullptr; } - BIO_set_data(bio.get(), out_timeout); + BIO_set_data(bio.get(), new PacketedBio(advance_clock)); return bio; } + +timeval PacketedBioGetClock(const BIO *bio) { + return GetData(bio)->clock; +} + +bool PacketedBioAdvanceClock(BIO *bio) { + PacketedBio *data = GetData(bio); + if (data == nullptr) { + return false; + } + + if (!data->HasTimeout()) { + return false; + } + + data->clock.tv_usec += data->timeout.tv_usec; + data->clock.tv_sec += data->clock.tv_usec / 1000000; + data->clock.tv_usec %= 1000000; + data->clock.tv_sec += data->timeout.tv_sec; + memset(&data->timeout, 0, sizeof(data->timeout)); + return true; +} diff --git a/test/ossl_shim/packeted_bio.h b/test/ossl_shim/packeted_bio.h index df76506105..07930d4708 100644 --- a/test/ossl_shim/packeted_bio.h +++ b/test/ossl_shim/packeted_bio.h @@ -15,30 +15,35 @@ #ifndef HEADER_PACKETED_BIO #define HEADER_PACKETED_BIO -#include +#include #include -#include "crypto/scoped_types.h" - -#if defined(OPENSSL_SYS_WINDOWS) -#pragma warning(push, 3) +#if defined(OPENSSL_WINDOWS) +OPENSSL_MSVC_PRAGMA(warning(push, 3)) #include -#pragma warning(pop) +OPENSSL_MSVC_PRAGMA(warning(pop)) #else #include #endif // PacketedBioCreate creates a filter BIO which implements a reliable in-order -// blocking datagram socket. The resulting BIO, on |BIO_read|, may simulate a -// timeout which sets |*out_timeout| to the timeout and fails the read. -// |*out_timeout| must be zero on entry to |BIO_read|; it is an error to not -// apply the timeout before the next |BIO_read|. +// blocking datagram socket. It internally maintains a clock and honors +// |BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT| based on it. // -// Note: The read timeout simulation is intended to be used with the async BIO -// wrapper. It doesn't simulate BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, used in DTLS's -// blocking mode. -ScopedBIO PacketedBioCreate(timeval *out_timeout); +// During a |BIO_read|, the peer may signal the filter BIO to simulate a +// timeout. If |advance_clock| is true, it automatically advances the clock and +// continues reading, subject to the read deadline. Otherwise, it fails +// immediately. The caller must then call |PacketedBioAdvanceClock| before +// retrying |BIO_read|. +bssl::UniquePtr PacketedBioCreate(bool advance_clock); + +// PacketedBioGetClock returns the current time for |bio|. +timeval PacketedBioGetClock(const BIO *bio); + +// PacketedBioAdvanceClock advances |bio|'s internal clock and returns true if +// there is a pending timeout. Otherwise, it returns false. +bool PacketedBioAdvanceClock(BIO *bio); #endif // HEADER_PACKETED_BIO diff --git a/test/ossl_shim/test_config.cc b/test/ossl_shim/test_config.cc index 75b03f254f..84f290d2f1 100644 --- a/test/ossl_shim/test_config.cc +++ b/test/ossl_shim/test_config.cc @@ -46,7 +46,6 @@ T *FindField(TestConfig *config, const Flag (&flags)[N], const char *flag) { const Flag kBoolFlags[] = { { "-server", &TestConfig::is_server }, { "-dtls", &TestConfig::is_dtls }, - { "-resume", &TestConfig::resume }, { "-fallback-scsv", &TestConfig::fallback_scsv }, { "-require-any-client-certificate", &TestConfig::require_any_client_certificate }, @@ -56,12 +55,15 @@ const Flag kBoolFlags[] = { &TestConfig::write_different_record_sizes }, { "-cbc-record-splitting", &TestConfig::cbc_record_splitting }, { "-partial-write", &TestConfig::partial_write }, + { "-no-tls13", &TestConfig::no_tls13 }, { "-no-tls12", &TestConfig::no_tls12 }, { "-no-tls11", &TestConfig::no_tls11 }, { "-no-tls1", &TestConfig::no_tls1 }, { "-no-ssl3", &TestConfig::no_ssl3 }, + { "-enable-channel-id", &TestConfig::enable_channel_id }, { "-shim-writes-first", &TestConfig::shim_writes_first }, { "-expect-session-miss", &TestConfig::expect_session_miss }, + { "-decline-alpn", &TestConfig::decline_alpn }, { "-expect-extended-master-secret", &TestConfig::expect_extended_master_secret }, { "-enable-ocsp-stapling", &TestConfig::enable_ocsp_stapling }, @@ -100,6 +102,10 @@ const Flag kBoolFlags[] = { { "-use-sparse-dh-prime", &TestConfig::use_sparse_dh_prime }, { "-use-old-client-cert-callback", &TestConfig::use_old_client_cert_callback }, + { "-use-null-client-ca-list", &TestConfig::use_null_client_ca_list }, + { "-send-alert", &TestConfig::send_alert }, + { "-peek-then-read", &TestConfig::peek_then_read }, + { "-enable-grease", &TestConfig::enable_grease }, }; const Flag kStringFlags[] = { @@ -138,15 +144,22 @@ const Flag kBase64Flags[] = { const Flag kIntFlags[] = { { "-port", &TestConfig::port }, + { "-resume-count", &TestConfig::resume_count }, { "-min-version", &TestConfig::min_version }, { "-max-version", &TestConfig::max_version }, { "-mtu", &TestConfig::mtu }, { "-export-keying-material", &TestConfig::export_keying_material }, { "-expect-total-renegotiations", &TestConfig::expect_total_renegotiations }, - { "-expect-server-key-exchange-hash", - &TestConfig::expect_server_key_exchange_hash }, - { "-expect-key-exchange-info", - &TestConfig::expect_key_exchange_info }, + { "-expect-peer-signature-algorithm", + &TestConfig::expect_peer_signature_algorithm }, + { "-expect-curve-id", &TestConfig::expect_curve_id }, + { "-expect-dhe-group-size", &TestConfig::expect_dhe_group_size }, + { "-initial-timeout-duration-ms", &TestConfig::initial_timeout_duration_ms }, + { "-max-cert-list", &TestConfig::max_cert_list }, +}; + +const Flag> kIntVectorFlags[] = { + { "-signing-prefs", &TestConfig::signing_prefs }, }; } // namespace @@ -200,6 +213,20 @@ bool ParseConfig(int argc, char **argv, TestConfig *out_config) { continue; } + std::vector *int_vector_field = + FindField(out_config, kIntVectorFlags, argv[i]); + if (int_vector_field) { + i++; + if (i >= argc) { + fprintf(stderr, "Missing parameter\n"); + return false; + } + + // Each instance of the flag adds to the list. + int_vector_field->push_back(atoi(argv[i])); + continue; + } + fprintf(stderr, "Unknown argument: %s\n", argv[i]); return false; } diff --git a/test/ossl_shim/test_config.h b/test/ossl_shim/test_config.h index e04fdd40ea..9f742975b5 100644 --- a/test/ossl_shim/test_config.h +++ b/test/ossl_shim/test_config.h @@ -16,15 +16,17 @@ #define HEADER_TEST_CONFIG #include +#include struct TestConfig { int port = 0; bool is_server = false; bool is_dtls = false; - bool resume = false; + int resume_count = 0; bool fallback_scsv = false; std::string digest_prefs; + std::vector signing_prefs; std::string key_file; std::string cert_file; std::string expected_server_name; @@ -38,11 +40,13 @@ struct TestConfig { bool write_different_record_sizes = false; bool cbc_record_splitting = false; bool partial_write = false; + bool no_tls13 = false; bool no_tls12 = false; bool no_tls11 = false; bool no_tls1 = false; bool no_ssl3 = false; std::string expected_channel_id; + bool enable_channel_id = false; std::string send_channel_id; bool shim_writes_first = false; std::string host_name; @@ -50,6 +54,7 @@ struct TestConfig { std::string expected_alpn; std::string expected_advertised_alpn; std::string select_alpn; + bool decline_alpn = false; bool expect_session_miss = false; bool expect_extended_master_secret = false; std::string psk; @@ -97,12 +102,19 @@ struct TestConfig { bool renegotiate_freely = false; bool renegotiate_ignore = false; bool disable_npn = false; - int expect_server_key_exchange_hash = 0; + int expect_peer_signature_algorithm = 0; bool p384_only = false; bool enable_all_curves = false; bool use_sparse_dh_prime = false; - int expect_key_exchange_info = 0; + int expect_curve_id = 0; + int expect_dhe_group_size = 0; bool use_old_client_cert_callback = false; + int initial_timeout_duration_ms = 0; + bool use_null_client_ca_list = false; + bool send_alert = false; + bool peek_then_read = false; + bool enable_grease = false; + int max_cert_list = 0; }; bool ParseConfig(int argc, char **argv, TestConfig *out_config); -- 2.39.2