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/e_os2.h>
21 #if !defined(OPENSSL_SYS_WINDOWS)
22 #include <arpa/inet.h>
23 #include <netinet/in.h>
24 #include <netinet/tcp.h>
26 #include <sys/socket.h>
31 #pragma warning(push, 3)
36 #pragma comment(lib, "Ws2_32.lib")
42 #include <openssl/bio.h>
43 #include <openssl/buffer.h>
44 #include <openssl/crypto.h>
45 #include <openssl/dh.h>
46 #include <openssl/err.h>
47 #include <openssl/evp.h>
48 #include <openssl/hmac.h>
49 #include <openssl/objects.h>
50 #include <openssl/rand.h>
51 #include <openssl/ssl.h>
57 #include "crypto/scoped_types.h"
58 #include "async_bio.h"
59 #include "packeted_bio.h"
60 #include "scoped_types.h"
61 #include "test_config.h"
64 #if !defined(OPENSSL_SYS_WINDOWS)
65 static int closesocket(int sock) {
69 static void PrintSocketError(const char *func) {
73 static void PrintSocketError(const char *func) {
74 fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
78 static int Usage(const char *program) {
79 fprintf(stderr, "Usage: %s [flags...]\n", program);
85 // MSVC cannot initialize these inline.
86 memset(&clock, 0, sizeof(clock));
87 memset(&clock_delta, 0, sizeof(clock_delta));
90 // async_bio is async BIO which pauses reads and writes.
91 BIO *async_bio = nullptr;
92 // clock is the current time for the SSL connection.
94 // clock_delta is how far the clock advanced in the most recent failed
97 bool cert_ready = false;
98 ScopedSSL_SESSION session;
99 ScopedSSL_SESSION pending_session;
100 bool early_callback_called = false;
101 bool handshake_done = false;
102 // private_key is the underlying private key used when testing custom keys.
103 ScopedEVP_PKEY private_key;
104 std::vector<uint8_t> private_key_result;
105 // private_key_retries is the number of times an asynchronous private key
106 // operation has been retried.
107 unsigned private_key_retries = 0;
108 bool got_new_session = false;
111 static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
112 int index, long argl, void *argp) {
113 delete ((TestState *)ptr);
116 static int g_config_index = 0;
117 static int g_state_index = 0;
119 static bool SetConfigPtr(SSL *ssl, const TestConfig *config) {
120 return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
123 static const TestConfig *GetConfigPtr(const SSL *ssl) {
124 return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
127 static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
128 // |SSL_set_ex_data| takes ownership of |state| only on success.
129 if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
136 static TestState *GetTestState(const SSL *ssl) {
137 return (TestState *)SSL_get_ex_data(ssl, g_state_index);
140 static ScopedX509 LoadCertificate(const std::string &file) {
141 ScopedBIO bio(BIO_new(BIO_s_file()));
142 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
145 return ScopedX509(PEM_read_bio_X509(bio.get(), NULL, NULL, NULL));
148 static ScopedEVP_PKEY LoadPrivateKey(const std::string &file) {
149 ScopedBIO bio(BIO_new(BIO_s_file()));
150 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
153 return ScopedEVP_PKEY(PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
158 void operator()(T *buf) {
163 static bool GetCertificate(SSL *ssl, ScopedX509 *out_x509,
164 ScopedEVP_PKEY *out_pkey) {
165 const TestConfig *config = GetConfigPtr(ssl);
167 if (!config->digest_prefs.empty()) {
168 fprintf(stderr, "Digest prefs not supported.\n");
172 if (!config->key_file.empty()) {
173 *out_pkey = LoadPrivateKey(config->key_file.c_str());
178 if (!config->cert_file.empty()) {
179 *out_x509 = LoadCertificate(config->cert_file.c_str());
184 if (!config->ocsp_response.empty()) {
185 fprintf(stderr, "OCSP response not supported.\n");
191 static bool InstallCertificate(SSL *ssl) {
194 if (!GetCertificate(ssl, &x509, &pkey)) {
199 TestState *test_state = GetTestState(ssl);
200 const TestConfig *config = GetConfigPtr(ssl);
201 if (!SSL_use_PrivateKey(ssl, pkey.get())) {
206 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
213 static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
214 if (GetConfigPtr(ssl)->async && !GetTestState(ssl)->cert_ready) {
220 if (!GetCertificate(ssl, &x509, &pkey)) {
224 // Return zero for no certificate.
229 // Asynchronous private keys are not supported with client_cert_cb.
230 *out_x509 = x509.release();
231 *out_pkey = pkey.release();
235 static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
239 static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
240 X509_STORE_CTX_set_error(store_ctx, X509_V_ERR_APPLICATION_VERIFICATION);
244 static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
245 unsigned int *out_len, void *arg) {
246 const TestConfig *config = GetConfigPtr(ssl);
247 if (config->advertise_npn.empty()) {
248 return SSL_TLSEXT_ERR_NOACK;
251 *out = (const uint8_t*)config->advertise_npn.data();
252 *out_len = config->advertise_npn.size();
253 return SSL_TLSEXT_ERR_OK;
256 static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
257 const uint8_t* in, unsigned inlen, void* arg) {
258 const TestConfig *config = GetConfigPtr(ssl);
259 if (config->select_next_proto.empty()) {
260 return SSL_TLSEXT_ERR_NOACK;
263 *out = (uint8_t*)config->select_next_proto.data();
264 *outlen = config->select_next_proto.size();
265 return SSL_TLSEXT_ERR_OK;
268 static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
269 const uint8_t* in, unsigned inlen, void* arg) {
270 const TestConfig *config = GetConfigPtr(ssl);
271 if (config->select_alpn.empty()) {
272 return SSL_TLSEXT_ERR_NOACK;
275 if (!config->expected_advertised_alpn.empty() &&
276 (config->expected_advertised_alpn.size() != inlen ||
277 memcmp(config->expected_advertised_alpn.data(),
279 fprintf(stderr, "bad ALPN select callback inputs\n");
283 *out = (const uint8_t*)config->select_alpn.data();
284 *outlen = config->select_alpn.size();
285 return SSL_TLSEXT_ERR_OK;
288 static unsigned PskClientCallback(SSL *ssl, const char *hint,
290 unsigned max_identity_len,
291 uint8_t *out_psk, unsigned max_psk_len) {
292 const TestConfig *config = GetConfigPtr(ssl);
294 if (strcmp(hint ? hint : "", config->psk_identity.c_str()) != 0) {
295 fprintf(stderr, "Server PSK hint did not match.\n");
299 // Account for the trailing '\0' for the identity.
300 if (config->psk_identity.size() >= max_identity_len ||
301 config->psk.size() > max_psk_len) {
302 fprintf(stderr, "PSK buffers too small\n");
306 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
308 memcpy(out_psk, config->psk.data(), config->psk.size());
309 return config->psk.size();
312 static unsigned PskServerCallback(SSL *ssl, const char *identity,
313 uint8_t *out_psk, unsigned max_psk_len) {
314 const TestConfig *config = GetConfigPtr(ssl);
316 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
317 fprintf(stderr, "Client PSK identity did not match.\n");
321 if (config->psk.size() > max_psk_len) {
322 fprintf(stderr, "PSK buffers too small\n");
326 memcpy(out_psk, config->psk.data(), config->psk.size());
327 return config->psk.size();
330 static int CertCallback(SSL *ssl, void *arg) {
331 if (!GetTestState(ssl)->cert_ready) {
334 if (!InstallCertificate(ssl)) {
340 static void InfoCallback(const SSL *ssl, int type, int val) {
341 if (type == SSL_CB_HANDSHAKE_DONE) {
342 if (GetConfigPtr(ssl)->handshake_never_done) {
343 fprintf(stderr, "handshake completed\n");
344 // Abort before any expected error code is printed, to ensure the overall
348 GetTestState(ssl)->handshake_done = true;
352 static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
353 GetTestState(ssl)->got_new_session = true;
354 // BoringSSL passes a reference to |session|.
355 SSL_SESSION_free(session);
359 static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
360 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
362 // This is just test code, so use the all-zeros key.
363 static const uint8_t kZeros[16] = {0};
366 memcpy(key_name, kZeros, sizeof(kZeros));
368 } else if (memcmp(key_name, kZeros, 16) != 0) {
372 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
373 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
378 return GetConfigPtr(ssl)->renew_ticket ? 2 : 1;
383 // kCustomExtensionValue is the extension value that the custom extension
384 // callbacks will add.
385 static const uint16_t kCustomExtensionValue = 1234;
386 static void *const kCustomExtensionAddArg =
387 reinterpret_cast<void *>(kCustomExtensionValue);
388 static void *const kCustomExtensionParseArg =
389 reinterpret_cast<void *>(kCustomExtensionValue + 1);
390 static const char kCustomExtensionContents[] = "custom extension";
392 static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
393 const uint8_t **out, size_t *out_len,
394 int *out_alert_value, void *add_arg) {
395 if (extension_value != kCustomExtensionValue ||
396 add_arg != kCustomExtensionAddArg) {
400 if (GetConfigPtr(ssl)->custom_extension_skip) {
403 if (GetConfigPtr(ssl)->custom_extension_fail_add) {
407 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
408 *out_len = sizeof(kCustomExtensionContents) - 1;
413 static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
414 const uint8_t *out, void *add_arg) {
415 if (extension_value != kCustomExtensionValue ||
416 add_arg != kCustomExtensionAddArg ||
417 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
422 static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
423 const uint8_t *contents,
425 int *out_alert_value, void *parse_arg) {
426 if (extension_value != kCustomExtensionValue ||
427 parse_arg != kCustomExtensionParseArg) {
431 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
432 memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
433 *out_alert_value = SSL_AD_DECODE_ERROR;
440 // Connect returns a new socket connected to localhost on |port| or -1 on
442 static int Connect(uint16_t port) {
443 int sock = socket(AF_INET, SOCK_STREAM, 0);
445 PrintSocketError("socket");
449 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
450 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
451 PrintSocketError("setsockopt");
456 memset(&sin, 0, sizeof(sin));
457 sin.sin_family = AF_INET;
458 sin.sin_port = htons(port);
459 if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
460 PrintSocketError("inet_pton");
464 if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
466 PrintSocketError("connect");
475 explicit SocketCloser(int sock) : sock_(sock) {}
477 // Half-close and drain the socket before releasing it. This seems to be
478 // necessary for graceful shutdown on Windows. It will also avoid write
479 // failures in the test runner.
480 #if defined(OPENSSL_WINDOWS)
481 shutdown(sock_, SD_SEND);
483 shutdown(sock_, SHUT_WR);
487 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
498 static ScopedSSL_CTX SetupCtx(const TestConfig *config) {
499 ScopedSSL_CTX ssl_ctx(SSL_CTX_new(
500 config->is_dtls ? DTLS_method() : TLS_method()));
505 SSL_CTX_set_security_level(ssl_ctx.get(), 0);
507 std::string cipher_list = "ALL";
508 if (!config->cipher.empty()) {
509 cipher_list = config->cipher;
510 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
512 if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
516 if (!config->cipher_tls10.empty() || !config->cipher_tls11.empty()) {
517 fprintf(stderr, "version-specific cipher lists not supported.\n");
523 if (config->use_sparse_dh_prime) {
528 if (p == NULL || g == NULL || tmpdh == NULL) {
534 // This prime number is 2^1024 + 643 – a value just above a power of two.
535 // Because of its form, values modulo it are essentially certain to be one
536 // byte shorter. This is used to test padding of these values.
539 "1000000000000000000000000000000000000000000000000000000000000000"
540 "0000000000000000000000000000000000000000000000000000000000000000"
541 "0000000000000000000000000000000000000000000000000000000000000000"
542 "0000000000000000000000000000000000000000000000000000000000000028"
544 !BN_set_word(g, 2)) {
550 DH_set0_pqg(tmpdh, p, NULL, g);
552 tmpdh = DH_get_2048_256();
557 if (!dh || !SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
561 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
563 if (config->use_old_client_cert_callback) {
564 SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
567 SSL_CTX_set_next_protos_advertised_cb(
568 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
569 if (!config->select_next_proto.empty()) {
570 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
574 if (!config->select_alpn.empty()) {
575 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
578 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
579 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
581 if (config->use_ticket_callback) {
582 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
585 if (config->enable_client_custom_extension &&
586 !SSL_CTX_add_client_custom_ext(
587 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
588 CustomExtensionFreeCallback, kCustomExtensionAddArg,
589 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
593 if (config->enable_server_custom_extension &&
594 !SSL_CTX_add_server_custom_ext(
595 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
596 CustomExtensionFreeCallback, kCustomExtensionAddArg,
597 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
601 if (config->verify_fail) {
602 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
604 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
607 if (!config->signed_cert_timestamps.empty()) {
608 fprintf(stderr, "SCTs not supported.\n");
615 // RetryAsync is called after a failed operation on |ssl| with return code
616 // |ret|. If the operation should be retried, it simulates one asynchronous
617 // event and returns true. Otherwise it returns false.
618 static bool RetryAsync(SSL *ssl, int ret) {
619 // No error; don't retry.
624 const TestConfig *config = GetConfigPtr(ssl);
625 TestState *test_state = GetTestState(ssl);
626 if (test_state->clock_delta.tv_usec != 0 ||
627 test_state->clock_delta.tv_sec != 0) {
628 // Process the timeout and retry.
629 test_state->clock.tv_usec += test_state->clock_delta.tv_usec;
630 test_state->clock.tv_sec += test_state->clock.tv_usec / 1000000;
631 test_state->clock.tv_usec %= 1000000;
632 test_state->clock.tv_sec += test_state->clock_delta.tv_sec;
633 memset(&test_state->clock_delta, 0, sizeof(test_state->clock_delta));
635 // The DTLS retransmit logic silently ignores write failures. So the test
636 // may progress, allow writes through synchronously.
638 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
640 int timeout_ret = DTLSv1_handle_timeout(ssl);
642 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
645 if (timeout_ret < 0) {
646 fprintf(stderr, "Error retransmitting.\n");
652 // See if we needed to read or write more. If so, allow one byte through on
653 // the appropriate end to maximally stress the state machine.
654 switch (SSL_get_error(ssl, ret)) {
655 case SSL_ERROR_WANT_READ:
656 AsyncBioAllowRead(test_state->async_bio, 1);
658 case SSL_ERROR_WANT_WRITE:
659 AsyncBioAllowWrite(test_state->async_bio, 1);
661 case SSL_ERROR_WANT_X509_LOOKUP:
662 test_state->cert_ready = true;
669 // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
670 // the result value of the final |SSL_read| call.
671 static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
672 const TestConfig *config = GetConfigPtr(ssl);
673 TestState *test_state = GetTestState(ssl);
677 // The DTLS retransmit logic silently ignores write failures. So the test
678 // may progress, allow writes through synchronously. |SSL_read| may
679 // trigger a retransmit, so disconnect the write quota.
680 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
682 ret = SSL_read(ssl, out, max_out);
684 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
686 } while (config->async && RetryAsync(ssl, ret));
690 // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
691 // operations. It returns the result of the final |SSL_write| call.
692 static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
693 const TestConfig *config = GetConfigPtr(ssl);
696 ret = SSL_write(ssl, in, in_len);
701 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
705 // DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
706 // returns the result of the final |SSL_shutdown| call.
707 static int DoShutdown(SSL *ssl) {
708 const TestConfig *config = GetConfigPtr(ssl);
711 ret = SSL_shutdown(ssl);
712 } while (config->async && RetryAsync(ssl, ret));
716 // CheckHandshakeProperties checks, immediately after |ssl| completes its
717 // initial handshake (or False Starts), whether all the properties are
718 // consistent with the test configuration and invariants.
719 static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
720 const TestConfig *config = GetConfigPtr(ssl);
722 if (SSL_get_current_cipher(ssl) == nullptr) {
723 fprintf(stderr, "null cipher after handshake\n");
728 (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
729 fprintf(stderr, "session was%s reused\n",
730 SSL_session_reused(ssl) ? "" : " not");
734 bool expect_handshake_done = is_resume || !config->false_start;
735 if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
736 fprintf(stderr, "handshake was%s completed\n",
737 GetTestState(ssl)->handshake_done ? "" : " not");
741 if (expect_handshake_done && !config->is_server) {
742 bool expect_new_session =
743 !config->expect_no_session &&
744 (!SSL_session_reused(ssl) || config->expect_ticket_renewal);
745 if (expect_new_session != GetTestState(ssl)->got_new_session) {
747 "new session was%s cached, but we expected the opposite\n",
748 GetTestState(ssl)->got_new_session ? "" : " not");
753 if (!config->expected_server_name.empty()) {
754 const char *server_name =
755 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
756 if (server_name != config->expected_server_name) {
757 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
758 server_name, config->expected_server_name.c_str());
763 if (!config->expected_certificate_types.empty()) {
764 const uint8_t *certificate_types;
765 size_t certificate_types_len =
766 SSL_get0_certificate_types(ssl, &certificate_types);
767 if (certificate_types_len != config->expected_certificate_types.size() ||
768 memcmp(certificate_types,
769 config->expected_certificate_types.data(),
770 certificate_types_len) != 0) {
771 fprintf(stderr, "certificate types mismatch\n");
776 if (!config->expected_next_proto.empty()) {
777 const uint8_t *next_proto;
778 unsigned next_proto_len;
779 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
780 if (next_proto_len != config->expected_next_proto.size() ||
781 memcmp(next_proto, config->expected_next_proto.data(),
782 next_proto_len) != 0) {
783 fprintf(stderr, "negotiated next proto mismatch\n");
788 if (!config->expected_alpn.empty()) {
789 const uint8_t *alpn_proto;
790 unsigned alpn_proto_len;
791 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
792 if (alpn_proto_len != config->expected_alpn.size() ||
793 memcmp(alpn_proto, config->expected_alpn.data(),
794 alpn_proto_len) != 0) {
795 fprintf(stderr, "negotiated alpn proto mismatch\n");
800 if (config->expect_verify_result) {
801 int expected_verify_result = config->verify_fail ?
802 X509_V_ERR_APPLICATION_VERIFICATION :
805 if (SSL_get_verify_result(ssl) != expected_verify_result) {
806 fprintf(stderr, "Wrong certificate verification result\n");
811 if (!config->is_server) {
812 /* Clients should expect a peer certificate chain iff this was not a PSK
814 if (config->psk.empty()) {
815 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
816 fprintf(stderr, "Missing peer certificate chain!\n");
819 } else if (SSL_get_peer_cert_chain(ssl) != nullptr) {
820 fprintf(stderr, "Unexpected peer certificate chain!\n");
827 // DoExchange runs a test SSL exchange against the peer. On success, it returns
828 // true and sets |*out_session| to the negotiated SSL session. If the test is a
829 // resumption attempt, |is_resume| is true and |session| is the session from the
830 // previous exchange.
831 static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx,
832 const TestConfig *config, bool is_resume,
833 SSL_SESSION *session) {
834 ScopedSSL ssl(SSL_new(ssl_ctx));
839 if (!SetConfigPtr(ssl.get(), config) ||
840 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
844 if (config->fallback_scsv &&
845 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
848 if (!config->use_early_callback && !config->use_old_client_cert_callback) {
850 SSL_set_cert_cb(ssl.get(), CertCallback, NULL);
851 } else if (!InstallCertificate(ssl.get())) {
855 fprintf(stderr, "Early callback not supported.\n");
858 if (config->require_any_client_certificate) {
859 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
862 if (config->verify_peer) {
863 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
865 if (config->false_start) {
866 fprintf(stderr, "False Start not supported\n");
869 if (config->partial_write) {
870 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
872 if (config->no_tls12) {
873 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
875 if (config->no_tls11) {
876 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
878 if (config->no_tls1) {
879 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
881 if (config->no_ssl3) {
882 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
884 if (!config->expected_channel_id.empty()) {
885 fprintf(stderr, "Channel ID not supported\n");
888 if (!config->send_channel_id.empty()) {
889 fprintf(stderr, "Channel ID not supported\n");
892 if (!config->host_name.empty() &&
893 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
896 if (!config->advertise_alpn.empty() &&
897 SSL_set_alpn_protos(ssl.get(),
898 (const uint8_t *)config->advertise_alpn.data(),
899 config->advertise_alpn.size()) != 0) {
902 if (!config->psk.empty()) {
903 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
904 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
906 if (!config->psk_identity.empty() &&
907 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
910 if (!config->srtp_profiles.empty() &&
911 SSL_set_tlsext_use_srtp(ssl.get(), config->srtp_profiles.c_str())) {
914 if (config->enable_ocsp_stapling) {
915 fprintf(stderr, "OCSP stapling not supported (with the same API).\n");
918 if (config->enable_signed_cert_timestamps) {
919 fprintf(stderr, "SCTs not supported (with the same API).\n");
922 if (config->min_version != 0) {
923 SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version);
925 if (config->max_version != 0) {
926 SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version);
928 if (config->mtu != 0) {
929 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
930 SSL_set_mtu(ssl.get(), config->mtu);
932 if (config->install_ddos_callback) {
933 fprintf(stderr, "DDoS callback not supported.\n");
936 if (config->renegotiate_once) {
937 fprintf(stderr, "renegotiate_once not supported.\n");
940 if (config->renegotiate_freely) {
941 // This is always on for OpenSSL.
943 if (config->renegotiate_ignore) {
944 fprintf(stderr, "renegotiate_ignore not supported.\n");
947 if (!config->check_close_notify) {
948 SSL_set_quiet_shutdown(ssl.get(), 1);
950 if (config->disable_npn) {
951 fprintf(stderr, "SSL_OP_DISABLE_NPN not supported.\n");
954 if (config->p384_only) {
955 int nid = NID_secp384r1;
956 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
960 if (config->enable_all_curves) {
961 static const int kAllCurves[] = {
962 NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_X25519,
964 if (!SSL_set1_curves(ssl.get(), kAllCurves,
965 sizeof(kAllCurves) / sizeof(kAllCurves[0]))) {
970 int sock = Connect(config->port);
974 SocketCloser closer(sock);
976 ScopedBIO bio(BIO_new_socket(sock, BIO_NOCLOSE));
980 if (config->is_dtls) {
982 PacketedBioCreate(&GetTestState(ssl.get())->clock_delta);
983 BIO_push(packeted.get(), bio.release());
984 bio = std::move(packeted);
987 ScopedBIO async_scoped =
988 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
989 BIO_push(async_scoped.get(), bio.release());
990 GetTestState(ssl.get())->async_bio = async_scoped.get();
991 bio = std::move(async_scoped);
993 SSL_set_bio(ssl.get(), bio.get(), bio.get());
994 bio.release(); // SSL_set_bio takes ownership.
996 if (session != NULL) {
997 if (!config->is_server) {
998 if (SSL_set_session(ssl.get(), session) != 1) {
1005 // KNOWN BUG: OpenSSL's SSL_get_current_cipher behaves incorrectly when
1006 // offering resumption.
1007 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1008 fprintf(stderr, "non-null cipher before handshake\n");
1014 if (config->implicit_handshake) {
1015 if (config->is_server) {
1016 SSL_set_accept_state(ssl.get());
1018 SSL_set_connect_state(ssl.get());
1022 if (config->is_server) {
1023 ret = SSL_accept(ssl.get());
1025 ret = SSL_connect(ssl.get());
1027 } while (config->async && RetryAsync(ssl.get(), ret));
1029 !CheckHandshakeProperties(ssl.get(), is_resume)) {
1033 // Reset the state to assert later that the callback isn't called in
1035 GetTestState(ssl.get())->got_new_session = false;
1038 if (config->export_keying_material > 0) {
1039 std::vector<uint8_t> result(
1040 static_cast<size_t>(config->export_keying_material));
1041 if (SSL_export_keying_material(
1042 ssl.get(), result.data(), result.size(),
1043 config->export_label.data(), config->export_label.size(),
1044 reinterpret_cast<const uint8_t*>(config->export_context.data()),
1045 config->export_context.size(), config->use_export_context) != 1) {
1046 fprintf(stderr, "failed to export keying material\n");
1049 if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1054 if (config->tls_unique) {
1055 fprintf(stderr, "tls_unique not supported\n");
1059 if (config->write_different_record_sizes) {
1060 if (config->is_dtls) {
1061 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
1064 // This mode writes a number of different record sizes in an attempt to
1065 // trip up the CBC record splitting code.
1066 static const size_t kBufLen = 32769;
1067 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1068 memset(buf.get(), 0x42, kBufLen);
1069 static const size_t kRecordSizes[] = {
1070 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
1071 for (size_t i = 0; i < sizeof(kRecordSizes) / sizeof(kRecordSizes[0]);
1073 const size_t len = kRecordSizes[i];
1074 if (len > kBufLen) {
1075 fprintf(stderr, "Bad kRecordSizes value.\n");
1078 if (WriteAll(ssl.get(), buf.get(), len) < 0) {
1083 if (config->shim_writes_first) {
1084 if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1089 if (!config->shim_shuts_down) {
1091 static const size_t kBufLen = 16384;
1092 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1094 // Read only 512 bytes at a time in TLS to ensure records may be
1095 // returned in multiple reads.
1096 int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
1097 int err = SSL_get_error(ssl.get(), n);
1098 if (err == SSL_ERROR_ZERO_RETURN ||
1099 (n == 0 && err == SSL_ERROR_SYSCALL)) {
1101 fprintf(stderr, "Invalid SSL_get_error output\n");
1104 // Stop on either clean or unclean shutdown.
1106 } else if (err != SSL_ERROR_NONE) {
1108 fprintf(stderr, "Invalid SSL_get_error output\n");
1113 // Successfully read data.
1115 fprintf(stderr, "Invalid SSL_get_error output\n");
1119 // After a successful read, with or without False Start, the handshake
1120 // must be complete.
1121 if (!GetTestState(ssl.get())->handshake_done) {
1122 fprintf(stderr, "handshake was not completed after SSL_read\n");
1126 for (int i = 0; i < n; i++) {
1129 if (WriteAll(ssl.get(), buf.get(), n) < 0) {
1136 if (!config->is_server && !config->false_start &&
1137 !config->implicit_handshake &&
1138 GetTestState(ssl.get())->got_new_session) {
1139 fprintf(stderr, "new session was established after the handshake\n");
1144 out_session->reset(SSL_get1_session(ssl.get()));
1147 ret = DoShutdown(ssl.get());
1149 if (config->shim_shuts_down && config->check_close_notify) {
1150 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1151 // it returns zero when our close_notify is sent, then one when the peer's
1154 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1157 ret = DoShutdown(ssl.get());
1161 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1165 if (SSL_total_renegotiations(ssl.get()) !=
1166 config->expect_total_renegotiations) {
1167 fprintf(stderr, "Expected %d renegotiations, got %ld\n",
1168 config->expect_total_renegotiations,
1169 SSL_total_renegotiations(ssl.get()));
1176 class StderrDelimiter {
1178 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
1181 int main(int argc, char **argv) {
1182 // To distinguish ASan's output from ours, add a trailing message to stderr.
1183 // Anything following this line will be considered an error.
1184 StderrDelimiter delimiter;
1186 #if defined(OPENSSL_WINDOWS)
1187 /* Initialize Winsock. */
1188 WORD wsa_version = MAKEWORD(2, 2);
1190 int wsa_err = WSAStartup(wsa_version, &wsa_data);
1192 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1195 if (wsa_data.wVersion != wsa_version) {
1196 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1200 signal(SIGPIPE, SIG_IGN);
1203 OPENSSL_init_crypto(0, NULL);
1204 OPENSSL_init_ssl(0, NULL);
1205 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
1206 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
1207 if (g_config_index < 0 || g_state_index < 0) {
1212 if (!ParseConfig(argc - 1, argv + 1, &config)) {
1213 return Usage(argv[0]);
1216 ScopedSSL_CTX ssl_ctx = SetupCtx(&config);
1218 ERR_print_errors_fp(stderr);
1222 ScopedSSL_SESSION session;
1223 if (!DoExchange(&session, ssl_ctx.get(), &config, false /* is_resume */,
1224 NULL /* session */)) {
1225 ERR_print_errors_fp(stderr);
1229 if (config.resume &&
1230 !DoExchange(NULL, ssl_ctx.get(), &config, true /* is_resume */,
1232 ERR_print_errors_fp(stderr);