blob: 82424266b14f332f8ba389ef74db2eafdbaf0936 [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>
Brian Smith83a82982015-04-09 16:21:10 -100041#include <openssl/err.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040042#include <openssl/ssl.h>
43
David Benjamin45fb1be2015-03-22 16:31:27 -040044#include <memory>
David Benjaminc565ebb2015-04-03 04:06:36 -040045#include <vector>
David Benjamin45fb1be2015-03-22 16:31:27 -040046
47#include "../../crypto/test/scoped_types.h"
David Benjamin43ec06f2014-08-05 02:28:57 -040048#include "async_bio.h"
David Benjamin6fd297b2014-08-11 18:43:38 -040049#include "packeted_bio.h"
David Benjamina7f333d2015-02-09 02:37:18 -050050#include "scoped_types.h"
David Benjamin5a593af2014-08-11 19:51:50 -040051#include "test_config.h"
David Benjamin43ec06f2014-08-05 02:28:57 -040052
David Benjamin87c8a642015-02-21 01:54:29 -050053
54#if !defined(OPENSSL_WINDOWS)
55static int closesocket(int sock) {
56 return close(sock);
57}
58
59static void PrintSocketError(const char *func) {
60 perror(func);
61}
62#else
63static void PrintSocketError(const char *func) {
64 fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
65}
66#endif
67
David Benjaminc273d2c2015-02-09 12:59:46 -050068static int Usage(const char *program) {
David Benjamina7f333d2015-02-09 02:37:18 -050069 fprintf(stderr, "Usage: %s [flags...]\n", program);
David Benjamin1d5c83e2014-07-22 19:20:02 -040070 return 1;
71}
David Benjamin025b3d32014-07-01 19:53:04 -040072
David Benjamin2d445c02015-02-09 13:03:50 -050073struct TestState {
David Benjaminff9c74f2015-04-06 20:17:56 -040074 TestState() {
75 // MSVC cannot initialize these inline.
76 memset(&clock, 0, sizeof(clock));
77 memset(&clock_delta, 0, sizeof(clock_delta));
78 }
79
David Benjamin6c2563e2015-04-03 03:47:47 -040080 // async_bio is async BIO which pauses reads and writes.
81 BIO *async_bio = nullptr;
82 // clock is the current time for the SSL connection.
David Benjamin4d2e7ce2015-05-08 13:29:45 -040083 timeval clock;
David Benjamin6c2563e2015-04-03 03:47:47 -040084 // clock_delta is how far the clock advanced in the most recent failed
85 // |BIO_read|.
David Benjamin4d2e7ce2015-05-08 13:29:45 -040086 timeval clock_delta;
David Benjamind9e07012015-02-09 03:04:34 -050087 ScopedEVP_PKEY channel_id;
David Benjamin0d4db502015-03-23 18:46:05 -040088 bool cert_ready = false;
David Benjamin1b8b6912015-02-09 04:28:16 -050089 ScopedSSL_SESSION session;
90 ScopedSSL_SESSION pending_session;
David Benjamin0d4db502015-03-23 18:46:05 -040091 bool early_callback_called = false;
David Benjamin87e4acd2015-04-02 19:57:35 -040092 bool handshake_done = false;
David Benjaminb4d65fd2015-05-29 17:11:21 -040093 // private_key is the underlying private key used when testing custom keys.
94 ScopedEVP_PKEY private_key;
95 std::vector<uint8_t> signature;
96 // signature_retries is the number of times an asynchronous sign operation has
97 // been retried.
98 unsigned signature_retries = 0;
David Benjaminba4594a2015-06-18 18:36:15 -040099 bool got_new_session = false;
David Benjamind9e07012015-02-09 03:04:34 -0500100};
101
David Benjamin2d445c02015-02-09 13:03:50 -0500102static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
103 int index, long argl, void *argp) {
104 delete ((TestState *)ptr);
David Benjamind9e07012015-02-09 03:04:34 -0500105}
106
107static int g_config_index = 0;
David Benjamin2d445c02015-02-09 13:03:50 -0500108static int g_state_index = 0;
David Benjamin5a593af2014-08-11 19:51:50 -0400109
Adam Langley69a01602014-11-17 17:26:55 -0800110static bool SetConfigPtr(SSL *ssl, const TestConfig *config) {
David Benjamind9e07012015-02-09 03:04:34 -0500111 return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
David Benjamin5a593af2014-08-11 19:51:50 -0400112}
113
David Benjamin87e4acd2015-04-02 19:57:35 -0400114static const TestConfig *GetConfigPtr(const SSL *ssl) {
David Benjamind9e07012015-02-09 03:04:34 -0500115 return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
David Benjamin5a593af2014-08-11 19:51:50 -0400116}
117
David Benjamin2d445c02015-02-09 13:03:50 -0500118static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> async) {
119 if (SSL_set_ex_data(ssl, g_state_index, (void *)async.get()) == 1) {
David Benjamind9e07012015-02-09 03:04:34 -0500120 async.release();
121 return true;
122 }
123 return false;
124}
125
David Benjamin87e4acd2015-04-02 19:57:35 -0400126static TestState *GetTestState(const SSL *ssl) {
David Benjamin2d445c02015-02-09 13:03:50 -0500127 return (TestState *)SSL_get_ex_data(ssl, g_state_index);
David Benjamin83f90402015-01-27 01:09:43 -0500128}
129
David Benjamina7f333d2015-02-09 02:37:18 -0500130static ScopedEVP_PKEY LoadPrivateKey(const std::string &file) {
131 ScopedBIO bio(BIO_new(BIO_s_file()));
132 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
133 return nullptr;
David Benjamina08e49d2014-08-24 01:46:07 -0400134 }
David Benjamina7f333d2015-02-09 02:37:18 -0500135 ScopedEVP_PKEY pkey(PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
David Benjamina08e49d2014-08-24 01:46:07 -0400136 return pkey;
137}
138
David Benjaminb4d65fd2015-05-29 17:11:21 -0400139static int AsyncPrivateKeyType(SSL *ssl) {
140 return EVP_PKEY_id(GetTestState(ssl)->private_key.get());
141}
142
143static int AsyncPrivateKeySupportsDigest(SSL *ssl, const EVP_MD *md) {
144 return EVP_PKEY_supports_digest(GetTestState(ssl)->private_key.get(), md);
145}
146
147static size_t AsyncPrivateKeyMaxSignatureLen(SSL *ssl) {
148 return EVP_PKEY_size(GetTestState(ssl)->private_key.get());
149}
150
151static ssl_private_key_result_t AsyncPrivateKeySign(
152 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
153 const EVP_MD *md, const uint8_t *in, size_t in_len) {
154 TestState *test_state = GetTestState(ssl);
155 if (!test_state->signature.empty()) {
156 fprintf(stderr, "AsyncPrivateKeySign called with operation pending.\n");
157 abort();
158 }
159
160 ScopedEVP_PKEY_CTX ctx(EVP_PKEY_CTX_new(test_state->private_key.get(),
161 nullptr));
162 if (!ctx) {
163 return ssl_private_key_failure;
164 }
165
166 // Write the signature into |test_state|.
167 size_t len = 0;
168 if (!EVP_PKEY_sign_init(ctx.get()) ||
169 !EVP_PKEY_CTX_set_signature_md(ctx.get(), md) ||
170 !EVP_PKEY_sign(ctx.get(), nullptr, &len, in, in_len)) {
171 return ssl_private_key_failure;
172 }
173 test_state->signature.resize(len);
174 if (!EVP_PKEY_sign(ctx.get(), bssl::vector_data(&test_state->signature), &len,
175 in, in_len)) {
176 return ssl_private_key_failure;
177 }
178 test_state->signature.resize(len);
179
180 // The signature will be released asynchronously in |AsyncPrivateKeySignComplete|.
181 return ssl_private_key_retry;
182}
183
184static ssl_private_key_result_t AsyncPrivateKeySignComplete(
185 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
186 TestState *test_state = GetTestState(ssl);
187 if (test_state->signature.empty()) {
188 fprintf(stderr,
189 "AsyncPrivateKeySignComplete called without operation pending.\n");
190 abort();
191 }
192
193 if (test_state->signature_retries < 2) {
194 // Only return the signature on the second attempt, to test both incomplete
195 // |sign| and |sign_complete|.
196 return ssl_private_key_retry;
197 }
198
199 if (max_out < test_state->signature.size()) {
200 fprintf(stderr, "Output buffer too small.\n");
201 return ssl_private_key_failure;
202 }
203 memcpy(out, bssl::vector_data(&test_state->signature),
204 test_state->signature.size());
205
206 test_state->signature.clear();
207 test_state->signature_retries = 0;
208 return ssl_private_key_success;
209}
210
211static const SSL_PRIVATE_KEY_METHOD g_async_private_key_method = {
212 AsyncPrivateKeyType,
213 AsyncPrivateKeySupportsDigest,
214 AsyncPrivateKeyMaxSignatureLen,
215 AsyncPrivateKeySign,
216 AsyncPrivateKeySignComplete,
217};
218
David Benjamin41fdbcd2015-02-09 03:13:35 -0500219static bool InstallCertificate(SSL *ssl) {
220 const TestConfig *config = GetConfigPtr(ssl);
David Benjaminb4d65fd2015-05-29 17:11:21 -0400221 TestState *test_state = GetTestState(ssl);
222 if (!config->key_file.empty()) {
223 if (config->use_async_private_key) {
224 test_state->private_key = LoadPrivateKey(config->key_file.c_str());
225 if (!test_state->private_key) {
226 return false;
227 }
228 SSL_set_private_key_method(ssl, &g_async_private_key_method);
229 } else if (!SSL_use_PrivateKey_file(ssl, config->key_file.c_str(),
230 SSL_FILETYPE_PEM)) {
231 return false;
232 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500233 }
234 if (!config->cert_file.empty() &&
235 !SSL_use_certificate_file(ssl, config->cert_file.c_str(),
236 SSL_FILETYPE_PEM)) {
237 return false;
238 }
239 return true;
240}
241
David Benjaminc273d2c2015-02-09 12:59:46 -0500242static int SelectCertificateCallback(const struct ssl_early_callback_ctx *ctx) {
David Benjamin5a593af2014-08-11 19:51:50 -0400243 const TestConfig *config = GetConfigPtr(ctx->ssl);
David Benjamin2d445c02015-02-09 13:03:50 -0500244 GetTestState(ctx->ssl)->early_callback_called = true;
David Benjamin5a593af2014-08-11 19:51:50 -0400245
David Benjamin6f5c0f42015-02-24 01:23:21 -0500246 if (!config->expected_server_name.empty()) {
247 const uint8_t *extension_data;
248 size_t extension_len;
249 CBS extension, server_name_list, host_name;
250 uint8_t name_type;
251
252 if (!SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
253 &extension_data,
254 &extension_len)) {
255 fprintf(stderr, "Could not find server_name extension.\n");
256 return -1;
257 }
258
259 CBS_init(&extension, extension_data, extension_len);
260 if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
261 CBS_len(&extension) != 0 ||
262 !CBS_get_u8(&server_name_list, &name_type) ||
263 name_type != TLSEXT_NAMETYPE_host_name ||
264 !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
265 CBS_len(&server_name_list) != 0) {
266 fprintf(stderr, "Could not decode server_name extension.\n");
267 return -1;
268 }
269
270 if (!CBS_mem_equal(&host_name,
271 (const uint8_t*)config->expected_server_name.data(),
272 config->expected_server_name.size())) {
273 fprintf(stderr, "Server name mismatch.\n");
274 }
David Benjamin7b030512014-07-08 17:30:11 -0400275 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400276
David Benjamin6f5c0f42015-02-24 01:23:21 -0500277 if (config->fail_early_callback) {
David Benjamin7b030512014-07-08 17:30:11 -0400278 return -1;
279 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400280
David Benjamin6f5c0f42015-02-24 01:23:21 -0500281 // Install the certificate in the early callback.
282 if (config->use_early_callback) {
283 if (config->async) {
284 // Install the certificate asynchronously.
285 return 0;
286 }
287 if (!InstallCertificate(ctx->ssl)) {
288 return -1;
289 }
David Benjamin7b030512014-07-08 17:30:11 -0400290 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400291 return 1;
292}
David Benjamin025b3d32014-07-01 19:53:04 -0400293
David Benjaminc273d2c2015-02-09 12:59:46 -0500294static int SkipVerify(int preverify_ok, X509_STORE_CTX *store_ctx) {
David Benjamin67666e72014-07-12 15:47:52 -0400295 return 1;
296}
297
David Benjaminc273d2c2015-02-09 12:59:46 -0500298static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
299 unsigned int *out_len, void *arg) {
David Benjamin5a593af2014-08-11 19:51:50 -0400300 const TestConfig *config = GetConfigPtr(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500301 if (config->advertise_npn.empty()) {
David Benjamin1f5f62b2014-07-12 16:18:02 -0400302 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500303 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400304
David Benjamin5a593af2014-08-11 19:51:50 -0400305 *out = (const uint8_t*)config->advertise_npn.data();
306 *out_len = config->advertise_npn.size();
David Benjamin1f5f62b2014-07-12 16:18:02 -0400307 return SSL_TLSEXT_ERR_OK;
308}
309
David Benjaminc273d2c2015-02-09 12:59:46 -0500310static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
David Benjamin8b368412015-03-14 01:54:17 -0400311 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin5a593af2014-08-11 19:51:50 -0400312 const TestConfig *config = GetConfigPtr(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500313 if (config->select_next_proto.empty()) {
David Benjamin7e3305e2014-07-28 14:52:32 -0400314 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500315 }
David Benjamin7e3305e2014-07-28 14:52:32 -0400316
David Benjamin5a593af2014-08-11 19:51:50 -0400317 *out = (uint8_t*)config->select_next_proto.data();
318 *outlen = config->select_next_proto.size();
David Benjamin7e3305e2014-07-28 14:52:32 -0400319 return SSL_TLSEXT_ERR_OK;
320}
321
David Benjaminc273d2c2015-02-09 12:59:46 -0500322static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
323 const uint8_t* in, unsigned inlen, void* arg) {
David Benjaminae2888f2014-09-06 12:58:58 -0400324 const TestConfig *config = GetConfigPtr(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500325 if (config->select_alpn.empty()) {
David Benjaminae2888f2014-09-06 12:58:58 -0400326 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500327 }
David Benjaminae2888f2014-09-06 12:58:58 -0400328
329 if (!config->expected_advertised_alpn.empty() &&
330 (config->expected_advertised_alpn.size() != inlen ||
331 memcmp(config->expected_advertised_alpn.data(),
332 in, inlen) != 0)) {
333 fprintf(stderr, "bad ALPN select callback inputs\n");
334 exit(1);
335 }
336
337 *out = (const uint8_t*)config->select_alpn.data();
338 *outlen = config->select_alpn.size();
339 return SSL_TLSEXT_ERR_OK;
340}
341
David Benjaminc273d2c2015-02-09 12:59:46 -0500342static unsigned PskClientCallback(SSL *ssl, const char *hint,
343 char *out_identity,
344 unsigned max_identity_len,
345 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin48cae082014-10-27 01:06:24 -0400346 const TestConfig *config = GetConfigPtr(ssl);
347
348 if (strcmp(hint ? hint : "", config->psk_identity.c_str()) != 0) {
349 fprintf(stderr, "Server PSK hint did not match.\n");
350 return 0;
351 }
352
353 // Account for the trailing '\0' for the identity.
354 if (config->psk_identity.size() >= max_identity_len ||
355 config->psk.size() > max_psk_len) {
356 fprintf(stderr, "PSK buffers too small\n");
357 return 0;
358 }
359
360 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
361 max_identity_len);
362 memcpy(out_psk, config->psk.data(), config->psk.size());
363 return config->psk.size();
364}
365
David Benjaminc273d2c2015-02-09 12:59:46 -0500366static unsigned PskServerCallback(SSL *ssl, const char *identity,
367 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin48cae082014-10-27 01:06:24 -0400368 const TestConfig *config = GetConfigPtr(ssl);
369
370 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
371 fprintf(stderr, "Client PSK identity did not match.\n");
372 return 0;
373 }
374
375 if (config->psk.size() > max_psk_len) {
376 fprintf(stderr, "PSK buffers too small\n");
377 return 0;
378 }
379
380 memcpy(out_psk, config->psk.data(), config->psk.size());
381 return config->psk.size();
382}
383
David Benjamin4d2e7ce2015-05-08 13:29:45 -0400384static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
David Benjamin6c2563e2015-04-03 03:47:47 -0400385 *out_clock = GetTestState(ssl)->clock;
David Benjamin377fc312015-01-26 00:22:12 -0500386}
387
David Benjaminc273d2c2015-02-09 12:59:46 -0500388static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
David Benjamin2d445c02015-02-09 13:03:50 -0500389 *out_pkey = GetTestState(ssl)->channel_id.release();
David Benjamind9e07012015-02-09 03:04:34 -0500390}
391
David Benjaminc273d2c2015-02-09 12:59:46 -0500392static int CertCallback(SSL *ssl, void *arg) {
David Benjamin2d445c02015-02-09 13:03:50 -0500393 if (!GetTestState(ssl)->cert_ready) {
David Benjamin41fdbcd2015-02-09 03:13:35 -0500394 return -1;
395 }
396 if (!InstallCertificate(ssl)) {
397 return 0;
398 }
399 return 1;
400}
401
David Benjaminc273d2c2015-02-09 12:59:46 -0500402static SSL_SESSION *GetSessionCallback(SSL *ssl, uint8_t *data, int len,
403 int *copy) {
David Benjamin2d445c02015-02-09 13:03:50 -0500404 TestState *async_state = GetTestState(ssl);
David Benjamin1b8b6912015-02-09 04:28:16 -0500405 if (async_state->session) {
406 *copy = 0;
407 return async_state->session.release();
408 } else if (async_state->pending_session) {
409 return SSL_magic_pending_session_ptr();
410 } else {
411 return NULL;
412 }
413}
414
Adam Langley524e7172015-02-20 16:04:00 -0800415static int DDoSCallback(const struct ssl_early_callback_ctx *early_context) {
416 const TestConfig *config = GetConfigPtr(early_context->ssl);
417 static int callback_num = 0;
418
419 callback_num++;
420 if (config->fail_ddos_callback ||
421 (config->fail_second_ddos_callback && callback_num == 2)) {
422 return 0;
423 }
424 return 1;
425}
426
David Benjamin87e4acd2015-04-02 19:57:35 -0400427static void InfoCallback(const SSL *ssl, int type, int val) {
428 if (type == SSL_CB_HANDSHAKE_DONE) {
429 if (GetConfigPtr(ssl)->handshake_never_done) {
430 fprintf(stderr, "handshake completed\n");
431 // Abort before any expected error code is printed, to ensure the overall
432 // test fails.
433 abort();
434 }
435 GetTestState(ssl)->handshake_done = true;
436 }
437}
438
David Benjaminba4594a2015-06-18 18:36:15 -0400439static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
440 GetTestState(ssl)->got_new_session = true;
441 // BoringSSL passes a reference to |session|.
442 SSL_SESSION_free(session);
443 return 1;
444}
445
David Benjamin87c8a642015-02-21 01:54:29 -0500446// Connect returns a new socket connected to localhost on |port| or -1 on
447// error.
448static int Connect(uint16_t port) {
449 int sock = socket(AF_INET, SOCK_STREAM, 0);
450 if (sock == -1) {
451 PrintSocketError("socket");
452 return -1;
453 }
454 int nodelay = 1;
455 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
456 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
457 PrintSocketError("setsockopt");
458 closesocket(sock);
459 return -1;
460 }
461 sockaddr_in sin;
462 memset(&sin, 0, sizeof(sin));
463 sin.sin_family = AF_INET;
464 sin.sin_port = htons(port);
465 if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
466 PrintSocketError("inet_pton");
467 closesocket(sock);
468 return -1;
469 }
470 if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
471 sizeof(sin)) != 0) {
472 PrintSocketError("connect");
473 closesocket(sock);
474 return -1;
475 }
476 return sock;
477}
478
479class SocketCloser {
480 public:
481 explicit SocketCloser(int sock) : sock_(sock) {}
482 ~SocketCloser() {
483 // Half-close and drain the socket before releasing it. This seems to be
484 // necessary for graceful shutdown on Windows. It will also avoid write
485 // failures in the test runner.
486#if defined(OPENSSL_WINDOWS)
487 shutdown(sock_, SD_SEND);
488#else
489 shutdown(sock_, SHUT_WR);
490#endif
491 while (true) {
492 char buf[1024];
493 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
494 break;
495 }
496 }
497 closesocket(sock_);
498 }
499
500 private:
501 const int sock_;
502};
503
David Benjaminc273d2c2015-02-09 12:59:46 -0500504static ScopedSSL_CTX SetupCtx(const TestConfig *config) {
David Benjamina7f333d2015-02-09 02:37:18 -0500505 ScopedSSL_CTX ssl_ctx(SSL_CTX_new(
506 config->is_dtls ? DTLS_method() : TLS_method()));
507 if (!ssl_ctx) {
508 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -0400509 }
510
David Benjamina7f333d2015-02-09 02:37:18 -0500511 if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), "ALL")) {
512 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -0400513 }
514
David Benjamina7f333d2015-02-09 02:37:18 -0500515 ScopedDH dh(DH_get_2048_256(NULL));
516 if (!dh || !SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
517 return nullptr;
David Benjaminf4e5c4e2014-08-02 17:35:45 -0400518 }
519
David Benjamin1b8b6912015-02-09 04:28:16 -0500520 if (config->async && config->is_server) {
521 // Disable the internal session cache. To test asynchronous session lookup,
522 // we use an external session cache.
523 SSL_CTX_set_session_cache_mode(
524 ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
David Benjaminc273d2c2015-02-09 12:59:46 -0500525 SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
David Benjamin1b8b6912015-02-09 04:28:16 -0500526 } else {
527 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
528 }
David Benjamin1d5c83e2014-07-22 19:20:02 -0400529
David Benjaminc273d2c2015-02-09 12:59:46 -0500530 ssl_ctx->select_certificate_cb = SelectCertificateCallback;
David Benjamin8f2c20e2014-07-09 09:30:38 -0400531
David Benjamin1f5f62b2014-07-12 16:18:02 -0400532 SSL_CTX_set_next_protos_advertised_cb(
David Benjaminc273d2c2015-02-09 12:59:46 -0500533 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400534 if (!config->select_next_proto.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500535 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
David Benjamina7f333d2015-02-09 02:37:18 -0500536 NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400537 }
538
539 if (!config->select_alpn.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500540 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -0400541 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400542
David Benjamina08e49d2014-08-24 01:46:07 -0400543 ssl_ctx->tlsext_channel_id_enabled_new = 1;
David Benjaminc273d2c2015-02-09 12:59:46 -0500544 SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
David Benjamina08e49d2014-08-24 01:46:07 -0400545
David Benjaminc273d2c2015-02-09 12:59:46 -0500546 ssl_ctx->current_time_cb = CurrentTimeCallback;
David Benjamin377fc312015-01-26 00:22:12 -0500547
David Benjamin87e4acd2015-04-02 19:57:35 -0400548 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
David Benjaminba4594a2015-06-18 18:36:15 -0400549 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
David Benjamin87e4acd2015-04-02 19:57:35 -0400550
David Benjamin1d5c83e2014-07-22 19:20:02 -0400551 return ssl_ctx;
David Benjamin1d5c83e2014-07-22 19:20:02 -0400552}
553
David Benjamin40f101b2015-02-20 11:23:42 -0500554// RetryAsync is called after a failed operation on |ssl| with return code
555// |ret|. If the operation should be retried, it simulates one asynchronous
David Benjamin6c2563e2015-04-03 03:47:47 -0400556// event and returns true. Otherwise it returns false.
557static bool RetryAsync(SSL *ssl, int ret) {
David Benjamin43ec06f2014-08-05 02:28:57 -0400558 // No error; don't retry.
559 if (ret >= 0) {
David Benjamin40f101b2015-02-20 11:23:42 -0500560 return false;
David Benjamin025b3d32014-07-01 19:53:04 -0400561 }
David Benjamin83f90402015-01-27 01:09:43 -0500562
David Benjamin6c2563e2015-04-03 03:47:47 -0400563 TestState *test_state = GetTestState(ssl);
564 if (test_state->clock_delta.tv_usec != 0 ||
565 test_state->clock_delta.tv_sec != 0) {
David Benjamin83f90402015-01-27 01:09:43 -0500566 // Process the timeout and retry.
David Benjamin6c2563e2015-04-03 03:47:47 -0400567 test_state->clock.tv_usec += test_state->clock_delta.tv_usec;
568 test_state->clock.tv_sec += test_state->clock.tv_usec / 1000000;
569 test_state->clock.tv_usec %= 1000000;
570 test_state->clock.tv_sec += test_state->clock_delta.tv_sec;
571 memset(&test_state->clock_delta, 0, sizeof(test_state->clock_delta));
David Benjamin83f90402015-01-27 01:09:43 -0500572
573 if (DTLSv1_handle_timeout(ssl) < 0) {
David Benjaminc565ebb2015-04-03 04:06:36 -0400574 fprintf(stderr, "Error retransmitting.\n");
David Benjamin40f101b2015-02-20 11:23:42 -0500575 return false;
David Benjamin83f90402015-01-27 01:09:43 -0500576 }
David Benjamin40f101b2015-02-20 11:23:42 -0500577 return true;
David Benjamin83f90402015-01-27 01:09:43 -0500578 }
579
David Benjamin43ec06f2014-08-05 02:28:57 -0400580 // See if we needed to read or write more. If so, allow one byte through on
581 // the appropriate end to maximally stress the state machine.
David Benjamind9e07012015-02-09 03:04:34 -0500582 switch (SSL_get_error(ssl, ret)) {
583 case SSL_ERROR_WANT_READ:
David Benjamin6c2563e2015-04-03 03:47:47 -0400584 AsyncBioAllowRead(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -0500585 return true;
David Benjamind9e07012015-02-09 03:04:34 -0500586 case SSL_ERROR_WANT_WRITE:
David Benjamin6c2563e2015-04-03 03:47:47 -0400587 AsyncBioAllowWrite(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -0500588 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -0500589 case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
590 ScopedEVP_PKEY pkey = LoadPrivateKey(GetConfigPtr(ssl)->send_channel_id);
591 if (!pkey) {
David Benjamin40f101b2015-02-20 11:23:42 -0500592 return false;
David Benjamin9d0847a2015-02-16 03:57:55 -0500593 }
David Benjamin6c2563e2015-04-03 03:47:47 -0400594 test_state->channel_id = std::move(pkey);
David Benjamin40f101b2015-02-20 11:23:42 -0500595 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -0500596 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500597 case SSL_ERROR_WANT_X509_LOOKUP:
David Benjamin6c2563e2015-04-03 03:47:47 -0400598 test_state->cert_ready = true;
David Benjamin40f101b2015-02-20 11:23:42 -0500599 return true;
David Benjamin1b8b6912015-02-09 04:28:16 -0500600 case SSL_ERROR_PENDING_SESSION:
David Benjamin6c2563e2015-04-03 03:47:47 -0400601 test_state->session = std::move(test_state->pending_session);
David Benjamin40f101b2015-02-20 11:23:42 -0500602 return true;
David Benjamin6f5c0f42015-02-24 01:23:21 -0500603 case SSL_ERROR_PENDING_CERTIFICATE:
604 // The handshake will resume without a second call to the early callback.
605 return InstallCertificate(ssl);
David Benjaminb4d65fd2015-05-29 17:11:21 -0400606 case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
607 test_state->signature_retries++;
608 return true;
David Benjamind9e07012015-02-09 03:04:34 -0500609 default:
David Benjamin40f101b2015-02-20 11:23:42 -0500610 return false;
David Benjamin025b3d32014-07-01 19:53:04 -0400611 }
David Benjamin025b3d32014-07-01 19:53:04 -0400612}
613
David Benjamin6c2563e2015-04-03 03:47:47 -0400614// DoRead reads from |ssl|, resolving any asynchronous operations. It returns
615// the result value of the final |SSL_read| call.
616static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
617 const TestConfig *config = GetConfigPtr(ssl);
618 int ret;
619 do {
620 ret = SSL_read(ssl, out, max_out);
621 } while (config->async && RetryAsync(ssl, ret));
622 return ret;
623}
624
625// WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
626// operations. It returns the result of the final |SSL_write| call.
627static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
628 const TestConfig *config = GetConfigPtr(ssl);
629 int ret;
630 do {
631 ret = SSL_write(ssl, in, in_len);
632 if (ret > 0) {
633 in += ret;
634 in_len -= ret;
635 }
636 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
637 return ret;
638}
639
David Benjamin91eab5c2015-06-18 18:35:46 -0400640// CheckHandshakeProperties checks, immediately after |ssl| completes its
641// initial handshake (or False Starts), whether all the properties are
642// consistent with the test configuration and invariants.
643static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
644 const TestConfig *config = GetConfigPtr(ssl);
645
646 if (SSL_get_current_cipher(ssl) == nullptr) {
647 fprintf(stderr, "null cipher after handshake\n");
648 return false;
649 }
650
651 if (is_resume &&
652 (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
653 fprintf(stderr, "session was%s reused\n",
654 SSL_session_reused(ssl) ? "" : " not");
655 return false;
656 }
657
658 bool expect_handshake_done = is_resume || !config->false_start;
659 if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
660 fprintf(stderr, "handshake was%s completed\n",
661 GetTestState(ssl)->handshake_done ? "" : " not");
662 return false;
663 }
664
David Benjaminba4594a2015-06-18 18:36:15 -0400665 if (expect_handshake_done && !config->is_server) {
666 bool expect_new_session =
667 !config->expect_no_session &&
668 (!SSL_session_reused(ssl) || config->expect_ticket_renewal);
669 if (expect_new_session != GetTestState(ssl)->got_new_session) {
670 fprintf(stderr,
671 "new session was%s established, but we expected the opposite\n",
672 GetTestState(ssl)->got_new_session ? "" : " not");
673 return false;
674 }
675 }
676
David Benjamin91eab5c2015-06-18 18:35:46 -0400677 if (config->is_server && !GetTestState(ssl)->early_callback_called) {
678 fprintf(stderr, "early callback not called\n");
679 return false;
680 }
681
682 if (!config->expected_server_name.empty()) {
683 const char *server_name =
684 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
685 if (server_name != config->expected_server_name) {
686 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
687 server_name, config->expected_server_name.c_str());
688 return false;
689 }
690 }
691
692 if (!config->expected_certificate_types.empty()) {
693 uint8_t *certificate_types;
694 int num_certificate_types =
695 SSL_get0_certificate_types(ssl, &certificate_types);
696 if (num_certificate_types !=
697 (int)config->expected_certificate_types.size() ||
698 memcmp(certificate_types,
699 config->expected_certificate_types.data(),
700 num_certificate_types) != 0) {
701 fprintf(stderr, "certificate types mismatch\n");
702 return false;
703 }
704 }
705
706 if (!config->expected_next_proto.empty()) {
707 const uint8_t *next_proto;
708 unsigned next_proto_len;
709 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
710 if (next_proto_len != config->expected_next_proto.size() ||
711 memcmp(next_proto, config->expected_next_proto.data(),
712 next_proto_len) != 0) {
713 fprintf(stderr, "negotiated next proto mismatch\n");
714 return false;
715 }
716 }
717
718 if (!config->expected_alpn.empty()) {
719 const uint8_t *alpn_proto;
720 unsigned alpn_proto_len;
721 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
722 if (alpn_proto_len != config->expected_alpn.size() ||
723 memcmp(alpn_proto, config->expected_alpn.data(),
724 alpn_proto_len) != 0) {
725 fprintf(stderr, "negotiated alpn proto mismatch\n");
726 return false;
727 }
728 }
729
730 if (!config->expected_channel_id.empty()) {
731 uint8_t channel_id[64];
732 if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
733 fprintf(stderr, "no channel id negotiated\n");
734 return false;
735 }
736 if (config->expected_channel_id.size() != 64 ||
737 memcmp(config->expected_channel_id.data(),
738 channel_id, 64) != 0) {
739 fprintf(stderr, "channel id mismatch\n");
740 return false;
741 }
742 }
743
744 if (config->expect_extended_master_secret) {
745 if (!ssl->session->extended_master_secret) {
746 fprintf(stderr, "No EMS for session when expected");
747 return false;
748 }
749 }
750
751 if (!config->expected_ocsp_response.empty()) {
752 const uint8_t *data;
753 size_t len;
754 SSL_get0_ocsp_response(ssl, &data, &len);
755 if (config->expected_ocsp_response.size() != len ||
756 memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
757 fprintf(stderr, "OCSP response mismatch\n");
758 return false;
759 }
760 }
761
762 if (!config->expected_signed_cert_timestamps.empty()) {
763 const uint8_t *data;
764 size_t len;
765 SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
766 if (config->expected_signed_cert_timestamps.size() != len ||
767 memcmp(config->expected_signed_cert_timestamps.data(),
768 data, len) != 0) {
769 fprintf(stderr, "SCT list mismatch\n");
770 return false;
771 }
772 }
773
774 if (!config->is_server) {
775 /* Clients should expect a peer certificate chain iff this was not a PSK
776 * cipher suite. */
777 if (config->psk.empty()) {
778 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
779 fprintf(stderr, "Missing peer certificate chain!\n");
780 return false;
781 }
782 } else if (SSL_get_peer_cert_chain(ssl) != nullptr) {
783 fprintf(stderr, "Unexpected peer certificate chain!\n");
784 return false;
785 }
786 }
787 return true;
788}
789
David Benjamin87c8a642015-02-21 01:54:29 -0500790// DoExchange runs a test SSL exchange against the peer. On success, it returns
791// true and sets |*out_session| to the negotiated SSL session. If the test is a
792// resumption attempt, |is_resume| is true and |session| is the session from the
793// previous exchange.
David Benjamin40f101b2015-02-20 11:23:42 -0500794static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx,
795 const TestConfig *config, bool is_resume,
David Benjamin87c8a642015-02-21 01:54:29 -0500796 SSL_SESSION *session) {
David Benjamina7f333d2015-02-09 02:37:18 -0500797 ScopedSSL ssl(SSL_new(ssl_ctx));
798 if (!ssl) {
David Benjamin40f101b2015-02-20 11:23:42 -0500799 return false;
David Benjamin025b3d32014-07-01 19:53:04 -0400800 }
801
David Benjamina7f333d2015-02-09 02:37:18 -0500802 if (!SetConfigPtr(ssl.get(), config) ||
David Benjamin2d445c02015-02-09 13:03:50 -0500803 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
David Benjamin40f101b2015-02-20 11:23:42 -0500804 return false;
Adam Langley69a01602014-11-17 17:26:55 -0800805 }
David Benjamin5a593af2014-08-11 19:51:50 -0400806
Adam Langley5f0efe02015-02-20 13:03:16 -0800807 if (config->fallback_scsv &&
808 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
809 return false;
David Benjamin025b3d32014-07-01 19:53:04 -0400810 }
David Benjamin6f5c0f42015-02-24 01:23:21 -0500811 if (!config->use_early_callback) {
812 if (config->async) {
813 // TODO(davidben): Also test |s->ctx->client_cert_cb| on the client.
814 SSL_set_cert_cb(ssl.get(), CertCallback, NULL);
815 } else if (!InstallCertificate(ssl.get())) {
816 return false;
817 }
David Benjamin5a593af2014-08-11 19:51:50 -0400818 }
819 if (config->require_any_client_certificate) {
David Benjamina7f333d2015-02-09 02:37:18 -0500820 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
David Benjaminc273d2c2015-02-09 12:59:46 -0500821 SkipVerify);
David Benjamin5a593af2014-08-11 19:51:50 -0400822 }
823 if (config->false_start) {
David Benjamined7c4752015-02-16 19:16:46 -0500824 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
David Benjamin5a593af2014-08-11 19:51:50 -0400825 }
826 if (config->cbc_record_splitting) {
David Benjamina7f333d2015-02-09 02:37:18 -0500827 SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
David Benjamin5a593af2014-08-11 19:51:50 -0400828 }
829 if (config->partial_write) {
David Benjamina7f333d2015-02-09 02:37:18 -0500830 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
David Benjamin5a593af2014-08-11 19:51:50 -0400831 }
832 if (config->no_tls12) {
David Benjamina7f333d2015-02-09 02:37:18 -0500833 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
David Benjamin5a593af2014-08-11 19:51:50 -0400834 }
835 if (config->no_tls11) {
David Benjamina7f333d2015-02-09 02:37:18 -0500836 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
David Benjamin5a593af2014-08-11 19:51:50 -0400837 }
838 if (config->no_tls1) {
David Benjamina7f333d2015-02-09 02:37:18 -0500839 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
David Benjamin5a593af2014-08-11 19:51:50 -0400840 }
841 if (config->no_ssl3) {
David Benjamina7f333d2015-02-09 02:37:18 -0500842 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
David Benjamin5a593af2014-08-11 19:51:50 -0400843 }
David Benjamin5c24a1d2014-08-31 00:59:27 -0400844 if (config->tls_d5_bug) {
David Benjamina7f333d2015-02-09 02:37:18 -0500845 SSL_set_options(ssl.get(), SSL_OP_TLS_D5_BUG);
David Benjamin5c24a1d2014-08-31 00:59:27 -0400846 }
David Benjaminca6554b2014-11-08 12:31:52 -0500847 if (config->allow_unsafe_legacy_renegotiation) {
David Benjamina7f333d2015-02-09 02:37:18 -0500848 SSL_set_options(ssl.get(), SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
David Benjaminca6554b2014-11-08 12:31:52 -0500849 }
David Benjamincff0b902015-05-15 23:09:47 -0400850 if (config->no_legacy_server_connect) {
851 SSL_clear_options(ssl.get(), SSL_OP_LEGACY_SERVER_CONNECT);
852 }
David Benjamina08e49d2014-08-24 01:46:07 -0400853 if (!config->expected_channel_id.empty()) {
David Benjamina7f333d2015-02-09 02:37:18 -0500854 SSL_enable_tls_channel_id(ssl.get());
David Benjamina08e49d2014-08-24 01:46:07 -0400855 }
856 if (!config->send_channel_id.empty()) {
David Benjamina7f333d2015-02-09 02:37:18 -0500857 SSL_enable_tls_channel_id(ssl.get());
David Benjamind9e07012015-02-09 03:04:34 -0500858 if (!config->async) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500859 // The async case will be supplied by |ChannelIdCallback|.
David Benjamind9e07012015-02-09 03:04:34 -0500860 ScopedEVP_PKEY pkey = LoadPrivateKey(config->send_channel_id);
861 if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -0500862 return false;
David Benjamind9e07012015-02-09 03:04:34 -0500863 }
David Benjamina08e49d2014-08-24 01:46:07 -0400864 }
David Benjamina08e49d2014-08-24 01:46:07 -0400865 }
David Benjamin9d0847a2015-02-16 03:57:55 -0500866 if (!config->host_name.empty() &&
867 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -0500868 return false;
David Benjamine78bfde2014-09-06 12:45:15 -0400869 }
David Benjamin9d0847a2015-02-16 03:57:55 -0500870 if (!config->advertise_alpn.empty() &&
871 SSL_set_alpn_protos(ssl.get(),
872 (const uint8_t *)config->advertise_alpn.data(),
873 config->advertise_alpn.size()) != 0) {
David Benjamin40f101b2015-02-20 11:23:42 -0500874 return false;
David Benjaminae2888f2014-09-06 12:58:58 -0400875 }
David Benjamin48cae082014-10-27 01:06:24 -0400876 if (!config->psk.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -0500877 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
878 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
David Benjamin48cae082014-10-27 01:06:24 -0400879 }
David Benjamin61f95272014-11-25 01:55:35 -0500880 if (!config->psk_identity.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -0500881 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -0500882 return false;
David Benjamin48cae082014-10-27 01:06:24 -0400883 }
David Benjamin61f95272014-11-25 01:55:35 -0500884 if (!config->srtp_profiles.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -0500885 !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -0500886 return false;
David Benjamin61f95272014-11-25 01:55:35 -0500887 }
888 if (config->enable_ocsp_stapling &&
David Benjamina7f333d2015-02-09 02:37:18 -0500889 !SSL_enable_ocsp_stapling(ssl.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -0500890 return false;
David Benjamin61f95272014-11-25 01:55:35 -0500891 }
892 if (config->enable_signed_cert_timestamps &&
David Benjamina7f333d2015-02-09 02:37:18 -0500893 !SSL_enable_signed_cert_timestamps(ssl.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -0500894 return false;
David Benjaminca6c8262014-11-15 19:06:08 -0500895 }
David Benjamina7f333d2015-02-09 02:37:18 -0500896 SSL_enable_fastradio_padding(ssl.get(), config->fastradio_padding);
David Benjamin1eb367c2014-12-12 18:17:51 -0500897 if (config->min_version != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -0500898 SSL_set_min_version(ssl.get(), (uint16_t)config->min_version);
David Benjamin1eb367c2014-12-12 18:17:51 -0500899 }
900 if (config->max_version != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -0500901 SSL_set_max_version(ssl.get(), (uint16_t)config->max_version);
David Benjamin1eb367c2014-12-12 18:17:51 -0500902 }
David Benjamin13be1de2015-01-11 16:29:36 -0500903 if (config->mtu != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -0500904 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
905 SSL_set_mtu(ssl.get(), config->mtu);
David Benjamin13be1de2015-01-11 16:29:36 -0500906 }
Adam Langley524e7172015-02-20 16:04:00 -0800907 if (config->install_ddos_callback) {
908 SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
909 }
David Benjamin67d1fb52015-03-16 15:16:23 -0400910 if (!config->cipher.empty() &&
911 !SSL_set_cipher_list(ssl.get(), config->cipher.c_str())) {
912 return false;
913 }
David Benjamin897e5e02015-05-12 17:03:54 -0400914 if (!config->reject_peer_renegotiations) {
915 /* Renegotiations are disabled by default. */
916 SSL_set_reject_peer_renegotiations(ssl.get(), 0);
David Benjaminb16346b2015-04-08 19:16:58 -0400917 }
David Benjamin025b3d32014-07-01 19:53:04 -0400918
David Benjamin87c8a642015-02-21 01:54:29 -0500919 int sock = Connect(config->port);
920 if (sock == -1) {
921 return false;
922 }
923 SocketCloser closer(sock);
924
925 ScopedBIO bio(BIO_new_socket(sock, BIO_NOCLOSE));
David Benjamina7f333d2015-02-09 02:37:18 -0500926 if (!bio) {
David Benjamin40f101b2015-02-20 11:23:42 -0500927 return false;
David Benjamin43ec06f2014-08-05 02:28:57 -0400928 }
David Benjamin6fd297b2014-08-11 18:43:38 -0400929 if (config->is_dtls) {
David Benjamin6c2563e2015-04-03 03:47:47 -0400930 ScopedBIO packeted =
931 PacketedBioCreate(&GetTestState(ssl.get())->clock_delta);
David Benjamina7f333d2015-02-09 02:37:18 -0500932 BIO_push(packeted.get(), bio.release());
933 bio = std::move(packeted);
David Benjamin6fd297b2014-08-11 18:43:38 -0400934 }
David Benjamin5a593af2014-08-11 19:51:50 -0400935 if (config->async) {
David Benjamina7f333d2015-02-09 02:37:18 -0500936 ScopedBIO async_scoped =
David Benjaminc273d2c2015-02-09 12:59:46 -0500937 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
David Benjamina7f333d2015-02-09 02:37:18 -0500938 BIO_push(async_scoped.get(), bio.release());
David Benjamin6c2563e2015-04-03 03:47:47 -0400939 GetTestState(ssl.get())->async_bio = async_scoped.get();
David Benjamina7f333d2015-02-09 02:37:18 -0500940 bio = std::move(async_scoped);
David Benjamin43ec06f2014-08-05 02:28:57 -0400941 }
David Benjamina7f333d2015-02-09 02:37:18 -0500942 SSL_set_bio(ssl.get(), bio.get(), bio.get());
943 bio.release(); // SSL_set_bio takes ownership.
David Benjamin43ec06f2014-08-05 02:28:57 -0400944
David Benjamin1d5c83e2014-07-22 19:20:02 -0400945 if (session != NULL) {
David Benjamin1b8b6912015-02-09 04:28:16 -0500946 if (!config->is_server) {
947 if (SSL_set_session(ssl.get(), session) != 1) {
David Benjamin40f101b2015-02-20 11:23:42 -0500948 return false;
David Benjamin1b8b6912015-02-09 04:28:16 -0500949 }
950 } else if (config->async) {
951 // The internal session cache is disabled, so install the session
952 // manually.
David Benjamin2d445c02015-02-09 13:03:50 -0500953 GetTestState(ssl.get())->pending_session.reset(
David Benjamin1b8b6912015-02-09 04:28:16 -0500954 SSL_SESSION_up_ref(session));
David Benjamin1d5c83e2014-07-22 19:20:02 -0400955 }
956 }
957
David Benjamina07c0fc2015-05-13 13:19:42 -0400958 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
959 fprintf(stderr, "non-null cipher before handshake\n");
960 return false;
961 }
962
David Benjamin1d5c83e2014-07-22 19:20:02 -0400963 int ret;
David Benjamine0e7d0d2015-02-08 19:33:25 -0500964 if (config->implicit_handshake) {
David Benjamin5a593af2014-08-11 19:51:50 -0400965 if (config->is_server) {
David Benjamina7f333d2015-02-09 02:37:18 -0500966 SSL_set_accept_state(ssl.get());
David Benjamin43ec06f2014-08-05 02:28:57 -0400967 } else {
David Benjamina7f333d2015-02-09 02:37:18 -0500968 SSL_set_connect_state(ssl.get());
David Benjamin43ec06f2014-08-05 02:28:57 -0400969 }
David Benjamine0e7d0d2015-02-08 19:33:25 -0500970 } else {
971 do {
972 if (config->is_server) {
David Benjamina7f333d2015-02-09 02:37:18 -0500973 ret = SSL_accept(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -0500974 } else {
David Benjamina7f333d2015-02-09 02:37:18 -0500975 ret = SSL_connect(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -0500976 }
David Benjamin6c2563e2015-04-03 03:47:47 -0400977 } while (config->async && RetryAsync(ssl.get(), ret));
David Benjamin91eab5c2015-06-18 18:35:46 -0400978 if (ret != 1 ||
979 !CheckHandshakeProperties(ssl.get(), is_resume)) {
David Benjamin40f101b2015-02-20 11:23:42 -0500980 return false;
David Benjamine0e7d0d2015-02-08 19:33:25 -0500981 }
David Benjamin025b3d32014-07-01 19:53:04 -0400982
David Benjaminba4594a2015-06-18 18:36:15 -0400983 // Reset the state to assert later that the callback isn't called in
984 // renegotations.
985 GetTestState(ssl.get())->got_new_session = false;
David Benjamin61f95272014-11-25 01:55:35 -0500986 }
987
David Benjaminc565ebb2015-04-03 04:06:36 -0400988 if (config->export_keying_material > 0) {
989 std::vector<uint8_t> result(
990 static_cast<size_t>(config->export_keying_material));
991 if (!SSL_export_keying_material(
992 ssl.get(), result.data(), result.size(),
993 config->export_label.data(), config->export_label.size(),
994 reinterpret_cast<const uint8_t*>(config->export_context.data()),
995 config->export_context.size(), config->use_export_context)) {
996 fprintf(stderr, "failed to export keying material\n");
997 return false;
998 }
999 if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1000 return false;
1001 }
1002 }
1003
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001004 if (config->tls_unique) {
1005 uint8_t tls_unique[16];
1006 size_t tls_unique_len;
1007 if (!SSL_get_tls_unique(ssl.get(), tls_unique, &tls_unique_len,
1008 sizeof(tls_unique))) {
1009 fprintf(stderr, "failed to get tls-unique\n");
1010 return false;
1011 }
1012
1013 if (tls_unique_len != 12) {
1014 fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
1015 static_cast<unsigned>(tls_unique_len));
1016 return false;
1017 }
1018
1019 if (WriteAll(ssl.get(), tls_unique, tls_unique_len) < 0) {
1020 return false;
1021 }
1022 }
1023
David Benjamin5a593af2014-08-11 19:51:50 -04001024 if (config->write_different_record_sizes) {
David Benjamin6fd297b2014-08-11 18:43:38 -04001025 if (config->is_dtls) {
1026 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001027 return false;
David Benjamin6fd297b2014-08-11 18:43:38 -04001028 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001029 // This mode writes a number of different record sizes in an attempt to
1030 // trip up the CBC record splitting code.
1031 uint8_t buf[32769];
1032 memset(buf, 0x42, sizeof(buf));
1033 static const size_t kRecordSizes[] = {
1034 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
1035 for (size_t i = 0; i < sizeof(kRecordSizes) / sizeof(kRecordSizes[0]);
1036 i++) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07001037 const size_t len = kRecordSizes[i];
Kenny Root7fdeaf12014-08-05 15:23:37 -07001038 if (len > sizeof(buf)) {
1039 fprintf(stderr, "Bad kRecordSizes value.\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001040 return false;
Kenny Root7fdeaf12014-08-05 15:23:37 -07001041 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001042 if (WriteAll(ssl.get(), buf, len) < 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001043 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001044 }
1045 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001046 } else {
David Benjamine58c4f52014-08-24 03:47:07 -04001047 if (config->shim_writes_first) {
David Benjamin6c2563e2015-04-03 03:47:47 -04001048 if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1049 5) < 0) {
1050 return false;
1051 }
David Benjamine58c4f52014-08-24 03:47:07 -04001052 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001053 for (;;) {
1054 uint8_t buf[512];
David Benjamin6c2563e2015-04-03 03:47:47 -04001055 int n = DoRead(ssl.get(), buf, sizeof(buf));
David Benjamina7f333d2015-02-09 02:37:18 -05001056 int err = SSL_get_error(ssl.get(), n);
David Benjamin9a38e922015-01-22 16:06:11 -05001057 if (err == SSL_ERROR_ZERO_RETURN ||
1058 (n == 0 && err == SSL_ERROR_SYSCALL)) {
1059 if (n != 0) {
1060 fprintf(stderr, "Invalid SSL_get_error output\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001061 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001062 }
David Benjaminc273d2c2015-02-09 12:59:46 -05001063 // Accept shutdowns with or without close_notify.
1064 // TODO(davidben): Write tests which distinguish these two cases.
David Benjamin9a38e922015-01-22 16:06:11 -05001065 break;
1066 } else if (err != SSL_ERROR_NONE) {
1067 if (n > 0) {
1068 fprintf(stderr, "Invalid SSL_get_error output\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001069 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001070 }
David Benjamin40f101b2015-02-20 11:23:42 -05001071 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001072 }
David Benjaminc273d2c2015-02-09 12:59:46 -05001073 // Successfully read data.
David Benjamin9a38e922015-01-22 16:06:11 -05001074 if (n <= 0) {
1075 fprintf(stderr, "Invalid SSL_get_error output\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001076 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05001077 }
David Benjamin87e4acd2015-04-02 19:57:35 -04001078
1079 // After a successful read, with or without False Start, the handshake
1080 // must be complete.
1081 if (!GetTestState(ssl.get())->handshake_done) {
1082 fprintf(stderr, "handshake was not completed after SSL_read\n");
1083 return false;
1084 }
1085
David Benjamin9a38e922015-01-22 16:06:11 -05001086 for (int i = 0; i < n; i++) {
1087 buf[i] ^= 0xff;
1088 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001089 if (WriteAll(ssl.get(), buf, n) < 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001090 return false;
Kenny Root7fdeaf12014-08-05 15:23:37 -07001091 }
1092 }
David Benjamin025b3d32014-07-01 19:53:04 -04001093 }
1094
David Benjaminba4594a2015-06-18 18:36:15 -04001095 if (!config->is_server && !config->false_start &&
1096 !config->implicit_handshake &&
1097 GetTestState(ssl.get())->got_new_session) {
1098 fprintf(stderr, "new session was established after the handshake\n");
1099 return false;
1100 }
1101
David Benjamin1d5c83e2014-07-22 19:20:02 -04001102 if (out_session) {
David Benjamina7f333d2015-02-09 02:37:18 -05001103 out_session->reset(SSL_get1_session(ssl.get()));
David Benjamin1d5c83e2014-07-22 19:20:02 -04001104 }
1105
David Benjamina7f333d2015-02-09 02:37:18 -05001106 SSL_shutdown(ssl.get());
David Benjamin40f101b2015-02-20 11:23:42 -05001107 return true;
David Benjamin025b3d32014-07-01 19:53:04 -04001108}
David Benjamin1d5c83e2014-07-22 19:20:02 -04001109
1110int main(int argc, char **argv) {
David Benjamin87c8a642015-02-21 01:54:29 -05001111#if defined(OPENSSL_WINDOWS)
1112 /* Initialize Winsock. */
1113 WORD wsa_version = MAKEWORD(2, 2);
1114 WSADATA wsa_data;
1115 int wsa_err = WSAStartup(wsa_version, &wsa_data);
1116 if (wsa_err != 0) {
1117 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1118 return 1;
1119 }
1120 if (wsa_data.wVersion != wsa_version) {
1121 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1122 return 1;
1123 }
1124#else
David Benjamin1d5c83e2014-07-22 19:20:02 -04001125 signal(SIGPIPE, SIG_IGN);
Adam Langleyded93582014-07-31 15:23:51 -07001126#endif
David Benjamin1d5c83e2014-07-22 19:20:02 -04001127
David Benjamin5a593af2014-08-11 19:51:50 -04001128 if (!SSL_library_init()) {
1129 return 1;
1130 }
David Benjamind9e07012015-02-09 03:04:34 -05001131 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
David Benjamin2d445c02015-02-09 13:03:50 -05001132 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
David Benjamin6c2563e2015-04-03 03:47:47 -04001133 if (g_config_index < 0 || g_state_index < 0) {
David Benjaminae3e4872014-11-18 21:52:26 -05001134 return 1;
1135 }
David Benjamin5a593af2014-08-11 19:51:50 -04001136
1137 TestConfig config;
1138 if (!ParseConfig(argc - 1, argv + 1, &config)) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001139 return Usage(argv[0]);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001140 }
1141
David Benjaminc273d2c2015-02-09 12:59:46 -05001142 ScopedSSL_CTX ssl_ctx = SetupCtx(&config);
David Benjamina7f333d2015-02-09 02:37:18 -05001143 if (!ssl_ctx) {
Brian Smith83a82982015-04-09 16:21:10 -10001144 ERR_print_errors_fp(stderr);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001145 return 1;
1146 }
1147
David Benjamina7f333d2015-02-09 02:37:18 -05001148 ScopedSSL_SESSION session;
David Benjamin40f101b2015-02-20 11:23:42 -05001149 if (!DoExchange(&session, ssl_ctx.get(), &config, false /* is_resume */,
David Benjamin87c8a642015-02-21 01:54:29 -05001150 NULL /* session */)) {
Brian Smith83a82982015-04-09 16:21:10 -10001151 ERR_print_errors_fp(stderr);
David Benjamin40f101b2015-02-20 11:23:42 -05001152 return 1;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001153 }
1154
David Benjamin40f101b2015-02-20 11:23:42 -05001155 if (config.resume &&
1156 !DoExchange(NULL, ssl_ctx.get(), &config, true /* is_resume */,
David Benjamin87c8a642015-02-21 01:54:29 -05001157 session.get())) {
Brian Smith83a82982015-04-09 16:21:10 -10001158 ERR_print_errors_fp(stderr);
David Benjamin40f101b2015-02-20 11:23:42 -05001159 return 1;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001160 }
1161
David Benjamina7f333d2015-02-09 02:37:18 -05001162 return 0;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001163}