Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

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