blob: 900e4f650af2624350e5eba3bda412d63ff4c653 [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
Adam Langleyd519bf62016-12-12 11:16:44 -080069static CRYPTO_BUFFER_POOL *g_pool = nullptr;
70
David Benjamin87c8a642015-02-21 01:54:29 -050071#if !defined(OPENSSL_WINDOWS)
72static int closesocket(int sock) {
73 return close(sock);
74}
75
76static void PrintSocketError(const char *func) {
77 perror(func);
78}
79#else
80static void PrintSocketError(const char *func) {
81 fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
82}
83#endif
84
David Benjaminc273d2c2015-02-09 12:59:46 -050085static int Usage(const char *program) {
David Benjamina7f333d2015-02-09 02:37:18 -050086 fprintf(stderr, "Usage: %s [flags...]\n", program);
David Benjamin1d5c83e2014-07-22 19:20:02 -040087 return 1;
88}
David Benjamin025b3d32014-07-01 19:53:04 -040089
David Benjamin2d445c02015-02-09 13:03:50 -050090struct TestState {
David Benjamin6c2563e2015-04-03 03:47:47 -040091 // async_bio is async BIO which pauses reads and writes.
92 BIO *async_bio = nullptr;
David Benjamin585d7a42016-06-02 14:58:00 -040093 // packeted_bio is the packeted BIO which simulates read timeouts.
94 BIO *packeted_bio = nullptr;
Matt Braithwaited17d74d2016-08-17 20:10:28 -070095 bssl::UniquePtr<EVP_PKEY> channel_id;
David Benjamin0d4db502015-03-23 18:46:05 -040096 bool cert_ready = false;
Matt Braithwaited17d74d2016-08-17 20:10:28 -070097 bssl::UniquePtr<SSL_SESSION> session;
98 bssl::UniquePtr<SSL_SESSION> pending_session;
David Benjamin0d4db502015-03-23 18:46:05 -040099 bool early_callback_called = false;
David Benjamin87e4acd2015-04-02 19:57:35 -0400100 bool handshake_done = false;
David Benjaminb4d65fd2015-05-29 17:11:21 -0400101 // private_key is the underlying private key used when testing custom keys.
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700102 bssl::UniquePtr<EVP_PKEY> private_key;
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700103 std::vector<uint8_t> private_key_result;
104 // private_key_retries is the number of times an asynchronous private key
105 // operation has been retried.
106 unsigned private_key_retries = 0;
David Benjaminba4594a2015-06-18 18:36:15 -0400107 bool got_new_session = false;
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700108 bssl::UniquePtr<SSL_SESSION> new_session;
David Benjamin25fe85b2016-08-09 20:00:32 -0400109 bool ticket_decrypt_done = false;
110 bool alpn_select_done = false;
David Benjamind9e07012015-02-09 03:04:34 -0500111};
112
David Benjamin2d445c02015-02-09 13:03:50 -0500113static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
Adam Langley09505632015-07-30 18:10:13 -0700114 int index, long argl, void *argp) {
David Benjamin2d445c02015-02-09 13:03:50 -0500115 delete ((TestState *)ptr);
David Benjamind9e07012015-02-09 03:04:34 -0500116}
117
118static int g_config_index = 0;
David Benjamin2d445c02015-02-09 13:03:50 -0500119static int g_state_index = 0;
David Benjamin5a593af2014-08-11 19:51:50 -0400120
David Benjamin7e7a82d2016-05-20 20:12:42 -0400121static bool SetTestConfig(SSL *ssl, const TestConfig *config) {
David Benjamind9e07012015-02-09 03:04:34 -0500122 return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
David Benjamin5a593af2014-08-11 19:51:50 -0400123}
124
David Benjamin7e7a82d2016-05-20 20:12:42 -0400125static const TestConfig *GetTestConfig(const SSL *ssl) {
David Benjamind9e07012015-02-09 03:04:34 -0500126 return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
David Benjamin5a593af2014-08-11 19:51:50 -0400127}
128
David Benjamin22050932015-11-23 13:44:48 -0500129static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
130 // |SSL_set_ex_data| takes ownership of |state| only on success.
131 if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
132 state.release();
David Benjamind9e07012015-02-09 03:04:34 -0500133 return true;
134 }
135 return false;
136}
137
David Benjamin87e4acd2015-04-02 19:57:35 -0400138static TestState *GetTestState(const SSL *ssl) {
David Benjamin2d445c02015-02-09 13:03:50 -0500139 return (TestState *)SSL_get_ex_data(ssl, g_state_index);
David Benjamin83f90402015-01-27 01:09:43 -0500140}
141
David Benjamin2c516452016-11-15 10:16:54 +0900142static bool LoadCertificate(bssl::UniquePtr<X509> *out_x509,
143 bssl::UniquePtr<STACK_OF(X509)> *out_chain,
144 const std::string &file) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700145 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
David Benjaminacb6dcc2016-03-10 09:15:01 -0500146 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
David Benjamin2c516452016-11-15 10:16:54 +0900147 return false;
David Benjaminacb6dcc2016-03-10 09:15:01 -0500148 }
David Benjamin2c516452016-11-15 10:16:54 +0900149
150 out_x509->reset(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
151 if (!*out_x509) {
152 return false;
153 }
154
155 out_chain->reset(sk_X509_new_null());
156 if (!*out_chain) {
157 return false;
158 }
159
160 // Keep reading the certificate chain.
161 for (;;) {
162 bssl::UniquePtr<X509> cert(
163 PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
164 if (!cert) {
165 break;
166 }
167
168 if (!sk_X509_push(out_chain->get(), cert.get())) {
169 return false;
170 }
171 cert.release(); // sk_X509_push takes ownership.
172 }
173
174 uint32_t err = ERR_peek_last_error();
175 if (ERR_GET_LIB(err) != ERR_LIB_PEM ||
176 ERR_GET_REASON(err) != PEM_R_NO_START_LINE) {
177 return false;
178}
179
180 ERR_clear_error();
181 return true;
David Benjaminacb6dcc2016-03-10 09:15:01 -0500182}
183
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700184static bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
185 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
David Benjamina7f333d2015-02-09 02:37:18 -0500186 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
187 return nullptr;
David Benjamina08e49d2014-08-24 01:46:07 -0400188 }
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700189 return bssl::UniquePtr<EVP_PKEY>(
190 PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
David Benjamina08e49d2014-08-24 01:46:07 -0400191}
192
David Benjaminb4d65fd2015-05-29 17:11:21 -0400193static int AsyncPrivateKeyType(SSL *ssl) {
David Benjamin0c0b7e12016-07-14 13:47:55 -0400194 EVP_PKEY *key = GetTestState(ssl)->private_key.get();
195 switch (EVP_PKEY_id(key)) {
196 case EVP_PKEY_RSA:
197 return NID_rsaEncryption;
198 case EVP_PKEY_EC:
199 return EC_GROUP_get_curve_name(
200 EC_KEY_get0_group(EVP_PKEY_get0_EC_KEY(key)));
201 default:
202 return NID_undef;
203 }
David Benjaminb4d65fd2015-05-29 17:11:21 -0400204}
205
David Benjaminb4d65fd2015-05-29 17:11:21 -0400206static size_t AsyncPrivateKeyMaxSignatureLen(SSL *ssl) {
207 return EVP_PKEY_size(GetTestState(ssl)->private_key.get());
208}
209
210static ssl_private_key_result_t AsyncPrivateKeySign(
211 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
David Benjamind3440b42016-07-14 14:52:41 -0400212 uint16_t signature_algorithm, const uint8_t *in, size_t in_len) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400213 TestState *test_state = GetTestState(ssl);
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700214 if (!test_state->private_key_result.empty()) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400215 fprintf(stderr, "AsyncPrivateKeySign called with operation pending.\n");
216 abort();
217 }
218
David Benjamind3440b42016-07-14 14:52:41 -0400219 // Determine the hash.
220 const EVP_MD *md;
221 switch (signature_algorithm) {
222 case SSL_SIGN_RSA_PKCS1_SHA1:
223 case SSL_SIGN_ECDSA_SHA1:
224 md = EVP_sha1();
225 break;
226 case SSL_SIGN_RSA_PKCS1_SHA256:
227 case SSL_SIGN_ECDSA_SECP256R1_SHA256:
228 case SSL_SIGN_RSA_PSS_SHA256:
229 md = EVP_sha256();
230 break;
231 case SSL_SIGN_RSA_PKCS1_SHA384:
232 case SSL_SIGN_ECDSA_SECP384R1_SHA384:
233 case SSL_SIGN_RSA_PSS_SHA384:
234 md = EVP_sha384();
235 break;
236 case SSL_SIGN_RSA_PKCS1_SHA512:
237 case SSL_SIGN_ECDSA_SECP521R1_SHA512:
238 case SSL_SIGN_RSA_PSS_SHA512:
239 md = EVP_sha512();
240 break;
241 case SSL_SIGN_RSA_PKCS1_MD5_SHA1:
242 md = EVP_md5_sha1();
243 break;
244 default:
245 fprintf(stderr, "Unknown signature algorithm %04x.\n",
246 signature_algorithm);
247 return ssl_private_key_failure;
248 }
249
David Benjaminaac1e2d2016-12-06 22:35:41 -0500250 bssl::ScopedEVP_MD_CTX ctx;
David Benjamind3440b42016-07-14 14:52:41 -0400251 EVP_PKEY_CTX *pctx;
252 if (!EVP_DigestSignInit(ctx.get(), &pctx, md, nullptr,
253 test_state->private_key.get())) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400254 return ssl_private_key_failure;
255 }
256
David Benjamind3440b42016-07-14 14:52:41 -0400257 // Configure additional signature parameters.
258 switch (signature_algorithm) {
259 case SSL_SIGN_RSA_PSS_SHA256:
260 case SSL_SIGN_RSA_PSS_SHA384:
261 case SSL_SIGN_RSA_PSS_SHA512:
262 if (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) ||
263 !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
264 -1 /* salt len = hash len */)) {
265 return ssl_private_key_failure;
266 }
267 }
268
David Benjaminb4d65fd2015-05-29 17:11:21 -0400269 // Write the signature into |test_state|.
270 size_t len = 0;
David Benjamind3440b42016-07-14 14:52:41 -0400271 if (!EVP_DigestSignUpdate(ctx.get(), in, in_len) ||
272 !EVP_DigestSignFinal(ctx.get(), nullptr, &len)) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400273 return ssl_private_key_failure;
274 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700275 test_state->private_key_result.resize(len);
David Benjamind3440b42016-07-14 14:52:41 -0400276 if (!EVP_DigestSignFinal(ctx.get(), test_state->private_key_result.data(),
277 &len)) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400278 return ssl_private_key_failure;
279 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700280 test_state->private_key_result.resize(len);
David Benjaminb4d65fd2015-05-29 17:11:21 -0400281
David Benjamind3440b42016-07-14 14:52:41 -0400282 // The signature will be released asynchronously in |AsyncPrivateKeyComplete|.
David Benjaminb4d65fd2015-05-29 17:11:21 -0400283 return ssl_private_key_retry;
284}
285
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700286static ssl_private_key_result_t AsyncPrivateKeyDecrypt(
287 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
288 const uint8_t *in, size_t in_len) {
289 TestState *test_state = GetTestState(ssl);
290 if (!test_state->private_key_result.empty()) {
291 fprintf(stderr,
292 "AsyncPrivateKeyDecrypt called with operation pending.\n");
293 abort();
294 }
295
David Benjamin758d1272015-11-20 17:47:25 -0500296 RSA *rsa = EVP_PKEY_get0_RSA(test_state->private_key.get());
297 if (rsa == NULL) {
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700298 fprintf(stderr,
299 "AsyncPrivateKeyDecrypt called with incorrect key type.\n");
300 abort();
301 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700302 test_state->private_key_result.resize(RSA_size(rsa));
David Benjaminef14b2d2015-11-11 14:01:27 -0800303 if (!RSA_decrypt(rsa, out_len, test_state->private_key_result.data(),
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700304 RSA_size(rsa), in, in_len, RSA_NO_PADDING)) {
305 return ssl_private_key_failure;
306 }
307
308 test_state->private_key_result.resize(*out_len);
309
David Benjamind3440b42016-07-14 14:52:41 -0400310 // The decryption will be released asynchronously in |AsyncPrivateComplete|.
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700311 return ssl_private_key_retry;
312}
313
David Benjamind3440b42016-07-14 14:52:41 -0400314static ssl_private_key_result_t AsyncPrivateKeyComplete(
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700315 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
316 TestState *test_state = GetTestState(ssl);
317 if (test_state->private_key_result.empty()) {
318 fprintf(stderr,
David Benjamind3440b42016-07-14 14:52:41 -0400319 "AsyncPrivateKeyComplete called without operation pending.\n");
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700320 abort();
321 }
322
323 if (test_state->private_key_retries < 2) {
324 // Only return the decryption on the second attempt, to test both incomplete
325 // |decrypt| and |decrypt_complete|.
326 return ssl_private_key_retry;
327 }
328
329 if (max_out < test_state->private_key_result.size()) {
330 fprintf(stderr, "Output buffer too small.\n");
331 return ssl_private_key_failure;
332 }
David Benjamin17cf2cb2016-12-13 01:07:13 -0500333 OPENSSL_memcpy(out, test_state->private_key_result.data(),
334 test_state->private_key_result.size());
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700335 *out_len = test_state->private_key_result.size();
336
337 test_state->private_key_result.clear();
338 test_state->private_key_retries = 0;
David Benjaminb4d65fd2015-05-29 17:11:21 -0400339 return ssl_private_key_success;
340}
341
342static const SSL_PRIVATE_KEY_METHOD g_async_private_key_method = {
343 AsyncPrivateKeyType,
David Benjaminb4d65fd2015-05-29 17:11:21 -0400344 AsyncPrivateKeyMaxSignatureLen,
345 AsyncPrivateKeySign,
David Benjamind3440b42016-07-14 14:52:41 -0400346 nullptr /* sign_digest */,
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700347 AsyncPrivateKeyDecrypt,
David Benjamind3440b42016-07-14 14:52:41 -0400348 AsyncPrivateKeyComplete,
David Benjaminb4d65fd2015-05-29 17:11:21 -0400349};
350
Steven Valdez0d62f262015-09-04 12:41:04 -0400351template<typename T>
Adam Langley10f97f32016-07-12 08:09:33 -0700352struct Free {
Steven Valdez0d62f262015-09-04 12:41:04 -0400353 void operator()(T *buf) {
354 free(buf);
355 }
356};
357
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700358static bool GetCertificate(SSL *ssl, bssl::UniquePtr<X509> *out_x509,
David Benjamin2c516452016-11-15 10:16:54 +0900359 bssl::UniquePtr<STACK_OF(X509)> *out_chain,
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700360 bssl::UniquePtr<EVP_PKEY> *out_pkey) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400361 const TestConfig *config = GetTestConfig(ssl);
Steven Valdez0d62f262015-09-04 12:41:04 -0400362
363 if (!config->digest_prefs.empty()) {
Adam Langley10f97f32016-07-12 08:09:33 -0700364 std::unique_ptr<char, Free<char>> digest_prefs(
Steven Valdez0d62f262015-09-04 12:41:04 -0400365 strdup(config->digest_prefs.c_str()));
Steven Valdez0d62f262015-09-04 12:41:04 -0400366 std::vector<int> digest_list;
367
368 for (;;) {
Adam Langley67251f22015-09-23 15:01:07 -0700369 char *token =
370 strtok(digest_list.empty() ? digest_prefs.get() : nullptr, ",");
Steven Valdez0d62f262015-09-04 12:41:04 -0400371 if (token == nullptr) {
372 break;
373 }
374
375 digest_list.push_back(EVP_MD_type(EVP_get_digestbyname(token)));
376 }
377
378 if (!SSL_set_private_key_digest_prefs(ssl, digest_list.data(),
379 digest_list.size())) {
380 return false;
381 }
382 }
383
David Benjaminca3d5452016-07-14 12:51:01 -0400384 if (!config->signing_prefs.empty()) {
385 std::vector<uint16_t> u16s(config->signing_prefs.begin(),
386 config->signing_prefs.end());
387 if (!SSL_set_signing_algorithm_prefs(ssl, u16s.data(), u16s.size())) {
388 return false;
389 }
390 }
391
David Benjaminb4d65fd2015-05-29 17:11:21 -0400392 if (!config->key_file.empty()) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500393 *out_pkey = LoadPrivateKey(config->key_file.c_str());
394 if (!*out_pkey) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400395 return false;
396 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500397 }
David Benjamin2c516452016-11-15 10:16:54 +0900398 if (!config->cert_file.empty() &&
399 !LoadCertificate(out_x509, out_chain, config->cert_file.c_str())) {
400 return false;
David Benjamin41fdbcd2015-02-09 03:13:35 -0500401 }
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100402 if (!config->ocsp_response.empty() &&
Alessandro Ghedini559f0642016-12-07 12:55:32 +0000403 !SSL_set_ocsp_response(ssl, (const uint8_t *)config->ocsp_response.data(),
404 config->ocsp_response.size())) {
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100405 return false;
406 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500407 return true;
408}
409
David Benjaminacb6dcc2016-03-10 09:15:01 -0500410static bool InstallCertificate(SSL *ssl) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700411 bssl::UniquePtr<X509> x509;
David Benjamin2c516452016-11-15 10:16:54 +0900412 bssl::UniquePtr<STACK_OF(X509)> chain;
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700413 bssl::UniquePtr<EVP_PKEY> pkey;
David Benjamin2c516452016-11-15 10:16:54 +0900414 if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500415 return false;
416 }
417
418 if (pkey) {
419 TestState *test_state = GetTestState(ssl);
David Benjamin7e7a82d2016-05-20 20:12:42 -0400420 const TestConfig *config = GetTestConfig(ssl);
David Benjaminacb6dcc2016-03-10 09:15:01 -0500421 if (config->async) {
422 test_state->private_key = std::move(pkey);
423 SSL_set_private_key_method(ssl, &g_async_private_key_method);
424 } else if (!SSL_use_PrivateKey(ssl, pkey.get())) {
425 return false;
426 }
427 }
428
429 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
430 return false;
431 }
432
David Benjamin2c516452016-11-15 10:16:54 +0900433 if (sk_X509_num(chain.get()) > 0 &&
434 !SSL_set1_chain(ssl, chain.get())) {
435 return false;
436 }
437
David Benjaminacb6dcc2016-03-10 09:15:01 -0500438 return true;
439}
440
David Benjamin731058e2016-12-03 23:15:13 -0500441static int SelectCertificateCallback(const SSL_CLIENT_HELLO *client_hello) {
442 const TestConfig *config = GetTestConfig(client_hello->ssl);
443 GetTestState(client_hello->ssl)->early_callback_called = true;
David Benjamin5a593af2014-08-11 19:51:50 -0400444
David Benjamin6f5c0f42015-02-24 01:23:21 -0500445 if (!config->expected_server_name.empty()) {
446 const uint8_t *extension_data;
447 size_t extension_len;
448 CBS extension, server_name_list, host_name;
449 uint8_t name_type;
450
David Benjamin731058e2016-12-03 23:15:13 -0500451 if (!SSL_early_callback_ctx_extension_get(
452 client_hello, TLSEXT_TYPE_server_name, &extension_data,
453 &extension_len)) {
David Benjamin6f5c0f42015-02-24 01:23:21 -0500454 fprintf(stderr, "Could not find server_name extension.\n");
455 return -1;
456 }
457
458 CBS_init(&extension, extension_data, extension_len);
459 if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
460 CBS_len(&extension) != 0 ||
461 !CBS_get_u8(&server_name_list, &name_type) ||
462 name_type != TLSEXT_NAMETYPE_host_name ||
463 !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
464 CBS_len(&server_name_list) != 0) {
465 fprintf(stderr, "Could not decode server_name extension.\n");
466 return -1;
467 }
468
469 if (!CBS_mem_equal(&host_name,
470 (const uint8_t*)config->expected_server_name.data(),
471 config->expected_server_name.size())) {
472 fprintf(stderr, "Server name mismatch.\n");
473 }
David Benjamin7b030512014-07-08 17:30:11 -0400474 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400475
David Benjamin6f5c0f42015-02-24 01:23:21 -0500476 if (config->fail_early_callback) {
David Benjamin7b030512014-07-08 17:30:11 -0400477 return -1;
478 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400479
David Benjamin6f5c0f42015-02-24 01:23:21 -0500480 // Install the certificate in the early callback.
481 if (config->use_early_callback) {
482 if (config->async) {
483 // Install the certificate asynchronously.
484 return 0;
485 }
David Benjamin731058e2016-12-03 23:15:13 -0500486 if (!InstallCertificate(client_hello->ssl)) {
David Benjamin6f5c0f42015-02-24 01:23:21 -0500487 return -1;
488 }
David Benjamin7b030512014-07-08 17:30:11 -0400489 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400490 return 1;
491}
David Benjamin025b3d32014-07-01 19:53:04 -0400492
David Benjamin5edfc8c2016-12-10 15:46:58 -0500493static bool CheckCertificateRequest(SSL *ssl) {
494 const TestConfig *config = GetTestConfig(ssl);
495
496 if (!config->expected_certificate_types.empty()) {
497 const uint8_t *certificate_types;
498 size_t certificate_types_len =
499 SSL_get0_certificate_types(ssl, &certificate_types);
500 if (certificate_types_len != config->expected_certificate_types.size() ||
David Benjamin17cf2cb2016-12-13 01:07:13 -0500501 OPENSSL_memcmp(certificate_types,
502 config->expected_certificate_types.data(),
503 certificate_types_len) != 0) {
David Benjamin5edfc8c2016-12-10 15:46:58 -0500504 fprintf(stderr, "certificate types mismatch\n");
505 return false;
506 }
507 }
508
509 // TODO(davidben): Test |SSL_get_client_CA_list|.
510 return true;
511}
512
David Benjaminacb6dcc2016-03-10 09:15:01 -0500513static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
David Benjamin5edfc8c2016-12-10 15:46:58 -0500514 if (!CheckCertificateRequest(ssl)) {
515 return -1;
516 }
517
David Benjamin7e7a82d2016-05-20 20:12:42 -0400518 if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500519 return -1;
520 }
521
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700522 bssl::UniquePtr<X509> x509;
David Benjamin2c516452016-11-15 10:16:54 +0900523 bssl::UniquePtr<STACK_OF(X509)> chain;
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700524 bssl::UniquePtr<EVP_PKEY> pkey;
David Benjamin2c516452016-11-15 10:16:54 +0900525 if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500526 return -1;
527 }
528
529 // Return zero for no certificate.
530 if (!x509) {
531 return 0;
532 }
533
David Benjamin2c516452016-11-15 10:16:54 +0900534 // Chains and asynchronous private keys are not supported with client_cert_cb.
David Benjaminacb6dcc2016-03-10 09:15:01 -0500535 *out_x509 = x509.release();
536 *out_pkey = pkey.release();
537 return 1;
538}
539
David Benjamin5edfc8c2016-12-10 15:46:58 -0500540static int CertCallback(SSL *ssl, void *arg) {
541 const TestConfig *config = GetTestConfig(ssl);
542
543 // Check the CertificateRequest metadata is as expected.
544 if (!SSL_is_server(ssl) && !CheckCertificateRequest(ssl)) {
545 return -1;
546 }
547
548 if (config->fail_cert_callback) {
549 return 0;
550 }
551
552 // The certificate will be installed via other means.
553 if (!config->async || config->use_early_callback) {
554 return 1;
555 }
556
557 if (!GetTestState(ssl)->cert_ready) {
558 return -1;
559 }
560 if (!InstallCertificate(ssl)) {
561 return 0;
562 }
563 return 1;
564}
565
Paul Lietar8f1c2682015-08-18 12:21:54 +0100566static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
567 SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data(store_ctx,
568 SSL_get_ex_data_X509_STORE_CTX_idx());
David Benjamin7e7a82d2016-05-20 20:12:42 -0400569 const TestConfig *config = GetTestConfig(ssl);
Paul Lietar8f1c2682015-08-18 12:21:54 +0100570
571 if (!config->expected_ocsp_response.empty()) {
572 const uint8_t *data;
573 size_t len;
574 SSL_get0_ocsp_response(ssl, &data, &len);
575 if (len == 0) {
576 fprintf(stderr, "OCSP response not available in verify callback\n");
577 return 0;
578 }
579 }
580
David Benjamin67666e72014-07-12 15:47:52 -0400581 return 1;
582}
583
Paul Lietar8f1c2682015-08-18 12:21:54 +0100584static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
585 store_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION;
586 return 0;
587}
588
David Benjaminc273d2c2015-02-09 12:59:46 -0500589static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
590 unsigned int *out_len, void *arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400591 const TestConfig *config = GetTestConfig(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500592 if (config->advertise_npn.empty()) {
David Benjamin1f5f62b2014-07-12 16:18:02 -0400593 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500594 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400595
David Benjamin5a593af2014-08-11 19:51:50 -0400596 *out = (const uint8_t*)config->advertise_npn.data();
597 *out_len = config->advertise_npn.size();
David Benjamin1f5f62b2014-07-12 16:18:02 -0400598 return SSL_TLSEXT_ERR_OK;
599}
600
David Benjaminc273d2c2015-02-09 12:59:46 -0500601static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
David Benjamin8b368412015-03-14 01:54:17 -0400602 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400603 const TestConfig *config = GetTestConfig(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500604 if (config->select_next_proto.empty()) {
David Benjamin7e3305e2014-07-28 14:52:32 -0400605 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500606 }
David Benjamin7e3305e2014-07-28 14:52:32 -0400607
David Benjamin5a593af2014-08-11 19:51:50 -0400608 *out = (uint8_t*)config->select_next_proto.data();
609 *outlen = config->select_next_proto.size();
David Benjamin7e3305e2014-07-28 14:52:32 -0400610 return SSL_TLSEXT_ERR_OK;
611}
612
David Benjaminc273d2c2015-02-09 12:59:46 -0500613static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
614 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin25fe85b2016-08-09 20:00:32 -0400615 if (GetTestState(ssl)->alpn_select_done) {
616 fprintf(stderr, "AlpnSelectCallback called after completion.\n");
617 exit(1);
618 }
619
620 GetTestState(ssl)->alpn_select_done = true;
621
David Benjamin7e7a82d2016-05-20 20:12:42 -0400622 const TestConfig *config = GetTestConfig(ssl);
David Benjamin594e7d22016-03-17 17:49:56 -0400623 if (config->decline_alpn) {
David Benjaminae2888f2014-09-06 12:58:58 -0400624 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500625 }
David Benjaminae2888f2014-09-06 12:58:58 -0400626
627 if (!config->expected_advertised_alpn.empty() &&
628 (config->expected_advertised_alpn.size() != inlen ||
David Benjamin17cf2cb2016-12-13 01:07:13 -0500629 OPENSSL_memcmp(config->expected_advertised_alpn.data(), in, inlen) !=
630 0)) {
David Benjaminae2888f2014-09-06 12:58:58 -0400631 fprintf(stderr, "bad ALPN select callback inputs\n");
632 exit(1);
633 }
634
635 *out = (const uint8_t*)config->select_alpn.data();
636 *outlen = config->select_alpn.size();
637 return SSL_TLSEXT_ERR_OK;
638}
639
David Benjaminc273d2c2015-02-09 12:59:46 -0500640static unsigned PskClientCallback(SSL *ssl, const char *hint,
641 char *out_identity,
642 unsigned max_identity_len,
643 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400644 const TestConfig *config = GetTestConfig(ssl);
David Benjamin48cae082014-10-27 01:06:24 -0400645
David Benjamin78679342016-09-16 19:42:05 -0400646 if (config->psk_identity.empty()) {
647 if (hint != nullptr) {
648 fprintf(stderr, "Server PSK hint was non-null.\n");
649 return 0;
650 }
651 } else if (hint == nullptr ||
652 strcmp(hint, config->psk_identity.c_str()) != 0) {
David Benjamin48cae082014-10-27 01:06:24 -0400653 fprintf(stderr, "Server PSK hint did not match.\n");
654 return 0;
655 }
656
657 // Account for the trailing '\0' for the identity.
658 if (config->psk_identity.size() >= max_identity_len ||
659 config->psk.size() > max_psk_len) {
660 fprintf(stderr, "PSK buffers too small\n");
661 return 0;
662 }
663
664 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
665 max_identity_len);
David Benjamin17cf2cb2016-12-13 01:07:13 -0500666 OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size());
David Benjamin48cae082014-10-27 01:06:24 -0400667 return config->psk.size();
668}
669
David Benjaminc273d2c2015-02-09 12:59:46 -0500670static unsigned PskServerCallback(SSL *ssl, const char *identity,
671 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400672 const TestConfig *config = GetTestConfig(ssl);
David Benjamin48cae082014-10-27 01:06:24 -0400673
674 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
675 fprintf(stderr, "Client PSK identity did not match.\n");
676 return 0;
677 }
678
679 if (config->psk.size() > max_psk_len) {
680 fprintf(stderr, "PSK buffers too small\n");
681 return 0;
682 }
683
David Benjamin17cf2cb2016-12-13 01:07:13 -0500684 OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size());
David Benjamin48cae082014-10-27 01:06:24 -0400685 return config->psk.size();
686}
687
David Benjamin1b22f852016-10-27 16:36:32 -0400688static timeval g_clock;
689
David Benjamin4d2e7ce2015-05-08 13:29:45 -0400690static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
David Benjamin1b22f852016-10-27 16:36:32 -0400691 *out_clock = g_clock;
David Benjamin377fc312015-01-26 00:22:12 -0500692}
693
David Benjaminc273d2c2015-02-09 12:59:46 -0500694static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
David Benjamin2d445c02015-02-09 13:03:50 -0500695 *out_pkey = GetTestState(ssl)->channel_id.release();
David Benjamind9e07012015-02-09 03:04:34 -0500696}
697
David Benjaminc273d2c2015-02-09 12:59:46 -0500698static SSL_SESSION *GetSessionCallback(SSL *ssl, uint8_t *data, int len,
699 int *copy) {
David Benjamin2d445c02015-02-09 13:03:50 -0500700 TestState *async_state = GetTestState(ssl);
David Benjamin1b8b6912015-02-09 04:28:16 -0500701 if (async_state->session) {
702 *copy = 0;
703 return async_state->session.release();
704 } else if (async_state->pending_session) {
705 return SSL_magic_pending_session_ptr();
706 } else {
707 return NULL;
708 }
709}
710
David Benjamin731058e2016-12-03 23:15:13 -0500711static int DDoSCallback(const SSL_CLIENT_HELLO *client_hello) {
712 const TestConfig *config = GetTestConfig(client_hello->ssl);
Adam Langley524e7172015-02-20 16:04:00 -0800713 static int callback_num = 0;
714
715 callback_num++;
716 if (config->fail_ddos_callback ||
717 (config->fail_second_ddos_callback && callback_num == 2)) {
718 return 0;
719 }
720 return 1;
721}
722
David Benjamin87e4acd2015-04-02 19:57:35 -0400723static void InfoCallback(const SSL *ssl, int type, int val) {
724 if (type == SSL_CB_HANDSHAKE_DONE) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400725 if (GetTestConfig(ssl)->handshake_never_done) {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400726 fprintf(stderr, "Handshake unexpectedly completed.\n");
David Benjamin87e4acd2015-04-02 19:57:35 -0400727 // Abort before any expected error code is printed, to ensure the overall
728 // test fails.
729 abort();
730 }
731 GetTestState(ssl)->handshake_done = true;
David Benjamin25fe85b2016-08-09 20:00:32 -0400732
733 // Callbacks may be called again on a new handshake.
734 GetTestState(ssl)->ticket_decrypt_done = false;
735 GetTestState(ssl)->alpn_select_done = false;
David Benjamin87e4acd2015-04-02 19:57:35 -0400736 }
737}
738
David Benjaminba4594a2015-06-18 18:36:15 -0400739static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
740 GetTestState(ssl)->got_new_session = true;
Steven Valdez4aa154e2016-07-29 14:32:55 -0400741 GetTestState(ssl)->new_session.reset(session);
David Benjaminba4594a2015-06-18 18:36:15 -0400742 return 1;
743}
744
David Benjamind98452d2015-06-16 14:16:23 -0400745static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
746 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
747 int encrypt) {
David Benjamin25fe85b2016-08-09 20:00:32 -0400748 if (!encrypt) {
749 if (GetTestState(ssl)->ticket_decrypt_done) {
750 fprintf(stderr, "TicketKeyCallback called after completion.\n");
751 return -1;
752 }
753
754 GetTestState(ssl)->ticket_decrypt_done = true;
755 }
756
David Benjamind98452d2015-06-16 14:16:23 -0400757 // This is just test code, so use the all-zeros key.
758 static const uint8_t kZeros[16] = {0};
759
760 if (encrypt) {
David Benjamin17cf2cb2016-12-13 01:07:13 -0500761 OPENSSL_memcpy(key_name, kZeros, sizeof(kZeros));
David Benjamind98452d2015-06-16 14:16:23 -0400762 RAND_bytes(iv, 16);
David Benjamin17cf2cb2016-12-13 01:07:13 -0500763 } else if (OPENSSL_memcmp(key_name, kZeros, 16) != 0) {
David Benjamind98452d2015-06-16 14:16:23 -0400764 return 0;
765 }
766
767 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
768 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
769 return -1;
770 }
771
772 if (!encrypt) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400773 return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
David Benjamind98452d2015-06-16 14:16:23 -0400774 }
775 return 1;
776}
777
Adam Langley09505632015-07-30 18:10:13 -0700778// kCustomExtensionValue is the extension value that the custom extension
779// callbacks will add.
Adam Langleyc5b23a12015-07-30 18:19:26 -0700780static const uint16_t kCustomExtensionValue = 1234;
Adam Langley09505632015-07-30 18:10:13 -0700781static void *const kCustomExtensionAddArg =
782 reinterpret_cast<void *>(kCustomExtensionValue);
783static void *const kCustomExtensionParseArg =
784 reinterpret_cast<void *>(kCustomExtensionValue + 1);
785static const char kCustomExtensionContents[] = "custom extension";
786
787static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
788 const uint8_t **out, size_t *out_len,
789 int *out_alert_value, void *add_arg) {
790 if (extension_value != kCustomExtensionValue ||
791 add_arg != kCustomExtensionAddArg) {
792 abort();
793 }
794
David Benjamin7e7a82d2016-05-20 20:12:42 -0400795 if (GetTestConfig(ssl)->custom_extension_skip) {
Adam Langley09505632015-07-30 18:10:13 -0700796 return 0;
797 }
David Benjamin7e7a82d2016-05-20 20:12:42 -0400798 if (GetTestConfig(ssl)->custom_extension_fail_add) {
Adam Langley09505632015-07-30 18:10:13 -0700799 return -1;
800 }
801
802 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
803 *out_len = sizeof(kCustomExtensionContents) - 1;
804
805 return 1;
806}
807
808static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
809 const uint8_t *out, void *add_arg) {
810 if (extension_value != kCustomExtensionValue ||
811 add_arg != kCustomExtensionAddArg ||
812 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
813 abort();
814 }
815}
816
817static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
818 const uint8_t *contents,
819 size_t contents_len,
820 int *out_alert_value, void *parse_arg) {
821 if (extension_value != kCustomExtensionValue ||
822 parse_arg != kCustomExtensionParseArg) {
823 abort();
824 }
825
826 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
David Benjamin17cf2cb2016-12-13 01:07:13 -0500827 OPENSSL_memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
Adam Langley09505632015-07-30 18:10:13 -0700828 *out_alert_value = SSL_AD_DECODE_ERROR;
829 return 0;
830 }
831
832 return 1;
833}
834
David Benjamin8b176712016-10-27 21:51:24 -0400835static int ServerNameCallback(SSL *ssl, int *out_alert, void *arg) {
836 // SNI must be accessible from the SNI callback.
837 const TestConfig *config = GetTestConfig(ssl);
838 const char *server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
839 if (server_name == nullptr ||
840 std::string(server_name) != config->expected_server_name) {
841 fprintf(stderr, "servername mismatch (got %s; want %s)\n", server_name,
842 config->expected_server_name.c_str());
843 return SSL_TLSEXT_ERR_ALERT_FATAL;
844 }
845
846 return SSL_TLSEXT_ERR_OK;
847}
848
David Benjamin87c8a642015-02-21 01:54:29 -0500849// Connect returns a new socket connected to localhost on |port| or -1 on
850// error.
851static int Connect(uint16_t port) {
852 int sock = socket(AF_INET, SOCK_STREAM, 0);
853 if (sock == -1) {
854 PrintSocketError("socket");
855 return -1;
856 }
857 int nodelay = 1;
858 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
859 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
860 PrintSocketError("setsockopt");
861 closesocket(sock);
862 return -1;
863 }
864 sockaddr_in sin;
David Benjamin17cf2cb2016-12-13 01:07:13 -0500865 OPENSSL_memset(&sin, 0, sizeof(sin));
David Benjamin87c8a642015-02-21 01:54:29 -0500866 sin.sin_family = AF_INET;
867 sin.sin_port = htons(port);
868 if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
869 PrintSocketError("inet_pton");
870 closesocket(sock);
871 return -1;
872 }
873 if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
874 sizeof(sin)) != 0) {
875 PrintSocketError("connect");
876 closesocket(sock);
877 return -1;
878 }
879 return sock;
880}
881
882class SocketCloser {
883 public:
884 explicit SocketCloser(int sock) : sock_(sock) {}
885 ~SocketCloser() {
886 // Half-close and drain the socket before releasing it. This seems to be
887 // necessary for graceful shutdown on Windows. It will also avoid write
888 // failures in the test runner.
889#if defined(OPENSSL_WINDOWS)
890 shutdown(sock_, SD_SEND);
891#else
892 shutdown(sock_, SHUT_WR);
893#endif
894 while (true) {
895 char buf[1024];
896 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
897 break;
898 }
899 }
900 closesocket(sock_);
901 }
902
903 private:
904 const int sock_;
905};
906
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700907static bssl::UniquePtr<SSL_CTX> SetupCtx(const TestConfig *config) {
908 bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(
David Benjamina7f333d2015-02-09 02:37:18 -0500909 config->is_dtls ? DTLS_method() : TLS_method()));
910 if (!ssl_ctx) {
911 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -0400912 }
913
Adam Langleyd519bf62016-12-12 11:16:44 -0800914 SSL_CTX_set0_buffer_pool(ssl_ctx.get(), g_pool);
915
David Benjamin2dc02042016-09-19 19:57:37 -0400916 // Enable TLS 1.3 for tests.
917 if (!config->is_dtls &&
David Benjamine4706902016-09-20 15:12:23 -0400918 !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION)) {
David Benjamin2dc02042016-09-19 19:57:37 -0400919 return nullptr;
Nick Harper1fd39d82016-06-14 18:14:35 -0700920 }
921
Adam Langleycef75832015-09-03 14:51:12 -0700922 std::string cipher_list = "ALL";
923 if (!config->cipher.empty()) {
924 cipher_list = config->cipher;
925 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
926 }
927 if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
928 return nullptr;
929 }
930
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700931 bssl::UniquePtr<DH> dh(DH_get_2048_256(NULL));
David Benjaminb7c5e842016-03-28 09:59:10 -0400932 if (!dh) {
933 return nullptr;
934 }
Adam Langleyc4f25ce2015-11-26 16:39:08 -0800935
936 if (config->use_sparse_dh_prime) {
937 // This prime number is 2^1024 + 643 – a value just above a power of two.
938 // Because of its form, values modulo it are essentially certain to be one
939 // byte shorter. This is used to test padding of these values.
940 if (BN_hex2bn(
941 &dh->p,
942 "1000000000000000000000000000000000000000000000000000000000000000"
943 "0000000000000000000000000000000000000000000000000000000000000000"
944 "0000000000000000000000000000000000000000000000000000000000000000"
945 "0000000000000000000000000000000000000000000000000000000000000028"
946 "3") == 0 ||
947 !BN_set_word(dh->g, 2)) {
948 return nullptr;
949 }
David Benjamine66148a2016-02-02 14:14:36 -0500950 BN_free(dh->q);
951 dh->q = NULL;
Adam Langleyc4f25ce2015-11-26 16:39:08 -0800952 dh->priv_length = 0;
953 }
954
David Benjaminb7c5e842016-03-28 09:59:10 -0400955 if (!SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
David Benjamina7f333d2015-02-09 02:37:18 -0500956 return nullptr;
David Benjaminf4e5c4e2014-08-02 17:35:45 -0400957 }
958
David Benjamin1b8b6912015-02-09 04:28:16 -0500959 if (config->async && config->is_server) {
960 // Disable the internal session cache. To test asynchronous session lookup,
961 // we use an external session cache.
962 SSL_CTX_set_session_cache_mode(
963 ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
David Benjaminc273d2c2015-02-09 12:59:46 -0500964 SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
David Benjamin1b8b6912015-02-09 04:28:16 -0500965 } else {
966 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
967 }
David Benjamin1d5c83e2014-07-22 19:20:02 -0400968
David Benjamind4c2bce2015-10-17 12:28:18 -0400969 SSL_CTX_set_select_certificate_cb(ssl_ctx.get(), SelectCertificateCallback);
David Benjamin8f2c20e2014-07-09 09:30:38 -0400970
David Benjaminacb6dcc2016-03-10 09:15:01 -0500971 if (config->use_old_client_cert_callback) {
972 SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
973 }
974
David Benjamin1f5f62b2014-07-12 16:18:02 -0400975 SSL_CTX_set_next_protos_advertised_cb(
David Benjaminc273d2c2015-02-09 12:59:46 -0500976 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400977 if (!config->select_next_proto.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500978 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
David Benjamina7f333d2015-02-09 02:37:18 -0500979 NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400980 }
981
David Benjamin594e7d22016-03-17 17:49:56 -0400982 if (!config->select_alpn.empty() || config->decline_alpn) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500983 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400984 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400985
David Benjaminc273d2c2015-02-09 12:59:46 -0500986 SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
David Benjamina08e49d2014-08-24 01:46:07 -0400987
David Benjamin1b22f852016-10-27 16:36:32 -0400988 SSL_CTX_set_current_time_cb(ssl_ctx.get(), CurrentTimeCallback);
David Benjamin377fc312015-01-26 00:22:12 -0500989
David Benjamin87e4acd2015-04-02 19:57:35 -0400990 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
David Benjaminba4594a2015-06-18 18:36:15 -0400991 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
David Benjamin87e4acd2015-04-02 19:57:35 -0400992
David Benjamind98452d2015-06-16 14:16:23 -0400993 if (config->use_ticket_callback) {
994 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
995 }
996
Adam Langley09505632015-07-30 18:10:13 -0700997 if (config->enable_client_custom_extension &&
998 !SSL_CTX_add_client_custom_ext(
999 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
1000 CustomExtensionFreeCallback, kCustomExtensionAddArg,
1001 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1002 return nullptr;
1003 }
1004
1005 if (config->enable_server_custom_extension &&
1006 !SSL_CTX_add_server_custom_ext(
1007 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
1008 CustomExtensionFreeCallback, kCustomExtensionAddArg,
1009 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1010 return nullptr;
1011 }
1012
Paul Lietar8f1c2682015-08-18 12:21:54 +01001013 if (config->verify_fail) {
1014 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
1015 } else {
1016 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
1017 }
1018
Paul Lietar4fac72e2015-09-09 13:44:55 +01001019 if (!config->signed_cert_timestamps.empty() &&
1020 !SSL_CTX_set_signed_cert_timestamp_list(
1021 ssl_ctx.get(), (const uint8_t *)config->signed_cert_timestamps.data(),
1022 config->signed_cert_timestamps.size())) {
1023 return nullptr;
1024 }
1025
David Benjamin2f8935d2016-07-13 19:47:39 -04001026 if (config->use_null_client_ca_list) {
1027 SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
1028 }
1029
David Benjamin65ac9972016-09-02 21:35:25 -04001030 if (config->enable_grease) {
1031 SSL_CTX_set_grease_enabled(ssl_ctx.get(), 1);
1032 }
1033
David Benjamin8b176712016-10-27 21:51:24 -04001034 if (!config->expected_server_name.empty()) {
1035 SSL_CTX_set_tlsext_servername_callback(ssl_ctx.get(), ServerNameCallback);
1036 }
1037
David Benjamin4199b0d2016-11-01 13:58:25 -04001038 if (!config->ticket_key.empty() &&
1039 !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), config->ticket_key.data(),
1040 config->ticket_key.size())) {
1041 return nullptr;
1042 }
1043
David Benjamin6f600d62016-12-21 16:06:54 -05001044 if (config->enable_short_header) {
1045 SSL_CTX_set_short_header_enabled(ssl_ctx.get(), 1);
1046 }
1047
Steven Valdez08b65f42016-12-07 15:29:45 -05001048 if (config->enable_early_data) {
1049 SSL_CTX_set_early_data_enabled(ssl_ctx.get(), 1);
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 ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001153 OPENSSL_memcmp(buf.get(), out, ret) != 0) {
David Benjaminf3fbade2016-09-19 13:08:16 -04001154 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 ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001161 OPENSSL_memcmp(buf.get(), out, ret) != 0) {
David Benjaminf3fbade2016-09-19 13:08:16 -04001162 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() ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001275 OPENSSL_memcmp(next_proto, config->expected_next_proto.data(),
1276 next_proto_len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001277 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() ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001287 OPENSSL_memcmp(alpn_proto, config->expected_alpn.data(),
1288 alpn_proto_len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001289 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 ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001301 OPENSSL_memcmp(config->expected_channel_id.data(), channel_id, 64) !=
1302 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001303 fprintf(stderr, "channel id mismatch\n");
1304 return false;
1305 }
1306 }
1307
David Benjamind2610042017-01-03 10:49:28 -05001308 if (config->expect_extended_master_secret && !SSL_get_extms_support(ssl)) {
1309 fprintf(stderr, "No EMS for connection when expected\n");
1310 return false;
1311 }
1312
1313 if (config->expect_secure_renegotiation &&
1314 !SSL_get_secure_renegotiation_support(ssl)) {
1315 fprintf(stderr, "No secure renegotiation for connection when expected\n");
1316 return false;
1317 }
1318
1319 if (config->expect_no_secure_renegotiation &&
1320 SSL_get_secure_renegotiation_support(ssl)) {
1321 fprintf(stderr,
1322 "Secure renegotiation unexpectedly negotiated for connection\n");
1323 return false;
David Benjamin91eab5c2015-06-18 18:35:46 -04001324 }
1325
1326 if (!config->expected_ocsp_response.empty()) {
1327 const uint8_t *data;
1328 size_t len;
1329 SSL_get0_ocsp_response(ssl, &data, &len);
1330 if (config->expected_ocsp_response.size() != len ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001331 OPENSSL_memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001332 fprintf(stderr, "OCSP response mismatch\n");
1333 return false;
1334 }
1335 }
1336
1337 if (!config->expected_signed_cert_timestamps.empty()) {
1338 const uint8_t *data;
1339 size_t len;
1340 SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
1341 if (config->expected_signed_cert_timestamps.size() != len ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001342 OPENSSL_memcmp(config->expected_signed_cert_timestamps.data(), data,
1343 len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001344 fprintf(stderr, "SCT list mismatch\n");
1345 return false;
1346 }
1347 }
1348
Paul Lietar8f1c2682015-08-18 12:21:54 +01001349 if (config->expect_verify_result) {
1350 int expected_verify_result = config->verify_fail ?
1351 X509_V_ERR_APPLICATION_VERIFICATION :
1352 X509_V_OK;
1353
1354 if (SSL_get_verify_result(ssl) != expected_verify_result) {
1355 fprintf(stderr, "Wrong certificate verification result\n");
1356 return false;
1357 }
1358 }
1359
Nick Harper60edffd2016-06-21 15:19:24 -07001360 if (config->expect_peer_signature_algorithm != 0 &&
1361 config->expect_peer_signature_algorithm !=
1362 SSL_get_peer_signature_algorithm(ssl)) {
1363 fprintf(stderr, "Peer signature algorithm was %04x, wanted %04x.\n",
1364 SSL_get_peer_signature_algorithm(ssl),
1365 config->expect_peer_signature_algorithm);
David Benjamin6e807652015-11-02 12:02:20 -05001366 return false;
1367 }
1368
David Benjamin8a55ce42016-12-11 03:03:42 -05001369 int expect_curve_id = config->expect_curve_id;
1370 if (is_resume && config->expect_resume_curve_id != 0) {
1371 expect_curve_id = config->expect_resume_curve_id;
1372 }
1373 if (expect_curve_id != 0) {
David Benjamin9e68f192016-06-30 14:55:33 -04001374 uint16_t curve_id = SSL_get_curve_id(ssl);
David Benjamin8a55ce42016-12-11 03:03:42 -05001375 if (static_cast<uint16_t>(expect_curve_id) != curve_id) {
David Benjamin9e68f192016-06-30 14:55:33 -04001376 fprintf(stderr, "curve_id was %04x, wanted %04x\n", curve_id,
David Benjamin8a55ce42016-12-11 03:03:42 -05001377 static_cast<uint16_t>(expect_curve_id));
David Benjamin9e68f192016-06-30 14:55:33 -04001378 return false;
1379 }
1380 }
1381
David Benjaminabbbee12016-10-31 19:20:42 -04001382 uint16_t cipher_id =
1383 static_cast<uint16_t>(SSL_CIPHER_get_id(SSL_get_current_cipher(ssl)));
1384 if (config->expect_cipher_aes != 0 &&
1385 EVP_has_aes_hardware() &&
1386 static_cast<uint16_t>(config->expect_cipher_aes) != cipher_id) {
1387 fprintf(stderr, "Cipher ID was %04x, wanted %04x (has AES hardware)\n",
1388 cipher_id, static_cast<uint16_t>(config->expect_cipher_aes));
1389 return false;
1390 }
1391
1392 if (config->expect_cipher_no_aes != 0 &&
1393 !EVP_has_aes_hardware() &&
1394 static_cast<uint16_t>(config->expect_cipher_no_aes) != cipher_id) {
1395 fprintf(stderr, "Cipher ID was %04x, wanted %04x (no AES hardware)\n",
1396 cipher_id, static_cast<uint16_t>(config->expect_cipher_no_aes));
1397 return false;
1398 }
1399
1400
David Benjaminbb9e36e2016-08-03 14:14:47 -04001401 if (!config->psk.empty()) {
1402 if (SSL_get_peer_cert_chain(ssl) != nullptr) {
1403 fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
1404 return false;
1405 }
1406 } else if (!config->is_server || config->require_any_client_certificate) {
1407 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
1408 fprintf(stderr, "Received no peer certificate but expected one.\n");
David Benjamin91eab5c2015-06-18 18:35:46 -04001409 return false;
1410 }
1411 }
David Benjaminbb9e36e2016-08-03 14:14:47 -04001412
David Benjamin2c516452016-11-15 10:16:54 +09001413 if (!config->expect_peer_cert_file.empty()) {
1414 bssl::UniquePtr<X509> expect_leaf;
1415 bssl::UniquePtr<STACK_OF(X509)> expect_chain;
1416 if (!LoadCertificate(&expect_leaf, &expect_chain,
1417 config->expect_peer_cert_file)) {
1418 return false;
1419 }
1420
1421 // For historical reasons, clients report a chain with a leaf and servers
1422 // without.
1423 if (!config->is_server) {
1424 if (!sk_X509_insert(expect_chain.get(), expect_leaf.get(), 0)) {
1425 return false;
1426 }
1427 X509_up_ref(expect_leaf.get()); // sk_X509_push takes ownership.
1428 }
1429
1430 bssl::UniquePtr<X509> leaf(SSL_get_peer_certificate(ssl));
1431 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl);
1432 if (X509_cmp(leaf.get(), expect_leaf.get()) != 0) {
1433 fprintf(stderr, "Received a different leaf certificate than expected.\n");
1434 return false;
1435 }
1436
1437 if (sk_X509_num(chain) != sk_X509_num(expect_chain.get())) {
1438 fprintf(stderr, "Received a chain of length %zu instead of %zu.\n",
1439 sk_X509_num(chain), sk_X509_num(expect_chain.get()));
1440 return false;
1441 }
1442
1443 for (size_t i = 0; i < sk_X509_num(chain); i++) {
1444 if (X509_cmp(sk_X509_value(chain, i),
1445 sk_X509_value(expect_chain.get(), i)) != 0) {
1446 fprintf(stderr, "Chain certificate %zu did not match.\n",
1447 i + 1);
1448 return false;
1449 }
1450 }
1451 }
1452
David Benjaminbbaf3672016-11-17 10:53:09 +09001453 bool expected_sha256_client_cert = config->expect_sha256_client_cert_initial;
1454 if (is_resume) {
1455 expected_sha256_client_cert = config->expect_sha256_client_cert_resume;
1456 }
1457
1458 if (SSL_get_session(ssl)->peer_sha256_valid != expected_sha256_client_cert) {
1459 fprintf(stderr,
1460 "Unexpected SHA-256 client cert state: expected:%d is_resume:%d.\n",
1461 expected_sha256_client_cert, is_resume);
1462 return false;
1463 }
1464
1465 if (expected_sha256_client_cert &&
1466 SSL_get_session(ssl)->x509_peer != nullptr) {
1467 fprintf(stderr, "Have both client cert and SHA-256 hash: is_resume:%d.\n",
1468 is_resume);
1469 return false;
1470 }
1471
David Benjamin91eab5c2015-06-18 18:35:46 -04001472 return true;
1473}
1474
David Benjamin87c8a642015-02-21 01:54:29 -05001475// DoExchange runs a test SSL exchange against the peer. On success, it returns
1476// true and sets |*out_session| to the negotiated SSL session. If the test is a
1477// resumption attempt, |is_resume| is true and |session| is the session from the
1478// previous exchange.
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001479static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
1480 SSL_CTX *ssl_ctx, const TestConfig *config,
1481 bool is_resume, SSL_SESSION *session) {
1482 bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
David Benjamina7f333d2015-02-09 02:37:18 -05001483 if (!ssl) {
David Benjamin40f101b2015-02-20 11:23:42 -05001484 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001485 }
1486
David Benjamin7e7a82d2016-05-20 20:12:42 -04001487 if (!SetTestConfig(ssl.get(), config) ||
David Benjamin2d445c02015-02-09 13:03:50 -05001488 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
David Benjamin40f101b2015-02-20 11:23:42 -05001489 return false;
Adam Langley69a01602014-11-17 17:26:55 -08001490 }
David Benjamin5a593af2014-08-11 19:51:50 -04001491
Adam Langley5f0efe02015-02-20 13:03:16 -08001492 if (config->fallback_scsv &&
1493 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
1494 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001495 }
David Benjamina0486782016-10-06 19:11:32 -04001496 // Install the certificate synchronously if nothing else will handle it.
1497 if (!config->use_early_callback &&
1498 !config->use_old_client_cert_callback &&
1499 !config->async &&
1500 !InstallCertificate(ssl.get())) {
1501 return false;
David Benjamin5a593af2014-08-11 19:51:50 -04001502 }
David Benjamin5edfc8c2016-12-10 15:46:58 -05001503 if (!config->use_old_client_cert_callback) {
1504 SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
1505 }
David Benjamin5a593af2014-08-11 19:51:50 -04001506 if (config->require_any_client_certificate) {
David Benjamina7f333d2015-02-09 02:37:18 -05001507 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
Paul Lietar8f1c2682015-08-18 12:21:54 +01001508 NULL);
1509 }
1510 if (config->verify_peer) {
1511 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
David Benjamin5a593af2014-08-11 19:51:50 -04001512 }
1513 if (config->false_start) {
David Benjamined7c4752015-02-16 19:16:46 -05001514 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
David Benjamin5a593af2014-08-11 19:51:50 -04001515 }
1516 if (config->cbc_record_splitting) {
David Benjamina7f333d2015-02-09 02:37:18 -05001517 SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
David Benjamin5a593af2014-08-11 19:51:50 -04001518 }
1519 if (config->partial_write) {
David Benjamina7f333d2015-02-09 02:37:18 -05001520 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
David Benjamin5a593af2014-08-11 19:51:50 -04001521 }
Steven Valdez4f94b1c2016-05-24 12:31:07 -04001522 if (config->no_tls13) {
1523 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
1524 }
David Benjamin5a593af2014-08-11 19:51:50 -04001525 if (config->no_tls12) {
David Benjamina7f333d2015-02-09 02:37:18 -05001526 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
David Benjamin5a593af2014-08-11 19:51:50 -04001527 }
1528 if (config->no_tls11) {
David Benjamina7f333d2015-02-09 02:37:18 -05001529 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
David Benjamin5a593af2014-08-11 19:51:50 -04001530 }
1531 if (config->no_tls1) {
David Benjamina7f333d2015-02-09 02:37:18 -05001532 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
David Benjamin5a593af2014-08-11 19:51:50 -04001533 }
1534 if (config->no_ssl3) {
David Benjamina7f333d2015-02-09 02:37:18 -05001535 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
David Benjamin5a593af2014-08-11 19:51:50 -04001536 }
Steven Valdez143e8b32016-07-11 13:19:03 -04001537 if (!config->expected_channel_id.empty() ||
1538 config->enable_channel_id) {
David Benjamineebd3c82016-12-06 17:43:58 -05001539 SSL_set_tls_channel_id_enabled(ssl.get(), 1);
David Benjamina08e49d2014-08-24 01:46:07 -04001540 }
1541 if (!config->send_channel_id.empty()) {
David Benjamineebd3c82016-12-06 17:43:58 -05001542 SSL_set_tls_channel_id_enabled(ssl.get(), 1);
David Benjamind9e07012015-02-09 03:04:34 -05001543 if (!config->async) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001544 // The async case will be supplied by |ChannelIdCallback|.
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001545 bssl::UniquePtr<EVP_PKEY> pkey = LoadPrivateKey(config->send_channel_id);
David Benjamind9e07012015-02-09 03:04:34 -05001546 if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001547 return false;
David Benjamind9e07012015-02-09 03:04:34 -05001548 }
David Benjamina08e49d2014-08-24 01:46:07 -04001549 }
David Benjamina08e49d2014-08-24 01:46:07 -04001550 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001551 if (!config->host_name.empty() &&
1552 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001553 return false;
David Benjamine78bfde2014-09-06 12:45:15 -04001554 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001555 if (!config->advertise_alpn.empty() &&
1556 SSL_set_alpn_protos(ssl.get(),
1557 (const uint8_t *)config->advertise_alpn.data(),
1558 config->advertise_alpn.size()) != 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001559 return false;
David Benjaminae2888f2014-09-06 12:58:58 -04001560 }
David Benjamin48cae082014-10-27 01:06:24 -04001561 if (!config->psk.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001562 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
1563 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
David Benjamin48cae082014-10-27 01:06:24 -04001564 }
David Benjamin61f95272014-11-25 01:55:35 -05001565 if (!config->psk_identity.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001566 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001567 return false;
David Benjamin48cae082014-10-27 01:06:24 -04001568 }
David Benjamin61f95272014-11-25 01:55:35 -05001569 if (!config->srtp_profiles.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001570 !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001571 return false;
David Benjamin61f95272014-11-25 01:55:35 -05001572 }
1573 if (config->enable_ocsp_stapling &&
David Benjamina7f333d2015-02-09 02:37:18 -05001574 !SSL_enable_ocsp_stapling(ssl.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001575 return false;
David Benjamin61f95272014-11-25 01:55:35 -05001576 }
1577 if (config->enable_signed_cert_timestamps &&
David Benjamina7f333d2015-02-09 02:37:18 -05001578 !SSL_enable_signed_cert_timestamps(ssl.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001579 return false;
David Benjaminca6c8262014-11-15 19:06:08 -05001580 }
David Benjamin2dc02042016-09-19 19:57:37 -04001581 if (config->min_version != 0 &&
David Benjamine4706902016-09-20 15:12:23 -04001582 !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) {
David Benjamin2dc02042016-09-19 19:57:37 -04001583 return false;
David Benjamin1eb367c2014-12-12 18:17:51 -05001584 }
David Benjamin2dc02042016-09-19 19:57:37 -04001585 if (config->max_version != 0 &&
David Benjamine4706902016-09-20 15:12:23 -04001586 !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) {
David Benjamin2dc02042016-09-19 19:57:37 -04001587 return false;
David Benjamin1eb367c2014-12-12 18:17:51 -05001588 }
David Benjamin13be1de2015-01-11 16:29:36 -05001589 if (config->mtu != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001590 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
1591 SSL_set_mtu(ssl.get(), config->mtu);
David Benjamin13be1de2015-01-11 16:29:36 -05001592 }
Adam Langley524e7172015-02-20 16:04:00 -08001593 if (config->install_ddos_callback) {
1594 SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
1595 }
David Benjamin1d5ef3b2015-10-12 19:54:18 -04001596 if (config->renegotiate_once) {
1597 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_once);
1598 }
1599 if (config->renegotiate_freely) {
1600 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
David Benjaminb16346b2015-04-08 19:16:58 -04001601 }
Adam Langley27a0d082015-11-03 13:34:10 -08001602 if (config->renegotiate_ignore) {
1603 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_ignore);
1604 }
David Benjamin30789da2015-08-29 22:56:45 -04001605 if (!config->check_close_notify) {
1606 SSL_set_quiet_shutdown(ssl.get(), 1);
1607 }
David Benjamin99fdfb92015-11-02 12:11:35 -05001608 if (config->p384_only) {
1609 int nid = NID_secp384r1;
1610 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
1611 return false;
1612 }
1613 }
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001614 if (config->enable_all_curves) {
1615 static const int kAllCurves[] = {
Matt Braithwaite053931e2016-05-25 12:06:05 -07001616 NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_X25519,
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001617 };
1618 if (!SSL_set1_curves(ssl.get(), kAllCurves,
Steven Valdezcb966542016-08-17 16:56:14 -04001619 OPENSSL_ARRAY_SIZE(kAllCurves))) {
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001620 return false;
1621 }
1622 }
Taylor Brandstetter376a0fe2016-05-10 19:30:28 -07001623 if (config->initial_timeout_duration_ms > 0) {
1624 DTLSv1_set_initial_timeout_duration(ssl.get(),
1625 config->initial_timeout_duration_ms);
1626 }
David Benjamina252b342016-09-26 19:57:53 -04001627 if (config->max_cert_list > 0) {
1628 SSL_set_max_cert_list(ssl.get(), config->max_cert_list);
1629 }
David Benjaminbbaf3672016-11-17 10:53:09 +09001630 if (!is_resume && config->retain_only_sha256_client_cert_initial) {
1631 SSL_set_retain_only_sha256_of_client_certs(ssl.get(), 1);
1632 }
1633 if (is_resume && config->retain_only_sha256_client_cert_resume) {
1634 SSL_set_retain_only_sha256_of_client_certs(ssl.get(), 1);
1635 }
David Benjamin025b3d32014-07-01 19:53:04 -04001636
David Benjamin87c8a642015-02-21 01:54:29 -05001637 int sock = Connect(config->port);
1638 if (sock == -1) {
1639 return false;
1640 }
1641 SocketCloser closer(sock);
1642
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001643 bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
David Benjamina7f333d2015-02-09 02:37:18 -05001644 if (!bio) {
David Benjamin40f101b2015-02-20 11:23:42 -05001645 return false;
David Benjamin43ec06f2014-08-05 02:28:57 -04001646 }
David Benjamin6fd297b2014-08-11 18:43:38 -04001647 if (config->is_dtls) {
David Benjamin1b22f852016-10-27 16:36:32 -04001648 bssl::UniquePtr<BIO> packeted = PacketedBioCreate(&g_clock, !config->async);
David Benjaminb7c5e842016-03-28 09:59:10 -04001649 if (!packeted) {
1650 return false;
1651 }
David Benjamin585d7a42016-06-02 14:58:00 -04001652 GetTestState(ssl.get())->packeted_bio = packeted.get();
David Benjamina7f333d2015-02-09 02:37:18 -05001653 BIO_push(packeted.get(), bio.release());
1654 bio = std::move(packeted);
David Benjamin6fd297b2014-08-11 18:43:38 -04001655 }
David Benjamin5a593af2014-08-11 19:51:50 -04001656 if (config->async) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001657 bssl::UniquePtr<BIO> async_scoped =
David Benjaminc273d2c2015-02-09 12:59:46 -05001658 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
David Benjaminb7c5e842016-03-28 09:59:10 -04001659 if (!async_scoped) {
1660 return false;
1661 }
David Benjamina7f333d2015-02-09 02:37:18 -05001662 BIO_push(async_scoped.get(), bio.release());
David Benjamin6c2563e2015-04-03 03:47:47 -04001663 GetTestState(ssl.get())->async_bio = async_scoped.get();
David Benjamina7f333d2015-02-09 02:37:18 -05001664 bio = std::move(async_scoped);
David Benjamin43ec06f2014-08-05 02:28:57 -04001665 }
David Benjamina7f333d2015-02-09 02:37:18 -05001666 SSL_set_bio(ssl.get(), bio.get(), bio.get());
1667 bio.release(); // SSL_set_bio takes ownership.
David Benjamin43ec06f2014-08-05 02:28:57 -04001668
David Benjamin1d5c83e2014-07-22 19:20:02 -04001669 if (session != NULL) {
David Benjamin1b8b6912015-02-09 04:28:16 -05001670 if (!config->is_server) {
1671 if (SSL_set_session(ssl.get(), session) != 1) {
David Benjamin40f101b2015-02-20 11:23:42 -05001672 return false;
David Benjamin1b8b6912015-02-09 04:28:16 -05001673 }
1674 } else if (config->async) {
1675 // The internal session cache is disabled, so install the session
1676 // manually.
David Benjaminb9195402016-08-05 10:51:43 -04001677 SSL_SESSION_up_ref(session);
1678 GetTestState(ssl.get())->pending_session.reset(session);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001679 }
1680 }
1681
David Benjamina07c0fc2015-05-13 13:19:42 -04001682 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1683 fprintf(stderr, "non-null cipher before handshake\n");
1684 return false;
1685 }
1686
David Benjamin1d5c83e2014-07-22 19:20:02 -04001687 int ret;
David Benjamine0e7d0d2015-02-08 19:33:25 -05001688 if (config->implicit_handshake) {
David Benjamin5a593af2014-08-11 19:51:50 -04001689 if (config->is_server) {
David Benjamina7f333d2015-02-09 02:37:18 -05001690 SSL_set_accept_state(ssl.get());
David Benjamin43ec06f2014-08-05 02:28:57 -04001691 } else {
David Benjamina7f333d2015-02-09 02:37:18 -05001692 SSL_set_connect_state(ssl.get());
David Benjamin43ec06f2014-08-05 02:28:57 -04001693 }
David Benjamine0e7d0d2015-02-08 19:33:25 -05001694 } else {
1695 do {
1696 if (config->is_server) {
David Benjamina7f333d2015-02-09 02:37:18 -05001697 ret = SSL_accept(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -05001698 } else {
David Benjamina7f333d2015-02-09 02:37:18 -05001699 ret = SSL_connect(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -05001700 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001701 } while (config->async && RetryAsync(ssl.get(), ret));
David Benjamin91eab5c2015-06-18 18:35:46 -04001702 if (ret != 1 ||
1703 !CheckHandshakeProperties(ssl.get(), is_resume)) {
David Benjamin40f101b2015-02-20 11:23:42 -05001704 return false;
David Benjamine0e7d0d2015-02-08 19:33:25 -05001705 }
David Benjamin025b3d32014-07-01 19:53:04 -04001706
David Benjaminba4594a2015-06-18 18:36:15 -04001707 // Reset the state to assert later that the callback isn't called in
1708 // renegotations.
1709 GetTestState(ssl.get())->got_new_session = false;
David Benjamin61f95272014-11-25 01:55:35 -05001710 }
1711
David Benjaminc565ebb2015-04-03 04:06:36 -04001712 if (config->export_keying_material > 0) {
1713 std::vector<uint8_t> result(
1714 static_cast<size_t>(config->export_keying_material));
1715 if (!SSL_export_keying_material(
1716 ssl.get(), result.data(), result.size(),
1717 config->export_label.data(), config->export_label.size(),
1718 reinterpret_cast<const uint8_t*>(config->export_context.data()),
1719 config->export_context.size(), config->use_export_context)) {
1720 fprintf(stderr, "failed to export keying material\n");
1721 return false;
1722 }
1723 if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1724 return false;
1725 }
1726 }
1727
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001728 if (config->tls_unique) {
1729 uint8_t tls_unique[16];
1730 size_t tls_unique_len;
1731 if (!SSL_get_tls_unique(ssl.get(), tls_unique, &tls_unique_len,
1732 sizeof(tls_unique))) {
1733 fprintf(stderr, "failed to get tls-unique\n");
1734 return false;
1735 }
1736
1737 if (tls_unique_len != 12) {
1738 fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
1739 static_cast<unsigned>(tls_unique_len));
1740 return false;
1741 }
1742
1743 if (WriteAll(ssl.get(), tls_unique, tls_unique_len) < 0) {
1744 return false;
1745 }
1746 }
1747
David Benjamin1d4f4c02016-07-26 18:03:08 -04001748 if (config->send_alert) {
1749 if (DoSendFatalAlert(ssl.get(), SSL_AD_DECOMPRESSION_FAILURE) < 0) {
1750 return false;
1751 }
1752 return true;
1753 }
1754
David Benjamin5a593af2014-08-11 19:51:50 -04001755 if (config->write_different_record_sizes) {
David Benjamin6fd297b2014-08-11 18:43:38 -04001756 if (config->is_dtls) {
1757 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001758 return false;
David Benjamin6fd297b2014-08-11 18:43:38 -04001759 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001760 // This mode writes a number of different record sizes in an attempt to
1761 // trip up the CBC record splitting code.
Adam Langleybc949292015-06-18 21:32:44 -07001762 static const size_t kBufLen = 32769;
1763 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
David Benjamin17cf2cb2016-12-13 01:07:13 -05001764 OPENSSL_memset(buf.get(), 0x42, kBufLen);
Kenny Root7fdeaf12014-08-05 15:23:37 -07001765 static const size_t kRecordSizes[] = {
1766 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
Steven Valdezcb966542016-08-17 16:56:14 -04001767 for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07001768 const size_t len = kRecordSizes[i];
Adam Langleybc949292015-06-18 21:32:44 -07001769 if (len > kBufLen) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07001770 fprintf(stderr, "Bad kRecordSizes value.\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001771 return false;
Kenny Root7fdeaf12014-08-05 15:23:37 -07001772 }
Adam Langleybc949292015-06-18 21:32:44 -07001773 if (WriteAll(ssl.get(), buf.get(), len) < 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001774 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001775 }
1776 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001777 } else {
David Benjamina1eaba12017-01-01 23:19:22 -05001778 if (config->read_with_unfinished_write) {
1779 if (!config->async) {
1780 fprintf(stderr, "-read-with-unfinished-write requires -async.\n");
1781 return false;
1782 }
1783
1784 int write_ret = SSL_write(ssl.get(),
1785 reinterpret_cast<const uint8_t *>("unfinished"), 10);
1786 if (SSL_get_error(ssl.get(), write_ret) != SSL_ERROR_WANT_WRITE) {
1787 fprintf(stderr, "Failed to leave unfinished write.\n");
1788 return false;
1789 }
1790 }
David Benjamine58c4f52014-08-24 03:47:07 -04001791 if (config->shim_writes_first) {
David Benjamin6c2563e2015-04-03 03:47:47 -04001792 if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1793 5) < 0) {
1794 return false;
1795 }
David Benjamine58c4f52014-08-24 03:47:07 -04001796 }
David Benjamin30789da2015-08-29 22:56:45 -04001797 if (!config->shim_shuts_down) {
1798 for (;;) {
Adam Langleya0a8dc22015-09-09 10:22:00 -07001799 static const size_t kBufLen = 16384;
1800 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1801
David Benjamin2c99d282015-09-01 10:23:00 -04001802 // Read only 512 bytes at a time in TLS to ensure records may be
1803 // returned in multiple reads.
Adam Langleya0a8dc22015-09-09 10:22:00 -07001804 int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
David Benjamin30789da2015-08-29 22:56:45 -04001805 int err = SSL_get_error(ssl.get(), n);
1806 if (err == SSL_ERROR_ZERO_RETURN ||
1807 (n == 0 && err == SSL_ERROR_SYSCALL)) {
1808 if (n != 0) {
1809 fprintf(stderr, "Invalid SSL_get_error output\n");
1810 return false;
1811 }
1812 // Stop on either clean or unclean shutdown.
1813 break;
1814 } else if (err != SSL_ERROR_NONE) {
1815 if (n > 0) {
1816 fprintf(stderr, "Invalid SSL_get_error output\n");
1817 return false;
1818 }
1819 return false;
1820 }
1821 // Successfully read data.
1822 if (n <= 0) {
David Benjamin9a38e922015-01-22 16:06:11 -05001823 fprintf(stderr, "Invalid SSL_get_error output\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001824 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001825 }
David Benjamin30789da2015-08-29 22:56:45 -04001826
1827 // After a successful read, with or without False Start, the handshake
1828 // must be complete.
1829 if (!GetTestState(ssl.get())->handshake_done) {
1830 fprintf(stderr, "handshake was not completed after SSL_read\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001831 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001832 }
David Benjamin87e4acd2015-04-02 19:57:35 -04001833
David Benjamin30789da2015-08-29 22:56:45 -04001834 for (int i = 0; i < n; i++) {
1835 buf[i] ^= 0xff;
1836 }
Adam Langleya0a8dc22015-09-09 10:22:00 -07001837 if (WriteAll(ssl.get(), buf.get(), n) < 0) {
David Benjamin30789da2015-08-29 22:56:45 -04001838 return false;
1839 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001840 }
1841 }
David Benjamin025b3d32014-07-01 19:53:04 -04001842 }
1843
David Benjaminba4594a2015-06-18 18:36:15 -04001844 if (!config->is_server && !config->false_start &&
1845 !config->implicit_handshake &&
Steven Valdez1e6f11a2016-07-27 11:10:52 -04001846 // Session tickets are sent post-handshake in TLS 1.3.
1847 GetProtocolVersion(ssl.get()) < TLS1_3_VERSION &&
David Benjaminba4594a2015-06-18 18:36:15 -04001848 GetTestState(ssl.get())->got_new_session) {
1849 fprintf(stderr, "new session was established after the handshake\n");
1850 return false;
1851 }
1852
Steven Valdez1e6f11a2016-07-27 11:10:52 -04001853 if (GetProtocolVersion(ssl.get()) >= TLS1_3_VERSION && !config->is_server) {
1854 bool expect_new_session =
1855 !config->expect_no_session && !config->shim_shuts_down;
1856 if (expect_new_session != GetTestState(ssl.get())->got_new_session) {
1857 fprintf(stderr,
1858 "new session was%s cached, but we expected the opposite\n",
1859 GetTestState(ssl.get())->got_new_session ? "" : " not");
1860 return false;
1861 }
Steven Valdez08b65f42016-12-07 15:29:45 -05001862
1863 if (expect_new_session) {
1864 bool got_early_data_info =
1865 GetTestState(ssl.get())->new_session->ticket_max_early_data != 0;
1866 if (config->expect_early_data_info != got_early_data_info) {
1867 fprintf(
1868 stderr,
1869 "new session did%s include ticket_early_data_info, but we expected "
1870 "the opposite\n",
1871 got_early_data_info ? "" : " not");
1872 return false;
1873 }
1874 }
Steven Valdez1e6f11a2016-07-27 11:10:52 -04001875 }
1876
David Benjamin1d5c83e2014-07-22 19:20:02 -04001877 if (out_session) {
Steven Valdez4aa154e2016-07-29 14:32:55 -04001878 *out_session = std::move(GetTestState(ssl.get())->new_session);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001879 }
1880
David Benjamin30789da2015-08-29 22:56:45 -04001881 ret = DoShutdown(ssl.get());
1882
1883 if (config->shim_shuts_down && config->check_close_notify) {
1884 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1885 // it returns zero when our close_notify is sent, then one when the peer's
1886 // is received.
1887 if (ret != 0) {
1888 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1889 return false;
1890 }
1891 ret = DoShutdown(ssl.get());
1892 }
1893
1894 if (ret != 1) {
1895 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1896 return false;
1897 }
1898
David Benjamin324dce42015-10-12 19:49:00 -04001899 if (SSL_total_renegotiations(ssl.get()) !=
1900 config->expect_total_renegotiations) {
1901 fprintf(stderr, "Expected %d renegotiations, got %d\n",
1902 config->expect_total_renegotiations,
1903 SSL_total_renegotiations(ssl.get()));
1904 return false;
1905 }
1906
David Benjamin40f101b2015-02-20 11:23:42 -05001907 return true;
David Benjamin025b3d32014-07-01 19:53:04 -04001908}
David Benjamin1d5c83e2014-07-22 19:20:02 -04001909
David Benjaminff3a1492016-03-02 10:12:06 -05001910class StderrDelimiter {
1911 public:
1912 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
1913};
1914
David Benjaminaac1e2d2016-12-06 22:35:41 -05001915int main(int argc, char **argv) {
David Benjaminff3a1492016-03-02 10:12:06 -05001916 // To distinguish ASan's output from ours, add a trailing message to stderr.
1917 // Anything following this line will be considered an error.
1918 StderrDelimiter delimiter;
1919
David Benjamin87c8a642015-02-21 01:54:29 -05001920#if defined(OPENSSL_WINDOWS)
1921 /* Initialize Winsock. */
1922 WORD wsa_version = MAKEWORD(2, 2);
1923 WSADATA wsa_data;
1924 int wsa_err = WSAStartup(wsa_version, &wsa_data);
1925 if (wsa_err != 0) {
1926 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1927 return 1;
1928 }
1929 if (wsa_data.wVersion != wsa_version) {
1930 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1931 return 1;
1932 }
1933#else
David Benjamin1d5c83e2014-07-22 19:20:02 -04001934 signal(SIGPIPE, SIG_IGN);
Adam Langleyded93582014-07-31 15:23:51 -07001935#endif
David Benjamin1d5c83e2014-07-22 19:20:02 -04001936
David Benjamin7a1eefd2015-10-17 23:39:22 -04001937 CRYPTO_library_init();
David Benjamind9e07012015-02-09 03:04:34 -05001938 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
David Benjamin2d445c02015-02-09 13:03:50 -05001939 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
David Benjamin6c2563e2015-04-03 03:47:47 -04001940 if (g_config_index < 0 || g_state_index < 0) {
David Benjaminae3e4872014-11-18 21:52:26 -05001941 return 1;
1942 }
David Benjamin5a593af2014-08-11 19:51:50 -04001943
1944 TestConfig config;
1945 if (!ParseConfig(argc - 1, argv + 1, &config)) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001946 return Usage(argv[0]);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001947 }
1948
Adam Langleyd519bf62016-12-12 11:16:44 -08001949 g_pool = CRYPTO_BUFFER_POOL_new();
1950
David Benjamin1b22f852016-10-27 16:36:32 -04001951 // Some code treats the zero time special, so initialize the clock to a
1952 // non-zero time.
1953 g_clock.tv_sec = 1234;
1954 g_clock.tv_usec = 1234;
1955
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001956 bssl::UniquePtr<SSL_CTX> ssl_ctx = SetupCtx(&config);
David Benjamina7f333d2015-02-09 02:37:18 -05001957 if (!ssl_ctx) {
Brian Smith83a82982015-04-09 16:21:10 -10001958 ERR_print_errors_fp(stderr);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001959 return 1;
1960 }
1961
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001962 bssl::UniquePtr<SSL_SESSION> session;
David Benjamin46662482016-08-17 00:51:00 -04001963 for (int i = 0; i < config.resume_count + 1; i++) {
1964 bool is_resume = i > 0;
1965 if (is_resume && !config.is_server && !session) {
1966 fprintf(stderr, "No session to offer.\n");
1967 return 1;
1968 }
David Benjamin1d5c83e2014-07-22 19:20:02 -04001969
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001970 bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
David Benjamin46662482016-08-17 00:51:00 -04001971 if (!DoExchange(&session, ssl_ctx.get(), &config, is_resume,
1972 offer_session.get())) {
1973 fprintf(stderr, "Connection %d failed.\n", i + 1);
1974 ERR_print_errors_fp(stderr);
1975 return 1;
1976 }
Steven Valdeza833c352016-11-01 13:39:36 -04001977
1978 if (config.resumption_delay != 0) {
1979 g_clock.tv_sec += config.resumption_delay;
1980 }
David Benjamin1d5c83e2014-07-22 19:20:02 -04001981 }
1982
David Benjamina7f333d2015-02-09 02:37:18 -05001983 return 0;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001984}