blob: 22ce8892b82c203f873ea844027c2276878da5c2 [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
Adam Langleyded93582014-07-31 15:23:51 -070015#include <openssl/base.h>
16
17#if !defined(OPENSSL_WINDOWS)
David Benjamin025b3d32014-07-01 19:53:04 -040018#include <arpa/inet.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040019#include <netinet/in.h>
David Benjamin87c8a642015-02-21 01:54:29 -050020#include <netinet/tcp.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040021#include <signal.h>
22#include <sys/socket.h>
David Benjamin4d2e7ce2015-05-08 13:29:45 -040023#include <sys/types.h>
David Benjamin8f2c20e2014-07-09 09:30:38 -040024#include <unistd.h>
David Benjamin87c8a642015-02-21 01:54:29 -050025#else
26#include <io.h>
27#pragma warning(push, 3)
Adam Langley3e719312015-03-20 16:32:23 -070028#include <winsock2.h>
29#include <ws2tcpip.h>
David Benjamin87c8a642015-02-21 01:54:29 -050030#pragma warning(pop)
31
32#pragma comment(lib, "Ws2_32.lib")
Adam Langleyded93582014-07-31 15:23:51 -070033#endif
34
Adam Langley2b2d66d2015-01-30 17:08:37 -080035#include <string.h>
Adam Langleyded93582014-07-31 15:23:51 -070036#include <sys/types.h>
David Benjamin025b3d32014-07-01 19:53:04 -040037
David Benjamin025b3d32014-07-01 19:53:04 -040038#include <openssl/bio.h>
David Benjamin48cae082014-10-27 01:06:24 -040039#include <openssl/buf.h>
David Benjamin8f2c20e2014-07-09 09:30:38 -040040#include <openssl/bytestring.h>
David Benjamind98452d2015-06-16 14:16:23 -040041#include <openssl/cipher.h>
David Benjamin7a1eefd2015-10-17 23:39:22 -040042#include <openssl/crypto.h>
Brian Smith83a82982015-04-09 16:21:10 -100043#include <openssl/err.h>
David Benjamind98452d2015-06-16 14:16:23 -040044#include <openssl/hmac.h>
David Benjamin99fdfb92015-11-02 12:11:35 -050045#include <openssl/obj.h>
David Benjamind98452d2015-06-16 14:16:23 -040046#include <openssl/rand.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040047#include <openssl/ssl.h>
48
David Benjamin45fb1be2015-03-22 16:31:27 -040049#include <memory>
Steven Valdez0d62f262015-09-04 12:41:04 -040050#include <string>
David Benjaminc565ebb2015-04-03 04:06:36 -040051#include <vector>
David Benjamin45fb1be2015-03-22 16:31:27 -040052
53#include "../../crypto/test/scoped_types.h"
David Benjamin43ec06f2014-08-05 02:28:57 -040054#include "async_bio.h"
David Benjamin6fd297b2014-08-11 18:43:38 -040055#include "packeted_bio.h"
David Benjamina7f333d2015-02-09 02:37:18 -050056#include "scoped_types.h"
David Benjamin5a593af2014-08-11 19:51:50 -040057#include "test_config.h"
David Benjamin43ec06f2014-08-05 02:28:57 -040058
David Benjamin87c8a642015-02-21 01:54:29 -050059
60#if !defined(OPENSSL_WINDOWS)
61static int closesocket(int sock) {
62 return close(sock);
63}
64
65static void PrintSocketError(const char *func) {
66 perror(func);
67}
68#else
69static void PrintSocketError(const char *func) {
70 fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
71}
72#endif
73
David Benjaminc273d2c2015-02-09 12:59:46 -050074static int Usage(const char *program) {
David Benjamina7f333d2015-02-09 02:37:18 -050075 fprintf(stderr, "Usage: %s [flags...]\n", program);
David Benjamin1d5c83e2014-07-22 19:20:02 -040076 return 1;
77}
David Benjamin025b3d32014-07-01 19:53:04 -040078
David Benjamin2d445c02015-02-09 13:03:50 -050079struct TestState {
David Benjaminff9c74f2015-04-06 20:17:56 -040080 TestState() {
81 // MSVC cannot initialize these inline.
82 memset(&clock, 0, sizeof(clock));
83 memset(&clock_delta, 0, sizeof(clock_delta));
84 }
85
David Benjamin6c2563e2015-04-03 03:47:47 -040086 // async_bio is async BIO which pauses reads and writes.
87 BIO *async_bio = nullptr;
88 // clock is the current time for the SSL connection.
David Benjamin4d2e7ce2015-05-08 13:29:45 -040089 timeval clock;
David Benjamin6c2563e2015-04-03 03:47:47 -040090 // clock_delta is how far the clock advanced in the most recent failed
91 // |BIO_read|.
David Benjamin4d2e7ce2015-05-08 13:29:45 -040092 timeval clock_delta;
David Benjamind9e07012015-02-09 03:04:34 -050093 ScopedEVP_PKEY channel_id;
David Benjamin0d4db502015-03-23 18:46:05 -040094 bool cert_ready = false;
David Benjamin1b8b6912015-02-09 04:28:16 -050095 ScopedSSL_SESSION session;
96 ScopedSSL_SESSION pending_session;
David Benjamin0d4db502015-03-23 18:46:05 -040097 bool early_callback_called = false;
David Benjamin87e4acd2015-04-02 19:57:35 -040098 bool handshake_done = false;
David Benjaminb4d65fd2015-05-29 17:11:21 -040099 // private_key is the underlying private key used when testing custom keys.
100 ScopedEVP_PKEY private_key;
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700101 std::vector<uint8_t> private_key_result;
102 // private_key_retries is the number of times an asynchronous private key
103 // operation has been retried.
104 unsigned private_key_retries = 0;
David Benjaminba4594a2015-06-18 18:36:15 -0400105 bool got_new_session = false;
David Benjamind9e07012015-02-09 03:04:34 -0500106};
107
David Benjamin2d445c02015-02-09 13:03:50 -0500108static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
Adam Langley09505632015-07-30 18:10:13 -0700109 int index, long argl, void *argp) {
David Benjamin2d445c02015-02-09 13:03:50 -0500110 delete ((TestState *)ptr);
David Benjamind9e07012015-02-09 03:04:34 -0500111}
112
113static int g_config_index = 0;
David Benjamin2d445c02015-02-09 13:03:50 -0500114static int g_state_index = 0;
David Benjamin5a593af2014-08-11 19:51:50 -0400115
Adam Langley69a01602014-11-17 17:26:55 -0800116static bool SetConfigPtr(SSL *ssl, const TestConfig *config) {
David Benjamind9e07012015-02-09 03:04:34 -0500117 return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
David Benjamin5a593af2014-08-11 19:51:50 -0400118}
119
David Benjamin87e4acd2015-04-02 19:57:35 -0400120static const TestConfig *GetConfigPtr(const SSL *ssl) {
David Benjamind9e07012015-02-09 03:04:34 -0500121 return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
David Benjamin5a593af2014-08-11 19:51:50 -0400122}
123
David Benjamin2d445c02015-02-09 13:03:50 -0500124static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> async) {
125 if (SSL_set_ex_data(ssl, g_state_index, (void *)async.get()) == 1) {
David Benjamind9e07012015-02-09 03:04:34 -0500126 async.release();
127 return true;
128 }
129 return false;
130}
131
David Benjamin87e4acd2015-04-02 19:57:35 -0400132static TestState *GetTestState(const SSL *ssl) {
David Benjamin2d445c02015-02-09 13:03:50 -0500133 return (TestState *)SSL_get_ex_data(ssl, g_state_index);
David Benjamin83f90402015-01-27 01:09:43 -0500134}
135
David Benjamina7f333d2015-02-09 02:37:18 -0500136static ScopedEVP_PKEY LoadPrivateKey(const std::string &file) {
137 ScopedBIO bio(BIO_new(BIO_s_file()));
138 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
139 return nullptr;
David Benjamina08e49d2014-08-24 01:46:07 -0400140 }
David Benjamina7f333d2015-02-09 02:37:18 -0500141 ScopedEVP_PKEY pkey(PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
David Benjamina08e49d2014-08-24 01:46:07 -0400142 return pkey;
143}
144
David Benjaminb4d65fd2015-05-29 17:11:21 -0400145static int AsyncPrivateKeyType(SSL *ssl) {
146 return EVP_PKEY_id(GetTestState(ssl)->private_key.get());
147}
148
David Benjaminb4d65fd2015-05-29 17:11:21 -0400149static size_t AsyncPrivateKeyMaxSignatureLen(SSL *ssl) {
150 return EVP_PKEY_size(GetTestState(ssl)->private_key.get());
151}
152
153static ssl_private_key_result_t AsyncPrivateKeySign(
154 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
155 const EVP_MD *md, const uint8_t *in, size_t in_len) {
156 TestState *test_state = GetTestState(ssl);
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700157 if (!test_state->private_key_result.empty()) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400158 fprintf(stderr, "AsyncPrivateKeySign called with operation pending.\n");
159 abort();
160 }
161
162 ScopedEVP_PKEY_CTX ctx(EVP_PKEY_CTX_new(test_state->private_key.get(),
163 nullptr));
164 if (!ctx) {
165 return ssl_private_key_failure;
166 }
167
168 // Write the signature into |test_state|.
169 size_t len = 0;
170 if (!EVP_PKEY_sign_init(ctx.get()) ||
171 !EVP_PKEY_CTX_set_signature_md(ctx.get(), md) ||
172 !EVP_PKEY_sign(ctx.get(), nullptr, &len, in, in_len)) {
173 return ssl_private_key_failure;
174 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700175 test_state->private_key_result.resize(len);
David Benjaminef14b2d2015-11-11 14:01:27 -0800176 if (!EVP_PKEY_sign(ctx.get(), test_state->private_key_result.data(), &len, in,
177 in_len)) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400178 return ssl_private_key_failure;
179 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700180 test_state->private_key_result.resize(len);
David Benjaminb4d65fd2015-05-29 17:11:21 -0400181
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700182 // The signature will be released asynchronously in
183 // |AsyncPrivateKeySignComplete|.
David Benjaminb4d65fd2015-05-29 17:11:21 -0400184 return ssl_private_key_retry;
185}
186
187static ssl_private_key_result_t AsyncPrivateKeySignComplete(
188 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
189 TestState *test_state = GetTestState(ssl);
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700190 if (test_state->private_key_result.empty()) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400191 fprintf(stderr,
192 "AsyncPrivateKeySignComplete called without operation pending.\n");
193 abort();
194 }
195
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700196 if (test_state->private_key_retries < 2) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400197 // Only return the signature on the second attempt, to test both incomplete
198 // |sign| and |sign_complete|.
199 return ssl_private_key_retry;
200 }
201
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700202 if (max_out < test_state->private_key_result.size()) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400203 fprintf(stderr, "Output buffer too small.\n");
204 return ssl_private_key_failure;
205 }
David Benjaminef14b2d2015-11-11 14:01:27 -0800206 memcpy(out, test_state->private_key_result.data(),
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700207 test_state->private_key_result.size());
208 *out_len = test_state->private_key_result.size();
David Benjaminb4d65fd2015-05-29 17:11:21 -0400209
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700210 test_state->private_key_result.clear();
211 test_state->private_key_retries = 0;
212 return ssl_private_key_success;
213}
214
215static ssl_private_key_result_t AsyncPrivateKeyDecrypt(
216 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
217 const uint8_t *in, size_t in_len) {
218 TestState *test_state = GetTestState(ssl);
219 if (!test_state->private_key_result.empty()) {
220 fprintf(stderr,
221 "AsyncPrivateKeyDecrypt called with operation pending.\n");
222 abort();
223 }
224
225 EVP_PKEY *pkey = test_state->private_key.get();
226 if (pkey->type != EVP_PKEY_RSA || pkey->pkey.rsa == NULL) {
227 fprintf(stderr,
228 "AsyncPrivateKeyDecrypt called with incorrect key type.\n");
229 abort();
230 }
231 RSA *rsa = pkey->pkey.rsa;
232 test_state->private_key_result.resize(RSA_size(rsa));
David Benjaminef14b2d2015-11-11 14:01:27 -0800233 if (!RSA_decrypt(rsa, out_len, test_state->private_key_result.data(),
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700234 RSA_size(rsa), in, in_len, RSA_NO_PADDING)) {
235 return ssl_private_key_failure;
236 }
237
238 test_state->private_key_result.resize(*out_len);
239
240 // The decryption will be released asynchronously in
241 // |AsyncPrivateKeyDecryptComplete|.
242 return ssl_private_key_retry;
243}
244
245static ssl_private_key_result_t AsyncPrivateKeyDecryptComplete(
246 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
247 TestState *test_state = GetTestState(ssl);
248 if (test_state->private_key_result.empty()) {
249 fprintf(stderr,
250 "AsyncPrivateKeyDecryptComplete called without operation "
251 "pending.\n");
252 abort();
253 }
254
255 if (test_state->private_key_retries < 2) {
256 // Only return the decryption on the second attempt, to test both incomplete
257 // |decrypt| and |decrypt_complete|.
258 return ssl_private_key_retry;
259 }
260
261 if (max_out < test_state->private_key_result.size()) {
262 fprintf(stderr, "Output buffer too small.\n");
263 return ssl_private_key_failure;
264 }
David Benjaminef14b2d2015-11-11 14:01:27 -0800265 memcpy(out, test_state->private_key_result.data(),
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700266 test_state->private_key_result.size());
267 *out_len = test_state->private_key_result.size();
268
269 test_state->private_key_result.clear();
270 test_state->private_key_retries = 0;
David Benjaminb4d65fd2015-05-29 17:11:21 -0400271 return ssl_private_key_success;
272}
273
274static const SSL_PRIVATE_KEY_METHOD g_async_private_key_method = {
275 AsyncPrivateKeyType,
David Benjaminb4d65fd2015-05-29 17:11:21 -0400276 AsyncPrivateKeyMaxSignatureLen,
277 AsyncPrivateKeySign,
278 AsyncPrivateKeySignComplete,
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700279 AsyncPrivateKeyDecrypt,
280 AsyncPrivateKeyDecryptComplete
David Benjaminb4d65fd2015-05-29 17:11:21 -0400281};
282
Steven Valdez0d62f262015-09-04 12:41:04 -0400283template<typename T>
284struct Free {
285 void operator()(T *buf) {
286 free(buf);
287 }
288};
289
David Benjamin41fdbcd2015-02-09 03:13:35 -0500290static bool InstallCertificate(SSL *ssl) {
291 const TestConfig *config = GetConfigPtr(ssl);
David Benjaminb4d65fd2015-05-29 17:11:21 -0400292 TestState *test_state = GetTestState(ssl);
Steven Valdez0d62f262015-09-04 12:41:04 -0400293
294 if (!config->digest_prefs.empty()) {
295 std::unique_ptr<char, Free<char>> digest_prefs(
296 strdup(config->digest_prefs.c_str()));
Steven Valdez0d62f262015-09-04 12:41:04 -0400297 std::vector<int> digest_list;
298
299 for (;;) {
Adam Langley67251f22015-09-23 15:01:07 -0700300 char *token =
301 strtok(digest_list.empty() ? digest_prefs.get() : nullptr, ",");
Steven Valdez0d62f262015-09-04 12:41:04 -0400302 if (token == nullptr) {
303 break;
304 }
305
306 digest_list.push_back(EVP_MD_type(EVP_get_digestbyname(token)));
307 }
308
309 if (!SSL_set_private_key_digest_prefs(ssl, digest_list.data(),
310 digest_list.size())) {
311 return false;
312 }
313 }
314
David Benjaminb4d65fd2015-05-29 17:11:21 -0400315 if (!config->key_file.empty()) {
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700316 if (config->async) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400317 test_state->private_key = LoadPrivateKey(config->key_file.c_str());
318 if (!test_state->private_key) {
319 return false;
320 }
321 SSL_set_private_key_method(ssl, &g_async_private_key_method);
322 } else if (!SSL_use_PrivateKey_file(ssl, config->key_file.c_str(),
323 SSL_FILETYPE_PEM)) {
324 return false;
325 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500326 }
327 if (!config->cert_file.empty() &&
328 !SSL_use_certificate_file(ssl, config->cert_file.c_str(),
329 SSL_FILETYPE_PEM)) {
330 return false;
331 }
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100332 if (!config->ocsp_response.empty() &&
333 !SSL_CTX_set_ocsp_response(ssl->ctx,
334 (const uint8_t *)config->ocsp_response.data(),
335 config->ocsp_response.size())) {
336 return false;
337 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500338 return true;
339}
340
David Benjaminc273d2c2015-02-09 12:59:46 -0500341static int SelectCertificateCallback(const struct ssl_early_callback_ctx *ctx) {
David Benjamin5a593af2014-08-11 19:51:50 -0400342 const TestConfig *config = GetConfigPtr(ctx->ssl);
David Benjamin2d445c02015-02-09 13:03:50 -0500343 GetTestState(ctx->ssl)->early_callback_called = true;
David Benjamin5a593af2014-08-11 19:51:50 -0400344
David Benjamin6f5c0f42015-02-24 01:23:21 -0500345 if (!config->expected_server_name.empty()) {
346 const uint8_t *extension_data;
347 size_t extension_len;
348 CBS extension, server_name_list, host_name;
349 uint8_t name_type;
350
351 if (!SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
352 &extension_data,
353 &extension_len)) {
354 fprintf(stderr, "Could not find server_name extension.\n");
355 return -1;
356 }
357
358 CBS_init(&extension, extension_data, extension_len);
359 if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
360 CBS_len(&extension) != 0 ||
361 !CBS_get_u8(&server_name_list, &name_type) ||
362 name_type != TLSEXT_NAMETYPE_host_name ||
363 !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
364 CBS_len(&server_name_list) != 0) {
365 fprintf(stderr, "Could not decode server_name extension.\n");
366 return -1;
367 }
368
369 if (!CBS_mem_equal(&host_name,
370 (const uint8_t*)config->expected_server_name.data(),
371 config->expected_server_name.size())) {
372 fprintf(stderr, "Server name mismatch.\n");
373 }
David Benjamin7b030512014-07-08 17:30:11 -0400374 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400375
David Benjamin6f5c0f42015-02-24 01:23:21 -0500376 if (config->fail_early_callback) {
David Benjamin7b030512014-07-08 17:30:11 -0400377 return -1;
378 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400379
David Benjamin6f5c0f42015-02-24 01:23:21 -0500380 // Install the certificate in the early callback.
381 if (config->use_early_callback) {
382 if (config->async) {
383 // Install the certificate asynchronously.
384 return 0;
385 }
386 if (!InstallCertificate(ctx->ssl)) {
387 return -1;
388 }
David Benjamin7b030512014-07-08 17:30:11 -0400389 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400390 return 1;
391}
David Benjamin025b3d32014-07-01 19:53:04 -0400392
Paul Lietar8f1c2682015-08-18 12:21:54 +0100393static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
394 SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data(store_ctx,
395 SSL_get_ex_data_X509_STORE_CTX_idx());
396 const TestConfig *config = GetConfigPtr(ssl);
397
398 if (!config->expected_ocsp_response.empty()) {
399 const uint8_t *data;
400 size_t len;
401 SSL_get0_ocsp_response(ssl, &data, &len);
402 if (len == 0) {
403 fprintf(stderr, "OCSP response not available in verify callback\n");
404 return 0;
405 }
406 }
407
David Benjamin67666e72014-07-12 15:47:52 -0400408 return 1;
409}
410
Paul Lietar8f1c2682015-08-18 12:21:54 +0100411static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
412 store_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION;
413 return 0;
414}
415
David Benjaminc273d2c2015-02-09 12:59:46 -0500416static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
417 unsigned int *out_len, void *arg) {
David Benjamin5a593af2014-08-11 19:51:50 -0400418 const TestConfig *config = GetConfigPtr(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500419 if (config->advertise_npn.empty()) {
David Benjamin1f5f62b2014-07-12 16:18:02 -0400420 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500421 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400422
David Benjamin5a593af2014-08-11 19:51:50 -0400423 *out = (const uint8_t*)config->advertise_npn.data();
424 *out_len = config->advertise_npn.size();
David Benjamin1f5f62b2014-07-12 16:18:02 -0400425 return SSL_TLSEXT_ERR_OK;
426}
427
David Benjaminc273d2c2015-02-09 12:59:46 -0500428static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
David Benjamin8b368412015-03-14 01:54:17 -0400429 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin5a593af2014-08-11 19:51:50 -0400430 const TestConfig *config = GetConfigPtr(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500431 if (config->select_next_proto.empty()) {
David Benjamin7e3305e2014-07-28 14:52:32 -0400432 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500433 }
David Benjamin7e3305e2014-07-28 14:52:32 -0400434
David Benjamin5a593af2014-08-11 19:51:50 -0400435 *out = (uint8_t*)config->select_next_proto.data();
436 *outlen = config->select_next_proto.size();
David Benjamin7e3305e2014-07-28 14:52:32 -0400437 return SSL_TLSEXT_ERR_OK;
438}
439
David Benjaminc273d2c2015-02-09 12:59:46 -0500440static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
441 const uint8_t* in, unsigned inlen, void* arg) {
David Benjaminae2888f2014-09-06 12:58:58 -0400442 const TestConfig *config = GetConfigPtr(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500443 if (config->select_alpn.empty()) {
David Benjaminae2888f2014-09-06 12:58:58 -0400444 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500445 }
David Benjaminae2888f2014-09-06 12:58:58 -0400446
447 if (!config->expected_advertised_alpn.empty() &&
448 (config->expected_advertised_alpn.size() != inlen ||
449 memcmp(config->expected_advertised_alpn.data(),
450 in, inlen) != 0)) {
451 fprintf(stderr, "bad ALPN select callback inputs\n");
452 exit(1);
453 }
454
455 *out = (const uint8_t*)config->select_alpn.data();
456 *outlen = config->select_alpn.size();
457 return SSL_TLSEXT_ERR_OK;
458}
459
David Benjaminc273d2c2015-02-09 12:59:46 -0500460static unsigned PskClientCallback(SSL *ssl, const char *hint,
461 char *out_identity,
462 unsigned max_identity_len,
463 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin48cae082014-10-27 01:06:24 -0400464 const TestConfig *config = GetConfigPtr(ssl);
465
466 if (strcmp(hint ? hint : "", config->psk_identity.c_str()) != 0) {
467 fprintf(stderr, "Server PSK hint did not match.\n");
468 return 0;
469 }
470
471 // Account for the trailing '\0' for the identity.
472 if (config->psk_identity.size() >= max_identity_len ||
473 config->psk.size() > max_psk_len) {
474 fprintf(stderr, "PSK buffers too small\n");
475 return 0;
476 }
477
478 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
479 max_identity_len);
480 memcpy(out_psk, config->psk.data(), config->psk.size());
481 return config->psk.size();
482}
483
David Benjaminc273d2c2015-02-09 12:59:46 -0500484static unsigned PskServerCallback(SSL *ssl, const char *identity,
485 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin48cae082014-10-27 01:06:24 -0400486 const TestConfig *config = GetConfigPtr(ssl);
487
488 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
489 fprintf(stderr, "Client PSK identity did not match.\n");
490 return 0;
491 }
492
493 if (config->psk.size() > max_psk_len) {
494 fprintf(stderr, "PSK buffers too small\n");
495 return 0;
496 }
497
498 memcpy(out_psk, config->psk.data(), config->psk.size());
499 return config->psk.size();
500}
501
David Benjamin4d2e7ce2015-05-08 13:29:45 -0400502static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
David Benjamin6c2563e2015-04-03 03:47:47 -0400503 *out_clock = GetTestState(ssl)->clock;
David Benjamin377fc312015-01-26 00:22:12 -0500504}
505
David Benjaminc273d2c2015-02-09 12:59:46 -0500506static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
David Benjamin2d445c02015-02-09 13:03:50 -0500507 *out_pkey = GetTestState(ssl)->channel_id.release();
David Benjamind9e07012015-02-09 03:04:34 -0500508}
509
David Benjaminc273d2c2015-02-09 12:59:46 -0500510static int CertCallback(SSL *ssl, void *arg) {
David Benjamin2d445c02015-02-09 13:03:50 -0500511 if (!GetTestState(ssl)->cert_ready) {
David Benjamin41fdbcd2015-02-09 03:13:35 -0500512 return -1;
513 }
514 if (!InstallCertificate(ssl)) {
515 return 0;
516 }
517 return 1;
518}
519
David Benjaminc273d2c2015-02-09 12:59:46 -0500520static SSL_SESSION *GetSessionCallback(SSL *ssl, uint8_t *data, int len,
521 int *copy) {
David Benjamin2d445c02015-02-09 13:03:50 -0500522 TestState *async_state = GetTestState(ssl);
David Benjamin1b8b6912015-02-09 04:28:16 -0500523 if (async_state->session) {
524 *copy = 0;
525 return async_state->session.release();
526 } else if (async_state->pending_session) {
527 return SSL_magic_pending_session_ptr();
528 } else {
529 return NULL;
530 }
531}
532
Adam Langley524e7172015-02-20 16:04:00 -0800533static int DDoSCallback(const struct ssl_early_callback_ctx *early_context) {
534 const TestConfig *config = GetConfigPtr(early_context->ssl);
535 static int callback_num = 0;
536
537 callback_num++;
538 if (config->fail_ddos_callback ||
539 (config->fail_second_ddos_callback && callback_num == 2)) {
540 return 0;
541 }
542 return 1;
543}
544
David Benjamin87e4acd2015-04-02 19:57:35 -0400545static void InfoCallback(const SSL *ssl, int type, int val) {
546 if (type == SSL_CB_HANDSHAKE_DONE) {
547 if (GetConfigPtr(ssl)->handshake_never_done) {
548 fprintf(stderr, "handshake completed\n");
549 // Abort before any expected error code is printed, to ensure the overall
550 // test fails.
551 abort();
552 }
553 GetTestState(ssl)->handshake_done = true;
554 }
555}
556
David Benjaminba4594a2015-06-18 18:36:15 -0400557static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
558 GetTestState(ssl)->got_new_session = true;
559 // BoringSSL passes a reference to |session|.
560 SSL_SESSION_free(session);
561 return 1;
562}
563
David Benjamind98452d2015-06-16 14:16:23 -0400564static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
565 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
566 int encrypt) {
567 // This is just test code, so use the all-zeros key.
568 static const uint8_t kZeros[16] = {0};
569
570 if (encrypt) {
571 memcpy(key_name, kZeros, sizeof(kZeros));
572 RAND_bytes(iv, 16);
573 } else if (memcmp(key_name, kZeros, 16) != 0) {
574 return 0;
575 }
576
577 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
578 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
579 return -1;
580 }
581
582 if (!encrypt) {
583 return GetConfigPtr(ssl)->renew_ticket ? 2 : 1;
584 }
585 return 1;
586}
587
Adam Langley09505632015-07-30 18:10:13 -0700588// kCustomExtensionValue is the extension value that the custom extension
589// callbacks will add.
Adam Langleyc5b23a12015-07-30 18:19:26 -0700590static const uint16_t kCustomExtensionValue = 1234;
Adam Langley09505632015-07-30 18:10:13 -0700591static void *const kCustomExtensionAddArg =
592 reinterpret_cast<void *>(kCustomExtensionValue);
593static void *const kCustomExtensionParseArg =
594 reinterpret_cast<void *>(kCustomExtensionValue + 1);
595static const char kCustomExtensionContents[] = "custom extension";
596
597static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
598 const uint8_t **out, size_t *out_len,
599 int *out_alert_value, void *add_arg) {
600 if (extension_value != kCustomExtensionValue ||
601 add_arg != kCustomExtensionAddArg) {
602 abort();
603 }
604
605 if (GetConfigPtr(ssl)->custom_extension_skip) {
606 return 0;
607 }
608 if (GetConfigPtr(ssl)->custom_extension_fail_add) {
609 return -1;
610 }
611
612 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
613 *out_len = sizeof(kCustomExtensionContents) - 1;
614
615 return 1;
616}
617
618static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
619 const uint8_t *out, void *add_arg) {
620 if (extension_value != kCustomExtensionValue ||
621 add_arg != kCustomExtensionAddArg ||
622 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
623 abort();
624 }
625}
626
627static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
628 const uint8_t *contents,
629 size_t contents_len,
630 int *out_alert_value, void *parse_arg) {
631 if (extension_value != kCustomExtensionValue ||
632 parse_arg != kCustomExtensionParseArg) {
633 abort();
634 }
635
636 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
637 memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
638 *out_alert_value = SSL_AD_DECODE_ERROR;
639 return 0;
640 }
641
642 return 1;
643}
644
David Benjamin87c8a642015-02-21 01:54:29 -0500645// Connect returns a new socket connected to localhost on |port| or -1 on
646// error.
647static int Connect(uint16_t port) {
648 int sock = socket(AF_INET, SOCK_STREAM, 0);
649 if (sock == -1) {
650 PrintSocketError("socket");
651 return -1;
652 }
653 int nodelay = 1;
654 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
655 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
656 PrintSocketError("setsockopt");
657 closesocket(sock);
658 return -1;
659 }
660 sockaddr_in sin;
661 memset(&sin, 0, sizeof(sin));
662 sin.sin_family = AF_INET;
663 sin.sin_port = htons(port);
664 if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
665 PrintSocketError("inet_pton");
666 closesocket(sock);
667 return -1;
668 }
669 if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
670 sizeof(sin)) != 0) {
671 PrintSocketError("connect");
672 closesocket(sock);
673 return -1;
674 }
675 return sock;
676}
677
678class SocketCloser {
679 public:
680 explicit SocketCloser(int sock) : sock_(sock) {}
681 ~SocketCloser() {
682 // Half-close and drain the socket before releasing it. This seems to be
683 // necessary for graceful shutdown on Windows. It will also avoid write
684 // failures in the test runner.
685#if defined(OPENSSL_WINDOWS)
686 shutdown(sock_, SD_SEND);
687#else
688 shutdown(sock_, SHUT_WR);
689#endif
690 while (true) {
691 char buf[1024];
692 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
693 break;
694 }
695 }
696 closesocket(sock_);
697 }
698
699 private:
700 const int sock_;
701};
702
David Benjaminc273d2c2015-02-09 12:59:46 -0500703static ScopedSSL_CTX SetupCtx(const TestConfig *config) {
David Benjamina7f333d2015-02-09 02:37:18 -0500704 ScopedSSL_CTX ssl_ctx(SSL_CTX_new(
705 config->is_dtls ? DTLS_method() : TLS_method()));
706 if (!ssl_ctx) {
707 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -0400708 }
709
Adam Langleycef75832015-09-03 14:51:12 -0700710 std::string cipher_list = "ALL";
711 if (!config->cipher.empty()) {
712 cipher_list = config->cipher;
713 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
714 }
715 if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
716 return nullptr;
717 }
718
719 if (!config->cipher_tls10.empty() &&
720 !SSL_CTX_set_cipher_list_tls10(ssl_ctx.get(),
721 config->cipher_tls10.c_str())) {
722 return nullptr;
723 }
724 if (!config->cipher_tls11.empty() &&
725 !SSL_CTX_set_cipher_list_tls11(ssl_ctx.get(),
726 config->cipher_tls11.c_str())) {
David Benjamina7f333d2015-02-09 02:37:18 -0500727 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -0400728 }
729
David Benjamina7f333d2015-02-09 02:37:18 -0500730 ScopedDH dh(DH_get_2048_256(NULL));
731 if (!dh || !SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
732 return nullptr;
David Benjaminf4e5c4e2014-08-02 17:35:45 -0400733 }
734
David Benjamin1b8b6912015-02-09 04:28:16 -0500735 if (config->async && config->is_server) {
736 // Disable the internal session cache. To test asynchronous session lookup,
737 // we use an external session cache.
738 SSL_CTX_set_session_cache_mode(
739 ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
David Benjaminc273d2c2015-02-09 12:59:46 -0500740 SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
David Benjamin1b8b6912015-02-09 04:28:16 -0500741 } else {
742 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
743 }
David Benjamin1d5c83e2014-07-22 19:20:02 -0400744
David Benjamind4c2bce2015-10-17 12:28:18 -0400745 SSL_CTX_set_select_certificate_cb(ssl_ctx.get(), SelectCertificateCallback);
David Benjamin8f2c20e2014-07-09 09:30:38 -0400746
David Benjamin1f5f62b2014-07-12 16:18:02 -0400747 SSL_CTX_set_next_protos_advertised_cb(
David Benjaminc273d2c2015-02-09 12:59:46 -0500748 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400749 if (!config->select_next_proto.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500750 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
David Benjamina7f333d2015-02-09 02:37:18 -0500751 NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400752 }
753
754 if (!config->select_alpn.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500755 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400756 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400757
Adam Langley49c7af12015-07-10 14:33:46 -0700758 SSL_CTX_enable_tls_channel_id(ssl_ctx.get());
David Benjaminc273d2c2015-02-09 12:59:46 -0500759 SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
David Benjamina08e49d2014-08-24 01:46:07 -0400760
David Benjaminc273d2c2015-02-09 12:59:46 -0500761 ssl_ctx->current_time_cb = CurrentTimeCallback;
David Benjamin377fc312015-01-26 00:22:12 -0500762
David Benjamin87e4acd2015-04-02 19:57:35 -0400763 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
David Benjaminba4594a2015-06-18 18:36:15 -0400764 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
David Benjamin87e4acd2015-04-02 19:57:35 -0400765
David Benjamind98452d2015-06-16 14:16:23 -0400766 if (config->use_ticket_callback) {
767 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
768 }
769
Adam Langley09505632015-07-30 18:10:13 -0700770 if (config->enable_client_custom_extension &&
771 !SSL_CTX_add_client_custom_ext(
772 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
773 CustomExtensionFreeCallback, kCustomExtensionAddArg,
774 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
775 return nullptr;
776 }
777
778 if (config->enable_server_custom_extension &&
779 !SSL_CTX_add_server_custom_ext(
780 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
781 CustomExtensionFreeCallback, kCustomExtensionAddArg,
782 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
783 return nullptr;
784 }
785
Paul Lietar8f1c2682015-08-18 12:21:54 +0100786 if (config->verify_fail) {
787 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
788 } else {
789 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
790 }
791
Paul Lietar4fac72e2015-09-09 13:44:55 +0100792 if (!config->signed_cert_timestamps.empty() &&
793 !SSL_CTX_set_signed_cert_timestamp_list(
794 ssl_ctx.get(), (const uint8_t *)config->signed_cert_timestamps.data(),
795 config->signed_cert_timestamps.size())) {
796 return nullptr;
797 }
798
David Benjamin1d5c83e2014-07-22 19:20:02 -0400799 return ssl_ctx;
David Benjamin1d5c83e2014-07-22 19:20:02 -0400800}
801
David Benjamin40f101b2015-02-20 11:23:42 -0500802// RetryAsync is called after a failed operation on |ssl| with return code
803// |ret|. If the operation should be retried, it simulates one asynchronous
David Benjamin6c2563e2015-04-03 03:47:47 -0400804// event and returns true. Otherwise it returns false.
805static bool RetryAsync(SSL *ssl, int ret) {
David Benjamin43ec06f2014-08-05 02:28:57 -0400806 // No error; don't retry.
807 if (ret >= 0) {
David Benjamin40f101b2015-02-20 11:23:42 -0500808 return false;
David Benjamin025b3d32014-07-01 19:53:04 -0400809 }
David Benjamin83f90402015-01-27 01:09:43 -0500810
David Benjamin13e81fc2015-11-02 17:16:13 -0500811 const TestConfig *config = GetConfigPtr(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -0400812 TestState *test_state = GetTestState(ssl);
813 if (test_state->clock_delta.tv_usec != 0 ||
814 test_state->clock_delta.tv_sec != 0) {
David Benjamin83f90402015-01-27 01:09:43 -0500815 // Process the timeout and retry.
David Benjamin6c2563e2015-04-03 03:47:47 -0400816 test_state->clock.tv_usec += test_state->clock_delta.tv_usec;
817 test_state->clock.tv_sec += test_state->clock.tv_usec / 1000000;
818 test_state->clock.tv_usec %= 1000000;
819 test_state->clock.tv_sec += test_state->clock_delta.tv_sec;
820 memset(&test_state->clock_delta, 0, sizeof(test_state->clock_delta));
David Benjamin83f90402015-01-27 01:09:43 -0500821
David Benjamin13e81fc2015-11-02 17:16:13 -0500822 // The DTLS retransmit logic silently ignores write failures. So the test
823 // may progress, allow writes through synchronously.
824 if (config->async) {
825 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
826 }
827 int timeout_ret = DTLSv1_handle_timeout(ssl);
828 if (config->async) {
829 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
830 }
831
832 if (timeout_ret < 0) {
David Benjaminc565ebb2015-04-03 04:06:36 -0400833 fprintf(stderr, "Error retransmitting.\n");
David Benjamin40f101b2015-02-20 11:23:42 -0500834 return false;
David Benjamin83f90402015-01-27 01:09:43 -0500835 }
David Benjamin40f101b2015-02-20 11:23:42 -0500836 return true;
David Benjamin83f90402015-01-27 01:09:43 -0500837 }
838
David Benjamin43ec06f2014-08-05 02:28:57 -0400839 // See if we needed to read or write more. If so, allow one byte through on
840 // the appropriate end to maximally stress the state machine.
David Benjamind9e07012015-02-09 03:04:34 -0500841 switch (SSL_get_error(ssl, ret)) {
842 case SSL_ERROR_WANT_READ:
David Benjamin6c2563e2015-04-03 03:47:47 -0400843 AsyncBioAllowRead(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -0500844 return true;
David Benjamind9e07012015-02-09 03:04:34 -0500845 case SSL_ERROR_WANT_WRITE:
David Benjamin6c2563e2015-04-03 03:47:47 -0400846 AsyncBioAllowWrite(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -0500847 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -0500848 case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
849 ScopedEVP_PKEY pkey = LoadPrivateKey(GetConfigPtr(ssl)->send_channel_id);
850 if (!pkey) {
David Benjamin40f101b2015-02-20 11:23:42 -0500851 return false;
David Benjamin9d0847a2015-02-16 03:57:55 -0500852 }
David Benjamin6c2563e2015-04-03 03:47:47 -0400853 test_state->channel_id = std::move(pkey);
David Benjamin40f101b2015-02-20 11:23:42 -0500854 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -0500855 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500856 case SSL_ERROR_WANT_X509_LOOKUP:
David Benjamin6c2563e2015-04-03 03:47:47 -0400857 test_state->cert_ready = true;
David Benjamin40f101b2015-02-20 11:23:42 -0500858 return true;
David Benjamin1b8b6912015-02-09 04:28:16 -0500859 case SSL_ERROR_PENDING_SESSION:
David Benjamin6c2563e2015-04-03 03:47:47 -0400860 test_state->session = std::move(test_state->pending_session);
David Benjamin40f101b2015-02-20 11:23:42 -0500861 return true;
David Benjamin6f5c0f42015-02-24 01:23:21 -0500862 case SSL_ERROR_PENDING_CERTIFICATE:
863 // The handshake will resume without a second call to the early callback.
864 return InstallCertificate(ssl);
David Benjaminb4d65fd2015-05-29 17:11:21 -0400865 case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700866 test_state->private_key_retries++;
David Benjaminb4d65fd2015-05-29 17:11:21 -0400867 return true;
David Benjamind9e07012015-02-09 03:04:34 -0500868 default:
David Benjamin40f101b2015-02-20 11:23:42 -0500869 return false;
David Benjamin025b3d32014-07-01 19:53:04 -0400870 }
David Benjamin025b3d32014-07-01 19:53:04 -0400871}
872
David Benjamin6c2563e2015-04-03 03:47:47 -0400873// DoRead reads from |ssl|, resolving any asynchronous operations. It returns
874// the result value of the final |SSL_read| call.
875static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
876 const TestConfig *config = GetConfigPtr(ssl);
David Benjamin13e81fc2015-11-02 17:16:13 -0500877 TestState *test_state = GetTestState(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -0400878 int ret;
879 do {
David Benjamin13e81fc2015-11-02 17:16:13 -0500880 if (config->async) {
881 // The DTLS retransmit logic silently ignores write failures. So the test
882 // may progress, allow writes through synchronously. |SSL_read| may
883 // trigger a retransmit, so disconnect the write quota.
884 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
885 }
David Benjamin6c2563e2015-04-03 03:47:47 -0400886 ret = SSL_read(ssl, out, max_out);
David Benjamin13e81fc2015-11-02 17:16:13 -0500887 if (config->async) {
888 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
889 }
David Benjamin6c2563e2015-04-03 03:47:47 -0400890 } while (config->async && RetryAsync(ssl, ret));
891 return ret;
892}
893
894// WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
895// operations. It returns the result of the final |SSL_write| call.
896static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
897 const TestConfig *config = GetConfigPtr(ssl);
898 int ret;
899 do {
900 ret = SSL_write(ssl, in, in_len);
901 if (ret > 0) {
902 in += ret;
903 in_len -= ret;
904 }
905 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
906 return ret;
907}
908
David Benjamin30789da2015-08-29 22:56:45 -0400909// DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
910// returns the result of the final |SSL_shutdown| call.
911static int DoShutdown(SSL *ssl) {
912 const TestConfig *config = GetConfigPtr(ssl);
913 int ret;
914 do {
915 ret = SSL_shutdown(ssl);
916 } while (config->async && RetryAsync(ssl, ret));
917 return ret;
918}
919
David Benjamin91eab5c2015-06-18 18:35:46 -0400920// CheckHandshakeProperties checks, immediately after |ssl| completes its
921// initial handshake (or False Starts), whether all the properties are
922// consistent with the test configuration and invariants.
923static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
924 const TestConfig *config = GetConfigPtr(ssl);
925
926 if (SSL_get_current_cipher(ssl) == nullptr) {
927 fprintf(stderr, "null cipher after handshake\n");
928 return false;
929 }
930
931 if (is_resume &&
932 (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
933 fprintf(stderr, "session was%s reused\n",
934 SSL_session_reused(ssl) ? "" : " not");
935 return false;
936 }
937
938 bool expect_handshake_done = is_resume || !config->false_start;
939 if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
940 fprintf(stderr, "handshake was%s completed\n",
941 GetTestState(ssl)->handshake_done ? "" : " not");
942 return false;
943 }
944
David Benjaminba4594a2015-06-18 18:36:15 -0400945 if (expect_handshake_done && !config->is_server) {
946 bool expect_new_session =
947 !config->expect_no_session &&
948 (!SSL_session_reused(ssl) || config->expect_ticket_renewal);
949 if (expect_new_session != GetTestState(ssl)->got_new_session) {
950 fprintf(stderr,
David Benjamindd6fed92015-10-23 17:41:12 -0400951 "new session was%s cached, but we expected the opposite\n",
David Benjaminba4594a2015-06-18 18:36:15 -0400952 GetTestState(ssl)->got_new_session ? "" : " not");
953 return false;
954 }
955 }
956
David Benjamin91eab5c2015-06-18 18:35:46 -0400957 if (config->is_server && !GetTestState(ssl)->early_callback_called) {
958 fprintf(stderr, "early callback not called\n");
959 return false;
960 }
961
962 if (!config->expected_server_name.empty()) {
963 const char *server_name =
964 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
965 if (server_name != config->expected_server_name) {
966 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
967 server_name, config->expected_server_name.c_str());
968 return false;
969 }
970 }
971
972 if (!config->expected_certificate_types.empty()) {
David Benjamin75910642015-08-09 10:42:33 -0400973 const uint8_t *certificate_types;
974 size_t certificate_types_len =
David Benjamin91eab5c2015-06-18 18:35:46 -0400975 SSL_get0_certificate_types(ssl, &certificate_types);
David Benjamin75910642015-08-09 10:42:33 -0400976 if (certificate_types_len != config->expected_certificate_types.size() ||
David Benjamin91eab5c2015-06-18 18:35:46 -0400977 memcmp(certificate_types,
978 config->expected_certificate_types.data(),
David Benjamin75910642015-08-09 10:42:33 -0400979 certificate_types_len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -0400980 fprintf(stderr, "certificate types mismatch\n");
981 return false;
982 }
983 }
984
985 if (!config->expected_next_proto.empty()) {
986 const uint8_t *next_proto;
987 unsigned next_proto_len;
988 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
989 if (next_proto_len != config->expected_next_proto.size() ||
990 memcmp(next_proto, config->expected_next_proto.data(),
991 next_proto_len) != 0) {
992 fprintf(stderr, "negotiated next proto mismatch\n");
993 return false;
994 }
995 }
996
997 if (!config->expected_alpn.empty()) {
998 const uint8_t *alpn_proto;
999 unsigned alpn_proto_len;
1000 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
1001 if (alpn_proto_len != config->expected_alpn.size() ||
1002 memcmp(alpn_proto, config->expected_alpn.data(),
1003 alpn_proto_len) != 0) {
1004 fprintf(stderr, "negotiated alpn proto mismatch\n");
1005 return false;
1006 }
1007 }
1008
1009 if (!config->expected_channel_id.empty()) {
1010 uint8_t channel_id[64];
1011 if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
1012 fprintf(stderr, "no channel id negotiated\n");
1013 return false;
1014 }
1015 if (config->expected_channel_id.size() != 64 ||
1016 memcmp(config->expected_channel_id.data(),
1017 channel_id, 64) != 0) {
1018 fprintf(stderr, "channel id mismatch\n");
1019 return false;
1020 }
1021 }
1022
1023 if (config->expect_extended_master_secret) {
1024 if (!ssl->session->extended_master_secret) {
1025 fprintf(stderr, "No EMS for session when expected");
1026 return false;
1027 }
1028 }
1029
1030 if (!config->expected_ocsp_response.empty()) {
1031 const uint8_t *data;
1032 size_t len;
1033 SSL_get0_ocsp_response(ssl, &data, &len);
1034 if (config->expected_ocsp_response.size() != len ||
1035 memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
1036 fprintf(stderr, "OCSP response mismatch\n");
1037 return false;
1038 }
1039 }
1040
1041 if (!config->expected_signed_cert_timestamps.empty()) {
1042 const uint8_t *data;
1043 size_t len;
1044 SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
1045 if (config->expected_signed_cert_timestamps.size() != len ||
1046 memcmp(config->expected_signed_cert_timestamps.data(),
1047 data, len) != 0) {
1048 fprintf(stderr, "SCT list mismatch\n");
1049 return false;
1050 }
1051 }
1052
Paul Lietar8f1c2682015-08-18 12:21:54 +01001053 if (config->expect_verify_result) {
1054 int expected_verify_result = config->verify_fail ?
1055 X509_V_ERR_APPLICATION_VERIFICATION :
1056 X509_V_OK;
1057
1058 if (SSL_get_verify_result(ssl) != expected_verify_result) {
1059 fprintf(stderr, "Wrong certificate verification result\n");
1060 return false;
1061 }
1062 }
1063
David Benjamin6e807652015-11-02 12:02:20 -05001064 if (config->expect_server_key_exchange_hash != 0 &&
1065 config->expect_server_key_exchange_hash !=
1066 SSL_get_server_key_exchange_hash(ssl)) {
1067 fprintf(stderr, "ServerKeyExchange hash was %d, wanted %d.\n",
1068 SSL_get_server_key_exchange_hash(ssl),
1069 config->expect_server_key_exchange_hash);
1070 return false;
1071 }
1072
David Benjamin91eab5c2015-06-18 18:35:46 -04001073 if (!config->is_server) {
1074 /* Clients should expect a peer certificate chain iff this was not a PSK
1075 * cipher suite. */
1076 if (config->psk.empty()) {
1077 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
1078 fprintf(stderr, "Missing peer certificate chain!\n");
1079 return false;
1080 }
1081 } else if (SSL_get_peer_cert_chain(ssl) != nullptr) {
1082 fprintf(stderr, "Unexpected peer certificate chain!\n");
1083 return false;
1084 }
1085 }
1086 return true;
1087}
1088
David Benjamin87c8a642015-02-21 01:54:29 -05001089// DoExchange runs a test SSL exchange against the peer. On success, it returns
1090// true and sets |*out_session| to the negotiated SSL session. If the test is a
1091// resumption attempt, |is_resume| is true and |session| is the session from the
1092// previous exchange.
David Benjamin40f101b2015-02-20 11:23:42 -05001093static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx,
1094 const TestConfig *config, bool is_resume,
David Benjamin87c8a642015-02-21 01:54:29 -05001095 SSL_SESSION *session) {
David Benjamina7f333d2015-02-09 02:37:18 -05001096 ScopedSSL ssl(SSL_new(ssl_ctx));
1097 if (!ssl) {
David Benjamin40f101b2015-02-20 11:23:42 -05001098 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001099 }
1100
David Benjamina7f333d2015-02-09 02:37:18 -05001101 if (!SetConfigPtr(ssl.get(), config) ||
David Benjamin2d445c02015-02-09 13:03:50 -05001102 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
David Benjamin40f101b2015-02-20 11:23:42 -05001103 return false;
Adam Langley69a01602014-11-17 17:26:55 -08001104 }
David Benjamin5a593af2014-08-11 19:51:50 -04001105
Adam Langley5f0efe02015-02-20 13:03:16 -08001106 if (config->fallback_scsv &&
1107 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
1108 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001109 }
David Benjamin6f5c0f42015-02-24 01:23:21 -05001110 if (!config->use_early_callback) {
1111 if (config->async) {
1112 // TODO(davidben): Also test |s->ctx->client_cert_cb| on the client.
1113 SSL_set_cert_cb(ssl.get(), CertCallback, NULL);
1114 } else if (!InstallCertificate(ssl.get())) {
1115 return false;
1116 }
David Benjamin5a593af2014-08-11 19:51:50 -04001117 }
1118 if (config->require_any_client_certificate) {
David Benjamina7f333d2015-02-09 02:37:18 -05001119 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
Paul Lietar8f1c2682015-08-18 12:21:54 +01001120 NULL);
1121 }
1122 if (config->verify_peer) {
1123 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
David Benjamin5a593af2014-08-11 19:51:50 -04001124 }
1125 if (config->false_start) {
David Benjamined7c4752015-02-16 19:16:46 -05001126 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
David Benjamin5a593af2014-08-11 19:51:50 -04001127 }
1128 if (config->cbc_record_splitting) {
David Benjamina7f333d2015-02-09 02:37:18 -05001129 SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
David Benjamin5a593af2014-08-11 19:51:50 -04001130 }
1131 if (config->partial_write) {
David Benjamina7f333d2015-02-09 02:37:18 -05001132 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
David Benjamin5a593af2014-08-11 19:51:50 -04001133 }
1134 if (config->no_tls12) {
David Benjamina7f333d2015-02-09 02:37:18 -05001135 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
David Benjamin5a593af2014-08-11 19:51:50 -04001136 }
1137 if (config->no_tls11) {
David Benjamina7f333d2015-02-09 02:37:18 -05001138 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
David Benjamin5a593af2014-08-11 19:51:50 -04001139 }
1140 if (config->no_tls1) {
David Benjamina7f333d2015-02-09 02:37:18 -05001141 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
David Benjamin5a593af2014-08-11 19:51:50 -04001142 }
1143 if (config->no_ssl3) {
David Benjamina7f333d2015-02-09 02:37:18 -05001144 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
David Benjamin5a593af2014-08-11 19:51:50 -04001145 }
David Benjamin5c24a1d2014-08-31 00:59:27 -04001146 if (config->tls_d5_bug) {
David Benjamina7f333d2015-02-09 02:37:18 -05001147 SSL_set_options(ssl.get(), SSL_OP_TLS_D5_BUG);
David Benjamin5c24a1d2014-08-31 00:59:27 -04001148 }
David Benjamin2c99d282015-09-01 10:23:00 -04001149 if (config->microsoft_big_sslv3_buffer) {
1150 SSL_set_options(ssl.get(), SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER);
1151 }
David Benjamincff0b902015-05-15 23:09:47 -04001152 if (config->no_legacy_server_connect) {
1153 SSL_clear_options(ssl.get(), SSL_OP_LEGACY_SERVER_CONNECT);
1154 }
David Benjamina08e49d2014-08-24 01:46:07 -04001155 if (!config->expected_channel_id.empty()) {
David Benjamina7f333d2015-02-09 02:37:18 -05001156 SSL_enable_tls_channel_id(ssl.get());
David Benjamina08e49d2014-08-24 01:46:07 -04001157 }
1158 if (!config->send_channel_id.empty()) {
David Benjamina7f333d2015-02-09 02:37:18 -05001159 SSL_enable_tls_channel_id(ssl.get());
David Benjamind9e07012015-02-09 03:04:34 -05001160 if (!config->async) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001161 // The async case will be supplied by |ChannelIdCallback|.
David Benjamind9e07012015-02-09 03:04:34 -05001162 ScopedEVP_PKEY pkey = LoadPrivateKey(config->send_channel_id);
1163 if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001164 return false;
David Benjamind9e07012015-02-09 03:04:34 -05001165 }
David Benjamina08e49d2014-08-24 01:46:07 -04001166 }
David Benjamina08e49d2014-08-24 01:46:07 -04001167 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001168 if (!config->host_name.empty() &&
1169 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001170 return false;
David Benjamine78bfde2014-09-06 12:45:15 -04001171 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001172 if (!config->advertise_alpn.empty() &&
1173 SSL_set_alpn_protos(ssl.get(),
1174 (const uint8_t *)config->advertise_alpn.data(),
1175 config->advertise_alpn.size()) != 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001176 return false;
David Benjaminae2888f2014-09-06 12:58:58 -04001177 }
David Benjamin48cae082014-10-27 01:06:24 -04001178 if (!config->psk.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001179 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
1180 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
David Benjamin48cae082014-10-27 01:06:24 -04001181 }
David Benjamin61f95272014-11-25 01:55:35 -05001182 if (!config->psk_identity.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001183 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001184 return false;
David Benjamin48cae082014-10-27 01:06:24 -04001185 }
David Benjamin61f95272014-11-25 01:55:35 -05001186 if (!config->srtp_profiles.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001187 !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001188 return false;
David Benjamin61f95272014-11-25 01:55:35 -05001189 }
1190 if (config->enable_ocsp_stapling &&
David Benjamina7f333d2015-02-09 02:37:18 -05001191 !SSL_enable_ocsp_stapling(ssl.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001192 return false;
David Benjamin61f95272014-11-25 01:55:35 -05001193 }
1194 if (config->enable_signed_cert_timestamps &&
David Benjamina7f333d2015-02-09 02:37:18 -05001195 !SSL_enable_signed_cert_timestamps(ssl.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001196 return false;
David Benjaminca6c8262014-11-15 19:06:08 -05001197 }
David Benjamin1eb367c2014-12-12 18:17:51 -05001198 if (config->min_version != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001199 SSL_set_min_version(ssl.get(), (uint16_t)config->min_version);
David Benjamin1eb367c2014-12-12 18:17:51 -05001200 }
1201 if (config->max_version != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001202 SSL_set_max_version(ssl.get(), (uint16_t)config->max_version);
David Benjamin1eb367c2014-12-12 18:17:51 -05001203 }
David Benjamin13be1de2015-01-11 16:29:36 -05001204 if (config->mtu != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001205 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
1206 SSL_set_mtu(ssl.get(), config->mtu);
David Benjamin13be1de2015-01-11 16:29:36 -05001207 }
Adam Langley524e7172015-02-20 16:04:00 -08001208 if (config->install_ddos_callback) {
1209 SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
1210 }
David Benjamin1d5ef3b2015-10-12 19:54:18 -04001211 if (config->renegotiate_once) {
1212 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_once);
1213 }
1214 if (config->renegotiate_freely) {
1215 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
David Benjaminb16346b2015-04-08 19:16:58 -04001216 }
Adam Langley27a0d082015-11-03 13:34:10 -08001217 if (config->renegotiate_ignore) {
1218 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_ignore);
1219 }
David Benjamin30789da2015-08-29 22:56:45 -04001220 if (!config->check_close_notify) {
1221 SSL_set_quiet_shutdown(ssl.get(), 1);
1222 }
David Benjamin091c4b92015-10-26 13:33:21 -04001223 if (config->disable_npn) {
1224 SSL_set_options(ssl.get(), SSL_OP_DISABLE_NPN);
1225 }
David Benjamin99fdfb92015-11-02 12:11:35 -05001226 if (config->p384_only) {
1227 int nid = NID_secp384r1;
1228 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
1229 return false;
1230 }
1231 }
David Benjamin025b3d32014-07-01 19:53:04 -04001232
David Benjamin87c8a642015-02-21 01:54:29 -05001233 int sock = Connect(config->port);
1234 if (sock == -1) {
1235 return false;
1236 }
1237 SocketCloser closer(sock);
1238
1239 ScopedBIO bio(BIO_new_socket(sock, BIO_NOCLOSE));
David Benjamina7f333d2015-02-09 02:37:18 -05001240 if (!bio) {
David Benjamin40f101b2015-02-20 11:23:42 -05001241 return false;
David Benjamin43ec06f2014-08-05 02:28:57 -04001242 }
David Benjamin6fd297b2014-08-11 18:43:38 -04001243 if (config->is_dtls) {
David Benjamin6c2563e2015-04-03 03:47:47 -04001244 ScopedBIO packeted =
1245 PacketedBioCreate(&GetTestState(ssl.get())->clock_delta);
David Benjamina7f333d2015-02-09 02:37:18 -05001246 BIO_push(packeted.get(), bio.release());
1247 bio = std::move(packeted);
David Benjamin6fd297b2014-08-11 18:43:38 -04001248 }
David Benjamin5a593af2014-08-11 19:51:50 -04001249 if (config->async) {
David Benjamina7f333d2015-02-09 02:37:18 -05001250 ScopedBIO async_scoped =
David Benjaminc273d2c2015-02-09 12:59:46 -05001251 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
David Benjamina7f333d2015-02-09 02:37:18 -05001252 BIO_push(async_scoped.get(), bio.release());
David Benjamin6c2563e2015-04-03 03:47:47 -04001253 GetTestState(ssl.get())->async_bio = async_scoped.get();
David Benjamina7f333d2015-02-09 02:37:18 -05001254 bio = std::move(async_scoped);
David Benjamin43ec06f2014-08-05 02:28:57 -04001255 }
David Benjamina7f333d2015-02-09 02:37:18 -05001256 SSL_set_bio(ssl.get(), bio.get(), bio.get());
1257 bio.release(); // SSL_set_bio takes ownership.
David Benjamin43ec06f2014-08-05 02:28:57 -04001258
David Benjamin1d5c83e2014-07-22 19:20:02 -04001259 if (session != NULL) {
David Benjamin1b8b6912015-02-09 04:28:16 -05001260 if (!config->is_server) {
1261 if (SSL_set_session(ssl.get(), session) != 1) {
David Benjamin40f101b2015-02-20 11:23:42 -05001262 return false;
David Benjamin1b8b6912015-02-09 04:28:16 -05001263 }
1264 } else if (config->async) {
1265 // The internal session cache is disabled, so install the session
1266 // manually.
David Benjamin2d445c02015-02-09 13:03:50 -05001267 GetTestState(ssl.get())->pending_session.reset(
David Benjamin1b8b6912015-02-09 04:28:16 -05001268 SSL_SESSION_up_ref(session));
David Benjamin1d5c83e2014-07-22 19:20:02 -04001269 }
1270 }
1271
David Benjamina07c0fc2015-05-13 13:19:42 -04001272 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1273 fprintf(stderr, "non-null cipher before handshake\n");
1274 return false;
1275 }
1276
David Benjamin1d5c83e2014-07-22 19:20:02 -04001277 int ret;
David Benjamine0e7d0d2015-02-08 19:33:25 -05001278 if (config->implicit_handshake) {
David Benjamin5a593af2014-08-11 19:51:50 -04001279 if (config->is_server) {
David Benjamina7f333d2015-02-09 02:37:18 -05001280 SSL_set_accept_state(ssl.get());
David Benjamin43ec06f2014-08-05 02:28:57 -04001281 } else {
David Benjamina7f333d2015-02-09 02:37:18 -05001282 SSL_set_connect_state(ssl.get());
David Benjamin43ec06f2014-08-05 02:28:57 -04001283 }
David Benjamine0e7d0d2015-02-08 19:33:25 -05001284 } else {
1285 do {
1286 if (config->is_server) {
David Benjamina7f333d2015-02-09 02:37:18 -05001287 ret = SSL_accept(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -05001288 } else {
David Benjamina7f333d2015-02-09 02:37:18 -05001289 ret = SSL_connect(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -05001290 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001291 } while (config->async && RetryAsync(ssl.get(), ret));
David Benjamin91eab5c2015-06-18 18:35:46 -04001292 if (ret != 1 ||
1293 !CheckHandshakeProperties(ssl.get(), is_resume)) {
David Benjamin40f101b2015-02-20 11:23:42 -05001294 return false;
David Benjamine0e7d0d2015-02-08 19:33:25 -05001295 }
David Benjamin025b3d32014-07-01 19:53:04 -04001296
David Benjaminba4594a2015-06-18 18:36:15 -04001297 // Reset the state to assert later that the callback isn't called in
1298 // renegotations.
1299 GetTestState(ssl.get())->got_new_session = false;
David Benjamin61f95272014-11-25 01:55:35 -05001300 }
1301
David Benjaminc565ebb2015-04-03 04:06:36 -04001302 if (config->export_keying_material > 0) {
1303 std::vector<uint8_t> result(
1304 static_cast<size_t>(config->export_keying_material));
1305 if (!SSL_export_keying_material(
1306 ssl.get(), result.data(), result.size(),
1307 config->export_label.data(), config->export_label.size(),
1308 reinterpret_cast<const uint8_t*>(config->export_context.data()),
1309 config->export_context.size(), config->use_export_context)) {
1310 fprintf(stderr, "failed to export keying material\n");
1311 return false;
1312 }
1313 if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1314 return false;
1315 }
1316 }
1317
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001318 if (config->tls_unique) {
1319 uint8_t tls_unique[16];
1320 size_t tls_unique_len;
1321 if (!SSL_get_tls_unique(ssl.get(), tls_unique, &tls_unique_len,
1322 sizeof(tls_unique))) {
1323 fprintf(stderr, "failed to get tls-unique\n");
1324 return false;
1325 }
1326
1327 if (tls_unique_len != 12) {
1328 fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
1329 static_cast<unsigned>(tls_unique_len));
1330 return false;
1331 }
1332
1333 if (WriteAll(ssl.get(), tls_unique, tls_unique_len) < 0) {
1334 return false;
1335 }
1336 }
1337
David Benjamin5a593af2014-08-11 19:51:50 -04001338 if (config->write_different_record_sizes) {
David Benjamin6fd297b2014-08-11 18:43:38 -04001339 if (config->is_dtls) {
1340 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001341 return false;
David Benjamin6fd297b2014-08-11 18:43:38 -04001342 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001343 // This mode writes a number of different record sizes in an attempt to
1344 // trip up the CBC record splitting code.
Adam Langleybc949292015-06-18 21:32:44 -07001345 static const size_t kBufLen = 32769;
1346 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1347 memset(buf.get(), 0x42, kBufLen);
Kenny Root7fdeaf12014-08-05 15:23:37 -07001348 static const size_t kRecordSizes[] = {
1349 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
1350 for (size_t i = 0; i < sizeof(kRecordSizes) / sizeof(kRecordSizes[0]);
1351 i++) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07001352 const size_t len = kRecordSizes[i];
Adam Langleybc949292015-06-18 21:32:44 -07001353 if (len > kBufLen) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07001354 fprintf(stderr, "Bad kRecordSizes value.\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001355 return false;
Kenny Root7fdeaf12014-08-05 15:23:37 -07001356 }
Adam Langleybc949292015-06-18 21:32:44 -07001357 if (WriteAll(ssl.get(), buf.get(), len) < 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001358 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001359 }
1360 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001361 } else {
David Benjamine58c4f52014-08-24 03:47:07 -04001362 if (config->shim_writes_first) {
David Benjamin6c2563e2015-04-03 03:47:47 -04001363 if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1364 5) < 0) {
1365 return false;
1366 }
David Benjamine58c4f52014-08-24 03:47:07 -04001367 }
David Benjamin30789da2015-08-29 22:56:45 -04001368 if (!config->shim_shuts_down) {
1369 for (;;) {
Adam Langleya0a8dc22015-09-09 10:22:00 -07001370 static const size_t kBufLen = 16384;
1371 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1372
David Benjamin2c99d282015-09-01 10:23:00 -04001373 // Read only 512 bytes at a time in TLS to ensure records may be
1374 // returned in multiple reads.
Adam Langleya0a8dc22015-09-09 10:22:00 -07001375 int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
David Benjamin30789da2015-08-29 22:56:45 -04001376 int err = SSL_get_error(ssl.get(), n);
1377 if (err == SSL_ERROR_ZERO_RETURN ||
1378 (n == 0 && err == SSL_ERROR_SYSCALL)) {
1379 if (n != 0) {
1380 fprintf(stderr, "Invalid SSL_get_error output\n");
1381 return false;
1382 }
1383 // Stop on either clean or unclean shutdown.
1384 break;
1385 } else if (err != SSL_ERROR_NONE) {
1386 if (n > 0) {
1387 fprintf(stderr, "Invalid SSL_get_error output\n");
1388 return false;
1389 }
1390 return false;
1391 }
1392 // Successfully read data.
1393 if (n <= 0) {
David Benjamin9a38e922015-01-22 16:06:11 -05001394 fprintf(stderr, "Invalid SSL_get_error output\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001395 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001396 }
David Benjamin30789da2015-08-29 22:56:45 -04001397
1398 // After a successful read, with or without False Start, the handshake
1399 // must be complete.
1400 if (!GetTestState(ssl.get())->handshake_done) {
1401 fprintf(stderr, "handshake was not completed after SSL_read\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001402 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001403 }
David Benjamin87e4acd2015-04-02 19:57:35 -04001404
David Benjamin30789da2015-08-29 22:56:45 -04001405 for (int i = 0; i < n; i++) {
1406 buf[i] ^= 0xff;
1407 }
Adam Langleya0a8dc22015-09-09 10:22:00 -07001408 if (WriteAll(ssl.get(), buf.get(), n) < 0) {
David Benjamin30789da2015-08-29 22:56:45 -04001409 return false;
1410 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001411 }
1412 }
David Benjamin025b3d32014-07-01 19:53:04 -04001413 }
1414
David Benjaminba4594a2015-06-18 18:36:15 -04001415 if (!config->is_server && !config->false_start &&
1416 !config->implicit_handshake &&
1417 GetTestState(ssl.get())->got_new_session) {
1418 fprintf(stderr, "new session was established after the handshake\n");
1419 return false;
1420 }
1421
David Benjamin1d5c83e2014-07-22 19:20:02 -04001422 if (out_session) {
David Benjamina7f333d2015-02-09 02:37:18 -05001423 out_session->reset(SSL_get1_session(ssl.get()));
David Benjamin1d5c83e2014-07-22 19:20:02 -04001424 }
1425
David Benjamin30789da2015-08-29 22:56:45 -04001426 ret = DoShutdown(ssl.get());
1427
1428 if (config->shim_shuts_down && config->check_close_notify) {
1429 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1430 // it returns zero when our close_notify is sent, then one when the peer's
1431 // is received.
1432 if (ret != 0) {
1433 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1434 return false;
1435 }
1436 ret = DoShutdown(ssl.get());
1437 }
1438
1439 if (ret != 1) {
1440 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1441 return false;
1442 }
1443
David Benjamin324dce42015-10-12 19:49:00 -04001444 if (SSL_total_renegotiations(ssl.get()) !=
1445 config->expect_total_renegotiations) {
1446 fprintf(stderr, "Expected %d renegotiations, got %d\n",
1447 config->expect_total_renegotiations,
1448 SSL_total_renegotiations(ssl.get()));
1449 return false;
1450 }
1451
David Benjamin40f101b2015-02-20 11:23:42 -05001452 return true;
David Benjamin025b3d32014-07-01 19:53:04 -04001453}
David Benjamin1d5c83e2014-07-22 19:20:02 -04001454
1455int main(int argc, char **argv) {
David Benjamin87c8a642015-02-21 01:54:29 -05001456#if defined(OPENSSL_WINDOWS)
1457 /* Initialize Winsock. */
1458 WORD wsa_version = MAKEWORD(2, 2);
1459 WSADATA wsa_data;
1460 int wsa_err = WSAStartup(wsa_version, &wsa_data);
1461 if (wsa_err != 0) {
1462 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1463 return 1;
1464 }
1465 if (wsa_data.wVersion != wsa_version) {
1466 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1467 return 1;
1468 }
1469#else
David Benjamin1d5c83e2014-07-22 19:20:02 -04001470 signal(SIGPIPE, SIG_IGN);
Adam Langleyded93582014-07-31 15:23:51 -07001471#endif
David Benjamin1d5c83e2014-07-22 19:20:02 -04001472
David Benjamin7a1eefd2015-10-17 23:39:22 -04001473 CRYPTO_library_init();
David Benjamind9e07012015-02-09 03:04:34 -05001474 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
David Benjamin2d445c02015-02-09 13:03:50 -05001475 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
David Benjamin6c2563e2015-04-03 03:47:47 -04001476 if (g_config_index < 0 || g_state_index < 0) {
David Benjaminae3e4872014-11-18 21:52:26 -05001477 return 1;
1478 }
David Benjamin5a593af2014-08-11 19:51:50 -04001479
1480 TestConfig config;
1481 if (!ParseConfig(argc - 1, argv + 1, &config)) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001482 return Usage(argv[0]);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001483 }
1484
David Benjaminc273d2c2015-02-09 12:59:46 -05001485 ScopedSSL_CTX ssl_ctx = SetupCtx(&config);
David Benjamina7f333d2015-02-09 02:37:18 -05001486 if (!ssl_ctx) {
Brian Smith83a82982015-04-09 16:21:10 -10001487 ERR_print_errors_fp(stderr);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001488 return 1;
1489 }
1490
David Benjamina7f333d2015-02-09 02:37:18 -05001491 ScopedSSL_SESSION session;
David Benjamin40f101b2015-02-20 11:23:42 -05001492 if (!DoExchange(&session, ssl_ctx.get(), &config, false /* is_resume */,
David Benjamin87c8a642015-02-21 01:54:29 -05001493 NULL /* session */)) {
Brian Smith83a82982015-04-09 16:21:10 -10001494 ERR_print_errors_fp(stderr);
David Benjamin40f101b2015-02-20 11:23:42 -05001495 return 1;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001496 }
1497
David Benjamin40f101b2015-02-20 11:23:42 -05001498 if (config.resume &&
1499 !DoExchange(NULL, ssl_ctx.get(), &config, true /* is_resume */,
David Benjamin87c8a642015-02-21 01:54:29 -05001500 session.get())) {
Brian Smith83a82982015-04-09 16:21:10 -10001501 ERR_print_errors_fp(stderr);
David Benjamin40f101b2015-02-20 11:23:42 -05001502 return 1;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001503 }
1504
David Benjamina7f333d2015-02-09 02:37:18 -05001505 return 0;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001506}