blob: 85169773190757afed31ef89caa50480438c0836 [file] [log] [blame]
David Benjamin025b3d32014-07-01 19:53:04 -04001/* Copyright (c) 2014, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
David Benjamin4cc36ad2015-12-19 14:23:26 -050015#if !defined(__STDC_FORMAT_MACROS)
16#define __STDC_FORMAT_MACROS
17#endif
18
Adam Langleyded93582014-07-31 15:23:51 -070019#include <openssl/base.h>
20
21#if !defined(OPENSSL_WINDOWS)
David Benjamin025b3d32014-07-01 19:53:04 -040022#include <arpa/inet.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040023#include <netinet/in.h>
David Benjamin87c8a642015-02-21 01:54:29 -050024#include <netinet/tcp.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040025#include <signal.h>
26#include <sys/socket.h>
David Benjamin0abd6f22015-12-04 21:49:53 -050027#include <sys/time.h>
David Benjamin8f2c20e2014-07-09 09:30:38 -040028#include <unistd.h>
David Benjamin87c8a642015-02-21 01:54:29 -050029#else
30#include <io.h>
David Benjamina353cdb2016-06-09 16:48:33 -040031OPENSSL_MSVC_PRAGMA(warning(push, 3))
Adam Langley3e719312015-03-20 16:32:23 -070032#include <winsock2.h>
33#include <ws2tcpip.h>
David Benjamina353cdb2016-06-09 16:48:33 -040034OPENSSL_MSVC_PRAGMA(warning(pop))
David Benjamin87c8a642015-02-21 01:54:29 -050035
36#pragma comment(lib, "Ws2_32.lib")
Adam Langleyded93582014-07-31 15:23:51 -070037#endif
38
David Benjamin585d7a42016-06-02 14:58:00 -040039#include <assert.h>
David Benjamin4cc36ad2015-12-19 14:23:26 -050040#include <inttypes.h>
Adam Langley2b2d66d2015-01-30 17:08:37 -080041#include <string.h>
David Benjamin025b3d32014-07-01 19:53:04 -040042
David Benjamin025b3d32014-07-01 19:53:04 -040043#include <openssl/bio.h>
David Benjamin48cae082014-10-27 01:06:24 -040044#include <openssl/buf.h>
David Benjamin8f2c20e2014-07-09 09:30:38 -040045#include <openssl/bytestring.h>
David Benjamind98452d2015-06-16 14:16:23 -040046#include <openssl/cipher.h>
David Benjamin7a1eefd2015-10-17 23:39:22 -040047#include <openssl/crypto.h>
Brian Smith83a82982015-04-09 16:21:10 -100048#include <openssl/err.h>
David Benjamind98452d2015-06-16 14:16:23 -040049#include <openssl/hmac.h>
David Benjamin98193672016-03-25 18:07:11 -040050#include <openssl/nid.h>
David Benjamind98452d2015-06-16 14:16:23 -040051#include <openssl/rand.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040052#include <openssl/ssl.h>
53
David Benjamin45fb1be2015-03-22 16:31:27 -040054#include <memory>
Steven Valdez0d62f262015-09-04 12:41:04 -040055#include <string>
David Benjaminc565ebb2015-04-03 04:06:36 -040056#include <vector>
David Benjamin45fb1be2015-03-22 16:31:27 -040057
58#include "../../crypto/test/scoped_types.h"
David Benjamin43ec06f2014-08-05 02:28:57 -040059#include "async_bio.h"
David Benjamin6fd297b2014-08-11 18:43:38 -040060#include "packeted_bio.h"
David Benjamina7f333d2015-02-09 02:37:18 -050061#include "scoped_types.h"
David Benjamin5a593af2014-08-11 19:51:50 -040062#include "test_config.h"
David Benjamin43ec06f2014-08-05 02:28:57 -040063
David Benjamin87c8a642015-02-21 01:54:29 -050064
65#if !defined(OPENSSL_WINDOWS)
66static int closesocket(int sock) {
67 return close(sock);
68}
69
70static void PrintSocketError(const char *func) {
71 perror(func);
72}
73#else
74static void PrintSocketError(const char *func) {
75 fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
76}
77#endif
78
David Benjaminc273d2c2015-02-09 12:59:46 -050079static int Usage(const char *program) {
David Benjamina7f333d2015-02-09 02:37:18 -050080 fprintf(stderr, "Usage: %s [flags...]\n", program);
David Benjamin1d5c83e2014-07-22 19:20:02 -040081 return 1;
82}
David Benjamin025b3d32014-07-01 19:53:04 -040083
David Benjamin2d445c02015-02-09 13:03:50 -050084struct TestState {
David Benjamin6c2563e2015-04-03 03:47:47 -040085 // async_bio is async BIO which pauses reads and writes.
86 BIO *async_bio = nullptr;
David Benjamin585d7a42016-06-02 14:58:00 -040087 // packeted_bio is the packeted BIO which simulates read timeouts.
88 BIO *packeted_bio = nullptr;
David Benjamind9e07012015-02-09 03:04:34 -050089 ScopedEVP_PKEY channel_id;
David Benjamin0d4db502015-03-23 18:46:05 -040090 bool cert_ready = false;
David Benjamin1b8b6912015-02-09 04:28:16 -050091 ScopedSSL_SESSION session;
92 ScopedSSL_SESSION pending_session;
David Benjamin0d4db502015-03-23 18:46:05 -040093 bool early_callback_called = false;
David Benjamin87e4acd2015-04-02 19:57:35 -040094 bool handshake_done = false;
David Benjaminb4d65fd2015-05-29 17:11:21 -040095 // private_key is the underlying private key used when testing custom keys.
96 ScopedEVP_PKEY private_key;
nagendra modadugu3398dbf2015-08-07 14:07:52 -070097 std::vector<uint8_t> private_key_result;
98 // private_key_retries is the number of times an asynchronous private key
99 // operation has been retried.
100 unsigned private_key_retries = 0;
David Benjaminba4594a2015-06-18 18:36:15 -0400101 bool got_new_session = false;
David Benjamind9e07012015-02-09 03:04:34 -0500102};
103
David Benjamin2d445c02015-02-09 13:03:50 -0500104static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
Adam Langley09505632015-07-30 18:10:13 -0700105 int index, long argl, void *argp) {
David Benjamin2d445c02015-02-09 13:03:50 -0500106 delete ((TestState *)ptr);
David Benjamind9e07012015-02-09 03:04:34 -0500107}
108
109static int g_config_index = 0;
David Benjamin2d445c02015-02-09 13:03:50 -0500110static int g_state_index = 0;
David Benjamin5a593af2014-08-11 19:51:50 -0400111
David Benjamin7e7a82d2016-05-20 20:12:42 -0400112static bool SetTestConfig(SSL *ssl, const TestConfig *config) {
David Benjamind9e07012015-02-09 03:04:34 -0500113 return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
David Benjamin5a593af2014-08-11 19:51:50 -0400114}
115
David Benjamin7e7a82d2016-05-20 20:12:42 -0400116static const TestConfig *GetTestConfig(const SSL *ssl) {
David Benjamind9e07012015-02-09 03:04:34 -0500117 return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
David Benjamin5a593af2014-08-11 19:51:50 -0400118}
119
David Benjamin22050932015-11-23 13:44:48 -0500120static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
121 // |SSL_set_ex_data| takes ownership of |state| only on success.
122 if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
123 state.release();
David Benjamind9e07012015-02-09 03:04:34 -0500124 return true;
125 }
126 return false;
127}
128
David Benjamin87e4acd2015-04-02 19:57:35 -0400129static TestState *GetTestState(const SSL *ssl) {
David Benjamin2d445c02015-02-09 13:03:50 -0500130 return (TestState *)SSL_get_ex_data(ssl, g_state_index);
David Benjamin83f90402015-01-27 01:09:43 -0500131}
132
David Benjaminacb6dcc2016-03-10 09:15:01 -0500133static ScopedX509 LoadCertificate(const std::string &file) {
134 ScopedBIO bio(BIO_new(BIO_s_file()));
135 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
136 return nullptr;
137 }
138 return ScopedX509(PEM_read_bio_X509(bio.get(), NULL, NULL, NULL));
139}
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 Benjaminacb6dcc2016-03-10 09:15:01 -0500146 return ScopedEVP_PKEY(PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
David Benjamina08e49d2014-08-24 01:46:07 -0400147}
148
David Benjaminb4d65fd2015-05-29 17:11:21 -0400149static int AsyncPrivateKeyType(SSL *ssl) {
150 return EVP_PKEY_id(GetTestState(ssl)->private_key.get());
151}
152
David Benjaminb4d65fd2015-05-29 17:11:21 -0400153static size_t AsyncPrivateKeyMaxSignatureLen(SSL *ssl) {
154 return EVP_PKEY_size(GetTestState(ssl)->private_key.get());
155}
156
157static ssl_private_key_result_t AsyncPrivateKeySign(
158 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
159 const EVP_MD *md, const uint8_t *in, size_t in_len) {
160 TestState *test_state = GetTestState(ssl);
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700161 if (!test_state->private_key_result.empty()) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400162 fprintf(stderr, "AsyncPrivateKeySign called with operation pending.\n");
163 abort();
164 }
165
166 ScopedEVP_PKEY_CTX ctx(EVP_PKEY_CTX_new(test_state->private_key.get(),
167 nullptr));
168 if (!ctx) {
169 return ssl_private_key_failure;
170 }
171
172 // Write the signature into |test_state|.
173 size_t len = 0;
174 if (!EVP_PKEY_sign_init(ctx.get()) ||
175 !EVP_PKEY_CTX_set_signature_md(ctx.get(), md) ||
176 !EVP_PKEY_sign(ctx.get(), nullptr, &len, in, in_len)) {
177 return ssl_private_key_failure;
178 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700179 test_state->private_key_result.resize(len);
David Benjaminef14b2d2015-11-11 14:01:27 -0800180 if (!EVP_PKEY_sign(ctx.get(), test_state->private_key_result.data(), &len, in,
181 in_len)) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400182 return ssl_private_key_failure;
183 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700184 test_state->private_key_result.resize(len);
David Benjaminb4d65fd2015-05-29 17:11:21 -0400185
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700186 // The signature will be released asynchronously in
187 // |AsyncPrivateKeySignComplete|.
David Benjaminb4d65fd2015-05-29 17:11:21 -0400188 return ssl_private_key_retry;
189}
190
191static ssl_private_key_result_t AsyncPrivateKeySignComplete(
192 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
193 TestState *test_state = GetTestState(ssl);
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700194 if (test_state->private_key_result.empty()) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400195 fprintf(stderr,
196 "AsyncPrivateKeySignComplete called without operation pending.\n");
197 abort();
198 }
199
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700200 if (test_state->private_key_retries < 2) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400201 // Only return the signature on the second attempt, to test both incomplete
202 // |sign| and |sign_complete|.
203 return ssl_private_key_retry;
204 }
205
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700206 if (max_out < test_state->private_key_result.size()) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400207 fprintf(stderr, "Output buffer too small.\n");
208 return ssl_private_key_failure;
209 }
David Benjaminef14b2d2015-11-11 14:01:27 -0800210 memcpy(out, test_state->private_key_result.data(),
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700211 test_state->private_key_result.size());
212 *out_len = test_state->private_key_result.size();
David Benjaminb4d65fd2015-05-29 17:11:21 -0400213
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700214 test_state->private_key_result.clear();
215 test_state->private_key_retries = 0;
216 return ssl_private_key_success;
217}
218
219static ssl_private_key_result_t AsyncPrivateKeyDecrypt(
220 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
221 const uint8_t *in, size_t in_len) {
222 TestState *test_state = GetTestState(ssl);
223 if (!test_state->private_key_result.empty()) {
224 fprintf(stderr,
225 "AsyncPrivateKeyDecrypt called with operation pending.\n");
226 abort();
227 }
228
David Benjamin758d1272015-11-20 17:47:25 -0500229 RSA *rsa = EVP_PKEY_get0_RSA(test_state->private_key.get());
230 if (rsa == NULL) {
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700231 fprintf(stderr,
232 "AsyncPrivateKeyDecrypt called with incorrect key type.\n");
233 abort();
234 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700235 test_state->private_key_result.resize(RSA_size(rsa));
David Benjaminef14b2d2015-11-11 14:01:27 -0800236 if (!RSA_decrypt(rsa, out_len, test_state->private_key_result.data(),
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700237 RSA_size(rsa), in, in_len, RSA_NO_PADDING)) {
238 return ssl_private_key_failure;
239 }
240
241 test_state->private_key_result.resize(*out_len);
242
243 // The decryption will be released asynchronously in
244 // |AsyncPrivateKeyDecryptComplete|.
245 return ssl_private_key_retry;
246}
247
248static ssl_private_key_result_t AsyncPrivateKeyDecryptComplete(
249 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
250 TestState *test_state = GetTestState(ssl);
251 if (test_state->private_key_result.empty()) {
252 fprintf(stderr,
253 "AsyncPrivateKeyDecryptComplete called without operation "
254 "pending.\n");
255 abort();
256 }
257
258 if (test_state->private_key_retries < 2) {
259 // Only return the decryption on the second attempt, to test both incomplete
260 // |decrypt| and |decrypt_complete|.
261 return ssl_private_key_retry;
262 }
263
264 if (max_out < test_state->private_key_result.size()) {
265 fprintf(stderr, "Output buffer too small.\n");
266 return ssl_private_key_failure;
267 }
David Benjaminef14b2d2015-11-11 14:01:27 -0800268 memcpy(out, test_state->private_key_result.data(),
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700269 test_state->private_key_result.size());
270 *out_len = test_state->private_key_result.size();
271
272 test_state->private_key_result.clear();
273 test_state->private_key_retries = 0;
David Benjaminb4d65fd2015-05-29 17:11:21 -0400274 return ssl_private_key_success;
275}
276
277static const SSL_PRIVATE_KEY_METHOD g_async_private_key_method = {
278 AsyncPrivateKeyType,
David Benjaminb4d65fd2015-05-29 17:11:21 -0400279 AsyncPrivateKeyMaxSignatureLen,
280 AsyncPrivateKeySign,
281 AsyncPrivateKeySignComplete,
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700282 AsyncPrivateKeyDecrypt,
283 AsyncPrivateKeyDecryptComplete
David Benjaminb4d65fd2015-05-29 17:11:21 -0400284};
285
Steven Valdez0d62f262015-09-04 12:41:04 -0400286template<typename T>
287struct Free {
288 void operator()(T *buf) {
289 free(buf);
290 }
291};
292
David Benjaminacb6dcc2016-03-10 09:15:01 -0500293static bool GetCertificate(SSL *ssl, ScopedX509 *out_x509,
294 ScopedEVP_PKEY *out_pkey) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400295 const TestConfig *config = GetTestConfig(ssl);
Steven Valdez0d62f262015-09-04 12:41:04 -0400296
297 if (!config->digest_prefs.empty()) {
298 std::unique_ptr<char, Free<char>> digest_prefs(
299 strdup(config->digest_prefs.c_str()));
Steven Valdez0d62f262015-09-04 12:41:04 -0400300 std::vector<int> digest_list;
301
302 for (;;) {
Adam Langley67251f22015-09-23 15:01:07 -0700303 char *token =
304 strtok(digest_list.empty() ? digest_prefs.get() : nullptr, ",");
Steven Valdez0d62f262015-09-04 12:41:04 -0400305 if (token == nullptr) {
306 break;
307 }
308
309 digest_list.push_back(EVP_MD_type(EVP_get_digestbyname(token)));
310 }
311
312 if (!SSL_set_private_key_digest_prefs(ssl, digest_list.data(),
313 digest_list.size())) {
314 return false;
315 }
316 }
317
David Benjaminb4d65fd2015-05-29 17:11:21 -0400318 if (!config->key_file.empty()) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500319 *out_pkey = LoadPrivateKey(config->key_file.c_str());
320 if (!*out_pkey) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400321 return false;
322 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500323 }
David Benjaminacb6dcc2016-03-10 09:15:01 -0500324 if (!config->cert_file.empty()) {
325 *out_x509 = LoadCertificate(config->cert_file.c_str());
326 if (!*out_x509) {
327 return false;
328 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500329 }
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100330 if (!config->ocsp_response.empty() &&
331 !SSL_CTX_set_ocsp_response(ssl->ctx,
332 (const uint8_t *)config->ocsp_response.data(),
333 config->ocsp_response.size())) {
334 return false;
335 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500336 return true;
337}
338
David Benjaminacb6dcc2016-03-10 09:15:01 -0500339static bool InstallCertificate(SSL *ssl) {
340 ScopedX509 x509;
341 ScopedEVP_PKEY pkey;
342 if (!GetCertificate(ssl, &x509, &pkey)) {
343 return false;
344 }
345
346 if (pkey) {
347 TestState *test_state = GetTestState(ssl);
David Benjamin7e7a82d2016-05-20 20:12:42 -0400348 const TestConfig *config = GetTestConfig(ssl);
David Benjaminacb6dcc2016-03-10 09:15:01 -0500349 if (config->async) {
350 test_state->private_key = std::move(pkey);
351 SSL_set_private_key_method(ssl, &g_async_private_key_method);
352 } else if (!SSL_use_PrivateKey(ssl, pkey.get())) {
353 return false;
354 }
355 }
356
357 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
358 return false;
359 }
360
361 return true;
362}
363
David Benjaminc273d2c2015-02-09 12:59:46 -0500364static int SelectCertificateCallback(const struct ssl_early_callback_ctx *ctx) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400365 const TestConfig *config = GetTestConfig(ctx->ssl);
David Benjamin2d445c02015-02-09 13:03:50 -0500366 GetTestState(ctx->ssl)->early_callback_called = true;
David Benjamin5a593af2014-08-11 19:51:50 -0400367
David Benjamin6f5c0f42015-02-24 01:23:21 -0500368 if (!config->expected_server_name.empty()) {
369 const uint8_t *extension_data;
370 size_t extension_len;
371 CBS extension, server_name_list, host_name;
372 uint8_t name_type;
373
374 if (!SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
375 &extension_data,
376 &extension_len)) {
377 fprintf(stderr, "Could not find server_name extension.\n");
378 return -1;
379 }
380
381 CBS_init(&extension, extension_data, extension_len);
382 if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
383 CBS_len(&extension) != 0 ||
384 !CBS_get_u8(&server_name_list, &name_type) ||
385 name_type != TLSEXT_NAMETYPE_host_name ||
386 !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
387 CBS_len(&server_name_list) != 0) {
388 fprintf(stderr, "Could not decode server_name extension.\n");
389 return -1;
390 }
391
392 if (!CBS_mem_equal(&host_name,
393 (const uint8_t*)config->expected_server_name.data(),
394 config->expected_server_name.size())) {
395 fprintf(stderr, "Server name mismatch.\n");
396 }
David Benjamin7b030512014-07-08 17:30:11 -0400397 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400398
David Benjamin6f5c0f42015-02-24 01:23:21 -0500399 if (config->fail_early_callback) {
David Benjamin7b030512014-07-08 17:30:11 -0400400 return -1;
401 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400402
David Benjamin6f5c0f42015-02-24 01:23:21 -0500403 // Install the certificate in the early callback.
404 if (config->use_early_callback) {
405 if (config->async) {
406 // Install the certificate asynchronously.
407 return 0;
408 }
409 if (!InstallCertificate(ctx->ssl)) {
410 return -1;
411 }
David Benjamin7b030512014-07-08 17:30:11 -0400412 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400413 return 1;
414}
David Benjamin025b3d32014-07-01 19:53:04 -0400415
David Benjaminacb6dcc2016-03-10 09:15:01 -0500416static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400417 if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500418 return -1;
419 }
420
421 ScopedX509 x509;
422 ScopedEVP_PKEY pkey;
423 if (!GetCertificate(ssl, &x509, &pkey)) {
424 return -1;
425 }
426
427 // Return zero for no certificate.
428 if (!x509) {
429 return 0;
430 }
431
432 // Asynchronous private keys are not supported with client_cert_cb.
433 *out_x509 = x509.release();
434 *out_pkey = pkey.release();
435 return 1;
436}
437
Paul Lietar8f1c2682015-08-18 12:21:54 +0100438static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
439 SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data(store_ctx,
440 SSL_get_ex_data_X509_STORE_CTX_idx());
David Benjamin7e7a82d2016-05-20 20:12:42 -0400441 const TestConfig *config = GetTestConfig(ssl);
Paul Lietar8f1c2682015-08-18 12:21:54 +0100442
443 if (!config->expected_ocsp_response.empty()) {
444 const uint8_t *data;
445 size_t len;
446 SSL_get0_ocsp_response(ssl, &data, &len);
447 if (len == 0) {
448 fprintf(stderr, "OCSP response not available in verify callback\n");
449 return 0;
450 }
451 }
452
David Benjamin67666e72014-07-12 15:47:52 -0400453 return 1;
454}
455
Paul Lietar8f1c2682015-08-18 12:21:54 +0100456static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
457 store_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION;
458 return 0;
459}
460
David Benjaminc273d2c2015-02-09 12:59:46 -0500461static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
462 unsigned int *out_len, void *arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400463 const TestConfig *config = GetTestConfig(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500464 if (config->advertise_npn.empty()) {
David Benjamin1f5f62b2014-07-12 16:18:02 -0400465 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500466 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400467
David Benjamin5a593af2014-08-11 19:51:50 -0400468 *out = (const uint8_t*)config->advertise_npn.data();
469 *out_len = config->advertise_npn.size();
David Benjamin1f5f62b2014-07-12 16:18:02 -0400470 return SSL_TLSEXT_ERR_OK;
471}
472
David Benjaminc273d2c2015-02-09 12:59:46 -0500473static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
David Benjamin8b368412015-03-14 01:54:17 -0400474 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400475 const TestConfig *config = GetTestConfig(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500476 if (config->select_next_proto.empty()) {
David Benjamin7e3305e2014-07-28 14:52:32 -0400477 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500478 }
David Benjamin7e3305e2014-07-28 14:52:32 -0400479
David Benjamin5a593af2014-08-11 19:51:50 -0400480 *out = (uint8_t*)config->select_next_proto.data();
481 *outlen = config->select_next_proto.size();
David Benjamin7e3305e2014-07-28 14:52:32 -0400482 return SSL_TLSEXT_ERR_OK;
483}
484
David Benjaminc273d2c2015-02-09 12:59:46 -0500485static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
486 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400487 const TestConfig *config = GetTestConfig(ssl);
David Benjamin594e7d22016-03-17 17:49:56 -0400488 if (config->decline_alpn) {
David Benjaminae2888f2014-09-06 12:58:58 -0400489 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500490 }
David Benjaminae2888f2014-09-06 12:58:58 -0400491
492 if (!config->expected_advertised_alpn.empty() &&
493 (config->expected_advertised_alpn.size() != inlen ||
494 memcmp(config->expected_advertised_alpn.data(),
495 in, inlen) != 0)) {
496 fprintf(stderr, "bad ALPN select callback inputs\n");
497 exit(1);
498 }
499
500 *out = (const uint8_t*)config->select_alpn.data();
501 *outlen = config->select_alpn.size();
502 return SSL_TLSEXT_ERR_OK;
503}
504
David Benjaminc273d2c2015-02-09 12:59:46 -0500505static unsigned PskClientCallback(SSL *ssl, const char *hint,
506 char *out_identity,
507 unsigned max_identity_len,
508 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400509 const TestConfig *config = GetTestConfig(ssl);
David Benjamin48cae082014-10-27 01:06:24 -0400510
511 if (strcmp(hint ? hint : "", config->psk_identity.c_str()) != 0) {
512 fprintf(stderr, "Server PSK hint did not match.\n");
513 return 0;
514 }
515
516 // Account for the trailing '\0' for the identity.
517 if (config->psk_identity.size() >= max_identity_len ||
518 config->psk.size() > max_psk_len) {
519 fprintf(stderr, "PSK buffers too small\n");
520 return 0;
521 }
522
523 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
524 max_identity_len);
525 memcpy(out_psk, config->psk.data(), config->psk.size());
526 return config->psk.size();
527}
528
David Benjaminc273d2c2015-02-09 12:59:46 -0500529static unsigned PskServerCallback(SSL *ssl, const char *identity,
530 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400531 const TestConfig *config = GetTestConfig(ssl);
David Benjamin48cae082014-10-27 01:06:24 -0400532
533 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
534 fprintf(stderr, "Client PSK identity did not match.\n");
535 return 0;
536 }
537
538 if (config->psk.size() > max_psk_len) {
539 fprintf(stderr, "PSK buffers too small\n");
540 return 0;
541 }
542
543 memcpy(out_psk, config->psk.data(), config->psk.size());
544 return config->psk.size();
545}
546
David Benjamin4d2e7ce2015-05-08 13:29:45 -0400547static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
David Benjamin585d7a42016-06-02 14:58:00 -0400548 *out_clock = PacketedBioGetClock(GetTestState(ssl)->packeted_bio);
David Benjamin377fc312015-01-26 00:22:12 -0500549}
550
David Benjaminc273d2c2015-02-09 12:59:46 -0500551static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
David Benjamin2d445c02015-02-09 13:03:50 -0500552 *out_pkey = GetTestState(ssl)->channel_id.release();
David Benjamind9e07012015-02-09 03:04:34 -0500553}
554
David Benjaminc273d2c2015-02-09 12:59:46 -0500555static int CertCallback(SSL *ssl, void *arg) {
David Benjamin2d445c02015-02-09 13:03:50 -0500556 if (!GetTestState(ssl)->cert_ready) {
David Benjamin41fdbcd2015-02-09 03:13:35 -0500557 return -1;
558 }
559 if (!InstallCertificate(ssl)) {
560 return 0;
561 }
562 return 1;
563}
564
David Benjaminc273d2c2015-02-09 12:59:46 -0500565static SSL_SESSION *GetSessionCallback(SSL *ssl, uint8_t *data, int len,
566 int *copy) {
David Benjamin2d445c02015-02-09 13:03:50 -0500567 TestState *async_state = GetTestState(ssl);
David Benjamin1b8b6912015-02-09 04:28:16 -0500568 if (async_state->session) {
569 *copy = 0;
570 return async_state->session.release();
571 } else if (async_state->pending_session) {
572 return SSL_magic_pending_session_ptr();
573 } else {
574 return NULL;
575 }
576}
577
Adam Langley524e7172015-02-20 16:04:00 -0800578static int DDoSCallback(const struct ssl_early_callback_ctx *early_context) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400579 const TestConfig *config = GetTestConfig(early_context->ssl);
Adam Langley524e7172015-02-20 16:04:00 -0800580 static int callback_num = 0;
581
582 callback_num++;
583 if (config->fail_ddos_callback ||
584 (config->fail_second_ddos_callback && callback_num == 2)) {
585 return 0;
586 }
587 return 1;
588}
589
David Benjamin87e4acd2015-04-02 19:57:35 -0400590static void InfoCallback(const SSL *ssl, int type, int val) {
591 if (type == SSL_CB_HANDSHAKE_DONE) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400592 if (GetTestConfig(ssl)->handshake_never_done) {
David Benjamin87e4acd2015-04-02 19:57:35 -0400593 fprintf(stderr, "handshake completed\n");
594 // Abort before any expected error code is printed, to ensure the overall
595 // test fails.
596 abort();
597 }
598 GetTestState(ssl)->handshake_done = true;
599 }
600}
601
David Benjaminba4594a2015-06-18 18:36:15 -0400602static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
603 GetTestState(ssl)->got_new_session = true;
604 // BoringSSL passes a reference to |session|.
605 SSL_SESSION_free(session);
606 return 1;
607}
608
David Benjamind98452d2015-06-16 14:16:23 -0400609static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
610 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
611 int encrypt) {
612 // This is just test code, so use the all-zeros key.
613 static const uint8_t kZeros[16] = {0};
614
615 if (encrypt) {
616 memcpy(key_name, kZeros, sizeof(kZeros));
617 RAND_bytes(iv, 16);
618 } else if (memcmp(key_name, kZeros, 16) != 0) {
619 return 0;
620 }
621
622 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
623 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
624 return -1;
625 }
626
627 if (!encrypt) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400628 return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
David Benjamind98452d2015-06-16 14:16:23 -0400629 }
630 return 1;
631}
632
Adam Langley09505632015-07-30 18:10:13 -0700633// kCustomExtensionValue is the extension value that the custom extension
634// callbacks will add.
Adam Langleyc5b23a12015-07-30 18:19:26 -0700635static const uint16_t kCustomExtensionValue = 1234;
Adam Langley09505632015-07-30 18:10:13 -0700636static void *const kCustomExtensionAddArg =
637 reinterpret_cast<void *>(kCustomExtensionValue);
638static void *const kCustomExtensionParseArg =
639 reinterpret_cast<void *>(kCustomExtensionValue + 1);
640static const char kCustomExtensionContents[] = "custom extension";
641
642static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
643 const uint8_t **out, size_t *out_len,
644 int *out_alert_value, void *add_arg) {
645 if (extension_value != kCustomExtensionValue ||
646 add_arg != kCustomExtensionAddArg) {
647 abort();
648 }
649
David Benjamin7e7a82d2016-05-20 20:12:42 -0400650 if (GetTestConfig(ssl)->custom_extension_skip) {
Adam Langley09505632015-07-30 18:10:13 -0700651 return 0;
652 }
David Benjamin7e7a82d2016-05-20 20:12:42 -0400653 if (GetTestConfig(ssl)->custom_extension_fail_add) {
Adam Langley09505632015-07-30 18:10:13 -0700654 return -1;
655 }
656
657 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
658 *out_len = sizeof(kCustomExtensionContents) - 1;
659
660 return 1;
661}
662
663static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
664 const uint8_t *out, void *add_arg) {
665 if (extension_value != kCustomExtensionValue ||
666 add_arg != kCustomExtensionAddArg ||
667 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
668 abort();
669 }
670}
671
672static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
673 const uint8_t *contents,
674 size_t contents_len,
675 int *out_alert_value, void *parse_arg) {
676 if (extension_value != kCustomExtensionValue ||
677 parse_arg != kCustomExtensionParseArg) {
678 abort();
679 }
680
681 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
682 memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
683 *out_alert_value = SSL_AD_DECODE_ERROR;
684 return 0;
685 }
686
687 return 1;
688}
689
David Benjamin87c8a642015-02-21 01:54:29 -0500690// Connect returns a new socket connected to localhost on |port| or -1 on
691// error.
692static int Connect(uint16_t port) {
693 int sock = socket(AF_INET, SOCK_STREAM, 0);
694 if (sock == -1) {
695 PrintSocketError("socket");
696 return -1;
697 }
698 int nodelay = 1;
699 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
700 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
701 PrintSocketError("setsockopt");
702 closesocket(sock);
703 return -1;
704 }
705 sockaddr_in sin;
706 memset(&sin, 0, sizeof(sin));
707 sin.sin_family = AF_INET;
708 sin.sin_port = htons(port);
709 if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
710 PrintSocketError("inet_pton");
711 closesocket(sock);
712 return -1;
713 }
714 if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
715 sizeof(sin)) != 0) {
716 PrintSocketError("connect");
717 closesocket(sock);
718 return -1;
719 }
720 return sock;
721}
722
723class SocketCloser {
724 public:
725 explicit SocketCloser(int sock) : sock_(sock) {}
726 ~SocketCloser() {
727 // Half-close and drain the socket before releasing it. This seems to be
728 // necessary for graceful shutdown on Windows. It will also avoid write
729 // failures in the test runner.
730#if defined(OPENSSL_WINDOWS)
731 shutdown(sock_, SD_SEND);
732#else
733 shutdown(sock_, SHUT_WR);
734#endif
735 while (true) {
736 char buf[1024];
737 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
738 break;
739 }
740 }
741 closesocket(sock_);
742 }
743
744 private:
745 const int sock_;
746};
747
David Benjaminc273d2c2015-02-09 12:59:46 -0500748static ScopedSSL_CTX SetupCtx(const TestConfig *config) {
David Benjamina7f333d2015-02-09 02:37:18 -0500749 ScopedSSL_CTX ssl_ctx(SSL_CTX_new(
750 config->is_dtls ? DTLS_method() : TLS_method()));
751 if (!ssl_ctx) {
752 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -0400753 }
754
Nick Harper1fd39d82016-06-14 18:14:35 -0700755 if (!config->is_dtls) {
756 // Enable TLS 1.3 for tests.
757 SSL_CTX_set_max_version(ssl_ctx.get(), TLS1_3_VERSION);
758 }
759
Adam Langleycef75832015-09-03 14:51:12 -0700760 std::string cipher_list = "ALL";
761 if (!config->cipher.empty()) {
762 cipher_list = config->cipher;
763 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
764 }
765 if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
766 return nullptr;
767 }
768
769 if (!config->cipher_tls10.empty() &&
770 !SSL_CTX_set_cipher_list_tls10(ssl_ctx.get(),
771 config->cipher_tls10.c_str())) {
772 return nullptr;
773 }
774 if (!config->cipher_tls11.empty() &&
775 !SSL_CTX_set_cipher_list_tls11(ssl_ctx.get(),
776 config->cipher_tls11.c_str())) {
David Benjamina7f333d2015-02-09 02:37:18 -0500777 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -0400778 }
779
David Benjamina7f333d2015-02-09 02:37:18 -0500780 ScopedDH dh(DH_get_2048_256(NULL));
David Benjaminb7c5e842016-03-28 09:59:10 -0400781 if (!dh) {
782 return nullptr;
783 }
Adam Langleyc4f25ce2015-11-26 16:39:08 -0800784
785 if (config->use_sparse_dh_prime) {
786 // This prime number is 2^1024 + 643 – a value just above a power of two.
787 // Because of its form, values modulo it are essentially certain to be one
788 // byte shorter. This is used to test padding of these values.
789 if (BN_hex2bn(
790 &dh->p,
791 "1000000000000000000000000000000000000000000000000000000000000000"
792 "0000000000000000000000000000000000000000000000000000000000000000"
793 "0000000000000000000000000000000000000000000000000000000000000000"
794 "0000000000000000000000000000000000000000000000000000000000000028"
795 "3") == 0 ||
796 !BN_set_word(dh->g, 2)) {
797 return nullptr;
798 }
David Benjamine66148a2016-02-02 14:14:36 -0500799 BN_free(dh->q);
800 dh->q = NULL;
Adam Langleyc4f25ce2015-11-26 16:39:08 -0800801 dh->priv_length = 0;
802 }
803
David Benjaminb7c5e842016-03-28 09:59:10 -0400804 if (!SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
David Benjamina7f333d2015-02-09 02:37:18 -0500805 return nullptr;
David Benjaminf4e5c4e2014-08-02 17:35:45 -0400806 }
807
David Benjamin1b8b6912015-02-09 04:28:16 -0500808 if (config->async && config->is_server) {
809 // Disable the internal session cache. To test asynchronous session lookup,
810 // we use an external session cache.
811 SSL_CTX_set_session_cache_mode(
812 ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
David Benjaminc273d2c2015-02-09 12:59:46 -0500813 SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
David Benjamin1b8b6912015-02-09 04:28:16 -0500814 } else {
815 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
816 }
David Benjamin1d5c83e2014-07-22 19:20:02 -0400817
David Benjamind4c2bce2015-10-17 12:28:18 -0400818 SSL_CTX_set_select_certificate_cb(ssl_ctx.get(), SelectCertificateCallback);
David Benjamin8f2c20e2014-07-09 09:30:38 -0400819
David Benjaminacb6dcc2016-03-10 09:15:01 -0500820 if (config->use_old_client_cert_callback) {
821 SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
822 }
823
David Benjamin1f5f62b2014-07-12 16:18:02 -0400824 SSL_CTX_set_next_protos_advertised_cb(
David Benjaminc273d2c2015-02-09 12:59:46 -0500825 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400826 if (!config->select_next_proto.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500827 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
David Benjamina7f333d2015-02-09 02:37:18 -0500828 NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400829 }
830
David Benjamin594e7d22016-03-17 17:49:56 -0400831 if (!config->select_alpn.empty() || config->decline_alpn) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500832 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400833 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400834
Adam Langley49c7af12015-07-10 14:33:46 -0700835 SSL_CTX_enable_tls_channel_id(ssl_ctx.get());
David Benjaminc273d2c2015-02-09 12:59:46 -0500836 SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
David Benjamina08e49d2014-08-24 01:46:07 -0400837
David Benjamin82d0ffb2016-06-08 19:19:58 -0400838 SSL_CTX_set_current_time_cb(ssl_ctx.get(), CurrentTimeCallback);
David Benjamin377fc312015-01-26 00:22:12 -0500839
David Benjamin87e4acd2015-04-02 19:57:35 -0400840 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
David Benjaminba4594a2015-06-18 18:36:15 -0400841 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
David Benjamin87e4acd2015-04-02 19:57:35 -0400842
David Benjamind98452d2015-06-16 14:16:23 -0400843 if (config->use_ticket_callback) {
844 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
845 }
846
Adam Langley09505632015-07-30 18:10:13 -0700847 if (config->enable_client_custom_extension &&
848 !SSL_CTX_add_client_custom_ext(
849 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
850 CustomExtensionFreeCallback, kCustomExtensionAddArg,
851 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
852 return nullptr;
853 }
854
855 if (config->enable_server_custom_extension &&
856 !SSL_CTX_add_server_custom_ext(
857 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
858 CustomExtensionFreeCallback, kCustomExtensionAddArg,
859 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
860 return nullptr;
861 }
862
Paul Lietar8f1c2682015-08-18 12:21:54 +0100863 if (config->verify_fail) {
864 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
865 } else {
866 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
867 }
868
Paul Lietar4fac72e2015-09-09 13:44:55 +0100869 if (!config->signed_cert_timestamps.empty() &&
870 !SSL_CTX_set_signed_cert_timestamp_list(
871 ssl_ctx.get(), (const uint8_t *)config->signed_cert_timestamps.data(),
872 config->signed_cert_timestamps.size())) {
873 return nullptr;
874 }
875
David Benjamin1d5c83e2014-07-22 19:20:02 -0400876 return ssl_ctx;
David Benjamin1d5c83e2014-07-22 19:20:02 -0400877}
878
David Benjamin40f101b2015-02-20 11:23:42 -0500879// RetryAsync is called after a failed operation on |ssl| with return code
880// |ret|. If the operation should be retried, it simulates one asynchronous
David Benjamin6c2563e2015-04-03 03:47:47 -0400881// event and returns true. Otherwise it returns false.
882static bool RetryAsync(SSL *ssl, int ret) {
David Benjamin43ec06f2014-08-05 02:28:57 -0400883 // No error; don't retry.
884 if (ret >= 0) {
David Benjamin40f101b2015-02-20 11:23:42 -0500885 return false;
David Benjamin025b3d32014-07-01 19:53:04 -0400886 }
David Benjamin83f90402015-01-27 01:09:43 -0500887
David Benjamin6c2563e2015-04-03 03:47:47 -0400888 TestState *test_state = GetTestState(ssl);
Matt Braithwaite6278e242016-06-14 08:18:22 -0700889 assert(GetTestConfig(ssl)->async);
David Benjamin83f90402015-01-27 01:09:43 -0500890
David Benjamin585d7a42016-06-02 14:58:00 -0400891 if (test_state->packeted_bio != nullptr &&
892 PacketedBioAdvanceClock(test_state->packeted_bio)) {
David Benjamin13e81fc2015-11-02 17:16:13 -0500893 // The DTLS retransmit logic silently ignores write failures. So the test
894 // may progress, allow writes through synchronously.
David Benjamin585d7a42016-06-02 14:58:00 -0400895 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
David Benjamin13e81fc2015-11-02 17:16:13 -0500896 int timeout_ret = DTLSv1_handle_timeout(ssl);
David Benjamin585d7a42016-06-02 14:58:00 -0400897 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
David Benjamin13e81fc2015-11-02 17:16:13 -0500898
899 if (timeout_ret < 0) {
David Benjaminc565ebb2015-04-03 04:06:36 -0400900 fprintf(stderr, "Error retransmitting.\n");
David Benjamin40f101b2015-02-20 11:23:42 -0500901 return false;
David Benjamin83f90402015-01-27 01:09:43 -0500902 }
David Benjamin40f101b2015-02-20 11:23:42 -0500903 return true;
David Benjamin83f90402015-01-27 01:09:43 -0500904 }
905
David Benjamin43ec06f2014-08-05 02:28:57 -0400906 // See if we needed to read or write more. If so, allow one byte through on
907 // the appropriate end to maximally stress the state machine.
David Benjamind9e07012015-02-09 03:04:34 -0500908 switch (SSL_get_error(ssl, ret)) {
909 case SSL_ERROR_WANT_READ:
David Benjamin6c2563e2015-04-03 03:47:47 -0400910 AsyncBioAllowRead(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -0500911 return true;
David Benjamind9e07012015-02-09 03:04:34 -0500912 case SSL_ERROR_WANT_WRITE:
David Benjamin6c2563e2015-04-03 03:47:47 -0400913 AsyncBioAllowWrite(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -0500914 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -0500915 case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400916 ScopedEVP_PKEY pkey = LoadPrivateKey(GetTestConfig(ssl)->send_channel_id);
David Benjamin9d0847a2015-02-16 03:57:55 -0500917 if (!pkey) {
David Benjamin40f101b2015-02-20 11:23:42 -0500918 return false;
David Benjamin9d0847a2015-02-16 03:57:55 -0500919 }
David Benjamin6c2563e2015-04-03 03:47:47 -0400920 test_state->channel_id = std::move(pkey);
David Benjamin40f101b2015-02-20 11:23:42 -0500921 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -0500922 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500923 case SSL_ERROR_WANT_X509_LOOKUP:
David Benjamin6c2563e2015-04-03 03:47:47 -0400924 test_state->cert_ready = true;
David Benjamin40f101b2015-02-20 11:23:42 -0500925 return true;
David Benjamin1b8b6912015-02-09 04:28:16 -0500926 case SSL_ERROR_PENDING_SESSION:
David Benjamin6c2563e2015-04-03 03:47:47 -0400927 test_state->session = std::move(test_state->pending_session);
David Benjamin40f101b2015-02-20 11:23:42 -0500928 return true;
David Benjamin6f5c0f42015-02-24 01:23:21 -0500929 case SSL_ERROR_PENDING_CERTIFICATE:
930 // The handshake will resume without a second call to the early callback.
931 return InstallCertificate(ssl);
David Benjaminb4d65fd2015-05-29 17:11:21 -0400932 case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700933 test_state->private_key_retries++;
David Benjaminb4d65fd2015-05-29 17:11:21 -0400934 return true;
David Benjamind9e07012015-02-09 03:04:34 -0500935 default:
David Benjamin40f101b2015-02-20 11:23:42 -0500936 return false;
David Benjamin025b3d32014-07-01 19:53:04 -0400937 }
David Benjamin025b3d32014-07-01 19:53:04 -0400938}
939
David Benjamin6c2563e2015-04-03 03:47:47 -0400940// DoRead reads from |ssl|, resolving any asynchronous operations. It returns
941// the result value of the final |SSL_read| call.
942static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400943 const TestConfig *config = GetTestConfig(ssl);
David Benjamin13e81fc2015-11-02 17:16:13 -0500944 TestState *test_state = GetTestState(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -0400945 int ret;
946 do {
David Benjamin13e81fc2015-11-02 17:16:13 -0500947 if (config->async) {
948 // The DTLS retransmit logic silently ignores write failures. So the test
949 // may progress, allow writes through synchronously. |SSL_read| may
950 // trigger a retransmit, so disconnect the write quota.
951 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
952 }
David Benjamin6c2563e2015-04-03 03:47:47 -0400953 ret = SSL_read(ssl, out, max_out);
David Benjamin13e81fc2015-11-02 17:16:13 -0500954 if (config->async) {
955 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
956 }
David Benjamin6c2563e2015-04-03 03:47:47 -0400957 } while (config->async && RetryAsync(ssl, ret));
958 return ret;
959}
960
961// WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
962// operations. It returns the result of the final |SSL_write| call.
963static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400964 const TestConfig *config = GetTestConfig(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -0400965 int ret;
966 do {
967 ret = SSL_write(ssl, in, in_len);
968 if (ret > 0) {
969 in += ret;
970 in_len -= ret;
971 }
972 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
973 return ret;
974}
975
David Benjamin30789da2015-08-29 22:56:45 -0400976// DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
977// returns the result of the final |SSL_shutdown| call.
978static int DoShutdown(SSL *ssl) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400979 const TestConfig *config = GetTestConfig(ssl);
David Benjamin30789da2015-08-29 22:56:45 -0400980 int ret;
981 do {
982 ret = SSL_shutdown(ssl);
983 } while (config->async && RetryAsync(ssl, ret));
984 return ret;
985}
986
David Benjamin91eab5c2015-06-18 18:35:46 -0400987// CheckHandshakeProperties checks, immediately after |ssl| completes its
988// initial handshake (or False Starts), whether all the properties are
989// consistent with the test configuration and invariants.
990static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400991 const TestConfig *config = GetTestConfig(ssl);
David Benjamin91eab5c2015-06-18 18:35:46 -0400992
993 if (SSL_get_current_cipher(ssl) == nullptr) {
994 fprintf(stderr, "null cipher after handshake\n");
995 return false;
996 }
997
998 if (is_resume &&
999 (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
1000 fprintf(stderr, "session was%s reused\n",
1001 SSL_session_reused(ssl) ? "" : " not");
1002 return false;
1003 }
1004
1005 bool expect_handshake_done = is_resume || !config->false_start;
1006 if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
1007 fprintf(stderr, "handshake was%s completed\n",
1008 GetTestState(ssl)->handshake_done ? "" : " not");
1009 return false;
1010 }
1011
David Benjaminba4594a2015-06-18 18:36:15 -04001012 if (expect_handshake_done && !config->is_server) {
1013 bool expect_new_session =
1014 !config->expect_no_session &&
1015 (!SSL_session_reused(ssl) || config->expect_ticket_renewal);
1016 if (expect_new_session != GetTestState(ssl)->got_new_session) {
1017 fprintf(stderr,
David Benjamindd6fed92015-10-23 17:41:12 -04001018 "new session was%s cached, but we expected the opposite\n",
David Benjaminba4594a2015-06-18 18:36:15 -04001019 GetTestState(ssl)->got_new_session ? "" : " not");
1020 return false;
1021 }
1022 }
1023
David Benjamin91eab5c2015-06-18 18:35:46 -04001024 if (config->is_server && !GetTestState(ssl)->early_callback_called) {
1025 fprintf(stderr, "early callback not called\n");
1026 return false;
1027 }
1028
1029 if (!config->expected_server_name.empty()) {
1030 const char *server_name =
1031 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1032 if (server_name != config->expected_server_name) {
1033 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
1034 server_name, config->expected_server_name.c_str());
1035 return false;
1036 }
1037 }
1038
1039 if (!config->expected_certificate_types.empty()) {
David Benjamin75910642015-08-09 10:42:33 -04001040 const uint8_t *certificate_types;
1041 size_t certificate_types_len =
David Benjamin91eab5c2015-06-18 18:35:46 -04001042 SSL_get0_certificate_types(ssl, &certificate_types);
David Benjamin75910642015-08-09 10:42:33 -04001043 if (certificate_types_len != config->expected_certificate_types.size() ||
David Benjamin91eab5c2015-06-18 18:35:46 -04001044 memcmp(certificate_types,
1045 config->expected_certificate_types.data(),
David Benjamin75910642015-08-09 10:42:33 -04001046 certificate_types_len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001047 fprintf(stderr, "certificate types mismatch\n");
1048 return false;
1049 }
1050 }
1051
1052 if (!config->expected_next_proto.empty()) {
1053 const uint8_t *next_proto;
1054 unsigned next_proto_len;
1055 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
1056 if (next_proto_len != config->expected_next_proto.size() ||
1057 memcmp(next_proto, config->expected_next_proto.data(),
1058 next_proto_len) != 0) {
1059 fprintf(stderr, "negotiated next proto mismatch\n");
1060 return false;
1061 }
1062 }
1063
1064 if (!config->expected_alpn.empty()) {
1065 const uint8_t *alpn_proto;
1066 unsigned alpn_proto_len;
1067 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
1068 if (alpn_proto_len != config->expected_alpn.size() ||
1069 memcmp(alpn_proto, config->expected_alpn.data(),
1070 alpn_proto_len) != 0) {
1071 fprintf(stderr, "negotiated alpn proto mismatch\n");
1072 return false;
1073 }
1074 }
1075
1076 if (!config->expected_channel_id.empty()) {
1077 uint8_t channel_id[64];
1078 if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
1079 fprintf(stderr, "no channel id negotiated\n");
1080 return false;
1081 }
1082 if (config->expected_channel_id.size() != 64 ||
1083 memcmp(config->expected_channel_id.data(),
1084 channel_id, 64) != 0) {
1085 fprintf(stderr, "channel id mismatch\n");
1086 return false;
1087 }
1088 }
1089
1090 if (config->expect_extended_master_secret) {
1091 if (!ssl->session->extended_master_secret) {
1092 fprintf(stderr, "No EMS for session when expected");
1093 return false;
1094 }
1095 }
1096
1097 if (!config->expected_ocsp_response.empty()) {
1098 const uint8_t *data;
1099 size_t len;
1100 SSL_get0_ocsp_response(ssl, &data, &len);
1101 if (config->expected_ocsp_response.size() != len ||
1102 memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
1103 fprintf(stderr, "OCSP response mismatch\n");
1104 return false;
1105 }
1106 }
1107
1108 if (!config->expected_signed_cert_timestamps.empty()) {
1109 const uint8_t *data;
1110 size_t len;
1111 SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
1112 if (config->expected_signed_cert_timestamps.size() != len ||
1113 memcmp(config->expected_signed_cert_timestamps.data(),
1114 data, len) != 0) {
1115 fprintf(stderr, "SCT list mismatch\n");
1116 return false;
1117 }
1118 }
1119
Paul Lietar8f1c2682015-08-18 12:21:54 +01001120 if (config->expect_verify_result) {
1121 int expected_verify_result = config->verify_fail ?
1122 X509_V_ERR_APPLICATION_VERIFICATION :
1123 X509_V_OK;
1124
1125 if (SSL_get_verify_result(ssl) != expected_verify_result) {
1126 fprintf(stderr, "Wrong certificate verification result\n");
1127 return false;
1128 }
1129 }
1130
David Benjamin6e807652015-11-02 12:02:20 -05001131 if (config->expect_server_key_exchange_hash != 0 &&
1132 config->expect_server_key_exchange_hash !=
1133 SSL_get_server_key_exchange_hash(ssl)) {
1134 fprintf(stderr, "ServerKeyExchange hash was %d, wanted %d.\n",
1135 SSL_get_server_key_exchange_hash(ssl),
1136 config->expect_server_key_exchange_hash);
1137 return false;
1138 }
1139
David Benjamin9e68f192016-06-30 14:55:33 -04001140 if (config->expect_curve_id != 0) {
1141 uint16_t curve_id = SSL_get_curve_id(ssl);
1142 if (static_cast<uint16_t>(config->expect_curve_id) != curve_id) {
1143 fprintf(stderr, "curve_id was %04x, wanted %04x\n", curve_id,
1144 static_cast<uint16_t>(config->expect_curve_id));
1145 return false;
1146 }
1147 }
1148
1149 if (config->expect_dhe_group_size != 0) {
1150 unsigned dhe_group_size = SSL_get_dhe_group_size(ssl);
1151 if (static_cast<unsigned>(config->expect_dhe_group_size) !=
1152 dhe_group_size) {
1153 fprintf(stderr, "dhe_group_size was %u, wanted %d\n", dhe_group_size,
1154 config->expect_dhe_group_size);
David Benjamin4cc36ad2015-12-19 14:23:26 -05001155 return false;
1156 }
1157 }
1158
David Benjamin91eab5c2015-06-18 18:35:46 -04001159 if (!config->is_server) {
1160 /* Clients should expect a peer certificate chain iff this was not a PSK
1161 * cipher suite. */
1162 if (config->psk.empty()) {
1163 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
1164 fprintf(stderr, "Missing peer certificate chain!\n");
1165 return false;
1166 }
1167 } else if (SSL_get_peer_cert_chain(ssl) != nullptr) {
1168 fprintf(stderr, "Unexpected peer certificate chain!\n");
1169 return false;
1170 }
1171 }
1172 return true;
1173}
1174
David Benjamin87c8a642015-02-21 01:54:29 -05001175// DoExchange runs a test SSL exchange against the peer. On success, it returns
1176// true and sets |*out_session| to the negotiated SSL session. If the test is a
1177// resumption attempt, |is_resume| is true and |session| is the session from the
1178// previous exchange.
David Benjamin40f101b2015-02-20 11:23:42 -05001179static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx,
1180 const TestConfig *config, bool is_resume,
David Benjamin87c8a642015-02-21 01:54:29 -05001181 SSL_SESSION *session) {
David Benjamina7f333d2015-02-09 02:37:18 -05001182 ScopedSSL ssl(SSL_new(ssl_ctx));
1183 if (!ssl) {
David Benjamin40f101b2015-02-20 11:23:42 -05001184 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001185 }
1186
David Benjamin7e7a82d2016-05-20 20:12:42 -04001187 if (!SetTestConfig(ssl.get(), config) ||
David Benjamin2d445c02015-02-09 13:03:50 -05001188 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
David Benjamin40f101b2015-02-20 11:23:42 -05001189 return false;
Adam Langley69a01602014-11-17 17:26:55 -08001190 }
David Benjamin5a593af2014-08-11 19:51:50 -04001191
Adam Langley5f0efe02015-02-20 13:03:16 -08001192 if (config->fallback_scsv &&
1193 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
1194 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001195 }
David Benjaminacb6dcc2016-03-10 09:15:01 -05001196 if (!config->use_early_callback && !config->use_old_client_cert_callback) {
David Benjamin6f5c0f42015-02-24 01:23:21 -05001197 if (config->async) {
David Benjamin6f5c0f42015-02-24 01:23:21 -05001198 SSL_set_cert_cb(ssl.get(), CertCallback, NULL);
1199 } else if (!InstallCertificate(ssl.get())) {
1200 return false;
1201 }
David Benjamin5a593af2014-08-11 19:51:50 -04001202 }
1203 if (config->require_any_client_certificate) {
David Benjamina7f333d2015-02-09 02:37:18 -05001204 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
Paul Lietar8f1c2682015-08-18 12:21:54 +01001205 NULL);
1206 }
1207 if (config->verify_peer) {
1208 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
David Benjamin5a593af2014-08-11 19:51:50 -04001209 }
1210 if (config->false_start) {
David Benjamined7c4752015-02-16 19:16:46 -05001211 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
David Benjamin5a593af2014-08-11 19:51:50 -04001212 }
1213 if (config->cbc_record_splitting) {
David Benjamina7f333d2015-02-09 02:37:18 -05001214 SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
David Benjamin5a593af2014-08-11 19:51:50 -04001215 }
1216 if (config->partial_write) {
David Benjamina7f333d2015-02-09 02:37:18 -05001217 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
David Benjamin5a593af2014-08-11 19:51:50 -04001218 }
Steven Valdez4f94b1c2016-05-24 12:31:07 -04001219 if (config->no_tls13) {
1220 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
1221 }
David Benjamin5a593af2014-08-11 19:51:50 -04001222 if (config->no_tls12) {
David Benjamina7f333d2015-02-09 02:37:18 -05001223 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
David Benjamin5a593af2014-08-11 19:51:50 -04001224 }
1225 if (config->no_tls11) {
David Benjamina7f333d2015-02-09 02:37:18 -05001226 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
David Benjamin5a593af2014-08-11 19:51:50 -04001227 }
1228 if (config->no_tls1) {
David Benjamina7f333d2015-02-09 02:37:18 -05001229 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
David Benjamin5a593af2014-08-11 19:51:50 -04001230 }
1231 if (config->no_ssl3) {
David Benjamina7f333d2015-02-09 02:37:18 -05001232 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
David Benjamin5a593af2014-08-11 19:51:50 -04001233 }
David Benjamina08e49d2014-08-24 01:46:07 -04001234 if (!config->expected_channel_id.empty()) {
David Benjamina7f333d2015-02-09 02:37:18 -05001235 SSL_enable_tls_channel_id(ssl.get());
David Benjamina08e49d2014-08-24 01:46:07 -04001236 }
1237 if (!config->send_channel_id.empty()) {
David Benjamina7f333d2015-02-09 02:37:18 -05001238 SSL_enable_tls_channel_id(ssl.get());
David Benjamind9e07012015-02-09 03:04:34 -05001239 if (!config->async) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001240 // The async case will be supplied by |ChannelIdCallback|.
David Benjamind9e07012015-02-09 03:04:34 -05001241 ScopedEVP_PKEY pkey = LoadPrivateKey(config->send_channel_id);
1242 if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001243 return false;
David Benjamind9e07012015-02-09 03:04:34 -05001244 }
David Benjamina08e49d2014-08-24 01:46:07 -04001245 }
David Benjamina08e49d2014-08-24 01:46:07 -04001246 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001247 if (!config->host_name.empty() &&
1248 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001249 return false;
David Benjamine78bfde2014-09-06 12:45:15 -04001250 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001251 if (!config->advertise_alpn.empty() &&
1252 SSL_set_alpn_protos(ssl.get(),
1253 (const uint8_t *)config->advertise_alpn.data(),
1254 config->advertise_alpn.size()) != 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001255 return false;
David Benjaminae2888f2014-09-06 12:58:58 -04001256 }
David Benjamin48cae082014-10-27 01:06:24 -04001257 if (!config->psk.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001258 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
1259 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
David Benjamin48cae082014-10-27 01:06:24 -04001260 }
David Benjamin61f95272014-11-25 01:55:35 -05001261 if (!config->psk_identity.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001262 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001263 return false;
David Benjamin48cae082014-10-27 01:06:24 -04001264 }
David Benjamin61f95272014-11-25 01:55:35 -05001265 if (!config->srtp_profiles.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001266 !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001267 return false;
David Benjamin61f95272014-11-25 01:55:35 -05001268 }
1269 if (config->enable_ocsp_stapling &&
David Benjamina7f333d2015-02-09 02:37:18 -05001270 !SSL_enable_ocsp_stapling(ssl.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001271 return false;
David Benjamin61f95272014-11-25 01:55:35 -05001272 }
1273 if (config->enable_signed_cert_timestamps &&
David Benjamina7f333d2015-02-09 02:37:18 -05001274 !SSL_enable_signed_cert_timestamps(ssl.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001275 return false;
David Benjaminca6c8262014-11-15 19:06:08 -05001276 }
David Benjamin1eb367c2014-12-12 18:17:51 -05001277 if (config->min_version != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001278 SSL_set_min_version(ssl.get(), (uint16_t)config->min_version);
David Benjamin1eb367c2014-12-12 18:17:51 -05001279 }
1280 if (config->max_version != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001281 SSL_set_max_version(ssl.get(), (uint16_t)config->max_version);
David Benjamin1eb367c2014-12-12 18:17:51 -05001282 }
David Benjamin13be1de2015-01-11 16:29:36 -05001283 if (config->mtu != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001284 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
1285 SSL_set_mtu(ssl.get(), config->mtu);
David Benjamin13be1de2015-01-11 16:29:36 -05001286 }
Adam Langley524e7172015-02-20 16:04:00 -08001287 if (config->install_ddos_callback) {
1288 SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
1289 }
David Benjamin1d5ef3b2015-10-12 19:54:18 -04001290 if (config->renegotiate_once) {
1291 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_once);
1292 }
1293 if (config->renegotiate_freely) {
1294 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
David Benjaminb16346b2015-04-08 19:16:58 -04001295 }
Adam Langley27a0d082015-11-03 13:34:10 -08001296 if (config->renegotiate_ignore) {
1297 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_ignore);
1298 }
David Benjamin30789da2015-08-29 22:56:45 -04001299 if (!config->check_close_notify) {
1300 SSL_set_quiet_shutdown(ssl.get(), 1);
1301 }
David Benjamin091c4b92015-10-26 13:33:21 -04001302 if (config->disable_npn) {
1303 SSL_set_options(ssl.get(), SSL_OP_DISABLE_NPN);
1304 }
David Benjamin99fdfb92015-11-02 12:11:35 -05001305 if (config->p384_only) {
1306 int nid = NID_secp384r1;
1307 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
1308 return false;
1309 }
1310 }
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001311 if (config->enable_all_curves) {
1312 static const int kAllCurves[] = {
Matt Braithwaite053931e2016-05-25 12:06:05 -07001313 NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_X25519,
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001314 };
1315 if (!SSL_set1_curves(ssl.get(), kAllCurves,
1316 sizeof(kAllCurves) / sizeof(kAllCurves[0]))) {
1317 return false;
1318 }
1319 }
Taylor Brandstetter376a0fe2016-05-10 19:30:28 -07001320 if (config->initial_timeout_duration_ms > 0) {
1321 DTLSv1_set_initial_timeout_duration(ssl.get(),
1322 config->initial_timeout_duration_ms);
1323 }
David Benjamin025b3d32014-07-01 19:53:04 -04001324
David Benjamin87c8a642015-02-21 01:54:29 -05001325 int sock = Connect(config->port);
1326 if (sock == -1) {
1327 return false;
1328 }
1329 SocketCloser closer(sock);
1330
1331 ScopedBIO bio(BIO_new_socket(sock, BIO_NOCLOSE));
David Benjamina7f333d2015-02-09 02:37:18 -05001332 if (!bio) {
David Benjamin40f101b2015-02-20 11:23:42 -05001333 return false;
David Benjamin43ec06f2014-08-05 02:28:57 -04001334 }
David Benjamin6fd297b2014-08-11 18:43:38 -04001335 if (config->is_dtls) {
David Benjamin585d7a42016-06-02 14:58:00 -04001336 ScopedBIO packeted = PacketedBioCreate(!config->async);
David Benjaminb7c5e842016-03-28 09:59:10 -04001337 if (!packeted) {
1338 return false;
1339 }
David Benjamin585d7a42016-06-02 14:58:00 -04001340 GetTestState(ssl.get())->packeted_bio = packeted.get();
David Benjamina7f333d2015-02-09 02:37:18 -05001341 BIO_push(packeted.get(), bio.release());
1342 bio = std::move(packeted);
David Benjamin6fd297b2014-08-11 18:43:38 -04001343 }
David Benjamin5a593af2014-08-11 19:51:50 -04001344 if (config->async) {
David Benjamina7f333d2015-02-09 02:37:18 -05001345 ScopedBIO async_scoped =
David Benjaminc273d2c2015-02-09 12:59:46 -05001346 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
David Benjaminb7c5e842016-03-28 09:59:10 -04001347 if (!async_scoped) {
1348 return false;
1349 }
David Benjamina7f333d2015-02-09 02:37:18 -05001350 BIO_push(async_scoped.get(), bio.release());
David Benjamin6c2563e2015-04-03 03:47:47 -04001351 GetTestState(ssl.get())->async_bio = async_scoped.get();
David Benjamina7f333d2015-02-09 02:37:18 -05001352 bio = std::move(async_scoped);
David Benjamin43ec06f2014-08-05 02:28:57 -04001353 }
David Benjamina7f333d2015-02-09 02:37:18 -05001354 SSL_set_bio(ssl.get(), bio.get(), bio.get());
1355 bio.release(); // SSL_set_bio takes ownership.
David Benjamin43ec06f2014-08-05 02:28:57 -04001356
David Benjamin1d5c83e2014-07-22 19:20:02 -04001357 if (session != NULL) {
David Benjamin1b8b6912015-02-09 04:28:16 -05001358 if (!config->is_server) {
1359 if (SSL_set_session(ssl.get(), session) != 1) {
David Benjamin40f101b2015-02-20 11:23:42 -05001360 return false;
David Benjamin1b8b6912015-02-09 04:28:16 -05001361 }
1362 } else if (config->async) {
1363 // The internal session cache is disabled, so install the session
1364 // manually.
David Benjamin2d445c02015-02-09 13:03:50 -05001365 GetTestState(ssl.get())->pending_session.reset(
David Benjamin1b8b6912015-02-09 04:28:16 -05001366 SSL_SESSION_up_ref(session));
David Benjamin1d5c83e2014-07-22 19:20:02 -04001367 }
1368 }
1369
David Benjamina07c0fc2015-05-13 13:19:42 -04001370 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1371 fprintf(stderr, "non-null cipher before handshake\n");
1372 return false;
1373 }
1374
David Benjamin1d5c83e2014-07-22 19:20:02 -04001375 int ret;
David Benjamine0e7d0d2015-02-08 19:33:25 -05001376 if (config->implicit_handshake) {
David Benjamin5a593af2014-08-11 19:51:50 -04001377 if (config->is_server) {
David Benjamina7f333d2015-02-09 02:37:18 -05001378 SSL_set_accept_state(ssl.get());
David Benjamin43ec06f2014-08-05 02:28:57 -04001379 } else {
David Benjamina7f333d2015-02-09 02:37:18 -05001380 SSL_set_connect_state(ssl.get());
David Benjamin43ec06f2014-08-05 02:28:57 -04001381 }
David Benjamine0e7d0d2015-02-08 19:33:25 -05001382 } else {
1383 do {
1384 if (config->is_server) {
David Benjamina7f333d2015-02-09 02:37:18 -05001385 ret = SSL_accept(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -05001386 } else {
David Benjamina7f333d2015-02-09 02:37:18 -05001387 ret = SSL_connect(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -05001388 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001389 } while (config->async && RetryAsync(ssl.get(), ret));
David Benjamin91eab5c2015-06-18 18:35:46 -04001390 if (ret != 1 ||
1391 !CheckHandshakeProperties(ssl.get(), is_resume)) {
David Benjamin40f101b2015-02-20 11:23:42 -05001392 return false;
David Benjamine0e7d0d2015-02-08 19:33:25 -05001393 }
David Benjamin025b3d32014-07-01 19:53:04 -04001394
David Benjaminba4594a2015-06-18 18:36:15 -04001395 // Reset the state to assert later that the callback isn't called in
1396 // renegotations.
1397 GetTestState(ssl.get())->got_new_session = false;
David Benjamin61f95272014-11-25 01:55:35 -05001398 }
1399
David Benjaminc565ebb2015-04-03 04:06:36 -04001400 if (config->export_keying_material > 0) {
1401 std::vector<uint8_t> result(
1402 static_cast<size_t>(config->export_keying_material));
1403 if (!SSL_export_keying_material(
1404 ssl.get(), result.data(), result.size(),
1405 config->export_label.data(), config->export_label.size(),
1406 reinterpret_cast<const uint8_t*>(config->export_context.data()),
1407 config->export_context.size(), config->use_export_context)) {
1408 fprintf(stderr, "failed to export keying material\n");
1409 return false;
1410 }
1411 if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1412 return false;
1413 }
1414 }
1415
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001416 if (config->tls_unique) {
1417 uint8_t tls_unique[16];
1418 size_t tls_unique_len;
1419 if (!SSL_get_tls_unique(ssl.get(), tls_unique, &tls_unique_len,
1420 sizeof(tls_unique))) {
1421 fprintf(stderr, "failed to get tls-unique\n");
1422 return false;
1423 }
1424
1425 if (tls_unique_len != 12) {
1426 fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
1427 static_cast<unsigned>(tls_unique_len));
1428 return false;
1429 }
1430
1431 if (WriteAll(ssl.get(), tls_unique, tls_unique_len) < 0) {
1432 return false;
1433 }
1434 }
1435
David Benjamin5a593af2014-08-11 19:51:50 -04001436 if (config->write_different_record_sizes) {
David Benjamin6fd297b2014-08-11 18:43:38 -04001437 if (config->is_dtls) {
1438 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001439 return false;
David Benjamin6fd297b2014-08-11 18:43:38 -04001440 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001441 // This mode writes a number of different record sizes in an attempt to
1442 // trip up the CBC record splitting code.
Adam Langleybc949292015-06-18 21:32:44 -07001443 static const size_t kBufLen = 32769;
1444 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1445 memset(buf.get(), 0x42, kBufLen);
Kenny Root7fdeaf12014-08-05 15:23:37 -07001446 static const size_t kRecordSizes[] = {
1447 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
1448 for (size_t i = 0; i < sizeof(kRecordSizes) / sizeof(kRecordSizes[0]);
1449 i++) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07001450 const size_t len = kRecordSizes[i];
Adam Langleybc949292015-06-18 21:32:44 -07001451 if (len > kBufLen) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07001452 fprintf(stderr, "Bad kRecordSizes value.\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001453 return false;
Kenny Root7fdeaf12014-08-05 15:23:37 -07001454 }
Adam Langleybc949292015-06-18 21:32:44 -07001455 if (WriteAll(ssl.get(), buf.get(), len) < 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001456 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001457 }
1458 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001459 } else {
David Benjamine58c4f52014-08-24 03:47:07 -04001460 if (config->shim_writes_first) {
David Benjamin6c2563e2015-04-03 03:47:47 -04001461 if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1462 5) < 0) {
1463 return false;
1464 }
David Benjamine58c4f52014-08-24 03:47:07 -04001465 }
David Benjamin30789da2015-08-29 22:56:45 -04001466 if (!config->shim_shuts_down) {
1467 for (;;) {
Adam Langleya0a8dc22015-09-09 10:22:00 -07001468 static const size_t kBufLen = 16384;
1469 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1470
David Benjamin2c99d282015-09-01 10:23:00 -04001471 // Read only 512 bytes at a time in TLS to ensure records may be
1472 // returned in multiple reads.
Adam Langleya0a8dc22015-09-09 10:22:00 -07001473 int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
David Benjamin30789da2015-08-29 22:56:45 -04001474 int err = SSL_get_error(ssl.get(), n);
1475 if (err == SSL_ERROR_ZERO_RETURN ||
1476 (n == 0 && err == SSL_ERROR_SYSCALL)) {
1477 if (n != 0) {
1478 fprintf(stderr, "Invalid SSL_get_error output\n");
1479 return false;
1480 }
1481 // Stop on either clean or unclean shutdown.
1482 break;
1483 } else if (err != SSL_ERROR_NONE) {
1484 if (n > 0) {
1485 fprintf(stderr, "Invalid SSL_get_error output\n");
1486 return false;
1487 }
1488 return false;
1489 }
1490 // Successfully read data.
1491 if (n <= 0) {
David Benjamin9a38e922015-01-22 16:06:11 -05001492 fprintf(stderr, "Invalid SSL_get_error output\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001493 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001494 }
David Benjamin30789da2015-08-29 22:56:45 -04001495
1496 // After a successful read, with or without False Start, the handshake
1497 // must be complete.
1498 if (!GetTestState(ssl.get())->handshake_done) {
1499 fprintf(stderr, "handshake was not completed after SSL_read\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001500 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001501 }
David Benjamin87e4acd2015-04-02 19:57:35 -04001502
David Benjamin30789da2015-08-29 22:56:45 -04001503 for (int i = 0; i < n; i++) {
1504 buf[i] ^= 0xff;
1505 }
Adam Langleya0a8dc22015-09-09 10:22:00 -07001506 if (WriteAll(ssl.get(), buf.get(), n) < 0) {
David Benjamin30789da2015-08-29 22:56:45 -04001507 return false;
1508 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001509 }
1510 }
David Benjamin025b3d32014-07-01 19:53:04 -04001511 }
1512
David Benjaminba4594a2015-06-18 18:36:15 -04001513 if (!config->is_server && !config->false_start &&
1514 !config->implicit_handshake &&
1515 GetTestState(ssl.get())->got_new_session) {
1516 fprintf(stderr, "new session was established after the handshake\n");
1517 return false;
1518 }
1519
David Benjamin1d5c83e2014-07-22 19:20:02 -04001520 if (out_session) {
David Benjamina7f333d2015-02-09 02:37:18 -05001521 out_session->reset(SSL_get1_session(ssl.get()));
David Benjamin1d5c83e2014-07-22 19:20:02 -04001522 }
1523
David Benjamin30789da2015-08-29 22:56:45 -04001524 ret = DoShutdown(ssl.get());
1525
1526 if (config->shim_shuts_down && config->check_close_notify) {
1527 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1528 // it returns zero when our close_notify is sent, then one when the peer's
1529 // is received.
1530 if (ret != 0) {
1531 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1532 return false;
1533 }
1534 ret = DoShutdown(ssl.get());
1535 }
1536
1537 if (ret != 1) {
1538 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1539 return false;
1540 }
1541
David Benjamin324dce42015-10-12 19:49:00 -04001542 if (SSL_total_renegotiations(ssl.get()) !=
1543 config->expect_total_renegotiations) {
1544 fprintf(stderr, "Expected %d renegotiations, got %d\n",
1545 config->expect_total_renegotiations,
1546 SSL_total_renegotiations(ssl.get()));
1547 return false;
1548 }
1549
David Benjamin40f101b2015-02-20 11:23:42 -05001550 return true;
David Benjamin025b3d32014-07-01 19:53:04 -04001551}
David Benjamin1d5c83e2014-07-22 19:20:02 -04001552
David Benjaminff3a1492016-03-02 10:12:06 -05001553class StderrDelimiter {
1554 public:
1555 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
1556};
1557
David Benjamin1d5c83e2014-07-22 19:20:02 -04001558int main(int argc, char **argv) {
David Benjaminff3a1492016-03-02 10:12:06 -05001559 // To distinguish ASan's output from ours, add a trailing message to stderr.
1560 // Anything following this line will be considered an error.
1561 StderrDelimiter delimiter;
1562
David Benjamin87c8a642015-02-21 01:54:29 -05001563#if defined(OPENSSL_WINDOWS)
1564 /* Initialize Winsock. */
1565 WORD wsa_version = MAKEWORD(2, 2);
1566 WSADATA wsa_data;
1567 int wsa_err = WSAStartup(wsa_version, &wsa_data);
1568 if (wsa_err != 0) {
1569 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1570 return 1;
1571 }
1572 if (wsa_data.wVersion != wsa_version) {
1573 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1574 return 1;
1575 }
1576#else
David Benjamin1d5c83e2014-07-22 19:20:02 -04001577 signal(SIGPIPE, SIG_IGN);
Adam Langleyded93582014-07-31 15:23:51 -07001578#endif
David Benjamin1d5c83e2014-07-22 19:20:02 -04001579
David Benjamin7a1eefd2015-10-17 23:39:22 -04001580 CRYPTO_library_init();
David Benjamind9e07012015-02-09 03:04:34 -05001581 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
David Benjamin2d445c02015-02-09 13:03:50 -05001582 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
David Benjamin6c2563e2015-04-03 03:47:47 -04001583 if (g_config_index < 0 || g_state_index < 0) {
David Benjaminae3e4872014-11-18 21:52:26 -05001584 return 1;
1585 }
David Benjamin5a593af2014-08-11 19:51:50 -04001586
1587 TestConfig config;
1588 if (!ParseConfig(argc - 1, argv + 1, &config)) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001589 return Usage(argv[0]);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001590 }
1591
David Benjaminc273d2c2015-02-09 12:59:46 -05001592 ScopedSSL_CTX ssl_ctx = SetupCtx(&config);
David Benjamina7f333d2015-02-09 02:37:18 -05001593 if (!ssl_ctx) {
Brian Smith83a82982015-04-09 16:21:10 -10001594 ERR_print_errors_fp(stderr);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001595 return 1;
1596 }
1597
David Benjamina7f333d2015-02-09 02:37:18 -05001598 ScopedSSL_SESSION session;
David Benjamin40f101b2015-02-20 11:23:42 -05001599 if (!DoExchange(&session, ssl_ctx.get(), &config, false /* is_resume */,
David Benjamin87c8a642015-02-21 01:54:29 -05001600 NULL /* session */)) {
Brian Smith83a82982015-04-09 16:21:10 -10001601 ERR_print_errors_fp(stderr);
David Benjamin40f101b2015-02-20 11:23:42 -05001602 return 1;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001603 }
1604
David Benjamin40f101b2015-02-20 11:23:42 -05001605 if (config.resume &&
1606 !DoExchange(NULL, ssl_ctx.get(), &config, true /* is_resume */,
David Benjamin87c8a642015-02-21 01:54:29 -05001607 session.get())) {
Brian Smith83a82982015-04-09 16:21:10 -10001608 ERR_print_errors_fp(stderr);
David Benjamin40f101b2015-02-20 11:23:42 -05001609 return 1;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001610 }
1611
David Benjamina7f333d2015-02-09 02:37:18 -05001612 return 0;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001613}