Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

1016 řádky
30 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 (!SSL_CTX_set_cipher_list(ssl_ctx.get(), "ALL")) {
  354. return nullptr;
  355. }
  356. ScopedDH dh(DH_get_2048_256(NULL));
  357. if (!dh || !SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
  358. return nullptr;
  359. }
  360. if (config->async && config->is_server) {
  361. // Disable the internal session cache. To test asynchronous session lookup,
  362. // we use an external session cache.
  363. SSL_CTX_set_session_cache_mode(
  364. ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
  365. SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
  366. } else {
  367. SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
  368. }
  369. ssl_ctx->select_certificate_cb = SelectCertificateCallback;
  370. SSL_CTX_set_next_protos_advertised_cb(
  371. ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
  372. if (!config->select_next_proto.empty()) {
  373. SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
  374. NULL);
  375. }
  376. if (!config->select_alpn.empty()) {
  377. SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
  378. }
  379. ssl_ctx->tlsext_channel_id_enabled_new = 1;
  380. SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
  381. ssl_ctx->current_time_cb = CurrentTimeCallback;
  382. SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
  383. return ssl_ctx;
  384. }
  385. // RetryAsync is called after a failed operation on |ssl| with return code
  386. // |ret|. If the operation should be retried, it simulates one asynchronous
  387. // event and returns true. Otherwise it returns false.
  388. static bool RetryAsync(SSL *ssl, int ret) {
  389. // No error; don't retry.
  390. if (ret >= 0) {
  391. return false;
  392. }
  393. TestState *test_state = GetTestState(ssl);
  394. if (test_state->clock_delta.tv_usec != 0 ||
  395. test_state->clock_delta.tv_sec != 0) {
  396. // Process the timeout and retry.
  397. test_state->clock.tv_usec += test_state->clock_delta.tv_usec;
  398. test_state->clock.tv_sec += test_state->clock.tv_usec / 1000000;
  399. test_state->clock.tv_usec %= 1000000;
  400. test_state->clock.tv_sec += test_state->clock_delta.tv_sec;
  401. memset(&test_state->clock_delta, 0, sizeof(test_state->clock_delta));
  402. if (DTLSv1_handle_timeout(ssl) < 0) {
  403. fprintf(stderr, "Error retransmitting.\n");
  404. return false;
  405. }
  406. return true;
  407. }
  408. // See if we needed to read or write more. If so, allow one byte through on
  409. // the appropriate end to maximally stress the state machine.
  410. switch (SSL_get_error(ssl, ret)) {
  411. case SSL_ERROR_WANT_READ:
  412. AsyncBioAllowRead(test_state->async_bio, 1);
  413. return true;
  414. case SSL_ERROR_WANT_WRITE:
  415. AsyncBioAllowWrite(test_state->async_bio, 1);
  416. return true;
  417. case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
  418. ScopedEVP_PKEY pkey = LoadPrivateKey(GetConfigPtr(ssl)->send_channel_id);
  419. if (!pkey) {
  420. return false;
  421. }
  422. test_state->channel_id = std::move(pkey);
  423. return true;
  424. }
  425. case SSL_ERROR_WANT_X509_LOOKUP:
  426. test_state->cert_ready = true;
  427. return true;
  428. case SSL_ERROR_PENDING_SESSION:
  429. test_state->session = std::move(test_state->pending_session);
  430. return true;
  431. case SSL_ERROR_PENDING_CERTIFICATE:
  432. // The handshake will resume without a second call to the early callback.
  433. return InstallCertificate(ssl);
  434. default:
  435. return false;
  436. }
  437. }
  438. // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
  439. // the result value of the final |SSL_read| call.
  440. static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
  441. const TestConfig *config = GetConfigPtr(ssl);
  442. int ret;
  443. do {
  444. ret = SSL_read(ssl, out, max_out);
  445. } while (config->async && RetryAsync(ssl, ret));
  446. return ret;
  447. }
  448. // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
  449. // operations. It returns the result of the final |SSL_write| call.
  450. static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
  451. const TestConfig *config = GetConfigPtr(ssl);
  452. int ret;
  453. do {
  454. ret = SSL_write(ssl, in, in_len);
  455. if (ret > 0) {
  456. in += ret;
  457. in_len -= ret;
  458. }
  459. } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
  460. return ret;
  461. }
  462. // DoExchange runs a test SSL exchange against the peer. On success, it returns
  463. // true and sets |*out_session| to the negotiated SSL session. If the test is a
  464. // resumption attempt, |is_resume| is true and |session| is the session from the
  465. // previous exchange.
  466. static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx,
  467. const TestConfig *config, bool is_resume,
  468. SSL_SESSION *session) {
  469. ScopedSSL ssl(SSL_new(ssl_ctx));
  470. if (!ssl) {
  471. return false;
  472. }
  473. if (!SetConfigPtr(ssl.get(), config) ||
  474. !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
  475. return false;
  476. }
  477. if (config->fallback_scsv &&
  478. !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
  479. return false;
  480. }
  481. if (!config->use_early_callback) {
  482. if (config->async) {
  483. // TODO(davidben): Also test |s->ctx->client_cert_cb| on the client.
  484. SSL_set_cert_cb(ssl.get(), CertCallback, NULL);
  485. } else if (!InstallCertificate(ssl.get())) {
  486. return false;
  487. }
  488. }
  489. if (config->require_any_client_certificate) {
  490. SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  491. SkipVerify);
  492. }
  493. if (config->false_start) {
  494. SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
  495. }
  496. if (config->cbc_record_splitting) {
  497. SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
  498. }
  499. if (config->partial_write) {
  500. SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
  501. }
  502. if (config->no_tls12) {
  503. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
  504. }
  505. if (config->no_tls11) {
  506. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
  507. }
  508. if (config->no_tls1) {
  509. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
  510. }
  511. if (config->no_ssl3) {
  512. SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
  513. }
  514. if (config->tls_d5_bug) {
  515. SSL_set_options(ssl.get(), SSL_OP_TLS_D5_BUG);
  516. }
  517. if (config->allow_unsafe_legacy_renegotiation) {
  518. SSL_set_options(ssl.get(), SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
  519. }
  520. if (config->no_legacy_server_connect) {
  521. SSL_clear_options(ssl.get(), SSL_OP_LEGACY_SERVER_CONNECT);
  522. }
  523. if (!config->expected_channel_id.empty()) {
  524. SSL_enable_tls_channel_id(ssl.get());
  525. }
  526. if (!config->send_channel_id.empty()) {
  527. SSL_enable_tls_channel_id(ssl.get());
  528. if (!config->async) {
  529. // The async case will be supplied by |ChannelIdCallback|.
  530. ScopedEVP_PKEY pkey = LoadPrivateKey(config->send_channel_id);
  531. if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
  532. return false;
  533. }
  534. }
  535. }
  536. if (!config->host_name.empty() &&
  537. !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
  538. return false;
  539. }
  540. if (!config->advertise_alpn.empty() &&
  541. SSL_set_alpn_protos(ssl.get(),
  542. (const uint8_t *)config->advertise_alpn.data(),
  543. config->advertise_alpn.size()) != 0) {
  544. return false;
  545. }
  546. if (!config->psk.empty()) {
  547. SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
  548. SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
  549. }
  550. if (!config->psk_identity.empty() &&
  551. !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
  552. return false;
  553. }
  554. if (!config->srtp_profiles.empty() &&
  555. !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
  556. return false;
  557. }
  558. if (config->enable_ocsp_stapling &&
  559. !SSL_enable_ocsp_stapling(ssl.get())) {
  560. return false;
  561. }
  562. if (config->enable_signed_cert_timestamps &&
  563. !SSL_enable_signed_cert_timestamps(ssl.get())) {
  564. return false;
  565. }
  566. SSL_enable_fastradio_padding(ssl.get(), config->fastradio_padding);
  567. if (config->min_version != 0) {
  568. SSL_set_min_version(ssl.get(), (uint16_t)config->min_version);
  569. }
  570. if (config->max_version != 0) {
  571. SSL_set_max_version(ssl.get(), (uint16_t)config->max_version);
  572. }
  573. if (config->mtu != 0) {
  574. SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
  575. SSL_set_mtu(ssl.get(), config->mtu);
  576. }
  577. if (config->install_ddos_callback) {
  578. SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
  579. }
  580. if (!config->cipher.empty() &&
  581. !SSL_set_cipher_list(ssl.get(), config->cipher.c_str())) {
  582. return false;
  583. }
  584. if (!config->reject_peer_renegotiations) {
  585. /* Renegotiations are disabled by default. */
  586. SSL_set_reject_peer_renegotiations(ssl.get(), 0);
  587. }
  588. int sock = Connect(config->port);
  589. if (sock == -1) {
  590. return false;
  591. }
  592. SocketCloser closer(sock);
  593. ScopedBIO bio(BIO_new_socket(sock, BIO_NOCLOSE));
  594. if (!bio) {
  595. return false;
  596. }
  597. if (config->is_dtls) {
  598. ScopedBIO packeted =
  599. PacketedBioCreate(&GetTestState(ssl.get())->clock_delta);
  600. BIO_push(packeted.get(), bio.release());
  601. bio = std::move(packeted);
  602. }
  603. if (config->async) {
  604. ScopedBIO async_scoped =
  605. config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
  606. BIO_push(async_scoped.get(), bio.release());
  607. GetTestState(ssl.get())->async_bio = async_scoped.get();
  608. bio = std::move(async_scoped);
  609. }
  610. SSL_set_bio(ssl.get(), bio.get(), bio.get());
  611. bio.release(); // SSL_set_bio takes ownership.
  612. if (session != NULL) {
  613. if (!config->is_server) {
  614. if (SSL_set_session(ssl.get(), session) != 1) {
  615. return false;
  616. }
  617. } else if (config->async) {
  618. // The internal session cache is disabled, so install the session
  619. // manually.
  620. GetTestState(ssl.get())->pending_session.reset(
  621. SSL_SESSION_up_ref(session));
  622. }
  623. }
  624. if (SSL_get_current_cipher(ssl.get()) != nullptr) {
  625. fprintf(stderr, "non-null cipher before handshake\n");
  626. return false;
  627. }
  628. int ret;
  629. if (config->implicit_handshake) {
  630. if (config->is_server) {
  631. SSL_set_accept_state(ssl.get());
  632. } else {
  633. SSL_set_connect_state(ssl.get());
  634. }
  635. } else {
  636. do {
  637. if (config->is_server) {
  638. ret = SSL_accept(ssl.get());
  639. } else {
  640. ret = SSL_connect(ssl.get());
  641. }
  642. } while (config->async && RetryAsync(ssl.get(), ret));
  643. if (ret != 1) {
  644. return false;
  645. }
  646. if (SSL_get_current_cipher(ssl.get()) == nullptr) {
  647. fprintf(stderr, "null cipher after handshake\n");
  648. return false;
  649. }
  650. if (is_resume &&
  651. (!!SSL_session_reused(ssl.get()) == config->expect_session_miss)) {
  652. fprintf(stderr, "session was%s reused\n",
  653. SSL_session_reused(ssl.get()) ? "" : " not");
  654. return false;
  655. }
  656. bool expect_handshake_done = is_resume || !config->false_start;
  657. if (expect_handshake_done != GetTestState(ssl.get())->handshake_done) {
  658. fprintf(stderr, "handshake was%s completed\n",
  659. GetTestState(ssl.get())->handshake_done ? "" : " not");
  660. return false;
  661. }
  662. if (config->is_server && !GetTestState(ssl.get())->early_callback_called) {
  663. fprintf(stderr, "early callback not called\n");
  664. return false;
  665. }
  666. if (!config->expected_server_name.empty()) {
  667. const char *server_name =
  668. SSL_get_servername(ssl.get(), TLSEXT_NAMETYPE_host_name);
  669. if (server_name != config->expected_server_name) {
  670. fprintf(stderr, "servername mismatch (got %s; want %s)\n",
  671. server_name, config->expected_server_name.c_str());
  672. return false;
  673. }
  674. }
  675. if (!config->expected_certificate_types.empty()) {
  676. uint8_t *certificate_types;
  677. int num_certificate_types =
  678. SSL_get0_certificate_types(ssl.get(), &certificate_types);
  679. if (num_certificate_types !=
  680. (int)config->expected_certificate_types.size() ||
  681. memcmp(certificate_types,
  682. config->expected_certificate_types.data(),
  683. num_certificate_types) != 0) {
  684. fprintf(stderr, "certificate types mismatch\n");
  685. return false;
  686. }
  687. }
  688. if (!config->expected_next_proto.empty()) {
  689. const uint8_t *next_proto;
  690. unsigned next_proto_len;
  691. SSL_get0_next_proto_negotiated(ssl.get(), &next_proto, &next_proto_len);
  692. if (next_proto_len != config->expected_next_proto.size() ||
  693. memcmp(next_proto, config->expected_next_proto.data(),
  694. next_proto_len) != 0) {
  695. fprintf(stderr, "negotiated next proto mismatch\n");
  696. return false;
  697. }
  698. }
  699. if (!config->expected_alpn.empty()) {
  700. const uint8_t *alpn_proto;
  701. unsigned alpn_proto_len;
  702. SSL_get0_alpn_selected(ssl.get(), &alpn_proto, &alpn_proto_len);
  703. if (alpn_proto_len != config->expected_alpn.size() ||
  704. memcmp(alpn_proto, config->expected_alpn.data(),
  705. alpn_proto_len) != 0) {
  706. fprintf(stderr, "negotiated alpn proto mismatch\n");
  707. return false;
  708. }
  709. }
  710. if (!config->expected_channel_id.empty()) {
  711. uint8_t channel_id[64];
  712. if (!SSL_get_tls_channel_id(ssl.get(), channel_id, sizeof(channel_id))) {
  713. fprintf(stderr, "no channel id negotiated\n");
  714. return false;
  715. }
  716. if (config->expected_channel_id.size() != 64 ||
  717. memcmp(config->expected_channel_id.data(),
  718. channel_id, 64) != 0) {
  719. fprintf(stderr, "channel id mismatch\n");
  720. return false;
  721. }
  722. }
  723. if (config->expect_extended_master_secret) {
  724. if (!ssl->session->extended_master_secret) {
  725. fprintf(stderr, "No EMS for session when expected");
  726. return false;
  727. }
  728. }
  729. if (!config->expected_ocsp_response.empty()) {
  730. const uint8_t *data;
  731. size_t len;
  732. SSL_get0_ocsp_response(ssl.get(), &data, &len);
  733. if (config->expected_ocsp_response.size() != len ||
  734. memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
  735. fprintf(stderr, "OCSP response mismatch\n");
  736. return false;
  737. }
  738. }
  739. if (!config->expected_signed_cert_timestamps.empty()) {
  740. const uint8_t *data;
  741. size_t len;
  742. SSL_get0_signed_cert_timestamp_list(ssl.get(), &data, &len);
  743. if (config->expected_signed_cert_timestamps.size() != len ||
  744. memcmp(config->expected_signed_cert_timestamps.data(),
  745. data, len) != 0) {
  746. fprintf(stderr, "SCT list mismatch\n");
  747. return false;
  748. }
  749. }
  750. }
  751. if (config->renegotiate) {
  752. if (config->async) {
  753. fprintf(stderr, "-renegotiate is not supported with -async.\n");
  754. return false;
  755. }
  756. if (config->implicit_handshake) {
  757. fprintf(stderr, "-renegotiate is not supported with -implicit-handshake.\n");
  758. return false;
  759. }
  760. SSL_renegotiate(ssl.get());
  761. ret = SSL_do_handshake(ssl.get());
  762. if (ret != 1) {
  763. return false;
  764. }
  765. SSL_set_state(ssl.get(), SSL_ST_ACCEPT);
  766. ret = SSL_do_handshake(ssl.get());
  767. if (ret != 1) {
  768. return false;
  769. }
  770. }
  771. if (config->export_keying_material > 0) {
  772. std::vector<uint8_t> result(
  773. static_cast<size_t>(config->export_keying_material));
  774. if (!SSL_export_keying_material(
  775. ssl.get(), result.data(), result.size(),
  776. config->export_label.data(), config->export_label.size(),
  777. reinterpret_cast<const uint8_t*>(config->export_context.data()),
  778. config->export_context.size(), config->use_export_context)) {
  779. fprintf(stderr, "failed to export keying material\n");
  780. return false;
  781. }
  782. if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
  783. return false;
  784. }
  785. }
  786. if (config->write_different_record_sizes) {
  787. if (config->is_dtls) {
  788. fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
  789. return false;
  790. }
  791. // This mode writes a number of different record sizes in an attempt to
  792. // trip up the CBC record splitting code.
  793. uint8_t buf[32769];
  794. memset(buf, 0x42, sizeof(buf));
  795. static const size_t kRecordSizes[] = {
  796. 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
  797. for (size_t i = 0; i < sizeof(kRecordSizes) / sizeof(kRecordSizes[0]);
  798. i++) {
  799. const size_t len = kRecordSizes[i];
  800. if (len > sizeof(buf)) {
  801. fprintf(stderr, "Bad kRecordSizes value.\n");
  802. return false;
  803. }
  804. if (WriteAll(ssl.get(), buf, len) < 0) {
  805. return false;
  806. }
  807. }
  808. } else {
  809. if (config->shim_writes_first) {
  810. if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
  811. 5) < 0) {
  812. return false;
  813. }
  814. }
  815. for (;;) {
  816. uint8_t buf[512];
  817. int n = DoRead(ssl.get(), buf, sizeof(buf));
  818. int err = SSL_get_error(ssl.get(), n);
  819. if (err == SSL_ERROR_ZERO_RETURN ||
  820. (n == 0 && err == SSL_ERROR_SYSCALL)) {
  821. if (n != 0) {
  822. fprintf(stderr, "Invalid SSL_get_error output\n");
  823. return false;
  824. }
  825. // Accept shutdowns with or without close_notify.
  826. // TODO(davidben): Write tests which distinguish these two cases.
  827. break;
  828. } else if (err != SSL_ERROR_NONE) {
  829. if (n > 0) {
  830. fprintf(stderr, "Invalid SSL_get_error output\n");
  831. return false;
  832. }
  833. return false;
  834. }
  835. // Successfully read data.
  836. if (n <= 0) {
  837. fprintf(stderr, "Invalid SSL_get_error output\n");
  838. return false;
  839. }
  840. // After a successful read, with or without False Start, the handshake
  841. // must be complete.
  842. if (!GetTestState(ssl.get())->handshake_done) {
  843. fprintf(stderr, "handshake was not completed after SSL_read\n");
  844. return false;
  845. }
  846. for (int i = 0; i < n; i++) {
  847. buf[i] ^= 0xff;
  848. }
  849. if (WriteAll(ssl.get(), buf, n) < 0) {
  850. return false;
  851. }
  852. }
  853. }
  854. if (out_session) {
  855. out_session->reset(SSL_get1_session(ssl.get()));
  856. }
  857. SSL_shutdown(ssl.get());
  858. return true;
  859. }
  860. int main(int argc, char **argv) {
  861. #if defined(OPENSSL_WINDOWS)
  862. /* Initialize Winsock. */
  863. WORD wsa_version = MAKEWORD(2, 2);
  864. WSADATA wsa_data;
  865. int wsa_err = WSAStartup(wsa_version, &wsa_data);
  866. if (wsa_err != 0) {
  867. fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
  868. return 1;
  869. }
  870. if (wsa_data.wVersion != wsa_version) {
  871. fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
  872. return 1;
  873. }
  874. #else
  875. signal(SIGPIPE, SIG_IGN);
  876. #endif
  877. if (!SSL_library_init()) {
  878. return 1;
  879. }
  880. g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  881. g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
  882. if (g_config_index < 0 || g_state_index < 0) {
  883. return 1;
  884. }
  885. TestConfig config;
  886. if (!ParseConfig(argc - 1, argv + 1, &config)) {
  887. return Usage(argv[0]);
  888. }
  889. ScopedSSL_CTX ssl_ctx = SetupCtx(&config);
  890. if (!ssl_ctx) {
  891. ERR_print_errors_fp(stderr);
  892. return 1;
  893. }
  894. ScopedSSL_SESSION session;
  895. if (!DoExchange(&session, ssl_ctx.get(), &config, false /* is_resume */,
  896. NULL /* session */)) {
  897. ERR_print_errors_fp(stderr);
  898. return 1;
  899. }
  900. if (config.resume &&
  901. !DoExchange(NULL, ssl_ctx.get(), &config, true /* is_resume */,
  902. session.get())) {
  903. ERR_print_errors_fp(stderr);
  904. return 1;
  905. }
  906. return 0;
  907. }