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