blob: 898245944ca63b91ac865d7de9d944920b984fe3 [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>
31#pragma warning(push, 3)
Adam Langley3e719312015-03-20 16:32:23 -070032#include <winsock2.h>
33#include <ws2tcpip.h>
David Benjamin87c8a642015-02-21 01:54:29 -050034#pragma warning(pop)
35
36#pragma comment(lib, "Ws2_32.lib")
Adam Langleyded93582014-07-31 15:23:51 -070037#endif
38
David Benjamin4cc36ad2015-12-19 14:23:26 -050039#include <inttypes.h>
Adam Langley2b2d66d2015-01-30 17:08:37 -080040#include <string.h>
David Benjamin025b3d32014-07-01 19:53:04 -040041
David Benjamin025b3d32014-07-01 19:53:04 -040042#include <openssl/bio.h>
David Benjamin48cae082014-10-27 01:06:24 -040043#include <openssl/buf.h>
David Benjamin8f2c20e2014-07-09 09:30:38 -040044#include <openssl/bytestring.h>
David Benjamind98452d2015-06-16 14:16:23 -040045#include <openssl/cipher.h>
David Benjamin7a1eefd2015-10-17 23:39:22 -040046#include <openssl/crypto.h>
Brian Smith83a82982015-04-09 16:21:10 -100047#include <openssl/err.h>
David Benjamind98452d2015-06-16 14:16:23 -040048#include <openssl/hmac.h>
David Benjamin98193672016-03-25 18:07:11 -040049#include <openssl/nid.h>
David Benjamind98452d2015-06-16 14:16:23 -040050#include <openssl/rand.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040051#include <openssl/ssl.h>
52
David Benjamin45fb1be2015-03-22 16:31:27 -040053#include <memory>
Steven Valdez0d62f262015-09-04 12:41:04 -040054#include <string>
David Benjaminc565ebb2015-04-03 04:06:36 -040055#include <vector>
David Benjamin45fb1be2015-03-22 16:31:27 -040056
57#include "../../crypto/test/scoped_types.h"
David Benjamin43ec06f2014-08-05 02:28:57 -040058#include "async_bio.h"
David Benjamin6fd297b2014-08-11 18:43:38 -040059#include "packeted_bio.h"
David Benjamina7f333d2015-02-09 02:37:18 -050060#include "scoped_types.h"
David Benjamin5a593af2014-08-11 19:51:50 -040061#include "test_config.h"
David Benjamin43ec06f2014-08-05 02:28:57 -040062
David Benjamin87c8a642015-02-21 01:54:29 -050063
64#if !defined(OPENSSL_WINDOWS)
65static int closesocket(int sock) {
66 return close(sock);
67}
68
69static void PrintSocketError(const char *func) {
70 perror(func);
71}
72#else
73static void PrintSocketError(const char *func) {
74 fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
75}
76#endif
77
David Benjaminc273d2c2015-02-09 12:59:46 -050078static int Usage(const char *program) {
David Benjamina7f333d2015-02-09 02:37:18 -050079 fprintf(stderr, "Usage: %s [flags...]\n", program);
David Benjamin1d5c83e2014-07-22 19:20:02 -040080 return 1;
81}
David Benjamin025b3d32014-07-01 19:53:04 -040082
David Benjamin2d445c02015-02-09 13:03:50 -050083struct TestState {
David Benjaminff9c74f2015-04-06 20:17:56 -040084 TestState() {
85 // MSVC cannot initialize these inline.
86 memset(&clock, 0, sizeof(clock));
87 memset(&clock_delta, 0, sizeof(clock_delta));
88 }
89
David Benjamin6c2563e2015-04-03 03:47:47 -040090 // async_bio is async BIO which pauses reads and writes.
91 BIO *async_bio = nullptr;
92 // clock is the current time for the SSL connection.
David Benjamin4d2e7ce2015-05-08 13:29:45 -040093 timeval clock;
David Benjamin6c2563e2015-04-03 03:47:47 -040094 // clock_delta is how far the clock advanced in the most recent failed
95 // |BIO_read|.
David Benjamin4d2e7ce2015-05-08 13:29:45 -040096 timeval clock_delta;
David Benjamind9e07012015-02-09 03:04:34 -050097 ScopedEVP_PKEY channel_id;
David Benjamin0d4db502015-03-23 18:46:05 -040098 bool cert_ready = false;
David Benjamin1b8b6912015-02-09 04:28:16 -050099 ScopedSSL_SESSION session;
100 ScopedSSL_SESSION pending_session;
David Benjamin0d4db502015-03-23 18:46:05 -0400101 bool early_callback_called = false;
David Benjamin87e4acd2015-04-02 19:57:35 -0400102 bool handshake_done = false;
David Benjaminb4d65fd2015-05-29 17:11:21 -0400103 // private_key is the underlying private key used when testing custom keys.
104 ScopedEVP_PKEY private_key;
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700105 std::vector<uint8_t> private_key_result;
106 // private_key_retries is the number of times an asynchronous private key
107 // operation has been retried.
108 unsigned private_key_retries = 0;
David Benjaminba4594a2015-06-18 18:36:15 -0400109 bool got_new_session = false;
David Benjamind9e07012015-02-09 03:04:34 -0500110};
111
David Benjamin2d445c02015-02-09 13:03:50 -0500112static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
Adam Langley09505632015-07-30 18:10:13 -0700113 int index, long argl, void *argp) {
David Benjamin2d445c02015-02-09 13:03:50 -0500114 delete ((TestState *)ptr);
David Benjamind9e07012015-02-09 03:04:34 -0500115}
116
117static int g_config_index = 0;
David Benjamin2d445c02015-02-09 13:03:50 -0500118static int g_state_index = 0;
David Benjamin5a593af2014-08-11 19:51:50 -0400119
David Benjamin7e7a82d2016-05-20 20:12:42 -0400120static bool SetTestConfig(SSL *ssl, const TestConfig *config) {
David Benjamind9e07012015-02-09 03:04:34 -0500121 return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
David Benjamin5a593af2014-08-11 19:51:50 -0400122}
123
David Benjamin7e7a82d2016-05-20 20:12:42 -0400124static const TestConfig *GetTestConfig(const SSL *ssl) {
David Benjamind9e07012015-02-09 03:04:34 -0500125 return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
David Benjamin5a593af2014-08-11 19:51:50 -0400126}
127
David Benjamin22050932015-11-23 13:44:48 -0500128static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
129 // |SSL_set_ex_data| takes ownership of |state| only on success.
130 if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
131 state.release();
David Benjamind9e07012015-02-09 03:04:34 -0500132 return true;
133 }
134 return false;
135}
136
David Benjamin87e4acd2015-04-02 19:57:35 -0400137static TestState *GetTestState(const SSL *ssl) {
David Benjamin2d445c02015-02-09 13:03:50 -0500138 return (TestState *)SSL_get_ex_data(ssl, g_state_index);
David Benjamin83f90402015-01-27 01:09:43 -0500139}
140
David Benjaminacb6dcc2016-03-10 09:15:01 -0500141static ScopedX509 LoadCertificate(const std::string &file) {
142 ScopedBIO bio(BIO_new(BIO_s_file()));
143 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
144 return nullptr;
145 }
146 return ScopedX509(PEM_read_bio_X509(bio.get(), NULL, NULL, NULL));
147}
148
David Benjamina7f333d2015-02-09 02:37:18 -0500149static ScopedEVP_PKEY LoadPrivateKey(const std::string &file) {
150 ScopedBIO bio(BIO_new(BIO_s_file()));
151 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
152 return nullptr;
David Benjamina08e49d2014-08-24 01:46:07 -0400153 }
David Benjaminacb6dcc2016-03-10 09:15:01 -0500154 return ScopedEVP_PKEY(PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
David Benjamina08e49d2014-08-24 01:46:07 -0400155}
156
David Benjaminb4d65fd2015-05-29 17:11:21 -0400157static int AsyncPrivateKeyType(SSL *ssl) {
158 return EVP_PKEY_id(GetTestState(ssl)->private_key.get());
159}
160
David Benjaminb4d65fd2015-05-29 17:11:21 -0400161static size_t AsyncPrivateKeyMaxSignatureLen(SSL *ssl) {
162 return EVP_PKEY_size(GetTestState(ssl)->private_key.get());
163}
164
165static ssl_private_key_result_t AsyncPrivateKeySign(
166 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
167 const EVP_MD *md, const uint8_t *in, size_t in_len) {
168 TestState *test_state = GetTestState(ssl);
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700169 if (!test_state->private_key_result.empty()) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400170 fprintf(stderr, "AsyncPrivateKeySign called with operation pending.\n");
171 abort();
172 }
173
174 ScopedEVP_PKEY_CTX ctx(EVP_PKEY_CTX_new(test_state->private_key.get(),
175 nullptr));
176 if (!ctx) {
177 return ssl_private_key_failure;
178 }
179
180 // Write the signature into |test_state|.
181 size_t len = 0;
182 if (!EVP_PKEY_sign_init(ctx.get()) ||
183 !EVP_PKEY_CTX_set_signature_md(ctx.get(), md) ||
184 !EVP_PKEY_sign(ctx.get(), nullptr, &len, in, in_len)) {
185 return ssl_private_key_failure;
186 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700187 test_state->private_key_result.resize(len);
David Benjaminef14b2d2015-11-11 14:01:27 -0800188 if (!EVP_PKEY_sign(ctx.get(), test_state->private_key_result.data(), &len, in,
189 in_len)) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400190 return ssl_private_key_failure;
191 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700192 test_state->private_key_result.resize(len);
David Benjaminb4d65fd2015-05-29 17:11:21 -0400193
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700194 // The signature will be released asynchronously in
195 // |AsyncPrivateKeySignComplete|.
David Benjaminb4d65fd2015-05-29 17:11:21 -0400196 return ssl_private_key_retry;
197}
198
199static ssl_private_key_result_t AsyncPrivateKeySignComplete(
200 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
201 TestState *test_state = GetTestState(ssl);
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700202 if (test_state->private_key_result.empty()) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400203 fprintf(stderr,
204 "AsyncPrivateKeySignComplete called without operation pending.\n");
205 abort();
206 }
207
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700208 if (test_state->private_key_retries < 2) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400209 // Only return the signature on the second attempt, to test both incomplete
210 // |sign| and |sign_complete|.
211 return ssl_private_key_retry;
212 }
213
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700214 if (max_out < test_state->private_key_result.size()) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400215 fprintf(stderr, "Output buffer too small.\n");
216 return ssl_private_key_failure;
217 }
David Benjaminef14b2d2015-11-11 14:01:27 -0800218 memcpy(out, test_state->private_key_result.data(),
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700219 test_state->private_key_result.size());
220 *out_len = test_state->private_key_result.size();
David Benjaminb4d65fd2015-05-29 17:11:21 -0400221
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700222 test_state->private_key_result.clear();
223 test_state->private_key_retries = 0;
224 return ssl_private_key_success;
225}
226
227static ssl_private_key_result_t AsyncPrivateKeyDecrypt(
228 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
229 const uint8_t *in, size_t in_len) {
230 TestState *test_state = GetTestState(ssl);
231 if (!test_state->private_key_result.empty()) {
232 fprintf(stderr,
233 "AsyncPrivateKeyDecrypt called with operation pending.\n");
234 abort();
235 }
236
David Benjamin758d1272015-11-20 17:47:25 -0500237 RSA *rsa = EVP_PKEY_get0_RSA(test_state->private_key.get());
238 if (rsa == NULL) {
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700239 fprintf(stderr,
240 "AsyncPrivateKeyDecrypt called with incorrect key type.\n");
241 abort();
242 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700243 test_state->private_key_result.resize(RSA_size(rsa));
David Benjaminef14b2d2015-11-11 14:01:27 -0800244 if (!RSA_decrypt(rsa, out_len, test_state->private_key_result.data(),
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700245 RSA_size(rsa), in, in_len, RSA_NO_PADDING)) {
246 return ssl_private_key_failure;
247 }
248
249 test_state->private_key_result.resize(*out_len);
250
251 // The decryption will be released asynchronously in
252 // |AsyncPrivateKeyDecryptComplete|.
253 return ssl_private_key_retry;
254}
255
256static ssl_private_key_result_t AsyncPrivateKeyDecryptComplete(
257 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
258 TestState *test_state = GetTestState(ssl);
259 if (test_state->private_key_result.empty()) {
260 fprintf(stderr,
261 "AsyncPrivateKeyDecryptComplete called without operation "
262 "pending.\n");
263 abort();
264 }
265
266 if (test_state->private_key_retries < 2) {
267 // Only return the decryption on the second attempt, to test both incomplete
268 // |decrypt| and |decrypt_complete|.
269 return ssl_private_key_retry;
270 }
271
272 if (max_out < test_state->private_key_result.size()) {
273 fprintf(stderr, "Output buffer too small.\n");
274 return ssl_private_key_failure;
275 }
David Benjaminef14b2d2015-11-11 14:01:27 -0800276 memcpy(out, test_state->private_key_result.data(),
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700277 test_state->private_key_result.size());
278 *out_len = test_state->private_key_result.size();
279
280 test_state->private_key_result.clear();
281 test_state->private_key_retries = 0;
David Benjaminb4d65fd2015-05-29 17:11:21 -0400282 return ssl_private_key_success;
283}
284
285static const SSL_PRIVATE_KEY_METHOD g_async_private_key_method = {
286 AsyncPrivateKeyType,
David Benjaminb4d65fd2015-05-29 17:11:21 -0400287 AsyncPrivateKeyMaxSignatureLen,
288 AsyncPrivateKeySign,
289 AsyncPrivateKeySignComplete,
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700290 AsyncPrivateKeyDecrypt,
291 AsyncPrivateKeyDecryptComplete
David Benjaminb4d65fd2015-05-29 17:11:21 -0400292};
293
Steven Valdez0d62f262015-09-04 12:41:04 -0400294template<typename T>
295struct Free {
296 void operator()(T *buf) {
297 free(buf);
298 }
299};
300
David Benjaminacb6dcc2016-03-10 09:15:01 -0500301static bool GetCertificate(SSL *ssl, ScopedX509 *out_x509,
302 ScopedEVP_PKEY *out_pkey) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400303 const TestConfig *config = GetTestConfig(ssl);
Steven Valdez0d62f262015-09-04 12:41:04 -0400304
305 if (!config->digest_prefs.empty()) {
306 std::unique_ptr<char, Free<char>> digest_prefs(
307 strdup(config->digest_prefs.c_str()));
Steven Valdez0d62f262015-09-04 12:41:04 -0400308 std::vector<int> digest_list;
309
310 for (;;) {
Adam Langley67251f22015-09-23 15:01:07 -0700311 char *token =
312 strtok(digest_list.empty() ? digest_prefs.get() : nullptr, ",");
Steven Valdez0d62f262015-09-04 12:41:04 -0400313 if (token == nullptr) {
314 break;
315 }
316
317 digest_list.push_back(EVP_MD_type(EVP_get_digestbyname(token)));
318 }
319
320 if (!SSL_set_private_key_digest_prefs(ssl, digest_list.data(),
321 digest_list.size())) {
322 return false;
323 }
324 }
325
David Benjaminb4d65fd2015-05-29 17:11:21 -0400326 if (!config->key_file.empty()) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500327 *out_pkey = LoadPrivateKey(config->key_file.c_str());
328 if (!*out_pkey) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400329 return false;
330 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500331 }
David Benjaminacb6dcc2016-03-10 09:15:01 -0500332 if (!config->cert_file.empty()) {
333 *out_x509 = LoadCertificate(config->cert_file.c_str());
334 if (!*out_x509) {
335 return false;
336 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500337 }
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100338 if (!config->ocsp_response.empty() &&
339 !SSL_CTX_set_ocsp_response(ssl->ctx,
340 (const uint8_t *)config->ocsp_response.data(),
341 config->ocsp_response.size())) {
342 return false;
343 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500344 return true;
345}
346
David Benjaminacb6dcc2016-03-10 09:15:01 -0500347static bool InstallCertificate(SSL *ssl) {
348 ScopedX509 x509;
349 ScopedEVP_PKEY pkey;
350 if (!GetCertificate(ssl, &x509, &pkey)) {
351 return false;
352 }
353
354 if (pkey) {
355 TestState *test_state = GetTestState(ssl);
David Benjamin7e7a82d2016-05-20 20:12:42 -0400356 const TestConfig *config = GetTestConfig(ssl);
David Benjaminacb6dcc2016-03-10 09:15:01 -0500357 if (config->async) {
358 test_state->private_key = std::move(pkey);
359 SSL_set_private_key_method(ssl, &g_async_private_key_method);
360 } else if (!SSL_use_PrivateKey(ssl, pkey.get())) {
361 return false;
362 }
363 }
364
365 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
366 return false;
367 }
368
369 return true;
370}
371
David Benjaminc273d2c2015-02-09 12:59:46 -0500372static int SelectCertificateCallback(const struct ssl_early_callback_ctx *ctx) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400373 const TestConfig *config = GetTestConfig(ctx->ssl);
David Benjamin2d445c02015-02-09 13:03:50 -0500374 GetTestState(ctx->ssl)->early_callback_called = true;
David Benjamin5a593af2014-08-11 19:51:50 -0400375
David Benjamin6f5c0f42015-02-24 01:23:21 -0500376 if (!config->expected_server_name.empty()) {
377 const uint8_t *extension_data;
378 size_t extension_len;
379 CBS extension, server_name_list, host_name;
380 uint8_t name_type;
381
382 if (!SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
383 &extension_data,
384 &extension_len)) {
385 fprintf(stderr, "Could not find server_name extension.\n");
386 return -1;
387 }
388
389 CBS_init(&extension, extension_data, extension_len);
390 if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
391 CBS_len(&extension) != 0 ||
392 !CBS_get_u8(&server_name_list, &name_type) ||
393 name_type != TLSEXT_NAMETYPE_host_name ||
394 !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
395 CBS_len(&server_name_list) != 0) {
396 fprintf(stderr, "Could not decode server_name extension.\n");
397 return -1;
398 }
399
400 if (!CBS_mem_equal(&host_name,
401 (const uint8_t*)config->expected_server_name.data(),
402 config->expected_server_name.size())) {
403 fprintf(stderr, "Server name mismatch.\n");
404 }
David Benjamin7b030512014-07-08 17:30:11 -0400405 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400406
David Benjamin6f5c0f42015-02-24 01:23:21 -0500407 if (config->fail_early_callback) {
David Benjamin7b030512014-07-08 17:30:11 -0400408 return -1;
409 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400410
David Benjamin6f5c0f42015-02-24 01:23:21 -0500411 // Install the certificate in the early callback.
412 if (config->use_early_callback) {
413 if (config->async) {
414 // Install the certificate asynchronously.
415 return 0;
416 }
417 if (!InstallCertificate(ctx->ssl)) {
418 return -1;
419 }
David Benjamin7b030512014-07-08 17:30:11 -0400420 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400421 return 1;
422}
David Benjamin025b3d32014-07-01 19:53:04 -0400423
David Benjaminacb6dcc2016-03-10 09:15:01 -0500424static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400425 if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500426 return -1;
427 }
428
429 ScopedX509 x509;
430 ScopedEVP_PKEY pkey;
431 if (!GetCertificate(ssl, &x509, &pkey)) {
432 return -1;
433 }
434
435 // Return zero for no certificate.
436 if (!x509) {
437 return 0;
438 }
439
440 // Asynchronous private keys are not supported with client_cert_cb.
441 *out_x509 = x509.release();
442 *out_pkey = pkey.release();
443 return 1;
444}
445
Paul Lietar8f1c2682015-08-18 12:21:54 +0100446static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
447 SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data(store_ctx,
448 SSL_get_ex_data_X509_STORE_CTX_idx());
David Benjamin7e7a82d2016-05-20 20:12:42 -0400449 const TestConfig *config = GetTestConfig(ssl);
Paul Lietar8f1c2682015-08-18 12:21:54 +0100450
451 if (!config->expected_ocsp_response.empty()) {
452 const uint8_t *data;
453 size_t len;
454 SSL_get0_ocsp_response(ssl, &data, &len);
455 if (len == 0) {
456 fprintf(stderr, "OCSP response not available in verify callback\n");
457 return 0;
458 }
459 }
460
David Benjamin67666e72014-07-12 15:47:52 -0400461 return 1;
462}
463
Paul Lietar8f1c2682015-08-18 12:21:54 +0100464static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
465 store_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION;
466 return 0;
467}
468
David Benjaminc273d2c2015-02-09 12:59:46 -0500469static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
470 unsigned int *out_len, void *arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400471 const TestConfig *config = GetTestConfig(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500472 if (config->advertise_npn.empty()) {
David Benjamin1f5f62b2014-07-12 16:18:02 -0400473 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500474 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400475
David Benjamin5a593af2014-08-11 19:51:50 -0400476 *out = (const uint8_t*)config->advertise_npn.data();
477 *out_len = config->advertise_npn.size();
David Benjamin1f5f62b2014-07-12 16:18:02 -0400478 return SSL_TLSEXT_ERR_OK;
479}
480
David Benjaminc273d2c2015-02-09 12:59:46 -0500481static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
David Benjamin8b368412015-03-14 01:54:17 -0400482 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400483 const TestConfig *config = GetTestConfig(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500484 if (config->select_next_proto.empty()) {
David Benjamin7e3305e2014-07-28 14:52:32 -0400485 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500486 }
David Benjamin7e3305e2014-07-28 14:52:32 -0400487
David Benjamin5a593af2014-08-11 19:51:50 -0400488 *out = (uint8_t*)config->select_next_proto.data();
489 *outlen = config->select_next_proto.size();
David Benjamin7e3305e2014-07-28 14:52:32 -0400490 return SSL_TLSEXT_ERR_OK;
491}
492
David Benjaminc273d2c2015-02-09 12:59:46 -0500493static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
494 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400495 const TestConfig *config = GetTestConfig(ssl);
David Benjamin594e7d22016-03-17 17:49:56 -0400496 if (config->decline_alpn) {
David Benjaminae2888f2014-09-06 12:58:58 -0400497 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500498 }
David Benjaminae2888f2014-09-06 12:58:58 -0400499
500 if (!config->expected_advertised_alpn.empty() &&
501 (config->expected_advertised_alpn.size() != inlen ||
502 memcmp(config->expected_advertised_alpn.data(),
503 in, inlen) != 0)) {
504 fprintf(stderr, "bad ALPN select callback inputs\n");
505 exit(1);
506 }
507
508 *out = (const uint8_t*)config->select_alpn.data();
509 *outlen = config->select_alpn.size();
510 return SSL_TLSEXT_ERR_OK;
511}
512
David Benjaminc273d2c2015-02-09 12:59:46 -0500513static unsigned PskClientCallback(SSL *ssl, const char *hint,
514 char *out_identity,
515 unsigned max_identity_len,
516 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400517 const TestConfig *config = GetTestConfig(ssl);
David Benjamin48cae082014-10-27 01:06:24 -0400518
519 if (strcmp(hint ? hint : "", config->psk_identity.c_str()) != 0) {
520 fprintf(stderr, "Server PSK hint did not match.\n");
521 return 0;
522 }
523
524 // Account for the trailing '\0' for the identity.
525 if (config->psk_identity.size() >= max_identity_len ||
526 config->psk.size() > max_psk_len) {
527 fprintf(stderr, "PSK buffers too small\n");
528 return 0;
529 }
530
531 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
532 max_identity_len);
533 memcpy(out_psk, config->psk.data(), config->psk.size());
534 return config->psk.size();
535}
536
David Benjaminc273d2c2015-02-09 12:59:46 -0500537static unsigned PskServerCallback(SSL *ssl, const char *identity,
538 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400539 const TestConfig *config = GetTestConfig(ssl);
David Benjamin48cae082014-10-27 01:06:24 -0400540
541 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
542 fprintf(stderr, "Client PSK identity did not match.\n");
543 return 0;
544 }
545
546 if (config->psk.size() > max_psk_len) {
547 fprintf(stderr, "PSK buffers too small\n");
548 return 0;
549 }
550
551 memcpy(out_psk, config->psk.data(), config->psk.size());
552 return config->psk.size();
553}
554
David Benjamin4d2e7ce2015-05-08 13:29:45 -0400555static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
David Benjamin6c2563e2015-04-03 03:47:47 -0400556 *out_clock = GetTestState(ssl)->clock;
David Benjamin377fc312015-01-26 00:22:12 -0500557}
558
David Benjaminc273d2c2015-02-09 12:59:46 -0500559static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
David Benjamin2d445c02015-02-09 13:03:50 -0500560 *out_pkey = GetTestState(ssl)->channel_id.release();
David Benjamind9e07012015-02-09 03:04:34 -0500561}
562
David Benjaminc273d2c2015-02-09 12:59:46 -0500563static int CertCallback(SSL *ssl, void *arg) {
David Benjamin2d445c02015-02-09 13:03:50 -0500564 if (!GetTestState(ssl)->cert_ready) {
David Benjamin41fdbcd2015-02-09 03:13:35 -0500565 return -1;
566 }
567 if (!InstallCertificate(ssl)) {
568 return 0;
569 }
570 return 1;
571}
572
David Benjaminc273d2c2015-02-09 12:59:46 -0500573static SSL_SESSION *GetSessionCallback(SSL *ssl, uint8_t *data, int len,
574 int *copy) {
David Benjamin2d445c02015-02-09 13:03:50 -0500575 TestState *async_state = GetTestState(ssl);
David Benjamin1b8b6912015-02-09 04:28:16 -0500576 if (async_state->session) {
577 *copy = 0;
578 return async_state->session.release();
579 } else if (async_state->pending_session) {
580 return SSL_magic_pending_session_ptr();
581 } else {
582 return NULL;
583 }
584}
585
Adam Langley524e7172015-02-20 16:04:00 -0800586static int DDoSCallback(const struct ssl_early_callback_ctx *early_context) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400587 const TestConfig *config = GetTestConfig(early_context->ssl);
Adam Langley524e7172015-02-20 16:04:00 -0800588 static int callback_num = 0;
589
590 callback_num++;
591 if (config->fail_ddos_callback ||
592 (config->fail_second_ddos_callback && callback_num == 2)) {
593 return 0;
594 }
595 return 1;
596}
597
David Benjamin87e4acd2015-04-02 19:57:35 -0400598static void InfoCallback(const SSL *ssl, int type, int val) {
599 if (type == SSL_CB_HANDSHAKE_DONE) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400600 if (GetTestConfig(ssl)->handshake_never_done) {
David Benjamin87e4acd2015-04-02 19:57:35 -0400601 fprintf(stderr, "handshake completed\n");
602 // Abort before any expected error code is printed, to ensure the overall
603 // test fails.
604 abort();
605 }
606 GetTestState(ssl)->handshake_done = true;
607 }
608}
609
David Benjaminba4594a2015-06-18 18:36:15 -0400610static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
611 GetTestState(ssl)->got_new_session = true;
612 // BoringSSL passes a reference to |session|.
613 SSL_SESSION_free(session);
614 return 1;
615}
616
David Benjamind98452d2015-06-16 14:16:23 -0400617static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
618 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
619 int encrypt) {
620 // This is just test code, so use the all-zeros key.
621 static const uint8_t kZeros[16] = {0};
622
623 if (encrypt) {
624 memcpy(key_name, kZeros, sizeof(kZeros));
625 RAND_bytes(iv, 16);
626 } else if (memcmp(key_name, kZeros, 16) != 0) {
627 return 0;
628 }
629
630 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
631 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
632 return -1;
633 }
634
635 if (!encrypt) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400636 return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
David Benjamind98452d2015-06-16 14:16:23 -0400637 }
638 return 1;
639}
640
Adam Langley09505632015-07-30 18:10:13 -0700641// kCustomExtensionValue is the extension value that the custom extension
642// callbacks will add.
Adam Langleyc5b23a12015-07-30 18:19:26 -0700643static const uint16_t kCustomExtensionValue = 1234;
Adam Langley09505632015-07-30 18:10:13 -0700644static void *const kCustomExtensionAddArg =
645 reinterpret_cast<void *>(kCustomExtensionValue);
646static void *const kCustomExtensionParseArg =
647 reinterpret_cast<void *>(kCustomExtensionValue + 1);
648static const char kCustomExtensionContents[] = "custom extension";
649
650static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
651 const uint8_t **out, size_t *out_len,
652 int *out_alert_value, void *add_arg) {
653 if (extension_value != kCustomExtensionValue ||
654 add_arg != kCustomExtensionAddArg) {
655 abort();
656 }
657
David Benjamin7e7a82d2016-05-20 20:12:42 -0400658 if (GetTestConfig(ssl)->custom_extension_skip) {
Adam Langley09505632015-07-30 18:10:13 -0700659 return 0;
660 }
David Benjamin7e7a82d2016-05-20 20:12:42 -0400661 if (GetTestConfig(ssl)->custom_extension_fail_add) {
Adam Langley09505632015-07-30 18:10:13 -0700662 return -1;
663 }
664
665 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
666 *out_len = sizeof(kCustomExtensionContents) - 1;
667
668 return 1;
669}
670
671static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
672 const uint8_t *out, void *add_arg) {
673 if (extension_value != kCustomExtensionValue ||
674 add_arg != kCustomExtensionAddArg ||
675 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
676 abort();
677 }
678}
679
680static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
681 const uint8_t *contents,
682 size_t contents_len,
683 int *out_alert_value, void *parse_arg) {
684 if (extension_value != kCustomExtensionValue ||
685 parse_arg != kCustomExtensionParseArg) {
686 abort();
687 }
688
689 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
690 memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
691 *out_alert_value = SSL_AD_DECODE_ERROR;
692 return 0;
693 }
694
695 return 1;
696}
697
David Benjamin87c8a642015-02-21 01:54:29 -0500698// Connect returns a new socket connected to localhost on |port| or -1 on
699// error.
700static int Connect(uint16_t port) {
701 int sock = socket(AF_INET, SOCK_STREAM, 0);
702 if (sock == -1) {
703 PrintSocketError("socket");
704 return -1;
705 }
706 int nodelay = 1;
707 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
708 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
709 PrintSocketError("setsockopt");
710 closesocket(sock);
711 return -1;
712 }
713 sockaddr_in sin;
714 memset(&sin, 0, sizeof(sin));
715 sin.sin_family = AF_INET;
716 sin.sin_port = htons(port);
717 if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
718 PrintSocketError("inet_pton");
719 closesocket(sock);
720 return -1;
721 }
722 if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
723 sizeof(sin)) != 0) {
724 PrintSocketError("connect");
725 closesocket(sock);
726 return -1;
727 }
728 return sock;
729}
730
731class SocketCloser {
732 public:
733 explicit SocketCloser(int sock) : sock_(sock) {}
734 ~SocketCloser() {
735 // Half-close and drain the socket before releasing it. This seems to be
736 // necessary for graceful shutdown on Windows. It will also avoid write
737 // failures in the test runner.
738#if defined(OPENSSL_WINDOWS)
739 shutdown(sock_, SD_SEND);
740#else
741 shutdown(sock_, SHUT_WR);
742#endif
743 while (true) {
744 char buf[1024];
745 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
746 break;
747 }
748 }
749 closesocket(sock_);
750 }
751
752 private:
753 const int sock_;
754};
755
David Benjaminc273d2c2015-02-09 12:59:46 -0500756static ScopedSSL_CTX SetupCtx(const TestConfig *config) {
David Benjamina7f333d2015-02-09 02:37:18 -0500757 ScopedSSL_CTX ssl_ctx(SSL_CTX_new(
758 config->is_dtls ? DTLS_method() : TLS_method()));
759 if (!ssl_ctx) {
760 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -0400761 }
762
Adam Langleycef75832015-09-03 14:51:12 -0700763 std::string cipher_list = "ALL";
764 if (!config->cipher.empty()) {
765 cipher_list = config->cipher;
766 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
767 }
768 if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
769 return nullptr;
770 }
771
772 if (!config->cipher_tls10.empty() &&
773 !SSL_CTX_set_cipher_list_tls10(ssl_ctx.get(),
774 config->cipher_tls10.c_str())) {
775 return nullptr;
776 }
777 if (!config->cipher_tls11.empty() &&
778 !SSL_CTX_set_cipher_list_tls11(ssl_ctx.get(),
779 config->cipher_tls11.c_str())) {
David Benjamina7f333d2015-02-09 02:37:18 -0500780 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -0400781 }
782
David Benjamina7f333d2015-02-09 02:37:18 -0500783 ScopedDH dh(DH_get_2048_256(NULL));
David Benjaminb7c5e842016-03-28 09:59:10 -0400784 if (!dh) {
785 return nullptr;
786 }
Adam Langleyc4f25ce2015-11-26 16:39:08 -0800787
788 if (config->use_sparse_dh_prime) {
789 // This prime number is 2^1024 + 643 – a value just above a power of two.
790 // Because of its form, values modulo it are essentially certain to be one
791 // byte shorter. This is used to test padding of these values.
792 if (BN_hex2bn(
793 &dh->p,
794 "1000000000000000000000000000000000000000000000000000000000000000"
795 "0000000000000000000000000000000000000000000000000000000000000000"
796 "0000000000000000000000000000000000000000000000000000000000000000"
797 "0000000000000000000000000000000000000000000000000000000000000028"
798 "3") == 0 ||
799 !BN_set_word(dh->g, 2)) {
800 return nullptr;
801 }
David Benjamine66148a2016-02-02 14:14:36 -0500802 BN_free(dh->q);
803 dh->q = NULL;
Adam Langleyc4f25ce2015-11-26 16:39:08 -0800804 dh->priv_length = 0;
805 }
806
David Benjaminb7c5e842016-03-28 09:59:10 -0400807 if (!SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
David Benjamina7f333d2015-02-09 02:37:18 -0500808 return nullptr;
David Benjaminf4e5c4e2014-08-02 17:35:45 -0400809 }
810
David Benjamin1b8b6912015-02-09 04:28:16 -0500811 if (config->async && config->is_server) {
812 // Disable the internal session cache. To test asynchronous session lookup,
813 // we use an external session cache.
814 SSL_CTX_set_session_cache_mode(
815 ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
David Benjaminc273d2c2015-02-09 12:59:46 -0500816 SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
David Benjamin1b8b6912015-02-09 04:28:16 -0500817 } else {
818 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
819 }
David Benjamin1d5c83e2014-07-22 19:20:02 -0400820
David Benjamind4c2bce2015-10-17 12:28:18 -0400821 SSL_CTX_set_select_certificate_cb(ssl_ctx.get(), SelectCertificateCallback);
David Benjamin8f2c20e2014-07-09 09:30:38 -0400822
David Benjaminacb6dcc2016-03-10 09:15:01 -0500823 if (config->use_old_client_cert_callback) {
824 SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
825 }
826
David Benjamin1f5f62b2014-07-12 16:18:02 -0400827 SSL_CTX_set_next_protos_advertised_cb(
David Benjaminc273d2c2015-02-09 12:59:46 -0500828 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400829 if (!config->select_next_proto.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500830 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
David Benjamina7f333d2015-02-09 02:37:18 -0500831 NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400832 }
833
David Benjamin594e7d22016-03-17 17:49:56 -0400834 if (!config->select_alpn.empty() || config->decline_alpn) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500835 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400836 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400837
Adam Langley49c7af12015-07-10 14:33:46 -0700838 SSL_CTX_enable_tls_channel_id(ssl_ctx.get());
David Benjaminc273d2c2015-02-09 12:59:46 -0500839 SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
David Benjamina08e49d2014-08-24 01:46:07 -0400840
David Benjaminc273d2c2015-02-09 12:59:46 -0500841 ssl_ctx->current_time_cb = CurrentTimeCallback;
David Benjamin377fc312015-01-26 00:22:12 -0500842
David Benjamin87e4acd2015-04-02 19:57:35 -0400843 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
David Benjaminba4594a2015-06-18 18:36:15 -0400844 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
David Benjamin87e4acd2015-04-02 19:57:35 -0400845
David Benjamind98452d2015-06-16 14:16:23 -0400846 if (config->use_ticket_callback) {
847 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
848 }
849
Adam Langley09505632015-07-30 18:10:13 -0700850 if (config->enable_client_custom_extension &&
851 !SSL_CTX_add_client_custom_ext(
852 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
853 CustomExtensionFreeCallback, kCustomExtensionAddArg,
854 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
855 return nullptr;
856 }
857
858 if (config->enable_server_custom_extension &&
859 !SSL_CTX_add_server_custom_ext(
860 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
861 CustomExtensionFreeCallback, kCustomExtensionAddArg,
862 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
863 return nullptr;
864 }
865
Paul Lietar8f1c2682015-08-18 12:21:54 +0100866 if (config->verify_fail) {
867 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
868 } else {
869 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
870 }
871
Paul Lietar4fac72e2015-09-09 13:44:55 +0100872 if (!config->signed_cert_timestamps.empty() &&
873 !SSL_CTX_set_signed_cert_timestamp_list(
874 ssl_ctx.get(), (const uint8_t *)config->signed_cert_timestamps.data(),
875 config->signed_cert_timestamps.size())) {
876 return nullptr;
877 }
878
David Benjamin1d5c83e2014-07-22 19:20:02 -0400879 return ssl_ctx;
David Benjamin1d5c83e2014-07-22 19:20:02 -0400880}
881
David Benjamin40f101b2015-02-20 11:23:42 -0500882// RetryAsync is called after a failed operation on |ssl| with return code
883// |ret|. If the operation should be retried, it simulates one asynchronous
David Benjamin6c2563e2015-04-03 03:47:47 -0400884// event and returns true. Otherwise it returns false.
885static bool RetryAsync(SSL *ssl, int ret) {
David Benjamin43ec06f2014-08-05 02:28:57 -0400886 // No error; don't retry.
887 if (ret >= 0) {
David Benjamin40f101b2015-02-20 11:23:42 -0500888 return false;
David Benjamin025b3d32014-07-01 19:53:04 -0400889 }
David Benjamin83f90402015-01-27 01:09:43 -0500890
David Benjamin7e7a82d2016-05-20 20:12:42 -0400891 const TestConfig *config = GetTestConfig(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -0400892 TestState *test_state = GetTestState(ssl);
893 if (test_state->clock_delta.tv_usec != 0 ||
894 test_state->clock_delta.tv_sec != 0) {
David Benjamin83f90402015-01-27 01:09:43 -0500895 // Process the timeout and retry.
David Benjamin6c2563e2015-04-03 03:47:47 -0400896 test_state->clock.tv_usec += test_state->clock_delta.tv_usec;
897 test_state->clock.tv_sec += test_state->clock.tv_usec / 1000000;
898 test_state->clock.tv_usec %= 1000000;
899 test_state->clock.tv_sec += test_state->clock_delta.tv_sec;
900 memset(&test_state->clock_delta, 0, sizeof(test_state->clock_delta));
David Benjamin83f90402015-01-27 01:09:43 -0500901
David Benjamin13e81fc2015-11-02 17:16:13 -0500902 // The DTLS retransmit logic silently ignores write failures. So the test
903 // may progress, allow writes through synchronously.
904 if (config->async) {
905 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
906 }
907 int timeout_ret = DTLSv1_handle_timeout(ssl);
908 if (config->async) {
909 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
910 }
911
912 if (timeout_ret < 0) {
David Benjaminc565ebb2015-04-03 04:06:36 -0400913 fprintf(stderr, "Error retransmitting.\n");
David Benjamin40f101b2015-02-20 11:23:42 -0500914 return false;
David Benjamin83f90402015-01-27 01:09:43 -0500915 }
David Benjamin40f101b2015-02-20 11:23:42 -0500916 return true;
David Benjamin83f90402015-01-27 01:09:43 -0500917 }
918
David Benjamin43ec06f2014-08-05 02:28:57 -0400919 // See if we needed to read or write more. If so, allow one byte through on
920 // the appropriate end to maximally stress the state machine.
David Benjamind9e07012015-02-09 03:04:34 -0500921 switch (SSL_get_error(ssl, ret)) {
922 case SSL_ERROR_WANT_READ:
David Benjamin6c2563e2015-04-03 03:47:47 -0400923 AsyncBioAllowRead(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -0500924 return true;
David Benjamind9e07012015-02-09 03:04:34 -0500925 case SSL_ERROR_WANT_WRITE:
David Benjamin6c2563e2015-04-03 03:47:47 -0400926 AsyncBioAllowWrite(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -0500927 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -0500928 case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400929 ScopedEVP_PKEY pkey = LoadPrivateKey(GetTestConfig(ssl)->send_channel_id);
David Benjamin9d0847a2015-02-16 03:57:55 -0500930 if (!pkey) {
David Benjamin40f101b2015-02-20 11:23:42 -0500931 return false;
David Benjamin9d0847a2015-02-16 03:57:55 -0500932 }
David Benjamin6c2563e2015-04-03 03:47:47 -0400933 test_state->channel_id = std::move(pkey);
David Benjamin40f101b2015-02-20 11:23:42 -0500934 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -0500935 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500936 case SSL_ERROR_WANT_X509_LOOKUP:
David Benjamin6c2563e2015-04-03 03:47:47 -0400937 test_state->cert_ready = true;
David Benjamin40f101b2015-02-20 11:23:42 -0500938 return true;
David Benjamin1b8b6912015-02-09 04:28:16 -0500939 case SSL_ERROR_PENDING_SESSION:
David Benjamin6c2563e2015-04-03 03:47:47 -0400940 test_state->session = std::move(test_state->pending_session);
David Benjamin40f101b2015-02-20 11:23:42 -0500941 return true;
David Benjamin6f5c0f42015-02-24 01:23:21 -0500942 case SSL_ERROR_PENDING_CERTIFICATE:
943 // The handshake will resume without a second call to the early callback.
944 return InstallCertificate(ssl);
David Benjaminb4d65fd2015-05-29 17:11:21 -0400945 case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700946 test_state->private_key_retries++;
David Benjaminb4d65fd2015-05-29 17:11:21 -0400947 return true;
David Benjamind9e07012015-02-09 03:04:34 -0500948 default:
David Benjamin40f101b2015-02-20 11:23:42 -0500949 return false;
David Benjamin025b3d32014-07-01 19:53:04 -0400950 }
David Benjamin025b3d32014-07-01 19:53:04 -0400951}
952
David Benjamin6c2563e2015-04-03 03:47:47 -0400953// DoRead reads from |ssl|, resolving any asynchronous operations. It returns
954// the result value of the final |SSL_read| call.
955static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400956 const TestConfig *config = GetTestConfig(ssl);
David Benjamin13e81fc2015-11-02 17:16:13 -0500957 TestState *test_state = GetTestState(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -0400958 int ret;
959 do {
David Benjamin13e81fc2015-11-02 17:16:13 -0500960 if (config->async) {
961 // The DTLS retransmit logic silently ignores write failures. So the test
962 // may progress, allow writes through synchronously. |SSL_read| may
963 // trigger a retransmit, so disconnect the write quota.
964 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
965 }
David Benjamin6c2563e2015-04-03 03:47:47 -0400966 ret = SSL_read(ssl, out, max_out);
David Benjamin13e81fc2015-11-02 17:16:13 -0500967 if (config->async) {
968 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
969 }
David Benjamin6c2563e2015-04-03 03:47:47 -0400970 } while (config->async && RetryAsync(ssl, ret));
971 return ret;
972}
973
974// WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
975// operations. It returns the result of the final |SSL_write| call.
976static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400977 const TestConfig *config = GetTestConfig(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -0400978 int ret;
979 do {
980 ret = SSL_write(ssl, in, in_len);
981 if (ret > 0) {
982 in += ret;
983 in_len -= ret;
984 }
985 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
986 return ret;
987}
988
David Benjamin30789da2015-08-29 22:56:45 -0400989// DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
990// returns the result of the final |SSL_shutdown| call.
991static int DoShutdown(SSL *ssl) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400992 const TestConfig *config = GetTestConfig(ssl);
David Benjamin30789da2015-08-29 22:56:45 -0400993 int ret;
994 do {
995 ret = SSL_shutdown(ssl);
996 } while (config->async && RetryAsync(ssl, ret));
997 return ret;
998}
999
David Benjamin91eab5c2015-06-18 18:35:46 -04001000// CheckHandshakeProperties checks, immediately after |ssl| completes its
1001// initial handshake (or False Starts), whether all the properties are
1002// consistent with the test configuration and invariants.
1003static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
David Benjamin7e7a82d2016-05-20 20:12:42 -04001004 const TestConfig *config = GetTestConfig(ssl);
David Benjamin91eab5c2015-06-18 18:35:46 -04001005
1006 if (SSL_get_current_cipher(ssl) == nullptr) {
1007 fprintf(stderr, "null cipher after handshake\n");
1008 return false;
1009 }
1010
1011 if (is_resume &&
1012 (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
1013 fprintf(stderr, "session was%s reused\n",
1014 SSL_session_reused(ssl) ? "" : " not");
1015 return false;
1016 }
1017
1018 bool expect_handshake_done = is_resume || !config->false_start;
1019 if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
1020 fprintf(stderr, "handshake was%s completed\n",
1021 GetTestState(ssl)->handshake_done ? "" : " not");
1022 return false;
1023 }
1024
David Benjaminba4594a2015-06-18 18:36:15 -04001025 if (expect_handshake_done && !config->is_server) {
1026 bool expect_new_session =
1027 !config->expect_no_session &&
1028 (!SSL_session_reused(ssl) || config->expect_ticket_renewal);
1029 if (expect_new_session != GetTestState(ssl)->got_new_session) {
1030 fprintf(stderr,
David Benjamindd6fed92015-10-23 17:41:12 -04001031 "new session was%s cached, but we expected the opposite\n",
David Benjaminba4594a2015-06-18 18:36:15 -04001032 GetTestState(ssl)->got_new_session ? "" : " not");
1033 return false;
1034 }
1035 }
1036
David Benjamin91eab5c2015-06-18 18:35:46 -04001037 if (config->is_server && !GetTestState(ssl)->early_callback_called) {
1038 fprintf(stderr, "early callback not called\n");
1039 return false;
1040 }
1041
1042 if (!config->expected_server_name.empty()) {
1043 const char *server_name =
1044 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1045 if (server_name != config->expected_server_name) {
1046 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
1047 server_name, config->expected_server_name.c_str());
1048 return false;
1049 }
1050 }
1051
1052 if (!config->expected_certificate_types.empty()) {
David Benjamin75910642015-08-09 10:42:33 -04001053 const uint8_t *certificate_types;
1054 size_t certificate_types_len =
David Benjamin91eab5c2015-06-18 18:35:46 -04001055 SSL_get0_certificate_types(ssl, &certificate_types);
David Benjamin75910642015-08-09 10:42:33 -04001056 if (certificate_types_len != config->expected_certificate_types.size() ||
David Benjamin91eab5c2015-06-18 18:35:46 -04001057 memcmp(certificate_types,
1058 config->expected_certificate_types.data(),
David Benjamin75910642015-08-09 10:42:33 -04001059 certificate_types_len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001060 fprintf(stderr, "certificate types mismatch\n");
1061 return false;
1062 }
1063 }
1064
1065 if (!config->expected_next_proto.empty()) {
1066 const uint8_t *next_proto;
1067 unsigned next_proto_len;
1068 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
1069 if (next_proto_len != config->expected_next_proto.size() ||
1070 memcmp(next_proto, config->expected_next_proto.data(),
1071 next_proto_len) != 0) {
1072 fprintf(stderr, "negotiated next proto mismatch\n");
1073 return false;
1074 }
1075 }
1076
1077 if (!config->expected_alpn.empty()) {
1078 const uint8_t *alpn_proto;
1079 unsigned alpn_proto_len;
1080 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
1081 if (alpn_proto_len != config->expected_alpn.size() ||
1082 memcmp(alpn_proto, config->expected_alpn.data(),
1083 alpn_proto_len) != 0) {
1084 fprintf(stderr, "negotiated alpn proto mismatch\n");
1085 return false;
1086 }
1087 }
1088
1089 if (!config->expected_channel_id.empty()) {
1090 uint8_t channel_id[64];
1091 if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
1092 fprintf(stderr, "no channel id negotiated\n");
1093 return false;
1094 }
1095 if (config->expected_channel_id.size() != 64 ||
1096 memcmp(config->expected_channel_id.data(),
1097 channel_id, 64) != 0) {
1098 fprintf(stderr, "channel id mismatch\n");
1099 return false;
1100 }
1101 }
1102
1103 if (config->expect_extended_master_secret) {
1104 if (!ssl->session->extended_master_secret) {
1105 fprintf(stderr, "No EMS for session when expected");
1106 return false;
1107 }
1108 }
1109
1110 if (!config->expected_ocsp_response.empty()) {
1111 const uint8_t *data;
1112 size_t len;
1113 SSL_get0_ocsp_response(ssl, &data, &len);
1114 if (config->expected_ocsp_response.size() != len ||
1115 memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
1116 fprintf(stderr, "OCSP response mismatch\n");
1117 return false;
1118 }
1119 }
1120
1121 if (!config->expected_signed_cert_timestamps.empty()) {
1122 const uint8_t *data;
1123 size_t len;
1124 SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
1125 if (config->expected_signed_cert_timestamps.size() != len ||
1126 memcmp(config->expected_signed_cert_timestamps.data(),
1127 data, len) != 0) {
1128 fprintf(stderr, "SCT list mismatch\n");
1129 return false;
1130 }
1131 }
1132
Paul Lietar8f1c2682015-08-18 12:21:54 +01001133 if (config->expect_verify_result) {
1134 int expected_verify_result = config->verify_fail ?
1135 X509_V_ERR_APPLICATION_VERIFICATION :
1136 X509_V_OK;
1137
1138 if (SSL_get_verify_result(ssl) != expected_verify_result) {
1139 fprintf(stderr, "Wrong certificate verification result\n");
1140 return false;
1141 }
1142 }
1143
David Benjamin6e807652015-11-02 12:02:20 -05001144 if (config->expect_server_key_exchange_hash != 0 &&
1145 config->expect_server_key_exchange_hash !=
1146 SSL_get_server_key_exchange_hash(ssl)) {
1147 fprintf(stderr, "ServerKeyExchange hash was %d, wanted %d.\n",
1148 SSL_get_server_key_exchange_hash(ssl),
1149 config->expect_server_key_exchange_hash);
1150 return false;
1151 }
1152
David Benjamin4cc36ad2015-12-19 14:23:26 -05001153 if (config->expect_key_exchange_info != 0) {
1154 uint32_t info = SSL_SESSION_get_key_exchange_info(SSL_get_session(ssl));
1155 if (static_cast<uint32_t>(config->expect_key_exchange_info) != info) {
1156 fprintf(stderr, "key_exchange_info was %" PRIu32 ", wanted %" PRIu32 "\n",
1157 info, static_cast<uint32_t>(config->expect_key_exchange_info));
1158 return false;
1159 }
1160 }
1161
David Benjamin91eab5c2015-06-18 18:35:46 -04001162 if (!config->is_server) {
1163 /* Clients should expect a peer certificate chain iff this was not a PSK
1164 * cipher suite. */
1165 if (config->psk.empty()) {
1166 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
1167 fprintf(stderr, "Missing peer certificate chain!\n");
1168 return false;
1169 }
1170 } else if (SSL_get_peer_cert_chain(ssl) != nullptr) {
1171 fprintf(stderr, "Unexpected peer certificate chain!\n");
1172 return false;
1173 }
1174 }
1175 return true;
1176}
1177
David Benjamin87c8a642015-02-21 01:54:29 -05001178// DoExchange runs a test SSL exchange against the peer. On success, it returns
1179// true and sets |*out_session| to the negotiated SSL session. If the test is a
1180// resumption attempt, |is_resume| is true and |session| is the session from the
1181// previous exchange.
David Benjamin40f101b2015-02-20 11:23:42 -05001182static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx,
1183 const TestConfig *config, bool is_resume,
David Benjamin87c8a642015-02-21 01:54:29 -05001184 SSL_SESSION *session) {
David Benjamina7f333d2015-02-09 02:37:18 -05001185 ScopedSSL ssl(SSL_new(ssl_ctx));
1186 if (!ssl) {
David Benjamin40f101b2015-02-20 11:23:42 -05001187 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001188 }
1189
David Benjamin7e7a82d2016-05-20 20:12:42 -04001190 if (!SetTestConfig(ssl.get(), config) ||
David Benjamin2d445c02015-02-09 13:03:50 -05001191 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
David Benjamin40f101b2015-02-20 11:23:42 -05001192 return false;
Adam Langley69a01602014-11-17 17:26:55 -08001193 }
David Benjamin5a593af2014-08-11 19:51:50 -04001194
Adam Langley5f0efe02015-02-20 13:03:16 -08001195 if (config->fallback_scsv &&
1196 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
1197 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001198 }
David Benjaminacb6dcc2016-03-10 09:15:01 -05001199 if (!config->use_early_callback && !config->use_old_client_cert_callback) {
David Benjamin6f5c0f42015-02-24 01:23:21 -05001200 if (config->async) {
David Benjamin6f5c0f42015-02-24 01:23:21 -05001201 SSL_set_cert_cb(ssl.get(), CertCallback, NULL);
1202 } else if (!InstallCertificate(ssl.get())) {
1203 return false;
1204 }
David Benjamin5a593af2014-08-11 19:51:50 -04001205 }
1206 if (config->require_any_client_certificate) {
David Benjamina7f333d2015-02-09 02:37:18 -05001207 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
Paul Lietar8f1c2682015-08-18 12:21:54 +01001208 NULL);
1209 }
1210 if (config->verify_peer) {
1211 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
David Benjamin5a593af2014-08-11 19:51:50 -04001212 }
1213 if (config->false_start) {
David Benjamined7c4752015-02-16 19:16:46 -05001214 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
David Benjamin5a593af2014-08-11 19:51:50 -04001215 }
1216 if (config->cbc_record_splitting) {
David Benjamina7f333d2015-02-09 02:37:18 -05001217 SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
David Benjamin5a593af2014-08-11 19:51:50 -04001218 }
1219 if (config->partial_write) {
David Benjamina7f333d2015-02-09 02:37:18 -05001220 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
David Benjamin5a593af2014-08-11 19:51:50 -04001221 }
Steven Valdez4f94b1c2016-05-24 12:31:07 -04001222 if (config->no_tls13) {
1223 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
1224 }
David Benjamin5a593af2014-08-11 19:51:50 -04001225 if (config->no_tls12) {
David Benjamina7f333d2015-02-09 02:37:18 -05001226 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
David Benjamin5a593af2014-08-11 19:51:50 -04001227 }
1228 if (config->no_tls11) {
David Benjamina7f333d2015-02-09 02:37:18 -05001229 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
David Benjamin5a593af2014-08-11 19:51:50 -04001230 }
1231 if (config->no_tls1) {
David Benjamina7f333d2015-02-09 02:37:18 -05001232 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
David Benjamin5a593af2014-08-11 19:51:50 -04001233 }
1234 if (config->no_ssl3) {
David Benjamina7f333d2015-02-09 02:37:18 -05001235 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
David Benjamin5a593af2014-08-11 19:51:50 -04001236 }
David Benjamina08e49d2014-08-24 01:46:07 -04001237 if (!config->expected_channel_id.empty()) {
David Benjamina7f333d2015-02-09 02:37:18 -05001238 SSL_enable_tls_channel_id(ssl.get());
David Benjamina08e49d2014-08-24 01:46:07 -04001239 }
1240 if (!config->send_channel_id.empty()) {
David Benjamina7f333d2015-02-09 02:37:18 -05001241 SSL_enable_tls_channel_id(ssl.get());
David Benjamind9e07012015-02-09 03:04:34 -05001242 if (!config->async) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001243 // The async case will be supplied by |ChannelIdCallback|.
David Benjamind9e07012015-02-09 03:04:34 -05001244 ScopedEVP_PKEY pkey = LoadPrivateKey(config->send_channel_id);
1245 if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001246 return false;
David Benjamind9e07012015-02-09 03:04:34 -05001247 }
David Benjamina08e49d2014-08-24 01:46:07 -04001248 }
David Benjamina08e49d2014-08-24 01:46:07 -04001249 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001250 if (!config->host_name.empty() &&
1251 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001252 return false;
David Benjamine78bfde2014-09-06 12:45:15 -04001253 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001254 if (!config->advertise_alpn.empty() &&
1255 SSL_set_alpn_protos(ssl.get(),
1256 (const uint8_t *)config->advertise_alpn.data(),
1257 config->advertise_alpn.size()) != 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001258 return false;
David Benjaminae2888f2014-09-06 12:58:58 -04001259 }
David Benjamin48cae082014-10-27 01:06:24 -04001260 if (!config->psk.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001261 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
1262 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
David Benjamin48cae082014-10-27 01:06:24 -04001263 }
David Benjamin61f95272014-11-25 01:55:35 -05001264 if (!config->psk_identity.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001265 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001266 return false;
David Benjamin48cae082014-10-27 01:06:24 -04001267 }
David Benjamin61f95272014-11-25 01:55:35 -05001268 if (!config->srtp_profiles.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001269 !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001270 return false;
David Benjamin61f95272014-11-25 01:55:35 -05001271 }
1272 if (config->enable_ocsp_stapling &&
David Benjamina7f333d2015-02-09 02:37:18 -05001273 !SSL_enable_ocsp_stapling(ssl.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001274 return false;
David Benjamin61f95272014-11-25 01:55:35 -05001275 }
1276 if (config->enable_signed_cert_timestamps &&
David Benjamina7f333d2015-02-09 02:37:18 -05001277 !SSL_enable_signed_cert_timestamps(ssl.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001278 return false;
David Benjaminca6c8262014-11-15 19:06:08 -05001279 }
David Benjamin1eb367c2014-12-12 18:17:51 -05001280 if (config->min_version != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001281 SSL_set_min_version(ssl.get(), (uint16_t)config->min_version);
David Benjamin1eb367c2014-12-12 18:17:51 -05001282 }
1283 if (config->max_version != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001284 SSL_set_max_version(ssl.get(), (uint16_t)config->max_version);
David Benjamin1eb367c2014-12-12 18:17:51 -05001285 }
David Benjamin13be1de2015-01-11 16:29:36 -05001286 if (config->mtu != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001287 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
1288 SSL_set_mtu(ssl.get(), config->mtu);
David Benjamin13be1de2015-01-11 16:29:36 -05001289 }
Adam Langley524e7172015-02-20 16:04:00 -08001290 if (config->install_ddos_callback) {
1291 SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
1292 }
David Benjamin1d5ef3b2015-10-12 19:54:18 -04001293 if (config->renegotiate_once) {
1294 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_once);
1295 }
1296 if (config->renegotiate_freely) {
1297 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
David Benjaminb16346b2015-04-08 19:16:58 -04001298 }
Adam Langley27a0d082015-11-03 13:34:10 -08001299 if (config->renegotiate_ignore) {
1300 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_ignore);
1301 }
David Benjamin30789da2015-08-29 22:56:45 -04001302 if (!config->check_close_notify) {
1303 SSL_set_quiet_shutdown(ssl.get(), 1);
1304 }
David Benjamin091c4b92015-10-26 13:33:21 -04001305 if (config->disable_npn) {
1306 SSL_set_options(ssl.get(), SSL_OP_DISABLE_NPN);
1307 }
David Benjamin99fdfb92015-11-02 12:11:35 -05001308 if (config->p384_only) {
1309 int nid = NID_secp384r1;
1310 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
1311 return false;
1312 }
1313 }
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001314 if (config->enable_all_curves) {
1315 static const int kAllCurves[] = {
Matt Braithwaitee25775b2016-05-16 16:31:05 -07001316 NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_X25519, NID_cecpq1
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001317 };
1318 if (!SSL_set1_curves(ssl.get(), kAllCurves,
1319 sizeof(kAllCurves) / sizeof(kAllCurves[0]))) {
1320 return false;
1321 }
1322 }
Taylor Brandstetter376a0fe2016-05-10 19:30:28 -07001323 if (config->initial_timeout_duration_ms > 0) {
1324 DTLSv1_set_initial_timeout_duration(ssl.get(),
1325 config->initial_timeout_duration_ms);
1326 }
David Benjamin025b3d32014-07-01 19:53:04 -04001327
David Benjamin87c8a642015-02-21 01:54:29 -05001328 int sock = Connect(config->port);
1329 if (sock == -1) {
1330 return false;
1331 }
1332 SocketCloser closer(sock);
1333
1334 ScopedBIO bio(BIO_new_socket(sock, BIO_NOCLOSE));
David Benjamina7f333d2015-02-09 02:37:18 -05001335 if (!bio) {
David Benjamin40f101b2015-02-20 11:23:42 -05001336 return false;
David Benjamin43ec06f2014-08-05 02:28:57 -04001337 }
David Benjamin6fd297b2014-08-11 18:43:38 -04001338 if (config->is_dtls) {
David Benjamin6c2563e2015-04-03 03:47:47 -04001339 ScopedBIO packeted =
1340 PacketedBioCreate(&GetTestState(ssl.get())->clock_delta);
David Benjaminb7c5e842016-03-28 09:59:10 -04001341 if (!packeted) {
1342 return false;
1343 }
David Benjamina7f333d2015-02-09 02:37:18 -05001344 BIO_push(packeted.get(), bio.release());
1345 bio = std::move(packeted);
David Benjamin6fd297b2014-08-11 18:43:38 -04001346 }
David Benjamin5a593af2014-08-11 19:51:50 -04001347 if (config->async) {
David Benjamina7f333d2015-02-09 02:37:18 -05001348 ScopedBIO async_scoped =
David Benjaminc273d2c2015-02-09 12:59:46 -05001349 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
David Benjaminb7c5e842016-03-28 09:59:10 -04001350 if (!async_scoped) {
1351 return false;
1352 }
David Benjamina7f333d2015-02-09 02:37:18 -05001353 BIO_push(async_scoped.get(), bio.release());
David Benjamin6c2563e2015-04-03 03:47:47 -04001354 GetTestState(ssl.get())->async_bio = async_scoped.get();
David Benjamina7f333d2015-02-09 02:37:18 -05001355 bio = std::move(async_scoped);
David Benjamin43ec06f2014-08-05 02:28:57 -04001356 }
David Benjamina7f333d2015-02-09 02:37:18 -05001357 SSL_set_bio(ssl.get(), bio.get(), bio.get());
1358 bio.release(); // SSL_set_bio takes ownership.
David Benjamin43ec06f2014-08-05 02:28:57 -04001359
David Benjamin1d5c83e2014-07-22 19:20:02 -04001360 if (session != NULL) {
David Benjamin1b8b6912015-02-09 04:28:16 -05001361 if (!config->is_server) {
1362 if (SSL_set_session(ssl.get(), session) != 1) {
David Benjamin40f101b2015-02-20 11:23:42 -05001363 return false;
David Benjamin1b8b6912015-02-09 04:28:16 -05001364 }
1365 } else if (config->async) {
1366 // The internal session cache is disabled, so install the session
1367 // manually.
David Benjamin2d445c02015-02-09 13:03:50 -05001368 GetTestState(ssl.get())->pending_session.reset(
David Benjamin1b8b6912015-02-09 04:28:16 -05001369 SSL_SESSION_up_ref(session));
David Benjamin1d5c83e2014-07-22 19:20:02 -04001370 }
1371 }
1372
David Benjamina07c0fc2015-05-13 13:19:42 -04001373 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1374 fprintf(stderr, "non-null cipher before handshake\n");
1375 return false;
1376 }
1377
David Benjamin1d5c83e2014-07-22 19:20:02 -04001378 int ret;
David Benjamine0e7d0d2015-02-08 19:33:25 -05001379 if (config->implicit_handshake) {
David Benjamin5a593af2014-08-11 19:51:50 -04001380 if (config->is_server) {
David Benjamina7f333d2015-02-09 02:37:18 -05001381 SSL_set_accept_state(ssl.get());
David Benjamin43ec06f2014-08-05 02:28:57 -04001382 } else {
David Benjamina7f333d2015-02-09 02:37:18 -05001383 SSL_set_connect_state(ssl.get());
David Benjamin43ec06f2014-08-05 02:28:57 -04001384 }
David Benjamine0e7d0d2015-02-08 19:33:25 -05001385 } else {
1386 do {
1387 if (config->is_server) {
David Benjamina7f333d2015-02-09 02:37:18 -05001388 ret = SSL_accept(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -05001389 } else {
David Benjamina7f333d2015-02-09 02:37:18 -05001390 ret = SSL_connect(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -05001391 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001392 } while (config->async && RetryAsync(ssl.get(), ret));
David Benjamin91eab5c2015-06-18 18:35:46 -04001393 if (ret != 1 ||
1394 !CheckHandshakeProperties(ssl.get(), is_resume)) {
David Benjamin40f101b2015-02-20 11:23:42 -05001395 return false;
David Benjamine0e7d0d2015-02-08 19:33:25 -05001396 }
David Benjamin025b3d32014-07-01 19:53:04 -04001397
David Benjaminba4594a2015-06-18 18:36:15 -04001398 // Reset the state to assert later that the callback isn't called in
1399 // renegotations.
1400 GetTestState(ssl.get())->got_new_session = false;
David Benjamin61f95272014-11-25 01:55:35 -05001401 }
1402
David Benjaminc565ebb2015-04-03 04:06:36 -04001403 if (config->export_keying_material > 0) {
1404 std::vector<uint8_t> result(
1405 static_cast<size_t>(config->export_keying_material));
1406 if (!SSL_export_keying_material(
1407 ssl.get(), result.data(), result.size(),
1408 config->export_label.data(), config->export_label.size(),
1409 reinterpret_cast<const uint8_t*>(config->export_context.data()),
1410 config->export_context.size(), config->use_export_context)) {
1411 fprintf(stderr, "failed to export keying material\n");
1412 return false;
1413 }
1414 if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1415 return false;
1416 }
1417 }
1418
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001419 if (config->tls_unique) {
1420 uint8_t tls_unique[16];
1421 size_t tls_unique_len;
1422 if (!SSL_get_tls_unique(ssl.get(), tls_unique, &tls_unique_len,
1423 sizeof(tls_unique))) {
1424 fprintf(stderr, "failed to get tls-unique\n");
1425 return false;
1426 }
1427
1428 if (tls_unique_len != 12) {
1429 fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
1430 static_cast<unsigned>(tls_unique_len));
1431 return false;
1432 }
1433
1434 if (WriteAll(ssl.get(), tls_unique, tls_unique_len) < 0) {
1435 return false;
1436 }
1437 }
1438
David Benjamin5a593af2014-08-11 19:51:50 -04001439 if (config->write_different_record_sizes) {
David Benjamin6fd297b2014-08-11 18:43:38 -04001440 if (config->is_dtls) {
1441 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001442 return false;
David Benjamin6fd297b2014-08-11 18:43:38 -04001443 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001444 // This mode writes a number of different record sizes in an attempt to
1445 // trip up the CBC record splitting code.
Adam Langleybc949292015-06-18 21:32:44 -07001446 static const size_t kBufLen = 32769;
1447 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1448 memset(buf.get(), 0x42, kBufLen);
Kenny Root7fdeaf12014-08-05 15:23:37 -07001449 static const size_t kRecordSizes[] = {
1450 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
1451 for (size_t i = 0; i < sizeof(kRecordSizes) / sizeof(kRecordSizes[0]);
1452 i++) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07001453 const size_t len = kRecordSizes[i];
Adam Langleybc949292015-06-18 21:32:44 -07001454 if (len > kBufLen) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07001455 fprintf(stderr, "Bad kRecordSizes value.\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001456 return false;
Kenny Root7fdeaf12014-08-05 15:23:37 -07001457 }
Adam Langleybc949292015-06-18 21:32:44 -07001458 if (WriteAll(ssl.get(), buf.get(), len) < 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001459 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001460 }
1461 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001462 } else {
David Benjamine58c4f52014-08-24 03:47:07 -04001463 if (config->shim_writes_first) {
David Benjamin6c2563e2015-04-03 03:47:47 -04001464 if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1465 5) < 0) {
1466 return false;
1467 }
David Benjamine58c4f52014-08-24 03:47:07 -04001468 }
David Benjamin30789da2015-08-29 22:56:45 -04001469 if (!config->shim_shuts_down) {
1470 for (;;) {
Adam Langleya0a8dc22015-09-09 10:22:00 -07001471 static const size_t kBufLen = 16384;
1472 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1473
David Benjamin2c99d282015-09-01 10:23:00 -04001474 // Read only 512 bytes at a time in TLS to ensure records may be
1475 // returned in multiple reads.
Adam Langleya0a8dc22015-09-09 10:22:00 -07001476 int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
David Benjamin30789da2015-08-29 22:56:45 -04001477 int err = SSL_get_error(ssl.get(), n);
1478 if (err == SSL_ERROR_ZERO_RETURN ||
1479 (n == 0 && err == SSL_ERROR_SYSCALL)) {
1480 if (n != 0) {
1481 fprintf(stderr, "Invalid SSL_get_error output\n");
1482 return false;
1483 }
1484 // Stop on either clean or unclean shutdown.
1485 break;
1486 } else if (err != SSL_ERROR_NONE) {
1487 if (n > 0) {
1488 fprintf(stderr, "Invalid SSL_get_error output\n");
1489 return false;
1490 }
1491 return false;
1492 }
1493 // Successfully read data.
1494 if (n <= 0) {
David Benjamin9a38e922015-01-22 16:06:11 -05001495 fprintf(stderr, "Invalid SSL_get_error output\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001496 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001497 }
David Benjamin30789da2015-08-29 22:56:45 -04001498
1499 // After a successful read, with or without False Start, the handshake
1500 // must be complete.
1501 if (!GetTestState(ssl.get())->handshake_done) {
1502 fprintf(stderr, "handshake was not completed after SSL_read\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001503 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001504 }
David Benjamin87e4acd2015-04-02 19:57:35 -04001505
David Benjamin30789da2015-08-29 22:56:45 -04001506 for (int i = 0; i < n; i++) {
1507 buf[i] ^= 0xff;
1508 }
Adam Langleya0a8dc22015-09-09 10:22:00 -07001509 if (WriteAll(ssl.get(), buf.get(), n) < 0) {
David Benjamin30789da2015-08-29 22:56:45 -04001510 return false;
1511 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001512 }
1513 }
David Benjamin025b3d32014-07-01 19:53:04 -04001514 }
1515
David Benjaminba4594a2015-06-18 18:36:15 -04001516 if (!config->is_server && !config->false_start &&
1517 !config->implicit_handshake &&
1518 GetTestState(ssl.get())->got_new_session) {
1519 fprintf(stderr, "new session was established after the handshake\n");
1520 return false;
1521 }
1522
David Benjamin1d5c83e2014-07-22 19:20:02 -04001523 if (out_session) {
David Benjamina7f333d2015-02-09 02:37:18 -05001524 out_session->reset(SSL_get1_session(ssl.get()));
David Benjamin1d5c83e2014-07-22 19:20:02 -04001525 }
1526
David Benjamin30789da2015-08-29 22:56:45 -04001527 ret = DoShutdown(ssl.get());
1528
1529 if (config->shim_shuts_down && config->check_close_notify) {
1530 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1531 // it returns zero when our close_notify is sent, then one when the peer's
1532 // is received.
1533 if (ret != 0) {
1534 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1535 return false;
1536 }
1537 ret = DoShutdown(ssl.get());
1538 }
1539
1540 if (ret != 1) {
1541 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1542 return false;
1543 }
1544
David Benjamin324dce42015-10-12 19:49:00 -04001545 if (SSL_total_renegotiations(ssl.get()) !=
1546 config->expect_total_renegotiations) {
1547 fprintf(stderr, "Expected %d renegotiations, got %d\n",
1548 config->expect_total_renegotiations,
1549 SSL_total_renegotiations(ssl.get()));
1550 return false;
1551 }
1552
David Benjamin40f101b2015-02-20 11:23:42 -05001553 return true;
David Benjamin025b3d32014-07-01 19:53:04 -04001554}
David Benjamin1d5c83e2014-07-22 19:20:02 -04001555
David Benjaminff3a1492016-03-02 10:12:06 -05001556class StderrDelimiter {
1557 public:
1558 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
1559};
1560
David Benjamin1d5c83e2014-07-22 19:20:02 -04001561int main(int argc, char **argv) {
David Benjaminff3a1492016-03-02 10:12:06 -05001562 // To distinguish ASan's output from ours, add a trailing message to stderr.
1563 // Anything following this line will be considered an error.
1564 StderrDelimiter delimiter;
1565
David Benjamin87c8a642015-02-21 01:54:29 -05001566#if defined(OPENSSL_WINDOWS)
1567 /* Initialize Winsock. */
1568 WORD wsa_version = MAKEWORD(2, 2);
1569 WSADATA wsa_data;
1570 int wsa_err = WSAStartup(wsa_version, &wsa_data);
1571 if (wsa_err != 0) {
1572 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1573 return 1;
1574 }
1575 if (wsa_data.wVersion != wsa_version) {
1576 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1577 return 1;
1578 }
1579#else
David Benjamin1d5c83e2014-07-22 19:20:02 -04001580 signal(SIGPIPE, SIG_IGN);
Adam Langleyded93582014-07-31 15:23:51 -07001581#endif
David Benjamin1d5c83e2014-07-22 19:20:02 -04001582
David Benjamin7a1eefd2015-10-17 23:39:22 -04001583 CRYPTO_library_init();
David Benjamind9e07012015-02-09 03:04:34 -05001584 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
David Benjamin2d445c02015-02-09 13:03:50 -05001585 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
David Benjamin6c2563e2015-04-03 03:47:47 -04001586 if (g_config_index < 0 || g_state_index < 0) {
David Benjaminae3e4872014-11-18 21:52:26 -05001587 return 1;
1588 }
David Benjamin5a593af2014-08-11 19:51:50 -04001589
1590 TestConfig config;
1591 if (!ParseConfig(argc - 1, argv + 1, &config)) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001592 return Usage(argv[0]);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001593 }
1594
David Benjaminc273d2c2015-02-09 12:59:46 -05001595 ScopedSSL_CTX ssl_ctx = SetupCtx(&config);
David Benjamina7f333d2015-02-09 02:37:18 -05001596 if (!ssl_ctx) {
Brian Smith83a82982015-04-09 16:21:10 -10001597 ERR_print_errors_fp(stderr);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001598 return 1;
1599 }
1600
David Benjamina7f333d2015-02-09 02:37:18 -05001601 ScopedSSL_SESSION session;
David Benjamin40f101b2015-02-20 11:23:42 -05001602 if (!DoExchange(&session, ssl_ctx.get(), &config, false /* is_resume */,
David Benjamin87c8a642015-02-21 01:54:29 -05001603 NULL /* session */)) {
Brian Smith83a82982015-04-09 16:21:10 -10001604 ERR_print_errors_fp(stderr);
David Benjamin40f101b2015-02-20 11:23:42 -05001605 return 1;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001606 }
1607
David Benjamin40f101b2015-02-20 11:23:42 -05001608 if (config.resume &&
1609 !DoExchange(NULL, ssl_ctx.get(), &config, true /* is_resume */,
David Benjamin87c8a642015-02-21 01:54:29 -05001610 session.get())) {
Brian Smith83a82982015-04-09 16:21:10 -10001611 ERR_print_errors_fp(stderr);
David Benjamin40f101b2015-02-20 11:23:42 -05001612 return 1;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001613 }
1614
David Benjamina7f333d2015-02-09 02:37:18 -05001615 return 0;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001616}