blob: e088aa9c8c26ced48f5ebc1ec07c0f7c4cd78625 [file] [log] [blame]
David Benjamin025b3d32014-07-01 19:53:04 -04001/* Copyright (c) 2014, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
David Benjamin4cc36ad2015-12-19 14:23:26 -050015#if !defined(__STDC_FORMAT_MACROS)
16#define __STDC_FORMAT_MACROS
17#endif
18
Adam Langleyded93582014-07-31 15:23:51 -070019#include <openssl/base.h>
20
21#if !defined(OPENSSL_WINDOWS)
David Benjamin025b3d32014-07-01 19:53:04 -040022#include <arpa/inet.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040023#include <netinet/in.h>
David Benjamin87c8a642015-02-21 01:54:29 -050024#include <netinet/tcp.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040025#include <signal.h>
26#include <sys/socket.h>
David Benjamin0abd6f22015-12-04 21:49:53 -050027#include <sys/time.h>
David Benjamin8f2c20e2014-07-09 09:30:38 -040028#include <unistd.h>
David Benjamin87c8a642015-02-21 01:54:29 -050029#else
30#include <io.h>
David Benjamina353cdb2016-06-09 16:48:33 -040031OPENSSL_MSVC_PRAGMA(warning(push, 3))
Adam Langley3e719312015-03-20 16:32:23 -070032#include <winsock2.h>
33#include <ws2tcpip.h>
David Benjamina353cdb2016-06-09 16:48:33 -040034OPENSSL_MSVC_PRAGMA(warning(pop))
David Benjamin87c8a642015-02-21 01:54:29 -050035
David Benjamin4fec04b2016-10-10 14:56:47 -040036OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
Adam Langleyded93582014-07-31 15:23:51 -070037#endif
38
David Benjamin585d7a42016-06-02 14:58:00 -040039#include <assert.h>
David Benjamin4cc36ad2015-12-19 14:23:26 -050040#include <inttypes.h>
Adam Langley2b2d66d2015-01-30 17:08:37 -080041#include <string.h>
David Benjamin025b3d32014-07-01 19:53:04 -040042
David Benjaminabbbee12016-10-31 19:20:42 -040043#include <openssl/aead.h>
David Benjamin025b3d32014-07-01 19:53:04 -040044#include <openssl/bio.h>
David Benjamin48cae082014-10-27 01:06:24 -040045#include <openssl/buf.h>
David Benjamin8f2c20e2014-07-09 09:30:38 -040046#include <openssl/bytestring.h>
David Benjamind98452d2015-06-16 14:16:23 -040047#include <openssl/cipher.h>
David Benjamin7a1eefd2015-10-17 23:39:22 -040048#include <openssl/crypto.h>
David Benjaminf0e935d2016-09-06 18:10:19 -040049#include <openssl/digest.h>
Brian Smith83a82982015-04-09 16:21:10 -100050#include <openssl/err.h>
Matt Braithwaited17d74d2016-08-17 20:10:28 -070051#include <openssl/evp.h>
David Benjamind98452d2015-06-16 14:16:23 -040052#include <openssl/hmac.h>
David Benjamin98193672016-03-25 18:07:11 -040053#include <openssl/nid.h>
David Benjamind98452d2015-06-16 14:16:23 -040054#include <openssl/rand.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040055#include <openssl/ssl.h>
Matt Braithwaited17d74d2016-08-17 20:10:28 -070056#include <openssl/x509.h>
David Benjamin1d5c83e2014-07-22 19:20:02 -040057
David Benjamin45fb1be2015-03-22 16:31:27 -040058#include <memory>
Steven Valdez0d62f262015-09-04 12:41:04 -040059#include <string>
David Benjaminc565ebb2015-04-03 04:06:36 -040060#include <vector>
David Benjamin45fb1be2015-03-22 16:31:27 -040061
Steven Valdezcb966542016-08-17 16:56:14 -040062#include "../../crypto/internal.h"
Steven Valdez873ebc92017-05-09 12:12:58 -040063#include "../internal.h"
David Benjamin43ec06f2014-08-05 02:28:57 -040064#include "async_bio.h"
David Benjamin6fd297b2014-08-11 18:43:38 -040065#include "packeted_bio.h"
David Benjamin5a593af2014-08-11 19:51:50 -040066#include "test_config.h"
David Benjamin43ec06f2014-08-05 02:28:57 -040067
David Benjamin87c8a642015-02-21 01:54:29 -050068
Adam Langleyd519bf62016-12-12 11:16:44 -080069static CRYPTO_BUFFER_POOL *g_pool = nullptr;
70
David Benjamin87c8a642015-02-21 01:54:29 -050071#if !defined(OPENSSL_WINDOWS)
72static int closesocket(int sock) {
73 return close(sock);
74}
75
76static void PrintSocketError(const char *func) {
77 perror(func);
78}
79#else
80static void PrintSocketError(const char *func) {
81 fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
82}
83#endif
84
David Benjaminc273d2c2015-02-09 12:59:46 -050085static int Usage(const char *program) {
David Benjamina7f333d2015-02-09 02:37:18 -050086 fprintf(stderr, "Usage: %s [flags...]\n", program);
David Benjamin1d5c83e2014-07-22 19:20:02 -040087 return 1;
88}
David Benjamin025b3d32014-07-01 19:53:04 -040089
David Benjamin2d445c02015-02-09 13:03:50 -050090struct TestState {
David Benjamin6c2563e2015-04-03 03:47:47 -040091 // async_bio is async BIO which pauses reads and writes.
92 BIO *async_bio = nullptr;
David Benjamin585d7a42016-06-02 14:58:00 -040093 // packeted_bio is the packeted BIO which simulates read timeouts.
94 BIO *packeted_bio = nullptr;
Matt Braithwaited17d74d2016-08-17 20:10:28 -070095 bssl::UniquePtr<EVP_PKEY> channel_id;
David Benjamin0d4db502015-03-23 18:46:05 -040096 bool cert_ready = false;
Matt Braithwaited17d74d2016-08-17 20:10:28 -070097 bssl::UniquePtr<SSL_SESSION> session;
98 bssl::UniquePtr<SSL_SESSION> pending_session;
David Benjamin0d4db502015-03-23 18:46:05 -040099 bool early_callback_called = false;
David Benjamin87e4acd2015-04-02 19:57:35 -0400100 bool handshake_done = false;
David Benjaminb4d65fd2015-05-29 17:11:21 -0400101 // private_key is the underlying private key used when testing custom keys.
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700102 bssl::UniquePtr<EVP_PKEY> private_key;
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700103 std::vector<uint8_t> private_key_result;
104 // private_key_retries is the number of times an asynchronous private key
105 // operation has been retried.
106 unsigned private_key_retries = 0;
David Benjaminba4594a2015-06-18 18:36:15 -0400107 bool got_new_session = false;
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700108 bssl::UniquePtr<SSL_SESSION> new_session;
David Benjamin25fe85b2016-08-09 20:00:32 -0400109 bool ticket_decrypt_done = false;
110 bool alpn_select_done = false;
Steven Valdez2d850622017-01-11 11:34:52 -0500111 bool is_resume = false;
Alessandro Ghedini958346a2016-12-20 19:42:15 +0000112 bool early_callback_ready = false;
David Benjamind9e07012015-02-09 03:04:34 -0500113};
114
David Benjamin2d445c02015-02-09 13:03:50 -0500115static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
Adam Langley09505632015-07-30 18:10:13 -0700116 int index, long argl, void *argp) {
David Benjamin2d445c02015-02-09 13:03:50 -0500117 delete ((TestState *)ptr);
David Benjamind9e07012015-02-09 03:04:34 -0500118}
119
120static int g_config_index = 0;
David Benjamin2d445c02015-02-09 13:03:50 -0500121static int g_state_index = 0;
David Benjamin5a593af2014-08-11 19:51:50 -0400122
David Benjamin7e7a82d2016-05-20 20:12:42 -0400123static bool SetTestConfig(SSL *ssl, const TestConfig *config) {
David Benjamind9e07012015-02-09 03:04:34 -0500124 return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
David Benjamin5a593af2014-08-11 19:51:50 -0400125}
126
David Benjamin7e7a82d2016-05-20 20:12:42 -0400127static const TestConfig *GetTestConfig(const SSL *ssl) {
David Benjamind9e07012015-02-09 03:04:34 -0500128 return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
David Benjamin5a593af2014-08-11 19:51:50 -0400129}
130
David Benjamin22050932015-11-23 13:44:48 -0500131static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
132 // |SSL_set_ex_data| takes ownership of |state| only on success.
133 if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
134 state.release();
David Benjamind9e07012015-02-09 03:04:34 -0500135 return true;
136 }
137 return false;
138}
139
David Benjamin87e4acd2015-04-02 19:57:35 -0400140static TestState *GetTestState(const SSL *ssl) {
David Benjamin2d445c02015-02-09 13:03:50 -0500141 return (TestState *)SSL_get_ex_data(ssl, g_state_index);
David Benjamin83f90402015-01-27 01:09:43 -0500142}
143
David Benjamin2c516452016-11-15 10:16:54 +0900144static bool LoadCertificate(bssl::UniquePtr<X509> *out_x509,
145 bssl::UniquePtr<STACK_OF(X509)> *out_chain,
146 const std::string &file) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700147 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
David Benjaminacb6dcc2016-03-10 09:15:01 -0500148 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
David Benjamin2c516452016-11-15 10:16:54 +0900149 return false;
David Benjaminacb6dcc2016-03-10 09:15:01 -0500150 }
David Benjamin2c516452016-11-15 10:16:54 +0900151
152 out_x509->reset(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
153 if (!*out_x509) {
154 return false;
155 }
156
157 out_chain->reset(sk_X509_new_null());
158 if (!*out_chain) {
159 return false;
160 }
161
162 // Keep reading the certificate chain.
163 for (;;) {
164 bssl::UniquePtr<X509> cert(
165 PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
166 if (!cert) {
167 break;
168 }
169
170 if (!sk_X509_push(out_chain->get(), cert.get())) {
171 return false;
172 }
173 cert.release(); // sk_X509_push takes ownership.
174 }
175
176 uint32_t err = ERR_peek_last_error();
177 if (ERR_GET_LIB(err) != ERR_LIB_PEM ||
178 ERR_GET_REASON(err) != PEM_R_NO_START_LINE) {
179 return false;
180}
181
182 ERR_clear_error();
183 return true;
David Benjaminacb6dcc2016-03-10 09:15:01 -0500184}
185
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700186static bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
187 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
David Benjamina7f333d2015-02-09 02:37:18 -0500188 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
189 return nullptr;
David Benjamina08e49d2014-08-24 01:46:07 -0400190 }
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700191 return bssl::UniquePtr<EVP_PKEY>(
192 PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
David Benjamina08e49d2014-08-24 01:46:07 -0400193}
194
Adam Langley2ff79332017-02-28 13:45:39 -0800195static bool FromHexDigit(uint8_t *out, char c) {
196 if ('0' <= c && c <= '9') {
197 *out = c - '0';
198 return true;
199 }
200 if ('a' <= c && c <= 'f') {
201 *out = c - 'a' + 10;
202 return true;
203 }
204 if ('A' <= c && c <= 'F') {
205 *out = c - 'A' + 10;
206 return true;
207 }
208 return false;
209}
210
211static bool HexDecode(std::string *out, const std::string &in) {
212 if ((in.size() & 1) != 0) {
213 return false;
214 }
215
216 std::unique_ptr<uint8_t[]> buf(new uint8_t[in.size() / 2]);
217 for (size_t i = 0; i < in.size() / 2; i++) {
218 uint8_t high, low;
219 if (!FromHexDigit(&high, in[i*2]) ||
220 !FromHexDigit(&low, in[i*2+1])) {
221 return false;
222 }
223 buf[i] = (high << 4) | low;
224 }
225
226 out->assign(reinterpret_cast<const char *>(buf.get()), in.size() / 2);
227 return true;
228}
229
230static std::vector<std::string> SplitParts(const std::string &in,
231 const char delim) {
232 std::vector<std::string> ret;
233 size_t start = 0;
234
235 for (size_t i = 0; i < in.size(); i++) {
236 if (in[i] == delim) {
237 ret.push_back(in.substr(start, i - start));
238 start = i + 1;
239 }
240 }
241
242 ret.push_back(in.substr(start, std::string::npos));
243 return ret;
244}
245
246static std::vector<std::string> DecodeHexStrings(
247 const std::string &hex_strings) {
248 std::vector<std::string> ret;
249 const std::vector<std::string> parts = SplitParts(hex_strings, ',');
250
251 for (const auto &part : parts) {
252 std::string binary;
253 if (!HexDecode(&binary, part)) {
254 fprintf(stderr, "Bad hex string: %s\n", part.c_str());
255 return ret;
256 }
257
258 ret.push_back(binary);
259 }
260
261 return ret;
262}
263
264static bssl::UniquePtr<STACK_OF(X509_NAME)> DecodeHexX509Names(
265 const std::string &hex_names) {
266 const std::vector<std::string> der_names = DecodeHexStrings(hex_names);
267 bssl::UniquePtr<STACK_OF(X509_NAME)> ret(sk_X509_NAME_new_null());
268
269 for (const auto &der_name : der_names) {
270 const uint8_t *const data =
271 reinterpret_cast<const uint8_t *>(der_name.data());
272 const uint8_t *derp = data;
273 bssl::UniquePtr<X509_NAME> name(
274 d2i_X509_NAME(nullptr, &derp, der_name.size()));
275 if (!name || derp != data + der_name.size()) {
276 fprintf(stderr, "Failed to parse X509_NAME.\n");
277 return nullptr;
278 }
279
280 if (!sk_X509_NAME_push(ret.get(), name.get())) {
281 return nullptr;
282 }
283 name.release();
284 }
285
286 return ret;
287}
288
David Benjaminb4d65fd2015-05-29 17:11:21 -0400289static ssl_private_key_result_t AsyncPrivateKeySign(
290 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
David Benjamind3440b42016-07-14 14:52:41 -0400291 uint16_t signature_algorithm, const uint8_t *in, size_t in_len) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400292 TestState *test_state = GetTestState(ssl);
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700293 if (!test_state->private_key_result.empty()) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400294 fprintf(stderr, "AsyncPrivateKeySign called with operation pending.\n");
295 abort();
296 }
297
David Benjamind3440b42016-07-14 14:52:41 -0400298 // Determine the hash.
299 const EVP_MD *md;
300 switch (signature_algorithm) {
301 case SSL_SIGN_RSA_PKCS1_SHA1:
302 case SSL_SIGN_ECDSA_SHA1:
303 md = EVP_sha1();
304 break;
305 case SSL_SIGN_RSA_PKCS1_SHA256:
306 case SSL_SIGN_ECDSA_SECP256R1_SHA256:
307 case SSL_SIGN_RSA_PSS_SHA256:
308 md = EVP_sha256();
309 break;
310 case SSL_SIGN_RSA_PKCS1_SHA384:
311 case SSL_SIGN_ECDSA_SECP384R1_SHA384:
312 case SSL_SIGN_RSA_PSS_SHA384:
313 md = EVP_sha384();
314 break;
315 case SSL_SIGN_RSA_PKCS1_SHA512:
316 case SSL_SIGN_ECDSA_SECP521R1_SHA512:
317 case SSL_SIGN_RSA_PSS_SHA512:
318 md = EVP_sha512();
319 break;
320 case SSL_SIGN_RSA_PKCS1_MD5_SHA1:
321 md = EVP_md5_sha1();
322 break;
David Benjamin69522112017-03-28 15:38:29 -0500323 case SSL_SIGN_ED25519:
324 md = nullptr;
325 break;
David Benjamind3440b42016-07-14 14:52:41 -0400326 default:
327 fprintf(stderr, "Unknown signature algorithm %04x.\n",
328 signature_algorithm);
329 return ssl_private_key_failure;
330 }
331
David Benjamin19670942017-05-31 19:07:31 -0400332 bssl::ScopedEVP_MD_CTX ctx;
333 EVP_PKEY_CTX *pctx;
334 if (!EVP_DigestSignInit(ctx.get(), &pctx, md, nullptr,
335 test_state->private_key.get())) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400336 return ssl_private_key_failure;
337 }
338
David Benjamind3440b42016-07-14 14:52:41 -0400339 // Configure additional signature parameters.
340 switch (signature_algorithm) {
341 case SSL_SIGN_RSA_PSS_SHA256:
342 case SSL_SIGN_RSA_PSS_SHA384:
343 case SSL_SIGN_RSA_PSS_SHA512:
David Benjamin19670942017-05-31 19:07:31 -0400344 if (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) ||
345 !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
David Benjamind3440b42016-07-14 14:52:41 -0400346 -1 /* salt len = hash len */)) {
347 return ssl_private_key_failure;
348 }
349 }
350
David Benjaminb4d65fd2015-05-29 17:11:21 -0400351 // Write the signature into |test_state|.
352 size_t len = 0;
David Benjamin19670942017-05-31 19:07:31 -0400353 if (!EVP_DigestSign(ctx.get(), nullptr, &len, in, in_len)) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400354 return ssl_private_key_failure;
355 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700356 test_state->private_key_result.resize(len);
David Benjamin19670942017-05-31 19:07:31 -0400357 if (!EVP_DigestSign(ctx.get(), test_state->private_key_result.data(), &len,
358 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 Benjaminb4d65fd2015-05-29 17:11:21 -0400362
David Benjamind3440b42016-07-14 14:52:41 -0400363 // The signature will be released asynchronously in |AsyncPrivateKeyComplete|.
David Benjaminb4d65fd2015-05-29 17:11:21 -0400364 return ssl_private_key_retry;
365}
366
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700367static ssl_private_key_result_t AsyncPrivateKeyDecrypt(
368 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
369 const uint8_t *in, size_t in_len) {
370 TestState *test_state = GetTestState(ssl);
371 if (!test_state->private_key_result.empty()) {
372 fprintf(stderr,
373 "AsyncPrivateKeyDecrypt called with operation pending.\n");
374 abort();
375 }
376
David Benjamin758d1272015-11-20 17:47:25 -0500377 RSA *rsa = EVP_PKEY_get0_RSA(test_state->private_key.get());
378 if (rsa == NULL) {
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700379 fprintf(stderr,
380 "AsyncPrivateKeyDecrypt called with incorrect key type.\n");
381 abort();
382 }
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700383 test_state->private_key_result.resize(RSA_size(rsa));
David Benjaminef14b2d2015-11-11 14:01:27 -0800384 if (!RSA_decrypt(rsa, out_len, test_state->private_key_result.data(),
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700385 RSA_size(rsa), in, in_len, RSA_NO_PADDING)) {
386 return ssl_private_key_failure;
387 }
388
389 test_state->private_key_result.resize(*out_len);
390
David Benjamind3440b42016-07-14 14:52:41 -0400391 // The decryption will be released asynchronously in |AsyncPrivateComplete|.
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700392 return ssl_private_key_retry;
393}
394
David Benjamind3440b42016-07-14 14:52:41 -0400395static ssl_private_key_result_t AsyncPrivateKeyComplete(
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700396 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
397 TestState *test_state = GetTestState(ssl);
398 if (test_state->private_key_result.empty()) {
399 fprintf(stderr,
David Benjamind3440b42016-07-14 14:52:41 -0400400 "AsyncPrivateKeyComplete called without operation pending.\n");
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700401 abort();
402 }
403
404 if (test_state->private_key_retries < 2) {
405 // Only return the decryption on the second attempt, to test both incomplete
406 // |decrypt| and |decrypt_complete|.
407 return ssl_private_key_retry;
408 }
409
410 if (max_out < test_state->private_key_result.size()) {
411 fprintf(stderr, "Output buffer too small.\n");
412 return ssl_private_key_failure;
413 }
David Benjamin17cf2cb2016-12-13 01:07:13 -0500414 OPENSSL_memcpy(out, test_state->private_key_result.data(),
415 test_state->private_key_result.size());
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700416 *out_len = test_state->private_key_result.size();
417
418 test_state->private_key_result.clear();
419 test_state->private_key_retries = 0;
David Benjaminb4d65fd2015-05-29 17:11:21 -0400420 return ssl_private_key_success;
421}
422
423static const SSL_PRIVATE_KEY_METHOD g_async_private_key_method = {
David Benjamina232a712017-03-30 15:51:53 -0500424 nullptr /* type */,
425 nullptr /* max_signature_len */,
David Benjaminb4d65fd2015-05-29 17:11:21 -0400426 AsyncPrivateKeySign,
David Benjamind3440b42016-07-14 14:52:41 -0400427 nullptr /* sign_digest */,
nagendra modadugu3398dbf2015-08-07 14:07:52 -0700428 AsyncPrivateKeyDecrypt,
David Benjamind3440b42016-07-14 14:52:41 -0400429 AsyncPrivateKeyComplete,
David Benjaminb4d65fd2015-05-29 17:11:21 -0400430};
431
Steven Valdez0d62f262015-09-04 12:41:04 -0400432template<typename T>
Adam Langley10f97f32016-07-12 08:09:33 -0700433struct Free {
Steven Valdez0d62f262015-09-04 12:41:04 -0400434 void operator()(T *buf) {
435 free(buf);
436 }
437};
438
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700439static bool GetCertificate(SSL *ssl, bssl::UniquePtr<X509> *out_x509,
David Benjamin2c516452016-11-15 10:16:54 +0900440 bssl::UniquePtr<STACK_OF(X509)> *out_chain,
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700441 bssl::UniquePtr<EVP_PKEY> *out_pkey) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400442 const TestConfig *config = GetTestConfig(ssl);
Steven Valdez0d62f262015-09-04 12:41:04 -0400443
444 if (!config->digest_prefs.empty()) {
David Benjamin8ba6a142017-05-05 20:49:53 -0400445 bssl::UniquePtr<char> digest_prefs(
446 OPENSSL_strdup(config->digest_prefs.c_str()));
Steven Valdez0d62f262015-09-04 12:41:04 -0400447 std::vector<int> digest_list;
448
449 for (;;) {
Adam Langley67251f22015-09-23 15:01:07 -0700450 char *token =
451 strtok(digest_list.empty() ? digest_prefs.get() : nullptr, ",");
Steven Valdez0d62f262015-09-04 12:41:04 -0400452 if (token == nullptr) {
453 break;
454 }
455
456 digest_list.push_back(EVP_MD_type(EVP_get_digestbyname(token)));
457 }
458
459 if (!SSL_set_private_key_digest_prefs(ssl, digest_list.data(),
460 digest_list.size())) {
461 return false;
462 }
463 }
464
David Benjaminca3d5452016-07-14 12:51:01 -0400465 if (!config->signing_prefs.empty()) {
466 std::vector<uint16_t> u16s(config->signing_prefs.begin(),
467 config->signing_prefs.end());
468 if (!SSL_set_signing_algorithm_prefs(ssl, u16s.data(), u16s.size())) {
469 return false;
470 }
471 }
472
David Benjaminb4d65fd2015-05-29 17:11:21 -0400473 if (!config->key_file.empty()) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500474 *out_pkey = LoadPrivateKey(config->key_file.c_str());
475 if (!*out_pkey) {
David Benjaminb4d65fd2015-05-29 17:11:21 -0400476 return false;
477 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500478 }
David Benjamin2c516452016-11-15 10:16:54 +0900479 if (!config->cert_file.empty() &&
480 !LoadCertificate(out_x509, out_chain, config->cert_file.c_str())) {
481 return false;
David Benjamin41fdbcd2015-02-09 03:13:35 -0500482 }
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100483 if (!config->ocsp_response.empty() &&
Alessandro Ghedini559f0642016-12-07 12:55:32 +0000484 !SSL_set_ocsp_response(ssl, (const uint8_t *)config->ocsp_response.data(),
485 config->ocsp_response.size())) {
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100486 return false;
487 }
David Benjamin41fdbcd2015-02-09 03:13:35 -0500488 return true;
489}
490
David Benjaminacb6dcc2016-03-10 09:15:01 -0500491static bool InstallCertificate(SSL *ssl) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700492 bssl::UniquePtr<X509> x509;
David Benjamin2c516452016-11-15 10:16:54 +0900493 bssl::UniquePtr<STACK_OF(X509)> chain;
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700494 bssl::UniquePtr<EVP_PKEY> pkey;
David Benjamin2c516452016-11-15 10:16:54 +0900495 if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500496 return false;
497 }
498
499 if (pkey) {
500 TestState *test_state = GetTestState(ssl);
David Benjamin7e7a82d2016-05-20 20:12:42 -0400501 const TestConfig *config = GetTestConfig(ssl);
David Benjaminacb6dcc2016-03-10 09:15:01 -0500502 if (config->async) {
503 test_state->private_key = std::move(pkey);
504 SSL_set_private_key_method(ssl, &g_async_private_key_method);
505 } else if (!SSL_use_PrivateKey(ssl, pkey.get())) {
506 return false;
507 }
508 }
509
510 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
511 return false;
512 }
513
David Benjamin2c516452016-11-15 10:16:54 +0900514 if (sk_X509_num(chain.get()) > 0 &&
515 !SSL_set1_chain(ssl, chain.get())) {
516 return false;
517 }
518
David Benjaminacb6dcc2016-03-10 09:15:01 -0500519 return true;
520}
521
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000522static enum ssl_select_cert_result_t SelectCertificateCallback(
523 const SSL_CLIENT_HELLO *client_hello) {
David Benjamin731058e2016-12-03 23:15:13 -0500524 const TestConfig *config = GetTestConfig(client_hello->ssl);
525 GetTestState(client_hello->ssl)->early_callback_called = true;
David Benjamin5a593af2014-08-11 19:51:50 -0400526
David Benjamin6f5c0f42015-02-24 01:23:21 -0500527 if (!config->expected_server_name.empty()) {
528 const uint8_t *extension_data;
529 size_t extension_len;
530 CBS extension, server_name_list, host_name;
531 uint8_t name_type;
532
David Benjamin731058e2016-12-03 23:15:13 -0500533 if (!SSL_early_callback_ctx_extension_get(
534 client_hello, TLSEXT_TYPE_server_name, &extension_data,
535 &extension_len)) {
David Benjamin6f5c0f42015-02-24 01:23:21 -0500536 fprintf(stderr, "Could not find server_name extension.\n");
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000537 return ssl_select_cert_error;
David Benjamin6f5c0f42015-02-24 01:23:21 -0500538 }
539
540 CBS_init(&extension, extension_data, extension_len);
541 if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
542 CBS_len(&extension) != 0 ||
543 !CBS_get_u8(&server_name_list, &name_type) ||
544 name_type != TLSEXT_NAMETYPE_host_name ||
545 !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
546 CBS_len(&server_name_list) != 0) {
547 fprintf(stderr, "Could not decode server_name extension.\n");
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000548 return ssl_select_cert_error;
David Benjamin6f5c0f42015-02-24 01:23:21 -0500549 }
550
551 if (!CBS_mem_equal(&host_name,
552 (const uint8_t*)config->expected_server_name.data(),
553 config->expected_server_name.size())) {
554 fprintf(stderr, "Server name mismatch.\n");
555 }
David Benjamin7b030512014-07-08 17:30:11 -0400556 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400557
David Benjamin6f5c0f42015-02-24 01:23:21 -0500558 if (config->fail_early_callback) {
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000559 return ssl_select_cert_error;
David Benjamin7b030512014-07-08 17:30:11 -0400560 }
David Benjamin8f2c20e2014-07-09 09:30:38 -0400561
David Benjamin6f5c0f42015-02-24 01:23:21 -0500562 // Install the certificate in the early callback.
563 if (config->use_early_callback) {
Alessandro Ghedini958346a2016-12-20 19:42:15 +0000564 bool early_callback_ready =
565 GetTestState(client_hello->ssl)->early_callback_ready;
566 if (config->async && !early_callback_ready) {
David Benjamin6f5c0f42015-02-24 01:23:21 -0500567 // Install the certificate asynchronously.
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000568 return ssl_select_cert_retry;
David Benjamin6f5c0f42015-02-24 01:23:21 -0500569 }
David Benjamin731058e2016-12-03 23:15:13 -0500570 if (!InstallCertificate(client_hello->ssl)) {
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000571 return ssl_select_cert_error;
David Benjamin6f5c0f42015-02-24 01:23:21 -0500572 }
David Benjamin7b030512014-07-08 17:30:11 -0400573 }
Alessandro Ghedini57e81e62017-03-14 23:36:00 +0000574 return ssl_select_cert_success;
David Benjamin8f2c20e2014-07-09 09:30:38 -0400575}
David Benjamin025b3d32014-07-01 19:53:04 -0400576
David Benjamin5edfc8c2016-12-10 15:46:58 -0500577static bool CheckCertificateRequest(SSL *ssl) {
578 const TestConfig *config = GetTestConfig(ssl);
579
580 if (!config->expected_certificate_types.empty()) {
581 const uint8_t *certificate_types;
582 size_t certificate_types_len =
583 SSL_get0_certificate_types(ssl, &certificate_types);
584 if (certificate_types_len != config->expected_certificate_types.size() ||
David Benjamin17cf2cb2016-12-13 01:07:13 -0500585 OPENSSL_memcmp(certificate_types,
586 config->expected_certificate_types.data(),
587 certificate_types_len) != 0) {
David Benjamin5edfc8c2016-12-10 15:46:58 -0500588 fprintf(stderr, "certificate types mismatch\n");
589 return false;
590 }
591 }
592
Adam Langley2ff79332017-02-28 13:45:39 -0800593 if (!config->expected_client_ca_list.empty()) {
594 bssl::UniquePtr<STACK_OF(X509_NAME)> expected =
595 DecodeHexX509Names(config->expected_client_ca_list);
596 const size_t num_expected = sk_X509_NAME_num(expected.get());
597
598 const STACK_OF(X509_NAME) *received = SSL_get_client_CA_list(ssl);
599 const size_t num_received = sk_X509_NAME_num(received);
600
601 if (num_received != num_expected) {
602 fprintf(stderr, "expected %u names in CertificateRequest but got %u\n",
603 static_cast<unsigned>(num_expected),
604 static_cast<unsigned>(num_received));
605 return false;
606 }
607
608 for (size_t i = 0; i < num_received; i++) {
609 if (X509_NAME_cmp(sk_X509_NAME_value(received, i),
610 sk_X509_NAME_value(expected.get(), i)) != 0) {
611 fprintf(stderr, "names in CertificateRequest differ at index #%d\n",
612 static_cast<unsigned>(i));
613 return false;
614 }
615 }
Adam Langleyd6c22ee2017-03-02 12:56:32 -0800616
617 STACK_OF(CRYPTO_BUFFER) *buffers = SSL_get0_server_requested_CAs(ssl);
618 if (sk_CRYPTO_BUFFER_num(buffers) != num_received) {
619 fprintf(stderr,
620 "Mismatch between SSL_get_server_requested_CAs and "
621 "SSL_get_client_CA_list.\n");
622 return false;
623 }
Adam Langley2ff79332017-02-28 13:45:39 -0800624 }
625
David Benjamin5edfc8c2016-12-10 15:46:58 -0500626 return true;
627}
628
David Benjaminacb6dcc2016-03-10 09:15:01 -0500629static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
David Benjamin5edfc8c2016-12-10 15:46:58 -0500630 if (!CheckCertificateRequest(ssl)) {
631 return -1;
632 }
633
David Benjamin7e7a82d2016-05-20 20:12:42 -0400634 if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500635 return -1;
636 }
637
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700638 bssl::UniquePtr<X509> x509;
David Benjamin2c516452016-11-15 10:16:54 +0900639 bssl::UniquePtr<STACK_OF(X509)> chain;
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700640 bssl::UniquePtr<EVP_PKEY> pkey;
David Benjamin2c516452016-11-15 10:16:54 +0900641 if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
David Benjaminacb6dcc2016-03-10 09:15:01 -0500642 return -1;
643 }
644
645 // Return zero for no certificate.
646 if (!x509) {
647 return 0;
648 }
649
David Benjamin2c516452016-11-15 10:16:54 +0900650 // Chains and asynchronous private keys are not supported with client_cert_cb.
David Benjaminacb6dcc2016-03-10 09:15:01 -0500651 *out_x509 = x509.release();
652 *out_pkey = pkey.release();
653 return 1;
654}
655
David Benjamin5edfc8c2016-12-10 15:46:58 -0500656static int CertCallback(SSL *ssl, void *arg) {
657 const TestConfig *config = GetTestConfig(ssl);
658
659 // Check the CertificateRequest metadata is as expected.
660 if (!SSL_is_server(ssl) && !CheckCertificateRequest(ssl)) {
661 return -1;
662 }
663
664 if (config->fail_cert_callback) {
665 return 0;
666 }
667
668 // The certificate will be installed via other means.
669 if (!config->async || config->use_early_callback) {
670 return 1;
671 }
672
673 if (!GetTestState(ssl)->cert_ready) {
674 return -1;
675 }
676 if (!InstallCertificate(ssl)) {
677 return 0;
678 }
679 return 1;
680}
681
Paul Lietar8f1c2682015-08-18 12:21:54 +0100682static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
683 SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data(store_ctx,
684 SSL_get_ex_data_X509_STORE_CTX_idx());
David Benjamin7e7a82d2016-05-20 20:12:42 -0400685 const TestConfig *config = GetTestConfig(ssl);
Paul Lietar8f1c2682015-08-18 12:21:54 +0100686
687 if (!config->expected_ocsp_response.empty()) {
688 const uint8_t *data;
689 size_t len;
690 SSL_get0_ocsp_response(ssl, &data, &len);
691 if (len == 0) {
692 fprintf(stderr, "OCSP response not available in verify callback\n");
693 return 0;
694 }
695 }
696
David Benjamin67666e72014-07-12 15:47:52 -0400697 return 1;
698}
699
Paul Lietar8f1c2682015-08-18 12:21:54 +0100700static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
701 store_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION;
702 return 0;
703}
704
David Benjaminc273d2c2015-02-09 12:59:46 -0500705static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
706 unsigned int *out_len, void *arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400707 const TestConfig *config = GetTestConfig(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500708 if (config->advertise_npn.empty()) {
David Benjamin1f5f62b2014-07-12 16:18:02 -0400709 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500710 }
David Benjamin1f5f62b2014-07-12 16:18:02 -0400711
David Benjamin5a593af2014-08-11 19:51:50 -0400712 *out = (const uint8_t*)config->advertise_npn.data();
713 *out_len = config->advertise_npn.size();
David Benjamin1f5f62b2014-07-12 16:18:02 -0400714 return SSL_TLSEXT_ERR_OK;
715}
716
David Benjaminc273d2c2015-02-09 12:59:46 -0500717static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
David Benjamin8b368412015-03-14 01:54:17 -0400718 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400719 const TestConfig *config = GetTestConfig(ssl);
David Benjaminc273d2c2015-02-09 12:59:46 -0500720 if (config->select_next_proto.empty()) {
David Benjamin7e3305e2014-07-28 14:52:32 -0400721 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500722 }
David Benjamin7e3305e2014-07-28 14:52:32 -0400723
David Benjamin5a593af2014-08-11 19:51:50 -0400724 *out = (uint8_t*)config->select_next_proto.data();
725 *outlen = config->select_next_proto.size();
David Benjamin7e3305e2014-07-28 14:52:32 -0400726 return SSL_TLSEXT_ERR_OK;
727}
728
David Benjaminc273d2c2015-02-09 12:59:46 -0500729static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
730 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamin25fe85b2016-08-09 20:00:32 -0400731 if (GetTestState(ssl)->alpn_select_done) {
732 fprintf(stderr, "AlpnSelectCallback called after completion.\n");
733 exit(1);
734 }
735
736 GetTestState(ssl)->alpn_select_done = true;
737
David Benjamin7e7a82d2016-05-20 20:12:42 -0400738 const TestConfig *config = GetTestConfig(ssl);
David Benjamin594e7d22016-03-17 17:49:56 -0400739 if (config->decline_alpn) {
David Benjaminae2888f2014-09-06 12:58:58 -0400740 return SSL_TLSEXT_ERR_NOACK;
David Benjaminc273d2c2015-02-09 12:59:46 -0500741 }
David Benjaminae2888f2014-09-06 12:58:58 -0400742
743 if (!config->expected_advertised_alpn.empty() &&
744 (config->expected_advertised_alpn.size() != inlen ||
David Benjamin17cf2cb2016-12-13 01:07:13 -0500745 OPENSSL_memcmp(config->expected_advertised_alpn.data(), in, inlen) !=
746 0)) {
David Benjaminae2888f2014-09-06 12:58:58 -0400747 fprintf(stderr, "bad ALPN select callback inputs\n");
748 exit(1);
749 }
750
751 *out = (const uint8_t*)config->select_alpn.data();
752 *outlen = config->select_alpn.size();
753 return SSL_TLSEXT_ERR_OK;
754}
755
David Benjaminc273d2c2015-02-09 12:59:46 -0500756static unsigned PskClientCallback(SSL *ssl, const char *hint,
757 char *out_identity,
758 unsigned max_identity_len,
759 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400760 const TestConfig *config = GetTestConfig(ssl);
David Benjamin48cae082014-10-27 01:06:24 -0400761
David Benjamin78679342016-09-16 19:42:05 -0400762 if (config->psk_identity.empty()) {
763 if (hint != nullptr) {
764 fprintf(stderr, "Server PSK hint was non-null.\n");
765 return 0;
766 }
767 } else if (hint == nullptr ||
768 strcmp(hint, config->psk_identity.c_str()) != 0) {
David Benjamin48cae082014-10-27 01:06:24 -0400769 fprintf(stderr, "Server PSK hint did not match.\n");
770 return 0;
771 }
772
773 // Account for the trailing '\0' for the identity.
774 if (config->psk_identity.size() >= max_identity_len ||
775 config->psk.size() > max_psk_len) {
776 fprintf(stderr, "PSK buffers too small\n");
777 return 0;
778 }
779
780 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
781 max_identity_len);
David Benjamin17cf2cb2016-12-13 01:07:13 -0500782 OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size());
David Benjamin48cae082014-10-27 01:06:24 -0400783 return config->psk.size();
784}
785
David Benjaminc273d2c2015-02-09 12:59:46 -0500786static unsigned PskServerCallback(SSL *ssl, const char *identity,
787 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400788 const TestConfig *config = GetTestConfig(ssl);
David Benjamin48cae082014-10-27 01:06:24 -0400789
790 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
791 fprintf(stderr, "Client PSK identity did not match.\n");
792 return 0;
793 }
794
795 if (config->psk.size() > max_psk_len) {
796 fprintf(stderr, "PSK buffers too small\n");
797 return 0;
798 }
799
David Benjamin17cf2cb2016-12-13 01:07:13 -0500800 OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size());
David Benjamin48cae082014-10-27 01:06:24 -0400801 return config->psk.size();
802}
803
David Benjamin1b22f852016-10-27 16:36:32 -0400804static timeval g_clock;
805
David Benjamin4d2e7ce2015-05-08 13:29:45 -0400806static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
David Benjamin1b22f852016-10-27 16:36:32 -0400807 *out_clock = g_clock;
David Benjamin377fc312015-01-26 00:22:12 -0500808}
809
David Benjaminc273d2c2015-02-09 12:59:46 -0500810static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
David Benjamin2d445c02015-02-09 13:03:50 -0500811 *out_pkey = GetTestState(ssl)->channel_id.release();
David Benjamind9e07012015-02-09 03:04:34 -0500812}
813
David Benjaminc273d2c2015-02-09 12:59:46 -0500814static SSL_SESSION *GetSessionCallback(SSL *ssl, uint8_t *data, int len,
815 int *copy) {
David Benjamin2d445c02015-02-09 13:03:50 -0500816 TestState *async_state = GetTestState(ssl);
David Benjamin1b8b6912015-02-09 04:28:16 -0500817 if (async_state->session) {
818 *copy = 0;
819 return async_state->session.release();
820 } else if (async_state->pending_session) {
821 return SSL_magic_pending_session_ptr();
822 } else {
823 return NULL;
824 }
825}
826
David Benjamin731058e2016-12-03 23:15:13 -0500827static int DDoSCallback(const SSL_CLIENT_HELLO *client_hello) {
828 const TestConfig *config = GetTestConfig(client_hello->ssl);
Adam Langley524e7172015-02-20 16:04:00 -0800829 static int callback_num = 0;
830
831 callback_num++;
832 if (config->fail_ddos_callback ||
833 (config->fail_second_ddos_callback && callback_num == 2)) {
834 return 0;
835 }
836 return 1;
837}
838
David Benjamin87e4acd2015-04-02 19:57:35 -0400839static void InfoCallback(const SSL *ssl, int type, int val) {
840 if (type == SSL_CB_HANDSHAKE_DONE) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400841 if (GetTestConfig(ssl)->handshake_never_done) {
David Benjamin7a4aaa42016-09-20 17:58:14 -0400842 fprintf(stderr, "Handshake unexpectedly completed.\n");
David Benjamin87e4acd2015-04-02 19:57:35 -0400843 // Abort before any expected error code is printed, to ensure the overall
844 // test fails.
845 abort();
846 }
847 GetTestState(ssl)->handshake_done = true;
David Benjamin25fe85b2016-08-09 20:00:32 -0400848
849 // Callbacks may be called again on a new handshake.
850 GetTestState(ssl)->ticket_decrypt_done = false;
851 GetTestState(ssl)->alpn_select_done = false;
David Benjamin87e4acd2015-04-02 19:57:35 -0400852 }
853}
854
David Benjaminba4594a2015-06-18 18:36:15 -0400855static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
856 GetTestState(ssl)->got_new_session = true;
Steven Valdez4aa154e2016-07-29 14:32:55 -0400857 GetTestState(ssl)->new_session.reset(session);
David Benjaminba4594a2015-06-18 18:36:15 -0400858 return 1;
859}
860
David Benjamind98452d2015-06-16 14:16:23 -0400861static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
862 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
863 int encrypt) {
David Benjamin25fe85b2016-08-09 20:00:32 -0400864 if (!encrypt) {
865 if (GetTestState(ssl)->ticket_decrypt_done) {
866 fprintf(stderr, "TicketKeyCallback called after completion.\n");
867 return -1;
868 }
869
870 GetTestState(ssl)->ticket_decrypt_done = true;
871 }
872
David Benjamind98452d2015-06-16 14:16:23 -0400873 // This is just test code, so use the all-zeros key.
874 static const uint8_t kZeros[16] = {0};
875
876 if (encrypt) {
David Benjamin17cf2cb2016-12-13 01:07:13 -0500877 OPENSSL_memcpy(key_name, kZeros, sizeof(kZeros));
David Benjamind98452d2015-06-16 14:16:23 -0400878 RAND_bytes(iv, 16);
David Benjamin17cf2cb2016-12-13 01:07:13 -0500879 } else if (OPENSSL_memcmp(key_name, kZeros, 16) != 0) {
David Benjamind98452d2015-06-16 14:16:23 -0400880 return 0;
881 }
882
883 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
884 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
885 return -1;
886 }
887
888 if (!encrypt) {
David Benjamin7e7a82d2016-05-20 20:12:42 -0400889 return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
David Benjamind98452d2015-06-16 14:16:23 -0400890 }
891 return 1;
892}
893
Adam Langley09505632015-07-30 18:10:13 -0700894// kCustomExtensionValue is the extension value that the custom extension
895// callbacks will add.
Adam Langleyc5b23a12015-07-30 18:19:26 -0700896static const uint16_t kCustomExtensionValue = 1234;
Adam Langley09505632015-07-30 18:10:13 -0700897static void *const kCustomExtensionAddArg =
898 reinterpret_cast<void *>(kCustomExtensionValue);
899static void *const kCustomExtensionParseArg =
900 reinterpret_cast<void *>(kCustomExtensionValue + 1);
901static const char kCustomExtensionContents[] = "custom extension";
902
903static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
904 const uint8_t **out, size_t *out_len,
905 int *out_alert_value, void *add_arg) {
906 if (extension_value != kCustomExtensionValue ||
907 add_arg != kCustomExtensionAddArg) {
908 abort();
909 }
910
David Benjamin7e7a82d2016-05-20 20:12:42 -0400911 if (GetTestConfig(ssl)->custom_extension_skip) {
Adam Langley09505632015-07-30 18:10:13 -0700912 return 0;
913 }
David Benjamin7e7a82d2016-05-20 20:12:42 -0400914 if (GetTestConfig(ssl)->custom_extension_fail_add) {
Adam Langley09505632015-07-30 18:10:13 -0700915 return -1;
916 }
917
918 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
919 *out_len = sizeof(kCustomExtensionContents) - 1;
920
921 return 1;
922}
923
924static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
925 const uint8_t *out, void *add_arg) {
926 if (extension_value != kCustomExtensionValue ||
927 add_arg != kCustomExtensionAddArg ||
928 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
929 abort();
930 }
931}
932
933static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
934 const uint8_t *contents,
935 size_t contents_len,
936 int *out_alert_value, void *parse_arg) {
937 if (extension_value != kCustomExtensionValue ||
938 parse_arg != kCustomExtensionParseArg) {
939 abort();
940 }
941
942 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
David Benjamin17cf2cb2016-12-13 01:07:13 -0500943 OPENSSL_memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
Adam Langley09505632015-07-30 18:10:13 -0700944 *out_alert_value = SSL_AD_DECODE_ERROR;
945 return 0;
946 }
947
948 return 1;
949}
950
David Benjamin8b176712016-10-27 21:51:24 -0400951static int ServerNameCallback(SSL *ssl, int *out_alert, void *arg) {
952 // SNI must be accessible from the SNI callback.
953 const TestConfig *config = GetTestConfig(ssl);
954 const char *server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
955 if (server_name == nullptr ||
956 std::string(server_name) != config->expected_server_name) {
957 fprintf(stderr, "servername mismatch (got %s; want %s)\n", server_name,
958 config->expected_server_name.c_str());
959 return SSL_TLSEXT_ERR_ALERT_FATAL;
960 }
961
962 return SSL_TLSEXT_ERR_OK;
963}
964
David Benjamin87c8a642015-02-21 01:54:29 -0500965// Connect returns a new socket connected to localhost on |port| or -1 on
966// error.
967static int Connect(uint16_t port) {
Matthew Braithwaite2d04cf02017-05-19 18:13:25 -0700968 for (int af : { AF_INET6, AF_INET }) {
969 int sock = socket(af, SOCK_STREAM, 0);
970 if (sock == -1) {
971 PrintSocketError("socket");
972 return -1;
973 }
974 int nodelay = 1;
975 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
976 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
977 PrintSocketError("setsockopt");
978 closesocket(sock);
979 return -1;
980 }
981
982 sockaddr_storage ss;
983 OPENSSL_memset(&ss, 0, sizeof(ss));
984 ss.ss_family = af;
985 socklen_t len = 0;
986
987 if (af == AF_INET6) {
988 sockaddr_in6 *sin6 = (sockaddr_in6 *) &ss;
989 len = sizeof(*sin6);
990 sin6->sin6_port = htons(port);
991 if (!inet_pton(AF_INET6, "::1", &sin6->sin6_addr)) {
992 PrintSocketError("inet_pton");
993 closesocket(sock);
994 return -1;
995 }
996 } else if (af == AF_INET) {
997 sockaddr_in *sin = (sockaddr_in *) &ss;
998 len = sizeof(*sin);
999 sin->sin_port = htons(port);
1000 if (!inet_pton(AF_INET, "127.0.0.1", &sin->sin_addr)) {
1001 PrintSocketError("inet_pton");
1002 closesocket(sock);
1003 return -1;
1004 }
1005 }
1006
1007 if (connect(sock, reinterpret_cast<const sockaddr*>(&ss), len) == 0) {
1008 return sock;
1009 }
David Benjamin87c8a642015-02-21 01:54:29 -05001010 closesocket(sock);
David Benjamin87c8a642015-02-21 01:54:29 -05001011 }
Matthew Braithwaite2d04cf02017-05-19 18:13:25 -07001012 return -1;
David Benjamin87c8a642015-02-21 01:54:29 -05001013}
1014
1015class SocketCloser {
1016 public:
1017 explicit SocketCloser(int sock) : sock_(sock) {}
1018 ~SocketCloser() {
1019 // Half-close and drain the socket before releasing it. This seems to be
1020 // necessary for graceful shutdown on Windows. It will also avoid write
1021 // failures in the test runner.
1022#if defined(OPENSSL_WINDOWS)
1023 shutdown(sock_, SD_SEND);
1024#else
1025 shutdown(sock_, SHUT_WR);
1026#endif
1027 while (true) {
1028 char buf[1024];
1029 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
1030 break;
1031 }
1032 }
1033 closesocket(sock_);
1034 }
1035
1036 private:
1037 const int sock_;
1038};
1039
Steven Valdez873ebc92017-05-09 12:12:58 -04001040static void ssl_ctx_add_session(SSL_SESSION *session, void *void_param) {
1041 SSL_SESSION *new_session = SSL_SESSION_dup(
1042 session, SSL_SESSION_INCLUDE_NONAUTH | SSL_SESSION_INCLUDE_TICKET);
1043 if (new_session != nullptr) {
1044 SSL_CTX_add_session((SSL_CTX *)void_param, new_session);
1045 }
1046 SSL_SESSION_free(new_session);
1047}
1048
1049static bssl::UniquePtr<SSL_CTX> SetupCtx(SSL_CTX *old_ctx,
1050 const TestConfig *config) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001051 bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(
David Benjamina7f333d2015-02-09 02:37:18 -05001052 config->is_dtls ? DTLS_method() : TLS_method()));
1053 if (!ssl_ctx) {
1054 return nullptr;
David Benjamin025b3d32014-07-01 19:53:04 -04001055 }
1056
Adam Langleyd519bf62016-12-12 11:16:44 -08001057 SSL_CTX_set0_buffer_pool(ssl_ctx.get(), g_pool);
1058
David Benjamin3cfeb952017-03-01 16:48:38 -05001059 // Enable SSL 3.0 and TLS 1.3 for tests.
David Benjamin2dc02042016-09-19 19:57:37 -04001060 if (!config->is_dtls &&
David Benjamin3cfeb952017-03-01 16:48:38 -05001061 (!SSL_CTX_set_min_proto_version(ssl_ctx.get(), SSL3_VERSION) ||
1062 !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION))) {
David Benjamin2dc02042016-09-19 19:57:37 -04001063 return nullptr;
Nick Harper1fd39d82016-06-14 18:14:35 -07001064 }
1065
Adam Langleycef75832015-09-03 14:51:12 -07001066 std::string cipher_list = "ALL";
1067 if (!config->cipher.empty()) {
1068 cipher_list = config->cipher;
1069 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
1070 }
Matthew Braithwaitea57dcfb2017-02-17 22:08:23 -08001071 if (!SSL_CTX_set_strict_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
Adam Langleycef75832015-09-03 14:51:12 -07001072 return nullptr;
1073 }
1074
David Benjamin1b8b6912015-02-09 04:28:16 -05001075 if (config->async && config->is_server) {
1076 // Disable the internal session cache. To test asynchronous session lookup,
1077 // we use an external session cache.
1078 SSL_CTX_set_session_cache_mode(
1079 ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
David Benjaminc273d2c2015-02-09 12:59:46 -05001080 SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
David Benjamin1b8b6912015-02-09 04:28:16 -05001081 } else {
1082 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
1083 }
David Benjamin1d5c83e2014-07-22 19:20:02 -04001084
David Benjamind4c2bce2015-10-17 12:28:18 -04001085 SSL_CTX_set_select_certificate_cb(ssl_ctx.get(), SelectCertificateCallback);
David Benjamin8f2c20e2014-07-09 09:30:38 -04001086
David Benjaminacb6dcc2016-03-10 09:15:01 -05001087 if (config->use_old_client_cert_callback) {
1088 SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
1089 }
1090
David Benjamin1f5f62b2014-07-12 16:18:02 -04001091 SSL_CTX_set_next_protos_advertised_cb(
David Benjaminc273d2c2015-02-09 12:59:46 -05001092 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -04001093 if (!config->select_next_proto.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001094 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
David Benjamina7f333d2015-02-09 02:37:18 -05001095 NULL);
David Benjaminae2888f2014-09-06 12:58:58 -04001096 }
1097
Steven Valdez873ebc92017-05-09 12:12:58 -04001098 if (!config->select_alpn.empty() || config->decline_alpn) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001099 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
David Benjaminae2888f2014-09-06 12:58:58 -04001100 }
David Benjamin1f5f62b2014-07-12 16:18:02 -04001101
David Benjaminc273d2c2015-02-09 12:59:46 -05001102 SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
David Benjamina08e49d2014-08-24 01:46:07 -04001103
David Benjamin1b22f852016-10-27 16:36:32 -04001104 SSL_CTX_set_current_time_cb(ssl_ctx.get(), CurrentTimeCallback);
David Benjamin377fc312015-01-26 00:22:12 -05001105
David Benjamin87e4acd2015-04-02 19:57:35 -04001106 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
David Benjaminba4594a2015-06-18 18:36:15 -04001107 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
David Benjamin87e4acd2015-04-02 19:57:35 -04001108
David Benjamind98452d2015-06-16 14:16:23 -04001109 if (config->use_ticket_callback) {
1110 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
1111 }
1112
Adam Langley09505632015-07-30 18:10:13 -07001113 if (config->enable_client_custom_extension &&
1114 !SSL_CTX_add_client_custom_ext(
1115 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
1116 CustomExtensionFreeCallback, kCustomExtensionAddArg,
1117 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1118 return nullptr;
1119 }
1120
1121 if (config->enable_server_custom_extension &&
1122 !SSL_CTX_add_server_custom_ext(
1123 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
1124 CustomExtensionFreeCallback, kCustomExtensionAddArg,
1125 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1126 return nullptr;
1127 }
1128
Paul Lietar8f1c2682015-08-18 12:21:54 +01001129 if (config->verify_fail) {
1130 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
1131 } else {
1132 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
1133 }
1134
Paul Lietar4fac72e2015-09-09 13:44:55 +01001135 if (!config->signed_cert_timestamps.empty() &&
1136 !SSL_CTX_set_signed_cert_timestamp_list(
1137 ssl_ctx.get(), (const uint8_t *)config->signed_cert_timestamps.data(),
1138 config->signed_cert_timestamps.size())) {
1139 return nullptr;
1140 }
1141
Adam Langley2ff79332017-02-28 13:45:39 -08001142 if (!config->use_client_ca_list.empty()) {
1143 if (config->use_client_ca_list == "<NULL>") {
1144 SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
1145 } else {
1146 bssl::UniquePtr<STACK_OF(X509_NAME)> names =
1147 DecodeHexX509Names(config->use_client_ca_list);
1148 SSL_CTX_set_client_CA_list(ssl_ctx.get(), names.release());
1149 }
David Benjamin2f8935d2016-07-13 19:47:39 -04001150 }
1151
David Benjamin65ac9972016-09-02 21:35:25 -04001152 if (config->enable_grease) {
1153 SSL_CTX_set_grease_enabled(ssl_ctx.get(), 1);
1154 }
1155
David Benjamin8b176712016-10-27 21:51:24 -04001156 if (!config->expected_server_name.empty()) {
1157 SSL_CTX_set_tlsext_servername_callback(ssl_ctx.get(), ServerNameCallback);
1158 }
1159
David Benjamin4199b0d2016-11-01 13:58:25 -04001160 if (!config->ticket_key.empty() &&
1161 !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), config->ticket_key.data(),
1162 config->ticket_key.size())) {
1163 return nullptr;
1164 }
1165
Steven Valdez08b65f42016-12-07 15:29:45 -05001166 if (config->enable_early_data) {
1167 SSL_CTX_set_early_data_enabled(ssl_ctx.get(), 1);
1168 }
1169
David Benjaminc8ff30c2017-04-04 13:52:36 -04001170 if (config->allow_unknown_alpn_protos) {
1171 SSL_CTX_set_allow_unknown_alpn_protos(ssl_ctx.get(), 1);
1172 }
1173
David Benjamin69522112017-03-28 15:38:29 -05001174 if (config->enable_ed25519) {
1175 SSL_CTX_set_ed25519_enabled(ssl_ctx.get(), 1);
1176 }
1177
David Benjamin71c21b42017-04-14 17:05:40 -04001178 if (!config->verify_prefs.empty()) {
1179 std::vector<uint16_t> u16s(config->verify_prefs.begin(),
1180 config->verify_prefs.end());
1181 if (!SSL_CTX_set_verify_algorithm_prefs(ssl_ctx.get(), u16s.data(),
1182 u16s.size())) {
1183 return nullptr;
1184 }
1185 }
1186
Steven Valdez873ebc92017-05-09 12:12:58 -04001187 if (old_ctx) {
1188 uint8_t keys[48];
1189 if (!SSL_CTX_get_tlsext_ticket_keys(old_ctx, &keys, sizeof(keys)) ||
1190 !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), keys, sizeof(keys))) {
1191 return nullptr;
1192 }
1193 lh_SSL_SESSION_doall_arg(old_ctx->sessions, ssl_ctx_add_session,
1194 ssl_ctx.get());
1195 }
1196
David Benjamin1d5c83e2014-07-22 19:20:02 -04001197 return ssl_ctx;
David Benjamin1d5c83e2014-07-22 19:20:02 -04001198}
1199
David Benjamin40f101b2015-02-20 11:23:42 -05001200// RetryAsync is called after a failed operation on |ssl| with return code
1201// |ret|. If the operation should be retried, it simulates one asynchronous
David Benjamin6c2563e2015-04-03 03:47:47 -04001202// event and returns true. Otherwise it returns false.
1203static bool RetryAsync(SSL *ssl, int ret) {
David Benjamin43ec06f2014-08-05 02:28:57 -04001204 // No error; don't retry.
1205 if (ret >= 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001206 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001207 }
David Benjamin83f90402015-01-27 01:09:43 -05001208
David Benjamin6c2563e2015-04-03 03:47:47 -04001209 TestState *test_state = GetTestState(ssl);
Matt Braithwaite6278e242016-06-14 08:18:22 -07001210 assert(GetTestConfig(ssl)->async);
David Benjamin83f90402015-01-27 01:09:43 -05001211
David Benjamin585d7a42016-06-02 14:58:00 -04001212 if (test_state->packeted_bio != nullptr &&
1213 PacketedBioAdvanceClock(test_state->packeted_bio)) {
David Benjamin13e81fc2015-11-02 17:16:13 -05001214 // The DTLS retransmit logic silently ignores write failures. So the test
1215 // may progress, allow writes through synchronously.
David Benjamin585d7a42016-06-02 14:58:00 -04001216 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
David Benjamin13e81fc2015-11-02 17:16:13 -05001217 int timeout_ret = DTLSv1_handle_timeout(ssl);
David Benjamin585d7a42016-06-02 14:58:00 -04001218 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
David Benjamin13e81fc2015-11-02 17:16:13 -05001219
1220 if (timeout_ret < 0) {
David Benjaminc565ebb2015-04-03 04:06:36 -04001221 fprintf(stderr, "Error retransmitting.\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001222 return false;
David Benjamin83f90402015-01-27 01:09:43 -05001223 }
David Benjamin40f101b2015-02-20 11:23:42 -05001224 return true;
David Benjamin83f90402015-01-27 01:09:43 -05001225 }
1226
David Benjamin43ec06f2014-08-05 02:28:57 -04001227 // See if we needed to read or write more. If so, allow one byte through on
1228 // the appropriate end to maximally stress the state machine.
David Benjamind9e07012015-02-09 03:04:34 -05001229 switch (SSL_get_error(ssl, ret)) {
1230 case SSL_ERROR_WANT_READ:
David Benjamin6c2563e2015-04-03 03:47:47 -04001231 AsyncBioAllowRead(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -05001232 return true;
David Benjamind9e07012015-02-09 03:04:34 -05001233 case SSL_ERROR_WANT_WRITE:
David Benjamin6c2563e2015-04-03 03:47:47 -04001234 AsyncBioAllowWrite(test_state->async_bio, 1);
David Benjamin40f101b2015-02-20 11:23:42 -05001235 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -05001236 case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001237 bssl::UniquePtr<EVP_PKEY> pkey =
1238 LoadPrivateKey(GetTestConfig(ssl)->send_channel_id);
David Benjamin9d0847a2015-02-16 03:57:55 -05001239 if (!pkey) {
David Benjamin40f101b2015-02-20 11:23:42 -05001240 return false;
David Benjamin9d0847a2015-02-16 03:57:55 -05001241 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001242 test_state->channel_id = std::move(pkey);
David Benjamin40f101b2015-02-20 11:23:42 -05001243 return true;
David Benjamin9d0847a2015-02-16 03:57:55 -05001244 }
David Benjamin41fdbcd2015-02-09 03:13:35 -05001245 case SSL_ERROR_WANT_X509_LOOKUP:
David Benjamin6c2563e2015-04-03 03:47:47 -04001246 test_state->cert_ready = true;
David Benjamin40f101b2015-02-20 11:23:42 -05001247 return true;
David Benjamin1b8b6912015-02-09 04:28:16 -05001248 case SSL_ERROR_PENDING_SESSION:
David Benjamin6c2563e2015-04-03 03:47:47 -04001249 test_state->session = std::move(test_state->pending_session);
David Benjamin40f101b2015-02-20 11:23:42 -05001250 return true;
David Benjamin6f5c0f42015-02-24 01:23:21 -05001251 case SSL_ERROR_PENDING_CERTIFICATE:
Alessandro Ghedini958346a2016-12-20 19:42:15 +00001252 test_state->early_callback_ready = true;
1253 return true;
David Benjaminb4d65fd2015-05-29 17:11:21 -04001254 case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
nagendra modadugu3398dbf2015-08-07 14:07:52 -07001255 test_state->private_key_retries++;
David Benjaminb4d65fd2015-05-29 17:11:21 -04001256 return true;
David Benjamind9e07012015-02-09 03:04:34 -05001257 default:
David Benjamin40f101b2015-02-20 11:23:42 -05001258 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001259 }
David Benjamin025b3d32014-07-01 19:53:04 -04001260}
1261
David Benjamin6c2563e2015-04-03 03:47:47 -04001262// DoRead reads from |ssl|, resolving any asynchronous operations. It returns
1263// the result value of the final |SSL_read| call.
1264static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
David Benjamin7e7a82d2016-05-20 20:12:42 -04001265 const TestConfig *config = GetTestConfig(ssl);
David Benjamin13e81fc2015-11-02 17:16:13 -05001266 TestState *test_state = GetTestState(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -04001267 int ret;
1268 do {
David Benjamin13e81fc2015-11-02 17:16:13 -05001269 if (config->async) {
1270 // The DTLS retransmit logic silently ignores write failures. So the test
1271 // may progress, allow writes through synchronously. |SSL_read| may
1272 // trigger a retransmit, so disconnect the write quota.
1273 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
1274 }
David Benjaminf3fbade2016-09-19 13:08:16 -04001275 ret = config->peek_then_read ? SSL_peek(ssl, out, max_out)
1276 : SSL_read(ssl, out, max_out);
David Benjamin13e81fc2015-11-02 17:16:13 -05001277 if (config->async) {
1278 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
1279 }
David Benjamin7bb1d292016-11-01 19:45:06 -04001280
1281 // Run the exporter after each read. This is to test that the exporter fails
1282 // during a renegotiation.
1283 if (config->use_exporter_between_reads) {
1284 uint8_t buf;
1285 if (!SSL_export_keying_material(ssl, &buf, 1, NULL, 0, NULL, 0, 0)) {
1286 fprintf(stderr, "failed to export keying material\n");
1287 return -1;
1288 }
1289 }
David Benjamin6c2563e2015-04-03 03:47:47 -04001290 } while (config->async && RetryAsync(ssl, ret));
David Benjaminf3fbade2016-09-19 13:08:16 -04001291
1292 if (config->peek_then_read && ret > 0) {
1293 std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
1294
1295 // SSL_peek should synchronously return the same data.
1296 int ret2 = SSL_peek(ssl, buf.get(), ret);
1297 if (ret2 != ret ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001298 OPENSSL_memcmp(buf.get(), out, ret) != 0) {
David Benjaminf3fbade2016-09-19 13:08:16 -04001299 fprintf(stderr, "First and second SSL_peek did not match.\n");
1300 return -1;
1301 }
1302
1303 // SSL_read should synchronously return the same data and consume it.
1304 ret2 = SSL_read(ssl, buf.get(), ret);
1305 if (ret2 != ret ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001306 OPENSSL_memcmp(buf.get(), out, ret) != 0) {
David Benjaminf3fbade2016-09-19 13:08:16 -04001307 fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
1308 return -1;
1309 }
1310 }
1311
David Benjamin6c2563e2015-04-03 03:47:47 -04001312 return ret;
1313}
1314
1315// WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
1316// operations. It returns the result of the final |SSL_write| call.
David Benjaminbbba9392017-04-06 12:54:12 -04001317static int WriteAll(SSL *ssl, const void *in_, size_t in_len) {
1318 const uint8_t *in = reinterpret_cast<const uint8_t *>(in_);
David Benjamin7e7a82d2016-05-20 20:12:42 -04001319 const TestConfig *config = GetTestConfig(ssl);
David Benjamin6c2563e2015-04-03 03:47:47 -04001320 int ret;
1321 do {
1322 ret = SSL_write(ssl, in, in_len);
1323 if (ret > 0) {
1324 in += ret;
1325 in_len -= ret;
1326 }
1327 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
1328 return ret;
1329}
1330
David Benjamin30789da2015-08-29 22:56:45 -04001331// DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
1332// returns the result of the final |SSL_shutdown| call.
1333static int DoShutdown(SSL *ssl) {
David Benjamin7e7a82d2016-05-20 20:12:42 -04001334 const TestConfig *config = GetTestConfig(ssl);
David Benjamin30789da2015-08-29 22:56:45 -04001335 int ret;
1336 do {
1337 ret = SSL_shutdown(ssl);
1338 } while (config->async && RetryAsync(ssl, ret));
1339 return ret;
1340}
1341
David Benjamin1d4f4c02016-07-26 18:03:08 -04001342// DoSendFatalAlert calls |SSL_send_fatal_alert|, resolving any asynchronous
1343// operations. It returns the result of the final |SSL_send_fatal_alert| call.
1344static int DoSendFatalAlert(SSL *ssl, uint8_t alert) {
1345 const TestConfig *config = GetTestConfig(ssl);
1346 int ret;
1347 do {
1348 ret = SSL_send_fatal_alert(ssl, alert);
1349 } while (config->async && RetryAsync(ssl, ret));
1350 return ret;
1351}
1352
Steven Valdez1e6f11a2016-07-27 11:10:52 -04001353static uint16_t GetProtocolVersion(const SSL *ssl) {
1354 uint16_t version = SSL_version(ssl);
1355 if (!SSL_is_dtls(ssl)) {
1356 return version;
1357 }
1358 return 0x0201 + ~version;
1359}
1360
David Benjamin91eab5c2015-06-18 18:35:46 -04001361// CheckHandshakeProperties checks, immediately after |ssl| completes its
1362// initial handshake (or False Starts), whether all the properties are
1363// consistent with the test configuration and invariants.
Steven Valdeze831a812017-03-09 14:56:07 -05001364static bool CheckHandshakeProperties(SSL *ssl, bool is_resume,
1365 const TestConfig *config) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001366 if (SSL_get_current_cipher(ssl) == nullptr) {
1367 fprintf(stderr, "null cipher after handshake\n");
1368 return false;
1369 }
1370
Steven Valdeze831a812017-03-09 14:56:07 -05001371 bool expect_resume =
1372 is_resume && (!config->expect_session_miss || SSL_in_early_data(ssl));
1373 if (!!SSL_session_reused(ssl) != expect_resume) {
1374 fprintf(stderr, "session unexpectedly was%s reused\n",
David Benjamin91eab5c2015-06-18 18:35:46 -04001375 SSL_session_reused(ssl) ? "" : " not");
1376 return false;
1377 }
1378
Steven Valdez681eb6a2016-12-19 13:19:29 -05001379 bool expect_handshake_done =
Steven Valdeze831a812017-03-09 14:56:07 -05001380 (is_resume || !config->false_start) && !SSL_in_early_data(ssl);
David Benjamin91eab5c2015-06-18 18:35:46 -04001381 if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
1382 fprintf(stderr, "handshake was%s completed\n",
1383 GetTestState(ssl)->handshake_done ? "" : " not");
1384 return false;
1385 }
1386
David Benjaminba4594a2015-06-18 18:36:15 -04001387 if (expect_handshake_done && !config->is_server) {
1388 bool expect_new_session =
1389 !config->expect_no_session &&
Steven Valdez143e8b32016-07-11 13:19:03 -04001390 (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
Steven Valdez1e6f11a2016-07-27 11:10:52 -04001391 // Session tickets are sent post-handshake in TLS 1.3.
1392 GetProtocolVersion(ssl) < TLS1_3_VERSION;
David Benjaminba4594a2015-06-18 18:36:15 -04001393 if (expect_new_session != GetTestState(ssl)->got_new_session) {
1394 fprintf(stderr,
David Benjamindd6fed92015-10-23 17:41:12 -04001395 "new session was%s cached, but we expected the opposite\n",
David Benjaminba4594a2015-06-18 18:36:15 -04001396 GetTestState(ssl)->got_new_session ? "" : " not");
1397 return false;
1398 }
1399 }
1400
David Benjaminb5c58db2017-01-28 01:39:29 -05001401 if (!is_resume) {
1402 if (config->expect_session_id && !GetTestState(ssl)->got_new_session) {
1403 fprintf(stderr, "session was not cached on the server.\n");
1404 return false;
1405 }
1406 if (config->expect_no_session_id && GetTestState(ssl)->got_new_session) {
1407 fprintf(stderr, "session was unexpectedly cached on the server.\n");
1408 return false;
1409 }
1410 }
1411
David Benjamin91eab5c2015-06-18 18:35:46 -04001412 if (config->is_server && !GetTestState(ssl)->early_callback_called) {
1413 fprintf(stderr, "early callback not called\n");
1414 return false;
1415 }
1416
1417 if (!config->expected_server_name.empty()) {
1418 const char *server_name =
1419 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
David Benjamin8b176712016-10-27 21:51:24 -04001420 if (server_name == nullptr ||
1421 server_name != config->expected_server_name) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001422 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
1423 server_name, config->expected_server_name.c_str());
1424 return false;
1425 }
1426 }
1427
David Benjamin91eab5c2015-06-18 18:35:46 -04001428 if (!config->expected_next_proto.empty()) {
1429 const uint8_t *next_proto;
1430 unsigned next_proto_len;
1431 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
1432 if (next_proto_len != config->expected_next_proto.size() ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001433 OPENSSL_memcmp(next_proto, config->expected_next_proto.data(),
1434 next_proto_len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001435 fprintf(stderr, "negotiated next proto mismatch\n");
1436 return false;
1437 }
1438 }
1439
Steven Valdez873ebc92017-05-09 12:12:58 -04001440 if (!config->is_server) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001441 const uint8_t *alpn_proto;
1442 unsigned alpn_proto_len;
1443 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
Steven Valdez873ebc92017-05-09 12:12:58 -04001444 if (alpn_proto_len != config->expected_alpn.size() ||
1445 OPENSSL_memcmp(alpn_proto, config->expected_alpn.data(),
1446 alpn_proto_len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001447 fprintf(stderr, "negotiated alpn proto mismatch\n");
1448 return false;
1449 }
1450 }
1451
1452 if (!config->expected_channel_id.empty()) {
1453 uint8_t channel_id[64];
1454 if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
1455 fprintf(stderr, "no channel id negotiated\n");
1456 return false;
1457 }
1458 if (config->expected_channel_id.size() != 64 ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001459 OPENSSL_memcmp(config->expected_channel_id.data(), channel_id, 64) !=
1460 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001461 fprintf(stderr, "channel id mismatch\n");
1462 return false;
1463 }
1464 }
1465
David Benjamind2610042017-01-03 10:49:28 -05001466 if (config->expect_extended_master_secret && !SSL_get_extms_support(ssl)) {
1467 fprintf(stderr, "No EMS for connection when expected\n");
1468 return false;
1469 }
1470
1471 if (config->expect_secure_renegotiation &&
1472 !SSL_get_secure_renegotiation_support(ssl)) {
1473 fprintf(stderr, "No secure renegotiation for connection when expected\n");
1474 return false;
1475 }
1476
1477 if (config->expect_no_secure_renegotiation &&
1478 SSL_get_secure_renegotiation_support(ssl)) {
1479 fprintf(stderr,
1480 "Secure renegotiation unexpectedly negotiated for connection\n");
1481 return false;
David Benjamin91eab5c2015-06-18 18:35:46 -04001482 }
1483
1484 if (!config->expected_ocsp_response.empty()) {
1485 const uint8_t *data;
1486 size_t len;
1487 SSL_get0_ocsp_response(ssl, &data, &len);
1488 if (config->expected_ocsp_response.size() != len ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001489 OPENSSL_memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001490 fprintf(stderr, "OCSP response mismatch\n");
1491 return false;
1492 }
1493 }
1494
1495 if (!config->expected_signed_cert_timestamps.empty()) {
1496 const uint8_t *data;
1497 size_t len;
1498 SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
1499 if (config->expected_signed_cert_timestamps.size() != len ||
David Benjamin17cf2cb2016-12-13 01:07:13 -05001500 OPENSSL_memcmp(config->expected_signed_cert_timestamps.data(), data,
1501 len) != 0) {
David Benjamin91eab5c2015-06-18 18:35:46 -04001502 fprintf(stderr, "SCT list mismatch\n");
1503 return false;
1504 }
1505 }
1506
Paul Lietar8f1c2682015-08-18 12:21:54 +01001507 if (config->expect_verify_result) {
1508 int expected_verify_result = config->verify_fail ?
1509 X509_V_ERR_APPLICATION_VERIFICATION :
1510 X509_V_OK;
1511
1512 if (SSL_get_verify_result(ssl) != expected_verify_result) {
1513 fprintf(stderr, "Wrong certificate verification result\n");
1514 return false;
1515 }
1516 }
1517
Nick Harper60edffd2016-06-21 15:19:24 -07001518 if (config->expect_peer_signature_algorithm != 0 &&
1519 config->expect_peer_signature_algorithm !=
1520 SSL_get_peer_signature_algorithm(ssl)) {
1521 fprintf(stderr, "Peer signature algorithm was %04x, wanted %04x.\n",
1522 SSL_get_peer_signature_algorithm(ssl),
1523 config->expect_peer_signature_algorithm);
David Benjamin6e807652015-11-02 12:02:20 -05001524 return false;
1525 }
1526
Steven Valdez873ebc92017-05-09 12:12:58 -04001527 if (config->expect_curve_id != 0) {
David Benjamin9e68f192016-06-30 14:55:33 -04001528 uint16_t curve_id = SSL_get_curve_id(ssl);
Steven Valdez873ebc92017-05-09 12:12:58 -04001529 if (static_cast<uint16_t>(config->expect_curve_id) != curve_id) {
David Benjamin9e68f192016-06-30 14:55:33 -04001530 fprintf(stderr, "curve_id was %04x, wanted %04x\n", curve_id,
Steven Valdez873ebc92017-05-09 12:12:58 -04001531 static_cast<uint16_t>(config->expect_curve_id));
David Benjamin9e68f192016-06-30 14:55:33 -04001532 return false;
1533 }
1534 }
1535
David Benjaminabbbee12016-10-31 19:20:42 -04001536 uint16_t cipher_id =
1537 static_cast<uint16_t>(SSL_CIPHER_get_id(SSL_get_current_cipher(ssl)));
1538 if (config->expect_cipher_aes != 0 &&
1539 EVP_has_aes_hardware() &&
1540 static_cast<uint16_t>(config->expect_cipher_aes) != cipher_id) {
1541 fprintf(stderr, "Cipher ID was %04x, wanted %04x (has AES hardware)\n",
1542 cipher_id, static_cast<uint16_t>(config->expect_cipher_aes));
1543 return false;
1544 }
1545
1546 if (config->expect_cipher_no_aes != 0 &&
1547 !EVP_has_aes_hardware() &&
1548 static_cast<uint16_t>(config->expect_cipher_no_aes) != cipher_id) {
1549 fprintf(stderr, "Cipher ID was %04x, wanted %04x (no AES hardware)\n",
1550 cipher_id, static_cast<uint16_t>(config->expect_cipher_no_aes));
1551 return false;
1552 }
1553
Steven Valdeze831a812017-03-09 14:56:07 -05001554 if (is_resume && !SSL_in_early_data(ssl)) {
Steven Valdez2d850622017-01-11 11:34:52 -05001555 if ((config->expect_accept_early_data && !SSL_early_data_accepted(ssl)) ||
1556 (config->expect_reject_early_data && SSL_early_data_accepted(ssl))) {
1557 fprintf(stderr,
1558 "Early data was%s accepted, but we expected the opposite\n",
1559 SSL_early_data_accepted(ssl) ? "" : " not");
1560 return false;
1561 }
1562 }
David Benjaminabbbee12016-10-31 19:20:42 -04001563
David Benjaminbb9e36e2016-08-03 14:14:47 -04001564 if (!config->psk.empty()) {
1565 if (SSL_get_peer_cert_chain(ssl) != nullptr) {
1566 fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
1567 return false;
1568 }
1569 } else if (!config->is_server || config->require_any_client_certificate) {
1570 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
1571 fprintf(stderr, "Received no peer certificate but expected one.\n");
David Benjamin91eab5c2015-06-18 18:35:46 -04001572 return false;
1573 }
1574 }
David Benjaminbb9e36e2016-08-03 14:14:47 -04001575
David Benjamin2c516452016-11-15 10:16:54 +09001576 if (!config->expect_peer_cert_file.empty()) {
1577 bssl::UniquePtr<X509> expect_leaf;
1578 bssl::UniquePtr<STACK_OF(X509)> expect_chain;
1579 if (!LoadCertificate(&expect_leaf, &expect_chain,
1580 config->expect_peer_cert_file)) {
1581 return false;
1582 }
1583
1584 // For historical reasons, clients report a chain with a leaf and servers
1585 // without.
1586 if (!config->is_server) {
1587 if (!sk_X509_insert(expect_chain.get(), expect_leaf.get(), 0)) {
1588 return false;
1589 }
1590 X509_up_ref(expect_leaf.get()); // sk_X509_push takes ownership.
1591 }
1592
1593 bssl::UniquePtr<X509> leaf(SSL_get_peer_certificate(ssl));
1594 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl);
1595 if (X509_cmp(leaf.get(), expect_leaf.get()) != 0) {
1596 fprintf(stderr, "Received a different leaf certificate than expected.\n");
1597 return false;
1598 }
1599
1600 if (sk_X509_num(chain) != sk_X509_num(expect_chain.get())) {
1601 fprintf(stderr, "Received a chain of length %zu instead of %zu.\n",
1602 sk_X509_num(chain), sk_X509_num(expect_chain.get()));
1603 return false;
1604 }
1605
1606 for (size_t i = 0; i < sk_X509_num(chain); i++) {
1607 if (X509_cmp(sk_X509_value(chain, i),
1608 sk_X509_value(expect_chain.get(), i)) != 0) {
1609 fprintf(stderr, "Chain certificate %zu did not match.\n",
1610 i + 1);
1611 return false;
1612 }
1613 }
1614 }
1615
David Benjaminbbaf3672016-11-17 10:53:09 +09001616 bool expected_sha256_client_cert = config->expect_sha256_client_cert_initial;
1617 if (is_resume) {
1618 expected_sha256_client_cert = config->expect_sha256_client_cert_resume;
1619 }
1620
1621 if (SSL_get_session(ssl)->peer_sha256_valid != expected_sha256_client_cert) {
1622 fprintf(stderr,
1623 "Unexpected SHA-256 client cert state: expected:%d is_resume:%d.\n",
1624 expected_sha256_client_cert, is_resume);
1625 return false;
1626 }
1627
1628 if (expected_sha256_client_cert &&
Adam Langley46db7af2017-02-01 15:49:37 -08001629 SSL_get_session(ssl)->certs != nullptr) {
David Benjaminbbaf3672016-11-17 10:53:09 +09001630 fprintf(stderr, "Have both client cert and SHA-256 hash: is_resume:%d.\n",
1631 is_resume);
1632 return false;
1633 }
1634
David Benjamin35ac5b72017-03-03 15:05:56 -05001635 if (is_resume && config->expect_ticket_age_skew != 0 &&
1636 SSL_get_ticket_age_skew(ssl) != config->expect_ticket_age_skew) {
1637 fprintf(stderr, "Ticket age skew was %" PRId32 ", wanted %d\n",
1638 SSL_get_ticket_age_skew(ssl), config->expect_ticket_age_skew);
1639 return false;
1640 }
1641
David Benjamin91eab5c2015-06-18 18:35:46 -04001642 return true;
1643}
1644
Steven Valdeze831a812017-03-09 14:56:07 -05001645static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session, SSL *ssl,
1646 const TestConfig *config, bool is_resume, bool is_retry);
1647
1648// DoConnection tests an SSL connection against the peer. On success, it returns
David Benjamin87c8a642015-02-21 01:54:29 -05001649// true and sets |*out_session| to the negotiated SSL session. If the test is a
1650// resumption attempt, |is_resume| is true and |session| is the session from the
1651// previous exchange.
Steven Valdeze831a812017-03-09 14:56:07 -05001652static bool DoConnection(bssl::UniquePtr<SSL_SESSION> *out_session,
1653 SSL_CTX *ssl_ctx, const TestConfig *config,
1654 const TestConfig *retry_config, bool is_resume,
1655 SSL_SESSION *session) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001656 bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
David Benjamina7f333d2015-02-09 02:37:18 -05001657 if (!ssl) {
David Benjamin40f101b2015-02-20 11:23:42 -05001658 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001659 }
1660
David Benjamin7e7a82d2016-05-20 20:12:42 -04001661 if (!SetTestConfig(ssl.get(), config) ||
David Benjamin2d445c02015-02-09 13:03:50 -05001662 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
David Benjamin40f101b2015-02-20 11:23:42 -05001663 return false;
Adam Langley69a01602014-11-17 17:26:55 -08001664 }
David Benjamin5a593af2014-08-11 19:51:50 -04001665
Steven Valdez2d850622017-01-11 11:34:52 -05001666 GetTestState(ssl.get())->is_resume = is_resume;
1667
Adam Langley5f0efe02015-02-20 13:03:16 -08001668 if (config->fallback_scsv &&
1669 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
1670 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04001671 }
David Benjamina0486782016-10-06 19:11:32 -04001672 // Install the certificate synchronously if nothing else will handle it.
1673 if (!config->use_early_callback &&
1674 !config->use_old_client_cert_callback &&
1675 !config->async &&
1676 !InstallCertificate(ssl.get())) {
1677 return false;
David Benjamin5a593af2014-08-11 19:51:50 -04001678 }
David Benjamin5edfc8c2016-12-10 15:46:58 -05001679 if (!config->use_old_client_cert_callback) {
1680 SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
1681 }
David Benjamin5a593af2014-08-11 19:51:50 -04001682 if (config->require_any_client_certificate) {
David Benjamina7f333d2015-02-09 02:37:18 -05001683 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
Paul Lietar8f1c2682015-08-18 12:21:54 +01001684 NULL);
1685 }
1686 if (config->verify_peer) {
1687 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
David Benjamin5a593af2014-08-11 19:51:50 -04001688 }
1689 if (config->false_start) {
David Benjamined7c4752015-02-16 19:16:46 -05001690 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
David Benjamin5a593af2014-08-11 19:51:50 -04001691 }
1692 if (config->cbc_record_splitting) {
David Benjamina7f333d2015-02-09 02:37:18 -05001693 SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
David Benjamin5a593af2014-08-11 19:51:50 -04001694 }
1695 if (config->partial_write) {
David Benjamina7f333d2015-02-09 02:37:18 -05001696 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
David Benjamin5a593af2014-08-11 19:51:50 -04001697 }
Steven Valdez4f94b1c2016-05-24 12:31:07 -04001698 if (config->no_tls13) {
1699 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
1700 }
David Benjamin5a593af2014-08-11 19:51:50 -04001701 if (config->no_tls12) {
David Benjamina7f333d2015-02-09 02:37:18 -05001702 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
David Benjamin5a593af2014-08-11 19:51:50 -04001703 }
1704 if (config->no_tls11) {
David Benjamina7f333d2015-02-09 02:37:18 -05001705 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
David Benjamin5a593af2014-08-11 19:51:50 -04001706 }
1707 if (config->no_tls1) {
David Benjamina7f333d2015-02-09 02:37:18 -05001708 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
David Benjamin5a593af2014-08-11 19:51:50 -04001709 }
1710 if (config->no_ssl3) {
David Benjamina7f333d2015-02-09 02:37:18 -05001711 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
David Benjamin5a593af2014-08-11 19:51:50 -04001712 }
Steven Valdez143e8b32016-07-11 13:19:03 -04001713 if (!config->expected_channel_id.empty() ||
1714 config->enable_channel_id) {
David Benjamineebd3c82016-12-06 17:43:58 -05001715 SSL_set_tls_channel_id_enabled(ssl.get(), 1);
David Benjamina08e49d2014-08-24 01:46:07 -04001716 }
1717 if (!config->send_channel_id.empty()) {
David Benjamineebd3c82016-12-06 17:43:58 -05001718 SSL_set_tls_channel_id_enabled(ssl.get(), 1);
David Benjamind9e07012015-02-09 03:04:34 -05001719 if (!config->async) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001720 // The async case will be supplied by |ChannelIdCallback|.
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001721 bssl::UniquePtr<EVP_PKEY> pkey = LoadPrivateKey(config->send_channel_id);
David Benjamind9e07012015-02-09 03:04:34 -05001722 if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001723 return false;
David Benjamind9e07012015-02-09 03:04:34 -05001724 }
David Benjamina08e49d2014-08-24 01:46:07 -04001725 }
David Benjamina08e49d2014-08-24 01:46:07 -04001726 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001727 if (!config->host_name.empty() &&
1728 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001729 return false;
David Benjamine78bfde2014-09-06 12:45:15 -04001730 }
David Benjamin9d0847a2015-02-16 03:57:55 -05001731 if (!config->advertise_alpn.empty() &&
1732 SSL_set_alpn_protos(ssl.get(),
1733 (const uint8_t *)config->advertise_alpn.data(),
1734 config->advertise_alpn.size()) != 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05001735 return false;
David Benjaminae2888f2014-09-06 12:58:58 -04001736 }
David Benjamin48cae082014-10-27 01:06:24 -04001737 if (!config->psk.empty()) {
David Benjaminc273d2c2015-02-09 12:59:46 -05001738 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
1739 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
David Benjamin48cae082014-10-27 01:06:24 -04001740 }
David Benjamin61f95272014-11-25 01:55:35 -05001741 if (!config->psk_identity.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001742 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001743 return false;
David Benjamin48cae082014-10-27 01:06:24 -04001744 }
David Benjamin61f95272014-11-25 01:55:35 -05001745 if (!config->srtp_profiles.empty() &&
David Benjamina7f333d2015-02-09 02:37:18 -05001746 !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
David Benjamin40f101b2015-02-20 11:23:42 -05001747 return false;
David Benjamin61f95272014-11-25 01:55:35 -05001748 }
David Benjamin26e1ff32017-02-14 20:13:00 -05001749 if (config->enable_ocsp_stapling) {
1750 SSL_enable_ocsp_stapling(ssl.get());
David Benjamin61f95272014-11-25 01:55:35 -05001751 }
David Benjamin26e1ff32017-02-14 20:13:00 -05001752 if (config->enable_signed_cert_timestamps) {
1753 SSL_enable_signed_cert_timestamps(ssl.get());
David Benjaminca6c8262014-11-15 19:06:08 -05001754 }
David Benjamin2dc02042016-09-19 19:57:37 -04001755 if (config->min_version != 0 &&
David Benjamine4706902016-09-20 15:12:23 -04001756 !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) {
David Benjamin2dc02042016-09-19 19:57:37 -04001757 return false;
David Benjamin1eb367c2014-12-12 18:17:51 -05001758 }
David Benjamin2dc02042016-09-19 19:57:37 -04001759 if (config->max_version != 0 &&
David Benjamine4706902016-09-20 15:12:23 -04001760 !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) {
David Benjamin2dc02042016-09-19 19:57:37 -04001761 return false;
David Benjamin1eb367c2014-12-12 18:17:51 -05001762 }
David Benjamin13be1de2015-01-11 16:29:36 -05001763 if (config->mtu != 0) {
David Benjamina7f333d2015-02-09 02:37:18 -05001764 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
1765 SSL_set_mtu(ssl.get(), config->mtu);
David Benjamin13be1de2015-01-11 16:29:36 -05001766 }
Adam Langley524e7172015-02-20 16:04:00 -08001767 if (config->install_ddos_callback) {
1768 SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
1769 }
David Benjamin1d5ef3b2015-10-12 19:54:18 -04001770 if (config->renegotiate_once) {
1771 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_once);
1772 }
1773 if (config->renegotiate_freely) {
1774 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
David Benjaminb16346b2015-04-08 19:16:58 -04001775 }
Adam Langley27a0d082015-11-03 13:34:10 -08001776 if (config->renegotiate_ignore) {
1777 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_ignore);
1778 }
David Benjamin30789da2015-08-29 22:56:45 -04001779 if (!config->check_close_notify) {
1780 SSL_set_quiet_shutdown(ssl.get(), 1);
1781 }
David Benjamin99fdfb92015-11-02 12:11:35 -05001782 if (config->p384_only) {
1783 int nid = NID_secp384r1;
1784 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
1785 return false;
1786 }
1787 }
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001788 if (config->enable_all_curves) {
1789 static const int kAllCurves[] = {
Adam Langley764ab982017-03-10 18:01:30 -08001790 NID_secp224r1, NID_X9_62_prime256v1, NID_secp384r1,
1791 NID_secp521r1, NID_X25519,
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001792 };
1793 if (!SSL_set1_curves(ssl.get(), kAllCurves,
Steven Valdezcb966542016-08-17 16:56:14 -04001794 OPENSSL_ARRAY_SIZE(kAllCurves))) {
David Benjamin8c2b3bf2015-12-18 20:55:44 -05001795 return false;
1796 }
1797 }
Taylor Brandstetter376a0fe2016-05-10 19:30:28 -07001798 if (config->initial_timeout_duration_ms > 0) {
1799 DTLSv1_set_initial_timeout_duration(ssl.get(),
1800 config->initial_timeout_duration_ms);
1801 }
David Benjamina252b342016-09-26 19:57:53 -04001802 if (config->max_cert_list > 0) {
1803 SSL_set_max_cert_list(ssl.get(), config->max_cert_list);
1804 }
David Benjaminbbaf3672016-11-17 10:53:09 +09001805 if (!is_resume && config->retain_only_sha256_client_cert_initial) {
1806 SSL_set_retain_only_sha256_of_client_certs(ssl.get(), 1);
1807 }
1808 if (is_resume && config->retain_only_sha256_client_cert_resume) {
1809 SSL_set_retain_only_sha256_of_client_certs(ssl.get(), 1);
1810 }
David Benjamine3fbb362017-01-06 16:19:28 -05001811 if (config->max_send_fragment > 0) {
1812 SSL_set_max_send_fragment(ssl.get(), config->max_send_fragment);
1813 }
David Benjamin025b3d32014-07-01 19:53:04 -04001814
David Benjamin87c8a642015-02-21 01:54:29 -05001815 int sock = Connect(config->port);
1816 if (sock == -1) {
1817 return false;
1818 }
1819 SocketCloser closer(sock);
1820
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001821 bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
David Benjamina7f333d2015-02-09 02:37:18 -05001822 if (!bio) {
David Benjamin40f101b2015-02-20 11:23:42 -05001823 return false;
David Benjamin43ec06f2014-08-05 02:28:57 -04001824 }
David Benjamin6fd297b2014-08-11 18:43:38 -04001825 if (config->is_dtls) {
David Benjamin11c82892017-02-23 20:40:31 -05001826 bssl::UniquePtr<BIO> packeted = PacketedBioCreate(&g_clock);
David Benjaminb7c5e842016-03-28 09:59:10 -04001827 if (!packeted) {
1828 return false;
1829 }
David Benjamin585d7a42016-06-02 14:58:00 -04001830 GetTestState(ssl.get())->packeted_bio = packeted.get();
David Benjamina7f333d2015-02-09 02:37:18 -05001831 BIO_push(packeted.get(), bio.release());
1832 bio = std::move(packeted);
David Benjamin6fd297b2014-08-11 18:43:38 -04001833 }
David Benjamin5a593af2014-08-11 19:51:50 -04001834 if (config->async) {
Matt Braithwaited17d74d2016-08-17 20:10:28 -07001835 bssl::UniquePtr<BIO> async_scoped =
David Benjaminc273d2c2015-02-09 12:59:46 -05001836 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
David Benjaminb7c5e842016-03-28 09:59:10 -04001837 if (!async_scoped) {
1838 return false;
1839 }
David Benjamina7f333d2015-02-09 02:37:18 -05001840 BIO_push(async_scoped.get(), bio.release());
David Benjamin6c2563e2015-04-03 03:47:47 -04001841 GetTestState(ssl.get())->async_bio = async_scoped.get();
David Benjamina7f333d2015-02-09 02:37:18 -05001842 bio = std::move(async_scoped);
David Benjamin43ec06f2014-08-05 02:28:57 -04001843 }
David Benjamina7f333d2015-02-09 02:37:18 -05001844 SSL_set_bio(ssl.get(), bio.get(), bio.get());
1845 bio.release(); // SSL_set_bio takes ownership.
David Benjamin43ec06f2014-08-05 02:28:57 -04001846
David Benjamin1d5c83e2014-07-22 19:20:02 -04001847 if (session != NULL) {
David Benjamin1b8b6912015-02-09 04:28:16 -05001848 if (!config->is_server) {
1849 if (SSL_set_session(ssl.get(), session) != 1) {
David Benjamin40f101b2015-02-20 11:23:42 -05001850 return false;
David Benjamin1b8b6912015-02-09 04:28:16 -05001851 }
1852 } else if (config->async) {
1853 // The internal session cache is disabled, so install the session
1854 // manually.
David Benjaminb9195402016-08-05 10:51:43 -04001855 SSL_SESSION_up_ref(session);
1856 GetTestState(ssl.get())->pending_session.reset(session);
David Benjamin1d5c83e2014-07-22 19:20:02 -04001857 }
1858 }
1859
David Benjamina07c0fc2015-05-13 13:19:42 -04001860 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1861 fprintf(stderr, "non-null cipher before handshake\n");
1862 return false;
1863 }
1864
David Benjamin4784b992017-03-25 18:22:19 -05001865 if (config->is_server) {
1866 SSL_set_accept_state(ssl.get());
David Benjamine0e7d0d2015-02-08 19:33:25 -05001867 } else {
David Benjamin4784b992017-03-25 18:22:19 -05001868 SSL_set_connect_state(ssl.get());
1869 }
1870
Steven Valdeze831a812017-03-09 14:56:07 -05001871 bool ret = DoExchange(out_session, ssl.get(), config, is_resume, false);
1872 if (!config->is_server && is_resume && config->expect_reject_early_data) {
1873 // We must have failed due to an early data rejection.
1874 if (ret) {
1875 fprintf(stderr, "0-RTT exchange unexpected succeeded.\n");
1876 return false;
1877 }
1878 if (SSL_get_error(ssl.get(), -1) != SSL_ERROR_EARLY_DATA_REJECTED) {
1879 fprintf(stderr,
1880 "SSL_get_error did not signal SSL_ERROR_EARLY_DATA_REJECTED.\n");
1881 return false;
1882 }
1883
1884 // Before reseting, early state should still be available.
1885 if (!SSL_in_early_data(ssl.get()) ||
1886 !CheckHandshakeProperties(ssl.get(), is_resume, config)) {
1887 fprintf(stderr, "SSL_in_early_data returned false before reset.\n");
1888 return false;
1889 }
1890
1891 // Reset the connection and try again at 1-RTT.
1892 SSL_reset_early_data_reject(ssl.get());
1893
1894 // After reseting, the socket should report it is no longer in an early data
1895 // state.
1896 if (SSL_in_early_data(ssl.get())) {
1897 fprintf(stderr, "SSL_in_early_data returned true after reset.\n");
1898 return false;
1899 }
1900
1901 if (!SetTestConfig(ssl.get(), retry_config)) {
1902 return false;
1903 }
1904
1905 ret = DoExchange(out_session, ssl.get(), retry_config, is_resume, true);
1906 }
1907 return ret;
1908}
1909
1910static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session, SSL *ssl,
1911 const TestConfig *config, bool is_resume,
1912 bool is_retry) {
David Benjamin4784b992017-03-25 18:22:19 -05001913 int ret;
1914 if (!config->implicit_handshake) {
David Benjamine0e7d0d2015-02-08 19:33:25 -05001915 do {
Steven Valdeze831a812017-03-09 14:56:07 -05001916 ret = SSL_do_handshake(ssl);
1917 } while (config->async && RetryAsync(ssl, ret));
David Benjamin91eab5c2015-06-18 18:35:46 -04001918 if (ret != 1 ||
Steven Valdeze831a812017-03-09 14:56:07 -05001919 !CheckHandshakeProperties(ssl, is_resume, config)) {
David Benjamin40f101b2015-02-20 11:23:42 -05001920 return false;
David Benjamine0e7d0d2015-02-08 19:33:25 -05001921 }
David Benjamin025b3d32014-07-01 19:53:04 -04001922
David Benjamin8c26d752017-03-26 15:13:51 -05001923 if (config->handshake_twice) {
1924 do {
Steven Valdeze831a812017-03-09 14:56:07 -05001925 ret = SSL_do_handshake(ssl);
1926 } while (config->async && RetryAsync(ssl, ret));
David Benjamin8c26d752017-03-26 15:13:51 -05001927 if (ret != 1) {
1928 return false;
1929 }
1930 }
1931
1932 // Skip the |config->async| logic as this should be a no-op.
1933 if (config->no_op_extra_handshake &&
Steven Valdeze831a812017-03-09 14:56:07 -05001934 SSL_do_handshake(ssl) != 1) {
David Benjamin8c26d752017-03-26 15:13:51 -05001935 fprintf(stderr, "Extra SSL_do_handshake was not a no-op.\n");
1936 return false;
1937 }
1938
David Benjaminba4594a2015-06-18 18:36:15 -04001939 // Reset the state to assert later that the callback isn't called in
1940 // renegotations.
Steven Valdeze831a812017-03-09 14:56:07 -05001941 GetTestState(ssl)->got_new_session = false;
David Benjamin61f95272014-11-25 01:55:35 -05001942 }
1943
David Benjaminc565ebb2015-04-03 04:06:36 -04001944 if (config->export_keying_material > 0) {
1945 std::vector<uint8_t> result(
1946 static_cast<size_t>(config->export_keying_material));
1947 if (!SSL_export_keying_material(
Steven Valdeze831a812017-03-09 14:56:07 -05001948 ssl, result.data(), result.size(), config->export_label.data(),
1949 config->export_label.size(),
1950 reinterpret_cast<const uint8_t *>(config->export_context.data()),
David Benjaminc565ebb2015-04-03 04:06:36 -04001951 config->export_context.size(), config->use_export_context)) {
1952 fprintf(stderr, "failed to export keying material\n");
1953 return false;
1954 }
Steven Valdeze831a812017-03-09 14:56:07 -05001955 if (WriteAll(ssl, result.data(), result.size()) < 0) {
David Benjaminc565ebb2015-04-03 04:06:36 -04001956 return false;
1957 }
1958 }
1959
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001960 if (config->tls_unique) {
1961 uint8_t tls_unique[16];
1962 size_t tls_unique_len;
Steven Valdeze831a812017-03-09 14:56:07 -05001963 if (!SSL_get_tls_unique(ssl, tls_unique, &tls_unique_len,
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001964 sizeof(tls_unique))) {
1965 fprintf(stderr, "failed to get tls-unique\n");
1966 return false;
1967 }
1968
1969 if (tls_unique_len != 12) {
1970 fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
1971 static_cast<unsigned>(tls_unique_len));
1972 return false;
1973 }
1974
Steven Valdeze831a812017-03-09 14:56:07 -05001975 if (WriteAll(ssl, tls_unique, tls_unique_len) < 0) {
Adam Langleyaf0e32c2015-06-03 09:57:23 -07001976 return false;
1977 }
1978 }
1979
David Benjamin1d4f4c02016-07-26 18:03:08 -04001980 if (config->send_alert) {
Steven Valdeze831a812017-03-09 14:56:07 -05001981 if (DoSendFatalAlert(ssl, SSL_AD_DECOMPRESSION_FAILURE) < 0) {
David Benjamin1d4f4c02016-07-26 18:03:08 -04001982 return false;
1983 }
1984 return true;
1985 }
1986
David Benjamin5a593af2014-08-11 19:51:50 -04001987 if (config->write_different_record_sizes) {
David Benjamin6fd297b2014-08-11 18:43:38 -04001988 if (config->is_dtls) {
1989 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
David Benjamin40f101b2015-02-20 11:23:42 -05001990 return false;
David Benjamin6fd297b2014-08-11 18:43:38 -04001991 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07001992 // This mode writes a number of different record sizes in an attempt to
1993 // trip up the CBC record splitting code.
Adam Langleybc949292015-06-18 21:32:44 -07001994 static const size_t kBufLen = 32769;
1995 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
David Benjamin17cf2cb2016-12-13 01:07:13 -05001996 OPENSSL_memset(buf.get(), 0x42, kBufLen);
Kenny Root7fdeaf12014-08-05 15:23:37 -07001997 static const size_t kRecordSizes[] = {
1998 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
Steven Valdezcb966542016-08-17 16:56:14 -04001999 for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07002000 const size_t len = kRecordSizes[i];
Adam Langleybc949292015-06-18 21:32:44 -07002001 if (len > kBufLen) {
Kenny Root7fdeaf12014-08-05 15:23:37 -07002002 fprintf(stderr, "Bad kRecordSizes value.\n");
David Benjamin40f101b2015-02-20 11:23:42 -05002003 return false;
Kenny Root7fdeaf12014-08-05 15:23:37 -07002004 }
Steven Valdeze831a812017-03-09 14:56:07 -05002005 if (WriteAll(ssl, buf.get(), len) < 0) {
David Benjamin40f101b2015-02-20 11:23:42 -05002006 return false;
David Benjamin025b3d32014-07-01 19:53:04 -04002007 }
2008 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07002009 } else {
David Benjaminbbba9392017-04-06 12:54:12 -04002010 static const char kInitialWrite[] = "hello";
2011 bool pending_initial_write = false;
David Benjamina1eaba12017-01-01 23:19:22 -05002012 if (config->read_with_unfinished_write) {
2013 if (!config->async) {
2014 fprintf(stderr, "-read-with-unfinished-write requires -async.\n");
2015 return false;
2016 }
2017
Steven Valdeze831a812017-03-09 14:56:07 -05002018 // Let only one byte of the record through.
2019 AsyncBioAllowWrite(GetTestState(ssl)->async_bio, 1);
David Benjaminbbba9392017-04-06 12:54:12 -04002020 int write_ret =
Steven Valdeze831a812017-03-09 14:56:07 -05002021 SSL_write(ssl, kInitialWrite, strlen(kInitialWrite));
2022 if (SSL_get_error(ssl, write_ret) != SSL_ERROR_WANT_WRITE) {
David Benjamina1eaba12017-01-01 23:19:22 -05002023 fprintf(stderr, "Failed to leave unfinished write.\n");
2024 return false;
2025 }
David Benjaminbbba9392017-04-06 12:54:12 -04002026 pending_initial_write = true;
2027 } else if (config->shim_writes_first) {
Steven Valdeze831a812017-03-09 14:56:07 -05002028 if (WriteAll(ssl, kInitialWrite, strlen(kInitialWrite)) < 0) {
David Benjamin6c2563e2015-04-03 03:47:47 -04002029 return false;
2030 }
David Benjamine58c4f52014-08-24 03:47:07 -04002031 }
David Benjamin30789da2015-08-29 22:56:45 -04002032 if (!config->shim_shuts_down) {
2033 for (;;) {
David Benjamin2c99d282015-09-01 10:23:00 -04002034 // Read only 512 bytes at a time in TLS to ensure records may be
2035 // returned in multiple reads.
David Benjamine3fbb362017-01-06 16:19:28 -05002036 size_t read_size = config->is_dtls ? 16384 : 512;
2037 if (config->read_size > 0) {
2038 read_size = config->read_size;
2039 }
2040 std::unique_ptr<uint8_t[]> buf(new uint8_t[read_size]);
2041
Steven Valdeze831a812017-03-09 14:56:07 -05002042 int n = DoRead(ssl, buf.get(), read_size);
2043 int err = SSL_get_error(ssl, n);
David Benjamin30789da2015-08-29 22:56:45 -04002044 if (err == SSL_ERROR_ZERO_RETURN ||
2045 (n == 0 && err == SSL_ERROR_SYSCALL)) {
2046 if (n != 0) {
2047 fprintf(stderr, "Invalid SSL_get_error output\n");
2048 return false;
2049 }
2050 // Stop on either clean or unclean shutdown.
2051 break;
2052 } else if (err != SSL_ERROR_NONE) {
2053 if (n > 0) {
2054 fprintf(stderr, "Invalid SSL_get_error output\n");
2055 return false;
2056 }
2057 return false;
2058 }
2059 // Successfully read data.
2060 if (n <= 0) {
David Benjamin9a38e922015-01-22 16:06:11 -05002061 fprintf(stderr, "Invalid SSL_get_error output\n");
David Benjamin40f101b2015-02-20 11:23:42 -05002062 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05002063 }
David Benjamin30789da2015-08-29 22:56:45 -04002064
Steven Valdeze831a812017-03-09 14:56:07 -05002065 if (!config->is_server && is_resume && !is_retry &&
2066 config->expect_reject_early_data) {
2067 fprintf(stderr,
2068 "Unexpectedly received data instead of 0-RTT reject.\n");
2069 return false;
2070 }
2071
David Benjamin30789da2015-08-29 22:56:45 -04002072 // After a successful read, with or without False Start, the handshake
Steven Valdez681eb6a2016-12-19 13:19:29 -05002073 // must be complete unless we are doing early data.
Steven Valdeze831a812017-03-09 14:56:07 -05002074 if (!GetTestState(ssl)->handshake_done &&
2075 !SSL_early_data_accepted(ssl)) {
David Benjamin30789da2015-08-29 22:56:45 -04002076 fprintf(stderr, "handshake was not completed after SSL_read\n");
David Benjamin40f101b2015-02-20 11:23:42 -05002077 return false;
David Benjamin9a38e922015-01-22 16:06:11 -05002078 }
David Benjamin87e4acd2015-04-02 19:57:35 -04002079
David Benjaminbbba9392017-04-06 12:54:12 -04002080 // Clear the initial write, if unfinished.
2081 if (pending_initial_write) {
Steven Valdeze831a812017-03-09 14:56:07 -05002082 if (WriteAll(ssl, kInitialWrite, strlen(kInitialWrite)) < 0) {
David Benjaminbbba9392017-04-06 12:54:12 -04002083 return false;
2084 }
2085 pending_initial_write = false;
2086 }
2087
David Benjamin30789da2015-08-29 22:56:45 -04002088 for (int i = 0; i < n; i++) {
2089 buf[i] ^= 0xff;
2090 }
Steven Valdeze831a812017-03-09 14:56:07 -05002091 if (WriteAll(ssl, buf.get(), n) < 0) {
David Benjamin30789da2015-08-29 22:56:45 -04002092 return false;
2093 }
Kenny Root7fdeaf12014-08-05 15:23:37 -07002094 }
2095 }
David Benjamin025b3d32014-07-01 19:53:04 -04002096 }
2097
David Benjaminba4594a2015-06-18 18:36:15 -04002098 if (!config->is_server && !config->false_start &&
2099 !config->implicit_handshake &&
Steven Valdez1e6f11a2016-07-27 11:10:52 -04002100 // Session tickets are sent post-handshake in TLS 1.3.
Steven Valdeze831a812017-03-09 14:56:07 -05002101 GetProtocolVersion(ssl) < TLS1_3_VERSION &&
2102 GetTestState(ssl)->got_new_session) {
David Benjaminba4594a2015-06-18 18:36:15 -04002103 fprintf(stderr, "new session was established after the handshake\n");
2104 return false;
2105 }
2106
Steven Valdeze831a812017-03-09 14:56:07 -05002107 if (GetProtocolVersion(ssl) >= TLS1_3_VERSION && !config->is_server) {
Steven Valdez1e6f11a2016-07-27 11:10:52 -04002108 bool expect_new_session =
2109 !config->expect_no_session && !config->shim_shuts_down;
Steven Valdeze831a812017-03-09 14:56:07 -05002110 if (expect_new_session != GetTestState(ssl)->got_new_session) {
Steven Valdez1e6f11a2016-07-27 11:10:52 -04002111 fprintf(stderr,
2112 "new session was%s cached, but we expected the opposite\n",
Steven Valdeze831a812017-03-09 14:56:07 -05002113 GetTestState(ssl)->got_new_session ? "" : " not");
Steven Valdez1e6f11a2016-07-27 11:10:52 -04002114 return false;
2115 }
Steven Valdez08b65f42016-12-07 15:29:45 -05002116
2117 if (expect_new_session) {
2118 bool got_early_data_info =
Steven Valdeze831a812017-03-09 14:56:07 -05002119 GetTestState(ssl)->new_session->ticket_max_early_data != 0;
Steven Valdez08b65f42016-12-07 15:29:45 -05002120 if (config->expect_early_data_info != got_early_data_info) {
2121 fprintf(
2122 stderr,
2123 "new session did%s include ticket_early_data_info, but we expected "
2124 "the opposite\n",
2125 got_early_data_info ? "" : " not");
2126 return false;
2127 }
2128 }
Steven Valdez1e6f11a2016-07-27 11:10:52 -04002129 }
2130
David Benjamin1d5c83e2014-07-22 19:20:02 -04002131 if (out_session) {
Steven Valdeze831a812017-03-09 14:56:07 -05002132 *out_session = std::move(GetTestState(ssl)->new_session);
David Benjamin1d5c83e2014-07-22 19:20:02 -04002133 }
2134
Steven Valdeze831a812017-03-09 14:56:07 -05002135 ret = DoShutdown(ssl);
David Benjamin30789da2015-08-29 22:56:45 -04002136
2137 if (config->shim_shuts_down && config->check_close_notify) {
2138 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
2139 // it returns zero when our close_notify is sent, then one when the peer's
2140 // is received.
2141 if (ret != 0) {
2142 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
2143 return false;
2144 }
Steven Valdeze831a812017-03-09 14:56:07 -05002145 ret = DoShutdown(ssl);
David Benjamin30789da2015-08-29 22:56:45 -04002146 }
2147
2148 if (ret != 1) {
2149 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
2150 return false;
2151 }
2152
Steven Valdeze831a812017-03-09 14:56:07 -05002153 if (SSL_total_renegotiations(ssl) != config->expect_total_renegotiations) {
David Benjamin324dce42015-10-12 19:49:00 -04002154 fprintf(stderr, "Expected %d renegotiations, got %d\n",
Steven Valdeze831a812017-03-09 14:56:07 -05002155 config->expect_total_renegotiations, SSL_total_renegotiations(ssl));
David Benjamin324dce42015-10-12 19:49:00 -04002156 return false;
2157 }
2158
David Benjamin40f101b2015-02-20 11:23:42 -05002159 return true;
David Benjamin025b3d32014-07-01 19:53:04 -04002160}
David Benjamin1d5c83e2014-07-22 19:20:02 -04002161
David Benjaminff3a1492016-03-02 10:12:06 -05002162class StderrDelimiter {
2163 public:
2164 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
2165};
2166
David Benjaminaac1e2d2016-12-06 22:35:41 -05002167int main(int argc, char **argv) {
David Benjaminff3a1492016-03-02 10:12:06 -05002168 // To distinguish ASan's output from ours, add a trailing message to stderr.
2169 // Anything following this line will be considered an error.
2170 StderrDelimiter delimiter;
2171
David Benjamin87c8a642015-02-21 01:54:29 -05002172#if defined(OPENSSL_WINDOWS)
2173 /* Initialize Winsock. */
2174 WORD wsa_version = MAKEWORD(2, 2);
2175 WSADATA wsa_data;
2176 int wsa_err = WSAStartup(wsa_version, &wsa_data);
2177 if (wsa_err != 0) {
2178 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
2179 return 1;
2180 }
2181 if (wsa_data.wVersion != wsa_version) {
2182 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
2183 return 1;
2184 }
2185#else
David Benjamin1d5c83e2014-07-22 19:20:02 -04002186 signal(SIGPIPE, SIG_IGN);
Adam Langleyded93582014-07-31 15:23:51 -07002187#endif
David Benjamin1d5c83e2014-07-22 19:20:02 -04002188
David Benjamin7a1eefd2015-10-17 23:39:22 -04002189 CRYPTO_library_init();
David Benjamind9e07012015-02-09 03:04:34 -05002190 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
David Benjamin2d445c02015-02-09 13:03:50 -05002191 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
David Benjamin6c2563e2015-04-03 03:47:47 -04002192 if (g_config_index < 0 || g_state_index < 0) {
David Benjaminae3e4872014-11-18 21:52:26 -05002193 return 1;
2194 }
David Benjamin5a593af2014-08-11 19:51:50 -04002195
Steven Valdeze831a812017-03-09 14:56:07 -05002196 TestConfig initial_config, resume_config, retry_config;
2197 if (!ParseConfig(argc - 1, argv + 1, &initial_config, &resume_config,
2198 &retry_config)) {
David Benjaminc273d2c2015-02-09 12:59:46 -05002199 return Usage(argv[0]);
David Benjamin1d5c83e2014-07-22 19:20:02 -04002200 }
2201
Adam Langleyd519bf62016-12-12 11:16:44 -08002202 g_pool = CRYPTO_BUFFER_POOL_new();
2203
David Benjamin1b22f852016-10-27 16:36:32 -04002204 // Some code treats the zero time special, so initialize the clock to a
2205 // non-zero time.
2206 g_clock.tv_sec = 1234;
2207 g_clock.tv_usec = 1234;
2208
Steven Valdez873ebc92017-05-09 12:12:58 -04002209 bssl::UniquePtr<SSL_CTX> ssl_ctx;
David Benjamin1d5c83e2014-07-22 19:20:02 -04002210
Matt Braithwaited17d74d2016-08-17 20:10:28 -07002211 bssl::UniquePtr<SSL_SESSION> session;
Steven Valdez873ebc92017-05-09 12:12:58 -04002212 for (int i = 0; i < initial_config.resume_count + 1; i++) {
David Benjamin46662482016-08-17 00:51:00 -04002213 bool is_resume = i > 0;
Steven Valdez873ebc92017-05-09 12:12:58 -04002214 TestConfig *config = is_resume ? &resume_config : &initial_config;
2215 ssl_ctx = SetupCtx(ssl_ctx.get(), config);
2216 if (!ssl_ctx) {
2217 ERR_print_errors_fp(stderr);
2218 return 1;
2219 }
2220
2221 if (is_resume && !initial_config.is_server && !session) {
David Benjamin46662482016-08-17 00:51:00 -04002222 fprintf(stderr, "No session to offer.\n");
2223 return 1;
2224 }
David Benjamin1d5c83e2014-07-22 19:20:02 -04002225
Matt Braithwaited17d74d2016-08-17 20:10:28 -07002226 bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
Steven Valdeze831a812017-03-09 14:56:07 -05002227 if (!DoConnection(&session, ssl_ctx.get(), config, &retry_config, is_resume,
2228 offer_session.get())) {
David Benjamin46662482016-08-17 00:51:00 -04002229 fprintf(stderr, "Connection %d failed.\n", i + 1);
2230 ERR_print_errors_fp(stderr);
2231 return 1;
2232 }
Steven Valdeza833c352016-11-01 13:39:36 -04002233
Steven Valdez873ebc92017-05-09 12:12:58 -04002234 if (config->resumption_delay != 0) {
2235 g_clock.tv_sec += config->resumption_delay;
Steven Valdeza833c352016-11-01 13:39:36 -04002236 }
David Benjamin1d5c83e2014-07-22 19:20:02 -04002237 }
2238
David Benjamina7f333d2015-02-09 02:37:18 -05002239 return 0;
David Benjamin1d5c83e2014-07-22 19:20:02 -04002240}