• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2018, 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 "handshake_util.h"
16 
17 #include <assert.h>
18 #if defined(OPENSSL_LINUX) && !defined(OPENSSL_ANDROID)
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 
31 #include "async_bio.h"
32 #include "packeted_bio.h"
33 #include "test_config.h"
34 #include "test_state.h"
35 
36 #include <openssl/ssl.h>
37 
38 using namespace bssl;
39 
RetryAsync(SSL * ssl,int ret)40 bool RetryAsync(SSL *ssl, int ret) {
41   const TestConfig *config = GetTestConfig(ssl);
42   TestState *test_state = GetTestState(ssl);
43   if (ret >= 0) {
44     return false;
45   }
46 
47   int ssl_err = SSL_get_error(ssl, ret);
48   if (ssl_err == SSL_ERROR_WANT_RENEGOTIATE && config->renegotiate_explicit) {
49     test_state->explicit_renegotiates++;
50     return SSL_renegotiate(ssl);
51   }
52 
53   if (!config->async) {
54     // Only asynchronous tests should trigger other retries.
55     return false;
56   }
57 
58   if (test_state->packeted_bio != nullptr &&
59       PacketedBioAdvanceClock(test_state->packeted_bio)) {
60     // The DTLS retransmit logic silently ignores write failures. So the test
61     // may progress, allow writes through synchronously.
62     AsyncBioEnforceWriteQuota(test_state->async_bio, false);
63     int timeout_ret = DTLSv1_handle_timeout(ssl);
64     AsyncBioEnforceWriteQuota(test_state->async_bio, true);
65 
66     if (timeout_ret < 0) {
67       fprintf(stderr, "Error retransmitting.\n");
68       return false;
69     }
70     return true;
71   }
72 
73   // See if we needed to read or write more. If so, allow one byte through on
74   // the appropriate end to maximally stress the state machine.
75   switch (ssl_err) {
76     case SSL_ERROR_WANT_READ:
77       AsyncBioAllowRead(test_state->async_bio, 1);
78       return true;
79     case SSL_ERROR_WANT_WRITE:
80       AsyncBioAllowWrite(test_state->async_bio, 1);
81       return true;
82     case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
83       UniquePtr<EVP_PKEY> pkey = LoadPrivateKey(config->send_channel_id);
84       if (!pkey) {
85         return false;
86       }
87       test_state->channel_id = std::move(pkey);
88       return true;
89     }
90     case SSL_ERROR_WANT_X509_LOOKUP:
91       test_state->cert_ready = true;
92       return true;
93     case SSL_ERROR_PENDING_SESSION:
94       test_state->session = std::move(test_state->pending_session);
95       return true;
96     case SSL_ERROR_PENDING_CERTIFICATE:
97       test_state->early_callback_ready = true;
98       return true;
99     case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
100       test_state->private_key_retries++;
101       return true;
102     case SSL_ERROR_WANT_CERTIFICATE_VERIFY:
103       test_state->custom_verify_ready = true;
104       return true;
105     default:
106       return false;
107   }
108 }
109 
CheckIdempotentError(const char * name,SSL * ssl,std::function<int ()> func)110 int CheckIdempotentError(const char *name, SSL *ssl,
111                          std::function<int()> func) {
112   int ret = func();
113   int ssl_err = SSL_get_error(ssl, ret);
114   uint32_t err = ERR_peek_error();
115   if (ssl_err == SSL_ERROR_SSL || ssl_err == SSL_ERROR_ZERO_RETURN) {
116     int ret2 = func();
117     int ssl_err2 = SSL_get_error(ssl, ret2);
118     uint32_t err2 = ERR_peek_error();
119     if (ret != ret2 || ssl_err != ssl_err2 || err != err2) {
120       fprintf(stderr, "Repeating %s did not replay the error.\n", name);
121       char buf[256];
122       ERR_error_string_n(err, buf, sizeof(buf));
123       fprintf(stderr, "Wanted: %d %d %s\n", ret, ssl_err, buf);
124       ERR_error_string_n(err2, buf, sizeof(buf));
125       fprintf(stderr, "Got:    %d %d %s\n", ret2, ssl_err2, buf);
126       // runner treats exit code 90 as always failing. Otherwise, it may
127       // accidentally consider the result an expected protocol failure.
128       exit(90);
129     }
130   }
131   return ret;
132 }
133 
134 #if defined(OPENSSL_LINUX) && !defined(OPENSSL_ANDROID)
135 
136 // MoveBIOs moves the |BIO|s of |src| to |dst|.  It is used for handoff.
MoveBIOs(SSL * dest,SSL * src)137 static void MoveBIOs(SSL *dest, SSL *src) {
138   BIO *rbio = SSL_get_rbio(src);
139   BIO_up_ref(rbio);
140   SSL_set0_rbio(dest, rbio);
141 
142   BIO *wbio = SSL_get_wbio(src);
143   BIO_up_ref(wbio);
144   SSL_set0_wbio(dest, wbio);
145 
146   SSL_set0_rbio(src, nullptr);
147   SSL_set0_wbio(src, nullptr);
148 }
149 
HandoffReady(SSL * ssl,int ret)150 static bool HandoffReady(SSL *ssl, int ret) {
151   return ret < 0 && SSL_get_error(ssl, ret) == SSL_ERROR_HANDOFF;
152 }
153 
read_eintr(int fd,void * out,size_t len)154 static ssize_t read_eintr(int fd, void *out, size_t len) {
155   ssize_t ret;
156   do {
157     ret = read(fd, out, len);
158   } while (ret < 0 && errno == EINTR);
159   return ret;
160 }
161 
write_eintr(int fd,const void * in,size_t len)162 static ssize_t write_eintr(int fd, const void *in, size_t len) {
163   ssize_t ret;
164   do {
165     ret = write(fd, in, len);
166   } while (ret < 0 && errno == EINTR);
167   return ret;
168 }
169 
waitpid_eintr(pid_t pid,int * wstatus,int options)170 static ssize_t waitpid_eintr(pid_t pid, int *wstatus, int options) {
171   pid_t ret;
172   do {
173     ret = waitpid(pid, wstatus, options);
174   } while (ret < 0 && errno == EINTR);
175   return ret;
176 }
177 
178 // Proxy relays data between |socket|, which is connected to the client, and the
179 // handshaker, which is connected to the numerically specified file descriptors,
180 // until the handshaker returns control.
Proxy(BIO * socket,bool async,int control,int rfd,int wfd)181 static bool Proxy(BIO *socket, bool async, int control, int rfd, int wfd) {
182   for (;;) {
183     fd_set rfds;
184     FD_ZERO(&rfds);
185     FD_SET(wfd, &rfds);
186     FD_SET(control, &rfds);
187     int fd_max = wfd > control ? wfd : control;
188     if (select(fd_max + 1, &rfds, nullptr, nullptr, nullptr) == -1) {
189       perror("select");
190       return false;
191     }
192 
193     char buf[64];
194     ssize_t bytes;
195     if (FD_ISSET(wfd, &rfds) &&
196         (bytes = read_eintr(wfd, buf, sizeof(buf))) > 0) {
197       char *b = buf;
198       while (bytes) {
199         int written = BIO_write(socket, b, bytes);
200         if (!written) {
201           fprintf(stderr, "BIO_write wrote nothing\n");
202           return false;
203         }
204         if (written < 0) {
205           if (async) {
206             AsyncBioAllowWrite(socket, 1);
207             continue;
208           }
209           fprintf(stderr, "BIO_write failed\n");
210           return false;
211         }
212         b += written;
213         bytes -= written;
214       }
215       // Flush all pending data from the handshaker to the client before
216       // considering control messages.
217       continue;
218     }
219 
220     if (!FD_ISSET(control, &rfds)) {
221       continue;
222     }
223 
224     char msg;
225     if (read_eintr(control, &msg, 1) != 1) {
226       perror("read");
227       return false;
228     }
229     switch (msg) {
230       case kControlMsgHandback:
231         return true;
232       case kControlMsgError:
233         return false;
234       case kControlMsgWantRead:
235         break;
236       default:
237         fprintf(stderr, "Unknown control message from handshaker: %c\n", msg);
238         return false;
239     }
240 
241     char readbuf[64];
242     if (async) {
243       AsyncBioAllowRead(socket, 1);
244     }
245     int read = BIO_read(socket, readbuf, sizeof(readbuf));
246     if (read < 1) {
247       fprintf(stderr, "BIO_read failed\n");
248       return false;
249     }
250     ssize_t written = write_eintr(rfd, readbuf, read);
251     if (written == -1) {
252       perror("write");
253       return false;
254     }
255     if (written != read) {
256       fprintf(stderr, "short write (%zu of %d bytes)\n", written, read);
257       return false;
258     }
259     // The handshaker blocks on the control channel, so we have to signal
260     // it that the data have been written.
261     msg = kControlMsgWriteCompleted;
262     if (write_eintr(control, &msg, 1) != 1) {
263       perror("write");
264       return false;
265     }
266   }
267 }
268 
269 class ScopedFD {
270  public:
ScopedFD(int fd)271   explicit ScopedFD(int fd): fd_(fd) {}
~ScopedFD()272   ~ScopedFD() { close(fd_); }
273  private:
274   const int fd_;
275 };
276 
277 // RunHandshaker forks and execs the handshaker binary, handing off |input|,
278 // and, after proxying some amount of handshake traffic, handing back |out|.
RunHandshaker(BIO * bio,const TestConfig * config,bool is_resume,const Array<uint8_t> & input,Array<uint8_t> * out)279 static bool RunHandshaker(BIO *bio, const TestConfig *config, bool is_resume,
280                           const Array<uint8_t> &input,
281                           Array<uint8_t> *out) {
282   if (config->handshaker_path.empty()) {
283     fprintf(stderr, "no -handshaker-path specified\n");
284     return false;
285   }
286   struct stat dummy;
287   if (stat(config->handshaker_path.c_str(), &dummy) == -1) {
288     perror(config->handshaker_path.c_str());
289     return false;
290   }
291 
292   // A datagram socket guarantees that writes are all-or-nothing.
293   int control[2];
294   if (socketpair(AF_LOCAL, SOCK_DGRAM, 0, control) != 0) {
295     perror("socketpair");
296     return false;
297   }
298   int rfd[2], wfd[2];
299   // We use pipes, rather than some other mechanism, for their buffers.  During
300   // the handshake, this process acts as a dumb proxy until receiving the
301   // handback signal, which arrives asynchronously.  The race condition means
302   // that this process could incorrectly proxy post-handshake data from the
303   // client to the handshaker.
304   //
305   // To avoid this, this process never proxies data to the handshaker that the
306   // handshaker has not explicitly requested as a result of hitting
307   // |SSL_ERROR_WANT_READ|.  Pipes allow the data to sit in a buffer while the
308   // two processes synchronize over the |control| channel.
309   if (pipe(rfd) != 0 || pipe(wfd) != 0) {
310     perror("pipe2");
311     return false;
312   }
313 
314   fflush(stdout);
315   fflush(stderr);
316 
317   std::vector<char *> args;
318   bssl::UniquePtr<char> handshaker_path(
319       OPENSSL_strdup(config->handshaker_path.c_str()));
320   args.push_back(handshaker_path.get());
321   char resume[] = "-handshaker-resume";
322   if (is_resume) {
323     args.push_back(resume);
324   }
325   // config->argv omits argv[0].
326   for (int j = 0; j < config->argc; ++j) {
327     args.push_back(config->argv[j]);
328   }
329   args.push_back(nullptr);
330 
331   posix_spawn_file_actions_t actions;
332   if (posix_spawn_file_actions_init(&actions) != 0 ||
333       posix_spawn_file_actions_addclose(&actions, control[0]) ||
334       posix_spawn_file_actions_addclose(&actions, rfd[1]) ||
335       posix_spawn_file_actions_addclose(&actions, wfd[0])) {
336     return false;
337   }
338   assert(kFdControl != rfd[0]);
339   assert(kFdControl != wfd[1]);
340   if (control[1] != kFdControl &&
341       posix_spawn_file_actions_adddup2(&actions, control[1], kFdControl) != 0) {
342     return false;
343   }
344   assert(kFdProxyToHandshaker != wfd[1]);
345   if (rfd[0] != kFdProxyToHandshaker &&
346       posix_spawn_file_actions_adddup2(&actions, rfd[0],
347                                        kFdProxyToHandshaker) != 0) {
348     return false;
349   }
350   if (wfd[1] != kFdHandshakerToProxy &&
351       posix_spawn_file_actions_adddup2(&actions, wfd[1],
352                                        kFdHandshakerToProxy) != 0) {
353       return false;
354   }
355 
356   // MSan doesn't know that |posix_spawn| initializes its output, so initialize
357   // it to -1.
358   pid_t handshaker_pid = -1;
359   int ret = posix_spawn(&handshaker_pid, args[0], &actions, nullptr,
360                         args.data(), environ);
361   if (posix_spawn_file_actions_destroy(&actions) != 0 ||
362       ret != 0) {
363     return false;
364   }
365 
366   close(control[1]);
367   close(rfd[0]);
368   close(wfd[1]);
369   ScopedFD rfd_closer(rfd[1]);
370   ScopedFD wfd_closer(wfd[0]);
371   ScopedFD control_closer(control[0]);
372 
373   if (write_eintr(control[0], input.data(), input.size()) == -1) {
374     perror("write");
375     return false;
376   }
377   bool ok = Proxy(bio, config->async, control[0], rfd[1], wfd[0]);
378   int wstatus;
379   if (waitpid_eintr(handshaker_pid, &wstatus, 0) != handshaker_pid) {
380     perror("waitpid");
381     return false;
382   }
383   if (ok && wstatus) {
384     fprintf(stderr, "handshaker exited irregularly\n");
385     return false;
386   }
387   if (!ok) {
388     return false;  // This is a "good", i.e. expected, error.
389   }
390 
391   constexpr size_t kBufSize = 1024 * 1024;
392   bssl::UniquePtr<uint8_t> buf((uint8_t *) OPENSSL_malloc(kBufSize));
393   int len = read_eintr(control[0], buf.get(), kBufSize);
394   if (len == -1) {
395     perror("read");
396     return false;
397   }
398   out->CopyFrom({buf.get(), (size_t)len});
399   return true;
400 }
401 
402 // PrepareHandoff accepts the |ClientHello| from |ssl| and serializes state to
403 // be passed to the handshaker.  The serialized state includes both the SSL
404 // handoff, as well test-related state.
PrepareHandoff(SSL * ssl,SettingsWriter * writer,Array<uint8_t> * out_handoff)405 static bool PrepareHandoff(SSL *ssl, SettingsWriter *writer,
406                            Array<uint8_t> *out_handoff) {
407   SSL_set_handoff_mode(ssl, 1);
408 
409   const TestConfig *config = GetTestConfig(ssl);
410   int ret = -1;
411   do {
412     ret = CheckIdempotentError(
413         "SSL_do_handshake", ssl,
414         [&]() -> int { return SSL_do_handshake(ssl); });
415   } while (!HandoffReady(ssl, ret) &&
416            config->async &&
417            RetryAsync(ssl, ret));
418   if (!HandoffReady(ssl, ret)) {
419     fprintf(stderr, "Handshake failed while waiting for handoff.\n");
420     return false;
421   }
422 
423   ScopedCBB cbb;
424   SSL_CLIENT_HELLO hello;
425   if (!CBB_init(cbb.get(), 512) ||
426       !SSL_serialize_handoff(ssl, cbb.get(), &hello) ||
427       !writer->WriteHandoff({CBB_data(cbb.get()), CBB_len(cbb.get())}) ||
428       !SerializeContextState(ssl->ctx.get(), cbb.get()) ||
429       !GetTestState(ssl)->Serialize(cbb.get())) {
430     fprintf(stderr, "Handoff serialisation failed.\n");
431     return false;
432   }
433   return CBBFinishArray(cbb.get(), out_handoff);
434 }
435 
436 // DoSplitHandshake delegates the SSL handshake to a separate process, called
437 // the handshaker.  This process proxies I/O between the handshaker and the
438 // client, using the |BIO| from |ssl|.  After a successful handshake, |ssl| is
439 // replaced with a new |SSL| object, in a way that is intended to be invisible
440 // to the caller.
DoSplitHandshake(UniquePtr<SSL> * ssl,SettingsWriter * writer,bool is_resume)441 bool DoSplitHandshake(UniquePtr<SSL> *ssl, SettingsWriter *writer,
442                       bool is_resume) {
443   assert(SSL_get_rbio(ssl->get()) == SSL_get_wbio(ssl->get()));
444   Array<uint8_t> handshaker_input;
445   const TestConfig *config = GetTestConfig(ssl->get());
446   // out is the response from the handshaker, which includes a serialized
447   // handback message, but also serialized updates to the |TestState|.
448   Array<uint8_t> out;
449   if (!PrepareHandoff(ssl->get(), writer, &handshaker_input) ||
450       !RunHandshaker(SSL_get_rbio(ssl->get()), config, is_resume,
451                      handshaker_input, &out)) {
452     fprintf(stderr, "Handoff failed.\n");
453     return false;
454   }
455 
456   UniquePtr<SSL> ssl_handback =
457       config->NewSSL((*ssl)->ctx.get(), nullptr, false, nullptr);
458   if (!ssl_handback) {
459     return false;
460   }
461   CBS output, handback;
462   CBS_init(&output, out.data(), out.size());
463   if (!CBS_get_u24_length_prefixed(&output, &handback) ||
464       !DeserializeContextState(&output, ssl_handback->ctx.get()) ||
465       !SetTestState(ssl_handback.get(), TestState::Deserialize(
466           &output, ssl_handback->ctx.get())) ||
467       !GetTestState(ssl_handback.get()) ||
468       !writer->WriteHandback(handback) ||
469       !SSL_apply_handback(ssl_handback.get(), handback)) {
470     fprintf(stderr, "Handback failed.\n");
471     return false;
472   }
473   MoveBIOs(ssl_handback.get(), ssl->get());
474   GetTestState(ssl_handback.get())->async_bio =
475       GetTestState(ssl->get())->async_bio;
476   GetTestState(ssl->get())->async_bio = nullptr;
477 
478   *ssl = std::move(ssl_handback);
479   return true;
480 }
481 
482 #endif  // defined(OPENSSL_LINUX) && !defined(OPENSSL_ANDROID)
483