Debian Codegraph @

external/boringssl/ssl/test/bssl_shim.cc

raw
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/base.h>
20
21 #if !defined(OPENSSL_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>
31 OPENSSL_MSVC_PRAGMA(warning(push, 3))
32 #include <winsock2.h>
33 #include <ws2tcpip.h>
34 OPENSSL_MSVC_PRAGMA(warning(pop))
35
36 #pragma comment(lib, "Ws2_32.lib")
37 #endif
38
39 #include <assert.h>
40 #include <inttypes.h>
41 #include <string.h>
42
43 #include <openssl/bio.h>
44 #include <openssl/buf.h>
45 #include <openssl/bytestring.h>
46 #include <openssl/cipher.h>
47 #include <openssl/crypto.h>
48 #include <openssl/err.h>
49 #include <openssl/hmac.h>
50 #include <openssl/nid.h>
51 #include <openssl/rand.h>
52 #include <openssl/ssl.h>
53
54 #include <memory>
55 #include <string>
56 #include <vector>
57
58 #include "../../crypto/test/scoped_types.h"
59 #include "async_bio.h"
60 #include "packeted_bio.h"
61 #include "scoped_types.h"
62 #include "test_config.h"
63
64
65 #if !defined(OPENSSL_WINDOWS)
66 static int closesocket(int sock) {
67 return close(sock);
68 }
69
70 static void PrintSocketError(const char *func) {
71 perror(func);
72 }
73 #else
74 static void PrintSocketError(const char *func) {
75 fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
76 }
77 #endif
78
79 static int Usage(const char *program) {
80 fprintf(stderr, "Usage: %s [flags...]\n", program);
81 return 1;
82 }
83
84 struct TestState {
85 // async_bio is async BIO which pauses reads and writes.
86 BIO *async_bio = nullptr;
87 // packeted_bio is the packeted BIO which simulates read timeouts.
88 BIO *packeted_bio = nullptr;
89 ScopedEVP_PKEY channel_id;
90 bool cert_ready = false;
91 ScopedSSL_SESSION session;
92 ScopedSSL_SESSION pending_session;
93 bool early_callback_called = false;
94 bool handshake_done = false;
95 // private_key is the underlying private key used when testing custom keys.
96 ScopedEVP_PKEY private_key;
97 std::vector<uint8_t> private_key_result;
98 // private_key_retries is the number of times an asynchronous private key
99 // operation has been retried.
100 unsigned private_key_retries = 0;
101 bool got_new_session = false;
102 };
103
104 static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
105 int index, long argl, void *argp) {
106 delete ((TestState *)ptr);
107 }
108
109 static int g_config_index = 0;
110 static int g_state_index = 0;
111
112 static bool SetTestConfig(SSL *ssl, const TestConfig *config) {
113 return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
114 }
115
116 static const TestConfig *GetTestConfig(const SSL *ssl) {
117 return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
118 }
119
120 static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
121 // |SSL_set_ex_data| takes ownership of |state| only on success.
122 if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
123 state.release();
124 return true;
125 }
126 return false;
127 }
128
129 static TestState *GetTestState(const SSL *ssl) {
130 return (TestState *)SSL_get_ex_data(ssl, g_state_index);
131 }
132
133 static ScopedX509 LoadCertificate(const std::string &file) {
134 ScopedBIO bio(BIO_new(BIO_s_file()));
135 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
136 return nullptr;
137 }
138 return ScopedX509(PEM_read_bio_X509(bio.get(), NULL, NULL, NULL));
139 }
140
141 static ScopedEVP_PKEY LoadPrivateKey(const std::string &file) {
142 ScopedBIO bio(BIO_new(BIO_s_file()));
143 if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
144 return nullptr;
145 }
146 return ScopedEVP_PKEY(PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
147 }
148
149 static int AsyncPrivateKeyType(SSL *ssl) {
150 return EVP_PKEY_id(GetTestState(ssl)->private_key.get());
151 }
152
153 static size_t AsyncPrivateKeyMaxSignatureLen(SSL *ssl) {
154 return EVP_PKEY_size(GetTestState(ssl)->private_key.get());
155 }
156
157 static ssl_private_key_result_t AsyncPrivateKeySign(
158 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
159 const EVP_MD *md, const uint8_t *in, size_t in_len) {
160 TestState *test_state = GetTestState(ssl);
161 if (!test_state->private_key_result.empty()) {
162 fprintf(stderr, "AsyncPrivateKeySign called with operation pending.\n");
163 abort();
164 }
165
166 ScopedEVP_PKEY_CTX ctx(EVP_PKEY_CTX_new(test_state->private_key.get(),
167 nullptr));
168 if (!ctx) {
169 return ssl_private_key_failure;
170 }
171
172 // Write the signature into |test_state|.
173 size_t len = 0;
174 if (!EVP_PKEY_sign_init(ctx.get()) ||
175 !EVP_PKEY_CTX_set_signature_md(ctx.get(), md) ||
176 !EVP_PKEY_sign(ctx.get(), nullptr, &len, in, in_len)) {
177 return ssl_private_key_failure;
178 }
179 test_state->private_key_result.resize(len);
180 if (!EVP_PKEY_sign(ctx.get(), test_state->private_key_result.data(), &len, in,
181 in_len)) {
182 return ssl_private_key_failure;
183 }
184 test_state->private_key_result.resize(len);
185
186 // The signature will be released asynchronously in
187 // |AsyncPrivateKeySignComplete|.
188 return ssl_private_key_retry;
189 }
190
191 static ssl_private_key_result_t AsyncPrivateKeySignComplete(
192 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
193 TestState *test_state = GetTestState(ssl);
194 if (test_state->private_key_result.empty()) {
195 fprintf(stderr,
196 "AsyncPrivateKeySignComplete called without operation pending.\n");
197 abort();
198 }
199
200 if (test_state->private_key_retries < 2) {
201 // Only return the signature on the second attempt, to test both incomplete
202 // |sign| and |sign_complete|.
203 return ssl_private_key_retry;
204 }
205
206 if (max_out < test_state->private_key_result.size()) {
207 fprintf(stderr, "Output buffer too small.\n");
208 return ssl_private_key_failure;
209 }
210 memcpy(out, test_state->private_key_result.data(),
211 test_state->private_key_result.size());
212 *out_len = test_state->private_key_result.size();
213
214 test_state->private_key_result.clear();
215 test_state->private_key_retries = 0;
216 return ssl_private_key_success;
217 }
218
219 static ssl_private_key_result_t AsyncPrivateKeyDecrypt(
220 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
221 const uint8_t *in, size_t in_len) {
222 TestState *test_state = GetTestState(ssl);
223 if (!test_state->private_key_result.empty()) {
224 fprintf(stderr,
225 "AsyncPrivateKeyDecrypt called with operation pending.\n");
226 abort();
227 }
228
229 RSA *rsa = EVP_PKEY_get0_RSA(test_state->private_key.get());
230 if (rsa == NULL) {
231 fprintf(stderr,
232 "AsyncPrivateKeyDecrypt called with incorrect key type.\n");
233 abort();
234 }
235 test_state->private_key_result.resize(RSA_size(rsa));
236 if (!RSA_decrypt(rsa, out_len, test_state->private_key_result.data(),
237 RSA_size(rsa), in, in_len, RSA_NO_PADDING)) {
238 return ssl_private_key_failure;
239 }
240
241 test_state->private_key_result.resize(*out_len);
242
243 // The decryption will be released asynchronously in
244 // |AsyncPrivateKeyDecryptComplete|.
245 return ssl_private_key_retry;
246 }
247
248 static ssl_private_key_result_t AsyncPrivateKeyDecryptComplete(
249 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
250 TestState *test_state = GetTestState(ssl);
251 if (test_state->private_key_result.empty()) {
252 fprintf(stderr,
253 "AsyncPrivateKeyDecryptComplete called without operation "
254 "pending.\n");
255 abort();
256 }
257
258 if (test_state->private_key_retries < 2) {
259 // Only return the decryption on the second attempt, to test both incomplete
260 // |decrypt| and |decrypt_complete|.
261 return ssl_private_key_retry;
262 }
263
264 if (max_out < test_state->private_key_result.size()) {
265 fprintf(stderr, "Output buffer too small.\n");
266 return ssl_private_key_failure;
267 }
268 memcpy(out, test_state->private_key_result.data(),
269 test_state->private_key_result.size());
270 *out_len = test_state->private_key_result.size();
271
272 test_state->private_key_result.clear();
273 test_state->private_key_retries = 0;
274 return ssl_private_key_success;
275 }
276
277 static const SSL_PRIVATE_KEY_METHOD g_async_private_key_method = {
278 AsyncPrivateKeyType,
279 AsyncPrivateKeyMaxSignatureLen,
280 AsyncPrivateKeySign,
281 AsyncPrivateKeySignComplete,
282 AsyncPrivateKeyDecrypt,
283 AsyncPrivateKeyDecryptComplete
284 };
285
286 template<typename T>
287 struct Free {
288 void operator()(T *buf) {
289 free(buf);
290 }
291 };
292
293 static bool GetCertificate(SSL *ssl, ScopedX509 *out_x509,
294 ScopedEVP_PKEY *out_pkey) {
295 const TestConfig *config = GetTestConfig(ssl);
296
297 if (!config->digest_prefs.empty()) {
298 std::unique_ptr<char, Free<char>> digest_prefs(
299 strdup(config->digest_prefs.c_str()));
300 std::vector<int> digest_list;
301
302 for (;;) {
303 char *token =
304 strtok(digest_list.empty() ? digest_prefs.get() : nullptr, ",");
305 if (token == nullptr) {
306 break;
307 }
308
309 digest_list.push_back(EVP_MD_type(EVP_get_digestbyname(token)));
310 }
311
312 if (!SSL_set_private_key_digest_prefs(ssl, digest_list.data(),
313 digest_list.size())) {
314 return false;
315 }
316 }
317
318 if (!config->key_file.empty()) {
319 *out_pkey = LoadPrivateKey(config->key_file.c_str());
320 if (!*out_pkey) {
321 return false;
322 }
323 }
324 if (!config->cert_file.empty()) {
325 *out_x509 = LoadCertificate(config->cert_file.c_str());
326 if (!*out_x509) {
327 return false;
328 }
329 }
330 if (!config->ocsp_response.empty() &&
331 !SSL_CTX_set_ocsp_response(ssl->ctx,
332 (const uint8_t *)config->ocsp_response.data(),
333 config->ocsp_response.size())) {
334 return false;
335 }
336 return true;
337 }
338
339 static bool InstallCertificate(SSL *ssl) {
340 ScopedX509 x509;
341 ScopedEVP_PKEY pkey;
342 if (!GetCertificate(ssl, &x509, &pkey)) {
343 return false;
344 }
345
346 if (pkey) {
347 TestState *test_state = GetTestState(ssl);
348 const TestConfig *config = GetTestConfig(ssl);
349 if (config->async) {
350 test_state->private_key = std::move(pkey);
351 SSL_set_private_key_method(ssl, &g_async_private_key_method);
352 } else if (!SSL_use_PrivateKey(ssl, pkey.get())) {
353 return false;
354 }
355 }
356
357 if (x509 && !SSL_use_certificate(ssl, x509.get())) {
358 return false;
359 }
360
361 return true;
362 }
363
364 static int SelectCertificateCallback(const struct ssl_early_callback_ctx *ctx) {
365 const TestConfig *config = GetTestConfig(ctx->ssl);
366 GetTestState(ctx->ssl)->early_callback_called = true;
367
368 if (!config->expected_server_name.empty()) {
369 const uint8_t *extension_data;
370 size_t extension_len;
371 CBS extension, server_name_list, host_name;
372 uint8_t name_type;
373
374 if (!SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
375 &extension_data,
376 &extension_len)) {
377 fprintf(stderr, "Could not find server_name extension.\n");
378 return -1;
379 }
380
381 CBS_init(&extension, extension_data, extension_len);
382 if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
383 CBS_len(&extension) != 0 ||
384 !CBS_get_u8(&server_name_list, &name_type) ||
385 name_type != TLSEXT_NAMETYPE_host_name ||
386 !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
387 CBS_len(&server_name_list) != 0) {
388 fprintf(stderr, "Could not decode server_name extension.\n");
389 return -1;
390 }
391
392 if (!CBS_mem_equal(&host_name,
393 (const uint8_t*)config->expected_server_name.data(),
394 config->expected_server_name.size())) {
395 fprintf(stderr, "Server name mismatch.\n");
396 }
397 }
398
399 if (config->fail_early_callback) {
400 return -1;
401 }
402
403 // Install the certificate in the early callback.
404 if (config->use_early_callback) {
405 if (config->async) {
406 // Install the certificate asynchronously.
407 return 0;
408 }
409 if (!InstallCertificate(ctx->ssl)) {
410 return -1;
411 }
412 }
413 return 1;
414 }
415
416 static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
417 if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
418 return -1;
419 }
420
421 ScopedX509 x509;
422 ScopedEVP_PKEY pkey;
423 if (!GetCertificate(ssl, &x509, &pkey)) {
424 return -1;
425 }
426
427 // Return zero for no certificate.
428 if (!x509) {
429 return 0;
430 }
431
432 // Asynchronous private keys are not supported with client_cert_cb.
433 *out_x509 = x509.release();
434 *out_pkey = pkey.release();
435 return 1;
436 }
437
438 static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
439 SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data(store_ctx,
440 SSL_get_ex_data_X509_STORE_CTX_idx());
441 const TestConfig *config = GetTestConfig(ssl);
442
443 if (!config->expected_ocsp_response.empty()) {
444 const uint8_t *data;
445 size_t len;
446 SSL_get0_ocsp_response(ssl, &data, &len);
447 if (len == 0) {
448 fprintf(stderr, "OCSP response not available in verify callback\n");
449 return 0;
450 }
451 }
452
453 return 1;
454 }
455
456 static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
457 store_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION;
458 return 0;
459 }
460
461 static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
462 unsigned int *out_len, void *arg) {
463 const TestConfig *config = GetTestConfig(ssl);
464 if (config->advertise_npn.empty()) {
465 return SSL_TLSEXT_ERR_NOACK;
466 }
467
468 *out = (const uint8_t*)config->advertise_npn.data();
469 *out_len = config->advertise_npn.size();
470 return SSL_TLSEXT_ERR_OK;
471 }
472
473 static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
474 const uint8_t* in, unsigned inlen, void* arg) {
475 const TestConfig *config = GetTestConfig(ssl);
476 if (config->select_next_proto.empty()) {
477 return SSL_TLSEXT_ERR_NOACK;
478 }
479
480 *out = (uint8_t*)config->select_next_proto.data();
481 *outlen = config->select_next_proto.size();
482 return SSL_TLSEXT_ERR_OK;
483 }
484
485 static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
486 const uint8_t* in, unsigned inlen, void* arg) {
487 const TestConfig *config = GetTestConfig(ssl);
488 if (config->decline_alpn) {
489 return SSL_TLSEXT_ERR_NOACK;
490 }
491
492 if (!config->expected_advertised_alpn.empty() &&
493 (config->expected_advertised_alpn.size() != inlen ||
494 memcmp(config->expected_advertised_alpn.data(),
495 in, inlen) != 0)) {
496 fprintf(stderr, "bad ALPN select callback inputs\n");
497 exit(1);
498 }
499
500 *out = (const uint8_t*)config->select_alpn.data();
501 *outlen = config->select_alpn.size();
502 return SSL_TLSEXT_ERR_OK;
503 }
504
505 static unsigned PskClientCallback(SSL *ssl, const char *hint,
506 char *out_identity,
507 unsigned max_identity_len,
508 uint8_t *out_psk, unsigned max_psk_len) {
509 const TestConfig *config = GetTestConfig(ssl);
510
511 if (strcmp(hint ? hint : "", config->psk_identity.c_str()) != 0) {
512 fprintf(stderr, "Server PSK hint did not match.\n");
513 return 0;
514 }
515
516 // Account for the trailing '\0' for the identity.
517 if (config->psk_identity.size() >= max_identity_len ||
518 config->psk.size() > max_psk_len) {
519 fprintf(stderr, "PSK buffers too small\n");
520 return 0;
521 }
522
523 BUF_strlcpy(out_identity, config->psk_identity.c_str(),
524 max_identity_len);
525 memcpy(out_psk, config->psk.data(), config->psk.size());
526 return config->psk.size();
527 }
528
529 static unsigned PskServerCallback(SSL *ssl, const char *identity,
530 uint8_t *out_psk, unsigned max_psk_len) {
531 const TestConfig *config = GetTestConfig(ssl);
532
533 if (strcmp(identity, config->psk_identity.c_str()) != 0) {
534 fprintf(stderr, "Client PSK identity did not match.\n");
535 return 0;
536 }
537
538 if (config->psk.size() > max_psk_len) {
539 fprintf(stderr, "PSK buffers too small\n");
540 return 0;
541 }
542
543 memcpy(out_psk, config->psk.data(), config->psk.size());
544 return config->psk.size();
545 }
546
547 static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
548 *out_clock = PacketedBioGetClock(GetTestState(ssl)->packeted_bio);
549 }
550
551 static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
552 *out_pkey = GetTestState(ssl)->channel_id.release();
553 }
554
555 static int CertCallback(SSL *ssl, void *arg) {
556 if (!GetTestState(ssl)->cert_ready) {
557 return -1;
558 }
559 if (!InstallCertificate(ssl)) {
560 return 0;
561 }
562 return 1;
563 }
564
565 static SSL_SESSION *GetSessionCallback(SSL *ssl, uint8_t *data, int len,
566 int *copy) {
567 TestState *async_state = GetTestState(ssl);
568 if (async_state->session) {
569 *copy = 0;
570 return async_state->session.release();
571 } else if (async_state->pending_session) {
572 return SSL_magic_pending_session_ptr();
573 } else {
574 return NULL;
575 }
576 }
577
578 static int DDoSCallback(const struct ssl_early_callback_ctx *early_context) {
579 const TestConfig *config = GetTestConfig(early_context->ssl);
580 static int callback_num = 0;
581
582 callback_num++;
583 if (config->fail_ddos_callback ||
584 (config->fail_second_ddos_callback && callback_num == 2)) {
585 return 0;
586 }
587 return 1;
588 }
589
590 static void InfoCallback(const SSL *ssl, int type, int val) {
591 if (type == SSL_CB_HANDSHAKE_DONE) {
592 if (GetTestConfig(ssl)->handshake_never_done) {
593 fprintf(stderr, "handshake completed\n");
594 // Abort before any expected error code is printed, to ensure the overall
595 // test fails.
596 abort();
597 }
598 GetTestState(ssl)->handshake_done = true;
599 }
600 }
601
602 static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
603 GetTestState(ssl)->got_new_session = true;
604 // BoringSSL passes a reference to |session|.
605 SSL_SESSION_free(session);
606 return 1;
607 }
608
609 static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
610 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
611 int encrypt) {
612 // This is just test code, so use the all-zeros key.
613 static const uint8_t kZeros[16] = {0};
614
615 if (encrypt) {
616 memcpy(key_name, kZeros, sizeof(kZeros));
617 RAND_bytes(iv, 16);
618 } else if (memcmp(key_name, kZeros, 16) != 0) {
619 return 0;
620 }
621
622 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
623 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
624 return -1;
625 }
626
627 if (!encrypt) {
628 return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
629 }
630 return 1;
631 }
632
633 // kCustomExtensionValue is the extension value that the custom extension
634 // callbacks will add.
635 static const uint16_t kCustomExtensionValue = 1234;
636 static void *const kCustomExtensionAddArg =
637 reinterpret_cast<void *>(kCustomExtensionValue);
638 static void *const kCustomExtensionParseArg =
639 reinterpret_cast<void *>(kCustomExtensionValue + 1);
640 static const char kCustomExtensionContents[] = "custom extension";
641
642 static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
643 const uint8_t **out, size_t *out_len,
644 int *out_alert_value, void *add_arg) {
645 if (extension_value != kCustomExtensionValue ||
646 add_arg != kCustomExtensionAddArg) {
647 abort();
648 }
649
650 if (GetTestConfig(ssl)->custom_extension_skip) {
651 return 0;
652 }
653 if (GetTestConfig(ssl)->custom_extension_fail_add) {
654 return -1;
655 }
656
657 *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
658 *out_len = sizeof(kCustomExtensionContents) - 1;
659
660 return 1;
661 }
662
663 static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
664 const uint8_t *out, void *add_arg) {
665 if (extension_value != kCustomExtensionValue ||
666 add_arg != kCustomExtensionAddArg ||
667 out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
668 abort();
669 }
670 }
671
672 static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
673 const uint8_t *contents,
674 size_t contents_len,
675 int *out_alert_value, void *parse_arg) {
676 if (extension_value != kCustomExtensionValue ||
677 parse_arg != kCustomExtensionParseArg) {
678 abort();
679 }
680
681 if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
682 memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
683 *out_alert_value = SSL_AD_DECODE_ERROR;
684 return 0;
685 }
686
687 return 1;
688 }
689
690 // Connect returns a new socket connected to localhost on |port| or -1 on
691 // error.
692 static int Connect(uint16_t port) {
693 int sock = socket(AF_INET, SOCK_STREAM, 0);
694 if (sock == -1) {
695 PrintSocketError("socket");
696 return -1;
697 }
698 int nodelay = 1;
699 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
700 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
701 PrintSocketError("setsockopt");
702 closesocket(sock);
703 return -1;
704 }
705 sockaddr_in sin;
706 memset(&sin, 0, sizeof(sin));
707 sin.sin_family = AF_INET;
708 sin.sin_port = htons(port);
709 if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
710 PrintSocketError("inet_pton");
711 closesocket(sock);
712 return -1;
713 }
714 if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
715 sizeof(sin)) != 0) {
716 PrintSocketError("connect");
717 closesocket(sock);
718 return -1;
719 }
720 return sock;
721 }
722
723 class SocketCloser {
724 public:
725 explicit SocketCloser(int sock) : sock_(sock) {}
726 ~SocketCloser() {
727 // Half-close and drain the socket before releasing it. This seems to be
728 // necessary for graceful shutdown on Windows. It will also avoid write
729 // failures in the test runner.
730 #if defined(OPENSSL_WINDOWS)
731 shutdown(sock_, SD_SEND);
732 #else
733 shutdown(sock_, SHUT_WR);
734 #endif
735 while (true) {
736 char buf[1024];
737 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
738 break;
739 }
740 }
741 closesocket(sock_);
742 }
743
744 private:
745 const int sock_;
746 };
747
748 static ScopedSSL_CTX SetupCtx(const TestConfig *config) {
749 ScopedSSL_CTX ssl_ctx(SSL_CTX_new(
750 config->is_dtls ? DTLS_method() : TLS_method()));
751 if (!ssl_ctx) {
752 return nullptr;
753 }
754
755 std::string cipher_list = "ALL";
756 if (!config->cipher.empty()) {
757 cipher_list = config->cipher;
758 SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
759 }
760 if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
761 return nullptr;
762 }
763
764 if (!config->cipher_tls10.empty() &&
765 !SSL_CTX_set_cipher_list_tls10(ssl_ctx.get(),
766 config->cipher_tls10.c_str())) {
767 return nullptr;
768 }
769 if (!config->cipher_tls11.empty() &&
770 !SSL_CTX_set_cipher_list_tls11(ssl_ctx.get(),
771 config->cipher_tls11.c_str())) {
772 return nullptr;
773 }
774
775 ScopedDH dh(DH_get_2048_256(NULL));
776 if (!dh) {
777 return nullptr;
778 }
779
780 if (config->use_sparse_dh_prime) {
781 // This prime number is 2^1024 + 643 – a value just above a power of two.
782 // Because of its form, values modulo it are essentially certain to be one
783 // byte shorter. This is used to test padding of these values.
784 if (BN_hex2bn(
785 &dh->p,
786 "1000000000000000000000000000000000000000000000000000000000000000"
787 "0000000000000000000000000000000000000000000000000000000000000000"
788 "0000000000000000000000000000000000000000000000000000000000000000"
789 "0000000000000000000000000000000000000000000000000000000000000028"
790 "3") == 0 ||
791 !BN_set_word(dh->g, 2)) {
792 return nullptr;
793 }
794 BN_free(dh->q);
795 dh->q = NULL;
796 dh->priv_length = 0;
797 }
798
799 if (!SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
800 return nullptr;
801 }
802
803 if (config->async && config->is_server) {
804 // Disable the internal session cache. To test asynchronous session lookup,
805 // we use an external session cache.
806 SSL_CTX_set_session_cache_mode(
807 ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
808 SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
809 } else {
810 SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
811 }
812
813 SSL_CTX_set_select_certificate_cb(ssl_ctx.get(), SelectCertificateCallback);
814
815 if (config->use_old_client_cert_callback) {
816 SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
817 }
818
819 SSL_CTX_set_next_protos_advertised_cb(
820 ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
821 if (!config->select_next_proto.empty()) {
822 SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
823 NULL);
824 }
825
826 if (!config->select_alpn.empty() || config->decline_alpn) {
827 SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
828 }
829
830 SSL_CTX_enable_tls_channel_id(ssl_ctx.get());
831 SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
832
833 SSL_CTX_set_current_time_cb(ssl_ctx.get(), CurrentTimeCallback);
834
835 SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
836 SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
837
838 if (config->use_ticket_callback) {
839 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
840 }
841
842 if (config->enable_client_custom_extension &&
843 !SSL_CTX_add_client_custom_ext(
844 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
845 CustomExtensionFreeCallback, kCustomExtensionAddArg,
846 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
847 return nullptr;
848 }
849
850 if (config->enable_server_custom_extension &&
851 !SSL_CTX_add_server_custom_ext(
852 ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
853 CustomExtensionFreeCallback, kCustomExtensionAddArg,
854 CustomExtensionParseCallback, kCustomExtensionParseArg)) {
855 return nullptr;
856 }
857
858 if (config->verify_fail) {
859 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
860 } else {
861 SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
862 }
863
864 if (!config->signed_cert_timestamps.empty() &&
865 !SSL_CTX_set_signed_cert_timestamp_list(
866 ssl_ctx.get(), (const uint8_t *)config->signed_cert_timestamps.data(),
867 config->signed_cert_timestamps.size())) {
868 return nullptr;
869 }
870
871 return ssl_ctx;
872 }
873
874 // RetryAsync is called after a failed operation on |ssl| with return code
875 // |ret|. If the operation should be retried, it simulates one asynchronous
876 // event and returns true. Otherwise it returns false.
877 static bool RetryAsync(SSL *ssl, int ret) {
878 // No error; don't retry.
879 if (ret >= 0) {
880 return false;
881 }
882
883 TestState *test_state = GetTestState(ssl);
884 assert(GetTestConfig(ssl)->async);
885
886 if (test_state->packeted_bio != nullptr &&
887 PacketedBioAdvanceClock(test_state->packeted_bio)) {
888 // The DTLS retransmit logic silently ignores write failures. So the test
889 // may progress, allow writes through synchronously.
890 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
891 int timeout_ret = DTLSv1_handle_timeout(ssl);
892 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
893
894 if (timeout_ret < 0) {
895 fprintf(stderr, "Error retransmitting.\n");
896 return false;
897 }
898 return true;
899 }
900
901 // See if we needed to read or write more. If so, allow one byte through on
902 // the appropriate end to maximally stress the state machine.
903 switch (SSL_get_error(ssl, ret)) {
904 case SSL_ERROR_WANT_READ:
905 AsyncBioAllowRead(test_state->async_bio, 1);
906 return true;
907 case SSL_ERROR_WANT_WRITE:
908 AsyncBioAllowWrite(test_state->async_bio, 1);
909 return true;
910 case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
911 ScopedEVP_PKEY pkey = LoadPrivateKey(GetTestConfig(ssl)->send_channel_id);
912 if (!pkey) {
913 return false;
914 }
915 test_state->channel_id = std::move(pkey);
916 return true;
917 }
918 case SSL_ERROR_WANT_X509_LOOKUP:
919 test_state->cert_ready = true;
920 return true;
921 case SSL_ERROR_PENDING_SESSION:
922 test_state->session = std::move(test_state->pending_session);
923 return true;
924 case SSL_ERROR_PENDING_CERTIFICATE:
925 // The handshake will resume without a second call to the early callback.
926 return InstallCertificate(ssl);
927 case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
928 test_state->private_key_retries++;
929 return true;
930 default:
931 return false;
932 }
933 }
934
935 // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
936 // the result value of the final |SSL_read| call.
937 static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
938 const TestConfig *config = GetTestConfig(ssl);
939 TestState *test_state = GetTestState(ssl);
940 int ret;
941 do {
942 if (config->async) {
943 // The DTLS retransmit logic silently ignores write failures. So the test
944 // may progress, allow writes through synchronously. |SSL_read| may
945 // trigger a retransmit, so disconnect the write quota.
946 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
947 }
948 ret = SSL_read(ssl, out, max_out);
949 if (config->async) {
950 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
951 }
952 } while (config->async && RetryAsync(ssl, ret));
953 return ret;
954 }
955
956 // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
957 // operations. It returns the result of the final |SSL_write| call.
958 static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
959 const TestConfig *config = GetTestConfig(ssl);
960 int ret;
961 do {
962 ret = SSL_write(ssl, in, in_len);
963 if (ret > 0) {
964 in += ret;
965 in_len -= ret;
966 }
967 } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
968 return ret;
969 }
970
971 // DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
972 // returns the result of the final |SSL_shutdown| call.
973 static int DoShutdown(SSL *ssl) {
974 const TestConfig *config = GetTestConfig(ssl);
975 int ret;
976 do {
977 ret = SSL_shutdown(ssl);
978 } while (config->async && RetryAsync(ssl, ret));
979 return ret;
980 }
981
982 // CheckHandshakeProperties checks, immediately after |ssl| completes its
983 // initial handshake (or False Starts), whether all the properties are
984 // consistent with the test configuration and invariants.
985 static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
986 const TestConfig *config = GetTestConfig(ssl);
987
988 if (SSL_get_current_cipher(ssl) == nullptr) {
989 fprintf(stderr, "null cipher after handshake\n");
990 return false;
991 }
992
993 if (is_resume &&
994 (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
995 fprintf(stderr, "session was%s reused\n",
996 SSL_session_reused(ssl) ? "" : " not");
997 return false;
998 }
999
1000 bool expect_handshake_done = is_resume || !config->false_start;
1001 if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
1002 fprintf(stderr, "handshake was%s completed\n",
1003 GetTestState(ssl)->handshake_done ? "" : " not");
1004 return false;
1005 }
1006
1007 if (expect_handshake_done && !config->is_server) {
1008 bool expect_new_session =
1009 !config->expect_no_session &&
1010 (!SSL_session_reused(ssl) || config->expect_ticket_renewal);
1011 if (expect_new_session != GetTestState(ssl)->got_new_session) {
1012 fprintf(stderr,
1013 "new session was%s cached, but we expected the opposite\n",
1014 GetTestState(ssl)->got_new_session ? "" : " not");
1015 return false;
1016 }
1017 }
1018
1019 if (config->is_server && !GetTestState(ssl)->early_callback_called) {
1020 fprintf(stderr, "early callback not called\n");
1021 return false;
1022 }
1023
1024 if (!config->expected_server_name.empty()) {
1025 const char *server_name =
1026 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1027 if (server_name != config->expected_server_name) {
1028 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
1029 server_name, config->expected_server_name.c_str());
1030 return false;
1031 }
1032 }
1033
1034 if (!config->expected_certificate_types.empty()) {
1035 const uint8_t *certificate_types;
1036 size_t certificate_types_len =
1037 SSL_get0_certificate_types(ssl, &certificate_types);
1038 if (certificate_types_len != config->expected_certificate_types.size() ||
1039 memcmp(certificate_types,
1040 config->expected_certificate_types.data(),
1041 certificate_types_len) != 0) {
1042 fprintf(stderr, "certificate types mismatch\n");
1043 return false;
1044 }
1045 }
1046
1047 if (!config->expected_next_proto.empty()) {
1048 const uint8_t *next_proto;
1049 unsigned next_proto_len;
1050 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
1051 if (next_proto_len != config->expected_next_proto.size() ||
1052 memcmp(next_proto, config->expected_next_proto.data(),
1053 next_proto_len) != 0) {
1054 fprintf(stderr, "negotiated next proto mismatch\n");
1055 return false;
1056 }
1057 }
1058
1059 if (!config->expected_alpn.empty()) {
1060 const uint8_t *alpn_proto;
1061 unsigned alpn_proto_len;
1062 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
1063 if (alpn_proto_len != config->expected_alpn.size() ||
1064 memcmp(alpn_proto, config->expected_alpn.data(),
1065 alpn_proto_len) != 0) {
1066 fprintf(stderr, "negotiated alpn proto mismatch\n");
1067 return false;
1068 }
1069 }
1070
1071 if (!config->expected_channel_id.empty()) {
1072 uint8_t channel_id[64];
1073 if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
1074 fprintf(stderr, "no channel id negotiated\n");
1075 return false;
1076 }
1077 if (config->expected_channel_id.size() != 64 ||
1078 memcmp(config->expected_channel_id.data(),
1079 channel_id, 64) != 0) {
1080 fprintf(stderr, "channel id mismatch\n");
1081 return false;
1082 }
1083 }
1084
1085 if (config->expect_extended_master_secret) {
1086 if (!ssl->session->extended_master_secret) {
1087 fprintf(stderr, "No EMS for session when expected");
1088 return false;
1089 }
1090 }
1091
1092 if (!config->expected_ocsp_response.empty()) {
1093 const uint8_t *data;
1094 size_t len;
1095 SSL_get0_ocsp_response(ssl, &data, &len);
1096 if (config->expected_ocsp_response.size() != len ||
1097 memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
1098 fprintf(stderr, "OCSP response mismatch\n");
1099 return false;
1100 }
1101 }
1102
1103 if (!config->expected_signed_cert_timestamps.empty()) {
1104 const uint8_t *data;
1105 size_t len;
1106 SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
1107 if (config->expected_signed_cert_timestamps.size() != len ||
1108 memcmp(config->expected_signed_cert_timestamps.data(),
1109 data, len) != 0) {
1110 fprintf(stderr, "SCT list mismatch\n");
1111 return false;
1112 }
1113 }
1114
1115 if (config->expect_verify_result) {
1116 int expected_verify_result = config->verify_fail ?
1117 X509_V_ERR_APPLICATION_VERIFICATION :
1118 X509_V_OK;
1119
1120 if (SSL_get_verify_result(ssl) != expected_verify_result) {
1121 fprintf(stderr, "Wrong certificate verification result\n");
1122 return false;
1123 }
1124 }
1125
1126 if (config->expect_server_key_exchange_hash != 0 &&
1127 config->expect_server_key_exchange_hash !=
1128 SSL_get_server_key_exchange_hash(ssl)) {
1129 fprintf(stderr, "ServerKeyExchange hash was %d, wanted %d.\n",
1130 SSL_get_server_key_exchange_hash(ssl),
1131 config->expect_server_key_exchange_hash);
1132 return false;
1133 }
1134
1135 if (config->expect_key_exchange_info != 0) {
1136 uint32_t info = SSL_SESSION_get_key_exchange_info(SSL_get_session(ssl));
1137 if (static_cast<uint32_t>(config->expect_key_exchange_info) != info) {
1138 fprintf(stderr, "key_exchange_info was %" PRIu32 ", wanted %" PRIu32 "\n",
1139 info, static_cast<uint32_t>(config->expect_key_exchange_info));
1140 return false;
1141 }
1142 }
1143
1144 if (!config->is_server) {
1145 /* Clients should expect a peer certificate chain iff this was not a PSK
1146 * cipher suite. */
1147 if (config->psk.empty()) {
1148 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
1149 fprintf(stderr, "Missing peer certificate chain!\n");
1150 return false;
1151 }
1152 } else if (SSL_get_peer_cert_chain(ssl) != nullptr) {
1153 fprintf(stderr, "Unexpected peer certificate chain!\n");
1154 return false;
1155 }
1156 }
1157 return true;
1158 }
1159
1160 // DoExchange runs a test SSL exchange against the peer. On success, it returns
1161 // true and sets |*out_session| to the negotiated SSL session. If the test is a
1162 // resumption attempt, |is_resume| is true and |session| is the session from the
1163 // previous exchange.
1164 static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx,
1165 const TestConfig *config, bool is_resume,
1166 SSL_SESSION *session) {
1167 ScopedSSL ssl(SSL_new(ssl_ctx));
1168 if (!ssl) {
1169 return false;
1170 }
1171
1172 if (!SetTestConfig(ssl.get(), config) ||
1173 !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
1174 return false;
1175 }
1176
1177 if (config->fallback_scsv &&
1178 !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
1179 return false;
1180 }
1181 if (!config->use_early_callback && !config->use_old_client_cert_callback) {
1182 if (config->async) {
1183 SSL_set_cert_cb(ssl.get(), CertCallback, NULL);
1184 } else if (!InstallCertificate(ssl.get())) {
1185 return false;
1186 }
1187 }
1188 if (config->require_any_client_certificate) {
1189 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1190 NULL);
1191 }
1192 if (config->verify_peer) {
1193 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
1194 }
1195 if (config->false_start) {
1196 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
1197 }
1198 if (config->cbc_record_splitting) {
1199 SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
1200 }
1201 if (config->partial_write) {
1202 SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
1203 }
1204 if (config->no_tls13) {
1205 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
1206 }
1207 if (config->no_tls12) {
1208 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
1209 }
1210 if (config->no_tls11) {
1211 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
1212 }
1213 if (config->no_tls1) {
1214 SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
1215 }
1216 if (config->no_ssl3) {
1217 SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
1218 }
1219 if (!config->expected_channel_id.empty()) {
1220 SSL_enable_tls_channel_id(ssl.get());
1221 }
1222 if (!config->send_channel_id.empty()) {
1223 SSL_enable_tls_channel_id(ssl.get());
1224 if (!config->async) {
1225 // The async case will be supplied by |ChannelIdCallback|.
1226 ScopedEVP_PKEY pkey = LoadPrivateKey(config->send_channel_id);
1227 if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
1228 return false;
1229 }
1230 }
1231 }
1232 if (!config->host_name.empty() &&
1233 !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
1234 return false;
1235 }
1236 if (!config->advertise_alpn.empty() &&
1237 SSL_set_alpn_protos(ssl.get(),
1238 (const uint8_t *)config->advertise_alpn.data(),
1239 config->advertise_alpn.size()) != 0) {
1240 return false;
1241 }
1242 if (!config->psk.empty()) {
1243 SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
1244 SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
1245 }
1246 if (!config->psk_identity.empty() &&
1247 !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
1248 return false;
1249 }
1250 if (!config->srtp_profiles.empty() &&
1251 !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
1252 return false;
1253 }
1254 if (config->enable_ocsp_stapling &&
1255 !SSL_enable_ocsp_stapling(ssl.get())) {
1256 return false;
1257 }
1258 if (config->enable_signed_cert_timestamps &&
1259 !SSL_enable_signed_cert_timestamps(ssl.get())) {
1260 return false;
1261 }
1262 if (config->min_version != 0) {
1263 SSL_set_min_version(ssl.get(), (uint16_t)config->min_version);
1264 }
1265 if (config->max_version != 0) {
1266 SSL_set_max_version(ssl.get(), (uint16_t)config->max_version);
1267 }
1268 if (config->mtu != 0) {
1269 SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
1270 SSL_set_mtu(ssl.get(), config->mtu);
1271 }
1272 if (config->install_ddos_callback) {
1273 SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
1274 }
1275 if (config->renegotiate_once) {
1276 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_once);
1277 }
1278 if (config->renegotiate_freely) {
1279 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
1280 }
1281 if (config->renegotiate_ignore) {
1282 SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_ignore);
1283 }
1284 if (!config->check_close_notify) {
1285 SSL_set_quiet_shutdown(ssl.get(), 1);
1286 }
1287 if (config->disable_npn) {
1288 SSL_set_options(ssl.get(), SSL_OP_DISABLE_NPN);
1289 }
1290 if (config->p384_only) {
1291 int nid = NID_secp384r1;
1292 if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
1293 return false;
1294 }
1295 }
1296 if (config->enable_all_curves) {
1297 static const int kAllCurves[] = {
1298 NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_X25519,
1299 };
1300 if (!SSL_set1_curves(ssl.get(), kAllCurves,
1301 sizeof(kAllCurves) / sizeof(kAllCurves[0]))) {
1302 return false;
1303 }
1304 }
1305 if (config->initial_timeout_duration_ms > 0) {
1306 DTLSv1_set_initial_timeout_duration(ssl.get(),
1307 config->initial_timeout_duration_ms);
1308 }
1309
1310 int sock = Connect(config->port);
1311 if (sock == -1) {
1312 return false;
1313 }
1314 SocketCloser closer(sock);
1315
1316 ScopedBIO bio(BIO_new_socket(sock, BIO_NOCLOSE));
1317 if (!bio) {
1318 return false;
1319 }
1320 if (config->is_dtls) {
1321 ScopedBIO packeted = PacketedBioCreate(!config->async);
1322 if (!packeted) {
1323 return false;
1324 }
1325 GetTestState(ssl.get())->packeted_bio = packeted.get();
1326 BIO_push(packeted.get(), bio.release());
1327 bio = std::move(packeted);
1328 }
1329 if (config->async) {
1330 ScopedBIO async_scoped =
1331 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
1332 if (!async_scoped) {
1333 return false;
1334 }
1335 BIO_push(async_scoped.get(), bio.release());
1336 GetTestState(ssl.get())->async_bio = async_scoped.get();
1337 bio = std::move(async_scoped);
1338 }
1339 SSL_set_bio(ssl.get(), bio.get(), bio.get());
1340 bio.release(); // SSL_set_bio takes ownership.
1341
1342 if (session != NULL) {
1343 if (!config->is_server) {
1344 if (SSL_set_session(ssl.get(), session) != 1) {
1345 return false;
1346 }
1347 } else if (config->async) {
1348 // The internal session cache is disabled, so install the session
1349 // manually.
1350 GetTestState(ssl.get())->pending_session.reset(
1351 SSL_SESSION_up_ref(session));
1352 }
1353 }
1354
1355 if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1356 fprintf(stderr, "non-null cipher before handshake\n");
1357 return false;
1358 }
1359
1360 int ret;
1361 if (config->implicit_handshake) {
1362 if (config->is_server) {
1363 SSL_set_accept_state(ssl.get());
1364 } else {
1365 SSL_set_connect_state(ssl.get());
1366 }
1367 } else {
1368 do {
1369 if (config->is_server) {
1370 ret = SSL_accept(ssl.get());
1371 } else {
1372 ret = SSL_connect(ssl.get());
1373 }
1374 } while (config->async && RetryAsync(ssl.get(), ret));
1375 if (ret != 1 ||
1376 !CheckHandshakeProperties(ssl.get(), is_resume)) {
1377 return false;
1378 }
1379
1380 // Reset the state to assert later that the callback isn't called in
1381 // renegotations.
1382 GetTestState(ssl.get())->got_new_session = false;
1383 }
1384
1385 if (config->export_keying_material > 0) {
1386 std::vector<uint8_t> result(
1387 static_cast<size_t>(config->export_keying_material));
1388 if (!SSL_export_keying_material(
1389 ssl.get(), result.data(), result.size(),
1390 config->export_label.data(), config->export_label.size(),
1391 reinterpret_cast<const uint8_t*>(config->export_context.data()),
1392 config->export_context.size(), config->use_export_context)) {
1393 fprintf(stderr, "failed to export keying material\n");
1394 return false;
1395 }
1396 if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1397 return false;
1398 }
1399 }
1400
1401 if (config->tls_unique) {
1402 uint8_t tls_unique[16];
1403 size_t tls_unique_len;
1404 if (!SSL_get_tls_unique(ssl.get(), tls_unique, &tls_unique_len,
1405 sizeof(tls_unique))) {
1406 fprintf(stderr, "failed to get tls-unique\n");
1407 return false;
1408 }
1409
1410 if (tls_unique_len != 12) {
1411 fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
1412 static_cast<unsigned>(tls_unique_len));
1413 return false;
1414 }
1415
1416 if (WriteAll(ssl.get(), tls_unique, tls_unique_len) < 0) {
1417 return false;
1418 }
1419 }
1420
1421 if (config->write_different_record_sizes) {
1422 if (config->is_dtls) {
1423 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
1424 return false;
1425 }
1426 // This mode writes a number of different record sizes in an attempt to
1427 // trip up the CBC record splitting code.
1428 static const size_t kBufLen = 32769;
1429 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1430 memset(buf.get(), 0x42, kBufLen);
1431 static const size_t kRecordSizes[] = {
1432 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
1433 for (size_t i = 0; i < sizeof(kRecordSizes) / sizeof(kRecordSizes[0]);
1434 i++) {
1435 const size_t len = kRecordSizes[i];
1436 if (len > kBufLen) {
1437 fprintf(stderr, "Bad kRecordSizes value.\n");
1438 return false;
1439 }
1440 if (WriteAll(ssl.get(), buf.get(), len) < 0) {
1441 return false;
1442 }
1443 }
1444 } else {
1445 if (config->shim_writes_first) {
1446 if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1447 5) < 0) {
1448 return false;
1449 }
1450 }
1451 if (!config->shim_shuts_down) {
1452 for (;;) {
1453 static const size_t kBufLen = 16384;
1454 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1455
1456 // Read only 512 bytes at a time in TLS to ensure records may be
1457 // returned in multiple reads.
1458 int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
1459 int err = SSL_get_error(ssl.get(), n);
1460 if (err == SSL_ERROR_ZERO_RETURN ||
1461 (n == 0 && err == SSL_ERROR_SYSCALL)) {
1462 if (n != 0) {
1463 fprintf(stderr, "Invalid SSL_get_error output\n");
1464 return false;
1465 }
1466 // Stop on either clean or unclean shutdown.
1467 break;
1468 } else if (err != SSL_ERROR_NONE) {
1469 if (n > 0) {
1470 fprintf(stderr, "Invalid SSL_get_error output\n");
1471 return false;
1472 }
1473 return false;
1474 }
1475 // Successfully read data.
1476 if (n <= 0) {
1477 fprintf(stderr, "Invalid SSL_get_error output\n");
1478 return false;
1479 }
1480
1481 // After a successful read, with or without False Start, the handshake
1482 // must be complete.
1483 if (!GetTestState(ssl.get())->handshake_done) {
1484 fprintf(stderr, "handshake was not completed after SSL_read\n");
1485 return false;
1486 }
1487
1488 for (int i = 0; i < n; i++) {
1489 buf[i] ^= 0xff;
1490 }
1491 if (WriteAll(ssl.get(), buf.get(), n) < 0) {
1492 return false;
1493 }
1494 }
1495 }
1496 }
1497
1498 if (!config->is_server && !config->false_start &&
1499 !config->implicit_handshake &&
1500 GetTestState(ssl.get())->got_new_session) {
1501 fprintf(stderr, "new session was established after the handshake\n");
1502 return false;
1503 }
1504
1505 if (out_session) {
1506 out_session->reset(SSL_get1_session(ssl.get()));
1507 }
1508
1509 ret = DoShutdown(ssl.get());
1510
1511 if (config->shim_shuts_down && config->check_close_notify) {
1512 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1513 // it returns zero when our close_notify is sent, then one when the peer's
1514 // is received.
1515 if (ret != 0) {
1516 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1517 return false;
1518 }
1519 ret = DoShutdown(ssl.get());
1520 }
1521
1522 if (ret != 1) {
1523 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1524 return false;
1525 }
1526
1527 if (SSL_total_renegotiations(ssl.get()) !=
1528 config->expect_total_renegotiations) {
1529 fprintf(stderr, "Expected %d renegotiations, got %d\n",
1530 config->expect_total_renegotiations,
1531 SSL_total_renegotiations(ssl.get()));
1532 return false;
1533 }
1534
1535 return true;
1536 }
1537
1538 class StderrDelimiter {
1539 public:
1540 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
1541 };
1542
1543 int main(int argc, char **argv) {
1544 // To distinguish ASan's output from ours, add a trailing message to stderr.
1545 // Anything following this line will be considered an error.
1546 StderrDelimiter delimiter;
1547
1548 #if defined(OPENSSL_WINDOWS)
1549 /* Initialize Winsock. */
1550 WORD wsa_version = MAKEWORD(2, 2);
1551 WSADATA wsa_data;
1552 int wsa_err = WSAStartup(wsa_version, &wsa_data);
1553 if (wsa_err != 0) {
1554 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1555 return 1;
1556 }
1557 if (wsa_data.wVersion != wsa_version) {
1558 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1559 return 1;
1560 }
1561 #else
1562 signal(SIGPIPE, SIG_IGN);
1563 #endif
1564
1565 CRYPTO_library_init();
1566 g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
1567 g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
1568 if (g_config_index < 0 || g_state_index < 0) {
1569 return 1;
1570 }
1571
1572 TestConfig config;
1573 if (!ParseConfig(argc - 1, argv + 1, &config)) {
1574 return Usage(argv[0]);
1575 }
1576
1577 ScopedSSL_CTX ssl_ctx = SetupCtx(&config);
1578 if (!ssl_ctx) {
1579 ERR_print_errors_fp(stderr);
1580 return 1;
1581 }
1582
1583 ScopedSSL_SESSION session;
1584 if (!DoExchange(&session, ssl_ctx.get(), &config, false /* is_resume */,
1585 NULL /* session */)) {
1586 ERR_print_errors_fp(stderr);
1587 return 1;
1588 }
1589
1590 if (config.resume &&
1591 !DoExchange(NULL, ssl_ctx.get(), &config, true /* is_resume */,
1592 session.get())) {
1593 ERR_print_errors_fp(stderr);
1594 return 1;
1595 }
1596
1597 return 0;
1598 }