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