1 /* Copyright (c) 2014, Google Inc.
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
15 #if !defined(__STDC_FORMAT_MACROS)
16 #define __STDC_FORMAT_MACROS
19 #include <openssl/base.h>
21 #if !defined(OPENSSL_WINDOWS)
22 #include <arpa/inet.h>
23 #include <netinet/in.h>
24 #include <netinet/tcp.h>
26 #include <sys/socket.h>
31 OPENSSL_MSVC_PRAGMA(warning(push, 3))
34 OPENSSL_MSVC_PRAGMA(warning(pop))
36 OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
44 #include <openssl/aead.h>
45 #include <openssl/bio.h>
46 #include <openssl/buf.h>
47 #include <openssl/bytestring.h>
48 #include <openssl/cipher.h>
49 #include <openssl/crypto.h>
50 #include <openssl/digest.h>
51 #include <openssl/err.h>
52 #include <openssl/evp.h>
53 #include <openssl/hmac.h>
54 #include <openssl/nid.h>
55 #include <openssl/rand.h>
56 #include <openssl/ssl.h>
57 #include <openssl/x509.h>
64 #include "../../crypto/internal.h"
65 #include "../internal.h"
66 #include "async_bio.h"
67 #include "fuzzer_tags.h"
68 #include "packeted_bio.h"
69 #include "test_config.h"
72 static CRYPTO_BUFFER_POOL *g_pool = nullptr;
74 #if !defined(OPENSSL_WINDOWS)
75 static int closesocket(int sock) {
79 static void PrintSocketError(const char *func) {
83 static void PrintSocketError(const char *func) {
84 fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
88 static int Usage(const char *program) {
89 fprintf(stderr, "Usage: %s [flags...]\n", program);
94 // async_bio is async BIO which pauses reads and writes.
95 BIO *async_bio = nullptr;
96 // packeted_bio is the packeted BIO which simulates read timeouts.
97 BIO *packeted_bio = nullptr;
98 bssl::UniquePtr<EVP_PKEY> channel_id;
99 bool cert_ready = false;
100 bssl::UniquePtr<SSL_SESSION> session;
101 bssl::UniquePtr<SSL_SESSION> pending_session;
102 bool early_callback_called = false;
103 bool handshake_done = false;
104 // private_key is the underlying private key used when testing custom keys.
105 bssl::UniquePtr<EVP_PKEY> private_key;
106 std::vector<uint8_t> private_key_result;
107 // private_key_retries is the number of times an asynchronous private key
108 // operation has been retried.
109 unsigned private_key_retries = 0;
110 bool got_new_session = false;
111 bssl::UniquePtr<SSL_SESSION> new_session;
112 bool ticket_decrypt_done = false;
113 bool alpn_select_done = false;
114 bool is_resume = false;
115 bool early_callback_ready = false;
116 bool custom_verify_ready = false;
117 std::string msg_callback_text;
118 bool msg_callback_ok = true;
119 // cert_verified is true if certificate verification has been driven to
120 // completion. This tests that the callback is not called again after this.
121 bool cert_verified = false;
124 static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
125 int index, long argl, void *argp) {
126 delete ((TestState *)ptr);
129 static int g_config_index = 0;
130 static int g_state_index = 0;
132 static bool SetTestConfig(SSL *ssl, const TestConfig *config) {
133 return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
136 static const TestConfig *GetTestConfig(const SSL *ssl) {
137 return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
140 static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
141 // |SSL_set_ex_data| takes ownership of |state| only on success.
142 if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
149 static TestState *GetTestState(const SSL *ssl) {
150 return (TestState *)SSL_get_ex_data(ssl, g_state_index);
153 static bool MoveExData(SSL *dest, SSL *src) {
154 TestState *state = GetTestState(src);
155 const TestConfig *config = GetTestConfig(src);
156 if (!SSL_set_ex_data(src, g_state_index, nullptr) ||
157 !SSL_set_ex_data(dest, g_state_index, state) ||
158 !SSL_set_ex_data(src, g_config_index, nullptr) ||
159 !SSL_set_ex_data(dest, g_config_index, (void *) config)) {
166 static void MoveBIOs(SSL *dest, SSL *src) {
167 BIO *rbio = SSL_get_rbio(src);
169 SSL_set0_rbio(dest, rbio);
171 BIO *wbio = SSL_get_wbio(src);
173 SSL_set0_wbio(dest, wbio);
175 SSL_set0_rbio(src, nullptr);
176 SSL_set0_wbio(src, nullptr);
179 static bool LoadCertificate(bssl::UniquePtr<X509> *out_x509,
180 bssl::UniquePtr<STACK_OF(X509)> *out_chain,
181 const std::string &file) {
182 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
183 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
187 out_x509->reset(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
192 out_chain->reset(sk_X509_new_null());
197 // Keep reading the certificate chain.
199 bssl::UniquePtr<X509> cert(
200 PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
205 if (!sk_X509_push(out_chain->get(), cert.get())) {
208 cert.release(); // sk_X509_push takes ownership.
211 uint32_t err = ERR_peek_last_error();
212 if (ERR_GET_LIB(err) != ERR_LIB_PEM ||
213 ERR_GET_REASON(err) != PEM_R_NO_START_LINE) {
221 static bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
222 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
223 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
226 return bssl::UniquePtr<EVP_PKEY>(
227 PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
230 static bool FromHexDigit(uint8_t *out, char c) {
231 if ('0' <= c && c <= '9') {
235 if ('a' <= c && c <= 'f') {
239 if ('A' <= c && c <= 'F') {
246 static bool HexDecode(std::string *out, const std::string &in) {
247 if ((in.size() & 1) != 0) {
251 std::unique_ptr<uint8_t[]> buf(new uint8_t[in.size() / 2]);
252 for (size_t i = 0; i < in.size() / 2; i++) {
254 if (!FromHexDigit(&high, in[i*2]) ||
255 !FromHexDigit(&low, in[i*2+1])) {
258 buf[i] = (high << 4) | low;
261 out->assign(reinterpret_cast<const char *>(buf.get()), in.size() / 2);
265 static std::vector<std::string> SplitParts(const std::string &in,
267 std::vector<std::string> ret;
270 for (size_t i = 0; i < in.size(); i++) {
271 if (in[i] == delim) {
272 ret.push_back(in.substr(start, i - start));
277 ret.push_back(in.substr(start, std::string::npos));
281 static std::vector<std::string> DecodeHexStrings(
282 const std::string &hex_strings) {
283 std::vector<std::string> ret;
284 const std::vector<std::string> parts = SplitParts(hex_strings, ',');
286 for (const auto &part : parts) {
288 if (!HexDecode(&binary, part)) {
289 fprintf(stderr, "Bad hex string: %s\n", part.c_str());
293 ret.push_back(binary);
299 static bssl::UniquePtr<STACK_OF(X509_NAME)> DecodeHexX509Names(
300 const std::string &hex_names) {
301 const std::vector<std::string> der_names = DecodeHexStrings(hex_names);
302 bssl::UniquePtr<STACK_OF(X509_NAME)> ret(sk_X509_NAME_new_null());
307 for (const auto &der_name : der_names) {
308 const uint8_t *const data =
309 reinterpret_cast<const uint8_t *>(der_name.data());
310 const uint8_t *derp = data;
311 bssl::UniquePtr<X509_NAME> name(
312 d2i_X509_NAME(nullptr, &derp, der_name.size()));
313 if (!name || derp != data + der_name.size()) {
314 fprintf(stderr, "Failed to parse X509_NAME.\n");
318 if (!sk_X509_NAME_push(ret.get(), name.get())) {
327 static ssl_private_key_result_t AsyncPrivateKeySign(
328 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
329 uint16_t signature_algorithm, const uint8_t *in, size_t in_len) {
330 TestState *test_state = GetTestState(ssl);
331 if (!test_state->private_key_result.empty()) {
332 fprintf(stderr, "AsyncPrivateKeySign called with operation pending.\n");
336 // Determine the hash.
338 switch (signature_algorithm) {
339 case SSL_SIGN_RSA_PKCS1_SHA1:
340 case SSL_SIGN_ECDSA_SHA1:
343 case SSL_SIGN_RSA_PKCS1_SHA256:
344 case SSL_SIGN_ECDSA_SECP256R1_SHA256:
345 case SSL_SIGN_RSA_PSS_SHA256:
348 case SSL_SIGN_RSA_PKCS1_SHA384:
349 case SSL_SIGN_ECDSA_SECP384R1_SHA384:
350 case SSL_SIGN_RSA_PSS_SHA384:
353 case SSL_SIGN_RSA_PKCS1_SHA512:
354 case SSL_SIGN_ECDSA_SECP521R1_SHA512:
355 case SSL_SIGN_RSA_PSS_SHA512:
358 case SSL_SIGN_RSA_PKCS1_MD5_SHA1:
361 case SSL_SIGN_ED25519:
365 fprintf(stderr, "Unknown signature algorithm %04x.\n",
366 signature_algorithm);
367 return ssl_private_key_failure;
370 bssl::ScopedEVP_MD_CTX ctx;
372 if (!EVP_DigestSignInit(ctx.get(), &pctx, md, nullptr,
373 test_state->private_key.get())) {
374 return ssl_private_key_failure;
377 // Configure additional signature parameters.
378 switch (signature_algorithm) {
379 case SSL_SIGN_RSA_PSS_SHA256:
380 case SSL_SIGN_RSA_PSS_SHA384:
381 case SSL_SIGN_RSA_PSS_SHA512:
382 if (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) ||
383 !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
384 -1 /* salt len = hash len */)) {
385 return ssl_private_key_failure;
389 // Write the signature into |test_state|.
391 if (!EVP_DigestSign(ctx.get(), nullptr, &len, in, in_len)) {
392 return ssl_private_key_failure;
394 test_state->private_key_result.resize(len);
395 if (!EVP_DigestSign(ctx.get(), test_state->private_key_result.data(), &len,
397 return ssl_private_key_failure;
399 test_state->private_key_result.resize(len);
401 // The signature will be released asynchronously in |AsyncPrivateKeyComplete|.
402 return ssl_private_key_retry;
405 static ssl_private_key_result_t AsyncPrivateKeyDecrypt(
406 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
407 const uint8_t *in, size_t in_len) {
408 TestState *test_state = GetTestState(ssl);
409 if (!test_state->private_key_result.empty()) {
411 "AsyncPrivateKeyDecrypt called with operation pending.\n");
415 RSA *rsa = EVP_PKEY_get0_RSA(test_state->private_key.get());
418 "AsyncPrivateKeyDecrypt called with incorrect key type.\n");
421 test_state->private_key_result.resize(RSA_size(rsa));
422 if (!RSA_decrypt(rsa, out_len, test_state->private_key_result.data(),
423 RSA_size(rsa), in, in_len, RSA_NO_PADDING)) {
424 return ssl_private_key_failure;
427 test_state->private_key_result.resize(*out_len);
429 // The decryption will be released asynchronously in |AsyncPrivateComplete|.
430 return ssl_private_key_retry;
433 static ssl_private_key_result_t AsyncPrivateKeyComplete(
434 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
435 TestState *test_state = GetTestState(ssl);
436 if (test_state->private_key_result.empty()) {
438 "AsyncPrivateKeyComplete called without operation pending.\n");
442 if (test_state->private_key_retries < 2) {
443 // Only return the decryption on the second attempt, to test both incomplete
444 // |decrypt| and |decrypt_complete|.
445 return ssl_private_key_retry;
448 if (max_out < test_state->private_key_result.size()) {
449 fprintf(stderr, "Output buffer too small.\n");
450 return ssl_private_key_failure;
452 OPENSSL_memcpy(out, test_state->private_key_result.data(),
453 test_state->private_key_result.size());
454 *out_len = test_state->private_key_result.size();
456 test_state->private_key_result.clear();
457 test_state->private_key_retries = 0;
458 return ssl_private_key_success;
461 static const SSL_PRIVATE_KEY_METHOD g_async_private_key_method = {
463 AsyncPrivateKeyDecrypt,
464 AsyncPrivateKeyComplete,
469 void operator()(T *buf) {
474 static bool GetCertificate(SSL *ssl, bssl::UniquePtr<X509> *out_x509,
475 bssl::UniquePtr<STACK_OF(X509)> *out_chain,
476 bssl::UniquePtr<EVP_PKEY> *out_pkey) {
477 const TestConfig *config = GetTestConfig(ssl);
479 if (!config->signing_prefs.empty()) {
480 std::vector<uint16_t> u16s(config->signing_prefs.begin(),
481 config->signing_prefs.end());
482 if (!SSL_set_signing_algorithm_prefs(ssl, u16s.data(), u16s.size())) {
487 if (!config->key_file.empty()) {
488 *out_pkey = LoadPrivateKey(config->key_file.c_str());
493 if (!config->cert_file.empty() &&
494 !LoadCertificate(out_x509, out_chain, config->cert_file.c_str())) {
497 if (!config->ocsp_response.empty() &&
498 !SSL_set_ocsp_response(ssl, (const uint8_t *)config->ocsp_response.data(),
499 config->ocsp_response.size())) {
505 static bool InstallCertificate(SSL *ssl) {
506 bssl::UniquePtr<X509> x509;
507 bssl::UniquePtr<STACK_OF(X509)> chain;
508 bssl::UniquePtr<EVP_PKEY> pkey;
509 if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
514 TestState *test_state = GetTestState(ssl);
515 const TestConfig *config = GetTestConfig(ssl);
517 test_state->private_key = std::move(pkey);
518 SSL_set_private_key_method(ssl, &g_async_private_key_method);
519 } else if (!SSL_use_PrivateKey(ssl, pkey.get())) {
524 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
528 if (sk_X509_num(chain.get()) > 0 &&
529 !SSL_set1_chain(ssl, chain.get())) {
536 static enum ssl_select_cert_result_t SelectCertificateCallback(
537 const SSL_CLIENT_HELLO *client_hello) {
538 const TestConfig *config = GetTestConfig(client_hello->ssl);
539 GetTestState(client_hello->ssl)->early_callback_called = true;
541 if (!config->expected_server_name.empty()) {
542 const uint8_t *extension_data;
543 size_t extension_len;
544 CBS extension, server_name_list, host_name;
547 if (!SSL_early_callback_ctx_extension_get(
548 client_hello, TLSEXT_TYPE_server_name, &extension_data,
550 fprintf(stderr, "Could not find server_name extension.\n");
551 return ssl_select_cert_error;
554 CBS_init(&extension, extension_data, extension_len);
555 if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
556 CBS_len(&extension) != 0 ||
557 !CBS_get_u8(&server_name_list, &name_type) ||
558 name_type != TLSEXT_NAMETYPE_host_name ||
559 !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
560 CBS_len(&server_name_list) != 0) {
561 fprintf(stderr, "Could not decode server_name extension.\n");
562 return ssl_select_cert_error;
565 if (!CBS_mem_equal(&host_name,
566 (const uint8_t*)config->expected_server_name.data(),
567 config->expected_server_name.size())) {
568 fprintf(stderr, "Server name mismatch.\n");
572 if (config->fail_early_callback) {
573 return ssl_select_cert_error;
576 // Install the certificate in the early callback.
577 if (config->use_early_callback) {
578 bool early_callback_ready =
579 GetTestState(client_hello->ssl)->early_callback_ready;
580 if (config->async && !early_callback_ready) {
581 // Install the certificate asynchronously.
582 return ssl_select_cert_retry;
584 if (!InstallCertificate(client_hello->ssl)) {
585 return ssl_select_cert_error;
588 return ssl_select_cert_success;
591 static bool CheckCertificateRequest(SSL *ssl) {
592 const TestConfig *config = GetTestConfig(ssl);
594 if (!config->expected_certificate_types.empty()) {
595 const uint8_t *certificate_types;
596 size_t certificate_types_len =
597 SSL_get0_certificate_types(ssl, &certificate_types);
598 if (certificate_types_len != config->expected_certificate_types.size() ||
599 OPENSSL_memcmp(certificate_types,
600 config->expected_certificate_types.data(),
601 certificate_types_len) != 0) {
602 fprintf(stderr, "certificate types mismatch\n");
607 if (!config->expected_client_ca_list.empty()) {
608 bssl::UniquePtr<STACK_OF(X509_NAME)> expected =
609 DecodeHexX509Names(config->expected_client_ca_list);
610 const size_t num_expected = sk_X509_NAME_num(expected.get());
612 const STACK_OF(X509_NAME) *received = SSL_get_client_CA_list(ssl);
613 const size_t num_received = sk_X509_NAME_num(received);
615 if (num_received != num_expected) {
616 fprintf(stderr, "expected %u names in CertificateRequest but got %u\n",
617 static_cast<unsigned>(num_expected),
618 static_cast<unsigned>(num_received));
622 for (size_t i = 0; i < num_received; i++) {
623 if (X509_NAME_cmp(sk_X509_NAME_value(received, i),
624 sk_X509_NAME_value(expected.get(), i)) != 0) {
625 fprintf(stderr, "names in CertificateRequest differ at index #%d\n",
626 static_cast<unsigned>(i));
631 STACK_OF(CRYPTO_BUFFER) *buffers = SSL_get0_server_requested_CAs(ssl);
632 if (sk_CRYPTO_BUFFER_num(buffers) != num_received) {
634 "Mismatch between SSL_get_server_requested_CAs and "
635 "SSL_get_client_CA_list.\n");
643 static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
644 if (!CheckCertificateRequest(ssl)) {
648 if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
652 bssl::UniquePtr<X509> x509;
653 bssl::UniquePtr<STACK_OF(X509)> chain;
654 bssl::UniquePtr<EVP_PKEY> pkey;
655 if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
659 // Return zero for no certificate.
664 // Chains and asynchronous private keys are not supported with client_cert_cb.
665 *out_x509 = x509.release();
666 *out_pkey = pkey.release();
670 static int CertCallback(SSL *ssl, void *arg) {
671 const TestConfig *config = GetTestConfig(ssl);
673 // Check the CertificateRequest metadata is as expected.
674 if (!SSL_is_server(ssl) && !CheckCertificateRequest(ssl)) {
678 if (config->fail_cert_callback) {
682 // The certificate will be installed via other means.
683 if (!config->async || config->use_early_callback) {
687 if (!GetTestState(ssl)->cert_ready) {
690 if (!InstallCertificate(ssl)) {
696 static bool CheckVerifyCallback(SSL *ssl) {
697 const TestConfig *config = GetTestConfig(ssl);
698 if (!config->expected_ocsp_response.empty()) {
701 SSL_get0_ocsp_response(ssl, &data, &len);
703 fprintf(stderr, "OCSP response not available in verify callback\n");
708 if (GetTestState(ssl)->cert_verified) {
709 fprintf(stderr, "Certificate verified twice.\n");
716 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
717 SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data(store_ctx,
718 SSL_get_ex_data_X509_STORE_CTX_idx());
719 const TestConfig *config = GetTestConfig(ssl);
720 if (!CheckVerifyCallback(ssl)) {
724 GetTestState(ssl)->cert_verified = true;
725 if (config->verify_fail) {
726 store_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION;
733 static ssl_verify_result_t CustomVerifyCallback(SSL *ssl, uint8_t *out_alert) {
734 const TestConfig *config = GetTestConfig(ssl);
735 if (!CheckVerifyCallback(ssl)) {
736 return ssl_verify_invalid;
739 if (config->async && !GetTestState(ssl)->custom_verify_ready) {
740 return ssl_verify_retry;
743 GetTestState(ssl)->cert_verified = true;
744 if (config->verify_fail) {
745 return ssl_verify_invalid;
748 return ssl_verify_ok;
751 static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
752 unsigned int *out_len, void *arg) {
753 const TestConfig *config = GetTestConfig(ssl);
754 if (config->advertise_npn.empty()) {
755 return SSL_TLSEXT_ERR_NOACK;
758 *out = (const uint8_t*)config->advertise_npn.data();
759 *out_len = config->advertise_npn.size();
760 return SSL_TLSEXT_ERR_OK;
763 static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
764 const uint8_t* in, unsigned inlen, void* arg) {
765 const TestConfig *config = GetTestConfig(ssl);
766 if (config->select_next_proto.empty()) {
767 return SSL_TLSEXT_ERR_NOACK;
770 *out = (uint8_t*)config->select_next_proto.data();
771 *outlen = config->select_next_proto.size();
772 return SSL_TLSEXT_ERR_OK;
775 static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
776 const uint8_t* in, unsigned inlen, void* arg) {
777 if (GetTestState(ssl)->alpn_select_done) {
778 fprintf(stderr, "AlpnSelectCallback called after completion.\n");
782 GetTestState(ssl)->alpn_select_done = true;
784 const TestConfig *config = GetTestConfig(ssl);
785 if (config->decline_alpn) {
786 return SSL_TLSEXT_ERR_NOACK;
789 if (!config->expected_advertised_alpn.empty() &&
790 (config->expected_advertised_alpn.size() != inlen ||
791 OPENSSL_memcmp(config->expected_advertised_alpn.data(), in, inlen) !=
793 fprintf(stderr, "bad ALPN select callback inputs\n");
797 *out = (const uint8_t*)config->select_alpn.data();
798 *outlen = config->select_alpn.size();
799 return SSL_TLSEXT_ERR_OK;
802 static unsigned PskClientCallback(SSL *ssl, const char *hint,
804 unsigned max_identity_len,
805 uint8_t *out_psk, unsigned max_psk_len) {
806 const TestConfig *config = GetTestConfig(ssl);
808 if (config->psk_identity.empty()) {
809 if (hint != nullptr) {
810 fprintf(stderr, "Server PSK hint was non-null.\n");
813 } else if (hint == nullptr ||
814 strcmp(hint, config->psk_identity.c_str()) != 0) {
815 fprintf(stderr, "Server PSK hint did not match.\n");
819 // Account for the trailing '\0' for the identity.
820 if (config->psk_identity.size() >= max_identity_len ||
821 config->psk.size() > max_psk_len) {
822 fprintf(stderr, "PSK buffers too small\n");
826 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
828 OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size());
829 return config->psk.size();
832 static unsigned PskServerCallback(SSL *ssl, const char *identity,
833 uint8_t *out_psk, unsigned max_psk_len) {
834 const TestConfig *config = GetTestConfig(ssl);
836 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
837 fprintf(stderr, "Client PSK identity did not match.\n");
841 if (config->psk.size() > max_psk_len) {
842 fprintf(stderr, "PSK buffers too small\n");
846 OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size());
847 return config->psk.size();
850 static timeval g_clock;
852 static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
853 *out_clock = g_clock;
856 static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
857 *out_pkey = GetTestState(ssl)->channel_id.release();
860 static SSL_SESSION *GetSessionCallback(SSL *ssl, const uint8_t *data, int len,
862 TestState *async_state = GetTestState(ssl);
863 if (async_state->session) {
865 return async_state->session.release();
866 } else if (async_state->pending_session) {
867 return SSL_magic_pending_session_ptr();
873 static int DDoSCallback(const SSL_CLIENT_HELLO *client_hello) {
874 const TestConfig *config = GetTestConfig(client_hello->ssl);
875 static int callback_num = 0;
878 if (config->fail_ddos_callback ||
879 (config->fail_second_ddos_callback && callback_num == 2)) {
885 static void InfoCallback(const SSL *ssl, int type, int val) {
886 if (type == SSL_CB_HANDSHAKE_DONE) {
887 if (GetTestConfig(ssl)->handshake_never_done) {
888 fprintf(stderr, "Handshake unexpectedly completed.\n");
889 // Abort before any expected error code is printed, to ensure the overall
893 // This callback is called when the handshake completes. |SSL_get_session|
894 // must continue to work and |SSL_in_init| must return false.
895 if (SSL_in_init(ssl) || SSL_get_session(ssl) == nullptr) {
896 fprintf(stderr, "Invalid state for SSL_CB_HANDSHAKE_DONE.\n");
899 GetTestState(ssl)->handshake_done = true;
901 // Callbacks may be called again on a new handshake.
902 GetTestState(ssl)->ticket_decrypt_done = false;
903 GetTestState(ssl)->alpn_select_done = false;
907 static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
908 // This callback is called as the handshake completes. |SSL_get_session|
909 // must continue to work and, historically, |SSL_in_init| returned false at
911 if (SSL_in_init(ssl) || SSL_get_session(ssl) == nullptr) {
912 fprintf(stderr, "Invalid state for NewSessionCallback.\n");
916 GetTestState(ssl)->got_new_session = true;
917 GetTestState(ssl)->new_session.reset(session);
921 static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
922 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
925 if (GetTestState(ssl)->ticket_decrypt_done) {
926 fprintf(stderr, "TicketKeyCallback called after completion.\n");
930 GetTestState(ssl)->ticket_decrypt_done = true;
933 // This is just test code, so use the all-zeros key.
934 static const uint8_t kZeros[16] = {0};
937 OPENSSL_memcpy(key_name, kZeros, sizeof(kZeros));
939 } else if (OPENSSL_memcmp(key_name, kZeros, 16) != 0) {
943 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
944 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
949 return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
954 // kCustomExtensionValue is the extension value that the custom extension
955 // callbacks will add.
956 static const uint16_t kCustomExtensionValue = 1234;
957 static void *const kCustomExtensionAddArg =
958 reinterpret_cast<void *>(kCustomExtensionValue);
959 static void *const kCustomExtensionParseArg =
960 reinterpret_cast<void *>(kCustomExtensionValue + 1);
961 static const char kCustomExtensionContents[] = "custom extension";
963 static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
964 const uint8_t **out, size_t *out_len,
965 int *out_alert_value, void *add_arg) {
966 if (extension_value != kCustomExtensionValue ||
967 add_arg != kCustomExtensionAddArg) {
971 if (GetTestConfig(ssl)->custom_extension_skip) {
974 if (GetTestConfig(ssl)->custom_extension_fail_add) {
978 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
979 *out_len = sizeof(kCustomExtensionContents) - 1;
984 static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
985 const uint8_t *out, void *add_arg) {
986 if (extension_value != kCustomExtensionValue ||
987 add_arg != kCustomExtensionAddArg ||
988 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
993 static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
994 const uint8_t *contents,
996 int *out_alert_value, void *parse_arg) {
997 if (extension_value != kCustomExtensionValue ||
998 parse_arg != kCustomExtensionParseArg) {
1002 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
1003 OPENSSL_memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
1004 *out_alert_value = SSL_AD_DECODE_ERROR;
1011 static int ServerNameCallback(SSL *ssl, int *out_alert, void *arg) {
1012 // SNI must be accessible from the SNI callback.
1013 const TestConfig *config = GetTestConfig(ssl);
1014 const char *server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1015 if (server_name == nullptr ||
1016 std::string(server_name) != config->expected_server_name) {
1017 fprintf(stderr, "servername mismatch (got %s; want %s)\n", server_name,
1018 config->expected_server_name.c_str());
1019 return SSL_TLSEXT_ERR_ALERT_FATAL;
1022 return SSL_TLSEXT_ERR_OK;
1025 static void MessageCallback(int is_write, int version, int content_type,
1026 const void *buf, size_t len, SSL *ssl, void *arg) {
1027 const uint8_t *buf_u8 = reinterpret_cast<const uint8_t *>(buf);
1028 const TestConfig *config = GetTestConfig(ssl);
1029 TestState *state = GetTestState(ssl);
1030 if (!state->msg_callback_ok) {
1034 if (content_type == SSL3_RT_HEADER) {
1036 (config->is_dtls ? DTLS1_RT_HEADER_LENGTH : SSL3_RT_HEADER_LENGTH)) {
1037 fprintf(stderr, "Incorrect length for record header: %zu\n", len);
1038 state->msg_callback_ok = false;
1043 state->msg_callback_text += is_write ? "write " : "read ";
1044 switch (content_type) {
1046 if (version != SSL2_VERSION) {
1047 fprintf(stderr, "Incorrect version for V2ClientHello: %x\n", version);
1048 state->msg_callback_ok = false;
1051 state->msg_callback_text += "v2clienthello\n";
1054 case SSL3_RT_HANDSHAKE: {
1056 CBS_init(&cbs, buf_u8, len);
1059 if (!CBS_get_u8(&cbs, &type) ||
1060 // TODO(davidben): Reporting on entire messages would be more
1061 // consistent than fragments.
1063 !CBS_skip(&cbs, 3 /* total */ + 2 /* seq */ + 3 /* frag_off */)) ||
1064 !CBS_get_u24(&cbs, &msg_len) ||
1065 !CBS_skip(&cbs, msg_len) ||
1066 CBS_len(&cbs) != 0) {
1067 fprintf(stderr, "Could not parse handshake message.\n");
1068 state->msg_callback_ok = false;
1072 snprintf(text, sizeof(text), "hs %d\n", type);
1073 state->msg_callback_text += text;
1077 case SSL3_RT_CHANGE_CIPHER_SPEC:
1078 if (len != 1 || buf_u8[0] != 1) {
1079 fprintf(stderr, "Invalid ChangeCipherSpec.\n");
1080 state->msg_callback_ok = false;
1083 state->msg_callback_text += "ccs\n";
1088 fprintf(stderr, "Invalid alert.\n");
1089 state->msg_callback_ok = false;
1093 snprintf(text, sizeof(text), "alert %d %d\n", buf_u8[0], buf_u8[1]);
1094 state->msg_callback_text += text;
1098 fprintf(stderr, "Invalid content_type: %d\n", content_type);
1099 state->msg_callback_ok = false;
1103 // Connect returns a new socket connected to localhost on |port| or -1 on
1105 static int Connect(uint16_t port) {
1106 for (int af : { AF_INET6, AF_INET }) {
1107 int sock = socket(af, SOCK_STREAM, 0);
1109 PrintSocketError("socket");
1113 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
1114 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
1115 PrintSocketError("setsockopt");
1120 sockaddr_storage ss;
1121 OPENSSL_memset(&ss, 0, sizeof(ss));
1125 if (af == AF_INET6) {
1126 sockaddr_in6 *sin6 = (sockaddr_in6 *) &ss;
1127 len = sizeof(*sin6);
1128 sin6->sin6_port = htons(port);
1129 if (!inet_pton(AF_INET6, "::1", &sin6->sin6_addr)) {
1130 PrintSocketError("inet_pton");
1134 } else if (af == AF_INET) {
1135 sockaddr_in *sin = (sockaddr_in *) &ss;
1137 sin->sin_port = htons(port);
1138 if (!inet_pton(AF_INET, "127.0.0.1", &sin->sin_addr)) {
1139 PrintSocketError("inet_pton");
1145 if (connect(sock, reinterpret_cast<const sockaddr*>(&ss), len) == 0) {
1151 PrintSocketError("connect");
1155 class SocketCloser {
1157 explicit SocketCloser(int sock) : sock_(sock) {}
1159 // Half-close and drain the socket before releasing it. This seems to be
1160 // necessary for graceful shutdown on Windows. It will also avoid write
1161 // failures in the test runner.
1162 #if defined(OPENSSL_WINDOWS)
1163 shutdown(sock_, SD_SEND);
1165 shutdown(sock_, SHUT_WR);
1169 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
1180 static void ssl_ctx_add_session(SSL_SESSION *session, void *void_param) {
1181 SSL_CTX *ctx = reinterpret_cast<SSL_CTX *>(void_param);
1182 bssl::UniquePtr<SSL_SESSION> new_session = bssl::SSL_SESSION_dup(
1183 session, SSL_SESSION_INCLUDE_NONAUTH | SSL_SESSION_INCLUDE_TICKET);
1184 if (new_session != nullptr) {
1185 SSL_CTX_add_session(ctx, new_session.get());
1189 static bssl::UniquePtr<SSL_CTX> SetupCtx(SSL_CTX *old_ctx,
1190 const TestConfig *config) {
1191 bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(
1192 config->is_dtls ? DTLS_method() : TLS_method()));
1197 SSL_CTX_set0_buffer_pool(ssl_ctx.get(), g_pool);
1199 // Enable SSL 3.0 and TLS 1.3 for tests.
1200 if (!config->is_dtls &&
1201 (!SSL_CTX_set_min_proto_version(ssl_ctx.get(), SSL3_VERSION) ||
1202 !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION))) {
1206 std::string cipher_list = "ALL";
1207 if (!config->cipher.empty()) {
1208 cipher_list = config->cipher;
1209 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
1211 if (!SSL_CTX_set_strict_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
1215 if (config->async && config->is_server) {
1216 // Disable the internal session cache. To test asynchronous session lookup,
1217 // we use an external session cache.
1218 SSL_CTX_set_session_cache_mode(
1219 ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
1220 SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
1222 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
1225 SSL_CTX_set_select_certificate_cb(ssl_ctx.get(), SelectCertificateCallback);
1227 if (config->use_old_client_cert_callback) {
1228 SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
1231 SSL_CTX_set_next_protos_advertised_cb(
1232 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
1233 if (!config->select_next_proto.empty()) {
1234 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
1238 if (!config->select_alpn.empty() || config->decline_alpn) {
1239 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
1242 SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
1244 SSL_CTX_set_current_time_cb(ssl_ctx.get(), CurrentTimeCallback);
1246 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
1247 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
1249 if (config->use_ticket_callback) {
1250 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
1253 if (config->enable_client_custom_extension &&
1254 !SSL_CTX_add_client_custom_ext(
1255 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
1256 CustomExtensionFreeCallback, kCustomExtensionAddArg,
1257 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1261 if (config->enable_server_custom_extension &&
1262 !SSL_CTX_add_server_custom_ext(
1263 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
1264 CustomExtensionFreeCallback, kCustomExtensionAddArg,
1265 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1269 if (!config->use_custom_verify_callback) {
1270 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), CertVerifyCallback, NULL);
1273 if (!config->signed_cert_timestamps.empty() &&
1274 !SSL_CTX_set_signed_cert_timestamp_list(
1275 ssl_ctx.get(), (const uint8_t *)config->signed_cert_timestamps.data(),
1276 config->signed_cert_timestamps.size())) {
1280 if (!config->use_client_ca_list.empty()) {
1281 if (config->use_client_ca_list == "<NULL>") {
1282 SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
1283 } else if (config->use_client_ca_list == "<EMPTY>") {
1284 bssl::UniquePtr<STACK_OF(X509_NAME)> names;
1285 SSL_CTX_set_client_CA_list(ssl_ctx.get(), names.release());
1287 bssl::UniquePtr<STACK_OF(X509_NAME)> names =
1288 DecodeHexX509Names(config->use_client_ca_list);
1289 SSL_CTX_set_client_CA_list(ssl_ctx.get(), names.release());
1293 if (config->enable_grease) {
1294 SSL_CTX_set_grease_enabled(ssl_ctx.get(), 1);
1297 if (!config->expected_server_name.empty()) {
1298 SSL_CTX_set_tlsext_servername_callback(ssl_ctx.get(), ServerNameCallback);
1301 if (!config->ticket_key.empty() &&
1302 !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), config->ticket_key.data(),
1303 config->ticket_key.size())) {
1307 if (config->enable_early_data) {
1308 SSL_CTX_set_early_data_enabled(ssl_ctx.get(), 1);
1311 SSL_CTX_set_tls13_variant(
1312 ssl_ctx.get(), static_cast<enum tls13_variant_t>(config->tls13_variant));
1314 if (config->allow_unknown_alpn_protos) {
1315 SSL_CTX_set_allow_unknown_alpn_protos(ssl_ctx.get(), 1);
1318 if (config->enable_ed25519) {
1319 SSL_CTX_set_ed25519_enabled(ssl_ctx.get(), 1);
1322 if (!config->verify_prefs.empty()) {
1323 std::vector<uint16_t> u16s(config->verify_prefs.begin(),
1324 config->verify_prefs.end());
1325 if (!SSL_CTX_set_verify_algorithm_prefs(ssl_ctx.get(), u16s.data(),
1331 SSL_CTX_set_msg_callback(ssl_ctx.get(), MessageCallback);
1333 if (config->allow_false_start_without_alpn) {
1334 SSL_CTX_set_false_start_allowed_without_alpn(ssl_ctx.get(), 1);
1339 if (!SSL_CTX_get_tlsext_ticket_keys(old_ctx, &keys, sizeof(keys)) ||
1340 !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), keys, sizeof(keys))) {
1343 lh_SSL_SESSION_doall_arg(old_ctx->sessions, ssl_ctx_add_session,
1350 // RetryAsync is called after a failed operation on |ssl| with return code
1351 // |ret|. If the operation should be retried, it simulates one asynchronous
1352 // event and returns true. Otherwise it returns false.
1353 static bool RetryAsync(SSL *ssl, int ret) {
1354 // No error; don't retry.
1359 TestState *test_state = GetTestState(ssl);
1360 assert(GetTestConfig(ssl)->async);
1362 if (test_state->packeted_bio != nullptr &&
1363 PacketedBioAdvanceClock(test_state->packeted_bio)) {
1364 // The DTLS retransmit logic silently ignores write failures. So the test
1365 // may progress, allow writes through synchronously.
1366 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
1367 int timeout_ret = DTLSv1_handle_timeout(ssl);
1368 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
1370 if (timeout_ret < 0) {
1371 fprintf(stderr, "Error retransmitting.\n");
1377 // See if we needed to read or write more. If so, allow one byte through on
1378 // the appropriate end to maximally stress the state machine.
1379 switch (SSL_get_error(ssl, ret)) {
1380 case SSL_ERROR_WANT_READ:
1381 AsyncBioAllowRead(test_state->async_bio, 1);
1383 case SSL_ERROR_WANT_WRITE:
1384 AsyncBioAllowWrite(test_state->async_bio, 1);
1386 case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
1387 bssl::UniquePtr<EVP_PKEY> pkey =
1388 LoadPrivateKey(GetTestConfig(ssl)->send_channel_id);
1392 test_state->channel_id = std::move(pkey);
1395 case SSL_ERROR_WANT_X509_LOOKUP:
1396 test_state->cert_ready = true;
1398 case SSL_ERROR_PENDING_SESSION:
1399 test_state->session = std::move(test_state->pending_session);
1401 case SSL_ERROR_PENDING_CERTIFICATE:
1402 test_state->early_callback_ready = true;
1404 case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
1405 test_state->private_key_retries++;
1407 case SSL_ERROR_WANT_CERTIFICATE_VERIFY:
1408 test_state->custom_verify_ready = true;
1415 // CheckIdempotentError runs |func|, an operation on |ssl|, ensuring that
1416 // errors are idempotent.
1417 static int CheckIdempotentError(const char *name, SSL *ssl,
1418 std::function<int()> func) {
1420 int ssl_err = SSL_get_error(ssl, ret);
1421 uint32_t err = ERR_peek_error();
1422 if (ssl_err == SSL_ERROR_SSL || ssl_err == SSL_ERROR_ZERO_RETURN) {
1424 int ssl_err2 = SSL_get_error(ssl, ret2);
1425 uint32_t err2 = ERR_peek_error();
1426 if (ret != ret2 || ssl_err != ssl_err2 || err != err2) {
1427 fprintf(stderr, "Repeating %s did not replay the error.\n", name);
1429 ERR_error_string_n(err, buf, sizeof(buf));
1430 fprintf(stderr, "Wanted: %d %d %s\n", ret, ssl_err, buf);
1431 ERR_error_string_n(err2, buf, sizeof(buf));
1432 fprintf(stderr, "Got: %d %d %s\n", ret2, ssl_err2, buf);
1433 // runner treats exit code 90 as always failing. Otherwise, it may
1434 // accidentally consider the result an expected protocol failure.
1441 // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
1442 // the result value of the final |SSL_read| call.
1443 static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
1444 const TestConfig *config = GetTestConfig(ssl);
1445 TestState *test_state = GetTestState(ssl);
1448 if (config->async) {
1449 // The DTLS retransmit logic silently ignores write failures. So the test
1450 // may progress, allow writes through synchronously. |SSL_read| may
1451 // trigger a retransmit, so disconnect the write quota.
1452 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
1454 ret = CheckIdempotentError("SSL_peek/SSL_read", ssl, [&]() -> int {
1455 return config->peek_then_read ? SSL_peek(ssl, out, max_out)
1456 : SSL_read(ssl, out, max_out);
1458 if (config->async) {
1459 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
1462 // Run the exporter after each read. This is to test that the exporter fails
1463 // during a renegotiation.
1464 if (config->use_exporter_between_reads) {
1466 if (!SSL_export_keying_material(ssl, &buf, 1, NULL, 0, NULL, 0, 0)) {
1467 fprintf(stderr, "failed to export keying material\n");
1471 } while (config->async && RetryAsync(ssl, ret));
1473 if (config->peek_then_read && ret > 0) {
1474 std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
1476 // SSL_peek should synchronously return the same data.
1477 int ret2 = SSL_peek(ssl, buf.get(), ret);
1479 OPENSSL_memcmp(buf.get(), out, ret) != 0) {
1480 fprintf(stderr, "First and second SSL_peek did not match.\n");
1484 // SSL_read should synchronously return the same data and consume it.
1485 ret2 = SSL_read(ssl, buf.get(), ret);
1487 OPENSSL_memcmp(buf.get(), out, ret) != 0) {
1488 fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
1496 // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
1497 // operations. It returns the result of the final |SSL_write| call.
1498 static int WriteAll(SSL *ssl, const void *in_, size_t in_len) {
1499 const uint8_t *in = reinterpret_cast<const uint8_t *>(in_);
1500 const TestConfig *config = GetTestConfig(ssl);
1503 ret = SSL_write(ssl, in, in_len);
1508 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
1512 // DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
1513 // returns the result of the final |SSL_shutdown| call.
1514 static int DoShutdown(SSL *ssl) {
1515 const TestConfig *config = GetTestConfig(ssl);
1518 ret = SSL_shutdown(ssl);
1519 } while (config->async && RetryAsync(ssl, ret));
1523 // DoSendFatalAlert calls |SSL_send_fatal_alert|, resolving any asynchronous
1524 // operations. It returns the result of the final |SSL_send_fatal_alert| call.
1525 static int DoSendFatalAlert(SSL *ssl, uint8_t alert) {
1526 const TestConfig *config = GetTestConfig(ssl);
1529 ret = SSL_send_fatal_alert(ssl, alert);
1530 } while (config->async && RetryAsync(ssl, ret));
1534 static uint16_t GetProtocolVersion(const SSL *ssl) {
1535 uint16_t version = SSL_version(ssl);
1536 if (!SSL_is_dtls(ssl)) {
1539 return 0x0201 + ~version;
1542 // CheckAuthProperties checks, after the initial handshake is completed or
1543 // after a renegotiation, that authentication-related properties match |config|.
1544 static bool CheckAuthProperties(SSL *ssl, bool is_resume,
1545 const TestConfig *config) {
1546 if (!config->expected_ocsp_response.empty()) {
1547 const uint8_t *data;
1549 SSL_get0_ocsp_response(ssl, &data, &len);
1550 if (config->expected_ocsp_response.size() != len ||
1551 OPENSSL_memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
1552 fprintf(stderr, "OCSP response mismatch\n");
1557 if (!config->expected_signed_cert_timestamps.empty()) {
1558 const uint8_t *data;
1560 SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
1561 if (config->expected_signed_cert_timestamps.size() != len ||
1562 OPENSSL_memcmp(config->expected_signed_cert_timestamps.data(), data,
1564 fprintf(stderr, "SCT list mismatch\n");
1569 if (config->expect_verify_result) {
1570 int expected_verify_result = config->verify_fail ?
1571 X509_V_ERR_APPLICATION_VERIFICATION :
1574 if (SSL_get_verify_result(ssl) != expected_verify_result) {
1575 fprintf(stderr, "Wrong certificate verification result\n");
1580 if (!config->expect_peer_cert_file.empty()) {
1581 bssl::UniquePtr<X509> expect_leaf;
1582 bssl::UniquePtr<STACK_OF(X509)> expect_chain;
1583 if (!LoadCertificate(&expect_leaf, &expect_chain,
1584 config->expect_peer_cert_file)) {
1588 // For historical reasons, clients report a chain with a leaf and servers
1590 if (!config->is_server) {
1591 if (!sk_X509_insert(expect_chain.get(), expect_leaf.get(), 0)) {
1594 X509_up_ref(expect_leaf.get()); // sk_X509_push takes ownership.
1597 bssl::UniquePtr<X509> leaf(SSL_get_peer_certificate(ssl));
1598 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl);
1599 if (X509_cmp(leaf.get(), expect_leaf.get()) != 0) {
1600 fprintf(stderr, "Received a different leaf certificate than expected.\n");
1604 if (sk_X509_num(chain) != sk_X509_num(expect_chain.get())) {
1605 fprintf(stderr, "Received a chain of length %zu instead of %zu.\n",
1606 sk_X509_num(chain), sk_X509_num(expect_chain.get()));
1610 for (size_t i = 0; i < sk_X509_num(chain); i++) {
1611 if (X509_cmp(sk_X509_value(chain, i),
1612 sk_X509_value(expect_chain.get(), i)) != 0) {
1613 fprintf(stderr, "Chain certificate %zu did not match.\n",
1620 if (SSL_get_session(ssl)->peer_sha256_valid !=
1621 config->expect_sha256_client_cert) {
1623 "Unexpected SHA-256 client cert state: expected:%d is_resume:%d.\n",
1624 config->expect_sha256_client_cert, is_resume);
1628 if (config->expect_sha256_client_cert &&
1629 SSL_get_session(ssl)->certs != nullptr) {
1630 fprintf(stderr, "Have both client cert and SHA-256 hash: is_resume:%d.\n",
1638 // CheckHandshakeProperties checks, immediately after |ssl| completes its
1639 // initial handshake (or False Starts), whether all the properties are
1640 // consistent with the test configuration and invariants.
1641 static bool CheckHandshakeProperties(SSL *ssl, bool is_resume,
1642 const TestConfig *config) {
1643 if (!CheckAuthProperties(ssl, is_resume, config)) {
1647 if (SSL_get_current_cipher(ssl) == nullptr) {
1648 fprintf(stderr, "null cipher after handshake\n");
1652 if (config->expect_version != 0 &&
1653 SSL_version(ssl) != config->expect_version) {
1654 fprintf(stderr, "want version %04x, got %04x\n", config->expect_version,
1659 bool expect_resume =
1660 is_resume && (!config->expect_session_miss || SSL_in_early_data(ssl));
1661 if (!!SSL_session_reused(ssl) != expect_resume) {
1662 fprintf(stderr, "session unexpectedly was%s reused\n",
1663 SSL_session_reused(ssl) ? "" : " not");
1667 bool expect_handshake_done =
1668 (is_resume || !config->false_start) && !SSL_in_early_data(ssl);
1669 if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
1670 fprintf(stderr, "handshake was%s completed\n",
1671 GetTestState(ssl)->handshake_done ? "" : " not");
1675 if (expect_handshake_done && !config->is_server) {
1676 bool expect_new_session =
1677 !config->expect_no_session &&
1678 (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
1679 // Session tickets are sent post-handshake in TLS 1.3.
1680 GetProtocolVersion(ssl) < TLS1_3_VERSION;
1681 if (expect_new_session != GetTestState(ssl)->got_new_session) {
1683 "new session was%s cached, but we expected the opposite\n",
1684 GetTestState(ssl)->got_new_session ? "" : " not");
1690 if (config->expect_session_id && !GetTestState(ssl)->got_new_session) {
1691 fprintf(stderr, "session was not cached on the server.\n");
1694 if (config->expect_no_session_id && GetTestState(ssl)->got_new_session) {
1695 fprintf(stderr, "session was unexpectedly cached on the server.\n");
1700 if (config->is_server && !GetTestState(ssl)->early_callback_called) {
1701 fprintf(stderr, "early callback not called\n");
1705 if (!config->expected_server_name.empty()) {
1706 const char *server_name =
1707 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1708 if (server_name == nullptr ||
1709 server_name != config->expected_server_name) {
1710 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
1711 server_name, config->expected_server_name.c_str());
1716 if (!config->expected_next_proto.empty()) {
1717 const uint8_t *next_proto;
1718 unsigned next_proto_len;
1719 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
1720 if (next_proto_len != config->expected_next_proto.size() ||
1721 OPENSSL_memcmp(next_proto, config->expected_next_proto.data(),
1722 next_proto_len) != 0) {
1723 fprintf(stderr, "negotiated next proto mismatch\n");
1728 if (!config->is_server) {
1729 const uint8_t *alpn_proto;
1730 unsigned alpn_proto_len;
1731 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
1732 if (alpn_proto_len != config->expected_alpn.size() ||
1733 OPENSSL_memcmp(alpn_proto, config->expected_alpn.data(),
1734 alpn_proto_len) != 0) {
1735 fprintf(stderr, "negotiated alpn proto mismatch\n");
1740 if (!config->expected_quic_transport_params.empty()) {
1741 const uint8_t *peer_params;
1742 size_t peer_params_len;
1743 SSL_get_peer_quic_transport_params(ssl, &peer_params, &peer_params_len);
1744 if (peer_params_len != config->expected_quic_transport_params.size() ||
1745 OPENSSL_memcmp(peer_params,
1746 config->expected_quic_transport_params.data(),
1747 peer_params_len) != 0) {
1748 fprintf(stderr, "QUIC transport params mismatch\n");
1753 if (!config->expected_channel_id.empty()) {
1754 uint8_t channel_id[64];
1755 if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
1756 fprintf(stderr, "no channel id negotiated\n");
1759 if (config->expected_channel_id.size() != 64 ||
1760 OPENSSL_memcmp(config->expected_channel_id.data(), channel_id, 64) !=
1762 fprintf(stderr, "channel id mismatch\n");
1767 if (config->expected_token_binding_param != -1) {
1768 if (!SSL_is_token_binding_negotiated(ssl)) {
1769 fprintf(stderr, "no Token Binding negotiated\n");
1772 if (SSL_get_negotiated_token_binding_param(ssl) !=
1773 static_cast<uint8_t>(config->expected_token_binding_param)) {
1774 fprintf(stderr, "Token Binding param mismatch\n");
1779 if (config->expect_extended_master_secret && !SSL_get_extms_support(ssl)) {
1780 fprintf(stderr, "No EMS for connection when expected\n");
1784 if (config->expect_secure_renegotiation &&
1785 !SSL_get_secure_renegotiation_support(ssl)) {
1786 fprintf(stderr, "No secure renegotiation for connection when expected\n");
1790 if (config->expect_no_secure_renegotiation &&
1791 SSL_get_secure_renegotiation_support(ssl)) {
1793 "Secure renegotiation unexpectedly negotiated for connection\n");
1797 if (config->expect_peer_signature_algorithm != 0 &&
1798 config->expect_peer_signature_algorithm !=
1799 SSL_get_peer_signature_algorithm(ssl)) {
1800 fprintf(stderr, "Peer signature algorithm was %04x, wanted %04x.\n",
1801 SSL_get_peer_signature_algorithm(ssl),
1802 config->expect_peer_signature_algorithm);
1806 if (config->expect_curve_id != 0) {
1807 uint16_t curve_id = SSL_get_curve_id(ssl);
1808 if (static_cast<uint16_t>(config->expect_curve_id) != curve_id) {
1809 fprintf(stderr, "curve_id was %04x, wanted %04x\n", curve_id,
1810 static_cast<uint16_t>(config->expect_curve_id));
1815 uint16_t cipher_id =
1816 static_cast<uint16_t>(SSL_CIPHER_get_id(SSL_get_current_cipher(ssl)));
1817 if (config->expect_cipher_aes != 0 &&
1818 EVP_has_aes_hardware() &&
1819 static_cast<uint16_t>(config->expect_cipher_aes) != cipher_id) {
1820 fprintf(stderr, "Cipher ID was %04x, wanted %04x (has AES hardware)\n",
1821 cipher_id, static_cast<uint16_t>(config->expect_cipher_aes));
1825 if (config->expect_cipher_no_aes != 0 &&
1826 !EVP_has_aes_hardware() &&
1827 static_cast<uint16_t>(config->expect_cipher_no_aes) != cipher_id) {
1828 fprintf(stderr, "Cipher ID was %04x, wanted %04x (no AES hardware)\n",
1829 cipher_id, static_cast<uint16_t>(config->expect_cipher_no_aes));
1833 if (is_resume && !SSL_in_early_data(ssl)) {
1834 if ((config->expect_accept_early_data && !SSL_early_data_accepted(ssl)) ||
1835 (config->expect_reject_early_data && SSL_early_data_accepted(ssl))) {
1837 "Early data was%s accepted, but we expected the opposite\n",
1838 SSL_early_data_accepted(ssl) ? "" : " not");
1843 if (!config->psk.empty()) {
1844 if (SSL_get_peer_cert_chain(ssl) != nullptr) {
1845 fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
1848 } else if (!config->is_server || config->require_any_client_certificate) {
1849 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
1850 fprintf(stderr, "Received no peer certificate but expected one.\n");
1855 if (is_resume && config->expect_ticket_age_skew != 0 &&
1856 SSL_get_ticket_age_skew(ssl) != config->expect_ticket_age_skew) {
1857 fprintf(stderr, "Ticket age skew was %" PRId32 ", wanted %d\n",
1858 SSL_get_ticket_age_skew(ssl), config->expect_ticket_age_skew);
1862 if (config->expect_draft_downgrade != !!SSL_is_draft_downgrade(ssl)) {
1863 fprintf(stderr, "Got %sdraft downgrade signal, but wanted the opposite.\n",
1864 SSL_is_draft_downgrade(ssl) ? "" : "no ");
1868 const bool did_dummy_pq_padding = !!SSL_dummy_pq_padding_used(ssl);
1869 if (config->expect_dummy_pq_padding != did_dummy_pq_padding) {
1871 "Dummy PQ padding %s observed, but expected the opposite.\n",
1872 did_dummy_pq_padding ? "was" : "was not");
1879 static bool WriteSettings(int i, const TestConfig *config,
1880 const SSL_SESSION *session) {
1881 if (config->write_settings.empty()) {
1885 // Treat write_settings as a path prefix for each connection in the run.
1886 char buf[DECIMAL_SIZE(int)];
1887 snprintf(buf, sizeof(buf), "%d", i);
1888 std::string path = config->write_settings + buf;
1890 bssl::ScopedCBB cbb;
1891 if (!CBB_init(cbb.get(), 64)) {
1895 if (session != nullptr) {
1898 if (!SSL_SESSION_to_bytes(session, &data, &len)) {
1901 bssl::UniquePtr<uint8_t> free_data(data);
1903 if (!CBB_add_u16(cbb.get(), kSessionTag) ||
1904 !CBB_add_u24_length_prefixed(cbb.get(), &child) ||
1905 !CBB_add_bytes(&child, data, len) ||
1906 !CBB_flush(cbb.get())) {
1911 if (config->is_server &&
1912 (config->require_any_client_certificate || config->verify_peer) &&
1913 !CBB_add_u16(cbb.get(), kRequestClientCert)) {
1917 if (config->tls13_variant != 0 &&
1918 (!CBB_add_u16(cbb.get(), kTLS13Variant) ||
1919 !CBB_add_u8(cbb.get(), static_cast<uint8_t>(config->tls13_variant)))) {
1924 size_t settings_len;
1925 if (!CBB_add_u16(cbb.get(), kDataTag) ||
1926 !CBB_finish(cbb.get(), &settings, &settings_len)) {
1929 bssl::UniquePtr<uint8_t> free_settings(settings);
1931 using ScopedFILE = std::unique_ptr<FILE, decltype(&fclose)>;
1932 ScopedFILE file(fopen(path.c_str(), "w"), fclose);
1937 return fwrite(settings, settings_len, 1, file.get()) == 1;
1940 static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
1941 bssl::UniquePtr<SSL> *ssl_uniqueptr,
1942 const TestConfig *config, bool is_resume, bool is_retry);
1944 // DoConnection tests an SSL connection against the peer. On success, it returns
1945 // true and sets |*out_session| to the negotiated SSL session. If the test is a
1946 // resumption attempt, |is_resume| is true and |session| is the session from the
1947 // previous exchange.
1948 static bool DoConnection(bssl::UniquePtr<SSL_SESSION> *out_session,
1949 SSL_CTX *ssl_ctx, const TestConfig *config,
1950 const TestConfig *retry_config, bool is_resume,
1951 SSL_SESSION *session) {
1952 bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
1957 if (!SetTestConfig(ssl.get(), config) ||
1958 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
1962 GetTestState(ssl.get())->is_resume = is_resume;
1964 if (config->fallback_scsv &&
1965 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
1968 // Install the certificate synchronously if nothing else will handle it.
1969 if (!config->use_early_callback &&
1970 !config->use_old_client_cert_callback &&
1972 !InstallCertificate(ssl.get())) {
1975 if (!config->use_old_client_cert_callback) {
1976 SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
1978 int mode = SSL_VERIFY_NONE;
1979 if (config->require_any_client_certificate) {
1980 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1982 if (config->verify_peer) {
1983 mode = SSL_VERIFY_PEER;
1985 if (config->verify_peer_if_no_obc) {
1986 // Set SSL_VERIFY_FAIL_IF_NO_PEER_CERT so testing whether client
1987 // certificates were requested is easy.
1988 mode = SSL_VERIFY_PEER | SSL_VERIFY_PEER_IF_NO_OBC |
1989 SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1991 if (config->use_custom_verify_callback) {
1992 SSL_set_custom_verify(ssl.get(), mode, CustomVerifyCallback);
1993 } else if (mode != SSL_VERIFY_NONE) {
1994 SSL_set_verify(ssl.get(), mode, NULL);
1996 if (config->false_start) {
1997 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
1999 if (config->cbc_record_splitting) {
2000 SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
2002 if (config->partial_write) {
2003 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
2005 if (config->no_tls13) {
2006 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
2008 if (config->no_tls12) {
2009 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
2011 if (config->no_tls11) {
2012 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
2014 if (config->no_tls1) {
2015 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
2017 if (config->no_ssl3) {
2018 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
2020 if (!config->expected_channel_id.empty() ||
2021 config->enable_channel_id) {
2022 SSL_set_tls_channel_id_enabled(ssl.get(), 1);
2024 if (!config->send_channel_id.empty()) {
2025 SSL_set_tls_channel_id_enabled(ssl.get(), 1);
2026 if (!config->async) {
2027 // The async case will be supplied by |ChannelIdCallback|.
2028 bssl::UniquePtr<EVP_PKEY> pkey = LoadPrivateKey(config->send_channel_id);
2029 if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
2034 if (!config->send_token_binding_params.empty()) {
2035 SSL_set_token_binding_params(ssl.get(),
2036 reinterpret_cast<const uint8_t *>(
2037 config->send_token_binding_params.data()),
2038 config->send_token_binding_params.length());
2040 if (!config->host_name.empty() &&
2041 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
2044 if (!config->advertise_alpn.empty() &&
2045 SSL_set_alpn_protos(ssl.get(),
2046 (const uint8_t *)config->advertise_alpn.data(),
2047 config->advertise_alpn.size()) != 0) {
2050 if (!config->psk.empty()) {
2051 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
2052 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
2054 if (!config->psk_identity.empty() &&
2055 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
2058 if (!config->srtp_profiles.empty() &&
2059 !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
2062 if (config->enable_ocsp_stapling) {
2063 SSL_enable_ocsp_stapling(ssl.get());
2065 if (config->enable_signed_cert_timestamps) {
2066 SSL_enable_signed_cert_timestamps(ssl.get());
2068 if (config->min_version != 0 &&
2069 !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) {
2072 if (config->max_version != 0 &&
2073 !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) {
2076 if (config->mtu != 0) {
2077 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
2078 SSL_set_mtu(ssl.get(), config->mtu);
2080 if (config->install_ddos_callback) {
2081 SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
2083 if (config->renegotiate_once) {
2084 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_once);
2086 if (config->renegotiate_freely) {
2087 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
2089 if (config->renegotiate_ignore) {
2090 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_ignore);
2092 if (!config->check_close_notify) {
2093 SSL_set_quiet_shutdown(ssl.get(), 1);
2095 if (config->p384_only) {
2096 int nid = NID_secp384r1;
2097 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
2101 if (config->enable_all_curves) {
2102 static const int kAllCurves[] = {
2103 NID_secp224r1, NID_X9_62_prime256v1, NID_secp384r1,
2104 NID_secp521r1, NID_X25519,
2106 if (!SSL_set1_curves(ssl.get(), kAllCurves,
2107 OPENSSL_ARRAY_SIZE(kAllCurves))) {
2111 if (config->initial_timeout_duration_ms > 0) {
2112 DTLSv1_set_initial_timeout_duration(ssl.get(),
2113 config->initial_timeout_duration_ms);
2115 if (config->max_cert_list > 0) {
2116 SSL_set_max_cert_list(ssl.get(), config->max_cert_list);
2118 if (config->retain_only_sha256_client_cert) {
2119 SSL_set_retain_only_sha256_of_client_certs(ssl.get(), 1);
2121 if (config->max_send_fragment > 0) {
2122 SSL_set_max_send_fragment(ssl.get(), config->max_send_fragment);
2124 if (config->dummy_pq_padding_len > 0 &&
2125 !SSL_set_dummy_pq_padding_size(ssl.get(), config->dummy_pq_padding_len)) {
2128 if (!config->quic_transport_params.empty()) {
2129 if (!SSL_set_quic_transport_params(
2131 reinterpret_cast<const uint8_t *>(
2132 config->quic_transport_params.data()),
2133 config->quic_transport_params.size())) {
2138 int sock = Connect(config->port);
2142 SocketCloser closer(sock);
2144 bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
2148 if (config->is_dtls) {
2149 bssl::UniquePtr<BIO> packeted = PacketedBioCreate(&g_clock);
2153 GetTestState(ssl.get())->packeted_bio = packeted.get();
2154 BIO_push(packeted.get(), bio.release());
2155 bio = std::move(packeted);
2157 if (config->async) {
2158 bssl::UniquePtr<BIO> async_scoped =
2159 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
2160 if (!async_scoped) {
2163 BIO_push(async_scoped.get(), bio.release());
2164 GetTestState(ssl.get())->async_bio = async_scoped.get();
2165 bio = std::move(async_scoped);
2167 SSL_set_bio(ssl.get(), bio.get(), bio.get());
2168 bio.release(); // SSL_set_bio takes ownership.
2170 if (session != NULL) {
2171 if (!config->is_server) {
2172 if (SSL_set_session(ssl.get(), session) != 1) {
2175 } else if (config->async) {
2176 // The internal session cache is disabled, so install the session
2178 SSL_SESSION_up_ref(session);
2179 GetTestState(ssl.get())->pending_session.reset(session);
2183 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
2184 fprintf(stderr, "non-null cipher before handshake\n");
2188 if (config->is_server) {
2189 SSL_set_accept_state(ssl.get());
2191 SSL_set_connect_state(ssl.get());
2194 bool ret = DoExchange(out_session, &ssl, config, is_resume, false);
2195 if (!config->is_server && is_resume && config->expect_reject_early_data) {
2196 // We must have failed due to an early data rejection.
2198 fprintf(stderr, "0-RTT exchange unexpected succeeded.\n");
2201 if (SSL_get_error(ssl.get(), -1) != SSL_ERROR_EARLY_DATA_REJECTED) {
2203 "SSL_get_error did not signal SSL_ERROR_EARLY_DATA_REJECTED.\n");
2207 // Before reseting, early state should still be available.
2208 if (!SSL_in_early_data(ssl.get()) ||
2209 !CheckHandshakeProperties(ssl.get(), is_resume, config)) {
2210 fprintf(stderr, "SSL_in_early_data returned false before reset.\n");
2214 // Reset the connection and try again at 1-RTT.
2215 SSL_reset_early_data_reject(ssl.get());
2217 // After reseting, the socket should report it is no longer in an early data
2219 if (SSL_in_early_data(ssl.get())) {
2220 fprintf(stderr, "SSL_in_early_data returned true after reset.\n");
2224 if (!SetTestConfig(ssl.get(), retry_config)) {
2228 assert(!config->handoff);
2229 ret = DoExchange(out_session, &ssl, retry_config, is_resume, true);
2236 if (!GetTestState(ssl.get())->msg_callback_ok) {
2240 if (!config->expect_msg_callback.empty() &&
2241 GetTestState(ssl.get())->msg_callback_text !=
2242 config->expect_msg_callback) {
2243 fprintf(stderr, "Bad message callback trace. Wanted:\n%s\nGot:\n%s\n",
2244 config->expect_msg_callback.c_str(),
2245 GetTestState(ssl.get())->msg_callback_text.c_str());
2252 static bool HandoffReady(SSL *ssl, int ret) {
2253 return ret < 0 && SSL_get_error(ssl, ret) == SSL_ERROR_HANDOFF;
2256 static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
2257 bssl::UniquePtr<SSL> *ssl_uniqueptr,
2258 const TestConfig *config, bool is_resume,
2261 SSL *ssl = ssl_uniqueptr->get();
2263 if (!config->implicit_handshake) {
2264 if (config->handoff) {
2265 bssl::UniquePtr<SSL_CTX> ctx_handoff(SSL_CTX_new(TLSv1_method()));
2269 SSL_CTX_set_handoff_mode(ctx_handoff.get(), 1);
2271 bssl::UniquePtr<SSL> ssl_handoff(SSL_new(ctx_handoff.get()));
2275 SSL_set_accept_state(ssl_handoff.get());
2276 if (!MoveExData(ssl_handoff.get(), ssl)) {
2279 MoveBIOs(ssl_handoff.get(), ssl);
2282 ret = CheckIdempotentError("SSL_do_handshake", ssl_handoff.get(),
2284 return SSL_do_handshake(ssl_handoff.get());
2286 } while (!HandoffReady(ssl_handoff.get(), ret) &&
2288 RetryAsync(ssl_handoff.get(), ret));
2290 if (!HandoffReady(ssl_handoff.get(), ret)) {
2291 fprintf(stderr, "Handshake failed while waiting for handoff.\n");
2295 bssl::ScopedCBB cbb;
2296 bssl::Array<uint8_t> handoff;
2297 if (!CBB_init(cbb.get(), 512) ||
2298 !SSL_serialize_handoff(ssl_handoff.get(), cbb.get()) ||
2299 !CBBFinishArray(cbb.get(), &handoff)) {
2300 fprintf(stderr, "Handoff serialisation failed.\n");
2304 MoveBIOs(ssl, ssl_handoff.get());
2305 if (!MoveExData(ssl, ssl_handoff.get())) {
2309 if (!SSL_apply_handoff(ssl, handoff)) {
2310 fprintf(stderr, "Handoff application failed.\n");
2316 ret = CheckIdempotentError("SSL_do_handshake", ssl, [&]() -> int {
2317 return SSL_do_handshake(ssl);
2319 } while (config->async && RetryAsync(ssl, ret));
2322 !CheckHandshakeProperties(ssl, is_resume, config)) {
2326 if (config->handoff) {
2327 bssl::ScopedCBB cbb;
2328 bssl::Array<uint8_t> handback;
2329 if (!CBB_init(cbb.get(), 512) ||
2330 !SSL_serialize_handback(ssl, cbb.get()) ||
2331 !CBBFinishArray(cbb.get(), &handback)) {
2332 fprintf(stderr, "Handback serialisation failed.\n");
2336 bssl::UniquePtr<SSL_CTX> ctx_handback(SSL_CTX_new(TLSv1_method()));
2337 SSL_CTX_set_msg_callback(ctx_handback.get(), MessageCallback);
2338 bssl::UniquePtr<SSL> ssl_handback(SSL_new(ctx_handback.get()));
2339 if (!ssl_handback) {
2342 if (!SSL_apply_handback(ssl_handback.get(), handback)) {
2343 fprintf(stderr, "Applying handback failed.\n");
2347 MoveBIOs(ssl_handback.get(), ssl);
2348 if (!MoveExData(ssl_handback.get(), ssl)) {
2352 *ssl_uniqueptr = std::move(ssl_handback);
2353 ssl = ssl_uniqueptr->get();
2356 if (is_resume && !is_retry && !config->is_server &&
2357 config->expect_no_offer_early_data && SSL_in_early_data(ssl)) {
2358 fprintf(stderr, "Client unexpectedly offered early data.\n");
2362 if (config->handshake_twice) {
2364 ret = SSL_do_handshake(ssl);
2365 } while (config->async && RetryAsync(ssl, ret));
2371 // Skip the |config->async| logic as this should be a no-op.
2372 if (config->no_op_extra_handshake &&
2373 SSL_do_handshake(ssl) != 1) {
2374 fprintf(stderr, "Extra SSL_do_handshake was not a no-op.\n");
2378 // Reset the state to assert later that the callback isn't called in
2380 GetTestState(ssl)->got_new_session = false;
2383 if (config->export_early_keying_material > 0) {
2384 std::vector<uint8_t> result(
2385 static_cast<size_t>(config->export_early_keying_material));
2386 if (!SSL_export_early_keying_material(
2387 ssl, result.data(), result.size(), config->export_label.data(),
2388 config->export_label.size(),
2389 reinterpret_cast<const uint8_t *>(config->export_context.data()),
2390 config->export_context.size())) {
2391 fprintf(stderr, "failed to export keying material\n");
2394 if (WriteAll(ssl, result.data(), result.size()) < 0) {
2399 if (config->export_keying_material > 0) {
2400 std::vector<uint8_t> result(
2401 static_cast<size_t>(config->export_keying_material));
2402 if (!SSL_export_keying_material(
2403 ssl, result.data(), result.size(), config->export_label.data(),
2404 config->export_label.size(),
2405 reinterpret_cast<const uint8_t *>(config->export_context.data()),
2406 config->export_context.size(), config->use_export_context)) {
2407 fprintf(stderr, "failed to export keying material\n");
2410 if (WriteAll(ssl, result.data(), result.size()) < 0) {
2415 if (config->tls_unique) {
2416 uint8_t tls_unique[16];
2417 size_t tls_unique_len;
2418 if (!SSL_get_tls_unique(ssl, tls_unique, &tls_unique_len,
2419 sizeof(tls_unique))) {
2420 fprintf(stderr, "failed to get tls-unique\n");
2424 if (tls_unique_len != 12) {
2425 fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
2426 static_cast<unsigned>(tls_unique_len));
2430 if (WriteAll(ssl, tls_unique, tls_unique_len) < 0) {
2435 if (config->send_alert) {
2436 if (DoSendFatalAlert(ssl, SSL_AD_DECOMPRESSION_FAILURE) < 0) {
2442 if (config->write_different_record_sizes) {
2443 if (config->is_dtls) {
2444 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
2447 // This mode writes a number of different record sizes in an attempt to
2448 // trip up the CBC record splitting code.
2449 static const size_t kBufLen = 32769;
2450 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
2451 OPENSSL_memset(buf.get(), 0x42, kBufLen);
2452 static const size_t kRecordSizes[] = {
2453 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
2454 for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
2455 const size_t len = kRecordSizes[i];
2456 if (len > kBufLen) {
2457 fprintf(stderr, "Bad kRecordSizes value.\n");
2460 if (WriteAll(ssl, buf.get(), len) < 0) {
2465 static const char kInitialWrite[] = "hello";
2466 bool pending_initial_write = false;
2467 if (config->read_with_unfinished_write) {
2468 if (!config->async) {
2469 fprintf(stderr, "-read-with-unfinished-write requires -async.\n");
2473 // Let only one byte of the record through.
2474 AsyncBioAllowWrite(GetTestState(ssl)->async_bio, 1);
2476 SSL_write(ssl, kInitialWrite, strlen(kInitialWrite));
2477 if (SSL_get_error(ssl, write_ret) != SSL_ERROR_WANT_WRITE) {
2478 fprintf(stderr, "Failed to leave unfinished write.\n");
2481 pending_initial_write = true;
2482 } else if (config->shim_writes_first) {
2483 if (WriteAll(ssl, kInitialWrite, strlen(kInitialWrite)) < 0) {
2487 if (!config->shim_shuts_down) {
2489 // Read only 512 bytes at a time in TLS to ensure records may be
2490 // returned in multiple reads.
2491 size_t read_size = config->is_dtls ? 16384 : 512;
2492 if (config->read_size > 0) {
2493 read_size = config->read_size;
2495 std::unique_ptr<uint8_t[]> buf(new uint8_t[read_size]);
2497 int n = DoRead(ssl, buf.get(), read_size);
2498 int err = SSL_get_error(ssl, n);
2499 if (err == SSL_ERROR_ZERO_RETURN ||
2500 (n == 0 && err == SSL_ERROR_SYSCALL)) {
2502 fprintf(stderr, "Invalid SSL_get_error output\n");
2505 // Stop on either clean or unclean shutdown.
2507 } else if (err != SSL_ERROR_NONE) {
2509 fprintf(stderr, "Invalid SSL_get_error output\n");
2514 // Successfully read data.
2516 fprintf(stderr, "Invalid SSL_get_error output\n");
2520 if (!config->is_server && is_resume && !is_retry &&
2521 config->expect_reject_early_data) {
2523 "Unexpectedly received data instead of 0-RTT reject.\n");
2527 // After a successful read, with or without False Start, the handshake
2528 // must be complete unless we are doing early data.
2529 if (!GetTestState(ssl)->handshake_done &&
2530 !SSL_early_data_accepted(ssl)) {
2531 fprintf(stderr, "handshake was not completed after SSL_read\n");
2535 // Clear the initial write, if unfinished.
2536 if (pending_initial_write) {
2537 if (WriteAll(ssl, kInitialWrite, strlen(kInitialWrite)) < 0) {
2540 pending_initial_write = false;
2543 for (int i = 0; i < n; i++) {
2546 if (WriteAll(ssl, buf.get(), n) < 0) {
2553 if (!config->is_server && !config->false_start &&
2554 !config->implicit_handshake &&
2555 // Session tickets are sent post-handshake in TLS 1.3.
2556 GetProtocolVersion(ssl) < TLS1_3_VERSION &&
2557 GetTestState(ssl)->got_new_session) {
2558 fprintf(stderr, "new session was established after the handshake\n");
2562 if (GetProtocolVersion(ssl) >= TLS1_3_VERSION && !config->is_server) {
2563 bool expect_new_session =
2564 !config->expect_no_session && !config->shim_shuts_down;
2565 if (expect_new_session != GetTestState(ssl)->got_new_session) {
2567 "new session was%s cached, but we expected the opposite\n",
2568 GetTestState(ssl)->got_new_session ? "" : " not");
2572 if (expect_new_session) {
2573 bool got_early_data =
2574 GetTestState(ssl)->new_session->ticket_max_early_data != 0;
2575 if (config->expect_ticket_supports_early_data != got_early_data) {
2577 "new session did%s support early data, but we expected the "
2579 got_early_data ? "" : " not");
2586 *out_session = std::move(GetTestState(ssl)->new_session);
2589 ret = DoShutdown(ssl);
2591 if (config->shim_shuts_down && config->check_close_notify) {
2592 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
2593 // it returns zero when our close_notify is sent, then one when the peer's
2596 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
2599 ret = DoShutdown(ssl);
2603 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
2607 if (SSL_total_renegotiations(ssl) > 0) {
2608 if (!SSL_get_session(ssl)->not_resumable) {
2610 "Renegotiations should never produce resumable sessions.\n");
2614 if (SSL_session_reused(ssl)) {
2615 fprintf(stderr, "Renegotiations should never resume sessions.\n");
2619 // Re-check authentication properties after a renegotiation. The reported
2620 // values should remain unchanged even if the server sent different SCT
2622 if (!CheckAuthProperties(ssl, is_resume, config)) {
2627 if (SSL_total_renegotiations(ssl) != config->expect_total_renegotiations) {
2628 fprintf(stderr, "Expected %d renegotiations, got %d\n",
2629 config->expect_total_renegotiations, SSL_total_renegotiations(ssl));
2636 class StderrDelimiter {
2638 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
2641 int main(int argc, char **argv) {
2642 // To distinguish ASan's output from ours, add a trailing message to stderr.
2643 // Anything following this line will be considered an error.
2644 StderrDelimiter delimiter;
2646 #if defined(OPENSSL_WINDOWS)
2647 // Initialize Winsock.
2648 WORD wsa_version = MAKEWORD(2, 2);
2650 int wsa_err = WSAStartup(wsa_version, &wsa_data);
2652 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
2655 if (wsa_data.wVersion != wsa_version) {
2656 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
2660 signal(SIGPIPE, SIG_IGN);
2663 CRYPTO_library_init();
2664 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
2665 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
2666 if (g_config_index < 0 || g_state_index < 0) {
2670 TestConfig initial_config, resume_config, retry_config;
2671 if (!ParseConfig(argc - 1, argv + 1, &initial_config, &resume_config,
2673 return Usage(argv[0]);
2676 g_pool = CRYPTO_BUFFER_POOL_new();
2678 // Some code treats the zero time special, so initialize the clock to a
2680 g_clock.tv_sec = 1234;
2681 g_clock.tv_usec = 1234;
2683 bssl::UniquePtr<SSL_CTX> ssl_ctx;
2685 bssl::UniquePtr<SSL_SESSION> session;
2686 for (int i = 0; i < initial_config.resume_count + 1; i++) {
2687 bool is_resume = i > 0;
2688 TestConfig *config = is_resume ? &resume_config : &initial_config;
2689 ssl_ctx = SetupCtx(ssl_ctx.get(), config);
2691 ERR_print_errors_fp(stderr);
2695 if (is_resume && !initial_config.is_server && !session) {
2696 fprintf(stderr, "No session to offer.\n");
2700 bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
2701 if (!WriteSettings(i, config, offer_session.get())) {
2702 fprintf(stderr, "Error writing settings.\n");
2705 if (!DoConnection(&session, ssl_ctx.get(), config, &retry_config, is_resume,
2706 offer_session.get())) {
2707 fprintf(stderr, "Connection %d failed.\n", i + 1);
2708 ERR_print_errors_fp(stderr);
2712 if (config->resumption_delay != 0) {
2713 g_clock.tv_sec += config->resumption_delay;