blob: 4f27c1717d16df4229c214ac29299d0c810efe34 [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 Benjamin99fdfb92015-11-02 12:11:35 -050049#include <openssl/obj.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
Adam Langley69a01602014-11-17 17:26:55 -0800120static bool SetConfigPtr(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 Benjamin87e4acd2015-04-02 19:57:35 -0400124static const TestConfig *GetConfigPtr(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 Benjamina7f333d2015-02-09 02:37:18 -0500141static ScopedEVP_PKEY LoadPrivateKey(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;
David Benjamina08e49d2014-08-24 01:46:07 -0400145 }
David Benjamina7f333d2015-02-09 02:37:18 -0500146 ScopedEVP_PKEY pkey(PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
David Benjamina08e49d2014-08-24 01:46:07 -0400147 return pkey;
148}
149
David Benjaminb4d65fd2015-05-29 17:11:21 -0400150static int AsyncPrivateKeyType(SSL *ssl) {
151 return EVP_PKEY_id(GetTestState(ssl)->private_key.get());
152}
153
David Benjaminb4d65fd2015-05-29 17:11:21 -0400154static size_t AsyncPrivateKeyMaxSignatureLen(SSL *ssl) {
155 return EVP_PKEY_size(GetTestState(ssl)->private_key.get());
156}
157
158static ssl_private_key_result_t AsyncPrivateKeySign(
159 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
160 const EVP_MD *md, const uint8_t *in, size_t in_len) {
161 TestState *test_state = GetTestState(ssl);
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700162 if (!test_state->private_key_result.empty()) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400163 fprintf(stderr, "AsyncPrivateKeySign called with operation pending.\n");
164 abort();
165 }
166
167 ScopedEVP_PKEY_CTX ctx(EVP_PKEY_CTX_new(test_state->private_key.get(),
168 nullptr));
169 if (!ctx) {
170 return ssl_private_key_failure;
171 }
172
173 // Write the signature into |test_state|.
174 size_t len = 0;
175 if (!EVP_PKEY_sign_init(ctx.get()) ||
176 !EVP_PKEY_CTX_set_signature_md(ctx.get(), md) ||
177 !EVP_PKEY_sign(ctx.get(), nullptr, &len, in, in_len)) {
178 return ssl_private_key_failure;
179 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700180 test_state->private_key_result.resize(len);
David Benjaminef14b2d2015-11-11 14:01:27 -0800181 if (!EVP_PKEY_sign(ctx.get(), test_state->private_key_result.data(), &len, in,
182 in_len)) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400183 return ssl_private_key_failure;
184 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700185 test_state->private_key_result.resize(len);
David Benjaminb4d65fd2015-05-29 17:11:21 -0400186
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700187 // The signature will be released asynchronously in
188 // |AsyncPrivateKeySignComplete|.
David Benjaminb4d65fd2015-05-29 17:11:21 -0400189 return ssl_private_key_retry;
190}
191
192static ssl_private_key_result_t AsyncPrivateKeySignComplete(
193 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
194 TestState *test_state = GetTestState(ssl);
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700195 if (test_state->private_key_result.empty()) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400196 fprintf(stderr,
197 "AsyncPrivateKeySignComplete called without operation pending.\n");
198 abort();
199 }
200
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700201 if (test_state->private_key_retries < 2) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400202 // Only return the signature on the second attempt, to test both incomplete
203 // |sign| and |sign_complete|.
204 return ssl_private_key_retry;
205 }
206
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700207 if (max_out < test_state->private_key_result.size()) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400208 fprintf(stderr, "Output buffer too small.\n");
209 return ssl_private_key_failure;
210 }
David Benjaminef14b2d2015-11-11 14:01:27 -0800211 memcpy(out, test_state->private_key_result.data(),
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700212 test_state->private_key_result.size());
213 *out_len = test_state->private_key_result.size();
David Benjaminb4d65fd2015-05-29 17:11:21 -0400214
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700215 test_state->private_key_result.clear();
216 test_state->private_key_retries = 0;
217 return ssl_private_key_success;
218}
219
220static ssl_private_key_result_t AsyncPrivateKeyDecrypt(
221 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
222 const uint8_t *in, size_t in_len) {
223 TestState *test_state = GetTestState(ssl);
224 if (!test_state->private_key_result.empty()) {
225 fprintf(stderr,
226 "AsyncPrivateKeyDecrypt called with operation pending.\n");
227 abort();
228 }
229
David Benjamin758d1272015-11-20 17:47:25 -0500230 RSA *rsa = EVP_PKEY_get0_RSA(test_state->private_key.get());
231 if (rsa == NULL) {
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700232 fprintf(stderr,
233 "AsyncPrivateKeyDecrypt called with incorrect key type.\n");
234 abort();
235 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700236 test_state->private_key_result.resize(RSA_size(rsa));
David Benjaminef14b2d2015-11-11 14:01:27 -0800237 if (!RSA_decrypt(rsa, out_len, test_state->private_key_result.data(),
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700238 RSA_size(rsa), in, in_len, RSA_NO_PADDING)) {
239 return ssl_private_key_failure;
240 }
241
242 test_state->private_key_result.resize(*out_len);
243
244 // The decryption will be released asynchronously in
245 // |AsyncPrivateKeyDecryptComplete|.
246 return ssl_private_key_retry;
247}
248
249static ssl_private_key_result_t AsyncPrivateKeyDecryptComplete(
250 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
251 TestState *test_state = GetTestState(ssl);
252 if (test_state->private_key_result.empty()) {
253 fprintf(stderr,
254 "AsyncPrivateKeyDecryptComplete called without operation "
255 "pending.\n");
256 abort();
257 }
258
259 if (test_state->private_key_retries < 2) {
260 // Only return the decryption on the second attempt, to test both incomplete
261 // |decrypt| and |decrypt_complete|.
262 return ssl_private_key_retry;
263 }
264
265 if (max_out < test_state->private_key_result.size()) {
266 fprintf(stderr, "Output buffer too small.\n");
267 return ssl_private_key_failure;
268 }
David Benjaminef14b2d2015-11-11 14:01:27 -0800269 memcpy(out, test_state->private_key_result.data(),
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700270 test_state->private_key_result.size());
271 *out_len = test_state->private_key_result.size();
272
273 test_state->private_key_result.clear();
274 test_state->private_key_retries = 0;
David Benjaminb4d65fd2015-05-29 17:11:21 -0400275 return ssl_private_key_success;
276}
277
278static const SSL_PRIVATE_KEY_METHOD g_async_private_key_method = {
279 AsyncPrivateKeyType,
David Benjaminb4d65fd2015-05-29 17:11:21 -0400280 AsyncPrivateKeyMaxSignatureLen,
281 AsyncPrivateKeySign,
282 AsyncPrivateKeySignComplete,
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700283 AsyncPrivateKeyDecrypt,
284 AsyncPrivateKeyDecryptComplete
David Benjaminb4d65fd2015-05-29 17:11:21 -0400285};
286
Steven Valdez0d62f262015-09-04 12:41:04 -0400287template<typename T>
288struct Free {
289 void operator()(T *buf) {
290 free(buf);
291 }
292};
293
David Benjamin41fdbcd2015-02-09 03:13:35 -0500294static bool InstallCertificate(SSL *ssl) {
295 const TestConfig *config = GetConfigPtr(ssl);
David Benjaminb4d65fd2015-05-29 17:11:21 -0400296 TestState *test_state = GetTestState(ssl);
Steven Valdez0d62f262015-09-04 12:41:04 -0400297
298 if (!config->digest_prefs.empty()) {
299 std::unique_ptr<char, Free<char>> digest_prefs(
300 strdup(config->digest_prefs.c_str()));
Steven Valdez0d62f262015-09-04 12:41:04 -0400301 std::vector<int> digest_list;
302
303 for (;;) {
Adam Langley67251f22015-09-23 15:01:07 -0700304 char *token =
305 strtok(digest_list.empty() ? digest_prefs.get() : nullptr, ",");
Steven Valdez0d62f262015-09-04 12:41:04 -0400306 if (token == nullptr) {
307 break;
308 }
309
310 digest_list.push_back(EVP_MD_type(EVP_get_digestbyname(token)));
311 }
312
313 if (!SSL_set_private_key_digest_prefs(ssl, digest_list.data(),
314 digest_list.size())) {
315 return false;
316 }
317 }
318
David Benjaminb4d65fd2015-05-29 17:11:21 -0400319 if (!config->key_file.empty()) {
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700320 if (config->async) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400321 test_state->private_key = LoadPrivateKey(config->key_file.c_str());
322 if (!test_state->private_key) {
323 return false;
324 }
325 SSL_set_private_key_method(ssl, &g_async_private_key_method);
326 } else if (!SSL_use_PrivateKey_file(ssl, config->key_file.c_str(),
327 SSL_FILETYPE_PEM)) {
328 return false;
329 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500330 }
331 if (!config->cert_file.empty() &&
332 !SSL_use_certificate_file(ssl, config->cert_file.c_str(),
333 SSL_FILETYPE_PEM)) {
334 return false;
335 }
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100336 if (!config->ocsp_response.empty() &&
337 !SSL_CTX_set_ocsp_response(ssl->ctx,
338 (const uint8_t *)config->ocsp_response.data(),
339 config->ocsp_response.size())) {
340 return false;
341 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500342 return true;
343}
344
David Benjaminc273d2c2015-02-09 12:59:46 -0500345static int SelectCertificateCallback(const struct ssl_early_callback_ctx *ctx) {
David Benjamin5a593af2014-08-11 19:51:50 -0400346 const TestConfig *config = GetConfigPtr(ctx->ssl);
David Benjamin2d445c02015-02-09 13:03:50 -0500347 GetTestState(ctx->ssl)->early_callback_called = true;
David Benjamin5a593af2014-08-11 19:51:50 -0400348
David Benjamin6f5c0f42015-02-24 01:23:21 -0500349 if (!config->expected_server_name.empty()) {
350 const uint8_t *extension_data;
351 size_t extension_len;
352 CBS extension, server_name_list, host_name;
353 uint8_t name_type;
354
355 if (!SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
356 &extension_data,
357 &extension_len)) {
358 fprintf(stderr, "Could not find server_name extension.\n");
359 return -1;
360 }
361
362 CBS_init(&extension, extension_data, extension_len);
363 if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
364 CBS_len(&extension) != 0 ||
365 !CBS_get_u8(&server_name_list, &name_type) ||
366 name_type != TLSEXT_NAMETYPE_host_name ||
367 !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
368 CBS_len(&server_name_list) != 0) {
369 fprintf(stderr, "Could not decode server_name extension.\n");
370 return -1;
371 }
372
373 if (!CBS_mem_equal(&host_name,
374 (const uint8_t*)config->expected_server_name.data(),
375 config->expected_server_name.size())) {
376 fprintf(stderr, "Server name mismatch.\n");
377 }
David Benjamin7b030512014-07-08 17:30:11 -0400378 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400379
David Benjamin6f5c0f42015-02-24 01:23:21 -0500380 if (config->fail_early_callback) {
David Benjamin7b030512014-07-08 17:30:11 -0400381 return -1;
382 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400383
David Benjamin6f5c0f42015-02-24 01:23:21 -0500384 // Install the certificate in the early callback.
385 if (config->use_early_callback) {
386 if (config->async) {
387 // Install the certificate asynchronously.
388 return 0;
389 }
390 if (!InstallCertificate(ctx->ssl)) {
391 return -1;
392 }
David Benjamin7b030512014-07-08 17:30:11 -0400393 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400394 return 1;
395}
David Benjamin025b3d32014-07-01 19:53:04 -0400396
Paul Lietar8f1c2682015-08-18 12:21:54 +0100397static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
398 SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data(store_ctx,
399 SSL_get_ex_data_X509_STORE_CTX_idx());
400 const TestConfig *config = GetConfigPtr(ssl);
401
402 if (!config->expected_ocsp_response.empty()) {
403 const uint8_t *data;
404 size_t len;
405 SSL_get0_ocsp_response(ssl, &data, &len);
406 if (len == 0) {
407 fprintf(stderr, "OCSP response not available in verify callback\n");
408 return 0;
409 }
410 }
411
David Benjamin67666e72014-07-12 15:47:52 -0400412 return 1;
413}
414
Paul Lietar8f1c2682015-08-18 12:21:54 +0100415static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
416 store_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION;
417 return 0;
418}
419
David Benjaminc273d2c2015-02-09 12:59:46 -0500420static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
421 unsigned int *out_len, void *arg) {
David Benjamin5a593af2014-08-11 19:51:50 -0400422 const TestConfig *config = GetConfigPtr(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500423 if (config->advertise_npn.empty()) {
David Benjamin1f5f62b2014-07-12 16:18:02 -0400424 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500425 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400426
David Benjamin5a593af2014-08-11 19:51:50 -0400427 *out = (const uint8_t*)config->advertise_npn.data();
428 *out_len = config->advertise_npn.size();
David Benjamin1f5f62b2014-07-12 16:18:02 -0400429 return SSL_TLSEXT_ERR_OK;
430}
431
David Benjaminc273d2c2015-02-09 12:59:46 -0500432static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
David Benjamin8b368412015-03-14 01:54:17 -0400433 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin5a593af2014-08-11 19:51:50 -0400434 const TestConfig *config = GetConfigPtr(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500435 if (config->select_next_proto.empty()) {
David Benjamin7e3305e2014-07-28 14:52:32 -0400436 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500437 }
David Benjamin7e3305e2014-07-28 14:52:32 -0400438
David Benjamin5a593af2014-08-11 19:51:50 -0400439 *out = (uint8_t*)config->select_next_proto.data();
440 *outlen = config->select_next_proto.size();
David Benjamin7e3305e2014-07-28 14:52:32 -0400441 return SSL_TLSEXT_ERR_OK;
442}
443
David Benjaminc273d2c2015-02-09 12:59:46 -0500444static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
445 const uint8_t* in, unsigned inlen, void* arg) {
David Benjaminae2888f2014-09-06 12:58:58 -0400446 const TestConfig *config = GetConfigPtr(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500447 if (config->select_alpn.empty()) {
David Benjaminae2888f2014-09-06 12:58:58 -0400448 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500449 }
David Benjaminae2888f2014-09-06 12:58:58 -0400450
451 if (!config->expected_advertised_alpn.empty() &&
452 (config->expected_advertised_alpn.size() != inlen ||
453 memcmp(config->expected_advertised_alpn.data(),
454 in, inlen) != 0)) {
455 fprintf(stderr, "bad ALPN select callback inputs\n");
456 exit(1);
457 }
458
459 *out = (const uint8_t*)config->select_alpn.data();
460 *outlen = config->select_alpn.size();
461 return SSL_TLSEXT_ERR_OK;
462}
463
David Benjaminc273d2c2015-02-09 12:59:46 -0500464static unsigned PskClientCallback(SSL *ssl, const char *hint,
465 char *out_identity,
466 unsigned max_identity_len,
467 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin48cae082014-10-27 01:06:24 -0400468 const TestConfig *config = GetConfigPtr(ssl);
469
470 if (strcmp(hint ? hint : "", config->psk_identity.c_str()) != 0) {
471 fprintf(stderr, "Server PSK hint did not match.\n");
472 return 0;
473 }
474
475 // Account for the trailing '\0' for the identity.
476 if (config->psk_identity.size() >= max_identity_len ||
477 config->psk.size() > max_psk_len) {
478 fprintf(stderr, "PSK buffers too small\n");
479 return 0;
480 }
481
482 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
483 max_identity_len);
484 memcpy(out_psk, config->psk.data(), config->psk.size());
485 return config->psk.size();
486}
487
David Benjaminc273d2c2015-02-09 12:59:46 -0500488static unsigned PskServerCallback(SSL *ssl, const char *identity,
489 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin48cae082014-10-27 01:06:24 -0400490 const TestConfig *config = GetConfigPtr(ssl);
491
492 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
493 fprintf(stderr, "Client PSK identity did not match.\n");
494 return 0;
495 }
496
497 if (config->psk.size() > max_psk_len) {
498 fprintf(stderr, "PSK buffers too small\n");
499 return 0;
500 }
501
502 memcpy(out_psk, config->psk.data(), config->psk.size());
503 return config->psk.size();
504}
505
David Benjamin4d2e7ce2015-05-08 13:29:45 -0400506static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
David Benjamin6c2563e2015-04-03 03:47:47 -0400507 *out_clock = GetTestState(ssl)->clock;
David Benjamin377fc312015-01-26 00:22:12 -0500508}
509
David Benjaminc273d2c2015-02-09 12:59:46 -0500510static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
David Benjamin2d445c02015-02-09 13:03:50 -0500511 *out_pkey = GetTestState(ssl)->channel_id.release();
David Benjamind9e07012015-02-09 03:04:34 -0500512}
513
David Benjaminc273d2c2015-02-09 12:59:46 -0500514static int CertCallback(SSL *ssl, void *arg) {
David Benjamin2d445c02015-02-09 13:03:50 -0500515 if (!GetTestState(ssl)->cert_ready) {
David Benjamin41fdbcd2015-02-09 03:13:35 -0500516 return -1;
517 }
518 if (!InstallCertificate(ssl)) {
519 return 0;
520 }
521 return 1;
522}
523
David Benjaminc273d2c2015-02-09 12:59:46 -0500524static SSL_SESSION *GetSessionCallback(SSL *ssl, uint8_t *data, int len,
525 int *copy) {
David Benjamin2d445c02015-02-09 13:03:50 -0500526 TestState *async_state = GetTestState(ssl);
David Benjamin1b8b6912015-02-09 04:28:16 -0500527 if (async_state->session) {
528 *copy = 0;
529 return async_state->session.release();
530 } else if (async_state->pending_session) {
531 return SSL_magic_pending_session_ptr();
532 } else {
533 return NULL;
534 }
535}
536
Adam Langley524e7172015-02-20 16:04:00 -0800537static int DDoSCallback(const struct ssl_early_callback_ctx *early_context) {
538 const TestConfig *config = GetConfigPtr(early_context->ssl);
539 static int callback_num = 0;
540
541 callback_num++;
542 if (config->fail_ddos_callback ||
543 (config->fail_second_ddos_callback && callback_num == 2)) {
544 return 0;
545 }
546 return 1;
547}
548
David Benjamin87e4acd2015-04-02 19:57:35 -0400549static void InfoCallback(const SSL *ssl, int type, int val) {
550 if (type == SSL_CB_HANDSHAKE_DONE) {
551 if (GetConfigPtr(ssl)->handshake_never_done) {
552 fprintf(stderr, "handshake completed\n");
553 // Abort before any expected error code is printed, to ensure the overall
554 // test fails.
555 abort();
556 }
557 GetTestState(ssl)->handshake_done = true;
558 }
559}
560
David Benjaminba4594a2015-06-18 18:36:15 -0400561static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
562 GetTestState(ssl)->got_new_session = true;
563 // BoringSSL passes a reference to |session|.
564 SSL_SESSION_free(session);
565 return 1;
566}
567
David Benjamind98452d2015-06-16 14:16:23 -0400568static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
569 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
570 int encrypt) {
571 // This is just test code, so use the all-zeros key.
572 static const uint8_t kZeros[16] = {0};
573
574 if (encrypt) {
575 memcpy(key_name, kZeros, sizeof(kZeros));
576 RAND_bytes(iv, 16);
577 } else if (memcmp(key_name, kZeros, 16) != 0) {
578 return 0;
579 }
580
581 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
582 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
583 return -1;
584 }
585
586 if (!encrypt) {
587 return GetConfigPtr(ssl)->renew_ticket ? 2 : 1;
588 }
589 return 1;
590}
591
Adam Langley09505632015-07-30 18:10:13 -0700592// kCustomExtensionValue is the extension value that the custom extension
593// callbacks will add.
Adam Langleyc5b23a12015-07-30 18:19:26 -0700594static const uint16_t kCustomExtensionValue = 1234;
Adam Langley09505632015-07-30 18:10:13 -0700595static void *const kCustomExtensionAddArg =
596 reinterpret_cast<void *>(kCustomExtensionValue);
597static void *const kCustomExtensionParseArg =
598 reinterpret_cast<void *>(kCustomExtensionValue + 1);
599static const char kCustomExtensionContents[] = "custom extension";
600
601static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
602 const uint8_t **out, size_t *out_len,
603 int *out_alert_value, void *add_arg) {
604 if (extension_value != kCustomExtensionValue ||
605 add_arg != kCustomExtensionAddArg) {
606 abort();
607 }
608
609 if (GetConfigPtr(ssl)->custom_extension_skip) {
610 return 0;
611 }
612 if (GetConfigPtr(ssl)->custom_extension_fail_add) {
613 return -1;
614 }
615
616 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
617 *out_len = sizeof(kCustomExtensionContents) - 1;
618
619 return 1;
620}
621
622static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
623 const uint8_t *out, void *add_arg) {
624 if (extension_value != kCustomExtensionValue ||
625 add_arg != kCustomExtensionAddArg ||
626 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
627 abort();
628 }
629}
630
631static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
632 const uint8_t *contents,
633 size_t contents_len,
634 int *out_alert_value, void *parse_arg) {
635 if (extension_value != kCustomExtensionValue ||
636 parse_arg != kCustomExtensionParseArg) {
637 abort();
638 }
639
640 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
641 memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
642 *out_alert_value = SSL_AD_DECODE_ERROR;
643 return 0;
644 }
645
646 return 1;
647}
648
David Benjamin87c8a642015-02-21 01:54:29 -0500649// Connect returns a new socket connected to localhost on |port| or -1 on
650// error.
651static int Connect(uint16_t port) {
652 int sock = socket(AF_INET, SOCK_STREAM, 0);
653 if (sock == -1) {
654 PrintSocketError("socket");
655 return -1;
656 }
657 int nodelay = 1;
658 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
659 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
660 PrintSocketError("setsockopt");
661 closesocket(sock);
662 return -1;
663 }
664 sockaddr_in sin;
665 memset(&sin, 0, sizeof(sin));
666 sin.sin_family = AF_INET;
667 sin.sin_port = htons(port);
668 if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
669 PrintSocketError("inet_pton");
670 closesocket(sock);
671 return -1;
672 }
673 if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
674 sizeof(sin)) != 0) {
675 PrintSocketError("connect");
676 closesocket(sock);
677 return -1;
678 }
679 return sock;
680}
681
682class SocketCloser {
683 public:
684 explicit SocketCloser(int sock) : sock_(sock) {}
685 ~SocketCloser() {
686 // Half-close and drain the socket before releasing it. This seems to be
687 // necessary for graceful shutdown on Windows. It will also avoid write
688 // failures in the test runner.
689#if defined(OPENSSL_WINDOWS)
690 shutdown(sock_, SD_SEND);
691#else
692 shutdown(sock_, SHUT_WR);
693#endif
694 while (true) {
695 char buf[1024];
696 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
697 break;
698 }
699 }
700 closesocket(sock_);
701 }
702
703 private:
704 const int sock_;
705};
706
David Benjaminc273d2c2015-02-09 12:59:46 -0500707static ScopedSSL_CTX SetupCtx(const TestConfig *config) {
David Benjamina7f333d2015-02-09 02:37:18 -0500708 ScopedSSL_CTX ssl_ctx(SSL_CTX_new(
709 config->is_dtls ? DTLS_method() : TLS_method()));
710 if (!ssl_ctx) {
711 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -0400712 }
713
Adam Langleycef75832015-09-03 14:51:12 -0700714 std::string cipher_list = "ALL";
715 if (!config->cipher.empty()) {
716 cipher_list = config->cipher;
717 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
718 }
719 if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
720 return nullptr;
721 }
722
723 if (!config->cipher_tls10.empty() &&
724 !SSL_CTX_set_cipher_list_tls10(ssl_ctx.get(),
725 config->cipher_tls10.c_str())) {
726 return nullptr;
727 }
728 if (!config->cipher_tls11.empty() &&
729 !SSL_CTX_set_cipher_list_tls11(ssl_ctx.get(),
730 config->cipher_tls11.c_str())) {
David Benjamina7f333d2015-02-09 02:37:18 -0500731 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -0400732 }
733
David Benjamina7f333d2015-02-09 02:37:18 -0500734 ScopedDH dh(DH_get_2048_256(NULL));
Adam Langleyc4f25ce2015-11-26 16:39:08 -0800735
736 if (config->use_sparse_dh_prime) {
737 // This prime number is 2^1024 + 643 – a value just above a power of two.
738 // Because of its form, values modulo it are essentially certain to be one
739 // byte shorter. This is used to test padding of these values.
740 if (BN_hex2bn(
741 &dh->p,
742 "1000000000000000000000000000000000000000000000000000000000000000"
743 "0000000000000000000000000000000000000000000000000000000000000000"
744 "0000000000000000000000000000000000000000000000000000000000000000"
745 "0000000000000000000000000000000000000000000000000000000000000028"
746 "3") == 0 ||
747 !BN_set_word(dh->g, 2)) {
748 return nullptr;
749 }
David Benjamine66148a2016-02-02 14:14:36 -0500750 BN_free(dh->q);
751 dh->q = NULL;
Adam Langleyc4f25ce2015-11-26 16:39:08 -0800752 dh->priv_length = 0;
753 }
754
David Benjamina7f333d2015-02-09 02:37:18 -0500755 if (!dh || !SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
756 return nullptr;
David Benjaminf4e5c4e2014-08-02 17:35:45 -0400757 }
758
David Benjamin1b8b6912015-02-09 04:28:16 -0500759 if (config->async && config->is_server) {
760 // Disable the internal session cache. To test asynchronous session lookup,
761 // we use an external session cache.
762 SSL_CTX_set_session_cache_mode(
763 ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
David Benjaminc273d2c2015-02-09 12:59:46 -0500764 SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
David Benjamin1b8b6912015-02-09 04:28:16 -0500765 } else {
766 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
767 }
David Benjamin1d5c83e2014-07-22 19:20:02 -0400768
David Benjamind4c2bce2015-10-17 12:28:18 -0400769 SSL_CTX_set_select_certificate_cb(ssl_ctx.get(), SelectCertificateCallback);
David Benjamin8f2c20e2014-07-09 09:30:38 -0400770
David Benjamin1f5f62b2014-07-12 16:18:02 -0400771 SSL_CTX_set_next_protos_advertised_cb(
David Benjaminc273d2c2015-02-09 12:59:46 -0500772 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400773 if (!config->select_next_proto.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500774 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
David Benjamina7f333d2015-02-09 02:37:18 -0500775 NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400776 }
777
778 if (!config->select_alpn.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500779 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400780 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400781
Adam Langley49c7af12015-07-10 14:33:46 -0700782 SSL_CTX_enable_tls_channel_id(ssl_ctx.get());
David Benjaminc273d2c2015-02-09 12:59:46 -0500783 SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
David Benjamina08e49d2014-08-24 01:46:07 -0400784
David Benjaminc273d2c2015-02-09 12:59:46 -0500785 ssl_ctx->current_time_cb = CurrentTimeCallback;
David Benjamin377fc312015-01-26 00:22:12 -0500786
David Benjamin87e4acd2015-04-02 19:57:35 -0400787 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
David Benjaminba4594a2015-06-18 18:36:15 -0400788 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
David Benjamin87e4acd2015-04-02 19:57:35 -0400789
David Benjamind98452d2015-06-16 14:16:23 -0400790 if (config->use_ticket_callback) {
791 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
792 }
793
Adam Langley09505632015-07-30 18:10:13 -0700794 if (config->enable_client_custom_extension &&
795 !SSL_CTX_add_client_custom_ext(
796 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
797 CustomExtensionFreeCallback, kCustomExtensionAddArg,
798 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
799 return nullptr;
800 }
801
802 if (config->enable_server_custom_extension &&
803 !SSL_CTX_add_server_custom_ext(
804 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
805 CustomExtensionFreeCallback, kCustomExtensionAddArg,
806 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
807 return nullptr;
808 }
809
Paul Lietar8f1c2682015-08-18 12:21:54 +0100810 if (config->verify_fail) {
811 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
812 } else {
813 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
814 }
815
Paul Lietar4fac72e2015-09-09 13:44:55 +0100816 if (!config->signed_cert_timestamps.empty() &&
817 !SSL_CTX_set_signed_cert_timestamp_list(
818 ssl_ctx.get(), (const uint8_t *)config->signed_cert_timestamps.data(),
819 config->signed_cert_timestamps.size())) {
820 return nullptr;
821 }
822
David Benjamin1d5c83e2014-07-22 19:20:02 -0400823 return ssl_ctx;
David Benjamin1d5c83e2014-07-22 19:20:02 -0400824}
825
David Benjamin40f101b2015-02-20 11:23:42 -0500826// RetryAsync is called after a failed operation on |ssl| with return code
827// |ret|. If the operation should be retried, it simulates one asynchronous
David Benjamin6c2563e2015-04-03 03:47:47 -0400828// event and returns true. Otherwise it returns false.
829static bool RetryAsync(SSL *ssl, int ret) {
David Benjamin43ec06f2014-08-05 02:28:57 -0400830 // No error; don't retry.
831 if (ret >= 0) {
David Benjamin40f101b2015-02-20 11:23:42 -0500832 return false;
David Benjamin025b3d32014-07-01 19:53:04 -0400833 }
David Benjamin83f90402015-01-27 01:09:43 -0500834
David Benjamin13e81fc2015-11-02 17:16:13 -0500835 const TestConfig *config = GetConfigPtr(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -0400836 TestState *test_state = GetTestState(ssl);
837 if (test_state->clock_delta.tv_usec != 0 ||
838 test_state->clock_delta.tv_sec != 0) {
David Benjamin83f90402015-01-27 01:09:43 -0500839 // Process the timeout and retry.
David Benjamin6c2563e2015-04-03 03:47:47 -0400840 test_state->clock.tv_usec += test_state->clock_delta.tv_usec;
841 test_state->clock.tv_sec += test_state->clock.tv_usec / 1000000;
842 test_state->clock.tv_usec %= 1000000;
843 test_state->clock.tv_sec += test_state->clock_delta.tv_sec;
844 memset(&test_state->clock_delta, 0, sizeof(test_state->clock_delta));
David Benjamin83f90402015-01-27 01:09:43 -0500845
David Benjamin13e81fc2015-11-02 17:16:13 -0500846 // The DTLS retransmit logic silently ignores write failures. So the test
847 // may progress, allow writes through synchronously.
848 if (config->async) {
849 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
850 }
851 int timeout_ret = DTLSv1_handle_timeout(ssl);
852 if (config->async) {
853 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
854 }
855
856 if (timeout_ret < 0) {
David Benjaminc565ebb2015-04-03 04:06:36 -0400857 fprintf(stderr, "Error retransmitting.\n");
David Benjamin40f101b2015-02-20 11:23:42 -0500858 return false;
David Benjamin83f90402015-01-27 01:09:43 -0500859 }
David Benjamin40f101b2015-02-20 11:23:42 -0500860 return true;
David Benjamin83f90402015-01-27 01:09:43 -0500861 }
862
David Benjamin43ec06f2014-08-05 02:28:57 -0400863 // See if we needed to read or write more. If so, allow one byte through on
864 // the appropriate end to maximally stress the state machine.
David Benjamind9e07012015-02-09 03:04:34 -0500865 switch (SSL_get_error(ssl, ret)) {
866 case SSL_ERROR_WANT_READ:
David Benjamin6c2563e2015-04-03 03:47:47 -0400867 AsyncBioAllowRead(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -0500868 return true;
David Benjamind9e07012015-02-09 03:04:34 -0500869 case SSL_ERROR_WANT_WRITE:
David Benjamin6c2563e2015-04-03 03:47:47 -0400870 AsyncBioAllowWrite(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -0500871 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -0500872 case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
873 ScopedEVP_PKEY pkey = LoadPrivateKey(GetConfigPtr(ssl)->send_channel_id);
874 if (!pkey) {
David Benjamin40f101b2015-02-20 11:23:42 -0500875 return false;
David Benjamin9d0847a2015-02-16 03:57:55 -0500876 }
David Benjamin6c2563e2015-04-03 03:47:47 -0400877 test_state->channel_id = std::move(pkey);
David Benjamin40f101b2015-02-20 11:23:42 -0500878 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -0500879 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500880 case SSL_ERROR_WANT_X509_LOOKUP:
David Benjamin6c2563e2015-04-03 03:47:47 -0400881 test_state->cert_ready = true;
David Benjamin40f101b2015-02-20 11:23:42 -0500882 return true;
David Benjamin1b8b6912015-02-09 04:28:16 -0500883 case SSL_ERROR_PENDING_SESSION:
David Benjamin6c2563e2015-04-03 03:47:47 -0400884 test_state->session = std::move(test_state->pending_session);
David Benjamin40f101b2015-02-20 11:23:42 -0500885 return true;
David Benjamin6f5c0f42015-02-24 01:23:21 -0500886 case SSL_ERROR_PENDING_CERTIFICATE:
887 // The handshake will resume without a second call to the early callback.
888 return InstallCertificate(ssl);
David Benjaminb4d65fd2015-05-29 17:11:21 -0400889 case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700890 test_state->private_key_retries++;
David Benjaminb4d65fd2015-05-29 17:11:21 -0400891 return true;
David Benjamind9e07012015-02-09 03:04:34 -0500892 default:
David Benjamin40f101b2015-02-20 11:23:42 -0500893 return false;
David Benjamin025b3d32014-07-01 19:53:04 -0400894 }
David Benjamin025b3d32014-07-01 19:53:04 -0400895}
896
David Benjamin6c2563e2015-04-03 03:47:47 -0400897// DoRead reads from |ssl|, resolving any asynchronous operations. It returns
898// the result value of the final |SSL_read| call.
899static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
900 const TestConfig *config = GetConfigPtr(ssl);
David Benjamin13e81fc2015-11-02 17:16:13 -0500901 TestState *test_state = GetTestState(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -0400902 int ret;
903 do {
David Benjamin13e81fc2015-11-02 17:16:13 -0500904 if (config->async) {
905 // The DTLS retransmit logic silently ignores write failures. So the test
906 // may progress, allow writes through synchronously. |SSL_read| may
907 // trigger a retransmit, so disconnect the write quota.
908 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
909 }
David Benjamin6c2563e2015-04-03 03:47:47 -0400910 ret = SSL_read(ssl, out, max_out);
David Benjamin13e81fc2015-11-02 17:16:13 -0500911 if (config->async) {
912 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
913 }
David Benjamin6c2563e2015-04-03 03:47:47 -0400914 } while (config->async && RetryAsync(ssl, ret));
915 return ret;
916}
917
918// WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
919// operations. It returns the result of the final |SSL_write| call.
920static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
921 const TestConfig *config = GetConfigPtr(ssl);
922 int ret;
923 do {
924 ret = SSL_write(ssl, in, in_len);
925 if (ret > 0) {
926 in += ret;
927 in_len -= ret;
928 }
929 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
930 return ret;
931}
932
David Benjamin30789da2015-08-29 22:56:45 -0400933// DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
934// returns the result of the final |SSL_shutdown| call.
935static int DoShutdown(SSL *ssl) {
936 const TestConfig *config = GetConfigPtr(ssl);
937 int ret;
938 do {
939 ret = SSL_shutdown(ssl);
940 } while (config->async && RetryAsync(ssl, ret));
941 return ret;
942}
943
David Benjamin91eab5c2015-06-18 18:35:46 -0400944// CheckHandshakeProperties checks, immediately after |ssl| completes its
945// initial handshake (or False Starts), whether all the properties are
946// consistent with the test configuration and invariants.
947static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
948 const TestConfig *config = GetConfigPtr(ssl);
949
950 if (SSL_get_current_cipher(ssl) == nullptr) {
951 fprintf(stderr, "null cipher after handshake\n");
952 return false;
953 }
954
955 if (is_resume &&
956 (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
957 fprintf(stderr, "session was%s reused\n",
958 SSL_session_reused(ssl) ? "" : " not");
959 return false;
960 }
961
962 bool expect_handshake_done = is_resume || !config->false_start;
963 if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
964 fprintf(stderr, "handshake was%s completed\n",
965 GetTestState(ssl)->handshake_done ? "" : " not");
966 return false;
967 }
968
David Benjaminba4594a2015-06-18 18:36:15 -0400969 if (expect_handshake_done && !config->is_server) {
970 bool expect_new_session =
971 !config->expect_no_session &&
972 (!SSL_session_reused(ssl) || config->expect_ticket_renewal);
973 if (expect_new_session != GetTestState(ssl)->got_new_session) {
974 fprintf(stderr,
David Benjamindd6fed92015-10-23 17:41:12 -0400975 "new session was%s cached, but we expected the opposite\n",
David Benjaminba4594a2015-06-18 18:36:15 -0400976 GetTestState(ssl)->got_new_session ? "" : " not");
977 return false;
978 }
979 }
980
David Benjamin91eab5c2015-06-18 18:35:46 -0400981 if (config->is_server && !GetTestState(ssl)->early_callback_called) {
982 fprintf(stderr, "early callback not called\n");
983 return false;
984 }
985
986 if (!config->expected_server_name.empty()) {
987 const char *server_name =
988 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
989 if (server_name != config->expected_server_name) {
990 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
991 server_name, config->expected_server_name.c_str());
992 return false;
993 }
994 }
995
996 if (!config->expected_certificate_types.empty()) {
David Benjamin75910642015-08-09 10:42:33 -0400997 const uint8_t *certificate_types;
998 size_t certificate_types_len =
David Benjamin91eab5c2015-06-18 18:35:46 -0400999 SSL_get0_certificate_types(ssl, &certificate_types);
David Benjamin75910642015-08-09 10:42:33 -04001000 if (certificate_types_len != config->expected_certificate_types.size() ||
David Benjamin91eab5c2015-06-18 18:35:46 -04001001 memcmp(certificate_types,
1002 config->expected_certificate_types.data(),
David Benjamin75910642015-08-09 10:42:33 -04001003 certificate_types_len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001004 fprintf(stderr, "certificate types mismatch\n");
1005 return false;
1006 }
1007 }
1008
1009 if (!config->expected_next_proto.empty()) {
1010 const uint8_t *next_proto;
1011 unsigned next_proto_len;
1012 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
1013 if (next_proto_len != config->expected_next_proto.size() ||
1014 memcmp(next_proto, config->expected_next_proto.data(),
1015 next_proto_len) != 0) {
1016 fprintf(stderr, "negotiated next proto mismatch\n");
1017 return false;
1018 }
1019 }
1020
1021 if (!config->expected_alpn.empty()) {
1022 const uint8_t *alpn_proto;
1023 unsigned alpn_proto_len;
1024 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
1025 if (alpn_proto_len != config->expected_alpn.size() ||
1026 memcmp(alpn_proto, config->expected_alpn.data(),
1027 alpn_proto_len) != 0) {
1028 fprintf(stderr, "negotiated alpn proto mismatch\n");
1029 return false;
1030 }
1031 }
1032
1033 if (!config->expected_channel_id.empty()) {
1034 uint8_t channel_id[64];
1035 if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
1036 fprintf(stderr, "no channel id negotiated\n");
1037 return false;
1038 }
1039 if (config->expected_channel_id.size() != 64 ||
1040 memcmp(config->expected_channel_id.data(),
1041 channel_id, 64) != 0) {
1042 fprintf(stderr, "channel id mismatch\n");
1043 return false;
1044 }
1045 }
1046
1047 if (config->expect_extended_master_secret) {
1048 if (!ssl->session->extended_master_secret) {
1049 fprintf(stderr, "No EMS for session when expected");
1050 return false;
1051 }
1052 }
1053
1054 if (!config->expected_ocsp_response.empty()) {
1055 const uint8_t *data;
1056 size_t len;
1057 SSL_get0_ocsp_response(ssl, &data, &len);
1058 if (config->expected_ocsp_response.size() != len ||
1059 memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
1060 fprintf(stderr, "OCSP response mismatch\n");
1061 return false;
1062 }
1063 }
1064
1065 if (!config->expected_signed_cert_timestamps.empty()) {
1066 const uint8_t *data;
1067 size_t len;
1068 SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
1069 if (config->expected_signed_cert_timestamps.size() != len ||
1070 memcmp(config->expected_signed_cert_timestamps.data(),
1071 data, len) != 0) {
1072 fprintf(stderr, "SCT list mismatch\n");
1073 return false;
1074 }
1075 }
1076
Paul Lietar8f1c2682015-08-18 12:21:54 +01001077 if (config->expect_verify_result) {
1078 int expected_verify_result = config->verify_fail ?
1079 X509_V_ERR_APPLICATION_VERIFICATION :
1080 X509_V_OK;
1081
1082 if (SSL_get_verify_result(ssl) != expected_verify_result) {
1083 fprintf(stderr, "Wrong certificate verification result\n");
1084 return false;
1085 }
1086 }
1087
David Benjamin6e807652015-11-02 12:02:20 -05001088 if (config->expect_server_key_exchange_hash != 0 &&
1089 config->expect_server_key_exchange_hash !=
1090 SSL_get_server_key_exchange_hash(ssl)) {
1091 fprintf(stderr, "ServerKeyExchange hash was %d, wanted %d.\n",
1092 SSL_get_server_key_exchange_hash(ssl),
1093 config->expect_server_key_exchange_hash);
1094 return false;
1095 }
1096
David Benjamin4cc36ad2015-12-19 14:23:26 -05001097 if (config->expect_key_exchange_info != 0) {
1098 uint32_t info = SSL_SESSION_get_key_exchange_info(SSL_get_session(ssl));
1099 if (static_cast<uint32_t>(config->expect_key_exchange_info) != info) {
1100 fprintf(stderr, "key_exchange_info was %" PRIu32 ", wanted %" PRIu32 "\n",
1101 info, static_cast<uint32_t>(config->expect_key_exchange_info));
1102 return false;
1103 }
1104 }
1105
David Benjamin91eab5c2015-06-18 18:35:46 -04001106 if (!config->is_server) {
1107 /* Clients should expect a peer certificate chain iff this was not a PSK
1108 * cipher suite. */
1109 if (config->psk.empty()) {
1110 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
1111 fprintf(stderr, "Missing peer certificate chain!\n");
1112 return false;
1113 }
1114 } else if (SSL_get_peer_cert_chain(ssl) != nullptr) {
1115 fprintf(stderr, "Unexpected peer certificate chain!\n");
1116 return false;
1117 }
1118 }
1119 return true;
1120}
1121
David Benjamin87c8a642015-02-21 01:54:29 -05001122// DoExchange runs a test SSL exchange against the peer. On success, it returns
1123// true and sets |*out_session| to the negotiated SSL session. If the test is a
1124// resumption attempt, |is_resume| is true and |session| is the session from the
1125// previous exchange.
David Benjamin40f101b2015-02-20 11:23:42 -05001126static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx,
1127 const TestConfig *config, bool is_resume,
David Benjamin87c8a642015-02-21 01:54:29 -05001128 SSL_SESSION *session) {
David Benjamina7f333d2015-02-09 02:37:18 -05001129 ScopedSSL ssl(SSL_new(ssl_ctx));
1130 if (!ssl) {
David Benjamin40f101b2015-02-20 11:23:42 -05001131 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001132 }
1133
David Benjamina7f333d2015-02-09 02:37:18 -05001134 if (!SetConfigPtr(ssl.get(), config) ||
David Benjamin2d445c02015-02-09 13:03:50 -05001135 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
David Benjamin40f101b2015-02-20 11:23:42 -05001136 return false;
Adam Langley69a01602014-11-17 17:26:55 -08001137 }
David Benjamin5a593af2014-08-11 19:51:50 -04001138
Adam Langley5f0efe02015-02-20 13:03:16 -08001139 if (config->fallback_scsv &&
1140 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
1141 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001142 }
David Benjamin6f5c0f42015-02-24 01:23:21 -05001143 if (!config->use_early_callback) {
1144 if (config->async) {
1145 // TODO(davidben): Also test |s->ctx->client_cert_cb| on the client.
1146 SSL_set_cert_cb(ssl.get(), CertCallback, NULL);
1147 } else if (!InstallCertificate(ssl.get())) {
1148 return false;
1149 }
David Benjamin5a593af2014-08-11 19:51:50 -04001150 }
1151 if (config->require_any_client_certificate) {
David Benjamina7f333d2015-02-09 02:37:18 -05001152 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
Paul Lietar8f1c2682015-08-18 12:21:54 +01001153 NULL);
1154 }
1155 if (config->verify_peer) {
1156 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
David Benjamin5a593af2014-08-11 19:51:50 -04001157 }
1158 if (config->false_start) {
David Benjamined7c4752015-02-16 19:16:46 -05001159 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
David Benjamin5a593af2014-08-11 19:51:50 -04001160 }
1161 if (config->cbc_record_splitting) {
David Benjamina7f333d2015-02-09 02:37:18 -05001162 SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
David Benjamin5a593af2014-08-11 19:51:50 -04001163 }
1164 if (config->partial_write) {
David Benjamina7f333d2015-02-09 02:37:18 -05001165 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
David Benjamin5a593af2014-08-11 19:51:50 -04001166 }
1167 if (config->no_tls12) {
David Benjamina7f333d2015-02-09 02:37:18 -05001168 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
David Benjamin5a593af2014-08-11 19:51:50 -04001169 }
1170 if (config->no_tls11) {
David Benjamina7f333d2015-02-09 02:37:18 -05001171 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
David Benjamin5a593af2014-08-11 19:51:50 -04001172 }
1173 if (config->no_tls1) {
David Benjamina7f333d2015-02-09 02:37:18 -05001174 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
David Benjamin5a593af2014-08-11 19:51:50 -04001175 }
1176 if (config->no_ssl3) {
David Benjamina7f333d2015-02-09 02:37:18 -05001177 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
David Benjamin5a593af2014-08-11 19:51:50 -04001178 }
David Benjamina08e49d2014-08-24 01:46:07 -04001179 if (!config->expected_channel_id.empty()) {
David Benjamina7f333d2015-02-09 02:37:18 -05001180 SSL_enable_tls_channel_id(ssl.get());
David Benjamina08e49d2014-08-24 01:46:07 -04001181 }
1182 if (!config->send_channel_id.empty()) {
David Benjamina7f333d2015-02-09 02:37:18 -05001183 SSL_enable_tls_channel_id(ssl.get());
David Benjamind9e07012015-02-09 03:04:34 -05001184 if (!config->async) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001185 // The async case will be supplied by |ChannelIdCallback|.
David Benjamind9e07012015-02-09 03:04:34 -05001186 ScopedEVP_PKEY pkey = LoadPrivateKey(config->send_channel_id);
1187 if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001188 return false;
David Benjamind9e07012015-02-09 03:04:34 -05001189 }
David Benjamina08e49d2014-08-24 01:46:07 -04001190 }
David Benjamina08e49d2014-08-24 01:46:07 -04001191 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001192 if (!config->host_name.empty() &&
1193 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001194 return false;
David Benjamine78bfde2014-09-06 12:45:15 -04001195 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001196 if (!config->advertise_alpn.empty() &&
1197 SSL_set_alpn_protos(ssl.get(),
1198 (const uint8_t *)config->advertise_alpn.data(),
1199 config->advertise_alpn.size()) != 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001200 return false;
David Benjaminae2888f2014-09-06 12:58:58 -04001201 }
David Benjamin48cae082014-10-27 01:06:24 -04001202 if (!config->psk.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001203 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
1204 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
David Benjamin48cae082014-10-27 01:06:24 -04001205 }
David Benjamin61f95272014-11-25 01:55:35 -05001206 if (!config->psk_identity.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001207 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001208 return false;
David Benjamin48cae082014-10-27 01:06:24 -04001209 }
David Benjamin61f95272014-11-25 01:55:35 -05001210 if (!config->srtp_profiles.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001211 !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001212 return false;
David Benjamin61f95272014-11-25 01:55:35 -05001213 }
1214 if (config->enable_ocsp_stapling &&
David Benjamina7f333d2015-02-09 02:37:18 -05001215 !SSL_enable_ocsp_stapling(ssl.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001216 return false;
David Benjamin61f95272014-11-25 01:55:35 -05001217 }
1218 if (config->enable_signed_cert_timestamps &&
David Benjamina7f333d2015-02-09 02:37:18 -05001219 !SSL_enable_signed_cert_timestamps(ssl.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001220 return false;
David Benjaminca6c8262014-11-15 19:06:08 -05001221 }
David Benjamin1eb367c2014-12-12 18:17:51 -05001222 if (config->min_version != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001223 SSL_set_min_version(ssl.get(), (uint16_t)config->min_version);
David Benjamin1eb367c2014-12-12 18:17:51 -05001224 }
1225 if (config->max_version != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001226 SSL_set_max_version(ssl.get(), (uint16_t)config->max_version);
David Benjamin1eb367c2014-12-12 18:17:51 -05001227 }
David Benjamin13be1de2015-01-11 16:29:36 -05001228 if (config->mtu != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001229 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
1230 SSL_set_mtu(ssl.get(), config->mtu);
David Benjamin13be1de2015-01-11 16:29:36 -05001231 }
Adam Langley524e7172015-02-20 16:04:00 -08001232 if (config->install_ddos_callback) {
1233 SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
1234 }
David Benjamin1d5ef3b2015-10-12 19:54:18 -04001235 if (config->renegotiate_once) {
1236 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_once);
1237 }
1238 if (config->renegotiate_freely) {
1239 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
David Benjaminb16346b2015-04-08 19:16:58 -04001240 }
Adam Langley27a0d082015-11-03 13:34:10 -08001241 if (config->renegotiate_ignore) {
1242 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_ignore);
1243 }
David Benjamin30789da2015-08-29 22:56:45 -04001244 if (!config->check_close_notify) {
1245 SSL_set_quiet_shutdown(ssl.get(), 1);
1246 }
David Benjamin091c4b92015-10-26 13:33:21 -04001247 if (config->disable_npn) {
1248 SSL_set_options(ssl.get(), SSL_OP_DISABLE_NPN);
1249 }
David Benjamin99fdfb92015-11-02 12:11:35 -05001250 if (config->p384_only) {
1251 int nid = NID_secp384r1;
1252 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
1253 return false;
1254 }
1255 }
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001256 if (config->enable_all_curves) {
1257 static const int kAllCurves[] = {
David Benjamin4298d772015-12-19 00:18:25 -05001258 NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_x25519,
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001259 };
1260 if (!SSL_set1_curves(ssl.get(), kAllCurves,
1261 sizeof(kAllCurves) / sizeof(kAllCurves[0]))) {
1262 return false;
1263 }
1264 }
David Benjamin025b3d32014-07-01 19:53:04 -04001265
David Benjamin87c8a642015-02-21 01:54:29 -05001266 int sock = Connect(config->port);
1267 if (sock == -1) {
1268 return false;
1269 }
1270 SocketCloser closer(sock);
1271
1272 ScopedBIO bio(BIO_new_socket(sock, BIO_NOCLOSE));
David Benjamina7f333d2015-02-09 02:37:18 -05001273 if (!bio) {
David Benjamin40f101b2015-02-20 11:23:42 -05001274 return false;
David Benjamin43ec06f2014-08-05 02:28:57 -04001275 }
David Benjamin6fd297b2014-08-11 18:43:38 -04001276 if (config->is_dtls) {
David Benjamin6c2563e2015-04-03 03:47:47 -04001277 ScopedBIO packeted =
1278 PacketedBioCreate(&GetTestState(ssl.get())->clock_delta);
David Benjamina7f333d2015-02-09 02:37:18 -05001279 BIO_push(packeted.get(), bio.release());
1280 bio = std::move(packeted);
David Benjamin6fd297b2014-08-11 18:43:38 -04001281 }
David Benjamin5a593af2014-08-11 19:51:50 -04001282 if (config->async) {
David Benjamina7f333d2015-02-09 02:37:18 -05001283 ScopedBIO async_scoped =
David Benjaminc273d2c2015-02-09 12:59:46 -05001284 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
David Benjamina7f333d2015-02-09 02:37:18 -05001285 BIO_push(async_scoped.get(), bio.release());
David Benjamin6c2563e2015-04-03 03:47:47 -04001286 GetTestState(ssl.get())->async_bio = async_scoped.get();
David Benjamina7f333d2015-02-09 02:37:18 -05001287 bio = std::move(async_scoped);
David Benjamin43ec06f2014-08-05 02:28:57 -04001288 }
David Benjamina7f333d2015-02-09 02:37:18 -05001289 SSL_set_bio(ssl.get(), bio.get(), bio.get());
1290 bio.release(); // SSL_set_bio takes ownership.
David Benjamin43ec06f2014-08-05 02:28:57 -04001291
David Benjamin1d5c83e2014-07-22 19:20:02 -04001292 if (session != NULL) {
David Benjamin1b8b6912015-02-09 04:28:16 -05001293 if (!config->is_server) {
1294 if (SSL_set_session(ssl.get(), session) != 1) {
David Benjamin40f101b2015-02-20 11:23:42 -05001295 return false;
David Benjamin1b8b6912015-02-09 04:28:16 -05001296 }
1297 } else if (config->async) {
1298 // The internal session cache is disabled, so install the session
1299 // manually.
David Benjamin2d445c02015-02-09 13:03:50 -05001300 GetTestState(ssl.get())->pending_session.reset(
David Benjamin1b8b6912015-02-09 04:28:16 -05001301 SSL_SESSION_up_ref(session));
David Benjamin1d5c83e2014-07-22 19:20:02 -04001302 }
1303 }
1304
David Benjamina07c0fc2015-05-13 13:19:42 -04001305 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1306 fprintf(stderr, "non-null cipher before handshake\n");
1307 return false;
1308 }
1309
David Benjamin1d5c83e2014-07-22 19:20:02 -04001310 int ret;
David Benjamine0e7d0d2015-02-08 19:33:25 -05001311 if (config->implicit_handshake) {
David Benjamin5a593af2014-08-11 19:51:50 -04001312 if (config->is_server) {
David Benjamina7f333d2015-02-09 02:37:18 -05001313 SSL_set_accept_state(ssl.get());
David Benjamin43ec06f2014-08-05 02:28:57 -04001314 } else {
David Benjamina7f333d2015-02-09 02:37:18 -05001315 SSL_set_connect_state(ssl.get());
David Benjamin43ec06f2014-08-05 02:28:57 -04001316 }
David Benjamine0e7d0d2015-02-08 19:33:25 -05001317 } else {
1318 do {
1319 if (config->is_server) {
David Benjamina7f333d2015-02-09 02:37:18 -05001320 ret = SSL_accept(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -05001321 } else {
David Benjamina7f333d2015-02-09 02:37:18 -05001322 ret = SSL_connect(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -05001323 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001324 } while (config->async && RetryAsync(ssl.get(), ret));
David Benjamin91eab5c2015-06-18 18:35:46 -04001325 if (ret != 1 ||
1326 !CheckHandshakeProperties(ssl.get(), is_resume)) {
David Benjamin40f101b2015-02-20 11:23:42 -05001327 return false;
David Benjamine0e7d0d2015-02-08 19:33:25 -05001328 }
David Benjamin025b3d32014-07-01 19:53:04 -04001329
David Benjaminba4594a2015-06-18 18:36:15 -04001330 // Reset the state to assert later that the callback isn't called in
1331 // renegotations.
1332 GetTestState(ssl.get())->got_new_session = false;
David Benjamin61f95272014-11-25 01:55:35 -05001333 }
1334
David Benjaminc565ebb2015-04-03 04:06:36 -04001335 if (config->export_keying_material > 0) {
1336 std::vector<uint8_t> result(
1337 static_cast<size_t>(config->export_keying_material));
1338 if (!SSL_export_keying_material(
1339 ssl.get(), result.data(), result.size(),
1340 config->export_label.data(), config->export_label.size(),
1341 reinterpret_cast<const uint8_t*>(config->export_context.data()),
1342 config->export_context.size(), config->use_export_context)) {
1343 fprintf(stderr, "failed to export keying material\n");
1344 return false;
1345 }
1346 if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1347 return false;
1348 }
1349 }
1350
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001351 if (config->tls_unique) {
1352 uint8_t tls_unique[16];
1353 size_t tls_unique_len;
1354 if (!SSL_get_tls_unique(ssl.get(), tls_unique, &tls_unique_len,
1355 sizeof(tls_unique))) {
1356 fprintf(stderr, "failed to get tls-unique\n");
1357 return false;
1358 }
1359
1360 if (tls_unique_len != 12) {
1361 fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
1362 static_cast<unsigned>(tls_unique_len));
1363 return false;
1364 }
1365
1366 if (WriteAll(ssl.get(), tls_unique, tls_unique_len) < 0) {
1367 return false;
1368 }
1369 }
1370
David Benjamin5a593af2014-08-11 19:51:50 -04001371 if (config->write_different_record_sizes) {
David Benjamin6fd297b2014-08-11 18:43:38 -04001372 if (config->is_dtls) {
1373 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001374 return false;
David Benjamin6fd297b2014-08-11 18:43:38 -04001375 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001376 // This mode writes a number of different record sizes in an attempt to
1377 // trip up the CBC record splitting code.
Adam Langleybc949292015-06-18 21:32:44 -07001378 static const size_t kBufLen = 32769;
1379 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1380 memset(buf.get(), 0x42, kBufLen);
Kenny Root7fdeaf12014-08-05 15:23:37 -07001381 static const size_t kRecordSizes[] = {
1382 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
1383 for (size_t i = 0; i < sizeof(kRecordSizes) / sizeof(kRecordSizes[0]);
1384 i++) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07001385 const size_t len = kRecordSizes[i];
Adam Langleybc949292015-06-18 21:32:44 -07001386 if (len > kBufLen) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07001387 fprintf(stderr, "Bad kRecordSizes value.\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001388 return false;
Kenny Root7fdeaf12014-08-05 15:23:37 -07001389 }
Adam Langleybc949292015-06-18 21:32:44 -07001390 if (WriteAll(ssl.get(), buf.get(), len) < 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001391 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001392 }
1393 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001394 } else {
David Benjamine58c4f52014-08-24 03:47:07 -04001395 if (config->shim_writes_first) {
David Benjamin6c2563e2015-04-03 03:47:47 -04001396 if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1397 5) < 0) {
1398 return false;
1399 }
David Benjamine58c4f52014-08-24 03:47:07 -04001400 }
David Benjamin30789da2015-08-29 22:56:45 -04001401 if (!config->shim_shuts_down) {
1402 for (;;) {
Adam Langleya0a8dc22015-09-09 10:22:00 -07001403 static const size_t kBufLen = 16384;
1404 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1405
David Benjamin2c99d282015-09-01 10:23:00 -04001406 // Read only 512 bytes at a time in TLS to ensure records may be
1407 // returned in multiple reads.
Adam Langleya0a8dc22015-09-09 10:22:00 -07001408 int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
David Benjamin30789da2015-08-29 22:56:45 -04001409 int err = SSL_get_error(ssl.get(), n);
1410 if (err == SSL_ERROR_ZERO_RETURN ||
1411 (n == 0 && err == SSL_ERROR_SYSCALL)) {
1412 if (n != 0) {
1413 fprintf(stderr, "Invalid SSL_get_error output\n");
1414 return false;
1415 }
1416 // Stop on either clean or unclean shutdown.
1417 break;
1418 } else if (err != SSL_ERROR_NONE) {
1419 if (n > 0) {
1420 fprintf(stderr, "Invalid SSL_get_error output\n");
1421 return false;
1422 }
1423 return false;
1424 }
1425 // Successfully read data.
1426 if (n <= 0) {
David Benjamin9a38e922015-01-22 16:06:11 -05001427 fprintf(stderr, "Invalid SSL_get_error output\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001428 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001429 }
David Benjamin30789da2015-08-29 22:56:45 -04001430
1431 // After a successful read, with or without False Start, the handshake
1432 // must be complete.
1433 if (!GetTestState(ssl.get())->handshake_done) {
1434 fprintf(stderr, "handshake was not completed after SSL_read\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001435 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001436 }
David Benjamin87e4acd2015-04-02 19:57:35 -04001437
David Benjamin30789da2015-08-29 22:56:45 -04001438 for (int i = 0; i < n; i++) {
1439 buf[i] ^= 0xff;
1440 }
Adam Langleya0a8dc22015-09-09 10:22:00 -07001441 if (WriteAll(ssl.get(), buf.get(), n) < 0) {
David Benjamin30789da2015-08-29 22:56:45 -04001442 return false;
1443 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001444 }
1445 }
David Benjamin025b3d32014-07-01 19:53:04 -04001446 }
1447
David Benjaminba4594a2015-06-18 18:36:15 -04001448 if (!config->is_server && !config->false_start &&
1449 !config->implicit_handshake &&
1450 GetTestState(ssl.get())->got_new_session) {
1451 fprintf(stderr, "new session was established after the handshake\n");
1452 return false;
1453 }
1454
David Benjamin1d5c83e2014-07-22 19:20:02 -04001455 if (out_session) {
David Benjamina7f333d2015-02-09 02:37:18 -05001456 out_session->reset(SSL_get1_session(ssl.get()));
David Benjamin1d5c83e2014-07-22 19:20:02 -04001457 }
1458
David Benjamin30789da2015-08-29 22:56:45 -04001459 ret = DoShutdown(ssl.get());
1460
1461 if (config->shim_shuts_down && config->check_close_notify) {
1462 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1463 // it returns zero when our close_notify is sent, then one when the peer's
1464 // is received.
1465 if (ret != 0) {
1466 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1467 return false;
1468 }
1469 ret = DoShutdown(ssl.get());
1470 }
1471
1472 if (ret != 1) {
1473 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1474 return false;
1475 }
1476
David Benjamin324dce42015-10-12 19:49:00 -04001477 if (SSL_total_renegotiations(ssl.get()) !=
1478 config->expect_total_renegotiations) {
1479 fprintf(stderr, "Expected %d renegotiations, got %d\n",
1480 config->expect_total_renegotiations,
1481 SSL_total_renegotiations(ssl.get()));
1482 return false;
1483 }
1484
David Benjamin40f101b2015-02-20 11:23:42 -05001485 return true;
David Benjamin025b3d32014-07-01 19:53:04 -04001486}
David Benjamin1d5c83e2014-07-22 19:20:02 -04001487
David Benjaminff3a1492016-03-02 10:12:06 -05001488class StderrDelimiter {
1489 public:
1490 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
1491};
1492
David Benjamin1d5c83e2014-07-22 19:20:02 -04001493int main(int argc, char **argv) {
David Benjaminff3a1492016-03-02 10:12:06 -05001494 // To distinguish ASan's output from ours, add a trailing message to stderr.
1495 // Anything following this line will be considered an error.
1496 StderrDelimiter delimiter;
1497
David Benjamin87c8a642015-02-21 01:54:29 -05001498#if defined(OPENSSL_WINDOWS)
1499 /* Initialize Winsock. */
1500 WORD wsa_version = MAKEWORD(2, 2);
1501 WSADATA wsa_data;
1502 int wsa_err = WSAStartup(wsa_version, &wsa_data);
1503 if (wsa_err != 0) {
1504 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1505 return 1;
1506 }
1507 if (wsa_data.wVersion != wsa_version) {
1508 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1509 return 1;
1510 }
1511#else
David Benjamin1d5c83e2014-07-22 19:20:02 -04001512 signal(SIGPIPE, SIG_IGN);
Adam Langleyded93582014-07-31 15:23:51 -07001513#endif
David Benjamin1d5c83e2014-07-22 19:20:02 -04001514
David Benjamin7a1eefd2015-10-17 23:39:22 -04001515 CRYPTO_library_init();
David Benjamind9e07012015-02-09 03:04:34 -05001516 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
David Benjamin2d445c02015-02-09 13:03:50 -05001517 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
David Benjamin6c2563e2015-04-03 03:47:47 -04001518 if (g_config_index < 0 || g_state_index < 0) {
David Benjaminae3e4872014-11-18 21:52:26 -05001519 return 1;
1520 }
David Benjamin5a593af2014-08-11 19:51:50 -04001521
1522 TestConfig config;
1523 if (!ParseConfig(argc - 1, argv + 1, &config)) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001524 return Usage(argv[0]);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001525 }
1526
David Benjaminc273d2c2015-02-09 12:59:46 -05001527 ScopedSSL_CTX ssl_ctx = SetupCtx(&config);
David Benjamina7f333d2015-02-09 02:37:18 -05001528 if (!ssl_ctx) {
Brian Smith83a82982015-04-09 16:21:10 -10001529 ERR_print_errors_fp(stderr);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001530 return 1;
1531 }
1532
David Benjamina7f333d2015-02-09 02:37:18 -05001533 ScopedSSL_SESSION session;
David Benjamin40f101b2015-02-20 11:23:42 -05001534 if (!DoExchange(&session, ssl_ctx.get(), &config, false /* is_resume */,
David Benjamin87c8a642015-02-21 01:54:29 -05001535 NULL /* session */)) {
Brian Smith83a82982015-04-09 16:21:10 -10001536 ERR_print_errors_fp(stderr);
David Benjamin40f101b2015-02-20 11:23:42 -05001537 return 1;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001538 }
1539
David Benjamin40f101b2015-02-20 11:23:42 -05001540 if (config.resume &&
1541 !DoExchange(NULL, ssl_ctx.get(), &config, true /* is_resume */,
David Benjamin87c8a642015-02-21 01:54:29 -05001542 session.get())) {
Brian Smith83a82982015-04-09 16:21:10 -10001543 ERR_print_errors_fp(stderr);
David Benjamin40f101b2015-02-20 11:23:42 -05001544 return 1;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001545 }
1546
David Benjamina7f333d2015-02-09 02:37:18 -05001547 return 0;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001548}