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.
 
 
 
 
 
 

1150 lines
36 KiB

  1. /* Copyright (c) 2014, 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. #if !defined(__STDC_FORMAT_MACROS)
  15. #define __STDC_FORMAT_MACROS
  16. #endif
  17. #include <openssl/base.h>
  18. #if !defined(OPENSSL_WINDOWS)
  19. #include <arpa/inet.h>
  20. #include <netinet/in.h>
  21. #include <netinet/tcp.h>
  22. #include <signal.h>
  23. #include <sys/socket.h>
  24. #include <sys/time.h>
  25. #include <unistd.h>
  26. #else
  27. #include <io.h>
  28. OPENSSL_MSVC_PRAGMA(warning(push, 3))
  29. #include <winsock2.h>
  30. #include <ws2tcpip.h>
  31. OPENSSL_MSVC_PRAGMA(warning(pop))
  32. OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
  33. #endif
  34. #include <assert.h>
  35. #include <inttypes.h>
  36. #include <string.h>
  37. #include <time.h>
  38. #include <openssl/aead.h>
  39. #include <openssl/bio.h>
  40. #include <openssl/buf.h>
  41. #include <openssl/bytestring.h>
  42. #include <openssl/cipher.h>
  43. #include <openssl/crypto.h>
  44. #include <openssl/digest.h>
  45. #include <openssl/err.h>
  46. #include <openssl/evp.h>
  47. #include <openssl/hmac.h>
  48. #include <openssl/nid.h>
  49. #include <openssl/rand.h>
  50. #include <openssl/ssl.h>
  51. #include <openssl/x509.h>
  52. #include <functional>
  53. #include <memory>
  54. #include <string>
  55. #include <vector>
  56. #include "../../crypto/internal.h"
  57. #include "../internal.h"
  58. #include "async_bio.h"
  59. #include "handshake_util.h"
  60. #include "packeted_bio.h"
  61. #include "settings_writer.h"
  62. #include "test_config.h"
  63. #include "test_state.h"
  64. #if defined(OPENSSL_LINUX) && !defined(OPENSSL_ANDROID)
  65. #define HANDSHAKER_SUPPORTED
  66. #endif
  67. #if !defined(OPENSSL_WINDOWS)
  68. static int closesocket(int sock) {
  69. return close(sock);
  70. }
  71. static void PrintSocketError(const char *func) {
  72. perror(func);
  73. }
  74. #else
  75. static void PrintSocketError(const char *func) {
  76. fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
  77. }
  78. #endif
  79. static int Usage(const char *program) {
  80. fprintf(stderr, "Usage: %s [flags...]\n", program);
  81. return 1;
  82. }
  83. template<typename T>
  84. struct Free {
  85. void operator()(T *buf) {
  86. free(buf);
  87. }
  88. };
  89. // Connect returns a new socket connected to localhost on |port| or -1 on
  90. // error.
  91. static int Connect(uint16_t port) {
  92. for (int af : { AF_INET6, AF_INET }) {
  93. int sock = socket(af, SOCK_STREAM, 0);
  94. if (sock == -1) {
  95. PrintSocketError("socket");
  96. return -1;
  97. }
  98. int nodelay = 1;
  99. if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  100. reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
  101. PrintSocketError("setsockopt");
  102. closesocket(sock);
  103. return -1;
  104. }
  105. sockaddr_storage ss;
  106. OPENSSL_memset(&ss, 0, sizeof(ss));
  107. ss.ss_family = af;
  108. socklen_t len = 0;
  109. if (af == AF_INET6) {
  110. sockaddr_in6 *sin6 = (sockaddr_in6 *) &ss;
  111. len = sizeof(*sin6);
  112. sin6->sin6_port = htons(port);
  113. if (!inet_pton(AF_INET6, "::1", &sin6->sin6_addr)) {
  114. PrintSocketError("inet_pton");
  115. closesocket(sock);
  116. return -1;
  117. }
  118. } else if (af == AF_INET) {
  119. sockaddr_in *sin = (sockaddr_in *) &ss;
  120. len = sizeof(*sin);
  121. sin->sin_port = htons(port);
  122. if (!inet_pton(AF_INET, "127.0.0.1", &sin->sin_addr)) {
  123. PrintSocketError("inet_pton");
  124. closesocket(sock);
  125. return -1;
  126. }
  127. }
  128. if (connect(sock, reinterpret_cast<const sockaddr*>(&ss), len) == 0) {
  129. return sock;
  130. }
  131. closesocket(sock);
  132. }
  133. PrintSocketError("connect");
  134. return -1;
  135. }
  136. class SocketCloser {
  137. public:
  138. explicit SocketCloser(int sock) : sock_(sock) {}
  139. ~SocketCloser() {
  140. // Half-close and drain the socket before releasing it. This seems to be
  141. // necessary for graceful shutdown on Windows. It will also avoid write
  142. // failures in the test runner.
  143. #if defined(OPENSSL_WINDOWS)
  144. shutdown(sock_, SD_SEND);
  145. #else
  146. shutdown(sock_, SHUT_WR);
  147. #endif
  148. while (true) {
  149. char buf[1024];
  150. if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
  151. break;
  152. }
  153. }
  154. closesocket(sock_);
  155. }
  156. private:
  157. const int sock_;
  158. };
  159. // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
  160. // the result value of the final |SSL_read| call.
  161. static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
  162. const TestConfig *config = GetTestConfig(ssl);
  163. TestState *test_state = GetTestState(ssl);
  164. int ret;
  165. do {
  166. if (config->async) {
  167. // The DTLS retransmit logic silently ignores write failures. So the test
  168. // may progress, allow writes through synchronously. |SSL_read| may
  169. // trigger a retransmit, so disconnect the write quota.
  170. AsyncBioEnforceWriteQuota(test_state->async_bio, false);
  171. }
  172. ret = CheckIdempotentError("SSL_peek/SSL_read", ssl, [&]() -> int {
  173. return config->peek_then_read ? SSL_peek(ssl, out, max_out)
  174. : SSL_read(ssl, out, max_out);
  175. });
  176. if (config->async) {
  177. AsyncBioEnforceWriteQuota(test_state->async_bio, true);
  178. }
  179. // Run the exporter after each read. This is to test that the exporter fails
  180. // during a renegotiation.
  181. if (config->use_exporter_between_reads) {
  182. uint8_t buf;
  183. if (!SSL_export_keying_material(ssl, &buf, 1, NULL, 0, NULL, 0, 0)) {
  184. fprintf(stderr, "failed to export keying material\n");
  185. return -1;
  186. }
  187. }
  188. } while (config->async && RetryAsync(ssl, ret));
  189. if (config->peek_then_read && ret > 0) {
  190. std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
  191. // SSL_peek should synchronously return the same data.
  192. int ret2 = SSL_peek(ssl, buf.get(), ret);
  193. if (ret2 != ret ||
  194. OPENSSL_memcmp(buf.get(), out, ret) != 0) {
  195. fprintf(stderr, "First and second SSL_peek did not match.\n");
  196. return -1;
  197. }
  198. // SSL_read should synchronously return the same data and consume it.
  199. ret2 = SSL_read(ssl, buf.get(), ret);
  200. if (ret2 != ret ||
  201. OPENSSL_memcmp(buf.get(), out, ret) != 0) {
  202. fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
  203. return -1;
  204. }
  205. }
  206. return ret;
  207. }
  208. // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
  209. // operations. It returns the result of the final |SSL_write| call.
  210. static int WriteAll(SSL *ssl, const void *in_, size_t in_len) {
  211. const uint8_t *in = reinterpret_cast<const uint8_t *>(in_);
  212. const TestConfig *config = GetTestConfig(ssl);
  213. int ret;
  214. do {
  215. ret = SSL_write(ssl, in, in_len);
  216. if (ret > 0) {
  217. in += ret;
  218. in_len -= ret;
  219. }
  220. } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
  221. return ret;
  222. }
  223. // DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
  224. // returns the result of the final |SSL_shutdown| call.
  225. static int DoShutdown(SSL *ssl) {
  226. const TestConfig *config = GetTestConfig(ssl);
  227. int ret;
  228. do {
  229. ret = SSL_shutdown(ssl);
  230. } while (config->async && RetryAsync(ssl, ret));
  231. return ret;
  232. }
  233. // DoSendFatalAlert calls |SSL_send_fatal_alert|, resolving any asynchronous
  234. // operations. It returns the result of the final |SSL_send_fatal_alert| call.
  235. static int DoSendFatalAlert(SSL *ssl, uint8_t alert) {
  236. const TestConfig *config = GetTestConfig(ssl);
  237. int ret;
  238. do {
  239. ret = SSL_send_fatal_alert(ssl, alert);
  240. } while (config->async && RetryAsync(ssl, ret));
  241. return ret;
  242. }
  243. static uint16_t GetProtocolVersion(const SSL *ssl) {
  244. uint16_t version = SSL_version(ssl);
  245. if (!SSL_is_dtls(ssl)) {
  246. return version;
  247. }
  248. return 0x0201 + ~version;
  249. }
  250. // CheckAuthProperties checks, after the initial handshake is completed or
  251. // after a renegotiation, that authentication-related properties match |config|.
  252. static bool CheckAuthProperties(SSL *ssl, bool is_resume,
  253. const TestConfig *config) {
  254. if (!config->expected_ocsp_response.empty()) {
  255. const uint8_t *data;
  256. size_t len;
  257. SSL_get0_ocsp_response(ssl, &data, &len);
  258. if (config->expected_ocsp_response.size() != len ||
  259. OPENSSL_memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
  260. fprintf(stderr, "OCSP response mismatch\n");
  261. return false;
  262. }
  263. }
  264. if (!config->expected_signed_cert_timestamps.empty()) {
  265. const uint8_t *data;
  266. size_t len;
  267. SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
  268. if (config->expected_signed_cert_timestamps.size() != len ||
  269. OPENSSL_memcmp(config->expected_signed_cert_timestamps.data(), data,
  270. len) != 0) {
  271. fprintf(stderr, "SCT list mismatch\n");
  272. return false;
  273. }
  274. }
  275. if (config->expect_verify_result) {
  276. int expected_verify_result = config->verify_fail ?
  277. X509_V_ERR_APPLICATION_VERIFICATION :
  278. X509_V_OK;
  279. if (SSL_get_verify_result(ssl) != expected_verify_result) {
  280. fprintf(stderr, "Wrong certificate verification result\n");
  281. return false;
  282. }
  283. }
  284. if (!config->expect_peer_cert_file.empty()) {
  285. bssl::UniquePtr<X509> expect_leaf;
  286. bssl::UniquePtr<STACK_OF(X509)> expect_chain;
  287. if (!LoadCertificate(&expect_leaf, &expect_chain,
  288. config->expect_peer_cert_file)) {
  289. return false;
  290. }
  291. // For historical reasons, clients report a chain with a leaf and servers
  292. // without.
  293. if (!config->is_server) {
  294. if (!sk_X509_insert(expect_chain.get(), expect_leaf.get(), 0)) {
  295. return false;
  296. }
  297. X509_up_ref(expect_leaf.get()); // sk_X509_insert takes ownership.
  298. }
  299. bssl::UniquePtr<X509> leaf(SSL_get_peer_certificate(ssl));
  300. STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl);
  301. if (X509_cmp(leaf.get(), expect_leaf.get()) != 0) {
  302. fprintf(stderr, "Received a different leaf certificate than expected.\n");
  303. return false;
  304. }
  305. if (sk_X509_num(chain) != sk_X509_num(expect_chain.get())) {
  306. fprintf(stderr, "Received a chain of length %zu instead of %zu.\n",
  307. sk_X509_num(chain), sk_X509_num(expect_chain.get()));
  308. return false;
  309. }
  310. for (size_t i = 0; i < sk_X509_num(chain); i++) {
  311. if (X509_cmp(sk_X509_value(chain, i),
  312. sk_X509_value(expect_chain.get(), i)) != 0) {
  313. fprintf(stderr, "Chain certificate %zu did not match.\n",
  314. i + 1);
  315. return false;
  316. }
  317. }
  318. }
  319. if (!!SSL_SESSION_has_peer_sha256(SSL_get_session(ssl)) !=
  320. config->expect_sha256_client_cert) {
  321. fprintf(stderr,
  322. "Unexpected SHA-256 client cert state: expected:%d is_resume:%d.\n",
  323. config->expect_sha256_client_cert, is_resume);
  324. return false;
  325. }
  326. if (config->expect_sha256_client_cert &&
  327. SSL_SESSION_get0_peer_certificates(SSL_get_session(ssl)) != nullptr) {
  328. fprintf(stderr, "Have both client cert and SHA-256 hash: is_resume:%d.\n",
  329. is_resume);
  330. return false;
  331. }
  332. const uint8_t *peer_sha256;
  333. size_t peer_sha256_len;
  334. SSL_SESSION_get0_peer_sha256(SSL_get_session(ssl), &peer_sha256,
  335. &peer_sha256_len);
  336. if (SSL_SESSION_has_peer_sha256(SSL_get_session(ssl))) {
  337. if (peer_sha256_len != 32) {
  338. fprintf(stderr, "Peer SHA-256 hash had length %zu instead of 32\n",
  339. peer_sha256_len);
  340. return false;
  341. }
  342. } else {
  343. if (peer_sha256_len != 0) {
  344. fprintf(stderr, "Unexpected peer SHA-256 hash of length %zu\n",
  345. peer_sha256_len);
  346. return false;
  347. }
  348. }
  349. return true;
  350. }
  351. // CheckHandshakeProperties checks, immediately after |ssl| completes its
  352. // initial handshake (or False Starts), whether all the properties are
  353. // consistent with the test configuration and invariants.
  354. static bool CheckHandshakeProperties(SSL *ssl, bool is_resume,
  355. const TestConfig *config) {
  356. if (!CheckAuthProperties(ssl, is_resume, config)) {
  357. return false;
  358. }
  359. if (SSL_get_current_cipher(ssl) == nullptr) {
  360. fprintf(stderr, "null cipher after handshake\n");
  361. return false;
  362. }
  363. if (config->expect_version != 0 &&
  364. SSL_version(ssl) != config->expect_version) {
  365. fprintf(stderr, "want version %04x, got %04x\n", config->expect_version,
  366. SSL_version(ssl));
  367. return false;
  368. }
  369. bool expect_resume =
  370. is_resume && (!config->expect_session_miss || SSL_in_early_data(ssl));
  371. if (!!SSL_session_reused(ssl) != expect_resume) {
  372. fprintf(stderr, "session unexpectedly was%s reused\n",
  373. SSL_session_reused(ssl) ? "" : " not");
  374. return false;
  375. }
  376. bool expect_handshake_done =
  377. (is_resume || !config->false_start) && !SSL_in_early_data(ssl);
  378. if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
  379. fprintf(stderr, "handshake was%s completed\n",
  380. GetTestState(ssl)->handshake_done ? "" : " not");
  381. return false;
  382. }
  383. if (expect_handshake_done && !config->is_server) {
  384. bool expect_new_session =
  385. !config->expect_no_session &&
  386. (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
  387. // Session tickets are sent post-handshake in TLS 1.3.
  388. GetProtocolVersion(ssl) < TLS1_3_VERSION;
  389. if (expect_new_session != GetTestState(ssl)->got_new_session) {
  390. fprintf(stderr,
  391. "new session was%s cached, but we expected the opposite\n",
  392. GetTestState(ssl)->got_new_session ? "" : " not");
  393. return false;
  394. }
  395. }
  396. if (!is_resume) {
  397. if (config->expect_session_id && !GetTestState(ssl)->got_new_session) {
  398. fprintf(stderr, "session was not cached on the server.\n");
  399. return false;
  400. }
  401. if (config->expect_no_session_id && GetTestState(ssl)->got_new_session) {
  402. fprintf(stderr, "session was unexpectedly cached on the server.\n");
  403. return false;
  404. }
  405. }
  406. // early_callback_called is updated in the handshaker, so we don't see it
  407. // here.
  408. if (!config->handoff && config->is_server &&
  409. !GetTestState(ssl)->early_callback_called) {
  410. fprintf(stderr, "early callback not called\n");
  411. return false;
  412. }
  413. if (!config->expected_server_name.empty()) {
  414. const char *server_name =
  415. SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  416. if (server_name == nullptr ||
  417. server_name != config->expected_server_name) {
  418. fprintf(stderr, "servername mismatch (got %s; want %s)\n",
  419. server_name, config->expected_server_name.c_str());
  420. return false;
  421. }
  422. }
  423. if (!config->expected_next_proto.empty()) {
  424. const uint8_t *next_proto;
  425. unsigned next_proto_len;
  426. SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
  427. if (next_proto_len != config->expected_next_proto.size() ||
  428. OPENSSL_memcmp(next_proto, config->expected_next_proto.data(),
  429. next_proto_len) != 0) {
  430. fprintf(stderr, "negotiated next proto mismatch\n");
  431. return false;
  432. }
  433. }
  434. if (!config->is_server) {
  435. const uint8_t *alpn_proto;
  436. unsigned alpn_proto_len;
  437. SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
  438. if (alpn_proto_len != config->expected_alpn.size() ||
  439. OPENSSL_memcmp(alpn_proto, config->expected_alpn.data(),
  440. alpn_proto_len) != 0) {
  441. fprintf(stderr, "negotiated alpn proto mismatch\n");
  442. return false;
  443. }
  444. }
  445. if (!config->expected_quic_transport_params.empty()) {
  446. const uint8_t *peer_params;
  447. size_t peer_params_len;
  448. SSL_get_peer_quic_transport_params(ssl, &peer_params, &peer_params_len);
  449. if (peer_params_len != config->expected_quic_transport_params.size() ||
  450. OPENSSL_memcmp(peer_params,
  451. config->expected_quic_transport_params.data(),
  452. peer_params_len) != 0) {
  453. fprintf(stderr, "QUIC transport params mismatch\n");
  454. return false;
  455. }
  456. }
  457. if (!config->expected_channel_id.empty()) {
  458. uint8_t channel_id[64];
  459. if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
  460. fprintf(stderr, "no channel id negotiated\n");
  461. return false;
  462. }
  463. if (config->expected_channel_id.size() != 64 ||
  464. OPENSSL_memcmp(config->expected_channel_id.data(), channel_id, 64) !=
  465. 0) {
  466. fprintf(stderr, "channel id mismatch\n");
  467. return false;
  468. }
  469. }
  470. if (config->expected_token_binding_param != -1) {
  471. if (!SSL_is_token_binding_negotiated(ssl)) {
  472. fprintf(stderr, "no Token Binding negotiated\n");
  473. return false;
  474. }
  475. if (SSL_get_negotiated_token_binding_param(ssl) !=
  476. static_cast<uint8_t>(config->expected_token_binding_param)) {
  477. fprintf(stderr, "Token Binding param mismatch\n");
  478. return false;
  479. }
  480. }
  481. if (config->expect_extended_master_secret && !SSL_get_extms_support(ssl)) {
  482. fprintf(stderr, "No EMS for connection when expected\n");
  483. return false;
  484. }
  485. if (config->expect_secure_renegotiation &&
  486. !SSL_get_secure_renegotiation_support(ssl)) {
  487. fprintf(stderr, "No secure renegotiation for connection when expected\n");
  488. return false;
  489. }
  490. if (config->expect_no_secure_renegotiation &&
  491. SSL_get_secure_renegotiation_support(ssl)) {
  492. fprintf(stderr,
  493. "Secure renegotiation unexpectedly negotiated for connection\n");
  494. return false;
  495. }
  496. if (config->expect_peer_signature_algorithm != 0 &&
  497. config->expect_peer_signature_algorithm !=
  498. SSL_get_peer_signature_algorithm(ssl)) {
  499. fprintf(stderr, "Peer signature algorithm was %04x, wanted %04x.\n",
  500. SSL_get_peer_signature_algorithm(ssl),
  501. config->expect_peer_signature_algorithm);
  502. return false;
  503. }
  504. if (config->expect_curve_id != 0) {
  505. uint16_t curve_id = SSL_get_curve_id(ssl);
  506. if (static_cast<uint16_t>(config->expect_curve_id) != curve_id) {
  507. fprintf(stderr, "curve_id was %04x, wanted %04x\n", curve_id,
  508. static_cast<uint16_t>(config->expect_curve_id));
  509. return false;
  510. }
  511. }
  512. uint16_t cipher_id =
  513. static_cast<uint16_t>(SSL_CIPHER_get_id(SSL_get_current_cipher(ssl)));
  514. if (config->expect_cipher_aes != 0 &&
  515. EVP_has_aes_hardware() &&
  516. static_cast<uint16_t>(config->expect_cipher_aes) != cipher_id) {
  517. fprintf(stderr, "Cipher ID was %04x, wanted %04x (has AES hardware)\n",
  518. cipher_id, static_cast<uint16_t>(config->expect_cipher_aes));
  519. return false;
  520. }
  521. if (config->expect_cipher_no_aes != 0 &&
  522. !EVP_has_aes_hardware() &&
  523. static_cast<uint16_t>(config->expect_cipher_no_aes) != cipher_id) {
  524. fprintf(stderr, "Cipher ID was %04x, wanted %04x (no AES hardware)\n",
  525. cipher_id, static_cast<uint16_t>(config->expect_cipher_no_aes));
  526. return false;
  527. }
  528. if (is_resume && !SSL_in_early_data(ssl)) {
  529. if ((config->expect_accept_early_data && !SSL_early_data_accepted(ssl)) ||
  530. (config->expect_reject_early_data && SSL_early_data_accepted(ssl))) {
  531. fprintf(stderr,
  532. "Early data was%s accepted, but we expected the opposite\n",
  533. SSL_early_data_accepted(ssl) ? "" : " not");
  534. return false;
  535. }
  536. }
  537. if (!config->psk.empty()) {
  538. if (SSL_get_peer_cert_chain(ssl) != nullptr) {
  539. fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
  540. return false;
  541. }
  542. } else if (!config->is_server || config->require_any_client_certificate) {
  543. if (SSL_get_peer_cert_chain(ssl) == nullptr) {
  544. fprintf(stderr, "Received no peer certificate but expected one.\n");
  545. return false;
  546. }
  547. }
  548. if (is_resume && config->expect_ticket_age_skew != 0 &&
  549. SSL_get_ticket_age_skew(ssl) != config->expect_ticket_age_skew) {
  550. fprintf(stderr, "Ticket age skew was %" PRId32 ", wanted %d\n",
  551. SSL_get_ticket_age_skew(ssl), config->expect_ticket_age_skew);
  552. return false;
  553. }
  554. if (config->expect_tls13_downgrade != !!SSL_is_tls13_downgrade(ssl)) {
  555. fprintf(stderr, "Got %s downgrade signal, but wanted the opposite.\n",
  556. SSL_is_tls13_downgrade(ssl) ? "" : "no ");
  557. return false;
  558. }
  559. return true;
  560. }
  561. static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
  562. bssl::UniquePtr<SSL> *ssl_uniqueptr,
  563. const TestConfig *config, bool is_resume, bool is_retry,
  564. SettingsWriter *writer);
  565. // DoConnection tests an SSL connection against the peer. On success, it returns
  566. // true and sets |*out_session| to the negotiated SSL session. If the test is a
  567. // resumption attempt, |is_resume| is true and |session| is the session from the
  568. // previous exchange.
  569. static bool DoConnection(bssl::UniquePtr<SSL_SESSION> *out_session,
  570. SSL_CTX *ssl_ctx, const TestConfig *config,
  571. const TestConfig *retry_config, bool is_resume,
  572. SSL_SESSION *session, SettingsWriter *writer) {
  573. bssl::UniquePtr<SSL> ssl = config->NewSSL(
  574. ssl_ctx, session, is_resume, std::unique_ptr<TestState>(new TestState));
  575. if (!ssl) {
  576. return false;
  577. }
  578. if (config->is_server) {
  579. SSL_set_accept_state(ssl.get());
  580. } else {
  581. SSL_set_connect_state(ssl.get());
  582. }
  583. int sock = Connect(config->port);
  584. if (sock == -1) {
  585. return false;
  586. }
  587. SocketCloser closer(sock);
  588. bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
  589. if (!bio) {
  590. return false;
  591. }
  592. if (config->is_dtls) {
  593. bssl::UniquePtr<BIO> packeted = PacketedBioCreate(GetClock());
  594. if (!packeted) {
  595. return false;
  596. }
  597. GetTestState(ssl.get())->packeted_bio = packeted.get();
  598. BIO_push(packeted.get(), bio.release());
  599. bio = std::move(packeted);
  600. }
  601. if (config->async) {
  602. bssl::UniquePtr<BIO> async_scoped =
  603. config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
  604. if (!async_scoped) {
  605. return false;
  606. }
  607. BIO_push(async_scoped.get(), bio.release());
  608. GetTestState(ssl.get())->async_bio = async_scoped.get();
  609. bio = std::move(async_scoped);
  610. }
  611. SSL_set_bio(ssl.get(), bio.get(), bio.get());
  612. bio.release(); // SSL_set_bio takes ownership.
  613. bool ret = DoExchange(out_session, &ssl, config, is_resume, false, writer);
  614. if (!config->is_server && is_resume && config->expect_reject_early_data) {
  615. // We must have failed due to an early data rejection.
  616. if (ret) {
  617. fprintf(stderr, "0-RTT exchange unexpected succeeded.\n");
  618. return false;
  619. }
  620. if (SSL_get_error(ssl.get(), -1) != SSL_ERROR_EARLY_DATA_REJECTED) {
  621. fprintf(stderr,
  622. "SSL_get_error did not signal SSL_ERROR_EARLY_DATA_REJECTED.\n");
  623. return false;
  624. }
  625. // Before reseting, early state should still be available.
  626. if (!SSL_in_early_data(ssl.get()) ||
  627. !CheckHandshakeProperties(ssl.get(), is_resume, config)) {
  628. fprintf(stderr, "SSL_in_early_data returned false before reset.\n");
  629. return false;
  630. }
  631. // Reset the connection and try again at 1-RTT.
  632. SSL_reset_early_data_reject(ssl.get());
  633. // After reseting, the socket should report it is no longer in an early data
  634. // state.
  635. if (SSL_in_early_data(ssl.get())) {
  636. fprintf(stderr, "SSL_in_early_data returned true after reset.\n");
  637. return false;
  638. }
  639. if (!SetTestConfig(ssl.get(), retry_config)) {
  640. return false;
  641. }
  642. assert(!config->handoff);
  643. ret = DoExchange(out_session, &ssl, retry_config, is_resume, true, writer);
  644. }
  645. if (!ret) {
  646. return false;
  647. }
  648. if (!GetTestState(ssl.get())->msg_callback_ok) {
  649. return false;
  650. }
  651. if (!config->expect_msg_callback.empty() &&
  652. GetTestState(ssl.get())->msg_callback_text !=
  653. config->expect_msg_callback) {
  654. fprintf(stderr, "Bad message callback trace. Wanted:\n%s\nGot:\n%s\n",
  655. config->expect_msg_callback.c_str(),
  656. GetTestState(ssl.get())->msg_callback_text.c_str());
  657. return false;
  658. }
  659. return true;
  660. }
  661. static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
  662. bssl::UniquePtr<SSL> *ssl_uniqueptr,
  663. const TestConfig *config, bool is_resume, bool is_retry,
  664. SettingsWriter *writer) {
  665. int ret;
  666. SSL *ssl = ssl_uniqueptr->get();
  667. SSL_CTX *session_ctx = SSL_get_SSL_CTX(ssl);
  668. if (!config->implicit_handshake) {
  669. if (config->handoff) {
  670. #if defined(HANDSHAKER_SUPPORTED)
  671. if (!DoSplitHandshake(ssl_uniqueptr, writer, is_resume)) {
  672. return false;
  673. }
  674. ssl = ssl_uniqueptr->get();
  675. #else
  676. fprintf(stderr, "The external handshaker can only be used on Linux\n");
  677. return false;
  678. #endif
  679. }
  680. do {
  681. ret = CheckIdempotentError("SSL_do_handshake", ssl, [&]() -> int {
  682. return SSL_do_handshake(ssl);
  683. });
  684. } while (config->async && RetryAsync(ssl, ret));
  685. if (config->forbid_renegotiation_after_handshake) {
  686. SSL_set_renegotiate_mode(ssl, ssl_renegotiate_never);
  687. }
  688. if (ret != 1 || !CheckHandshakeProperties(ssl, is_resume, config)) {
  689. return false;
  690. }
  691. CopySessions(session_ctx, SSL_get_SSL_CTX(ssl));
  692. if (is_resume && !is_retry && !config->is_server &&
  693. config->expect_no_offer_early_data && SSL_in_early_data(ssl)) {
  694. fprintf(stderr, "Client unexpectedly offered early data.\n");
  695. return false;
  696. }
  697. if (config->handshake_twice) {
  698. do {
  699. ret = SSL_do_handshake(ssl);
  700. } while (config->async && RetryAsync(ssl, ret));
  701. if (ret != 1) {
  702. return false;
  703. }
  704. }
  705. // Skip the |config->async| logic as this should be a no-op.
  706. if (config->no_op_extra_handshake &&
  707. SSL_do_handshake(ssl) != 1) {
  708. fprintf(stderr, "Extra SSL_do_handshake was not a no-op.\n");
  709. return false;
  710. }
  711. // Reset the state to assert later that the callback isn't called in
  712. // renegotations.
  713. GetTestState(ssl)->got_new_session = false;
  714. }
  715. if (config->export_early_keying_material > 0) {
  716. std::vector<uint8_t> result(
  717. static_cast<size_t>(config->export_early_keying_material));
  718. if (!SSL_export_early_keying_material(
  719. ssl, result.data(), result.size(), config->export_label.data(),
  720. config->export_label.size(),
  721. reinterpret_cast<const uint8_t *>(config->export_context.data()),
  722. config->export_context.size())) {
  723. fprintf(stderr, "failed to export keying material\n");
  724. return false;
  725. }
  726. if (WriteAll(ssl, result.data(), result.size()) < 0) {
  727. return false;
  728. }
  729. }
  730. if (config->export_keying_material > 0) {
  731. std::vector<uint8_t> result(
  732. static_cast<size_t>(config->export_keying_material));
  733. if (!SSL_export_keying_material(
  734. ssl, result.data(), result.size(), config->export_label.data(),
  735. config->export_label.size(),
  736. reinterpret_cast<const uint8_t *>(config->export_context.data()),
  737. config->export_context.size(), config->use_export_context)) {
  738. fprintf(stderr, "failed to export keying material\n");
  739. return false;
  740. }
  741. if (WriteAll(ssl, result.data(), result.size()) < 0) {
  742. return false;
  743. }
  744. }
  745. if (config->tls_unique) {
  746. uint8_t tls_unique[16];
  747. size_t tls_unique_len;
  748. if (!SSL_get_tls_unique(ssl, tls_unique, &tls_unique_len,
  749. sizeof(tls_unique))) {
  750. fprintf(stderr, "failed to get tls-unique\n");
  751. return false;
  752. }
  753. if (tls_unique_len != 12) {
  754. fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
  755. static_cast<unsigned>(tls_unique_len));
  756. return false;
  757. }
  758. if (WriteAll(ssl, tls_unique, tls_unique_len) < 0) {
  759. return false;
  760. }
  761. }
  762. if (config->send_alert) {
  763. if (DoSendFatalAlert(ssl, SSL_AD_DECOMPRESSION_FAILURE) < 0) {
  764. return false;
  765. }
  766. return true;
  767. }
  768. if (config->write_different_record_sizes) {
  769. if (config->is_dtls) {
  770. fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
  771. return false;
  772. }
  773. // This mode writes a number of different record sizes in an attempt to
  774. // trip up the CBC record splitting code.
  775. static const size_t kBufLen = 32769;
  776. std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
  777. OPENSSL_memset(buf.get(), 0x42, kBufLen);
  778. static const size_t kRecordSizes[] = {
  779. 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
  780. for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
  781. const size_t len = kRecordSizes[i];
  782. if (len > kBufLen) {
  783. fprintf(stderr, "Bad kRecordSizes value.\n");
  784. return false;
  785. }
  786. if (WriteAll(ssl, buf.get(), len) < 0) {
  787. return false;
  788. }
  789. }
  790. } else {
  791. static const char kInitialWrite[] = "hello";
  792. bool pending_initial_write = false;
  793. if (config->read_with_unfinished_write) {
  794. if (!config->async) {
  795. fprintf(stderr, "-read-with-unfinished-write requires -async.\n");
  796. return false;
  797. }
  798. // Let only one byte of the record through.
  799. AsyncBioAllowWrite(GetTestState(ssl)->async_bio, 1);
  800. int write_ret =
  801. SSL_write(ssl, kInitialWrite, strlen(kInitialWrite));
  802. if (SSL_get_error(ssl, write_ret) != SSL_ERROR_WANT_WRITE) {
  803. fprintf(stderr, "Failed to leave unfinished write.\n");
  804. return false;
  805. }
  806. pending_initial_write = true;
  807. } else if (config->shim_writes_first) {
  808. if (WriteAll(ssl, kInitialWrite, strlen(kInitialWrite)) < 0) {
  809. return false;
  810. }
  811. }
  812. if (!config->shim_shuts_down) {
  813. for (;;) {
  814. // Read only 512 bytes at a time in TLS to ensure records may be
  815. // returned in multiple reads.
  816. size_t read_size = config->is_dtls ? 16384 : 512;
  817. if (config->read_size > 0) {
  818. read_size = config->read_size;
  819. }
  820. std::unique_ptr<uint8_t[]> buf(new uint8_t[read_size]);
  821. int n = DoRead(ssl, buf.get(), read_size);
  822. int err = SSL_get_error(ssl, n);
  823. if (err == SSL_ERROR_ZERO_RETURN ||
  824. (n == 0 && err == SSL_ERROR_SYSCALL)) {
  825. if (n != 0) {
  826. fprintf(stderr, "Invalid SSL_get_error output\n");
  827. return false;
  828. }
  829. // Stop on either clean or unclean shutdown.
  830. break;
  831. } else if (err != SSL_ERROR_NONE) {
  832. if (n > 0) {
  833. fprintf(stderr, "Invalid SSL_get_error output\n");
  834. return false;
  835. }
  836. return false;
  837. }
  838. // Successfully read data.
  839. if (n <= 0) {
  840. fprintf(stderr, "Invalid SSL_get_error output\n");
  841. return false;
  842. }
  843. if (!config->is_server && is_resume && !is_retry &&
  844. config->expect_reject_early_data) {
  845. fprintf(stderr,
  846. "Unexpectedly received data instead of 0-RTT reject.\n");
  847. return false;
  848. }
  849. // After a successful read, with or without False Start, the handshake
  850. // must be complete unless we are doing early data.
  851. if (!GetTestState(ssl)->handshake_done &&
  852. !SSL_early_data_accepted(ssl)) {
  853. fprintf(stderr, "handshake was not completed after SSL_read\n");
  854. return false;
  855. }
  856. // Clear the initial write, if unfinished.
  857. if (pending_initial_write) {
  858. if (WriteAll(ssl, kInitialWrite, strlen(kInitialWrite)) < 0) {
  859. return false;
  860. }
  861. pending_initial_write = false;
  862. }
  863. for (int i = 0; i < n; i++) {
  864. buf[i] ^= 0xff;
  865. }
  866. if (WriteAll(ssl, buf.get(), n) < 0) {
  867. return false;
  868. }
  869. }
  870. }
  871. }
  872. if (!config->is_server && !config->false_start &&
  873. !config->implicit_handshake &&
  874. // Session tickets are sent post-handshake in TLS 1.3.
  875. GetProtocolVersion(ssl) < TLS1_3_VERSION &&
  876. GetTestState(ssl)->got_new_session) {
  877. fprintf(stderr, "new session was established after the handshake\n");
  878. return false;
  879. }
  880. if (GetProtocolVersion(ssl) >= TLS1_3_VERSION && !config->is_server) {
  881. bool expect_new_session =
  882. !config->expect_no_session && !config->shim_shuts_down;
  883. if (expect_new_session != GetTestState(ssl)->got_new_session) {
  884. fprintf(stderr,
  885. "new session was%s cached, but we expected the opposite\n",
  886. GetTestState(ssl)->got_new_session ? "" : " not");
  887. return false;
  888. }
  889. if (expect_new_session) {
  890. bool got_early_data =
  891. GetTestState(ssl)->new_session->ticket_max_early_data != 0;
  892. if (config->expect_ticket_supports_early_data != got_early_data) {
  893. fprintf(stderr,
  894. "new session did%s support early data, but we expected the "
  895. "opposite\n",
  896. got_early_data ? "" : " not");
  897. return false;
  898. }
  899. }
  900. }
  901. if (out_session) {
  902. *out_session = std::move(GetTestState(ssl)->new_session);
  903. }
  904. ret = DoShutdown(ssl);
  905. if (config->shim_shuts_down && config->check_close_notify) {
  906. // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
  907. // it returns zero when our close_notify is sent, then one when the peer's
  908. // is received.
  909. if (ret != 0) {
  910. fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
  911. return false;
  912. }
  913. ret = DoShutdown(ssl);
  914. }
  915. if (ret != 1) {
  916. fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
  917. return false;
  918. }
  919. if (SSL_total_renegotiations(ssl) > 0) {
  920. if (!SSL_get_session(ssl)->not_resumable) {
  921. fprintf(stderr,
  922. "Renegotiations should never produce resumable sessions.\n");
  923. return false;
  924. }
  925. if (SSL_session_reused(ssl)) {
  926. fprintf(stderr, "Renegotiations should never resume sessions.\n");
  927. return false;
  928. }
  929. // Re-check authentication properties after a renegotiation. The reported
  930. // values should remain unchanged even if the server sent different SCT
  931. // lists.
  932. if (!CheckAuthProperties(ssl, is_resume, config)) {
  933. return false;
  934. }
  935. }
  936. if (SSL_total_renegotiations(ssl) != config->expect_total_renegotiations) {
  937. fprintf(stderr, "Expected %d renegotiations, got %d\n",
  938. config->expect_total_renegotiations, SSL_total_renegotiations(ssl));
  939. return false;
  940. }
  941. return true;
  942. }
  943. class StderrDelimiter {
  944. public:
  945. ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
  946. };
  947. int main(int argc, char **argv) {
  948. // To distinguish ASan's output from ours, add a trailing message to stderr.
  949. // Anything following this line will be considered an error.
  950. StderrDelimiter delimiter;
  951. #if defined(OPENSSL_WINDOWS)
  952. // Initialize Winsock.
  953. WORD wsa_version = MAKEWORD(2, 2);
  954. WSADATA wsa_data;
  955. int wsa_err = WSAStartup(wsa_version, &wsa_data);
  956. if (wsa_err != 0) {
  957. fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
  958. return 1;
  959. }
  960. if (wsa_data.wVersion != wsa_version) {
  961. fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
  962. return 1;
  963. }
  964. #else
  965. signal(SIGPIPE, SIG_IGN);
  966. #endif
  967. CRYPTO_library_init();
  968. TestConfig initial_config, resume_config, retry_config;
  969. if (!ParseConfig(argc - 1, argv + 1, &initial_config, &resume_config,
  970. &retry_config)) {
  971. return Usage(argv[0]);
  972. }
  973. if (initial_config.is_handshaker_supported) {
  974. #if defined(HANDSHAKER_SUPPORTED)
  975. printf("Yes\n");
  976. #else
  977. printf("No\n");
  978. #endif
  979. return 0;
  980. }
  981. bssl::UniquePtr<SSL_CTX> ssl_ctx;
  982. bssl::UniquePtr<SSL_SESSION> session;
  983. for (int i = 0; i < initial_config.resume_count + 1; i++) {
  984. bool is_resume = i > 0;
  985. TestConfig *config = is_resume ? &resume_config : &initial_config;
  986. ssl_ctx = config->SetupCtx(ssl_ctx.get());
  987. if (!ssl_ctx) {
  988. ERR_print_errors_fp(stderr);
  989. return 1;
  990. }
  991. if (is_resume && !initial_config.is_server && !session) {
  992. fprintf(stderr, "No session to offer.\n");
  993. return 1;
  994. }
  995. bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
  996. SettingsWriter writer;
  997. if (!writer.Init(i, config, offer_session.get())) {
  998. fprintf(stderr, "Error writing settings.\n");
  999. return 1;
  1000. }
  1001. bool ok = DoConnection(&session, ssl_ctx.get(), config, &retry_config,
  1002. is_resume, offer_session.get(), &writer);
  1003. if (!writer.Commit()) {
  1004. fprintf(stderr, "Error writing settings.\n");
  1005. return 1;
  1006. }
  1007. if (!ok) {
  1008. fprintf(stderr, "Connection %d failed.\n", i + 1);
  1009. ERR_print_errors_fp(stderr);
  1010. return 1;
  1011. }
  1012. if (config->resumption_delay != 0) {
  1013. AdvanceClock(config->resumption_delay);
  1014. }
  1015. }
  1016. return 0;
  1017. }