]> git.ipfire.org Git - thirdparty/openssl.git/blame - test/ossl_shim/ossl_shim.cc
Add missing bn.h include
[thirdparty/openssl.git] / test / ossl_shim / ossl_shim.cc
CommitLineData
eef977aa
MC
1/* 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
15#if !defined(__STDC_FORMAT_MACROS)
16#define __STDC_FORMAT_MACROS
17#endif
18
19#include <openssl/e_os2.h>
20
21#if !defined(OPENSSL_SYS_WINDOWS)
22#include <arpa/inet.h>
23#include <netinet/in.h>
24#include <netinet/tcp.h>
25#include <signal.h>
26#include <sys/socket.h>
27#include <sys/time.h>
28#include <unistd.h>
29#else
30#include <io.h>
7b73b7be 31OPENSSL_MSVC_PRAGMA(warning(push, 3))
eef977aa
MC
32#include <winsock2.h>
33#include <ws2tcpip.h>
7b73b7be 34OPENSSL_MSVC_PRAGMA(warning(pop))
eef977aa 35
7b73b7be 36OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
eef977aa
MC
37#endif
38
7b73b7be 39#include <assert.h>
eef977aa
MC
40#include <inttypes.h>
41#include <string.h>
42
43#include <openssl/bio.h>
44#include <openssl/buffer.h>
bc708af4 45#include <openssl/bn.h>
eef977aa
MC
46#include <openssl/crypto.h>
47#include <openssl/dh.h>
48#include <openssl/err.h>
49#include <openssl/evp.h>
50#include <openssl/hmac.h>
51#include <openssl/objects.h>
52#include <openssl/rand.h>
53#include <openssl/ssl.h>
7b73b7be 54#include <openssl/x509.h>
eef977aa
MC
55
56#include <memory>
57#include <string>
58#include <vector>
59
eef977aa
MC
60#include "async_bio.h"
61#include "packeted_bio.h"
eef977aa
MC
62#include "test_config.h"
63
7b73b7be 64namespace bssl {
eef977aa
MC
65
66#if !defined(OPENSSL_SYS_WINDOWS)
67static int closesocket(int sock) {
68 return close(sock);
69}
70
71static void PrintSocketError(const char *func) {
72 perror(func);
73}
74#else
75static void PrintSocketError(const char *func) {
76 fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
77}
78#endif
79
80static int Usage(const char *program) {
81 fprintf(stderr, "Usage: %s [flags...]\n", program);
82 return 1;
83}
84
85struct TestState {
eef977aa
MC
86 // async_bio is async BIO which pauses reads and writes.
87 BIO *async_bio = nullptr;
7b73b7be
MC
88 // packeted_bio is the packeted BIO which simulates read timeouts.
89 BIO *packeted_bio = nullptr;
eef977aa 90 bool cert_ready = false;
7b73b7be 91 bssl::UniquePtr<SSL_SESSION> session;
eef977aa
MC
92 bool handshake_done = false;
93 // private_key is the underlying private key used when testing custom keys.
7b73b7be 94 bssl::UniquePtr<EVP_PKEY> private_key;
eef977aa 95 bool got_new_session = false;
7b73b7be
MC
96 bssl::UniquePtr<SSL_SESSION> new_session;
97 bool ticket_decrypt_done = false;
98 bool alpn_select_done = false;
eef977aa
MC
99};
100
101static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
102 int index, long argl, void *argp) {
103 delete ((TestState *)ptr);
104}
105
106static int g_config_index = 0;
107static int g_state_index = 0;
108
7b73b7be 109static bool SetTestConfig(SSL *ssl, const TestConfig *config) {
eef977aa
MC
110 return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
111}
112
7b73b7be 113static const TestConfig *GetTestConfig(const SSL *ssl) {
eef977aa
MC
114 return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
115}
116
117static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
118 // |SSL_set_ex_data| takes ownership of |state| only on success.
119 if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
120 state.release();
121 return true;
122 }
123 return false;
124}
125
126static TestState *GetTestState(const SSL *ssl) {
127 return (TestState *)SSL_get_ex_data(ssl, g_state_index);
128}
129
7b73b7be
MC
130static bssl::UniquePtr<X509> LoadCertificate(const std::string &file) {
131 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
eef977aa
MC
132 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
133 return nullptr;
134 }
7b73b7be 135 return bssl::UniquePtr<X509>(PEM_read_bio_X509(bio.get(), NULL, NULL, NULL));
eef977aa
MC
136}
137
7b73b7be
MC
138static bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
139 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
eef977aa
MC
140 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
141 return nullptr;
142 }
7b73b7be
MC
143 return bssl::UniquePtr<EVP_PKEY>(
144 PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
eef977aa
MC
145}
146
147template<typename T>
148struct Free {
149 void operator()(T *buf) {
150 free(buf);
151 }
152};
153
7b73b7be
MC
154static bool GetCertificate(SSL *ssl, bssl::UniquePtr<X509> *out_x509,
155 bssl::UniquePtr<EVP_PKEY> *out_pkey) {
156 const TestConfig *config = GetTestConfig(ssl);
eef977aa 157
eef977aa
MC
158 if (!config->key_file.empty()) {
159 *out_pkey = LoadPrivateKey(config->key_file.c_str());
160 if (!*out_pkey) {
161 return false;
162 }
163 }
164 if (!config->cert_file.empty()) {
165 *out_x509 = LoadCertificate(config->cert_file.c_str());
166 if (!*out_x509) {
167 return false;
168 }
169 }
eef977aa
MC
170 return true;
171}
172
173static bool InstallCertificate(SSL *ssl) {
7b73b7be
MC
174 bssl::UniquePtr<X509> x509;
175 bssl::UniquePtr<EVP_PKEY> pkey;
eef977aa
MC
176 if (!GetCertificate(ssl, &x509, &pkey)) {
177 return false;
178 }
179
1c8235c9
MC
180 if (pkey && !SSL_use_PrivateKey(ssl, pkey.get())) {
181 return false;
eef977aa
MC
182 }
183
184 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
185 return false;
186 }
187
188 return true;
189}
190
191static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
7b73b7be 192 if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
eef977aa
MC
193 return -1;
194 }
195
7b73b7be
MC
196 bssl::UniquePtr<X509> x509;
197 bssl::UniquePtr<EVP_PKEY> pkey;
eef977aa
MC
198 if (!GetCertificate(ssl, &x509, &pkey)) {
199 return -1;
200 }
201
202 // Return zero for no certificate.
203 if (!x509) {
204 return 0;
205 }
206
207 // Asynchronous private keys are not supported with client_cert_cb.
208 *out_x509 = x509.release();
209 *out_pkey = pkey.release();
210 return 1;
211}
212
213static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
214 return 1;
215}
216
217static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
218 X509_STORE_CTX_set_error(store_ctx, X509_V_ERR_APPLICATION_VERIFICATION);
219 return 0;
220}
221
222static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
223 unsigned int *out_len, void *arg) {
7b73b7be 224 const TestConfig *config = GetTestConfig(ssl);
eef977aa
MC
225 if (config->advertise_npn.empty()) {
226 return SSL_TLSEXT_ERR_NOACK;
227 }
228
229 *out = (const uint8_t*)config->advertise_npn.data();
230 *out_len = config->advertise_npn.size();
231 return SSL_TLSEXT_ERR_OK;
232}
233
234static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
235 const uint8_t* in, unsigned inlen, void* arg) {
7b73b7be 236 const TestConfig *config = GetTestConfig(ssl);
eef977aa
MC
237 if (config->select_next_proto.empty()) {
238 return SSL_TLSEXT_ERR_NOACK;
239 }
240
241 *out = (uint8_t*)config->select_next_proto.data();
242 *outlen = config->select_next_proto.size();
243 return SSL_TLSEXT_ERR_OK;
244}
245
246static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
247 const uint8_t* in, unsigned inlen, void* arg) {
7b73b7be
MC
248 if (GetTestState(ssl)->alpn_select_done) {
249 fprintf(stderr, "AlpnSelectCallback called after completion.\n");
250 exit(1);
251 }
252
253 GetTestState(ssl)->alpn_select_done = true;
254
255 const TestConfig *config = GetTestConfig(ssl);
256 if (config->decline_alpn) {
eef977aa
MC
257 return SSL_TLSEXT_ERR_NOACK;
258 }
259
260 if (!config->expected_advertised_alpn.empty() &&
261 (config->expected_advertised_alpn.size() != inlen ||
262 memcmp(config->expected_advertised_alpn.data(),
263 in, inlen) != 0)) {
264 fprintf(stderr, "bad ALPN select callback inputs\n");
265 exit(1);
266 }
267
268 *out = (const uint8_t*)config->select_alpn.data();
269 *outlen = config->select_alpn.size();
270 return SSL_TLSEXT_ERR_OK;
271}
272
273static unsigned PskClientCallback(SSL *ssl, const char *hint,
274 char *out_identity,
275 unsigned max_identity_len,
276 uint8_t *out_psk, unsigned max_psk_len) {
7b73b7be 277 const TestConfig *config = GetTestConfig(ssl);
eef977aa 278
7b73b7be
MC
279 if (config->psk_identity.empty()) {
280 if (hint != nullptr) {
281 fprintf(stderr, "Server PSK hint was non-null.\n");
282 return 0;
283 }
284 } else if (hint == nullptr ||
285 strcmp(hint, config->psk_identity.c_str()) != 0) {
eef977aa
MC
286 fprintf(stderr, "Server PSK hint did not match.\n");
287 return 0;
288 }
289
290 // Account for the trailing '\0' for the identity.
291 if (config->psk_identity.size() >= max_identity_len ||
292 config->psk.size() > max_psk_len) {
293 fprintf(stderr, "PSK buffers too small\n");
294 return 0;
295 }
296
297 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
298 max_identity_len);
299 memcpy(out_psk, config->psk.data(), config->psk.size());
300 return config->psk.size();
301}
302
303static unsigned PskServerCallback(SSL *ssl, const char *identity,
304 uint8_t *out_psk, unsigned max_psk_len) {
7b73b7be 305 const TestConfig *config = GetTestConfig(ssl);
eef977aa
MC
306
307 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
308 fprintf(stderr, "Client PSK identity did not match.\n");
309 return 0;
310 }
311
312 if (config->psk.size() > max_psk_len) {
313 fprintf(stderr, "PSK buffers too small\n");
314 return 0;
315 }
316
317 memcpy(out_psk, config->psk.data(), config->psk.size());
318 return config->psk.size();
319}
320
321static int CertCallback(SSL *ssl, void *arg) {
7b73b7be
MC
322 const TestConfig *config = GetTestConfig(ssl);
323
324 // Check the CertificateRequest metadata is as expected.
325 //
326 // TODO(davidben): Test |SSL_get_client_CA_list|.
327 if (!SSL_is_server(ssl) &&
328 !config->expected_certificate_types.empty()) {
329 const uint8_t *certificate_types;
330 size_t certificate_types_len =
331 SSL_get0_certificate_types(ssl, &certificate_types);
332 if (certificate_types_len != config->expected_certificate_types.size() ||
333 memcmp(certificate_types,
334 config->expected_certificate_types.data(),
335 certificate_types_len) != 0) {
336 fprintf(stderr, "certificate types mismatch\n");
337 return 0;
338 }
339 }
340
341 // The certificate will be installed via other means.
aedf33ae 342 if (!config->async ||
7b73b7be
MC
343 config->use_old_client_cert_callback) {
344 return 1;
345 }
346
eef977aa
MC
347 if (!GetTestState(ssl)->cert_ready) {
348 return -1;
349 }
350 if (!InstallCertificate(ssl)) {
351 return 0;
352 }
353 return 1;
354}
355
356static void InfoCallback(const SSL *ssl, int type, int val) {
357 if (type == SSL_CB_HANDSHAKE_DONE) {
7b73b7be
MC
358 if (GetTestConfig(ssl)->handshake_never_done) {
359 fprintf(stderr, "Handshake unexpectedly completed.\n");
eef977aa
MC
360 // Abort before any expected error code is printed, to ensure the overall
361 // test fails.
362 abort();
363 }
364 GetTestState(ssl)->handshake_done = true;
7b73b7be
MC
365
366 // Callbacks may be called again on a new handshake.
367 GetTestState(ssl)->ticket_decrypt_done = false;
368 GetTestState(ssl)->alpn_select_done = false;
eef977aa
MC
369 }
370}
371
372static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
373 GetTestState(ssl)->got_new_session = true;
7b73b7be 374 GetTestState(ssl)->new_session.reset(session);
eef977aa
MC
375 return 1;
376}
377
378static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
379 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
380 int encrypt) {
7b73b7be
MC
381 if (!encrypt) {
382 if (GetTestState(ssl)->ticket_decrypt_done) {
383 fprintf(stderr, "TicketKeyCallback called after completion.\n");
384 return -1;
385 }
386
387 GetTestState(ssl)->ticket_decrypt_done = true;
388 }
389
eef977aa
MC
390 // This is just test code, so use the all-zeros key.
391 static const uint8_t kZeros[16] = {0};
392
393 if (encrypt) {
394 memcpy(key_name, kZeros, sizeof(kZeros));
395 RAND_bytes(iv, 16);
396 } else if (memcmp(key_name, kZeros, 16) != 0) {
397 return 0;
398 }
399
400 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
401 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
402 return -1;
403 }
404
405 if (!encrypt) {
7b73b7be 406 return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
eef977aa
MC
407 }
408 return 1;
409}
410
411// kCustomExtensionValue is the extension value that the custom extension
412// callbacks will add.
413static const uint16_t kCustomExtensionValue = 1234;
414static void *const kCustomExtensionAddArg =
415 reinterpret_cast<void *>(kCustomExtensionValue);
416static void *const kCustomExtensionParseArg =
417 reinterpret_cast<void *>(kCustomExtensionValue + 1);
418static const char kCustomExtensionContents[] = "custom extension";
419
420static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
421 const uint8_t **out, size_t *out_len,
422 int *out_alert_value, void *add_arg) {
423 if (extension_value != kCustomExtensionValue ||
424 add_arg != kCustomExtensionAddArg) {
425 abort();
426 }
427
7b73b7be 428 if (GetTestConfig(ssl)->custom_extension_skip) {
eef977aa
MC
429 return 0;
430 }
7b73b7be 431 if (GetTestConfig(ssl)->custom_extension_fail_add) {
eef977aa
MC
432 return -1;
433 }
434
435 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
436 *out_len = sizeof(kCustomExtensionContents) - 1;
437
438 return 1;
439}
440
441static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
442 const uint8_t *out, void *add_arg) {
443 if (extension_value != kCustomExtensionValue ||
444 add_arg != kCustomExtensionAddArg ||
445 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
446 abort();
447 }
448}
449
450static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
451 const uint8_t *contents,
452 size_t contents_len,
453 int *out_alert_value, void *parse_arg) {
454 if (extension_value != kCustomExtensionValue ||
455 parse_arg != kCustomExtensionParseArg) {
456 abort();
457 }
458
459 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
460 memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
461 *out_alert_value = SSL_AD_DECODE_ERROR;
462 return 0;
463 }
464
465 return 1;
466}
467
468// Connect returns a new socket connected to localhost on |port| or -1 on
469// error.
470static int Connect(uint16_t port) {
471 int sock = socket(AF_INET, SOCK_STREAM, 0);
472 if (sock == -1) {
473 PrintSocketError("socket");
474 return -1;
475 }
476 int nodelay = 1;
477 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
478 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
479 PrintSocketError("setsockopt");
480 closesocket(sock);
481 return -1;
482 }
483 sockaddr_in sin;
484 memset(&sin, 0, sizeof(sin));
485 sin.sin_family = AF_INET;
486 sin.sin_port = htons(port);
487 if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
488 PrintSocketError("inet_pton");
489 closesocket(sock);
490 return -1;
491 }
492 if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
493 sizeof(sin)) != 0) {
494 PrintSocketError("connect");
495 closesocket(sock);
496 return -1;
497 }
498 return sock;
499}
500
501class SocketCloser {
502 public:
503 explicit SocketCloser(int sock) : sock_(sock) {}
504 ~SocketCloser() {
505 // Half-close and drain the socket before releasing it. This seems to be
506 // necessary for graceful shutdown on Windows. It will also avoid write
507 // failures in the test runner.
1669b7b5 508#if defined(OPENSSL_SYS_WINDOWS)
eef977aa
MC
509 shutdown(sock_, SD_SEND);
510#else
511 shutdown(sock_, SHUT_WR);
512#endif
513 while (true) {
514 char buf[1024];
515 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
516 break;
517 }
518 }
519 closesocket(sock_);
520 }
521
522 private:
523 const int sock_;
524};
525
7b73b7be
MC
526static bssl::UniquePtr<SSL_CTX> SetupCtx(const TestConfig *config) {
527 bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(
eef977aa
MC
528 config->is_dtls ? DTLS_method() : TLS_method()));
529 if (!ssl_ctx) {
530 return nullptr;
531 }
532
533 SSL_CTX_set_security_level(ssl_ctx.get(), 0);
7b73b7be
MC
534#if 0
535 /* Disabled for now until we have some TLS1.3 support */
536 // Enable TLS 1.3 for tests.
537 if (!config->is_dtls &&
538 !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION)) {
539 return nullptr;
540 }
541#endif
eef977aa
MC
542
543 std::string cipher_list = "ALL";
544 if (!config->cipher.empty()) {
545 cipher_list = config->cipher;
546 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
547 }
548 if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
549 return nullptr;
550 }
551
eef977aa
MC
552 DH *tmpdh;
553
554 if (config->use_sparse_dh_prime) {
555 BIGNUM *p, *g;
556 p = BN_new();
557 g = BN_new();
558 tmpdh = DH_new();
559 if (p == NULL || g == NULL || tmpdh == NULL) {
560 BN_free(p);
561 BN_free(g);
562 DH_free(tmpdh);
563 return nullptr;
564 }
565 // This prime number is 2^1024 + 643 – a value just above a power of two.
566 // Because of its form, values modulo it are essentially certain to be one
567 // byte shorter. This is used to test padding of these values.
568 if (BN_hex2bn(
569 &p,
570 "1000000000000000000000000000000000000000000000000000000000000000"
571 "0000000000000000000000000000000000000000000000000000000000000000"
572 "0000000000000000000000000000000000000000000000000000000000000000"
573 "0000000000000000000000000000000000000000000000000000000000000028"
574 "3") == 0 ||
575 !BN_set_word(g, 2)) {
576 BN_free(p);
577 BN_free(g);
578 DH_free(tmpdh);
579 return nullptr;
580 }
581 DH_set0_pqg(tmpdh, p, NULL, g);
582 } else {
583 tmpdh = DH_get_2048_256();
584 }
585
7b73b7be 586 bssl::UniquePtr<DH> dh(tmpdh);
eef977aa
MC
587
588 if (!dh || !SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
589 return nullptr;
590 }
591
592 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
593
594 if (config->use_old_client_cert_callback) {
595 SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
596 }
597
598 SSL_CTX_set_next_protos_advertised_cb(
599 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
600 if (!config->select_next_proto.empty()) {
601 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
602 NULL);
603 }
604
7b73b7be 605 if (!config->select_alpn.empty() || config->decline_alpn) {
eef977aa
MC
606 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
607 }
608
609 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
610 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
611
612 if (config->use_ticket_callback) {
613 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
614 }
615
616 if (config->enable_client_custom_extension &&
617 !SSL_CTX_add_client_custom_ext(
618 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
619 CustomExtensionFreeCallback, kCustomExtensionAddArg,
620 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
621 return nullptr;
622 }
623
624 if (config->enable_server_custom_extension &&
625 !SSL_CTX_add_server_custom_ext(
626 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
627 CustomExtensionFreeCallback, kCustomExtensionAddArg,
628 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
629 return nullptr;
630 }
631
632 if (config->verify_fail) {
633 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
634 } else {
635 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
636 }
637
7b73b7be
MC
638 if (config->use_null_client_ca_list) {
639 SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
640 }
641
eef977aa
MC
642 return ssl_ctx;
643}
644
645// RetryAsync is called after a failed operation on |ssl| with return code
646// |ret|. If the operation should be retried, it simulates one asynchronous
647// event and returns true. Otherwise it returns false.
648static bool RetryAsync(SSL *ssl, int ret) {
649 // No error; don't retry.
650 if (ret >= 0) {
651 return false;
652 }
653
eef977aa 654 TestState *test_state = GetTestState(ssl);
7b73b7be 655 assert(GetTestConfig(ssl)->async);
eef977aa 656
7b73b7be
MC
657 if (test_state->packeted_bio != nullptr &&
658 PacketedBioAdvanceClock(test_state->packeted_bio)) {
eef977aa
MC
659 // The DTLS retransmit logic silently ignores write failures. So the test
660 // may progress, allow writes through synchronously.
7b73b7be 661 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
eef977aa 662 int timeout_ret = DTLSv1_handle_timeout(ssl);
7b73b7be 663 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
eef977aa
MC
664
665 if (timeout_ret < 0) {
666 fprintf(stderr, "Error retransmitting.\n");
667 return false;
668 }
669 return true;
670 }
671
672 // See if we needed to read or write more. If so, allow one byte through on
673 // the appropriate end to maximally stress the state machine.
674 switch (SSL_get_error(ssl, ret)) {
675 case SSL_ERROR_WANT_READ:
676 AsyncBioAllowRead(test_state->async_bio, 1);
677 return true;
678 case SSL_ERROR_WANT_WRITE:
679 AsyncBioAllowWrite(test_state->async_bio, 1);
680 return true;
681 case SSL_ERROR_WANT_X509_LOOKUP:
682 test_state->cert_ready = true;
683 return true;
684 default:
685 return false;
686 }
687}
688
689// DoRead reads from |ssl|, resolving any asynchronous operations. It returns
690// the result value of the final |SSL_read| call.
691static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
7b73b7be 692 const TestConfig *config = GetTestConfig(ssl);
eef977aa
MC
693 TestState *test_state = GetTestState(ssl);
694 int ret;
695 do {
696 if (config->async) {
697 // The DTLS retransmit logic silently ignores write failures. So the test
698 // may progress, allow writes through synchronously. |SSL_read| may
699 // trigger a retransmit, so disconnect the write quota.
700 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
701 }
7b73b7be
MC
702 ret = config->peek_then_read ? SSL_peek(ssl, out, max_out)
703 : SSL_read(ssl, out, max_out);
eef977aa
MC
704 if (config->async) {
705 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
706 }
707 } while (config->async && RetryAsync(ssl, ret));
7b73b7be
MC
708
709 if (config->peek_then_read && ret > 0) {
710 std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
711
712 // SSL_peek should synchronously return the same data.
713 int ret2 = SSL_peek(ssl, buf.get(), ret);
714 if (ret2 != ret ||
715 memcmp(buf.get(), out, ret) != 0) {
716 fprintf(stderr, "First and second SSL_peek did not match.\n");
717 return -1;
718 }
719
720 // SSL_read should synchronously return the same data and consume it.
721 ret2 = SSL_read(ssl, buf.get(), ret);
722 if (ret2 != ret ||
723 memcmp(buf.get(), out, ret) != 0) {
724 fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
725 return -1;
726 }
727 }
728
eef977aa
MC
729 return ret;
730}
731
732// WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
733// operations. It returns the result of the final |SSL_write| call.
734static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
7b73b7be 735 const TestConfig *config = GetTestConfig(ssl);
eef977aa
MC
736 int ret;
737 do {
738 ret = SSL_write(ssl, in, in_len);
739 if (ret > 0) {
740 in += ret;
741 in_len -= ret;
742 }
743 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
744 return ret;
745}
746
747// DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
748// returns the result of the final |SSL_shutdown| call.
749static int DoShutdown(SSL *ssl) {
7b73b7be 750 const TestConfig *config = GetTestConfig(ssl);
eef977aa
MC
751 int ret;
752 do {
753 ret = SSL_shutdown(ssl);
754 } while (config->async && RetryAsync(ssl, ret));
755 return ret;
756}
757
7b73b7be
MC
758static uint16_t GetProtocolVersion(const SSL *ssl) {
759 uint16_t version = SSL_version(ssl);
760 if (!SSL_is_dtls(ssl)) {
761 return version;
762 }
763 return 0x0201 + ~version;
764}
765
eef977aa
MC
766// CheckHandshakeProperties checks, immediately after |ssl| completes its
767// initial handshake (or False Starts), whether all the properties are
768// consistent with the test configuration and invariants.
769static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
7b73b7be 770 const TestConfig *config = GetTestConfig(ssl);
eef977aa
MC
771
772 if (SSL_get_current_cipher(ssl) == nullptr) {
773 fprintf(stderr, "null cipher after handshake\n");
774 return false;
775 }
776
777 if (is_resume &&
778 (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
779 fprintf(stderr, "session was%s reused\n",
780 SSL_session_reused(ssl) ? "" : " not");
781 return false;
782 }
783
8beda2c1
MC
784 if (!GetTestState(ssl)->handshake_done) {
785 fprintf(stderr, "handshake was not completed\n");
eef977aa
MC
786 return false;
787 }
788
8beda2c1 789 if (!config->is_server) {
eef977aa
MC
790 bool expect_new_session =
791 !config->expect_no_session &&
7b73b7be
MC
792 (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
793 // Session tickets are sent post-handshake in TLS 1.3.
794 GetProtocolVersion(ssl) < TLS1_3_VERSION;
eef977aa
MC
795 if (expect_new_session != GetTestState(ssl)->got_new_session) {
796 fprintf(stderr,
797 "new session was%s cached, but we expected the opposite\n",
798 GetTestState(ssl)->got_new_session ? "" : " not");
799 return false;
800 }
801 }
802
803 if (!config->expected_server_name.empty()) {
804 const char *server_name =
805 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
806 if (server_name != config->expected_server_name) {
807 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
808 server_name, config->expected_server_name.c_str());
809 return false;
810 }
811 }
812
eef977aa
MC
813 if (!config->expected_next_proto.empty()) {
814 const uint8_t *next_proto;
815 unsigned next_proto_len;
816 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
817 if (next_proto_len != config->expected_next_proto.size() ||
818 memcmp(next_proto, config->expected_next_proto.data(),
819 next_proto_len) != 0) {
820 fprintf(stderr, "negotiated next proto mismatch\n");
821 return false;
822 }
823 }
824
825 if (!config->expected_alpn.empty()) {
826 const uint8_t *alpn_proto;
827 unsigned alpn_proto_len;
828 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
829 if (alpn_proto_len != config->expected_alpn.size() ||
830 memcmp(alpn_proto, config->expected_alpn.data(),
831 alpn_proto_len) != 0) {
832 fprintf(stderr, "negotiated alpn proto mismatch\n");
833 return false;
834 }
835 }
836
7b73b7be
MC
837 if (config->expect_extended_master_secret) {
838 if (!SSL_get_extms_support(ssl)) {
839 fprintf(stderr, "No EMS for connection when expected");
840 return false;
841 }
842 }
843
eef977aa
MC
844 if (config->expect_verify_result) {
845 int expected_verify_result = config->verify_fail ?
846 X509_V_ERR_APPLICATION_VERIFICATION :
847 X509_V_OK;
848
849 if (SSL_get_verify_result(ssl) != expected_verify_result) {
850 fprintf(stderr, "Wrong certificate verification result\n");
851 return false;
852 }
853 }
854
7b73b7be
MC
855 if (!config->psk.empty()) {
856 if (SSL_get_peer_cert_chain(ssl) != nullptr) {
857 fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
858 return false;
859 }
860 } else if (!config->is_server || config->require_any_client_certificate) {
861 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
862 fprintf(stderr, "Received no peer certificate but expected one.\n");
eef977aa
MC
863 return false;
864 }
865 }
7b73b7be 866
eef977aa
MC
867 return true;
868}
869
870// DoExchange runs a test SSL exchange against the peer. On success, it returns
871// true and sets |*out_session| to the negotiated SSL session. If the test is a
872// resumption attempt, |is_resume| is true and |session| is the session from the
873// previous exchange.
7b73b7be
MC
874static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
875 SSL_CTX *ssl_ctx, const TestConfig *config,
876 bool is_resume, SSL_SESSION *session) {
877 bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
eef977aa
MC
878 if (!ssl) {
879 return false;
880 }
881
7b73b7be 882 if (!SetTestConfig(ssl.get(), config) ||
eef977aa
MC
883 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
884 return false;
885 }
886
887 if (config->fallback_scsv &&
888 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
889 return false;
890 }
7b73b7be 891 // Install the certificate synchronously if nothing else will handle it.
aedf33ae 892 if (!config->use_old_client_cert_callback &&
7b73b7be
MC
893 !config->async &&
894 !InstallCertificate(ssl.get())) {
eef977aa
MC
895 return false;
896 }
7b73b7be 897 SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
eef977aa
MC
898 if (config->require_any_client_certificate) {
899 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
900 NULL);
901 }
902 if (config->verify_peer) {
903 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
904 }
eef977aa
MC
905 if (config->partial_write) {
906 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
907 }
7b73b7be
MC
908 if (config->no_tls13) {
909 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
910 }
eef977aa
MC
911 if (config->no_tls12) {
912 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
913 }
914 if (config->no_tls11) {
915 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
916 }
917 if (config->no_tls1) {
918 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
919 }
920 if (config->no_ssl3) {
921 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
922 }
eef977aa
MC
923 if (!config->host_name.empty() &&
924 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
925 return false;
926 }
927 if (!config->advertise_alpn.empty() &&
928 SSL_set_alpn_protos(ssl.get(),
929 (const uint8_t *)config->advertise_alpn.data(),
930 config->advertise_alpn.size()) != 0) {
931 return false;
932 }
933 if (!config->psk.empty()) {
934 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
935 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
936 }
937 if (!config->psk_identity.empty() &&
938 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
939 return false;
940 }
941 if (!config->srtp_profiles.empty() &&
942 SSL_set_tlsext_use_srtp(ssl.get(), config->srtp_profiles.c_str())) {
943 return false;
944 }
7b73b7be
MC
945 if (config->min_version != 0 &&
946 !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) {
947 return false;
eef977aa 948 }
7b73b7be
MC
949 if (config->max_version != 0 &&
950 !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) {
951 return false;
eef977aa
MC
952 }
953 if (config->mtu != 0) {
954 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
955 SSL_set_mtu(ssl.get(), config->mtu);
956 }
eef977aa
MC
957 if (config->renegotiate_freely) {
958 // This is always on for OpenSSL.
959 }
eef977aa
MC
960 if (!config->check_close_notify) {
961 SSL_set_quiet_shutdown(ssl.get(), 1);
962 }
eef977aa
MC
963 if (config->p384_only) {
964 int nid = NID_secp384r1;
965 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
966 return false;
967 }
968 }
969 if (config->enable_all_curves) {
970 static const int kAllCurves[] = {
7b73b7be 971 NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_X25519,
eef977aa
MC
972 };
973 if (!SSL_set1_curves(ssl.get(), kAllCurves,
7b73b7be 974 OPENSSL_ARRAY_SIZE(kAllCurves))) {
eef977aa
MC
975 return false;
976 }
977 }
7b73b7be
MC
978 if (config->max_cert_list > 0) {
979 SSL_set_max_cert_list(ssl.get(), config->max_cert_list);
980 }
eef977aa
MC
981
982 int sock = Connect(config->port);
983 if (sock == -1) {
984 return false;
985 }
986 SocketCloser closer(sock);
987
7b73b7be 988 bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
eef977aa
MC
989 if (!bio) {
990 return false;
991 }
992 if (config->is_dtls) {
7b73b7be
MC
993 bssl::UniquePtr<BIO> packeted = PacketedBioCreate(!config->async);
994 if (!packeted) {
995 return false;
996 }
997 GetTestState(ssl.get())->packeted_bio = packeted.get();
eef977aa
MC
998 BIO_push(packeted.get(), bio.release());
999 bio = std::move(packeted);
1000 }
1001 if (config->async) {
7b73b7be 1002 bssl::UniquePtr<BIO> async_scoped =
eef977aa 1003 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
7b73b7be
MC
1004 if (!async_scoped) {
1005 return false;
1006 }
eef977aa
MC
1007 BIO_push(async_scoped.get(), bio.release());
1008 GetTestState(ssl.get())->async_bio = async_scoped.get();
1009 bio = std::move(async_scoped);
1010 }
1011 SSL_set_bio(ssl.get(), bio.get(), bio.get());
1012 bio.release(); // SSL_set_bio takes ownership.
1013
1014 if (session != NULL) {
1015 if (!config->is_server) {
1016 if (SSL_set_session(ssl.get(), session) != 1) {
1017 return false;
1018 }
1019 }
1020 }
1021
1022#if 0
1023 // KNOWN BUG: OpenSSL's SSL_get_current_cipher behaves incorrectly when
1024 // offering resumption.
1025 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1026 fprintf(stderr, "non-null cipher before handshake\n");
1027 return false;
1028 }
1029#endif
1030
1031 int ret;
1032 if (config->implicit_handshake) {
1033 if (config->is_server) {
1034 SSL_set_accept_state(ssl.get());
1035 } else {
1036 SSL_set_connect_state(ssl.get());
1037 }
1038 } else {
1039 do {
1040 if (config->is_server) {
1041 ret = SSL_accept(ssl.get());
1042 } else {
1043 ret = SSL_connect(ssl.get());
1044 }
1045 } while (config->async && RetryAsync(ssl.get(), ret));
1046 if (ret != 1 ||
1047 !CheckHandshakeProperties(ssl.get(), is_resume)) {
1048 return false;
1049 }
1050
1051 // Reset the state to assert later that the callback isn't called in
1052 // renegotations.
1053 GetTestState(ssl.get())->got_new_session = false;
1054 }
1055
1056 if (config->export_keying_material > 0) {
1057 std::vector<uint8_t> result(
1058 static_cast<size_t>(config->export_keying_material));
1059 if (SSL_export_keying_material(
1060 ssl.get(), result.data(), result.size(),
1061 config->export_label.data(), config->export_label.size(),
1062 reinterpret_cast<const uint8_t*>(config->export_context.data()),
1063 config->export_context.size(), config->use_export_context) != 1) {
1064 fprintf(stderr, "failed to export keying material\n");
1065 return false;
1066 }
1067 if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1068 return false;
1069 }
1070 }
1071
eef977aa
MC
1072 if (config->write_different_record_sizes) {
1073 if (config->is_dtls) {
1074 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
1075 return false;
1076 }
1077 // This mode writes a number of different record sizes in an attempt to
1078 // trip up the CBC record splitting code.
1079 static const size_t kBufLen = 32769;
1080 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1081 memset(buf.get(), 0x42, kBufLen);
1082 static const size_t kRecordSizes[] = {
1083 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
7b73b7be 1084 for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
eef977aa
MC
1085 const size_t len = kRecordSizes[i];
1086 if (len > kBufLen) {
1087 fprintf(stderr, "Bad kRecordSizes value.\n");
1088 return false;
1089 }
1090 if (WriteAll(ssl.get(), buf.get(), len) < 0) {
1091 return false;
1092 }
1093 }
1094 } else {
1095 if (config->shim_writes_first) {
1096 if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1097 5) < 0) {
1098 return false;
1099 }
1100 }
1101 if (!config->shim_shuts_down) {
1102 for (;;) {
1103 static const size_t kBufLen = 16384;
1104 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1105
1106 // Read only 512 bytes at a time in TLS to ensure records may be
1107 // returned in multiple reads.
1108 int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
1109 int err = SSL_get_error(ssl.get(), n);
1110 if (err == SSL_ERROR_ZERO_RETURN ||
1111 (n == 0 && err == SSL_ERROR_SYSCALL)) {
1112 if (n != 0) {
1113 fprintf(stderr, "Invalid SSL_get_error output\n");
1114 return false;
1115 }
1116 // Stop on either clean or unclean shutdown.
1117 break;
1118 } else if (err != SSL_ERROR_NONE) {
1119 if (n > 0) {
1120 fprintf(stderr, "Invalid SSL_get_error output\n");
1121 return false;
1122 }
1123 return false;
1124 }
1125 // Successfully read data.
1126 if (n <= 0) {
1127 fprintf(stderr, "Invalid SSL_get_error output\n");
1128 return false;
1129 }
1130
1131 // After a successful read, with or without False Start, the handshake
1132 // must be complete.
1133 if (!GetTestState(ssl.get())->handshake_done) {
1134 fprintf(stderr, "handshake was not completed after SSL_read\n");
1135 return false;
1136 }
1137
1138 for (int i = 0; i < n; i++) {
1139 buf[i] ^= 0xff;
1140 }
1141 if (WriteAll(ssl.get(), buf.get(), n) < 0) {
1142 return false;
1143 }
1144 }
1145 }
1146 }
1147
8beda2c1 1148 if (!config->is_server &&
eef977aa 1149 !config->implicit_handshake &&
7b73b7be
MC
1150 // Session tickets are sent post-handshake in TLS 1.3.
1151 GetProtocolVersion(ssl.get()) < TLS1_3_VERSION &&
eef977aa
MC
1152 GetTestState(ssl.get())->got_new_session) {
1153 fprintf(stderr, "new session was established after the handshake\n");
1154 return false;
1155 }
1156
7b73b7be
MC
1157 if (GetProtocolVersion(ssl.get()) >= TLS1_3_VERSION && !config->is_server) {
1158 bool expect_new_session =
1159 !config->expect_no_session && !config->shim_shuts_down;
1160 if (expect_new_session != GetTestState(ssl.get())->got_new_session) {
1161 fprintf(stderr,
1162 "new session was%s cached, but we expected the opposite\n",
1163 GetTestState(ssl.get())->got_new_session ? "" : " not");
1164 return false;
1165 }
1166 }
1167
eef977aa 1168 if (out_session) {
7b73b7be 1169 *out_session = std::move(GetTestState(ssl.get())->new_session);
eef977aa
MC
1170 }
1171
1172 ret = DoShutdown(ssl.get());
1173
1174 if (config->shim_shuts_down && config->check_close_notify) {
1175 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1176 // it returns zero when our close_notify is sent, then one when the peer's
1177 // is received.
1178 if (ret != 0) {
1179 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1180 return false;
1181 }
1182 ret = DoShutdown(ssl.get());
1183 }
1184
1185 if (ret != 1) {
1186 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1187 return false;
1188 }
1189
1190 if (SSL_total_renegotiations(ssl.get()) !=
1191 config->expect_total_renegotiations) {
1192 fprintf(stderr, "Expected %d renegotiations, got %ld\n",
1193 config->expect_total_renegotiations,
1194 SSL_total_renegotiations(ssl.get()));
1195 return false;
1196 }
1197
1198 return true;
1199}
1200
1201class StderrDelimiter {
1202 public:
1203 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
1204};
1205
7b73b7be 1206static int Main(int argc, char **argv) {
eef977aa
MC
1207 // To distinguish ASan's output from ours, add a trailing message to stderr.
1208 // Anything following this line will be considered an error.
1209 StderrDelimiter delimiter;
1210
1669b7b5 1211#if defined(OPENSSL_SYS_WINDOWS)
eef977aa
MC
1212 /* Initialize Winsock. */
1213 WORD wsa_version = MAKEWORD(2, 2);
1214 WSADATA wsa_data;
1215 int wsa_err = WSAStartup(wsa_version, &wsa_data);
1216 if (wsa_err != 0) {
1217 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1218 return 1;
1219 }
1220 if (wsa_data.wVersion != wsa_version) {
1221 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1222 return 1;
1223 }
1224#else
1225 signal(SIGPIPE, SIG_IGN);
1226#endif
1227
1228 OPENSSL_init_crypto(0, NULL);
1229 OPENSSL_init_ssl(0, NULL);
1230 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
1231 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
1232 if (g_config_index < 0 || g_state_index < 0) {
1233 return 1;
1234 }
1235
1236 TestConfig config;
1237 if (!ParseConfig(argc - 1, argv + 1, &config)) {
1238 return Usage(argv[0]);
1239 }
1240
7b73b7be 1241 bssl::UniquePtr<SSL_CTX> ssl_ctx = SetupCtx(&config);
eef977aa
MC
1242 if (!ssl_ctx) {
1243 ERR_print_errors_fp(stderr);
1244 return 1;
1245 }
1246
7b73b7be
MC
1247 bssl::UniquePtr<SSL_SESSION> session;
1248 for (int i = 0; i < config.resume_count + 1; i++) {
1249 bool is_resume = i > 0;
1250 if (is_resume && !config.is_server && !session) {
1251 fprintf(stderr, "No session to offer.\n");
1252 return 1;
1253 }
eef977aa 1254
7b73b7be
MC
1255 bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
1256 if (!DoExchange(&session, ssl_ctx.get(), &config, is_resume,
1257 offer_session.get())) {
1258 fprintf(stderr, "Connection %d failed.\n", i + 1);
1259 ERR_print_errors_fp(stderr);
1260 return 1;
1261 }
eef977aa
MC
1262 }
1263
1264 return 0;
1265}
7b73b7be
MC
1266
1267} // namespace bssl
1268
1269int main(int argc, char **argv) {
1270 return bssl::Main(argc, argv);
1271}