blob: 5790dc3f0d627d6c7696a61b298064171fd94d32 [file] [log] [blame]
Adam Langleyd9e397b2015-01-22 14:27:53 -08001/* Copyright (c) 2014, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
Adam Langley4139edb2016-01-13 15:00:54 -080015#if !defined(__STDC_FORMAT_MACROS)
16#define __STDC_FORMAT_MACROS
17#endif
18
Adam Langleyd9e397b2015-01-22 14:27:53 -080019#include <openssl/base.h>
20
21#if !defined(OPENSSL_WINDOWS)
22#include <arpa/inet.h>
23#include <netinet/in.h>
Adam Langleye9ada862015-05-11 17:20:37 -070024#include <netinet/tcp.h>
Adam Langleyd9e397b2015-01-22 14:27:53 -080025#include <signal.h>
26#include <sys/socket.h>
Adam Langley4139edb2016-01-13 15:00:54 -080027#include <sys/time.h>
Adam Langleyd9e397b2015-01-22 14:27:53 -080028#include <unistd.h>
Adam Langleye9ada862015-05-11 17:20:37 -070029#else
30#include <io.h>
David Benjamin6e899c72016-06-09 18:02:18 -040031OPENSSL_MSVC_PRAGMA(warning(push, 3))
Adam Langleye9ada862015-05-11 17:20:37 -070032#include <winsock2.h>
33#include <ws2tcpip.h>
David Benjamin6e899c72016-06-09 18:02:18 -040034OPENSSL_MSVC_PRAGMA(warning(pop))
Adam Langleye9ada862015-05-11 17:20:37 -070035
David Benjamin95add822016-10-19 01:09:12 -040036OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
Adam Langleyd9e397b2015-01-22 14:27:53 -080037#endif
38
David Benjamin6e899c72016-06-09 18:02:18 -040039#include <assert.h>
Adam Langley4139edb2016-01-13 15:00:54 -080040#include <inttypes.h>
Adam Langleyd9e397b2015-01-22 14:27:53 -080041#include <string.h>
Robert Sloana12bf462017-07-17 07:08:26 -070042#include <time.h>
Adam Langleyd9e397b2015-01-22 14:27:53 -080043
Steven Valdez909b19f2016-11-21 15:35:44 -050044#include <openssl/aead.h>
Adam Langleyd9e397b2015-01-22 14:27:53 -080045#include <openssl/bio.h>
46#include <openssl/buf.h>
47#include <openssl/bytestring.h>
Kenny Rootb8494592015-09-25 02:29:14 +000048#include <openssl/cipher.h>
Kenny Roote99801b2015-11-06 15:31:15 -080049#include <openssl/crypto.h>
David Benjaminf0c4a6c2016-08-11 13:26:41 -040050#include <openssl/digest.h>
Adam Langleye9ada862015-05-11 17:20:37 -070051#include <openssl/err.h>
David Benjaminf0c4a6c2016-08-11 13:26:41 -040052#include <openssl/evp.h>
Kenny Rootb8494592015-09-25 02:29:14 +000053#include <openssl/hmac.h>
David Benjamin4969cc92016-04-22 15:02:23 -040054#include <openssl/nid.h>
Kenny Rootb8494592015-09-25 02:29:14 +000055#include <openssl/rand.h>
Adam Langleyd9e397b2015-01-22 14:27:53 -080056#include <openssl/ssl.h>
David Benjaminf0c4a6c2016-08-11 13:26:41 -040057#include <openssl/x509.h>
Adam Langleyd9e397b2015-01-22 14:27:53 -080058
Robert Sloan36272962017-10-23 10:28:39 -070059#include <functional>
Adam Langleye9ada862015-05-11 17:20:37 -070060#include <memory>
Kenny Rootb8494592015-09-25 02:29:14 +000061#include <string>
Adam Langleye9ada862015-05-11 17:20:37 -070062#include <vector>
63
David Benjaminf0c4a6c2016-08-11 13:26:41 -040064#include "../../crypto/internal.h"
Robert Sloan8ff03552017-06-14 12:40:58 -070065#include "../internal.h"
Adam Langleyd9e397b2015-01-22 14:27:53 -080066#include "async_bio.h"
Robert Sloand1d118f2017-09-11 09:00:48 -070067#include "fuzzer_tags.h"
Adam Langleyd9e397b2015-01-22 14:27:53 -080068#include "packeted_bio.h"
69#include "test_config.h"
70
Adam Langleye9ada862015-05-11 17:20:37 -070071
Steven Valdeze7531f02016-12-14 13:29:57 -050072static CRYPTO_BUFFER_POOL *g_pool = nullptr;
73
Adam Langleye9ada862015-05-11 17:20:37 -070074#if !defined(OPENSSL_WINDOWS)
75static int closesocket(int sock) {
76 return close(sock);
77}
78
79static void PrintSocketError(const char *func) {
80 perror(func);
81}
82#else
83static void PrintSocketError(const char *func) {
84 fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
85}
86#endif
87
88static int Usage(const char *program) {
89 fprintf(stderr, "Usage: %s [flags...]\n", program);
Adam Langleyd9e397b2015-01-22 14:27:53 -080090 return 1;
91}
92
Adam Langleye9ada862015-05-11 17:20:37 -070093struct TestState {
Adam Langleye9ada862015-05-11 17:20:37 -070094 // async_bio is async BIO which pauses reads and writes.
95 BIO *async_bio = nullptr;
David Benjamin6e899c72016-06-09 18:02:18 -040096 // packeted_bio is the packeted BIO which simulates read timeouts.
97 BIO *packeted_bio = nullptr;
David Benjaminf0c4a6c2016-08-11 13:26:41 -040098 bssl::UniquePtr<EVP_PKEY> channel_id;
Adam Langleye9ada862015-05-11 17:20:37 -070099 bool cert_ready = false;
David Benjaminf0c4a6c2016-08-11 13:26:41 -0400100 bssl::UniquePtr<SSL_SESSION> session;
101 bssl::UniquePtr<SSL_SESSION> pending_session;
Adam Langleye9ada862015-05-11 17:20:37 -0700102 bool early_callback_called = false;
103 bool handshake_done = false;
Kenny Rootb8494592015-09-25 02:29:14 +0000104 // private_key is the underlying private key used when testing custom keys.
David Benjaminf0c4a6c2016-08-11 13:26:41 -0400105 bssl::UniquePtr<EVP_PKEY> private_key;
Kenny Roote99801b2015-11-06 15:31:15 -0800106 std::vector<uint8_t> private_key_result;
107 // private_key_retries is the number of times an asynchronous private key
108 // operation has been retried.
109 unsigned private_key_retries = 0;
Kenny Rootb8494592015-09-25 02:29:14 +0000110 bool got_new_session = false;
David Benjaminf0c4a6c2016-08-11 13:26:41 -0400111 bssl::UniquePtr<SSL_SESSION> new_session;
David Benjaminc895d6b2016-08-11 13:26:41 -0400112 bool ticket_decrypt_done = false;
113 bool alpn_select_done = false;
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700114 bool is_resume = false;
David Benjaminf31229b2017-01-25 14:08:15 -0500115 bool early_callback_ready = false;
Robert Sloanb6d070c2017-07-24 08:40:01 -0700116 bool custom_verify_ready = false;
Robert Sloanfe7cd212017-08-07 09:03:39 -0700117 std::string msg_callback_text;
118 bool msg_callback_ok = true;
Robert Sloana27a6a42017-09-05 08:39:28 -0700119 // cert_verified is true if certificate verification has been driven to
120 // completion. This tests that the callback is not called again after this.
Robert Sloan8f860b12017-08-28 07:37:06 -0700121 bool cert_verified = false;
Adam Langleye9ada862015-05-11 17:20:37 -0700122};
123
124static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
Kenny Rootb8494592015-09-25 02:29:14 +0000125 int index, long argl, void *argp) {
Adam Langleye9ada862015-05-11 17:20:37 -0700126 delete ((TestState *)ptr);
127}
128
129static int g_config_index = 0;
130static int g_state_index = 0;
Adam Langleyd9e397b2015-01-22 14:27:53 -0800131
David Benjamind316cba2016-06-02 16:17:39 -0400132static bool SetTestConfig(SSL *ssl, const TestConfig *config) {
Adam Langleye9ada862015-05-11 17:20:37 -0700133 return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
Adam Langleyd9e397b2015-01-22 14:27:53 -0800134}
135
David Benjamind316cba2016-06-02 16:17:39 -0400136static const TestConfig *GetTestConfig(const SSL *ssl) {
Adam Langleye9ada862015-05-11 17:20:37 -0700137 return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
Adam Langleyd9e397b2015-01-22 14:27:53 -0800138}
139
Adam Langley4139edb2016-01-13 15:00:54 -0800140static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
141 // |SSL_set_ex_data| takes ownership of |state| only on success.
142 if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
143 state.release();
Adam Langleye9ada862015-05-11 17:20:37 -0700144 return true;
Adam Langleyd9e397b2015-01-22 14:27:53 -0800145 }
Adam Langleye9ada862015-05-11 17:20:37 -0700146 return false;
147}
148
149static TestState *GetTestState(const SSL *ssl) {
150 return (TestState *)SSL_get_ex_data(ssl, g_state_index);
151}
152
Robert Sloan8542c082018-02-05 09:07:34 -0800153static bool MoveExData(SSL *dest, SSL *src) {
154 TestState *state = GetTestState(src);
155 const TestConfig *config = GetTestConfig(src);
156 if (!SSL_set_ex_data(src, g_state_index, nullptr) ||
157 !SSL_set_ex_data(dest, g_state_index, state) ||
158 !SSL_set_ex_data(src, g_config_index, nullptr) ||
159 !SSL_set_ex_data(dest, g_config_index, (void *) config)) {
160 return false;
161 }
162
163 return true;
164}
165
166static void MoveBIOs(SSL *dest, SSL *src) {
167 BIO *rbio = SSL_get_rbio(src);
168 BIO_up_ref(rbio);
169 SSL_set0_rbio(dest, rbio);
170
171 BIO *wbio = SSL_get_wbio(src);
172 BIO_up_ref(wbio);
173 SSL_set0_wbio(dest, wbio);
174
175 SSL_set0_rbio(src, nullptr);
176 SSL_set0_wbio(src, nullptr);
177}
178
Steven Valdez909b19f2016-11-21 15:35:44 -0500179static bool LoadCertificate(bssl::UniquePtr<X509> *out_x509,
180 bssl::UniquePtr<STACK_OF(X509)> *out_chain,
181 const std::string &file) {
David Benjaminf0c4a6c2016-08-11 13:26:41 -0400182 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
David Benjamin4969cc92016-04-22 15:02:23 -0400183 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
Steven Valdez909b19f2016-11-21 15:35:44 -0500184 return false;
David Benjamin4969cc92016-04-22 15:02:23 -0400185 }
Steven Valdez909b19f2016-11-21 15:35:44 -0500186
187 out_x509->reset(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
188 if (!*out_x509) {
189 return false;
190 }
191
192 out_chain->reset(sk_X509_new_null());
193 if (!*out_chain) {
194 return false;
195 }
196
197 // Keep reading the certificate chain.
198 for (;;) {
199 bssl::UniquePtr<X509> cert(
200 PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
201 if (!cert) {
202 break;
203 }
204
205 if (!sk_X509_push(out_chain->get(), cert.get())) {
206 return false;
207 }
208 cert.release(); // sk_X509_push takes ownership.
209 }
210
211 uint32_t err = ERR_peek_last_error();
212 if (ERR_GET_LIB(err) != ERR_LIB_PEM ||
213 ERR_GET_REASON(err) != PEM_R_NO_START_LINE) {
214 return false;
215}
216
217 ERR_clear_error();
218 return true;
David Benjamin4969cc92016-04-22 15:02:23 -0400219}
220
David Benjaminf0c4a6c2016-08-11 13:26:41 -0400221static bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
222 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
Adam Langleye9ada862015-05-11 17:20:37 -0700223 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
224 return nullptr;
Adam Langleyd9e397b2015-01-22 14:27:53 -0800225 }
David Benjaminf0c4a6c2016-08-11 13:26:41 -0400226 return bssl::UniquePtr<EVP_PKEY>(
227 PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
Adam Langleyd9e397b2015-01-22 14:27:53 -0800228}
229
Robert Sloan7d422bc2017-03-06 10:04:29 -0800230static bool FromHexDigit(uint8_t *out, char c) {
231 if ('0' <= c && c <= '9') {
232 *out = c - '0';
233 return true;
234 }
235 if ('a' <= c && c <= 'f') {
236 *out = c - 'a' + 10;
237 return true;
238 }
239 if ('A' <= c && c <= 'F') {
240 *out = c - 'A' + 10;
241 return true;
242 }
243 return false;
244}
245
246static bool HexDecode(std::string *out, const std::string &in) {
247 if ((in.size() & 1) != 0) {
248 return false;
249 }
250
251 std::unique_ptr<uint8_t[]> buf(new uint8_t[in.size() / 2]);
252 for (size_t i = 0; i < in.size() / 2; i++) {
253 uint8_t high, low;
254 if (!FromHexDigit(&high, in[i*2]) ||
255 !FromHexDigit(&low, in[i*2+1])) {
256 return false;
257 }
258 buf[i] = (high << 4) | low;
259 }
260
261 out->assign(reinterpret_cast<const char *>(buf.get()), in.size() / 2);
262 return true;
263}
264
265static std::vector<std::string> SplitParts(const std::string &in,
266 const char delim) {
267 std::vector<std::string> ret;
268 size_t start = 0;
269
270 for (size_t i = 0; i < in.size(); i++) {
271 if (in[i] == delim) {
272 ret.push_back(in.substr(start, i - start));
273 start = i + 1;
274 }
275 }
276
277 ret.push_back(in.substr(start, std::string::npos));
278 return ret;
279}
280
281static std::vector<std::string> DecodeHexStrings(
282 const std::string &hex_strings) {
283 std::vector<std::string> ret;
284 const std::vector<std::string> parts = SplitParts(hex_strings, ',');
285
286 for (const auto &part : parts) {
287 std::string binary;
288 if (!HexDecode(&binary, part)) {
289 fprintf(stderr, "Bad hex string: %s\n", part.c_str());
290 return ret;
291 }
292
293 ret.push_back(binary);
294 }
295
296 return ret;
297}
298
299static bssl::UniquePtr<STACK_OF(X509_NAME)> DecodeHexX509Names(
300 const std::string &hex_names) {
301 const std::vector<std::string> der_names = DecodeHexStrings(hex_names);
302 bssl::UniquePtr<STACK_OF(X509_NAME)> ret(sk_X509_NAME_new_null());
Robert Sloane56da3e2017-06-26 08:26:42 -0700303 if (!ret) {
304 return nullptr;
305 }
Robert Sloan7d422bc2017-03-06 10:04:29 -0800306
307 for (const auto &der_name : der_names) {
308 const uint8_t *const data =
309 reinterpret_cast<const uint8_t *>(der_name.data());
310 const uint8_t *derp = data;
311 bssl::UniquePtr<X509_NAME> name(
312 d2i_X509_NAME(nullptr, &derp, der_name.size()));
313 if (!name || derp != data + der_name.size()) {
314 fprintf(stderr, "Failed to parse X509_NAME.\n");
315 return nullptr;
316 }
317
318 if (!sk_X509_NAME_push(ret.get(), name.get())) {
319 return nullptr;
320 }
321 name.release();
322 }
323
324 return ret;
325}
326
Kenny Rootb8494592015-09-25 02:29:14 +0000327static ssl_private_key_result_t AsyncPrivateKeySign(
328 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
David Benjaminc895d6b2016-08-11 13:26:41 -0400329 uint16_t signature_algorithm, const uint8_t *in, size_t in_len) {
Kenny Rootb8494592015-09-25 02:29:14 +0000330 TestState *test_state = GetTestState(ssl);
Kenny Roote99801b2015-11-06 15:31:15 -0800331 if (!test_state->private_key_result.empty()) {
Kenny Rootb8494592015-09-25 02:29:14 +0000332 fprintf(stderr, "AsyncPrivateKeySign called with operation pending.\n");
333 abort();
334 }
335
David Benjaminc895d6b2016-08-11 13:26:41 -0400336 // Determine the hash.
337 const EVP_MD *md;
338 switch (signature_algorithm) {
339 case SSL_SIGN_RSA_PKCS1_SHA1:
340 case SSL_SIGN_ECDSA_SHA1:
341 md = EVP_sha1();
342 break;
343 case SSL_SIGN_RSA_PKCS1_SHA256:
344 case SSL_SIGN_ECDSA_SECP256R1_SHA256:
345 case SSL_SIGN_RSA_PSS_SHA256:
346 md = EVP_sha256();
347 break;
348 case SSL_SIGN_RSA_PKCS1_SHA384:
349 case SSL_SIGN_ECDSA_SECP384R1_SHA384:
350 case SSL_SIGN_RSA_PSS_SHA384:
351 md = EVP_sha384();
352 break;
353 case SSL_SIGN_RSA_PKCS1_SHA512:
354 case SSL_SIGN_ECDSA_SECP521R1_SHA512:
355 case SSL_SIGN_RSA_PSS_SHA512:
356 md = EVP_sha512();
357 break;
358 case SSL_SIGN_RSA_PKCS1_MD5_SHA1:
359 md = EVP_md5_sha1();
360 break;
Robert Sloan572a4e22017-04-17 10:52:19 -0700361 case SSL_SIGN_ED25519:
362 md = nullptr;
363 break;
David Benjaminc895d6b2016-08-11 13:26:41 -0400364 default:
365 fprintf(stderr, "Unknown signature algorithm %04x.\n",
366 signature_algorithm);
367 return ssl_private_key_failure;
368 }
369
Robert Sloan8ff03552017-06-14 12:40:58 -0700370 bssl::ScopedEVP_MD_CTX ctx;
371 EVP_PKEY_CTX *pctx;
372 if (!EVP_DigestSignInit(ctx.get(), &pctx, md, nullptr,
373 test_state->private_key.get())) {
Kenny Rootb8494592015-09-25 02:29:14 +0000374 return ssl_private_key_failure;
375 }
376
David Benjaminc895d6b2016-08-11 13:26:41 -0400377 // Configure additional signature parameters.
378 switch (signature_algorithm) {
379 case SSL_SIGN_RSA_PSS_SHA256:
380 case SSL_SIGN_RSA_PSS_SHA384:
381 case SSL_SIGN_RSA_PSS_SHA512:
Robert Sloan8ff03552017-06-14 12:40:58 -0700382 if (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) ||
383 !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
David Benjaminc895d6b2016-08-11 13:26:41 -0400384 -1 /* salt len = hash len */)) {
385 return ssl_private_key_failure;
386 }
387 }
388
Kenny Rootb8494592015-09-25 02:29:14 +0000389 // Write the signature into |test_state|.
390 size_t len = 0;
Robert Sloan8ff03552017-06-14 12:40:58 -0700391 if (!EVP_DigestSign(ctx.get(), nullptr, &len, in, in_len)) {
Kenny Rootb8494592015-09-25 02:29:14 +0000392 return ssl_private_key_failure;
393 }
Kenny Roote99801b2015-11-06 15:31:15 -0800394 test_state->private_key_result.resize(len);
Robert Sloan8ff03552017-06-14 12:40:58 -0700395 if (!EVP_DigestSign(ctx.get(), test_state->private_key_result.data(), &len,
396 in, in_len)) {
Kenny Rootb8494592015-09-25 02:29:14 +0000397 return ssl_private_key_failure;
398 }
Kenny Roote99801b2015-11-06 15:31:15 -0800399 test_state->private_key_result.resize(len);
Kenny Rootb8494592015-09-25 02:29:14 +0000400
David Benjaminc895d6b2016-08-11 13:26:41 -0400401 // The signature will be released asynchronously in |AsyncPrivateKeyComplete|.
Kenny Rootb8494592015-09-25 02:29:14 +0000402 return ssl_private_key_retry;
403}
404
Kenny Roote99801b2015-11-06 15:31:15 -0800405static ssl_private_key_result_t AsyncPrivateKeyDecrypt(
406 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
407 const uint8_t *in, size_t in_len) {
408 TestState *test_state = GetTestState(ssl);
409 if (!test_state->private_key_result.empty()) {
410 fprintf(stderr,
411 "AsyncPrivateKeyDecrypt called with operation pending.\n");
412 abort();
413 }
414
Adam Langley4139edb2016-01-13 15:00:54 -0800415 RSA *rsa = EVP_PKEY_get0_RSA(test_state->private_key.get());
416 if (rsa == NULL) {
Kenny Roote99801b2015-11-06 15:31:15 -0800417 fprintf(stderr,
418 "AsyncPrivateKeyDecrypt called with incorrect key type.\n");
419 abort();
420 }
Kenny Roote99801b2015-11-06 15:31:15 -0800421 test_state->private_key_result.resize(RSA_size(rsa));
Adam Langley4139edb2016-01-13 15:00:54 -0800422 if (!RSA_decrypt(rsa, out_len, test_state->private_key_result.data(),
Kenny Roote99801b2015-11-06 15:31:15 -0800423 RSA_size(rsa), in, in_len, RSA_NO_PADDING)) {
424 return ssl_private_key_failure;
425 }
426
427 test_state->private_key_result.resize(*out_len);
428
David Benjaminc895d6b2016-08-11 13:26:41 -0400429 // The decryption will be released asynchronously in |AsyncPrivateComplete|.
Kenny Roote99801b2015-11-06 15:31:15 -0800430 return ssl_private_key_retry;
431}
432
David Benjaminc895d6b2016-08-11 13:26:41 -0400433static ssl_private_key_result_t AsyncPrivateKeyComplete(
Kenny Roote99801b2015-11-06 15:31:15 -0800434 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
435 TestState *test_state = GetTestState(ssl);
436 if (test_state->private_key_result.empty()) {
437 fprintf(stderr,
David Benjaminc895d6b2016-08-11 13:26:41 -0400438 "AsyncPrivateKeyComplete called without operation pending.\n");
Kenny Roote99801b2015-11-06 15:31:15 -0800439 abort();
440 }
441
442 if (test_state->private_key_retries < 2) {
443 // Only return the decryption on the second attempt, to test both incomplete
444 // |decrypt| and |decrypt_complete|.
445 return ssl_private_key_retry;
446 }
447
448 if (max_out < test_state->private_key_result.size()) {
449 fprintf(stderr, "Output buffer too small.\n");
450 return ssl_private_key_failure;
451 }
Robert Sloan69939df2017-01-09 10:53:07 -0800452 OPENSSL_memcpy(out, test_state->private_key_result.data(),
453 test_state->private_key_result.size());
Kenny Roote99801b2015-11-06 15:31:15 -0800454 *out_len = test_state->private_key_result.size();
455
456 test_state->private_key_result.clear();
457 test_state->private_key_retries = 0;
Kenny Rootb8494592015-09-25 02:29:14 +0000458 return ssl_private_key_success;
459}
460
461static const SSL_PRIVATE_KEY_METHOD g_async_private_key_method = {
Kenny Rootb8494592015-09-25 02:29:14 +0000462 AsyncPrivateKeySign,
Kenny Roote99801b2015-11-06 15:31:15 -0800463 AsyncPrivateKeyDecrypt,
David Benjaminc895d6b2016-08-11 13:26:41 -0400464 AsyncPrivateKeyComplete,
Kenny Rootb8494592015-09-25 02:29:14 +0000465};
466
467template<typename T>
468struct Free {
469 void operator()(T *buf) {
470 free(buf);
471 }
472};
473
David Benjaminf0c4a6c2016-08-11 13:26:41 -0400474static bool GetCertificate(SSL *ssl, bssl::UniquePtr<X509> *out_x509,
Steven Valdez909b19f2016-11-21 15:35:44 -0500475 bssl::UniquePtr<STACK_OF(X509)> *out_chain,
David Benjaminf0c4a6c2016-08-11 13:26:41 -0400476 bssl::UniquePtr<EVP_PKEY> *out_pkey) {
David Benjamind316cba2016-06-02 16:17:39 -0400477 const TestConfig *config = GetTestConfig(ssl);
Kenny Rootb8494592015-09-25 02:29:14 +0000478
David Benjaminc895d6b2016-08-11 13:26:41 -0400479 if (!config->signing_prefs.empty()) {
480 std::vector<uint16_t> u16s(config->signing_prefs.begin(),
481 config->signing_prefs.end());
482 if (!SSL_set_signing_algorithm_prefs(ssl, u16s.data(), u16s.size())) {
483 return false;
484 }
485 }
486
Kenny Rootb8494592015-09-25 02:29:14 +0000487 if (!config->key_file.empty()) {
David Benjamin4969cc92016-04-22 15:02:23 -0400488 *out_pkey = LoadPrivateKey(config->key_file.c_str());
489 if (!*out_pkey) {
Kenny Rootb8494592015-09-25 02:29:14 +0000490 return false;
491 }
Adam Langleye9ada862015-05-11 17:20:37 -0700492 }
Steven Valdez909b19f2016-11-21 15:35:44 -0500493 if (!config->cert_file.empty() &&
494 !LoadCertificate(out_x509, out_chain, config->cert_file.c_str())) {
495 return false;
Adam Langleye9ada862015-05-11 17:20:37 -0700496 }
Kenny Rootb8494592015-09-25 02:29:14 +0000497 if (!config->ocsp_response.empty() &&
Steven Valdeze7531f02016-12-14 13:29:57 -0500498 !SSL_set_ocsp_response(ssl, (const uint8_t *)config->ocsp_response.data(),
499 config->ocsp_response.size())) {
Kenny Rootb8494592015-09-25 02:29:14 +0000500 return false;
501 }
Adam Langleye9ada862015-05-11 17:20:37 -0700502 return true;
503}
504
David Benjamin4969cc92016-04-22 15:02:23 -0400505static bool InstallCertificate(SSL *ssl) {
David Benjaminf0c4a6c2016-08-11 13:26:41 -0400506 bssl::UniquePtr<X509> x509;
Steven Valdez909b19f2016-11-21 15:35:44 -0500507 bssl::UniquePtr<STACK_OF(X509)> chain;
David Benjaminf0c4a6c2016-08-11 13:26:41 -0400508 bssl::UniquePtr<EVP_PKEY> pkey;
Steven Valdez909b19f2016-11-21 15:35:44 -0500509 if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
David Benjamin4969cc92016-04-22 15:02:23 -0400510 return false;
511 }
512
513 if (pkey) {
514 TestState *test_state = GetTestState(ssl);
David Benjamind316cba2016-06-02 16:17:39 -0400515 const TestConfig *config = GetTestConfig(ssl);
David Benjamin4969cc92016-04-22 15:02:23 -0400516 if (config->async) {
517 test_state->private_key = std::move(pkey);
518 SSL_set_private_key_method(ssl, &g_async_private_key_method);
519 } else if (!SSL_use_PrivateKey(ssl, pkey.get())) {
520 return false;
521 }
522 }
523
524 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
525 return false;
526 }
527
Steven Valdez909b19f2016-11-21 15:35:44 -0500528 if (sk_X509_num(chain.get()) > 0 &&
529 !SSL_set1_chain(ssl, chain.get())) {
530 return false;
531 }
532
David Benjamin4969cc92016-04-22 15:02:23 -0400533 return true;
534}
535
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700536static enum ssl_select_cert_result_t SelectCertificateCallback(
537 const SSL_CLIENT_HELLO *client_hello) {
David Benjamin1b249672016-12-06 18:25:50 -0500538 const TestConfig *config = GetTestConfig(client_hello->ssl);
539 GetTestState(client_hello->ssl)->early_callback_called = true;
Adam Langleye9ada862015-05-11 17:20:37 -0700540
541 if (!config->expected_server_name.empty()) {
542 const uint8_t *extension_data;
543 size_t extension_len;
544 CBS extension, server_name_list, host_name;
545 uint8_t name_type;
546
David Benjamin1b249672016-12-06 18:25:50 -0500547 if (!SSL_early_callback_ctx_extension_get(
548 client_hello, TLSEXT_TYPE_server_name, &extension_data,
549 &extension_len)) {
Adam Langleye9ada862015-05-11 17:20:37 -0700550 fprintf(stderr, "Could not find server_name extension.\n");
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700551 return ssl_select_cert_error;
Adam Langleye9ada862015-05-11 17:20:37 -0700552 }
553
554 CBS_init(&extension, extension_data, extension_len);
555 if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
556 CBS_len(&extension) != 0 ||
557 !CBS_get_u8(&server_name_list, &name_type) ||
558 name_type != TLSEXT_NAMETYPE_host_name ||
559 !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
560 CBS_len(&server_name_list) != 0) {
561 fprintf(stderr, "Could not decode server_name extension.\n");
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700562 return ssl_select_cert_error;
Adam Langleye9ada862015-05-11 17:20:37 -0700563 }
564
565 if (!CBS_mem_equal(&host_name,
566 (const uint8_t*)config->expected_server_name.data(),
567 config->expected_server_name.size())) {
568 fprintf(stderr, "Server name mismatch.\n");
569 }
570 }
571
572 if (config->fail_early_callback) {
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700573 return ssl_select_cert_error;
Adam Langleye9ada862015-05-11 17:20:37 -0700574 }
575
576 // Install the certificate in the early callback.
577 if (config->use_early_callback) {
David Benjaminf31229b2017-01-25 14:08:15 -0500578 bool early_callback_ready =
579 GetTestState(client_hello->ssl)->early_callback_ready;
580 if (config->async && !early_callback_ready) {
Adam Langleye9ada862015-05-11 17:20:37 -0700581 // Install the certificate asynchronously.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700582 return ssl_select_cert_retry;
Adam Langleye9ada862015-05-11 17:20:37 -0700583 }
David Benjamin1b249672016-12-06 18:25:50 -0500584 if (!InstallCertificate(client_hello->ssl)) {
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700585 return ssl_select_cert_error;
Adam Langleye9ada862015-05-11 17:20:37 -0700586 }
587 }
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700588 return ssl_select_cert_success;
Adam Langleye9ada862015-05-11 17:20:37 -0700589}
590
Steven Valdeze7531f02016-12-14 13:29:57 -0500591static bool CheckCertificateRequest(SSL *ssl) {
592 const TestConfig *config = GetTestConfig(ssl);
593
594 if (!config->expected_certificate_types.empty()) {
595 const uint8_t *certificate_types;
596 size_t certificate_types_len =
597 SSL_get0_certificate_types(ssl, &certificate_types);
598 if (certificate_types_len != config->expected_certificate_types.size() ||
Robert Sloan69939df2017-01-09 10:53:07 -0800599 OPENSSL_memcmp(certificate_types,
600 config->expected_certificate_types.data(),
601 certificate_types_len) != 0) {
Steven Valdeze7531f02016-12-14 13:29:57 -0500602 fprintf(stderr, "certificate types mismatch\n");
603 return false;
604 }
605 }
606
Robert Sloan7d422bc2017-03-06 10:04:29 -0800607 if (!config->expected_client_ca_list.empty()) {
608 bssl::UniquePtr<STACK_OF(X509_NAME)> expected =
609 DecodeHexX509Names(config->expected_client_ca_list);
610 const size_t num_expected = sk_X509_NAME_num(expected.get());
611
612 const STACK_OF(X509_NAME) *received = SSL_get_client_CA_list(ssl);
613 const size_t num_received = sk_X509_NAME_num(received);
614
615 if (num_received != num_expected) {
616 fprintf(stderr, "expected %u names in CertificateRequest but got %u\n",
617 static_cast<unsigned>(num_expected),
618 static_cast<unsigned>(num_received));
619 return false;
620 }
621
622 for (size_t i = 0; i < num_received; i++) {
623 if (X509_NAME_cmp(sk_X509_NAME_value(received, i),
624 sk_X509_NAME_value(expected.get(), i)) != 0) {
625 fprintf(stderr, "names in CertificateRequest differ at index #%d\n",
626 static_cast<unsigned>(i));
627 return false;
628 }
629 }
630
631 STACK_OF(CRYPTO_BUFFER) *buffers = SSL_get0_server_requested_CAs(ssl);
632 if (sk_CRYPTO_BUFFER_num(buffers) != num_received) {
633 fprintf(stderr,
634 "Mismatch between SSL_get_server_requested_CAs and "
635 "SSL_get_client_CA_list.\n");
636 return false;
637 }
638 }
639
Steven Valdeze7531f02016-12-14 13:29:57 -0500640 return true;
641}
642
David Benjamin4969cc92016-04-22 15:02:23 -0400643static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
Steven Valdeze7531f02016-12-14 13:29:57 -0500644 if (!CheckCertificateRequest(ssl)) {
645 return -1;
646 }
647
David Benjamind316cba2016-06-02 16:17:39 -0400648 if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
David Benjamin4969cc92016-04-22 15:02:23 -0400649 return -1;
650 }
651
David Benjaminf0c4a6c2016-08-11 13:26:41 -0400652 bssl::UniquePtr<X509> x509;
Steven Valdez909b19f2016-11-21 15:35:44 -0500653 bssl::UniquePtr<STACK_OF(X509)> chain;
David Benjaminf0c4a6c2016-08-11 13:26:41 -0400654 bssl::UniquePtr<EVP_PKEY> pkey;
Steven Valdez909b19f2016-11-21 15:35:44 -0500655 if (!GetCertificate(ssl, &x509, &chain, &pkey)) {
David Benjamin4969cc92016-04-22 15:02:23 -0400656 return -1;
657 }
658
659 // Return zero for no certificate.
660 if (!x509) {
661 return 0;
662 }
663
Steven Valdez909b19f2016-11-21 15:35:44 -0500664 // Chains and asynchronous private keys are not supported with client_cert_cb.
David Benjamin4969cc92016-04-22 15:02:23 -0400665 *out_x509 = x509.release();
666 *out_pkey = pkey.release();
667 return 1;
668}
669
Steven Valdeze7531f02016-12-14 13:29:57 -0500670static int CertCallback(SSL *ssl, void *arg) {
671 const TestConfig *config = GetTestConfig(ssl);
672
673 // Check the CertificateRequest metadata is as expected.
674 if (!SSL_is_server(ssl) && !CheckCertificateRequest(ssl)) {
675 return -1;
676 }
677
678 if (config->fail_cert_callback) {
679 return 0;
680 }
681
682 // The certificate will be installed via other means.
683 if (!config->async || config->use_early_callback) {
684 return 1;
685 }
686
687 if (!GetTestState(ssl)->cert_ready) {
688 return -1;
689 }
690 if (!InstallCertificate(ssl)) {
691 return 0;
692 }
693 return 1;
694}
695
Robert Sloanb6d070c2017-07-24 08:40:01 -0700696static bool CheckVerifyCallback(SSL *ssl) {
David Benjamind316cba2016-06-02 16:17:39 -0400697 const TestConfig *config = GetTestConfig(ssl);
Kenny Rootb8494592015-09-25 02:29:14 +0000698 if (!config->expected_ocsp_response.empty()) {
699 const uint8_t *data;
700 size_t len;
701 SSL_get0_ocsp_response(ssl, &data, &len);
702 if (len == 0) {
703 fprintf(stderr, "OCSP response not available in verify callback\n");
Robert Sloanb6d070c2017-07-24 08:40:01 -0700704 return false;
Kenny Rootb8494592015-09-25 02:29:14 +0000705 }
706 }
707
Robert Sloan8f860b12017-08-28 07:37:06 -0700708 if (GetTestState(ssl)->cert_verified) {
709 fprintf(stderr, "Certificate verified twice.\n");
710 return false;
711 }
712
Robert Sloanb6d070c2017-07-24 08:40:01 -0700713 return true;
714}
715
716static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
717 SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data(store_ctx,
718 SSL_get_ex_data_X509_STORE_CTX_idx());
719 const TestConfig *config = GetTestConfig(ssl);
720 if (!CheckVerifyCallback(ssl)) {
721 return 0;
722 }
723
Robert Sloana27a6a42017-09-05 08:39:28 -0700724 GetTestState(ssl)->cert_verified = true;
Robert Sloanb6d070c2017-07-24 08:40:01 -0700725 if (config->verify_fail) {
726 store_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION;
727 return 0;
728 }
729
Adam Langleye9ada862015-05-11 17:20:37 -0700730 return 1;
731}
732
Robert Sloanb6d070c2017-07-24 08:40:01 -0700733static ssl_verify_result_t CustomVerifyCallback(SSL *ssl, uint8_t *out_alert) {
734 const TestConfig *config = GetTestConfig(ssl);
735 if (!CheckVerifyCallback(ssl)) {
736 return ssl_verify_invalid;
737 }
738
739 if (config->async && !GetTestState(ssl)->custom_verify_ready) {
740 return ssl_verify_retry;
741 }
742
Robert Sloana27a6a42017-09-05 08:39:28 -0700743 GetTestState(ssl)->cert_verified = true;
Robert Sloanb6d070c2017-07-24 08:40:01 -0700744 if (config->verify_fail) {
745 return ssl_verify_invalid;
746 }
747
748 return ssl_verify_ok;
Kenny Rootb8494592015-09-25 02:29:14 +0000749}
750
Adam Langleye9ada862015-05-11 17:20:37 -0700751static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
752 unsigned int *out_len, void *arg) {
David Benjamind316cba2016-06-02 16:17:39 -0400753 const TestConfig *config = GetTestConfig(ssl);
Adam Langleye9ada862015-05-11 17:20:37 -0700754 if (config->advertise_npn.empty()) {
Adam Langleyd9e397b2015-01-22 14:27:53 -0800755 return SSL_TLSEXT_ERR_NOACK;
Adam Langleye9ada862015-05-11 17:20:37 -0700756 }
Adam Langleyd9e397b2015-01-22 14:27:53 -0800757
758 *out = (const uint8_t*)config->advertise_npn.data();
759 *out_len = config->advertise_npn.size();
760 return SSL_TLSEXT_ERR_OK;
761}
762
Adam Langleye9ada862015-05-11 17:20:37 -0700763static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
764 const uint8_t* in, unsigned inlen, void* arg) {
David Benjamind316cba2016-06-02 16:17:39 -0400765 const TestConfig *config = GetTestConfig(ssl);
Adam Langleye9ada862015-05-11 17:20:37 -0700766 if (config->select_next_proto.empty()) {
Adam Langleyd9e397b2015-01-22 14:27:53 -0800767 return SSL_TLSEXT_ERR_NOACK;
Adam Langleye9ada862015-05-11 17:20:37 -0700768 }
Adam Langleyd9e397b2015-01-22 14:27:53 -0800769
770 *out = (uint8_t*)config->select_next_proto.data();
771 *outlen = config->select_next_proto.size();
772 return SSL_TLSEXT_ERR_OK;
773}
774
Adam Langleye9ada862015-05-11 17:20:37 -0700775static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
776 const uint8_t* in, unsigned inlen, void* arg) {
David Benjaminc895d6b2016-08-11 13:26:41 -0400777 if (GetTestState(ssl)->alpn_select_done) {
778 fprintf(stderr, "AlpnSelectCallback called after completion.\n");
779 exit(1);
780 }
781
782 GetTestState(ssl)->alpn_select_done = true;
783
David Benjamind316cba2016-06-02 16:17:39 -0400784 const TestConfig *config = GetTestConfig(ssl);
David Benjamin4969cc92016-04-22 15:02:23 -0400785 if (config->decline_alpn) {
Adam Langleyd9e397b2015-01-22 14:27:53 -0800786 return SSL_TLSEXT_ERR_NOACK;
Adam Langleye9ada862015-05-11 17:20:37 -0700787 }
Adam Langleyd9e397b2015-01-22 14:27:53 -0800788
789 if (!config->expected_advertised_alpn.empty() &&
790 (config->expected_advertised_alpn.size() != inlen ||
Robert Sloan69939df2017-01-09 10:53:07 -0800791 OPENSSL_memcmp(config->expected_advertised_alpn.data(), in, inlen) !=
792 0)) {
Adam Langleyd9e397b2015-01-22 14:27:53 -0800793 fprintf(stderr, "bad ALPN select callback inputs\n");
794 exit(1);
795 }
796
797 *out = (const uint8_t*)config->select_alpn.data();
798 *outlen = config->select_alpn.size();
799 return SSL_TLSEXT_ERR_OK;
800}
801
Adam Langleye9ada862015-05-11 17:20:37 -0700802static unsigned PskClientCallback(SSL *ssl, const char *hint,
803 char *out_identity,
804 unsigned max_identity_len,
805 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamind316cba2016-06-02 16:17:39 -0400806 const TestConfig *config = GetTestConfig(ssl);
Adam Langleyd9e397b2015-01-22 14:27:53 -0800807
David Benjamin7c0d06c2016-08-11 13:26:41 -0400808 if (config->psk_identity.empty()) {
809 if (hint != nullptr) {
810 fprintf(stderr, "Server PSK hint was non-null.\n");
811 return 0;
812 }
813 } else if (hint == nullptr ||
814 strcmp(hint, config->psk_identity.c_str()) != 0) {
Adam Langleyd9e397b2015-01-22 14:27:53 -0800815 fprintf(stderr, "Server PSK hint did not match.\n");
816 return 0;
817 }
818
819 // Account for the trailing '\0' for the identity.
820 if (config->psk_identity.size() >= max_identity_len ||
821 config->psk.size() > max_psk_len) {
822 fprintf(stderr, "PSK buffers too small\n");
823 return 0;
824 }
825
826 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
827 max_identity_len);
Robert Sloan69939df2017-01-09 10:53:07 -0800828 OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size());
Adam Langleyd9e397b2015-01-22 14:27:53 -0800829 return config->psk.size();
830}
831
Adam Langleye9ada862015-05-11 17:20:37 -0700832static unsigned PskServerCallback(SSL *ssl, const char *identity,
833 uint8_t *out_psk, unsigned max_psk_len) {
David Benjamind316cba2016-06-02 16:17:39 -0400834 const TestConfig *config = GetTestConfig(ssl);
Adam Langleyd9e397b2015-01-22 14:27:53 -0800835
836 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
837 fprintf(stderr, "Client PSK identity did not match.\n");
838 return 0;
839 }
840
841 if (config->psk.size() > max_psk_len) {
842 fprintf(stderr, "PSK buffers too small\n");
843 return 0;
844 }
845
Robert Sloan69939df2017-01-09 10:53:07 -0800846 OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size());
Adam Langleyd9e397b2015-01-22 14:27:53 -0800847 return config->psk.size();
848}
849
Steven Valdez909b19f2016-11-21 15:35:44 -0500850static timeval g_clock;
851
Adam Langleye9ada862015-05-11 17:20:37 -0700852static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
Steven Valdez909b19f2016-11-21 15:35:44 -0500853 *out_clock = g_clock;
Adam Langleye9ada862015-05-11 17:20:37 -0700854}
Adam Langleyd9e397b2015-01-22 14:27:53 -0800855
Adam Langleye9ada862015-05-11 17:20:37 -0700856static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
857 *out_pkey = GetTestState(ssl)->channel_id.release();
858}
859
Robert Sloan4562e9d2017-10-02 10:26:51 -0700860static SSL_SESSION *GetSessionCallback(SSL *ssl, const uint8_t *data, int len,
Adam Langleye9ada862015-05-11 17:20:37 -0700861 int *copy) {
862 TestState *async_state = GetTestState(ssl);
863 if (async_state->session) {
864 *copy = 0;
865 return async_state->session.release();
866 } else if (async_state->pending_session) {
867 return SSL_magic_pending_session_ptr();
868 } else {
869 return NULL;
870 }
871}
872
David Benjamin1b249672016-12-06 18:25:50 -0500873static int DDoSCallback(const SSL_CLIENT_HELLO *client_hello) {
874 const TestConfig *config = GetTestConfig(client_hello->ssl);
Adam Langleye9ada862015-05-11 17:20:37 -0700875 static int callback_num = 0;
876
877 callback_num++;
878 if (config->fail_ddos_callback ||
879 (config->fail_second_ddos_callback && callback_num == 2)) {
880 return 0;
881 }
882 return 1;
883}
884
885static void InfoCallback(const SSL *ssl, int type, int val) {
886 if (type == SSL_CB_HANDSHAKE_DONE) {
David Benjamind316cba2016-06-02 16:17:39 -0400887 if (GetTestConfig(ssl)->handshake_never_done) {
David Benjamin7c0d06c2016-08-11 13:26:41 -0400888 fprintf(stderr, "Handshake unexpectedly completed.\n");
Adam Langleye9ada862015-05-11 17:20:37 -0700889 // Abort before any expected error code is printed, to ensure the overall
890 // test fails.
891 abort();
892 }
Robert Sloana27a6a42017-09-05 08:39:28 -0700893 // This callback is called when the handshake completes. |SSL_get_session|
894 // must continue to work and |SSL_in_init| must return false.
895 if (SSL_in_init(ssl) || SSL_get_session(ssl) == nullptr) {
896 fprintf(stderr, "Invalid state for SSL_CB_HANDSHAKE_DONE.\n");
897 abort();
898 }
Adam Langleye9ada862015-05-11 17:20:37 -0700899 GetTestState(ssl)->handshake_done = true;
David Benjaminc895d6b2016-08-11 13:26:41 -0400900
901 // Callbacks may be called again on a new handshake.
902 GetTestState(ssl)->ticket_decrypt_done = false;
903 GetTestState(ssl)->alpn_select_done = false;
Adam Langleye9ada862015-05-11 17:20:37 -0700904 }
905}
906
Kenny Rootb8494592015-09-25 02:29:14 +0000907static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
Robert Sloana27a6a42017-09-05 08:39:28 -0700908 // This callback is called as the handshake completes. |SSL_get_session|
909 // must continue to work and, historically, |SSL_in_init| returned false at
910 // this point.
911 if (SSL_in_init(ssl) || SSL_get_session(ssl) == nullptr) {
912 fprintf(stderr, "Invalid state for NewSessionCallback.\n");
913 abort();
914 }
915
Kenny Rootb8494592015-09-25 02:29:14 +0000916 GetTestState(ssl)->got_new_session = true;
David Benjaminf0c4a6c2016-08-11 13:26:41 -0400917 GetTestState(ssl)->new_session.reset(session);
Kenny Rootb8494592015-09-25 02:29:14 +0000918 return 1;
919}
920
921static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
922 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
923 int encrypt) {
David Benjaminc895d6b2016-08-11 13:26:41 -0400924 if (!encrypt) {
925 if (GetTestState(ssl)->ticket_decrypt_done) {
926 fprintf(stderr, "TicketKeyCallback called after completion.\n");
927 return -1;
928 }
929
930 GetTestState(ssl)->ticket_decrypt_done = true;
931 }
932
Kenny Rootb8494592015-09-25 02:29:14 +0000933 // This is just test code, so use the all-zeros key.
934 static const uint8_t kZeros[16] = {0};
935
936 if (encrypt) {
Robert Sloan69939df2017-01-09 10:53:07 -0800937 OPENSSL_memcpy(key_name, kZeros, sizeof(kZeros));
Kenny Rootb8494592015-09-25 02:29:14 +0000938 RAND_bytes(iv, 16);
Robert Sloan69939df2017-01-09 10:53:07 -0800939 } else if (OPENSSL_memcmp(key_name, kZeros, 16) != 0) {
Kenny Rootb8494592015-09-25 02:29:14 +0000940 return 0;
941 }
942
943 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
944 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
945 return -1;
946 }
947
948 if (!encrypt) {
David Benjamind316cba2016-06-02 16:17:39 -0400949 return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
Kenny Rootb8494592015-09-25 02:29:14 +0000950 }
951 return 1;
952}
953
954// kCustomExtensionValue is the extension value that the custom extension
955// callbacks will add.
956static const uint16_t kCustomExtensionValue = 1234;
957static void *const kCustomExtensionAddArg =
958 reinterpret_cast<void *>(kCustomExtensionValue);
959static void *const kCustomExtensionParseArg =
960 reinterpret_cast<void *>(kCustomExtensionValue + 1);
961static const char kCustomExtensionContents[] = "custom extension";
962
963static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
964 const uint8_t **out, size_t *out_len,
965 int *out_alert_value, void *add_arg) {
966 if (extension_value != kCustomExtensionValue ||
967 add_arg != kCustomExtensionAddArg) {
968 abort();
969 }
970
David Benjamind316cba2016-06-02 16:17:39 -0400971 if (GetTestConfig(ssl)->custom_extension_skip) {
Kenny Rootb8494592015-09-25 02:29:14 +0000972 return 0;
973 }
David Benjamind316cba2016-06-02 16:17:39 -0400974 if (GetTestConfig(ssl)->custom_extension_fail_add) {
Kenny Rootb8494592015-09-25 02:29:14 +0000975 return -1;
976 }
977
978 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
979 *out_len = sizeof(kCustomExtensionContents) - 1;
980
981 return 1;
982}
983
984static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
985 const uint8_t *out, void *add_arg) {
986 if (extension_value != kCustomExtensionValue ||
987 add_arg != kCustomExtensionAddArg ||
988 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
989 abort();
990 }
991}
992
993static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
994 const uint8_t *contents,
995 size_t contents_len,
996 int *out_alert_value, void *parse_arg) {
997 if (extension_value != kCustomExtensionValue ||
998 parse_arg != kCustomExtensionParseArg) {
999 abort();
1000 }
1001
1002 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
Robert Sloan69939df2017-01-09 10:53:07 -08001003 OPENSSL_memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
Kenny Rootb8494592015-09-25 02:29:14 +00001004 *out_alert_value = SSL_AD_DECODE_ERROR;
1005 return 0;
1006 }
1007
1008 return 1;
1009}
1010
Steven Valdez909b19f2016-11-21 15:35:44 -05001011static int ServerNameCallback(SSL *ssl, int *out_alert, void *arg) {
1012 // SNI must be accessible from the SNI callback.
1013 const TestConfig *config = GetTestConfig(ssl);
1014 const char *server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1015 if (server_name == nullptr ||
1016 std::string(server_name) != config->expected_server_name) {
1017 fprintf(stderr, "servername mismatch (got %s; want %s)\n", server_name,
1018 config->expected_server_name.c_str());
1019 return SSL_TLSEXT_ERR_ALERT_FATAL;
1020 }
1021
1022 return SSL_TLSEXT_ERR_OK;
1023}
1024
Robert Sloanfe7cd212017-08-07 09:03:39 -07001025static void MessageCallback(int is_write, int version, int content_type,
1026 const void *buf, size_t len, SSL *ssl, void *arg) {
1027 const uint8_t *buf_u8 = reinterpret_cast<const uint8_t *>(buf);
1028 const TestConfig *config = GetTestConfig(ssl);
1029 TestState *state = GetTestState(ssl);
1030 if (!state->msg_callback_ok) {
1031 return;
1032 }
1033
1034 if (content_type == SSL3_RT_HEADER) {
1035 if (len !=
1036 (config->is_dtls ? DTLS1_RT_HEADER_LENGTH : SSL3_RT_HEADER_LENGTH)) {
1037 fprintf(stderr, "Incorrect length for record header: %zu\n", len);
1038 state->msg_callback_ok = false;
1039 }
1040 return;
1041 }
1042
1043 state->msg_callback_text += is_write ? "write " : "read ";
1044 switch (content_type) {
1045 case 0:
1046 if (version != SSL2_VERSION) {
1047 fprintf(stderr, "Incorrect version for V2ClientHello: %x\n", version);
1048 state->msg_callback_ok = false;
1049 return;
1050 }
1051 state->msg_callback_text += "v2clienthello\n";
1052 return;
1053
1054 case SSL3_RT_HANDSHAKE: {
1055 CBS cbs;
1056 CBS_init(&cbs, buf_u8, len);
1057 uint8_t type;
1058 uint32_t msg_len;
1059 if (!CBS_get_u8(&cbs, &type) ||
Robert Sloana27a6a42017-09-05 08:39:28 -07001060 // TODO(davidben): Reporting on entire messages would be more
1061 // consistent than fragments.
Robert Sloanfe7cd212017-08-07 09:03:39 -07001062 (config->is_dtls &&
1063 !CBS_skip(&cbs, 3 /* total */ + 2 /* seq */ + 3 /* frag_off */)) ||
1064 !CBS_get_u24(&cbs, &msg_len) ||
1065 !CBS_skip(&cbs, msg_len) ||
1066 CBS_len(&cbs) != 0) {
1067 fprintf(stderr, "Could not parse handshake message.\n");
1068 state->msg_callback_ok = false;
1069 return;
1070 }
1071 char text[16];
1072 snprintf(text, sizeof(text), "hs %d\n", type);
1073 state->msg_callback_text += text;
1074 return;
1075 }
1076
1077 case SSL3_RT_CHANGE_CIPHER_SPEC:
1078 if (len != 1 || buf_u8[0] != 1) {
1079 fprintf(stderr, "Invalid ChangeCipherSpec.\n");
1080 state->msg_callback_ok = false;
1081 return;
1082 }
1083 state->msg_callback_text += "ccs\n";
1084 return;
1085
1086 case SSL3_RT_ALERT:
1087 if (len != 2) {
1088 fprintf(stderr, "Invalid alert.\n");
1089 state->msg_callback_ok = false;
1090 return;
1091 }
1092 char text[16];
1093 snprintf(text, sizeof(text), "alert %d %d\n", buf_u8[0], buf_u8[1]);
1094 state->msg_callback_text += text;
1095 return;
1096
1097 default:
1098 fprintf(stderr, "Invalid content_type: %d\n", content_type);
1099 state->msg_callback_ok = false;
1100 }
1101}
1102
Adam Langleye9ada862015-05-11 17:20:37 -07001103// Connect returns a new socket connected to localhost on |port| or -1 on
1104// error.
1105static int Connect(uint16_t port) {
Robert Sloan8ff03552017-06-14 12:40:58 -07001106 for (int af : { AF_INET6, AF_INET }) {
1107 int sock = socket(af, SOCK_STREAM, 0);
1108 if (sock == -1) {
1109 PrintSocketError("socket");
1110 return -1;
1111 }
1112 int nodelay = 1;
1113 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
1114 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
1115 PrintSocketError("setsockopt");
1116 closesocket(sock);
1117 return -1;
1118 }
1119
1120 sockaddr_storage ss;
1121 OPENSSL_memset(&ss, 0, sizeof(ss));
1122 ss.ss_family = af;
1123 socklen_t len = 0;
1124
1125 if (af == AF_INET6) {
1126 sockaddr_in6 *sin6 = (sockaddr_in6 *) &ss;
1127 len = sizeof(*sin6);
1128 sin6->sin6_port = htons(port);
1129 if (!inet_pton(AF_INET6, "::1", &sin6->sin6_addr)) {
1130 PrintSocketError("inet_pton");
1131 closesocket(sock);
1132 return -1;
1133 }
1134 } else if (af == AF_INET) {
1135 sockaddr_in *sin = (sockaddr_in *) &ss;
1136 len = sizeof(*sin);
1137 sin->sin_port = htons(port);
1138 if (!inet_pton(AF_INET, "127.0.0.1", &sin->sin_addr)) {
1139 PrintSocketError("inet_pton");
1140 closesocket(sock);
1141 return -1;
1142 }
1143 }
1144
1145 if (connect(sock, reinterpret_cast<const sockaddr*>(&ss), len) == 0) {
1146 return sock;
1147 }
Adam Langleye9ada862015-05-11 17:20:37 -07001148 closesocket(sock);
Adam Langleye9ada862015-05-11 17:20:37 -07001149 }
Robert Sloana12bf462017-07-17 07:08:26 -07001150
1151 PrintSocketError("connect");
Robert Sloan8ff03552017-06-14 12:40:58 -07001152 return -1;
Adam Langleye9ada862015-05-11 17:20:37 -07001153}
1154
1155class SocketCloser {
1156 public:
1157 explicit SocketCloser(int sock) : sock_(sock) {}
1158 ~SocketCloser() {
1159 // Half-close and drain the socket before releasing it. This seems to be
1160 // necessary for graceful shutdown on Windows. It will also avoid write
1161 // failures in the test runner.
1162#if defined(OPENSSL_WINDOWS)
1163 shutdown(sock_, SD_SEND);
1164#else
1165 shutdown(sock_, SHUT_WR);
1166#endif
1167 while (true) {
1168 char buf[1024];
1169 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
1170 break;
1171 }
1172 }
1173 closesocket(sock_);
1174 }
1175
1176 private:
1177 const int sock_;
1178};
1179
Robert Sloan8ff03552017-06-14 12:40:58 -07001180static void ssl_ctx_add_session(SSL_SESSION *session, void *void_param) {
Robert Sloanb6d070c2017-07-24 08:40:01 -07001181 SSL_CTX *ctx = reinterpret_cast<SSL_CTX *>(void_param);
1182 bssl::UniquePtr<SSL_SESSION> new_session = bssl::SSL_SESSION_dup(
Robert Sloan8ff03552017-06-14 12:40:58 -07001183 session, SSL_SESSION_INCLUDE_NONAUTH | SSL_SESSION_INCLUDE_TICKET);
1184 if (new_session != nullptr) {
Robert Sloanb6d070c2017-07-24 08:40:01 -07001185 SSL_CTX_add_session(ctx, new_session.get());
Robert Sloan8ff03552017-06-14 12:40:58 -07001186 }
Robert Sloan8ff03552017-06-14 12:40:58 -07001187}
1188
1189static bssl::UniquePtr<SSL_CTX> SetupCtx(SSL_CTX *old_ctx,
1190 const TestConfig *config) {
David Benjaminf0c4a6c2016-08-11 13:26:41 -04001191 bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(
Adam Langleye9ada862015-05-11 17:20:37 -07001192 config->is_dtls ? DTLS_method() : TLS_method()));
1193 if (!ssl_ctx) {
1194 return nullptr;
Adam Langleyd9e397b2015-01-22 14:27:53 -08001195 }
1196
Steven Valdeze7531f02016-12-14 13:29:57 -05001197 SSL_CTX_set0_buffer_pool(ssl_ctx.get(), g_pool);
1198
Robert Sloan572a4e22017-04-17 10:52:19 -07001199 // Enable SSL 3.0 and TLS 1.3 for tests.
David Benjamin7c0d06c2016-08-11 13:26:41 -04001200 if (!config->is_dtls &&
Robert Sloan572a4e22017-04-17 10:52:19 -07001201 (!SSL_CTX_set_min_proto_version(ssl_ctx.get(), SSL3_VERSION) ||
1202 !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION))) {
David Benjamin7c0d06c2016-08-11 13:26:41 -04001203 return nullptr;
David Benjaminc895d6b2016-08-11 13:26:41 -04001204 }
1205
Kenny Rootb8494592015-09-25 02:29:14 +00001206 std::string cipher_list = "ALL";
1207 if (!config->cipher.empty()) {
1208 cipher_list = config->cipher;
1209 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
1210 }
Robert Sloan7c50ec52017-02-27 08:17:21 -08001211 if (!SSL_CTX_set_strict_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
Kenny Rootb8494592015-09-25 02:29:14 +00001212 return nullptr;
1213 }
1214
Adam Langleye9ada862015-05-11 17:20:37 -07001215 if (config->async && config->is_server) {
1216 // Disable the internal session cache. To test asynchronous session lookup,
1217 // we use an external session cache.
1218 SSL_CTX_set_session_cache_mode(
1219 ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
1220 SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
1221 } else {
1222 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
Adam Langleyd9e397b2015-01-22 14:27:53 -08001223 }
1224
Kenny Roote99801b2015-11-06 15:31:15 -08001225 SSL_CTX_set_select_certificate_cb(ssl_ctx.get(), SelectCertificateCallback);
Adam Langleyd9e397b2015-01-22 14:27:53 -08001226
David Benjamin4969cc92016-04-22 15:02:23 -04001227 if (config->use_old_client_cert_callback) {
1228 SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
1229 }
1230
Adam Langleyd9e397b2015-01-22 14:27:53 -08001231 SSL_CTX_set_next_protos_advertised_cb(
Adam Langleye9ada862015-05-11 17:20:37 -07001232 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
Adam Langleyd9e397b2015-01-22 14:27:53 -08001233 if (!config->select_next_proto.empty()) {
Adam Langleye9ada862015-05-11 17:20:37 -07001234 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
1235 NULL);
Adam Langleyd9e397b2015-01-22 14:27:53 -08001236 }
1237
Robert Sloan8ff03552017-06-14 12:40:58 -07001238 if (!config->select_alpn.empty() || config->decline_alpn) {
Adam Langleye9ada862015-05-11 17:20:37 -07001239 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
Adam Langleyd9e397b2015-01-22 14:27:53 -08001240 }
1241
Adam Langleye9ada862015-05-11 17:20:37 -07001242 SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
Adam Langleyd9e397b2015-01-22 14:27:53 -08001243
Steven Valdez909b19f2016-11-21 15:35:44 -05001244 SSL_CTX_set_current_time_cb(ssl_ctx.get(), CurrentTimeCallback);
Adam Langleye9ada862015-05-11 17:20:37 -07001245
1246 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
Kenny Rootb8494592015-09-25 02:29:14 +00001247 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
1248
1249 if (config->use_ticket_callback) {
1250 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
1251 }
1252
1253 if (config->enable_client_custom_extension &&
1254 !SSL_CTX_add_client_custom_ext(
1255 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
1256 CustomExtensionFreeCallback, kCustomExtensionAddArg,
1257 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1258 return nullptr;
1259 }
1260
1261 if (config->enable_server_custom_extension &&
1262 !SSL_CTX_add_server_custom_ext(
1263 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
1264 CustomExtensionFreeCallback, kCustomExtensionAddArg,
1265 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
1266 return nullptr;
1267 }
1268
Robert Sloanb6d070c2017-07-24 08:40:01 -07001269 if (!config->use_custom_verify_callback) {
1270 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), CertVerifyCallback, NULL);
Kenny Rootb8494592015-09-25 02:29:14 +00001271 }
1272
1273 if (!config->signed_cert_timestamps.empty() &&
1274 !SSL_CTX_set_signed_cert_timestamp_list(
1275 ssl_ctx.get(), (const uint8_t *)config->signed_cert_timestamps.data(),
1276 config->signed_cert_timestamps.size())) {
1277 return nullptr;
1278 }
Adam Langleye9ada862015-05-11 17:20:37 -07001279
Robert Sloan7d422bc2017-03-06 10:04:29 -08001280 if (!config->use_client_ca_list.empty()) {
1281 if (config->use_client_ca_list == "<NULL>") {
1282 SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
Robert Sloanb1b54b82017-11-06 13:50:02 -08001283 } else if (config->use_client_ca_list == "<EMPTY>") {
1284 bssl::UniquePtr<STACK_OF(X509_NAME)> names;
1285 SSL_CTX_set_client_CA_list(ssl_ctx.get(), names.release());
Robert Sloan7d422bc2017-03-06 10:04:29 -08001286 } else {
1287 bssl::UniquePtr<STACK_OF(X509_NAME)> names =
1288 DecodeHexX509Names(config->use_client_ca_list);
1289 SSL_CTX_set_client_CA_list(ssl_ctx.get(), names.release());
1290 }
David Benjaminc895d6b2016-08-11 13:26:41 -04001291 }
1292
Steven Valdezbb1ceac2016-10-07 10:34:51 -04001293 if (config->enable_grease) {
1294 SSL_CTX_set_grease_enabled(ssl_ctx.get(), 1);
1295 }
1296
Steven Valdez909b19f2016-11-21 15:35:44 -05001297 if (!config->expected_server_name.empty()) {
1298 SSL_CTX_set_tlsext_servername_callback(ssl_ctx.get(), ServerNameCallback);
1299 }
1300
1301 if (!config->ticket_key.empty() &&
1302 !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), config->ticket_key.data(),
1303 config->ticket_key.size())) {
1304 return nullptr;
1305 }
1306
Robert Sloan69939df2017-01-09 10:53:07 -08001307 if (config->enable_early_data) {
1308 SSL_CTX_set_early_data_enabled(ssl_ctx.get(), 1);
1309 }
1310
Robert Sloana12bf462017-07-17 07:08:26 -07001311 SSL_CTX_set_tls13_variant(
1312 ssl_ctx.get(), static_cast<enum tls13_variant_t>(config->tls13_variant));
1313
Robert Sloan572a4e22017-04-17 10:52:19 -07001314 if (config->allow_unknown_alpn_protos) {
1315 SSL_CTX_set_allow_unknown_alpn_protos(ssl_ctx.get(), 1);
1316 }
1317
1318 if (config->enable_ed25519) {
1319 SSL_CTX_set_ed25519_enabled(ssl_ctx.get(), 1);
1320 }
1321
1322 if (!config->verify_prefs.empty()) {
1323 std::vector<uint16_t> u16s(config->verify_prefs.begin(),
1324 config->verify_prefs.end());
1325 if (!SSL_CTX_set_verify_algorithm_prefs(ssl_ctx.get(), u16s.data(),
1326 u16s.size())) {
1327 return nullptr;
1328 }
1329 }
1330
Robert Sloanfe7cd212017-08-07 09:03:39 -07001331 SSL_CTX_set_msg_callback(ssl_ctx.get(), MessageCallback);
1332
Robert Sloancd79cde2017-12-11 09:06:12 -08001333 if (config->allow_false_start_without_alpn) {
1334 SSL_CTX_set_false_start_allowed_without_alpn(ssl_ctx.get(), 1);
1335 }
1336
Robert Sloan8ff03552017-06-14 12:40:58 -07001337 if (old_ctx) {
1338 uint8_t keys[48];
1339 if (!SSL_CTX_get_tlsext_ticket_keys(old_ctx, &keys, sizeof(keys)) ||
1340 !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), keys, sizeof(keys))) {
1341 return nullptr;
1342 }
1343 lh_SSL_SESSION_doall_arg(old_ctx->sessions, ssl_ctx_add_session,
1344 ssl_ctx.get());
1345 }
1346
Adam Langleyd9e397b2015-01-22 14:27:53 -08001347 return ssl_ctx;
Adam Langleyd9e397b2015-01-22 14:27:53 -08001348}
1349
Adam Langleye9ada862015-05-11 17:20:37 -07001350// RetryAsync is called after a failed operation on |ssl| with return code
1351// |ret|. If the operation should be retried, it simulates one asynchronous
1352// event and returns true. Otherwise it returns false.
1353static bool RetryAsync(SSL *ssl, int ret) {
Adam Langleyd9e397b2015-01-22 14:27:53 -08001354 // No error; don't retry.
1355 if (ret >= 0) {
Adam Langleye9ada862015-05-11 17:20:37 -07001356 return false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08001357 }
Adam Langleye9ada862015-05-11 17:20:37 -07001358
1359 TestState *test_state = GetTestState(ssl);
David Benjaminc895d6b2016-08-11 13:26:41 -04001360 assert(GetTestConfig(ssl)->async);
Adam Langleye9ada862015-05-11 17:20:37 -07001361
David Benjamin6e899c72016-06-09 18:02:18 -04001362 if (test_state->packeted_bio != nullptr &&
1363 PacketedBioAdvanceClock(test_state->packeted_bio)) {
Adam Langleyfad63272015-11-12 12:15:39 -08001364 // The DTLS retransmit logic silently ignores write failures. So the test
1365 // may progress, allow writes through synchronously.
David Benjamin6e899c72016-06-09 18:02:18 -04001366 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
Adam Langleyfad63272015-11-12 12:15:39 -08001367 int timeout_ret = DTLSv1_handle_timeout(ssl);
David Benjamin6e899c72016-06-09 18:02:18 -04001368 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
Adam Langleyfad63272015-11-12 12:15:39 -08001369
1370 if (timeout_ret < 0) {
Adam Langleye9ada862015-05-11 17:20:37 -07001371 fprintf(stderr, "Error retransmitting.\n");
1372 return false;
1373 }
1374 return true;
1375 }
1376
Adam Langleyd9e397b2015-01-22 14:27:53 -08001377 // See if we needed to read or write more. If so, allow one byte through on
1378 // the appropriate end to maximally stress the state machine.
Adam Langleye9ada862015-05-11 17:20:37 -07001379 switch (SSL_get_error(ssl, ret)) {
1380 case SSL_ERROR_WANT_READ:
1381 AsyncBioAllowRead(test_state->async_bio, 1);
1382 return true;
1383 case SSL_ERROR_WANT_WRITE:
1384 AsyncBioAllowWrite(test_state->async_bio, 1);
1385 return true;
1386 case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
David Benjaminf0c4a6c2016-08-11 13:26:41 -04001387 bssl::UniquePtr<EVP_PKEY> pkey =
1388 LoadPrivateKey(GetTestConfig(ssl)->send_channel_id);
Adam Langleye9ada862015-05-11 17:20:37 -07001389 if (!pkey) {
1390 return false;
1391 }
1392 test_state->channel_id = std::move(pkey);
1393 return true;
1394 }
1395 case SSL_ERROR_WANT_X509_LOOKUP:
1396 test_state->cert_ready = true;
1397 return true;
1398 case SSL_ERROR_PENDING_SESSION:
1399 test_state->session = std::move(test_state->pending_session);
1400 return true;
1401 case SSL_ERROR_PENDING_CERTIFICATE:
David Benjaminf31229b2017-01-25 14:08:15 -05001402 test_state->early_callback_ready = true;
1403 return true;
Kenny Rootb8494592015-09-25 02:29:14 +00001404 case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
Kenny Roote99801b2015-11-06 15:31:15 -08001405 test_state->private_key_retries++;
Kenny Rootb8494592015-09-25 02:29:14 +00001406 return true;
Robert Sloanb6d070c2017-07-24 08:40:01 -07001407 case SSL_ERROR_WANT_CERTIFICATE_VERIFY:
1408 test_state->custom_verify_ready = true;
1409 return true;
Adam Langleye9ada862015-05-11 17:20:37 -07001410 default:
1411 return false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08001412 }
Adam Langleyd9e397b2015-01-22 14:27:53 -08001413}
1414
Robert Sloan36272962017-10-23 10:28:39 -07001415// CheckIdempotentError runs |func|, an operation on |ssl|, ensuring that
1416// errors are idempotent.
1417static int CheckIdempotentError(const char *name, SSL *ssl,
1418 std::function<int()> func) {
1419 int ret = func();
1420 int ssl_err = SSL_get_error(ssl, ret);
1421 uint32_t err = ERR_peek_error();
1422 if (ssl_err == SSL_ERROR_SSL || ssl_err == SSL_ERROR_ZERO_RETURN) {
1423 int ret2 = func();
1424 int ssl_err2 = SSL_get_error(ssl, ret2);
1425 uint32_t err2 = ERR_peek_error();
1426 if (ret != ret2 || ssl_err != ssl_err2 || err != err2) {
1427 fprintf(stderr, "Repeating %s did not replay the error.\n", name);
1428 char buf[256];
1429 ERR_error_string_n(err, buf, sizeof(buf));
1430 fprintf(stderr, "Wanted: %d %d %s\n", ret, ssl_err, buf);
1431 ERR_error_string_n(err2, buf, sizeof(buf));
1432 fprintf(stderr, "Got: %d %d %s\n", ret2, ssl_err2, buf);
1433 // runner treats exit code 90 as always failing. Otherwise, it may
1434 // accidentally consider the result an expected protocol failure.
1435 exit(90);
1436 }
1437 }
1438 return ret;
1439}
1440
Adam Langleye9ada862015-05-11 17:20:37 -07001441// DoRead reads from |ssl|, resolving any asynchronous operations. It returns
1442// the result value of the final |SSL_read| call.
1443static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
David Benjamind316cba2016-06-02 16:17:39 -04001444 const TestConfig *config = GetTestConfig(ssl);
Adam Langleyfad63272015-11-12 12:15:39 -08001445 TestState *test_state = GetTestState(ssl);
Adam Langleye9ada862015-05-11 17:20:37 -07001446 int ret;
1447 do {
Adam Langleyfad63272015-11-12 12:15:39 -08001448 if (config->async) {
1449 // The DTLS retransmit logic silently ignores write failures. So the test
1450 // may progress, allow writes through synchronously. |SSL_read| may
1451 // trigger a retransmit, so disconnect the write quota.
1452 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
1453 }
Robert Sloan36272962017-10-23 10:28:39 -07001454 ret = CheckIdempotentError("SSL_peek/SSL_read", ssl, [&]() -> int {
1455 return config->peek_then_read ? SSL_peek(ssl, out, max_out)
1456 : SSL_read(ssl, out, max_out);
1457 });
Adam Langleyfad63272015-11-12 12:15:39 -08001458 if (config->async) {
1459 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
1460 }
Steven Valdez909b19f2016-11-21 15:35:44 -05001461
1462 // Run the exporter after each read. This is to test that the exporter fails
1463 // during a renegotiation.
1464 if (config->use_exporter_between_reads) {
1465 uint8_t buf;
1466 if (!SSL_export_keying_material(ssl, &buf, 1, NULL, 0, NULL, 0, 0)) {
1467 fprintf(stderr, "failed to export keying material\n");
1468 return -1;
1469 }
1470 }
Adam Langleye9ada862015-05-11 17:20:37 -07001471 } while (config->async && RetryAsync(ssl, ret));
Steven Valdezbb1ceac2016-10-07 10:34:51 -04001472
1473 if (config->peek_then_read && ret > 0) {
1474 std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
1475
1476 // SSL_peek should synchronously return the same data.
1477 int ret2 = SSL_peek(ssl, buf.get(), ret);
1478 if (ret2 != ret ||
Robert Sloan69939df2017-01-09 10:53:07 -08001479 OPENSSL_memcmp(buf.get(), out, ret) != 0) {
Steven Valdezbb1ceac2016-10-07 10:34:51 -04001480 fprintf(stderr, "First and second SSL_peek did not match.\n");
1481 return -1;
1482 }
1483
1484 // SSL_read should synchronously return the same data and consume it.
1485 ret2 = SSL_read(ssl, buf.get(), ret);
1486 if (ret2 != ret ||
Robert Sloan69939df2017-01-09 10:53:07 -08001487 OPENSSL_memcmp(buf.get(), out, ret) != 0) {
Steven Valdezbb1ceac2016-10-07 10:34:51 -04001488 fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
1489 return -1;
1490 }
1491 }
1492
Adam Langleye9ada862015-05-11 17:20:37 -07001493 return ret;
1494}
1495
1496// WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
1497// operations. It returns the result of the final |SSL_write| call.
Robert Sloan572a4e22017-04-17 10:52:19 -07001498static int WriteAll(SSL *ssl, const void *in_, size_t in_len) {
1499 const uint8_t *in = reinterpret_cast<const uint8_t *>(in_);
David Benjamind316cba2016-06-02 16:17:39 -04001500 const TestConfig *config = GetTestConfig(ssl);
Adam Langleye9ada862015-05-11 17:20:37 -07001501 int ret;
1502 do {
1503 ret = SSL_write(ssl, in, in_len);
1504 if (ret > 0) {
1505 in += ret;
1506 in_len -= ret;
1507 }
1508 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
1509 return ret;
1510}
1511
Kenny Rootb8494592015-09-25 02:29:14 +00001512// DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
1513// returns the result of the final |SSL_shutdown| call.
1514static int DoShutdown(SSL *ssl) {
David Benjamind316cba2016-06-02 16:17:39 -04001515 const TestConfig *config = GetTestConfig(ssl);
Kenny Rootb8494592015-09-25 02:29:14 +00001516 int ret;
1517 do {
1518 ret = SSL_shutdown(ssl);
1519 } while (config->async && RetryAsync(ssl, ret));
1520 return ret;
1521}
1522
David Benjaminc895d6b2016-08-11 13:26:41 -04001523// DoSendFatalAlert calls |SSL_send_fatal_alert|, resolving any asynchronous
1524// operations. It returns the result of the final |SSL_send_fatal_alert| call.
1525static int DoSendFatalAlert(SSL *ssl, uint8_t alert) {
1526 const TestConfig *config = GetTestConfig(ssl);
1527 int ret;
1528 do {
1529 ret = SSL_send_fatal_alert(ssl, alert);
1530 } while (config->async && RetryAsync(ssl, ret));
1531 return ret;
1532}
1533
1534static uint16_t GetProtocolVersion(const SSL *ssl) {
1535 uint16_t version = SSL_version(ssl);
1536 if (!SSL_is_dtls(ssl)) {
1537 return version;
1538 }
1539 return 0x0201 + ~version;
1540}
1541
Robert Sloan8f860b12017-08-28 07:37:06 -07001542// CheckAuthProperties checks, after the initial handshake is completed or
1543// after a renegotiation, that authentication-related properties match |config|.
1544static bool CheckAuthProperties(SSL *ssl, bool is_resume,
1545 const TestConfig *config) {
1546 if (!config->expected_ocsp_response.empty()) {
1547 const uint8_t *data;
1548 size_t len;
1549 SSL_get0_ocsp_response(ssl, &data, &len);
1550 if (config->expected_ocsp_response.size() != len ||
1551 OPENSSL_memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
1552 fprintf(stderr, "OCSP response mismatch\n");
1553 return false;
1554 }
1555 }
1556
1557 if (!config->expected_signed_cert_timestamps.empty()) {
1558 const uint8_t *data;
1559 size_t len;
1560 SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
1561 if (config->expected_signed_cert_timestamps.size() != len ||
1562 OPENSSL_memcmp(config->expected_signed_cert_timestamps.data(), data,
1563 len) != 0) {
1564 fprintf(stderr, "SCT list mismatch\n");
1565 return false;
1566 }
1567 }
1568
1569 if (config->expect_verify_result) {
1570 int expected_verify_result = config->verify_fail ?
1571 X509_V_ERR_APPLICATION_VERIFICATION :
1572 X509_V_OK;
1573
1574 if (SSL_get_verify_result(ssl) != expected_verify_result) {
1575 fprintf(stderr, "Wrong certificate verification result\n");
1576 return false;
1577 }
1578 }
1579
1580 if (!config->expect_peer_cert_file.empty()) {
1581 bssl::UniquePtr<X509> expect_leaf;
1582 bssl::UniquePtr<STACK_OF(X509)> expect_chain;
1583 if (!LoadCertificate(&expect_leaf, &expect_chain,
1584 config->expect_peer_cert_file)) {
1585 return false;
1586 }
1587
1588 // For historical reasons, clients report a chain with a leaf and servers
1589 // without.
1590 if (!config->is_server) {
1591 if (!sk_X509_insert(expect_chain.get(), expect_leaf.get(), 0)) {
1592 return false;
1593 }
1594 X509_up_ref(expect_leaf.get()); // sk_X509_push takes ownership.
1595 }
1596
1597 bssl::UniquePtr<X509> leaf(SSL_get_peer_certificate(ssl));
1598 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl);
1599 if (X509_cmp(leaf.get(), expect_leaf.get()) != 0) {
1600 fprintf(stderr, "Received a different leaf certificate than expected.\n");
1601 return false;
1602 }
1603
1604 if (sk_X509_num(chain) != sk_X509_num(expect_chain.get())) {
1605 fprintf(stderr, "Received a chain of length %zu instead of %zu.\n",
1606 sk_X509_num(chain), sk_X509_num(expect_chain.get()));
1607 return false;
1608 }
1609
1610 for (size_t i = 0; i < sk_X509_num(chain); i++) {
1611 if (X509_cmp(sk_X509_value(chain, i),
1612 sk_X509_value(expect_chain.get(), i)) != 0) {
1613 fprintf(stderr, "Chain certificate %zu did not match.\n",
1614 i + 1);
1615 return false;
1616 }
1617 }
1618 }
1619
1620 if (SSL_get_session(ssl)->peer_sha256_valid !=
1621 config->expect_sha256_client_cert) {
1622 fprintf(stderr,
1623 "Unexpected SHA-256 client cert state: expected:%d is_resume:%d.\n",
1624 config->expect_sha256_client_cert, is_resume);
1625 return false;
1626 }
1627
1628 if (config->expect_sha256_client_cert &&
1629 SSL_get_session(ssl)->certs != nullptr) {
1630 fprintf(stderr, "Have both client cert and SHA-256 hash: is_resume:%d.\n",
1631 is_resume);
1632 return false;
1633 }
1634
1635 return true;
1636}
1637
Kenny Rootb8494592015-09-25 02:29:14 +00001638// CheckHandshakeProperties checks, immediately after |ssl| completes its
1639// initial handshake (or False Starts), whether all the properties are
1640// consistent with the test configuration and invariants.
Robert Sloane56da3e2017-06-26 08:26:42 -07001641static bool CheckHandshakeProperties(SSL *ssl, bool is_resume,
1642 const TestConfig *config) {
Robert Sloan8f860b12017-08-28 07:37:06 -07001643 if (!CheckAuthProperties(ssl, is_resume, config)) {
1644 return false;
1645 }
1646
Kenny Rootb8494592015-09-25 02:29:14 +00001647 if (SSL_get_current_cipher(ssl) == nullptr) {
1648 fprintf(stderr, "null cipher after handshake\n");
1649 return false;
1650 }
1651
Robert Sloanf6200e72017-07-10 08:09:18 -07001652 if (config->expect_version != 0 &&
1653 SSL_version(ssl) != config->expect_version) {
1654 fprintf(stderr, "want version %04x, got %04x\n", config->expect_version,
1655 SSL_version(ssl));
1656 return false;
1657 }
1658
Robert Sloane56da3e2017-06-26 08:26:42 -07001659 bool expect_resume =
1660 is_resume && (!config->expect_session_miss || SSL_in_early_data(ssl));
1661 if (!!SSL_session_reused(ssl) != expect_resume) {
1662 fprintf(stderr, "session unexpectedly was%s reused\n",
Kenny Rootb8494592015-09-25 02:29:14 +00001663 SSL_session_reused(ssl) ? "" : " not");
1664 return false;
1665 }
1666
Robert Sloan6d0d00e2017-03-27 07:13:07 -07001667 bool expect_handshake_done =
Robert Sloane56da3e2017-06-26 08:26:42 -07001668 (is_resume || !config->false_start) && !SSL_in_early_data(ssl);
Kenny Rootb8494592015-09-25 02:29:14 +00001669 if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
1670 fprintf(stderr, "handshake was%s completed\n",
1671 GetTestState(ssl)->handshake_done ? "" : " not");
1672 return false;
1673 }
1674
1675 if (expect_handshake_done && !config->is_server) {
1676 bool expect_new_session =
1677 !config->expect_no_session &&
David Benjaminc895d6b2016-08-11 13:26:41 -04001678 (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
1679 // Session tickets are sent post-handshake in TLS 1.3.
1680 GetProtocolVersion(ssl) < TLS1_3_VERSION;
Kenny Rootb8494592015-09-25 02:29:14 +00001681 if (expect_new_session != GetTestState(ssl)->got_new_session) {
1682 fprintf(stderr,
Kenny Roote99801b2015-11-06 15:31:15 -08001683 "new session was%s cached, but we expected the opposite\n",
Kenny Rootb8494592015-09-25 02:29:14 +00001684 GetTestState(ssl)->got_new_session ? "" : " not");
1685 return false;
1686 }
1687 }
1688
Robert Sloan4d1ac502017-02-06 08:36:14 -08001689 if (!is_resume) {
1690 if (config->expect_session_id && !GetTestState(ssl)->got_new_session) {
1691 fprintf(stderr, "session was not cached on the server.\n");
1692 return false;
1693 }
1694 if (config->expect_no_session_id && GetTestState(ssl)->got_new_session) {
1695 fprintf(stderr, "session was unexpectedly cached on the server.\n");
1696 return false;
1697 }
1698 }
1699
Kenny Rootb8494592015-09-25 02:29:14 +00001700 if (config->is_server && !GetTestState(ssl)->early_callback_called) {
1701 fprintf(stderr, "early callback not called\n");
1702 return false;
1703 }
1704
1705 if (!config->expected_server_name.empty()) {
1706 const char *server_name =
1707 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
Steven Valdez909b19f2016-11-21 15:35:44 -05001708 if (server_name == nullptr ||
1709 server_name != config->expected_server_name) {
Kenny Rootb8494592015-09-25 02:29:14 +00001710 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
1711 server_name, config->expected_server_name.c_str());
1712 return false;
1713 }
1714 }
1715
Kenny Rootb8494592015-09-25 02:29:14 +00001716 if (!config->expected_next_proto.empty()) {
1717 const uint8_t *next_proto;
1718 unsigned next_proto_len;
1719 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
1720 if (next_proto_len != config->expected_next_proto.size() ||
Robert Sloan69939df2017-01-09 10:53:07 -08001721 OPENSSL_memcmp(next_proto, config->expected_next_proto.data(),
1722 next_proto_len) != 0) {
Kenny Rootb8494592015-09-25 02:29:14 +00001723 fprintf(stderr, "negotiated next proto mismatch\n");
1724 return false;
1725 }
1726 }
1727
Robert Sloan8ff03552017-06-14 12:40:58 -07001728 if (!config->is_server) {
Kenny Rootb8494592015-09-25 02:29:14 +00001729 const uint8_t *alpn_proto;
1730 unsigned alpn_proto_len;
1731 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
Robert Sloan8ff03552017-06-14 12:40:58 -07001732 if (alpn_proto_len != config->expected_alpn.size() ||
1733 OPENSSL_memcmp(alpn_proto, config->expected_alpn.data(),
1734 alpn_proto_len) != 0) {
Kenny Rootb8494592015-09-25 02:29:14 +00001735 fprintf(stderr, "negotiated alpn proto mismatch\n");
1736 return false;
1737 }
1738 }
1739
Robert Sloan8542c082018-02-05 09:07:34 -08001740 if (!config->expected_quic_transport_params.empty()) {
1741 const uint8_t *peer_params;
1742 size_t peer_params_len;
1743 SSL_get_peer_quic_transport_params(ssl, &peer_params, &peer_params_len);
1744 if (peer_params_len != config->expected_quic_transport_params.size() ||
1745 OPENSSL_memcmp(peer_params,
1746 config->expected_quic_transport_params.data(),
1747 peer_params_len) != 0) {
1748 fprintf(stderr, "QUIC transport params mismatch\n");
1749 return false;
1750 }
1751 }
1752
Kenny Rootb8494592015-09-25 02:29:14 +00001753 if (!config->expected_channel_id.empty()) {
1754 uint8_t channel_id[64];
1755 if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
1756 fprintf(stderr, "no channel id negotiated\n");
1757 return false;
1758 }
1759 if (config->expected_channel_id.size() != 64 ||
Robert Sloan69939df2017-01-09 10:53:07 -08001760 OPENSSL_memcmp(config->expected_channel_id.data(), channel_id, 64) !=
1761 0) {
Kenny Rootb8494592015-09-25 02:29:14 +00001762 fprintf(stderr, "channel id mismatch\n");
1763 return false;
1764 }
1765 }
1766
Robert Sloan978112c2018-01-22 12:53:01 -08001767 if (config->expected_token_binding_param != -1) {
1768 if (!SSL_is_token_binding_negotiated(ssl)) {
1769 fprintf(stderr, "no Token Binding negotiated\n");
1770 return false;
1771 }
1772 if (SSL_get_negotiated_token_binding_param(ssl) !=
1773 static_cast<uint8_t>(config->expected_token_binding_param)) {
1774 fprintf(stderr, "Token Binding param mismatch\n");
1775 return false;
1776 }
1777 }
1778
Steven Valdezb0b45c62017-01-17 16:23:54 -05001779 if (config->expect_extended_master_secret && !SSL_get_extms_support(ssl)) {
1780 fprintf(stderr, "No EMS for connection when expected\n");
1781 return false;
1782 }
1783
1784 if (config->expect_secure_renegotiation &&
1785 !SSL_get_secure_renegotiation_support(ssl)) {
1786 fprintf(stderr, "No secure renegotiation for connection when expected\n");
1787 return false;
1788 }
1789
1790 if (config->expect_no_secure_renegotiation &&
1791 SSL_get_secure_renegotiation_support(ssl)) {
1792 fprintf(stderr,
1793 "Secure renegotiation unexpectedly negotiated for connection\n");
1794 return false;
Kenny Rootb8494592015-09-25 02:29:14 +00001795 }
1796
David Benjaminc895d6b2016-08-11 13:26:41 -04001797 if (config->expect_peer_signature_algorithm != 0 &&
1798 config->expect_peer_signature_algorithm !=
1799 SSL_get_peer_signature_algorithm(ssl)) {
1800 fprintf(stderr, "Peer signature algorithm was %04x, wanted %04x.\n",
1801 SSL_get_peer_signature_algorithm(ssl),
1802 config->expect_peer_signature_algorithm);
Adam Langleyfad63272015-11-12 12:15:39 -08001803 return false;
1804 }
1805
Robert Sloan8ff03552017-06-14 12:40:58 -07001806 if (config->expect_curve_id != 0) {
Steven Valdeze7531f02016-12-14 13:29:57 -05001807 uint16_t curve_id = SSL_get_curve_id(ssl);
Robert Sloan8ff03552017-06-14 12:40:58 -07001808 if (static_cast<uint16_t>(config->expect_curve_id) != curve_id) {
Steven Valdeze7531f02016-12-14 13:29:57 -05001809 fprintf(stderr, "curve_id was %04x, wanted %04x\n", curve_id,
Robert Sloan8ff03552017-06-14 12:40:58 -07001810 static_cast<uint16_t>(config->expect_curve_id));
Kenny Rootb8494592015-09-25 02:29:14 +00001811 return false;
1812 }
1813 }
David Benjaminc895d6b2016-08-11 13:26:41 -04001814
Steven Valdez909b19f2016-11-21 15:35:44 -05001815 uint16_t cipher_id =
1816 static_cast<uint16_t>(SSL_CIPHER_get_id(SSL_get_current_cipher(ssl)));
1817 if (config->expect_cipher_aes != 0 &&
1818 EVP_has_aes_hardware() &&
1819 static_cast<uint16_t>(config->expect_cipher_aes) != cipher_id) {
1820 fprintf(stderr, "Cipher ID was %04x, wanted %04x (has AES hardware)\n",
1821 cipher_id, static_cast<uint16_t>(config->expect_cipher_aes));
1822 return false;
1823 }
1824
1825 if (config->expect_cipher_no_aes != 0 &&
1826 !EVP_has_aes_hardware() &&
1827 static_cast<uint16_t>(config->expect_cipher_no_aes) != cipher_id) {
1828 fprintf(stderr, "Cipher ID was %04x, wanted %04x (no AES hardware)\n",
1829 cipher_id, static_cast<uint16_t>(config->expect_cipher_no_aes));
1830 return false;
1831 }
1832
Robert Sloane56da3e2017-06-26 08:26:42 -07001833 if (is_resume && !SSL_in_early_data(ssl)) {
Robert Sloan6d0d00e2017-03-27 07:13:07 -07001834 if ((config->expect_accept_early_data && !SSL_early_data_accepted(ssl)) ||
1835 (config->expect_reject_early_data && SSL_early_data_accepted(ssl))) {
1836 fprintf(stderr,
1837 "Early data was%s accepted, but we expected the opposite\n",
1838 SSL_early_data_accepted(ssl) ? "" : " not");
1839 return false;
1840 }
1841 }
Steven Valdez909b19f2016-11-21 15:35:44 -05001842
David Benjaminc895d6b2016-08-11 13:26:41 -04001843 if (!config->psk.empty()) {
1844 if (SSL_get_peer_cert_chain(ssl) != nullptr) {
1845 fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
1846 return false;
1847 }
1848 } else if (!config->is_server || config->require_any_client_certificate) {
1849 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
1850 fprintf(stderr, "Received no peer certificate but expected one.\n");
1851 return false;
1852 }
1853 }
1854
Robert Sloan1c9db532017-03-13 08:03:59 -07001855 if (is_resume && config->expect_ticket_age_skew != 0 &&
1856 SSL_get_ticket_age_skew(ssl) != config->expect_ticket_age_skew) {
1857 fprintf(stderr, "Ticket age skew was %" PRId32 ", wanted %d\n",
1858 SSL_get_ticket_age_skew(ssl), config->expect_ticket_age_skew);
1859 return false;
1860 }
1861
Robert Sloan0da43952018-01-03 15:13:14 -08001862 if (config->expect_draft_downgrade != !!SSL_is_draft_downgrade(ssl)) {
1863 fprintf(stderr, "Got %sdraft downgrade signal, but wanted the opposite.\n",
1864 SSL_is_draft_downgrade(ssl) ? "" : "no ");
1865 }
1866
Kenny Rootb8494592015-09-25 02:29:14 +00001867 return true;
1868}
1869
Robert Sloanf6200e72017-07-10 08:09:18 -07001870static bool WriteSettings(int i, const TestConfig *config,
1871 const SSL_SESSION *session) {
1872 if (config->write_settings.empty()) {
1873 return true;
1874 }
1875
1876 // Treat write_settings as a path prefix for each connection in the run.
1877 char buf[DECIMAL_SIZE(int)];
1878 snprintf(buf, sizeof(buf), "%d", i);
1879 std::string path = config->write_settings + buf;
1880
1881 bssl::ScopedCBB cbb;
1882 if (!CBB_init(cbb.get(), 64)) {
1883 return false;
1884 }
1885
1886 if (session != nullptr) {
1887 uint8_t *data;
1888 size_t len;
1889 if (!SSL_SESSION_to_bytes(session, &data, &len)) {
1890 return false;
1891 }
1892 bssl::UniquePtr<uint8_t> free_data(data);
1893 CBB child;
1894 if (!CBB_add_u16(cbb.get(), kSessionTag) ||
1895 !CBB_add_u24_length_prefixed(cbb.get(), &child) ||
1896 !CBB_add_bytes(&child, data, len) ||
1897 !CBB_flush(cbb.get())) {
1898 return false;
1899 }
1900 }
1901
1902 if (config->is_server &&
1903 (config->require_any_client_certificate || config->verify_peer) &&
1904 !CBB_add_u16(cbb.get(), kRequestClientCert)) {
1905 return false;
1906 }
1907
Robert Sloana12bf462017-07-17 07:08:26 -07001908 if (config->tls13_variant != 0 &&
1909 (!CBB_add_u16(cbb.get(), kTLS13Variant) ||
1910 !CBB_add_u8(cbb.get(), static_cast<uint8_t>(config->tls13_variant)))) {
1911 return false;
1912 }
1913
Robert Sloanf6200e72017-07-10 08:09:18 -07001914 uint8_t *settings;
1915 size_t settings_len;
1916 if (!CBB_add_u16(cbb.get(), kDataTag) ||
1917 !CBB_finish(cbb.get(), &settings, &settings_len)) {
1918 return false;
1919 }
1920 bssl::UniquePtr<uint8_t> free_settings(settings);
1921
1922 using ScopedFILE = std::unique_ptr<FILE, decltype(&fclose)>;
1923 ScopedFILE file(fopen(path.c_str(), "w"), fclose);
1924 if (!file) {
1925 return false;
1926 }
1927
1928 return fwrite(settings, settings_len, 1, file.get()) == 1;
1929}
1930
Robert Sloan8542c082018-02-05 09:07:34 -08001931static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
1932 bssl::UniquePtr<SSL> *ssl_uniqueptr,
Robert Sloane56da3e2017-06-26 08:26:42 -07001933 const TestConfig *config, bool is_resume, bool is_retry);
1934
1935// DoConnection tests an SSL connection against the peer. On success, it returns
Adam Langleye9ada862015-05-11 17:20:37 -07001936// true and sets |*out_session| to the negotiated SSL session. If the test is a
1937// resumption attempt, |is_resume| is true and |session| is the session from the
1938// previous exchange.
Robert Sloane56da3e2017-06-26 08:26:42 -07001939static bool DoConnection(bssl::UniquePtr<SSL_SESSION> *out_session,
1940 SSL_CTX *ssl_ctx, const TestConfig *config,
1941 const TestConfig *retry_config, bool is_resume,
1942 SSL_SESSION *session) {
David Benjaminf0c4a6c2016-08-11 13:26:41 -04001943 bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
Adam Langleye9ada862015-05-11 17:20:37 -07001944 if (!ssl) {
1945 return false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08001946 }
1947
David Benjamind316cba2016-06-02 16:17:39 -04001948 if (!SetTestConfig(ssl.get(), config) ||
Adam Langleye9ada862015-05-11 17:20:37 -07001949 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
1950 return false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08001951 }
1952
Robert Sloan6d0d00e2017-03-27 07:13:07 -07001953 GetTestState(ssl.get())->is_resume = is_resume;
1954
Adam Langleye9ada862015-05-11 17:20:37 -07001955 if (config->fallback_scsv &&
1956 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
1957 return false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08001958 }
David Benjamin95add822016-10-19 01:09:12 -04001959 // Install the certificate synchronously if nothing else will handle it.
1960 if (!config->use_early_callback &&
1961 !config->use_old_client_cert_callback &&
1962 !config->async &&
1963 !InstallCertificate(ssl.get())) {
1964 return false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08001965 }
Steven Valdeze7531f02016-12-14 13:29:57 -05001966 if (!config->use_old_client_cert_callback) {
1967 SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
1968 }
Robert Sloanb6d070c2017-07-24 08:40:01 -07001969 int mode = SSL_VERIFY_NONE;
Adam Langleyd9e397b2015-01-22 14:27:53 -08001970 if (config->require_any_client_certificate) {
Robert Sloanb6d070c2017-07-24 08:40:01 -07001971 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
Kenny Rootb8494592015-09-25 02:29:14 +00001972 }
1973 if (config->verify_peer) {
Robert Sloanb6d070c2017-07-24 08:40:01 -07001974 mode = SSL_VERIFY_PEER;
Adam Langleyd9e397b2015-01-22 14:27:53 -08001975 }
Robert Sloanf6200e72017-07-10 08:09:18 -07001976 if (config->verify_peer_if_no_obc) {
1977 // Set SSL_VERIFY_FAIL_IF_NO_PEER_CERT so testing whether client
1978 // certificates were requested is easy.
Robert Sloanb6d070c2017-07-24 08:40:01 -07001979 mode = SSL_VERIFY_PEER | SSL_VERIFY_PEER_IF_NO_OBC |
1980 SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1981 }
1982 if (config->use_custom_verify_callback) {
1983 SSL_set_custom_verify(ssl.get(), mode, CustomVerifyCallback);
1984 } else if (mode != SSL_VERIFY_NONE) {
1985 SSL_set_verify(ssl.get(), mode, NULL);
Robert Sloanf6200e72017-07-10 08:09:18 -07001986 }
Adam Langleyd9e397b2015-01-22 14:27:53 -08001987 if (config->false_start) {
Adam Langleye9ada862015-05-11 17:20:37 -07001988 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
Adam Langleyd9e397b2015-01-22 14:27:53 -08001989 }
1990 if (config->cbc_record_splitting) {
Adam Langleye9ada862015-05-11 17:20:37 -07001991 SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
Adam Langleyd9e397b2015-01-22 14:27:53 -08001992 }
1993 if (config->partial_write) {
Adam Langleye9ada862015-05-11 17:20:37 -07001994 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
Adam Langleyd9e397b2015-01-22 14:27:53 -08001995 }
David Benjamind316cba2016-06-02 16:17:39 -04001996 if (config->no_tls13) {
1997 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
1998 }
Adam Langleyd9e397b2015-01-22 14:27:53 -08001999 if (config->no_tls12) {
Adam Langleye9ada862015-05-11 17:20:37 -07002000 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
Adam Langleyd9e397b2015-01-22 14:27:53 -08002001 }
2002 if (config->no_tls11) {
Adam Langleye9ada862015-05-11 17:20:37 -07002003 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
Adam Langleyd9e397b2015-01-22 14:27:53 -08002004 }
2005 if (config->no_tls1) {
Adam Langleye9ada862015-05-11 17:20:37 -07002006 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
Adam Langleyd9e397b2015-01-22 14:27:53 -08002007 }
2008 if (config->no_ssl3) {
Adam Langleye9ada862015-05-11 17:20:37 -07002009 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
Adam Langleyd9e397b2015-01-22 14:27:53 -08002010 }
David Benjaminc895d6b2016-08-11 13:26:41 -04002011 if (!config->expected_channel_id.empty() ||
2012 config->enable_channel_id) {
David Benjamin1b249672016-12-06 18:25:50 -05002013 SSL_set_tls_channel_id_enabled(ssl.get(), 1);
Adam Langleyd9e397b2015-01-22 14:27:53 -08002014 }
2015 if (!config->send_channel_id.empty()) {
David Benjamin1b249672016-12-06 18:25:50 -05002016 SSL_set_tls_channel_id_enabled(ssl.get(), 1);
Adam Langleye9ada862015-05-11 17:20:37 -07002017 if (!config->async) {
2018 // The async case will be supplied by |ChannelIdCallback|.
David Benjaminf0c4a6c2016-08-11 13:26:41 -04002019 bssl::UniquePtr<EVP_PKEY> pkey = LoadPrivateKey(config->send_channel_id);
Adam Langleye9ada862015-05-11 17:20:37 -07002020 if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
2021 return false;
2022 }
Adam Langleyd9e397b2015-01-22 14:27:53 -08002023 }
Adam Langleyd9e397b2015-01-22 14:27:53 -08002024 }
Robert Sloan978112c2018-01-22 12:53:01 -08002025 if (!config->send_token_binding_params.empty()) {
2026 SSL_set_token_binding_params(ssl.get(),
2027 reinterpret_cast<const uint8_t *>(
2028 config->send_token_binding_params.data()),
2029 config->send_token_binding_params.length());
2030 }
Adam Langleye9ada862015-05-11 17:20:37 -07002031 if (!config->host_name.empty() &&
2032 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
2033 return false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08002034 }
Adam Langleye9ada862015-05-11 17:20:37 -07002035 if (!config->advertise_alpn.empty() &&
2036 SSL_set_alpn_protos(ssl.get(),
2037 (const uint8_t *)config->advertise_alpn.data(),
2038 config->advertise_alpn.size()) != 0) {
2039 return false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08002040 }
2041 if (!config->psk.empty()) {
Adam Langleye9ada862015-05-11 17:20:37 -07002042 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
2043 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
Adam Langleyd9e397b2015-01-22 14:27:53 -08002044 }
2045 if (!config->psk_identity.empty() &&
Adam Langleye9ada862015-05-11 17:20:37 -07002046 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
2047 return false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08002048 }
2049 if (!config->srtp_profiles.empty() &&
Adam Langleye9ada862015-05-11 17:20:37 -07002050 !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
2051 return false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08002052 }
Robert Sloana94fe052017-02-21 08:49:28 -08002053 if (config->enable_ocsp_stapling) {
2054 SSL_enable_ocsp_stapling(ssl.get());
Adam Langleyd9e397b2015-01-22 14:27:53 -08002055 }
Robert Sloana94fe052017-02-21 08:49:28 -08002056 if (config->enable_signed_cert_timestamps) {
2057 SSL_enable_signed_cert_timestamps(ssl.get());
Adam Langleyd9e397b2015-01-22 14:27:53 -08002058 }
David Benjamin7c0d06c2016-08-11 13:26:41 -04002059 if (config->min_version != 0 &&
2060 !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) {
2061 return false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08002062 }
David Benjamin7c0d06c2016-08-11 13:26:41 -04002063 if (config->max_version != 0 &&
2064 !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) {
2065 return false;
David Benjaminc895d6b2016-08-11 13:26:41 -04002066 }
Adam Langleyd9e397b2015-01-22 14:27:53 -08002067 if (config->mtu != 0) {
Adam Langleye9ada862015-05-11 17:20:37 -07002068 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
2069 SSL_set_mtu(ssl.get(), config->mtu);
2070 }
2071 if (config->install_ddos_callback) {
2072 SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
2073 }
Kenny Roote99801b2015-11-06 15:31:15 -08002074 if (config->renegotiate_once) {
2075 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_once);
2076 }
2077 if (config->renegotiate_freely) {
2078 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
Adam Langleyd9e397b2015-01-22 14:27:53 -08002079 }
Adam Langleyfad63272015-11-12 12:15:39 -08002080 if (config->renegotiate_ignore) {
2081 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_ignore);
2082 }
Kenny Rootb8494592015-09-25 02:29:14 +00002083 if (!config->check_close_notify) {
2084 SSL_set_quiet_shutdown(ssl.get(), 1);
2085 }
Adam Langley4139edb2016-01-13 15:00:54 -08002086 if (config->p384_only) {
2087 int nid = NID_secp384r1;
2088 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
2089 return false;
2090 }
2091 }
2092 if (config->enable_all_curves) {
2093 static const int kAllCurves[] = {
Robert Sloan6f79a502017-04-03 09:16:40 -07002094 NID_secp224r1, NID_X9_62_prime256v1, NID_secp384r1,
2095 NID_secp521r1, NID_X25519,
Adam Langley4139edb2016-01-13 15:00:54 -08002096 };
2097 if (!SSL_set1_curves(ssl.get(), kAllCurves,
David Benjaminf0c4a6c2016-08-11 13:26:41 -04002098 OPENSSL_ARRAY_SIZE(kAllCurves))) {
Adam Langley4139edb2016-01-13 15:00:54 -08002099 return false;
2100 }
2101 }
David Benjamind316cba2016-06-02 16:17:39 -04002102 if (config->initial_timeout_duration_ms > 0) {
2103 DTLSv1_set_initial_timeout_duration(ssl.get(),
2104 config->initial_timeout_duration_ms);
2105 }
Steven Valdezbb1ceac2016-10-07 10:34:51 -04002106 if (config->max_cert_list > 0) {
2107 SSL_set_max_cert_list(ssl.get(), config->max_cert_list);
2108 }
Robert Sloan8f860b12017-08-28 07:37:06 -07002109 if (config->retain_only_sha256_client_cert) {
Steven Valdez909b19f2016-11-21 15:35:44 -05002110 SSL_set_retain_only_sha256_of_client_certs(ssl.get(), 1);
2111 }
Steven Valdezb0b45c62017-01-17 16:23:54 -05002112 if (config->max_send_fragment > 0) {
2113 SSL_set_max_send_fragment(ssl.get(), config->max_send_fragment);
2114 }
Robert Sloan0db7f542018-01-16 15:48:33 -08002115 if (config->dummy_pq_padding_len > 0 &&
2116 !SSL_set_dummy_pq_padding_size(ssl.get(), config->dummy_pq_padding_len)) {
2117 return false;
2118 }
Robert Sloan8542c082018-02-05 09:07:34 -08002119 if (!config->quic_transport_params.empty()) {
2120 if (!SSL_set_quic_transport_params(
2121 ssl.get(),
2122 reinterpret_cast<const uint8_t *>(
2123 config->quic_transport_params.data()),
2124 config->quic_transport_params.size())) {
2125 return false;
2126 }
2127 }
Adam Langleyd9e397b2015-01-22 14:27:53 -08002128
Adam Langleye9ada862015-05-11 17:20:37 -07002129 int sock = Connect(config->port);
2130 if (sock == -1) {
2131 return false;
2132 }
2133 SocketCloser closer(sock);
2134
David Benjaminf0c4a6c2016-08-11 13:26:41 -04002135 bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
Adam Langleye9ada862015-05-11 17:20:37 -07002136 if (!bio) {
2137 return false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08002138 }
2139 if (config->is_dtls) {
Robert Sloan7d422bc2017-03-06 10:04:29 -08002140 bssl::UniquePtr<BIO> packeted = PacketedBioCreate(&g_clock);
David Benjamin4969cc92016-04-22 15:02:23 -04002141 if (!packeted) {
2142 return false;
2143 }
David Benjamin6e899c72016-06-09 18:02:18 -04002144 GetTestState(ssl.get())->packeted_bio = packeted.get();
Adam Langleye9ada862015-05-11 17:20:37 -07002145 BIO_push(packeted.get(), bio.release());
2146 bio = std::move(packeted);
Adam Langleyd9e397b2015-01-22 14:27:53 -08002147 }
2148 if (config->async) {
David Benjaminf0c4a6c2016-08-11 13:26:41 -04002149 bssl::UniquePtr<BIO> async_scoped =
Adam Langleye9ada862015-05-11 17:20:37 -07002150 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
David Benjamin4969cc92016-04-22 15:02:23 -04002151 if (!async_scoped) {
2152 return false;
2153 }
Adam Langleye9ada862015-05-11 17:20:37 -07002154 BIO_push(async_scoped.get(), bio.release());
2155 GetTestState(ssl.get())->async_bio = async_scoped.get();
2156 bio = std::move(async_scoped);
Adam Langleyd9e397b2015-01-22 14:27:53 -08002157 }
Adam Langleye9ada862015-05-11 17:20:37 -07002158 SSL_set_bio(ssl.get(), bio.get(), bio.get());
2159 bio.release(); // SSL_set_bio takes ownership.
Adam Langleyd9e397b2015-01-22 14:27:53 -08002160
2161 if (session != NULL) {
Adam Langleye9ada862015-05-11 17:20:37 -07002162 if (!config->is_server) {
2163 if (SSL_set_session(ssl.get(), session) != 1) {
2164 return false;
2165 }
2166 } else if (config->async) {
2167 // The internal session cache is disabled, so install the session
2168 // manually.
David Benjaminc895d6b2016-08-11 13:26:41 -04002169 SSL_SESSION_up_ref(session);
2170 GetTestState(ssl.get())->pending_session.reset(session);
Adam Langleyd9e397b2015-01-22 14:27:53 -08002171 }
2172 }
2173
Adam Langleyf4e42722015-06-04 17:45:09 -07002174 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
2175 fprintf(stderr, "non-null cipher before handshake\n");
2176 return false;
2177 }
2178
Robert Sloan6d0d00e2017-03-27 07:13:07 -07002179 if (config->is_server) {
2180 SSL_set_accept_state(ssl.get());
Adam Langleye9ada862015-05-11 17:20:37 -07002181 } else {
Robert Sloan6d0d00e2017-03-27 07:13:07 -07002182 SSL_set_connect_state(ssl.get());
2183 }
2184
Robert Sloan8542c082018-02-05 09:07:34 -08002185 bool ret = DoExchange(out_session, &ssl, config, is_resume, false);
Robert Sloane56da3e2017-06-26 08:26:42 -07002186 if (!config->is_server && is_resume && config->expect_reject_early_data) {
2187 // We must have failed due to an early data rejection.
2188 if (ret) {
2189 fprintf(stderr, "0-RTT exchange unexpected succeeded.\n");
2190 return false;
2191 }
2192 if (SSL_get_error(ssl.get(), -1) != SSL_ERROR_EARLY_DATA_REJECTED) {
2193 fprintf(stderr,
2194 "SSL_get_error did not signal SSL_ERROR_EARLY_DATA_REJECTED.\n");
2195 return false;
2196 }
2197
2198 // Before reseting, early state should still be available.
2199 if (!SSL_in_early_data(ssl.get()) ||
2200 !CheckHandshakeProperties(ssl.get(), is_resume, config)) {
2201 fprintf(stderr, "SSL_in_early_data returned false before reset.\n");
2202 return false;
2203 }
2204
2205 // Reset the connection and try again at 1-RTT.
2206 SSL_reset_early_data_reject(ssl.get());
2207
2208 // After reseting, the socket should report it is no longer in an early data
2209 // state.
2210 if (SSL_in_early_data(ssl.get())) {
2211 fprintf(stderr, "SSL_in_early_data returned true after reset.\n");
2212 return false;
2213 }
2214
2215 if (!SetTestConfig(ssl.get(), retry_config)) {
2216 return false;
2217 }
2218
Robert Sloan8542c082018-02-05 09:07:34 -08002219 assert(!config->handoff);
2220 ret = DoExchange(out_session, &ssl, retry_config, is_resume, true);
Robert Sloane56da3e2017-06-26 08:26:42 -07002221 }
Robert Sloanfe7cd212017-08-07 09:03:39 -07002222
2223 if (!ret) {
2224 return false;
2225 }
2226
2227 if (!GetTestState(ssl.get())->msg_callback_ok) {
2228 return false;
2229 }
2230
2231 if (!config->expect_msg_callback.empty() &&
2232 GetTestState(ssl.get())->msg_callback_text !=
2233 config->expect_msg_callback) {
2234 fprintf(stderr, "Bad message callback trace. Wanted:\n%s\nGot:\n%s\n",
2235 config->expect_msg_callback.c_str(),
2236 GetTestState(ssl.get())->msg_callback_text.c_str());
2237 return false;
2238 }
2239
2240 return true;
Robert Sloane56da3e2017-06-26 08:26:42 -07002241}
2242
Robert Sloan8542c082018-02-05 09:07:34 -08002243static bool HandoffReady(SSL *ssl, int ret) {
2244 return ret < 0 && SSL_get_error(ssl, ret) == SSL_ERROR_HANDOFF;
2245}
2246
2247static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
2248 bssl::UniquePtr<SSL> *ssl_uniqueptr,
Robert Sloane56da3e2017-06-26 08:26:42 -07002249 const TestConfig *config, bool is_resume,
2250 bool is_retry) {
Robert Sloan6d0d00e2017-03-27 07:13:07 -07002251 int ret;
Robert Sloan8542c082018-02-05 09:07:34 -08002252 SSL *ssl = ssl_uniqueptr->get();
2253
Robert Sloan6d0d00e2017-03-27 07:13:07 -07002254 if (!config->implicit_handshake) {
Robert Sloan8542c082018-02-05 09:07:34 -08002255 if (config->handoff) {
2256 bssl::UniquePtr<SSL_CTX> ctx_handoff(SSL_CTX_new(TLSv1_method()));
2257 if (!ctx_handoff) {
2258 return false;
2259 }
2260 SSL_CTX_set_handoff_mode(ctx_handoff.get(), 1);
2261
2262 bssl::UniquePtr<SSL> ssl_handoff(SSL_new(ctx_handoff.get()));
2263 if (!ssl_handoff) {
2264 return false;
2265 }
2266 SSL_set_accept_state(ssl_handoff.get());
2267 if (!MoveExData(ssl_handoff.get(), ssl)) {
2268 return false;
2269 }
2270 MoveBIOs(ssl_handoff.get(), ssl);
2271
2272 do {
2273 ret = CheckIdempotentError("SSL_do_handshake", ssl_handoff.get(),
2274 [&]() -> int {
2275 return SSL_do_handshake(ssl_handoff.get());
2276 });
2277 } while (!HandoffReady(ssl_handoff.get(), ret) &&
2278 config->async &&
2279 RetryAsync(ssl_handoff.get(), ret));
2280
2281 if (!HandoffReady(ssl_handoff.get(), ret)) {
2282 fprintf(stderr, "Handshake failed while waiting for handoff.\n");
2283 return false;
2284 }
2285
2286 bssl::ScopedCBB cbb;
2287 bssl::Array<uint8_t> handoff;
2288 if (!CBB_init(cbb.get(), 512) ||
2289 !SSL_serialize_handoff(ssl_handoff.get(), cbb.get()) ||
2290 !CBBFinishArray(cbb.get(), &handoff)) {
2291 fprintf(stderr, "Handoff serialisation failed.\n");
2292 return false;
2293 }
2294
2295 MoveBIOs(ssl, ssl_handoff.get());
2296 if (!MoveExData(ssl, ssl_handoff.get())) {
2297 return false;
2298 }
2299
2300 if (!SSL_apply_handoff(ssl, handoff)) {
2301 fprintf(stderr, "Handoff application failed.\n");
2302 return false;
2303 }
2304 }
2305
Adam Langleye9ada862015-05-11 17:20:37 -07002306 do {
Robert Sloan36272962017-10-23 10:28:39 -07002307 ret = CheckIdempotentError("SSL_do_handshake", ssl, [&]() -> int {
2308 return SSL_do_handshake(ssl);
2309 });
Robert Sloane56da3e2017-06-26 08:26:42 -07002310 } while (config->async && RetryAsync(ssl, ret));
Robert Sloan8542c082018-02-05 09:07:34 -08002311
Kenny Rootb8494592015-09-25 02:29:14 +00002312 if (ret != 1 ||
Robert Sloane56da3e2017-06-26 08:26:42 -07002313 !CheckHandshakeProperties(ssl, is_resume, config)) {
Adam Langleye9ada862015-05-11 17:20:37 -07002314 return false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08002315 }
2316
Robert Sloan8542c082018-02-05 09:07:34 -08002317 if (config->handoff) {
2318 bssl::ScopedCBB cbb;
2319 bssl::Array<uint8_t> handback;
2320 if (!CBB_init(cbb.get(), 512) ||
2321 !SSL_serialize_handback(ssl, cbb.get()) ||
2322 !CBBFinishArray(cbb.get(), &handback)) {
2323 fprintf(stderr, "Handback serialisation failed.\n");
2324 return false;
2325 }
2326
2327 bssl::UniquePtr<SSL_CTX> ctx_handback(SSL_CTX_new(TLSv1_method()));
2328 SSL_CTX_set_msg_callback(ctx_handback.get(), MessageCallback);
2329 bssl::UniquePtr<SSL> ssl_handback(SSL_new(ctx_handback.get()));
2330 if (!ssl_handback) {
2331 return false;
2332 }
2333 if (!SSL_apply_handback(ssl_handback.get(), handback)) {
2334 fprintf(stderr, "Applying handback failed.\n");
2335 return false;
2336 }
2337
2338 MoveBIOs(ssl_handback.get(), ssl);
2339 if (!MoveExData(ssl_handback.get(), ssl)) {
2340 return false;
2341 }
2342
2343 *ssl_uniqueptr = std::move(ssl_handback);
2344 ssl = ssl_uniqueptr->get();
2345 }
2346
Robert Sloan29c1d2c2017-10-30 14:10:28 -07002347 if (is_resume && !is_retry && !config->is_server &&
2348 config->expect_no_offer_early_data && SSL_in_early_data(ssl)) {
2349 fprintf(stderr, "Client unexpectedly offered early data.\n");
2350 return false;
2351 }
2352
Robert Sloan6f79a502017-04-03 09:16:40 -07002353 if (config->handshake_twice) {
2354 do {
Robert Sloane56da3e2017-06-26 08:26:42 -07002355 ret = SSL_do_handshake(ssl);
2356 } while (config->async && RetryAsync(ssl, ret));
Robert Sloan6f79a502017-04-03 09:16:40 -07002357 if (ret != 1) {
2358 return false;
2359 }
2360 }
2361
2362 // Skip the |config->async| logic as this should be a no-op.
2363 if (config->no_op_extra_handshake &&
Robert Sloane56da3e2017-06-26 08:26:42 -07002364 SSL_do_handshake(ssl) != 1) {
Robert Sloan6f79a502017-04-03 09:16:40 -07002365 fprintf(stderr, "Extra SSL_do_handshake was not a no-op.\n");
2366 return false;
2367 }
2368
Kenny Rootb8494592015-09-25 02:29:14 +00002369 // Reset the state to assert later that the callback isn't called in
2370 // renegotations.
Robert Sloane56da3e2017-06-26 08:26:42 -07002371 GetTestState(ssl)->got_new_session = false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08002372 }
2373
Robert Sloan55818102017-12-18 11:26:17 -08002374 if (config->export_early_keying_material > 0) {
2375 std::vector<uint8_t> result(
2376 static_cast<size_t>(config->export_early_keying_material));
2377 if (!SSL_export_early_keying_material(
2378 ssl, result.data(), result.size(), config->export_label.data(),
2379 config->export_label.size(),
2380 reinterpret_cast<const uint8_t *>(config->export_context.data()),
2381 config->export_context.size())) {
2382 fprintf(stderr, "failed to export keying material\n");
2383 return false;
2384 }
2385 if (WriteAll(ssl, result.data(), result.size()) < 0) {
2386 return false;
2387 }
2388 }
2389
Adam Langleye9ada862015-05-11 17:20:37 -07002390 if (config->export_keying_material > 0) {
2391 std::vector<uint8_t> result(
2392 static_cast<size_t>(config->export_keying_material));
2393 if (!SSL_export_keying_material(
Robert Sloane56da3e2017-06-26 08:26:42 -07002394 ssl, result.data(), result.size(), config->export_label.data(),
2395 config->export_label.size(),
2396 reinterpret_cast<const uint8_t *>(config->export_context.data()),
Adam Langleye9ada862015-05-11 17:20:37 -07002397 config->export_context.size(), config->use_export_context)) {
2398 fprintf(stderr, "failed to export keying material\n");
2399 return false;
2400 }
Robert Sloane56da3e2017-06-26 08:26:42 -07002401 if (WriteAll(ssl, result.data(), result.size()) < 0) {
Adam Langleye9ada862015-05-11 17:20:37 -07002402 return false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08002403 }
2404 }
2405
Adam Langleyf4e42722015-06-04 17:45:09 -07002406 if (config->tls_unique) {
2407 uint8_t tls_unique[16];
2408 size_t tls_unique_len;
Robert Sloane56da3e2017-06-26 08:26:42 -07002409 if (!SSL_get_tls_unique(ssl, tls_unique, &tls_unique_len,
Adam Langleyf4e42722015-06-04 17:45:09 -07002410 sizeof(tls_unique))) {
2411 fprintf(stderr, "failed to get tls-unique\n");
2412 return false;
2413 }
2414
2415 if (tls_unique_len != 12) {
2416 fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
2417 static_cast<unsigned>(tls_unique_len));
2418 return false;
2419 }
2420
Robert Sloane56da3e2017-06-26 08:26:42 -07002421 if (WriteAll(ssl, tls_unique, tls_unique_len) < 0) {
Adam Langleyf4e42722015-06-04 17:45:09 -07002422 return false;
2423 }
2424 }
2425
David Benjaminc895d6b2016-08-11 13:26:41 -04002426 if (config->send_alert) {
Robert Sloane56da3e2017-06-26 08:26:42 -07002427 if (DoSendFatalAlert(ssl, SSL_AD_DECOMPRESSION_FAILURE) < 0) {
David Benjaminc895d6b2016-08-11 13:26:41 -04002428 return false;
2429 }
2430 return true;
2431 }
2432
Adam Langleyd9e397b2015-01-22 14:27:53 -08002433 if (config->write_different_record_sizes) {
2434 if (config->is_dtls) {
2435 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
Adam Langleye9ada862015-05-11 17:20:37 -07002436 return false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08002437 }
2438 // This mode writes a number of different record sizes in an attempt to
2439 // trip up the CBC record splitting code.
Kenny Rootb8494592015-09-25 02:29:14 +00002440 static const size_t kBufLen = 32769;
2441 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
Robert Sloan69939df2017-01-09 10:53:07 -08002442 OPENSSL_memset(buf.get(), 0x42, kBufLen);
Adam Langleyd9e397b2015-01-22 14:27:53 -08002443 static const size_t kRecordSizes[] = {
2444 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
David Benjaminf0c4a6c2016-08-11 13:26:41 -04002445 for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
Adam Langleyd9e397b2015-01-22 14:27:53 -08002446 const size_t len = kRecordSizes[i];
Kenny Rootb8494592015-09-25 02:29:14 +00002447 if (len > kBufLen) {
Adam Langleyd9e397b2015-01-22 14:27:53 -08002448 fprintf(stderr, "Bad kRecordSizes value.\n");
Adam Langleye9ada862015-05-11 17:20:37 -07002449 return false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08002450 }
Robert Sloane56da3e2017-06-26 08:26:42 -07002451 if (WriteAll(ssl, buf.get(), len) < 0) {
Adam Langleye9ada862015-05-11 17:20:37 -07002452 return false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08002453 }
2454 }
2455 } else {
Robert Sloan572a4e22017-04-17 10:52:19 -07002456 static const char kInitialWrite[] = "hello";
2457 bool pending_initial_write = false;
Robert Sloan69939df2017-01-09 10:53:07 -08002458 if (config->read_with_unfinished_write) {
2459 if (!config->async) {
2460 fprintf(stderr, "-read-with-unfinished-write requires -async.\n");
2461 return false;
2462 }
2463
Robert Sloane56da3e2017-06-26 08:26:42 -07002464 // Let only one byte of the record through.
2465 AsyncBioAllowWrite(GetTestState(ssl)->async_bio, 1);
Robert Sloan572a4e22017-04-17 10:52:19 -07002466 int write_ret =
Robert Sloane56da3e2017-06-26 08:26:42 -07002467 SSL_write(ssl, kInitialWrite, strlen(kInitialWrite));
2468 if (SSL_get_error(ssl, write_ret) != SSL_ERROR_WANT_WRITE) {
Robert Sloan69939df2017-01-09 10:53:07 -08002469 fprintf(stderr, "Failed to leave unfinished write.\n");
2470 return false;
2471 }
Robert Sloan572a4e22017-04-17 10:52:19 -07002472 pending_initial_write = true;
2473 } else if (config->shim_writes_first) {
Robert Sloane56da3e2017-06-26 08:26:42 -07002474 if (WriteAll(ssl, kInitialWrite, strlen(kInitialWrite)) < 0) {
Adam Langleye9ada862015-05-11 17:20:37 -07002475 return false;
2476 }
Adam Langleyd9e397b2015-01-22 14:27:53 -08002477 }
Kenny Rootb8494592015-09-25 02:29:14 +00002478 if (!config->shim_shuts_down) {
2479 for (;;) {
Kenny Rootb8494592015-09-25 02:29:14 +00002480 // Read only 512 bytes at a time in TLS to ensure records may be
2481 // returned in multiple reads.
Steven Valdezb0b45c62017-01-17 16:23:54 -05002482 size_t read_size = config->is_dtls ? 16384 : 512;
2483 if (config->read_size > 0) {
2484 read_size = config->read_size;
2485 }
2486 std::unique_ptr<uint8_t[]> buf(new uint8_t[read_size]);
2487
Robert Sloane56da3e2017-06-26 08:26:42 -07002488 int n = DoRead(ssl, buf.get(), read_size);
2489 int err = SSL_get_error(ssl, n);
Kenny Rootb8494592015-09-25 02:29:14 +00002490 if (err == SSL_ERROR_ZERO_RETURN ||
2491 (n == 0 && err == SSL_ERROR_SYSCALL)) {
2492 if (n != 0) {
2493 fprintf(stderr, "Invalid SSL_get_error output\n");
2494 return false;
2495 }
2496 // Stop on either clean or unclean shutdown.
2497 break;
2498 } else if (err != SSL_ERROR_NONE) {
2499 if (n > 0) {
2500 fprintf(stderr, "Invalid SSL_get_error output\n");
2501 return false;
2502 }
2503 return false;
2504 }
2505 // Successfully read data.
2506 if (n <= 0) {
Adam Langleyd9e397b2015-01-22 14:27:53 -08002507 fprintf(stderr, "Invalid SSL_get_error output\n");
Adam Langleye9ada862015-05-11 17:20:37 -07002508 return false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08002509 }
Kenny Rootb8494592015-09-25 02:29:14 +00002510
Robert Sloane56da3e2017-06-26 08:26:42 -07002511 if (!config->is_server && is_resume && !is_retry &&
2512 config->expect_reject_early_data) {
2513 fprintf(stderr,
2514 "Unexpectedly received data instead of 0-RTT reject.\n");
2515 return false;
2516 }
2517
Kenny Rootb8494592015-09-25 02:29:14 +00002518 // After a successful read, with or without False Start, the handshake
Robert Sloan6d0d00e2017-03-27 07:13:07 -07002519 // must be complete unless we are doing early data.
Robert Sloane56da3e2017-06-26 08:26:42 -07002520 if (!GetTestState(ssl)->handshake_done &&
2521 !SSL_early_data_accepted(ssl)) {
Kenny Rootb8494592015-09-25 02:29:14 +00002522 fprintf(stderr, "handshake was not completed after SSL_read\n");
Adam Langleye9ada862015-05-11 17:20:37 -07002523 return false;
Adam Langleyd9e397b2015-01-22 14:27:53 -08002524 }
Adam Langleye9ada862015-05-11 17:20:37 -07002525
Robert Sloan572a4e22017-04-17 10:52:19 -07002526 // Clear the initial write, if unfinished.
2527 if (pending_initial_write) {
Robert Sloane56da3e2017-06-26 08:26:42 -07002528 if (WriteAll(ssl, kInitialWrite, strlen(kInitialWrite)) < 0) {
Robert Sloan572a4e22017-04-17 10:52:19 -07002529 return false;
2530 }
2531 pending_initial_write = false;
2532 }
2533
Kenny Rootb8494592015-09-25 02:29:14 +00002534 for (int i = 0; i < n; i++) {
2535 buf[i] ^= 0xff;
2536 }
Robert Sloane56da3e2017-06-26 08:26:42 -07002537 if (WriteAll(ssl, buf.get(), n) < 0) {
Kenny Rootb8494592015-09-25 02:29:14 +00002538 return false;
2539 }
Adam Langleyd9e397b2015-01-22 14:27:53 -08002540 }
2541 }
2542 }
2543
Kenny Rootb8494592015-09-25 02:29:14 +00002544 if (!config->is_server && !config->false_start &&
2545 !config->implicit_handshake &&
David Benjaminc895d6b2016-08-11 13:26:41 -04002546 // Session tickets are sent post-handshake in TLS 1.3.
Robert Sloane56da3e2017-06-26 08:26:42 -07002547 GetProtocolVersion(ssl) < TLS1_3_VERSION &&
2548 GetTestState(ssl)->got_new_session) {
Kenny Rootb8494592015-09-25 02:29:14 +00002549 fprintf(stderr, "new session was established after the handshake\n");
2550 return false;
2551 }
2552
Robert Sloane56da3e2017-06-26 08:26:42 -07002553 if (GetProtocolVersion(ssl) >= TLS1_3_VERSION && !config->is_server) {
David Benjaminc895d6b2016-08-11 13:26:41 -04002554 bool expect_new_session =
2555 !config->expect_no_session && !config->shim_shuts_down;
Robert Sloane56da3e2017-06-26 08:26:42 -07002556 if (expect_new_session != GetTestState(ssl)->got_new_session) {
David Benjaminc895d6b2016-08-11 13:26:41 -04002557 fprintf(stderr,
2558 "new session was%s cached, but we expected the opposite\n",
Robert Sloane56da3e2017-06-26 08:26:42 -07002559 GetTestState(ssl)->got_new_session ? "" : " not");
David Benjaminc895d6b2016-08-11 13:26:41 -04002560 return false;
2561 }
Robert Sloan69939df2017-01-09 10:53:07 -08002562
2563 if (expect_new_session) {
Robert Sloanb1b54b82017-11-06 13:50:02 -08002564 bool got_early_data =
Robert Sloane56da3e2017-06-26 08:26:42 -07002565 GetTestState(ssl)->new_session->ticket_max_early_data != 0;
Robert Sloanb1b54b82017-11-06 13:50:02 -08002566 if (config->expect_ticket_supports_early_data != got_early_data) {
2567 fprintf(stderr,
2568 "new session did%s support early data, but we expected the "
2569 "opposite\n",
2570 got_early_data ? "" : " not");
Robert Sloan69939df2017-01-09 10:53:07 -08002571 return false;
2572 }
2573 }
David Benjaminc895d6b2016-08-11 13:26:41 -04002574 }
2575
Adam Langleyd9e397b2015-01-22 14:27:53 -08002576 if (out_session) {
Robert Sloane56da3e2017-06-26 08:26:42 -07002577 *out_session = std::move(GetTestState(ssl)->new_session);
Adam Langleyd9e397b2015-01-22 14:27:53 -08002578 }
2579
Robert Sloane56da3e2017-06-26 08:26:42 -07002580 ret = DoShutdown(ssl);
Kenny Rootb8494592015-09-25 02:29:14 +00002581
2582 if (config->shim_shuts_down && config->check_close_notify) {
2583 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
2584 // it returns zero when our close_notify is sent, then one when the peer's
2585 // is received.
2586 if (ret != 0) {
2587 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
2588 return false;
2589 }
Robert Sloane56da3e2017-06-26 08:26:42 -07002590 ret = DoShutdown(ssl);
Kenny Rootb8494592015-09-25 02:29:14 +00002591 }
2592
2593 if (ret != 1) {
2594 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
2595 return false;
2596 }
2597
Robert Sloan8f860b12017-08-28 07:37:06 -07002598 if (SSL_total_renegotiations(ssl) > 0) {
2599 if (!SSL_get_session(ssl)->not_resumable) {
2600 fprintf(stderr,
2601 "Renegotiations should never produce resumable sessions.\n");
2602 return false;
2603 }
2604
Robert Sloand1d118f2017-09-11 09:00:48 -07002605 if (SSL_session_reused(ssl)) {
2606 fprintf(stderr, "Renegotiations should never resume sessions.\n");
2607 return false;
2608 }
2609
Robert Sloan8f860b12017-08-28 07:37:06 -07002610 // Re-check authentication properties after a renegotiation. The reported
2611 // values should remain unchanged even if the server sent different SCT
2612 // lists.
2613 if (!CheckAuthProperties(ssl, is_resume, config)) {
2614 return false;
2615 }
2616 }
2617
Robert Sloane56da3e2017-06-26 08:26:42 -07002618 if (SSL_total_renegotiations(ssl) != config->expect_total_renegotiations) {
Kenny Roote99801b2015-11-06 15:31:15 -08002619 fprintf(stderr, "Expected %d renegotiations, got %d\n",
Robert Sloane56da3e2017-06-26 08:26:42 -07002620 config->expect_total_renegotiations, SSL_total_renegotiations(ssl));
Kenny Roote99801b2015-11-06 15:31:15 -08002621 return false;
2622 }
2623
Adam Langleye9ada862015-05-11 17:20:37 -07002624 return true;
Adam Langleyd9e397b2015-01-22 14:27:53 -08002625}
2626
David Benjamin4969cc92016-04-22 15:02:23 -04002627class StderrDelimiter {
2628 public:
2629 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
2630};
2631
David Benjamin1b249672016-12-06 18:25:50 -05002632int main(int argc, char **argv) {
David Benjamin4969cc92016-04-22 15:02:23 -04002633 // To distinguish ASan's output from ours, add a trailing message to stderr.
2634 // Anything following this line will be considered an error.
2635 StderrDelimiter delimiter;
2636
Adam Langleye9ada862015-05-11 17:20:37 -07002637#if defined(OPENSSL_WINDOWS)
Robert Sloana27a6a42017-09-05 08:39:28 -07002638 // Initialize Winsock.
Adam Langleye9ada862015-05-11 17:20:37 -07002639 WORD wsa_version = MAKEWORD(2, 2);
2640 WSADATA wsa_data;
2641 int wsa_err = WSAStartup(wsa_version, &wsa_data);
2642 if (wsa_err != 0) {
2643 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
2644 return 1;
2645 }
2646 if (wsa_data.wVersion != wsa_version) {
2647 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
2648 return 1;
2649 }
2650#else
Adam Langleyd9e397b2015-01-22 14:27:53 -08002651 signal(SIGPIPE, SIG_IGN);
2652#endif
2653
Kenny Roote99801b2015-11-06 15:31:15 -08002654 CRYPTO_library_init();
Adam Langleye9ada862015-05-11 17:20:37 -07002655 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
2656 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
2657 if (g_config_index < 0 || g_state_index < 0) {
Adam Langleyd9e397b2015-01-22 14:27:53 -08002658 return 1;
2659 }
2660
Robert Sloane56da3e2017-06-26 08:26:42 -07002661 TestConfig initial_config, resume_config, retry_config;
2662 if (!ParseConfig(argc - 1, argv + 1, &initial_config, &resume_config,
2663 &retry_config)) {
Adam Langleye9ada862015-05-11 17:20:37 -07002664 return Usage(argv[0]);
Adam Langleyd9e397b2015-01-22 14:27:53 -08002665 }
2666
Steven Valdeze7531f02016-12-14 13:29:57 -05002667 g_pool = CRYPTO_BUFFER_POOL_new();
2668
Steven Valdez909b19f2016-11-21 15:35:44 -05002669 // Some code treats the zero time special, so initialize the clock to a
2670 // non-zero time.
2671 g_clock.tv_sec = 1234;
2672 g_clock.tv_usec = 1234;
2673
Robert Sloan8ff03552017-06-14 12:40:58 -07002674 bssl::UniquePtr<SSL_CTX> ssl_ctx;
Adam Langleyd9e397b2015-01-22 14:27:53 -08002675
David Benjaminf0c4a6c2016-08-11 13:26:41 -04002676 bssl::UniquePtr<SSL_SESSION> session;
Robert Sloan8ff03552017-06-14 12:40:58 -07002677 for (int i = 0; i < initial_config.resume_count + 1; i++) {
David Benjaminf0c4a6c2016-08-11 13:26:41 -04002678 bool is_resume = i > 0;
Robert Sloan8ff03552017-06-14 12:40:58 -07002679 TestConfig *config = is_resume ? &resume_config : &initial_config;
2680 ssl_ctx = SetupCtx(ssl_ctx.get(), config);
2681 if (!ssl_ctx) {
2682 ERR_print_errors_fp(stderr);
2683 return 1;
2684 }
2685
2686 if (is_resume && !initial_config.is_server && !session) {
David Benjaminf0c4a6c2016-08-11 13:26:41 -04002687 fprintf(stderr, "No session to offer.\n");
2688 return 1;
2689 }
Adam Langleyd9e397b2015-01-22 14:27:53 -08002690
David Benjaminf0c4a6c2016-08-11 13:26:41 -04002691 bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
Robert Sloanf6200e72017-07-10 08:09:18 -07002692 if (!WriteSettings(i, config, offer_session.get())) {
2693 fprintf(stderr, "Error writing settings.\n");
2694 return 1;
2695 }
Robert Sloane56da3e2017-06-26 08:26:42 -07002696 if (!DoConnection(&session, ssl_ctx.get(), config, &retry_config, is_resume,
2697 offer_session.get())) {
David Benjaminf0c4a6c2016-08-11 13:26:41 -04002698 fprintf(stderr, "Connection %d failed.\n", i + 1);
2699 ERR_print_errors_fp(stderr);
2700 return 1;
2701 }
Steven Valdez909b19f2016-11-21 15:35:44 -05002702
Robert Sloan8ff03552017-06-14 12:40:58 -07002703 if (config->resumption_delay != 0) {
2704 g_clock.tv_sec += config->resumption_delay;
Steven Valdez909b19f2016-11-21 15:35:44 -05002705 }
Adam Langleyd9e397b2015-01-22 14:27:53 -08002706 }
2707
Adam Langleye9ada862015-05-11 17:20:37 -07002708 return 0;
Adam Langleyd9e397b2015-01-22 14:27:53 -08002709}