blob: f7bcb0fd1fa4b7d8d590d36f1267a1d576b03bc6 [file] [log] [blame]
David Benjamin025b3d32014-07-01 19:53:04 -04001/* Copyright (c) 2014, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
David Benjamin4cc36ad2015-12-19 14:23:26 -050015#if !defined(__STDC_FORMAT_MACROS)
16#define __STDC_FORMAT_MACROS
17#endif
18
Adam Langleyded93582014-07-31 15:23:51 -070019#include <openssl/base.h>
20
21#if !defined(OPENSSL_WINDOWS)
David Benjamin025b3d32014-07-01 19:53:04 -040022#include <arpa/inet.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040023#include <netinet/in.h>
David Benjamin87c8a642015-02-21 01:54:29 -050024#include <netinet/tcp.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040025#include <signal.h>
26#include <sys/socket.h>
David Benjamin0abd6f22015-12-04 21:49:53 -050027#include <sys/time.h>
David Benjamin8f2c20e2014-07-09 09:30:38 -040028#include <unistd.h>
David Benjamin87c8a642015-02-21 01:54:29 -050029#else
30#include <io.h>
David Benjamina353cdb2016-06-09 16:48:33 -040031OPENSSL_MSVC_PRAGMA(warning(push, 3))
Adam Langley3e719312015-03-20 16:32:23 -070032#include <winsock2.h>
33#include <ws2tcpip.h>
David Benjamina353cdb2016-06-09 16:48:33 -040034OPENSSL_MSVC_PRAGMA(warning(pop))
David Benjamin87c8a642015-02-21 01:54:29 -050035
David Benjamin4fec04b2016-10-10 14:56:47 -040036OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
Adam Langleyded93582014-07-31 15:23:51 -070037#endif
38
David Benjamin585d7a42016-06-02 14:58:00 -040039#include <assert.h>
David Benjamin4cc36ad2015-12-19 14:23:26 -050040#include <inttypes.h>
Adam Langley2b2d66d2015-01-30 17:08:37 -080041#include <string.h>
David Benjamin025b3d32014-07-01 19:53:04 -040042
David Benjaminabbbee12016-10-31 19:20:42 -040043#include <openssl/aead.h>
David Benjamin025b3d32014-07-01 19:53:04 -040044#include <openssl/bio.h>
David Benjamin48cae082014-10-27 01:06:24 -040045#include <openssl/buf.h>
David Benjamin8f2c20e2014-07-09 09:30:38 -040046#include <openssl/bytestring.h>
David Benjamind98452d2015-06-16 14:16:23 -040047#include <openssl/cipher.h>
David Benjamin7a1eefd2015-10-17 23:39:22 -040048#include <openssl/crypto.h>
Matt Braithwaited17d74d2016-08-17 20:10:28 -070049#include <openssl/dh.h>
David Benjaminf0e935d2016-09-06 18:10:19 -040050#include <openssl/digest.h>
Brian Smith83a82982015-04-09 16:21:10 -100051#include <openssl/err.h>
Matt Braithwaited17d74d2016-08-17 20:10:28 -070052#include <openssl/evp.h>
David Benjamind98452d2015-06-16 14:16:23 -040053#include <openssl/hmac.h>
David Benjamin98193672016-03-25 18:07:11 -040054#include <openssl/nid.h>
David Benjamind98452d2015-06-16 14:16:23 -040055#include <openssl/rand.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040056#include <openssl/ssl.h>
Matt Braithwaited17d74d2016-08-17 20:10:28 -070057#include <openssl/x509.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040058
David Benjamin45fb1be2015-03-22 16:31:27 -040059#include <memory>
Steven Valdez0d62f262015-09-04 12:41:04 -040060#include <string>
David Benjaminc565ebb2015-04-03 04:06:36 -040061#include <vector>
David Benjamin45fb1be2015-03-22 16:31:27 -040062
Steven Valdezcb966542016-08-17 16:56:14 -040063#include "../../crypto/internal.h"
David Benjamin43ec06f2014-08-05 02:28:57 -040064#include "async_bio.h"
David Benjamin6fd297b2014-08-11 18:43:38 -040065#include "packeted_bio.h"
David Benjamin5a593af2014-08-11 19:51:50 -040066#include "test_config.h"
David Benjamin43ec06f2014-08-05 02:28:57 -040067
David Benjamin87c8a642015-02-21 01:54:29 -050068
Adam Langleyd519bf62016-12-12 11:16:44 -080069static CRYPTO_BUFFER_POOL *g_pool = nullptr;
70
David Benjamin87c8a642015-02-21 01:54:29 -050071#if !defined(OPENSSL_WINDOWS)
72static int closesocket(int sock) {
73 return close(sock);
74}
75
76static void PrintSocketError(const char *func) {
77 perror(func);
78}
79#else
80static void PrintSocketError(const char *func) {
81 fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
82}
83#endif
84
David Benjaminc273d2c2015-02-09 12:59:46 -050085static int Usage(const char *program) {
David Benjamina7f333d2015-02-09 02:37:18 -050086 fprintf(stderr, "Usage: %s [flags...]\n", program);
David Benjamin1d5c83e2014-07-22 19:20:02 -040087 return 1;
88}
David Benjamin025b3d32014-07-01 19:53:04 -040089
David Benjamin2d445c02015-02-09 13:03:50 -050090struct TestState {
David Benjamin6c2563e2015-04-03 03:47:47 -040091 // async_bio is async BIO which pauses reads and writes.
92 BIO *async_bio = nullptr;
David Benjamin585d7a42016-06-02 14:58:00 -040093 // packeted_bio is the packeted BIO which simulates read timeouts.
94 BIO *packeted_bio = nullptr;
Matt Braithwaited17d74d2016-08-17 20:10:28 -070095 bssl::UniquePtr<EVP_PKEY> channel_id;
David Benjamin0d4db502015-03-23 18:46:05 -040096 bool cert_ready = false;
Matt Braithwaited17d74d2016-08-17 20:10:28 -070097 bssl::UniquePtr<SSL_SESSION> session;
98 bssl::UniquePtr<SSL_SESSION> pending_session;
David Benjamin0d4db502015-03-23 18:46:05 -040099 bool early_callback_called = false;
David Benjamin87e4acd2015-04-02 19:57:35 -0400100 bool handshake_done = false;
David Benjaminb4d65fd2015-05-29 17:11:21 -0400101 // private_key is the underlying private key used when testing custom keys.
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700102 bssl::UniquePtr<EVP_PKEY> private_key;
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700103 std::vector<uint8_t> private_key_result;
104 // private_key_retries is the number of times an asynchronous private key
105 // operation has been retried.
106 unsigned private_key_retries = 0;
David Benjaminba4594a2015-06-18 18:36:15 -0400107 bool got_new_session = false;
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700108 bssl::UniquePtr<SSL_SESSION> new_session;
David Benjamin25fe85b2016-08-09 20:00:32 -0400109 bool ticket_decrypt_done = false;
110 bool alpn_select_done = false;
Steven Valdez2d850622017-01-11 11:34:52 -0500111 bool is_resume = false;
Alessandro Ghedini958346a2016-12-20 19:42:15 +0000112 bool early_callback_ready = false;
David Benjamind9e07012015-02-09 03:04:34 -0500113};
114
David Benjamin2d445c02015-02-09 13:03:50 -0500115static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
Adam Langley09505632015-07-30 18:10:13 -0700116 int index, long argl, void *argp) {
David Benjamin2d445c02015-02-09 13:03:50 -0500117 delete ((TestState *)ptr);
David Benjamind9e07012015-02-09 03:04:34 -0500118}
119
120static int g_config_index = 0;
David Benjamin2d445c02015-02-09 13:03:50 -0500121static int g_state_index = 0;
David Benjamin5a593af2014-08-11 19:51:50 -0400122
David Benjamin7e7a82d2016-05-20 20:12:42 -0400123static bool SetTestConfig(SSL *ssl, const TestConfig *config) {
David Benjamind9e07012015-02-09 03:04:34 -0500124 return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
David Benjamin5a593af2014-08-11 19:51:50 -0400125}
126
David Benjamin7e7a82d2016-05-20 20:12:42 -0400127static const TestConfig *GetTestConfig(const SSL *ssl) {
David Benjamind9e07012015-02-09 03:04:34 -0500128 return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
David Benjamin5a593af2014-08-11 19:51:50 -0400129}
130
David Benjamin22050932015-11-23 13:44:48 -0500131static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
132 // |SSL_set_ex_data| takes ownership of |state| only on success.
133 if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
134 state.release();
David Benjamind9e07012015-02-09 03:04:34 -0500135 return true;
136 }
137 return false;
138}
139
David Benjamin87e4acd2015-04-02 19:57:35 -0400140static TestState *GetTestState(const SSL *ssl) {
David Benjamin2d445c02015-02-09 13:03:50 -0500141 return (TestState *)SSL_get_ex_data(ssl, g_state_index);
David Benjamin83f90402015-01-27 01:09:43 -0500142}
143
David Benjamin2c516452016-11-15 10:16:54 +0900144static bool LoadCertificate(bssl::UniquePtr<X509> *out_x509,
145 bssl::UniquePtr<STACK_OF(X509)> *out_chain,
146 const std::string &file) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700147 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
David Benjaminacb6dcc2016-03-10 09:15:01 -0500148 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
David Benjamin2c516452016-11-15 10:16:54 +0900149 return false;
David Benjaminacb6dcc2016-03-10 09:15:01 -0500150 }
David Benjamin2c516452016-11-15 10:16:54 +0900151
152 out_x509->reset(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
153 if (!*out_x509) {
154 return false;
155 }
156
157 out_chain->reset(sk_X509_new_null());
158 if (!*out_chain) {
159 return false;
160 }
161
162 // Keep reading the certificate chain.
163 for (;;) {
164 bssl::UniquePtr<X509> cert(
165 PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
166 if (!cert) {
167 break;
168 }
169
170 if (!sk_X509_push(out_chain->get(), cert.get())) {
171 return false;
172 }
173 cert.release(); // sk_X509_push takes ownership.
174 }
175
176 uint32_t err = ERR_peek_last_error();
177 if (ERR_GET_LIB(err) != ERR_LIB_PEM ||
178 ERR_GET_REASON(err) != PEM_R_NO_START_LINE) {
179 return false;
180}
181
182 ERR_clear_error();
183 return true;
David Benjaminacb6dcc2016-03-10 09:15:01 -0500184}
185
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700186static bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
187 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
David Benjamina7f333d2015-02-09 02:37:18 -0500188 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
189 return nullptr;
David Benjamina08e49d2014-08-24 01:46:07 -0400190 }
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700191 return bssl::UniquePtr<EVP_PKEY>(
192 PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
David Benjamina08e49d2014-08-24 01:46:07 -0400193}
194
Adam Langley2ff79332017-02-28 13:45:39 -0800195static bool FromHexDigit(uint8_t *out, char c) {
196 if ('0' <= c && c <= '9') {
197 *out = c - '0';
198 return true;
199 }
200 if ('a' <= c && c <= 'f') {
201 *out = c - 'a' + 10;
202 return true;
203 }
204 if ('A' <= c && c <= 'F') {
205 *out = c - 'A' + 10;
206 return true;
207 }
208 return false;
209}
210
211static bool HexDecode(std::string *out, const std::string &in) {
212 if ((in.size() & 1) != 0) {
213 return false;
214 }
215
216 std::unique_ptr<uint8_t[]> buf(new uint8_t[in.size() / 2]);
217 for (size_t i = 0; i < in.size() / 2; i++) {
218 uint8_t high, low;
219 if (!FromHexDigit(&high, in[i*2]) ||
220 !FromHexDigit(&low, in[i*2+1])) {
221 return false;
222 }
223 buf[i] = (high << 4) | low;
224 }
225
226 out->assign(reinterpret_cast<const char *>(buf.get()), in.size() / 2);
227 return true;
228}
229
230static std::vector<std::string> SplitParts(const std::string &in,
231 const char delim) {
232 std::vector<std::string> ret;
233 size_t start = 0;
234
235 for (size_t i = 0; i < in.size(); i++) {
236 if (in[i] == delim) {
237 ret.push_back(in.substr(start, i - start));
238 start = i + 1;
239 }
240 }
241
242 ret.push_back(in.substr(start, std::string::npos));
243 return ret;
244}
245
246static std::vector<std::string> DecodeHexStrings(
247 const std::string &hex_strings) {
248 std::vector<std::string> ret;
249 const std::vector<std::string> parts = SplitParts(hex_strings, ',');
250
251 for (const auto &part : parts) {
252 std::string binary;
253 if (!HexDecode(&binary, part)) {
254 fprintf(stderr, "Bad hex string: %s\n", part.c_str());
255 return ret;
256 }
257
258 ret.push_back(binary);
259 }
260
261 return ret;
262}
263
264static bssl::UniquePtr<STACK_OF(X509_NAME)> DecodeHexX509Names(
265 const std::string &hex_names) {
266 const std::vector<std::string> der_names = DecodeHexStrings(hex_names);
267 bssl::UniquePtr<STACK_OF(X509_NAME)> ret(sk_X509_NAME_new_null());
268
269 for (const auto &der_name : der_names) {
270 const uint8_t *const data =
271 reinterpret_cast<const uint8_t *>(der_name.data());
272 const uint8_t *derp = data;
273 bssl::UniquePtr<X509_NAME> name(
274 d2i_X509_NAME(nullptr, &derp, der_name.size()));
275 if (!name || derp != data + der_name.size()) {
276 fprintf(stderr, "Failed to parse X509_NAME.\n");
277 return nullptr;
278 }
279
280 if (!sk_X509_NAME_push(ret.get(), name.get())) {
281 return nullptr;
282 }
283 name.release();
284 }
285
286 return ret;
287}
288
David Benjaminb4d65fd2015-05-29 17:11:21 -0400289static ssl_private_key_result_t AsyncPrivateKeySign(
290 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
David Benjamind3440b42016-07-14 14:52:41 -0400291 uint16_t signature_algorithm, const uint8_t *in, size_t in_len) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400292 TestState *test_state = GetTestState(ssl);
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700293 if (!test_state->private_key_result.empty()) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400294 fprintf(stderr, "AsyncPrivateKeySign called with operation pending.\n");
295 abort();
296 }
297
David Benjamind3440b42016-07-14 14:52:41 -0400298 // Determine the hash.
299 const EVP_MD *md;
300 switch (signature_algorithm) {
301 case SSL_SIGN_RSA_PKCS1_SHA1:
302 case SSL_SIGN_ECDSA_SHA1:
303 md = EVP_sha1();
304 break;
305 case SSL_SIGN_RSA_PKCS1_SHA256:
306 case SSL_SIGN_ECDSA_SECP256R1_SHA256:
307 case SSL_SIGN_RSA_PSS_SHA256:
308 md = EVP_sha256();
309 break;
310 case SSL_SIGN_RSA_PKCS1_SHA384:
311 case SSL_SIGN_ECDSA_SECP384R1_SHA384:
312 case SSL_SIGN_RSA_PSS_SHA384:
313 md = EVP_sha384();
314 break;
315 case SSL_SIGN_RSA_PKCS1_SHA512:
316 case SSL_SIGN_ECDSA_SECP521R1_SHA512:
317 case SSL_SIGN_RSA_PSS_SHA512:
318 md = EVP_sha512();
319 break;
320 case SSL_SIGN_RSA_PKCS1_MD5_SHA1:
321 md = EVP_md5_sha1();
322 break;
323 default:
324 fprintf(stderr, "Unknown signature algorithm %04x.\n",
325 signature_algorithm);
326 return ssl_private_key_failure;
327 }
328
David Benjaminaac1e2d2016-12-06 22:35:41 -0500329 bssl::ScopedEVP_MD_CTX ctx;
David Benjamind3440b42016-07-14 14:52:41 -0400330 EVP_PKEY_CTX *pctx;
331 if (!EVP_DigestSignInit(ctx.get(), &pctx, md, nullptr,
332 test_state->private_key.get())) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400333 return ssl_private_key_failure;
334 }
335
David Benjamind3440b42016-07-14 14:52:41 -0400336 // Configure additional signature parameters.
337 switch (signature_algorithm) {
338 case SSL_SIGN_RSA_PSS_SHA256:
339 case SSL_SIGN_RSA_PSS_SHA384:
340 case SSL_SIGN_RSA_PSS_SHA512:
341 if (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) ||
342 !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
343 -1 /* salt len = hash len */)) {
344 return ssl_private_key_failure;
345 }
346 }
347
David Benjaminb4d65fd2015-05-29 17:11:21 -0400348 // Write the signature into |test_state|.
349 size_t len = 0;
David Benjamind3440b42016-07-14 14:52:41 -0400350 if (!EVP_DigestSignUpdate(ctx.get(), in, in_len) ||
351 !EVP_DigestSignFinal(ctx.get(), nullptr, &len)) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400352 return ssl_private_key_failure;
353 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700354 test_state->private_key_result.resize(len);
David Benjamind3440b42016-07-14 14:52:41 -0400355 if (!EVP_DigestSignFinal(ctx.get(), test_state->private_key_result.data(),
356 &len)) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400357 return ssl_private_key_failure;
358 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700359 test_state->private_key_result.resize(len);
David Benjaminb4d65fd2015-05-29 17:11:21 -0400360
David Benjamind3440b42016-07-14 14:52:41 -0400361 // The signature will be released asynchronously in |AsyncPrivateKeyComplete|.
David Benjaminb4d65fd2015-05-29 17:11:21 -0400362 return ssl_private_key_retry;
363}
364
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700365static ssl_private_key_result_t AsyncPrivateKeyDecrypt(
366 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
367 const uint8_t *in, size_t in_len) {
368 TestState *test_state = GetTestState(ssl);
369 if (!test_state->private_key_result.empty()) {
370 fprintf(stderr,
371 "AsyncPrivateKeyDecrypt called with operation pending.\n");
372 abort();
373 }
374
David Benjamin758d1272015-11-20 17:47:25 -0500375 RSA *rsa = EVP_PKEY_get0_RSA(test_state->private_key.get());
376 if (rsa == NULL) {
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700377 fprintf(stderr,
378 "AsyncPrivateKeyDecrypt called with incorrect key type.\n");
379 abort();
380 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700381 test_state->private_key_result.resize(RSA_size(rsa));
David Benjaminef14b2d2015-11-11 14:01:27 -0800382 if (!RSA_decrypt(rsa, out_len, test_state->private_key_result.data(),
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700383 RSA_size(rsa), in, in_len, RSA_NO_PADDING)) {
384 return ssl_private_key_failure;
385 }
386
387 test_state->private_key_result.resize(*out_len);
388
David Benjamind3440b42016-07-14 14:52:41 -0400389 // The decryption will be released asynchronously in |AsyncPrivateComplete|.
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700390 return ssl_private_key_retry;
391}
392
David Benjamind3440b42016-07-14 14:52:41 -0400393static ssl_private_key_result_t AsyncPrivateKeyComplete(
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700394 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
395 TestState *test_state = GetTestState(ssl);
396 if (test_state->private_key_result.empty()) {
397 fprintf(stderr,
David Benjamind3440b42016-07-14 14:52:41 -0400398 "AsyncPrivateKeyComplete called without operation pending.\n");
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700399 abort();
400 }
401
402 if (test_state->private_key_retries < 2) {
403 // Only return the decryption on the second attempt, to test both incomplete
404 // |decrypt| and |decrypt_complete|.
405 return ssl_private_key_retry;
406 }
407
408 if (max_out < test_state->private_key_result.size()) {
409 fprintf(stderr, "Output buffer too small.\n");
410 return ssl_private_key_failure;
411 }
David Benjamin17cf2cb2016-12-13 01:07:13 -0500412 OPENSSL_memcpy(out, test_state->private_key_result.data(),
413 test_state->private_key_result.size());
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700414 *out_len = test_state->private_key_result.size();
415
416 test_state->private_key_result.clear();
417 test_state->private_key_retries = 0;
David Benjaminb4d65fd2015-05-29 17:11:21 -0400418 return ssl_private_key_success;
419}
420
421static const SSL_PRIVATE_KEY_METHOD g_async_private_key_method = {
David Benjamina232a712017-03-30 15:51:53 -0500422 nullptr /* type */,
423 nullptr /* max_signature_len */,
David Benjaminb4d65fd2015-05-29 17:11:21 -0400424 AsyncPrivateKeySign,
David Benjamind3440b42016-07-14 14:52:41 -0400425 nullptr /* sign_digest */,
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700426 AsyncPrivateKeyDecrypt,
David Benjamind3440b42016-07-14 14:52:41 -0400427 AsyncPrivateKeyComplete,
David Benjaminb4d65fd2015-05-29 17:11:21 -0400428};
429
Steven Valdez0d62f262015-09-04 12:41:04 -0400430template<typename T>
Adam Langley10f97f32016-07-12 08:09:33 -0700431struct Free {
Steven Valdez0d62f262015-09-04 12:41:04 -0400432 void operator()(T *buf) {
433 free(buf);
434 }
435};
436
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700437static bool GetCertificate(SSL *ssl, bssl::UniquePtr<X509> *out_x509,
David Benjamin2c516452016-11-15 10:16:54 +0900438 bssl::UniquePtr<STACK_OF(X509)> *out_chain,
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700439 bssl::UniquePtr<EVP_PKEY> *out_pkey) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400440 const TestConfig *config = GetTestConfig(ssl);
Steven Valdez0d62f262015-09-04 12:41:04 -0400441
442 if (!config->digest_prefs.empty()) {
Adam Langley10f97f32016-07-12 08:09:33 -0700443 std::unique_ptr<char, Free<char>> digest_prefs(
Steven Valdez0d62f262015-09-04 12:41:04 -0400444 strdup(config->digest_prefs.c_str()));
Steven Valdez0d62f262015-09-04 12:41:04 -0400445 std::vector<int> digest_list;
446
447 for (;;) {
Adam Langley67251f22015-09-23 15:01:07 -0700448 char *token =
449 strtok(digest_list.empty() ? digest_prefs.get() : nullptr, ",");
Steven Valdez0d62f262015-09-04 12:41:04 -0400450 if (token == nullptr) {
451 break;
452 }
453
454 digest_list.push_back(EVP_MD_type(EVP_get_digestbyname(token)));
455 }
456
457 if (!SSL_set_private_key_digest_prefs(ssl, digest_list.data(),
458 digest_list.size())) {
459 return false;
460 }
461 }
462
David Benjaminca3d5452016-07-14 12:51:01 -0400463 if (!config->signing_prefs.empty()) {
464 std::vector<uint16_t> u16s(config->signing_prefs.begin(),
465 config->signing_prefs.end());
466 if (!SSL_set_signing_algorithm_prefs(ssl, u16s.data(), u16s.size())) {
467 return false;
468 }
469 }
470
David Benjaminb4d65fd2015-05-29 17:11:21 -0400471 if (!config->key_file.empty()) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500472 *out_pkey = LoadPrivateKey(config->key_file.c_str());
473 if (!*out_pkey) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400474 return false;
475 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500476 }
David Benjamin2c516452016-11-15 10:16:54 +0900477 if (!config->cert_file.empty() &&
478 !LoadCertificate(out_x509, out_chain, config->cert_file.c_str())) {
479 return false;
David Benjamin41fdbcd2015-02-09 03:13:35 -0500480 }
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100481 if (!config->ocsp_response.empty() &&
Alessandro Ghedini559f0642016-12-07 12:55:32 +0000482 !SSL_set_ocsp_response(ssl, (const uint8_t *)config->ocsp_response.data(),
483 config->ocsp_response.size())) {
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100484 return false;
485 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500486 return true;
487}
488
David Benjaminacb6dcc2016-03-10 09:15:01 -0500489static bool InstallCertificate(SSL *ssl) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700490 bssl::UniquePtr<X509> x509;
David Benjamin2c516452016-11-15 10:16:54 +0900491 bssl::UniquePtr<STACK_OF(X509)> chain;
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700492 bssl::UniquePtr<EVP_PKEY> pkey;
David Benjamin2c516452016-11-15 10:16:54 +0900493 if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500494 return false;
495 }
496
497 if (pkey) {
498 TestState *test_state = GetTestState(ssl);
David Benjamin7e7a82d2016-05-20 20:12:42 -0400499 const TestConfig *config = GetTestConfig(ssl);
David Benjaminacb6dcc2016-03-10 09:15:01 -0500500 if (config->async) {
501 test_state->private_key = std::move(pkey);
502 SSL_set_private_key_method(ssl, &g_async_private_key_method);
503 } else if (!SSL_use_PrivateKey(ssl, pkey.get())) {
504 return false;
505 }
506 }
507
508 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
509 return false;
510 }
511
David Benjamin2c516452016-11-15 10:16:54 +0900512 if (sk_X509_num(chain.get()) > 0 &&
513 !SSL_set1_chain(ssl, chain.get())) {
514 return false;
515 }
516
David Benjaminacb6dcc2016-03-10 09:15:01 -0500517 return true;
518}
519
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000520static enum ssl_select_cert_result_t SelectCertificateCallback(
521 const SSL_CLIENT_HELLO *client_hello) {
David Benjamin731058e2016-12-03 23:15:13 -0500522 const TestConfig *config = GetTestConfig(client_hello->ssl);
523 GetTestState(client_hello->ssl)->early_callback_called = true;
David Benjamin5a593af2014-08-11 19:51:50 -0400524
David Benjamin6f5c0f42015-02-24 01:23:21 -0500525 if (!config->expected_server_name.empty()) {
526 const uint8_t *extension_data;
527 size_t extension_len;
528 CBS extension, server_name_list, host_name;
529 uint8_t name_type;
530
David Benjamin731058e2016-12-03 23:15:13 -0500531 if (!SSL_early_callback_ctx_extension_get(
532 client_hello, TLSEXT_TYPE_server_name, &extension_data,
533 &extension_len)) {
David Benjamin6f5c0f42015-02-24 01:23:21 -0500534 fprintf(stderr, "Could not find server_name extension.\n");
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000535 return ssl_select_cert_error;
David Benjamin6f5c0f42015-02-24 01:23:21 -0500536 }
537
538 CBS_init(&extension, extension_data, extension_len);
539 if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
540 CBS_len(&extension) != 0 ||
541 !CBS_get_u8(&server_name_list, &name_type) ||
542 name_type != TLSEXT_NAMETYPE_host_name ||
543 !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
544 CBS_len(&server_name_list) != 0) {
545 fprintf(stderr, "Could not decode server_name extension.\n");
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000546 return ssl_select_cert_error;
David Benjamin6f5c0f42015-02-24 01:23:21 -0500547 }
548
549 if (!CBS_mem_equal(&host_name,
550 (const uint8_t*)config->expected_server_name.data(),
551 config->expected_server_name.size())) {
552 fprintf(stderr, "Server name mismatch.\n");
553 }
David Benjamin7b030512014-07-08 17:30:11 -0400554 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400555
David Benjamin6f5c0f42015-02-24 01:23:21 -0500556 if (config->fail_early_callback) {
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000557 return ssl_select_cert_error;
David Benjamin7b030512014-07-08 17:30:11 -0400558 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400559
David Benjamin6f5c0f42015-02-24 01:23:21 -0500560 // Install the certificate in the early callback.
561 if (config->use_early_callback) {
Alessandro Ghedini958346a2016-12-20 19:42:15 +0000562 bool early_callback_ready =
563 GetTestState(client_hello->ssl)->early_callback_ready;
564 if (config->async && !early_callback_ready) {
David Benjamin6f5c0f42015-02-24 01:23:21 -0500565 // Install the certificate asynchronously.
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000566 return ssl_select_cert_retry;
David Benjamin6f5c0f42015-02-24 01:23:21 -0500567 }
David Benjamin731058e2016-12-03 23:15:13 -0500568 if (!InstallCertificate(client_hello->ssl)) {
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000569 return ssl_select_cert_error;
David Benjamin6f5c0f42015-02-24 01:23:21 -0500570 }
David Benjamin7b030512014-07-08 17:30:11 -0400571 }
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000572 return ssl_select_cert_success;
David Benjamin8f2c20e2014-07-09 09:30:38 -0400573}
David Benjamin025b3d32014-07-01 19:53:04 -0400574
David Benjamin5edfc8c2016-12-10 15:46:58 -0500575static bool CheckCertificateRequest(SSL *ssl) {
576 const TestConfig *config = GetTestConfig(ssl);
577
578 if (!config->expected_certificate_types.empty()) {
579 const uint8_t *certificate_types;
580 size_t certificate_types_len =
581 SSL_get0_certificate_types(ssl, &certificate_types);
582 if (certificate_types_len != config->expected_certificate_types.size() ||
David Benjamin17cf2cb2016-12-13 01:07:13 -0500583 OPENSSL_memcmp(certificate_types,
584 config->expected_certificate_types.data(),
585 certificate_types_len) != 0) {
David Benjamin5edfc8c2016-12-10 15:46:58 -0500586 fprintf(stderr, "certificate types mismatch\n");
587 return false;
588 }
589 }
590
Adam Langley2ff79332017-02-28 13:45:39 -0800591 if (!config->expected_client_ca_list.empty()) {
592 bssl::UniquePtr<STACK_OF(X509_NAME)> expected =
593 DecodeHexX509Names(config->expected_client_ca_list);
594 const size_t num_expected = sk_X509_NAME_num(expected.get());
595
596 const STACK_OF(X509_NAME) *received = SSL_get_client_CA_list(ssl);
597 const size_t num_received = sk_X509_NAME_num(received);
598
599 if (num_received != num_expected) {
600 fprintf(stderr, "expected %u names in CertificateRequest but got %u\n",
601 static_cast<unsigned>(num_expected),
602 static_cast<unsigned>(num_received));
603 return false;
604 }
605
606 for (size_t i = 0; i < num_received; i++) {
607 if (X509_NAME_cmp(sk_X509_NAME_value(received, i),
608 sk_X509_NAME_value(expected.get(), i)) != 0) {
609 fprintf(stderr, "names in CertificateRequest differ at index #%d\n",
610 static_cast<unsigned>(i));
611 return false;
612 }
613 }
Adam Langleyd6c22ee2017-03-02 12:56:32 -0800614
615 STACK_OF(CRYPTO_BUFFER) *buffers = SSL_get0_server_requested_CAs(ssl);
616 if (sk_CRYPTO_BUFFER_num(buffers) != num_received) {
617 fprintf(stderr,
618 "Mismatch between SSL_get_server_requested_CAs and "
619 "SSL_get_client_CA_list.\n");
620 return false;
621 }
Adam Langley2ff79332017-02-28 13:45:39 -0800622 }
623
David Benjamin5edfc8c2016-12-10 15:46:58 -0500624 return true;
625}
626
David Benjaminacb6dcc2016-03-10 09:15:01 -0500627static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
David Benjamin5edfc8c2016-12-10 15:46:58 -0500628 if (!CheckCertificateRequest(ssl)) {
629 return -1;
630 }
631
David Benjamin7e7a82d2016-05-20 20:12:42 -0400632 if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500633 return -1;
634 }
635
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700636 bssl::UniquePtr<X509> x509;
David Benjamin2c516452016-11-15 10:16:54 +0900637 bssl::UniquePtr<STACK_OF(X509)> chain;
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700638 bssl::UniquePtr<EVP_PKEY> pkey;
David Benjamin2c516452016-11-15 10:16:54 +0900639 if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500640 return -1;
641 }
642
643 // Return zero for no certificate.
644 if (!x509) {
645 return 0;
646 }
647
David Benjamin2c516452016-11-15 10:16:54 +0900648 // Chains and asynchronous private keys are not supported with client_cert_cb.
David Benjaminacb6dcc2016-03-10 09:15:01 -0500649 *out_x509 = x509.release();
650 *out_pkey = pkey.release();
651 return 1;
652}
653
David Benjamin5edfc8c2016-12-10 15:46:58 -0500654static int CertCallback(SSL *ssl, void *arg) {
655 const TestConfig *config = GetTestConfig(ssl);
656
657 // Check the CertificateRequest metadata is as expected.
658 if (!SSL_is_server(ssl) && !CheckCertificateRequest(ssl)) {
659 return -1;
660 }
661
662 if (config->fail_cert_callback) {
663 return 0;
664 }
665
666 // The certificate will be installed via other means.
667 if (!config->async || config->use_early_callback) {
668 return 1;
669 }
670
671 if (!GetTestState(ssl)->cert_ready) {
672 return -1;
673 }
674 if (!InstallCertificate(ssl)) {
675 return 0;
676 }
677 return 1;
678}
679
Paul Lietar8f1c2682015-08-18 12:21:54 +0100680static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
681 SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data(store_ctx,
682 SSL_get_ex_data_X509_STORE_CTX_idx());
David Benjamin7e7a82d2016-05-20 20:12:42 -0400683 const TestConfig *config = GetTestConfig(ssl);
Paul Lietar8f1c2682015-08-18 12:21:54 +0100684
685 if (!config->expected_ocsp_response.empty()) {
686 const uint8_t *data;
687 size_t len;
688 SSL_get0_ocsp_response(ssl, &data, &len);
689 if (len == 0) {
690 fprintf(stderr, "OCSP response not available in verify callback\n");
691 return 0;
692 }
693 }
694
David Benjamin67666e72014-07-12 15:47:52 -0400695 return 1;
696}
697
Paul Lietar8f1c2682015-08-18 12:21:54 +0100698static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
699 store_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION;
700 return 0;
701}
702
David Benjaminc273d2c2015-02-09 12:59:46 -0500703static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
704 unsigned int *out_len, void *arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400705 const TestConfig *config = GetTestConfig(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500706 if (config->advertise_npn.empty()) {
David Benjamin1f5f62b2014-07-12 16:18:02 -0400707 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500708 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400709
David Benjamin5a593af2014-08-11 19:51:50 -0400710 *out = (const uint8_t*)config->advertise_npn.data();
711 *out_len = config->advertise_npn.size();
David Benjamin1f5f62b2014-07-12 16:18:02 -0400712 return SSL_TLSEXT_ERR_OK;
713}
714
David Benjaminc273d2c2015-02-09 12:59:46 -0500715static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
David Benjamin8b368412015-03-14 01:54:17 -0400716 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400717 const TestConfig *config = GetTestConfig(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500718 if (config->select_next_proto.empty()) {
David Benjamin7e3305e2014-07-28 14:52:32 -0400719 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500720 }
David Benjamin7e3305e2014-07-28 14:52:32 -0400721
David Benjamin5a593af2014-08-11 19:51:50 -0400722 *out = (uint8_t*)config->select_next_proto.data();
723 *outlen = config->select_next_proto.size();
David Benjamin7e3305e2014-07-28 14:52:32 -0400724 return SSL_TLSEXT_ERR_OK;
725}
726
David Benjaminc273d2c2015-02-09 12:59:46 -0500727static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
728 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin25fe85b2016-08-09 20:00:32 -0400729 if (GetTestState(ssl)->alpn_select_done) {
730 fprintf(stderr, "AlpnSelectCallback called after completion.\n");
731 exit(1);
732 }
733
734 GetTestState(ssl)->alpn_select_done = true;
735
David Benjamin7e7a82d2016-05-20 20:12:42 -0400736 const TestConfig *config = GetTestConfig(ssl);
David Benjamin594e7d22016-03-17 17:49:56 -0400737 if (config->decline_alpn) {
David Benjaminae2888f2014-09-06 12:58:58 -0400738 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500739 }
David Benjaminae2888f2014-09-06 12:58:58 -0400740
741 if (!config->expected_advertised_alpn.empty() &&
742 (config->expected_advertised_alpn.size() != inlen ||
David Benjamin17cf2cb2016-12-13 01:07:13 -0500743 OPENSSL_memcmp(config->expected_advertised_alpn.data(), in, inlen) !=
744 0)) {
David Benjaminae2888f2014-09-06 12:58:58 -0400745 fprintf(stderr, "bad ALPN select callback inputs\n");
746 exit(1);
747 }
748
749 *out = (const uint8_t*)config->select_alpn.data();
750 *outlen = config->select_alpn.size();
Steven Valdez2d850622017-01-11 11:34:52 -0500751 if (GetTestState(ssl)->is_resume && config->select_resume_alpn.size() > 0) {
752 *out = (const uint8_t*)config->select_resume_alpn.data();
753 *outlen = config->select_resume_alpn.size();
754 }
David Benjaminae2888f2014-09-06 12:58:58 -0400755 return SSL_TLSEXT_ERR_OK;
756}
757
David Benjaminc273d2c2015-02-09 12:59:46 -0500758static unsigned PskClientCallback(SSL *ssl, const char *hint,
759 char *out_identity,
760 unsigned max_identity_len,
761 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400762 const TestConfig *config = GetTestConfig(ssl);
David Benjamin48cae082014-10-27 01:06:24 -0400763
David Benjamin78679342016-09-16 19:42:05 -0400764 if (config->psk_identity.empty()) {
765 if (hint != nullptr) {
766 fprintf(stderr, "Server PSK hint was non-null.\n");
767 return 0;
768 }
769 } else if (hint == nullptr ||
770 strcmp(hint, config->psk_identity.c_str()) != 0) {
David Benjamin48cae082014-10-27 01:06:24 -0400771 fprintf(stderr, "Server PSK hint did not match.\n");
772 return 0;
773 }
774
775 // Account for the trailing '\0' for the identity.
776 if (config->psk_identity.size() >= max_identity_len ||
777 config->psk.size() > max_psk_len) {
778 fprintf(stderr, "PSK buffers too small\n");
779 return 0;
780 }
781
782 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
783 max_identity_len);
David Benjamin17cf2cb2016-12-13 01:07:13 -0500784 OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size());
David Benjamin48cae082014-10-27 01:06:24 -0400785 return config->psk.size();
786}
787
David Benjaminc273d2c2015-02-09 12:59:46 -0500788static unsigned PskServerCallback(SSL *ssl, const char *identity,
789 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400790 const TestConfig *config = GetTestConfig(ssl);
David Benjamin48cae082014-10-27 01:06:24 -0400791
792 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
793 fprintf(stderr, "Client PSK identity did not match.\n");
794 return 0;
795 }
796
797 if (config->psk.size() > max_psk_len) {
798 fprintf(stderr, "PSK buffers too small\n");
799 return 0;
800 }
801
David Benjamin17cf2cb2016-12-13 01:07:13 -0500802 OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size());
David Benjamin48cae082014-10-27 01:06:24 -0400803 return config->psk.size();
804}
805
David Benjamin1b22f852016-10-27 16:36:32 -0400806static timeval g_clock;
807
David Benjamin4d2e7ce2015-05-08 13:29:45 -0400808static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
David Benjamin1b22f852016-10-27 16:36:32 -0400809 *out_clock = g_clock;
David Benjamin377fc312015-01-26 00:22:12 -0500810}
811
David Benjaminc273d2c2015-02-09 12:59:46 -0500812static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
David Benjamin2d445c02015-02-09 13:03:50 -0500813 *out_pkey = GetTestState(ssl)->channel_id.release();
David Benjamind9e07012015-02-09 03:04:34 -0500814}
815
David Benjaminc273d2c2015-02-09 12:59:46 -0500816static SSL_SESSION *GetSessionCallback(SSL *ssl, uint8_t *data, int len,
817 int *copy) {
David Benjamin2d445c02015-02-09 13:03:50 -0500818 TestState *async_state = GetTestState(ssl);
David Benjamin1b8b6912015-02-09 04:28:16 -0500819 if (async_state->session) {
820 *copy = 0;
821 return async_state->session.release();
822 } else if (async_state->pending_session) {
823 return SSL_magic_pending_session_ptr();
824 } else {
825 return NULL;
826 }
827}
828
David Benjamin731058e2016-12-03 23:15:13 -0500829static int DDoSCallback(const SSL_CLIENT_HELLO *client_hello) {
830 const TestConfig *config = GetTestConfig(client_hello->ssl);
Adam Langley524e7172015-02-20 16:04:00 -0800831 static int callback_num = 0;
832
833 callback_num++;
834 if (config->fail_ddos_callback ||
835 (config->fail_second_ddos_callback && callback_num == 2)) {
836 return 0;
837 }
838 return 1;
839}
840
David Benjamin87e4acd2015-04-02 19:57:35 -0400841static void InfoCallback(const SSL *ssl, int type, int val) {
842 if (type == SSL_CB_HANDSHAKE_DONE) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400843 if (GetTestConfig(ssl)->handshake_never_done) {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400844 fprintf(stderr, "Handshake unexpectedly completed.\n");
David Benjamin87e4acd2015-04-02 19:57:35 -0400845 // Abort before any expected error code is printed, to ensure the overall
846 // test fails.
847 abort();
848 }
849 GetTestState(ssl)->handshake_done = true;
David Benjamin25fe85b2016-08-09 20:00:32 -0400850
851 // Callbacks may be called again on a new handshake.
852 GetTestState(ssl)->ticket_decrypt_done = false;
853 GetTestState(ssl)->alpn_select_done = false;
David Benjamin87e4acd2015-04-02 19:57:35 -0400854 }
855}
856
David Benjaminba4594a2015-06-18 18:36:15 -0400857static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
858 GetTestState(ssl)->got_new_session = true;
Steven Valdez4aa154e2016-07-29 14:32:55 -0400859 GetTestState(ssl)->new_session.reset(session);
David Benjaminba4594a2015-06-18 18:36:15 -0400860 return 1;
861}
862
David Benjamind98452d2015-06-16 14:16:23 -0400863static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
864 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
865 int encrypt) {
David Benjamin25fe85b2016-08-09 20:00:32 -0400866 if (!encrypt) {
867 if (GetTestState(ssl)->ticket_decrypt_done) {
868 fprintf(stderr, "TicketKeyCallback called after completion.\n");
869 return -1;
870 }
871
872 GetTestState(ssl)->ticket_decrypt_done = true;
873 }
874
David Benjamind98452d2015-06-16 14:16:23 -0400875 // This is just test code, so use the all-zeros key.
876 static const uint8_t kZeros[16] = {0};
877
878 if (encrypt) {
David Benjamin17cf2cb2016-12-13 01:07:13 -0500879 OPENSSL_memcpy(key_name, kZeros, sizeof(kZeros));
David Benjamind98452d2015-06-16 14:16:23 -0400880 RAND_bytes(iv, 16);
David Benjamin17cf2cb2016-12-13 01:07:13 -0500881 } else if (OPENSSL_memcmp(key_name, kZeros, 16) != 0) {
David Benjamind98452d2015-06-16 14:16:23 -0400882 return 0;
883 }
884
885 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
886 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
887 return -1;
888 }
889
890 if (!encrypt) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400891 return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
David Benjamind98452d2015-06-16 14:16:23 -0400892 }
893 return 1;
894}
895
Adam Langley09505632015-07-30 18:10:13 -0700896// kCustomExtensionValue is the extension value that the custom extension
897// callbacks will add.
Adam Langleyc5b23a12015-07-30 18:19:26 -0700898static const uint16_t kCustomExtensionValue = 1234;
Adam Langley09505632015-07-30 18:10:13 -0700899static void *const kCustomExtensionAddArg =
900 reinterpret_cast<void *>(kCustomExtensionValue);
901static void *const kCustomExtensionParseArg =
902 reinterpret_cast<void *>(kCustomExtensionValue + 1);
903static const char kCustomExtensionContents[] = "custom extension";
904
905static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
906 const uint8_t **out, size_t *out_len,
907 int *out_alert_value, void *add_arg) {
908 if (extension_value != kCustomExtensionValue ||
909 add_arg != kCustomExtensionAddArg) {
910 abort();
911 }
912
David Benjamin7e7a82d2016-05-20 20:12:42 -0400913 if (GetTestConfig(ssl)->custom_extension_skip) {
Adam Langley09505632015-07-30 18:10:13 -0700914 return 0;
915 }
David Benjamin7e7a82d2016-05-20 20:12:42 -0400916 if (GetTestConfig(ssl)->custom_extension_fail_add) {
Adam Langley09505632015-07-30 18:10:13 -0700917 return -1;
918 }
919
920 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
921 *out_len = sizeof(kCustomExtensionContents) - 1;
922
923 return 1;
924}
925
926static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
927 const uint8_t *out, void *add_arg) {
928 if (extension_value != kCustomExtensionValue ||
929 add_arg != kCustomExtensionAddArg ||
930 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
931 abort();
932 }
933}
934
935static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
936 const uint8_t *contents,
937 size_t contents_len,
938 int *out_alert_value, void *parse_arg) {
939 if (extension_value != kCustomExtensionValue ||
940 parse_arg != kCustomExtensionParseArg) {
941 abort();
942 }
943
944 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
David Benjamin17cf2cb2016-12-13 01:07:13 -0500945 OPENSSL_memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
Adam Langley09505632015-07-30 18:10:13 -0700946 *out_alert_value = SSL_AD_DECODE_ERROR;
947 return 0;
948 }
949
950 return 1;
951}
952
David Benjamin8b176712016-10-27 21:51:24 -0400953static int ServerNameCallback(SSL *ssl, int *out_alert, void *arg) {
954 // SNI must be accessible from the SNI callback.
955 const TestConfig *config = GetTestConfig(ssl);
956 const char *server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
957 if (server_name == nullptr ||
958 std::string(server_name) != config->expected_server_name) {
959 fprintf(stderr, "servername mismatch (got %s; want %s)\n", server_name,
960 config->expected_server_name.c_str());
961 return SSL_TLSEXT_ERR_ALERT_FATAL;
962 }
963
964 return SSL_TLSEXT_ERR_OK;
965}
966
David Benjamin87c8a642015-02-21 01:54:29 -0500967// Connect returns a new socket connected to localhost on |port| or -1 on
968// error.
969static int Connect(uint16_t port) {
970 int sock = socket(AF_INET, SOCK_STREAM, 0);
971 if (sock == -1) {
972 PrintSocketError("socket");
973 return -1;
974 }
975 int nodelay = 1;
976 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
977 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
978 PrintSocketError("setsockopt");
979 closesocket(sock);
980 return -1;
981 }
982 sockaddr_in sin;
David Benjamin17cf2cb2016-12-13 01:07:13 -0500983 OPENSSL_memset(&sin, 0, sizeof(sin));
David Benjamin87c8a642015-02-21 01:54:29 -0500984 sin.sin_family = AF_INET;
985 sin.sin_port = htons(port);
986 if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
987 PrintSocketError("inet_pton");
988 closesocket(sock);
989 return -1;
990 }
991 if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
992 sizeof(sin)) != 0) {
993 PrintSocketError("connect");
994 closesocket(sock);
995 return -1;
996 }
997 return sock;
998}
999
1000class SocketCloser {
1001 public:
1002 explicit SocketCloser(int sock) : sock_(sock) {}
1003 ~SocketCloser() {
1004 // Half-close and drain the socket before releasing it. This seems to be
1005 // necessary for graceful shutdown on Windows. It will also avoid write
1006 // failures in the test runner.
1007#if defined(OPENSSL_WINDOWS)
1008 shutdown(sock_, SD_SEND);
1009#else
1010 shutdown(sock_, SHUT_WR);
1011#endif
1012 while (true) {
1013 char buf[1024];
1014 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
1015 break;
1016 }
1017 }
1018 closesocket(sock_);
1019 }
1020
1021 private:
1022 const int sock_;
1023};
1024
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001025static bssl::UniquePtr<SSL_CTX> SetupCtx(const TestConfig *config) {
1026 bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(
David Benjamina7f333d2015-02-09 02:37:18 -05001027 config->is_dtls ? DTLS_method() : TLS_method()));
1028 if (!ssl_ctx) {
1029 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -04001030 }
1031
Adam Langleyd519bf62016-12-12 11:16:44 -08001032 SSL_CTX_set0_buffer_pool(ssl_ctx.get(), g_pool);
1033
David Benjamin2dc02042016-09-19 19:57:37 -04001034 // Enable TLS 1.3 for tests.
1035 if (!config->is_dtls &&
David Benjamine4706902016-09-20 15:12:23 -04001036 !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION)) {
David Benjamin2dc02042016-09-19 19:57:37 -04001037 return nullptr;
Nick Harper1fd39d82016-06-14 18:14:35 -07001038 }
1039
Adam Langleycef75832015-09-03 14:51:12 -07001040 std::string cipher_list = "ALL";
1041 if (!config->cipher.empty()) {
1042 cipher_list = config->cipher;
1043 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
1044 }
Matthew Braithwaitea57dcfb2017-02-17 22:08:23 -08001045 if (!SSL_CTX_set_strict_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
Adam Langleycef75832015-09-03 14:51:12 -07001046 return nullptr;
1047 }
1048
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001049 bssl::UniquePtr<DH> dh(DH_get_2048_256(NULL));
David Benjaminb7c5e842016-03-28 09:59:10 -04001050 if (!dh) {
1051 return nullptr;
1052 }
Adam Langleyc4f25ce2015-11-26 16:39:08 -08001053
1054 if (config->use_sparse_dh_prime) {
1055 // This prime number is 2^1024 + 643 – a value just above a power of two.
1056 // Because of its form, values modulo it are essentially certain to be one
1057 // byte shorter. This is used to test padding of these values.
1058 if (BN_hex2bn(
1059 &dh->p,
1060 "1000000000000000000000000000000000000000000000000000000000000000"
1061 "0000000000000000000000000000000000000000000000000000000000000000"
1062 "0000000000000000000000000000000000000000000000000000000000000000"
1063 "0000000000000000000000000000000000000000000000000000000000000028"
1064 "3") == 0 ||
1065 !BN_set_word(dh->g, 2)) {
1066 return nullptr;
1067 }
David Benjamine66148a2016-02-02 14:14:36 -05001068 BN_free(dh->q);
1069 dh->q = NULL;
Adam Langleyc4f25ce2015-11-26 16:39:08 -08001070 dh->priv_length = 0;
1071 }
1072
David Benjaminb7c5e842016-03-28 09:59:10 -04001073 if (!SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
David Benjamina7f333d2015-02-09 02:37:18 -05001074 return nullptr;
David Benjaminf4e5c4e2014-08-02 17:35:45 -04001075 }
1076
David Benjamin1b8b6912015-02-09 04:28:16 -05001077 if (config->async && config->is_server) {
1078 // Disable the internal session cache. To test asynchronous session lookup,
1079 // we use an external session cache.
1080 SSL_CTX_set_session_cache_mode(
1081 ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
David Benjaminc273d2c2015-02-09 12:59:46 -05001082 SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
David Benjamin1b8b6912015-02-09 04:28:16 -05001083 } else {
1084 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
1085 }
David Benjamin1d5c83e2014-07-22 19:20:02 -04001086
David Benjamind4c2bce2015-10-17 12:28:18 -04001087 SSL_CTX_set_select_certificate_cb(ssl_ctx.get(), SelectCertificateCallback);
David Benjamin8f2c20e2014-07-09 09:30:38 -04001088
David Benjaminacb6dcc2016-03-10 09:15:01 -05001089 if (config->use_old_client_cert_callback) {
1090 SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
1091 }
1092
David Benjamin1f5f62b2014-07-12 16:18:02 -04001093 SSL_CTX_set_next_protos_advertised_cb(
David Benjaminc273d2c2015-02-09 12:59:46 -05001094 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -04001095 if (!config->select_next_proto.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001096 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
David Benjamina7f333d2015-02-09 02:37:18 -05001097 NULL);
David Benjaminae2888f2014-09-06 12:58:58 -04001098 }
1099
Steven Valdez2d850622017-01-11 11:34:52 -05001100 if (!config->select_alpn.empty() || !config->select_resume_alpn.empty() ||
1101 config->decline_alpn) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001102 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -04001103 }
David Benjamin1f5f62b2014-07-12 16:18:02 -04001104
David Benjaminc273d2c2015-02-09 12:59:46 -05001105 SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
David Benjamina08e49d2014-08-24 01:46:07 -04001106
David Benjamin1b22f852016-10-27 16:36:32 -04001107 SSL_CTX_set_current_time_cb(ssl_ctx.get(), CurrentTimeCallback);
David Benjamin377fc312015-01-26 00:22:12 -05001108
David Benjamin87e4acd2015-04-02 19:57:35 -04001109 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
David Benjaminba4594a2015-06-18 18:36:15 -04001110 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
David Benjamin87e4acd2015-04-02 19:57:35 -04001111
David Benjamind98452d2015-06-16 14:16:23 -04001112 if (config->use_ticket_callback) {
1113 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
1114 }
1115
Adam Langley09505632015-07-30 18:10:13 -07001116 if (config->enable_client_custom_extension &&
1117 !SSL_CTX_add_client_custom_ext(
1118 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
1119 CustomExtensionFreeCallback, kCustomExtensionAddArg,
1120 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1121 return nullptr;
1122 }
1123
1124 if (config->enable_server_custom_extension &&
1125 !SSL_CTX_add_server_custom_ext(
1126 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
1127 CustomExtensionFreeCallback, kCustomExtensionAddArg,
1128 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1129 return nullptr;
1130 }
1131
Paul Lietar8f1c2682015-08-18 12:21:54 +01001132 if (config->verify_fail) {
1133 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
1134 } else {
1135 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
1136 }
1137
Paul Lietar4fac72e2015-09-09 13:44:55 +01001138 if (!config->signed_cert_timestamps.empty() &&
1139 !SSL_CTX_set_signed_cert_timestamp_list(
1140 ssl_ctx.get(), (const uint8_t *)config->signed_cert_timestamps.data(),
1141 config->signed_cert_timestamps.size())) {
1142 return nullptr;
1143 }
1144
Adam Langley2ff79332017-02-28 13:45:39 -08001145 if (!config->use_client_ca_list.empty()) {
1146 if (config->use_client_ca_list == "<NULL>") {
1147 SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
1148 } else {
1149 bssl::UniquePtr<STACK_OF(X509_NAME)> names =
1150 DecodeHexX509Names(config->use_client_ca_list);
1151 SSL_CTX_set_client_CA_list(ssl_ctx.get(), names.release());
1152 }
David Benjamin2f8935d2016-07-13 19:47:39 -04001153 }
1154
David Benjamin65ac9972016-09-02 21:35:25 -04001155 if (config->enable_grease) {
1156 SSL_CTX_set_grease_enabled(ssl_ctx.get(), 1);
1157 }
1158
David Benjamin8b176712016-10-27 21:51:24 -04001159 if (!config->expected_server_name.empty()) {
1160 SSL_CTX_set_tlsext_servername_callback(ssl_ctx.get(), ServerNameCallback);
1161 }
1162
David Benjamin4199b0d2016-11-01 13:58:25 -04001163 if (!config->ticket_key.empty() &&
1164 !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), config->ticket_key.data(),
1165 config->ticket_key.size())) {
1166 return nullptr;
1167 }
1168
Steven Valdez08b65f42016-12-07 15:29:45 -05001169 if (config->enable_early_data) {
1170 SSL_CTX_set_early_data_enabled(ssl_ctx.get(), 1);
1171 }
1172
David Benjaminc8ff30c2017-04-04 13:52:36 -04001173 if (config->allow_unknown_alpn_protos) {
1174 SSL_CTX_set_allow_unknown_alpn_protos(ssl_ctx.get(), 1);
1175 }
1176
David Benjamin1d5c83e2014-07-22 19:20:02 -04001177 return ssl_ctx;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001178}
1179
David Benjamin40f101b2015-02-20 11:23:42 -05001180// RetryAsync is called after a failed operation on |ssl| with return code
1181// |ret|. If the operation should be retried, it simulates one asynchronous
David Benjamin6c2563e2015-04-03 03:47:47 -04001182// event and returns true. Otherwise it returns false.
1183static bool RetryAsync(SSL *ssl, int ret) {
David Benjamin43ec06f2014-08-05 02:28:57 -04001184 // No error; don't retry.
1185 if (ret >= 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001186 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001187 }
David Benjamin83f90402015-01-27 01:09:43 -05001188
David Benjamin6c2563e2015-04-03 03:47:47 -04001189 TestState *test_state = GetTestState(ssl);
Matt Braithwaite6278e242016-06-14 08:18:22 -07001190 assert(GetTestConfig(ssl)->async);
David Benjamin83f90402015-01-27 01:09:43 -05001191
David Benjamin585d7a42016-06-02 14:58:00 -04001192 if (test_state->packeted_bio != nullptr &&
1193 PacketedBioAdvanceClock(test_state->packeted_bio)) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001194 // The DTLS retransmit logic silently ignores write failures. So the test
1195 // may progress, allow writes through synchronously.
David Benjamin585d7a42016-06-02 14:58:00 -04001196 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
David Benjamin13e81fc2015-11-02 17:16:13 -05001197 int timeout_ret = DTLSv1_handle_timeout(ssl);
David Benjamin585d7a42016-06-02 14:58:00 -04001198 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
David Benjamin13e81fc2015-11-02 17:16:13 -05001199
1200 if (timeout_ret < 0) {
David Benjaminc565ebb2015-04-03 04:06:36 -04001201 fprintf(stderr, "Error retransmitting.\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001202 return false;
David Benjamin83f90402015-01-27 01:09:43 -05001203 }
David Benjamin40f101b2015-02-20 11:23:42 -05001204 return true;
David Benjamin83f90402015-01-27 01:09:43 -05001205 }
1206
David Benjamin43ec06f2014-08-05 02:28:57 -04001207 // See if we needed to read or write more. If so, allow one byte through on
1208 // the appropriate end to maximally stress the state machine.
David Benjamind9e07012015-02-09 03:04:34 -05001209 switch (SSL_get_error(ssl, ret)) {
1210 case SSL_ERROR_WANT_READ:
David Benjamin6c2563e2015-04-03 03:47:47 -04001211 AsyncBioAllowRead(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -05001212 return true;
David Benjamind9e07012015-02-09 03:04:34 -05001213 case SSL_ERROR_WANT_WRITE:
David Benjamin6c2563e2015-04-03 03:47:47 -04001214 AsyncBioAllowWrite(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -05001215 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -05001216 case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001217 bssl::UniquePtr<EVP_PKEY> pkey =
1218 LoadPrivateKey(GetTestConfig(ssl)->send_channel_id);
David Benjamin9d0847a2015-02-16 03:57:55 -05001219 if (!pkey) {
David Benjamin40f101b2015-02-20 11:23:42 -05001220 return false;
David Benjamin9d0847a2015-02-16 03:57:55 -05001221 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001222 test_state->channel_id = std::move(pkey);
David Benjamin40f101b2015-02-20 11:23:42 -05001223 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -05001224 }
David Benjamin41fdbcd2015-02-09 03:13:35 -05001225 case SSL_ERROR_WANT_X509_LOOKUP:
David Benjamin6c2563e2015-04-03 03:47:47 -04001226 test_state->cert_ready = true;
David Benjamin40f101b2015-02-20 11:23:42 -05001227 return true;
David Benjamin1b8b6912015-02-09 04:28:16 -05001228 case SSL_ERROR_PENDING_SESSION:
David Benjamin6c2563e2015-04-03 03:47:47 -04001229 test_state->session = std::move(test_state->pending_session);
David Benjamin40f101b2015-02-20 11:23:42 -05001230 return true;
David Benjamin6f5c0f42015-02-24 01:23:21 -05001231 case SSL_ERROR_PENDING_CERTIFICATE:
Alessandro Ghedini958346a2016-12-20 19:42:15 +00001232 test_state->early_callback_ready = true;
1233 return true;
David Benjaminb4d65fd2015-05-29 17:11:21 -04001234 case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
nagendra modadugu3398dbf2015-08-07 14:07:52 -07001235 test_state->private_key_retries++;
David Benjaminb4d65fd2015-05-29 17:11:21 -04001236 return true;
David Benjamind9e07012015-02-09 03:04:34 -05001237 default:
David Benjamin40f101b2015-02-20 11:23:42 -05001238 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001239 }
David Benjamin025b3d32014-07-01 19:53:04 -04001240}
1241
David Benjamin6c2563e2015-04-03 03:47:47 -04001242// DoRead reads from |ssl|, resolving any asynchronous operations. It returns
1243// the result value of the final |SSL_read| call.
1244static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
David Benjamin7e7a82d2016-05-20 20:12:42 -04001245 const TestConfig *config = GetTestConfig(ssl);
David Benjamin13e81fc2015-11-02 17:16:13 -05001246 TestState *test_state = GetTestState(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -04001247 int ret;
1248 do {
David Benjamin13e81fc2015-11-02 17:16:13 -05001249 if (config->async) {
1250 // The DTLS retransmit logic silently ignores write failures. So the test
1251 // may progress, allow writes through synchronously. |SSL_read| may
1252 // trigger a retransmit, so disconnect the write quota.
1253 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
1254 }
David Benjaminf3fbade2016-09-19 13:08:16 -04001255 ret = config->peek_then_read ? SSL_peek(ssl, out, max_out)
1256 : SSL_read(ssl, out, max_out);
David Benjamin13e81fc2015-11-02 17:16:13 -05001257 if (config->async) {
1258 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
1259 }
David Benjamin7bb1d292016-11-01 19:45:06 -04001260
1261 // Run the exporter after each read. This is to test that the exporter fails
1262 // during a renegotiation.
1263 if (config->use_exporter_between_reads) {
1264 uint8_t buf;
1265 if (!SSL_export_keying_material(ssl, &buf, 1, NULL, 0, NULL, 0, 0)) {
1266 fprintf(stderr, "failed to export keying material\n");
1267 return -1;
1268 }
1269 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001270 } while (config->async && RetryAsync(ssl, ret));
David Benjaminf3fbade2016-09-19 13:08:16 -04001271
1272 if (config->peek_then_read && ret > 0) {
1273 std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
1274
1275 // SSL_peek should synchronously return the same data.
1276 int ret2 = SSL_peek(ssl, buf.get(), ret);
1277 if (ret2 != ret ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001278 OPENSSL_memcmp(buf.get(), out, ret) != 0) {
David Benjaminf3fbade2016-09-19 13:08:16 -04001279 fprintf(stderr, "First and second SSL_peek did not match.\n");
1280 return -1;
1281 }
1282
1283 // SSL_read should synchronously return the same data and consume it.
1284 ret2 = SSL_read(ssl, buf.get(), ret);
1285 if (ret2 != ret ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001286 OPENSSL_memcmp(buf.get(), out, ret) != 0) {
David Benjaminf3fbade2016-09-19 13:08:16 -04001287 fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
1288 return -1;
1289 }
1290 }
1291
David Benjamin6c2563e2015-04-03 03:47:47 -04001292 return ret;
1293}
1294
1295// WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
1296// operations. It returns the result of the final |SSL_write| call.
1297static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -04001298 const TestConfig *config = GetTestConfig(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -04001299 int ret;
1300 do {
1301 ret = SSL_write(ssl, in, in_len);
1302 if (ret > 0) {
1303 in += ret;
1304 in_len -= ret;
1305 }
1306 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
1307 return ret;
1308}
1309
David Benjamin30789da2015-08-29 22:56:45 -04001310// DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
1311// returns the result of the final |SSL_shutdown| call.
1312static int DoShutdown(SSL *ssl) {
David Benjamin7e7a82d2016-05-20 20:12:42 -04001313 const TestConfig *config = GetTestConfig(ssl);
David Benjamin30789da2015-08-29 22:56:45 -04001314 int ret;
1315 do {
1316 ret = SSL_shutdown(ssl);
1317 } while (config->async && RetryAsync(ssl, ret));
1318 return ret;
1319}
1320
David Benjamin1d4f4c02016-07-26 18:03:08 -04001321// DoSendFatalAlert calls |SSL_send_fatal_alert|, resolving any asynchronous
1322// operations. It returns the result of the final |SSL_send_fatal_alert| call.
1323static int DoSendFatalAlert(SSL *ssl, uint8_t alert) {
1324 const TestConfig *config = GetTestConfig(ssl);
1325 int ret;
1326 do {
1327 ret = SSL_send_fatal_alert(ssl, alert);
1328 } while (config->async && RetryAsync(ssl, ret));
1329 return ret;
1330}
1331
Steven Valdez1e6f11a2016-07-27 11:10:52 -04001332static uint16_t GetProtocolVersion(const SSL *ssl) {
1333 uint16_t version = SSL_version(ssl);
1334 if (!SSL_is_dtls(ssl)) {
1335 return version;
1336 }
1337 return 0x0201 + ~version;
1338}
1339
David Benjamin91eab5c2015-06-18 18:35:46 -04001340// CheckHandshakeProperties checks, immediately after |ssl| completes its
1341// initial handshake (or False Starts), whether all the properties are
1342// consistent with the test configuration and invariants.
1343static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
David Benjamin7e7a82d2016-05-20 20:12:42 -04001344 const TestConfig *config = GetTestConfig(ssl);
David Benjamin91eab5c2015-06-18 18:35:46 -04001345
1346 if (SSL_get_current_cipher(ssl) == nullptr) {
1347 fprintf(stderr, "null cipher after handshake\n");
1348 return false;
1349 }
1350
1351 if (is_resume &&
1352 (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
1353 fprintf(stderr, "session was%s reused\n",
1354 SSL_session_reused(ssl) ? "" : " not");
1355 return false;
1356 }
1357
Steven Valdez681eb6a2016-12-19 13:19:29 -05001358 bool expect_handshake_done =
1359 (is_resume || !config->false_start) &&
1360 !(config->is_server && SSL_early_data_accepted(ssl));
David Benjamin91eab5c2015-06-18 18:35:46 -04001361 if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
1362 fprintf(stderr, "handshake was%s completed\n",
1363 GetTestState(ssl)->handshake_done ? "" : " not");
1364 return false;
1365 }
1366
David Benjaminba4594a2015-06-18 18:36:15 -04001367 if (expect_handshake_done && !config->is_server) {
1368 bool expect_new_session =
1369 !config->expect_no_session &&
Steven Valdez143e8b32016-07-11 13:19:03 -04001370 (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
Steven Valdez1e6f11a2016-07-27 11:10:52 -04001371 // Session tickets are sent post-handshake in TLS 1.3.
1372 GetProtocolVersion(ssl) < TLS1_3_VERSION;
David Benjaminba4594a2015-06-18 18:36:15 -04001373 if (expect_new_session != GetTestState(ssl)->got_new_session) {
1374 fprintf(stderr,
David Benjamindd6fed92015-10-23 17:41:12 -04001375 "new session was%s cached, but we expected the opposite\n",
David Benjaminba4594a2015-06-18 18:36:15 -04001376 GetTestState(ssl)->got_new_session ? "" : " not");
1377 return false;
1378 }
1379 }
1380
David Benjaminb5c58db2017-01-28 01:39:29 -05001381 if (!is_resume) {
1382 if (config->expect_session_id && !GetTestState(ssl)->got_new_session) {
1383 fprintf(stderr, "session was not cached on the server.\n");
1384 return false;
1385 }
1386 if (config->expect_no_session_id && GetTestState(ssl)->got_new_session) {
1387 fprintf(stderr, "session was unexpectedly cached on the server.\n");
1388 return false;
1389 }
1390 }
1391
David Benjamin91eab5c2015-06-18 18:35:46 -04001392 if (config->is_server && !GetTestState(ssl)->early_callback_called) {
1393 fprintf(stderr, "early callback not called\n");
1394 return false;
1395 }
1396
1397 if (!config->expected_server_name.empty()) {
1398 const char *server_name =
1399 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
David Benjamin8b176712016-10-27 21:51:24 -04001400 if (server_name == nullptr ||
1401 server_name != config->expected_server_name) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001402 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
1403 server_name, config->expected_server_name.c_str());
1404 return false;
1405 }
1406 }
1407
David Benjamin91eab5c2015-06-18 18:35:46 -04001408 if (!config->expected_next_proto.empty()) {
1409 const uint8_t *next_proto;
1410 unsigned next_proto_len;
1411 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
1412 if (next_proto_len != config->expected_next_proto.size() ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001413 OPENSSL_memcmp(next_proto, config->expected_next_proto.data(),
1414 next_proto_len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001415 fprintf(stderr, "negotiated next proto mismatch\n");
1416 return false;
1417 }
1418 }
1419
Steven Valdez2d850622017-01-11 11:34:52 -05001420 std::string expected_alpn = config->expected_alpn;
1421 if (is_resume && !config->expected_resume_alpn.empty()) {
1422 expected_alpn = config->expected_resume_alpn;
1423 }
1424 bool expect_no_alpn = (!is_resume && config->expect_no_alpn) ||
1425 (is_resume && config->expect_no_resume_alpn);
1426 if (expect_no_alpn) {
1427 expected_alpn.clear();
1428 }
1429
1430 if (!expected_alpn.empty() || expect_no_alpn) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001431 const uint8_t *alpn_proto;
1432 unsigned alpn_proto_len;
1433 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
Steven Valdez2d850622017-01-11 11:34:52 -05001434 if (alpn_proto_len != expected_alpn.size() ||
1435 OPENSSL_memcmp(alpn_proto, expected_alpn.data(), alpn_proto_len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001436 fprintf(stderr, "negotiated alpn proto mismatch\n");
1437 return false;
1438 }
1439 }
1440
1441 if (!config->expected_channel_id.empty()) {
1442 uint8_t channel_id[64];
1443 if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
1444 fprintf(stderr, "no channel id negotiated\n");
1445 return false;
1446 }
1447 if (config->expected_channel_id.size() != 64 ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001448 OPENSSL_memcmp(config->expected_channel_id.data(), channel_id, 64) !=
1449 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001450 fprintf(stderr, "channel id mismatch\n");
1451 return false;
1452 }
1453 }
1454
David Benjamind2610042017-01-03 10:49:28 -05001455 if (config->expect_extended_master_secret && !SSL_get_extms_support(ssl)) {
1456 fprintf(stderr, "No EMS for connection when expected\n");
1457 return false;
1458 }
1459
1460 if (config->expect_secure_renegotiation &&
1461 !SSL_get_secure_renegotiation_support(ssl)) {
1462 fprintf(stderr, "No secure renegotiation for connection when expected\n");
1463 return false;
1464 }
1465
1466 if (config->expect_no_secure_renegotiation &&
1467 SSL_get_secure_renegotiation_support(ssl)) {
1468 fprintf(stderr,
1469 "Secure renegotiation unexpectedly negotiated for connection\n");
1470 return false;
David Benjamin91eab5c2015-06-18 18:35:46 -04001471 }
1472
1473 if (!config->expected_ocsp_response.empty()) {
1474 const uint8_t *data;
1475 size_t len;
1476 SSL_get0_ocsp_response(ssl, &data, &len);
1477 if (config->expected_ocsp_response.size() != len ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001478 OPENSSL_memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001479 fprintf(stderr, "OCSP response mismatch\n");
1480 return false;
1481 }
1482 }
1483
1484 if (!config->expected_signed_cert_timestamps.empty()) {
1485 const uint8_t *data;
1486 size_t len;
1487 SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
1488 if (config->expected_signed_cert_timestamps.size() != len ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001489 OPENSSL_memcmp(config->expected_signed_cert_timestamps.data(), data,
1490 len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001491 fprintf(stderr, "SCT list mismatch\n");
1492 return false;
1493 }
1494 }
1495
Paul Lietar8f1c2682015-08-18 12:21:54 +01001496 if (config->expect_verify_result) {
1497 int expected_verify_result = config->verify_fail ?
1498 X509_V_ERR_APPLICATION_VERIFICATION :
1499 X509_V_OK;
1500
1501 if (SSL_get_verify_result(ssl) != expected_verify_result) {
1502 fprintf(stderr, "Wrong certificate verification result\n");
1503 return false;
1504 }
1505 }
1506
Nick Harper60edffd2016-06-21 15:19:24 -07001507 if (config->expect_peer_signature_algorithm != 0 &&
1508 config->expect_peer_signature_algorithm !=
1509 SSL_get_peer_signature_algorithm(ssl)) {
1510 fprintf(stderr, "Peer signature algorithm was %04x, wanted %04x.\n",
1511 SSL_get_peer_signature_algorithm(ssl),
1512 config->expect_peer_signature_algorithm);
David Benjamin6e807652015-11-02 12:02:20 -05001513 return false;
1514 }
1515
David Benjamin8a55ce42016-12-11 03:03:42 -05001516 int expect_curve_id = config->expect_curve_id;
1517 if (is_resume && config->expect_resume_curve_id != 0) {
1518 expect_curve_id = config->expect_resume_curve_id;
1519 }
1520 if (expect_curve_id != 0) {
David Benjamin9e68f192016-06-30 14:55:33 -04001521 uint16_t curve_id = SSL_get_curve_id(ssl);
David Benjamin8a55ce42016-12-11 03:03:42 -05001522 if (static_cast<uint16_t>(expect_curve_id) != curve_id) {
David Benjamin9e68f192016-06-30 14:55:33 -04001523 fprintf(stderr, "curve_id was %04x, wanted %04x\n", curve_id,
David Benjamin8a55ce42016-12-11 03:03:42 -05001524 static_cast<uint16_t>(expect_curve_id));
David Benjamin9e68f192016-06-30 14:55:33 -04001525 return false;
1526 }
1527 }
1528
David Benjaminabbbee12016-10-31 19:20:42 -04001529 uint16_t cipher_id =
1530 static_cast<uint16_t>(SSL_CIPHER_get_id(SSL_get_current_cipher(ssl)));
1531 if (config->expect_cipher_aes != 0 &&
1532 EVP_has_aes_hardware() &&
1533 static_cast<uint16_t>(config->expect_cipher_aes) != cipher_id) {
1534 fprintf(stderr, "Cipher ID was %04x, wanted %04x (has AES hardware)\n",
1535 cipher_id, static_cast<uint16_t>(config->expect_cipher_aes));
1536 return false;
1537 }
1538
1539 if (config->expect_cipher_no_aes != 0 &&
1540 !EVP_has_aes_hardware() &&
1541 static_cast<uint16_t>(config->expect_cipher_no_aes) != cipher_id) {
1542 fprintf(stderr, "Cipher ID was %04x, wanted %04x (no AES hardware)\n",
1543 cipher_id, static_cast<uint16_t>(config->expect_cipher_no_aes));
1544 return false;
1545 }
1546
Steven Valdez2d850622017-01-11 11:34:52 -05001547 if (is_resume) {
1548 if ((config->expect_accept_early_data && !SSL_early_data_accepted(ssl)) ||
1549 (config->expect_reject_early_data && SSL_early_data_accepted(ssl))) {
1550 fprintf(stderr,
1551 "Early data was%s accepted, but we expected the opposite\n",
1552 SSL_early_data_accepted(ssl) ? "" : " not");
1553 return false;
1554 }
1555 }
David Benjaminabbbee12016-10-31 19:20:42 -04001556
David Benjaminbb9e36e2016-08-03 14:14:47 -04001557 if (!config->psk.empty()) {
1558 if (SSL_get_peer_cert_chain(ssl) != nullptr) {
1559 fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
1560 return false;
1561 }
1562 } else if (!config->is_server || config->require_any_client_certificate) {
1563 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
1564 fprintf(stderr, "Received no peer certificate but expected one.\n");
David Benjamin91eab5c2015-06-18 18:35:46 -04001565 return false;
1566 }
1567 }
David Benjaminbb9e36e2016-08-03 14:14:47 -04001568
David Benjamin2c516452016-11-15 10:16:54 +09001569 if (!config->expect_peer_cert_file.empty()) {
1570 bssl::UniquePtr<X509> expect_leaf;
1571 bssl::UniquePtr<STACK_OF(X509)> expect_chain;
1572 if (!LoadCertificate(&expect_leaf, &expect_chain,
1573 config->expect_peer_cert_file)) {
1574 return false;
1575 }
1576
1577 // For historical reasons, clients report a chain with a leaf and servers
1578 // without.
1579 if (!config->is_server) {
1580 if (!sk_X509_insert(expect_chain.get(), expect_leaf.get(), 0)) {
1581 return false;
1582 }
1583 X509_up_ref(expect_leaf.get()); // sk_X509_push takes ownership.
1584 }
1585
1586 bssl::UniquePtr<X509> leaf(SSL_get_peer_certificate(ssl));
1587 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl);
1588 if (X509_cmp(leaf.get(), expect_leaf.get()) != 0) {
1589 fprintf(stderr, "Received a different leaf certificate than expected.\n");
1590 return false;
1591 }
1592
1593 if (sk_X509_num(chain) != sk_X509_num(expect_chain.get())) {
1594 fprintf(stderr, "Received a chain of length %zu instead of %zu.\n",
1595 sk_X509_num(chain), sk_X509_num(expect_chain.get()));
1596 return false;
1597 }
1598
1599 for (size_t i = 0; i < sk_X509_num(chain); i++) {
1600 if (X509_cmp(sk_X509_value(chain, i),
1601 sk_X509_value(expect_chain.get(), i)) != 0) {
1602 fprintf(stderr, "Chain certificate %zu did not match.\n",
1603 i + 1);
1604 return false;
1605 }
1606 }
1607 }
1608
David Benjaminbbaf3672016-11-17 10:53:09 +09001609 bool expected_sha256_client_cert = config->expect_sha256_client_cert_initial;
1610 if (is_resume) {
1611 expected_sha256_client_cert = config->expect_sha256_client_cert_resume;
1612 }
1613
1614 if (SSL_get_session(ssl)->peer_sha256_valid != expected_sha256_client_cert) {
1615 fprintf(stderr,
1616 "Unexpected SHA-256 client cert state: expected:%d is_resume:%d.\n",
1617 expected_sha256_client_cert, is_resume);
1618 return false;
1619 }
1620
1621 if (expected_sha256_client_cert &&
Adam Langley46db7af2017-02-01 15:49:37 -08001622 SSL_get_session(ssl)->certs != nullptr) {
David Benjaminbbaf3672016-11-17 10:53:09 +09001623 fprintf(stderr, "Have both client cert and SHA-256 hash: is_resume:%d.\n",
1624 is_resume);
1625 return false;
1626 }
1627
David Benjamin35ac5b72017-03-03 15:05:56 -05001628 if (is_resume && config->expect_ticket_age_skew != 0 &&
1629 SSL_get_ticket_age_skew(ssl) != config->expect_ticket_age_skew) {
1630 fprintf(stderr, "Ticket age skew was %" PRId32 ", wanted %d\n",
1631 SSL_get_ticket_age_skew(ssl), config->expect_ticket_age_skew);
1632 return false;
1633 }
1634
David Benjamin91eab5c2015-06-18 18:35:46 -04001635 return true;
1636}
1637
David Benjamin87c8a642015-02-21 01:54:29 -05001638// DoExchange runs a test SSL exchange against the peer. On success, it returns
1639// true and sets |*out_session| to the negotiated SSL session. If the test is a
1640// resumption attempt, |is_resume| is true and |session| is the session from the
1641// previous exchange.
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001642static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
1643 SSL_CTX *ssl_ctx, const TestConfig *config,
1644 bool is_resume, SSL_SESSION *session) {
Steven Valdez2d850622017-01-11 11:34:52 -05001645 if (is_resume && config->enable_resume_early_data) {
1646 SSL_CTX_set_early_data_enabled(ssl_ctx, 1);
1647 }
1648
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001649 bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
David Benjamina7f333d2015-02-09 02:37:18 -05001650 if (!ssl) {
David Benjamin40f101b2015-02-20 11:23:42 -05001651 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001652 }
1653
David Benjamin7e7a82d2016-05-20 20:12:42 -04001654 if (!SetTestConfig(ssl.get(), config) ||
David Benjamin2d445c02015-02-09 13:03:50 -05001655 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
David Benjamin40f101b2015-02-20 11:23:42 -05001656 return false;
Adam Langley69a01602014-11-17 17:26:55 -08001657 }
David Benjamin5a593af2014-08-11 19:51:50 -04001658
Steven Valdez2d850622017-01-11 11:34:52 -05001659 GetTestState(ssl.get())->is_resume = is_resume;
1660
Adam Langley5f0efe02015-02-20 13:03:16 -08001661 if (config->fallback_scsv &&
1662 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
1663 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001664 }
David Benjamina0486782016-10-06 19:11:32 -04001665 // Install the certificate synchronously if nothing else will handle it.
1666 if (!config->use_early_callback &&
1667 !config->use_old_client_cert_callback &&
1668 !config->async &&
1669 !InstallCertificate(ssl.get())) {
1670 return false;
David Benjamin5a593af2014-08-11 19:51:50 -04001671 }
David Benjamin5edfc8c2016-12-10 15:46:58 -05001672 if (!config->use_old_client_cert_callback) {
1673 SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
1674 }
David Benjamin5a593af2014-08-11 19:51:50 -04001675 if (config->require_any_client_certificate) {
David Benjamina7f333d2015-02-09 02:37:18 -05001676 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
Paul Lietar8f1c2682015-08-18 12:21:54 +01001677 NULL);
1678 }
1679 if (config->verify_peer) {
1680 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
David Benjamin5a593af2014-08-11 19:51:50 -04001681 }
1682 if (config->false_start) {
David Benjamined7c4752015-02-16 19:16:46 -05001683 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
David Benjamin5a593af2014-08-11 19:51:50 -04001684 }
1685 if (config->cbc_record_splitting) {
David Benjamina7f333d2015-02-09 02:37:18 -05001686 SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
David Benjamin5a593af2014-08-11 19:51:50 -04001687 }
1688 if (config->partial_write) {
David Benjamina7f333d2015-02-09 02:37:18 -05001689 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
David Benjamin5a593af2014-08-11 19:51:50 -04001690 }
Steven Valdez4f94b1c2016-05-24 12:31:07 -04001691 if (config->no_tls13) {
1692 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
1693 }
David Benjamin5a593af2014-08-11 19:51:50 -04001694 if (config->no_tls12) {
David Benjamina7f333d2015-02-09 02:37:18 -05001695 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
David Benjamin5a593af2014-08-11 19:51:50 -04001696 }
1697 if (config->no_tls11) {
David Benjamina7f333d2015-02-09 02:37:18 -05001698 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
David Benjamin5a593af2014-08-11 19:51:50 -04001699 }
1700 if (config->no_tls1) {
David Benjamina7f333d2015-02-09 02:37:18 -05001701 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
David Benjamin5a593af2014-08-11 19:51:50 -04001702 }
1703 if (config->no_ssl3) {
David Benjamina7f333d2015-02-09 02:37:18 -05001704 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
David Benjamin5a593af2014-08-11 19:51:50 -04001705 }
Steven Valdez143e8b32016-07-11 13:19:03 -04001706 if (!config->expected_channel_id.empty() ||
1707 config->enable_channel_id) {
David Benjamineebd3c82016-12-06 17:43:58 -05001708 SSL_set_tls_channel_id_enabled(ssl.get(), 1);
David Benjamina08e49d2014-08-24 01:46:07 -04001709 }
1710 if (!config->send_channel_id.empty()) {
David Benjamineebd3c82016-12-06 17:43:58 -05001711 SSL_set_tls_channel_id_enabled(ssl.get(), 1);
David Benjamind9e07012015-02-09 03:04:34 -05001712 if (!config->async) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001713 // The async case will be supplied by |ChannelIdCallback|.
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001714 bssl::UniquePtr<EVP_PKEY> pkey = LoadPrivateKey(config->send_channel_id);
David Benjamind9e07012015-02-09 03:04:34 -05001715 if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001716 return false;
David Benjamind9e07012015-02-09 03:04:34 -05001717 }
David Benjamina08e49d2014-08-24 01:46:07 -04001718 }
David Benjamina08e49d2014-08-24 01:46:07 -04001719 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001720 if (!config->host_name.empty() &&
1721 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001722 return false;
David Benjamine78bfde2014-09-06 12:45:15 -04001723 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001724 if (!config->advertise_alpn.empty() &&
1725 SSL_set_alpn_protos(ssl.get(),
1726 (const uint8_t *)config->advertise_alpn.data(),
1727 config->advertise_alpn.size()) != 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001728 return false;
David Benjaminae2888f2014-09-06 12:58:58 -04001729 }
David Benjamin48cae082014-10-27 01:06:24 -04001730 if (!config->psk.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001731 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
1732 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
David Benjamin48cae082014-10-27 01:06:24 -04001733 }
David Benjamin61f95272014-11-25 01:55:35 -05001734 if (!config->psk_identity.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001735 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001736 return false;
David Benjamin48cae082014-10-27 01:06:24 -04001737 }
David Benjamin61f95272014-11-25 01:55:35 -05001738 if (!config->srtp_profiles.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001739 !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001740 return false;
David Benjamin61f95272014-11-25 01:55:35 -05001741 }
David Benjamin26e1ff32017-02-14 20:13:00 -05001742 if (config->enable_ocsp_stapling) {
1743 SSL_enable_ocsp_stapling(ssl.get());
David Benjamin61f95272014-11-25 01:55:35 -05001744 }
David Benjamin26e1ff32017-02-14 20:13:00 -05001745 if (config->enable_signed_cert_timestamps) {
1746 SSL_enable_signed_cert_timestamps(ssl.get());
David Benjaminca6c8262014-11-15 19:06:08 -05001747 }
David Benjamin2dc02042016-09-19 19:57:37 -04001748 if (config->min_version != 0 &&
David Benjamine4706902016-09-20 15:12:23 -04001749 !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) {
David Benjamin2dc02042016-09-19 19:57:37 -04001750 return false;
David Benjamin1eb367c2014-12-12 18:17:51 -05001751 }
David Benjamin2dc02042016-09-19 19:57:37 -04001752 if (config->max_version != 0 &&
David Benjamine4706902016-09-20 15:12:23 -04001753 !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) {
David Benjamin2dc02042016-09-19 19:57:37 -04001754 return false;
David Benjamin1eb367c2014-12-12 18:17:51 -05001755 }
David Benjamin13be1de2015-01-11 16:29:36 -05001756 if (config->mtu != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001757 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
1758 SSL_set_mtu(ssl.get(), config->mtu);
David Benjamin13be1de2015-01-11 16:29:36 -05001759 }
Adam Langley524e7172015-02-20 16:04:00 -08001760 if (config->install_ddos_callback) {
1761 SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
1762 }
David Benjamin1d5ef3b2015-10-12 19:54:18 -04001763 if (config->renegotiate_once) {
1764 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_once);
1765 }
1766 if (config->renegotiate_freely) {
1767 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
David Benjaminb16346b2015-04-08 19:16:58 -04001768 }
Adam Langley27a0d082015-11-03 13:34:10 -08001769 if (config->renegotiate_ignore) {
1770 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_ignore);
1771 }
David Benjamin30789da2015-08-29 22:56:45 -04001772 if (!config->check_close_notify) {
1773 SSL_set_quiet_shutdown(ssl.get(), 1);
1774 }
David Benjamin99fdfb92015-11-02 12:11:35 -05001775 if (config->p384_only) {
1776 int nid = NID_secp384r1;
1777 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
1778 return false;
1779 }
1780 }
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001781 if (config->enable_all_curves) {
1782 static const int kAllCurves[] = {
Adam Langley764ab982017-03-10 18:01:30 -08001783 NID_secp224r1, NID_X9_62_prime256v1, NID_secp384r1,
1784 NID_secp521r1, NID_X25519,
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001785 };
1786 if (!SSL_set1_curves(ssl.get(), kAllCurves,
Steven Valdezcb966542016-08-17 16:56:14 -04001787 OPENSSL_ARRAY_SIZE(kAllCurves))) {
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001788 return false;
1789 }
1790 }
Taylor Brandstetter376a0fe2016-05-10 19:30:28 -07001791 if (config->initial_timeout_duration_ms > 0) {
1792 DTLSv1_set_initial_timeout_duration(ssl.get(),
1793 config->initial_timeout_duration_ms);
1794 }
David Benjamina252b342016-09-26 19:57:53 -04001795 if (config->max_cert_list > 0) {
1796 SSL_set_max_cert_list(ssl.get(), config->max_cert_list);
1797 }
David Benjaminbbaf3672016-11-17 10:53:09 +09001798 if (!is_resume && config->retain_only_sha256_client_cert_initial) {
1799 SSL_set_retain_only_sha256_of_client_certs(ssl.get(), 1);
1800 }
1801 if (is_resume && config->retain_only_sha256_client_cert_resume) {
1802 SSL_set_retain_only_sha256_of_client_certs(ssl.get(), 1);
1803 }
David Benjamine3fbb362017-01-06 16:19:28 -05001804 if (config->max_send_fragment > 0) {
1805 SSL_set_max_send_fragment(ssl.get(), config->max_send_fragment);
1806 }
David Benjamin025b3d32014-07-01 19:53:04 -04001807
David Benjamin87c8a642015-02-21 01:54:29 -05001808 int sock = Connect(config->port);
1809 if (sock == -1) {
1810 return false;
1811 }
1812 SocketCloser closer(sock);
1813
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001814 bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
David Benjamina7f333d2015-02-09 02:37:18 -05001815 if (!bio) {
David Benjamin40f101b2015-02-20 11:23:42 -05001816 return false;
David Benjamin43ec06f2014-08-05 02:28:57 -04001817 }
David Benjamin6fd297b2014-08-11 18:43:38 -04001818 if (config->is_dtls) {
David Benjamin11c82892017-02-23 20:40:31 -05001819 bssl::UniquePtr<BIO> packeted = PacketedBioCreate(&g_clock);
David Benjaminb7c5e842016-03-28 09:59:10 -04001820 if (!packeted) {
1821 return false;
1822 }
David Benjamin585d7a42016-06-02 14:58:00 -04001823 GetTestState(ssl.get())->packeted_bio = packeted.get();
David Benjamina7f333d2015-02-09 02:37:18 -05001824 BIO_push(packeted.get(), bio.release());
1825 bio = std::move(packeted);
David Benjamin6fd297b2014-08-11 18:43:38 -04001826 }
David Benjamin5a593af2014-08-11 19:51:50 -04001827 if (config->async) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001828 bssl::UniquePtr<BIO> async_scoped =
David Benjaminc273d2c2015-02-09 12:59:46 -05001829 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
David Benjaminb7c5e842016-03-28 09:59:10 -04001830 if (!async_scoped) {
1831 return false;
1832 }
David Benjamina7f333d2015-02-09 02:37:18 -05001833 BIO_push(async_scoped.get(), bio.release());
David Benjamin6c2563e2015-04-03 03:47:47 -04001834 GetTestState(ssl.get())->async_bio = async_scoped.get();
David Benjamina7f333d2015-02-09 02:37:18 -05001835 bio = std::move(async_scoped);
David Benjamin43ec06f2014-08-05 02:28:57 -04001836 }
David Benjamina7f333d2015-02-09 02:37:18 -05001837 SSL_set_bio(ssl.get(), bio.get(), bio.get());
1838 bio.release(); // SSL_set_bio takes ownership.
David Benjamin43ec06f2014-08-05 02:28:57 -04001839
David Benjamin1d5c83e2014-07-22 19:20:02 -04001840 if (session != NULL) {
David Benjamin1b8b6912015-02-09 04:28:16 -05001841 if (!config->is_server) {
1842 if (SSL_set_session(ssl.get(), session) != 1) {
David Benjamin40f101b2015-02-20 11:23:42 -05001843 return false;
David Benjamin1b8b6912015-02-09 04:28:16 -05001844 }
1845 } else if (config->async) {
1846 // The internal session cache is disabled, so install the session
1847 // manually.
David Benjaminb9195402016-08-05 10:51:43 -04001848 SSL_SESSION_up_ref(session);
1849 GetTestState(ssl.get())->pending_session.reset(session);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001850 }
1851 }
1852
David Benjamina07c0fc2015-05-13 13:19:42 -04001853 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1854 fprintf(stderr, "non-null cipher before handshake\n");
1855 return false;
1856 }
1857
David Benjamin4784b992017-03-25 18:22:19 -05001858 if (config->is_server) {
1859 SSL_set_accept_state(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -05001860 } else {
David Benjamin4784b992017-03-25 18:22:19 -05001861 SSL_set_connect_state(ssl.get());
1862 }
1863
1864 int ret;
1865 if (!config->implicit_handshake) {
David Benjamine0e7d0d2015-02-08 19:33:25 -05001866 do {
David Benjamin4784b992017-03-25 18:22:19 -05001867 ret = SSL_do_handshake(ssl.get());
David Benjamin6c2563e2015-04-03 03:47:47 -04001868 } while (config->async && RetryAsync(ssl.get(), ret));
David Benjamin91eab5c2015-06-18 18:35:46 -04001869 if (ret != 1 ||
1870 !CheckHandshakeProperties(ssl.get(), is_resume)) {
David Benjamin40f101b2015-02-20 11:23:42 -05001871 return false;
David Benjamine0e7d0d2015-02-08 19:33:25 -05001872 }
David Benjamin025b3d32014-07-01 19:53:04 -04001873
David Benjamin8c26d752017-03-26 15:13:51 -05001874 if (config->handshake_twice) {
1875 do {
1876 ret = SSL_do_handshake(ssl.get());
1877 } while (config->async && RetryAsync(ssl.get(), ret));
1878 if (ret != 1) {
1879 return false;
1880 }
1881 }
1882
1883 // Skip the |config->async| logic as this should be a no-op.
1884 if (config->no_op_extra_handshake &&
1885 SSL_do_handshake(ssl.get()) != 1) {
1886 fprintf(stderr, "Extra SSL_do_handshake was not a no-op.\n");
1887 return false;
1888 }
1889
David Benjaminba4594a2015-06-18 18:36:15 -04001890 // Reset the state to assert later that the callback isn't called in
1891 // renegotations.
1892 GetTestState(ssl.get())->got_new_session = false;
David Benjamin61f95272014-11-25 01:55:35 -05001893 }
1894
David Benjaminc565ebb2015-04-03 04:06:36 -04001895 if (config->export_keying_material > 0) {
1896 std::vector<uint8_t> result(
1897 static_cast<size_t>(config->export_keying_material));
1898 if (!SSL_export_keying_material(
1899 ssl.get(), result.data(), result.size(),
1900 config->export_label.data(), config->export_label.size(),
1901 reinterpret_cast<const uint8_t*>(config->export_context.data()),
1902 config->export_context.size(), config->use_export_context)) {
1903 fprintf(stderr, "failed to export keying material\n");
1904 return false;
1905 }
1906 if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1907 return false;
1908 }
1909 }
1910
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001911 if (config->tls_unique) {
1912 uint8_t tls_unique[16];
1913 size_t tls_unique_len;
1914 if (!SSL_get_tls_unique(ssl.get(), tls_unique, &tls_unique_len,
1915 sizeof(tls_unique))) {
1916 fprintf(stderr, "failed to get tls-unique\n");
1917 return false;
1918 }
1919
1920 if (tls_unique_len != 12) {
1921 fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
1922 static_cast<unsigned>(tls_unique_len));
1923 return false;
1924 }
1925
1926 if (WriteAll(ssl.get(), tls_unique, tls_unique_len) < 0) {
1927 return false;
1928 }
1929 }
1930
David Benjamin1d4f4c02016-07-26 18:03:08 -04001931 if (config->send_alert) {
1932 if (DoSendFatalAlert(ssl.get(), SSL_AD_DECOMPRESSION_FAILURE) < 0) {
1933 return false;
1934 }
1935 return true;
1936 }
1937
David Benjamin5a593af2014-08-11 19:51:50 -04001938 if (config->write_different_record_sizes) {
David Benjamin6fd297b2014-08-11 18:43:38 -04001939 if (config->is_dtls) {
1940 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001941 return false;
David Benjamin6fd297b2014-08-11 18:43:38 -04001942 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001943 // This mode writes a number of different record sizes in an attempt to
1944 // trip up the CBC record splitting code.
Adam Langleybc949292015-06-18 21:32:44 -07001945 static const size_t kBufLen = 32769;
1946 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
David Benjamin17cf2cb2016-12-13 01:07:13 -05001947 OPENSSL_memset(buf.get(), 0x42, kBufLen);
Kenny Root7fdeaf12014-08-05 15:23:37 -07001948 static const size_t kRecordSizes[] = {
1949 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
Steven Valdezcb966542016-08-17 16:56:14 -04001950 for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07001951 const size_t len = kRecordSizes[i];
Adam Langleybc949292015-06-18 21:32:44 -07001952 if (len > kBufLen) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07001953 fprintf(stderr, "Bad kRecordSizes value.\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001954 return false;
Kenny Root7fdeaf12014-08-05 15:23:37 -07001955 }
Adam Langleybc949292015-06-18 21:32:44 -07001956 if (WriteAll(ssl.get(), buf.get(), len) < 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001957 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001958 }
1959 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001960 } else {
David Benjamina1eaba12017-01-01 23:19:22 -05001961 if (config->read_with_unfinished_write) {
1962 if (!config->async) {
1963 fprintf(stderr, "-read-with-unfinished-write requires -async.\n");
1964 return false;
1965 }
1966
1967 int write_ret = SSL_write(ssl.get(),
1968 reinterpret_cast<const uint8_t *>("unfinished"), 10);
1969 if (SSL_get_error(ssl.get(), write_ret) != SSL_ERROR_WANT_WRITE) {
1970 fprintf(stderr, "Failed to leave unfinished write.\n");
1971 return false;
1972 }
1973 }
David Benjamine58c4f52014-08-24 03:47:07 -04001974 if (config->shim_writes_first) {
David Benjamin6c2563e2015-04-03 03:47:47 -04001975 if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1976 5) < 0) {
1977 return false;
1978 }
David Benjamine58c4f52014-08-24 03:47:07 -04001979 }
David Benjamin30789da2015-08-29 22:56:45 -04001980 if (!config->shim_shuts_down) {
1981 for (;;) {
David Benjamin2c99d282015-09-01 10:23:00 -04001982 // Read only 512 bytes at a time in TLS to ensure records may be
1983 // returned in multiple reads.
David Benjamine3fbb362017-01-06 16:19:28 -05001984 size_t read_size = config->is_dtls ? 16384 : 512;
1985 if (config->read_size > 0) {
1986 read_size = config->read_size;
1987 }
1988 std::unique_ptr<uint8_t[]> buf(new uint8_t[read_size]);
1989
1990 int n = DoRead(ssl.get(), buf.get(), read_size);
David Benjamin30789da2015-08-29 22:56:45 -04001991 int err = SSL_get_error(ssl.get(), n);
1992 if (err == SSL_ERROR_ZERO_RETURN ||
1993 (n == 0 && err == SSL_ERROR_SYSCALL)) {
1994 if (n != 0) {
1995 fprintf(stderr, "Invalid SSL_get_error output\n");
1996 return false;
1997 }
1998 // Stop on either clean or unclean shutdown.
1999 break;
2000 } else if (err != SSL_ERROR_NONE) {
2001 if (n > 0) {
2002 fprintf(stderr, "Invalid SSL_get_error output\n");
2003 return false;
2004 }
2005 return false;
2006 }
2007 // Successfully read data.
2008 if (n <= 0) {
David Benjamin9a38e922015-01-22 16:06:11 -05002009 fprintf(stderr, "Invalid SSL_get_error output\n");
David Benjamin40f101b2015-02-20 11:23:42 -05002010 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05002011 }
David Benjamin30789da2015-08-29 22:56:45 -04002012
2013 // After a successful read, with or without False Start, the handshake
Steven Valdez681eb6a2016-12-19 13:19:29 -05002014 // must be complete unless we are doing early data.
2015 if (!GetTestState(ssl.get())->handshake_done &&
2016 !SSL_early_data_accepted(ssl.get())) {
David Benjamin30789da2015-08-29 22:56:45 -04002017 fprintf(stderr, "handshake was not completed after SSL_read\n");
David Benjamin40f101b2015-02-20 11:23:42 -05002018 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05002019 }
David Benjamin87e4acd2015-04-02 19:57:35 -04002020
David Benjamin30789da2015-08-29 22:56:45 -04002021 for (int i = 0; i < n; i++) {
2022 buf[i] ^= 0xff;
2023 }
Adam Langleya0a8dc22015-09-09 10:22:00 -07002024 if (WriteAll(ssl.get(), buf.get(), n) < 0) {
David Benjamin30789da2015-08-29 22:56:45 -04002025 return false;
2026 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07002027 }
2028 }
David Benjamin025b3d32014-07-01 19:53:04 -04002029 }
2030
David Benjaminba4594a2015-06-18 18:36:15 -04002031 if (!config->is_server && !config->false_start &&
2032 !config->implicit_handshake &&
Steven Valdez1e6f11a2016-07-27 11:10:52 -04002033 // Session tickets are sent post-handshake in TLS 1.3.
2034 GetProtocolVersion(ssl.get()) < TLS1_3_VERSION &&
David Benjaminba4594a2015-06-18 18:36:15 -04002035 GetTestState(ssl.get())->got_new_session) {
2036 fprintf(stderr, "new session was established after the handshake\n");
2037 return false;
2038 }
2039
Steven Valdez1e6f11a2016-07-27 11:10:52 -04002040 if (GetProtocolVersion(ssl.get()) >= TLS1_3_VERSION && !config->is_server) {
2041 bool expect_new_session =
2042 !config->expect_no_session && !config->shim_shuts_down;
2043 if (expect_new_session != GetTestState(ssl.get())->got_new_session) {
2044 fprintf(stderr,
2045 "new session was%s cached, but we expected the opposite\n",
2046 GetTestState(ssl.get())->got_new_session ? "" : " not");
2047 return false;
2048 }
Steven Valdez08b65f42016-12-07 15:29:45 -05002049
2050 if (expect_new_session) {
2051 bool got_early_data_info =
2052 GetTestState(ssl.get())->new_session->ticket_max_early_data != 0;
2053 if (config->expect_early_data_info != got_early_data_info) {
2054 fprintf(
2055 stderr,
2056 "new session did%s include ticket_early_data_info, but we expected "
2057 "the opposite\n",
2058 got_early_data_info ? "" : " not");
2059 return false;
2060 }
2061 }
Steven Valdez1e6f11a2016-07-27 11:10:52 -04002062 }
2063
David Benjamin1d5c83e2014-07-22 19:20:02 -04002064 if (out_session) {
Steven Valdez4aa154e2016-07-29 14:32:55 -04002065 *out_session = std::move(GetTestState(ssl.get())->new_session);
David Benjamin1d5c83e2014-07-22 19:20:02 -04002066 }
2067
David Benjamin30789da2015-08-29 22:56:45 -04002068 ret = DoShutdown(ssl.get());
2069
2070 if (config->shim_shuts_down && config->check_close_notify) {
2071 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
2072 // it returns zero when our close_notify is sent, then one when the peer's
2073 // is received.
2074 if (ret != 0) {
2075 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
2076 return false;
2077 }
2078 ret = DoShutdown(ssl.get());
2079 }
2080
2081 if (ret != 1) {
2082 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
2083 return false;
2084 }
2085
David Benjamin324dce42015-10-12 19:49:00 -04002086 if (SSL_total_renegotiations(ssl.get()) !=
2087 config->expect_total_renegotiations) {
2088 fprintf(stderr, "Expected %d renegotiations, got %d\n",
2089 config->expect_total_renegotiations,
2090 SSL_total_renegotiations(ssl.get()));
2091 return false;
2092 }
2093
David Benjamin40f101b2015-02-20 11:23:42 -05002094 return true;
David Benjamin025b3d32014-07-01 19:53:04 -04002095}
David Benjamin1d5c83e2014-07-22 19:20:02 -04002096
David Benjaminff3a1492016-03-02 10:12:06 -05002097class StderrDelimiter {
2098 public:
2099 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
2100};
2101
David Benjaminaac1e2d2016-12-06 22:35:41 -05002102int main(int argc, char **argv) {
David Benjaminff3a1492016-03-02 10:12:06 -05002103 // To distinguish ASan's output from ours, add a trailing message to stderr.
2104 // Anything following this line will be considered an error.
2105 StderrDelimiter delimiter;
2106
David Benjamin87c8a642015-02-21 01:54:29 -05002107#if defined(OPENSSL_WINDOWS)
2108 /* Initialize Winsock. */
2109 WORD wsa_version = MAKEWORD(2, 2);
2110 WSADATA wsa_data;
2111 int wsa_err = WSAStartup(wsa_version, &wsa_data);
2112 if (wsa_err != 0) {
2113 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
2114 return 1;
2115 }
2116 if (wsa_data.wVersion != wsa_version) {
2117 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
2118 return 1;
2119 }
2120#else
David Benjamin1d5c83e2014-07-22 19:20:02 -04002121 signal(SIGPIPE, SIG_IGN);
Adam Langleyded93582014-07-31 15:23:51 -07002122#endif
David Benjamin1d5c83e2014-07-22 19:20:02 -04002123
David Benjamin7a1eefd2015-10-17 23:39:22 -04002124 CRYPTO_library_init();
David Benjamind9e07012015-02-09 03:04:34 -05002125 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
David Benjamin2d445c02015-02-09 13:03:50 -05002126 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
David Benjamin6c2563e2015-04-03 03:47:47 -04002127 if (g_config_index < 0 || g_state_index < 0) {
David Benjaminae3e4872014-11-18 21:52:26 -05002128 return 1;
2129 }
David Benjamin5a593af2014-08-11 19:51:50 -04002130
2131 TestConfig config;
2132 if (!ParseConfig(argc - 1, argv + 1, &config)) {
David Benjaminc273d2c2015-02-09 12:59:46 -05002133 return Usage(argv[0]);
David Benjamin1d5c83e2014-07-22 19:20:02 -04002134 }
2135
Adam Langleyd519bf62016-12-12 11:16:44 -08002136 g_pool = CRYPTO_BUFFER_POOL_new();
2137
David Benjamin1b22f852016-10-27 16:36:32 -04002138 // Some code treats the zero time special, so initialize the clock to a
2139 // non-zero time.
2140 g_clock.tv_sec = 1234;
2141 g_clock.tv_usec = 1234;
2142
Matt Braithwaited17d74d2016-08-17 20:10:28 -07002143 bssl::UniquePtr<SSL_CTX> ssl_ctx = SetupCtx(&config);
David Benjamina7f333d2015-02-09 02:37:18 -05002144 if (!ssl_ctx) {
Brian Smith83a82982015-04-09 16:21:10 -10002145 ERR_print_errors_fp(stderr);
David Benjamin1d5c83e2014-07-22 19:20:02 -04002146 return 1;
2147 }
2148
Matt Braithwaited17d74d2016-08-17 20:10:28 -07002149 bssl::UniquePtr<SSL_SESSION> session;
David Benjamin46662482016-08-17 00:51:00 -04002150 for (int i = 0; i < config.resume_count + 1; i++) {
2151 bool is_resume = i > 0;
2152 if (is_resume && !config.is_server && !session) {
2153 fprintf(stderr, "No session to offer.\n");
2154 return 1;
2155 }
David Benjamin1d5c83e2014-07-22 19:20:02 -04002156
Matt Braithwaited17d74d2016-08-17 20:10:28 -07002157 bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
David Benjamin46662482016-08-17 00:51:00 -04002158 if (!DoExchange(&session, ssl_ctx.get(), &config, is_resume,
2159 offer_session.get())) {
2160 fprintf(stderr, "Connection %d failed.\n", i + 1);
2161 ERR_print_errors_fp(stderr);
2162 return 1;
2163 }
Steven Valdeza833c352016-11-01 13:39:36 -04002164
2165 if (config.resumption_delay != 0) {
2166 g_clock.tv_sec += config.resumption_delay;
2167 }
David Benjamin1d5c83e2014-07-22 19:20:02 -04002168 }
2169
David Benjamina7f333d2015-02-09 02:37:18 -05002170 return 0;
David Benjamin1d5c83e2014-07-22 19:20:02 -04002171}