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