blob: cd846be49d6baefbed9f463170cc4246d869d8d8 [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 Benjaminc3864402017-07-14 16:48:36 -040042#include <time.h>
David Benjamin025b3d32014-07-01 19:53:04 -040043
David Benjaminabbbee12016-10-31 19:20:42 -040044#include <openssl/aead.h>
David Benjamin025b3d32014-07-01 19:53:04 -040045#include <openssl/bio.h>
David Benjamin48cae082014-10-27 01:06:24 -040046#include <openssl/buf.h>
David Benjamin8f2c20e2014-07-09 09:30:38 -040047#include <openssl/bytestring.h>
David Benjamind98452d2015-06-16 14:16:23 -040048#include <openssl/cipher.h>
David Benjamin7a1eefd2015-10-17 23:39:22 -040049#include <openssl/crypto.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"
Steven Valdez873ebc92017-05-09 12:12:58 -040064#include "../internal.h"
David Benjamin43ec06f2014-08-05 02:28:57 -040065#include "async_bio.h"
David Benjamin0fde2eb2017-06-30 19:11:22 -040066#include "fuzzer.h"
David Benjamin6fd297b2014-08-11 18:43:38 -040067#include "packeted_bio.h"
David Benjamin5a593af2014-08-11 19:51:50 -040068#include "test_config.h"
David Benjamin43ec06f2014-08-05 02:28:57 -040069
David Benjamin87c8a642015-02-21 01:54:29 -050070
Adam Langleyd519bf62016-12-12 11:16:44 -080071static CRYPTO_BUFFER_POOL *g_pool = nullptr;
72
David Benjamin87c8a642015-02-21 01:54:29 -050073#if !defined(OPENSSL_WINDOWS)
74static int closesocket(int sock) {
75 return close(sock);
76}
77
78static void PrintSocketError(const char *func) {
79 perror(func);
80}
81#else
82static void PrintSocketError(const char *func) {
83 fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
84}
85#endif
86
David Benjaminc273d2c2015-02-09 12:59:46 -050087static int Usage(const char *program) {
David Benjamina7f333d2015-02-09 02:37:18 -050088 fprintf(stderr, "Usage: %s [flags...]\n", program);
David Benjamin1d5c83e2014-07-22 19:20:02 -040089 return 1;
90}
David Benjamin025b3d32014-07-01 19:53:04 -040091
David Benjamin2d445c02015-02-09 13:03:50 -050092struct TestState {
David Benjamin6c2563e2015-04-03 03:47:47 -040093 // async_bio is async BIO which pauses reads and writes.
94 BIO *async_bio = nullptr;
David Benjamin585d7a42016-06-02 14:58:00 -040095 // packeted_bio is the packeted BIO which simulates read timeouts.
96 BIO *packeted_bio = nullptr;
Matt Braithwaited17d74d2016-08-17 20:10:28 -070097 bssl::UniquePtr<EVP_PKEY> channel_id;
David Benjamin0d4db502015-03-23 18:46:05 -040098 bool cert_ready = false;
Matt Braithwaited17d74d2016-08-17 20:10:28 -070099 bssl::UniquePtr<SSL_SESSION> session;
100 bssl::UniquePtr<SSL_SESSION> pending_session;
David Benjamin0d4db502015-03-23 18:46:05 -0400101 bool early_callback_called = false;
David Benjamin87e4acd2015-04-02 19:57:35 -0400102 bool handshake_done = false;
David Benjaminb4d65fd2015-05-29 17:11:21 -0400103 // private_key is the underlying private key used when testing custom keys.
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700104 bssl::UniquePtr<EVP_PKEY> private_key;
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700105 std::vector<uint8_t> private_key_result;
106 // private_key_retries is the number of times an asynchronous private key
107 // operation has been retried.
108 unsigned private_key_retries = 0;
David Benjaminba4594a2015-06-18 18:36:15 -0400109 bool got_new_session = false;
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700110 bssl::UniquePtr<SSL_SESSION> new_session;
David Benjamin25fe85b2016-08-09 20:00:32 -0400111 bool ticket_decrypt_done = false;
112 bool alpn_select_done = false;
Steven Valdez2d850622017-01-11 11:34:52 -0500113 bool is_resume = false;
Alessandro Ghedini958346a2016-12-20 19:42:15 +0000114 bool early_callback_ready = false;
David Benjamind9e07012015-02-09 03:04:34 -0500115};
116
David Benjamin2d445c02015-02-09 13:03:50 -0500117static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
Adam Langley09505632015-07-30 18:10:13 -0700118 int index, long argl, void *argp) {
David Benjamin2d445c02015-02-09 13:03:50 -0500119 delete ((TestState *)ptr);
David Benjamind9e07012015-02-09 03:04:34 -0500120}
121
122static int g_config_index = 0;
David Benjamin2d445c02015-02-09 13:03:50 -0500123static int g_state_index = 0;
David Benjamin5a593af2014-08-11 19:51:50 -0400124
David Benjamin7e7a82d2016-05-20 20:12:42 -0400125static bool SetTestConfig(SSL *ssl, const TestConfig *config) {
David Benjamind9e07012015-02-09 03:04:34 -0500126 return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
David Benjamin5a593af2014-08-11 19:51:50 -0400127}
128
David Benjamin7e7a82d2016-05-20 20:12:42 -0400129static const TestConfig *GetTestConfig(const SSL *ssl) {
David Benjamind9e07012015-02-09 03:04:34 -0500130 return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
David Benjamin5a593af2014-08-11 19:51:50 -0400131}
132
David Benjamin22050932015-11-23 13:44:48 -0500133static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
134 // |SSL_set_ex_data| takes ownership of |state| only on success.
135 if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
136 state.release();
David Benjamind9e07012015-02-09 03:04:34 -0500137 return true;
138 }
139 return false;
140}
141
David Benjamin87e4acd2015-04-02 19:57:35 -0400142static TestState *GetTestState(const SSL *ssl) {
David Benjamin2d445c02015-02-09 13:03:50 -0500143 return (TestState *)SSL_get_ex_data(ssl, g_state_index);
David Benjamin83f90402015-01-27 01:09:43 -0500144}
145
David Benjamin2c516452016-11-15 10:16:54 +0900146static bool LoadCertificate(bssl::UniquePtr<X509> *out_x509,
147 bssl::UniquePtr<STACK_OF(X509)> *out_chain,
148 const std::string &file) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700149 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
David Benjaminacb6dcc2016-03-10 09:15:01 -0500150 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
David Benjamin2c516452016-11-15 10:16:54 +0900151 return false;
David Benjaminacb6dcc2016-03-10 09:15:01 -0500152 }
David Benjamin2c516452016-11-15 10:16:54 +0900153
154 out_x509->reset(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
155 if (!*out_x509) {
156 return false;
157 }
158
159 out_chain->reset(sk_X509_new_null());
160 if (!*out_chain) {
161 return false;
162 }
163
164 // Keep reading the certificate chain.
165 for (;;) {
166 bssl::UniquePtr<X509> cert(
167 PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
168 if (!cert) {
169 break;
170 }
171
172 if (!sk_X509_push(out_chain->get(), cert.get())) {
173 return false;
174 }
175 cert.release(); // sk_X509_push takes ownership.
176 }
177
178 uint32_t err = ERR_peek_last_error();
179 if (ERR_GET_LIB(err) != ERR_LIB_PEM ||
180 ERR_GET_REASON(err) != PEM_R_NO_START_LINE) {
181 return false;
182}
183
184 ERR_clear_error();
185 return true;
David Benjaminacb6dcc2016-03-10 09:15:01 -0500186}
187
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700188static bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
189 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
David Benjamina7f333d2015-02-09 02:37:18 -0500190 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
191 return nullptr;
David Benjamina08e49d2014-08-24 01:46:07 -0400192 }
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700193 return bssl::UniquePtr<EVP_PKEY>(
194 PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
David Benjamina08e49d2014-08-24 01:46:07 -0400195}
196
Adam Langley2ff79332017-02-28 13:45:39 -0800197static bool FromHexDigit(uint8_t *out, char c) {
198 if ('0' <= c && c <= '9') {
199 *out = c - '0';
200 return true;
201 }
202 if ('a' <= c && c <= 'f') {
203 *out = c - 'a' + 10;
204 return true;
205 }
206 if ('A' <= c && c <= 'F') {
207 *out = c - 'A' + 10;
208 return true;
209 }
210 return false;
211}
212
213static bool HexDecode(std::string *out, const std::string &in) {
214 if ((in.size() & 1) != 0) {
215 return false;
216 }
217
218 std::unique_ptr<uint8_t[]> buf(new uint8_t[in.size() / 2]);
219 for (size_t i = 0; i < in.size() / 2; i++) {
220 uint8_t high, low;
221 if (!FromHexDigit(&high, in[i*2]) ||
222 !FromHexDigit(&low, in[i*2+1])) {
223 return false;
224 }
225 buf[i] = (high << 4) | low;
226 }
227
228 out->assign(reinterpret_cast<const char *>(buf.get()), in.size() / 2);
229 return true;
230}
231
232static std::vector<std::string> SplitParts(const std::string &in,
233 const char delim) {
234 std::vector<std::string> ret;
235 size_t start = 0;
236
237 for (size_t i = 0; i < in.size(); i++) {
238 if (in[i] == delim) {
239 ret.push_back(in.substr(start, i - start));
240 start = i + 1;
241 }
242 }
243
244 ret.push_back(in.substr(start, std::string::npos));
245 return ret;
246}
247
248static std::vector<std::string> DecodeHexStrings(
249 const std::string &hex_strings) {
250 std::vector<std::string> ret;
251 const std::vector<std::string> parts = SplitParts(hex_strings, ',');
252
253 for (const auto &part : parts) {
254 std::string binary;
255 if (!HexDecode(&binary, part)) {
256 fprintf(stderr, "Bad hex string: %s\n", part.c_str());
257 return ret;
258 }
259
260 ret.push_back(binary);
261 }
262
263 return ret;
264}
265
266static bssl::UniquePtr<STACK_OF(X509_NAME)> DecodeHexX509Names(
267 const std::string &hex_names) {
268 const std::vector<std::string> der_names = DecodeHexStrings(hex_names);
269 bssl::UniquePtr<STACK_OF(X509_NAME)> ret(sk_X509_NAME_new_null());
David Benjamin0391f162017-06-15 15:27:59 -0400270 if (!ret) {
271 return nullptr;
272 }
Adam Langley2ff79332017-02-28 13:45:39 -0800273
274 for (const auto &der_name : der_names) {
275 const uint8_t *const data =
276 reinterpret_cast<const uint8_t *>(der_name.data());
277 const uint8_t *derp = data;
278 bssl::UniquePtr<X509_NAME> name(
279 d2i_X509_NAME(nullptr, &derp, der_name.size()));
280 if (!name || derp != data + der_name.size()) {
281 fprintf(stderr, "Failed to parse X509_NAME.\n");
282 return nullptr;
283 }
284
285 if (!sk_X509_NAME_push(ret.get(), name.get())) {
286 return nullptr;
287 }
288 name.release();
289 }
290
291 return ret;
292}
293
David Benjaminb4d65fd2015-05-29 17:11:21 -0400294static ssl_private_key_result_t AsyncPrivateKeySign(
295 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
David Benjamind3440b42016-07-14 14:52:41 -0400296 uint16_t signature_algorithm, const uint8_t *in, size_t in_len) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400297 TestState *test_state = GetTestState(ssl);
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700298 if (!test_state->private_key_result.empty()) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400299 fprintf(stderr, "AsyncPrivateKeySign called with operation pending.\n");
300 abort();
301 }
302
David Benjamind3440b42016-07-14 14:52:41 -0400303 // Determine the hash.
304 const EVP_MD *md;
305 switch (signature_algorithm) {
306 case SSL_SIGN_RSA_PKCS1_SHA1:
307 case SSL_SIGN_ECDSA_SHA1:
308 md = EVP_sha1();
309 break;
310 case SSL_SIGN_RSA_PKCS1_SHA256:
311 case SSL_SIGN_ECDSA_SECP256R1_SHA256:
312 case SSL_SIGN_RSA_PSS_SHA256:
313 md = EVP_sha256();
314 break;
315 case SSL_SIGN_RSA_PKCS1_SHA384:
316 case SSL_SIGN_ECDSA_SECP384R1_SHA384:
317 case SSL_SIGN_RSA_PSS_SHA384:
318 md = EVP_sha384();
319 break;
320 case SSL_SIGN_RSA_PKCS1_SHA512:
321 case SSL_SIGN_ECDSA_SECP521R1_SHA512:
322 case SSL_SIGN_RSA_PSS_SHA512:
323 md = EVP_sha512();
324 break;
325 case SSL_SIGN_RSA_PKCS1_MD5_SHA1:
326 md = EVP_md5_sha1();
327 break;
David Benjamin69522112017-03-28 15:38:29 -0500328 case SSL_SIGN_ED25519:
329 md = nullptr;
330 break;
David Benjamind3440b42016-07-14 14:52:41 -0400331 default:
332 fprintf(stderr, "Unknown signature algorithm %04x.\n",
333 signature_algorithm);
334 return ssl_private_key_failure;
335 }
336
David Benjamin19670942017-05-31 19:07:31 -0400337 bssl::ScopedEVP_MD_CTX ctx;
338 EVP_PKEY_CTX *pctx;
339 if (!EVP_DigestSignInit(ctx.get(), &pctx, md, nullptr,
340 test_state->private_key.get())) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400341 return ssl_private_key_failure;
342 }
343
David Benjamind3440b42016-07-14 14:52:41 -0400344 // Configure additional signature parameters.
345 switch (signature_algorithm) {
346 case SSL_SIGN_RSA_PSS_SHA256:
347 case SSL_SIGN_RSA_PSS_SHA384:
348 case SSL_SIGN_RSA_PSS_SHA512:
David Benjamin19670942017-05-31 19:07:31 -0400349 if (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) ||
350 !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
David Benjamind3440b42016-07-14 14:52:41 -0400351 -1 /* salt len = hash len */)) {
352 return ssl_private_key_failure;
353 }
354 }
355
David Benjaminb4d65fd2015-05-29 17:11:21 -0400356 // Write the signature into |test_state|.
357 size_t len = 0;
David Benjamin19670942017-05-31 19:07:31 -0400358 if (!EVP_DigestSign(ctx.get(), nullptr, &len, in, in_len)) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400359 return ssl_private_key_failure;
360 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700361 test_state->private_key_result.resize(len);
David Benjamin19670942017-05-31 19:07:31 -0400362 if (!EVP_DigestSign(ctx.get(), test_state->private_key_result.data(), &len,
363 in, in_len)) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400364 return ssl_private_key_failure;
365 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700366 test_state->private_key_result.resize(len);
David Benjaminb4d65fd2015-05-29 17:11:21 -0400367
David Benjamind3440b42016-07-14 14:52:41 -0400368 // The signature will be released asynchronously in |AsyncPrivateKeyComplete|.
David Benjaminb4d65fd2015-05-29 17:11:21 -0400369 return ssl_private_key_retry;
370}
371
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700372static ssl_private_key_result_t AsyncPrivateKeyDecrypt(
373 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
374 const uint8_t *in, size_t in_len) {
375 TestState *test_state = GetTestState(ssl);
376 if (!test_state->private_key_result.empty()) {
377 fprintf(stderr,
378 "AsyncPrivateKeyDecrypt called with operation pending.\n");
379 abort();
380 }
381
David Benjamin758d1272015-11-20 17:47:25 -0500382 RSA *rsa = EVP_PKEY_get0_RSA(test_state->private_key.get());
383 if (rsa == NULL) {
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700384 fprintf(stderr,
385 "AsyncPrivateKeyDecrypt called with incorrect key type.\n");
386 abort();
387 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700388 test_state->private_key_result.resize(RSA_size(rsa));
David Benjaminef14b2d2015-11-11 14:01:27 -0800389 if (!RSA_decrypt(rsa, out_len, test_state->private_key_result.data(),
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700390 RSA_size(rsa), in, in_len, RSA_NO_PADDING)) {
391 return ssl_private_key_failure;
392 }
393
394 test_state->private_key_result.resize(*out_len);
395
David Benjamind3440b42016-07-14 14:52:41 -0400396 // The decryption will be released asynchronously in |AsyncPrivateComplete|.
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700397 return ssl_private_key_retry;
398}
399
David Benjamind3440b42016-07-14 14:52:41 -0400400static ssl_private_key_result_t AsyncPrivateKeyComplete(
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700401 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
402 TestState *test_state = GetTestState(ssl);
403 if (test_state->private_key_result.empty()) {
404 fprintf(stderr,
David Benjamind3440b42016-07-14 14:52:41 -0400405 "AsyncPrivateKeyComplete called without operation pending.\n");
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700406 abort();
407 }
408
409 if (test_state->private_key_retries < 2) {
410 // Only return the decryption on the second attempt, to test both incomplete
411 // |decrypt| and |decrypt_complete|.
412 return ssl_private_key_retry;
413 }
414
415 if (max_out < test_state->private_key_result.size()) {
416 fprintf(stderr, "Output buffer too small.\n");
417 return ssl_private_key_failure;
418 }
David Benjamin17cf2cb2016-12-13 01:07:13 -0500419 OPENSSL_memcpy(out, test_state->private_key_result.data(),
420 test_state->private_key_result.size());
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700421 *out_len = test_state->private_key_result.size();
422
423 test_state->private_key_result.clear();
424 test_state->private_key_retries = 0;
David Benjaminb4d65fd2015-05-29 17:11:21 -0400425 return ssl_private_key_success;
426}
427
428static const SSL_PRIVATE_KEY_METHOD g_async_private_key_method = {
David Benjamina232a712017-03-30 15:51:53 -0500429 nullptr /* type */,
430 nullptr /* max_signature_len */,
David Benjaminb4d65fd2015-05-29 17:11:21 -0400431 AsyncPrivateKeySign,
David Benjamind3440b42016-07-14 14:52:41 -0400432 nullptr /* sign_digest */,
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700433 AsyncPrivateKeyDecrypt,
David Benjamind3440b42016-07-14 14:52:41 -0400434 AsyncPrivateKeyComplete,
David Benjaminb4d65fd2015-05-29 17:11:21 -0400435};
436
Steven Valdez0d62f262015-09-04 12:41:04 -0400437template<typename T>
Adam Langley10f97f32016-07-12 08:09:33 -0700438struct Free {
Steven Valdez0d62f262015-09-04 12:41:04 -0400439 void operator()(T *buf) {
440 free(buf);
441 }
442};
443
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700444static bool GetCertificate(SSL *ssl, bssl::UniquePtr<X509> *out_x509,
David Benjamin2c516452016-11-15 10:16:54 +0900445 bssl::UniquePtr<STACK_OF(X509)> *out_chain,
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700446 bssl::UniquePtr<EVP_PKEY> *out_pkey) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400447 const TestConfig *config = GetTestConfig(ssl);
Steven Valdez0d62f262015-09-04 12:41:04 -0400448
449 if (!config->digest_prefs.empty()) {
David Benjamin8ba6a142017-05-05 20:49:53 -0400450 bssl::UniquePtr<char> digest_prefs(
451 OPENSSL_strdup(config->digest_prefs.c_str()));
Steven Valdez0d62f262015-09-04 12:41:04 -0400452 std::vector<int> digest_list;
453
454 for (;;) {
Adam Langley67251f22015-09-23 15:01:07 -0700455 char *token =
456 strtok(digest_list.empty() ? digest_prefs.get() : nullptr, ",");
Steven Valdez0d62f262015-09-04 12:41:04 -0400457 if (token == nullptr) {
458 break;
459 }
460
461 digest_list.push_back(EVP_MD_type(EVP_get_digestbyname(token)));
462 }
463
464 if (!SSL_set_private_key_digest_prefs(ssl, digest_list.data(),
465 digest_list.size())) {
466 return false;
467 }
468 }
469
David Benjaminca3d5452016-07-14 12:51:01 -0400470 if (!config->signing_prefs.empty()) {
471 std::vector<uint16_t> u16s(config->signing_prefs.begin(),
472 config->signing_prefs.end());
473 if (!SSL_set_signing_algorithm_prefs(ssl, u16s.data(), u16s.size())) {
474 return false;
475 }
476 }
477
David Benjaminb4d65fd2015-05-29 17:11:21 -0400478 if (!config->key_file.empty()) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500479 *out_pkey = LoadPrivateKey(config->key_file.c_str());
480 if (!*out_pkey) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400481 return false;
482 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500483 }
David Benjamin2c516452016-11-15 10:16:54 +0900484 if (!config->cert_file.empty() &&
485 !LoadCertificate(out_x509, out_chain, config->cert_file.c_str())) {
486 return false;
David Benjamin41fdbcd2015-02-09 03:13:35 -0500487 }
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100488 if (!config->ocsp_response.empty() &&
Alessandro Ghedini559f0642016-12-07 12:55:32 +0000489 !SSL_set_ocsp_response(ssl, (const uint8_t *)config->ocsp_response.data(),
490 config->ocsp_response.size())) {
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100491 return false;
492 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500493 return true;
494}
495
David Benjaminacb6dcc2016-03-10 09:15:01 -0500496static bool InstallCertificate(SSL *ssl) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700497 bssl::UniquePtr<X509> x509;
David Benjamin2c516452016-11-15 10:16:54 +0900498 bssl::UniquePtr<STACK_OF(X509)> chain;
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700499 bssl::UniquePtr<EVP_PKEY> pkey;
David Benjamin2c516452016-11-15 10:16:54 +0900500 if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500501 return false;
502 }
503
504 if (pkey) {
505 TestState *test_state = GetTestState(ssl);
David Benjamin7e7a82d2016-05-20 20:12:42 -0400506 const TestConfig *config = GetTestConfig(ssl);
David Benjaminacb6dcc2016-03-10 09:15:01 -0500507 if (config->async) {
508 test_state->private_key = std::move(pkey);
509 SSL_set_private_key_method(ssl, &g_async_private_key_method);
510 } else if (!SSL_use_PrivateKey(ssl, pkey.get())) {
511 return false;
512 }
513 }
514
515 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
516 return false;
517 }
518
David Benjamin2c516452016-11-15 10:16:54 +0900519 if (sk_X509_num(chain.get()) > 0 &&
520 !SSL_set1_chain(ssl, chain.get())) {
521 return false;
522 }
523
David Benjaminacb6dcc2016-03-10 09:15:01 -0500524 return true;
525}
526
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000527static enum ssl_select_cert_result_t SelectCertificateCallback(
528 const SSL_CLIENT_HELLO *client_hello) {
David Benjamin731058e2016-12-03 23:15:13 -0500529 const TestConfig *config = GetTestConfig(client_hello->ssl);
530 GetTestState(client_hello->ssl)->early_callback_called = true;
David Benjamin5a593af2014-08-11 19:51:50 -0400531
David Benjamin6f5c0f42015-02-24 01:23:21 -0500532 if (!config->expected_server_name.empty()) {
533 const uint8_t *extension_data;
534 size_t extension_len;
535 CBS extension, server_name_list, host_name;
536 uint8_t name_type;
537
David Benjamin731058e2016-12-03 23:15:13 -0500538 if (!SSL_early_callback_ctx_extension_get(
539 client_hello, TLSEXT_TYPE_server_name, &extension_data,
540 &extension_len)) {
David Benjamin6f5c0f42015-02-24 01:23:21 -0500541 fprintf(stderr, "Could not find server_name extension.\n");
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000542 return ssl_select_cert_error;
David Benjamin6f5c0f42015-02-24 01:23:21 -0500543 }
544
545 CBS_init(&extension, extension_data, extension_len);
546 if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
547 CBS_len(&extension) != 0 ||
548 !CBS_get_u8(&server_name_list, &name_type) ||
549 name_type != TLSEXT_NAMETYPE_host_name ||
550 !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
551 CBS_len(&server_name_list) != 0) {
552 fprintf(stderr, "Could not decode server_name extension.\n");
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000553 return ssl_select_cert_error;
David Benjamin6f5c0f42015-02-24 01:23:21 -0500554 }
555
556 if (!CBS_mem_equal(&host_name,
557 (const uint8_t*)config->expected_server_name.data(),
558 config->expected_server_name.size())) {
559 fprintf(stderr, "Server name mismatch.\n");
560 }
David Benjamin7b030512014-07-08 17:30:11 -0400561 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400562
David Benjamin6f5c0f42015-02-24 01:23:21 -0500563 if (config->fail_early_callback) {
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000564 return ssl_select_cert_error;
David Benjamin7b030512014-07-08 17:30:11 -0400565 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400566
David Benjamin6f5c0f42015-02-24 01:23:21 -0500567 // Install the certificate in the early callback.
568 if (config->use_early_callback) {
Alessandro Ghedini958346a2016-12-20 19:42:15 +0000569 bool early_callback_ready =
570 GetTestState(client_hello->ssl)->early_callback_ready;
571 if (config->async && !early_callback_ready) {
David Benjamin6f5c0f42015-02-24 01:23:21 -0500572 // Install the certificate asynchronously.
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000573 return ssl_select_cert_retry;
David Benjamin6f5c0f42015-02-24 01:23:21 -0500574 }
David Benjamin731058e2016-12-03 23:15:13 -0500575 if (!InstallCertificate(client_hello->ssl)) {
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000576 return ssl_select_cert_error;
David Benjamin6f5c0f42015-02-24 01:23:21 -0500577 }
David Benjamin7b030512014-07-08 17:30:11 -0400578 }
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000579 return ssl_select_cert_success;
David Benjamin8f2c20e2014-07-09 09:30:38 -0400580}
David Benjamin025b3d32014-07-01 19:53:04 -0400581
David Benjamin5edfc8c2016-12-10 15:46:58 -0500582static bool CheckCertificateRequest(SSL *ssl) {
583 const TestConfig *config = GetTestConfig(ssl);
584
585 if (!config->expected_certificate_types.empty()) {
586 const uint8_t *certificate_types;
587 size_t certificate_types_len =
588 SSL_get0_certificate_types(ssl, &certificate_types);
589 if (certificate_types_len != config->expected_certificate_types.size() ||
David Benjamin17cf2cb2016-12-13 01:07:13 -0500590 OPENSSL_memcmp(certificate_types,
591 config->expected_certificate_types.data(),
592 certificate_types_len) != 0) {
David Benjamin5edfc8c2016-12-10 15:46:58 -0500593 fprintf(stderr, "certificate types mismatch\n");
594 return false;
595 }
596 }
597
Adam Langley2ff79332017-02-28 13:45:39 -0800598 if (!config->expected_client_ca_list.empty()) {
599 bssl::UniquePtr<STACK_OF(X509_NAME)> expected =
600 DecodeHexX509Names(config->expected_client_ca_list);
601 const size_t num_expected = sk_X509_NAME_num(expected.get());
602
603 const STACK_OF(X509_NAME) *received = SSL_get_client_CA_list(ssl);
604 const size_t num_received = sk_X509_NAME_num(received);
605
606 if (num_received != num_expected) {
607 fprintf(stderr, "expected %u names in CertificateRequest but got %u\n",
608 static_cast<unsigned>(num_expected),
609 static_cast<unsigned>(num_received));
610 return false;
611 }
612
613 for (size_t i = 0; i < num_received; i++) {
614 if (X509_NAME_cmp(sk_X509_NAME_value(received, i),
615 sk_X509_NAME_value(expected.get(), i)) != 0) {
616 fprintf(stderr, "names in CertificateRequest differ at index #%d\n",
617 static_cast<unsigned>(i));
618 return false;
619 }
620 }
Adam Langleyd6c22ee2017-03-02 12:56:32 -0800621
622 STACK_OF(CRYPTO_BUFFER) *buffers = SSL_get0_server_requested_CAs(ssl);
623 if (sk_CRYPTO_BUFFER_num(buffers) != num_received) {
624 fprintf(stderr,
625 "Mismatch between SSL_get_server_requested_CAs and "
626 "SSL_get_client_CA_list.\n");
627 return false;
628 }
Adam Langley2ff79332017-02-28 13:45:39 -0800629 }
630
David Benjamin5edfc8c2016-12-10 15:46:58 -0500631 return true;
632}
633
David Benjaminacb6dcc2016-03-10 09:15:01 -0500634static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
David Benjamin5edfc8c2016-12-10 15:46:58 -0500635 if (!CheckCertificateRequest(ssl)) {
636 return -1;
637 }
638
David Benjamin7e7a82d2016-05-20 20:12:42 -0400639 if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500640 return -1;
641 }
642
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700643 bssl::UniquePtr<X509> x509;
David Benjamin2c516452016-11-15 10:16:54 +0900644 bssl::UniquePtr<STACK_OF(X509)> chain;
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700645 bssl::UniquePtr<EVP_PKEY> pkey;
David Benjamin2c516452016-11-15 10:16:54 +0900646 if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500647 return -1;
648 }
649
650 // Return zero for no certificate.
651 if (!x509) {
652 return 0;
653 }
654
David Benjamin2c516452016-11-15 10:16:54 +0900655 // Chains and asynchronous private keys are not supported with client_cert_cb.
David Benjaminacb6dcc2016-03-10 09:15:01 -0500656 *out_x509 = x509.release();
657 *out_pkey = pkey.release();
658 return 1;
659}
660
David Benjamin5edfc8c2016-12-10 15:46:58 -0500661static int CertCallback(SSL *ssl, void *arg) {
662 const TestConfig *config = GetTestConfig(ssl);
663
664 // Check the CertificateRequest metadata is as expected.
665 if (!SSL_is_server(ssl) && !CheckCertificateRequest(ssl)) {
666 return -1;
667 }
668
669 if (config->fail_cert_callback) {
670 return 0;
671 }
672
673 // The certificate will be installed via other means.
674 if (!config->async || config->use_early_callback) {
675 return 1;
676 }
677
678 if (!GetTestState(ssl)->cert_ready) {
679 return -1;
680 }
681 if (!InstallCertificate(ssl)) {
682 return 0;
683 }
684 return 1;
685}
686
Paul Lietar8f1c2682015-08-18 12:21:54 +0100687static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
688 SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data(store_ctx,
689 SSL_get_ex_data_X509_STORE_CTX_idx());
David Benjamin7e7a82d2016-05-20 20:12:42 -0400690 const TestConfig *config = GetTestConfig(ssl);
Paul Lietar8f1c2682015-08-18 12:21:54 +0100691
692 if (!config->expected_ocsp_response.empty()) {
693 const uint8_t *data;
694 size_t len;
695 SSL_get0_ocsp_response(ssl, &data, &len);
696 if (len == 0) {
697 fprintf(stderr, "OCSP response not available in verify callback\n");
698 return 0;
699 }
700 }
701
David Benjamin67666e72014-07-12 15:47:52 -0400702 return 1;
703}
704
Paul Lietar8f1c2682015-08-18 12:21:54 +0100705static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
706 store_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION;
707 return 0;
708}
709
David Benjaminc273d2c2015-02-09 12:59:46 -0500710static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
711 unsigned int *out_len, void *arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400712 const TestConfig *config = GetTestConfig(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500713 if (config->advertise_npn.empty()) {
David Benjamin1f5f62b2014-07-12 16:18:02 -0400714 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500715 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400716
David Benjamin5a593af2014-08-11 19:51:50 -0400717 *out = (const uint8_t*)config->advertise_npn.data();
718 *out_len = config->advertise_npn.size();
David Benjamin1f5f62b2014-07-12 16:18:02 -0400719 return SSL_TLSEXT_ERR_OK;
720}
721
David Benjaminc273d2c2015-02-09 12:59:46 -0500722static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
David Benjamin8b368412015-03-14 01:54:17 -0400723 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400724 const TestConfig *config = GetTestConfig(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500725 if (config->select_next_proto.empty()) {
David Benjamin7e3305e2014-07-28 14:52:32 -0400726 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500727 }
David Benjamin7e3305e2014-07-28 14:52:32 -0400728
David Benjamin5a593af2014-08-11 19:51:50 -0400729 *out = (uint8_t*)config->select_next_proto.data();
730 *outlen = config->select_next_proto.size();
David Benjamin7e3305e2014-07-28 14:52:32 -0400731 return SSL_TLSEXT_ERR_OK;
732}
733
David Benjaminc273d2c2015-02-09 12:59:46 -0500734static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
735 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin25fe85b2016-08-09 20:00:32 -0400736 if (GetTestState(ssl)->alpn_select_done) {
737 fprintf(stderr, "AlpnSelectCallback called after completion.\n");
738 exit(1);
739 }
740
741 GetTestState(ssl)->alpn_select_done = true;
742
David Benjamin7e7a82d2016-05-20 20:12:42 -0400743 const TestConfig *config = GetTestConfig(ssl);
David Benjamin594e7d22016-03-17 17:49:56 -0400744 if (config->decline_alpn) {
David Benjaminae2888f2014-09-06 12:58:58 -0400745 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500746 }
David Benjaminae2888f2014-09-06 12:58:58 -0400747
748 if (!config->expected_advertised_alpn.empty() &&
749 (config->expected_advertised_alpn.size() != inlen ||
David Benjamin17cf2cb2016-12-13 01:07:13 -0500750 OPENSSL_memcmp(config->expected_advertised_alpn.data(), in, inlen) !=
751 0)) {
David Benjaminae2888f2014-09-06 12:58:58 -0400752 fprintf(stderr, "bad ALPN select callback inputs\n");
753 exit(1);
754 }
755
756 *out = (const uint8_t*)config->select_alpn.data();
757 *outlen = config->select_alpn.size();
758 return SSL_TLSEXT_ERR_OK;
759}
760
David Benjaminc273d2c2015-02-09 12:59:46 -0500761static unsigned PskClientCallback(SSL *ssl, const char *hint,
762 char *out_identity,
763 unsigned max_identity_len,
764 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400765 const TestConfig *config = GetTestConfig(ssl);
David Benjamin48cae082014-10-27 01:06:24 -0400766
David Benjamin78679342016-09-16 19:42:05 -0400767 if (config->psk_identity.empty()) {
768 if (hint != nullptr) {
769 fprintf(stderr, "Server PSK hint was non-null.\n");
770 return 0;
771 }
772 } else if (hint == nullptr ||
773 strcmp(hint, config->psk_identity.c_str()) != 0) {
David Benjamin48cae082014-10-27 01:06:24 -0400774 fprintf(stderr, "Server PSK hint did not match.\n");
775 return 0;
776 }
777
778 // Account for the trailing '\0' for the identity.
779 if (config->psk_identity.size() >= max_identity_len ||
780 config->psk.size() > max_psk_len) {
781 fprintf(stderr, "PSK buffers too small\n");
782 return 0;
783 }
784
785 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
786 max_identity_len);
David Benjamin17cf2cb2016-12-13 01:07:13 -0500787 OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size());
David Benjamin48cae082014-10-27 01:06:24 -0400788 return config->psk.size();
789}
790
David Benjaminc273d2c2015-02-09 12:59:46 -0500791static unsigned PskServerCallback(SSL *ssl, const char *identity,
792 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400793 const TestConfig *config = GetTestConfig(ssl);
David Benjamin48cae082014-10-27 01:06:24 -0400794
795 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
796 fprintf(stderr, "Client PSK identity did not match.\n");
797 return 0;
798 }
799
800 if (config->psk.size() > max_psk_len) {
801 fprintf(stderr, "PSK buffers too small\n");
802 return 0;
803 }
804
David Benjamin17cf2cb2016-12-13 01:07:13 -0500805 OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size());
David Benjamin48cae082014-10-27 01:06:24 -0400806 return config->psk.size();
807}
808
David Benjamin1b22f852016-10-27 16:36:32 -0400809static timeval g_clock;
810
David Benjamin4d2e7ce2015-05-08 13:29:45 -0400811static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
David Benjamin1b22f852016-10-27 16:36:32 -0400812 *out_clock = g_clock;
David Benjamin377fc312015-01-26 00:22:12 -0500813}
814
David Benjaminc273d2c2015-02-09 12:59:46 -0500815static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
David Benjamin2d445c02015-02-09 13:03:50 -0500816 *out_pkey = GetTestState(ssl)->channel_id.release();
David Benjamind9e07012015-02-09 03:04:34 -0500817}
818
David Benjaminc273d2c2015-02-09 12:59:46 -0500819static SSL_SESSION *GetSessionCallback(SSL *ssl, uint8_t *data, int len,
820 int *copy) {
David Benjamin2d445c02015-02-09 13:03:50 -0500821 TestState *async_state = GetTestState(ssl);
David Benjamin1b8b6912015-02-09 04:28:16 -0500822 if (async_state->session) {
823 *copy = 0;
824 return async_state->session.release();
825 } else if (async_state->pending_session) {
826 return SSL_magic_pending_session_ptr();
827 } else {
828 return NULL;
829 }
830}
831
David Benjamin731058e2016-12-03 23:15:13 -0500832static int DDoSCallback(const SSL_CLIENT_HELLO *client_hello) {
833 const TestConfig *config = GetTestConfig(client_hello->ssl);
Adam Langley524e7172015-02-20 16:04:00 -0800834 static int callback_num = 0;
835
836 callback_num++;
837 if (config->fail_ddos_callback ||
838 (config->fail_second_ddos_callback && callback_num == 2)) {
839 return 0;
840 }
841 return 1;
842}
843
David Benjamin87e4acd2015-04-02 19:57:35 -0400844static void InfoCallback(const SSL *ssl, int type, int val) {
845 if (type == SSL_CB_HANDSHAKE_DONE) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400846 if (GetTestConfig(ssl)->handshake_never_done) {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400847 fprintf(stderr, "Handshake unexpectedly completed.\n");
David Benjamin87e4acd2015-04-02 19:57:35 -0400848 // Abort before any expected error code is printed, to ensure the overall
849 // test fails.
850 abort();
851 }
852 GetTestState(ssl)->handshake_done = true;
David Benjamin25fe85b2016-08-09 20:00:32 -0400853
854 // Callbacks may be called again on a new handshake.
855 GetTestState(ssl)->ticket_decrypt_done = false;
856 GetTestState(ssl)->alpn_select_done = false;
David Benjamin87e4acd2015-04-02 19:57:35 -0400857 }
858}
859
David Benjaminba4594a2015-06-18 18:36:15 -0400860static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
861 GetTestState(ssl)->got_new_session = true;
Steven Valdez4aa154e2016-07-29 14:32:55 -0400862 GetTestState(ssl)->new_session.reset(session);
David Benjaminba4594a2015-06-18 18:36:15 -0400863 return 1;
864}
865
David Benjamind98452d2015-06-16 14:16:23 -0400866static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
867 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
868 int encrypt) {
David Benjamin25fe85b2016-08-09 20:00:32 -0400869 if (!encrypt) {
870 if (GetTestState(ssl)->ticket_decrypt_done) {
871 fprintf(stderr, "TicketKeyCallback called after completion.\n");
872 return -1;
873 }
874
875 GetTestState(ssl)->ticket_decrypt_done = true;
876 }
877
David Benjamind98452d2015-06-16 14:16:23 -0400878 // This is just test code, so use the all-zeros key.
879 static const uint8_t kZeros[16] = {0};
880
881 if (encrypt) {
David Benjamin17cf2cb2016-12-13 01:07:13 -0500882 OPENSSL_memcpy(key_name, kZeros, sizeof(kZeros));
David Benjamind98452d2015-06-16 14:16:23 -0400883 RAND_bytes(iv, 16);
David Benjamin17cf2cb2016-12-13 01:07:13 -0500884 } else if (OPENSSL_memcmp(key_name, kZeros, 16) != 0) {
David Benjamind98452d2015-06-16 14:16:23 -0400885 return 0;
886 }
887
888 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
889 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
890 return -1;
891 }
892
893 if (!encrypt) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400894 return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
David Benjamind98452d2015-06-16 14:16:23 -0400895 }
896 return 1;
897}
898
Adam Langley09505632015-07-30 18:10:13 -0700899// kCustomExtensionValue is the extension value that the custom extension
900// callbacks will add.
Adam Langleyc5b23a12015-07-30 18:19:26 -0700901static const uint16_t kCustomExtensionValue = 1234;
Adam Langley09505632015-07-30 18:10:13 -0700902static void *const kCustomExtensionAddArg =
903 reinterpret_cast<void *>(kCustomExtensionValue);
904static void *const kCustomExtensionParseArg =
905 reinterpret_cast<void *>(kCustomExtensionValue + 1);
906static const char kCustomExtensionContents[] = "custom extension";
907
908static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
909 const uint8_t **out, size_t *out_len,
910 int *out_alert_value, void *add_arg) {
911 if (extension_value != kCustomExtensionValue ||
912 add_arg != kCustomExtensionAddArg) {
913 abort();
914 }
915
David Benjamin7e7a82d2016-05-20 20:12:42 -0400916 if (GetTestConfig(ssl)->custom_extension_skip) {
Adam Langley09505632015-07-30 18:10:13 -0700917 return 0;
918 }
David Benjamin7e7a82d2016-05-20 20:12:42 -0400919 if (GetTestConfig(ssl)->custom_extension_fail_add) {
Adam Langley09505632015-07-30 18:10:13 -0700920 return -1;
921 }
922
923 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
924 *out_len = sizeof(kCustomExtensionContents) - 1;
925
926 return 1;
927}
928
929static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
930 const uint8_t *out, void *add_arg) {
931 if (extension_value != kCustomExtensionValue ||
932 add_arg != kCustomExtensionAddArg ||
933 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
934 abort();
935 }
936}
937
938static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
939 const uint8_t *contents,
940 size_t contents_len,
941 int *out_alert_value, void *parse_arg) {
942 if (extension_value != kCustomExtensionValue ||
943 parse_arg != kCustomExtensionParseArg) {
944 abort();
945 }
946
947 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
David Benjamin17cf2cb2016-12-13 01:07:13 -0500948 OPENSSL_memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
Adam Langley09505632015-07-30 18:10:13 -0700949 *out_alert_value = SSL_AD_DECODE_ERROR;
950 return 0;
951 }
952
953 return 1;
954}
955
David Benjamin8b176712016-10-27 21:51:24 -0400956static int ServerNameCallback(SSL *ssl, int *out_alert, void *arg) {
957 // SNI must be accessible from the SNI callback.
958 const TestConfig *config = GetTestConfig(ssl);
959 const char *server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
960 if (server_name == nullptr ||
961 std::string(server_name) != config->expected_server_name) {
962 fprintf(stderr, "servername mismatch (got %s; want %s)\n", server_name,
963 config->expected_server_name.c_str());
964 return SSL_TLSEXT_ERR_ALERT_FATAL;
965 }
966
967 return SSL_TLSEXT_ERR_OK;
968}
969
David Benjamin87c8a642015-02-21 01:54:29 -0500970// Connect returns a new socket connected to localhost on |port| or -1 on
971// error.
972static int Connect(uint16_t port) {
David Benjaminc3864402017-07-14 16:48:36 -0400973 time_t start_time = time(nullptr);
Matthew Braithwaite2d04cf02017-05-19 18:13:25 -0700974 for (int af : { AF_INET6, AF_INET }) {
975 int sock = socket(af, SOCK_STREAM, 0);
976 if (sock == -1) {
977 PrintSocketError("socket");
978 return -1;
979 }
980 int nodelay = 1;
981 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
982 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
983 PrintSocketError("setsockopt");
984 closesocket(sock);
985 return -1;
986 }
987
988 sockaddr_storage ss;
989 OPENSSL_memset(&ss, 0, sizeof(ss));
990 ss.ss_family = af;
991 socklen_t len = 0;
992
993 if (af == AF_INET6) {
994 sockaddr_in6 *sin6 = (sockaddr_in6 *) &ss;
995 len = sizeof(*sin6);
996 sin6->sin6_port = htons(port);
997 if (!inet_pton(AF_INET6, "::1", &sin6->sin6_addr)) {
998 PrintSocketError("inet_pton");
999 closesocket(sock);
1000 return -1;
1001 }
1002 } else if (af == AF_INET) {
1003 sockaddr_in *sin = (sockaddr_in *) &ss;
1004 len = sizeof(*sin);
1005 sin->sin_port = htons(port);
1006 if (!inet_pton(AF_INET, "127.0.0.1", &sin->sin_addr)) {
1007 PrintSocketError("inet_pton");
1008 closesocket(sock);
1009 return -1;
1010 }
1011 }
1012
1013 if (connect(sock, reinterpret_cast<const sockaddr*>(&ss), len) == 0) {
1014 return sock;
1015 }
David Benjamin87c8a642015-02-21 01:54:29 -05001016 closesocket(sock);
David Benjamin87c8a642015-02-21 01:54:29 -05001017 }
David Benjaminc3864402017-07-14 16:48:36 -04001018
David Benjamin8a5dcbc2017-07-13 18:43:51 -04001019 PrintSocketError("connect");
David Benjaminc3864402017-07-14 16:48:36 -04001020 // TODO(davidben): Remove this logging when https://crbug.com/boringssl/199 is
1021 // resolved.
1022 fprintf(stderr, "start_time = %lld, end_time = %lld\n",
1023 static_cast<long long>(start_time),
1024 static_cast<long long>(time(nullptr)));
Matthew Braithwaite2d04cf02017-05-19 18:13:25 -07001025 return -1;
David Benjamin87c8a642015-02-21 01:54:29 -05001026}
1027
1028class SocketCloser {
1029 public:
1030 explicit SocketCloser(int sock) : sock_(sock) {}
1031 ~SocketCloser() {
1032 // Half-close and drain the socket before releasing it. This seems to be
1033 // necessary for graceful shutdown on Windows. It will also avoid write
1034 // failures in the test runner.
1035#if defined(OPENSSL_WINDOWS)
1036 shutdown(sock_, SD_SEND);
1037#else
1038 shutdown(sock_, SHUT_WR);
1039#endif
1040 while (true) {
1041 char buf[1024];
1042 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
1043 break;
1044 }
1045 }
1046 closesocket(sock_);
1047 }
1048
1049 private:
1050 const int sock_;
1051};
1052
Steven Valdez873ebc92017-05-09 12:12:58 -04001053static void ssl_ctx_add_session(SSL_SESSION *session, void *void_param) {
1054 SSL_SESSION *new_session = SSL_SESSION_dup(
1055 session, SSL_SESSION_INCLUDE_NONAUTH | SSL_SESSION_INCLUDE_TICKET);
1056 if (new_session != nullptr) {
1057 SSL_CTX_add_session((SSL_CTX *)void_param, new_session);
1058 }
1059 SSL_SESSION_free(new_session);
1060}
1061
1062static bssl::UniquePtr<SSL_CTX> SetupCtx(SSL_CTX *old_ctx,
1063 const TestConfig *config) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001064 bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(
David Benjamina7f333d2015-02-09 02:37:18 -05001065 config->is_dtls ? DTLS_method() : TLS_method()));
1066 if (!ssl_ctx) {
1067 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -04001068 }
1069
Adam Langleyd519bf62016-12-12 11:16:44 -08001070 SSL_CTX_set0_buffer_pool(ssl_ctx.get(), g_pool);
1071
David Benjamin3cfeb952017-03-01 16:48:38 -05001072 // Enable SSL 3.0 and TLS 1.3 for tests.
David Benjamin2dc02042016-09-19 19:57:37 -04001073 if (!config->is_dtls &&
David Benjamin3cfeb952017-03-01 16:48:38 -05001074 (!SSL_CTX_set_min_proto_version(ssl_ctx.get(), SSL3_VERSION) ||
1075 !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION))) {
David Benjamin2dc02042016-09-19 19:57:37 -04001076 return nullptr;
Nick Harper1fd39d82016-06-14 18:14:35 -07001077 }
1078
Adam Langleycef75832015-09-03 14:51:12 -07001079 std::string cipher_list = "ALL";
1080 if (!config->cipher.empty()) {
1081 cipher_list = config->cipher;
1082 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
1083 }
Matthew Braithwaitea57dcfb2017-02-17 22:08:23 -08001084 if (!SSL_CTX_set_strict_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
Adam Langleycef75832015-09-03 14:51:12 -07001085 return nullptr;
1086 }
1087
David Benjamin1b8b6912015-02-09 04:28:16 -05001088 if (config->async && config->is_server) {
1089 // Disable the internal session cache. To test asynchronous session lookup,
1090 // we use an external session cache.
1091 SSL_CTX_set_session_cache_mode(
1092 ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
David Benjaminc273d2c2015-02-09 12:59:46 -05001093 SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
David Benjamin1b8b6912015-02-09 04:28:16 -05001094 } else {
1095 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
1096 }
David Benjamin1d5c83e2014-07-22 19:20:02 -04001097
David Benjamind4c2bce2015-10-17 12:28:18 -04001098 SSL_CTX_set_select_certificate_cb(ssl_ctx.get(), SelectCertificateCallback);
David Benjamin8f2c20e2014-07-09 09:30:38 -04001099
David Benjaminacb6dcc2016-03-10 09:15:01 -05001100 if (config->use_old_client_cert_callback) {
1101 SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
1102 }
1103
David Benjamin1f5f62b2014-07-12 16:18:02 -04001104 SSL_CTX_set_next_protos_advertised_cb(
David Benjaminc273d2c2015-02-09 12:59:46 -05001105 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -04001106 if (!config->select_next_proto.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001107 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
David Benjamina7f333d2015-02-09 02:37:18 -05001108 NULL);
David Benjaminae2888f2014-09-06 12:58:58 -04001109 }
1110
Steven Valdez873ebc92017-05-09 12:12:58 -04001111 if (!config->select_alpn.empty() || config->decline_alpn) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001112 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -04001113 }
David Benjamin1f5f62b2014-07-12 16:18:02 -04001114
David Benjaminc273d2c2015-02-09 12:59:46 -05001115 SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
David Benjamina08e49d2014-08-24 01:46:07 -04001116
David Benjamin1b22f852016-10-27 16:36:32 -04001117 SSL_CTX_set_current_time_cb(ssl_ctx.get(), CurrentTimeCallback);
David Benjamin377fc312015-01-26 00:22:12 -05001118
David Benjamin87e4acd2015-04-02 19:57:35 -04001119 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
David Benjaminba4594a2015-06-18 18:36:15 -04001120 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
David Benjamin87e4acd2015-04-02 19:57:35 -04001121
David Benjamind98452d2015-06-16 14:16:23 -04001122 if (config->use_ticket_callback) {
1123 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
1124 }
1125
Adam Langley09505632015-07-30 18:10:13 -07001126 if (config->enable_client_custom_extension &&
1127 !SSL_CTX_add_client_custom_ext(
1128 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
1129 CustomExtensionFreeCallback, kCustomExtensionAddArg,
1130 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1131 return nullptr;
1132 }
1133
1134 if (config->enable_server_custom_extension &&
1135 !SSL_CTX_add_server_custom_ext(
1136 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
1137 CustomExtensionFreeCallback, kCustomExtensionAddArg,
1138 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1139 return nullptr;
1140 }
1141
Paul Lietar8f1c2682015-08-18 12:21:54 +01001142 if (config->verify_fail) {
1143 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
1144 } else {
1145 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
1146 }
1147
Paul Lietar4fac72e2015-09-09 13:44:55 +01001148 if (!config->signed_cert_timestamps.empty() &&
1149 !SSL_CTX_set_signed_cert_timestamp_list(
1150 ssl_ctx.get(), (const uint8_t *)config->signed_cert_timestamps.data(),
1151 config->signed_cert_timestamps.size())) {
1152 return nullptr;
1153 }
1154
Adam Langley2ff79332017-02-28 13:45:39 -08001155 if (!config->use_client_ca_list.empty()) {
1156 if (config->use_client_ca_list == "<NULL>") {
1157 SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
1158 } else {
1159 bssl::UniquePtr<STACK_OF(X509_NAME)> names =
1160 DecodeHexX509Names(config->use_client_ca_list);
1161 SSL_CTX_set_client_CA_list(ssl_ctx.get(), names.release());
1162 }
David Benjamin2f8935d2016-07-13 19:47:39 -04001163 }
1164
David Benjamin65ac9972016-09-02 21:35:25 -04001165 if (config->enable_grease) {
1166 SSL_CTX_set_grease_enabled(ssl_ctx.get(), 1);
1167 }
1168
David Benjamin8b176712016-10-27 21:51:24 -04001169 if (!config->expected_server_name.empty()) {
1170 SSL_CTX_set_tlsext_servername_callback(ssl_ctx.get(), ServerNameCallback);
1171 }
1172
David Benjamin4199b0d2016-11-01 13:58:25 -04001173 if (!config->ticket_key.empty() &&
1174 !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), config->ticket_key.data(),
1175 config->ticket_key.size())) {
1176 return nullptr;
1177 }
1178
Steven Valdez08b65f42016-12-07 15:29:45 -05001179 if (config->enable_early_data) {
1180 SSL_CTX_set_early_data_enabled(ssl_ctx.get(), 1);
1181 }
1182
Steven Valdez520e1222017-06-13 12:45:25 -04001183 SSL_CTX_set_tls13_variant(
1184 ssl_ctx.get(), static_cast<enum tls13_variant_t>(config->tls13_variant));
1185
David Benjaminc8ff30c2017-04-04 13:52:36 -04001186 if (config->allow_unknown_alpn_protos) {
1187 SSL_CTX_set_allow_unknown_alpn_protos(ssl_ctx.get(), 1);
1188 }
1189
David Benjamin69522112017-03-28 15:38:29 -05001190 if (config->enable_ed25519) {
1191 SSL_CTX_set_ed25519_enabled(ssl_ctx.get(), 1);
1192 }
1193
David Benjamin71c21b42017-04-14 17:05:40 -04001194 if (!config->verify_prefs.empty()) {
1195 std::vector<uint16_t> u16s(config->verify_prefs.begin(),
1196 config->verify_prefs.end());
1197 if (!SSL_CTX_set_verify_algorithm_prefs(ssl_ctx.get(), u16s.data(),
1198 u16s.size())) {
1199 return nullptr;
1200 }
1201 }
1202
Steven Valdez873ebc92017-05-09 12:12:58 -04001203 if (old_ctx) {
1204 uint8_t keys[48];
1205 if (!SSL_CTX_get_tlsext_ticket_keys(old_ctx, &keys, sizeof(keys)) ||
1206 !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), keys, sizeof(keys))) {
1207 return nullptr;
1208 }
1209 lh_SSL_SESSION_doall_arg(old_ctx->sessions, ssl_ctx_add_session,
1210 ssl_ctx.get());
1211 }
1212
David Benjamin1d5c83e2014-07-22 19:20:02 -04001213 return ssl_ctx;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001214}
1215
David Benjamin40f101b2015-02-20 11:23:42 -05001216// RetryAsync is called after a failed operation on |ssl| with return code
1217// |ret|. If the operation should be retried, it simulates one asynchronous
David Benjamin6c2563e2015-04-03 03:47:47 -04001218// event and returns true. Otherwise it returns false.
1219static bool RetryAsync(SSL *ssl, int ret) {
David Benjamin43ec06f2014-08-05 02:28:57 -04001220 // No error; don't retry.
1221 if (ret >= 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001222 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001223 }
David Benjamin83f90402015-01-27 01:09:43 -05001224
David Benjamin6c2563e2015-04-03 03:47:47 -04001225 TestState *test_state = GetTestState(ssl);
Matt Braithwaite6278e242016-06-14 08:18:22 -07001226 assert(GetTestConfig(ssl)->async);
David Benjamin83f90402015-01-27 01:09:43 -05001227
David Benjamin585d7a42016-06-02 14:58:00 -04001228 if (test_state->packeted_bio != nullptr &&
1229 PacketedBioAdvanceClock(test_state->packeted_bio)) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001230 // The DTLS retransmit logic silently ignores write failures. So the test
1231 // may progress, allow writes through synchronously.
David Benjamin585d7a42016-06-02 14:58:00 -04001232 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
David Benjamin13e81fc2015-11-02 17:16:13 -05001233 int timeout_ret = DTLSv1_handle_timeout(ssl);
David Benjamin585d7a42016-06-02 14:58:00 -04001234 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
David Benjamin13e81fc2015-11-02 17:16:13 -05001235
1236 if (timeout_ret < 0) {
David Benjaminc565ebb2015-04-03 04:06:36 -04001237 fprintf(stderr, "Error retransmitting.\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001238 return false;
David Benjamin83f90402015-01-27 01:09:43 -05001239 }
David Benjamin40f101b2015-02-20 11:23:42 -05001240 return true;
David Benjamin83f90402015-01-27 01:09:43 -05001241 }
1242
David Benjamin43ec06f2014-08-05 02:28:57 -04001243 // See if we needed to read or write more. If so, allow one byte through on
1244 // the appropriate end to maximally stress the state machine.
David Benjamind9e07012015-02-09 03:04:34 -05001245 switch (SSL_get_error(ssl, ret)) {
1246 case SSL_ERROR_WANT_READ:
David Benjamin6c2563e2015-04-03 03:47:47 -04001247 AsyncBioAllowRead(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -05001248 return true;
David Benjamind9e07012015-02-09 03:04:34 -05001249 case SSL_ERROR_WANT_WRITE:
David Benjamin6c2563e2015-04-03 03:47:47 -04001250 AsyncBioAllowWrite(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -05001251 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -05001252 case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001253 bssl::UniquePtr<EVP_PKEY> pkey =
1254 LoadPrivateKey(GetTestConfig(ssl)->send_channel_id);
David Benjamin9d0847a2015-02-16 03:57:55 -05001255 if (!pkey) {
David Benjamin40f101b2015-02-20 11:23:42 -05001256 return false;
David Benjamin9d0847a2015-02-16 03:57:55 -05001257 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001258 test_state->channel_id = std::move(pkey);
David Benjamin40f101b2015-02-20 11:23:42 -05001259 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -05001260 }
David Benjamin41fdbcd2015-02-09 03:13:35 -05001261 case SSL_ERROR_WANT_X509_LOOKUP:
David Benjamin6c2563e2015-04-03 03:47:47 -04001262 test_state->cert_ready = true;
David Benjamin40f101b2015-02-20 11:23:42 -05001263 return true;
David Benjamin1b8b6912015-02-09 04:28:16 -05001264 case SSL_ERROR_PENDING_SESSION:
David Benjamin6c2563e2015-04-03 03:47:47 -04001265 test_state->session = std::move(test_state->pending_session);
David Benjamin40f101b2015-02-20 11:23:42 -05001266 return true;
David Benjamin6f5c0f42015-02-24 01:23:21 -05001267 case SSL_ERROR_PENDING_CERTIFICATE:
Alessandro Ghedini958346a2016-12-20 19:42:15 +00001268 test_state->early_callback_ready = true;
1269 return true;
David Benjaminb4d65fd2015-05-29 17:11:21 -04001270 case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
nagendra modadugu3398dbf2015-08-07 14:07:52 -07001271 test_state->private_key_retries++;
David Benjaminb4d65fd2015-05-29 17:11:21 -04001272 return true;
David Benjamind9e07012015-02-09 03:04:34 -05001273 default:
David Benjamin40f101b2015-02-20 11:23:42 -05001274 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001275 }
David Benjamin025b3d32014-07-01 19:53:04 -04001276}
1277
David Benjamin6c2563e2015-04-03 03:47:47 -04001278// DoRead reads from |ssl|, resolving any asynchronous operations. It returns
1279// the result value of the final |SSL_read| call.
1280static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
David Benjamin7e7a82d2016-05-20 20:12:42 -04001281 const TestConfig *config = GetTestConfig(ssl);
David Benjamin13e81fc2015-11-02 17:16:13 -05001282 TestState *test_state = GetTestState(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -04001283 int ret;
1284 do {
David Benjamin13e81fc2015-11-02 17:16:13 -05001285 if (config->async) {
1286 // The DTLS retransmit logic silently ignores write failures. So the test
1287 // may progress, allow writes through synchronously. |SSL_read| may
1288 // trigger a retransmit, so disconnect the write quota.
1289 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
1290 }
David Benjaminf3fbade2016-09-19 13:08:16 -04001291 ret = config->peek_then_read ? SSL_peek(ssl, out, max_out)
1292 : SSL_read(ssl, out, max_out);
David Benjamin13e81fc2015-11-02 17:16:13 -05001293 if (config->async) {
1294 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
1295 }
David Benjamin7bb1d292016-11-01 19:45:06 -04001296
1297 // Run the exporter after each read. This is to test that the exporter fails
1298 // during a renegotiation.
1299 if (config->use_exporter_between_reads) {
1300 uint8_t buf;
1301 if (!SSL_export_keying_material(ssl, &buf, 1, NULL, 0, NULL, 0, 0)) {
1302 fprintf(stderr, "failed to export keying material\n");
1303 return -1;
1304 }
1305 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001306 } while (config->async && RetryAsync(ssl, ret));
David Benjaminf3fbade2016-09-19 13:08:16 -04001307
1308 if (config->peek_then_read && ret > 0) {
1309 std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
1310
1311 // SSL_peek should synchronously return the same data.
1312 int ret2 = SSL_peek(ssl, buf.get(), ret);
1313 if (ret2 != ret ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001314 OPENSSL_memcmp(buf.get(), out, ret) != 0) {
David Benjaminf3fbade2016-09-19 13:08:16 -04001315 fprintf(stderr, "First and second SSL_peek did not match.\n");
1316 return -1;
1317 }
1318
1319 // SSL_read should synchronously return the same data and consume it.
1320 ret2 = SSL_read(ssl, buf.get(), ret);
1321 if (ret2 != ret ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001322 OPENSSL_memcmp(buf.get(), out, ret) != 0) {
David Benjaminf3fbade2016-09-19 13:08:16 -04001323 fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
1324 return -1;
1325 }
1326 }
1327
David Benjamin6c2563e2015-04-03 03:47:47 -04001328 return ret;
1329}
1330
1331// WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
1332// operations. It returns the result of the final |SSL_write| call.
David Benjaminbbba9392017-04-06 12:54:12 -04001333static int WriteAll(SSL *ssl, const void *in_, size_t in_len) {
1334 const uint8_t *in = reinterpret_cast<const uint8_t *>(in_);
David Benjamin7e7a82d2016-05-20 20:12:42 -04001335 const TestConfig *config = GetTestConfig(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -04001336 int ret;
1337 do {
1338 ret = SSL_write(ssl, in, in_len);
1339 if (ret > 0) {
1340 in += ret;
1341 in_len -= ret;
1342 }
1343 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
1344 return ret;
1345}
1346
David Benjamin30789da2015-08-29 22:56:45 -04001347// DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
1348// returns the result of the final |SSL_shutdown| call.
1349static int DoShutdown(SSL *ssl) {
David Benjamin7e7a82d2016-05-20 20:12:42 -04001350 const TestConfig *config = GetTestConfig(ssl);
David Benjamin30789da2015-08-29 22:56:45 -04001351 int ret;
1352 do {
1353 ret = SSL_shutdown(ssl);
1354 } while (config->async && RetryAsync(ssl, ret));
1355 return ret;
1356}
1357
David Benjamin1d4f4c02016-07-26 18:03:08 -04001358// DoSendFatalAlert calls |SSL_send_fatal_alert|, resolving any asynchronous
1359// operations. It returns the result of the final |SSL_send_fatal_alert| call.
1360static int DoSendFatalAlert(SSL *ssl, uint8_t alert) {
1361 const TestConfig *config = GetTestConfig(ssl);
1362 int ret;
1363 do {
1364 ret = SSL_send_fatal_alert(ssl, alert);
1365 } while (config->async && RetryAsync(ssl, ret));
1366 return ret;
1367}
1368
Steven Valdez1e6f11a2016-07-27 11:10:52 -04001369static uint16_t GetProtocolVersion(const SSL *ssl) {
1370 uint16_t version = SSL_version(ssl);
1371 if (!SSL_is_dtls(ssl)) {
1372 return version;
1373 }
1374 return 0x0201 + ~version;
1375}
1376
David Benjamin91eab5c2015-06-18 18:35:46 -04001377// CheckHandshakeProperties checks, immediately after |ssl| completes its
1378// initial handshake (or False Starts), whether all the properties are
1379// consistent with the test configuration and invariants.
Steven Valdeze831a812017-03-09 14:56:07 -05001380static bool CheckHandshakeProperties(SSL *ssl, bool is_resume,
1381 const TestConfig *config) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001382 if (SSL_get_current_cipher(ssl) == nullptr) {
1383 fprintf(stderr, "null cipher after handshake\n");
1384 return false;
1385 }
1386
David Benjamind9cbb532017-07-07 13:17:19 -04001387 if (config->expect_version != 0 &&
1388 SSL_version(ssl) != config->expect_version) {
1389 fprintf(stderr, "want version %04x, got %04x\n", config->expect_version,
1390 SSL_version(ssl));
1391 return false;
1392 }
1393
Steven Valdeze831a812017-03-09 14:56:07 -05001394 bool expect_resume =
1395 is_resume && (!config->expect_session_miss || SSL_in_early_data(ssl));
1396 if (!!SSL_session_reused(ssl) != expect_resume) {
1397 fprintf(stderr, "session unexpectedly was%s reused\n",
David Benjamin91eab5c2015-06-18 18:35:46 -04001398 SSL_session_reused(ssl) ? "" : " not");
1399 return false;
1400 }
1401
Steven Valdez681eb6a2016-12-19 13:19:29 -05001402 bool expect_handshake_done =
Steven Valdeze831a812017-03-09 14:56:07 -05001403 (is_resume || !config->false_start) && !SSL_in_early_data(ssl);
David Benjamin91eab5c2015-06-18 18:35:46 -04001404 if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
1405 fprintf(stderr, "handshake was%s completed\n",
1406 GetTestState(ssl)->handshake_done ? "" : " not");
1407 return false;
1408 }
1409
David Benjaminba4594a2015-06-18 18:36:15 -04001410 if (expect_handshake_done && !config->is_server) {
1411 bool expect_new_session =
1412 !config->expect_no_session &&
Steven Valdez143e8b32016-07-11 13:19:03 -04001413 (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
Steven Valdez1e6f11a2016-07-27 11:10:52 -04001414 // Session tickets are sent post-handshake in TLS 1.3.
1415 GetProtocolVersion(ssl) < TLS1_3_VERSION;
David Benjaminba4594a2015-06-18 18:36:15 -04001416 if (expect_new_session != GetTestState(ssl)->got_new_session) {
1417 fprintf(stderr,
David Benjamindd6fed92015-10-23 17:41:12 -04001418 "new session was%s cached, but we expected the opposite\n",
David Benjaminba4594a2015-06-18 18:36:15 -04001419 GetTestState(ssl)->got_new_session ? "" : " not");
1420 return false;
1421 }
1422 }
1423
David Benjaminb5c58db2017-01-28 01:39:29 -05001424 if (!is_resume) {
1425 if (config->expect_session_id && !GetTestState(ssl)->got_new_session) {
1426 fprintf(stderr, "session was not cached on the server.\n");
1427 return false;
1428 }
1429 if (config->expect_no_session_id && GetTestState(ssl)->got_new_session) {
1430 fprintf(stderr, "session was unexpectedly cached on the server.\n");
1431 return false;
1432 }
1433 }
1434
David Benjamin91eab5c2015-06-18 18:35:46 -04001435 if (config->is_server && !GetTestState(ssl)->early_callback_called) {
1436 fprintf(stderr, "early callback not called\n");
1437 return false;
1438 }
1439
1440 if (!config->expected_server_name.empty()) {
1441 const char *server_name =
1442 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
David Benjamin8b176712016-10-27 21:51:24 -04001443 if (server_name == nullptr ||
1444 server_name != config->expected_server_name) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001445 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
1446 server_name, config->expected_server_name.c_str());
1447 return false;
1448 }
1449 }
1450
David Benjamin91eab5c2015-06-18 18:35:46 -04001451 if (!config->expected_next_proto.empty()) {
1452 const uint8_t *next_proto;
1453 unsigned next_proto_len;
1454 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
1455 if (next_proto_len != config->expected_next_proto.size() ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001456 OPENSSL_memcmp(next_proto, config->expected_next_proto.data(),
1457 next_proto_len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001458 fprintf(stderr, "negotiated next proto mismatch\n");
1459 return false;
1460 }
1461 }
1462
Steven Valdez873ebc92017-05-09 12:12:58 -04001463 if (!config->is_server) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001464 const uint8_t *alpn_proto;
1465 unsigned alpn_proto_len;
1466 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
Steven Valdez873ebc92017-05-09 12:12:58 -04001467 if (alpn_proto_len != config->expected_alpn.size() ||
1468 OPENSSL_memcmp(alpn_proto, config->expected_alpn.data(),
1469 alpn_proto_len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001470 fprintf(stderr, "negotiated alpn proto mismatch\n");
1471 return false;
1472 }
1473 }
1474
1475 if (!config->expected_channel_id.empty()) {
1476 uint8_t channel_id[64];
1477 if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
1478 fprintf(stderr, "no channel id negotiated\n");
1479 return false;
1480 }
1481 if (config->expected_channel_id.size() != 64 ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001482 OPENSSL_memcmp(config->expected_channel_id.data(), channel_id, 64) !=
1483 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001484 fprintf(stderr, "channel id mismatch\n");
1485 return false;
1486 }
1487 }
1488
David Benjamind2610042017-01-03 10:49:28 -05001489 if (config->expect_extended_master_secret && !SSL_get_extms_support(ssl)) {
1490 fprintf(stderr, "No EMS for connection when expected\n");
1491 return false;
1492 }
1493
1494 if (config->expect_secure_renegotiation &&
1495 !SSL_get_secure_renegotiation_support(ssl)) {
1496 fprintf(stderr, "No secure renegotiation for connection when expected\n");
1497 return false;
1498 }
1499
1500 if (config->expect_no_secure_renegotiation &&
1501 SSL_get_secure_renegotiation_support(ssl)) {
1502 fprintf(stderr,
1503 "Secure renegotiation unexpectedly negotiated for connection\n");
1504 return false;
David Benjamin91eab5c2015-06-18 18:35:46 -04001505 }
1506
1507 if (!config->expected_ocsp_response.empty()) {
1508 const uint8_t *data;
1509 size_t len;
1510 SSL_get0_ocsp_response(ssl, &data, &len);
1511 if (config->expected_ocsp_response.size() != len ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001512 OPENSSL_memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001513 fprintf(stderr, "OCSP response mismatch\n");
1514 return false;
1515 }
1516 }
1517
1518 if (!config->expected_signed_cert_timestamps.empty()) {
1519 const uint8_t *data;
1520 size_t len;
1521 SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
1522 if (config->expected_signed_cert_timestamps.size() != len ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001523 OPENSSL_memcmp(config->expected_signed_cert_timestamps.data(), data,
1524 len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001525 fprintf(stderr, "SCT list mismatch\n");
1526 return false;
1527 }
1528 }
1529
Paul Lietar8f1c2682015-08-18 12:21:54 +01001530 if (config->expect_verify_result) {
1531 int expected_verify_result = config->verify_fail ?
1532 X509_V_ERR_APPLICATION_VERIFICATION :
1533 X509_V_OK;
1534
1535 if (SSL_get_verify_result(ssl) != expected_verify_result) {
1536 fprintf(stderr, "Wrong certificate verification result\n");
1537 return false;
1538 }
1539 }
1540
Nick Harper60edffd2016-06-21 15:19:24 -07001541 if (config->expect_peer_signature_algorithm != 0 &&
1542 config->expect_peer_signature_algorithm !=
1543 SSL_get_peer_signature_algorithm(ssl)) {
1544 fprintf(stderr, "Peer signature algorithm was %04x, wanted %04x.\n",
1545 SSL_get_peer_signature_algorithm(ssl),
1546 config->expect_peer_signature_algorithm);
David Benjamin6e807652015-11-02 12:02:20 -05001547 return false;
1548 }
1549
Steven Valdez873ebc92017-05-09 12:12:58 -04001550 if (config->expect_curve_id != 0) {
David Benjamin9e68f192016-06-30 14:55:33 -04001551 uint16_t curve_id = SSL_get_curve_id(ssl);
Steven Valdez873ebc92017-05-09 12:12:58 -04001552 if (static_cast<uint16_t>(config->expect_curve_id) != curve_id) {
David Benjamin9e68f192016-06-30 14:55:33 -04001553 fprintf(stderr, "curve_id was %04x, wanted %04x\n", curve_id,
Steven Valdez873ebc92017-05-09 12:12:58 -04001554 static_cast<uint16_t>(config->expect_curve_id));
David Benjamin9e68f192016-06-30 14:55:33 -04001555 return false;
1556 }
1557 }
1558
David Benjaminabbbee12016-10-31 19:20:42 -04001559 uint16_t cipher_id =
1560 static_cast<uint16_t>(SSL_CIPHER_get_id(SSL_get_current_cipher(ssl)));
1561 if (config->expect_cipher_aes != 0 &&
1562 EVP_has_aes_hardware() &&
1563 static_cast<uint16_t>(config->expect_cipher_aes) != cipher_id) {
1564 fprintf(stderr, "Cipher ID was %04x, wanted %04x (has AES hardware)\n",
1565 cipher_id, static_cast<uint16_t>(config->expect_cipher_aes));
1566 return false;
1567 }
1568
1569 if (config->expect_cipher_no_aes != 0 &&
1570 !EVP_has_aes_hardware() &&
1571 static_cast<uint16_t>(config->expect_cipher_no_aes) != cipher_id) {
1572 fprintf(stderr, "Cipher ID was %04x, wanted %04x (no AES hardware)\n",
1573 cipher_id, static_cast<uint16_t>(config->expect_cipher_no_aes));
1574 return false;
1575 }
1576
Steven Valdeze831a812017-03-09 14:56:07 -05001577 if (is_resume && !SSL_in_early_data(ssl)) {
Steven Valdez2d850622017-01-11 11:34:52 -05001578 if ((config->expect_accept_early_data && !SSL_early_data_accepted(ssl)) ||
1579 (config->expect_reject_early_data && SSL_early_data_accepted(ssl))) {
1580 fprintf(stderr,
1581 "Early data was%s accepted, but we expected the opposite\n",
1582 SSL_early_data_accepted(ssl) ? "" : " not");
1583 return false;
1584 }
1585 }
David Benjaminabbbee12016-10-31 19:20:42 -04001586
David Benjaminbb9e36e2016-08-03 14:14:47 -04001587 if (!config->psk.empty()) {
1588 if (SSL_get_peer_cert_chain(ssl) != nullptr) {
1589 fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
1590 return false;
1591 }
1592 } else if (!config->is_server || config->require_any_client_certificate) {
1593 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
1594 fprintf(stderr, "Received no peer certificate but expected one.\n");
David Benjamin91eab5c2015-06-18 18:35:46 -04001595 return false;
1596 }
1597 }
David Benjaminbb9e36e2016-08-03 14:14:47 -04001598
David Benjamin2c516452016-11-15 10:16:54 +09001599 if (!config->expect_peer_cert_file.empty()) {
1600 bssl::UniquePtr<X509> expect_leaf;
1601 bssl::UniquePtr<STACK_OF(X509)> expect_chain;
1602 if (!LoadCertificate(&expect_leaf, &expect_chain,
1603 config->expect_peer_cert_file)) {
1604 return false;
1605 }
1606
1607 // For historical reasons, clients report a chain with a leaf and servers
1608 // without.
1609 if (!config->is_server) {
1610 if (!sk_X509_insert(expect_chain.get(), expect_leaf.get(), 0)) {
1611 return false;
1612 }
1613 X509_up_ref(expect_leaf.get()); // sk_X509_push takes ownership.
1614 }
1615
1616 bssl::UniquePtr<X509> leaf(SSL_get_peer_certificate(ssl));
1617 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl);
1618 if (X509_cmp(leaf.get(), expect_leaf.get()) != 0) {
1619 fprintf(stderr, "Received a different leaf certificate than expected.\n");
1620 return false;
1621 }
1622
1623 if (sk_X509_num(chain) != sk_X509_num(expect_chain.get())) {
1624 fprintf(stderr, "Received a chain of length %zu instead of %zu.\n",
1625 sk_X509_num(chain), sk_X509_num(expect_chain.get()));
1626 return false;
1627 }
1628
1629 for (size_t i = 0; i < sk_X509_num(chain); i++) {
1630 if (X509_cmp(sk_X509_value(chain, i),
1631 sk_X509_value(expect_chain.get(), i)) != 0) {
1632 fprintf(stderr, "Chain certificate %zu did not match.\n",
1633 i + 1);
1634 return false;
1635 }
1636 }
1637 }
1638
David Benjaminbbaf3672016-11-17 10:53:09 +09001639 bool expected_sha256_client_cert = config->expect_sha256_client_cert_initial;
1640 if (is_resume) {
1641 expected_sha256_client_cert = config->expect_sha256_client_cert_resume;
1642 }
1643
1644 if (SSL_get_session(ssl)->peer_sha256_valid != expected_sha256_client_cert) {
1645 fprintf(stderr,
1646 "Unexpected SHA-256 client cert state: expected:%d is_resume:%d.\n",
1647 expected_sha256_client_cert, is_resume);
1648 return false;
1649 }
1650
1651 if (expected_sha256_client_cert &&
Adam Langley46db7af2017-02-01 15:49:37 -08001652 SSL_get_session(ssl)->certs != nullptr) {
David Benjaminbbaf3672016-11-17 10:53:09 +09001653 fprintf(stderr, "Have both client cert and SHA-256 hash: is_resume:%d.\n",
1654 is_resume);
1655 return false;
1656 }
1657
David Benjamin35ac5b72017-03-03 15:05:56 -05001658 if (is_resume && config->expect_ticket_age_skew != 0 &&
1659 SSL_get_ticket_age_skew(ssl) != config->expect_ticket_age_skew) {
1660 fprintf(stderr, "Ticket age skew was %" PRId32 ", wanted %d\n",
1661 SSL_get_ticket_age_skew(ssl), config->expect_ticket_age_skew);
1662 return false;
1663 }
1664
David Benjamin91eab5c2015-06-18 18:35:46 -04001665 return true;
1666}
1667
David Benjamin0fde2eb2017-06-30 19:11:22 -04001668static bool WriteSettings(int i, const TestConfig *config,
1669 const SSL_SESSION *session) {
1670 if (config->write_settings.empty()) {
1671 return true;
1672 }
1673
1674 // Treat write_settings as a path prefix for each connection in the run.
1675 char buf[DECIMAL_SIZE(int)];
1676 snprintf(buf, sizeof(buf), "%d", i);
1677 std::string path = config->write_settings + buf;
1678
1679 bssl::ScopedCBB cbb;
1680 if (!CBB_init(cbb.get(), 64)) {
1681 return false;
1682 }
1683
1684 if (session != nullptr) {
1685 uint8_t *data;
1686 size_t len;
1687 if (!SSL_SESSION_to_bytes(session, &data, &len)) {
1688 return false;
1689 }
1690 bssl::UniquePtr<uint8_t> free_data(data);
1691 CBB child;
1692 if (!CBB_add_u16(cbb.get(), kSessionTag) ||
1693 !CBB_add_u24_length_prefixed(cbb.get(), &child) ||
1694 !CBB_add_bytes(&child, data, len) ||
1695 !CBB_flush(cbb.get())) {
1696 return false;
1697 }
1698 }
1699
1700 if (config->is_server &&
1701 (config->require_any_client_certificate || config->verify_peer) &&
1702 !CBB_add_u16(cbb.get(), kRequestClientCert)) {
1703 return false;
1704 }
1705
David Benjamin1ffb4a42017-07-10 17:47:09 -04001706 if (config->tls13_variant != 0 &&
1707 (!CBB_add_u16(cbb.get(), kTLS13Variant) ||
1708 !CBB_add_u8(cbb.get(), static_cast<uint8_t>(config->tls13_variant)))) {
1709 return false;
1710 }
1711
David Benjamin0fde2eb2017-06-30 19:11:22 -04001712 uint8_t *settings;
1713 size_t settings_len;
1714 if (!CBB_add_u16(cbb.get(), kDataTag) ||
1715 !CBB_finish(cbb.get(), &settings, &settings_len)) {
1716 return false;
1717 }
1718 bssl::UniquePtr<uint8_t> free_settings(settings);
1719
1720 using ScopedFILE = std::unique_ptr<FILE, decltype(&fclose)>;
1721 ScopedFILE file(fopen(path.c_str(), "w"), fclose);
1722 if (!file) {
1723 return false;
1724 }
1725
1726 return fwrite(settings, settings_len, 1, file.get()) == 1;
1727}
1728
Steven Valdeze831a812017-03-09 14:56:07 -05001729static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session, SSL *ssl,
1730 const TestConfig *config, bool is_resume, bool is_retry);
1731
1732// DoConnection tests an SSL connection against the peer. On success, it returns
David Benjamin87c8a642015-02-21 01:54:29 -05001733// true and sets |*out_session| to the negotiated SSL session. If the test is a
1734// resumption attempt, |is_resume| is true and |session| is the session from the
1735// previous exchange.
Steven Valdeze831a812017-03-09 14:56:07 -05001736static bool DoConnection(bssl::UniquePtr<SSL_SESSION> *out_session,
1737 SSL_CTX *ssl_ctx, const TestConfig *config,
1738 const TestConfig *retry_config, bool is_resume,
1739 SSL_SESSION *session) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001740 bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
David Benjamina7f333d2015-02-09 02:37:18 -05001741 if (!ssl) {
David Benjamin40f101b2015-02-20 11:23:42 -05001742 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001743 }
1744
David Benjamin7e7a82d2016-05-20 20:12:42 -04001745 if (!SetTestConfig(ssl.get(), config) ||
David Benjamin2d445c02015-02-09 13:03:50 -05001746 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
David Benjamin40f101b2015-02-20 11:23:42 -05001747 return false;
Adam Langley69a01602014-11-17 17:26:55 -08001748 }
David Benjamin5a593af2014-08-11 19:51:50 -04001749
Steven Valdez2d850622017-01-11 11:34:52 -05001750 GetTestState(ssl.get())->is_resume = is_resume;
1751
Adam Langley5f0efe02015-02-20 13:03:16 -08001752 if (config->fallback_scsv &&
1753 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
1754 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001755 }
David Benjamina0486782016-10-06 19:11:32 -04001756 // Install the certificate synchronously if nothing else will handle it.
1757 if (!config->use_early_callback &&
1758 !config->use_old_client_cert_callback &&
1759 !config->async &&
1760 !InstallCertificate(ssl.get())) {
1761 return false;
David Benjamin5a593af2014-08-11 19:51:50 -04001762 }
David Benjamin5edfc8c2016-12-10 15:46:58 -05001763 if (!config->use_old_client_cert_callback) {
1764 SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
1765 }
David Benjamin5a593af2014-08-11 19:51:50 -04001766 if (config->require_any_client_certificate) {
David Benjaminc3648fa2017-07-01 10:50:56 -04001767 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
Paul Lietar8f1c2682015-08-18 12:21:54 +01001768 NULL);
1769 }
1770 if (config->verify_peer) {
1771 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
David Benjamin5a593af2014-08-11 19:51:50 -04001772 }
David Benjaminc3648fa2017-07-01 10:50:56 -04001773 if (config->verify_peer_if_no_obc) {
1774 // Set SSL_VERIFY_FAIL_IF_NO_PEER_CERT so testing whether client
1775 // certificates were requested is easy.
1776 SSL_set_verify(ssl.get(),
1777 SSL_VERIFY_PEER | SSL_VERIFY_PEER_IF_NO_OBC |
1778 SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1779 NULL);
1780 }
David Benjamin5a593af2014-08-11 19:51:50 -04001781 if (config->false_start) {
David Benjamined7c4752015-02-16 19:16:46 -05001782 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
David Benjamin5a593af2014-08-11 19:51:50 -04001783 }
1784 if (config->cbc_record_splitting) {
David Benjamina7f333d2015-02-09 02:37:18 -05001785 SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
David Benjamin5a593af2014-08-11 19:51:50 -04001786 }
1787 if (config->partial_write) {
David Benjamina7f333d2015-02-09 02:37:18 -05001788 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
David Benjamin5a593af2014-08-11 19:51:50 -04001789 }
Steven Valdez4f94b1c2016-05-24 12:31:07 -04001790 if (config->no_tls13) {
1791 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
1792 }
David Benjamin5a593af2014-08-11 19:51:50 -04001793 if (config->no_tls12) {
David Benjamina7f333d2015-02-09 02:37:18 -05001794 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
David Benjamin5a593af2014-08-11 19:51:50 -04001795 }
1796 if (config->no_tls11) {
David Benjamina7f333d2015-02-09 02:37:18 -05001797 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
David Benjamin5a593af2014-08-11 19:51:50 -04001798 }
1799 if (config->no_tls1) {
David Benjamina7f333d2015-02-09 02:37:18 -05001800 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
David Benjamin5a593af2014-08-11 19:51:50 -04001801 }
1802 if (config->no_ssl3) {
David Benjamina7f333d2015-02-09 02:37:18 -05001803 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
David Benjamin5a593af2014-08-11 19:51:50 -04001804 }
Steven Valdez143e8b32016-07-11 13:19:03 -04001805 if (!config->expected_channel_id.empty() ||
1806 config->enable_channel_id) {
David Benjamineebd3c82016-12-06 17:43:58 -05001807 SSL_set_tls_channel_id_enabled(ssl.get(), 1);
David Benjamina08e49d2014-08-24 01:46:07 -04001808 }
1809 if (!config->send_channel_id.empty()) {
David Benjamineebd3c82016-12-06 17:43:58 -05001810 SSL_set_tls_channel_id_enabled(ssl.get(), 1);
David Benjamind9e07012015-02-09 03:04:34 -05001811 if (!config->async) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001812 // The async case will be supplied by |ChannelIdCallback|.
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001813 bssl::UniquePtr<EVP_PKEY> pkey = LoadPrivateKey(config->send_channel_id);
David Benjamind9e07012015-02-09 03:04:34 -05001814 if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001815 return false;
David Benjamind9e07012015-02-09 03:04:34 -05001816 }
David Benjamina08e49d2014-08-24 01:46:07 -04001817 }
David Benjamina08e49d2014-08-24 01:46:07 -04001818 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001819 if (!config->host_name.empty() &&
1820 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001821 return false;
David Benjamine78bfde2014-09-06 12:45:15 -04001822 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001823 if (!config->advertise_alpn.empty() &&
1824 SSL_set_alpn_protos(ssl.get(),
1825 (const uint8_t *)config->advertise_alpn.data(),
1826 config->advertise_alpn.size()) != 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001827 return false;
David Benjaminae2888f2014-09-06 12:58:58 -04001828 }
David Benjamin48cae082014-10-27 01:06:24 -04001829 if (!config->psk.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001830 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
1831 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
David Benjamin48cae082014-10-27 01:06:24 -04001832 }
David Benjamin61f95272014-11-25 01:55:35 -05001833 if (!config->psk_identity.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001834 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001835 return false;
David Benjamin48cae082014-10-27 01:06:24 -04001836 }
David Benjamin61f95272014-11-25 01:55:35 -05001837 if (!config->srtp_profiles.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001838 !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001839 return false;
David Benjamin61f95272014-11-25 01:55:35 -05001840 }
David Benjamin26e1ff32017-02-14 20:13:00 -05001841 if (config->enable_ocsp_stapling) {
1842 SSL_enable_ocsp_stapling(ssl.get());
David Benjamin61f95272014-11-25 01:55:35 -05001843 }
David Benjamin26e1ff32017-02-14 20:13:00 -05001844 if (config->enable_signed_cert_timestamps) {
1845 SSL_enable_signed_cert_timestamps(ssl.get());
David Benjaminca6c8262014-11-15 19:06:08 -05001846 }
David Benjamin2dc02042016-09-19 19:57:37 -04001847 if (config->min_version != 0 &&
David Benjamine4706902016-09-20 15:12:23 -04001848 !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) {
David Benjamin2dc02042016-09-19 19:57:37 -04001849 return false;
David Benjamin1eb367c2014-12-12 18:17:51 -05001850 }
David Benjamin2dc02042016-09-19 19:57:37 -04001851 if (config->max_version != 0 &&
David Benjamine4706902016-09-20 15:12:23 -04001852 !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) {
David Benjamin2dc02042016-09-19 19:57:37 -04001853 return false;
David Benjamin1eb367c2014-12-12 18:17:51 -05001854 }
David Benjamin13be1de2015-01-11 16:29:36 -05001855 if (config->mtu != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001856 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
1857 SSL_set_mtu(ssl.get(), config->mtu);
David Benjamin13be1de2015-01-11 16:29:36 -05001858 }
Adam Langley524e7172015-02-20 16:04:00 -08001859 if (config->install_ddos_callback) {
1860 SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
1861 }
David Benjamin1d5ef3b2015-10-12 19:54:18 -04001862 if (config->renegotiate_once) {
1863 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_once);
1864 }
1865 if (config->renegotiate_freely) {
1866 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
David Benjaminb16346b2015-04-08 19:16:58 -04001867 }
Adam Langley27a0d082015-11-03 13:34:10 -08001868 if (config->renegotiate_ignore) {
1869 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_ignore);
1870 }
David Benjamin30789da2015-08-29 22:56:45 -04001871 if (!config->check_close_notify) {
1872 SSL_set_quiet_shutdown(ssl.get(), 1);
1873 }
David Benjamin99fdfb92015-11-02 12:11:35 -05001874 if (config->p384_only) {
1875 int nid = NID_secp384r1;
1876 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
1877 return false;
1878 }
1879 }
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001880 if (config->enable_all_curves) {
1881 static const int kAllCurves[] = {
Adam Langley764ab982017-03-10 18:01:30 -08001882 NID_secp224r1, NID_X9_62_prime256v1, NID_secp384r1,
1883 NID_secp521r1, NID_X25519,
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001884 };
1885 if (!SSL_set1_curves(ssl.get(), kAllCurves,
Steven Valdezcb966542016-08-17 16:56:14 -04001886 OPENSSL_ARRAY_SIZE(kAllCurves))) {
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001887 return false;
1888 }
1889 }
Taylor Brandstetter376a0fe2016-05-10 19:30:28 -07001890 if (config->initial_timeout_duration_ms > 0) {
1891 DTLSv1_set_initial_timeout_duration(ssl.get(),
1892 config->initial_timeout_duration_ms);
1893 }
David Benjamina252b342016-09-26 19:57:53 -04001894 if (config->max_cert_list > 0) {
1895 SSL_set_max_cert_list(ssl.get(), config->max_cert_list);
1896 }
David Benjaminbbaf3672016-11-17 10:53:09 +09001897 if (!is_resume && config->retain_only_sha256_client_cert_initial) {
1898 SSL_set_retain_only_sha256_of_client_certs(ssl.get(), 1);
1899 }
1900 if (is_resume && config->retain_only_sha256_client_cert_resume) {
1901 SSL_set_retain_only_sha256_of_client_certs(ssl.get(), 1);
1902 }
David Benjamine3fbb362017-01-06 16:19:28 -05001903 if (config->max_send_fragment > 0) {
1904 SSL_set_max_send_fragment(ssl.get(), config->max_send_fragment);
1905 }
David Benjamin025b3d32014-07-01 19:53:04 -04001906
David Benjamin87c8a642015-02-21 01:54:29 -05001907 int sock = Connect(config->port);
1908 if (sock == -1) {
1909 return false;
1910 }
1911 SocketCloser closer(sock);
1912
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001913 bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
David Benjamina7f333d2015-02-09 02:37:18 -05001914 if (!bio) {
David Benjamin40f101b2015-02-20 11:23:42 -05001915 return false;
David Benjamin43ec06f2014-08-05 02:28:57 -04001916 }
David Benjamin6fd297b2014-08-11 18:43:38 -04001917 if (config->is_dtls) {
David Benjamin11c82892017-02-23 20:40:31 -05001918 bssl::UniquePtr<BIO> packeted = PacketedBioCreate(&g_clock);
David Benjaminb7c5e842016-03-28 09:59:10 -04001919 if (!packeted) {
1920 return false;
1921 }
David Benjamin585d7a42016-06-02 14:58:00 -04001922 GetTestState(ssl.get())->packeted_bio = packeted.get();
David Benjamina7f333d2015-02-09 02:37:18 -05001923 BIO_push(packeted.get(), bio.release());
1924 bio = std::move(packeted);
David Benjamin6fd297b2014-08-11 18:43:38 -04001925 }
David Benjamin5a593af2014-08-11 19:51:50 -04001926 if (config->async) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001927 bssl::UniquePtr<BIO> async_scoped =
David Benjaminc273d2c2015-02-09 12:59:46 -05001928 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
David Benjaminb7c5e842016-03-28 09:59:10 -04001929 if (!async_scoped) {
1930 return false;
1931 }
David Benjamina7f333d2015-02-09 02:37:18 -05001932 BIO_push(async_scoped.get(), bio.release());
David Benjamin6c2563e2015-04-03 03:47:47 -04001933 GetTestState(ssl.get())->async_bio = async_scoped.get();
David Benjamina7f333d2015-02-09 02:37:18 -05001934 bio = std::move(async_scoped);
David Benjamin43ec06f2014-08-05 02:28:57 -04001935 }
David Benjamina7f333d2015-02-09 02:37:18 -05001936 SSL_set_bio(ssl.get(), bio.get(), bio.get());
1937 bio.release(); // SSL_set_bio takes ownership.
David Benjamin43ec06f2014-08-05 02:28:57 -04001938
David Benjamin1d5c83e2014-07-22 19:20:02 -04001939 if (session != NULL) {
David Benjamin1b8b6912015-02-09 04:28:16 -05001940 if (!config->is_server) {
1941 if (SSL_set_session(ssl.get(), session) != 1) {
David Benjamin40f101b2015-02-20 11:23:42 -05001942 return false;
David Benjamin1b8b6912015-02-09 04:28:16 -05001943 }
1944 } else if (config->async) {
1945 // The internal session cache is disabled, so install the session
1946 // manually.
David Benjaminb9195402016-08-05 10:51:43 -04001947 SSL_SESSION_up_ref(session);
1948 GetTestState(ssl.get())->pending_session.reset(session);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001949 }
1950 }
1951
David Benjamina07c0fc2015-05-13 13:19:42 -04001952 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1953 fprintf(stderr, "non-null cipher before handshake\n");
1954 return false;
1955 }
1956
David Benjamin4784b992017-03-25 18:22:19 -05001957 if (config->is_server) {
1958 SSL_set_accept_state(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -05001959 } else {
David Benjamin4784b992017-03-25 18:22:19 -05001960 SSL_set_connect_state(ssl.get());
1961 }
1962
Steven Valdeze831a812017-03-09 14:56:07 -05001963 bool ret = DoExchange(out_session, ssl.get(), config, is_resume, false);
1964 if (!config->is_server && is_resume && config->expect_reject_early_data) {
1965 // We must have failed due to an early data rejection.
1966 if (ret) {
1967 fprintf(stderr, "0-RTT exchange unexpected succeeded.\n");
1968 return false;
1969 }
1970 if (SSL_get_error(ssl.get(), -1) != SSL_ERROR_EARLY_DATA_REJECTED) {
1971 fprintf(stderr,
1972 "SSL_get_error did not signal SSL_ERROR_EARLY_DATA_REJECTED.\n");
1973 return false;
1974 }
1975
1976 // Before reseting, early state should still be available.
1977 if (!SSL_in_early_data(ssl.get()) ||
1978 !CheckHandshakeProperties(ssl.get(), is_resume, config)) {
1979 fprintf(stderr, "SSL_in_early_data returned false before reset.\n");
1980 return false;
1981 }
1982
1983 // Reset the connection and try again at 1-RTT.
1984 SSL_reset_early_data_reject(ssl.get());
1985
1986 // After reseting, the socket should report it is no longer in an early data
1987 // state.
1988 if (SSL_in_early_data(ssl.get())) {
1989 fprintf(stderr, "SSL_in_early_data returned true after reset.\n");
1990 return false;
1991 }
1992
1993 if (!SetTestConfig(ssl.get(), retry_config)) {
1994 return false;
1995 }
1996
1997 ret = DoExchange(out_session, ssl.get(), retry_config, is_resume, true);
1998 }
1999 return ret;
2000}
2001
2002static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session, SSL *ssl,
2003 const TestConfig *config, bool is_resume,
2004 bool is_retry) {
David Benjamin4784b992017-03-25 18:22:19 -05002005 int ret;
2006 if (!config->implicit_handshake) {
David Benjamine0e7d0d2015-02-08 19:33:25 -05002007 do {
Steven Valdeze831a812017-03-09 14:56:07 -05002008 ret = SSL_do_handshake(ssl);
2009 } while (config->async && RetryAsync(ssl, ret));
David Benjamin91eab5c2015-06-18 18:35:46 -04002010 if (ret != 1 ||
Steven Valdeze831a812017-03-09 14:56:07 -05002011 !CheckHandshakeProperties(ssl, is_resume, config)) {
David Benjamin40f101b2015-02-20 11:23:42 -05002012 return false;
David Benjamine0e7d0d2015-02-08 19:33:25 -05002013 }
David Benjamin025b3d32014-07-01 19:53:04 -04002014
David Benjamin8c26d752017-03-26 15:13:51 -05002015 if (config->handshake_twice) {
2016 do {
Steven Valdeze831a812017-03-09 14:56:07 -05002017 ret = SSL_do_handshake(ssl);
2018 } while (config->async && RetryAsync(ssl, ret));
David Benjamin8c26d752017-03-26 15:13:51 -05002019 if (ret != 1) {
2020 return false;
2021 }
2022 }
2023
2024 // Skip the |config->async| logic as this should be a no-op.
2025 if (config->no_op_extra_handshake &&
Steven Valdeze831a812017-03-09 14:56:07 -05002026 SSL_do_handshake(ssl) != 1) {
David Benjamin8c26d752017-03-26 15:13:51 -05002027 fprintf(stderr, "Extra SSL_do_handshake was not a no-op.\n");
2028 return false;
2029 }
2030
David Benjaminba4594a2015-06-18 18:36:15 -04002031 // Reset the state to assert later that the callback isn't called in
2032 // renegotations.
Steven Valdeze831a812017-03-09 14:56:07 -05002033 GetTestState(ssl)->got_new_session = false;
David Benjamin61f95272014-11-25 01:55:35 -05002034 }
2035
David Benjaminc565ebb2015-04-03 04:06:36 -04002036 if (config->export_keying_material > 0) {
2037 std::vector<uint8_t> result(
2038 static_cast<size_t>(config->export_keying_material));
2039 if (!SSL_export_keying_material(
Steven Valdeze831a812017-03-09 14:56:07 -05002040 ssl, result.data(), result.size(), config->export_label.data(),
2041 config->export_label.size(),
2042 reinterpret_cast<const uint8_t *>(config->export_context.data()),
David Benjaminc565ebb2015-04-03 04:06:36 -04002043 config->export_context.size(), config->use_export_context)) {
2044 fprintf(stderr, "failed to export keying material\n");
2045 return false;
2046 }
Steven Valdeze831a812017-03-09 14:56:07 -05002047 if (WriteAll(ssl, result.data(), result.size()) < 0) {
David Benjaminc565ebb2015-04-03 04:06:36 -04002048 return false;
2049 }
2050 }
2051
Adam Langleyaf0e32c2015-06-03 09:57:23 -07002052 if (config->tls_unique) {
2053 uint8_t tls_unique[16];
2054 size_t tls_unique_len;
Steven Valdeze831a812017-03-09 14:56:07 -05002055 if (!SSL_get_tls_unique(ssl, tls_unique, &tls_unique_len,
Adam Langleyaf0e32c2015-06-03 09:57:23 -07002056 sizeof(tls_unique))) {
2057 fprintf(stderr, "failed to get tls-unique\n");
2058 return false;
2059 }
2060
2061 if (tls_unique_len != 12) {
2062 fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
2063 static_cast<unsigned>(tls_unique_len));
2064 return false;
2065 }
2066
Steven Valdeze831a812017-03-09 14:56:07 -05002067 if (WriteAll(ssl, tls_unique, tls_unique_len) < 0) {
Adam Langleyaf0e32c2015-06-03 09:57:23 -07002068 return false;
2069 }
2070 }
2071
David Benjamin1d4f4c02016-07-26 18:03:08 -04002072 if (config->send_alert) {
Steven Valdeze831a812017-03-09 14:56:07 -05002073 if (DoSendFatalAlert(ssl, SSL_AD_DECOMPRESSION_FAILURE) < 0) {
David Benjamin1d4f4c02016-07-26 18:03:08 -04002074 return false;
2075 }
2076 return true;
2077 }
2078
David Benjamin5a593af2014-08-11 19:51:50 -04002079 if (config->write_different_record_sizes) {
David Benjamin6fd297b2014-08-11 18:43:38 -04002080 if (config->is_dtls) {
2081 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
David Benjamin40f101b2015-02-20 11:23:42 -05002082 return false;
David Benjamin6fd297b2014-08-11 18:43:38 -04002083 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07002084 // This mode writes a number of different record sizes in an attempt to
2085 // trip up the CBC record splitting code.
Adam Langleybc949292015-06-18 21:32:44 -07002086 static const size_t kBufLen = 32769;
2087 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
David Benjamin17cf2cb2016-12-13 01:07:13 -05002088 OPENSSL_memset(buf.get(), 0x42, kBufLen);
Kenny Root7fdeaf12014-08-05 15:23:37 -07002089 static const size_t kRecordSizes[] = {
2090 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
Steven Valdezcb966542016-08-17 16:56:14 -04002091 for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07002092 const size_t len = kRecordSizes[i];
Adam Langleybc949292015-06-18 21:32:44 -07002093 if (len > kBufLen) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07002094 fprintf(stderr, "Bad kRecordSizes value.\n");
David Benjamin40f101b2015-02-20 11:23:42 -05002095 return false;
Kenny Root7fdeaf12014-08-05 15:23:37 -07002096 }
Steven Valdeze831a812017-03-09 14:56:07 -05002097 if (WriteAll(ssl, buf.get(), len) < 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05002098 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04002099 }
2100 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07002101 } else {
David Benjaminbbba9392017-04-06 12:54:12 -04002102 static const char kInitialWrite[] = "hello";
2103 bool pending_initial_write = false;
David Benjamina1eaba12017-01-01 23:19:22 -05002104 if (config->read_with_unfinished_write) {
2105 if (!config->async) {
2106 fprintf(stderr, "-read-with-unfinished-write requires -async.\n");
2107 return false;
2108 }
2109
Steven Valdeze831a812017-03-09 14:56:07 -05002110 // Let only one byte of the record through.
2111 AsyncBioAllowWrite(GetTestState(ssl)->async_bio, 1);
David Benjaminbbba9392017-04-06 12:54:12 -04002112 int write_ret =
Steven Valdeze831a812017-03-09 14:56:07 -05002113 SSL_write(ssl, kInitialWrite, strlen(kInitialWrite));
2114 if (SSL_get_error(ssl, write_ret) != SSL_ERROR_WANT_WRITE) {
David Benjamina1eaba12017-01-01 23:19:22 -05002115 fprintf(stderr, "Failed to leave unfinished write.\n");
2116 return false;
2117 }
David Benjaminbbba9392017-04-06 12:54:12 -04002118 pending_initial_write = true;
2119 } else if (config->shim_writes_first) {
Steven Valdeze831a812017-03-09 14:56:07 -05002120 if (WriteAll(ssl, kInitialWrite, strlen(kInitialWrite)) < 0) {
David Benjamin6c2563e2015-04-03 03:47:47 -04002121 return false;
2122 }
David Benjamine58c4f52014-08-24 03:47:07 -04002123 }
David Benjamin30789da2015-08-29 22:56:45 -04002124 if (!config->shim_shuts_down) {
2125 for (;;) {
David Benjamin2c99d282015-09-01 10:23:00 -04002126 // Read only 512 bytes at a time in TLS to ensure records may be
2127 // returned in multiple reads.
David Benjamine3fbb362017-01-06 16:19:28 -05002128 size_t read_size = config->is_dtls ? 16384 : 512;
2129 if (config->read_size > 0) {
2130 read_size = config->read_size;
2131 }
2132 std::unique_ptr<uint8_t[]> buf(new uint8_t[read_size]);
2133
Steven Valdeze831a812017-03-09 14:56:07 -05002134 int n = DoRead(ssl, buf.get(), read_size);
2135 int err = SSL_get_error(ssl, n);
David Benjamin30789da2015-08-29 22:56:45 -04002136 if (err == SSL_ERROR_ZERO_RETURN ||
2137 (n == 0 && err == SSL_ERROR_SYSCALL)) {
2138 if (n != 0) {
2139 fprintf(stderr, "Invalid SSL_get_error output\n");
2140 return false;
2141 }
2142 // Stop on either clean or unclean shutdown.
2143 break;
2144 } else if (err != SSL_ERROR_NONE) {
2145 if (n > 0) {
2146 fprintf(stderr, "Invalid SSL_get_error output\n");
2147 return false;
2148 }
2149 return false;
2150 }
2151 // Successfully read data.
2152 if (n <= 0) {
David Benjamin9a38e922015-01-22 16:06:11 -05002153 fprintf(stderr, "Invalid SSL_get_error output\n");
David Benjamin40f101b2015-02-20 11:23:42 -05002154 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05002155 }
David Benjamin30789da2015-08-29 22:56:45 -04002156
Steven Valdeze831a812017-03-09 14:56:07 -05002157 if (!config->is_server && is_resume && !is_retry &&
2158 config->expect_reject_early_data) {
2159 fprintf(stderr,
2160 "Unexpectedly received data instead of 0-RTT reject.\n");
2161 return false;
2162 }
2163
David Benjamin30789da2015-08-29 22:56:45 -04002164 // After a successful read, with or without False Start, the handshake
Steven Valdez681eb6a2016-12-19 13:19:29 -05002165 // must be complete unless we are doing early data.
Steven Valdeze831a812017-03-09 14:56:07 -05002166 if (!GetTestState(ssl)->handshake_done &&
2167 !SSL_early_data_accepted(ssl)) {
David Benjamin30789da2015-08-29 22:56:45 -04002168 fprintf(stderr, "handshake was not completed after SSL_read\n");
David Benjamin40f101b2015-02-20 11:23:42 -05002169 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05002170 }
David Benjamin87e4acd2015-04-02 19:57:35 -04002171
David Benjaminbbba9392017-04-06 12:54:12 -04002172 // Clear the initial write, if unfinished.
2173 if (pending_initial_write) {
Steven Valdeze831a812017-03-09 14:56:07 -05002174 if (WriteAll(ssl, kInitialWrite, strlen(kInitialWrite)) < 0) {
David Benjaminbbba9392017-04-06 12:54:12 -04002175 return false;
2176 }
2177 pending_initial_write = false;
2178 }
2179
David Benjamin30789da2015-08-29 22:56:45 -04002180 for (int i = 0; i < n; i++) {
2181 buf[i] ^= 0xff;
2182 }
Steven Valdeze831a812017-03-09 14:56:07 -05002183 if (WriteAll(ssl, buf.get(), n) < 0) {
David Benjamin30789da2015-08-29 22:56:45 -04002184 return false;
2185 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07002186 }
2187 }
David Benjamin025b3d32014-07-01 19:53:04 -04002188 }
2189
David Benjaminba4594a2015-06-18 18:36:15 -04002190 if (!config->is_server && !config->false_start &&
2191 !config->implicit_handshake &&
Steven Valdez1e6f11a2016-07-27 11:10:52 -04002192 // Session tickets are sent post-handshake in TLS 1.3.
Steven Valdeze831a812017-03-09 14:56:07 -05002193 GetProtocolVersion(ssl) < TLS1_3_VERSION &&
2194 GetTestState(ssl)->got_new_session) {
David Benjaminba4594a2015-06-18 18:36:15 -04002195 fprintf(stderr, "new session was established after the handshake\n");
2196 return false;
2197 }
2198
Steven Valdeze831a812017-03-09 14:56:07 -05002199 if (GetProtocolVersion(ssl) >= TLS1_3_VERSION && !config->is_server) {
Steven Valdez1e6f11a2016-07-27 11:10:52 -04002200 bool expect_new_session =
2201 !config->expect_no_session && !config->shim_shuts_down;
Steven Valdeze831a812017-03-09 14:56:07 -05002202 if (expect_new_session != GetTestState(ssl)->got_new_session) {
Steven Valdez1e6f11a2016-07-27 11:10:52 -04002203 fprintf(stderr,
2204 "new session was%s cached, but we expected the opposite\n",
Steven Valdeze831a812017-03-09 14:56:07 -05002205 GetTestState(ssl)->got_new_session ? "" : " not");
Steven Valdez1e6f11a2016-07-27 11:10:52 -04002206 return false;
2207 }
Steven Valdez08b65f42016-12-07 15:29:45 -05002208
2209 if (expect_new_session) {
2210 bool got_early_data_info =
Steven Valdeze831a812017-03-09 14:56:07 -05002211 GetTestState(ssl)->new_session->ticket_max_early_data != 0;
Steven Valdez08b65f42016-12-07 15:29:45 -05002212 if (config->expect_early_data_info != got_early_data_info) {
2213 fprintf(
2214 stderr,
2215 "new session did%s include ticket_early_data_info, but we expected "
2216 "the opposite\n",
2217 got_early_data_info ? "" : " not");
2218 return false;
2219 }
2220 }
Steven Valdez1e6f11a2016-07-27 11:10:52 -04002221 }
2222
David Benjamin1d5c83e2014-07-22 19:20:02 -04002223 if (out_session) {
Steven Valdeze831a812017-03-09 14:56:07 -05002224 *out_session = std::move(GetTestState(ssl)->new_session);
David Benjamin1d5c83e2014-07-22 19:20:02 -04002225 }
2226
Steven Valdeze831a812017-03-09 14:56:07 -05002227 ret = DoShutdown(ssl);
David Benjamin30789da2015-08-29 22:56:45 -04002228
2229 if (config->shim_shuts_down && config->check_close_notify) {
2230 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
2231 // it returns zero when our close_notify is sent, then one when the peer's
2232 // is received.
2233 if (ret != 0) {
2234 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
2235 return false;
2236 }
Steven Valdeze831a812017-03-09 14:56:07 -05002237 ret = DoShutdown(ssl);
David Benjamin30789da2015-08-29 22:56:45 -04002238 }
2239
2240 if (ret != 1) {
2241 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
2242 return false;
2243 }
2244
Steven Valdeze831a812017-03-09 14:56:07 -05002245 if (SSL_total_renegotiations(ssl) != config->expect_total_renegotiations) {
David Benjamin324dce42015-10-12 19:49:00 -04002246 fprintf(stderr, "Expected %d renegotiations, got %d\n",
Steven Valdeze831a812017-03-09 14:56:07 -05002247 config->expect_total_renegotiations, SSL_total_renegotiations(ssl));
David Benjamin324dce42015-10-12 19:49:00 -04002248 return false;
2249 }
2250
David Benjamin40f101b2015-02-20 11:23:42 -05002251 return true;
David Benjamin025b3d32014-07-01 19:53:04 -04002252}
David Benjamin1d5c83e2014-07-22 19:20:02 -04002253
David Benjaminff3a1492016-03-02 10:12:06 -05002254class StderrDelimiter {
2255 public:
2256 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
2257};
2258
David Benjaminaac1e2d2016-12-06 22:35:41 -05002259int main(int argc, char **argv) {
David Benjaminff3a1492016-03-02 10:12:06 -05002260 // To distinguish ASan's output from ours, add a trailing message to stderr.
2261 // Anything following this line will be considered an error.
2262 StderrDelimiter delimiter;
2263
David Benjamin87c8a642015-02-21 01:54:29 -05002264#if defined(OPENSSL_WINDOWS)
2265 /* Initialize Winsock. */
2266 WORD wsa_version = MAKEWORD(2, 2);
2267 WSADATA wsa_data;
2268 int wsa_err = WSAStartup(wsa_version, &wsa_data);
2269 if (wsa_err != 0) {
2270 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
2271 return 1;
2272 }
2273 if (wsa_data.wVersion != wsa_version) {
2274 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
2275 return 1;
2276 }
2277#else
David Benjamin1d5c83e2014-07-22 19:20:02 -04002278 signal(SIGPIPE, SIG_IGN);
Adam Langleyded93582014-07-31 15:23:51 -07002279#endif
David Benjamin1d5c83e2014-07-22 19:20:02 -04002280
David Benjamin7a1eefd2015-10-17 23:39:22 -04002281 CRYPTO_library_init();
David Benjamind9e07012015-02-09 03:04:34 -05002282 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
David Benjamin2d445c02015-02-09 13:03:50 -05002283 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
David Benjamin6c2563e2015-04-03 03:47:47 -04002284 if (g_config_index < 0 || g_state_index < 0) {
David Benjaminae3e4872014-11-18 21:52:26 -05002285 return 1;
2286 }
David Benjamin5a593af2014-08-11 19:51:50 -04002287
Steven Valdeze831a812017-03-09 14:56:07 -05002288 TestConfig initial_config, resume_config, retry_config;
2289 if (!ParseConfig(argc - 1, argv + 1, &initial_config, &resume_config,
2290 &retry_config)) {
David Benjaminc273d2c2015-02-09 12:59:46 -05002291 return Usage(argv[0]);
David Benjamin1d5c83e2014-07-22 19:20:02 -04002292 }
2293
Adam Langleyd519bf62016-12-12 11:16:44 -08002294 g_pool = CRYPTO_BUFFER_POOL_new();
2295
David Benjamin1b22f852016-10-27 16:36:32 -04002296 // Some code treats the zero time special, so initialize the clock to a
2297 // non-zero time.
2298 g_clock.tv_sec = 1234;
2299 g_clock.tv_usec = 1234;
2300
Steven Valdez873ebc92017-05-09 12:12:58 -04002301 bssl::UniquePtr<SSL_CTX> ssl_ctx;
David Benjamin1d5c83e2014-07-22 19:20:02 -04002302
Matt Braithwaited17d74d2016-08-17 20:10:28 -07002303 bssl::UniquePtr<SSL_SESSION> session;
Steven Valdez873ebc92017-05-09 12:12:58 -04002304 for (int i = 0; i < initial_config.resume_count + 1; i++) {
David Benjamin46662482016-08-17 00:51:00 -04002305 bool is_resume = i > 0;
Steven Valdez873ebc92017-05-09 12:12:58 -04002306 TestConfig *config = is_resume ? &resume_config : &initial_config;
2307 ssl_ctx = SetupCtx(ssl_ctx.get(), config);
2308 if (!ssl_ctx) {
2309 ERR_print_errors_fp(stderr);
2310 return 1;
2311 }
2312
2313 if (is_resume && !initial_config.is_server && !session) {
David Benjamin46662482016-08-17 00:51:00 -04002314 fprintf(stderr, "No session to offer.\n");
2315 return 1;
2316 }
David Benjamin1d5c83e2014-07-22 19:20:02 -04002317
Matt Braithwaited17d74d2016-08-17 20:10:28 -07002318 bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
David Benjamin0fde2eb2017-06-30 19:11:22 -04002319 if (!WriteSettings(i, config, offer_session.get())) {
2320 fprintf(stderr, "Error writing settings.\n");
2321 return 1;
2322 }
Steven Valdeze831a812017-03-09 14:56:07 -05002323 if (!DoConnection(&session, ssl_ctx.get(), config, &retry_config, is_resume,
2324 offer_session.get())) {
David Benjamin46662482016-08-17 00:51:00 -04002325 fprintf(stderr, "Connection %d failed.\n", i + 1);
2326 ERR_print_errors_fp(stderr);
2327 return 1;
2328 }
Steven Valdeza833c352016-11-01 13:39:36 -04002329
Steven Valdez873ebc92017-05-09 12:12:58 -04002330 if (config->resumption_delay != 0) {
2331 g_clock.tv_sec += config->resumption_delay;
Steven Valdeza833c352016-11-01 13:39:36 -04002332 }
David Benjamin1d5c83e2014-07-22 19:20:02 -04002333 }
2334
David Benjamina7f333d2015-02-09 02:37:18 -05002335 return 0;
David Benjamin1d5c83e2014-07-22 19:20:02 -04002336}