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 #include <openssl/base.h>
16
17 #if !defined(OPENSSL_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>
27 OPENSSL_MSVC_PRAGMA(warning(push, 3))
28 #include <winsock2.h>
29 #include <ws2tcpip.h>
OPENSSL_MSVC_PRAGMA(warning (pop))30 OPENSSL_MSVC_PRAGMA(warning(pop))
31
32 OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
33 #endif
34
35 #include <assert.h>
36 #include <inttypes.h>
37 #include <string.h>
38 #include <time.h>
39
40 #include <openssl/aead.h>
41 #include <openssl/bio.h>
42 #include <openssl/bytestring.h>
43 #include <openssl/cipher.h>
44 #include <openssl/crypto.h>
45 #include <openssl/digest.h>
46 #include <openssl/err.h>
47 #include <openssl/evp.h>
48 #include <openssl/hmac.h>
49 #include <openssl/nid.h>
50 #include <openssl/rand.h>
51 #include <openssl/ssl.h>
52 #include <openssl/x509.h>
53
54 #include <functional>
55 #include <memory>
56 #include <string>
57 #include <vector>
58
59 #include "../../crypto/internal.h"
60 #include "../internal.h"
61 #include "async_bio.h"
62 #include "handshake_util.h"
63 #include "mock_quic_transport.h"
64 #include "packeted_bio.h"
65 #include "settings_writer.h"
66 #include "test_config.h"
67 #include "test_state.h"
68
69
70 #if !defined(OPENSSL_WINDOWS)
71 static int closesocket(int sock) {
72 return close(sock);
73 }
74
PrintSocketError(const char * func)75 static void PrintSocketError(const char *func) {
76 perror(func);
77 }
78 #else
79 static void PrintSocketError(const char *func) {
80 fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
81 }
82 #endif
83
Usage(const char * program)84 static int Usage(const char *program) {
85 fprintf(stderr, "Usage: %s [flags...]\n", program);
86 return 1;
87 }
88
89 template<typename T>
90 struct Free {
operator ()Free91 void operator()(T *buf) {
92 free(buf);
93 }
94 };
95
96 // Connect returns a new socket connected to localhost on |port| or -1 on
97 // error.
Connect(uint16_t port)98 static int Connect(uint16_t port) {
99 for (int af : { AF_INET6, AF_INET }) {
100 int sock = socket(af, SOCK_STREAM, 0);
101 if (sock == -1) {
102 PrintSocketError("socket");
103 return -1;
104 }
105 int nodelay = 1;
106 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
107 reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
108 PrintSocketError("setsockopt");
109 closesocket(sock);
110 return -1;
111 }
112
113 sockaddr_storage ss;
114 OPENSSL_memset(&ss, 0, sizeof(ss));
115 ss.ss_family = af;
116 socklen_t len = 0;
117
118 if (af == AF_INET6) {
119 sockaddr_in6 *sin6 = (sockaddr_in6 *) &ss;
120 len = sizeof(*sin6);
121 sin6->sin6_port = htons(port);
122 if (!inet_pton(AF_INET6, "::1", &sin6->sin6_addr)) {
123 PrintSocketError("inet_pton");
124 closesocket(sock);
125 return -1;
126 }
127 } else if (af == AF_INET) {
128 sockaddr_in *sin = (sockaddr_in *) &ss;
129 len = sizeof(*sin);
130 sin->sin_port = htons(port);
131 if (!inet_pton(AF_INET, "127.0.0.1", &sin->sin_addr)) {
132 PrintSocketError("inet_pton");
133 closesocket(sock);
134 return -1;
135 }
136 }
137
138 if (connect(sock, reinterpret_cast<const sockaddr*>(&ss), len) == 0) {
139 return sock;
140 }
141 closesocket(sock);
142 }
143
144 PrintSocketError("connect");
145 return -1;
146 }
147
148 class SocketCloser {
149 public:
SocketCloser(int sock)150 explicit SocketCloser(int sock) : sock_(sock) {}
~SocketCloser()151 ~SocketCloser() {
152 // Half-close and drain the socket before releasing it. This seems to be
153 // necessary for graceful shutdown on Windows. It will also avoid write
154 // failures in the test runner.
155 #if defined(OPENSSL_WINDOWS)
156 shutdown(sock_, SD_SEND);
157 #else
158 shutdown(sock_, SHUT_WR);
159 #endif
160 while (true) {
161 char buf[1024];
162 if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
163 break;
164 }
165 }
166 closesocket(sock_);
167 }
168
169 private:
170 const int sock_;
171 };
172
173 // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
174 // the result value of the final |SSL_read| call.
DoRead(SSL * ssl,uint8_t * out,size_t max_out)175 static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
176 const TestConfig *config = GetTestConfig(ssl);
177 TestState *test_state = GetTestState(ssl);
178 if (test_state->quic_transport) {
179 return test_state->quic_transport->ReadApplicationData(out, max_out);
180 }
181 int ret;
182 do {
183 if (config->async) {
184 // The DTLS retransmit logic silently ignores write failures. So the test
185 // may progress, allow writes through synchronously. |SSL_read| may
186 // trigger a retransmit, so disconnect the write quota.
187 AsyncBioEnforceWriteQuota(test_state->async_bio, false);
188 }
189 ret = CheckIdempotentError("SSL_peek/SSL_read", ssl, [&]() -> int {
190 return config->peek_then_read ? SSL_peek(ssl, out, max_out)
191 : SSL_read(ssl, out, max_out);
192 });
193 if (config->async) {
194 AsyncBioEnforceWriteQuota(test_state->async_bio, true);
195 }
196
197 // Run the exporter after each read. This is to test that the exporter fails
198 // during a renegotiation.
199 if (config->use_exporter_between_reads) {
200 uint8_t buf;
201 if (!SSL_export_keying_material(ssl, &buf, 1, NULL, 0, NULL, 0, 0)) {
202 fprintf(stderr, "failed to export keying material\n");
203 return -1;
204 }
205 }
206 } while (RetryAsync(ssl, ret));
207
208 if (config->peek_then_read && ret > 0) {
209 std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
210
211 // SSL_peek should synchronously return the same data.
212 int ret2 = SSL_peek(ssl, buf.get(), ret);
213 if (ret2 != ret ||
214 OPENSSL_memcmp(buf.get(), out, ret) != 0) {
215 fprintf(stderr, "First and second SSL_peek did not match.\n");
216 return -1;
217 }
218
219 // SSL_read should synchronously return the same data and consume it.
220 ret2 = SSL_read(ssl, buf.get(), ret);
221 if (ret2 != ret ||
222 OPENSSL_memcmp(buf.get(), out, ret) != 0) {
223 fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
224 return -1;
225 }
226 }
227
228 return ret;
229 }
230
231 // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
232 // operations. It returns the result of the final |SSL_write| call.
WriteAll(SSL * ssl,const void * in_,size_t in_len)233 static int WriteAll(SSL *ssl, const void *in_, size_t in_len) {
234 TestState *test_state = GetTestState(ssl);
235 const uint8_t *in = reinterpret_cast<const uint8_t *>(in_);
236 if (test_state->quic_transport) {
237 if (!test_state->quic_transport->WriteApplicationData(in, in_len)) {
238 return -1;
239 }
240 return in_len;
241 }
242 int ret;
243 do {
244 ret = SSL_write(ssl, in, in_len);
245 if (ret > 0) {
246 in += ret;
247 in_len -= ret;
248 }
249 } while (RetryAsync(ssl, ret) || (ret > 0 && in_len > 0));
250 return ret;
251 }
252
253 // DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
254 // returns the result of the final |SSL_shutdown| call.
DoShutdown(SSL * ssl)255 static int DoShutdown(SSL *ssl) {
256 int ret;
257 do {
258 ret = SSL_shutdown(ssl);
259 } while (RetryAsync(ssl, ret));
260 return ret;
261 }
262
263 // DoSendFatalAlert calls |SSL_send_fatal_alert|, resolving any asynchronous
264 // operations. It returns the result of the final |SSL_send_fatal_alert| call.
DoSendFatalAlert(SSL * ssl,uint8_t alert)265 static int DoSendFatalAlert(SSL *ssl, uint8_t alert) {
266 int ret;
267 do {
268 ret = SSL_send_fatal_alert(ssl, alert);
269 } while (RetryAsync(ssl, ret));
270 return ret;
271 }
272
GetProtocolVersion(const SSL * ssl)273 static uint16_t GetProtocolVersion(const SSL *ssl) {
274 uint16_t version = SSL_version(ssl);
275 if (!SSL_is_dtls(ssl)) {
276 return version;
277 }
278 return 0x0201 + ~version;
279 }
280
281 // CheckAuthProperties checks, after the initial handshake is completed or
282 // after a renegotiation, that authentication-related properties match |config|.
CheckAuthProperties(SSL * ssl,bool is_resume,const TestConfig * config)283 static bool CheckAuthProperties(SSL *ssl, bool is_resume,
284 const TestConfig *config) {
285 if (!config->expect_ocsp_response.empty()) {
286 const uint8_t *data;
287 size_t len;
288 SSL_get0_ocsp_response(ssl, &data, &len);
289 if (config->expect_ocsp_response.size() != len ||
290 OPENSSL_memcmp(config->expect_ocsp_response.data(), data, len) != 0) {
291 fprintf(stderr, "OCSP response mismatch\n");
292 return false;
293 }
294 }
295
296 if (!config->expect_signed_cert_timestamps.empty()) {
297 const uint8_t *data;
298 size_t len;
299 SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
300 if (config->expect_signed_cert_timestamps.size() != len ||
301 OPENSSL_memcmp(config->expect_signed_cert_timestamps.data(), data,
302 len) != 0) {
303 fprintf(stderr, "SCT list mismatch\n");
304 return false;
305 }
306 }
307
308 if (config->expect_verify_result) {
309 int expected_verify_result = config->verify_fail ?
310 X509_V_ERR_APPLICATION_VERIFICATION :
311 X509_V_OK;
312
313 if (SSL_get_verify_result(ssl) != expected_verify_result) {
314 fprintf(stderr, "Wrong certificate verification result\n");
315 return false;
316 }
317 }
318
319 if (!config->expect_peer_cert_file.empty()) {
320 bssl::UniquePtr<X509> expect_leaf;
321 bssl::UniquePtr<STACK_OF(X509)> expect_chain;
322 if (!LoadCertificate(&expect_leaf, &expect_chain,
323 config->expect_peer_cert_file)) {
324 return false;
325 }
326
327 // For historical reasons, clients report a chain with a leaf and servers
328 // without.
329 if (!config->is_server) {
330 if (!sk_X509_insert(expect_chain.get(), expect_leaf.get(), 0)) {
331 return false;
332 }
333 X509_up_ref(expect_leaf.get()); // sk_X509_insert takes ownership.
334 }
335
336 bssl::UniquePtr<X509> leaf(SSL_get_peer_certificate(ssl));
337 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl);
338 if (X509_cmp(leaf.get(), expect_leaf.get()) != 0) {
339 fprintf(stderr, "Received a different leaf certificate than expected.\n");
340 return false;
341 }
342
343 if (sk_X509_num(chain) != sk_X509_num(expect_chain.get())) {
344 fprintf(stderr, "Received a chain of length %zu instead of %zu.\n",
345 sk_X509_num(chain), sk_X509_num(expect_chain.get()));
346 return false;
347 }
348
349 for (size_t i = 0; i < sk_X509_num(chain); i++) {
350 if (X509_cmp(sk_X509_value(chain, i),
351 sk_X509_value(expect_chain.get(), i)) != 0) {
352 fprintf(stderr, "Chain certificate %zu did not match.\n",
353 i + 1);
354 return false;
355 }
356 }
357 }
358
359 if (!!SSL_SESSION_has_peer_sha256(SSL_get_session(ssl)) !=
360 config->expect_sha256_client_cert) {
361 fprintf(stderr,
362 "Unexpected SHA-256 client cert state: expected:%d is_resume:%d.\n",
363 config->expect_sha256_client_cert, is_resume);
364 return false;
365 }
366
367 if (config->expect_sha256_client_cert &&
368 SSL_SESSION_get0_peer_certificates(SSL_get_session(ssl)) != nullptr) {
369 fprintf(stderr, "Have both client cert and SHA-256 hash: is_resume:%d.\n",
370 is_resume);
371 return false;
372 }
373
374 const uint8_t *peer_sha256;
375 size_t peer_sha256_len;
376 SSL_SESSION_get0_peer_sha256(SSL_get_session(ssl), &peer_sha256,
377 &peer_sha256_len);
378 if (SSL_SESSION_has_peer_sha256(SSL_get_session(ssl))) {
379 if (peer_sha256_len != 32) {
380 fprintf(stderr, "Peer SHA-256 hash had length %zu instead of 32\n",
381 peer_sha256_len);
382 return false;
383 }
384 } else {
385 if (peer_sha256_len != 0) {
386 fprintf(stderr, "Unexpected peer SHA-256 hash of length %zu\n",
387 peer_sha256_len);
388 return false;
389 }
390 }
391
392 return true;
393 }
394
395 // CheckHandshakeProperties checks, immediately after |ssl| completes its
396 // initial handshake (or False Starts), whether all the properties are
397 // consistent with the test configuration and invariants.
CheckHandshakeProperties(SSL * ssl,bool is_resume,const TestConfig * config)398 static bool CheckHandshakeProperties(SSL *ssl, bool is_resume,
399 const TestConfig *config) {
400 if (!CheckAuthProperties(ssl, is_resume, config)) {
401 return false;
402 }
403
404 if (SSL_get_current_cipher(ssl) == nullptr) {
405 fprintf(stderr, "null cipher after handshake\n");
406 return false;
407 }
408
409 if (config->expect_version != 0 &&
410 SSL_version(ssl) != config->expect_version) {
411 fprintf(stderr, "want version %04x, got %04x\n", config->expect_version,
412 SSL_version(ssl));
413 return false;
414 }
415
416 bool expect_resume =
417 is_resume && (!config->expect_session_miss || SSL_in_early_data(ssl));
418 if (!!SSL_session_reused(ssl) != expect_resume) {
419 fprintf(stderr, "session unexpectedly was%s reused\n",
420 SSL_session_reused(ssl) ? "" : " not");
421 return false;
422 }
423
424 bool expect_handshake_done =
425 (is_resume || !config->false_start) && !SSL_in_early_data(ssl);
426 if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
427 fprintf(stderr, "handshake was%s completed\n",
428 GetTestState(ssl)->handshake_done ? "" : " not");
429 return false;
430 }
431
432 if (expect_handshake_done && !config->is_server) {
433 bool expect_new_session =
434 !config->expect_no_session &&
435 (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
436 // Session tickets are sent post-handshake in TLS 1.3.
437 GetProtocolVersion(ssl) < TLS1_3_VERSION;
438 if (expect_new_session != GetTestState(ssl)->got_new_session) {
439 fprintf(stderr,
440 "new session was%s cached, but we expected the opposite\n",
441 GetTestState(ssl)->got_new_session ? "" : " not");
442 return false;
443 }
444 }
445
446 if (!is_resume) {
447 if (config->expect_session_id && !GetTestState(ssl)->got_new_session) {
448 fprintf(stderr, "session was not cached on the server.\n");
449 return false;
450 }
451 if (config->expect_no_session_id && GetTestState(ssl)->got_new_session) {
452 fprintf(stderr, "session was unexpectedly cached on the server.\n");
453 return false;
454 }
455 }
456
457 // early_callback_called is updated in the handshaker, so we don't see it
458 // here.
459 if (!config->handoff && config->is_server &&
460 !GetTestState(ssl)->early_callback_called) {
461 fprintf(stderr, "early callback not called\n");
462 return false;
463 }
464
465 if (!config->expect_server_name.empty()) {
466 const char *server_name =
467 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
468 if (server_name == nullptr ||
469 server_name != config->expect_server_name) {
470 fprintf(stderr, "servername mismatch (got %s; want %s)\n",
471 server_name, config->expect_server_name.c_str());
472 return false;
473 }
474 }
475
476 if (!config->expect_next_proto.empty()) {
477 const uint8_t *next_proto;
478 unsigned next_proto_len;
479 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
480 if (next_proto_len != config->expect_next_proto.size() ||
481 OPENSSL_memcmp(next_proto, config->expect_next_proto.data(),
482 next_proto_len) != 0) {
483 fprintf(stderr, "negotiated next proto mismatch\n");
484 return false;
485 }
486 }
487
488 // On the server, the protocol selected in the ALPN callback must be echoed
489 // out of |SSL_get0_alpn_selected|. On the client, it should report what the
490 // test expected.
491 const std::string &expect_alpn =
492 config->is_server ? config->select_alpn : config->expect_alpn;
493 const uint8_t *alpn_proto;
494 unsigned alpn_proto_len;
495 SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
496 if (alpn_proto_len != expect_alpn.size() ||
497 OPENSSL_memcmp(alpn_proto, expect_alpn.data(), alpn_proto_len) != 0) {
498 fprintf(stderr, "negotiated alpn proto mismatch\n");
499 return false;
500 }
501
502 if (SSL_has_application_settings(ssl) !=
503 (config->expect_peer_application_settings ? 1 : 0)) {
504 fprintf(stderr,
505 "connection %s application settings, but expected the opposite\n",
506 SSL_has_application_settings(ssl) ? "has" : "does not have");
507 return false;
508 }
509 std::string expect_settings = config->expect_peer_application_settings
510 ? *config->expect_peer_application_settings
511 : "";
512 const uint8_t *peer_settings;
513 size_t peer_settings_len;
514 SSL_get0_peer_application_settings(ssl, &peer_settings, &peer_settings_len);
515 if (expect_settings !=
516 std::string(reinterpret_cast<const char *>(peer_settings),
517 peer_settings_len)) {
518 fprintf(stderr, "peer application settings mismatch\n");
519 return false;
520 }
521
522 if (!config->expect_quic_transport_params.empty() && expect_handshake_done) {
523 const uint8_t *peer_params;
524 size_t peer_params_len;
525 SSL_get_peer_quic_transport_params(ssl, &peer_params, &peer_params_len);
526 if (peer_params_len != config->expect_quic_transport_params.size() ||
527 OPENSSL_memcmp(peer_params,
528 config->expect_quic_transport_params.data(),
529 peer_params_len) != 0) {
530 fprintf(stderr, "QUIC transport params mismatch\n");
531 return false;
532 }
533 }
534
535 if (!config->expect_channel_id.empty()) {
536 uint8_t channel_id[64];
537 if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
538 fprintf(stderr, "no channel id negotiated\n");
539 return false;
540 }
541 if (config->expect_channel_id.size() != 64 ||
542 OPENSSL_memcmp(config->expect_channel_id.data(), channel_id, 64) !=
543 0) {
544 fprintf(stderr, "channel id mismatch\n");
545 return false;
546 }
547 }
548
549 if (config->expect_extended_master_secret && !SSL_get_extms_support(ssl)) {
550 fprintf(stderr, "No EMS for connection when expected\n");
551 return false;
552 }
553
554 if (config->expect_secure_renegotiation &&
555 !SSL_get_secure_renegotiation_support(ssl)) {
556 fprintf(stderr, "No secure renegotiation for connection when expected\n");
557 return false;
558 }
559
560 if (config->expect_no_secure_renegotiation &&
561 SSL_get_secure_renegotiation_support(ssl)) {
562 fprintf(stderr,
563 "Secure renegotiation unexpectedly negotiated for connection\n");
564 return false;
565 }
566
567 if (config->expect_peer_signature_algorithm != 0 &&
568 config->expect_peer_signature_algorithm !=
569 SSL_get_peer_signature_algorithm(ssl)) {
570 fprintf(stderr, "Peer signature algorithm was %04x, wanted %04x.\n",
571 SSL_get_peer_signature_algorithm(ssl),
572 config->expect_peer_signature_algorithm);
573 return false;
574 }
575
576 if (config->expect_curve_id != 0) {
577 uint16_t curve_id = SSL_get_curve_id(ssl);
578 if (static_cast<uint16_t>(config->expect_curve_id) != curve_id) {
579 fprintf(stderr, "curve_id was %04x, wanted %04x\n", curve_id,
580 static_cast<uint16_t>(config->expect_curve_id));
581 return false;
582 }
583 }
584
585 uint16_t cipher_id = SSL_CIPHER_get_protocol_id(SSL_get_current_cipher(ssl));
586 if (config->expect_cipher_aes != 0 &&
587 EVP_has_aes_hardware() &&
588 static_cast<uint16_t>(config->expect_cipher_aes) != cipher_id) {
589 fprintf(stderr, "Cipher ID was %04x, wanted %04x (has AES hardware)\n",
590 cipher_id, static_cast<uint16_t>(config->expect_cipher_aes));
591 return false;
592 }
593
594 if (config->expect_cipher_no_aes != 0 &&
595 !EVP_has_aes_hardware() &&
596 static_cast<uint16_t>(config->expect_cipher_no_aes) != cipher_id) {
597 fprintf(stderr, "Cipher ID was %04x, wanted %04x (no AES hardware)\n",
598 cipher_id, static_cast<uint16_t>(config->expect_cipher_no_aes));
599 return false;
600 }
601
602 if (config->expect_cipher != 0 &&
603 static_cast<uint16_t>(config->expect_cipher) != cipher_id) {
604 fprintf(stderr, "Cipher ID was %04x, wanted %04x\n", cipher_id,
605 static_cast<uint16_t>(config->expect_cipher));
606 return false;
607 }
608
609 // The early data status is only applicable after the handshake is confirmed.
610 if (!SSL_in_early_data(ssl)) {
611 if ((config->expect_accept_early_data && !SSL_early_data_accepted(ssl)) ||
612 (config->expect_reject_early_data && SSL_early_data_accepted(ssl))) {
613 fprintf(stderr,
614 "Early data was%s accepted, but we expected the opposite\n",
615 SSL_early_data_accepted(ssl) ? "" : " not");
616 return false;
617 }
618
619 const char *early_data_reason =
620 SSL_early_data_reason_string(SSL_get_early_data_reason(ssl));
621 if (!config->expect_early_data_reason.empty() &&
622 config->expect_early_data_reason != early_data_reason) {
623 fprintf(stderr, "Early data reason was \"%s\", expected \"%s\"\n",
624 early_data_reason, config->expect_early_data_reason.c_str());
625 return false;
626 }
627 }
628
629 if (!config->psk.empty()) {
630 if (SSL_get_peer_cert_chain(ssl) != nullptr) {
631 fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
632 return false;
633 }
634 } else if (!config->is_server || config->require_any_client_certificate) {
635 if (SSL_get_peer_cert_chain(ssl) == nullptr) {
636 fprintf(stderr, "Received no peer certificate but expected one.\n");
637 return false;
638 }
639 }
640
641 if (is_resume && config->expect_ticket_age_skew != 0 &&
642 SSL_get_ticket_age_skew(ssl) != config->expect_ticket_age_skew) {
643 fprintf(stderr, "Ticket age skew was %" PRId32 ", wanted %d\n",
644 SSL_get_ticket_age_skew(ssl), config->expect_ticket_age_skew);
645 return false;
646 }
647
648 if (config->expect_delegated_credential_used !=
649 !!SSL_delegated_credential_used(ssl)) {
650 fprintf(stderr,
651 "Got %s delegated credential usage, but wanted opposite. \n",
652 SSL_delegated_credential_used(ssl) ? "" : "no");
653 return false;
654 }
655
656 if ((config->expect_hrr && !SSL_used_hello_retry_request(ssl)) ||
657 (config->expect_no_hrr && SSL_used_hello_retry_request(ssl))) {
658 fprintf(stderr, "Got %sHRR, but wanted opposite.\n",
659 SSL_used_hello_retry_request(ssl) ? "" : "no ");
660 return false;
661 }
662
663 if (config->expect_ech_accept != !!SSL_ech_accepted(ssl)) {
664 fprintf(stderr, "ECH was %saccepted, but wanted opposite.\n",
665 SSL_ech_accepted(ssl) ? "" : "not ");
666 return false;
667 }
668
669 // Test that handshake hints correctly skipped the expected operations.
670 //
671 // TODO(davidben): Add support for TLS 1.2 hints and remove the version check.
672 // Also add a check for the session cache lookup.
673 if (config->handshake_hints && !config->allow_hint_mismatch &&
674 SSL_version(ssl) == TLS1_3_VERSION) {
675 const TestState *state = GetTestState(ssl);
676 if (!SSL_used_hello_retry_request(ssl) && state->used_private_key) {
677 fprintf(
678 stderr,
679 "Performed private key operation, but hint should have skipped it\n");
680 return false;
681 }
682
683 if (state->ticket_decrypt_done) {
684 fprintf(stderr,
685 "Performed ticket decryption, but hint should have skipped it\n");
686 return false;
687 }
688 }
689 return true;
690 }
691
692 static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
693 bssl::UniquePtr<SSL> *ssl_uniqueptr,
694 const TestConfig *config, bool is_resume, bool is_retry,
695 SettingsWriter *writer);
696
697 // DoConnection tests an SSL connection against the peer. On success, it returns
698 // true and sets |*out_session| to the negotiated SSL session. If the test is a
699 // resumption attempt, |is_resume| is true and |session| is the session from the
700 // previous exchange.
DoConnection(bssl::UniquePtr<SSL_SESSION> * out_session,SSL_CTX * ssl_ctx,const TestConfig * config,const TestConfig * retry_config,bool is_resume,SSL_SESSION * session,SettingsWriter * writer)701 static bool DoConnection(bssl::UniquePtr<SSL_SESSION> *out_session,
702 SSL_CTX *ssl_ctx, const TestConfig *config,
703 const TestConfig *retry_config, bool is_resume,
704 SSL_SESSION *session, SettingsWriter *writer) {
705 bssl::UniquePtr<SSL> ssl = config->NewSSL(
706 ssl_ctx, session, std::unique_ptr<TestState>(new TestState));
707 if (!ssl) {
708 return false;
709 }
710 if (config->is_server) {
711 SSL_set_accept_state(ssl.get());
712 } else {
713 SSL_set_connect_state(ssl.get());
714 }
715 if (config->handshake_hints) {
716 #if defined(HANDSHAKER_SUPPORTED)
717 GetTestState(ssl.get())->get_handshake_hints_cb =
718 [&](const SSL_CLIENT_HELLO *client_hello) {
719 return GetHandshakeHint(ssl.get(), writer, is_resume, client_hello);
720 };
721 #else
722 fprintf(stderr, "The external handshaker can only be used on Linux\n");
723 return false;
724 #endif
725 }
726
727 int sock = Connect(config->port);
728 if (sock == -1) {
729 return false;
730 }
731 SocketCloser closer(sock);
732
733 bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
734 if (!bio) {
735 return false;
736 }
737 if (config->is_dtls) {
738 bssl::UniquePtr<BIO> packeted = PacketedBioCreate(GetClock());
739 if (!packeted) {
740 return false;
741 }
742 GetTestState(ssl.get())->packeted_bio = packeted.get();
743 BIO_push(packeted.get(), bio.release());
744 bio = std::move(packeted);
745 }
746 if (config->async && !config->is_quic) {
747 // Note async tests only affect callbacks in QUIC. The IO path does not
748 // behave differently when synchronous or asynchronous our QUIC APIs.
749 bssl::UniquePtr<BIO> async_scoped =
750 config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
751 if (!async_scoped) {
752 return false;
753 }
754 BIO_push(async_scoped.get(), bio.release());
755 GetTestState(ssl.get())->async_bio = async_scoped.get();
756 bio = std::move(async_scoped);
757 }
758 if (config->is_quic) {
759 GetTestState(ssl.get())->quic_transport.reset(
760 new MockQuicTransport(std::move(bio), ssl.get()));
761 } else {
762 SSL_set_bio(ssl.get(), bio.get(), bio.get());
763 bio.release(); // SSL_set_bio takes ownership.
764 }
765
766 bool ret = DoExchange(out_session, &ssl, config, is_resume, false, writer);
767 if (!config->is_server && is_resume && config->expect_reject_early_data) {
768 // We must have failed due to an early data rejection.
769 if (ret) {
770 fprintf(stderr, "0-RTT exchange unexpected succeeded.\n");
771 return false;
772 }
773 if (SSL_get_error(ssl.get(), -1) != SSL_ERROR_EARLY_DATA_REJECTED) {
774 fprintf(stderr,
775 "SSL_get_error did not signal SSL_ERROR_EARLY_DATA_REJECTED.\n");
776 return false;
777 }
778
779 // Before reseting, early state should still be available.
780 if (!SSL_in_early_data(ssl.get()) ||
781 !CheckHandshakeProperties(ssl.get(), is_resume, config)) {
782 fprintf(stderr, "SSL_in_early_data returned false before reset.\n");
783 return false;
784 }
785
786 // Client pre- and post-0-RTT reject states are considered logically
787 // different connections with different test expections. Check that the test
788 // did not mistakenly configure reason expectations on the wrong one.
789 if (!config->expect_early_data_reason.empty()) {
790 fprintf(stderr,
791 "Test error: client reject -expect-early-data-reason flags "
792 "should be configured with -on-retry, not -on-resume.\n");
793 return false;
794 }
795
796 // Reset the connection and try again at 1-RTT.
797 SSL_reset_early_data_reject(ssl.get());
798 GetTestState(ssl.get())->cert_verified = false;
799
800 // After reseting, the socket should report it is no longer in an early data
801 // state.
802 if (SSL_in_early_data(ssl.get())) {
803 fprintf(stderr, "SSL_in_early_data returned true after reset.\n");
804 return false;
805 }
806
807 if (!SetTestConfig(ssl.get(), retry_config)) {
808 return false;
809 }
810
811 assert(!config->handoff);
812 config = retry_config;
813 ret = DoExchange(out_session, &ssl, retry_config, is_resume, true, writer);
814 }
815
816 // An ECH rejection appears as a failed connection. Note |ssl| may use a
817 // different config on ECH rejection.
818 if (config->expect_no_ech_retry_configs ||
819 !config->expect_ech_retry_configs.empty()) {
820 bssl::Span<const uint8_t> expected =
821 config->expect_no_ech_retry_configs
822 ? bssl::Span<const uint8_t>()
823 : bssl::MakeConstSpan(reinterpret_cast<const uint8_t *>(
824 config->expect_ech_retry_configs.data()),
825 config->expect_ech_retry_configs.size());
826 if (ret) {
827 fprintf(stderr, "Expected ECH rejection, but connection succeeded.\n");
828 return false;
829 }
830 uint32_t err = ERR_peek_error();
831 if (SSL_get_error(ssl.get(), -1) != SSL_ERROR_SSL ||
832 ERR_GET_LIB(err) != ERR_LIB_SSL ||
833 ERR_GET_REASON(err) != SSL_R_ECH_REJECTED) {
834 fprintf(stderr, "Expected ECH rejection, but connection succeeded.\n");
835 return false;
836 }
837 const uint8_t *retry_configs;
838 size_t retry_configs_len;
839 SSL_get0_ech_retry_configs(ssl.get(), &retry_configs, &retry_configs_len);
840 if (bssl::MakeConstSpan(retry_configs, retry_configs_len) != expected) {
841 fprintf(stderr, "ECH retry configs did not match expectations.\n");
842 // Clear the error queue. Otherwise |SSL_R_ECH_REJECTED| will be printed
843 // to stderr and the test framework will think the test had the expected
844 // expectations.
845 ERR_clear_error();
846 return false;
847 }
848 }
849
850 if (!ret) {
851 // Print the |SSL_get_error| code. Otherwise, some failures are silent and
852 // hard to debug.
853 int ssl_err = SSL_get_error(ssl.get(), -1);
854 if (ssl_err != SSL_ERROR_NONE) {
855 fprintf(stderr, "SSL error: %s\n", SSL_error_description(ssl_err));
856 }
857 return false;
858 }
859
860 if (!GetTestState(ssl.get())->msg_callback_ok) {
861 return false;
862 }
863
864 if (!config->expect_msg_callback.empty() &&
865 GetTestState(ssl.get())->msg_callback_text !=
866 config->expect_msg_callback) {
867 fprintf(stderr, "Bad message callback trace. Wanted:\n%s\nGot:\n%s\n",
868 config->expect_msg_callback.c_str(),
869 GetTestState(ssl.get())->msg_callback_text.c_str());
870 return false;
871 }
872
873 return true;
874 }
875
DoExchange(bssl::UniquePtr<SSL_SESSION> * out_session,bssl::UniquePtr<SSL> * ssl_uniqueptr,const TestConfig * config,bool is_resume,bool is_retry,SettingsWriter * writer)876 static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
877 bssl::UniquePtr<SSL> *ssl_uniqueptr,
878 const TestConfig *config, bool is_resume, bool is_retry,
879 SettingsWriter *writer) {
880 int ret;
881 SSL *ssl = ssl_uniqueptr->get();
882 SSL_CTX *session_ctx = SSL_get_SSL_CTX(ssl);
883 TestState *test_state = GetTestState(ssl);
884
885 if (!config->implicit_handshake) {
886 if (config->handoff) {
887 #if defined(HANDSHAKER_SUPPORTED)
888 if (!DoSplitHandshake(ssl_uniqueptr, writer, is_resume)) {
889 return false;
890 }
891 ssl = ssl_uniqueptr->get();
892 test_state = GetTestState(ssl);
893 #else
894 fprintf(stderr, "The external handshaker can only be used on Linux\n");
895 return false;
896 #endif
897 }
898
899 do {
900 ret = CheckIdempotentError("SSL_do_handshake", ssl, [&]() -> int {
901 return SSL_do_handshake(ssl);
902 });
903 } while (RetryAsync(ssl, ret));
904
905 if (config->forbid_renegotiation_after_handshake) {
906 SSL_set_renegotiate_mode(ssl, ssl_renegotiate_never);
907 }
908
909 if (ret != 1 || !CheckHandshakeProperties(ssl, is_resume, config)) {
910 return false;
911 }
912
913 CopySessions(session_ctx, SSL_get_SSL_CTX(ssl));
914
915 if (is_resume && !is_retry && !config->is_server &&
916 config->expect_no_offer_early_data && SSL_in_early_data(ssl)) {
917 fprintf(stderr, "Client unexpectedly offered early data.\n");
918 return false;
919 }
920
921 if (config->handshake_twice) {
922 do {
923 ret = SSL_do_handshake(ssl);
924 } while (RetryAsync(ssl, ret));
925 if (ret != 1) {
926 return false;
927 }
928 }
929
930 // Skip the |config->async| logic as this should be a no-op.
931 if (config->no_op_extra_handshake &&
932 SSL_do_handshake(ssl) != 1) {
933 fprintf(stderr, "Extra SSL_do_handshake was not a no-op.\n");
934 return false;
935 }
936
937 if (config->early_write_after_message != 0) {
938 if (!SSL_in_early_data(ssl) || config->is_server) {
939 fprintf(stderr,
940 "-early-write-after-message only works for 0-RTT connections "
941 "on servers.\n");
942 return false;
943 }
944 if (!config->shim_writes_first || !config->async) {
945 fprintf(stderr,
946 "-early-write-after-message requires -shim-writes-first and "
947 "-async.\n");
948 return false;
949 }
950 // Run the handshake until the specified message. Note that, if a
951 // handshake record contains multiple messages, |SSL_do_handshake| usually
952 // processes both atomically. The test must ensure there is a record
953 // boundary after the desired message. Checking |last_message_received|
954 // confirms this.
955 do {
956 ret = SSL_do_handshake(ssl);
957 } while (test_state->last_message_received !=
958 config->early_write_after_message &&
959 RetryAsync(ssl, ret));
960 if (ret == 1) {
961 fprintf(stderr, "Handshake unexpectedly succeeded.\n");
962 return false;
963 }
964 if (test_state->last_message_received !=
965 config->early_write_after_message) {
966 // The handshake failed before we saw the target message. The generic
967 // error-handling logic in the caller will print the error.
968 return false;
969 }
970 }
971
972 // Reset the state to assert later that the callback isn't called in
973 // renegotations.
974 test_state->got_new_session = false;
975 }
976
977 if (config->export_keying_material > 0) {
978 std::vector<uint8_t> result(
979 static_cast<size_t>(config->export_keying_material));
980 if (!SSL_export_keying_material(
981 ssl, result.data(), result.size(), config->export_label.data(),
982 config->export_label.size(),
983 reinterpret_cast<const uint8_t *>(config->export_context.data()),
984 config->export_context.size(), config->use_export_context)) {
985 fprintf(stderr, "failed to export keying material\n");
986 return false;
987 }
988 if (WriteAll(ssl, result.data(), result.size()) < 0) {
989 return false;
990 }
991 }
992
993 if (config->export_traffic_secrets) {
994 bssl::Span<const uint8_t> read_secret, write_secret;
995 if (!SSL_get_traffic_secrets(ssl, &read_secret, &write_secret)) {
996 fprintf(stderr, "failed to export traffic secrets\n");
997 return false;
998 }
999
1000 assert(read_secret.size() <= 0xffff);
1001 assert(write_secret.size() == read_secret.size());
1002 const uint16_t secret_len = read_secret.size();
1003 if (WriteAll(ssl, &secret_len, sizeof(secret_len)) < 0 ||
1004 WriteAll(ssl, read_secret.data(), read_secret.size()) < 0 ||
1005 WriteAll(ssl, write_secret.data(), write_secret.size()) < 0) {
1006 return false;
1007 }
1008 }
1009
1010 if (config->tls_unique) {
1011 uint8_t tls_unique[16];
1012 size_t tls_unique_len;
1013 if (!SSL_get_tls_unique(ssl, tls_unique, &tls_unique_len,
1014 sizeof(tls_unique))) {
1015 fprintf(stderr, "failed to get tls-unique\n");
1016 return false;
1017 }
1018
1019 if (tls_unique_len != 12) {
1020 fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
1021 static_cast<unsigned>(tls_unique_len));
1022 return false;
1023 }
1024
1025 if (WriteAll(ssl, tls_unique, tls_unique_len) < 0) {
1026 return false;
1027 }
1028 }
1029
1030 if (config->send_alert) {
1031 if (DoSendFatalAlert(ssl, SSL_AD_DECOMPRESSION_FAILURE) < 0) {
1032 return false;
1033 }
1034 return true;
1035 }
1036
1037 if (config->write_different_record_sizes) {
1038 if (config->is_dtls) {
1039 fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
1040 return false;
1041 }
1042 // This mode writes a number of different record sizes in an attempt to
1043 // trip up the CBC record splitting code.
1044 static const size_t kBufLen = 32769;
1045 std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1046 OPENSSL_memset(buf.get(), 0x42, kBufLen);
1047 static const size_t kRecordSizes[] = {
1048 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
1049 for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
1050 const size_t len = kRecordSizes[i];
1051 if (len > kBufLen) {
1052 fprintf(stderr, "Bad kRecordSizes value.\n");
1053 return false;
1054 }
1055 if (WriteAll(ssl, buf.get(), len) < 0) {
1056 return false;
1057 }
1058 }
1059 } else {
1060 static const char kInitialWrite[] = "hello";
1061 bool pending_initial_write = false;
1062 if (config->read_with_unfinished_write) {
1063 if (!config->async) {
1064 fprintf(stderr, "-read-with-unfinished-write requires -async.\n");
1065 return false;
1066 }
1067 if (config->is_quic) {
1068 fprintf(stderr,
1069 "-read-with-unfinished-write is incompatible with QUIC.\n");
1070 return false;
1071 }
1072
1073 // Let only one byte of the record through.
1074 AsyncBioAllowWrite(test_state->async_bio, 1);
1075 int write_ret =
1076 SSL_write(ssl, kInitialWrite, strlen(kInitialWrite));
1077 if (SSL_get_error(ssl, write_ret) != SSL_ERROR_WANT_WRITE) {
1078 fprintf(stderr, "Failed to leave unfinished write.\n");
1079 return false;
1080 }
1081 pending_initial_write = true;
1082 } else if (config->shim_writes_first) {
1083 if (WriteAll(ssl, kInitialWrite, strlen(kInitialWrite)) < 0) {
1084 return false;
1085 }
1086 }
1087 if (!config->shim_shuts_down) {
1088 for (;;) {
1089 // Read only 512 bytes at a time in TLS to ensure records may be
1090 // returned in multiple reads.
1091 size_t read_size = config->is_dtls ? 16384 : 512;
1092 if (config->read_size > 0) {
1093 read_size = config->read_size;
1094 }
1095 std::unique_ptr<uint8_t[]> buf(new uint8_t[read_size]);
1096
1097 int n = DoRead(ssl, buf.get(), read_size);
1098 int err = SSL_get_error(ssl, n);
1099 if (err == SSL_ERROR_ZERO_RETURN ||
1100 (n == 0 && err == SSL_ERROR_SYSCALL)) {
1101 if (n != 0) {
1102 fprintf(stderr, "Invalid SSL_get_error output\n");
1103 return false;
1104 }
1105 // Stop on either clean or unclean shutdown.
1106 break;
1107 } else if (err != SSL_ERROR_NONE) {
1108 if (n > 0) {
1109 fprintf(stderr, "Invalid SSL_get_error output\n");
1110 return false;
1111 }
1112 return false;
1113 }
1114 // Successfully read data.
1115 if (n <= 0) {
1116 fprintf(stderr, "Invalid SSL_get_error output\n");
1117 return false;
1118 }
1119
1120 if (!config->is_server && is_resume && !is_retry &&
1121 config->expect_reject_early_data) {
1122 fprintf(stderr,
1123 "Unexpectedly received data instead of 0-RTT reject.\n");
1124 return false;
1125 }
1126
1127 // After a successful read, with or without False Start, the handshake
1128 // must be complete unless we are doing early data.
1129 if (!test_state->handshake_done &&
1130 !SSL_early_data_accepted(ssl)) {
1131 fprintf(stderr, "handshake was not completed after SSL_read\n");
1132 return false;
1133 }
1134
1135 // Clear the initial write, if unfinished.
1136 if (pending_initial_write) {
1137 if (WriteAll(ssl, kInitialWrite, strlen(kInitialWrite)) < 0) {
1138 return false;
1139 }
1140 pending_initial_write = false;
1141 }
1142
1143 if (config->key_update &&
1144 !SSL_key_update(ssl, SSL_KEY_UPDATE_NOT_REQUESTED)) {
1145 fprintf(stderr, "SSL_key_update failed.\n");
1146 return false;
1147 }
1148
1149 for (int i = 0; i < n; i++) {
1150 buf[i] ^= 0xff;
1151 }
1152 if (WriteAll(ssl, buf.get(), n) < 0) {
1153 return false;
1154 }
1155 }
1156 }
1157 }
1158
1159 if (!config->is_server && !config->false_start &&
1160 !config->implicit_handshake &&
1161 // Session tickets are sent post-handshake in TLS 1.3.
1162 GetProtocolVersion(ssl) < TLS1_3_VERSION &&
1163 test_state->got_new_session) {
1164 fprintf(stderr, "new session was established after the handshake\n");
1165 return false;
1166 }
1167
1168 if (GetProtocolVersion(ssl) >= TLS1_3_VERSION && !config->is_server) {
1169 bool expect_new_session =
1170 !config->expect_no_session && !config->shim_shuts_down;
1171 if (expect_new_session != test_state->got_new_session) {
1172 fprintf(stderr,
1173 "new session was%s cached, but we expected the opposite\n",
1174 test_state->got_new_session ? "" : " not");
1175 return false;
1176 }
1177
1178 if (expect_new_session) {
1179 bool got_early_data =
1180 test_state->new_session->ticket_max_early_data != 0;
1181 if (config->expect_ticket_supports_early_data != got_early_data) {
1182 fprintf(stderr,
1183 "new session did%s support early data, but we expected the "
1184 "opposite\n",
1185 got_early_data ? "" : " not");
1186 return false;
1187 }
1188 }
1189 }
1190
1191 if (out_session) {
1192 *out_session = std::move(test_state->new_session);
1193 }
1194
1195 ret = DoShutdown(ssl);
1196
1197 if (config->shim_shuts_down && config->check_close_notify) {
1198 // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1199 // it returns zero when our close_notify is sent, then one when the peer's
1200 // is received.
1201 if (ret != 0) {
1202 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1203 return false;
1204 }
1205 ret = DoShutdown(ssl);
1206 }
1207
1208 if (ret != 1) {
1209 fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1210 return false;
1211 }
1212
1213 if (SSL_total_renegotiations(ssl) > 0) {
1214 if (!SSL_get_session(ssl)->not_resumable) {
1215 fprintf(stderr,
1216 "Renegotiations should never produce resumable sessions.\n");
1217 return false;
1218 }
1219
1220 if (SSL_session_reused(ssl)) {
1221 fprintf(stderr, "Renegotiations should never resume sessions.\n");
1222 return false;
1223 }
1224
1225 // Re-check authentication properties after a renegotiation. The reported
1226 // values should remain unchanged even if the server sent different SCT
1227 // lists.
1228 if (!CheckAuthProperties(ssl, is_resume, config)) {
1229 return false;
1230 }
1231 }
1232
1233 if (SSL_total_renegotiations(ssl) != config->expect_total_renegotiations) {
1234 fprintf(stderr, "Expected %d renegotiations, got %d\n",
1235 config->expect_total_renegotiations, SSL_total_renegotiations(ssl));
1236 return false;
1237 }
1238
1239 if (config->renegotiate_explicit &&
1240 SSL_total_renegotiations(ssl) !=
1241 test_state->explicit_renegotiates) {
1242 fprintf(stderr, "Performed %d renegotiations, but triggered %d of them\n",
1243 SSL_total_renegotiations(ssl),
1244 test_state->explicit_renegotiates);
1245 return false;
1246 }
1247
1248 return true;
1249 }
1250
1251 class StderrDelimiter {
1252 public:
~StderrDelimiter()1253 ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
1254 };
1255
main(int argc,char ** argv)1256 int main(int argc, char **argv) {
1257 // To distinguish ASan's output from ours, add a trailing message to stderr.
1258 // Anything following this line will be considered an error.
1259 StderrDelimiter delimiter;
1260
1261 #if defined(OPENSSL_WINDOWS)
1262 // Initialize Winsock.
1263 WORD wsa_version = MAKEWORD(2, 2);
1264 WSADATA wsa_data;
1265 int wsa_err = WSAStartup(wsa_version, &wsa_data);
1266 if (wsa_err != 0) {
1267 fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1268 return 1;
1269 }
1270 if (wsa_data.wVersion != wsa_version) {
1271 fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1272 return 1;
1273 }
1274 #else
1275 signal(SIGPIPE, SIG_IGN);
1276 #endif
1277
1278 CRYPTO_library_init();
1279
1280 TestConfig initial_config, resume_config, retry_config;
1281 if (!ParseConfig(argc - 1, argv + 1, /*is_shim=*/true, &initial_config,
1282 &resume_config, &retry_config)) {
1283 return Usage(argv[0]);
1284 }
1285
1286 if (initial_config.is_handshaker_supported) {
1287 #if defined(HANDSHAKER_SUPPORTED)
1288 printf("Yes\n");
1289 #else
1290 printf("No\n");
1291 #endif
1292 return 0;
1293 }
1294
1295 if (initial_config.wait_for_debugger) {
1296 #if defined(OPENSSL_WINDOWS)
1297 fprintf(stderr, "-wait-for-debugger is not supported on Windows.\n");
1298 return 1;
1299 #else
1300 // The debugger will resume the process.
1301 raise(SIGSTOP);
1302 #endif
1303 }
1304
1305 bssl::UniquePtr<SSL_CTX> ssl_ctx;
1306
1307 bssl::UniquePtr<SSL_SESSION> session;
1308 for (int i = 0; i < initial_config.resume_count + 1; i++) {
1309 bool is_resume = i > 0;
1310 TestConfig *config = is_resume ? &resume_config : &initial_config;
1311 ssl_ctx = config->SetupCtx(ssl_ctx.get());
1312 if (!ssl_ctx) {
1313 ERR_print_errors_fp(stderr);
1314 return 1;
1315 }
1316
1317 if (is_resume && !initial_config.is_server && !session) {
1318 fprintf(stderr, "No session to offer.\n");
1319 return 1;
1320 }
1321
1322 bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
1323 SettingsWriter writer;
1324 if (!writer.Init(i, config, offer_session.get())) {
1325 fprintf(stderr, "Error writing settings.\n");
1326 return 1;
1327 }
1328 bool ok = DoConnection(&session, ssl_ctx.get(), config, &retry_config,
1329 is_resume, offer_session.get(), &writer);
1330 if (!writer.Commit()) {
1331 fprintf(stderr, "Error writing settings.\n");
1332 return 1;
1333 }
1334 if (!ok) {
1335 fprintf(stderr, "Connection %d failed.\n", i + 1);
1336 ERR_print_errors_fp(stderr);
1337 return 1;
1338 }
1339
1340 if (config->resumption_delay != 0) {
1341 AdvanceClock(config->resumption_delay);
1342 }
1343 }
1344
1345 return 0;
1346 }
1347