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