• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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   if (!CheckAuthProperties(ssl, is_resume, config)) {
452     return false;
453   }
454 
455   if (SSL_get_current_cipher(ssl) == nullptr) {
456     fprintf(stderr, "null cipher after handshake\n");
457     return false;
458   }
459 
460   if (config->expect_version != 0 &&
461       SSL_version(ssl) != int{config->expect_version}) {
462     fprintf(stderr, "want version %04x, got %04x\n", config->expect_version,
463             static_cast<uint16_t>(SSL_version(ssl)));
464     return false;
465   }
466 
467   bool expect_resume =
468       is_resume && (!config->expect_session_miss || SSL_in_early_data(ssl));
469   if (!!SSL_session_reused(ssl) != expect_resume) {
470     fprintf(stderr, "session unexpectedly was%s reused\n",
471             SSL_session_reused(ssl) ? "" : " not");
472     return false;
473   }
474 
475   bool expect_handshake_done =
476       (is_resume || !config->false_start) && !SSL_in_early_data(ssl);
477   if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
478     fprintf(stderr, "handshake was%s completed\n",
479             GetTestState(ssl)->handshake_done ? "" : " not");
480     return false;
481   }
482 
483   if (expect_handshake_done && !config->is_server) {
484     bool expect_new_session =
485         !config->expect_no_session &&
486         (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
487         // Session tickets are sent post-handshake in TLS 1.3.
488         GetProtocolVersion(ssl) < TLS1_3_VERSION;
489     if (expect_new_session != GetTestState(ssl)->got_new_session) {
490       fprintf(stderr,
491               "new session was%s cached, but we expected the opposite\n",
492               GetTestState(ssl)->got_new_session ? "" : " not");
493       return false;
494     }
495   }
496 
497   if (!is_resume) {
498     if (config->expect_session_id && !GetTestState(ssl)->got_new_session) {
499       fprintf(stderr, "session was not cached on the server.\n");
500       return false;
501     }
502     if (config->expect_no_session_id && GetTestState(ssl)->got_new_session) {
503       fprintf(stderr, "session was unexpectedly cached on the server.\n");
504       return false;
505     }
506   }
507 
508   // early_callback_called is updated in the handshaker, so we don't see it
509   // here.
510   if (!config->handoff && config->is_server &&
511       !GetTestState(ssl)->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()) {
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_delegated_credential_used !=
698       !!SSL_delegated_credential_used(ssl)) {
699     fprintf(stderr,
700             "Got %s delegated credential usage, but wanted opposite. \n",
701             SSL_delegated_credential_used(ssl) ? "" : "no");
702     return false;
703   }
704 
705   if ((config->expect_hrr && !SSL_used_hello_retry_request(ssl)) ||
706       (config->expect_no_hrr && SSL_used_hello_retry_request(ssl))) {
707     fprintf(stderr, "Got %sHRR, but wanted opposite.\n",
708             SSL_used_hello_retry_request(ssl) ? "" : "no ");
709     return false;
710   }
711 
712   if (config->expect_ech_accept != !!SSL_ech_accepted(ssl)) {
713     fprintf(stderr, "ECH was %saccepted, but wanted opposite.\n",
714             SSL_ech_accepted(ssl) ? "" : "not ");
715     return false;
716   }
717 
718   if (config->expect_key_usage_invalid != !!SSL_was_key_usage_invalid(ssl)) {
719     fprintf(stderr, "X.509 key usage was %svalid, but wanted opposite.\n",
720             SSL_was_key_usage_invalid(ssl) ? "in" : "");
721     return false;
722   }
723 
724   // Check all the selected parameters are covered by the string APIs.
725   if (!CheckListContains("version", SSL_get_all_version_names,
726                          SSL_get_version(ssl)) ||
727       !CheckListContains(
728           "cipher", SSL_get_all_standard_cipher_names,
729           SSL_CIPHER_standard_name(SSL_get_current_cipher(ssl))) ||
730       !CheckListContains("OpenSSL cipher name", SSL_get_all_cipher_names,
731                          SSL_CIPHER_get_name(SSL_get_current_cipher(ssl))) ||
732       (SSL_get_group_id(ssl) != 0 &&
733        !CheckListContains("group", SSL_get_all_group_names,
734                           SSL_get_group_name(SSL_get_group_id(ssl)))) ||
735       (SSL_get_peer_signature_algorithm(ssl) != 0 &&
736        !CheckListContains(
737            "sigalg", SSL_get_all_signature_algorithm_names,
738            SSL_get_signature_algorithm_name(
739                SSL_get_peer_signature_algorithm(ssl), /*include_curve=*/0))) ||
740       (SSL_get_peer_signature_algorithm(ssl) != 0 &&
741        !CheckListContains(
742            "sigalg with curve", SSL_get_all_signature_algorithm_names,
743            SSL_get_signature_algorithm_name(
744                SSL_get_peer_signature_algorithm(ssl), /*include_curve=*/1)))) {
745     return false;
746   }
747 
748   // Test that handshake hints correctly skipped the expected operations.
749   if (config->handshake_hints && !config->allow_hint_mismatch) {
750     const TestState *state = GetTestState(ssl);
751     // If the private key operation is performed in the first roundtrip, a hint
752     // match should have skipped it. This is ECDHE-based cipher suites in TLS
753     // 1.2 and non-HRR handshakes in TLS 1.3.
754     bool private_key_allowed;
755     if (SSL_version(ssl) == TLS1_3_VERSION) {
756       private_key_allowed = SSL_used_hello_retry_request(ssl);
757     } else {
758       private_key_allowed =
759           SSL_CIPHER_get_kx_nid(SSL_get_current_cipher(ssl)) == NID_kx_rsa;
760     }
761     if (!private_key_allowed && state->used_private_key) {
762       fprintf(
763           stderr,
764           "Performed private key operation, but hint should have skipped it\n");
765       return false;
766     }
767 
768     if (state->ticket_decrypt_done) {
769       fprintf(stderr,
770               "Performed ticket decryption, but hint should have skipped it\n");
771       return false;
772     }
773 
774     // TODO(davidben): Decide what we want to do with TLS 1.2 stateful
775     // resumption.
776   }
777   return true;
778 }
779 
780 static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
781                        bssl::UniquePtr<SSL> *ssl_uniqueptr,
782                        const TestConfig *config, bool is_resume, bool is_retry,
783                        SettingsWriter *writer);
784 
785 // DoConnection tests an SSL connection against the peer. On success, it returns
786 // true and sets |*out_session| to the negotiated SSL session. If the test is a
787 // resumption attempt, |is_resume| is true and |session| is the session from the
788 // 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)789 static bool DoConnection(bssl::UniquePtr<SSL_SESSION> *out_session,
790                          SSL_CTX *ssl_ctx, const TestConfig *config,
791                          const TestConfig *retry_config, bool is_resume,
792                          SSL_SESSION *session, SettingsWriter *writer) {
793   bssl::UniquePtr<SSL> ssl =
794       config->NewSSL(ssl_ctx, session, std::make_unique<TestState>());
795   if (!ssl) {
796     return false;
797   }
798   if (config->is_server) {
799     SSL_set_accept_state(ssl.get());
800   } else {
801     SSL_set_connect_state(ssl.get());
802   }
803   if (config->handshake_hints) {
804 #if defined(HANDSHAKER_SUPPORTED)
805     GetTestState(ssl.get())->get_handshake_hints_cb =
806         [&](const SSL_CLIENT_HELLO *client_hello) {
807           return GetHandshakeHint(ssl.get(), writer, is_resume, client_hello);
808         };
809 #else
810     fprintf(stderr, "The external handshaker can only be used on Linux\n");
811     return false;
812 #endif
813   }
814 
815   OwnedSocket sock = Connect(config);
816   if (!sock.is_valid()) {
817     return false;
818   }
819 
820   // Half-close and drain the socket before releasing it. This seems to be
821   // necessary for graceful shutdown on Windows. It will also avoid write
822   // failures in the test runner.
823   sock.set_drain_on_close(true);
824 
825   // Windows uses |SOCKET| for socket types, but OpenSSL's API requires casting
826   // them to |int|.
827   bssl::UniquePtr<BIO> bio(
828       BIO_new_socket(static_cast<int>(sock.get()), BIO_NOCLOSE));
829   if (!bio) {
830     return false;
831   }
832 
833   uint8_t shim_id[8];
834   CRYPTO_store_u64_le(shim_id, config->shim_id);
835   if (!BIO_write_all(bio.get(), shim_id, sizeof(shim_id))) {
836     return false;
837   }
838 
839   if (config->is_dtls) {
840     bssl::UniquePtr<BIO> packeted = PacketedBioCreate(GetClock());
841     if (!packeted) {
842       return false;
843     }
844     GetTestState(ssl.get())->packeted_bio = packeted.get();
845     BIO_push(packeted.get(), bio.release());
846     bio = std::move(packeted);
847   }
848   if (config->async && !config->is_quic) {
849     // Note async tests only affect callbacks in QUIC. The IO path does not
850     // behave differently when synchronous or asynchronous our QUIC APIs.
851     bssl::UniquePtr<BIO> async_scoped =
852         config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
853     if (!async_scoped) {
854       return false;
855     }
856     BIO_push(async_scoped.get(), bio.release());
857     GetTestState(ssl.get())->async_bio = async_scoped.get();
858     bio = std::move(async_scoped);
859   }
860   if (config->is_quic) {
861     GetTestState(ssl.get())->quic_transport =
862         std::make_unique<MockQuicTransport>(std::move(bio), ssl.get());
863   } else {
864     SSL_set_bio(ssl.get(), bio.get(), bio.get());
865     bio.release();  // SSL_set_bio takes ownership.
866   }
867 
868   bool ret = DoExchange(out_session, &ssl, config, is_resume, false, writer);
869   if (!config->is_server && is_resume && config->expect_reject_early_data) {
870     // We must have failed due to an early data rejection.
871     if (ret) {
872       fprintf(stderr, "0-RTT exchange unexpected succeeded.\n");
873       return false;
874     }
875     if (SSL_get_error(ssl.get(), -1) != SSL_ERROR_EARLY_DATA_REJECTED) {
876       fprintf(stderr,
877               "SSL_get_error did not signal SSL_ERROR_EARLY_DATA_REJECTED.\n");
878       return false;
879     }
880 
881     // Before reseting, early state should still be available.
882     if (!SSL_in_early_data(ssl.get()) ||
883         !CheckHandshakeProperties(ssl.get(), is_resume, config)) {
884       fprintf(stderr, "SSL_in_early_data returned false before reset.\n");
885       return false;
886     }
887 
888     // Client pre- and post-0-RTT reject states are considered logically
889     // different connections with different test expections. Check that the test
890     // did not mistakenly configure reason expectations on the wrong one.
891     if (!config->expect_early_data_reason.empty()) {
892       fprintf(stderr,
893               "Test error: client reject -expect-early-data-reason flags "
894               "should be configured with -on-retry, not -on-resume.\n");
895       return false;
896     }
897 
898     // Reset the connection and try again at 1-RTT.
899     SSL_reset_early_data_reject(ssl.get());
900     GetTestState(ssl.get())->cert_verified = false;
901 
902     // After reseting, the socket should report it is no longer in an early data
903     // state.
904     if (SSL_in_early_data(ssl.get())) {
905       fprintf(stderr, "SSL_in_early_data returned true after reset.\n");
906       return false;
907     }
908 
909     if (!SetTestConfig(ssl.get(), retry_config)) {
910       return false;
911     }
912 
913     assert(!config->handoff);
914     config = retry_config;
915     ret = DoExchange(out_session, &ssl, retry_config, is_resume, true, writer);
916   }
917 
918   // An ECH rejection appears as a failed connection. Note |ssl| may use a
919   // different config on ECH rejection.
920   if (config->expect_no_ech_retry_configs ||
921       !config->expect_ech_retry_configs.empty()) {
922     bssl::Span<const uint8_t> expected =
923         config->expect_no_ech_retry_configs
924             ? bssl::Span<const uint8_t>()
925             : bssl::MakeConstSpan(reinterpret_cast<const uint8_t *>(
926                                       config->expect_ech_retry_configs.data()),
927                                   config->expect_ech_retry_configs.size());
928     if (ret) {
929       fprintf(stderr, "Expected ECH rejection, but connection succeeded.\n");
930       return false;
931     }
932     uint32_t err = ERR_peek_error();
933     if (SSL_get_error(ssl.get(), -1) != SSL_ERROR_SSL ||
934         ERR_GET_LIB(err) != ERR_LIB_SSL ||
935         ERR_GET_REASON(err) != SSL_R_ECH_REJECTED) {
936       fprintf(stderr, "Expected ECH rejection, but connection succeeded.\n");
937       return false;
938     }
939     const uint8_t *retry_configs;
940     size_t retry_configs_len;
941     SSL_get0_ech_retry_configs(ssl.get(), &retry_configs, &retry_configs_len);
942     if (bssl::MakeConstSpan(retry_configs, retry_configs_len) != expected) {
943       fprintf(stderr, "ECH retry configs did not match expectations.\n");
944       // Clear the error queue. Otherwise |SSL_R_ECH_REJECTED| will be printed
945       // to stderr and the test framework will think the test had the expected
946       // expectations.
947       ERR_clear_error();
948       return false;
949     }
950   }
951 
952   if (!ret) {
953     // Print the |SSL_get_error| code. Otherwise, some failures are silent and
954     // hard to debug.
955     int ssl_err = SSL_get_error(ssl.get(), -1);
956     if (ssl_err != SSL_ERROR_NONE) {
957       fprintf(stderr, "SSL error: %s\n", SSL_error_description(ssl_err));
958     }
959     return false;
960   }
961 
962   if (!GetTestState(ssl.get())->msg_callback_ok) {
963     return false;
964   }
965 
966   if (!config->expect_msg_callback.empty() &&
967       GetTestState(ssl.get())->msg_callback_text !=
968           config->expect_msg_callback) {
969     fprintf(stderr, "Bad message callback trace. Wanted:\n%s\nGot:\n%s\n",
970             config->expect_msg_callback.c_str(),
971             GetTestState(ssl.get())->msg_callback_text.c_str());
972     return false;
973   }
974 
975   return true;
976 }
977 
DoExchange(bssl::UniquePtr<SSL_SESSION> * out_session,bssl::UniquePtr<SSL> * ssl_uniqueptr,const TestConfig * config,bool is_resume,bool is_retry,SettingsWriter * writer)978 static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
979                        bssl::UniquePtr<SSL> *ssl_uniqueptr,
980                        const TestConfig *config, bool is_resume, bool is_retry,
981                        SettingsWriter *writer) {
982   int ret;
983   SSL *ssl = ssl_uniqueptr->get();
984   SSL_CTX *session_ctx = SSL_get_SSL_CTX(ssl);
985   TestState *test_state = GetTestState(ssl);
986 
987   if (!config->implicit_handshake) {
988     if (config->handoff) {
989 #if defined(HANDSHAKER_SUPPORTED)
990       if (!DoSplitHandshake(ssl_uniqueptr, writer, is_resume)) {
991         return false;
992       }
993       ssl = ssl_uniqueptr->get();
994       test_state = GetTestState(ssl);
995 #else
996       fprintf(stderr, "The external handshaker can only be used on Linux\n");
997       return false;
998 #endif
999     }
1000 
1001     do {
1002       ret = CheckIdempotentError("SSL_do_handshake", ssl, [&]() -> int {
1003         return SSL_do_handshake(ssl);
1004       });
1005     } while (RetryAsync(ssl, ret));
1006 
1007     if (config->forbid_renegotiation_after_handshake) {
1008       SSL_set_renegotiate_mode(ssl, ssl_renegotiate_never);
1009     }
1010 
1011     if (ret != 1 || !CheckHandshakeProperties(ssl, is_resume, config)) {
1012       return false;
1013     }
1014 
1015     CopySessions(session_ctx, SSL_get_SSL_CTX(ssl));
1016 
1017     if (is_resume && !is_retry && !config->is_server &&
1018         config->expect_no_offer_early_data && SSL_in_early_data(ssl)) {
1019       fprintf(stderr, "Client unexpectedly offered early data.\n");
1020       return false;
1021     }
1022 
1023     if (config->handshake_twice) {
1024       do {
1025         ret = SSL_do_handshake(ssl);
1026       } while (RetryAsync(ssl, ret));
1027       if (ret != 1) {
1028         return false;
1029       }
1030     }
1031 
1032     // Skip the |config->async| logic as this should be a no-op.
1033     if (config->no_op_extra_handshake &&
1034         SSL_do_handshake(ssl) != 1) {
1035       fprintf(stderr, "Extra SSL_do_handshake was not a no-op.\n");
1036       return false;
1037     }
1038 
1039     if (config->early_write_after_message != 0) {
1040       if (!SSL_in_early_data(ssl) || config->is_server) {
1041         fprintf(stderr,
1042                 "-early-write-after-message only works for 0-RTT connections "
1043                 "on servers.\n");
1044         return false;
1045       }
1046       if (!config->shim_writes_first || !config->async) {
1047         fprintf(stderr,
1048                 "-early-write-after-message requires -shim-writes-first and "
1049                 "-async.\n");
1050         return false;
1051       }
1052       // Run the handshake until the specified message. Note that, if a
1053       // handshake record contains multiple messages, |SSL_do_handshake| usually
1054       // processes both atomically. The test must ensure there is a record
1055       // boundary after the desired message. Checking |last_message_received|
1056       // confirms this.
1057       do {
1058         ret = SSL_do_handshake(ssl);
1059       } while (test_state->last_message_received !=
1060                    config->early_write_after_message &&
1061                RetryAsync(ssl, ret));
1062       if (ret == 1) {
1063         fprintf(stderr, "Handshake unexpectedly succeeded.\n");
1064         return false;
1065       }
1066       if (test_state->last_message_received !=
1067           config->early_write_after_message) {
1068         // The handshake failed before we saw the target message. The generic
1069         // error-handling logic in the caller will print the error.
1070         return false;
1071       }
1072     }
1073 
1074     // Reset the state to assert later that the callback isn't called in
1075     // renegotations.
1076     test_state->got_new_session = false;
1077   }
1078 
1079   if (config->export_keying_material > 0) {
1080     std::vector<uint8_t> result(
1081         static_cast<size_t>(config->export_keying_material));
1082     if (!SSL_export_keying_material(
1083             ssl, result.data(), result.size(), config->export_label.data(),
1084             config->export_label.size(),
1085             reinterpret_cast<const uint8_t *>(config->export_context.data()),
1086             config->export_context.size(), config->use_export_context)) {
1087       fprintf(stderr, "failed to export keying material\n");
1088       return false;
1089     }
1090     if (WriteAll(ssl, result.data(), result.size()) < 0) {
1091       return false;
1092     }
1093   }
1094 
1095   if (config->export_traffic_secrets) {
1096     bssl::Span<const uint8_t> read_secret, write_secret;
1097     if (!SSL_get_traffic_secrets(ssl, &read_secret, &write_secret)) {
1098       fprintf(stderr, "failed to export traffic secrets\n");
1099       return false;
1100     }
1101 
1102     assert(read_secret.size() <= 0xffff);
1103     assert(write_secret.size() == read_secret.size());
1104     const uint16_t secret_len = read_secret.size();
1105     if (WriteAll(ssl, &secret_len, sizeof(secret_len)) < 0 ||
1106         WriteAll(ssl, read_secret.data(), read_secret.size()) < 0 ||
1107         WriteAll(ssl, write_secret.data(), write_secret.size()) < 0) {
1108       return false;
1109     }
1110   }
1111 
1112   if (config->tls_unique) {
1113     uint8_t tls_unique[16];
1114     size_t tls_unique_len;
1115     if (!SSL_get_tls_unique(ssl, tls_unique, &tls_unique_len,
1116                             sizeof(tls_unique))) {
1117       fprintf(stderr, "failed to get tls-unique\n");
1118       return false;
1119     }
1120 
1121     if (tls_unique_len != 12) {
1122       fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
1123               static_cast<unsigned>(tls_unique_len));
1124       return false;
1125     }
1126 
1127     if (WriteAll(ssl, tls_unique, tls_unique_len) < 0) {
1128       return false;
1129     }
1130   }
1131 
1132   if (config->send_alert) {
1133     if (DoSendFatalAlert(ssl, SSL_AD_DECOMPRESSION_FAILURE) < 0) {
1134       return false;
1135     }
1136     return true;
1137   }
1138 
1139   if (config->write_different_record_sizes) {
1140     if (config->is_dtls) {
1141       fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
1142       return false;
1143     }
1144     // This mode writes a number of different record sizes in an attempt to
1145     // trip up the CBC record splitting code.
1146     static const size_t kBufLen = 32769;
1147     auto buf = std::make_unique<uint8_t[]>(kBufLen);
1148     OPENSSL_memset(buf.get(), 0x42, kBufLen);
1149     static const size_t kRecordSizes[] = {
1150         0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
1151     for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
1152       const size_t len = kRecordSizes[i];
1153       if (len > kBufLen) {
1154         fprintf(stderr, "Bad kRecordSizes value.\n");
1155         return false;
1156       }
1157       if (WriteAll(ssl, buf.get(), len) < 0) {
1158         return false;
1159       }
1160     }
1161   } else {
1162     static const char kInitialWrite[] = "hello";
1163     bool pending_initial_write = false;
1164     if (config->read_with_unfinished_write) {
1165       if (!config->async) {
1166         fprintf(stderr, "-read-with-unfinished-write requires -async.\n");
1167         return false;
1168       }
1169       if (config->is_quic) {
1170         fprintf(stderr,
1171                 "-read-with-unfinished-write is incompatible with QUIC.\n");
1172         return false;
1173       }
1174 
1175       // Let only one byte of the record through.
1176       AsyncBioAllowWrite(test_state->async_bio, 1);
1177       int write_ret =
1178           SSL_write(ssl, kInitialWrite, strlen(kInitialWrite));
1179       if (SSL_get_error(ssl, write_ret) != SSL_ERROR_WANT_WRITE) {
1180         fprintf(stderr, "Failed to leave unfinished write.\n");
1181         return false;
1182       }
1183       pending_initial_write = true;
1184     } else if (config->shim_writes_first) {
1185       if (WriteAll(ssl, kInitialWrite, strlen(kInitialWrite)) < 0) {
1186         return false;
1187       }
1188     }
1189     if (!config->shim_shuts_down) {
1190       for (;;) {
1191         // Read only 512 bytes at a time in TLS to ensure records may be
1192         // returned in multiple reads.
1193         size_t read_size = config->is_dtls ? 16384 : 512;
1194         if (config->read_size > 0) {
1195           read_size = config->read_size;
1196         }
1197         auto buf = std::make_unique<uint8_t[]>(read_size);
1198 
1199         int n = DoRead(ssl, buf.get(), read_size);
1200         int err = SSL_get_error(ssl, n);
1201         if (err == SSL_ERROR_ZERO_RETURN ||
1202             (n == 0 && err == SSL_ERROR_SYSCALL)) {
1203           if (n != 0) {
1204             fprintf(stderr, "Invalid SSL_get_error output\n");
1205             return false;
1206           }
1207           // Stop on either clean or unclean shutdown.
1208           break;
1209         } else if (err != SSL_ERROR_NONE) {
1210           if (n > 0) {
1211             fprintf(stderr, "Invalid SSL_get_error output\n");
1212             return false;
1213           }
1214           return false;
1215         }
1216         // Successfully read data.
1217         if (n <= 0) {
1218           fprintf(stderr, "Invalid SSL_get_error output\n");
1219           return false;
1220         }
1221 
1222         if (!config->is_server && is_resume && !is_retry &&
1223             config->expect_reject_early_data) {
1224           fprintf(stderr,
1225                   "Unexpectedly received data instead of 0-RTT reject.\n");
1226           return false;
1227         }
1228 
1229         // After a successful read, with or without False Start, the handshake
1230         // must be complete unless we are doing early data.
1231         if (!test_state->handshake_done &&
1232             !SSL_early_data_accepted(ssl)) {
1233           fprintf(stderr, "handshake was not completed after SSL_read\n");
1234           return false;
1235         }
1236 
1237         // Clear the initial write, if unfinished.
1238         if (pending_initial_write) {
1239           if (WriteAll(ssl, kInitialWrite, strlen(kInitialWrite)) < 0) {
1240             return false;
1241           }
1242           pending_initial_write = false;
1243         }
1244 
1245         if (config->key_update &&
1246             !SSL_key_update(ssl, SSL_KEY_UPDATE_NOT_REQUESTED)) {
1247           fprintf(stderr, "SSL_key_update failed.\n");
1248           return false;
1249         }
1250 
1251         for (int i = 0; i < n; i++) {
1252           buf[i] ^= 0xff;
1253         }
1254         if (WriteAll(ssl, buf.get(), n) < 0) {
1255           return false;
1256         }
1257       }
1258     }
1259   }
1260 
1261   if (!config->is_server && !config->false_start &&
1262       !config->implicit_handshake &&
1263       // Session tickets are sent post-handshake in TLS 1.3.
1264       GetProtocolVersion(ssl) < TLS1_3_VERSION &&
1265       test_state->got_new_session) {
1266     fprintf(stderr, "new session was established after the handshake\n");
1267     return false;
1268   }
1269 
1270   if (GetProtocolVersion(ssl) >= TLS1_3_VERSION && !config->is_server) {
1271     bool expect_new_session =
1272         !config->expect_no_session && !config->shim_shuts_down;
1273     if (expect_new_session != test_state->got_new_session) {
1274       fprintf(stderr,
1275               "new session was%s cached, but we expected the opposite\n",
1276               test_state->got_new_session ? "" : " not");
1277       return false;
1278     }
1279 
1280     if (expect_new_session) {
1281       bool got_early_data =
1282           test_state->new_session->ticket_max_early_data != 0;
1283       if (config->expect_ticket_supports_early_data != got_early_data) {
1284         fprintf(stderr,
1285                 "new session did%s support early data, but we expected the "
1286                 "opposite\n",
1287                 got_early_data ? "" : " not");
1288         return false;
1289       }
1290     }
1291   }
1292 
1293   if (out_session) {
1294     *out_session = std::move(test_state->new_session);
1295   }
1296 
1297   ret = DoShutdown(ssl);
1298 
1299   if (config->shim_shuts_down && config->check_close_notify) {
1300     // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1301     // it returns zero when our close_notify is sent, then one when the peer's
1302     // is received.
1303     if (ret != 0) {
1304       fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1305       return false;
1306     }
1307     ret = DoShutdown(ssl);
1308   }
1309 
1310   if (ret != 1) {
1311     fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1312     return false;
1313   }
1314 
1315   if (SSL_total_renegotiations(ssl) > 0) {
1316     if (!SSL_get_session(ssl)->not_resumable) {
1317       fprintf(stderr,
1318               "Renegotiations should never produce resumable sessions.\n");
1319       return false;
1320     }
1321 
1322     if (SSL_session_reused(ssl)) {
1323       fprintf(stderr, "Renegotiations should never resume sessions.\n");
1324       return false;
1325     }
1326 
1327     // Re-check authentication properties after a renegotiation. The reported
1328     // values should remain unchanged even if the server sent different SCT
1329     // lists.
1330     if (!CheckAuthProperties(ssl, is_resume, config)) {
1331       return false;
1332     }
1333   }
1334 
1335   if (SSL_total_renegotiations(ssl) != config->expect_total_renegotiations) {
1336     fprintf(stderr, "Expected %d renegotiations, got %d\n",
1337             config->expect_total_renegotiations, SSL_total_renegotiations(ssl));
1338     return false;
1339   }
1340 
1341   if (config->renegotiate_explicit &&
1342       SSL_total_renegotiations(ssl) !=
1343           test_state->explicit_renegotiates) {
1344     fprintf(stderr, "Performed %d renegotiations, but triggered %d of them\n",
1345             SSL_total_renegotiations(ssl),
1346             test_state->explicit_renegotiates);
1347     return false;
1348   }
1349 
1350   return true;
1351 }
1352 
1353 class StderrDelimiter {
1354  public:
~StderrDelimiter()1355   ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
1356 };
1357 
main(int argc,char ** argv)1358 int main(int argc, char **argv) {
1359   // To distinguish ASan's output from ours, add a trailing message to stderr.
1360   // Anything following this line will be considered an error.
1361   StderrDelimiter delimiter;
1362 
1363 #if defined(OPENSSL_WINDOWS)
1364   // Initialize Winsock.
1365   WORD wsa_version = MAKEWORD(2, 2);
1366   WSADATA wsa_data;
1367   int wsa_err = WSAStartup(wsa_version, &wsa_data);
1368   if (wsa_err != 0) {
1369     fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1370     return 1;
1371   }
1372   if (wsa_data.wVersion != wsa_version) {
1373     fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1374     return 1;
1375   }
1376 #else
1377   signal(SIGPIPE, SIG_IGN);
1378 #endif
1379 
1380   CRYPTO_library_init();
1381 
1382   TestConfig initial_config, resume_config, retry_config;
1383   if (!ParseConfig(argc - 1, argv + 1, /*is_shim=*/true, &initial_config,
1384                    &resume_config, &retry_config)) {
1385     return Usage(argv[0]);
1386   }
1387 
1388   if (initial_config.is_handshaker_supported) {
1389 #if defined(HANDSHAKER_SUPPORTED)
1390     printf("Yes\n");
1391 #else
1392     printf("No\n");
1393 #endif
1394     return 0;
1395   }
1396 
1397   if (initial_config.wait_for_debugger) {
1398 #if defined(OPENSSL_WINDOWS)
1399     fprintf(stderr, "-wait-for-debugger is not supported on Windows.\n");
1400     return 1;
1401 #else
1402     // The debugger will resume the process.
1403     raise(SIGSTOP);
1404 #endif
1405   }
1406 
1407   bssl::UniquePtr<SSL_CTX> ssl_ctx;
1408 
1409   bssl::UniquePtr<SSL_SESSION> session;
1410   for (int i = 0; i < initial_config.resume_count + 1; i++) {
1411     bool is_resume = i > 0;
1412     TestConfig *config = is_resume ? &resume_config : &initial_config;
1413     ssl_ctx = config->SetupCtx(ssl_ctx.get());
1414     if (!ssl_ctx) {
1415       ERR_print_errors_fp(stderr);
1416       return 1;
1417     }
1418 
1419     if (is_resume && !initial_config.is_server && !session) {
1420       fprintf(stderr, "No session to offer.\n");
1421       return 1;
1422     }
1423 
1424     bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
1425     SettingsWriter writer;
1426     if (!writer.Init(i, config, offer_session.get())) {
1427       fprintf(stderr, "Error writing settings.\n");
1428       return 1;
1429     }
1430     bool ok = DoConnection(&session, ssl_ctx.get(), config, &retry_config,
1431                            is_resume, offer_session.get(), &writer);
1432     if (!writer.Commit()) {
1433       fprintf(stderr, "Error writing settings.\n");
1434       return 1;
1435     }
1436     if (!ok) {
1437       fprintf(stderr, "Connection %d failed.\n", i + 1);
1438       ERR_print_errors_fp(stderr);
1439       return 1;
1440     }
1441 
1442     if (config->resumption_delay != 0) {
1443       AdvanceClock(config->resumption_delay);
1444     }
1445   }
1446 
1447   return 0;
1448 }
1449