Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

1192 рядки
36 KiB

  1. /* Copyright (c) 2014, Google Inc.
  2. *
  3. * Permission to use, copy, modify, and/or distribute this software for any
  4. * purpose with or without fee is hereby granted, provided that the above
  5. * copyright notice and this permission notice appear in all copies.
  6. *
  7. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  10. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  12. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  14. #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/cipher.h>
  37. #include <openssl/err.h>
  38. #include <openssl/hmac.h>
  39. #include <openssl/rand.h>
  40. #include <openssl/ssl.h>
  41. #include <memory>
  42. #include <vector>
  43. #include "../../crypto/test/scoped_types.h"
  44. #include "async_bio.h"
  45. #include "packeted_bio.h"
  46. #include "scoped_types.h"
  47. #include "test_config.h"
  48. #if !defined(OPENSSL_WINDOWS)
  49. static int closesocket(int sock) {
  50. return close(sock);
  51. }
  52. static void PrintSocketError(const char *func) {
  53. perror(func);
  54. }
  55. #else
  56. static void PrintSocketError(const char *func) {
  57. fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
  58. }
  59. #endif
  60. static int Usage(const char *program) {
  61. fprintf(stderr, "Usage: %s [flags...]\n", program);
  62. return 1;
  63. }
  64. struct TestState {
  65. TestState() {
  66. // MSVC cannot initialize these inline.
  67. memset(&clock, 0, sizeof(clock));
  68. memset(&clock_delta, 0, sizeof(clock_delta));
  69. }
  70. // async_bio is async BIO which pauses reads and writes.
  71. BIO *async_bio = nullptr;
  72. // clock is the current time for the SSL connection.
  73. timeval clock;
  74. // clock_delta is how far the clock advanced in the most recent failed
  75. // |BIO_read|.
  76. timeval clock_delta;
  77. ScopedEVP_PKEY channel_id;
  78. bool cert_ready = false;
  79. ScopedSSL_SESSION session;
  80. ScopedSSL_SESSION pending_session;
  81. bool early_callback_called = false;
  82. bool handshake_done = false;
  83. // private_key is the underlying private key used when testing custom keys.
  84. ScopedEVP_PKEY private_key;
  85. std::vector<uint8_t> signature;
  86. // signature_retries is the number of times an asynchronous sign operation has
  87. // been retried.
  88. unsigned signature_retries = 0;
  89. bool got_new_session = false;
  90. };
  91. static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
  92. int index, long argl, void *argp) {
  93. delete ((TestState *)ptr);
  94. }
  95. static int g_config_index = 0;
  96. static int g_state_index = 0;
  97. static bool SetConfigPtr(SSL *ssl, const TestConfig *config) {
  98. return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
  99. }
  100. static const TestConfig *GetConfigPtr(const SSL *ssl) {
  101. return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
  102. }
  103. static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> async) {
  104. if (SSL_set_ex_data(ssl, g_state_index, (void *)async.get()) == 1) {
  105. async.release();
  106. return true;
  107. }
  108. return false;
  109. }
  110. static TestState *GetTestState(const SSL *ssl) {
  111. return (TestState *)SSL_get_ex_data(ssl, g_state_index);
  112. }
  113. static ScopedEVP_PKEY LoadPrivateKey(const std::string &file) {
  114. ScopedBIO bio(BIO_new(BIO_s_file()));
  115. if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
  116. return nullptr;
  117. }
  118. ScopedEVP_PKEY pkey(PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
  119. return pkey;
  120. }
  121. static int AsyncPrivateKeyType(SSL *ssl) {
  122. return EVP_PKEY_id(GetTestState(ssl)->private_key.get());
  123. }
  124. static int AsyncPrivateKeySupportsDigest(SSL *ssl, const EVP_MD *md) {
  125. return EVP_PKEY_supports_digest(GetTestState(ssl)->private_key.get(), md);
  126. }
  127. static size_t AsyncPrivateKeyMaxSignatureLen(SSL *ssl) {
  128. return EVP_PKEY_size(GetTestState(ssl)->private_key.get());
  129. }
  130. static ssl_private_key_result_t AsyncPrivateKeySign(
  131. SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
  132. const EVP_MD *md, const uint8_t *in, size_t in_len) {
  133. TestState *test_state = GetTestState(ssl);
  134. if (!test_state->signature.empty()) {
  135. fprintf(stderr, "AsyncPrivateKeySign called with operation pending.\n");
  136. abort();
  137. }
  138. ScopedEVP_PKEY_CTX ctx(EVP_PKEY_CTX_new(test_state->private_key.get(),
  139. nullptr));
  140. if (!ctx) {
  141. return ssl_private_key_failure;
  142. }
  143. // Write the signature into |test_state|.
  144. size_t len = 0;
  145. if (!EVP_PKEY_sign_init(ctx.get()) ||
  146. !EVP_PKEY_CTX_set_signature_md(ctx.get(), md) ||
  147. !EVP_PKEY_sign(ctx.get(), nullptr, &len, in, in_len)) {
  148. return ssl_private_key_failure;
  149. }
  150. test_state->signature.resize(len);
  151. if (!EVP_PKEY_sign(ctx.get(), bssl::vector_data(&test_state->signature), &len,
  152. in, in_len)) {
  153. return ssl_private_key_failure;
  154. }
  155. test_state->signature.resize(len);
  156. // The signature will be released asynchronously in |AsyncPrivateKeySignComplete|.
  157. return ssl_private_key_retry;
  158. }
  159. static ssl_private_key_result_t AsyncPrivateKeySignComplete(
  160. SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
  161. TestState *test_state = GetTestState(ssl);
  162. if (test_state->signature.empty()) {
  163. fprintf(stderr,
  164. "AsyncPrivateKeySignComplete called without operation pending.\n");
  165. abort();
  166. }
  167. if (test_state->signature_retries < 2) {
  168. // Only return the signature on the second attempt, to test both incomplete
  169. // |sign| and |sign_complete|.
  170. return ssl_private_key_retry;
  171. }
  172. if (max_out < test_state->signature.size()) {
  173. fprintf(stderr, "Output buffer too small.\n");
  174. return ssl_private_key_failure;
  175. }
  176. memcpy(out, bssl::vector_data(&test_state->signature),
  177. test_state->signature.size());
  178. test_state->signature.clear();
  179. test_state->signature_retries = 0;
  180. return ssl_private_key_success;
  181. }
  182. static const SSL_PRIVATE_KEY_METHOD g_async_private_key_method = {
  183. AsyncPrivateKeyType,
  184. AsyncPrivateKeySupportsDigest,
  185. AsyncPrivateKeyMaxSignatureLen,
  186. AsyncPrivateKeySign,
  187. AsyncPrivateKeySignComplete,
  188. };
  189. static bool InstallCertificate(SSL *ssl) {
  190. const TestConfig *config = GetConfigPtr(ssl);
  191. TestState *test_state = GetTestState(ssl);
  192. if (!config->key_file.empty()) {
  193. if (config->use_async_private_key) {
  194. test_state->private_key = LoadPrivateKey(config->key_file.c_str());
  195. if (!test_state->private_key) {
  196. return false;
  197. }
  198. SSL_set_private_key_method(ssl, &g_async_private_key_method);
  199. } else if (!SSL_use_PrivateKey_file(ssl, config->key_file.c_str(),
  200. SSL_FILETYPE_PEM)) {
  201. return false;
  202. }
  203. }
  204. if (!config->cert_file.empty() &&
  205. !SSL_use_certificate_file(ssl, config->cert_file.c_str(),
  206. SSL_FILETYPE_PEM)) {
  207. return false;
  208. }
  209. return true;
  210. }
  211. static int SelectCertificateCallback(const struct ssl_early_callback_ctx *ctx) {
  212. const TestConfig *config = GetConfigPtr(ctx->ssl);
  213. GetTestState(ctx->ssl)->early_callback_called = true;
  214. if (!config->expected_server_name.empty()) {
  215. const uint8_t *extension_data;
  216. size_t extension_len;
  217. CBS extension, server_name_list, host_name;
  218. uint8_t name_type;
  219. if (!SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
  220. &extension_data,
  221. &extension_len)) {
  222. fprintf(stderr, "Could not find server_name extension.\n");
  223. return -1;
  224. }
  225. CBS_init(&extension, extension_data, extension_len);
  226. if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
  227. CBS_len(&extension) != 0 ||
  228. !CBS_get_u8(&server_name_list, &name_type) ||
  229. name_type != TLSEXT_NAMETYPE_host_name ||
  230. !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
  231. CBS_len(&server_name_list) != 0) {
  232. fprintf(stderr, "Could not decode server_name extension.\n");
  233. return -1;
  234. }
  235. if (!CBS_mem_equal(&host_name,
  236. (const uint8_t*)config->expected_server_name.data(),
  237. config->expected_server_name.size())) {
  238. fprintf(stderr, "Server name mismatch.\n");
  239. }
  240. }
  241. if (config->fail_early_callback) {
  242. return -1;
  243. }
  244. // Install the certificate in the early callback.
  245. if (config->use_early_callback) {
  246. if (config->async) {
  247. // Install the certificate asynchronously.
  248. return 0;
  249. }
  250. if (!InstallCertificate(ctx->ssl)) {
  251. return -1;
  252. }
  253. }
  254. return 1;
  255. }
  256. static int SkipVerify(int preverify_ok, X509_STORE_CTX *store_ctx) {
  257. return 1;
  258. }
  259. static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
  260. unsigned int *out_len, void *arg) {
  261. const TestConfig *config = GetConfigPtr(ssl);
  262. if (config->advertise_npn.empty()) {
  263. return SSL_TLSEXT_ERR_NOACK;
  264. }
  265. *out = (const uint8_t*)config->advertise_npn.data();
  266. *out_len = config->advertise_npn.size();
  267. return SSL_TLSEXT_ERR_OK;
  268. }
  269. static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
  270. const uint8_t* in, unsigned inlen, void* arg) {
  271. const TestConfig *config = GetConfigPtr(ssl);
  272. if (config->select_next_proto.empty()) {
  273. return SSL_TLSEXT_ERR_NOACK;
  274. }
  275. *out = (uint8_t*)config->select_next_proto.data();
  276. *outlen = config->select_next_proto.size();
  277. return SSL_TLSEXT_ERR_OK;
  278. }
  279. static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
  280. const uint8_t* in, unsigned inlen, void* arg) {
  281. const TestConfig *config = GetConfigPtr(ssl);
  282. if (config->select_alpn.empty()) {
  283. return SSL_TLSEXT_ERR_NOACK;
  284. }
  285. if (!config->expected_advertised_alpn.empty() &&
  286. (config->expected_advertised_alpn.size() != inlen ||
  287. memcmp(config->expected_advertised_alpn.data(),
  288. in, inlen) != 0)) {
  289. fprintf(stderr, "bad ALPN select callback inputs\n");
  290. exit(1);
  291. }
  292. *out = (const uint8_t*)config->select_alpn.data();
  293. *outlen = config->select_alpn.size();
  294. return SSL_TLSEXT_ERR_OK;
  295. }
  296. static unsigned PskClientCallback(SSL *ssl, const char *hint,
  297. char *out_identity,
  298. unsigned max_identity_len,
  299. uint8_t *out_psk, unsigned max_psk_len) {
  300. const TestConfig *config = GetConfigPtr(ssl);
  301. if (strcmp(hint ? hint : "", config->psk_identity.c_str()) != 0) {
  302. fprintf(stderr, "Server PSK hint did not match.\n");
  303. return 0;
  304. }
  305. // Account for the trailing '\0' for the identity.
  306. if (config->psk_identity.size() >= max_identity_len ||
  307. config->psk.size() > max_psk_len) {
  308. fprintf(stderr, "PSK buffers too small\n");
  309. return 0;
  310. }
  311. BUF_strlcpy(out_identity, config->psk_identity.c_str(),
  312. max_identity_len);
  313. memcpy(out_psk, config->psk.data(), config->psk.size());
  314. return config->psk.size();
  315. }
  316. static unsigned PskServerCallback(SSL *ssl, const char *identity,
  317. uint8_t *out_psk, unsigned max_psk_len) {
  318. const TestConfig *config = GetConfigPtr(ssl);
  319. if (strcmp(identity, config->psk_identity.c_str()) != 0) {
  320. fprintf(stderr, "Client PSK identity did not match.\n");
  321. return 0;
  322. }
  323. if (config->psk.size() > max_psk_len) {
  324. fprintf(stderr, "PSK buffers too small\n");
  325. return 0;
  326. }
  327. memcpy(out_psk, config->psk.data(), config->psk.size());
  328. return config->psk.size();
  329. }
  330. static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
  331. *out_clock = GetTestState(ssl)->clock;
  332. }
  333. static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
  334. *out_pkey = GetTestState(ssl)->channel_id.release();
  335. }
  336. static int CertCallback(SSL *ssl, void *arg) {
  337. if (!GetTestState(ssl)->cert_ready) {
  338. return -1;
  339. }
  340. if (!InstallCertificate(ssl)) {
  341. return 0;
  342. }
  343. return 1;
  344. }
  345. static SSL_SESSION *GetSessionCallback(SSL *ssl, uint8_t *data, int len,
  346. int *copy) {
  347. TestState *async_state = GetTestState(ssl);
  348. if (async_state->session) {
  349. *copy = 0;
  350. return async_state->session.release();
  351. } else if (async_state->pending_session) {
  352. return SSL_magic_pending_session_ptr();
  353. } else {
  354. return NULL;
  355. }
  356. }
  357. static int DDoSCallback(const struct ssl_early_callback_ctx *early_context) {
  358. const TestConfig *config = GetConfigPtr(early_context->ssl);
  359. static int callback_num = 0;
  360. callback_num++;
  361. if (config->fail_ddos_callback ||
  362. (config->fail_second_ddos_callback && callback_num == 2)) {
  363. return 0;
  364. }
  365. return 1;
  366. }
  367. static void InfoCallback(const SSL *ssl, int type, int val) {
  368. if (type == SSL_CB_HANDSHAKE_DONE) {
  369. if (GetConfigPtr(ssl)->handshake_never_done) {
  370. fprintf(stderr, "handshake completed\n");
  371. // Abort before any expected error code is printed, to ensure the overall
  372. // test fails.
  373. abort();
  374. }
  375. GetTestState(ssl)->handshake_done = true;
  376. }
  377. }
  378. static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
  379. GetTestState(ssl)->got_new_session = true;
  380. // BoringSSL passes a reference to |session|.
  381. SSL_SESSION_free(session);
  382. return 1;
  383. }
  384. static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
  385. EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
  386. int encrypt) {
  387. // This is just test code, so use the all-zeros key.
  388. static const uint8_t kZeros[16] = {0};
  389. if (encrypt) {
  390. memcpy(key_name, kZeros, sizeof(kZeros));
  391. RAND_bytes(iv, 16);
  392. } else if (memcmp(key_name, kZeros, 16) != 0) {
  393. return 0;
  394. }
  395. if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
  396. !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
  397. return -1;
  398. }
  399. if (!encrypt) {
  400. return GetConfigPtr(ssl)->renew_ticket ? 2 : 1;
  401. }
  402. return 1;
  403. }
  404. // Connect returns a new socket connected to localhost on |port| or -1 on
  405. // error.
  406. static int Connect(uint16_t port) {
  407. int sock = socket(AF_INET, SOCK_STREAM, 0);
  408. if (sock == -1) {
  409. PrintSocketError("socket");
  410. return -1;
  411. }
  412. int nodelay = 1;
  413. if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  414. reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
  415. PrintSocketError("setsockopt");
  416. closesocket(sock);
  417. return -1;
  418. }
  419. sockaddr_in sin;
  420. memset(&sin, 0, sizeof(sin));
  421. sin.sin_family = AF_INET;
  422. sin.sin_port = htons(port);
  423. if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
  424. PrintSocketError("inet_pton");
  425. closesocket(sock);
  426. return -1;
  427. }
  428. if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
  429. sizeof(sin)) != 0) {
  430. PrintSocketError("connect");
  431. closesocket(sock);
  432. return -1;
  433. }
  434. return sock;
  435. }
  436. class SocketCloser {
  437. public:
  438. explicit SocketCloser(int sock) : sock_(sock) {}
  439. ~SocketCloser() {
  440. // Half-close and drain the socket before releasing it. This seems to be
  441. // necessary for graceful shutdown on Windows. It will also avoid write
  442. // failures in the test runner.
  443. #if defined(OPENSSL_WINDOWS)
  444. shutdown(sock_, SD_SEND);
  445. #else
  446. shutdown(sock_, SHUT_WR);
  447. #endif
  448. while (true) {
  449. char buf[1024];
  450. if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
  451. break;
  452. }
  453. }
  454. closesocket(sock_);
  455. }
  456. private:
  457. const int sock_;
  458. };
  459. static ScopedSSL_CTX SetupCtx(const TestConfig *config) {
  460. ScopedSSL_CTX ssl_ctx(SSL_CTX_new(
  461. config->is_dtls ? DTLS_method() : TLS_method()));
  462. if (!ssl_ctx) {
  463. return nullptr;
  464. }
  465. if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), "ALL")) {
  466. return nullptr;
  467. }
  468. ScopedDH dh(DH_get_2048_256(NULL));
  469. if (!dh || !SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
  470. return nullptr;
  471. }
  472. if (config->async && config->is_server) {
  473. // Disable the internal session cache. To test asynchronous session lookup,
  474. // we use an external session cache.
  475. SSL_CTX_set_session_cache_mode(
  476. ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
  477. SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
  478. } else {
  479. SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
  480. }
  481. ssl_ctx->select_certificate_cb = SelectCertificateCallback;
  482. SSL_CTX_set_next_protos_advertised_cb(
  483. ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
  484. if (!config->select_next_proto.empty()) {
  485. SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
  486. NULL);
  487. }
  488. if (!config->select_alpn.empty()) {
  489. SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
  490. }
  491. SSL_CTX_enable_tls_channel_id(ssl_ctx.get());
  492. SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
  493. ssl_ctx->current_time_cb = CurrentTimeCallback;
  494. SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
  495. SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
  496. if (config->use_ticket_callback) {
  497. SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
  498. }
  499. return ssl_ctx;
  500. }
  501. // RetryAsync is called after a failed operation on |ssl| with return code
  502. // |ret|. If the operation should be retried, it simulates one asynchronous
  503. // event and returns true. Otherwise it returns false.
  504. static bool RetryAsync(SSL *ssl, int ret) {
  505. // No error; don't retry.
  506. if (ret >= 0) {
  507. return false;
  508. }
  509. TestState *test_state = GetTestState(ssl);
  510. if (test_state->clock_delta.tv_usec != 0 ||
  511. test_state->clock_delta.tv_sec != 0) {
  512. // Process the timeout and retry.
  513. test_state->clock.tv_usec += test_state->clock_delta.tv_usec;
  514. test_state->clock.tv_sec += test_state->clock.tv_usec / 1000000;
  515. test_state->clock.tv_usec %= 1000000;
  516. test_state->clock.tv_sec += test_state->clock_delta.tv_sec;
  517. memset(&test_state->clock_delta, 0, sizeof(test_state->clock_delta));
  518. if (DTLSv1_handle_timeout(ssl) < 0) {
  519. fprintf(stderr, "Error retransmitting.\n");
  520. return false;
  521. }
  522. return true;
  523. }
  524. // See if we needed to read or write more. If so, allow one byte through on
  525. // the appropriate end to maximally stress the state machine.
  526. switch (SSL_get_error(ssl, ret)) {
  527. case SSL_ERROR_WANT_READ:
  528. AsyncBioAllowRead(test_state->async_bio, 1);
  529. return true;
  530. case SSL_ERROR_WANT_WRITE:
  531. AsyncBioAllowWrite(test_state->async_bio, 1);
  532. return true;
  533. case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
  534. ScopedEVP_PKEY pkey = LoadPrivateKey(GetConfigPtr(ssl)->send_channel_id);
  535. if (!pkey) {
  536. return false;
  537. }
  538. test_state->channel_id = std::move(pkey);
  539. return true;
  540. }
  541. case SSL_ERROR_WANT_X509_LOOKUP:
  542. test_state->cert_ready = true;
  543. return true;
  544. case SSL_ERROR_PENDING_SESSION:
  545. test_state->session = std::move(test_state->pending_session);
  546. return true;
  547. case SSL_ERROR_PENDING_CERTIFICATE:
  548. // The handshake will resume without a second call to the early callback.
  549. return InstallCertificate(ssl);
  550. case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
  551. test_state->signature_retries++;
  552. return true;
  553. default:
  554. return false;
  555. }
  556. }
  557. // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
  558. // the result value of the final |SSL_read| call.
  559. static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
  560. const TestConfig *config = GetConfigPtr(ssl);
  561. int ret;
  562. do {
  563. ret = SSL_read(ssl, out, max_out);
  564. } while (config->async && RetryAsync(ssl, ret));
  565. return ret;
  566. }
  567. // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
  568. // operations. It returns the result of the final |SSL_write| call.
  569. static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
  570. const TestConfig *config = GetConfigPtr(ssl);
  571. int ret;
  572. do {
  573. ret = SSL_write(ssl, in, in_len);
  574. if (ret > 0) {
  575. in += ret;
  576. in_len -= ret;
  577. }
  578. } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
  579. return ret;
  580. }
  581. // CheckHandshakeProperties checks, immediately after |ssl| completes its
  582. // initial handshake (or False Starts), whether all the properties are
  583. // consistent with the test configuration and invariants.
  584. static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
  585. const TestConfig *config = GetConfigPtr(ssl);
  586. if (SSL_get_current_cipher(ssl) == nullptr) {
  587. fprintf(stderr, "null cipher after handshake\n");
  588. return false;
  589. }
  590. if (is_resume &&
  591. (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
  592. fprintf(stderr, "session was%s reused\n",
  593. SSL_session_reused(ssl) ? "" : " not");
  594. return false;
  595. }
  596. bool expect_handshake_done = is_resume || !config->false_start;
  597. if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
  598. fprintf(stderr, "handshake was%s completed\n",
  599. GetTestState(ssl)->handshake_done ? "" : " not");
  600. return false;
  601. }
  602. if (expect_handshake_done && !config->is_server) {
  603. bool expect_new_session =
  604. !config->expect_no_session &&
  605. (!SSL_session_reused(ssl) || config->expect_ticket_renewal);
  606. if (expect_new_session != GetTestState(ssl)->got_new_session) {
  607. fprintf(stderr,
  608. "new session was%s established, but we expected the opposite\n",
  609. GetTestState(ssl)->got_new_session ? "" : " not");
  610. return false;
  611. }
  612. }
  613. if (config->is_server && !GetTestState(ssl)->early_callback_called) {
  614. fprintf(stderr, "early callback not called\n");
  615. return false;
  616. }
  617. if (!config->expected_server_name.empty()) {
  618. const char *server_name =
  619. SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  620. if (server_name != config->expected_server_name) {
  621. fprintf(stderr, "servername mismatch (got %s; want %s)\n",
  622. server_name, config->expected_server_name.c_str());
  623. return false;
  624. }
  625. }
  626. if (!config->expected_certificate_types.empty()) {
  627. uint8_t *certificate_types;
  628. int num_certificate_types =
  629. SSL_get0_certificate_types(ssl, &certificate_types);
  630. if (num_certificate_types !=
  631. (int)config->expected_certificate_types.size() ||
  632. memcmp(certificate_types,
  633. config->expected_certificate_types.data(),
  634. num_certificate_types) != 0) {
  635. fprintf(stderr, "certificate types mismatch\n");
  636. return false;
  637. }
  638. }
  639. if (!config->expected_next_proto.empty()) {
  640. const uint8_t *next_proto;
  641. unsigned next_proto_len;
  642. SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
  643. if (next_proto_len != config->expected_next_proto.size() ||
  644. memcmp(next_proto, config->expected_next_proto.data(),
  645. next_proto_len) != 0) {
  646. fprintf(stderr, "negotiated next proto mismatch\n");
  647. return false;
  648. }
  649. }
  650. if (!config->expected_alpn.empty()) {
  651. const uint8_t *alpn_proto;
  652. unsigned alpn_proto_len;
  653. SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
  654. if (alpn_proto_len != config->expected_alpn.size() ||
  655. memcmp(alpn_proto, config->expected_alpn.data(),
  656. alpn_proto_len) != 0) {
  657. fprintf(stderr, "negotiated alpn proto mismatch\n");
  658. return false;
  659. }
  660. }
  661. if (!config->expected_channel_id.empty()) {
  662. uint8_t channel_id[64];
  663. if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
  664. fprintf(stderr, "no channel id negotiated\n");
  665. return false;
  666. }
  667. if (config->expected_channel_id.size() != 64 ||
  668. memcmp(config->expected_channel_id.data(),
  669. channel_id, 64) != 0) {
  670. fprintf(stderr, "channel id mismatch\n");
  671. return false;
  672. }
  673. }
  674. if (config->expect_extended_master_secret) {
  675. if (!ssl->session->extended_master_secret) {
  676. fprintf(stderr, "No EMS for session when expected");
  677. return false;
  678. }
  679. }
  680. if (!config->expected_ocsp_response.empty()) {
  681. const uint8_t *data;
  682. size_t len;
  683. SSL_get0_ocsp_response(ssl, &data, &len);
  684. if (config->expected_ocsp_response.size() != len ||
  685. memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
  686. fprintf(stderr, "OCSP response mismatch\n");
  687. return false;
  688. }
  689. }
  690. if (!config->expected_signed_cert_timestamps.empty()) {
  691. const uint8_t *data;
  692. size_t len;
  693. SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
  694. if (config->expected_signed_cert_timestamps.size() != len ||
  695. memcmp(config->expected_signed_cert_timestamps.data(),
  696. data, len) != 0) {
  697. fprintf(stderr, "SCT list mismatch\n");
  698. return false;
  699. }
  700. }
  701. if (!config->is_server) {
  702. /* Clients should expect a peer certificate chain iff this was not a PSK
  703. * cipher suite. */
  704. if (config->psk.empty()) {
  705. if (SSL_get_peer_cert_chain(ssl) == nullptr) {
  706. fprintf(stderr, "Missing peer certificate chain!\n");
  707. return false;
  708. }
  709. } else if (SSL_get_peer_cert_chain(ssl) != nullptr) {
  710. fprintf(stderr, "Unexpected peer certificate chain!\n");
  711. return false;
  712. }
  713. }
  714. return true;
  715. }
  716. // DoExchange runs a test SSL exchange against the peer. On success, it returns
  717. // true and sets |*out_session| to the negotiated SSL session. If the test is a
  718. // resumption attempt, |is_resume| is true and |session| is the session from the
  719. // previous exchange.
  720. static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx,
  721. const TestConfig *config, bool is_resume,
  722. SSL_SESSION *session) {
  723. ScopedSSL ssl(SSL_new(ssl_ctx));
  724. if (!ssl) {
  725. return false;
  726. }
  727. if (!SetConfigPtr(ssl.get(), config) ||
  728. !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
  729. return false;
  730. }
  731. if (config->fallback_scsv &&
  732. !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
  733. return false;
  734. }
  735. if (!config->use_early_callback) {
  736. if (config->async) {
  737. // TODO(davidben): Also test |s->ctx->client_cert_cb| on the client.
  738. SSL_set_cert_cb(ssl.get(), CertCallback, NULL);
  739. } else if (!InstallCertificate(ssl.get())) {
  740. return false;
  741. }
  742. }
  743. if (config->require_any_client_certificate) {
  744. SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  745. SkipVerify);
  746. }
  747. if (config->false_start) {
  748. SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
  749. }
  750. if (config->cbc_record_splitting) {
  751. SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
  752. }
  753. if (config->partial_write) {
  754. SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
  755. }
  756. if (config->no_tls12) {
  757. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
  758. }
  759. if (config->no_tls11) {
  760. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
  761. }
  762. if (config->no_tls1) {
  763. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
  764. }
  765. if (config->no_ssl3) {
  766. SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
  767. }
  768. if (config->tls_d5_bug) {
  769. SSL_set_options(ssl.get(), SSL_OP_TLS_D5_BUG);
  770. }
  771. if (config->no_legacy_server_connect) {
  772. SSL_clear_options(ssl.get(), SSL_OP_LEGACY_SERVER_CONNECT);
  773. }
  774. if (!config->expected_channel_id.empty()) {
  775. SSL_enable_tls_channel_id(ssl.get());
  776. }
  777. if (!config->send_channel_id.empty()) {
  778. SSL_enable_tls_channel_id(ssl.get());
  779. if (!config->async) {
  780. // The async case will be supplied by |ChannelIdCallback|.
  781. ScopedEVP_PKEY pkey = LoadPrivateKey(config->send_channel_id);
  782. if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
  783. return false;
  784. }
  785. }
  786. }
  787. if (!config->host_name.empty() &&
  788. !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
  789. return false;
  790. }
  791. if (!config->advertise_alpn.empty() &&
  792. SSL_set_alpn_protos(ssl.get(),
  793. (const uint8_t *)config->advertise_alpn.data(),
  794. config->advertise_alpn.size()) != 0) {
  795. return false;
  796. }
  797. if (!config->psk.empty()) {
  798. SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
  799. SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
  800. }
  801. if (!config->psk_identity.empty() &&
  802. !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
  803. return false;
  804. }
  805. if (!config->srtp_profiles.empty() &&
  806. !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
  807. return false;
  808. }
  809. if (config->enable_ocsp_stapling &&
  810. !SSL_enable_ocsp_stapling(ssl.get())) {
  811. return false;
  812. }
  813. if (config->enable_signed_cert_timestamps &&
  814. !SSL_enable_signed_cert_timestamps(ssl.get())) {
  815. return false;
  816. }
  817. if (config->min_version != 0) {
  818. SSL_set_min_version(ssl.get(), (uint16_t)config->min_version);
  819. }
  820. if (config->max_version != 0) {
  821. SSL_set_max_version(ssl.get(), (uint16_t)config->max_version);
  822. }
  823. if (config->mtu != 0) {
  824. SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
  825. SSL_set_mtu(ssl.get(), config->mtu);
  826. }
  827. if (config->install_ddos_callback) {
  828. SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
  829. }
  830. if (!config->cipher.empty() &&
  831. !SSL_set_cipher_list(ssl.get(), config->cipher.c_str())) {
  832. return false;
  833. }
  834. if (!config->reject_peer_renegotiations) {
  835. /* Renegotiations are disabled by default. */
  836. SSL_set_reject_peer_renegotiations(ssl.get(), 0);
  837. }
  838. int sock = Connect(config->port);
  839. if (sock == -1) {
  840. return false;
  841. }
  842. SocketCloser closer(sock);
  843. ScopedBIO bio(BIO_new_socket(sock, BIO_NOCLOSE));
  844. if (!bio) {
  845. return false;
  846. }
  847. if (config->is_dtls) {
  848. ScopedBIO packeted =
  849. PacketedBioCreate(&GetTestState(ssl.get())->clock_delta);
  850. BIO_push(packeted.get(), bio.release());
  851. bio = std::move(packeted);
  852. }
  853. if (config->async) {
  854. ScopedBIO async_scoped =
  855. config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
  856. BIO_push(async_scoped.get(), bio.release());
  857. GetTestState(ssl.get())->async_bio = async_scoped.get();
  858. bio = std::move(async_scoped);
  859. }
  860. SSL_set_bio(ssl.get(), bio.get(), bio.get());
  861. bio.release(); // SSL_set_bio takes ownership.
  862. if (session != NULL) {
  863. if (!config->is_server) {
  864. if (SSL_set_session(ssl.get(), session) != 1) {
  865. return false;
  866. }
  867. } else if (config->async) {
  868. // The internal session cache is disabled, so install the session
  869. // manually.
  870. GetTestState(ssl.get())->pending_session.reset(
  871. SSL_SESSION_up_ref(session));
  872. }
  873. }
  874. if (SSL_get_current_cipher(ssl.get()) != nullptr) {
  875. fprintf(stderr, "non-null cipher before handshake\n");
  876. return false;
  877. }
  878. int ret;
  879. if (config->implicit_handshake) {
  880. if (config->is_server) {
  881. SSL_set_accept_state(ssl.get());
  882. } else {
  883. SSL_set_connect_state(ssl.get());
  884. }
  885. } else {
  886. do {
  887. if (config->is_server) {
  888. ret = SSL_accept(ssl.get());
  889. } else {
  890. ret = SSL_connect(ssl.get());
  891. }
  892. } while (config->async && RetryAsync(ssl.get(), ret));
  893. if (ret != 1 ||
  894. !CheckHandshakeProperties(ssl.get(), is_resume)) {
  895. return false;
  896. }
  897. // Reset the state to assert later that the callback isn't called in
  898. // renegotations.
  899. GetTestState(ssl.get())->got_new_session = false;
  900. }
  901. if (config->export_keying_material > 0) {
  902. std::vector<uint8_t> result(
  903. static_cast<size_t>(config->export_keying_material));
  904. if (!SSL_export_keying_material(
  905. ssl.get(), result.data(), result.size(),
  906. config->export_label.data(), config->export_label.size(),
  907. reinterpret_cast<const uint8_t*>(config->export_context.data()),
  908. config->export_context.size(), config->use_export_context)) {
  909. fprintf(stderr, "failed to export keying material\n");
  910. return false;
  911. }
  912. if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
  913. return false;
  914. }
  915. }
  916. if (config->tls_unique) {
  917. uint8_t tls_unique[16];
  918. size_t tls_unique_len;
  919. if (!SSL_get_tls_unique(ssl.get(), tls_unique, &tls_unique_len,
  920. sizeof(tls_unique))) {
  921. fprintf(stderr, "failed to get tls-unique\n");
  922. return false;
  923. }
  924. if (tls_unique_len != 12) {
  925. fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
  926. static_cast<unsigned>(tls_unique_len));
  927. return false;
  928. }
  929. if (WriteAll(ssl.get(), tls_unique, tls_unique_len) < 0) {
  930. return false;
  931. }
  932. }
  933. if (config->write_different_record_sizes) {
  934. if (config->is_dtls) {
  935. fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
  936. return false;
  937. }
  938. // This mode writes a number of different record sizes in an attempt to
  939. // trip up the CBC record splitting code.
  940. static const size_t kBufLen = 32769;
  941. std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
  942. memset(buf.get(), 0x42, kBufLen);
  943. static const size_t kRecordSizes[] = {
  944. 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
  945. for (size_t i = 0; i < sizeof(kRecordSizes) / sizeof(kRecordSizes[0]);
  946. i++) {
  947. const size_t len = kRecordSizes[i];
  948. if (len > kBufLen) {
  949. fprintf(stderr, "Bad kRecordSizes value.\n");
  950. return false;
  951. }
  952. if (WriteAll(ssl.get(), buf.get(), len) < 0) {
  953. return false;
  954. }
  955. }
  956. } else {
  957. if (config->shim_writes_first) {
  958. if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
  959. 5) < 0) {
  960. return false;
  961. }
  962. }
  963. for (;;) {
  964. uint8_t buf[512];
  965. int n = DoRead(ssl.get(), buf, sizeof(buf));
  966. int err = SSL_get_error(ssl.get(), n);
  967. if (err == SSL_ERROR_ZERO_RETURN ||
  968. (n == 0 && err == SSL_ERROR_SYSCALL)) {
  969. if (n != 0) {
  970. fprintf(stderr, "Invalid SSL_get_error output\n");
  971. return false;
  972. }
  973. // Accept shutdowns with or without close_notify.
  974. // TODO(davidben): Write tests which distinguish these two cases.
  975. break;
  976. } else if (err != SSL_ERROR_NONE) {
  977. if (n > 0) {
  978. fprintf(stderr, "Invalid SSL_get_error output\n");
  979. return false;
  980. }
  981. return false;
  982. }
  983. // Successfully read data.
  984. if (n <= 0) {
  985. fprintf(stderr, "Invalid SSL_get_error output\n");
  986. return false;
  987. }
  988. // After a successful read, with or without False Start, the handshake
  989. // must be complete.
  990. if (!GetTestState(ssl.get())->handshake_done) {
  991. fprintf(stderr, "handshake was not completed after SSL_read\n");
  992. return false;
  993. }
  994. for (int i = 0; i < n; i++) {
  995. buf[i] ^= 0xff;
  996. }
  997. if (WriteAll(ssl.get(), buf, n) < 0) {
  998. return false;
  999. }
  1000. }
  1001. }
  1002. if (!config->is_server && !config->false_start &&
  1003. !config->implicit_handshake &&
  1004. GetTestState(ssl.get())->got_new_session) {
  1005. fprintf(stderr, "new session was established after the handshake\n");
  1006. return false;
  1007. }
  1008. if (out_session) {
  1009. out_session->reset(SSL_get1_session(ssl.get()));
  1010. }
  1011. SSL_shutdown(ssl.get());
  1012. return true;
  1013. }
  1014. int main(int argc, char **argv) {
  1015. #if defined(OPENSSL_WINDOWS)
  1016. /* Initialize Winsock. */
  1017. WORD wsa_version = MAKEWORD(2, 2);
  1018. WSADATA wsa_data;
  1019. int wsa_err = WSAStartup(wsa_version, &wsa_data);
  1020. if (wsa_err != 0) {
  1021. fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
  1022. return 1;
  1023. }
  1024. if (wsa_data.wVersion != wsa_version) {
  1025. fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
  1026. return 1;
  1027. }
  1028. #else
  1029. signal(SIGPIPE, SIG_IGN);
  1030. #endif
  1031. if (!SSL_library_init()) {
  1032. return 1;
  1033. }
  1034. g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  1035. g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
  1036. if (g_config_index < 0 || g_state_index < 0) {
  1037. return 1;
  1038. }
  1039. TestConfig config;
  1040. if (!ParseConfig(argc - 1, argv + 1, &config)) {
  1041. return Usage(argv[0]);
  1042. }
  1043. ScopedSSL_CTX ssl_ctx = SetupCtx(&config);
  1044. if (!ssl_ctx) {
  1045. ERR_print_errors_fp(stderr);
  1046. return 1;
  1047. }
  1048. ScopedSSL_SESSION session;
  1049. if (!DoExchange(&session, ssl_ctx.get(), &config, false /* is_resume */,
  1050. NULL /* session */)) {
  1051. ERR_print_errors_fp(stderr);
  1052. return 1;
  1053. }
  1054. if (config.resume &&
  1055. !DoExchange(NULL, ssl_ctx.get(), &config, true /* is_resume */,
  1056. session.get())) {
  1057. ERR_print_errors_fp(stderr);
  1058. return 1;
  1059. }
  1060. return 0;
  1061. }