You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

474 lines
15 KiB

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