Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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