blob: 27405d525d5c3cfa52b132049d5e93740d372a20 [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() &&
David Benjamin9ec37982016-11-02 17:18:13 -0400401 !SSL_CTX_set_ocsp_response(SSL_get_SSL_CTX(ssl),
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100402 (const uint8_t *)config->ocsp_response.data(),
403 config->ocsp_response.size())) {
404 return false;
405 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500406 return true;
407}
408
David Benjaminacb6dcc2016-03-10 09:15:01 -0500409static bool InstallCertificate(SSL *ssl) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700410 bssl::UniquePtr<X509> x509;
David Benjamin2c516452016-11-15 10:16:54 +0900411 bssl::UniquePtr<STACK_OF(X509)> chain;
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700412 bssl::UniquePtr<EVP_PKEY> pkey;
David Benjamin2c516452016-11-15 10:16:54 +0900413 if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500414 return false;
415 }
416
417 if (pkey) {
418 TestState *test_state = GetTestState(ssl);
David Benjamin7e7a82d2016-05-20 20:12:42 -0400419 const TestConfig *config = GetTestConfig(ssl);
David Benjaminacb6dcc2016-03-10 09:15:01 -0500420 if (config->async) {
421 test_state->private_key = std::move(pkey);
422 SSL_set_private_key_method(ssl, &g_async_private_key_method);
423 } else if (!SSL_use_PrivateKey(ssl, pkey.get())) {
424 return false;
425 }
426 }
427
428 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
429 return false;
430 }
431
David Benjamin2c516452016-11-15 10:16:54 +0900432 if (sk_X509_num(chain.get()) > 0 &&
433 !SSL_set1_chain(ssl, chain.get())) {
434 return false;
435 }
436
David Benjaminacb6dcc2016-03-10 09:15:01 -0500437 return true;
438}
439
David Benjamin731058e2016-12-03 23:15:13 -0500440static int SelectCertificateCallback(const SSL_CLIENT_HELLO *client_hello) {
441 const TestConfig *config = GetTestConfig(client_hello->ssl);
442 GetTestState(client_hello->ssl)->early_callback_called = true;
David Benjamin5a593af2014-08-11 19:51:50 -0400443
David Benjamin6f5c0f42015-02-24 01:23:21 -0500444 if (!config->expected_server_name.empty()) {
445 const uint8_t *extension_data;
446 size_t extension_len;
447 CBS extension, server_name_list, host_name;
448 uint8_t name_type;
449
David Benjamin731058e2016-12-03 23:15:13 -0500450 if (!SSL_early_callback_ctx_extension_get(
451 client_hello, TLSEXT_TYPE_server_name, &extension_data,
452 &extension_len)) {
David Benjamin6f5c0f42015-02-24 01:23:21 -0500453 fprintf(stderr, "Could not find server_name extension.\n");
454 return -1;
455 }
456
457 CBS_init(&extension, extension_data, extension_len);
458 if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
459 CBS_len(&extension) != 0 ||
460 !CBS_get_u8(&server_name_list, &name_type) ||
461 name_type != TLSEXT_NAMETYPE_host_name ||
462 !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
463 CBS_len(&server_name_list) != 0) {
464 fprintf(stderr, "Could not decode server_name extension.\n");
465 return -1;
466 }
467
468 if (!CBS_mem_equal(&host_name,
469 (const uint8_t*)config->expected_server_name.data(),
470 config->expected_server_name.size())) {
471 fprintf(stderr, "Server name mismatch.\n");
472 }
David Benjamin7b030512014-07-08 17:30:11 -0400473 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400474
David Benjamin6f5c0f42015-02-24 01:23:21 -0500475 if (config->fail_early_callback) {
David Benjamin7b030512014-07-08 17:30:11 -0400476 return -1;
477 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400478
David Benjamin6f5c0f42015-02-24 01:23:21 -0500479 // Install the certificate in the early callback.
480 if (config->use_early_callback) {
481 if (config->async) {
482 // Install the certificate asynchronously.
483 return 0;
484 }
David Benjamin731058e2016-12-03 23:15:13 -0500485 if (!InstallCertificate(client_hello->ssl)) {
David Benjamin6f5c0f42015-02-24 01:23:21 -0500486 return -1;
487 }
David Benjamin7b030512014-07-08 17:30:11 -0400488 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400489 return 1;
490}
David Benjamin025b3d32014-07-01 19:53:04 -0400491
David Benjaminacb6dcc2016-03-10 09:15:01 -0500492static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400493 if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500494 return -1;
495 }
496
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700497 bssl::UniquePtr<X509> x509;
David Benjamin2c516452016-11-15 10:16:54 +0900498 bssl::UniquePtr<STACK_OF(X509)> chain;
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700499 bssl::UniquePtr<EVP_PKEY> pkey;
David Benjamin2c516452016-11-15 10:16:54 +0900500 if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500501 return -1;
502 }
503
504 // Return zero for no certificate.
505 if (!x509) {
506 return 0;
507 }
508
David Benjamin2c516452016-11-15 10:16:54 +0900509 // Chains and asynchronous private keys are not supported with client_cert_cb.
David Benjaminacb6dcc2016-03-10 09:15:01 -0500510 *out_x509 = x509.release();
511 *out_pkey = pkey.release();
512 return 1;
513}
514
Paul Lietar8f1c2682015-08-18 12:21:54 +0100515static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
516 SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data(store_ctx,
517 SSL_get_ex_data_X509_STORE_CTX_idx());
David Benjamin7e7a82d2016-05-20 20:12:42 -0400518 const TestConfig *config = GetTestConfig(ssl);
Paul Lietar8f1c2682015-08-18 12:21:54 +0100519
520 if (!config->expected_ocsp_response.empty()) {
521 const uint8_t *data;
522 size_t len;
523 SSL_get0_ocsp_response(ssl, &data, &len);
524 if (len == 0) {
525 fprintf(stderr, "OCSP response not available in verify callback\n");
526 return 0;
527 }
528 }
529
David Benjamin67666e72014-07-12 15:47:52 -0400530 return 1;
531}
532
Paul Lietar8f1c2682015-08-18 12:21:54 +0100533static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
534 store_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION;
535 return 0;
536}
537
David Benjaminc273d2c2015-02-09 12:59:46 -0500538static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
539 unsigned int *out_len, void *arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400540 const TestConfig *config = GetTestConfig(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500541 if (config->advertise_npn.empty()) {
David Benjamin1f5f62b2014-07-12 16:18:02 -0400542 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500543 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400544
David Benjamin5a593af2014-08-11 19:51:50 -0400545 *out = (const uint8_t*)config->advertise_npn.data();
546 *out_len = config->advertise_npn.size();
David Benjamin1f5f62b2014-07-12 16:18:02 -0400547 return SSL_TLSEXT_ERR_OK;
548}
549
David Benjaminc273d2c2015-02-09 12:59:46 -0500550static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
David Benjamin8b368412015-03-14 01:54:17 -0400551 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400552 const TestConfig *config = GetTestConfig(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500553 if (config->select_next_proto.empty()) {
David Benjamin7e3305e2014-07-28 14:52:32 -0400554 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500555 }
David Benjamin7e3305e2014-07-28 14:52:32 -0400556
David Benjamin5a593af2014-08-11 19:51:50 -0400557 *out = (uint8_t*)config->select_next_proto.data();
558 *outlen = config->select_next_proto.size();
David Benjamin7e3305e2014-07-28 14:52:32 -0400559 return SSL_TLSEXT_ERR_OK;
560}
561
David Benjaminc273d2c2015-02-09 12:59:46 -0500562static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
563 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin25fe85b2016-08-09 20:00:32 -0400564 if (GetTestState(ssl)->alpn_select_done) {
565 fprintf(stderr, "AlpnSelectCallback called after completion.\n");
566 exit(1);
567 }
568
569 GetTestState(ssl)->alpn_select_done = true;
570
David Benjamin7e7a82d2016-05-20 20:12:42 -0400571 const TestConfig *config = GetTestConfig(ssl);
David Benjamin594e7d22016-03-17 17:49:56 -0400572 if (config->decline_alpn) {
David Benjaminae2888f2014-09-06 12:58:58 -0400573 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500574 }
David Benjaminae2888f2014-09-06 12:58:58 -0400575
576 if (!config->expected_advertised_alpn.empty() &&
577 (config->expected_advertised_alpn.size() != inlen ||
578 memcmp(config->expected_advertised_alpn.data(),
579 in, inlen) != 0)) {
580 fprintf(stderr, "bad ALPN select callback inputs\n");
581 exit(1);
582 }
583
584 *out = (const uint8_t*)config->select_alpn.data();
585 *outlen = config->select_alpn.size();
586 return SSL_TLSEXT_ERR_OK;
587}
588
David Benjaminc273d2c2015-02-09 12:59:46 -0500589static unsigned PskClientCallback(SSL *ssl, const char *hint,
590 char *out_identity,
591 unsigned max_identity_len,
592 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400593 const TestConfig *config = GetTestConfig(ssl);
David Benjamin48cae082014-10-27 01:06:24 -0400594
David Benjamin78679342016-09-16 19:42:05 -0400595 if (config->psk_identity.empty()) {
596 if (hint != nullptr) {
597 fprintf(stderr, "Server PSK hint was non-null.\n");
598 return 0;
599 }
600 } else if (hint == nullptr ||
601 strcmp(hint, config->psk_identity.c_str()) != 0) {
David Benjamin48cae082014-10-27 01:06:24 -0400602 fprintf(stderr, "Server PSK hint did not match.\n");
603 return 0;
604 }
605
606 // Account for the trailing '\0' for the identity.
607 if (config->psk_identity.size() >= max_identity_len ||
608 config->psk.size() > max_psk_len) {
609 fprintf(stderr, "PSK buffers too small\n");
610 return 0;
611 }
612
613 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
614 max_identity_len);
615 memcpy(out_psk, config->psk.data(), config->psk.size());
616 return config->psk.size();
617}
618
David Benjaminc273d2c2015-02-09 12:59:46 -0500619static unsigned PskServerCallback(SSL *ssl, const char *identity,
620 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400621 const TestConfig *config = GetTestConfig(ssl);
David Benjamin48cae082014-10-27 01:06:24 -0400622
623 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
624 fprintf(stderr, "Client PSK identity did not match.\n");
625 return 0;
626 }
627
628 if (config->psk.size() > max_psk_len) {
629 fprintf(stderr, "PSK buffers too small\n");
630 return 0;
631 }
632
633 memcpy(out_psk, config->psk.data(), config->psk.size());
634 return config->psk.size();
635}
636
David Benjamin1b22f852016-10-27 16:36:32 -0400637static timeval g_clock;
638
David Benjamin4d2e7ce2015-05-08 13:29:45 -0400639static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
David Benjamin1b22f852016-10-27 16:36:32 -0400640 *out_clock = g_clock;
David Benjamin377fc312015-01-26 00:22:12 -0500641}
642
David Benjaminc273d2c2015-02-09 12:59:46 -0500643static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
David Benjamin2d445c02015-02-09 13:03:50 -0500644 *out_pkey = GetTestState(ssl)->channel_id.release();
David Benjamind9e07012015-02-09 03:04:34 -0500645}
646
David Benjaminc273d2c2015-02-09 12:59:46 -0500647static int CertCallback(SSL *ssl, void *arg) {
David Benjamina0486782016-10-06 19:11:32 -0400648 const TestConfig *config = GetTestConfig(ssl);
649
650 // Check the CertificateRequest metadata is as expected.
651 //
652 // TODO(davidben): Test |SSL_get_client_CA_list|.
653 if (!SSL_is_server(ssl) &&
654 !config->expected_certificate_types.empty()) {
655 const uint8_t *certificate_types;
656 size_t certificate_types_len =
657 SSL_get0_certificate_types(ssl, &certificate_types);
658 if (certificate_types_len != config->expected_certificate_types.size() ||
659 memcmp(certificate_types,
660 config->expected_certificate_types.data(),
661 certificate_types_len) != 0) {
662 fprintf(stderr, "certificate types mismatch\n");
663 return 0;
664 }
665 }
666
David Benjaminb8d74f52016-11-14 22:02:50 +0900667 if (config->fail_cert_callback) {
668 return 0;
669 }
670
David Benjamina0486782016-10-06 19:11:32 -0400671 // The certificate will be installed via other means.
672 if (!config->async || config->use_early_callback ||
673 config->use_old_client_cert_callback) {
674 return 1;
675 }
676
David Benjamin2d445c02015-02-09 13:03:50 -0500677 if (!GetTestState(ssl)->cert_ready) {
David Benjamin41fdbcd2015-02-09 03:13:35 -0500678 return -1;
679 }
680 if (!InstallCertificate(ssl)) {
681 return 0;
682 }
683 return 1;
684}
685
David Benjaminc273d2c2015-02-09 12:59:46 -0500686static SSL_SESSION *GetSessionCallback(SSL *ssl, uint8_t *data, int len,
687 int *copy) {
David Benjamin2d445c02015-02-09 13:03:50 -0500688 TestState *async_state = GetTestState(ssl);
David Benjamin1b8b6912015-02-09 04:28:16 -0500689 if (async_state->session) {
690 *copy = 0;
691 return async_state->session.release();
692 } else if (async_state->pending_session) {
693 return SSL_magic_pending_session_ptr();
694 } else {
695 return NULL;
696 }
697}
698
David Benjamin731058e2016-12-03 23:15:13 -0500699static int DDoSCallback(const SSL_CLIENT_HELLO *client_hello) {
700 const TestConfig *config = GetTestConfig(client_hello->ssl);
Adam Langley524e7172015-02-20 16:04:00 -0800701 static int callback_num = 0;
702
703 callback_num++;
704 if (config->fail_ddos_callback ||
705 (config->fail_second_ddos_callback && callback_num == 2)) {
706 return 0;
707 }
708 return 1;
709}
710
David Benjamin87e4acd2015-04-02 19:57:35 -0400711static void InfoCallback(const SSL *ssl, int type, int val) {
712 if (type == SSL_CB_HANDSHAKE_DONE) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400713 if (GetTestConfig(ssl)->handshake_never_done) {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400714 fprintf(stderr, "Handshake unexpectedly completed.\n");
David Benjamin87e4acd2015-04-02 19:57:35 -0400715 // Abort before any expected error code is printed, to ensure the overall
716 // test fails.
717 abort();
718 }
719 GetTestState(ssl)->handshake_done = true;
David Benjamin25fe85b2016-08-09 20:00:32 -0400720
721 // Callbacks may be called again on a new handshake.
722 GetTestState(ssl)->ticket_decrypt_done = false;
723 GetTestState(ssl)->alpn_select_done = false;
David Benjamin87e4acd2015-04-02 19:57:35 -0400724 }
725}
726
David Benjaminba4594a2015-06-18 18:36:15 -0400727static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
728 GetTestState(ssl)->got_new_session = true;
Steven Valdez4aa154e2016-07-29 14:32:55 -0400729 GetTestState(ssl)->new_session.reset(session);
David Benjaminba4594a2015-06-18 18:36:15 -0400730 return 1;
731}
732
David Benjamind98452d2015-06-16 14:16:23 -0400733static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
734 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
735 int encrypt) {
David Benjamin25fe85b2016-08-09 20:00:32 -0400736 if (!encrypt) {
737 if (GetTestState(ssl)->ticket_decrypt_done) {
738 fprintf(stderr, "TicketKeyCallback called after completion.\n");
739 return -1;
740 }
741
742 GetTestState(ssl)->ticket_decrypt_done = true;
743 }
744
David Benjamind98452d2015-06-16 14:16:23 -0400745 // This is just test code, so use the all-zeros key.
746 static const uint8_t kZeros[16] = {0};
747
748 if (encrypt) {
749 memcpy(key_name, kZeros, sizeof(kZeros));
750 RAND_bytes(iv, 16);
751 } else if (memcmp(key_name, kZeros, 16) != 0) {
752 return 0;
753 }
754
755 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
756 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
757 return -1;
758 }
759
760 if (!encrypt) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400761 return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
David Benjamind98452d2015-06-16 14:16:23 -0400762 }
763 return 1;
764}
765
Adam Langley09505632015-07-30 18:10:13 -0700766// kCustomExtensionValue is the extension value that the custom extension
767// callbacks will add.
Adam Langleyc5b23a12015-07-30 18:19:26 -0700768static const uint16_t kCustomExtensionValue = 1234;
Adam Langley09505632015-07-30 18:10:13 -0700769static void *const kCustomExtensionAddArg =
770 reinterpret_cast<void *>(kCustomExtensionValue);
771static void *const kCustomExtensionParseArg =
772 reinterpret_cast<void *>(kCustomExtensionValue + 1);
773static const char kCustomExtensionContents[] = "custom extension";
774
775static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
776 const uint8_t **out, size_t *out_len,
777 int *out_alert_value, void *add_arg) {
778 if (extension_value != kCustomExtensionValue ||
779 add_arg != kCustomExtensionAddArg) {
780 abort();
781 }
782
David Benjamin7e7a82d2016-05-20 20:12:42 -0400783 if (GetTestConfig(ssl)->custom_extension_skip) {
Adam Langley09505632015-07-30 18:10:13 -0700784 return 0;
785 }
David Benjamin7e7a82d2016-05-20 20:12:42 -0400786 if (GetTestConfig(ssl)->custom_extension_fail_add) {
Adam Langley09505632015-07-30 18:10:13 -0700787 return -1;
788 }
789
790 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
791 *out_len = sizeof(kCustomExtensionContents) - 1;
792
793 return 1;
794}
795
796static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
797 const uint8_t *out, void *add_arg) {
798 if (extension_value != kCustomExtensionValue ||
799 add_arg != kCustomExtensionAddArg ||
800 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
801 abort();
802 }
803}
804
805static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
806 const uint8_t *contents,
807 size_t contents_len,
808 int *out_alert_value, void *parse_arg) {
809 if (extension_value != kCustomExtensionValue ||
810 parse_arg != kCustomExtensionParseArg) {
811 abort();
812 }
813
814 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
815 memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
816 *out_alert_value = SSL_AD_DECODE_ERROR;
817 return 0;
818 }
819
820 return 1;
821}
822
David Benjamin8b176712016-10-27 21:51:24 -0400823static int ServerNameCallback(SSL *ssl, int *out_alert, void *arg) {
824 // SNI must be accessible from the SNI callback.
825 const TestConfig *config = GetTestConfig(ssl);
826 const char *server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
827 if (server_name == nullptr ||
828 std::string(server_name) != config->expected_server_name) {
829 fprintf(stderr, "servername mismatch (got %s; want %s)\n", server_name,
830 config->expected_server_name.c_str());
831 return SSL_TLSEXT_ERR_ALERT_FATAL;
832 }
833
834 return SSL_TLSEXT_ERR_OK;
835}
836
David Benjamin87c8a642015-02-21 01:54:29 -0500837// Connect returns a new socket connected to localhost on |port| or -1 on
838// error.
839static int Connect(uint16_t port) {
840 int sock = socket(AF_INET, SOCK_STREAM, 0);
841 if (sock == -1) {
842 PrintSocketError("socket");
843 return -1;
844 }
845 int nodelay = 1;
846 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
847 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
848 PrintSocketError("setsockopt");
849 closesocket(sock);
850 return -1;
851 }
852 sockaddr_in sin;
853 memset(&sin, 0, sizeof(sin));
854 sin.sin_family = AF_INET;
855 sin.sin_port = htons(port);
856 if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
857 PrintSocketError("inet_pton");
858 closesocket(sock);
859 return -1;
860 }
861 if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
862 sizeof(sin)) != 0) {
863 PrintSocketError("connect");
864 closesocket(sock);
865 return -1;
866 }
867 return sock;
868}
869
870class SocketCloser {
871 public:
872 explicit SocketCloser(int sock) : sock_(sock) {}
873 ~SocketCloser() {
874 // Half-close and drain the socket before releasing it. This seems to be
875 // necessary for graceful shutdown on Windows. It will also avoid write
876 // failures in the test runner.
877#if defined(OPENSSL_WINDOWS)
878 shutdown(sock_, SD_SEND);
879#else
880 shutdown(sock_, SHUT_WR);
881#endif
882 while (true) {
883 char buf[1024];
884 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
885 break;
886 }
887 }
888 closesocket(sock_);
889 }
890
891 private:
892 const int sock_;
893};
894
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700895static bssl::UniquePtr<SSL_CTX> SetupCtx(const TestConfig *config) {
896 bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(
David Benjamina7f333d2015-02-09 02:37:18 -0500897 config->is_dtls ? DTLS_method() : TLS_method()));
898 if (!ssl_ctx) {
899 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -0400900 }
901
David Benjamin2dc02042016-09-19 19:57:37 -0400902 // Enable TLS 1.3 for tests.
903 if (!config->is_dtls &&
David Benjamine4706902016-09-20 15:12:23 -0400904 !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION)) {
David Benjamin2dc02042016-09-19 19:57:37 -0400905 return nullptr;
Nick Harper1fd39d82016-06-14 18:14:35 -0700906 }
907
Adam Langleycef75832015-09-03 14:51:12 -0700908 std::string cipher_list = "ALL";
909 if (!config->cipher.empty()) {
910 cipher_list = config->cipher;
911 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
912 }
913 if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
914 return nullptr;
915 }
916
917 if (!config->cipher_tls10.empty() &&
918 !SSL_CTX_set_cipher_list_tls10(ssl_ctx.get(),
919 config->cipher_tls10.c_str())) {
920 return nullptr;
921 }
922 if (!config->cipher_tls11.empty() &&
923 !SSL_CTX_set_cipher_list_tls11(ssl_ctx.get(),
924 config->cipher_tls11.c_str())) {
David Benjamina7f333d2015-02-09 02:37:18 -0500925 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -0400926 }
927
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700928 bssl::UniquePtr<DH> dh(DH_get_2048_256(NULL));
David Benjaminb7c5e842016-03-28 09:59:10 -0400929 if (!dh) {
930 return nullptr;
931 }
Adam Langleyc4f25ce2015-11-26 16:39:08 -0800932
933 if (config->use_sparse_dh_prime) {
934 // This prime number is 2^1024 + 643 – a value just above a power of two.
935 // Because of its form, values modulo it are essentially certain to be one
936 // byte shorter. This is used to test padding of these values.
937 if (BN_hex2bn(
938 &dh->p,
939 "1000000000000000000000000000000000000000000000000000000000000000"
940 "0000000000000000000000000000000000000000000000000000000000000000"
941 "0000000000000000000000000000000000000000000000000000000000000000"
942 "0000000000000000000000000000000000000000000000000000000000000028"
943 "3") == 0 ||
944 !BN_set_word(dh->g, 2)) {
945 return nullptr;
946 }
David Benjamine66148a2016-02-02 14:14:36 -0500947 BN_free(dh->q);
948 dh->q = NULL;
Adam Langleyc4f25ce2015-11-26 16:39:08 -0800949 dh->priv_length = 0;
950 }
951
David Benjaminb7c5e842016-03-28 09:59:10 -0400952 if (!SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
David Benjamina7f333d2015-02-09 02:37:18 -0500953 return nullptr;
David Benjaminf4e5c4e2014-08-02 17:35:45 -0400954 }
955
David Benjamin1b8b6912015-02-09 04:28:16 -0500956 if (config->async && config->is_server) {
957 // Disable the internal session cache. To test asynchronous session lookup,
958 // we use an external session cache.
959 SSL_CTX_set_session_cache_mode(
960 ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
David Benjaminc273d2c2015-02-09 12:59:46 -0500961 SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
David Benjamin1b8b6912015-02-09 04:28:16 -0500962 } else {
963 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
964 }
David Benjamin1d5c83e2014-07-22 19:20:02 -0400965
David Benjamind4c2bce2015-10-17 12:28:18 -0400966 SSL_CTX_set_select_certificate_cb(ssl_ctx.get(), SelectCertificateCallback);
David Benjamin8f2c20e2014-07-09 09:30:38 -0400967
David Benjaminacb6dcc2016-03-10 09:15:01 -0500968 if (config->use_old_client_cert_callback) {
969 SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
970 }
971
David Benjamin1f5f62b2014-07-12 16:18:02 -0400972 SSL_CTX_set_next_protos_advertised_cb(
David Benjaminc273d2c2015-02-09 12:59:46 -0500973 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400974 if (!config->select_next_proto.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500975 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
David Benjamina7f333d2015-02-09 02:37:18 -0500976 NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400977 }
978
David Benjamin594e7d22016-03-17 17:49:56 -0400979 if (!config->select_alpn.empty() || config->decline_alpn) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500980 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400981 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400982
David Benjamineebd3c82016-12-06 17:43:58 -0500983 SSL_CTX_set_tls_channel_id_enabled(ssl_ctx.get(), 1);
David Benjaminc273d2c2015-02-09 12:59:46 -0500984 SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
David Benjamina08e49d2014-08-24 01:46:07 -0400985
David Benjamin1b22f852016-10-27 16:36:32 -0400986 SSL_CTX_set_current_time_cb(ssl_ctx.get(), CurrentTimeCallback);
David Benjamin377fc312015-01-26 00:22:12 -0500987
David Benjamin87e4acd2015-04-02 19:57:35 -0400988 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
David Benjaminba4594a2015-06-18 18:36:15 -0400989 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
David Benjamin87e4acd2015-04-02 19:57:35 -0400990
David Benjamind98452d2015-06-16 14:16:23 -0400991 if (config->use_ticket_callback) {
992 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
993 }
994
Adam Langley09505632015-07-30 18:10:13 -0700995 if (config->enable_client_custom_extension &&
996 !SSL_CTX_add_client_custom_ext(
997 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
998 CustomExtensionFreeCallback, kCustomExtensionAddArg,
999 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1000 return nullptr;
1001 }
1002
1003 if (config->enable_server_custom_extension &&
1004 !SSL_CTX_add_server_custom_ext(
1005 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
1006 CustomExtensionFreeCallback, kCustomExtensionAddArg,
1007 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1008 return nullptr;
1009 }
1010
Paul Lietar8f1c2682015-08-18 12:21:54 +01001011 if (config->verify_fail) {
1012 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
1013 } else {
1014 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
1015 }
1016
Paul Lietar4fac72e2015-09-09 13:44:55 +01001017 if (!config->signed_cert_timestamps.empty() &&
1018 !SSL_CTX_set_signed_cert_timestamp_list(
1019 ssl_ctx.get(), (const uint8_t *)config->signed_cert_timestamps.data(),
1020 config->signed_cert_timestamps.size())) {
1021 return nullptr;
1022 }
1023
David Benjamin2f8935d2016-07-13 19:47:39 -04001024 if (config->use_null_client_ca_list) {
1025 SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
1026 }
1027
David Benjamin65ac9972016-09-02 21:35:25 -04001028 if (config->enable_grease) {
1029 SSL_CTX_set_grease_enabled(ssl_ctx.get(), 1);
1030 }
1031
David Benjamin8b176712016-10-27 21:51:24 -04001032 if (!config->expected_server_name.empty()) {
1033 SSL_CTX_set_tlsext_servername_callback(ssl_ctx.get(), ServerNameCallback);
1034 }
1035
David Benjamin4199b0d2016-11-01 13:58:25 -04001036 if (!config->ticket_key.empty() &&
1037 !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), config->ticket_key.data(),
1038 config->ticket_key.size())) {
1039 return nullptr;
1040 }
1041
David Benjamin1d5c83e2014-07-22 19:20:02 -04001042 return ssl_ctx;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001043}
1044
David Benjamin40f101b2015-02-20 11:23:42 -05001045// RetryAsync is called after a failed operation on |ssl| with return code
1046// |ret|. If the operation should be retried, it simulates one asynchronous
David Benjamin6c2563e2015-04-03 03:47:47 -04001047// event and returns true. Otherwise it returns false.
1048static bool RetryAsync(SSL *ssl, int ret) {
David Benjamin43ec06f2014-08-05 02:28:57 -04001049 // No error; don't retry.
1050 if (ret >= 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001051 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001052 }
David Benjamin83f90402015-01-27 01:09:43 -05001053
David Benjamin6c2563e2015-04-03 03:47:47 -04001054 TestState *test_state = GetTestState(ssl);
Matt Braithwaite6278e242016-06-14 08:18:22 -07001055 assert(GetTestConfig(ssl)->async);
David Benjamin83f90402015-01-27 01:09:43 -05001056
David Benjamin585d7a42016-06-02 14:58:00 -04001057 if (test_state->packeted_bio != nullptr &&
1058 PacketedBioAdvanceClock(test_state->packeted_bio)) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001059 // The DTLS retransmit logic silently ignores write failures. So the test
1060 // may progress, allow writes through synchronously.
David Benjamin585d7a42016-06-02 14:58:00 -04001061 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
David Benjamin13e81fc2015-11-02 17:16:13 -05001062 int timeout_ret = DTLSv1_handle_timeout(ssl);
David Benjamin585d7a42016-06-02 14:58:00 -04001063 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
David Benjamin13e81fc2015-11-02 17:16:13 -05001064
1065 if (timeout_ret < 0) {
David Benjaminc565ebb2015-04-03 04:06:36 -04001066 fprintf(stderr, "Error retransmitting.\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001067 return false;
David Benjamin83f90402015-01-27 01:09:43 -05001068 }
David Benjamin40f101b2015-02-20 11:23:42 -05001069 return true;
David Benjamin83f90402015-01-27 01:09:43 -05001070 }
1071
David Benjamin43ec06f2014-08-05 02:28:57 -04001072 // See if we needed to read or write more. If so, allow one byte through on
1073 // the appropriate end to maximally stress the state machine.
David Benjamind9e07012015-02-09 03:04:34 -05001074 switch (SSL_get_error(ssl, ret)) {
1075 case SSL_ERROR_WANT_READ:
David Benjamin6c2563e2015-04-03 03:47:47 -04001076 AsyncBioAllowRead(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -05001077 return true;
David Benjamind9e07012015-02-09 03:04:34 -05001078 case SSL_ERROR_WANT_WRITE:
David Benjamin6c2563e2015-04-03 03:47:47 -04001079 AsyncBioAllowWrite(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -05001080 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -05001081 case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001082 bssl::UniquePtr<EVP_PKEY> pkey =
1083 LoadPrivateKey(GetTestConfig(ssl)->send_channel_id);
David Benjamin9d0847a2015-02-16 03:57:55 -05001084 if (!pkey) {
David Benjamin40f101b2015-02-20 11:23:42 -05001085 return false;
David Benjamin9d0847a2015-02-16 03:57:55 -05001086 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001087 test_state->channel_id = std::move(pkey);
David Benjamin40f101b2015-02-20 11:23:42 -05001088 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -05001089 }
David Benjamin41fdbcd2015-02-09 03:13:35 -05001090 case SSL_ERROR_WANT_X509_LOOKUP:
David Benjamin6c2563e2015-04-03 03:47:47 -04001091 test_state->cert_ready = true;
David Benjamin40f101b2015-02-20 11:23:42 -05001092 return true;
David Benjamin1b8b6912015-02-09 04:28:16 -05001093 case SSL_ERROR_PENDING_SESSION:
David Benjamin6c2563e2015-04-03 03:47:47 -04001094 test_state->session = std::move(test_state->pending_session);
David Benjamin40f101b2015-02-20 11:23:42 -05001095 return true;
David Benjamin6f5c0f42015-02-24 01:23:21 -05001096 case SSL_ERROR_PENDING_CERTIFICATE:
1097 // The handshake will resume without a second call to the early callback.
1098 return InstallCertificate(ssl);
David Benjaminb4d65fd2015-05-29 17:11:21 -04001099 case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
nagendra modadugu3398dbf2015-08-07 14:07:52 -07001100 test_state->private_key_retries++;
David Benjaminb4d65fd2015-05-29 17:11:21 -04001101 return true;
David Benjamind9e07012015-02-09 03:04:34 -05001102 default:
David Benjamin40f101b2015-02-20 11:23:42 -05001103 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001104 }
David Benjamin025b3d32014-07-01 19:53:04 -04001105}
1106
David Benjamin6c2563e2015-04-03 03:47:47 -04001107// DoRead reads from |ssl|, resolving any asynchronous operations. It returns
1108// the result value of the final |SSL_read| call.
1109static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
David Benjamin7e7a82d2016-05-20 20:12:42 -04001110 const TestConfig *config = GetTestConfig(ssl);
David Benjamin13e81fc2015-11-02 17:16:13 -05001111 TestState *test_state = GetTestState(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -04001112 int ret;
1113 do {
David Benjamin13e81fc2015-11-02 17:16:13 -05001114 if (config->async) {
1115 // The DTLS retransmit logic silently ignores write failures. So the test
1116 // may progress, allow writes through synchronously. |SSL_read| may
1117 // trigger a retransmit, so disconnect the write quota.
1118 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
1119 }
David Benjaminf3fbade2016-09-19 13:08:16 -04001120 ret = config->peek_then_read ? SSL_peek(ssl, out, max_out)
1121 : SSL_read(ssl, out, max_out);
David Benjamin13e81fc2015-11-02 17:16:13 -05001122 if (config->async) {
1123 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
1124 }
David Benjamin7bb1d292016-11-01 19:45:06 -04001125
1126 // Run the exporter after each read. This is to test that the exporter fails
1127 // during a renegotiation.
1128 if (config->use_exporter_between_reads) {
1129 uint8_t buf;
1130 if (!SSL_export_keying_material(ssl, &buf, 1, NULL, 0, NULL, 0, 0)) {
1131 fprintf(stderr, "failed to export keying material\n");
1132 return -1;
1133 }
1134 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001135 } while (config->async && RetryAsync(ssl, ret));
David Benjaminf3fbade2016-09-19 13:08:16 -04001136
1137 if (config->peek_then_read && ret > 0) {
1138 std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
1139
1140 // SSL_peek should synchronously return the same data.
1141 int ret2 = SSL_peek(ssl, buf.get(), ret);
1142 if (ret2 != ret ||
1143 memcmp(buf.get(), out, ret) != 0) {
1144 fprintf(stderr, "First and second SSL_peek did not match.\n");
1145 return -1;
1146 }
1147
1148 // SSL_read should synchronously return the same data and consume it.
1149 ret2 = SSL_read(ssl, buf.get(), ret);
1150 if (ret2 != ret ||
1151 memcmp(buf.get(), out, ret) != 0) {
1152 fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
1153 return -1;
1154 }
1155 }
1156
David Benjamin6c2563e2015-04-03 03:47:47 -04001157 return ret;
1158}
1159
1160// WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
1161// operations. It returns the result of the final |SSL_write| call.
1162static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -04001163 const TestConfig *config = GetTestConfig(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -04001164 int ret;
1165 do {
1166 ret = SSL_write(ssl, in, in_len);
1167 if (ret > 0) {
1168 in += ret;
1169 in_len -= ret;
1170 }
1171 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
1172 return ret;
1173}
1174
David Benjamin30789da2015-08-29 22:56:45 -04001175// DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
1176// returns the result of the final |SSL_shutdown| call.
1177static int DoShutdown(SSL *ssl) {
David Benjamin7e7a82d2016-05-20 20:12:42 -04001178 const TestConfig *config = GetTestConfig(ssl);
David Benjamin30789da2015-08-29 22:56:45 -04001179 int ret;
1180 do {
1181 ret = SSL_shutdown(ssl);
1182 } while (config->async && RetryAsync(ssl, ret));
1183 return ret;
1184}
1185
David Benjamin1d4f4c02016-07-26 18:03:08 -04001186// DoSendFatalAlert calls |SSL_send_fatal_alert|, resolving any asynchronous
1187// operations. It returns the result of the final |SSL_send_fatal_alert| call.
1188static int DoSendFatalAlert(SSL *ssl, uint8_t alert) {
1189 const TestConfig *config = GetTestConfig(ssl);
1190 int ret;
1191 do {
1192 ret = SSL_send_fatal_alert(ssl, alert);
1193 } while (config->async && RetryAsync(ssl, ret));
1194 return ret;
1195}
1196
Steven Valdez1e6f11a2016-07-27 11:10:52 -04001197static uint16_t GetProtocolVersion(const SSL *ssl) {
1198 uint16_t version = SSL_version(ssl);
1199 if (!SSL_is_dtls(ssl)) {
1200 return version;
1201 }
1202 return 0x0201 + ~version;
1203}
1204
David Benjamin91eab5c2015-06-18 18:35:46 -04001205// CheckHandshakeProperties checks, immediately after |ssl| completes its
1206// initial handshake (or False Starts), whether all the properties are
1207// consistent with the test configuration and invariants.
1208static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
David Benjamin7e7a82d2016-05-20 20:12:42 -04001209 const TestConfig *config = GetTestConfig(ssl);
David Benjamin91eab5c2015-06-18 18:35:46 -04001210
1211 if (SSL_get_current_cipher(ssl) == nullptr) {
1212 fprintf(stderr, "null cipher after handshake\n");
1213 return false;
1214 }
1215
1216 if (is_resume &&
1217 (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
1218 fprintf(stderr, "session was%s reused\n",
1219 SSL_session_reused(ssl) ? "" : " not");
1220 return false;
1221 }
1222
1223 bool expect_handshake_done = is_resume || !config->false_start;
1224 if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
1225 fprintf(stderr, "handshake was%s completed\n",
1226 GetTestState(ssl)->handshake_done ? "" : " not");
1227 return false;
1228 }
1229
David Benjaminba4594a2015-06-18 18:36:15 -04001230 if (expect_handshake_done && !config->is_server) {
1231 bool expect_new_session =
1232 !config->expect_no_session &&
Steven Valdez143e8b32016-07-11 13:19:03 -04001233 (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
Steven Valdez1e6f11a2016-07-27 11:10:52 -04001234 // Session tickets are sent post-handshake in TLS 1.3.
1235 GetProtocolVersion(ssl) < TLS1_3_VERSION;
David Benjaminba4594a2015-06-18 18:36:15 -04001236 if (expect_new_session != GetTestState(ssl)->got_new_session) {
1237 fprintf(stderr,
David Benjamindd6fed92015-10-23 17:41:12 -04001238 "new session was%s cached, but we expected the opposite\n",
David Benjaminba4594a2015-06-18 18:36:15 -04001239 GetTestState(ssl)->got_new_session ? "" : " not");
1240 return false;
1241 }
1242 }
1243
David Benjamin91eab5c2015-06-18 18:35:46 -04001244 if (config->is_server && !GetTestState(ssl)->early_callback_called) {
1245 fprintf(stderr, "early callback not called\n");
1246 return false;
1247 }
1248
1249 if (!config->expected_server_name.empty()) {
1250 const char *server_name =
1251 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
David Benjamin8b176712016-10-27 21:51:24 -04001252 if (server_name == nullptr ||
1253 server_name != config->expected_server_name) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001254 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
1255 server_name, config->expected_server_name.c_str());
1256 return false;
1257 }
1258 }
1259
David Benjamin91eab5c2015-06-18 18:35:46 -04001260 if (!config->expected_next_proto.empty()) {
1261 const uint8_t *next_proto;
1262 unsigned next_proto_len;
1263 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
1264 if (next_proto_len != config->expected_next_proto.size() ||
1265 memcmp(next_proto, config->expected_next_proto.data(),
1266 next_proto_len) != 0) {
1267 fprintf(stderr, "negotiated next proto mismatch\n");
1268 return false;
1269 }
1270 }
1271
1272 if (!config->expected_alpn.empty()) {
1273 const uint8_t *alpn_proto;
1274 unsigned alpn_proto_len;
1275 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
1276 if (alpn_proto_len != config->expected_alpn.size() ||
1277 memcmp(alpn_proto, config->expected_alpn.data(),
1278 alpn_proto_len) != 0) {
1279 fprintf(stderr, "negotiated alpn proto mismatch\n");
1280 return false;
1281 }
1282 }
1283
1284 if (!config->expected_channel_id.empty()) {
1285 uint8_t channel_id[64];
1286 if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
1287 fprintf(stderr, "no channel id negotiated\n");
1288 return false;
1289 }
1290 if (config->expected_channel_id.size() != 64 ||
1291 memcmp(config->expected_channel_id.data(),
1292 channel_id, 64) != 0) {
1293 fprintf(stderr, "channel id mismatch\n");
1294 return false;
1295 }
1296 }
1297
1298 if (config->expect_extended_master_secret) {
David Benjamin8ac35712016-07-13 21:07:29 -04001299 if (!SSL_get_extms_support(ssl)) {
1300 fprintf(stderr, "No EMS for connection when expected");
David Benjamin91eab5c2015-06-18 18:35:46 -04001301 return false;
1302 }
1303 }
1304
1305 if (!config->expected_ocsp_response.empty()) {
1306 const uint8_t *data;
1307 size_t len;
1308 SSL_get0_ocsp_response(ssl, &data, &len);
1309 if (config->expected_ocsp_response.size() != len ||
1310 memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
1311 fprintf(stderr, "OCSP response mismatch\n");
1312 return false;
1313 }
1314 }
1315
1316 if (!config->expected_signed_cert_timestamps.empty()) {
1317 const uint8_t *data;
1318 size_t len;
1319 SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
1320 if (config->expected_signed_cert_timestamps.size() != len ||
1321 memcmp(config->expected_signed_cert_timestamps.data(),
1322 data, len) != 0) {
1323 fprintf(stderr, "SCT list mismatch\n");
1324 return false;
1325 }
1326 }
1327
Paul Lietar8f1c2682015-08-18 12:21:54 +01001328 if (config->expect_verify_result) {
1329 int expected_verify_result = config->verify_fail ?
1330 X509_V_ERR_APPLICATION_VERIFICATION :
1331 X509_V_OK;
1332
1333 if (SSL_get_verify_result(ssl) != expected_verify_result) {
1334 fprintf(stderr, "Wrong certificate verification result\n");
1335 return false;
1336 }
1337 }
1338
Nick Harper60edffd2016-06-21 15:19:24 -07001339 if (config->expect_peer_signature_algorithm != 0 &&
1340 config->expect_peer_signature_algorithm !=
1341 SSL_get_peer_signature_algorithm(ssl)) {
1342 fprintf(stderr, "Peer signature algorithm was %04x, wanted %04x.\n",
1343 SSL_get_peer_signature_algorithm(ssl),
1344 config->expect_peer_signature_algorithm);
David Benjamin6e807652015-11-02 12:02:20 -05001345 return false;
1346 }
1347
David Benjamin9e68f192016-06-30 14:55:33 -04001348 if (config->expect_curve_id != 0) {
1349 uint16_t curve_id = SSL_get_curve_id(ssl);
1350 if (static_cast<uint16_t>(config->expect_curve_id) != curve_id) {
1351 fprintf(stderr, "curve_id was %04x, wanted %04x\n", curve_id,
1352 static_cast<uint16_t>(config->expect_curve_id));
1353 return false;
1354 }
1355 }
1356
1357 if (config->expect_dhe_group_size != 0) {
1358 unsigned dhe_group_size = SSL_get_dhe_group_size(ssl);
1359 if (static_cast<unsigned>(config->expect_dhe_group_size) !=
1360 dhe_group_size) {
1361 fprintf(stderr, "dhe_group_size was %u, wanted %d\n", dhe_group_size,
1362 config->expect_dhe_group_size);
David Benjamin4cc36ad2015-12-19 14:23:26 -05001363 return false;
1364 }
1365 }
1366
David Benjaminabbbee12016-10-31 19:20:42 -04001367 uint16_t cipher_id =
1368 static_cast<uint16_t>(SSL_CIPHER_get_id(SSL_get_current_cipher(ssl)));
1369 if (config->expect_cipher_aes != 0 &&
1370 EVP_has_aes_hardware() &&
1371 static_cast<uint16_t>(config->expect_cipher_aes) != cipher_id) {
1372 fprintf(stderr, "Cipher ID was %04x, wanted %04x (has AES hardware)\n",
1373 cipher_id, static_cast<uint16_t>(config->expect_cipher_aes));
1374 return false;
1375 }
1376
1377 if (config->expect_cipher_no_aes != 0 &&
1378 !EVP_has_aes_hardware() &&
1379 static_cast<uint16_t>(config->expect_cipher_no_aes) != cipher_id) {
1380 fprintf(stderr, "Cipher ID was %04x, wanted %04x (no AES hardware)\n",
1381 cipher_id, static_cast<uint16_t>(config->expect_cipher_no_aes));
1382 return false;
1383 }
1384
1385
David Benjaminbb9e36e2016-08-03 14:14:47 -04001386 if (!config->psk.empty()) {
1387 if (SSL_get_peer_cert_chain(ssl) != nullptr) {
1388 fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
1389 return false;
1390 }
1391 } else if (!config->is_server || config->require_any_client_certificate) {
1392 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
1393 fprintf(stderr, "Received no peer certificate but expected one.\n");
David Benjamin91eab5c2015-06-18 18:35:46 -04001394 return false;
1395 }
1396 }
David Benjaminbb9e36e2016-08-03 14:14:47 -04001397
David Benjamin2c516452016-11-15 10:16:54 +09001398 if (!config->expect_peer_cert_file.empty()) {
1399 bssl::UniquePtr<X509> expect_leaf;
1400 bssl::UniquePtr<STACK_OF(X509)> expect_chain;
1401 if (!LoadCertificate(&expect_leaf, &expect_chain,
1402 config->expect_peer_cert_file)) {
1403 return false;
1404 }
1405
1406 // For historical reasons, clients report a chain with a leaf and servers
1407 // without.
1408 if (!config->is_server) {
1409 if (!sk_X509_insert(expect_chain.get(), expect_leaf.get(), 0)) {
1410 return false;
1411 }
1412 X509_up_ref(expect_leaf.get()); // sk_X509_push takes ownership.
1413 }
1414
1415 bssl::UniquePtr<X509> leaf(SSL_get_peer_certificate(ssl));
1416 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl);
1417 if (X509_cmp(leaf.get(), expect_leaf.get()) != 0) {
1418 fprintf(stderr, "Received a different leaf certificate than expected.\n");
1419 return false;
1420 }
1421
1422 if (sk_X509_num(chain) != sk_X509_num(expect_chain.get())) {
1423 fprintf(stderr, "Received a chain of length %zu instead of %zu.\n",
1424 sk_X509_num(chain), sk_X509_num(expect_chain.get()));
1425 return false;
1426 }
1427
1428 for (size_t i = 0; i < sk_X509_num(chain); i++) {
1429 if (X509_cmp(sk_X509_value(chain, i),
1430 sk_X509_value(expect_chain.get(), i)) != 0) {
1431 fprintf(stderr, "Chain certificate %zu did not match.\n",
1432 i + 1);
1433 return false;
1434 }
1435 }
1436 }
1437
David Benjaminbbaf3672016-11-17 10:53:09 +09001438 bool expected_sha256_client_cert = config->expect_sha256_client_cert_initial;
1439 if (is_resume) {
1440 expected_sha256_client_cert = config->expect_sha256_client_cert_resume;
1441 }
1442
1443 if (SSL_get_session(ssl)->peer_sha256_valid != expected_sha256_client_cert) {
1444 fprintf(stderr,
1445 "Unexpected SHA-256 client cert state: expected:%d is_resume:%d.\n",
1446 expected_sha256_client_cert, is_resume);
1447 return false;
1448 }
1449
1450 if (expected_sha256_client_cert &&
1451 SSL_get_session(ssl)->x509_peer != nullptr) {
1452 fprintf(stderr, "Have both client cert and SHA-256 hash: is_resume:%d.\n",
1453 is_resume);
1454 return false;
1455 }
1456
David Benjamin91eab5c2015-06-18 18:35:46 -04001457 return true;
1458}
1459
David Benjamin87c8a642015-02-21 01:54:29 -05001460// DoExchange runs a test SSL exchange against the peer. On success, it returns
1461// true and sets |*out_session| to the negotiated SSL session. If the test is a
1462// resumption attempt, |is_resume| is true and |session| is the session from the
1463// previous exchange.
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001464static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
1465 SSL_CTX *ssl_ctx, const TestConfig *config,
1466 bool is_resume, SSL_SESSION *session) {
1467 bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
David Benjamina7f333d2015-02-09 02:37:18 -05001468 if (!ssl) {
David Benjamin40f101b2015-02-20 11:23:42 -05001469 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001470 }
1471
David Benjamin7e7a82d2016-05-20 20:12:42 -04001472 if (!SetTestConfig(ssl.get(), config) ||
David Benjamin2d445c02015-02-09 13:03:50 -05001473 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
David Benjamin40f101b2015-02-20 11:23:42 -05001474 return false;
Adam Langley69a01602014-11-17 17:26:55 -08001475 }
David Benjamin5a593af2014-08-11 19:51:50 -04001476
Adam Langley5f0efe02015-02-20 13:03:16 -08001477 if (config->fallback_scsv &&
1478 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
1479 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001480 }
David Benjamina0486782016-10-06 19:11:32 -04001481 // Install the certificate synchronously if nothing else will handle it.
1482 if (!config->use_early_callback &&
1483 !config->use_old_client_cert_callback &&
1484 !config->async &&
1485 !InstallCertificate(ssl.get())) {
1486 return false;
David Benjamin5a593af2014-08-11 19:51:50 -04001487 }
David Benjamina0486782016-10-06 19:11:32 -04001488 SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
David Benjamin5a593af2014-08-11 19:51:50 -04001489 if (config->require_any_client_certificate) {
David Benjamina7f333d2015-02-09 02:37:18 -05001490 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
Paul Lietar8f1c2682015-08-18 12:21:54 +01001491 NULL);
1492 }
1493 if (config->verify_peer) {
1494 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
David Benjamin5a593af2014-08-11 19:51:50 -04001495 }
1496 if (config->false_start) {
David Benjamined7c4752015-02-16 19:16:46 -05001497 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
David Benjamin5a593af2014-08-11 19:51:50 -04001498 }
1499 if (config->cbc_record_splitting) {
David Benjamina7f333d2015-02-09 02:37:18 -05001500 SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
David Benjamin5a593af2014-08-11 19:51:50 -04001501 }
1502 if (config->partial_write) {
David Benjamina7f333d2015-02-09 02:37:18 -05001503 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
David Benjamin5a593af2014-08-11 19:51:50 -04001504 }
Steven Valdez4f94b1c2016-05-24 12:31:07 -04001505 if (config->no_tls13) {
1506 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
1507 }
David Benjamin5a593af2014-08-11 19:51:50 -04001508 if (config->no_tls12) {
David Benjamina7f333d2015-02-09 02:37:18 -05001509 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
David Benjamin5a593af2014-08-11 19:51:50 -04001510 }
1511 if (config->no_tls11) {
David Benjamina7f333d2015-02-09 02:37:18 -05001512 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
David Benjamin5a593af2014-08-11 19:51:50 -04001513 }
1514 if (config->no_tls1) {
David Benjamina7f333d2015-02-09 02:37:18 -05001515 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
David Benjamin5a593af2014-08-11 19:51:50 -04001516 }
1517 if (config->no_ssl3) {
David Benjamina7f333d2015-02-09 02:37:18 -05001518 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
David Benjamin5a593af2014-08-11 19:51:50 -04001519 }
Steven Valdez143e8b32016-07-11 13:19:03 -04001520 if (!config->expected_channel_id.empty() ||
1521 config->enable_channel_id) {
David Benjamineebd3c82016-12-06 17:43:58 -05001522 SSL_set_tls_channel_id_enabled(ssl.get(), 1);
David Benjamina08e49d2014-08-24 01:46:07 -04001523 }
1524 if (!config->send_channel_id.empty()) {
David Benjamineebd3c82016-12-06 17:43:58 -05001525 SSL_set_tls_channel_id_enabled(ssl.get(), 1);
David Benjamind9e07012015-02-09 03:04:34 -05001526 if (!config->async) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001527 // The async case will be supplied by |ChannelIdCallback|.
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001528 bssl::UniquePtr<EVP_PKEY> pkey = LoadPrivateKey(config->send_channel_id);
David Benjamind9e07012015-02-09 03:04:34 -05001529 if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001530 return false;
David Benjamind9e07012015-02-09 03:04:34 -05001531 }
David Benjamina08e49d2014-08-24 01:46:07 -04001532 }
David Benjamina08e49d2014-08-24 01:46:07 -04001533 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001534 if (!config->host_name.empty() &&
1535 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001536 return false;
David Benjamine78bfde2014-09-06 12:45:15 -04001537 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001538 if (!config->advertise_alpn.empty() &&
1539 SSL_set_alpn_protos(ssl.get(),
1540 (const uint8_t *)config->advertise_alpn.data(),
1541 config->advertise_alpn.size()) != 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001542 return false;
David Benjaminae2888f2014-09-06 12:58:58 -04001543 }
David Benjamin48cae082014-10-27 01:06:24 -04001544 if (!config->psk.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001545 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
1546 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
David Benjamin48cae082014-10-27 01:06:24 -04001547 }
David Benjamin61f95272014-11-25 01:55:35 -05001548 if (!config->psk_identity.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001549 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001550 return false;
David Benjamin48cae082014-10-27 01:06:24 -04001551 }
David Benjamin61f95272014-11-25 01:55:35 -05001552 if (!config->srtp_profiles.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001553 !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001554 return false;
David Benjamin61f95272014-11-25 01:55:35 -05001555 }
1556 if (config->enable_ocsp_stapling &&
David Benjamina7f333d2015-02-09 02:37:18 -05001557 !SSL_enable_ocsp_stapling(ssl.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001558 return false;
David Benjamin61f95272014-11-25 01:55:35 -05001559 }
1560 if (config->enable_signed_cert_timestamps &&
David Benjamina7f333d2015-02-09 02:37:18 -05001561 !SSL_enable_signed_cert_timestamps(ssl.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001562 return false;
David Benjaminca6c8262014-11-15 19:06:08 -05001563 }
David Benjamin2dc02042016-09-19 19:57:37 -04001564 if (config->min_version != 0 &&
David Benjamine4706902016-09-20 15:12:23 -04001565 !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) {
David Benjamin2dc02042016-09-19 19:57:37 -04001566 return false;
David Benjamin1eb367c2014-12-12 18:17:51 -05001567 }
David Benjamin2dc02042016-09-19 19:57:37 -04001568 if (config->max_version != 0 &&
David Benjamine4706902016-09-20 15:12:23 -04001569 !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) {
David Benjamin2dc02042016-09-19 19:57:37 -04001570 return false;
David Benjamin1eb367c2014-12-12 18:17:51 -05001571 }
David Benjamin13be1de2015-01-11 16:29:36 -05001572 if (config->mtu != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001573 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
1574 SSL_set_mtu(ssl.get(), config->mtu);
David Benjamin13be1de2015-01-11 16:29:36 -05001575 }
Adam Langley524e7172015-02-20 16:04:00 -08001576 if (config->install_ddos_callback) {
1577 SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
1578 }
David Benjamin1d5ef3b2015-10-12 19:54:18 -04001579 if (config->renegotiate_once) {
1580 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_once);
1581 }
1582 if (config->renegotiate_freely) {
1583 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
David Benjaminb16346b2015-04-08 19:16:58 -04001584 }
Adam Langley27a0d082015-11-03 13:34:10 -08001585 if (config->renegotiate_ignore) {
1586 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_ignore);
1587 }
David Benjamin30789da2015-08-29 22:56:45 -04001588 if (!config->check_close_notify) {
1589 SSL_set_quiet_shutdown(ssl.get(), 1);
1590 }
David Benjamin091c4b92015-10-26 13:33:21 -04001591 if (config->disable_npn) {
1592 SSL_set_options(ssl.get(), SSL_OP_DISABLE_NPN);
1593 }
David Benjamin99fdfb92015-11-02 12:11:35 -05001594 if (config->p384_only) {
1595 int nid = NID_secp384r1;
1596 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
1597 return false;
1598 }
1599 }
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001600 if (config->enable_all_curves) {
1601 static const int kAllCurves[] = {
Matt Braithwaite053931e2016-05-25 12:06:05 -07001602 NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_X25519,
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001603 };
1604 if (!SSL_set1_curves(ssl.get(), kAllCurves,
Steven Valdezcb966542016-08-17 16:56:14 -04001605 OPENSSL_ARRAY_SIZE(kAllCurves))) {
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001606 return false;
1607 }
1608 }
Taylor Brandstetter376a0fe2016-05-10 19:30:28 -07001609 if (config->initial_timeout_duration_ms > 0) {
1610 DTLSv1_set_initial_timeout_duration(ssl.get(),
1611 config->initial_timeout_duration_ms);
1612 }
David Benjamina252b342016-09-26 19:57:53 -04001613 if (config->max_cert_list > 0) {
1614 SSL_set_max_cert_list(ssl.get(), config->max_cert_list);
1615 }
David Benjaminbbaf3672016-11-17 10:53:09 +09001616 if (!is_resume && config->retain_only_sha256_client_cert_initial) {
1617 SSL_set_retain_only_sha256_of_client_certs(ssl.get(), 1);
1618 }
1619 if (is_resume && config->retain_only_sha256_client_cert_resume) {
1620 SSL_set_retain_only_sha256_of_client_certs(ssl.get(), 1);
1621 }
David Benjamin025b3d32014-07-01 19:53:04 -04001622
David Benjamin87c8a642015-02-21 01:54:29 -05001623 int sock = Connect(config->port);
1624 if (sock == -1) {
1625 return false;
1626 }
1627 SocketCloser closer(sock);
1628
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001629 bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
David Benjamina7f333d2015-02-09 02:37:18 -05001630 if (!bio) {
David Benjamin40f101b2015-02-20 11:23:42 -05001631 return false;
David Benjamin43ec06f2014-08-05 02:28:57 -04001632 }
David Benjamin6fd297b2014-08-11 18:43:38 -04001633 if (config->is_dtls) {
David Benjamin1b22f852016-10-27 16:36:32 -04001634 bssl::UniquePtr<BIO> packeted = PacketedBioCreate(&g_clock, !config->async);
David Benjaminb7c5e842016-03-28 09:59:10 -04001635 if (!packeted) {
1636 return false;
1637 }
David Benjamin585d7a42016-06-02 14:58:00 -04001638 GetTestState(ssl.get())->packeted_bio = packeted.get();
David Benjamina7f333d2015-02-09 02:37:18 -05001639 BIO_push(packeted.get(), bio.release());
1640 bio = std::move(packeted);
David Benjamin6fd297b2014-08-11 18:43:38 -04001641 }
David Benjamin5a593af2014-08-11 19:51:50 -04001642 if (config->async) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001643 bssl::UniquePtr<BIO> async_scoped =
David Benjaminc273d2c2015-02-09 12:59:46 -05001644 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
David Benjaminb7c5e842016-03-28 09:59:10 -04001645 if (!async_scoped) {
1646 return false;
1647 }
David Benjamina7f333d2015-02-09 02:37:18 -05001648 BIO_push(async_scoped.get(), bio.release());
David Benjamin6c2563e2015-04-03 03:47:47 -04001649 GetTestState(ssl.get())->async_bio = async_scoped.get();
David Benjamina7f333d2015-02-09 02:37:18 -05001650 bio = std::move(async_scoped);
David Benjamin43ec06f2014-08-05 02:28:57 -04001651 }
David Benjamina7f333d2015-02-09 02:37:18 -05001652 SSL_set_bio(ssl.get(), bio.get(), bio.get());
1653 bio.release(); // SSL_set_bio takes ownership.
David Benjamin43ec06f2014-08-05 02:28:57 -04001654
David Benjamin1d5c83e2014-07-22 19:20:02 -04001655 if (session != NULL) {
David Benjamin1b8b6912015-02-09 04:28:16 -05001656 if (!config->is_server) {
1657 if (SSL_set_session(ssl.get(), session) != 1) {
David Benjamin40f101b2015-02-20 11:23:42 -05001658 return false;
David Benjamin1b8b6912015-02-09 04:28:16 -05001659 }
1660 } else if (config->async) {
1661 // The internal session cache is disabled, so install the session
1662 // manually.
David Benjaminb9195402016-08-05 10:51:43 -04001663 SSL_SESSION_up_ref(session);
1664 GetTestState(ssl.get())->pending_session.reset(session);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001665 }
1666 }
1667
David Benjamina07c0fc2015-05-13 13:19:42 -04001668 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1669 fprintf(stderr, "non-null cipher before handshake\n");
1670 return false;
1671 }
1672
David Benjamin1d5c83e2014-07-22 19:20:02 -04001673 int ret;
David Benjamine0e7d0d2015-02-08 19:33:25 -05001674 if (config->implicit_handshake) {
David Benjamin5a593af2014-08-11 19:51:50 -04001675 if (config->is_server) {
David Benjamina7f333d2015-02-09 02:37:18 -05001676 SSL_set_accept_state(ssl.get());
David Benjamin43ec06f2014-08-05 02:28:57 -04001677 } else {
David Benjamina7f333d2015-02-09 02:37:18 -05001678 SSL_set_connect_state(ssl.get());
David Benjamin43ec06f2014-08-05 02:28:57 -04001679 }
David Benjamine0e7d0d2015-02-08 19:33:25 -05001680 } else {
1681 do {
1682 if (config->is_server) {
David Benjamina7f333d2015-02-09 02:37:18 -05001683 ret = SSL_accept(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -05001684 } else {
David Benjamina7f333d2015-02-09 02:37:18 -05001685 ret = SSL_connect(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -05001686 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001687 } while (config->async && RetryAsync(ssl.get(), ret));
David Benjamin91eab5c2015-06-18 18:35:46 -04001688 if (ret != 1 ||
1689 !CheckHandshakeProperties(ssl.get(), is_resume)) {
David Benjamin40f101b2015-02-20 11:23:42 -05001690 return false;
David Benjamine0e7d0d2015-02-08 19:33:25 -05001691 }
David Benjamin025b3d32014-07-01 19:53:04 -04001692
David Benjaminba4594a2015-06-18 18:36:15 -04001693 // Reset the state to assert later that the callback isn't called in
1694 // renegotations.
1695 GetTestState(ssl.get())->got_new_session = false;
David Benjamin61f95272014-11-25 01:55:35 -05001696 }
1697
David Benjaminc565ebb2015-04-03 04:06:36 -04001698 if (config->export_keying_material > 0) {
1699 std::vector<uint8_t> result(
1700 static_cast<size_t>(config->export_keying_material));
1701 if (!SSL_export_keying_material(
1702 ssl.get(), result.data(), result.size(),
1703 config->export_label.data(), config->export_label.size(),
1704 reinterpret_cast<const uint8_t*>(config->export_context.data()),
1705 config->export_context.size(), config->use_export_context)) {
1706 fprintf(stderr, "failed to export keying material\n");
1707 return false;
1708 }
1709 if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1710 return false;
1711 }
1712 }
1713
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001714 if (config->tls_unique) {
1715 uint8_t tls_unique[16];
1716 size_t tls_unique_len;
1717 if (!SSL_get_tls_unique(ssl.get(), tls_unique, &tls_unique_len,
1718 sizeof(tls_unique))) {
1719 fprintf(stderr, "failed to get tls-unique\n");
1720 return false;
1721 }
1722
1723 if (tls_unique_len != 12) {
1724 fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
1725 static_cast<unsigned>(tls_unique_len));
1726 return false;
1727 }
1728
1729 if (WriteAll(ssl.get(), tls_unique, tls_unique_len) < 0) {
1730 return false;
1731 }
1732 }
1733
David Benjamin1d4f4c02016-07-26 18:03:08 -04001734 if (config->send_alert) {
1735 if (DoSendFatalAlert(ssl.get(), SSL_AD_DECOMPRESSION_FAILURE) < 0) {
1736 return false;
1737 }
1738 return true;
1739 }
1740
David Benjamin5a593af2014-08-11 19:51:50 -04001741 if (config->write_different_record_sizes) {
David Benjamin6fd297b2014-08-11 18:43:38 -04001742 if (config->is_dtls) {
1743 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001744 return false;
David Benjamin6fd297b2014-08-11 18:43:38 -04001745 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001746 // This mode writes a number of different record sizes in an attempt to
1747 // trip up the CBC record splitting code.
Adam Langleybc949292015-06-18 21:32:44 -07001748 static const size_t kBufLen = 32769;
1749 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1750 memset(buf.get(), 0x42, kBufLen);
Kenny Root7fdeaf12014-08-05 15:23:37 -07001751 static const size_t kRecordSizes[] = {
1752 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
Steven Valdezcb966542016-08-17 16:56:14 -04001753 for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07001754 const size_t len = kRecordSizes[i];
Adam Langleybc949292015-06-18 21:32:44 -07001755 if (len > kBufLen) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07001756 fprintf(stderr, "Bad kRecordSizes value.\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001757 return false;
Kenny Root7fdeaf12014-08-05 15:23:37 -07001758 }
Adam Langleybc949292015-06-18 21:32:44 -07001759 if (WriteAll(ssl.get(), buf.get(), len) < 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001760 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001761 }
1762 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001763 } else {
David Benjamine58c4f52014-08-24 03:47:07 -04001764 if (config->shim_writes_first) {
David Benjamin6c2563e2015-04-03 03:47:47 -04001765 if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1766 5) < 0) {
1767 return false;
1768 }
David Benjamine58c4f52014-08-24 03:47:07 -04001769 }
David Benjamin30789da2015-08-29 22:56:45 -04001770 if (!config->shim_shuts_down) {
1771 for (;;) {
Adam Langleya0a8dc22015-09-09 10:22:00 -07001772 static const size_t kBufLen = 16384;
1773 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1774
David Benjamin2c99d282015-09-01 10:23:00 -04001775 // Read only 512 bytes at a time in TLS to ensure records may be
1776 // returned in multiple reads.
Adam Langleya0a8dc22015-09-09 10:22:00 -07001777 int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
David Benjamin30789da2015-08-29 22:56:45 -04001778 int err = SSL_get_error(ssl.get(), n);
1779 if (err == SSL_ERROR_ZERO_RETURN ||
1780 (n == 0 && err == SSL_ERROR_SYSCALL)) {
1781 if (n != 0) {
1782 fprintf(stderr, "Invalid SSL_get_error output\n");
1783 return false;
1784 }
1785 // Stop on either clean or unclean shutdown.
1786 break;
1787 } else if (err != SSL_ERROR_NONE) {
1788 if (n > 0) {
1789 fprintf(stderr, "Invalid SSL_get_error output\n");
1790 return false;
1791 }
1792 return false;
1793 }
1794 // Successfully read data.
1795 if (n <= 0) {
David Benjamin9a38e922015-01-22 16:06:11 -05001796 fprintf(stderr, "Invalid SSL_get_error output\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001797 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001798 }
David Benjamin30789da2015-08-29 22:56:45 -04001799
1800 // After a successful read, with or without False Start, the handshake
1801 // must be complete.
1802 if (!GetTestState(ssl.get())->handshake_done) {
1803 fprintf(stderr, "handshake was not completed after SSL_read\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001804 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001805 }
David Benjamin87e4acd2015-04-02 19:57:35 -04001806
David Benjamin30789da2015-08-29 22:56:45 -04001807 for (int i = 0; i < n; i++) {
1808 buf[i] ^= 0xff;
1809 }
Adam Langleya0a8dc22015-09-09 10:22:00 -07001810 if (WriteAll(ssl.get(), buf.get(), n) < 0) {
David Benjamin30789da2015-08-29 22:56:45 -04001811 return false;
1812 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001813 }
1814 }
David Benjamin025b3d32014-07-01 19:53:04 -04001815 }
1816
David Benjaminba4594a2015-06-18 18:36:15 -04001817 if (!config->is_server && !config->false_start &&
1818 !config->implicit_handshake &&
Steven Valdez1e6f11a2016-07-27 11:10:52 -04001819 // Session tickets are sent post-handshake in TLS 1.3.
1820 GetProtocolVersion(ssl.get()) < TLS1_3_VERSION &&
David Benjaminba4594a2015-06-18 18:36:15 -04001821 GetTestState(ssl.get())->got_new_session) {
1822 fprintf(stderr, "new session was established after the handshake\n");
1823 return false;
1824 }
1825
Steven Valdez1e6f11a2016-07-27 11:10:52 -04001826 if (GetProtocolVersion(ssl.get()) >= TLS1_3_VERSION && !config->is_server) {
1827 bool expect_new_session =
1828 !config->expect_no_session && !config->shim_shuts_down;
1829 if (expect_new_session != GetTestState(ssl.get())->got_new_session) {
1830 fprintf(stderr,
1831 "new session was%s cached, but we expected the opposite\n",
1832 GetTestState(ssl.get())->got_new_session ? "" : " not");
1833 return false;
1834 }
1835 }
1836
David Benjamin1d5c83e2014-07-22 19:20:02 -04001837 if (out_session) {
Steven Valdez4aa154e2016-07-29 14:32:55 -04001838 *out_session = std::move(GetTestState(ssl.get())->new_session);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001839 }
1840
David Benjamin30789da2015-08-29 22:56:45 -04001841 ret = DoShutdown(ssl.get());
1842
1843 if (config->shim_shuts_down && config->check_close_notify) {
1844 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1845 // it returns zero when our close_notify is sent, then one when the peer's
1846 // is received.
1847 if (ret != 0) {
1848 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1849 return false;
1850 }
1851 ret = DoShutdown(ssl.get());
1852 }
1853
1854 if (ret != 1) {
1855 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1856 return false;
1857 }
1858
David Benjamin324dce42015-10-12 19:49:00 -04001859 if (SSL_total_renegotiations(ssl.get()) !=
1860 config->expect_total_renegotiations) {
1861 fprintf(stderr, "Expected %d renegotiations, got %d\n",
1862 config->expect_total_renegotiations,
1863 SSL_total_renegotiations(ssl.get()));
1864 return false;
1865 }
1866
David Benjamin40f101b2015-02-20 11:23:42 -05001867 return true;
David Benjamin025b3d32014-07-01 19:53:04 -04001868}
David Benjamin1d5c83e2014-07-22 19:20:02 -04001869
David Benjaminff3a1492016-03-02 10:12:06 -05001870class StderrDelimiter {
1871 public:
1872 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
1873};
1874
David Benjaminaac1e2d2016-12-06 22:35:41 -05001875int main(int argc, char **argv) {
David Benjaminff3a1492016-03-02 10:12:06 -05001876 // To distinguish ASan's output from ours, add a trailing message to stderr.
1877 // Anything following this line will be considered an error.
1878 StderrDelimiter delimiter;
1879
David Benjamin87c8a642015-02-21 01:54:29 -05001880#if defined(OPENSSL_WINDOWS)
1881 /* Initialize Winsock. */
1882 WORD wsa_version = MAKEWORD(2, 2);
1883 WSADATA wsa_data;
1884 int wsa_err = WSAStartup(wsa_version, &wsa_data);
1885 if (wsa_err != 0) {
1886 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1887 return 1;
1888 }
1889 if (wsa_data.wVersion != wsa_version) {
1890 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1891 return 1;
1892 }
1893#else
David Benjamin1d5c83e2014-07-22 19:20:02 -04001894 signal(SIGPIPE, SIG_IGN);
Adam Langleyded93582014-07-31 15:23:51 -07001895#endif
David Benjamin1d5c83e2014-07-22 19:20:02 -04001896
David Benjamin7a1eefd2015-10-17 23:39:22 -04001897 CRYPTO_library_init();
David Benjamind9e07012015-02-09 03:04:34 -05001898 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
David Benjamin2d445c02015-02-09 13:03:50 -05001899 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
David Benjamin6c2563e2015-04-03 03:47:47 -04001900 if (g_config_index < 0 || g_state_index < 0) {
David Benjaminae3e4872014-11-18 21:52:26 -05001901 return 1;
1902 }
David Benjamin5a593af2014-08-11 19:51:50 -04001903
1904 TestConfig config;
1905 if (!ParseConfig(argc - 1, argv + 1, &config)) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001906 return Usage(argv[0]);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001907 }
1908
David Benjamin1b22f852016-10-27 16:36:32 -04001909 // Some code treats the zero time special, so initialize the clock to a
1910 // non-zero time.
1911 g_clock.tv_sec = 1234;
1912 g_clock.tv_usec = 1234;
1913
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001914 bssl::UniquePtr<SSL_CTX> ssl_ctx = SetupCtx(&config);
David Benjamina7f333d2015-02-09 02:37:18 -05001915 if (!ssl_ctx) {
Brian Smith83a82982015-04-09 16:21:10 -10001916 ERR_print_errors_fp(stderr);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001917 return 1;
1918 }
1919
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001920 bssl::UniquePtr<SSL_SESSION> session;
David Benjamin46662482016-08-17 00:51:00 -04001921 for (int i = 0; i < config.resume_count + 1; i++) {
1922 bool is_resume = i > 0;
1923 if (is_resume && !config.is_server && !session) {
1924 fprintf(stderr, "No session to offer.\n");
1925 return 1;
1926 }
David Benjamin1d5c83e2014-07-22 19:20:02 -04001927
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001928 bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
David Benjamin46662482016-08-17 00:51:00 -04001929 if (!DoExchange(&session, ssl_ctx.get(), &config, is_resume,
1930 offer_session.get())) {
1931 fprintf(stderr, "Connection %d failed.\n", i + 1);
1932 ERR_print_errors_fp(stderr);
1933 return 1;
1934 }
Steven Valdeza833c352016-11-01 13:39:36 -04001935
1936 if (config.resumption_delay != 0) {
1937 g_clock.tv_sec += config.resumption_delay;
1938 }
David Benjamin1d5c83e2014-07-22 19:20:02 -04001939 }
1940
David Benjamina7f333d2015-02-09 02:37:18 -05001941 return 0;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001942}