Você não pode selecionar mais de 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.
 
 
 
 
 
 

1024 linhas
31 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. #include <openssl/base.h>
  15. #if !defined(OPENSSL_WINDOWS)
  16. #include <arpa/inet.h>
  17. #include <netinet/in.h>
  18. #include <netinet/tcp.h>
  19. #include <signal.h>
  20. #include <sys/socket.h>
  21. #include <sys/types.h>
  22. #include <unistd.h>
  23. #else
  24. #include <io.h>
  25. #pragma warning(push, 3)
  26. #include <winsock2.h>
  27. #include <ws2tcpip.h>
  28. #pragma warning(pop)
  29. #pragma comment(lib, "Ws2_32.lib")
  30. #endif
  31. #include <string.h>
  32. #include <sys/types.h>
  33. #include <openssl/bio.h>
  34. #include <openssl/buf.h>
  35. #include <openssl/bytestring.h>
  36. #include <openssl/err.h>
  37. #include <openssl/ssl.h>
  38. #include <memory>
  39. #include <vector>
  40. #include "../../crypto/test/scoped_types.h"
  41. #include "async_bio.h"
  42. #include "packeted_bio.h"
  43. #include "scoped_types.h"
  44. #include "test_config.h"
  45. #if !defined(OPENSSL_WINDOWS)
  46. static int closesocket(int sock) {
  47. return close(sock);
  48. }
  49. static void PrintSocketError(const char *func) {
  50. perror(func);
  51. }
  52. #else
  53. static void PrintSocketError(const char *func) {
  54. fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
  55. }
  56. #endif
  57. static int Usage(const char *program) {
  58. fprintf(stderr, "Usage: %s [flags...]\n", program);
  59. return 1;
  60. }
  61. struct TestState {
  62. TestState() {
  63. // MSVC cannot initialize these inline.
  64. memset(&clock, 0, sizeof(clock));
  65. memset(&clock_delta, 0, sizeof(clock_delta));
  66. }
  67. // async_bio is async BIO which pauses reads and writes.
  68. BIO *async_bio = nullptr;
  69. // clock is the current time for the SSL connection.
  70. timeval clock;
  71. // clock_delta is how far the clock advanced in the most recent failed
  72. // |BIO_read|.
  73. timeval clock_delta;
  74. ScopedEVP_PKEY channel_id;
  75. bool cert_ready = false;
  76. ScopedSSL_SESSION session;
  77. ScopedSSL_SESSION pending_session;
  78. bool early_callback_called = false;
  79. bool handshake_done = false;
  80. };
  81. static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
  82. int index, long argl, void *argp) {
  83. delete ((TestState *)ptr);
  84. }
  85. static int g_config_index = 0;
  86. static int g_state_index = 0;
  87. static bool SetConfigPtr(SSL *ssl, const TestConfig *config) {
  88. return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
  89. }
  90. static const TestConfig *GetConfigPtr(const SSL *ssl) {
  91. return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
  92. }
  93. static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> async) {
  94. if (SSL_set_ex_data(ssl, g_state_index, (void *)async.get()) == 1) {
  95. async.release();
  96. return true;
  97. }
  98. return false;
  99. }
  100. static TestState *GetTestState(const SSL *ssl) {
  101. return (TestState *)SSL_get_ex_data(ssl, g_state_index);
  102. }
  103. static ScopedEVP_PKEY LoadPrivateKey(const std::string &file) {
  104. ScopedBIO bio(BIO_new(BIO_s_file()));
  105. if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
  106. return nullptr;
  107. }
  108. ScopedEVP_PKEY pkey(PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
  109. return pkey;
  110. }
  111. static bool InstallCertificate(SSL *ssl) {
  112. const TestConfig *config = GetConfigPtr(ssl);
  113. if (!config->key_file.empty() &&
  114. !SSL_use_PrivateKey_file(ssl, config->key_file.c_str(),
  115. SSL_FILETYPE_PEM)) {
  116. return false;
  117. }
  118. if (!config->cert_file.empty() &&
  119. !SSL_use_certificate_file(ssl, config->cert_file.c_str(),
  120. SSL_FILETYPE_PEM)) {
  121. return false;
  122. }
  123. return true;
  124. }
  125. static int SelectCertificateCallback(const struct ssl_early_callback_ctx *ctx) {
  126. const TestConfig *config = GetConfigPtr(ctx->ssl);
  127. GetTestState(ctx->ssl)->early_callback_called = true;
  128. if (!config->expected_server_name.empty()) {
  129. const uint8_t *extension_data;
  130. size_t extension_len;
  131. CBS extension, server_name_list, host_name;
  132. uint8_t name_type;
  133. if (!SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
  134. &extension_data,
  135. &extension_len)) {
  136. fprintf(stderr, "Could not find server_name extension.\n");
  137. return -1;
  138. }
  139. CBS_init(&extension, extension_data, extension_len);
  140. if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
  141. CBS_len(&extension) != 0 ||
  142. !CBS_get_u8(&server_name_list, &name_type) ||
  143. name_type != TLSEXT_NAMETYPE_host_name ||
  144. !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
  145. CBS_len(&server_name_list) != 0) {
  146. fprintf(stderr, "Could not decode server_name extension.\n");
  147. return -1;
  148. }
  149. if (!CBS_mem_equal(&host_name,
  150. (const uint8_t*)config->expected_server_name.data(),
  151. config->expected_server_name.size())) {
  152. fprintf(stderr, "Server name mismatch.\n");
  153. }
  154. }
  155. if (config->fail_early_callback) {
  156. return -1;
  157. }
  158. // Install the certificate in the early callback.
  159. if (config->use_early_callback) {
  160. if (config->async) {
  161. // Install the certificate asynchronously.
  162. return 0;
  163. }
  164. if (!InstallCertificate(ctx->ssl)) {
  165. return -1;
  166. }
  167. }
  168. return 1;
  169. }
  170. static int SkipVerify(int preverify_ok, X509_STORE_CTX *store_ctx) {
  171. return 1;
  172. }
  173. static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
  174. unsigned int *out_len, void *arg) {
  175. const TestConfig *config = GetConfigPtr(ssl);
  176. if (config->advertise_npn.empty()) {
  177. return SSL_TLSEXT_ERR_NOACK;
  178. }
  179. *out = (const uint8_t*)config->advertise_npn.data();
  180. *out_len = config->advertise_npn.size();
  181. return SSL_TLSEXT_ERR_OK;
  182. }
  183. static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
  184. const uint8_t* in, unsigned inlen, void* arg) {
  185. const TestConfig *config = GetConfigPtr(ssl);
  186. if (config->select_next_proto.empty()) {
  187. return SSL_TLSEXT_ERR_NOACK;
  188. }
  189. *out = (uint8_t*)config->select_next_proto.data();
  190. *outlen = config->select_next_proto.size();
  191. return SSL_TLSEXT_ERR_OK;
  192. }
  193. static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
  194. const uint8_t* in, unsigned inlen, void* arg) {
  195. const TestConfig *config = GetConfigPtr(ssl);
  196. if (config->select_alpn.empty()) {
  197. return SSL_TLSEXT_ERR_NOACK;
  198. }
  199. if (!config->expected_advertised_alpn.empty() &&
  200. (config->expected_advertised_alpn.size() != inlen ||
  201. memcmp(config->expected_advertised_alpn.data(),
  202. in, inlen) != 0)) {
  203. fprintf(stderr, "bad ALPN select callback inputs\n");
  204. exit(1);
  205. }
  206. *out = (const uint8_t*)config->select_alpn.data();
  207. *outlen = config->select_alpn.size();
  208. return SSL_TLSEXT_ERR_OK;
  209. }
  210. static unsigned PskClientCallback(SSL *ssl, const char *hint,
  211. char *out_identity,
  212. unsigned max_identity_len,
  213. uint8_t *out_psk, unsigned max_psk_len) {
  214. const TestConfig *config = GetConfigPtr(ssl);
  215. if (strcmp(hint ? hint : "", config->psk_identity.c_str()) != 0) {
  216. fprintf(stderr, "Server PSK hint did not match.\n");
  217. return 0;
  218. }
  219. // Account for the trailing '\0' for the identity.
  220. if (config->psk_identity.size() >= max_identity_len ||
  221. config->psk.size() > max_psk_len) {
  222. fprintf(stderr, "PSK buffers too small\n");
  223. return 0;
  224. }
  225. BUF_strlcpy(out_identity, config->psk_identity.c_str(),
  226. max_identity_len);
  227. memcpy(out_psk, config->psk.data(), config->psk.size());
  228. return config->psk.size();
  229. }
  230. static unsigned PskServerCallback(SSL *ssl, const char *identity,
  231. uint8_t *out_psk, unsigned max_psk_len) {
  232. const TestConfig *config = GetConfigPtr(ssl);
  233. if (strcmp(identity, config->psk_identity.c_str()) != 0) {
  234. fprintf(stderr, "Client PSK identity did not match.\n");
  235. return 0;
  236. }
  237. if (config->psk.size() > max_psk_len) {
  238. fprintf(stderr, "PSK buffers too small\n");
  239. return 0;
  240. }
  241. memcpy(out_psk, config->psk.data(), config->psk.size());
  242. return config->psk.size();
  243. }
  244. static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
  245. *out_clock = GetTestState(ssl)->clock;
  246. }
  247. static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
  248. *out_pkey = GetTestState(ssl)->channel_id.release();
  249. }
  250. static int CertCallback(SSL *ssl, void *arg) {
  251. if (!GetTestState(ssl)->cert_ready) {
  252. return -1;
  253. }
  254. if (!InstallCertificate(ssl)) {
  255. return 0;
  256. }
  257. return 1;
  258. }
  259. static SSL_SESSION *GetSessionCallback(SSL *ssl, uint8_t *data, int len,
  260. int *copy) {
  261. TestState *async_state = GetTestState(ssl);
  262. if (async_state->session) {
  263. *copy = 0;
  264. return async_state->session.release();
  265. } else if (async_state->pending_session) {
  266. return SSL_magic_pending_session_ptr();
  267. } else {
  268. return NULL;
  269. }
  270. }
  271. static int DDoSCallback(const struct ssl_early_callback_ctx *early_context) {
  272. const TestConfig *config = GetConfigPtr(early_context->ssl);
  273. static int callback_num = 0;
  274. callback_num++;
  275. if (config->fail_ddos_callback ||
  276. (config->fail_second_ddos_callback && callback_num == 2)) {
  277. return 0;
  278. }
  279. return 1;
  280. }
  281. static void InfoCallback(const SSL *ssl, int type, int val) {
  282. if (type == SSL_CB_HANDSHAKE_DONE) {
  283. if (GetConfigPtr(ssl)->handshake_never_done) {
  284. fprintf(stderr, "handshake completed\n");
  285. // Abort before any expected error code is printed, to ensure the overall
  286. // test fails.
  287. abort();
  288. }
  289. GetTestState(ssl)->handshake_done = true;
  290. }
  291. }
  292. // Connect returns a new socket connected to localhost on |port| or -1 on
  293. // error.
  294. static int Connect(uint16_t port) {
  295. int sock = socket(AF_INET, SOCK_STREAM, 0);
  296. if (sock == -1) {
  297. PrintSocketError("socket");
  298. return -1;
  299. }
  300. int nodelay = 1;
  301. if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
  303. PrintSocketError("setsockopt");
  304. closesocket(sock);
  305. return -1;
  306. }
  307. sockaddr_in sin;
  308. memset(&sin, 0, sizeof(sin));
  309. sin.sin_family = AF_INET;
  310. sin.sin_port = htons(port);
  311. if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
  312. PrintSocketError("inet_pton");
  313. closesocket(sock);
  314. return -1;
  315. }
  316. if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
  317. sizeof(sin)) != 0) {
  318. PrintSocketError("connect");
  319. closesocket(sock);
  320. return -1;
  321. }
  322. return sock;
  323. }
  324. class SocketCloser {
  325. public:
  326. explicit SocketCloser(int sock) : sock_(sock) {}
  327. ~SocketCloser() {
  328. // Half-close and drain the socket before releasing it. This seems to be
  329. // necessary for graceful shutdown on Windows. It will also avoid write
  330. // failures in the test runner.
  331. #if defined(OPENSSL_WINDOWS)
  332. shutdown(sock_, SD_SEND);
  333. #else
  334. shutdown(sock_, SHUT_WR);
  335. #endif
  336. while (true) {
  337. char buf[1024];
  338. if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
  339. break;
  340. }
  341. }
  342. closesocket(sock_);
  343. }
  344. private:
  345. const int sock_;
  346. };
  347. static ScopedSSL_CTX SetupCtx(const TestConfig *config) {
  348. ScopedSSL_CTX ssl_ctx(SSL_CTX_new(
  349. config->is_dtls ? DTLS_method() : TLS_method()));
  350. if (!ssl_ctx) {
  351. return nullptr;
  352. }
  353. if (config->is_dtls) {
  354. // DTLS needs read-ahead to function on a datagram BIO.
  355. //
  356. // TODO(davidben): this should not be necessary. DTLS code should only
  357. // expect a datagram BIO.
  358. SSL_CTX_set_read_ahead(ssl_ctx.get(), 1);
  359. }
  360. if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), "ALL")) {
  361. return nullptr;
  362. }
  363. ScopedDH dh(DH_get_2048_256(NULL));
  364. if (!dh || !SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
  365. return nullptr;
  366. }
  367. if (config->async && config->is_server) {
  368. // Disable the internal session cache. To test asynchronous session lookup,
  369. // we use an external session cache.
  370. SSL_CTX_set_session_cache_mode(
  371. ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
  372. SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
  373. } else {
  374. SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
  375. }
  376. ssl_ctx->select_certificate_cb = SelectCertificateCallback;
  377. SSL_CTX_set_next_protos_advertised_cb(
  378. ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
  379. if (!config->select_next_proto.empty()) {
  380. SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
  381. NULL);
  382. }
  383. if (!config->select_alpn.empty()) {
  384. SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
  385. }
  386. ssl_ctx->tlsext_channel_id_enabled_new = 1;
  387. SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
  388. ssl_ctx->current_time_cb = CurrentTimeCallback;
  389. SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
  390. return ssl_ctx;
  391. }
  392. // RetryAsync is called after a failed operation on |ssl| with return code
  393. // |ret|. If the operation should be retried, it simulates one asynchronous
  394. // event and returns true. Otherwise it returns false.
  395. static bool RetryAsync(SSL *ssl, int ret) {
  396. // No error; don't retry.
  397. if (ret >= 0) {
  398. return false;
  399. }
  400. TestState *test_state = GetTestState(ssl);
  401. if (test_state->clock_delta.tv_usec != 0 ||
  402. test_state->clock_delta.tv_sec != 0) {
  403. // Process the timeout and retry.
  404. test_state->clock.tv_usec += test_state->clock_delta.tv_usec;
  405. test_state->clock.tv_sec += test_state->clock.tv_usec / 1000000;
  406. test_state->clock.tv_usec %= 1000000;
  407. test_state->clock.tv_sec += test_state->clock_delta.tv_sec;
  408. memset(&test_state->clock_delta, 0, sizeof(test_state->clock_delta));
  409. if (DTLSv1_handle_timeout(ssl) < 0) {
  410. fprintf(stderr, "Error retransmitting.\n");
  411. return false;
  412. }
  413. return true;
  414. }
  415. // See if we needed to read or write more. If so, allow one byte through on
  416. // the appropriate end to maximally stress the state machine.
  417. switch (SSL_get_error(ssl, ret)) {
  418. case SSL_ERROR_WANT_READ:
  419. AsyncBioAllowRead(test_state->async_bio, 1);
  420. return true;
  421. case SSL_ERROR_WANT_WRITE:
  422. AsyncBioAllowWrite(test_state->async_bio, 1);
  423. return true;
  424. case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
  425. ScopedEVP_PKEY pkey = LoadPrivateKey(GetConfigPtr(ssl)->send_channel_id);
  426. if (!pkey) {
  427. return false;
  428. }
  429. test_state->channel_id = std::move(pkey);
  430. return true;
  431. }
  432. case SSL_ERROR_WANT_X509_LOOKUP:
  433. test_state->cert_ready = true;
  434. return true;
  435. case SSL_ERROR_PENDING_SESSION:
  436. test_state->session = std::move(test_state->pending_session);
  437. return true;
  438. case SSL_ERROR_PENDING_CERTIFICATE:
  439. // The handshake will resume without a second call to the early callback.
  440. return InstallCertificate(ssl);
  441. default:
  442. return false;
  443. }
  444. }
  445. // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
  446. // the result value of the final |SSL_read| call.
  447. static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
  448. const TestConfig *config = GetConfigPtr(ssl);
  449. int ret;
  450. do {
  451. ret = SSL_read(ssl, out, max_out);
  452. } while (config->async && RetryAsync(ssl, ret));
  453. return ret;
  454. }
  455. // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
  456. // operations. It returns the result of the final |SSL_write| call.
  457. static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
  458. const TestConfig *config = GetConfigPtr(ssl);
  459. int ret;
  460. do {
  461. ret = SSL_write(ssl, in, in_len);
  462. if (ret > 0) {
  463. in += ret;
  464. in_len -= ret;
  465. }
  466. } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
  467. return ret;
  468. }
  469. // DoExchange runs a test SSL exchange against the peer. On success, it returns
  470. // true and sets |*out_session| to the negotiated SSL session. If the test is a
  471. // resumption attempt, |is_resume| is true and |session| is the session from the
  472. // previous exchange.
  473. static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx,
  474. const TestConfig *config, bool is_resume,
  475. SSL_SESSION *session) {
  476. ScopedSSL ssl(SSL_new(ssl_ctx));
  477. if (!ssl) {
  478. return false;
  479. }
  480. if (!SetConfigPtr(ssl.get(), config) ||
  481. !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
  482. return false;
  483. }
  484. if (config->fallback_scsv &&
  485. !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
  486. return false;
  487. }
  488. if (!config->use_early_callback) {
  489. if (config->async) {
  490. // TODO(davidben): Also test |s->ctx->client_cert_cb| on the client.
  491. SSL_set_cert_cb(ssl.get(), CertCallback, NULL);
  492. } else if (!InstallCertificate(ssl.get())) {
  493. return false;
  494. }
  495. }
  496. if (config->require_any_client_certificate) {
  497. SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  498. SkipVerify);
  499. }
  500. if (config->false_start) {
  501. SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
  502. }
  503. if (config->cbc_record_splitting) {
  504. SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
  505. }
  506. if (config->partial_write) {
  507. SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
  508. }
  509. if (config->no_tls12) {
  510. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
  511. }
  512. if (config->no_tls11) {
  513. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
  514. }
  515. if (config->no_tls1) {
  516. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
  517. }
  518. if (config->no_ssl3) {
  519. SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
  520. }
  521. if (config->tls_d5_bug) {
  522. SSL_set_options(ssl.get(), SSL_OP_TLS_D5_BUG);
  523. }
  524. if (config->allow_unsafe_legacy_renegotiation) {
  525. SSL_set_options(ssl.get(), SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
  526. }
  527. if (config->no_legacy_server_connect) {
  528. SSL_clear_options(ssl.get(), SSL_OP_LEGACY_SERVER_CONNECT);
  529. }
  530. if (!config->expected_channel_id.empty()) {
  531. SSL_enable_tls_channel_id(ssl.get());
  532. }
  533. if (!config->send_channel_id.empty()) {
  534. SSL_enable_tls_channel_id(ssl.get());
  535. if (!config->async) {
  536. // The async case will be supplied by |ChannelIdCallback|.
  537. ScopedEVP_PKEY pkey = LoadPrivateKey(config->send_channel_id);
  538. if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
  539. return false;
  540. }
  541. }
  542. }
  543. if (!config->host_name.empty() &&
  544. !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
  545. return false;
  546. }
  547. if (!config->advertise_alpn.empty() &&
  548. SSL_set_alpn_protos(ssl.get(),
  549. (const uint8_t *)config->advertise_alpn.data(),
  550. config->advertise_alpn.size()) != 0) {
  551. return false;
  552. }
  553. if (!config->psk.empty()) {
  554. SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
  555. SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
  556. }
  557. if (!config->psk_identity.empty() &&
  558. !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
  559. return false;
  560. }
  561. if (!config->srtp_profiles.empty() &&
  562. !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
  563. return false;
  564. }
  565. if (config->enable_ocsp_stapling &&
  566. !SSL_enable_ocsp_stapling(ssl.get())) {
  567. return false;
  568. }
  569. if (config->enable_signed_cert_timestamps &&
  570. !SSL_enable_signed_cert_timestamps(ssl.get())) {
  571. return false;
  572. }
  573. SSL_enable_fastradio_padding(ssl.get(), config->fastradio_padding);
  574. if (config->min_version != 0) {
  575. SSL_set_min_version(ssl.get(), (uint16_t)config->min_version);
  576. }
  577. if (config->max_version != 0) {
  578. SSL_set_max_version(ssl.get(), (uint16_t)config->max_version);
  579. }
  580. if (config->mtu != 0) {
  581. SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
  582. SSL_set_mtu(ssl.get(), config->mtu);
  583. }
  584. if (config->install_ddos_callback) {
  585. SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
  586. }
  587. if (!config->cipher.empty() &&
  588. !SSL_set_cipher_list(ssl.get(), config->cipher.c_str())) {
  589. return false;
  590. }
  591. if (!config->reject_peer_renegotiations) {
  592. /* Renegotiations are disabled by default. */
  593. SSL_set_reject_peer_renegotiations(ssl.get(), 0);
  594. }
  595. int sock = Connect(config->port);
  596. if (sock == -1) {
  597. return false;
  598. }
  599. SocketCloser closer(sock);
  600. ScopedBIO bio(BIO_new_socket(sock, BIO_NOCLOSE));
  601. if (!bio) {
  602. return false;
  603. }
  604. if (config->is_dtls) {
  605. ScopedBIO packeted =
  606. PacketedBioCreate(&GetTestState(ssl.get())->clock_delta);
  607. BIO_push(packeted.get(), bio.release());
  608. bio = std::move(packeted);
  609. }
  610. if (config->async) {
  611. ScopedBIO async_scoped =
  612. config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
  613. BIO_push(async_scoped.get(), bio.release());
  614. GetTestState(ssl.get())->async_bio = async_scoped.get();
  615. bio = std::move(async_scoped);
  616. }
  617. SSL_set_bio(ssl.get(), bio.get(), bio.get());
  618. bio.release(); // SSL_set_bio takes ownership.
  619. if (session != NULL) {
  620. if (!config->is_server) {
  621. if (SSL_set_session(ssl.get(), session) != 1) {
  622. return false;
  623. }
  624. } else if (config->async) {
  625. // The internal session cache is disabled, so install the session
  626. // manually.
  627. GetTestState(ssl.get())->pending_session.reset(
  628. SSL_SESSION_up_ref(session));
  629. }
  630. }
  631. if (SSL_get_current_cipher(ssl.get()) != nullptr) {
  632. fprintf(stderr, "non-null cipher before handshake\n");
  633. return false;
  634. }
  635. int ret;
  636. if (config->implicit_handshake) {
  637. if (config->is_server) {
  638. SSL_set_accept_state(ssl.get());
  639. } else {
  640. SSL_set_connect_state(ssl.get());
  641. }
  642. } else {
  643. do {
  644. if (config->is_server) {
  645. ret = SSL_accept(ssl.get());
  646. } else {
  647. ret = SSL_connect(ssl.get());
  648. }
  649. } while (config->async && RetryAsync(ssl.get(), ret));
  650. if (ret != 1) {
  651. return false;
  652. }
  653. if (SSL_get_current_cipher(ssl.get()) == nullptr) {
  654. fprintf(stderr, "null cipher after handshake\n");
  655. return false;
  656. }
  657. if (is_resume &&
  658. (!!SSL_session_reused(ssl.get()) == config->expect_session_miss)) {
  659. fprintf(stderr, "session was%s reused\n",
  660. SSL_session_reused(ssl.get()) ? "" : " not");
  661. return false;
  662. }
  663. bool expect_handshake_done = is_resume || !config->false_start;
  664. if (expect_handshake_done != GetTestState(ssl.get())->handshake_done) {
  665. fprintf(stderr, "handshake was%s completed\n",
  666. GetTestState(ssl.get())->handshake_done ? "" : " not");
  667. return false;
  668. }
  669. if (config->is_server && !GetTestState(ssl.get())->early_callback_called) {
  670. fprintf(stderr, "early callback not called\n");
  671. return false;
  672. }
  673. if (!config->expected_server_name.empty()) {
  674. const char *server_name =
  675. SSL_get_servername(ssl.get(), TLSEXT_NAMETYPE_host_name);
  676. if (server_name != config->expected_server_name) {
  677. fprintf(stderr, "servername mismatch (got %s; want %s)\n",
  678. server_name, config->expected_server_name.c_str());
  679. return false;
  680. }
  681. }
  682. if (!config->expected_certificate_types.empty()) {
  683. uint8_t *certificate_types;
  684. int num_certificate_types =
  685. SSL_get0_certificate_types(ssl.get(), &certificate_types);
  686. if (num_certificate_types !=
  687. (int)config->expected_certificate_types.size() ||
  688. memcmp(certificate_types,
  689. config->expected_certificate_types.data(),
  690. num_certificate_types) != 0) {
  691. fprintf(stderr, "certificate types mismatch\n");
  692. return false;
  693. }
  694. }
  695. if (!config->expected_next_proto.empty()) {
  696. const uint8_t *next_proto;
  697. unsigned next_proto_len;
  698. SSL_get0_next_proto_negotiated(ssl.get(), &next_proto, &next_proto_len);
  699. if (next_proto_len != config->expected_next_proto.size() ||
  700. memcmp(next_proto, config->expected_next_proto.data(),
  701. next_proto_len) != 0) {
  702. fprintf(stderr, "negotiated next proto mismatch\n");
  703. return false;
  704. }
  705. }
  706. if (!config->expected_alpn.empty()) {
  707. const uint8_t *alpn_proto;
  708. unsigned alpn_proto_len;
  709. SSL_get0_alpn_selected(ssl.get(), &alpn_proto, &alpn_proto_len);
  710. if (alpn_proto_len != config->expected_alpn.size() ||
  711. memcmp(alpn_proto, config->expected_alpn.data(),
  712. alpn_proto_len) != 0) {
  713. fprintf(stderr, "negotiated alpn proto mismatch\n");
  714. return false;
  715. }
  716. }
  717. if (!config->expected_channel_id.empty()) {
  718. uint8_t channel_id[64];
  719. if (!SSL_get_tls_channel_id(ssl.get(), channel_id, sizeof(channel_id))) {
  720. fprintf(stderr, "no channel id negotiated\n");
  721. return false;
  722. }
  723. if (config->expected_channel_id.size() != 64 ||
  724. memcmp(config->expected_channel_id.data(),
  725. channel_id, 64) != 0) {
  726. fprintf(stderr, "channel id mismatch\n");
  727. return false;
  728. }
  729. }
  730. if (config->expect_extended_master_secret) {
  731. if (!ssl->session->extended_master_secret) {
  732. fprintf(stderr, "No EMS for session when expected");
  733. return false;
  734. }
  735. }
  736. if (!config->expected_ocsp_response.empty()) {
  737. const uint8_t *data;
  738. size_t len;
  739. SSL_get0_ocsp_response(ssl.get(), &data, &len);
  740. if (config->expected_ocsp_response.size() != len ||
  741. memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
  742. fprintf(stderr, "OCSP response mismatch\n");
  743. return false;
  744. }
  745. }
  746. if (!config->expected_signed_cert_timestamps.empty()) {
  747. const uint8_t *data;
  748. size_t len;
  749. SSL_get0_signed_cert_timestamp_list(ssl.get(), &data, &len);
  750. if (config->expected_signed_cert_timestamps.size() != len ||
  751. memcmp(config->expected_signed_cert_timestamps.data(),
  752. data, len) != 0) {
  753. fprintf(stderr, "SCT list mismatch\n");
  754. return false;
  755. }
  756. }
  757. }
  758. if (config->renegotiate) {
  759. if (config->async) {
  760. fprintf(stderr, "-renegotiate is not supported with -async.\n");
  761. return false;
  762. }
  763. if (config->implicit_handshake) {
  764. fprintf(stderr, "-renegotiate is not supported with -implicit-handshake.\n");
  765. return false;
  766. }
  767. SSL_renegotiate(ssl.get());
  768. ret = SSL_do_handshake(ssl.get());
  769. if (ret != 1) {
  770. return false;
  771. }
  772. SSL_set_state(ssl.get(), SSL_ST_ACCEPT);
  773. ret = SSL_do_handshake(ssl.get());
  774. if (ret != 1) {
  775. return false;
  776. }
  777. }
  778. if (config->export_keying_material > 0) {
  779. std::vector<uint8_t> result(
  780. static_cast<size_t>(config->export_keying_material));
  781. if (!SSL_export_keying_material(
  782. ssl.get(), result.data(), result.size(),
  783. config->export_label.data(), config->export_label.size(),
  784. reinterpret_cast<const uint8_t*>(config->export_context.data()),
  785. config->export_context.size(), config->use_export_context)) {
  786. fprintf(stderr, "failed to export keying material\n");
  787. return false;
  788. }
  789. if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
  790. return false;
  791. }
  792. }
  793. if (config->write_different_record_sizes) {
  794. if (config->is_dtls) {
  795. fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
  796. return false;
  797. }
  798. // This mode writes a number of different record sizes in an attempt to
  799. // trip up the CBC record splitting code.
  800. uint8_t buf[32769];
  801. memset(buf, 0x42, sizeof(buf));
  802. static const size_t kRecordSizes[] = {
  803. 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
  804. for (size_t i = 0; i < sizeof(kRecordSizes) / sizeof(kRecordSizes[0]);
  805. i++) {
  806. const size_t len = kRecordSizes[i];
  807. if (len > sizeof(buf)) {
  808. fprintf(stderr, "Bad kRecordSizes value.\n");
  809. return false;
  810. }
  811. if (WriteAll(ssl.get(), buf, len) < 0) {
  812. return false;
  813. }
  814. }
  815. } else {
  816. if (config->shim_writes_first) {
  817. if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
  818. 5) < 0) {
  819. return false;
  820. }
  821. }
  822. for (;;) {
  823. uint8_t buf[512];
  824. int n = DoRead(ssl.get(), buf, sizeof(buf));
  825. int err = SSL_get_error(ssl.get(), n);
  826. if (err == SSL_ERROR_ZERO_RETURN ||
  827. (n == 0 && err == SSL_ERROR_SYSCALL)) {
  828. if (n != 0) {
  829. fprintf(stderr, "Invalid SSL_get_error output\n");
  830. return false;
  831. }
  832. // Accept shutdowns with or without close_notify.
  833. // TODO(davidben): Write tests which distinguish these two cases.
  834. break;
  835. } else if (err != SSL_ERROR_NONE) {
  836. if (n > 0) {
  837. fprintf(stderr, "Invalid SSL_get_error output\n");
  838. return false;
  839. }
  840. return false;
  841. }
  842. // Successfully read data.
  843. if (n <= 0) {
  844. fprintf(stderr, "Invalid SSL_get_error output\n");
  845. return false;
  846. }
  847. // After a successful read, with or without False Start, the handshake
  848. // must be complete.
  849. if (!GetTestState(ssl.get())->handshake_done) {
  850. fprintf(stderr, "handshake was not completed after SSL_read\n");
  851. return false;
  852. }
  853. for (int i = 0; i < n; i++) {
  854. buf[i] ^= 0xff;
  855. }
  856. if (WriteAll(ssl.get(), buf, n) < 0) {
  857. return false;
  858. }
  859. }
  860. }
  861. if (out_session) {
  862. out_session->reset(SSL_get1_session(ssl.get()));
  863. }
  864. SSL_shutdown(ssl.get());
  865. return true;
  866. }
  867. int main(int argc, char **argv) {
  868. #if defined(OPENSSL_WINDOWS)
  869. /* Initialize Winsock. */
  870. WORD wsa_version = MAKEWORD(2, 2);
  871. WSADATA wsa_data;
  872. int wsa_err = WSAStartup(wsa_version, &wsa_data);
  873. if (wsa_err != 0) {
  874. fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
  875. return 1;
  876. }
  877. if (wsa_data.wVersion != wsa_version) {
  878. fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
  879. return 1;
  880. }
  881. #else
  882. signal(SIGPIPE, SIG_IGN);
  883. #endif
  884. if (!SSL_library_init()) {
  885. return 1;
  886. }
  887. g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  888. g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
  889. if (g_config_index < 0 || g_state_index < 0) {
  890. return 1;
  891. }
  892. TestConfig config;
  893. if (!ParseConfig(argc - 1, argv + 1, &config)) {
  894. return Usage(argv[0]);
  895. }
  896. ScopedSSL_CTX ssl_ctx = SetupCtx(&config);
  897. if (!ssl_ctx) {
  898. ERR_print_errors_fp(stderr);
  899. return 1;
  900. }
  901. ScopedSSL_SESSION session;
  902. if (!DoExchange(&session, ssl_ctx.get(), &config, false /* is_resume */,
  903. NULL /* session */)) {
  904. ERR_print_errors_fp(stderr);
  905. return 1;
  906. }
  907. if (config.resume &&
  908. !DoExchange(NULL, ssl_ctx.get(), &config, true /* is_resume */,
  909. session.get())) {
  910. ERR_print_errors_fp(stderr);
  911. return 1;
  912. }
  913. return 0;
  914. }