1 // Copyright 2018 The BoringSSL Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "handshake_util.h"
16 
17 #include <assert.h>
18 #if defined(HANDSHAKER_SUPPORTED)
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <spawn.h>
22 #include <sys/socket.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <sys/wait.h>
26 #include <unistd.h>
27 #endif
28 
29 #include <functional>
30 #include <map>
31 #include <vector>
32 
33 #include "async_bio.h"
34 #include "packeted_bio.h"
35 #include "test_config.h"
36 #include "test_state.h"
37 
38 #include <openssl/bytestring.h>
39 #include <openssl/ssl.h>
40 
41 using namespace bssl;
42 
RetryAsync(SSL * ssl,int ret)43 bool RetryAsync(SSL *ssl, int ret) {
44   const TestConfig *config = GetTestConfig(ssl);
45   TestState *test_state = GetTestState(ssl);
46   if (ret >= 0) {
47     return false;
48   }
49 
50   int ssl_err = SSL_get_error(ssl, ret);
51   if (ssl_err == SSL_ERROR_WANT_RENEGOTIATE && config->renegotiate_explicit) {
52     test_state->explicit_renegotiates++;
53     return SSL_renegotiate(ssl);
54   }
55 
56   if (test_state->quic_transport && ssl_err == SSL_ERROR_WANT_READ) {
57     return test_state->quic_transport->ReadHandshake();
58   }
59 
60   if (!config->async) {
61     // Only asynchronous tests should trigger other retries.
62     return false;
63   }
64 
65   if (test_state->packeted_bio != nullptr &&
66       PacketedBioAdvanceClock(test_state->packeted_bio)) {
67     int timeout_ret = DTLSv1_handle_timeout(ssl);
68     if (timeout_ret >= 0) {
69       return true;
70     }
71     ssl_err = SSL_get_error(ssl, timeout_ret);
72   }
73 
74   // See if we needed to read or write more. If so, allow one byte through on
75   // the appropriate end to maximally stress the state machine.
76   switch (ssl_err) {
77     case SSL_ERROR_WANT_READ:
78       AsyncBioAllowRead(test_state->async_bio, 1);
79       return true;
80     case SSL_ERROR_WANT_WRITE:
81       AsyncBioAllowWrite(test_state->async_bio, 1);
82       return true;
83     case SSL_ERROR_WANT_X509_LOOKUP:
84       test_state->cert_ready = true;
85       return true;
86     case SSL_ERROR_PENDING_SESSION:
87       test_state->session = std::move(test_state->pending_session);
88       return true;
89     case SSL_ERROR_PENDING_CERTIFICATE:
90       test_state->early_callback_ready = true;
91       return true;
92     case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
93       test_state->private_key_retries++;
94       if (config->private_key_delay_ms != 0 &&
95           test_state->private_key_retries == 1) {
96         // The first time around, simulate the private key operation taking a
97         // long time to run.
98         if (test_state->packeted_bio == nullptr) {
99           fprintf(stderr, "-private-key-delay-ms requires DTLS.\n");
100           return false;
101         }
102         timeval *clock = PacketedBioGetClock(test_state->packeted_bio);
103         clock->tv_sec += config->private_key_delay_ms / 1000;
104         clock->tv_usec += config->private_key_delay_ms * 1000;
105         if (clock->tv_usec >= 1000000) {
106           clock->tv_usec -= 1000000;
107           clock->tv_sec++;
108         }
109         int timeout_ret = DTLSv1_handle_timeout(ssl);
110         if (timeout_ret < 0) {
111           if (SSL_get_error(ssl, timeout_ret) == SSL_ERROR_WANT_WRITE) {
112             AsyncBioAllowWrite(test_state->async_bio, 1);
113             return true;
114           }
115           return false;
116         }
117       }
118       return true;
119     case SSL_ERROR_WANT_CERTIFICATE_VERIFY:
120       test_state->custom_verify_ready = true;
121       return true;
122     case SSL_ERROR_PENDING_TICKET:
123       test_state->async_ticket_decrypt_ready = true;
124       return true;
125     default:
126       return false;
127   }
128 }
129 
CheckIdempotentError(const char * name,SSL * ssl,std::function<int ()> func)130 int CheckIdempotentError(const char *name, SSL *ssl,
131                          std::function<int()> func) {
132   int ret = func();
133   int ssl_err = SSL_get_error(ssl, ret);
134   uint32_t err = ERR_peek_error();
135   if (ssl_err == SSL_ERROR_SSL || ssl_err == SSL_ERROR_ZERO_RETURN) {
136     int ret2 = func();
137     int ssl_err2 = SSL_get_error(ssl, ret2);
138     uint32_t err2 = ERR_peek_error();
139     if (ret != ret2 || ssl_err != ssl_err2 || err != err2) {
140       fprintf(stderr, "Repeating %s did not replay the error.\n", name);
141       char buf[256];
142       ERR_error_string_n(err, buf, sizeof(buf));
143       fprintf(stderr, "Wanted: %d %d %s\n", ret, ssl_err, buf);
144       ERR_error_string_n(err2, buf, sizeof(buf));
145       fprintf(stderr, "Got:    %d %d %s\n", ret2, ssl_err2, buf);
146       // runner treats exit code 90 as always failing. Otherwise, it may
147       // accidentally consider the result an expected protocol failure.
148       exit(90);
149     }
150   }
151   return ret;
152 }
153 
154 #if defined(HANDSHAKER_SUPPORTED)
155 
156 // MoveBIOs moves the |BIO|s of |src| to |dst|.  It is used for handoff.
MoveBIOs(SSL * dest,SSL * src)157 static void MoveBIOs(SSL *dest, SSL *src) {
158   BIO *rbio = SSL_get_rbio(src);
159   BIO_up_ref(rbio);
160   SSL_set0_rbio(dest, rbio);
161 
162   BIO *wbio = SSL_get_wbio(src);
163   BIO_up_ref(wbio);
164   SSL_set0_wbio(dest, wbio);
165 
166   SSL_set0_rbio(src, nullptr);
167   SSL_set0_wbio(src, nullptr);
168 }
169 
HandoffReady(SSL * ssl,int ret)170 static bool HandoffReady(SSL *ssl, int ret) {
171   return ret < 0 && SSL_get_error(ssl, ret) == SSL_ERROR_HANDOFF;
172 }
173 
read_eintr(int fd,void * out,size_t len)174 static ssize_t read_eintr(int fd, void *out, size_t len) {
175   ssize_t ret;
176   do {
177     ret = read(fd, out, len);
178   } while (ret < 0 && errno == EINTR);
179   return ret;
180 }
181 
write_eintr(int fd,const void * in,size_t len)182 static ssize_t write_eintr(int fd, const void *in, size_t len) {
183   ssize_t ret;
184   do {
185     ret = write(fd, in, len);
186   } while (ret < 0 && errno == EINTR);
187   return ret;
188 }
189 
waitpid_eintr(pid_t pid,int * wstatus,int options)190 static ssize_t waitpid_eintr(pid_t pid, int *wstatus, int options) {
191   pid_t ret;
192   do {
193     ret = waitpid(pid, wstatus, options);
194   } while (ret < 0 && errno == EINTR);
195   return ret;
196 }
197 
198 // Proxy relays data between |socket|, which is connected to the client, and the
199 // handshaker, which is connected to the numerically specified file descriptors,
200 // until the handshaker returns control.
Proxy(BIO * socket,bool async,int control,int rfd,int wfd)201 static bool Proxy(BIO *socket, bool async, int control, int rfd, int wfd) {
202   for (;;) {
203     fd_set rfds;
204     FD_ZERO(&rfds);
205     FD_SET(wfd, &rfds);
206     FD_SET(control, &rfds);
207     int fd_max = wfd > control ? wfd : control;
208     if (select(fd_max + 1, &rfds, nullptr, nullptr, nullptr) == -1) {
209       perror("select");
210       return false;
211     }
212 
213     char buf[64];
214     ssize_t bytes;
215     if (FD_ISSET(wfd, &rfds) &&
216         (bytes = read_eintr(wfd, buf, sizeof(buf))) > 0) {
217       char *b = buf;
218       while (bytes) {
219         int written = BIO_write(socket, b, bytes);
220         if (!written) {
221           fprintf(stderr, "BIO_write wrote nothing\n");
222           return false;
223         }
224         if (written < 0) {
225           if (async) {
226             AsyncBioAllowWrite(socket, 1);
227             continue;
228           }
229           fprintf(stderr, "BIO_write failed\n");
230           return false;
231         }
232         b += written;
233         bytes -= written;
234       }
235       // Flush all pending data from the handshaker to the client before
236       // considering control messages.
237       continue;
238     }
239 
240     if (!FD_ISSET(control, &rfds)) {
241       continue;
242     }
243 
244     char msg;
245     if (read_eintr(control, &msg, 1) != 1) {
246       perror("read");
247       return false;
248     }
249     switch (msg) {
250       case kControlMsgDone:
251         return true;
252       case kControlMsgError:
253         return false;
254       case kControlMsgWantRead:
255         break;
256       default:
257         fprintf(stderr, "Unknown control message from handshaker: %c\n", msg);
258         return false;
259     }
260 
261     auto proxy_data = [&](uint8_t *out, size_t len) -> bool {
262       if (async) {
263         AsyncBioAllowRead(socket, len);
264       }
265 
266       while (len > 0) {
267         int bytes_read = BIO_read(socket, out, len);
268         if (bytes_read < 1) {
269           fprintf(stderr, "BIO_read failed\n");
270           return false;
271         }
272 
273         ssize_t bytes_written = write_eintr(rfd, out, bytes_read);
274         if (bytes_written == -1) {
275           perror("write");
276           return false;
277         }
278         if (bytes_written != bytes_read) {
279           fprintf(stderr, "short write (%zd of %d bytes)\n", bytes_written,
280                   bytes_read);
281           return false;
282         }
283 
284         len -= bytes_read;
285         out += bytes_read;
286       }
287       return true;
288     };
289 
290     // Process one SSL record at a time.  That way, we don't send the handshaker
291     // anything it doesn't want to process, e.g. early data.
292     uint8_t header[SSL3_RT_HEADER_LENGTH];
293     if (!proxy_data(header, sizeof(header))) {
294       return false;
295     }
296     if (header[1] != 3) {
297        fprintf(stderr, "bad header\n");
298        return false;
299     }
300     size_t remaining = (header[3] << 8) + header[4];
301     while (remaining > 0) {
302       uint8_t readbuf[64];
303       size_t len = remaining > sizeof(readbuf) ? sizeof(readbuf) : remaining;
304       if (!proxy_data(readbuf, len)) {
305         return false;
306       }
307       remaining -= len;
308     }
309 
310     // The handshaker blocks on the control channel, so we have to signal
311     // it that the data have been written.
312     msg = kControlMsgWriteCompleted;
313     if (write_eintr(control, &msg, 1) != 1) {
314       perror("write");
315       return false;
316     }
317   }
318 }
319 
320 class ScopedFD {
321  public:
ScopedFD()322   ScopedFD() : fd_(-1) {}
ScopedFD(int fd)323   explicit ScopedFD(int fd) : fd_(fd) {}
~ScopedFD()324   ~ScopedFD() { Reset(); }
325 
ScopedFD(ScopedFD && other)326   ScopedFD(ScopedFD &&other) { *this = std::move(other); }
operator =(ScopedFD && other)327   ScopedFD &operator=(ScopedFD &&other) {
328     Reset(other.fd_);
329     other.fd_ = -1;
330     return *this;
331   }
332 
fd() const333   int fd() const { return fd_; }
334 
Reset(int fd=-1)335   void Reset(int fd = -1) {
336     if (fd_ >= 0) {
337       close(fd_);
338     }
339     fd_ = fd;
340   }
341 
342  private:
343   int fd_;
344 };
345 
346 class ScopedProcess {
347  public:
ScopedProcess()348   ScopedProcess() : pid_(-1) {}
~ScopedProcess()349   ~ScopedProcess() { Reset(); }
350 
ScopedProcess(ScopedProcess && other)351   ScopedProcess(ScopedProcess &&other) { *this = std::move(other); }
operator =(ScopedProcess && other)352   ScopedProcess &operator=(ScopedProcess &&other) {
353     Reset(other.pid_);
354     other.pid_ = -1;
355     return *this;
356   }
357 
pid() const358   pid_t pid() const { return pid_; }
359 
Reset(pid_t pid=-1)360   void Reset(pid_t pid = -1) {
361     if (pid_ >= 0) {
362       kill(pid_, SIGTERM);
363       int unused;
364       Wait(&unused);
365     }
366     pid_ = pid;
367   }
368 
Wait(int * out_status)369   bool Wait(int *out_status) {
370     if (pid_ < 0) {
371       return false;
372     }
373     if (waitpid_eintr(pid_, out_status, 0) != pid_) {
374       return false;
375     }
376     pid_ = -1;
377     return true;
378   }
379 
380  private:
381   pid_t pid_;
382 };
383 
384 class FileActionsDestroyer {
385  public:
FileActionsDestroyer(posix_spawn_file_actions_t * actions)386   explicit FileActionsDestroyer(posix_spawn_file_actions_t *actions)
387       : actions_(actions) {}
~FileActionsDestroyer()388   ~FileActionsDestroyer() { posix_spawn_file_actions_destroy(actions_); }
389   FileActionsDestroyer(const FileActionsDestroyer &) = delete;
390   FileActionsDestroyer &operator=(const FileActionsDestroyer &) = delete;
391 
392  private:
393   posix_spawn_file_actions_t *actions_;
394 };
395 
396 // StartHandshaker starts the handshaker process and, on success, returns a
397 // handle to the process in |*out|. It sets |*out_control| to a control pipe to
398 // the process. |map_fds| maps from desired fd number in the child process to
399 // the source fd in the calling process. |close_fds| is the list of additional
400 // fds to close, which may overlap with |map_fds|. Other than stdin, stdout, and
401 // stderr, the status of fds not listed in either set is undefined.
StartHandshaker(ScopedProcess * out,ScopedFD * out_control,const TestConfig * config,bool is_resume,std::map<int,int> map_fds,std::vector<int> close_fds)402 static bool StartHandshaker(ScopedProcess *out, ScopedFD *out_control,
403                             const TestConfig *config, bool is_resume,
404                             std::map<int, int> map_fds,
405                             std::vector<int> close_fds) {
406   if (config->handshaker_path.empty()) {
407     fprintf(stderr, "no -handshaker-path specified\n");
408     return false;
409   }
410   struct stat dummy;
411   if (stat(config->handshaker_path.c_str(), &dummy) == -1) {
412     perror(config->handshaker_path.c_str());
413     return false;
414   }
415 
416   std::vector<const char *> args;
417   args.push_back(config->handshaker_path.c_str());
418   static const char kResumeFlag[] = "-handshaker-resume";
419   if (is_resume) {
420     args.push_back(kResumeFlag);
421   }
422   // config->handshaker_args omits argv[0].
423   for (const char *arg : config->handshaker_args) {
424     args.push_back(arg);
425   }
426   args.push_back(nullptr);
427 
428   // A datagram socket guarantees that writes are all-or-nothing.
429   int control[2];
430   if (socketpair(AF_LOCAL, SOCK_DGRAM, 0, control) != 0) {
431     perror("socketpair");
432     return false;
433   }
434   ScopedFD scoped_control0(control[0]), scoped_control1(control[1]);
435   close_fds.push_back(control[0]);
436   map_fds[kFdControl] = control[1];
437 
438   posix_spawn_file_actions_t actions;
439   if (posix_spawn_file_actions_init(&actions) != 0) {
440     return false;
441   }
442   FileActionsDestroyer actions_destroyer(&actions);
443   for (int fd : close_fds) {
444     if (posix_spawn_file_actions_addclose(&actions, fd) != 0) {
445       return false;
446     }
447   }
448   if (!map_fds.empty()) {
449     int max_fd = STDERR_FILENO;
450     for (const auto &pair : map_fds) {
451       max_fd = std::max(max_fd, pair.first);
452       max_fd = std::max(max_fd, pair.second);
453     }
454     // |map_fds| may contain cycles, so make a copy of all the source fds.
455     // |posix_spawn| can only use |dup2|, not |dup|, so we assume |max_fd| is
456     // the last fd we care about inheriting. |temp_fds| maps from fd number in
457     // the parent process to a temporary fd number in the child process.
458     std::map<int, int> temp_fds;
459     int next_fd = max_fd + 1;
460     for (const auto &pair : map_fds) {
461       if (temp_fds.count(pair.second)) {
462         continue;
463       }
464       temp_fds[pair.second] = next_fd;
465       if (posix_spawn_file_actions_adddup2(&actions, pair.second, next_fd) !=
466           0 ||
467           posix_spawn_file_actions_addclose(&actions, pair.second) != 0) {
468         return false;
469       }
470       next_fd++;
471     }
472     for (const auto &pair : map_fds) {
473       if (posix_spawn_file_actions_adddup2(&actions, temp_fds[pair.second],
474                                            pair.first) != 0) {
475         return false;
476       }
477     }
478     // Clean up temporary fds.
479     for (int fd = max_fd + 1; fd < next_fd; fd++) {
480       if (posix_spawn_file_actions_addclose(&actions, fd) != 0) {
481         return false;
482       }
483     }
484   }
485 
486   fflush(stdout);
487   fflush(stderr);
488 
489   // MSan doesn't know that |posix_spawn| initializes its output, so initialize
490   // it to -1.
491   pid_t pid = -1;
492   if (posix_spawn(&pid, args[0], &actions, nullptr,
493                   const_cast<char *const *>(args.data()), environ) != 0) {
494     return false;
495   }
496 
497   out->Reset(pid);
498   *out_control = std::move(scoped_control0);
499   return true;
500 }
501 
502 // RunHandshaker forks and execs the handshaker binary, handing off |input|,
503 // and, after proxying some amount of handshake traffic, handing back |out|.
RunHandshaker(BIO * bio,const TestConfig * config,bool is_resume,Span<const uint8_t> input,std::vector<uint8_t> * out)504 static bool RunHandshaker(BIO *bio, const TestConfig *config, bool is_resume,
505                           Span<const uint8_t> input,
506                           std::vector<uint8_t> *out) {
507   int rfd[2], wfd[2];
508   // We use pipes, rather than some other mechanism, for their buffers.  During
509   // the handshake, this process acts as a dumb proxy until receiving the
510   // handback signal, which arrives asynchronously.  The race condition means
511   // that this process could incorrectly proxy post-handshake data from the
512   // client to the handshaker.
513   //
514   // To avoid this, this process never proxies data to the handshaker that the
515   // handshaker has not explicitly requested as a result of hitting
516   // |SSL_ERROR_WANT_READ|.  Pipes allow the data to sit in a buffer while the
517   // two processes synchronize over the |control| channel.
518   if (pipe(rfd) != 0) {
519     perror("pipe");
520     return false;
521   }
522   ScopedFD rfd0_closer(rfd[0]), rfd1_closer(rfd[1]);
523 
524   if (pipe(wfd) != 0) {
525     perror("pipe");
526     return false;
527   }
528   ScopedFD wfd0_closer(wfd[0]), wfd1_closer(wfd[1]);
529 
530   ScopedProcess handshaker;
531   ScopedFD control;
532   if (!StartHandshaker(
533           &handshaker, &control, config, is_resume,
534           {{kFdProxyToHandshaker, rfd[0]}, {kFdHandshakerToProxy, wfd[1]}},
535           {rfd[1], wfd[0]})) {
536     return false;
537   }
538 
539   rfd0_closer.Reset();
540   wfd1_closer.Reset();
541 
542   if (write_eintr(control.fd(), input.data(), input.size()) == -1) {
543     perror("write");
544     return false;
545   }
546   bool ok = Proxy(bio, config->async, control.fd(), rfd[1], wfd[0]);
547   int wstatus;
548   if (!handshaker.Wait(&wstatus)) {
549     perror("waitpid");
550     return false;
551   }
552   if (ok && wstatus) {
553     fprintf(stderr, "handshaker exited irregularly\n");
554     return false;
555   }
556   if (!ok) {
557     return false;  // This is a "good", i.e. expected, error.
558   }
559 
560   constexpr size_t kBufSize = 1024 * 1024;
561   std::vector<uint8_t> buf(kBufSize);
562   ssize_t len = read_eintr(control.fd(), buf.data(), buf.size());
563   if (len == -1) {
564     perror("read");
565     return false;
566   }
567   buf.resize(len);
568   *out = std::move(buf);
569   return true;
570 }
571 
RequestHandshakeHint(const TestConfig * config,bool is_resume,Span<const uint8_t> input,bool * out_has_hints,std::vector<uint8_t> * out_hints)572 static bool RequestHandshakeHint(const TestConfig *config, bool is_resume,
573                                  Span<const uint8_t> input, bool *out_has_hints,
574                                  std::vector<uint8_t> *out_hints) {
575   ScopedProcess handshaker;
576   ScopedFD control;
577   if (!StartHandshaker(&handshaker, &control, config, is_resume, {}, {})) {
578     return false;
579   }
580 
581   if (write_eintr(control.fd(), input.data(), input.size()) == -1) {
582     perror("write");
583     return false;
584   }
585 
586   char msg;
587   if (read_eintr(control.fd(), &msg, 1) != 1) {
588     perror("read");
589     return false;
590   }
591 
592   switch (msg) {
593     case kControlMsgDone: {
594       constexpr size_t kBufSize = 1024 * 1024;
595       out_hints->resize(kBufSize);
596       ssize_t len =
597           read_eintr(control.fd(), out_hints->data(), out_hints->size());
598       if (len == -1) {
599         perror("read");
600         return false;
601       }
602       out_hints->resize(len);
603       *out_has_hints = true;
604       break;
605     }
606     case kControlMsgError:
607       *out_has_hints = false;
608       break;
609     default:
610       fprintf(stderr, "Unknown control message from handshaker: %c\n", msg);
611       return false;
612   }
613 
614   int wstatus;
615   if (!handshaker.Wait(&wstatus)) {
616     perror("waitpid");
617     return false;
618   }
619   if (wstatus) {
620     fprintf(stderr, "handshaker exited irregularly\n");
621     return false;
622   }
623 
624   return true;
625 }
626 
627 // PrepareHandoff accepts the |ClientHello| from |ssl| and serializes state to
628 // be passed to the handshaker.  The serialized state includes both the SSL
629 // handoff, as well test-related state.
PrepareHandoff(SSL * ssl,SettingsWriter * writer,std::vector<uint8_t> * out_handoff)630 static bool PrepareHandoff(SSL *ssl, SettingsWriter *writer,
631                            std::vector<uint8_t> *out_handoff) {
632   SSL_set_handoff_mode(ssl, 1);
633 
634   const TestConfig *config = GetTestConfig(ssl);
635   int ret = -1;
636   do {
637     ret = CheckIdempotentError(
638         "SSL_do_handshake", ssl,
639         [&]() -> int { return SSL_do_handshake(ssl); });
640   } while (!HandoffReady(ssl, ret) &&
641            config->async &&
642            RetryAsync(ssl, ret));
643   if (!HandoffReady(ssl, ret)) {
644     fprintf(stderr, "Handshake failed while waiting for handoff.\n");
645     return false;
646   }
647 
648   ScopedCBB cbb;
649   SSL_CLIENT_HELLO hello;
650   if (!CBB_init(cbb.get(), 512) ||
651       !SSL_serialize_handoff(ssl, cbb.get(), &hello) ||
652       !writer->WriteHandoff({CBB_data(cbb.get()), CBB_len(cbb.get())}) ||
653       !SerializeContextState(SSL_get_SSL_CTX(ssl), cbb.get()) ||
654       !GetTestState(ssl)->Serialize(cbb.get())) {
655     fprintf(stderr, "Handoff serialisation failed.\n");
656     return false;
657   }
658   out_handoff->assign(CBB_data(cbb.get()),
659                       CBB_data(cbb.get()) + CBB_len(cbb.get()));
660   return true;
661 }
662 
663 // DoSplitHandshake delegates the SSL handshake to a separate process, called
664 // the handshaker.  This process proxies I/O between the handshaker and the
665 // client, using the |BIO| from |ssl|.  After a successful handshake, |ssl| is
666 // replaced with a new |SSL| object, in a way that is intended to be invisible
667 // to the caller.
DoSplitHandshake(UniquePtr<SSL> * ssl,SettingsWriter * writer,bool is_resume)668 bool DoSplitHandshake(UniquePtr<SSL> *ssl, SettingsWriter *writer,
669                       bool is_resume) {
670   assert(SSL_get_rbio(ssl->get()) == SSL_get_wbio(ssl->get()));
671   std::vector<uint8_t> handshaker_input;
672   const TestConfig *config = GetTestConfig(ssl->get());
673   // out is the response from the handshaker, which includes a serialized
674   // handback message, but also serialized updates to the |TestState|.
675   std::vector<uint8_t> out;
676   if (!PrepareHandoff(ssl->get(), writer, &handshaker_input) ||
677       !RunHandshaker(SSL_get_rbio(ssl->get()), config, is_resume,
678                      handshaker_input, &out)) {
679     fprintf(stderr, "Handoff failed.\n");
680     return false;
681   }
682 
683   SSL_CTX *ctx = SSL_get_SSL_CTX(ssl->get());
684   UniquePtr<SSL> ssl_handback = config->NewSSL(ctx, nullptr, nullptr);
685   if (!ssl_handback) {
686     return false;
687   }
688   CBS output, handback;
689   CBS_init(&output, out.data(), out.size());
690   if (!CBS_get_u24_length_prefixed(&output, &handback) ||
691       !DeserializeContextState(&output, ctx) ||
692       !SetTestState(ssl_handback.get(), TestState::Deserialize(&output, ctx)) ||
693       !GetTestState(ssl_handback.get()) || !writer->WriteHandback(handback) ||
694       !SSL_apply_handback(ssl_handback.get(), handback)) {
695     fprintf(stderr, "Handback failed.\n");
696     return false;
697   }
698   MoveBIOs(ssl_handback.get(), ssl->get());
699   GetTestState(ssl_handback.get())->async_bio =
700       GetTestState(ssl->get())->async_bio;
701   GetTestState(ssl->get())->async_bio = nullptr;
702 
703   *ssl = std::move(ssl_handback);
704   return true;
705 }
706 
GetHandshakeHint(SSL * ssl,SettingsWriter * writer,bool is_resume,const SSL_CLIENT_HELLO * client_hello)707 bool GetHandshakeHint(SSL *ssl, SettingsWriter *writer, bool is_resume,
708                       const SSL_CLIENT_HELLO *client_hello) {
709   ScopedCBB input;
710   CBB child;
711   if (!CBB_init(input.get(), client_hello->client_hello_len + 256) ||
712       !CBB_add_u24_length_prefixed(input.get(), &child) ||
713       !CBB_add_bytes(&child, client_hello->client_hello,
714                      client_hello->client_hello_len) ||
715       !CBB_add_u24_length_prefixed(input.get(), &child) ||
716       !SSL_serialize_capabilities(ssl, &child) ||  //
717       !CBB_flush(input.get())) {
718     return false;
719   }
720 
721   bool has_hints;
722   std::vector<uint8_t> hints;
723   if (!RequestHandshakeHint(GetTestConfig(ssl), is_resume,
724                             Span(CBB_data(input.get()), CBB_len(input.get())),
725                             &has_hints, &hints)) {
726     return false;
727   }
728   if (has_hints &&
729       (!writer->WriteHints(hints) ||
730        !SSL_set_handshake_hints(ssl, hints.data(), hints.size()))) {
731     return false;
732   }
733 
734   return true;
735 }
736 
737 #endif  // defined(HANDSHAKER_SUPPORTED)
738