summaryrefslogtreecommitdiffstats
path: root/test/ossl_shim
diff options
context:
space:
mode:
authorMatt Caswell <matt@openssl.org>2016-10-10 12:17:21 +0100
committerMatt Caswell <matt@openssl.org>2016-11-04 10:38:54 +0000
commiteef977aa0e6c6614bc99bd8357bc4afba91737f7 (patch)
tree808c4ca152294bf661af4ba6e8e84912c3b18bc7 /test/ossl_shim
parent62dd3351a16089aedb0f1e62e3b6df371c93389c (diff)
Integrate BoringSSL shim
The BoringSSL test suite contains numerous tests which OpenSSL does not. The BoringSSL test runner uses a shim to launch the library and execute the tests. This is a version of the BoringSSL shim converted to compile against OpenSSL instead. This is primarily based on the work of David Benjamin from the BoringSSL project who did most of the necessary conversion. It also includes a few other tweaks for opacity changes etc. This is based on a *very* old version of BoringSSL from commit f277add6c. That was the last commit known to work with this patched shim. Later versions may also work but lots of merge conflicts occur when trying to bring it up to date. At the moment this has not been integrated into the build system. There is a very simple standalone makefile in the ossl_shim directory which should be executed directly before tyring to use the shim. Reviewed-by: Richard Levitte <levitte@openssl.org>
Diffstat (limited to 'test/ossl_shim')
-rw-r--r--test/ossl_shim/Makefile9
-rw-r--r--test/ossl_shim/async_bio.cc196
-rw-r--r--test/ossl_shim/async_bio.h45
-rw-r--r--test/ossl_shim/crypto/scoped_types.h102
-rw-r--r--test/ossl_shim/ossl_shim.cc1237
-rw-r--r--test/ossl_shim/packeted_bio.cc189
-rw-r--r--test/ossl_shim/packeted_bio.h44
-rw-r--r--test/ossl_shim/scoped_types.h28
-rw-r--r--test/ossl_shim/test_config.cc208
-rw-r--r--test/ossl_shim/test_config.h111
10 files changed, 2169 insertions, 0 deletions
diff --git a/test/ossl_shim/Makefile b/test/ossl_shim/Makefile
new file mode 100644
index 0000000000..688317cc79
--- /dev/null
+++ b/test/ossl_shim/Makefile
@@ -0,0 +1,9 @@
+all: ossl_shim
+
+ossl_shim: ../../libssl.a ../../libcrypto.a *.cc
+ g++ -g -std=c++11 -I. -I../../include *.cc \
+ ../../libssl.a ../../libcrypto.a -ldl -lpthread \
+ -o ossl_shim
+
+clean:
+ rm ossl_shim
diff --git a/test/ossl_shim/async_bio.cc b/test/ossl_shim/async_bio.cc
new file mode 100644
index 0000000000..825b22372f
--- /dev/null
+++ b/test/ossl_shim/async_bio.cc
@@ -0,0 +1,196 @@
+/* Copyright (c) 2014, 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. */
+
+#include "async_bio.h"
+
+#include <errno.h>
+#include <string.h>
+
+#include <openssl/crypto.h>
+
+
+namespace {
+
+struct AsyncBio {
+ bool datagram;
+ bool enforce_write_quota;
+ size_t read_quota;
+ size_t write_quota;
+};
+
+AsyncBio *GetData(BIO *bio) {
+ /*
+ * TODO: Missing accessor? This probably needs a BIO_get_method() in OpenSSL
+ * For now skip this check
+ */
+#if 0
+ if (bio->method != &g_async_bio_method) {
+ return NULL;
+ }
+#endif
+ return (AsyncBio *)BIO_get_data(bio);
+}
+
+static int AsyncWrite(BIO *bio, const char *in, int inl) {
+ AsyncBio *a = GetData(bio);
+ if (a == NULL || BIO_next(bio) == NULL) {
+ return 0;
+ }
+
+ if (!a->enforce_write_quota) {
+ return BIO_write(BIO_next(bio), in, inl);
+ }
+
+ BIO_clear_retry_flags(bio);
+
+ if (a->write_quota == 0) {
+ BIO_set_retry_write(bio);
+ errno = EAGAIN;
+ return -1;
+ }
+
+ if (!a->datagram && (size_t)inl > a->write_quota) {
+ inl = a->write_quota;
+ }
+ int ret = BIO_write(BIO_next(bio), in, inl);
+ if (ret <= 0) {
+ BIO_copy_next_retry(bio);
+ } else {
+ a->write_quota -= (a->datagram ? 1 : ret);
+ }
+ return ret;
+}
+
+static int AsyncRead(BIO *bio, char *out, int outl) {
+ AsyncBio *a = GetData(bio);
+ if (a == NULL || BIO_next(bio) == NULL) {
+ return 0;
+ }
+
+ BIO_clear_retry_flags(bio);
+
+ if (a->read_quota == 0) {
+ BIO_set_retry_read(bio);
+ errno = EAGAIN;
+ return -1;
+ }
+
+ if (!a->datagram && (size_t)outl > a->read_quota) {
+ outl = a->read_quota;
+ }
+ int ret = BIO_read(BIO_next(bio), out, outl);
+ if (ret <= 0) {
+ BIO_copy_next_retry(bio);
+ } else {
+ a->read_quota -= (a->datagram ? 1 : ret);
+ }
+ return ret;
+}
+
+static long AsyncCtrl(BIO *bio, int cmd, long num, void *ptr) {
+ if (BIO_next(bio) == NULL) {
+ return 0;
+ }
+ BIO_clear_retry_flags(bio);
+ int ret = BIO_ctrl(BIO_next(bio), cmd, num, ptr);
+ BIO_copy_next_retry(bio);
+ return ret;
+}
+
+static int AsyncNew(BIO *bio) {
+ AsyncBio *a = (AsyncBio *)OPENSSL_malloc(sizeof(*a));
+ if (a == NULL) {
+ return 0;
+ }
+ memset(a, 0, sizeof(*a));
+ a->enforce_write_quota = true;
+ BIO_set_init(bio, 1);
+ BIO_set_data(bio, a);
+ return 1;
+}
+
+static int AsyncFree(BIO *bio) {
+ if (bio == NULL) {
+ return 0;
+ }
+
+ OPENSSL_free(BIO_get_data(bio));
+ BIO_set_data(bio, NULL);
+ BIO_set_init(bio, 0);
+ return 1;
+}
+
+static long AsyncCallbackCtrl(BIO *bio, int cmd, bio_info_cb fp) {
+ if (BIO_next(bio) == NULL) {
+ return 0;
+ }
+ return BIO_callback_ctrl(BIO_next(bio), cmd, fp);
+}
+
+static BIO_METHOD *g_async_bio_method = NULL;
+
+static const BIO_METHOD *AsyncMethod(void)
+{
+ if (g_async_bio_method == NULL) {
+ g_async_bio_method = BIO_meth_new(BIO_TYPE_FILTER, "async bio");
+ if ( g_async_bio_method == NULL
+ || !BIO_meth_set_write(g_async_bio_method, AsyncWrite)
+ || !BIO_meth_set_read(g_async_bio_method, AsyncRead)
+ || !BIO_meth_set_ctrl(g_async_bio_method, AsyncCtrl)
+ || !BIO_meth_set_create(g_async_bio_method, AsyncNew)
+ || !BIO_meth_set_destroy(g_async_bio_method, AsyncFree)
+ || !BIO_meth_set_callback_ctrl(g_async_bio_method, AsyncCallbackCtrl))
+ return NULL;
+ }
+ return g_async_bio_method;
+}
+
+} // namespace
+
+ScopedBIO AsyncBioCreate() {
+ return ScopedBIO(BIO_new(AsyncMethod()));
+}
+
+ScopedBIO AsyncBioCreateDatagram() {
+ ScopedBIO ret(BIO_new(AsyncMethod()));
+ if (!ret) {
+ return nullptr;
+ }
+ GetData(ret.get())->datagram = true;
+ return ret;
+}
+
+void AsyncBioAllowRead(BIO *bio, size_t count) {
+ AsyncBio *a = GetData(bio);
+ if (a == NULL) {
+ return;
+ }
+ a->read_quota += count;
+}
+
+void AsyncBioAllowWrite(BIO *bio, size_t count) {
+ AsyncBio *a = GetData(bio);
+ if (a == NULL) {
+ return;
+ }
+ a->write_quota += count;
+}
+
+void AsyncBioEnforceWriteQuota(BIO *bio, bool enforce) {
+ AsyncBio *a = GetData(bio);
+ if (a == NULL) {
+ return;
+ }
+ a->enforce_write_quota = enforce;
+}
diff --git a/test/ossl_shim/async_bio.h b/test/ossl_shim/async_bio.h
new file mode 100644
index 0000000000..9466a8ca3d
--- /dev/null
+++ b/test/ossl_shim/async_bio.h
@@ -0,0 +1,45 @@
+/* Copyright (c) 2014, 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 HEADER_ASYNC_BIO
+#define HEADER_ASYNC_BIO
+
+#include <openssl/bio.h>
+
+#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();
+
+// 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();
+
+// AsyncBioAllowRead increments |bio|'s read quota by |count|.
+void AsyncBioAllowRead(BIO *bio, size_t count);
+
+// AsyncBioAllowWrite increments |bio|'s write quota by |count|.
+void AsyncBioAllowWrite(BIO *bio, size_t count);
+
+// AsyncBioEnforceWriteQuota configures where |bio| enforces its write quota.
+void AsyncBioEnforceWriteQuota(BIO *bio, bool enforce);
+
+
+#endif // HEADER_ASYNC_BIO
diff --git a/test/ossl_shim/crypto/scoped_types.h b/test/ossl_shim/crypto/scoped_types.h
new file mode 100644
index 0000000000..a1f6851228
--- /dev/null
+++ b/test/ossl_shim/crypto/scoped_types.h
@@ -0,0 +1,102 @@
+/* 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 <stdint.h>
+#include <stdio.h>
+
+#include <memory>
+
+#include <openssl/asn1.h>
+#include <openssl/bio.h>
+#include <openssl/bn.h>
+#include <openssl/crypto.h>
+#include <openssl/cmac.h>
+#include <openssl/dh.h>
+#include <openssl/ecdsa.h>
+#include <openssl/ec.h>
+#include <openssl/evp.h>
+#include <openssl/pkcs12.h>
+#include <openssl/rsa.h>
+#include <openssl/stack.h>
+#include <openssl/x509.h>
+
+
+template<typename T, void (*func)(T*)>
+struct OpenSSLDeleter {
+ void operator()(T *obj) {
+ func(obj);
+ }
+};
+
+template<typename StackType, typename T, void (*func)(T*)>
+struct OpenSSLStackDeleter {
+ void operator()(StackType *obj) {
+ sk_pop_free(reinterpret_cast<_STACK*>(obj),
+ reinterpret_cast<void (*)(void *)>(func));
+ }
+};
+
+template<typename T>
+struct OpenSSLFree {
+ void operator()(T *buf) {
+ OPENSSL_free(buf);
+ }
+};
+
+struct FileCloser {
+ void operator()(FILE *file) {
+ fclose(file);
+ }
+};
+
+template<typename T, void (*func)(T*)>
+using ScopedOpenSSLType = std::unique_ptr<T, OpenSSLDeleter<T, func>>;
+
+template<typename StackType, typename T, void (*func)(T*)>
+using ScopedOpenSSLStack =
+ std::unique_ptr<StackType, OpenSSLStackDeleter<StackType, T, func>>;
+
+using ScopedASN1_TYPE = ScopedOpenSSLType<ASN1_TYPE, ASN1_TYPE_free>;
+using ScopedBIO = ScopedOpenSSLType<BIO, BIO_vfree>;
+using ScopedBIGNUM = ScopedOpenSSLType<BIGNUM, BN_free>;
+using ScopedBN_CTX = ScopedOpenSSLType<BN_CTX, BN_CTX_free>;
+using ScopedBN_MONT_CTX = ScopedOpenSSLType<BN_MONT_CTX, BN_MONT_CTX_free>;
+using ScopedCMAC_CTX = ScopedOpenSSLType<CMAC_CTX, CMAC_CTX_free>;
+using ScopedDH = ScopedOpenSSLType<DH, DH_free>;
+using ScopedECDSA_SIG = ScopedOpenSSLType<ECDSA_SIG, ECDSA_SIG_free>;
+using ScopedEC_GROUP = ScopedOpenSSLType<EC_GROUP, EC_GROUP_free>;
+using ScopedEC_KEY = ScopedOpenSSLType<EC_KEY, EC_KEY_free>;
+using ScopedEC_POINT = ScopedOpenSSLType<EC_POINT, EC_POINT_free>;
+using ScopedEVP_PKEY = ScopedOpenSSLType<EVP_PKEY, EVP_PKEY_free>;
+using ScopedEVP_PKEY_CTX = ScopedOpenSSLType<EVP_PKEY_CTX, EVP_PKEY_CTX_free>;
+using ScopedPKCS8_PRIV_KEY_INFO = ScopedOpenSSLType<PKCS8_PRIV_KEY_INFO,
+ PKCS8_PRIV_KEY_INFO_free>;
+using ScopedPKCS12 = ScopedOpenSSLType<PKCS12, PKCS12_free>;
+using ScopedRSA = ScopedOpenSSLType<RSA, RSA_free>;
+using ScopedX509 = ScopedOpenSSLType<X509, X509_free>;
+using ScopedX509_ALGOR = ScopedOpenSSLType<X509_ALGOR, X509_ALGOR_free>;
+using ScopedX509_SIG = ScopedOpenSSLType<X509_SIG, X509_SIG_free>;
+using ScopedX509_STORE_CTX = ScopedOpenSSLType<X509_STORE_CTX, X509_STORE_CTX_free>;
+
+using ScopedX509Stack = ScopedOpenSSLStack<STACK_OF(X509), X509, X509_free>;
+
+using ScopedOpenSSLBytes = std::unique_ptr<uint8_t, OpenSSLFree<uint8_t>>;
+using ScopedOpenSSLString = std::unique_ptr<char, OpenSSLFree<char>>;
+
+using ScopedFILE = std::unique_ptr<FILE, FileCloser>;
+
+#endif // OPENSSL_HEADER_CRYPTO_TEST_SCOPED_TYPES_H
diff --git a/test/ossl_shim/ossl_shim.cc b/test/ossl_shim/ossl_shim.cc
new file mode 100644
index 0000000000..b1abcf6d6c
--- /dev/null
+++ b/test/ossl_shim/ossl_shim.cc
@@ -0,0 +1,1237 @@
+/* Copyright (c) 2014, 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. */
+
+#if !defined(__STDC_FORMAT_MACROS)
+#define __STDC_FORMAT_MACROS
+#endif
+
+#include <openssl/e_os2.h>
+
+#if !defined(OPENSSL_SYS_WINDOWS)
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <signal.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <unistd.h>
+#else
+#include <io.h>
+#pragma warning(push, 3)
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#pragma warning(pop)
+
+#pragma comment(lib, "Ws2_32.lib")
+#endif
+
+#include <inttypes.h>
+#include <string.h>
+
+#include <openssl/bio.h>
+#include <openssl/buffer.h>
+#include <openssl/crypto.h>
+#include <openssl/dh.h>
+#include <openssl/err.h>
+#include <openssl/evp.h>
+#include <openssl/hmac.h>
+#include <openssl/objects.h>
+#include <openssl/rand.h>
+#include <openssl/ssl.h>
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "crypto/scoped_types.h"
+#include "async_bio.h"
+#include "packeted_bio.h"
+#include "scoped_types.h"
+#include "test_config.h"
+
+
+#if !defined(OPENSSL_SYS_WINDOWS)
+static int closesocket(int sock) {
+ return close(sock);
+}
+
+static void PrintSocketError(const char *func) {
+ perror(func);
+}
+#else
+static void PrintSocketError(const char *func) {
+ fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
+}
+#endif
+
+static int Usage(const char *program) {
+ fprintf(stderr, "Usage: %s [flags...]\n", program);
+ return 1;
+}
+
+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;
+ bool cert_ready = false;
+ ScopedSSL_SESSION session;
+ ScopedSSL_SESSION 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;
+ std::vector<uint8_t> 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;
+};
+
+static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
+ int index, long argl, void *argp) {
+ delete ((TestState *)ptr);
+}
+
+static int g_config_index = 0;
+static int g_state_index = 0;
+
+static bool SetConfigPtr(SSL *ssl, const TestConfig *config) {
+ return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
+}
+
+static const TestConfig *GetConfigPtr(const SSL *ssl) {
+ return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
+}
+
+static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
+ // |SSL_set_ex_data| takes ownership of |state| only on success.
+ if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
+ state.release();
+ return true;
+ }
+ return false;
+}
+
+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()));
+ if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
+ return nullptr;
+ }
+ return ScopedX509(PEM_read_bio_X509(bio.get(), NULL, NULL, NULL));
+}
+
+static ScopedEVP_PKEY LoadPrivateKey(const std::string &file) {
+ ScopedBIO 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));
+}
+
+template<typename T>
+struct Free {
+ void operator()(T *buf) {
+ free(buf);
+ }
+};
+
+static bool GetCertificate(SSL *ssl, ScopedX509 *out_x509,
+ ScopedEVP_PKEY *out_pkey) {
+ const TestConfig *config = GetConfigPtr(ssl);
+
+ if (!config->digest_prefs.empty()) {
+ fprintf(stderr, "Digest prefs not supported.\n");
+ return false;
+ }
+
+ if (!config->key_file.empty()) {
+ *out_pkey = LoadPrivateKey(config->key_file.c_str());
+ if (!*out_pkey) {
+ return false;
+ }
+ }
+ if (!config->cert_file.empty()) {
+ *out_x509 = LoadCertificate(config->cert_file.c_str());
+ if (!*out_x509) {
+ return false;
+ }
+ }
+ if (!config->ocsp_response.empty()) {
+ fprintf(stderr, "OCSP response not supported.\n");
+ return false;
+ }
+ return true;
+}
+
+static bool InstallCertificate(SSL *ssl) {
+ ScopedX509 x509;
+ ScopedEVP_PKEY pkey;
+ if (!GetCertificate(ssl, &x509, &pkey)) {
+ return false;
+ }
+
+ if (pkey) {
+ TestState *test_state = GetTestState(ssl);
+ const TestConfig *config = GetConfigPtr(ssl);
+ if (!SSL_use_PrivateKey(ssl, pkey.get())) {
+ return false;
+ }
+ }
+
+ if (x509 && !SSL_use_certificate(ssl, x509.get())) {
+ return false;
+ }
+
+ return true;
+}
+
+static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
+ if (GetConfigPtr(ssl)->async && !GetTestState(ssl)->cert_ready) {
+ return -1;
+ }
+
+ ScopedX509 x509;
+ ScopedEVP_PKEY pkey;
+ if (!GetCertificate(ssl, &x509, &pkey)) {
+ return -1;
+ }
+
+ // Return zero for no certificate.
+ if (!x509) {
+ return 0;
+ }
+
+ // Asynchronous private keys are not supported with client_cert_cb.
+ *out_x509 = x509.release();
+ *out_pkey = pkey.release();
+ return 1;
+}
+
+static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
+ return 1;
+}
+
+static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
+ X509_STORE_CTX_set_error(store_ctx, X509_V_ERR_APPLICATION_VERIFICATION);
+ return 0;
+}
+
+static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
+ unsigned int *out_len, void *arg) {
+ const TestConfig *config = GetConfigPtr(ssl);
+ if (config->advertise_npn.empty()) {
+ return SSL_TLSEXT_ERR_NOACK;
+ }
+
+ *out = (const uint8_t*)config->advertise_npn.data();
+ *out_len = config->advertise_npn.size();
+ return SSL_TLSEXT_ERR_OK;
+}
+
+static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
+ const uint8_t* in, unsigned inlen, void* arg) {
+ const TestConfig *config = GetConfigPtr(ssl);
+ if (config->select_next_proto.empty()) {
+ return SSL_TLSEXT_ERR_NOACK;
+ }
+
+ *out = (uint8_t*)config->select_next_proto.data();
+ *outlen = config->select_next_proto.size();
+ return SSL_TLSEXT_ERR_OK;
+}
+
+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()) {
+ return SSL_TLSEXT_ERR_NOACK;
+ }
+
+ if (!config->expected_advertised_alpn.empty() &&
+ (config->expected_advertised_alpn.size() != inlen ||
+ memcmp(config->expected_advertised_alpn.data(),
+ in, inlen) != 0)) {
+ fprintf(stderr, "bad ALPN select callback inputs\n");
+ exit(1);
+ }
+
+ *out = (const uint8_t*)config->select_alpn.data();
+ *outlen = config->select_alpn.size();
+ return SSL_TLSEXT_ERR_OK;
+}
+
+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);
+
+ if (strcmp(hint ? hint : "", config->psk_identity.c_str()) != 0) {
+ fprintf(stderr, "Server PSK hint did not match.\n");
+ return 0;
+ }
+
+ // Account for the trailing '\0' for the identity.
+ if (config->psk_identity.size() >= max_identity_len ||
+ config->psk.size() > max_psk_len) {
+ fprintf(stderr, "PSK buffers too small\n");
+ return 0;
+ }
+
+ BUF_strlcpy(out_identity, config->psk_identity.c_str(),
+ max_identity_len);
+ memcpy(out_psk, config->psk.data(), config->psk.size());
+ return config->psk.size();
+}
+
+static unsigned PskServerCallback(SSL *ssl, const char *identity,
+ uint8_t *out_psk, unsigned max_psk_len) {
+ const TestConfig *config = GetConfigPtr(ssl);
+
+ if (strcmp(identity, config->psk_identity.c_str()) != 0) {
+ fprintf(stderr, "Client PSK identity did not match.\n");
+ return 0;
+ }
+
+ if (config->psk.size() > max_psk_len) {
+ fprintf(stderr, "PSK buffers too small\n");
+ return 0;
+ }
+
+ memcpy(out_psk, config->psk.data(), config->psk.size());
+ return config->psk.size();
+}
+
+static int CertCallback(SSL *ssl, void *arg) {
+ if (!GetTestState(ssl)->cert_ready) {
+ return -1;
+ }
+ if (!InstallCertificate(ssl)) {
+ return 0;
+ }
+ return 1;
+}
+
+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");
+ // Abort before any expected error code is printed, to ensure the overall
+ // test fails.
+ abort();
+ }
+ GetTestState(ssl)->handshake_done = true;
+ }
+}
+
+static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
+ GetTestState(ssl)->got_new_session = true;
+ // BoringSSL passes a reference to |session|.
+ SSL_SESSION_free(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) {
+ // This is just test code, so use the all-zeros key.
+ static const uint8_t kZeros[16] = {0};
+
+ if (encrypt) {
+ memcpy(key_name, kZeros, sizeof(kZeros));
+ RAND_bytes(iv, 16);
+ } else if (memcmp(key_name, kZeros, 16) != 0) {
+ return 0;
+ }
+
+ if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
+ !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
+ return -1;
+ }
+
+ if (!encrypt) {
+ return GetConfigPtr(ssl)->renew_ticket ? 2 : 1;
+ }
+ return 1;
+}
+
+// kCustomExtensionValue is the extension value that the custom extension
+// callbacks will add.
+static const uint16_t kCustomExtensionValue = 1234;
+static void *const kCustomExtensionAddArg =
+ reinterpret_cast<void *>(kCustomExtensionValue);
+static void *const kCustomExtensionParseArg =
+ reinterpret_cast<void *>(kCustomExtensionValue + 1);
+static const char kCustomExtensionContents[] = "custom extension";
+
+static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
+ const uint8_t **out, size_t *out_len,
+ int *out_alert_value, void *add_arg) {
+ if (extension_value != kCustomExtensionValue ||
+ add_arg != kCustomExtensionAddArg) {
+ abort();
+ }
+
+ if (GetConfigPtr(ssl)->custom_extension_skip) {
+ return 0;
+ }
+ if (GetConfigPtr(ssl)->custom_extension_fail_add) {
+ return -1;
+ }
+
+ *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
+ *out_len = sizeof(kCustomExtensionContents) - 1;
+
+ return 1;
+}
+
+static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
+ const uint8_t *out, void *add_arg) {
+ if (extension_value != kCustomExtensionValue ||
+ add_arg != kCustomExtensionAddArg ||
+ out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
+ abort();
+ }
+}
+
+static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
+ const uint8_t *contents,
+ size_t contents_len,
+ int *out_alert_value, void *parse_arg) {
+ if (extension_value != kCustomExtensionValue ||
+ parse_arg != kCustomExtensionParseArg) {
+ abort();
+ }
+
+ if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
+ memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
+ *out_alert_value = SSL_AD_DECODE_ERROR;
+ return 0;
+ }
+
+ return 1;
+}
+
+// Connect returns a new socket connected to localhost on |port| or -1 on
+// error.
+static int Connect(uint16_t port) {
+ int sock = socket(AF_INET, SOCK_STREAM, 0);
+ if (sock == -1) {
+ PrintSocketError("socket");
+ return -1;
+ }
+ int nodelay = 1;
+ if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
+ reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
+ PrintSocketError("setsockopt");
+ closesocket(sock);
+ return -1;
+ }
+ sockaddr_in sin;
+ memset(&sin, 0, sizeof(sin));
+ sin.sin_family = AF_INET;
+ sin.sin_port = htons(port);
+ if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
+ PrintSocketError("inet_pton");
+ closesocket(sock);
+ return -1;
+ }
+ if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
+ sizeof(sin)) != 0) {
+ PrintSocketError("connect");
+ closesocket(sock);
+ return -1;
+ }
+ return sock;
+}
+
+class SocketCloser {
+ public:
+ explicit SocketCloser(int sock) : sock_(sock) {}
+ ~SocketCloser() {
+ // Half-close and drain the socket before releasing it. This seems to be
+ // necessary for graceful shutdown on Windows. It will also avoid write
+ // failures in the test runner.
+#if defined(OPENSSL_WINDOWS)
+ shutdown(sock_, SD_SEND);
+#else
+ shutdown(sock_, SHUT_WR);
+#endif
+ while (true) {
+ char buf[1024];
+ if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
+ break;
+ }
+ }
+ closesocket(sock_);
+ }
+
+ private:
+ const int sock_;
+};
+
+static ScopedSSL_CTX SetupCtx(const TestConfig *config) {
+ ScopedSSL_CTX 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);
+
+ std::string cipher_list = "ALL";
+ if (!config->cipher.empty()) {
+ cipher_list = config->cipher;
+ SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
+ }
+ if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
+ return nullptr;
+ }
+
+ if (!config->cipher_tls10.empty() || !config->cipher_tls11.empty()) {
+ fprintf(stderr, "version-specific cipher lists not supported.\n");
+ return nullptr;
+ }
+
+ DH *tmpdh;
+
+ if (config->use_sparse_dh_prime) {
+ BIGNUM *p, *g;
+ p = BN_new();
+ g = BN_new();
+ tmpdh = DH_new();
+ if (p == NULL || g == NULL || tmpdh == NULL) {
+ BN_free(p);
+ BN_free(g);
+ DH_free(tmpdh);
+ return nullptr;
+ }
+ // This prime number is 2^1024 + 643 – a value just above a power of two.
+ // Because of its form, values modulo it are essentially certain to be one
+ // byte shorter. This is used to test padding of these values.
+ if (BN_hex2bn(
+ &p,
+ "1000000000000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000028"
+ "3") == 0 ||
+ !BN_set_word(g, 2)) {
+ BN_free(p);
+ BN_free(g);
+ DH_free(tmpdh);
+ return nullptr;
+ }
+ DH_set0_pqg(tmpdh, p, NULL, g);
+ } else {
+ tmpdh = DH_get_2048_256();
+ }
+
+ ScopedDH dh(tmpdh);
+
+ if (!dh || !SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
+ return nullptr;
+ }
+
+ SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
+
+ if (config->use_old_client_cert_callback) {
+ SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
+ }
+
+ SSL_CTX_set_next_protos_advertised_cb(
+ ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
+ if (!config->select_next_proto.empty()) {
+ SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
+ NULL);
+ }
+
+ if (!config->select_alpn.empty()) {
+ SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
+ }
+
+ SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
+ SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
+
+ if (config->use_ticket_callback) {
+ SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
+ }
+
+ if (config->enable_client_custom_extension &&
+ !SSL_CTX_add_client_custom_ext(
+ ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
+ CustomExtensionFreeCallback, kCustomExtensionAddArg,
+ CustomExtensionParseCallback, kCustomExtensionParseArg)) {
+ return nullptr;
+ }
+
+ if (config->enable_server_c