blob: 140e666c1ecbae06de8aecac1e3c4cbc3b22583e [file] [log] [blame]
David Benjamin025b3d32014-07-01 19:53:04 -04001/* Copyright (c) 2014, Google Inc.
2 *
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.
6 *
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. */
14
David Benjamin4cc36ad2015-12-19 14:23:26 -050015#if !defined(__STDC_FORMAT_MACROS)
16#define __STDC_FORMAT_MACROS
17#endif
18
Adam Langleyded93582014-07-31 15:23:51 -070019#include <openssl/base.h>
20
21#if !defined(OPENSSL_WINDOWS)
David Benjamin025b3d32014-07-01 19:53:04 -040022#include <arpa/inet.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040023#include <netinet/in.h>
David Benjamin87c8a642015-02-21 01:54:29 -050024#include <netinet/tcp.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040025#include <signal.h>
26#include <sys/socket.h>
David Benjamin0abd6f22015-12-04 21:49:53 -050027#include <sys/time.h>
David Benjamin8f2c20e2014-07-09 09:30:38 -040028#include <unistd.h>
David Benjamin87c8a642015-02-21 01:54:29 -050029#else
30#include <io.h>
David Benjamina353cdb2016-06-09 16:48:33 -040031OPENSSL_MSVC_PRAGMA(warning(push, 3))
Adam Langley3e719312015-03-20 16:32:23 -070032#include <winsock2.h>
33#include <ws2tcpip.h>
David Benjamina353cdb2016-06-09 16:48:33 -040034OPENSSL_MSVC_PRAGMA(warning(pop))
David Benjamin87c8a642015-02-21 01:54:29 -050035
David Benjamin4fec04b2016-10-10 14:56:47 -040036OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
Adam Langleyded93582014-07-31 15:23:51 -070037#endif
38
David Benjamin585d7a42016-06-02 14:58:00 -040039#include <assert.h>
David Benjamin4cc36ad2015-12-19 14:23:26 -050040#include <inttypes.h>
Adam Langley2b2d66d2015-01-30 17:08:37 -080041#include <string.h>
David Benjamin025b3d32014-07-01 19:53:04 -040042
David Benjaminabbbee12016-10-31 19:20:42 -040043#include <openssl/aead.h>
David Benjamin025b3d32014-07-01 19:53:04 -040044#include <openssl/bio.h>
David Benjamin48cae082014-10-27 01:06:24 -040045#include <openssl/buf.h>
David Benjamin8f2c20e2014-07-09 09:30:38 -040046#include <openssl/bytestring.h>
David Benjamind98452d2015-06-16 14:16:23 -040047#include <openssl/cipher.h>
David Benjamin7a1eefd2015-10-17 23:39:22 -040048#include <openssl/crypto.h>
Matt Braithwaited17d74d2016-08-17 20:10:28 -070049#include <openssl/dh.h>
David Benjaminf0e935d2016-09-06 18:10:19 -040050#include <openssl/digest.h>
Brian Smith83a82982015-04-09 16:21:10 -100051#include <openssl/err.h>
Matt Braithwaited17d74d2016-08-17 20:10:28 -070052#include <openssl/evp.h>
David Benjamind98452d2015-06-16 14:16:23 -040053#include <openssl/hmac.h>
David Benjamin98193672016-03-25 18:07:11 -040054#include <openssl/nid.h>
David Benjamind98452d2015-06-16 14:16:23 -040055#include <openssl/rand.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040056#include <openssl/ssl.h>
Matt Braithwaited17d74d2016-08-17 20:10:28 -070057#include <openssl/x509.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040058
David Benjamin45fb1be2015-03-22 16:31:27 -040059#include <memory>
Steven Valdez0d62f262015-09-04 12:41:04 -040060#include <string>
David Benjaminc565ebb2015-04-03 04:06:36 -040061#include <vector>
David Benjamin45fb1be2015-03-22 16:31:27 -040062
Steven Valdezcb966542016-08-17 16:56:14 -040063#include "../../crypto/internal.h"
David Benjamin43ec06f2014-08-05 02:28:57 -040064#include "async_bio.h"
David Benjamin6fd297b2014-08-11 18:43:38 -040065#include "packeted_bio.h"
David Benjamin5a593af2014-08-11 19:51:50 -040066#include "test_config.h"
David Benjamin43ec06f2014-08-05 02:28:57 -040067
David Benjamin87c8a642015-02-21 01:54:29 -050068
69#if !defined(OPENSSL_WINDOWS)
70static int closesocket(int sock) {
71 return close(sock);
72}
73
74static void PrintSocketError(const char *func) {
75 perror(func);
76}
77#else
78static void PrintSocketError(const char *func) {
79 fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
80}
81#endif
82
David Benjaminc273d2c2015-02-09 12:59:46 -050083static int Usage(const char *program) {
David Benjamina7f333d2015-02-09 02:37:18 -050084 fprintf(stderr, "Usage: %s [flags...]\n", program);
David Benjamin1d5c83e2014-07-22 19:20:02 -040085 return 1;
86}
David Benjamin025b3d32014-07-01 19:53:04 -040087
David Benjamin2d445c02015-02-09 13:03:50 -050088struct TestState {
David Benjamin6c2563e2015-04-03 03:47:47 -040089 // async_bio is async BIO which pauses reads and writes.
90 BIO *async_bio = nullptr;
David Benjamin585d7a42016-06-02 14:58:00 -040091 // packeted_bio is the packeted BIO which simulates read timeouts.
92 BIO *packeted_bio = nullptr;
Matt Braithwaited17d74d2016-08-17 20:10:28 -070093 bssl::UniquePtr<EVP_PKEY> channel_id;
David Benjamin0d4db502015-03-23 18:46:05 -040094 bool cert_ready = false;
Matt Braithwaited17d74d2016-08-17 20:10:28 -070095 bssl::UniquePtr<SSL_SESSION> session;
96 bssl::UniquePtr<SSL_SESSION> pending_session;
David Benjamin0d4db502015-03-23 18:46:05 -040097 bool early_callback_called = false;
David Benjamin87e4acd2015-04-02 19:57:35 -040098 bool handshake_done = false;
David Benjaminb4d65fd2015-05-29 17:11:21 -040099 // private_key is the underlying private key used when testing custom keys.
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700100 bssl::UniquePtr<EVP_PKEY> private_key;
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700101 std::vector<uint8_t> private_key_result;
102 // private_key_retries is the number of times an asynchronous private key
103 // operation has been retried.
104 unsigned private_key_retries = 0;
David Benjaminba4594a2015-06-18 18:36:15 -0400105 bool got_new_session = false;
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700106 bssl::UniquePtr<SSL_SESSION> new_session;
David Benjamin25fe85b2016-08-09 20:00:32 -0400107 bool ticket_decrypt_done = false;
108 bool alpn_select_done = false;
David Benjamind9e07012015-02-09 03:04:34 -0500109};
110
David Benjamin2d445c02015-02-09 13:03:50 -0500111static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
Adam Langley09505632015-07-30 18:10:13 -0700112 int index, long argl, void *argp) {
David Benjamin2d445c02015-02-09 13:03:50 -0500113 delete ((TestState *)ptr);
David Benjamind9e07012015-02-09 03:04:34 -0500114}
115
116static int g_config_index = 0;
David Benjamin2d445c02015-02-09 13:03:50 -0500117static int g_state_index = 0;
David Benjamin5a593af2014-08-11 19:51:50 -0400118
David Benjamin7e7a82d2016-05-20 20:12:42 -0400119static bool SetTestConfig(SSL *ssl, const TestConfig *config) {
David Benjamind9e07012015-02-09 03:04:34 -0500120 return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
David Benjamin5a593af2014-08-11 19:51:50 -0400121}
122
David Benjamin7e7a82d2016-05-20 20:12:42 -0400123static const TestConfig *GetTestConfig(const SSL *ssl) {
David Benjamind9e07012015-02-09 03:04:34 -0500124 return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
David Benjamin5a593af2014-08-11 19:51:50 -0400125}
126
David Benjamin22050932015-11-23 13:44:48 -0500127static 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) {
130 state.release();
David Benjamind9e07012015-02-09 03:04:34 -0500131 return true;
132 }
133 return false;
134}
135
David Benjamin87e4acd2015-04-02 19:57:35 -0400136static TestState *GetTestState(const SSL *ssl) {
David Benjamin2d445c02015-02-09 13:03:50 -0500137 return (TestState *)SSL_get_ex_data(ssl, g_state_index);
David Benjamin83f90402015-01-27 01:09:43 -0500138}
139
David Benjamin2c516452016-11-15 10:16:54 +0900140static bool LoadCertificate(bssl::UniquePtr<X509> *out_x509,
141 bssl::UniquePtr<STACK_OF(X509)> *out_chain,
142 const std::string &file) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700143 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
David Benjaminacb6dcc2016-03-10 09:15:01 -0500144 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
David Benjamin2c516452016-11-15 10:16:54 +0900145 return false;
David Benjaminacb6dcc2016-03-10 09:15:01 -0500146 }
David Benjamin2c516452016-11-15 10:16:54 +0900147
148 out_x509->reset(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
149 if (!*out_x509) {
150 return false;
151 }
152
153 out_chain->reset(sk_X509_new_null());
154 if (!*out_chain) {
155 return false;
156 }
157
158 // Keep reading the certificate chain.
159 for (;;) {
160 bssl::UniquePtr<X509> cert(
161 PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
162 if (!cert) {
163 break;
164 }
165
166 if (!sk_X509_push(out_chain->get(), cert.get())) {
167 return false;
168 }
169 cert.release(); // sk_X509_push takes ownership.
170 }
171
172 uint32_t err = ERR_peek_last_error();
173 if (ERR_GET_LIB(err) != ERR_LIB_PEM ||
174 ERR_GET_REASON(err) != PEM_R_NO_START_LINE) {
175 return false;
176}
177
178 ERR_clear_error();
179 return true;
David Benjaminacb6dcc2016-03-10 09:15:01 -0500180}
181
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700182static bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
183 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
David Benjamina7f333d2015-02-09 02:37:18 -0500184 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
185 return nullptr;
David Benjamina08e49d2014-08-24 01:46:07 -0400186 }
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700187 return bssl::UniquePtr<EVP_PKEY>(
188 PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
David Benjamina08e49d2014-08-24 01:46:07 -0400189}
190
David Benjaminb4d65fd2015-05-29 17:11:21 -0400191static int AsyncPrivateKeyType(SSL *ssl) {
David Benjamin0c0b7e12016-07-14 13:47:55 -0400192 EVP_PKEY *key = GetTestState(ssl)->private_key.get();
193 switch (EVP_PKEY_id(key)) {
194 case EVP_PKEY_RSA:
195 return NID_rsaEncryption;
196 case EVP_PKEY_EC:
197 return EC_GROUP_get_curve_name(
198 EC_KEY_get0_group(EVP_PKEY_get0_EC_KEY(key)));
199 default:
200 return NID_undef;
201 }
David Benjaminb4d65fd2015-05-29 17:11:21 -0400202}
203
David Benjaminb4d65fd2015-05-29 17:11:21 -0400204static size_t AsyncPrivateKeyMaxSignatureLen(SSL *ssl) {
205 return EVP_PKEY_size(GetTestState(ssl)->private_key.get());
206}
207
208static ssl_private_key_result_t AsyncPrivateKeySign(
209 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
David Benjamind3440b42016-07-14 14:52:41 -0400210 uint16_t signature_algorithm, const uint8_t *in, size_t in_len) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400211 TestState *test_state = GetTestState(ssl);
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700212 if (!test_state->private_key_result.empty()) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400213 fprintf(stderr, "AsyncPrivateKeySign called with operation pending.\n");
214 abort();
215 }
216
David Benjamind3440b42016-07-14 14:52:41 -0400217 // Determine the hash.
218 const EVP_MD *md;
219 switch (signature_algorithm) {
220 case SSL_SIGN_RSA_PKCS1_SHA1:
221 case SSL_SIGN_ECDSA_SHA1:
222 md = EVP_sha1();
223 break;
224 case SSL_SIGN_RSA_PKCS1_SHA256:
225 case SSL_SIGN_ECDSA_SECP256R1_SHA256:
226 case SSL_SIGN_RSA_PSS_SHA256:
227 md = EVP_sha256();
228 break;
229 case SSL_SIGN_RSA_PKCS1_SHA384:
230 case SSL_SIGN_ECDSA_SECP384R1_SHA384:
231 case SSL_SIGN_RSA_PSS_SHA384:
232 md = EVP_sha384();
233 break;
234 case SSL_SIGN_RSA_PKCS1_SHA512:
235 case SSL_SIGN_ECDSA_SECP521R1_SHA512:
236 case SSL_SIGN_RSA_PSS_SHA512:
237 md = EVP_sha512();
238 break;
239 case SSL_SIGN_RSA_PKCS1_MD5_SHA1:
240 md = EVP_md5_sha1();
241 break;
242 default:
243 fprintf(stderr, "Unknown signature algorithm %04x.\n",
244 signature_algorithm);
245 return ssl_private_key_failure;
246 }
247
David Benjaminaac1e2d2016-12-06 22:35:41 -0500248 bssl::ScopedEVP_MD_CTX ctx;
David Benjamind3440b42016-07-14 14:52:41 -0400249 EVP_PKEY_CTX *pctx;
250 if (!EVP_DigestSignInit(ctx.get(), &pctx, md, nullptr,
251 test_state->private_key.get())) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400252 return ssl_private_key_failure;
253 }
254
David Benjamind3440b42016-07-14 14:52:41 -0400255 // Configure additional signature parameters.
256 switch (signature_algorithm) {
257 case SSL_SIGN_RSA_PSS_SHA256:
258 case SSL_SIGN_RSA_PSS_SHA384:
259 case SSL_SIGN_RSA_PSS_SHA512:
260 if (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) ||
261 !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
262 -1 /* salt len = hash len */)) {
263 return ssl_private_key_failure;
264 }
265 }
266
David Benjaminb4d65fd2015-05-29 17:11:21 -0400267 // Write the signature into |test_state|.
268 size_t len = 0;
David Benjamind3440b42016-07-14 14:52:41 -0400269 if (!EVP_DigestSignUpdate(ctx.get(), in, in_len) ||
270 !EVP_DigestSignFinal(ctx.get(), nullptr, &len)) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400271 return ssl_private_key_failure;
272 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700273 test_state->private_key_result.resize(len);
David Benjamind3440b42016-07-14 14:52:41 -0400274 if (!EVP_DigestSignFinal(ctx.get(), test_state->private_key_result.data(),
275 &len)) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400276 return ssl_private_key_failure;
277 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700278 test_state->private_key_result.resize(len);
David Benjaminb4d65fd2015-05-29 17:11:21 -0400279
David Benjamind3440b42016-07-14 14:52:41 -0400280 // The signature will be released asynchronously in |AsyncPrivateKeyComplete|.
David Benjaminb4d65fd2015-05-29 17:11:21 -0400281 return ssl_private_key_retry;
282}
283
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700284static ssl_private_key_result_t AsyncPrivateKeyDecrypt(
285 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
286 const uint8_t *in, size_t in_len) {
287 TestState *test_state = GetTestState(ssl);
288 if (!test_state->private_key_result.empty()) {
289 fprintf(stderr,
290 "AsyncPrivateKeyDecrypt called with operation pending.\n");
291 abort();
292 }
293
David Benjamin758d1272015-11-20 17:47:25 -0500294 RSA *rsa = EVP_PKEY_get0_RSA(test_state->private_key.get());
295 if (rsa == NULL) {
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700296 fprintf(stderr,
297 "AsyncPrivateKeyDecrypt called with incorrect key type.\n");
298 abort();
299 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700300 test_state->private_key_result.resize(RSA_size(rsa));
David Benjaminef14b2d2015-11-11 14:01:27 -0800301 if (!RSA_decrypt(rsa, out_len, test_state->private_key_result.data(),
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700302 RSA_size(rsa), in, in_len, RSA_NO_PADDING)) {
303 return ssl_private_key_failure;
304 }
305
306 test_state->private_key_result.resize(*out_len);
307
David Benjamind3440b42016-07-14 14:52:41 -0400308 // The decryption will be released asynchronously in |AsyncPrivateComplete|.
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700309 return ssl_private_key_retry;
310}
311
David Benjamind3440b42016-07-14 14:52:41 -0400312static ssl_private_key_result_t AsyncPrivateKeyComplete(
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700313 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
314 TestState *test_state = GetTestState(ssl);
315 if (test_state->private_key_result.empty()) {
316 fprintf(stderr,
David Benjamind3440b42016-07-14 14:52:41 -0400317 "AsyncPrivateKeyComplete called without operation pending.\n");
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700318 abort();
319 }
320
321 if (test_state->private_key_retries < 2) {
322 // Only return the decryption on the second attempt, to test both incomplete
323 // |decrypt| and |decrypt_complete|.
324 return ssl_private_key_retry;
325 }
326
327 if (max_out < test_state->private_key_result.size()) {
328 fprintf(stderr, "Output buffer too small.\n");
329 return ssl_private_key_failure;
330 }
David Benjaminef14b2d2015-11-11 14:01:27 -0800331 memcpy(out, test_state->private_key_result.data(),
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700332 test_state->private_key_result.size());
333 *out_len = test_state->private_key_result.size();
334
335 test_state->private_key_result.clear();
336 test_state->private_key_retries = 0;
David Benjaminb4d65fd2015-05-29 17:11:21 -0400337 return ssl_private_key_success;
338}
339
340static const SSL_PRIVATE_KEY_METHOD g_async_private_key_method = {
341 AsyncPrivateKeyType,
David Benjaminb4d65fd2015-05-29 17:11:21 -0400342 AsyncPrivateKeyMaxSignatureLen,
343 AsyncPrivateKeySign,
David Benjamind3440b42016-07-14 14:52:41 -0400344 nullptr /* sign_digest */,
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700345 AsyncPrivateKeyDecrypt,
David Benjamind3440b42016-07-14 14:52:41 -0400346 AsyncPrivateKeyComplete,
David Benjaminb4d65fd2015-05-29 17:11:21 -0400347};
348
Steven Valdez0d62f262015-09-04 12:41:04 -0400349template<typename T>
Adam Langley10f97f32016-07-12 08:09:33 -0700350struct Free {
Steven Valdez0d62f262015-09-04 12:41:04 -0400351 void operator()(T *buf) {
352 free(buf);
353 }
354};
355
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700356static bool GetCertificate(SSL *ssl, bssl::UniquePtr<X509> *out_x509,
David Benjamin2c516452016-11-15 10:16:54 +0900357 bssl::UniquePtr<STACK_OF(X509)> *out_chain,
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700358 bssl::UniquePtr<EVP_PKEY> *out_pkey) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400359 const TestConfig *config = GetTestConfig(ssl);
Steven Valdez0d62f262015-09-04 12:41:04 -0400360
361 if (!config->digest_prefs.empty()) {
Adam Langley10f97f32016-07-12 08:09:33 -0700362 std::unique_ptr<char, Free<char>> digest_prefs(
Steven Valdez0d62f262015-09-04 12:41:04 -0400363 strdup(config->digest_prefs.c_str()));
Steven Valdez0d62f262015-09-04 12:41:04 -0400364 std::vector<int> digest_list;
365
366 for (;;) {
Adam Langley67251f22015-09-23 15:01:07 -0700367 char *token =
368 strtok(digest_list.empty() ? digest_prefs.get() : nullptr, ",");
Steven Valdez0d62f262015-09-04 12:41:04 -0400369 if (token == nullptr) {
370 break;
371 }
372
373 digest_list.push_back(EVP_MD_type(EVP_get_digestbyname(token)));
374 }
375
376 if (!SSL_set_private_key_digest_prefs(ssl, digest_list.data(),
377 digest_list.size())) {
378 return false;
379 }
380 }
381
David Benjaminca3d5452016-07-14 12:51:01 -0400382 if (!config->signing_prefs.empty()) {
383 std::vector<uint16_t> u16s(config->signing_prefs.begin(),
384 config->signing_prefs.end());
385 if (!SSL_set_signing_algorithm_prefs(ssl, u16s.data(), u16s.size())) {
386 return false;
387 }
388 }
389
David Benjaminb4d65fd2015-05-29 17:11:21 -0400390 if (!config->key_file.empty()) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500391 *out_pkey = LoadPrivateKey(config->key_file.c_str());
392 if (!*out_pkey) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400393 return false;
394 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500395 }
David Benjamin2c516452016-11-15 10:16:54 +0900396 if (!config->cert_file.empty() &&
397 !LoadCertificate(out_x509, out_chain, config->cert_file.c_str())) {
398 return false;
David Benjamin41fdbcd2015-02-09 03:13:35 -0500399 }
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100400 if (!config->ocsp_response.empty() &&
Alessandro Ghedini559f0642016-12-07 12:55:32 +0000401 !SSL_set_ocsp_response(ssl, (const uint8_t *)config->ocsp_response.data(),
402 config->ocsp_response.size())) {
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100403 return false;
404 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500405 return true;
406}
407
David Benjaminacb6dcc2016-03-10 09:15:01 -0500408static bool InstallCertificate(SSL *ssl) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700409 bssl::UniquePtr<X509> x509;
David Benjamin2c516452016-11-15 10:16:54 +0900410 bssl::UniquePtr<STACK_OF(X509)> chain;
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700411 bssl::UniquePtr<EVP_PKEY> pkey;
David Benjamin2c516452016-11-15 10:16:54 +0900412 if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500413 return false;
414 }
415
416 if (pkey) {
417 TestState *test_state = GetTestState(ssl);
David Benjamin7e7a82d2016-05-20 20:12:42 -0400418 const TestConfig *config = GetTestConfig(ssl);
David Benjaminacb6dcc2016-03-10 09:15:01 -0500419 if (config->async) {
420 test_state->private_key = std::move(pkey);
421 SSL_set_private_key_method(ssl, &g_async_private_key_method);
422 } else if (!SSL_use_PrivateKey(ssl, pkey.get())) {
423 return false;
424 }
425 }
426
427 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
428 return false;
429 }
430
David Benjamin2c516452016-11-15 10:16:54 +0900431 if (sk_X509_num(chain.get()) > 0 &&
432 !SSL_set1_chain(ssl, chain.get())) {
433 return false;
434 }
435
David Benjaminacb6dcc2016-03-10 09:15:01 -0500436 return true;
437}
438
David Benjamin731058e2016-12-03 23:15:13 -0500439static int SelectCertificateCallback(const SSL_CLIENT_HELLO *client_hello) {
440 const TestConfig *config = GetTestConfig(client_hello->ssl);
441 GetTestState(client_hello->ssl)->early_callback_called = true;
David Benjamin5a593af2014-08-11 19:51:50 -0400442
David Benjamin6f5c0f42015-02-24 01:23:21 -0500443 if (!config->expected_server_name.empty()) {
444 const uint8_t *extension_data;
445 size_t extension_len;
446 CBS extension, server_name_list, host_name;
447 uint8_t name_type;
448
David Benjamin731058e2016-12-03 23:15:13 -0500449 if (!SSL_early_callback_ctx_extension_get(
450 client_hello, TLSEXT_TYPE_server_name, &extension_data,
451 &extension_len)) {
David Benjamin6f5c0f42015-02-24 01:23:21 -0500452 fprintf(stderr, "Could not find server_name extension.\n");
453 return -1;
454 }
455
456 CBS_init(&extension, extension_data, extension_len);
457 if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
458 CBS_len(&extension) != 0 ||
459 !CBS_get_u8(&server_name_list, &name_type) ||
460 name_type != TLSEXT_NAMETYPE_host_name ||
461 !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
462 CBS_len(&server_name_list) != 0) {
463 fprintf(stderr, "Could not decode server_name extension.\n");
464 return -1;
465 }
466
467 if (!CBS_mem_equal(&host_name,
468 (const uint8_t*)config->expected_server_name.data(),
469 config->expected_server_name.size())) {
470 fprintf(stderr, "Server name mismatch.\n");
471 }
David Benjamin7b030512014-07-08 17:30:11 -0400472 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400473
David Benjamin6f5c0f42015-02-24 01:23:21 -0500474 if (config->fail_early_callback) {
David Benjamin7b030512014-07-08 17:30:11 -0400475 return -1;
476 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400477
David Benjamin6f5c0f42015-02-24 01:23:21 -0500478 // Install the certificate in the early callback.
479 if (config->use_early_callback) {
480 if (config->async) {
481 // Install the certificate asynchronously.
482 return 0;
483 }
David Benjamin731058e2016-12-03 23:15:13 -0500484 if (!InstallCertificate(client_hello->ssl)) {
David Benjamin6f5c0f42015-02-24 01:23:21 -0500485 return -1;
486 }
David Benjamin7b030512014-07-08 17:30:11 -0400487 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400488 return 1;
489}
David Benjamin025b3d32014-07-01 19:53:04 -0400490
David Benjamin5edfc8c2016-12-10 15:46:58 -0500491static bool CheckCertificateRequest(SSL *ssl) {
492 const TestConfig *config = GetTestConfig(ssl);
493
494 if (!config->expected_certificate_types.empty()) {
495 const uint8_t *certificate_types;
496 size_t certificate_types_len =
497 SSL_get0_certificate_types(ssl, &certificate_types);
498 if (certificate_types_len != config->expected_certificate_types.size() ||
499 memcmp(certificate_types,
500 config->expected_certificate_types.data(),
501 certificate_types_len) != 0) {
502 fprintf(stderr, "certificate types mismatch\n");
503 return false;
504 }
505 }
506
507 // TODO(davidben): Test |SSL_get_client_CA_list|.
508 return true;
509}
510
David Benjaminacb6dcc2016-03-10 09:15:01 -0500511static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
David Benjamin5edfc8c2016-12-10 15:46:58 -0500512 if (!CheckCertificateRequest(ssl)) {
513 return -1;
514 }
515
David Benjamin7e7a82d2016-05-20 20:12:42 -0400516 if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500517 return -1;
518 }
519
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700520 bssl::UniquePtr<X509> x509;
David Benjamin2c516452016-11-15 10:16:54 +0900521 bssl::UniquePtr<STACK_OF(X509)> chain;
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700522 bssl::UniquePtr<EVP_PKEY> pkey;
David Benjamin2c516452016-11-15 10:16:54 +0900523 if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500524 return -1;
525 }
526
527 // Return zero for no certificate.
528 if (!x509) {
529 return 0;
530 }
531
David Benjamin2c516452016-11-15 10:16:54 +0900532 // Chains and asynchronous private keys are not supported with client_cert_cb.
David Benjaminacb6dcc2016-03-10 09:15:01 -0500533 *out_x509 = x509.release();
534 *out_pkey = pkey.release();
535 return 1;
536}
537
David Benjamin5edfc8c2016-12-10 15:46:58 -0500538static int CertCallback(SSL *ssl, void *arg) {
539 const TestConfig *config = GetTestConfig(ssl);
540
541 // Check the CertificateRequest metadata is as expected.
542 if (!SSL_is_server(ssl) && !CheckCertificateRequest(ssl)) {
543 return -1;
544 }
545
546 if (config->fail_cert_callback) {
547 return 0;
548 }
549
550 // The certificate will be installed via other means.
551 if (!config->async || config->use_early_callback) {
552 return 1;
553 }
554
555 if (!GetTestState(ssl)->cert_ready) {
556 return -1;
557 }
558 if (!InstallCertificate(ssl)) {
559 return 0;
560 }
561 return 1;
562}
563
Paul Lietar8f1c2682015-08-18 12:21:54 +0100564static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
565 SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data(store_ctx,
566 SSL_get_ex_data_X509_STORE_CTX_idx());
David Benjamin7e7a82d2016-05-20 20:12:42 -0400567 const TestConfig *config = GetTestConfig(ssl);
Paul Lietar8f1c2682015-08-18 12:21:54 +0100568
569 if (!config->expected_ocsp_response.empty()) {
570 const uint8_t *data;
571 size_t len;
572 SSL_get0_ocsp_response(ssl, &data, &len);
573 if (len == 0) {
574 fprintf(stderr, "OCSP response not available in verify callback\n");
575 return 0;
576 }
577 }
578
David Benjamin67666e72014-07-12 15:47:52 -0400579 return 1;
580}
581
Paul Lietar8f1c2682015-08-18 12:21:54 +0100582static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
583 store_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION;
584 return 0;
585}
586
David Benjaminc273d2c2015-02-09 12:59:46 -0500587static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
588 unsigned int *out_len, void *arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400589 const TestConfig *config = GetTestConfig(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500590 if (config->advertise_npn.empty()) {
David Benjamin1f5f62b2014-07-12 16:18:02 -0400591 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500592 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400593
David Benjamin5a593af2014-08-11 19:51:50 -0400594 *out = (const uint8_t*)config->advertise_npn.data();
595 *out_len = config->advertise_npn.size();
David Benjamin1f5f62b2014-07-12 16:18:02 -0400596 return SSL_TLSEXT_ERR_OK;
597}
598
David Benjaminc273d2c2015-02-09 12:59:46 -0500599static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
David Benjamin8b368412015-03-14 01:54:17 -0400600 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400601 const TestConfig *config = GetTestConfig(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500602 if (config->select_next_proto.empty()) {
David Benjamin7e3305e2014-07-28 14:52:32 -0400603 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500604 }
David Benjamin7e3305e2014-07-28 14:52:32 -0400605
David Benjamin5a593af2014-08-11 19:51:50 -0400606 *out = (uint8_t*)config->select_next_proto.data();
607 *outlen = config->select_next_proto.size();
David Benjamin7e3305e2014-07-28 14:52:32 -0400608 return SSL_TLSEXT_ERR_OK;
609}
610
David Benjaminc273d2c2015-02-09 12:59:46 -0500611static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
612 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin25fe85b2016-08-09 20:00:32 -0400613 if (GetTestState(ssl)->alpn_select_done) {
614 fprintf(stderr, "AlpnSelectCallback called after completion.\n");
615 exit(1);
616 }
617
618 GetTestState(ssl)->alpn_select_done = true;
619
David Benjamin7e7a82d2016-05-20 20:12:42 -0400620 const TestConfig *config = GetTestConfig(ssl);
David Benjamin594e7d22016-03-17 17:49:56 -0400621 if (config->decline_alpn) {
David Benjaminae2888f2014-09-06 12:58:58 -0400622 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500623 }
David Benjaminae2888f2014-09-06 12:58:58 -0400624
625 if (!config->expected_advertised_alpn.empty() &&
626 (config->expected_advertised_alpn.size() != inlen ||
627 memcmp(config->expected_advertised_alpn.data(),
628 in, inlen) != 0)) {
629 fprintf(stderr, "bad ALPN select callback inputs\n");
630 exit(1);
631 }
632
633 *out = (const uint8_t*)config->select_alpn.data();
634 *outlen = config->select_alpn.size();
635 return SSL_TLSEXT_ERR_OK;
636}
637
David Benjaminc273d2c2015-02-09 12:59:46 -0500638static unsigned PskClientCallback(SSL *ssl, const char *hint,
639 char *out_identity,
640 unsigned max_identity_len,
641 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400642 const TestConfig *config = GetTestConfig(ssl);
David Benjamin48cae082014-10-27 01:06:24 -0400643
David Benjamin78679342016-09-16 19:42:05 -0400644 if (config->psk_identity.empty()) {
645 if (hint != nullptr) {
646 fprintf(stderr, "Server PSK hint was non-null.\n");
647 return 0;
648 }
649 } else if (hint == nullptr ||
650 strcmp(hint, config->psk_identity.c_str()) != 0) {
David Benjamin48cae082014-10-27 01:06:24 -0400651 fprintf(stderr, "Server PSK hint did not match.\n");
652 return 0;
653 }
654
655 // Account for the trailing '\0' for the identity.
656 if (config->psk_identity.size() >= max_identity_len ||
657 config->psk.size() > max_psk_len) {
658 fprintf(stderr, "PSK buffers too small\n");
659 return 0;
660 }
661
662 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
663 max_identity_len);
664 memcpy(out_psk, config->psk.data(), config->psk.size());
665 return config->psk.size();
666}
667
David Benjaminc273d2c2015-02-09 12:59:46 -0500668static unsigned PskServerCallback(SSL *ssl, const char *identity,
669 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400670 const TestConfig *config = GetTestConfig(ssl);
David Benjamin48cae082014-10-27 01:06:24 -0400671
672 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
673 fprintf(stderr, "Client PSK identity did not match.\n");
674 return 0;
675 }
676
677 if (config->psk.size() > max_psk_len) {
678 fprintf(stderr, "PSK buffers too small\n");
679 return 0;
680 }
681
682 memcpy(out_psk, config->psk.data(), config->psk.size());
683 return config->psk.size();
684}
685
David Benjamin1b22f852016-10-27 16:36:32 -0400686static timeval g_clock;
687
David Benjamin4d2e7ce2015-05-08 13:29:45 -0400688static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
David Benjamin1b22f852016-10-27 16:36:32 -0400689 *out_clock = g_clock;
David Benjamin377fc312015-01-26 00:22:12 -0500690}
691
David Benjaminc273d2c2015-02-09 12:59:46 -0500692static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
David Benjamin2d445c02015-02-09 13:03:50 -0500693 *out_pkey = GetTestState(ssl)->channel_id.release();
David Benjamind9e07012015-02-09 03:04:34 -0500694}
695
David Benjaminc273d2c2015-02-09 12:59:46 -0500696static SSL_SESSION *GetSessionCallback(SSL *ssl, uint8_t *data, int len,
697 int *copy) {
David Benjamin2d445c02015-02-09 13:03:50 -0500698 TestState *async_state = GetTestState(ssl);
David Benjamin1b8b6912015-02-09 04:28:16 -0500699 if (async_state->session) {
700 *copy = 0;
701 return async_state->session.release();
702 } else if (async_state->pending_session) {
703 return SSL_magic_pending_session_ptr();
704 } else {
705 return NULL;
706 }
707}
708
David Benjamin731058e2016-12-03 23:15:13 -0500709static int DDoSCallback(const SSL_CLIENT_HELLO *client_hello) {
710 const TestConfig *config = GetTestConfig(client_hello->ssl);
Adam Langley524e7172015-02-20 16:04:00 -0800711 static int callback_num = 0;
712
713 callback_num++;
714 if (config->fail_ddos_callback ||
715 (config->fail_second_ddos_callback && callback_num == 2)) {
716 return 0;
717 }
718 return 1;
719}
720
David Benjamin87e4acd2015-04-02 19:57:35 -0400721static void InfoCallback(const SSL *ssl, int type, int val) {
722 if (type == SSL_CB_HANDSHAKE_DONE) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400723 if (GetTestConfig(ssl)->handshake_never_done) {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400724 fprintf(stderr, "Handshake unexpectedly completed.\n");
David Benjamin87e4acd2015-04-02 19:57:35 -0400725 // Abort before any expected error code is printed, to ensure the overall
726 // test fails.
727 abort();
728 }
729 GetTestState(ssl)->handshake_done = true;
David Benjamin25fe85b2016-08-09 20:00:32 -0400730
731 // Callbacks may be called again on a new handshake.
732 GetTestState(ssl)->ticket_decrypt_done = false;
733 GetTestState(ssl)->alpn_select_done = false;
David Benjamin87e4acd2015-04-02 19:57:35 -0400734 }
735}
736
David Benjaminba4594a2015-06-18 18:36:15 -0400737static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
738 GetTestState(ssl)->got_new_session = true;
Steven Valdez4aa154e2016-07-29 14:32:55 -0400739 GetTestState(ssl)->new_session.reset(session);
David Benjaminba4594a2015-06-18 18:36:15 -0400740 return 1;
741}
742
David Benjamind98452d2015-06-16 14:16:23 -0400743static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
744 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
745 int encrypt) {
David Benjamin25fe85b2016-08-09 20:00:32 -0400746 if (!encrypt) {
747 if (GetTestState(ssl)->ticket_decrypt_done) {
748 fprintf(stderr, "TicketKeyCallback called after completion.\n");
749 return -1;
750 }
751
752 GetTestState(ssl)->ticket_decrypt_done = true;
753 }
754
David Benjamind98452d2015-06-16 14:16:23 -0400755 // This is just test code, so use the all-zeros key.
756 static const uint8_t kZeros[16] = {0};
757
758 if (encrypt) {
759 memcpy(key_name, kZeros, sizeof(kZeros));
760 RAND_bytes(iv, 16);
761 } else if (memcmp(key_name, kZeros, 16) != 0) {
762 return 0;
763 }
764
765 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
766 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
767 return -1;
768 }
769
770 if (!encrypt) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400771 return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
David Benjamind98452d2015-06-16 14:16:23 -0400772 }
773 return 1;
774}
775
Adam Langley09505632015-07-30 18:10:13 -0700776// kCustomExtensionValue is the extension value that the custom extension
777// callbacks will add.
Adam Langleyc5b23a12015-07-30 18:19:26 -0700778static const uint16_t kCustomExtensionValue = 1234;
Adam Langley09505632015-07-30 18:10:13 -0700779static void *const kCustomExtensionAddArg =
780 reinterpret_cast<void *>(kCustomExtensionValue);
781static void *const kCustomExtensionParseArg =
782 reinterpret_cast<void *>(kCustomExtensionValue + 1);
783static const char kCustomExtensionContents[] = "custom extension";
784
785static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
786 const uint8_t **out, size_t *out_len,
787 int *out_alert_value, void *add_arg) {
788 if (extension_value != kCustomExtensionValue ||
789 add_arg != kCustomExtensionAddArg) {
790 abort();
791 }
792
David Benjamin7e7a82d2016-05-20 20:12:42 -0400793 if (GetTestConfig(ssl)->custom_extension_skip) {
Adam Langley09505632015-07-30 18:10:13 -0700794 return 0;
795 }
David Benjamin7e7a82d2016-05-20 20:12:42 -0400796 if (GetTestConfig(ssl)->custom_extension_fail_add) {
Adam Langley09505632015-07-30 18:10:13 -0700797 return -1;
798 }
799
800 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
801 *out_len = sizeof(kCustomExtensionContents) - 1;
802
803 return 1;
804}
805
806static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
807 const uint8_t *out, void *add_arg) {
808 if (extension_value != kCustomExtensionValue ||
809 add_arg != kCustomExtensionAddArg ||
810 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
811 abort();
812 }
813}
814
815static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
816 const uint8_t *contents,
817 size_t contents_len,
818 int *out_alert_value, void *parse_arg) {
819 if (extension_value != kCustomExtensionValue ||
820 parse_arg != kCustomExtensionParseArg) {
821 abort();
822 }
823
824 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
825 memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
826 *out_alert_value = SSL_AD_DECODE_ERROR;
827 return 0;
828 }
829
830 return 1;
831}
832
David Benjamin8b176712016-10-27 21:51:24 -0400833static int ServerNameCallback(SSL *ssl, int *out_alert, void *arg) {
834 // SNI must be accessible from the SNI callback.
835 const TestConfig *config = GetTestConfig(ssl);
836 const char *server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
837 if (server_name == nullptr ||
838 std::string(server_name) != config->expected_server_name) {
839 fprintf(stderr, "servername mismatch (got %s; want %s)\n", server_name,
840 config->expected_server_name.c_str());
841 return SSL_TLSEXT_ERR_ALERT_FATAL;
842 }
843
844 return SSL_TLSEXT_ERR_OK;
845}
846
David Benjamin87c8a642015-02-21 01:54:29 -0500847// Connect returns a new socket connected to localhost on |port| or -1 on
848// error.
849static int Connect(uint16_t port) {
850 int sock = socket(AF_INET, SOCK_STREAM, 0);
851 if (sock == -1) {
852 PrintSocketError("socket");
853 return -1;
854 }
855 int nodelay = 1;
856 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
857 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
858 PrintSocketError("setsockopt");
859 closesocket(sock);
860 return -1;
861 }
862 sockaddr_in sin;
863 memset(&sin, 0, sizeof(sin));
864 sin.sin_family = AF_INET;
865 sin.sin_port = htons(port);
866 if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
867 PrintSocketError("inet_pton");
868 closesocket(sock);
869 return -1;
870 }
871 if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
872 sizeof(sin)) != 0) {
873 PrintSocketError("connect");
874 closesocket(sock);
875 return -1;
876 }
877 return sock;
878}
879
880class SocketCloser {
881 public:
882 explicit SocketCloser(int sock) : sock_(sock) {}
883 ~SocketCloser() {
884 // Half-close and drain the socket before releasing it. This seems to be
885 // necessary for graceful shutdown on Windows. It will also avoid write
886 // failures in the test runner.
887#if defined(OPENSSL_WINDOWS)
888 shutdown(sock_, SD_SEND);
889#else
890 shutdown(sock_, SHUT_WR);
891#endif
892 while (true) {
893 char buf[1024];
894 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
895 break;
896 }
897 }
898 closesocket(sock_);
899 }
900
901 private:
902 const int sock_;
903};
904
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700905static bssl::UniquePtr<SSL_CTX> SetupCtx(const TestConfig *config) {
906 bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(
David Benjamina7f333d2015-02-09 02:37:18 -0500907 config->is_dtls ? DTLS_method() : TLS_method()));
908 if (!ssl_ctx) {
909 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -0400910 }
911
David Benjamin2dc02042016-09-19 19:57:37 -0400912 // Enable TLS 1.3 for tests.
913 if (!config->is_dtls &&
David Benjamine4706902016-09-20 15:12:23 -0400914 !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION)) {
David Benjamin2dc02042016-09-19 19:57:37 -0400915 return nullptr;
Nick Harper1fd39d82016-06-14 18:14:35 -0700916 }
917
Adam Langleycef75832015-09-03 14:51:12 -0700918 std::string cipher_list = "ALL";
919 if (!config->cipher.empty()) {
920 cipher_list = config->cipher;
921 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
922 }
923 if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
924 return nullptr;
925 }
926
927 if (!config->cipher_tls10.empty() &&
928 !SSL_CTX_set_cipher_list_tls10(ssl_ctx.get(),
929 config->cipher_tls10.c_str())) {
930 return nullptr;
931 }
932 if (!config->cipher_tls11.empty() &&
933 !SSL_CTX_set_cipher_list_tls11(ssl_ctx.get(),
934 config->cipher_tls11.c_str())) {
David Benjamina7f333d2015-02-09 02:37:18 -0500935 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -0400936 }
937
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700938 bssl::UniquePtr<DH> dh(DH_get_2048_256(NULL));
David Benjaminb7c5e842016-03-28 09:59:10 -0400939 if (!dh) {
940 return nullptr;
941 }
Adam Langleyc4f25ce2015-11-26 16:39:08 -0800942
943 if (config->use_sparse_dh_prime) {
944 // This prime number is 2^1024 + 643 – a value just above a power of two.
945 // Because of its form, values modulo it are essentially certain to be one
946 // byte shorter. This is used to test padding of these values.
947 if (BN_hex2bn(
948 &dh->p,
949 "1000000000000000000000000000000000000000000000000000000000000000"
950 "0000000000000000000000000000000000000000000000000000000000000000"
951 "0000000000000000000000000000000000000000000000000000000000000000"
952 "0000000000000000000000000000000000000000000000000000000000000028"
953 "3") == 0 ||
954 !BN_set_word(dh->g, 2)) {
955 return nullptr;
956 }
David Benjamine66148a2016-02-02 14:14:36 -0500957 BN_free(dh->q);
958 dh->q = NULL;
Adam Langleyc4f25ce2015-11-26 16:39:08 -0800959 dh->priv_length = 0;
960 }
961
David Benjaminb7c5e842016-03-28 09:59:10 -0400962 if (!SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
David Benjamina7f333d2015-02-09 02:37:18 -0500963 return nullptr;
David Benjaminf4e5c4e2014-08-02 17:35:45 -0400964 }
965
David Benjamin1b8b6912015-02-09 04:28:16 -0500966 if (config->async && config->is_server) {
967 // Disable the internal session cache. To test asynchronous session lookup,
968 // we use an external session cache.
969 SSL_CTX_set_session_cache_mode(
970 ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
David Benjaminc273d2c2015-02-09 12:59:46 -0500971 SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
David Benjamin1b8b6912015-02-09 04:28:16 -0500972 } else {
973 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
974 }
David Benjamin1d5c83e2014-07-22 19:20:02 -0400975
David Benjamind4c2bce2015-10-17 12:28:18 -0400976 SSL_CTX_set_select_certificate_cb(ssl_ctx.get(), SelectCertificateCallback);
David Benjamin8f2c20e2014-07-09 09:30:38 -0400977
David Benjaminacb6dcc2016-03-10 09:15:01 -0500978 if (config->use_old_client_cert_callback) {
979 SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
980 }
981
David Benjamin1f5f62b2014-07-12 16:18:02 -0400982 SSL_CTX_set_next_protos_advertised_cb(
David Benjaminc273d2c2015-02-09 12:59:46 -0500983 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400984 if (!config->select_next_proto.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500985 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
David Benjamina7f333d2015-02-09 02:37:18 -0500986 NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400987 }
988
David Benjamin594e7d22016-03-17 17:49:56 -0400989 if (!config->select_alpn.empty() || config->decline_alpn) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500990 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400991 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400992
David Benjamineebd3c82016-12-06 17:43:58 -0500993 SSL_CTX_set_tls_channel_id_enabled(ssl_ctx.get(), 1);
David Benjaminc273d2c2015-02-09 12:59:46 -0500994 SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
David Benjamina08e49d2014-08-24 01:46:07 -0400995
David Benjamin1b22f852016-10-27 16:36:32 -0400996 SSL_CTX_set_current_time_cb(ssl_ctx.get(), CurrentTimeCallback);
David Benjamin377fc312015-01-26 00:22:12 -0500997
David Benjamin87e4acd2015-04-02 19:57:35 -0400998 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
David Benjaminba4594a2015-06-18 18:36:15 -0400999 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
David Benjamin87e4acd2015-04-02 19:57:35 -04001000
David Benjamind98452d2015-06-16 14:16:23 -04001001 if (config->use_ticket_callback) {
1002 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
1003 }
1004
Adam Langley09505632015-07-30 18:10:13 -07001005 if (config->enable_client_custom_extension &&
1006 !SSL_CTX_add_client_custom_ext(
1007 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
1008 CustomExtensionFreeCallback, kCustomExtensionAddArg,
1009 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1010 return nullptr;
1011 }
1012
1013 if (config->enable_server_custom_extension &&
1014 !SSL_CTX_add_server_custom_ext(
1015 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
1016 CustomExtensionFreeCallback, kCustomExtensionAddArg,
1017 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1018 return nullptr;
1019 }
1020
Paul Lietar8f1c2682015-08-18 12:21:54 +01001021 if (config->verify_fail) {
1022 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
1023 } else {
1024 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
1025 }
1026
Paul Lietar4fac72e2015-09-09 13:44:55 +01001027 if (!config->signed_cert_timestamps.empty() &&
1028 !SSL_CTX_set_signed_cert_timestamp_list(
1029 ssl_ctx.get(), (const uint8_t *)config->signed_cert_timestamps.data(),
1030 config->signed_cert_timestamps.size())) {
1031 return nullptr;
1032 }
1033
David Benjamin2f8935d2016-07-13 19:47:39 -04001034 if (config->use_null_client_ca_list) {
1035 SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
1036 }
1037
David Benjamin65ac9972016-09-02 21:35:25 -04001038 if (config->enable_grease) {
1039 SSL_CTX_set_grease_enabled(ssl_ctx.get(), 1);
1040 }
1041
David Benjamin8b176712016-10-27 21:51:24 -04001042 if (!config->expected_server_name.empty()) {
1043 SSL_CTX_set_tlsext_servername_callback(ssl_ctx.get(), ServerNameCallback);
1044 }
1045
David Benjamin4199b0d2016-11-01 13:58:25 -04001046 if (!config->ticket_key.empty() &&
1047 !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), config->ticket_key.data(),
1048 config->ticket_key.size())) {
1049 return nullptr;
1050 }
1051
David Benjamin1d5c83e2014-07-22 19:20:02 -04001052 return ssl_ctx;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001053}
1054
David Benjamin40f101b2015-02-20 11:23:42 -05001055// RetryAsync is called after a failed operation on |ssl| with return code
1056// |ret|. If the operation should be retried, it simulates one asynchronous
David Benjamin6c2563e2015-04-03 03:47:47 -04001057// event and returns true. Otherwise it returns false.
1058static bool RetryAsync(SSL *ssl, int ret) {
David Benjamin43ec06f2014-08-05 02:28:57 -04001059 // No error; don't retry.
1060 if (ret >= 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001061 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001062 }
David Benjamin83f90402015-01-27 01:09:43 -05001063
David Benjamin6c2563e2015-04-03 03:47:47 -04001064 TestState *test_state = GetTestState(ssl);
Matt Braithwaite6278e242016-06-14 08:18:22 -07001065 assert(GetTestConfig(ssl)->async);
David Benjamin83f90402015-01-27 01:09:43 -05001066
David Benjamin585d7a42016-06-02 14:58:00 -04001067 if (test_state->packeted_bio != nullptr &&
1068 PacketedBioAdvanceClock(test_state->packeted_bio)) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001069 // The DTLS retransmit logic silently ignores write failures. So the test
1070 // may progress, allow writes through synchronously.
David Benjamin585d7a42016-06-02 14:58:00 -04001071 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
David Benjamin13e81fc2015-11-02 17:16:13 -05001072 int timeout_ret = DTLSv1_handle_timeout(ssl);
David Benjamin585d7a42016-06-02 14:58:00 -04001073 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
David Benjamin13e81fc2015-11-02 17:16:13 -05001074
1075 if (timeout_ret < 0) {
David Benjaminc565ebb2015-04-03 04:06:36 -04001076 fprintf(stderr, "Error retransmitting.\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001077 return false;
David Benjamin83f90402015-01-27 01:09:43 -05001078 }
David Benjamin40f101b2015-02-20 11:23:42 -05001079 return true;
David Benjamin83f90402015-01-27 01:09:43 -05001080 }
1081
David Benjamin43ec06f2014-08-05 02:28:57 -04001082 // See if we needed to read or write more. If so, allow one byte through on
1083 // the appropriate end to maximally stress the state machine.
David Benjamind9e07012015-02-09 03:04:34 -05001084 switch (SSL_get_error(ssl, ret)) {
1085 case SSL_ERROR_WANT_READ:
David Benjamin6c2563e2015-04-03 03:47:47 -04001086 AsyncBioAllowRead(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -05001087 return true;
David Benjamind9e07012015-02-09 03:04:34 -05001088 case SSL_ERROR_WANT_WRITE:
David Benjamin6c2563e2015-04-03 03:47:47 -04001089 AsyncBioAllowWrite(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -05001090 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -05001091 case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001092 bssl::UniquePtr<EVP_PKEY> pkey =
1093 LoadPrivateKey(GetTestConfig(ssl)->send_channel_id);
David Benjamin9d0847a2015-02-16 03:57:55 -05001094 if (!pkey) {
David Benjamin40f101b2015-02-20 11:23:42 -05001095 return false;
David Benjamin9d0847a2015-02-16 03:57:55 -05001096 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001097 test_state->channel_id = std::move(pkey);
David Benjamin40f101b2015-02-20 11:23:42 -05001098 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -05001099 }
David Benjamin41fdbcd2015-02-09 03:13:35 -05001100 case SSL_ERROR_WANT_X509_LOOKUP:
David Benjamin6c2563e2015-04-03 03:47:47 -04001101 test_state->cert_ready = true;
David Benjamin40f101b2015-02-20 11:23:42 -05001102 return true;
David Benjamin1b8b6912015-02-09 04:28:16 -05001103 case SSL_ERROR_PENDING_SESSION:
David Benjamin6c2563e2015-04-03 03:47:47 -04001104 test_state->session = std::move(test_state->pending_session);
David Benjamin40f101b2015-02-20 11:23:42 -05001105 return true;
David Benjamin6f5c0f42015-02-24 01:23:21 -05001106 case SSL_ERROR_PENDING_CERTIFICATE:
1107 // The handshake will resume without a second call to the early callback.
1108 return InstallCertificate(ssl);
David Benjaminb4d65fd2015-05-29 17:11:21 -04001109 case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
nagendra modadugu3398dbf2015-08-07 14:07:52 -07001110 test_state->private_key_retries++;
David Benjaminb4d65fd2015-05-29 17:11:21 -04001111 return true;
David Benjamind9e07012015-02-09 03:04:34 -05001112 default:
David Benjamin40f101b2015-02-20 11:23:42 -05001113 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001114 }
David Benjamin025b3d32014-07-01 19:53:04 -04001115}
1116
David Benjamin6c2563e2015-04-03 03:47:47 -04001117// DoRead reads from |ssl|, resolving any asynchronous operations. It returns
1118// the result value of the final |SSL_read| call.
1119static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
David Benjamin7e7a82d2016-05-20 20:12:42 -04001120 const TestConfig *config = GetTestConfig(ssl);
David Benjamin13e81fc2015-11-02 17:16:13 -05001121 TestState *test_state = GetTestState(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -04001122 int ret;
1123 do {
David Benjamin13e81fc2015-11-02 17:16:13 -05001124 if (config->async) {
1125 // The DTLS retransmit logic silently ignores write failures. So the test
1126 // may progress, allow writes through synchronously. |SSL_read| may
1127 // trigger a retransmit, so disconnect the write quota.
1128 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
1129 }
David Benjaminf3fbade2016-09-19 13:08:16 -04001130 ret = config->peek_then_read ? SSL_peek(ssl, out, max_out)
1131 : SSL_read(ssl, out, max_out);
David Benjamin13e81fc2015-11-02 17:16:13 -05001132 if (config->async) {
1133 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
1134 }
David Benjamin7bb1d292016-11-01 19:45:06 -04001135
1136 // Run the exporter after each read. This is to test that the exporter fails
1137 // during a renegotiation.
1138 if (config->use_exporter_between_reads) {
1139 uint8_t buf;
1140 if (!SSL_export_keying_material(ssl, &buf, 1, NULL, 0, NULL, 0, 0)) {
1141 fprintf(stderr, "failed to export keying material\n");
1142 return -1;
1143 }
1144 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001145 } while (config->async && RetryAsync(ssl, ret));
David Benjaminf3fbade2016-09-19 13:08:16 -04001146
1147 if (config->peek_then_read && ret > 0) {
1148 std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
1149
1150 // SSL_peek should synchronously return the same data.
1151 int ret2 = SSL_peek(ssl, buf.get(), ret);
1152 if (ret2 != ret ||
1153 memcmp(buf.get(), out, ret) != 0) {
1154 fprintf(stderr, "First and second SSL_peek did not match.\n");
1155 return -1;
1156 }
1157
1158 // SSL_read should synchronously return the same data and consume it.
1159 ret2 = SSL_read(ssl, buf.get(), ret);
1160 if (ret2 != ret ||
1161 memcmp(buf.get(), out, ret) != 0) {
1162 fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
1163 return -1;
1164 }
1165 }
1166
David Benjamin6c2563e2015-04-03 03:47:47 -04001167 return ret;
1168}
1169
1170// WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
1171// operations. It returns the result of the final |SSL_write| call.
1172static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -04001173 const TestConfig *config = GetTestConfig(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -04001174 int ret;
1175 do {
1176 ret = SSL_write(ssl, in, in_len);
1177 if (ret > 0) {
1178 in += ret;
1179 in_len -= ret;
1180 }
1181 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
1182 return ret;
1183}
1184
David Benjamin30789da2015-08-29 22:56:45 -04001185// DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
1186// returns the result of the final |SSL_shutdown| call.
1187static int DoShutdown(SSL *ssl) {
David Benjamin7e7a82d2016-05-20 20:12:42 -04001188 const TestConfig *config = GetTestConfig(ssl);
David Benjamin30789da2015-08-29 22:56:45 -04001189 int ret;
1190 do {
1191 ret = SSL_shutdown(ssl);
1192 } while (config->async && RetryAsync(ssl, ret));
1193 return ret;
1194}
1195
David Benjamin1d4f4c02016-07-26 18:03:08 -04001196// DoSendFatalAlert calls |SSL_send_fatal_alert|, resolving any asynchronous
1197// operations. It returns the result of the final |SSL_send_fatal_alert| call.
1198static int DoSendFatalAlert(SSL *ssl, uint8_t alert) {
1199 const TestConfig *config = GetTestConfig(ssl);
1200 int ret;
1201 do {
1202 ret = SSL_send_fatal_alert(ssl, alert);
1203 } while (config->async && RetryAsync(ssl, ret));
1204 return ret;
1205}
1206
Steven Valdez1e6f11a2016-07-27 11:10:52 -04001207static uint16_t GetProtocolVersion(const SSL *ssl) {
1208 uint16_t version = SSL_version(ssl);
1209 if (!SSL_is_dtls(ssl)) {
1210 return version;
1211 }
1212 return 0x0201 + ~version;
1213}
1214
David Benjamin91eab5c2015-06-18 18:35:46 -04001215// CheckHandshakeProperties checks, immediately after |ssl| completes its
1216// initial handshake (or False Starts), whether all the properties are
1217// consistent with the test configuration and invariants.
1218static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
David Benjamin7e7a82d2016-05-20 20:12:42 -04001219 const TestConfig *config = GetTestConfig(ssl);
David Benjamin91eab5c2015-06-18 18:35:46 -04001220
1221 if (SSL_get_current_cipher(ssl) == nullptr) {
1222 fprintf(stderr, "null cipher after handshake\n");
1223 return false;
1224 }
1225
1226 if (is_resume &&
1227 (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
1228 fprintf(stderr, "session was%s reused\n",
1229 SSL_session_reused(ssl) ? "" : " not");
1230 return false;
1231 }
1232
1233 bool expect_handshake_done = is_resume || !config->false_start;
1234 if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
1235 fprintf(stderr, "handshake was%s completed\n",
1236 GetTestState(ssl)->handshake_done ? "" : " not");
1237 return false;
1238 }
1239
David Benjaminba4594a2015-06-18 18:36:15 -04001240 if (expect_handshake_done && !config->is_server) {
1241 bool expect_new_session =
1242 !config->expect_no_session &&
Steven Valdez143e8b32016-07-11 13:19:03 -04001243 (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
Steven Valdez1e6f11a2016-07-27 11:10:52 -04001244 // Session tickets are sent post-handshake in TLS 1.3.
1245 GetProtocolVersion(ssl) < TLS1_3_VERSION;
David Benjaminba4594a2015-06-18 18:36:15 -04001246 if (expect_new_session != GetTestState(ssl)->got_new_session) {
1247 fprintf(stderr,
David Benjamindd6fed92015-10-23 17:41:12 -04001248 "new session was%s cached, but we expected the opposite\n",
David Benjaminba4594a2015-06-18 18:36:15 -04001249 GetTestState(ssl)->got_new_session ? "" : " not");
1250 return false;
1251 }
1252 }
1253
David Benjamin91eab5c2015-06-18 18:35:46 -04001254 if (config->is_server && !GetTestState(ssl)->early_callback_called) {
1255 fprintf(stderr, "early callback not called\n");
1256 return false;
1257 }
1258
1259 if (!config->expected_server_name.empty()) {
1260 const char *server_name =
1261 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
David Benjamin8b176712016-10-27 21:51:24 -04001262 if (server_name == nullptr ||
1263 server_name != config->expected_server_name) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001264 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
1265 server_name, config->expected_server_name.c_str());
1266 return false;
1267 }
1268 }
1269
David Benjamin91eab5c2015-06-18 18:35:46 -04001270 if (!config->expected_next_proto.empty()) {
1271 const uint8_t *next_proto;
1272 unsigned next_proto_len;
1273 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
1274 if (next_proto_len != config->expected_next_proto.size() ||
1275 memcmp(next_proto, config->expected_next_proto.data(),
1276 next_proto_len) != 0) {
1277 fprintf(stderr, "negotiated next proto mismatch\n");
1278 return false;
1279 }
1280 }
1281
1282 if (!config->expected_alpn.empty()) {
1283 const uint8_t *alpn_proto;
1284 unsigned alpn_proto_len;
1285 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
1286 if (alpn_proto_len != config->expected_alpn.size() ||
1287 memcmp(alpn_proto, config->expected_alpn.data(),
1288 alpn_proto_len) != 0) {
1289 fprintf(stderr, "negotiated alpn proto mismatch\n");
1290 return false;
1291 }
1292 }
1293
1294 if (!config->expected_channel_id.empty()) {
1295 uint8_t channel_id[64];
1296 if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
1297 fprintf(stderr, "no channel id negotiated\n");
1298 return false;
1299 }
1300 if (config->expected_channel_id.size() != 64 ||
1301 memcmp(config->expected_channel_id.data(),
1302 channel_id, 64) != 0) {
1303 fprintf(stderr, "channel id mismatch\n");
1304 return false;
1305 }
1306 }
1307
1308 if (config->expect_extended_master_secret) {
David Benjamin8ac35712016-07-13 21:07:29 -04001309 if (!SSL_get_extms_support(ssl)) {
1310 fprintf(stderr, "No EMS for connection when expected");
David Benjamin91eab5c2015-06-18 18:35:46 -04001311 return false;
1312 }
1313 }
1314
1315 if (!config->expected_ocsp_response.empty()) {
1316 const uint8_t *data;
1317 size_t len;
1318 SSL_get0_ocsp_response(ssl, &data, &len);
1319 if (config->expected_ocsp_response.size() != len ||
1320 memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
1321 fprintf(stderr, "OCSP response mismatch\n");
1322 return false;
1323 }
1324 }
1325
1326 if (!config->expected_signed_cert_timestamps.empty()) {
1327 const uint8_t *data;
1328 size_t len;
1329 SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
1330 if (config->expected_signed_cert_timestamps.size() != len ||
1331 memcmp(config->expected_signed_cert_timestamps.data(),
1332 data, len) != 0) {
1333 fprintf(stderr, "SCT list mismatch\n");
1334 return false;
1335 }
1336 }
1337
Paul Lietar8f1c2682015-08-18 12:21:54 +01001338 if (config->expect_verify_result) {
1339 int expected_verify_result = config->verify_fail ?
1340 X509_V_ERR_APPLICATION_VERIFICATION :
1341 X509_V_OK;
1342
1343 if (SSL_get_verify_result(ssl) != expected_verify_result) {
1344 fprintf(stderr, "Wrong certificate verification result\n");
1345 return false;
1346 }
1347 }
1348
Nick Harper60edffd2016-06-21 15:19:24 -07001349 if (config->expect_peer_signature_algorithm != 0 &&
1350 config->expect_peer_signature_algorithm !=
1351 SSL_get_peer_signature_algorithm(ssl)) {
1352 fprintf(stderr, "Peer signature algorithm was %04x, wanted %04x.\n",
1353 SSL_get_peer_signature_algorithm(ssl),
1354 config->expect_peer_signature_algorithm);
David Benjamin6e807652015-11-02 12:02:20 -05001355 return false;
1356 }
1357
David Benjamin9e68f192016-06-30 14:55:33 -04001358 if (config->expect_curve_id != 0) {
1359 uint16_t curve_id = SSL_get_curve_id(ssl);
1360 if (static_cast<uint16_t>(config->expect_curve_id) != curve_id) {
1361 fprintf(stderr, "curve_id was %04x, wanted %04x\n", curve_id,
1362 static_cast<uint16_t>(config->expect_curve_id));
1363 return false;
1364 }
1365 }
1366
1367 if (config->expect_dhe_group_size != 0) {
1368 unsigned dhe_group_size = SSL_get_dhe_group_size(ssl);
1369 if (static_cast<unsigned>(config->expect_dhe_group_size) !=
1370 dhe_group_size) {
1371 fprintf(stderr, "dhe_group_size was %u, wanted %d\n", dhe_group_size,
1372 config->expect_dhe_group_size);
David Benjamin4cc36ad2015-12-19 14:23:26 -05001373 return false;
1374 }
1375 }
1376
David Benjaminabbbee12016-10-31 19:20:42 -04001377 uint16_t cipher_id =
1378 static_cast<uint16_t>(SSL_CIPHER_get_id(SSL_get_current_cipher(ssl)));
1379 if (config->expect_cipher_aes != 0 &&
1380 EVP_has_aes_hardware() &&
1381 static_cast<uint16_t>(config->expect_cipher_aes) != cipher_id) {
1382 fprintf(stderr, "Cipher ID was %04x, wanted %04x (has AES hardware)\n",
1383 cipher_id, static_cast<uint16_t>(config->expect_cipher_aes));
1384 return false;
1385 }
1386
1387 if (config->expect_cipher_no_aes != 0 &&
1388 !EVP_has_aes_hardware() &&
1389 static_cast<uint16_t>(config->expect_cipher_no_aes) != cipher_id) {
1390 fprintf(stderr, "Cipher ID was %04x, wanted %04x (no AES hardware)\n",
1391 cipher_id, static_cast<uint16_t>(config->expect_cipher_no_aes));
1392 return false;
1393 }
1394
1395
David Benjaminbb9e36e2016-08-03 14:14:47 -04001396 if (!config->psk.empty()) {
1397 if (SSL_get_peer_cert_chain(ssl) != nullptr) {
1398 fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
1399 return false;
1400 }
1401 } else if (!config->is_server || config->require_any_client_certificate) {
1402 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
1403 fprintf(stderr, "Received no peer certificate but expected one.\n");
David Benjamin91eab5c2015-06-18 18:35:46 -04001404 return false;
1405 }
1406 }
David Benjaminbb9e36e2016-08-03 14:14:47 -04001407
David Benjamin2c516452016-11-15 10:16:54 +09001408 if (!config->expect_peer_cert_file.empty()) {
1409 bssl::UniquePtr<X509> expect_leaf;
1410 bssl::UniquePtr<STACK_OF(X509)> expect_chain;
1411 if (!LoadCertificate(&expect_leaf, &expect_chain,
1412 config->expect_peer_cert_file)) {
1413 return false;
1414 }
1415
1416 // For historical reasons, clients report a chain with a leaf and servers
1417 // without.
1418 if (!config->is_server) {
1419 if (!sk_X509_insert(expect_chain.get(), expect_leaf.get(), 0)) {
1420 return false;
1421 }
1422 X509_up_ref(expect_leaf.get()); // sk_X509_push takes ownership.
1423 }
1424
1425 bssl::UniquePtr<X509> leaf(SSL_get_peer_certificate(ssl));
1426 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl);
1427 if (X509_cmp(leaf.get(), expect_leaf.get()) != 0) {
1428 fprintf(stderr, "Received a different leaf certificate than expected.\n");
1429 return false;
1430 }
1431
1432 if (sk_X509_num(chain) != sk_X509_num(expect_chain.get())) {
1433 fprintf(stderr, "Received a chain of length %zu instead of %zu.\n",
1434 sk_X509_num(chain), sk_X509_num(expect_chain.get()));
1435 return false;
1436 }
1437
1438 for (size_t i = 0; i < sk_X509_num(chain); i++) {
1439 if (X509_cmp(sk_X509_value(chain, i),
1440 sk_X509_value(expect_chain.get(), i)) != 0) {
1441 fprintf(stderr, "Chain certificate %zu did not match.\n",
1442 i + 1);
1443 return false;
1444 }
1445 }
1446 }
1447
David Benjaminbbaf3672016-11-17 10:53:09 +09001448 bool expected_sha256_client_cert = config->expect_sha256_client_cert_initial;
1449 if (is_resume) {
1450 expected_sha256_client_cert = config->expect_sha256_client_cert_resume;
1451 }
1452
1453 if (SSL_get_session(ssl)->peer_sha256_valid != expected_sha256_client_cert) {
1454 fprintf(stderr,
1455 "Unexpected SHA-256 client cert state: expected:%d is_resume:%d.\n",
1456 expected_sha256_client_cert, is_resume);
1457 return false;
1458 }
1459
1460 if (expected_sha256_client_cert &&
1461 SSL_get_session(ssl)->x509_peer != nullptr) {
1462 fprintf(stderr, "Have both client cert and SHA-256 hash: is_resume:%d.\n",
1463 is_resume);
1464 return false;
1465 }
1466
David Benjamin91eab5c2015-06-18 18:35:46 -04001467 return true;
1468}
1469
David Benjamin87c8a642015-02-21 01:54:29 -05001470// DoExchange runs a test SSL exchange against the peer. On success, it returns
1471// true and sets |*out_session| to the negotiated SSL session. If the test is a
1472// resumption attempt, |is_resume| is true and |session| is the session from the
1473// previous exchange.
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001474static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
1475 SSL_CTX *ssl_ctx, const TestConfig *config,
1476 bool is_resume, SSL_SESSION *session) {
1477 bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
David Benjamina7f333d2015-02-09 02:37:18 -05001478 if (!ssl) {
David Benjamin40f101b2015-02-20 11:23:42 -05001479 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001480 }
1481
David Benjamin7e7a82d2016-05-20 20:12:42 -04001482 if (!SetTestConfig(ssl.get(), config) ||
David Benjamin2d445c02015-02-09 13:03:50 -05001483 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
David Benjamin40f101b2015-02-20 11:23:42 -05001484 return false;
Adam Langley69a01602014-11-17 17:26:55 -08001485 }
David Benjamin5a593af2014-08-11 19:51:50 -04001486
Adam Langley5f0efe02015-02-20 13:03:16 -08001487 if (config->fallback_scsv &&
1488 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
1489 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001490 }
David Benjamina0486782016-10-06 19:11:32 -04001491 // Install the certificate synchronously if nothing else will handle it.
1492 if (!config->use_early_callback &&
1493 !config->use_old_client_cert_callback &&
1494 !config->async &&
1495 !InstallCertificate(ssl.get())) {
1496 return false;
David Benjamin5a593af2014-08-11 19:51:50 -04001497 }
David Benjamin5edfc8c2016-12-10 15:46:58 -05001498 if (!config->use_old_client_cert_callback) {
1499 SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
1500 }
David Benjamin5a593af2014-08-11 19:51:50 -04001501 if (config->require_any_client_certificate) {
David Benjamina7f333d2015-02-09 02:37:18 -05001502 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
Paul Lietar8f1c2682015-08-18 12:21:54 +01001503 NULL);
1504 }
1505 if (config->verify_peer) {
1506 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
David Benjamin5a593af2014-08-11 19:51:50 -04001507 }
1508 if (config->false_start) {
David Benjamined7c4752015-02-16 19:16:46 -05001509 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
David Benjamin5a593af2014-08-11 19:51:50 -04001510 }
1511 if (config->cbc_record_splitting) {
David Benjamina7f333d2015-02-09 02:37:18 -05001512 SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
David Benjamin5a593af2014-08-11 19:51:50 -04001513 }
1514 if (config->partial_write) {
David Benjamina7f333d2015-02-09 02:37:18 -05001515 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
David Benjamin5a593af2014-08-11 19:51:50 -04001516 }
Steven Valdez4f94b1c2016-05-24 12:31:07 -04001517 if (config->no_tls13) {
1518 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
1519 }
David Benjamin5a593af2014-08-11 19:51:50 -04001520 if (config->no_tls12) {
David Benjamina7f333d2015-02-09 02:37:18 -05001521 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
David Benjamin5a593af2014-08-11 19:51:50 -04001522 }
1523 if (config->no_tls11) {
David Benjamina7f333d2015-02-09 02:37:18 -05001524 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
David Benjamin5a593af2014-08-11 19:51:50 -04001525 }
1526 if (config->no_tls1) {
David Benjamina7f333d2015-02-09 02:37:18 -05001527 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
David Benjamin5a593af2014-08-11 19:51:50 -04001528 }
1529 if (config->no_ssl3) {
David Benjamina7f333d2015-02-09 02:37:18 -05001530 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
David Benjamin5a593af2014-08-11 19:51:50 -04001531 }
Steven Valdez143e8b32016-07-11 13:19:03 -04001532 if (!config->expected_channel_id.empty() ||
1533 config->enable_channel_id) {
David Benjamineebd3c82016-12-06 17:43:58 -05001534 SSL_set_tls_channel_id_enabled(ssl.get(), 1);
David Benjamina08e49d2014-08-24 01:46:07 -04001535 }
1536 if (!config->send_channel_id.empty()) {
David Benjamineebd3c82016-12-06 17:43:58 -05001537 SSL_set_tls_channel_id_enabled(ssl.get(), 1);
David Benjamind9e07012015-02-09 03:04:34 -05001538 if (!config->async) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001539 // The async case will be supplied by |ChannelIdCallback|.
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001540 bssl::UniquePtr<EVP_PKEY> pkey = LoadPrivateKey(config->send_channel_id);
David Benjamind9e07012015-02-09 03:04:34 -05001541 if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001542 return false;
David Benjamind9e07012015-02-09 03:04:34 -05001543 }
David Benjamina08e49d2014-08-24 01:46:07 -04001544 }
David Benjamina08e49d2014-08-24 01:46:07 -04001545 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001546 if (!config->host_name.empty() &&
1547 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001548 return false;
David Benjamine78bfde2014-09-06 12:45:15 -04001549 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001550 if (!config->advertise_alpn.empty() &&
1551 SSL_set_alpn_protos(ssl.get(),
1552 (const uint8_t *)config->advertise_alpn.data(),
1553 config->advertise_alpn.size()) != 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001554 return false;
David Benjaminae2888f2014-09-06 12:58:58 -04001555 }
David Benjamin48cae082014-10-27 01:06:24 -04001556 if (!config->psk.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001557 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
1558 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
David Benjamin48cae082014-10-27 01:06:24 -04001559 }
David Benjamin61f95272014-11-25 01:55:35 -05001560 if (!config->psk_identity.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001561 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001562 return false;
David Benjamin48cae082014-10-27 01:06:24 -04001563 }
David Benjamin61f95272014-11-25 01:55:35 -05001564 if (!config->srtp_profiles.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001565 !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001566 return false;
David Benjamin61f95272014-11-25 01:55:35 -05001567 }
1568 if (config->enable_ocsp_stapling &&
David Benjamina7f333d2015-02-09 02:37:18 -05001569 !SSL_enable_ocsp_stapling(ssl.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001570 return false;
David Benjamin61f95272014-11-25 01:55:35 -05001571 }
1572 if (config->enable_signed_cert_timestamps &&
David Benjamina7f333d2015-02-09 02:37:18 -05001573 !SSL_enable_signed_cert_timestamps(ssl.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001574 return false;
David Benjaminca6c8262014-11-15 19:06:08 -05001575 }
David Benjamin2dc02042016-09-19 19:57:37 -04001576 if (config->min_version != 0 &&
David Benjamine4706902016-09-20 15:12:23 -04001577 !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) {
David Benjamin2dc02042016-09-19 19:57:37 -04001578 return false;
David Benjamin1eb367c2014-12-12 18:17:51 -05001579 }
David Benjamin2dc02042016-09-19 19:57:37 -04001580 if (config->max_version != 0 &&
David Benjamine4706902016-09-20 15:12:23 -04001581 !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) {
David Benjamin2dc02042016-09-19 19:57:37 -04001582 return false;
David Benjamin1eb367c2014-12-12 18:17:51 -05001583 }
David Benjamin13be1de2015-01-11 16:29:36 -05001584 if (config->mtu != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001585 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
1586 SSL_set_mtu(ssl.get(), config->mtu);
David Benjamin13be1de2015-01-11 16:29:36 -05001587 }
Adam Langley524e7172015-02-20 16:04:00 -08001588 if (config->install_ddos_callback) {
1589 SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
1590 }
David Benjamin1d5ef3b2015-10-12 19:54:18 -04001591 if (config->renegotiate_once) {
1592 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_once);
1593 }
1594 if (config->renegotiate_freely) {
1595 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
David Benjaminb16346b2015-04-08 19:16:58 -04001596 }
Adam Langley27a0d082015-11-03 13:34:10 -08001597 if (config->renegotiate_ignore) {
1598 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_ignore);
1599 }
David Benjamin30789da2015-08-29 22:56:45 -04001600 if (!config->check_close_notify) {
1601 SSL_set_quiet_shutdown(ssl.get(), 1);
1602 }
David Benjamin99fdfb92015-11-02 12:11:35 -05001603 if (config->p384_only) {
1604 int nid = NID_secp384r1;
1605 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
1606 return false;
1607 }
1608 }
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001609 if (config->enable_all_curves) {
1610 static const int kAllCurves[] = {
Matt Braithwaite053931e2016-05-25 12:06:05 -07001611 NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_X25519,
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001612 };
1613 if (!SSL_set1_curves(ssl.get(), kAllCurves,
Steven Valdezcb966542016-08-17 16:56:14 -04001614 OPENSSL_ARRAY_SIZE(kAllCurves))) {
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001615 return false;
1616 }
1617 }
Taylor Brandstetter376a0fe2016-05-10 19:30:28 -07001618 if (config->initial_timeout_duration_ms > 0) {
1619 DTLSv1_set_initial_timeout_duration(ssl.get(),
1620 config->initial_timeout_duration_ms);
1621 }
David Benjamina252b342016-09-26 19:57:53 -04001622 if (config->max_cert_list > 0) {
1623 SSL_set_max_cert_list(ssl.get(), config->max_cert_list);
1624 }
David Benjaminbbaf3672016-11-17 10:53:09 +09001625 if (!is_resume && config->retain_only_sha256_client_cert_initial) {
1626 SSL_set_retain_only_sha256_of_client_certs(ssl.get(), 1);
1627 }
1628 if (is_resume && config->retain_only_sha256_client_cert_resume) {
1629 SSL_set_retain_only_sha256_of_client_certs(ssl.get(), 1);
1630 }
David Benjamin025b3d32014-07-01 19:53:04 -04001631
David Benjamin87c8a642015-02-21 01:54:29 -05001632 int sock = Connect(config->port);
1633 if (sock == -1) {
1634 return false;
1635 }
1636 SocketCloser closer(sock);
1637
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001638 bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
David Benjamina7f333d2015-02-09 02:37:18 -05001639 if (!bio) {
David Benjamin40f101b2015-02-20 11:23:42 -05001640 return false;
David Benjamin43ec06f2014-08-05 02:28:57 -04001641 }
David Benjamin6fd297b2014-08-11 18:43:38 -04001642 if (config->is_dtls) {
David Benjamin1b22f852016-10-27 16:36:32 -04001643 bssl::UniquePtr<BIO> packeted = PacketedBioCreate(&g_clock, !config->async);
David Benjaminb7c5e842016-03-28 09:59:10 -04001644 if (!packeted) {
1645 return false;
1646 }
David Benjamin585d7a42016-06-02 14:58:00 -04001647 GetTestState(ssl.get())->packeted_bio = packeted.get();
David Benjamina7f333d2015-02-09 02:37:18 -05001648 BIO_push(packeted.get(), bio.release());
1649 bio = std::move(packeted);
David Benjamin6fd297b2014-08-11 18:43:38 -04001650 }
David Benjamin5a593af2014-08-11 19:51:50 -04001651 if (config->async) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001652 bssl::UniquePtr<BIO> async_scoped =
David Benjaminc273d2c2015-02-09 12:59:46 -05001653 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
David Benjaminb7c5e842016-03-28 09:59:10 -04001654 if (!async_scoped) {
1655 return false;
1656 }
David Benjamina7f333d2015-02-09 02:37:18 -05001657 BIO_push(async_scoped.get(), bio.release());
David Benjamin6c2563e2015-04-03 03:47:47 -04001658 GetTestState(ssl.get())->async_bio = async_scoped.get();
David Benjamina7f333d2015-02-09 02:37:18 -05001659 bio = std::move(async_scoped);
David Benjamin43ec06f2014-08-05 02:28:57 -04001660 }
David Benjamina7f333d2015-02-09 02:37:18 -05001661 SSL_set_bio(ssl.get(), bio.get(), bio.get());
1662 bio.release(); // SSL_set_bio takes ownership.
David Benjamin43ec06f2014-08-05 02:28:57 -04001663
David Benjamin1d5c83e2014-07-22 19:20:02 -04001664 if (session != NULL) {
David Benjamin1b8b6912015-02-09 04:28:16 -05001665 if (!config->is_server) {
1666 if (SSL_set_session(ssl.get(), session) != 1) {
David Benjamin40f101b2015-02-20 11:23:42 -05001667 return false;
David Benjamin1b8b6912015-02-09 04:28:16 -05001668 }
1669 } else if (config->async) {
1670 // The internal session cache is disabled, so install the session
1671 // manually.
David Benjaminb9195402016-08-05 10:51:43 -04001672 SSL_SESSION_up_ref(session);
1673 GetTestState(ssl.get())->pending_session.reset(session);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001674 }
1675 }
1676
David Benjamina07c0fc2015-05-13 13:19:42 -04001677 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1678 fprintf(stderr, "non-null cipher before handshake\n");
1679 return false;
1680 }
1681
David Benjamin1d5c83e2014-07-22 19:20:02 -04001682 int ret;
David Benjamine0e7d0d2015-02-08 19:33:25 -05001683 if (config->implicit_handshake) {
David Benjamin5a593af2014-08-11 19:51:50 -04001684 if (config->is_server) {
David Benjamina7f333d2015-02-09 02:37:18 -05001685 SSL_set_accept_state(ssl.get());
David Benjamin43ec06f2014-08-05 02:28:57 -04001686 } else {
David Benjamina7f333d2015-02-09 02:37:18 -05001687 SSL_set_connect_state(ssl.get());
David Benjamin43ec06f2014-08-05 02:28:57 -04001688 }
David Benjamine0e7d0d2015-02-08 19:33:25 -05001689 } else {
1690 do {
1691 if (config->is_server) {
David Benjamina7f333d2015-02-09 02:37:18 -05001692 ret = SSL_accept(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -05001693 } else {
David Benjamina7f333d2015-02-09 02:37:18 -05001694 ret = SSL_connect(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -05001695 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001696 } while (config->async && RetryAsync(ssl.get(), ret));
David Benjamin91eab5c2015-06-18 18:35:46 -04001697 if (ret != 1 ||
1698 !CheckHandshakeProperties(ssl.get(), is_resume)) {
David Benjamin40f101b2015-02-20 11:23:42 -05001699 return false;
David Benjamine0e7d0d2015-02-08 19:33:25 -05001700 }
David Benjamin025b3d32014-07-01 19:53:04 -04001701
David Benjaminba4594a2015-06-18 18:36:15 -04001702 // Reset the state to assert later that the callback isn't called in
1703 // renegotations.
1704 GetTestState(ssl.get())->got_new_session = false;
David Benjamin61f95272014-11-25 01:55:35 -05001705 }
1706
David Benjaminc565ebb2015-04-03 04:06:36 -04001707 if (config->export_keying_material > 0) {
1708 std::vector<uint8_t> result(
1709 static_cast<size_t>(config->export_keying_material));
1710 if (!SSL_export_keying_material(
1711 ssl.get(), result.data(), result.size(),
1712 config->export_label.data(), config->export_label.size(),
1713 reinterpret_cast<const uint8_t*>(config->export_context.data()),
1714 config->export_context.size(), config->use_export_context)) {
1715 fprintf(stderr, "failed to export keying material\n");
1716 return false;
1717 }
1718 if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1719 return false;
1720 }
1721 }
1722
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001723 if (config->tls_unique) {
1724 uint8_t tls_unique[16];
1725 size_t tls_unique_len;
1726 if (!SSL_get_tls_unique(ssl.get(), tls_unique, &tls_unique_len,
1727 sizeof(tls_unique))) {
1728 fprintf(stderr, "failed to get tls-unique\n");
1729 return false;
1730 }
1731
1732 if (tls_unique_len != 12) {
1733 fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
1734 static_cast<unsigned>(tls_unique_len));
1735 return false;
1736 }
1737
1738 if (WriteAll(ssl.get(), tls_unique, tls_unique_len) < 0) {
1739 return false;
1740 }
1741 }
1742
David Benjamin1d4f4c02016-07-26 18:03:08 -04001743 if (config->send_alert) {
1744 if (DoSendFatalAlert(ssl.get(), SSL_AD_DECOMPRESSION_FAILURE) < 0) {
1745 return false;
1746 }
1747 return true;
1748 }
1749
David Benjamin5a593af2014-08-11 19:51:50 -04001750 if (config->write_different_record_sizes) {
David Benjamin6fd297b2014-08-11 18:43:38 -04001751 if (config->is_dtls) {
1752 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001753 return false;
David Benjamin6fd297b2014-08-11 18:43:38 -04001754 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001755 // This mode writes a number of different record sizes in an attempt to
1756 // trip up the CBC record splitting code.
Adam Langleybc949292015-06-18 21:32:44 -07001757 static const size_t kBufLen = 32769;
1758 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1759 memset(buf.get(), 0x42, kBufLen);
Kenny Root7fdeaf12014-08-05 15:23:37 -07001760 static const size_t kRecordSizes[] = {
1761 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
Steven Valdezcb966542016-08-17 16:56:14 -04001762 for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07001763 const size_t len = kRecordSizes[i];
Adam Langleybc949292015-06-18 21:32:44 -07001764 if (len > kBufLen) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07001765 fprintf(stderr, "Bad kRecordSizes value.\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001766 return false;
Kenny Root7fdeaf12014-08-05 15:23:37 -07001767 }
Adam Langleybc949292015-06-18 21:32:44 -07001768 if (WriteAll(ssl.get(), buf.get(), len) < 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001769 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001770 }
1771 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001772 } else {
David Benjamine58c4f52014-08-24 03:47:07 -04001773 if (config->shim_writes_first) {
David Benjamin6c2563e2015-04-03 03:47:47 -04001774 if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1775 5) < 0) {
1776 return false;
1777 }
David Benjamine58c4f52014-08-24 03:47:07 -04001778 }
David Benjamin30789da2015-08-29 22:56:45 -04001779 if (!config->shim_shuts_down) {
1780 for (;;) {
Adam Langleya0a8dc22015-09-09 10:22:00 -07001781 static const size_t kBufLen = 16384;
1782 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1783
David Benjamin2c99d282015-09-01 10:23:00 -04001784 // Read only 512 bytes at a time in TLS to ensure records may be
1785 // returned in multiple reads.
Adam Langleya0a8dc22015-09-09 10:22:00 -07001786 int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
David Benjamin30789da2015-08-29 22:56:45 -04001787 int err = SSL_get_error(ssl.get(), n);
1788 if (err == SSL_ERROR_ZERO_RETURN ||
1789 (n == 0 && err == SSL_ERROR_SYSCALL)) {
1790 if (n != 0) {
1791 fprintf(stderr, "Invalid SSL_get_error output\n");
1792 return false;
1793 }
1794 // Stop on either clean or unclean shutdown.
1795 break;
1796 } else if (err != SSL_ERROR_NONE) {
1797 if (n > 0) {
1798 fprintf(stderr, "Invalid SSL_get_error output\n");
1799 return false;
1800 }
1801 return false;
1802 }
1803 // Successfully read data.
1804 if (n <= 0) {
David Benjamin9a38e922015-01-22 16:06:11 -05001805 fprintf(stderr, "Invalid SSL_get_error output\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001806 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001807 }
David Benjamin30789da2015-08-29 22:56:45 -04001808
1809 // After a successful read, with or without False Start, the handshake
1810 // must be complete.
1811 if (!GetTestState(ssl.get())->handshake_done) {
1812 fprintf(stderr, "handshake was not completed after SSL_read\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001813 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001814 }
David Benjamin87e4acd2015-04-02 19:57:35 -04001815
David Benjamin30789da2015-08-29 22:56:45 -04001816 for (int i = 0; i < n; i++) {
1817 buf[i] ^= 0xff;
1818 }
Adam Langleya0a8dc22015-09-09 10:22:00 -07001819 if (WriteAll(ssl.get(), buf.get(), n) < 0) {
David Benjamin30789da2015-08-29 22:56:45 -04001820 return false;
1821 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001822 }
1823 }
David Benjamin025b3d32014-07-01 19:53:04 -04001824 }
1825
David Benjaminba4594a2015-06-18 18:36:15 -04001826 if (!config->is_server && !config->false_start &&
1827 !config->implicit_handshake &&
Steven Valdez1e6f11a2016-07-27 11:10:52 -04001828 // Session tickets are sent post-handshake in TLS 1.3.
1829 GetProtocolVersion(ssl.get()) < TLS1_3_VERSION &&
David Benjaminba4594a2015-06-18 18:36:15 -04001830 GetTestState(ssl.get())->got_new_session) {
1831 fprintf(stderr, "new session was established after the handshake\n");
1832 return false;
1833 }
1834
Steven Valdez1e6f11a2016-07-27 11:10:52 -04001835 if (GetProtocolVersion(ssl.get()) >= TLS1_3_VERSION && !config->is_server) {
1836 bool expect_new_session =
1837 !config->expect_no_session && !config->shim_shuts_down;
1838 if (expect_new_session != GetTestState(ssl.get())->got_new_session) {
1839 fprintf(stderr,
1840 "new session was%s cached, but we expected the opposite\n",
1841 GetTestState(ssl.get())->got_new_session ? "" : " not");
1842 return false;
1843 }
1844 }
1845
David Benjamin1d5c83e2014-07-22 19:20:02 -04001846 if (out_session) {
Steven Valdez4aa154e2016-07-29 14:32:55 -04001847 *out_session = std::move(GetTestState(ssl.get())->new_session);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001848 }
1849
David Benjamin30789da2015-08-29 22:56:45 -04001850 ret = DoShutdown(ssl.get());
1851
1852 if (config->shim_shuts_down && config->check_close_notify) {
1853 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1854 // it returns zero when our close_notify is sent, then one when the peer's
1855 // is received.
1856 if (ret != 0) {
1857 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1858 return false;
1859 }
1860 ret = DoShutdown(ssl.get());
1861 }
1862
1863 if (ret != 1) {
1864 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1865 return false;
1866 }
1867
David Benjamin324dce42015-10-12 19:49:00 -04001868 if (SSL_total_renegotiations(ssl.get()) !=
1869 config->expect_total_renegotiations) {
1870 fprintf(stderr, "Expected %d renegotiations, got %d\n",
1871 config->expect_total_renegotiations,
1872 SSL_total_renegotiations(ssl.get()));
1873 return false;
1874 }
1875
David Benjamin40f101b2015-02-20 11:23:42 -05001876 return true;
David Benjamin025b3d32014-07-01 19:53:04 -04001877}
David Benjamin1d5c83e2014-07-22 19:20:02 -04001878
David Benjaminff3a1492016-03-02 10:12:06 -05001879class StderrDelimiter {
1880 public:
1881 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
1882};
1883
David Benjaminaac1e2d2016-12-06 22:35:41 -05001884int main(int argc, char **argv) {
David Benjaminff3a1492016-03-02 10:12:06 -05001885 // To distinguish ASan's output from ours, add a trailing message to stderr.
1886 // Anything following this line will be considered an error.
1887 StderrDelimiter delimiter;
1888
David Benjamin87c8a642015-02-21 01:54:29 -05001889#if defined(OPENSSL_WINDOWS)
1890 /* Initialize Winsock. */
1891 WORD wsa_version = MAKEWORD(2, 2);
1892 WSADATA wsa_data;
1893 int wsa_err = WSAStartup(wsa_version, &wsa_data);
1894 if (wsa_err != 0) {
1895 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1896 return 1;
1897 }
1898 if (wsa_data.wVersion != wsa_version) {
1899 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1900 return 1;
1901 }
1902#else
David Benjamin1d5c83e2014-07-22 19:20:02 -04001903 signal(SIGPIPE, SIG_IGN);
Adam Langleyded93582014-07-31 15:23:51 -07001904#endif
David Benjamin1d5c83e2014-07-22 19:20:02 -04001905
David Benjamin7a1eefd2015-10-17 23:39:22 -04001906 CRYPTO_library_init();
David Benjamind9e07012015-02-09 03:04:34 -05001907 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
David Benjamin2d445c02015-02-09 13:03:50 -05001908 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
David Benjamin6c2563e2015-04-03 03:47:47 -04001909 if (g_config_index < 0 || g_state_index < 0) {
David Benjaminae3e4872014-11-18 21:52:26 -05001910 return 1;
1911 }
David Benjamin5a593af2014-08-11 19:51:50 -04001912
1913 TestConfig config;
1914 if (!ParseConfig(argc - 1, argv + 1, &config)) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001915 return Usage(argv[0]);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001916 }
1917
David Benjamin1b22f852016-10-27 16:36:32 -04001918 // Some code treats the zero time special, so initialize the clock to a
1919 // non-zero time.
1920 g_clock.tv_sec = 1234;
1921 g_clock.tv_usec = 1234;
1922
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001923 bssl::UniquePtr<SSL_CTX> ssl_ctx = SetupCtx(&config);
David Benjamina7f333d2015-02-09 02:37:18 -05001924 if (!ssl_ctx) {
Brian Smith83a82982015-04-09 16:21:10 -10001925 ERR_print_errors_fp(stderr);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001926 return 1;
1927 }
1928
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001929 bssl::UniquePtr<SSL_SESSION> session;
David Benjamin46662482016-08-17 00:51:00 -04001930 for (int i = 0; i < config.resume_count + 1; i++) {
1931 bool is_resume = i > 0;
1932 if (is_resume && !config.is_server && !session) {
1933 fprintf(stderr, "No session to offer.\n");
1934 return 1;
1935 }
David Benjamin1d5c83e2014-07-22 19:20:02 -04001936
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001937 bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
David Benjamin46662482016-08-17 00:51:00 -04001938 if (!DoExchange(&session, ssl_ctx.get(), &config, is_resume,
1939 offer_session.get())) {
1940 fprintf(stderr, "Connection %d failed.\n", i + 1);
1941 ERR_print_errors_fp(stderr);
1942 return 1;
1943 }
Steven Valdeza833c352016-11-01 13:39:36 -04001944
1945 if (config.resumption_delay != 0) {
1946 g_clock.tv_sec += config.resumption_delay;
1947 }
David Benjamin1d5c83e2014-07-22 19:20:02 -04001948 }
1949
David Benjamina7f333d2015-02-09 02:37:18 -05001950 return 0;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001951}