blob: 3cfbeb3966bd67341f22d0571c75a1f4f2945b51 [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
Adam Langleyd2b5af52016-07-12 08:03:59 -070058#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"
Adam Langleyd2b5af52016-07-12 08:03:59 -070061#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>
Adam Langley10f97f32016-07-12 08:09:33 -0700287struct Free {
Steven Valdez0d62f262015-09-04 12:41:04 -0400288 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()) {
Adam Langley10f97f32016-07-12 08:09:33 -0700298 std::unique_ptr<char, Free<char>> digest_prefs(
Steven Valdez0d62f262015-09-04 12:41:04 -0400299 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 Benjaminca3d5452016-07-14 12:51:01 -0400318 if (!config->signing_prefs.empty()) {
319 std::vector<uint16_t> u16s(config->signing_prefs.begin(),
320 config->signing_prefs.end());
321 if (!SSL_set_signing_algorithm_prefs(ssl, u16s.data(), u16s.size())) {
322 return false;
323 }
324 }
325
David Benjaminb4d65fd2015-05-29 17:11:21 -0400326 if (!config->key_file.empty()) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500327 *out_pkey = LoadPrivateKey(config->key_file.c_str());
328 if (!*out_pkey) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400329 return false;
330 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500331 }
David Benjaminacb6dcc2016-03-10 09:15:01 -0500332 if (!config->cert_file.empty()) {
333 *out_x509 = LoadCertificate(config->cert_file.c_str());
334 if (!*out_x509) {
335 return false;
336 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500337 }
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100338 if (!config->ocsp_response.empty() &&
339 !SSL_CTX_set_ocsp_response(ssl->ctx,
340 (const uint8_t *)config->ocsp_response.data(),
341 config->ocsp_response.size())) {
342 return false;
343 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500344 return true;
345}
346
David Benjaminacb6dcc2016-03-10 09:15:01 -0500347static bool InstallCertificate(SSL *ssl) {
348 ScopedX509 x509;
349 ScopedEVP_PKEY pkey;
350 if (!GetCertificate(ssl, &x509, &pkey)) {
351 return false;
352 }
353
354 if (pkey) {
355 TestState *test_state = GetTestState(ssl);
David Benjamin7e7a82d2016-05-20 20:12:42 -0400356 const TestConfig *config = GetTestConfig(ssl);
David Benjaminacb6dcc2016-03-10 09:15:01 -0500357 if (config->async) {
358 test_state->private_key = std::move(pkey);
359 SSL_set_private_key_method(ssl, &g_async_private_key_method);
360 } else if (!SSL_use_PrivateKey(ssl, pkey.get())) {
361 return false;
362 }
363 }
364
365 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
366 return false;
367 }
368
369 return true;
370}
371
David Benjaminc273d2c2015-02-09 12:59:46 -0500372static int SelectCertificateCallback(const struct ssl_early_callback_ctx *ctx) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400373 const TestConfig *config = GetTestConfig(ctx->ssl);
David Benjamin2d445c02015-02-09 13:03:50 -0500374 GetTestState(ctx->ssl)->early_callback_called = true;
David Benjamin5a593af2014-08-11 19:51:50 -0400375
David Benjamin6f5c0f42015-02-24 01:23:21 -0500376 if (!config->expected_server_name.empty()) {
377 const uint8_t *extension_data;
378 size_t extension_len;
379 CBS extension, server_name_list, host_name;
380 uint8_t name_type;
381
382 if (!SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
383 &extension_data,
384 &extension_len)) {
385 fprintf(stderr, "Could not find server_name extension.\n");
386 return -1;
387 }
388
389 CBS_init(&extension, extension_data, extension_len);
390 if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
391 CBS_len(&extension) != 0 ||
392 !CBS_get_u8(&server_name_list, &name_type) ||
393 name_type != TLSEXT_NAMETYPE_host_name ||
394 !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
395 CBS_len(&server_name_list) != 0) {
396 fprintf(stderr, "Could not decode server_name extension.\n");
397 return -1;
398 }
399
400 if (!CBS_mem_equal(&host_name,
401 (const uint8_t*)config->expected_server_name.data(),
402 config->expected_server_name.size())) {
403 fprintf(stderr, "Server name mismatch.\n");
404 }
David Benjamin7b030512014-07-08 17:30:11 -0400405 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400406
David Benjamin6f5c0f42015-02-24 01:23:21 -0500407 if (config->fail_early_callback) {
David Benjamin7b030512014-07-08 17:30:11 -0400408 return -1;
409 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400410
David Benjamin6f5c0f42015-02-24 01:23:21 -0500411 // Install the certificate in the early callback.
412 if (config->use_early_callback) {
413 if (config->async) {
414 // Install the certificate asynchronously.
415 return 0;
416 }
417 if (!InstallCertificate(ctx->ssl)) {
418 return -1;
419 }
David Benjamin7b030512014-07-08 17:30:11 -0400420 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400421 return 1;
422}
David Benjamin025b3d32014-07-01 19:53:04 -0400423
David Benjaminacb6dcc2016-03-10 09:15:01 -0500424static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400425 if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500426 return -1;
427 }
428
429 ScopedX509 x509;
430 ScopedEVP_PKEY pkey;
431 if (!GetCertificate(ssl, &x509, &pkey)) {
432 return -1;
433 }
434
435 // Return zero for no certificate.
436 if (!x509) {
437 return 0;
438 }
439
440 // Asynchronous private keys are not supported with client_cert_cb.
441 *out_x509 = x509.release();
442 *out_pkey = pkey.release();
443 return 1;
444}
445
Paul Lietar8f1c2682015-08-18 12:21:54 +0100446static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
447 SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data(store_ctx,
448 SSL_get_ex_data_X509_STORE_CTX_idx());
David Benjamin7e7a82d2016-05-20 20:12:42 -0400449 const TestConfig *config = GetTestConfig(ssl);
Paul Lietar8f1c2682015-08-18 12:21:54 +0100450
451 if (!config->expected_ocsp_response.empty()) {
452 const uint8_t *data;
453 size_t len;
454 SSL_get0_ocsp_response(ssl, &data, &len);
455 if (len == 0) {
456 fprintf(stderr, "OCSP response not available in verify callback\n");
457 return 0;
458 }
459 }
460
David Benjamin67666e72014-07-12 15:47:52 -0400461 return 1;
462}
463
Paul Lietar8f1c2682015-08-18 12:21:54 +0100464static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
465 store_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION;
466 return 0;
467}
468
David Benjaminc273d2c2015-02-09 12:59:46 -0500469static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
470 unsigned int *out_len, void *arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400471 const TestConfig *config = GetTestConfig(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500472 if (config->advertise_npn.empty()) {
David Benjamin1f5f62b2014-07-12 16:18:02 -0400473 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500474 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400475
David Benjamin5a593af2014-08-11 19:51:50 -0400476 *out = (const uint8_t*)config->advertise_npn.data();
477 *out_len = config->advertise_npn.size();
David Benjamin1f5f62b2014-07-12 16:18:02 -0400478 return SSL_TLSEXT_ERR_OK;
479}
480
David Benjaminc273d2c2015-02-09 12:59:46 -0500481static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
David Benjamin8b368412015-03-14 01:54:17 -0400482 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400483 const TestConfig *config = GetTestConfig(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500484 if (config->select_next_proto.empty()) {
David Benjamin7e3305e2014-07-28 14:52:32 -0400485 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500486 }
David Benjamin7e3305e2014-07-28 14:52:32 -0400487
David Benjamin5a593af2014-08-11 19:51:50 -0400488 *out = (uint8_t*)config->select_next_proto.data();
489 *outlen = config->select_next_proto.size();
David Benjamin7e3305e2014-07-28 14:52:32 -0400490 return SSL_TLSEXT_ERR_OK;
491}
492
David Benjaminc273d2c2015-02-09 12:59:46 -0500493static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
494 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400495 const TestConfig *config = GetTestConfig(ssl);
David Benjamin594e7d22016-03-17 17:49:56 -0400496 if (config->decline_alpn) {
David Benjaminae2888f2014-09-06 12:58:58 -0400497 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500498 }
David Benjaminae2888f2014-09-06 12:58:58 -0400499
500 if (!config->expected_advertised_alpn.empty() &&
501 (config->expected_advertised_alpn.size() != inlen ||
502 memcmp(config->expected_advertised_alpn.data(),
503 in, inlen) != 0)) {
504 fprintf(stderr, "bad ALPN select callback inputs\n");
505 exit(1);
506 }
507
508 *out = (const uint8_t*)config->select_alpn.data();
509 *outlen = config->select_alpn.size();
510 return SSL_TLSEXT_ERR_OK;
511}
512
David Benjaminc273d2c2015-02-09 12:59:46 -0500513static unsigned PskClientCallback(SSL *ssl, const char *hint,
514 char *out_identity,
515 unsigned max_identity_len,
516 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400517 const TestConfig *config = GetTestConfig(ssl);
David Benjamin48cae082014-10-27 01:06:24 -0400518
519 if (strcmp(hint ? hint : "", config->psk_identity.c_str()) != 0) {
520 fprintf(stderr, "Server PSK hint did not match.\n");
521 return 0;
522 }
523
524 // Account for the trailing '\0' for the identity.
525 if (config->psk_identity.size() >= max_identity_len ||
526 config->psk.size() > max_psk_len) {
527 fprintf(stderr, "PSK buffers too small\n");
528 return 0;
529 }
530
531 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
532 max_identity_len);
533 memcpy(out_psk, config->psk.data(), config->psk.size());
534 return config->psk.size();
535}
536
David Benjaminc273d2c2015-02-09 12:59:46 -0500537static unsigned PskServerCallback(SSL *ssl, const char *identity,
538 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400539 const TestConfig *config = GetTestConfig(ssl);
David Benjamin48cae082014-10-27 01:06:24 -0400540
541 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
542 fprintf(stderr, "Client PSK identity did not match.\n");
543 return 0;
544 }
545
546 if (config->psk.size() > max_psk_len) {
547 fprintf(stderr, "PSK buffers too small\n");
548 return 0;
549 }
550
551 memcpy(out_psk, config->psk.data(), config->psk.size());
552 return config->psk.size();
553}
554
David Benjamin4d2e7ce2015-05-08 13:29:45 -0400555static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
David Benjamin585d7a42016-06-02 14:58:00 -0400556 *out_clock = PacketedBioGetClock(GetTestState(ssl)->packeted_bio);
David Benjamin377fc312015-01-26 00:22:12 -0500557}
558
David Benjaminc273d2c2015-02-09 12:59:46 -0500559static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
David Benjamin2d445c02015-02-09 13:03:50 -0500560 *out_pkey = GetTestState(ssl)->channel_id.release();
David Benjamind9e07012015-02-09 03:04:34 -0500561}
562
David Benjaminc273d2c2015-02-09 12:59:46 -0500563static int CertCallback(SSL *ssl, void *arg) {
David Benjamin2d445c02015-02-09 13:03:50 -0500564 if (!GetTestState(ssl)->cert_ready) {
David Benjamin41fdbcd2015-02-09 03:13:35 -0500565 return -1;
566 }
567 if (!InstallCertificate(ssl)) {
568 return 0;
569 }
570 return 1;
571}
572
David Benjaminc273d2c2015-02-09 12:59:46 -0500573static SSL_SESSION *GetSessionCallback(SSL *ssl, uint8_t *data, int len,
574 int *copy) {
David Benjamin2d445c02015-02-09 13:03:50 -0500575 TestState *async_state = GetTestState(ssl);
David Benjamin1b8b6912015-02-09 04:28:16 -0500576 if (async_state->session) {
577 *copy = 0;
578 return async_state->session.release();
579 } else if (async_state->pending_session) {
580 return SSL_magic_pending_session_ptr();
581 } else {
582 return NULL;
583 }
584}
585
Adam Langley524e7172015-02-20 16:04:00 -0800586static int DDoSCallback(const struct ssl_early_callback_ctx *early_context) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400587 const TestConfig *config = GetTestConfig(early_context->ssl);
Adam Langley524e7172015-02-20 16:04:00 -0800588 static int callback_num = 0;
589
590 callback_num++;
591 if (config->fail_ddos_callback ||
592 (config->fail_second_ddos_callback && callback_num == 2)) {
593 return 0;
594 }
595 return 1;
596}
597
David Benjamin87e4acd2015-04-02 19:57:35 -0400598static void InfoCallback(const SSL *ssl, int type, int val) {
599 if (type == SSL_CB_HANDSHAKE_DONE) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400600 if (GetTestConfig(ssl)->handshake_never_done) {
David Benjamin87e4acd2015-04-02 19:57:35 -0400601 fprintf(stderr, "handshake completed\n");
602 // Abort before any expected error code is printed, to ensure the overall
603 // test fails.
604 abort();
605 }
606 GetTestState(ssl)->handshake_done = true;
607 }
608}
609
David Benjaminba4594a2015-06-18 18:36:15 -0400610static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
611 GetTestState(ssl)->got_new_session = true;
612 // BoringSSL passes a reference to |session|.
613 SSL_SESSION_free(session);
614 return 1;
615}
616
David Benjamind98452d2015-06-16 14:16:23 -0400617static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
618 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
619 int encrypt) {
620 // This is just test code, so use the all-zeros key.
621 static const uint8_t kZeros[16] = {0};
622
623 if (encrypt) {
624 memcpy(key_name, kZeros, sizeof(kZeros));
625 RAND_bytes(iv, 16);
626 } else if (memcmp(key_name, kZeros, 16) != 0) {
627 return 0;
628 }
629
630 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
631 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
632 return -1;
633 }
634
635 if (!encrypt) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400636 return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
David Benjamind98452d2015-06-16 14:16:23 -0400637 }
638 return 1;
639}
640
Adam Langley09505632015-07-30 18:10:13 -0700641// kCustomExtensionValue is the extension value that the custom extension
642// callbacks will add.
Adam Langleyc5b23a12015-07-30 18:19:26 -0700643static const uint16_t kCustomExtensionValue = 1234;
Adam Langley09505632015-07-30 18:10:13 -0700644static void *const kCustomExtensionAddArg =
645 reinterpret_cast<void *>(kCustomExtensionValue);
646static void *const kCustomExtensionParseArg =
647 reinterpret_cast<void *>(kCustomExtensionValue + 1);
648static const char kCustomExtensionContents[] = "custom extension";
649
650static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
651 const uint8_t **out, size_t *out_len,
652 int *out_alert_value, void *add_arg) {
653 if (extension_value != kCustomExtensionValue ||
654 add_arg != kCustomExtensionAddArg) {
655 abort();
656 }
657
David Benjamin7e7a82d2016-05-20 20:12:42 -0400658 if (GetTestConfig(ssl)->custom_extension_skip) {
Adam Langley09505632015-07-30 18:10:13 -0700659 return 0;
660 }
David Benjamin7e7a82d2016-05-20 20:12:42 -0400661 if (GetTestConfig(ssl)->custom_extension_fail_add) {
Adam Langley09505632015-07-30 18:10:13 -0700662 return -1;
663 }
664
665 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
666 *out_len = sizeof(kCustomExtensionContents) - 1;
667
668 return 1;
669}
670
671static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
672 const uint8_t *out, void *add_arg) {
673 if (extension_value != kCustomExtensionValue ||
674 add_arg != kCustomExtensionAddArg ||
675 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
676 abort();
677 }
678}
679
680static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
681 const uint8_t *contents,
682 size_t contents_len,
683 int *out_alert_value, void *parse_arg) {
684 if (extension_value != kCustomExtensionValue ||
685 parse_arg != kCustomExtensionParseArg) {
686 abort();
687 }
688
689 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
690 memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
691 *out_alert_value = SSL_AD_DECODE_ERROR;
692 return 0;
693 }
694
695 return 1;
696}
697
David Benjamin87c8a642015-02-21 01:54:29 -0500698// Connect returns a new socket connected to localhost on |port| or -1 on
699// error.
700static int Connect(uint16_t port) {
701 int sock = socket(AF_INET, SOCK_STREAM, 0);
702 if (sock == -1) {
703 PrintSocketError("socket");
704 return -1;
705 }
706 int nodelay = 1;
707 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
708 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
709 PrintSocketError("setsockopt");
710 closesocket(sock);
711 return -1;
712 }
713 sockaddr_in sin;
714 memset(&sin, 0, sizeof(sin));
715 sin.sin_family = AF_INET;
716 sin.sin_port = htons(port);
717 if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
718 PrintSocketError("inet_pton");
719 closesocket(sock);
720 return -1;
721 }
722 if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
723 sizeof(sin)) != 0) {
724 PrintSocketError("connect");
725 closesocket(sock);
726 return -1;
727 }
728 return sock;
729}
730
731class SocketCloser {
732 public:
733 explicit SocketCloser(int sock) : sock_(sock) {}
734 ~SocketCloser() {
735 // Half-close and drain the socket before releasing it. This seems to be
736 // necessary for graceful shutdown on Windows. It will also avoid write
737 // failures in the test runner.
738#if defined(OPENSSL_WINDOWS)
739 shutdown(sock_, SD_SEND);
740#else
741 shutdown(sock_, SHUT_WR);
742#endif
743 while (true) {
744 char buf[1024];
745 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
746 break;
747 }
748 }
749 closesocket(sock_);
750 }
751
752 private:
753 const int sock_;
754};
755
David Benjaminc273d2c2015-02-09 12:59:46 -0500756static ScopedSSL_CTX SetupCtx(const TestConfig *config) {
David Benjamina7f333d2015-02-09 02:37:18 -0500757 ScopedSSL_CTX ssl_ctx(SSL_CTX_new(
758 config->is_dtls ? DTLS_method() : TLS_method()));
759 if (!ssl_ctx) {
760 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -0400761 }
762
Nick Harper1fd39d82016-06-14 18:14:35 -0700763 if (!config->is_dtls) {
764 // Enable TLS 1.3 for tests.
765 SSL_CTX_set_max_version(ssl_ctx.get(), TLS1_3_VERSION);
766 }
767
Adam Langleycef75832015-09-03 14:51:12 -0700768 std::string cipher_list = "ALL";
769 if (!config->cipher.empty()) {
770 cipher_list = config->cipher;
771 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
772 }
773 if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
774 return nullptr;
775 }
776
777 if (!config->cipher_tls10.empty() &&
778 !SSL_CTX_set_cipher_list_tls10(ssl_ctx.get(),
779 config->cipher_tls10.c_str())) {
780 return nullptr;
781 }
782 if (!config->cipher_tls11.empty() &&
783 !SSL_CTX_set_cipher_list_tls11(ssl_ctx.get(),
784 config->cipher_tls11.c_str())) {
David Benjamina7f333d2015-02-09 02:37:18 -0500785 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -0400786 }
787
David Benjamina7f333d2015-02-09 02:37:18 -0500788 ScopedDH dh(DH_get_2048_256(NULL));
David Benjaminb7c5e842016-03-28 09:59:10 -0400789 if (!dh) {
790 return nullptr;
791 }
Adam Langleyc4f25ce2015-11-26 16:39:08 -0800792
793 if (config->use_sparse_dh_prime) {
794 // This prime number is 2^1024 + 643 – a value just above a power of two.
795 // Because of its form, values modulo it are essentially certain to be one
796 // byte shorter. This is used to test padding of these values.
797 if (BN_hex2bn(
798 &dh->p,
799 "1000000000000000000000000000000000000000000000000000000000000000"
800 "0000000000000000000000000000000000000000000000000000000000000000"
801 "0000000000000000000000000000000000000000000000000000000000000000"
802 "0000000000000000000000000000000000000000000000000000000000000028"
803 "3") == 0 ||
804 !BN_set_word(dh->g, 2)) {
805 return nullptr;
806 }
David Benjamine66148a2016-02-02 14:14:36 -0500807 BN_free(dh->q);
808 dh->q = NULL;
Adam Langleyc4f25ce2015-11-26 16:39:08 -0800809 dh->priv_length = 0;
810 }
811
David Benjaminb7c5e842016-03-28 09:59:10 -0400812 if (!SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
David Benjamina7f333d2015-02-09 02:37:18 -0500813 return nullptr;
David Benjaminf4e5c4e2014-08-02 17:35:45 -0400814 }
815
David Benjamin1b8b6912015-02-09 04:28:16 -0500816 if (config->async && config->is_server) {
817 // Disable the internal session cache. To test asynchronous session lookup,
818 // we use an external session cache.
819 SSL_CTX_set_session_cache_mode(
820 ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
David Benjaminc273d2c2015-02-09 12:59:46 -0500821 SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
David Benjamin1b8b6912015-02-09 04:28:16 -0500822 } else {
823 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
824 }
David Benjamin1d5c83e2014-07-22 19:20:02 -0400825
David Benjamind4c2bce2015-10-17 12:28:18 -0400826 SSL_CTX_set_select_certificate_cb(ssl_ctx.get(), SelectCertificateCallback);
David Benjamin8f2c20e2014-07-09 09:30:38 -0400827
David Benjaminacb6dcc2016-03-10 09:15:01 -0500828 if (config->use_old_client_cert_callback) {
829 SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
830 }
831
David Benjamin1f5f62b2014-07-12 16:18:02 -0400832 SSL_CTX_set_next_protos_advertised_cb(
David Benjaminc273d2c2015-02-09 12:59:46 -0500833 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400834 if (!config->select_next_proto.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500835 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
David Benjamina7f333d2015-02-09 02:37:18 -0500836 NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400837 }
838
David Benjamin594e7d22016-03-17 17:49:56 -0400839 if (!config->select_alpn.empty() || config->decline_alpn) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500840 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400841 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400842
Adam Langley49c7af12015-07-10 14:33:46 -0700843 SSL_CTX_enable_tls_channel_id(ssl_ctx.get());
David Benjaminc273d2c2015-02-09 12:59:46 -0500844 SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
David Benjamina08e49d2014-08-24 01:46:07 -0400845
David Benjamin82d0ffb2016-06-08 19:19:58 -0400846 SSL_CTX_set_current_time_cb(ssl_ctx.get(), CurrentTimeCallback);
David Benjamin377fc312015-01-26 00:22:12 -0500847
David Benjamin87e4acd2015-04-02 19:57:35 -0400848 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
David Benjaminba4594a2015-06-18 18:36:15 -0400849 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
David Benjamin87e4acd2015-04-02 19:57:35 -0400850
David Benjamind98452d2015-06-16 14:16:23 -0400851 if (config->use_ticket_callback) {
852 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
853 }
854
Adam Langley09505632015-07-30 18:10:13 -0700855 if (config->enable_client_custom_extension &&
856 !SSL_CTX_add_client_custom_ext(
857 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
858 CustomExtensionFreeCallback, kCustomExtensionAddArg,
859 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
860 return nullptr;
861 }
862
863 if (config->enable_server_custom_extension &&
864 !SSL_CTX_add_server_custom_ext(
865 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
866 CustomExtensionFreeCallback, kCustomExtensionAddArg,
867 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
868 return nullptr;
869 }
870
Paul Lietar8f1c2682015-08-18 12:21:54 +0100871 if (config->verify_fail) {
872 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
873 } else {
874 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
875 }
876
Paul Lietar4fac72e2015-09-09 13:44:55 +0100877 if (!config->signed_cert_timestamps.empty() &&
878 !SSL_CTX_set_signed_cert_timestamp_list(
879 ssl_ctx.get(), (const uint8_t *)config->signed_cert_timestamps.data(),
880 config->signed_cert_timestamps.size())) {
881 return nullptr;
882 }
883
David Benjamin2f8935d2016-07-13 19:47:39 -0400884 if (config->use_null_client_ca_list) {
885 SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
886 }
887
David Benjamin1d5c83e2014-07-22 19:20:02 -0400888 return ssl_ctx;
David Benjamin1d5c83e2014-07-22 19:20:02 -0400889}
890
David Benjamin40f101b2015-02-20 11:23:42 -0500891// RetryAsync is called after a failed operation on |ssl| with return code
892// |ret|. If the operation should be retried, it simulates one asynchronous
David Benjamin6c2563e2015-04-03 03:47:47 -0400893// event and returns true. Otherwise it returns false.
894static bool RetryAsync(SSL *ssl, int ret) {
David Benjamin43ec06f2014-08-05 02:28:57 -0400895 // No error; don't retry.
896 if (ret >= 0) {
David Benjamin40f101b2015-02-20 11:23:42 -0500897 return false;
David Benjamin025b3d32014-07-01 19:53:04 -0400898 }
David Benjamin83f90402015-01-27 01:09:43 -0500899
David Benjamin6c2563e2015-04-03 03:47:47 -0400900 TestState *test_state = GetTestState(ssl);
Matt Braithwaite6278e242016-06-14 08:18:22 -0700901 assert(GetTestConfig(ssl)->async);
David Benjamin83f90402015-01-27 01:09:43 -0500902
David Benjamin585d7a42016-06-02 14:58:00 -0400903 if (test_state->packeted_bio != nullptr &&
904 PacketedBioAdvanceClock(test_state->packeted_bio)) {
David Benjamin13e81fc2015-11-02 17:16:13 -0500905 // The DTLS retransmit logic silently ignores write failures. So the test
906 // may progress, allow writes through synchronously.
David Benjamin585d7a42016-06-02 14:58:00 -0400907 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
David Benjamin13e81fc2015-11-02 17:16:13 -0500908 int timeout_ret = DTLSv1_handle_timeout(ssl);
David Benjamin585d7a42016-06-02 14:58:00 -0400909 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
David Benjamin13e81fc2015-11-02 17:16:13 -0500910
911 if (timeout_ret < 0) {
David Benjaminc565ebb2015-04-03 04:06:36 -0400912 fprintf(stderr, "Error retransmitting.\n");
David Benjamin40f101b2015-02-20 11:23:42 -0500913 return false;
David Benjamin83f90402015-01-27 01:09:43 -0500914 }
David Benjamin40f101b2015-02-20 11:23:42 -0500915 return true;
David Benjamin83f90402015-01-27 01:09:43 -0500916 }
917
David Benjamin43ec06f2014-08-05 02:28:57 -0400918 // See if we needed to read or write more. If so, allow one byte through on
919 // the appropriate end to maximally stress the state machine.
David Benjamind9e07012015-02-09 03:04:34 -0500920 switch (SSL_get_error(ssl, ret)) {
921 case SSL_ERROR_WANT_READ:
David Benjamin6c2563e2015-04-03 03:47:47 -0400922 AsyncBioAllowRead(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -0500923 return true;
David Benjamind9e07012015-02-09 03:04:34 -0500924 case SSL_ERROR_WANT_WRITE:
David Benjamin6c2563e2015-04-03 03:47:47 -0400925 AsyncBioAllowWrite(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -0500926 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -0500927 case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400928 ScopedEVP_PKEY pkey = LoadPrivateKey(GetTestConfig(ssl)->send_channel_id);
David Benjamin9d0847a2015-02-16 03:57:55 -0500929 if (!pkey) {
David Benjamin40f101b2015-02-20 11:23:42 -0500930 return false;
David Benjamin9d0847a2015-02-16 03:57:55 -0500931 }
David Benjamin6c2563e2015-04-03 03:47:47 -0400932 test_state->channel_id = std::move(pkey);
David Benjamin40f101b2015-02-20 11:23:42 -0500933 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -0500934 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500935 case SSL_ERROR_WANT_X509_LOOKUP:
David Benjamin6c2563e2015-04-03 03:47:47 -0400936 test_state->cert_ready = true;
David Benjamin40f101b2015-02-20 11:23:42 -0500937 return true;
David Benjamin1b8b6912015-02-09 04:28:16 -0500938 case SSL_ERROR_PENDING_SESSION:
David Benjamin6c2563e2015-04-03 03:47:47 -0400939 test_state->session = std::move(test_state->pending_session);
David Benjamin40f101b2015-02-20 11:23:42 -0500940 return true;
David Benjamin6f5c0f42015-02-24 01:23:21 -0500941 case SSL_ERROR_PENDING_CERTIFICATE:
942 // The handshake will resume without a second call to the early callback.
943 return InstallCertificate(ssl);
David Benjaminb4d65fd2015-05-29 17:11:21 -0400944 case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700945 test_state->private_key_retries++;
David Benjaminb4d65fd2015-05-29 17:11:21 -0400946 return true;
David Benjamind9e07012015-02-09 03:04:34 -0500947 default:
David Benjamin40f101b2015-02-20 11:23:42 -0500948 return false;
David Benjamin025b3d32014-07-01 19:53:04 -0400949 }
David Benjamin025b3d32014-07-01 19:53:04 -0400950}
951
David Benjamin6c2563e2015-04-03 03:47:47 -0400952// DoRead reads from |ssl|, resolving any asynchronous operations. It returns
953// the result value of the final |SSL_read| call.
954static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400955 const TestConfig *config = GetTestConfig(ssl);
David Benjamin13e81fc2015-11-02 17:16:13 -0500956 TestState *test_state = GetTestState(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -0400957 int ret;
958 do {
David Benjamin13e81fc2015-11-02 17:16:13 -0500959 if (config->async) {
960 // The DTLS retransmit logic silently ignores write failures. So the test
961 // may progress, allow writes through synchronously. |SSL_read| may
962 // trigger a retransmit, so disconnect the write quota.
963 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
964 }
David Benjamin6c2563e2015-04-03 03:47:47 -0400965 ret = SSL_read(ssl, out, max_out);
David Benjamin13e81fc2015-11-02 17:16:13 -0500966 if (config->async) {
967 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
968 }
David Benjamin6c2563e2015-04-03 03:47:47 -0400969 } while (config->async && RetryAsync(ssl, ret));
970 return ret;
971}
972
973// WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
974// operations. It returns the result of the final |SSL_write| call.
975static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400976 const TestConfig *config = GetTestConfig(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -0400977 int ret;
978 do {
979 ret = SSL_write(ssl, in, in_len);
980 if (ret > 0) {
981 in += ret;
982 in_len -= ret;
983 }
984 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
985 return ret;
986}
987
David Benjamin30789da2015-08-29 22:56:45 -0400988// DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
989// returns the result of the final |SSL_shutdown| call.
990static int DoShutdown(SSL *ssl) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400991 const TestConfig *config = GetTestConfig(ssl);
David Benjamin30789da2015-08-29 22:56:45 -0400992 int ret;
993 do {
994 ret = SSL_shutdown(ssl);
995 } while (config->async && RetryAsync(ssl, ret));
996 return ret;
997}
998
David Benjamin91eab5c2015-06-18 18:35:46 -0400999// CheckHandshakeProperties checks, immediately after |ssl| completes its
1000// initial handshake (or False Starts), whether all the properties are
1001// consistent with the test configuration and invariants.
1002static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
David Benjamin7e7a82d2016-05-20 20:12:42 -04001003 const TestConfig *config = GetTestConfig(ssl);
David Benjamin91eab5c2015-06-18 18:35:46 -04001004
1005 if (SSL_get_current_cipher(ssl) == nullptr) {
1006 fprintf(stderr, "null cipher after handshake\n");
1007 return false;
1008 }
1009
1010 if (is_resume &&
1011 (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
1012 fprintf(stderr, "session was%s reused\n",
1013 SSL_session_reused(ssl) ? "" : " not");
1014 return false;
1015 }
1016
1017 bool expect_handshake_done = is_resume || !config->false_start;
1018 if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
1019 fprintf(stderr, "handshake was%s completed\n",
1020 GetTestState(ssl)->handshake_done ? "" : " not");
1021 return false;
1022 }
1023
David Benjaminba4594a2015-06-18 18:36:15 -04001024 if (expect_handshake_done && !config->is_server) {
1025 bool expect_new_session =
1026 !config->expect_no_session &&
1027 (!SSL_session_reused(ssl) || config->expect_ticket_renewal);
1028 if (expect_new_session != GetTestState(ssl)->got_new_session) {
1029 fprintf(stderr,
David Benjamindd6fed92015-10-23 17:41:12 -04001030 "new session was%s cached, but we expected the opposite\n",
David Benjaminba4594a2015-06-18 18:36:15 -04001031 GetTestState(ssl)->got_new_session ? "" : " not");
1032 return false;
1033 }
1034 }
1035
David Benjamin91eab5c2015-06-18 18:35:46 -04001036 if (config->is_server && !GetTestState(ssl)->early_callback_called) {
1037 fprintf(stderr, "early callback not called\n");
1038 return false;
1039 }
1040
1041 if (!config->expected_server_name.empty()) {
1042 const char *server_name =
1043 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1044 if (server_name != config->expected_server_name) {
1045 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
1046 server_name, config->expected_server_name.c_str());
1047 return false;
1048 }
1049 }
1050
1051 if (!config->expected_certificate_types.empty()) {
David Benjamin75910642015-08-09 10:42:33 -04001052 const uint8_t *certificate_types;
1053 size_t certificate_types_len =
David Benjamin91eab5c2015-06-18 18:35:46 -04001054 SSL_get0_certificate_types(ssl, &certificate_types);
David Benjamin75910642015-08-09 10:42:33 -04001055 if (certificate_types_len != config->expected_certificate_types.size() ||
David Benjamin91eab5c2015-06-18 18:35:46 -04001056 memcmp(certificate_types,
1057 config->expected_certificate_types.data(),
David Benjamin75910642015-08-09 10:42:33 -04001058 certificate_types_len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001059 fprintf(stderr, "certificate types mismatch\n");
1060 return false;
1061 }
1062 }
1063
1064 if (!config->expected_next_proto.empty()) {
1065 const uint8_t *next_proto;
1066 unsigned next_proto_len;
1067 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
1068 if (next_proto_len != config->expected_next_proto.size() ||
1069 memcmp(next_proto, config->expected_next_proto.data(),
1070 next_proto_len) != 0) {
1071 fprintf(stderr, "negotiated next proto mismatch\n");
1072 return false;
1073 }
1074 }
1075
1076 if (!config->expected_alpn.empty()) {
1077 const uint8_t *alpn_proto;
1078 unsigned alpn_proto_len;
1079 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
1080 if (alpn_proto_len != config->expected_alpn.size() ||
1081 memcmp(alpn_proto, config->expected_alpn.data(),
1082 alpn_proto_len) != 0) {
1083 fprintf(stderr, "negotiated alpn proto mismatch\n");
1084 return false;
1085 }
1086 }
1087
1088 if (!config->expected_channel_id.empty()) {
1089 uint8_t channel_id[64];
1090 if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
1091 fprintf(stderr, "no channel id negotiated\n");
1092 return false;
1093 }
1094 if (config->expected_channel_id.size() != 64 ||
1095 memcmp(config->expected_channel_id.data(),
1096 channel_id, 64) != 0) {
1097 fprintf(stderr, "channel id mismatch\n");
1098 return false;
1099 }
1100 }
1101
1102 if (config->expect_extended_master_secret) {
David Benjamin8ac35712016-07-13 21:07:29 -04001103 if (!SSL_get_extms_support(ssl)) {
1104 fprintf(stderr, "No EMS for connection when expected");
David Benjamin91eab5c2015-06-18 18:35:46 -04001105 return false;
1106 }
1107 }
1108
1109 if (!config->expected_ocsp_response.empty()) {
1110 const uint8_t *data;
1111 size_t len;
1112 SSL_get0_ocsp_response(ssl, &data, &len);
1113 if (config->expected_ocsp_response.size() != len ||
1114 memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
1115 fprintf(stderr, "OCSP response mismatch\n");
1116 return false;
1117 }
1118 }
1119
1120 if (!config->expected_signed_cert_timestamps.empty()) {
1121 const uint8_t *data;
1122 size_t len;
1123 SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
1124 if (config->expected_signed_cert_timestamps.size() != len ||
1125 memcmp(config->expected_signed_cert_timestamps.data(),
1126 data, len) != 0) {
1127 fprintf(stderr, "SCT list mismatch\n");
1128 return false;
1129 }
1130 }
1131
Paul Lietar8f1c2682015-08-18 12:21:54 +01001132 if (config->expect_verify_result) {
1133 int expected_verify_result = config->verify_fail ?
1134 X509_V_ERR_APPLICATION_VERIFICATION :
1135 X509_V_OK;
1136
1137 if (SSL_get_verify_result(ssl) != expected_verify_result) {
1138 fprintf(stderr, "Wrong certificate verification result\n");
1139 return false;
1140 }
1141 }
1142
Nick Harper60edffd2016-06-21 15:19:24 -07001143 if (config->expect_peer_signature_algorithm != 0 &&
1144 config->expect_peer_signature_algorithm !=
1145 SSL_get_peer_signature_algorithm(ssl)) {
1146 fprintf(stderr, "Peer signature algorithm was %04x, wanted %04x.\n",
1147 SSL_get_peer_signature_algorithm(ssl),
1148 config->expect_peer_signature_algorithm);
David Benjamin6e807652015-11-02 12:02:20 -05001149 return false;
1150 }
1151
David Benjamin9e68f192016-06-30 14:55:33 -04001152 if (config->expect_curve_id != 0) {
1153 uint16_t curve_id = SSL_get_curve_id(ssl);
1154 if (static_cast<uint16_t>(config->expect_curve_id) != curve_id) {
1155 fprintf(stderr, "curve_id was %04x, wanted %04x\n", curve_id,
1156 static_cast<uint16_t>(config->expect_curve_id));
1157 return false;
1158 }
1159 }
1160
1161 if (config->expect_dhe_group_size != 0) {
1162 unsigned dhe_group_size = SSL_get_dhe_group_size(ssl);
1163 if (static_cast<unsigned>(config->expect_dhe_group_size) !=
1164 dhe_group_size) {
1165 fprintf(stderr, "dhe_group_size was %u, wanted %d\n", dhe_group_size,
1166 config->expect_dhe_group_size);
David Benjamin4cc36ad2015-12-19 14:23:26 -05001167 return false;
1168 }
1169 }
1170
David Benjamin91eab5c2015-06-18 18:35:46 -04001171 if (!config->is_server) {
1172 /* Clients should expect a peer certificate chain iff this was not a PSK
1173 * cipher suite. */
1174 if (config->psk.empty()) {
1175 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
1176 fprintf(stderr, "Missing peer certificate chain!\n");
1177 return false;
1178 }
1179 } else if (SSL_get_peer_cert_chain(ssl) != nullptr) {
1180 fprintf(stderr, "Unexpected peer certificate chain!\n");
1181 return false;
1182 }
1183 }
1184 return true;
1185}
1186
David Benjamin87c8a642015-02-21 01:54:29 -05001187// DoExchange runs a test SSL exchange against the peer. On success, it returns
1188// true and sets |*out_session| to the negotiated SSL session. If the test is a
1189// resumption attempt, |is_resume| is true and |session| is the session from the
1190// previous exchange.
David Benjamin40f101b2015-02-20 11:23:42 -05001191static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx,
1192 const TestConfig *config, bool is_resume,
David Benjamin87c8a642015-02-21 01:54:29 -05001193 SSL_SESSION *session) {
David Benjamina7f333d2015-02-09 02:37:18 -05001194 ScopedSSL ssl(SSL_new(ssl_ctx));
1195 if (!ssl) {
David Benjamin40f101b2015-02-20 11:23:42 -05001196 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001197 }
1198
David Benjamin7e7a82d2016-05-20 20:12:42 -04001199 if (!SetTestConfig(ssl.get(), config) ||
David Benjamin2d445c02015-02-09 13:03:50 -05001200 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
David Benjamin40f101b2015-02-20 11:23:42 -05001201 return false;
Adam Langley69a01602014-11-17 17:26:55 -08001202 }
David Benjamin5a593af2014-08-11 19:51:50 -04001203
Adam Langley5f0efe02015-02-20 13:03:16 -08001204 if (config->fallback_scsv &&
1205 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
1206 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001207 }
David Benjaminacb6dcc2016-03-10 09:15:01 -05001208 if (!config->use_early_callback && !config->use_old_client_cert_callback) {
David Benjamin6f5c0f42015-02-24 01:23:21 -05001209 if (config->async) {
David Benjamin6f5c0f42015-02-24 01:23:21 -05001210 SSL_set_cert_cb(ssl.get(), CertCallback, NULL);
1211 } else if (!InstallCertificate(ssl.get())) {
1212 return false;
1213 }
David Benjamin5a593af2014-08-11 19:51:50 -04001214 }
1215 if (config->require_any_client_certificate) {
David Benjamina7f333d2015-02-09 02:37:18 -05001216 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
Paul Lietar8f1c2682015-08-18 12:21:54 +01001217 NULL);
1218 }
1219 if (config->verify_peer) {
1220 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
David Benjamin5a593af2014-08-11 19:51:50 -04001221 }
1222 if (config->false_start) {
David Benjamined7c4752015-02-16 19:16:46 -05001223 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
David Benjamin5a593af2014-08-11 19:51:50 -04001224 }
1225 if (config->cbc_record_splitting) {
David Benjamina7f333d2015-02-09 02:37:18 -05001226 SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
David Benjamin5a593af2014-08-11 19:51:50 -04001227 }
1228 if (config->partial_write) {
David Benjamina7f333d2015-02-09 02:37:18 -05001229 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
David Benjamin5a593af2014-08-11 19:51:50 -04001230 }
Steven Valdez4f94b1c2016-05-24 12:31:07 -04001231 if (config->no_tls13) {
1232 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
1233 }
David Benjamin5a593af2014-08-11 19:51:50 -04001234 if (config->no_tls12) {
David Benjamina7f333d2015-02-09 02:37:18 -05001235 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
David Benjamin5a593af2014-08-11 19:51:50 -04001236 }
1237 if (config->no_tls11) {
David Benjamina7f333d2015-02-09 02:37:18 -05001238 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
David Benjamin5a593af2014-08-11 19:51:50 -04001239 }
1240 if (config->no_tls1) {
David Benjamina7f333d2015-02-09 02:37:18 -05001241 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
David Benjamin5a593af2014-08-11 19:51:50 -04001242 }
1243 if (config->no_ssl3) {
David Benjamina7f333d2015-02-09 02:37:18 -05001244 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
David Benjamin5a593af2014-08-11 19:51:50 -04001245 }
David Benjamina08e49d2014-08-24 01:46:07 -04001246 if (!config->expected_channel_id.empty()) {
David Benjamina7f333d2015-02-09 02:37:18 -05001247 SSL_enable_tls_channel_id(ssl.get());
David Benjamina08e49d2014-08-24 01:46:07 -04001248 }
1249 if (!config->send_channel_id.empty()) {
David Benjamina7f333d2015-02-09 02:37:18 -05001250 SSL_enable_tls_channel_id(ssl.get());
David Benjamind9e07012015-02-09 03:04:34 -05001251 if (!config->async) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001252 // The async case will be supplied by |ChannelIdCallback|.
David Benjamind9e07012015-02-09 03:04:34 -05001253 ScopedEVP_PKEY pkey = LoadPrivateKey(config->send_channel_id);
1254 if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001255 return false;
David Benjamind9e07012015-02-09 03:04:34 -05001256 }
David Benjamina08e49d2014-08-24 01:46:07 -04001257 }
David Benjamina08e49d2014-08-24 01:46:07 -04001258 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001259 if (!config->host_name.empty() &&
1260 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001261 return false;
David Benjamine78bfde2014-09-06 12:45:15 -04001262 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001263 if (!config->advertise_alpn.empty() &&
1264 SSL_set_alpn_protos(ssl.get(),
1265 (const uint8_t *)config->advertise_alpn.data(),
1266 config->advertise_alpn.size()) != 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001267 return false;
David Benjaminae2888f2014-09-06 12:58:58 -04001268 }
David Benjamin48cae082014-10-27 01:06:24 -04001269 if (!config->psk.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001270 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
1271 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
David Benjamin48cae082014-10-27 01:06:24 -04001272 }
David Benjamin61f95272014-11-25 01:55:35 -05001273 if (!config->psk_identity.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001274 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001275 return false;
David Benjamin48cae082014-10-27 01:06:24 -04001276 }
David Benjamin61f95272014-11-25 01:55:35 -05001277 if (!config->srtp_profiles.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001278 !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001279 return false;
David Benjamin61f95272014-11-25 01:55:35 -05001280 }
1281 if (config->enable_ocsp_stapling &&
David Benjamina7f333d2015-02-09 02:37:18 -05001282 !SSL_enable_ocsp_stapling(ssl.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001283 return false;
David Benjamin61f95272014-11-25 01:55:35 -05001284 }
1285 if (config->enable_signed_cert_timestamps &&
David Benjamina7f333d2015-02-09 02:37:18 -05001286 !SSL_enable_signed_cert_timestamps(ssl.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001287 return false;
David Benjaminca6c8262014-11-15 19:06:08 -05001288 }
David Benjamin1eb367c2014-12-12 18:17:51 -05001289 if (config->min_version != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001290 SSL_set_min_version(ssl.get(), (uint16_t)config->min_version);
David Benjamin1eb367c2014-12-12 18:17:51 -05001291 }
1292 if (config->max_version != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001293 SSL_set_max_version(ssl.get(), (uint16_t)config->max_version);
David Benjamin1eb367c2014-12-12 18:17:51 -05001294 }
David Benjamin13be1de2015-01-11 16:29:36 -05001295 if (config->mtu != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001296 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
1297 SSL_set_mtu(ssl.get(), config->mtu);
David Benjamin13be1de2015-01-11 16:29:36 -05001298 }
Adam Langley524e7172015-02-20 16:04:00 -08001299 if (config->install_ddos_callback) {
1300 SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
1301 }
David Benjamin1d5ef3b2015-10-12 19:54:18 -04001302 if (config->renegotiate_once) {
1303 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_once);
1304 }
1305 if (config->renegotiate_freely) {
1306 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
David Benjaminb16346b2015-04-08 19:16:58 -04001307 }
Adam Langley27a0d082015-11-03 13:34:10 -08001308 if (config->renegotiate_ignore) {
1309 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_ignore);
1310 }
David Benjamin30789da2015-08-29 22:56:45 -04001311 if (!config->check_close_notify) {
1312 SSL_set_quiet_shutdown(ssl.get(), 1);
1313 }
David Benjamin091c4b92015-10-26 13:33:21 -04001314 if (config->disable_npn) {
1315 SSL_set_options(ssl.get(), SSL_OP_DISABLE_NPN);
1316 }
David Benjamin99fdfb92015-11-02 12:11:35 -05001317 if (config->p384_only) {
1318 int nid = NID_secp384r1;
1319 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
1320 return false;
1321 }
1322 }
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001323 if (config->enable_all_curves) {
1324 static const int kAllCurves[] = {
Matt Braithwaite053931e2016-05-25 12:06:05 -07001325 NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_X25519,
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001326 };
1327 if (!SSL_set1_curves(ssl.get(), kAllCurves,
1328 sizeof(kAllCurves) / sizeof(kAllCurves[0]))) {
1329 return false;
1330 }
1331 }
Taylor Brandstetter376a0fe2016-05-10 19:30:28 -07001332 if (config->initial_timeout_duration_ms > 0) {
1333 DTLSv1_set_initial_timeout_duration(ssl.get(),
1334 config->initial_timeout_duration_ms);
1335 }
David Benjamin025b3d32014-07-01 19:53:04 -04001336
David Benjamin87c8a642015-02-21 01:54:29 -05001337 int sock = Connect(config->port);
1338 if (sock == -1) {
1339 return false;
1340 }
1341 SocketCloser closer(sock);
1342
1343 ScopedBIO bio(BIO_new_socket(sock, BIO_NOCLOSE));
David Benjamina7f333d2015-02-09 02:37:18 -05001344 if (!bio) {
David Benjamin40f101b2015-02-20 11:23:42 -05001345 return false;
David Benjamin43ec06f2014-08-05 02:28:57 -04001346 }
David Benjamin6fd297b2014-08-11 18:43:38 -04001347 if (config->is_dtls) {
David Benjamin585d7a42016-06-02 14:58:00 -04001348 ScopedBIO packeted = PacketedBioCreate(!config->async);
David Benjaminb7c5e842016-03-28 09:59:10 -04001349 if (!packeted) {
1350 return false;
1351 }
David Benjamin585d7a42016-06-02 14:58:00 -04001352 GetTestState(ssl.get())->packeted_bio = packeted.get();
David Benjamina7f333d2015-02-09 02:37:18 -05001353 BIO_push(packeted.get(), bio.release());
1354 bio = std::move(packeted);
David Benjamin6fd297b2014-08-11 18:43:38 -04001355 }
David Benjamin5a593af2014-08-11 19:51:50 -04001356 if (config->async) {
David Benjamina7f333d2015-02-09 02:37:18 -05001357 ScopedBIO async_scoped =
David Benjaminc273d2c2015-02-09 12:59:46 -05001358 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
David Benjaminb7c5e842016-03-28 09:59:10 -04001359 if (!async_scoped) {
1360 return false;
1361 }
David Benjamina7f333d2015-02-09 02:37:18 -05001362 BIO_push(async_scoped.get(), bio.release());
David Benjamin6c2563e2015-04-03 03:47:47 -04001363 GetTestState(ssl.get())->async_bio = async_scoped.get();
David Benjamina7f333d2015-02-09 02:37:18 -05001364 bio = std::move(async_scoped);
David Benjamin43ec06f2014-08-05 02:28:57 -04001365 }
David Benjamina7f333d2015-02-09 02:37:18 -05001366 SSL_set_bio(ssl.get(), bio.get(), bio.get());
1367 bio.release(); // SSL_set_bio takes ownership.
David Benjamin43ec06f2014-08-05 02:28:57 -04001368
David Benjamin1d5c83e2014-07-22 19:20:02 -04001369 if (session != NULL) {
David Benjamin1b8b6912015-02-09 04:28:16 -05001370 if (!config->is_server) {
1371 if (SSL_set_session(ssl.get(), session) != 1) {
David Benjamin40f101b2015-02-20 11:23:42 -05001372 return false;
David Benjamin1b8b6912015-02-09 04:28:16 -05001373 }
1374 } else if (config->async) {
1375 // The internal session cache is disabled, so install the session
1376 // manually.
David Benjamin2d445c02015-02-09 13:03:50 -05001377 GetTestState(ssl.get())->pending_session.reset(
David Benjamin1b8b6912015-02-09 04:28:16 -05001378 SSL_SESSION_up_ref(session));
David Benjamin1d5c83e2014-07-22 19:20:02 -04001379 }
1380 }
1381
David Benjamina07c0fc2015-05-13 13:19:42 -04001382 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1383 fprintf(stderr, "non-null cipher before handshake\n");
1384 return false;
1385 }
1386
David Benjamin1d5c83e2014-07-22 19:20:02 -04001387 int ret;
David Benjamine0e7d0d2015-02-08 19:33:25 -05001388 if (config->implicit_handshake) {
David Benjamin5a593af2014-08-11 19:51:50 -04001389 if (config->is_server) {
David Benjamina7f333d2015-02-09 02:37:18 -05001390 SSL_set_accept_state(ssl.get());
David Benjamin43ec06f2014-08-05 02:28:57 -04001391 } else {
David Benjamina7f333d2015-02-09 02:37:18 -05001392 SSL_set_connect_state(ssl.get());
David Benjamin43ec06f2014-08-05 02:28:57 -04001393 }
David Benjamine0e7d0d2015-02-08 19:33:25 -05001394 } else {
1395 do {
1396 if (config->is_server) {
David Benjamina7f333d2015-02-09 02:37:18 -05001397 ret = SSL_accept(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -05001398 } else {
David Benjamina7f333d2015-02-09 02:37:18 -05001399 ret = SSL_connect(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -05001400 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001401 } while (config->async && RetryAsync(ssl.get(), ret));
David Benjamin91eab5c2015-06-18 18:35:46 -04001402 if (ret != 1 ||
1403 !CheckHandshakeProperties(ssl.get(), is_resume)) {
David Benjamin40f101b2015-02-20 11:23:42 -05001404 return false;
David Benjamine0e7d0d2015-02-08 19:33:25 -05001405 }
David Benjamin025b3d32014-07-01 19:53:04 -04001406
David Benjaminba4594a2015-06-18 18:36:15 -04001407 // Reset the state to assert later that the callback isn't called in
1408 // renegotations.
1409 GetTestState(ssl.get())->got_new_session = false;
David Benjamin61f95272014-11-25 01:55:35 -05001410 }
1411
David Benjaminc565ebb2015-04-03 04:06:36 -04001412 if (config->export_keying_material > 0) {
1413 std::vector<uint8_t> result(
1414 static_cast<size_t>(config->export_keying_material));
1415 if (!SSL_export_keying_material(
1416 ssl.get(), result.data(), result.size(),
1417 config->export_label.data(), config->export_label.size(),
1418 reinterpret_cast<const uint8_t*>(config->export_context.data()),
1419 config->export_context.size(), config->use_export_context)) {
1420 fprintf(stderr, "failed to export keying material\n");
1421 return false;
1422 }
1423 if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1424 return false;
1425 }
1426 }
1427
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001428 if (config->tls_unique) {
1429 uint8_t tls_unique[16];
1430 size_t tls_unique_len;
1431 if (!SSL_get_tls_unique(ssl.get(), tls_unique, &tls_unique_len,
1432 sizeof(tls_unique))) {
1433 fprintf(stderr, "failed to get tls-unique\n");
1434 return false;
1435 }
1436
1437 if (tls_unique_len != 12) {
1438 fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
1439 static_cast<unsigned>(tls_unique_len));
1440 return false;
1441 }
1442
1443 if (WriteAll(ssl.get(), tls_unique, tls_unique_len) < 0) {
1444 return false;
1445 }
1446 }
1447
David Benjamin5a593af2014-08-11 19:51:50 -04001448 if (config->write_different_record_sizes) {
David Benjamin6fd297b2014-08-11 18:43:38 -04001449 if (config->is_dtls) {
1450 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001451 return false;
David Benjamin6fd297b2014-08-11 18:43:38 -04001452 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001453 // This mode writes a number of different record sizes in an attempt to
1454 // trip up the CBC record splitting code.
Adam Langleybc949292015-06-18 21:32:44 -07001455 static const size_t kBufLen = 32769;
1456 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1457 memset(buf.get(), 0x42, kBufLen);
Kenny Root7fdeaf12014-08-05 15:23:37 -07001458 static const size_t kRecordSizes[] = {
1459 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
1460 for (size_t i = 0; i < sizeof(kRecordSizes) / sizeof(kRecordSizes[0]);
1461 i++) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07001462 const size_t len = kRecordSizes[i];
Adam Langleybc949292015-06-18 21:32:44 -07001463 if (len > kBufLen) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07001464 fprintf(stderr, "Bad kRecordSizes value.\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001465 return false;
Kenny Root7fdeaf12014-08-05 15:23:37 -07001466 }
Adam Langleybc949292015-06-18 21:32:44 -07001467 if (WriteAll(ssl.get(), buf.get(), len) < 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001468 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001469 }
1470 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001471 } else {
David Benjamine58c4f52014-08-24 03:47:07 -04001472 if (config->shim_writes_first) {
David Benjamin6c2563e2015-04-03 03:47:47 -04001473 if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1474 5) < 0) {
1475 return false;
1476 }
David Benjamine58c4f52014-08-24 03:47:07 -04001477 }
David Benjamin30789da2015-08-29 22:56:45 -04001478 if (!config->shim_shuts_down) {
1479 for (;;) {
Adam Langleya0a8dc22015-09-09 10:22:00 -07001480 static const size_t kBufLen = 16384;
1481 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1482
David Benjamin2c99d282015-09-01 10:23:00 -04001483 // Read only 512 bytes at a time in TLS to ensure records may be
1484 // returned in multiple reads.
Adam Langleya0a8dc22015-09-09 10:22:00 -07001485 int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
David Benjamin30789da2015-08-29 22:56:45 -04001486 int err = SSL_get_error(ssl.get(), n);
1487 if (err == SSL_ERROR_ZERO_RETURN ||
1488 (n == 0 && err == SSL_ERROR_SYSCALL)) {
1489 if (n != 0) {
1490 fprintf(stderr, "Invalid SSL_get_error output\n");
1491 return false;
1492 }
1493 // Stop on either clean or unclean shutdown.
1494 break;
1495 } else if (err != SSL_ERROR_NONE) {
1496 if (n > 0) {
1497 fprintf(stderr, "Invalid SSL_get_error output\n");
1498 return false;
1499 }
1500 return false;
1501 }
1502 // Successfully read data.
1503 if (n <= 0) {
David Benjamin9a38e922015-01-22 16:06:11 -05001504 fprintf(stderr, "Invalid SSL_get_error output\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001505 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001506 }
David Benjamin30789da2015-08-29 22:56:45 -04001507
1508 // After a successful read, with or without False Start, the handshake
1509 // must be complete.
1510 if (!GetTestState(ssl.get())->handshake_done) {
1511 fprintf(stderr, "handshake was not completed after SSL_read\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001512 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001513 }
David Benjamin87e4acd2015-04-02 19:57:35 -04001514
David Benjamin30789da2015-08-29 22:56:45 -04001515 for (int i = 0; i < n; i++) {
1516 buf[i] ^= 0xff;
1517 }
Adam Langleya0a8dc22015-09-09 10:22:00 -07001518 if (WriteAll(ssl.get(), buf.get(), n) < 0) {
David Benjamin30789da2015-08-29 22:56:45 -04001519 return false;
1520 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001521 }
1522 }
David Benjamin025b3d32014-07-01 19:53:04 -04001523 }
1524
David Benjaminba4594a2015-06-18 18:36:15 -04001525 if (!config->is_server && !config->false_start &&
1526 !config->implicit_handshake &&
1527 GetTestState(ssl.get())->got_new_session) {
1528 fprintf(stderr, "new session was established after the handshake\n");
1529 return false;
1530 }
1531
David Benjamin1d5c83e2014-07-22 19:20:02 -04001532 if (out_session) {
David Benjamina7f333d2015-02-09 02:37:18 -05001533 out_session->reset(SSL_get1_session(ssl.get()));
David Benjamin1d5c83e2014-07-22 19:20:02 -04001534 }
1535
David Benjamin30789da2015-08-29 22:56:45 -04001536 ret = DoShutdown(ssl.get());
1537
1538 if (config->shim_shuts_down && config->check_close_notify) {
1539 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1540 // it returns zero when our close_notify is sent, then one when the peer's
1541 // is received.
1542 if (ret != 0) {
1543 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1544 return false;
1545 }
1546 ret = DoShutdown(ssl.get());
1547 }
1548
1549 if (ret != 1) {
1550 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1551 return false;
1552 }
1553
David Benjamin324dce42015-10-12 19:49:00 -04001554 if (SSL_total_renegotiations(ssl.get()) !=
1555 config->expect_total_renegotiations) {
1556 fprintf(stderr, "Expected %d renegotiations, got %d\n",
1557 config->expect_total_renegotiations,
1558 SSL_total_renegotiations(ssl.get()));
1559 return false;
1560 }
1561
David Benjamin40f101b2015-02-20 11:23:42 -05001562 return true;
David Benjamin025b3d32014-07-01 19:53:04 -04001563}
David Benjamin1d5c83e2014-07-22 19:20:02 -04001564
David Benjaminff3a1492016-03-02 10:12:06 -05001565class StderrDelimiter {
1566 public:
1567 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
1568};
1569
Adam Langley10f97f32016-07-12 08:09:33 -07001570int main(int argc, char **argv) {
David Benjaminff3a1492016-03-02 10:12:06 -05001571 // To distinguish ASan's output from ours, add a trailing message to stderr.
1572 // Anything following this line will be considered an error.
1573 StderrDelimiter delimiter;
1574
David Benjamin87c8a642015-02-21 01:54:29 -05001575#if defined(OPENSSL_WINDOWS)
1576 /* Initialize Winsock. */
1577 WORD wsa_version = MAKEWORD(2, 2);
1578 WSADATA wsa_data;
1579 int wsa_err = WSAStartup(wsa_version, &wsa_data);
1580 if (wsa_err != 0) {
1581 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1582 return 1;
1583 }
1584 if (wsa_data.wVersion != wsa_version) {
1585 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1586 return 1;
1587 }
1588#else
David Benjamin1d5c83e2014-07-22 19:20:02 -04001589 signal(SIGPIPE, SIG_IGN);
Adam Langleyded93582014-07-31 15:23:51 -07001590#endif
David Benjamin1d5c83e2014-07-22 19:20:02 -04001591
David Benjamin7a1eefd2015-10-17 23:39:22 -04001592 CRYPTO_library_init();
David Benjamind9e07012015-02-09 03:04:34 -05001593 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
David Benjamin2d445c02015-02-09 13:03:50 -05001594 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
David Benjamin6c2563e2015-04-03 03:47:47 -04001595 if (g_config_index < 0 || g_state_index < 0) {
David Benjaminae3e4872014-11-18 21:52:26 -05001596 return 1;
1597 }
David Benjamin5a593af2014-08-11 19:51:50 -04001598
1599 TestConfig config;
1600 if (!ParseConfig(argc - 1, argv + 1, &config)) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001601 return Usage(argv[0]);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001602 }
1603
David Benjaminc273d2c2015-02-09 12:59:46 -05001604 ScopedSSL_CTX ssl_ctx = SetupCtx(&config);
David Benjamina7f333d2015-02-09 02:37:18 -05001605 if (!ssl_ctx) {
Brian Smith83a82982015-04-09 16:21:10 -10001606 ERR_print_errors_fp(stderr);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001607 return 1;
1608 }
1609
David Benjamina7f333d2015-02-09 02:37:18 -05001610 ScopedSSL_SESSION session;
David Benjamin40f101b2015-02-20 11:23:42 -05001611 if (!DoExchange(&session, ssl_ctx.get(), &config, false /* is_resume */,
David Benjamin87c8a642015-02-21 01:54:29 -05001612 NULL /* session */)) {
Brian Smith83a82982015-04-09 16:21:10 -10001613 ERR_print_errors_fp(stderr);
David Benjamin40f101b2015-02-20 11:23:42 -05001614 return 1;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001615 }
1616
David Benjamin40f101b2015-02-20 11:23:42 -05001617 if (config.resume &&
1618 !DoExchange(NULL, ssl_ctx.get(), &config, true /* is_resume */,
David Benjamin87c8a642015-02-21 01:54:29 -05001619 session.get())) {
Brian Smith83a82982015-04-09 16:21:10 -10001620 ERR_print_errors_fp(stderr);
David Benjamin40f101b2015-02-20 11:23:42 -05001621 return 1;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001622 }
1623
David Benjamina7f333d2015-02-09 02:37:18 -05001624 return 0;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001625}