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

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