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