ossl_shim.cc 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270
  1. /*
  2. * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the OpenSSL license (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #if !defined(__STDC_FORMAT_MACROS)
  10. #define __STDC_FORMAT_MACROS
  11. #endif
  12. #include <openssl/e_os2.h>
  13. #if !defined(OPENSSL_SYS_WINDOWS)
  14. #include <arpa/inet.h>
  15. #include <netinet/in.h>
  16. #include <netinet/tcp.h>
  17. #include <signal.h>
  18. #include <sys/socket.h>
  19. #include <sys/time.h>
  20. #include <unistd.h>
  21. #else
  22. #include <io.h>
  23. OPENSSL_MSVC_PRAGMA(warning(push, 3))
  24. #include <winsock2.h>
  25. #include <ws2tcpip.h>
  26. OPENSSL_MSVC_PRAGMA(warning(pop))
  27. OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
  28. #endif
  29. #include <assert.h>
  30. #include <inttypes.h>
  31. #include <string.h>
  32. #include <openssl/bio.h>
  33. #include <openssl/buffer.h>
  34. #include <openssl/bn.h>
  35. #include <openssl/crypto.h>
  36. #include <openssl/dh.h>
  37. #include <openssl/err.h>
  38. #include <openssl/evp.h>
  39. #include <openssl/hmac.h>
  40. #include <openssl/objects.h>
  41. #include <openssl/rand.h>
  42. #include <openssl/ssl.h>
  43. #include <openssl/x509.h>
  44. #include <memory>
  45. #include <string>
  46. #include <vector>
  47. #include "async_bio.h"
  48. #include "packeted_bio.h"
  49. #include "test_config.h"
  50. namespace bssl {
  51. #if !defined(OPENSSL_SYS_WINDOWS)
  52. static int closesocket(int sock) {
  53. return close(sock);
  54. }
  55. static void PrintSocketError(const char *func) {
  56. perror(func);
  57. }
  58. #else
  59. static void PrintSocketError(const char *func) {
  60. fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
  61. }
  62. #endif
  63. static int Usage(const char *program) {
  64. fprintf(stderr, "Usage: %s [flags...]\n", program);
  65. return 1;
  66. }
  67. struct TestState {
  68. // async_bio is async BIO which pauses reads and writes.
  69. BIO *async_bio = nullptr;
  70. // packeted_bio is the packeted BIO which simulates read timeouts.
  71. BIO *packeted_bio = nullptr;
  72. bool cert_ready = false;
  73. bool handshake_done = false;
  74. // private_key is the underlying private key used when testing custom keys.
  75. bssl::UniquePtr<EVP_PKEY> private_key;
  76. bool got_new_session = false;
  77. bssl::UniquePtr<SSL_SESSION> new_session;
  78. bool ticket_decrypt_done = false;
  79. bool alpn_select_done = false;
  80. };
  81. static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
  82. int index, long argl, void *argp) {
  83. delete ((TestState *)ptr);
  84. }
  85. static int g_config_index = 0;
  86. static int g_state_index = 0;
  87. static bool SetTestConfig(SSL *ssl, const TestConfig *config) {
  88. return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
  89. }
  90. static const TestConfig *GetTestConfig(const SSL *ssl) {
  91. return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
  92. }
  93. static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
  94. // |SSL_set_ex_data| takes ownership of |state| only on success.
  95. if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
  96. state.release();
  97. return true;
  98. }
  99. return false;
  100. }
  101. static TestState *GetTestState(const SSL *ssl) {
  102. return (TestState *)SSL_get_ex_data(ssl, g_state_index);
  103. }
  104. static bssl::UniquePtr<X509> LoadCertificate(const std::string &file) {
  105. bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
  106. if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
  107. return nullptr;
  108. }
  109. return bssl::UniquePtr<X509>(PEM_read_bio_X509(bio.get(), NULL, NULL, NULL));
  110. }
  111. static bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
  112. bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
  113. if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
  114. return nullptr;
  115. }
  116. return bssl::UniquePtr<EVP_PKEY>(
  117. PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
  118. }
  119. template<typename T>
  120. struct Free {
  121. void operator()(T *buf) {
  122. free(buf);
  123. }
  124. };
  125. static bool GetCertificate(SSL *ssl, bssl::UniquePtr<X509> *out_x509,
  126. bssl::UniquePtr<EVP_PKEY> *out_pkey) {
  127. const TestConfig *config = GetTestConfig(ssl);
  128. if (!config->key_file.empty()) {
  129. *out_pkey = LoadPrivateKey(config->key_file.c_str());
  130. if (!*out_pkey) {
  131. return false;
  132. }
  133. }
  134. if (!config->cert_file.empty()) {
  135. *out_x509 = LoadCertificate(config->cert_file.c_str());
  136. if (!*out_x509) {
  137. return false;
  138. }
  139. }
  140. return true;
  141. }
  142. static bool InstallCertificate(SSL *ssl) {
  143. bssl::UniquePtr<X509> x509;
  144. bssl::UniquePtr<EVP_PKEY> pkey;
  145. if (!GetCertificate(ssl, &x509, &pkey)) {
  146. return false;
  147. }
  148. if (pkey && !SSL_use_PrivateKey(ssl, pkey.get())) {
  149. return false;
  150. }
  151. if (x509 && !SSL_use_certificate(ssl, x509.get())) {
  152. return false;
  153. }
  154. return true;
  155. }
  156. static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
  157. if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
  158. return -1;
  159. }
  160. bssl::UniquePtr<X509> x509;
  161. bssl::UniquePtr<EVP_PKEY> pkey;
  162. if (!GetCertificate(ssl, &x509, &pkey)) {
  163. return -1;
  164. }
  165. // Return zero for no certificate.
  166. if (!x509) {
  167. return 0;
  168. }
  169. // Asynchronous private keys are not supported with client_cert_cb.
  170. *out_x509 = x509.release();
  171. *out_pkey = pkey.release();
  172. return 1;
  173. }
  174. static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
  175. return 1;
  176. }
  177. static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
  178. X509_STORE_CTX_set_error(store_ctx, X509_V_ERR_APPLICATION_VERIFICATION);
  179. return 0;
  180. }
  181. static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
  182. unsigned int *out_len, void *arg) {
  183. const TestConfig *config = GetTestConfig(ssl);
  184. if (config->advertise_npn.empty()) {
  185. return SSL_TLSEXT_ERR_NOACK;
  186. }
  187. *out = (const uint8_t*)config->advertise_npn.data();
  188. *out_len = config->advertise_npn.size();
  189. return SSL_TLSEXT_ERR_OK;
  190. }
  191. static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
  192. const uint8_t* in, unsigned inlen, void* arg) {
  193. const TestConfig *config = GetTestConfig(ssl);
  194. if (config->select_next_proto.empty()) {
  195. return SSL_TLSEXT_ERR_NOACK;
  196. }
  197. *out = (uint8_t*)config->select_next_proto.data();
  198. *outlen = config->select_next_proto.size();
  199. return SSL_TLSEXT_ERR_OK;
  200. }
  201. static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
  202. const uint8_t* in, unsigned inlen, void* arg) {
  203. if (GetTestState(ssl)->alpn_select_done) {
  204. fprintf(stderr, "AlpnSelectCallback called after completion.\n");
  205. exit(1);
  206. }
  207. GetTestState(ssl)->alpn_select_done = true;
  208. const TestConfig *config = GetTestConfig(ssl);
  209. if (config->decline_alpn) {
  210. return SSL_TLSEXT_ERR_NOACK;
  211. }
  212. if (!config->expected_advertised_alpn.empty() &&
  213. (config->expected_advertised_alpn.size() != inlen ||
  214. memcmp(config->expected_advertised_alpn.data(),
  215. in, inlen) != 0)) {
  216. fprintf(stderr, "bad ALPN select callback inputs\n");
  217. exit(1);
  218. }
  219. *out = (const uint8_t*)config->select_alpn.data();
  220. *outlen = config->select_alpn.size();
  221. return SSL_TLSEXT_ERR_OK;
  222. }
  223. static unsigned PskClientCallback(SSL *ssl, const char *hint,
  224. char *out_identity,
  225. unsigned max_identity_len,
  226. uint8_t *out_psk, unsigned max_psk_len) {
  227. const TestConfig *config = GetTestConfig(ssl);
  228. if (config->psk_identity.empty()) {
  229. if (hint != nullptr) {
  230. fprintf(stderr, "Server PSK hint was non-null.\n");
  231. return 0;
  232. }
  233. } else if (hint == nullptr ||
  234. strcmp(hint, config->psk_identity.c_str()) != 0) {
  235. fprintf(stderr, "Server PSK hint did not match.\n");
  236. return 0;
  237. }
  238. // Account for the trailing '\0' for the identity.
  239. if (config->psk_identity.size() >= max_identity_len ||
  240. config->psk.size() > max_psk_len) {
  241. fprintf(stderr, "PSK buffers too small\n");
  242. return 0;
  243. }
  244. BUF_strlcpy(out_identity, config->psk_identity.c_str(),
  245. max_identity_len);
  246. memcpy(out_psk, config->psk.data(), config->psk.size());
  247. return config->psk.size();
  248. }
  249. static unsigned PskServerCallback(SSL *ssl, const char *identity,
  250. uint8_t *out_psk, unsigned max_psk_len) {
  251. const TestConfig *config = GetTestConfig(ssl);
  252. if (strcmp(identity, config->psk_identity.c_str()) != 0) {
  253. fprintf(stderr, "Client PSK identity did not match.\n");
  254. return 0;
  255. }
  256. if (config->psk.size() > max_psk_len) {
  257. fprintf(stderr, "PSK buffers too small\n");
  258. return 0;
  259. }
  260. memcpy(out_psk, config->psk.data(), config->psk.size());
  261. return config->psk.size();
  262. }
  263. static int CertCallback(SSL *ssl, void *arg) {
  264. const TestConfig *config = GetTestConfig(ssl);
  265. // Check the CertificateRequest metadata is as expected.
  266. //
  267. // TODO(davidben): Test |SSL_get_client_CA_list|.
  268. if (!SSL_is_server(ssl) &&
  269. !config->expected_certificate_types.empty()) {
  270. const uint8_t *certificate_types;
  271. size_t certificate_types_len =
  272. SSL_get0_certificate_types(ssl, &certificate_types);
  273. if (certificate_types_len != config->expected_certificate_types.size() ||
  274. memcmp(certificate_types,
  275. config->expected_certificate_types.data(),
  276. certificate_types_len) != 0) {
  277. fprintf(stderr, "certificate types mismatch\n");
  278. return 0;
  279. }
  280. }
  281. // The certificate will be installed via other means.
  282. if (!config->async ||
  283. config->use_old_client_cert_callback) {
  284. return 1;
  285. }
  286. if (!GetTestState(ssl)->cert_ready) {
  287. return -1;
  288. }
  289. if (!InstallCertificate(ssl)) {
  290. return 0;
  291. }
  292. return 1;
  293. }
  294. static void InfoCallback(const SSL *ssl, int type, int val) {
  295. if (type == SSL_CB_HANDSHAKE_DONE) {
  296. if (GetTestConfig(ssl)->handshake_never_done) {
  297. fprintf(stderr, "Handshake unexpectedly completed.\n");
  298. // Abort before any expected error code is printed, to ensure the overall
  299. // test fails.
  300. abort();
  301. }
  302. GetTestState(ssl)->handshake_done = true;
  303. // Callbacks may be called again on a new handshake.
  304. GetTestState(ssl)->ticket_decrypt_done = false;
  305. GetTestState(ssl)->alpn_select_done = false;
  306. }
  307. }
  308. static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
  309. GetTestState(ssl)->got_new_session = true;
  310. GetTestState(ssl)->new_session.reset(session);
  311. return 1;
  312. }
  313. static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
  314. EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
  315. int encrypt) {
  316. if (!encrypt) {
  317. if (GetTestState(ssl)->ticket_decrypt_done) {
  318. fprintf(stderr, "TicketKeyCallback called after completion.\n");
  319. return -1;
  320. }
  321. GetTestState(ssl)->ticket_decrypt_done = true;
  322. }
  323. // This is just test code, so use the all-zeros key.
  324. static const uint8_t kZeros[16] = {0};
  325. if (encrypt) {
  326. memcpy(key_name, kZeros, sizeof(kZeros));
  327. RAND_bytes(iv, 16);
  328. } else if (memcmp(key_name, kZeros, 16) != 0) {
  329. return 0;
  330. }
  331. if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
  332. !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
  333. return -1;
  334. }
  335. if (!encrypt) {
  336. return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
  337. }
  338. return 1;
  339. }
  340. // kCustomExtensionValue is the extension value that the custom extension
  341. // callbacks will add.
  342. static const uint16_t kCustomExtensionValue = 1234;
  343. static void *const kCustomExtensionAddArg =
  344. reinterpret_cast<void *>(kCustomExtensionValue);
  345. static void *const kCustomExtensionParseArg =
  346. reinterpret_cast<void *>(kCustomExtensionValue + 1);
  347. static const char kCustomExtensionContents[] = "custom extension";
  348. static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
  349. const uint8_t **out, size_t *out_len,
  350. int *out_alert_value, void *add_arg) {
  351. if (extension_value != kCustomExtensionValue ||
  352. add_arg != kCustomExtensionAddArg) {
  353. abort();
  354. }
  355. if (GetTestConfig(ssl)->custom_extension_skip) {
  356. return 0;
  357. }
  358. if (GetTestConfig(ssl)->custom_extension_fail_add) {
  359. return -1;
  360. }
  361. *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
  362. *out_len = sizeof(kCustomExtensionContents) - 1;
  363. return 1;
  364. }
  365. static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
  366. const uint8_t *out, void *add_arg) {
  367. if (extension_value != kCustomExtensionValue ||
  368. add_arg != kCustomExtensionAddArg ||
  369. out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
  370. abort();
  371. }
  372. }
  373. static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
  374. const uint8_t *contents,
  375. size_t contents_len,
  376. int *out_alert_value, void *parse_arg) {
  377. if (extension_value != kCustomExtensionValue ||
  378. parse_arg != kCustomExtensionParseArg) {
  379. abort();
  380. }
  381. if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
  382. memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
  383. *out_alert_value = SSL_AD_DECODE_ERROR;
  384. return 0;
  385. }
  386. return 1;
  387. }
  388. // Connect returns a new socket connected to localhost on |port| or -1 on
  389. // error.
  390. static int Connect(uint16_t port) {
  391. int sock = socket(AF_INET, SOCK_STREAM, 0);
  392. if (sock == -1) {
  393. PrintSocketError("socket");
  394. return -1;
  395. }
  396. int nodelay = 1;
  397. if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  398. reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
  399. PrintSocketError("setsockopt");
  400. closesocket(sock);
  401. return -1;
  402. }
  403. sockaddr_in sin;
  404. memset(&sin, 0, sizeof(sin));
  405. sin.sin_family = AF_INET;
  406. sin.sin_port = htons(port);
  407. if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
  408. PrintSocketError("inet_pton");
  409. closesocket(sock);
  410. return -1;
  411. }
  412. if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
  413. sizeof(sin)) != 0) {
  414. PrintSocketError("connect");
  415. closesocket(sock);
  416. return -1;
  417. }
  418. return sock;
  419. }
  420. class SocketCloser {
  421. public:
  422. explicit SocketCloser(int sock) : sock_(sock) {}
  423. ~SocketCloser() {
  424. // Half-close and drain the socket before releasing it. This seems to be
  425. // necessary for graceful shutdown on Windows. It will also avoid write
  426. // failures in the test runner.
  427. #if defined(OPENSSL_SYS_WINDOWS)
  428. shutdown(sock_, SD_SEND);
  429. #else
  430. shutdown(sock_, SHUT_WR);
  431. #endif
  432. while (true) {
  433. char buf[1024];
  434. if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
  435. break;
  436. }
  437. }
  438. closesocket(sock_);
  439. }
  440. private:
  441. const int sock_;
  442. };
  443. static bssl::UniquePtr<SSL_CTX> SetupCtx(const TestConfig *config) {
  444. const char sess_id_ctx[] = "ossl_shim";
  445. bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(
  446. config->is_dtls ? DTLS_method() : TLS_method()));
  447. if (!ssl_ctx) {
  448. return nullptr;
  449. }
  450. SSL_CTX_set_security_level(ssl_ctx.get(), 0);
  451. #if 0
  452. /* Disabled for now until we have some TLS1.3 support */
  453. // Enable TLS 1.3 for tests.
  454. if (!config->is_dtls &&
  455. !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION)) {
  456. return nullptr;
  457. }
  458. #endif
  459. std::string cipher_list = "ALL";
  460. if (!config->cipher.empty()) {
  461. cipher_list = config->cipher;
  462. SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
  463. }
  464. if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
  465. return nullptr;
  466. }
  467. DH *tmpdh;
  468. if (config->use_sparse_dh_prime) {
  469. BIGNUM *p, *g;
  470. p = BN_new();
  471. g = BN_new();
  472. tmpdh = DH_new();
  473. if (p == NULL || g == NULL || tmpdh == NULL) {
  474. BN_free(p);
  475. BN_free(g);
  476. DH_free(tmpdh);
  477. return nullptr;
  478. }
  479. // This prime number is 2^1024 + 643 – a value just above a power of two.
  480. // Because of its form, values modulo it are essentially certain to be one
  481. // byte shorter. This is used to test padding of these values.
  482. if (BN_hex2bn(
  483. &p,
  484. "1000000000000000000000000000000000000000000000000000000000000000"
  485. "0000000000000000000000000000000000000000000000000000000000000000"
  486. "0000000000000000000000000000000000000000000000000000000000000000"
  487. "0000000000000000000000000000000000000000000000000000000000000028"
  488. "3") == 0 ||
  489. !BN_set_word(g, 2)) {
  490. BN_free(p);
  491. BN_free(g);
  492. DH_free(tmpdh);
  493. return nullptr;
  494. }
  495. DH_set0_pqg(tmpdh, p, NULL, g);
  496. } else {
  497. tmpdh = DH_get_2048_256();
  498. }
  499. bssl::UniquePtr<DH> dh(tmpdh);
  500. if (!dh || !SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
  501. return nullptr;
  502. }
  503. SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
  504. if (config->use_old_client_cert_callback) {
  505. SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
  506. }
  507. SSL_CTX_set_npn_advertised_cb(
  508. ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
  509. if (!config->select_next_proto.empty()) {
  510. SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
  511. NULL);
  512. }
  513. if (!config->select_alpn.empty() || config->decline_alpn) {
  514. SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
  515. }
  516. SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
  517. SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
  518. if (config->use_ticket_callback) {
  519. SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
  520. }
  521. if (config->enable_client_custom_extension &&
  522. !SSL_CTX_add_client_custom_ext(
  523. ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
  524. CustomExtensionFreeCallback, kCustomExtensionAddArg,
  525. CustomExtensionParseCallback, kCustomExtensionParseArg)) {
  526. return nullptr;
  527. }
  528. if (config->enable_server_custom_extension &&
  529. !SSL_CTX_add_server_custom_ext(
  530. ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
  531. CustomExtensionFreeCallback, kCustomExtensionAddArg,
  532. CustomExtensionParseCallback, kCustomExtensionParseArg)) {
  533. return nullptr;
  534. }
  535. if (config->verify_fail) {
  536. SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
  537. } else {
  538. SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
  539. }
  540. if (config->use_null_client_ca_list) {
  541. SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
  542. }
  543. SSL_CTX_set_session_id_context(ssl_ctx.get(),
  544. (const unsigned char *)sess_id_ctx,
  545. sizeof(sess_id_ctx) - 1);
  546. return ssl_ctx;
  547. }
  548. // RetryAsync is called after a failed operation on |ssl| with return code
  549. // |ret|. If the operation should be retried, it simulates one asynchronous
  550. // event and returns true. Otherwise it returns false.
  551. static bool RetryAsync(SSL *ssl, int ret) {
  552. // No error; don't retry.
  553. if (ret >= 0) {
  554. return false;
  555. }
  556. TestState *test_state = GetTestState(ssl);
  557. assert(GetTestConfig(ssl)->async);
  558. if (test_state->packeted_bio != nullptr &&
  559. PacketedBioAdvanceClock(test_state->packeted_bio)) {
  560. // The DTLS retransmit logic silently ignores write failures. So the test
  561. // may progress, allow writes through synchronously.
  562. AsyncBioEnforceWriteQuota(test_state->async_bio, false);
  563. int timeout_ret = DTLSv1_handle_timeout(ssl);
  564. AsyncBioEnforceWriteQuota(test_state->async_bio, true);
  565. if (timeout_ret < 0) {
  566. fprintf(stderr, "Error retransmitting.\n");
  567. return false;
  568. }
  569. return true;
  570. }
  571. // See if we needed to read or write more. If so, allow one byte through on
  572. // the appropriate end to maximally stress the state machine.
  573. switch (SSL_get_error(ssl, ret)) {
  574. case SSL_ERROR_WANT_READ:
  575. AsyncBioAllowRead(test_state->async_bio, 1);
  576. return true;
  577. case SSL_ERROR_WANT_WRITE:
  578. AsyncBioAllowWrite(test_state->async_bio, 1);
  579. return true;
  580. case SSL_ERROR_WANT_X509_LOOKUP:
  581. test_state->cert_ready = true;
  582. return true;
  583. default:
  584. return false;
  585. }
  586. }
  587. // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
  588. // the result value of the final |SSL_read| call.
  589. static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
  590. const TestConfig *config = GetTestConfig(ssl);
  591. TestState *test_state = GetTestState(ssl);
  592. int ret;
  593. do {
  594. if (config->async) {
  595. // The DTLS retransmit logic silently ignores write failures. So the test
  596. // may progress, allow writes through synchronously. |SSL_read| may
  597. // trigger a retransmit, so disconnect the write quota.
  598. AsyncBioEnforceWriteQuota(test_state->async_bio, false);
  599. }
  600. ret = config->peek_then_read ? SSL_peek(ssl, out, max_out)
  601. : SSL_read(ssl, out, max_out);
  602. if (config->async) {
  603. AsyncBioEnforceWriteQuota(test_state->async_bio, true);
  604. }
  605. } while (config->async && RetryAsync(ssl, ret));
  606. if (config->peek_then_read && ret > 0) {
  607. std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
  608. // SSL_peek should synchronously return the same data.
  609. int ret2 = SSL_peek(ssl, buf.get(), ret);
  610. if (ret2 != ret ||
  611. memcmp(buf.get(), out, ret) != 0) {
  612. fprintf(stderr, "First and second SSL_peek did not match.\n");
  613. return -1;
  614. }
  615. // SSL_read should synchronously return the same data and consume it.
  616. ret2 = SSL_read(ssl, buf.get(), ret);
  617. if (ret2 != ret ||
  618. memcmp(buf.get(), out, ret) != 0) {
  619. fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
  620. return -1;
  621. }
  622. }
  623. return ret;
  624. }
  625. // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
  626. // operations. It returns the result of the final |SSL_write| call.
  627. static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
  628. const TestConfig *config = GetTestConfig(ssl);
  629. int ret;
  630. do {
  631. ret = SSL_write(ssl, in, in_len);
  632. if (ret > 0) {
  633. in += ret;
  634. in_len -= ret;
  635. }
  636. } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
  637. return ret;
  638. }
  639. // DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
  640. // returns the result of the final |SSL_shutdown| call.
  641. static int DoShutdown(SSL *ssl) {
  642. const TestConfig *config = GetTestConfig(ssl);
  643. int ret;
  644. do {
  645. ret = SSL_shutdown(ssl);
  646. } while (config->async && RetryAsync(ssl, ret));
  647. return ret;
  648. }
  649. static uint16_t GetProtocolVersion(const SSL *ssl) {
  650. uint16_t version = SSL_version(ssl);
  651. if (!SSL_is_dtls(ssl)) {
  652. return version;
  653. }
  654. return 0x0201 + ~version;
  655. }
  656. // CheckHandshakeProperties checks, immediately after |ssl| completes its
  657. // initial handshake (or False Starts), whether all the properties are
  658. // consistent with the test configuration and invariants.
  659. static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
  660. const TestConfig *config = GetTestConfig(ssl);
  661. if (SSL_get_current_cipher(ssl) == nullptr) {
  662. fprintf(stderr, "null cipher after handshake\n");
  663. return false;
  664. }
  665. if (is_resume &&
  666. (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
  667. fprintf(stderr, "session was%s reused\n",
  668. SSL_session_reused(ssl) ? "" : " not");
  669. return false;
  670. }
  671. if (!GetTestState(ssl)->handshake_done) {
  672. fprintf(stderr, "handshake was not completed\n");
  673. return false;
  674. }
  675. if (!config->is_server) {
  676. bool expect_new_session =
  677. !config->expect_no_session &&
  678. (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
  679. // Session tickets are sent post-handshake in TLS 1.3.
  680. GetProtocolVersion(ssl) < TLS1_3_VERSION;
  681. if (expect_new_session != GetTestState(ssl)->got_new_session) {
  682. fprintf(stderr,
  683. "new session was%s cached, but we expected the opposite\n",
  684. GetTestState(ssl)->got_new_session ? "" : " not");
  685. return false;
  686. }
  687. }
  688. if (!config->expected_server_name.empty()) {
  689. const char *server_name =
  690. SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  691. if (server_name != config->expected_server_name) {
  692. fprintf(stderr, "servername mismatch (got %s; want %s)\n",
  693. server_name, config->expected_server_name.c_str());
  694. return false;
  695. }
  696. }
  697. if (!config->expected_next_proto.empty()) {
  698. const uint8_t *next_proto;
  699. unsigned next_proto_len;
  700. SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
  701. if (next_proto_len != config->expected_next_proto.size() ||
  702. memcmp(next_proto, config->expected_next_proto.data(),
  703. next_proto_len) != 0) {
  704. fprintf(stderr, "negotiated next proto mismatch\n");
  705. return false;
  706. }
  707. }
  708. if (!config->expected_alpn.empty()) {
  709. const uint8_t *alpn_proto;
  710. unsigned alpn_proto_len;
  711. SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
  712. if (alpn_proto_len != config->expected_alpn.size() ||
  713. memcmp(alpn_proto, config->expected_alpn.data(),
  714. alpn_proto_len) != 0) {
  715. fprintf(stderr, "negotiated alpn proto mismatch\n");
  716. return false;
  717. }
  718. }
  719. if (config->expect_extended_master_secret) {
  720. if (!SSL_get_extms_support(ssl)) {
  721. fprintf(stderr, "No EMS for connection when expected");
  722. return false;
  723. }
  724. }
  725. if (config->expect_verify_result) {
  726. int expected_verify_result = config->verify_fail ?
  727. X509_V_ERR_APPLICATION_VERIFICATION :
  728. X509_V_OK;
  729. if (SSL_get_verify_result(ssl) != expected_verify_result) {
  730. fprintf(stderr, "Wrong certificate verification result\n");
  731. return false;
  732. }
  733. }
  734. if (!config->psk.empty()) {
  735. if (SSL_get_peer_cert_chain(ssl) != nullptr) {
  736. fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
  737. return false;
  738. }
  739. } else if (!config->is_server || config->require_any_client_certificate) {
  740. if (SSL_get_peer_certificate(ssl) == nullptr) {
  741. fprintf(stderr, "Received no peer certificate but expected one.\n");
  742. return false;
  743. }
  744. }
  745. return true;
  746. }
  747. // DoExchange runs a test SSL exchange against the peer. On success, it returns
  748. // true and sets |*out_session| to the negotiated SSL session. If the test is a
  749. // resumption attempt, |is_resume| is true and |session| is the session from the
  750. // previous exchange.
  751. static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
  752. SSL_CTX *ssl_ctx, const TestConfig *config,
  753. bool is_resume, SSL_SESSION *session) {
  754. bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
  755. if (!ssl) {
  756. return false;
  757. }
  758. if (!SetTestConfig(ssl.get(), config) ||
  759. !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
  760. return false;
  761. }
  762. if (config->fallback_scsv &&
  763. !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
  764. return false;
  765. }
  766. // Install the certificate synchronously if nothing else will handle it.
  767. if (!config->use_old_client_cert_callback &&
  768. !config->async &&
  769. !InstallCertificate(ssl.get())) {
  770. return false;
  771. }
  772. SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
  773. if (config->require_any_client_certificate) {
  774. SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  775. NULL);
  776. }
  777. if (config->verify_peer) {
  778. SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
  779. }
  780. if (config->partial_write) {
  781. SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
  782. }
  783. if (config->no_tls13) {
  784. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
  785. }
  786. if (config->no_tls12) {
  787. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
  788. }
  789. if (config->no_tls11) {
  790. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
  791. }
  792. if (config->no_tls1) {
  793. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
  794. }
  795. if (config->no_ssl3) {
  796. SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
  797. }
  798. if (!config->host_name.empty() &&
  799. !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
  800. return false;
  801. }
  802. if (!config->advertise_alpn.empty() &&
  803. SSL_set_alpn_protos(ssl.get(),
  804. (const uint8_t *)config->advertise_alpn.data(),
  805. config->advertise_alpn.size()) != 0) {
  806. return false;
  807. }
  808. if (!config->psk.empty()) {
  809. SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
  810. SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
  811. }
  812. if (!config->psk_identity.empty() &&
  813. !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
  814. return false;
  815. }
  816. if (!config->srtp_profiles.empty() &&
  817. SSL_set_tlsext_use_srtp(ssl.get(), config->srtp_profiles.c_str())) {
  818. return false;
  819. }
  820. if (config->min_version != 0 &&
  821. !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) {
  822. return false;
  823. }
  824. if (config->max_version != 0 &&
  825. !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) {
  826. return false;
  827. }
  828. if (config->mtu != 0) {
  829. SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
  830. SSL_set_mtu(ssl.get(), config->mtu);
  831. }
  832. if (config->renegotiate_freely) {
  833. // This is always on for OpenSSL.
  834. }
  835. if (!config->check_close_notify) {
  836. SSL_set_quiet_shutdown(ssl.get(), 1);
  837. }
  838. if (config->p384_only) {
  839. int nid = NID_secp384r1;
  840. if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
  841. return false;
  842. }
  843. }
  844. if (config->enable_all_curves) {
  845. static const int kAllCurves[] = {
  846. NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_X25519,
  847. };
  848. if (!SSL_set1_curves(ssl.get(), kAllCurves,
  849. OPENSSL_ARRAY_SIZE(kAllCurves))) {
  850. return false;
  851. }
  852. }
  853. if (config->max_cert_list > 0) {
  854. SSL_set_max_cert_list(ssl.get(), config->max_cert_list);
  855. }
  856. int sock = Connect(config->port);
  857. if (sock == -1) {
  858. return false;
  859. }
  860. SocketCloser closer(sock);
  861. bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
  862. if (!bio) {
  863. return false;
  864. }
  865. if (config->is_dtls) {
  866. bssl::UniquePtr<BIO> packeted = PacketedBioCreate(!config->async);
  867. if (!packeted) {
  868. return false;
  869. }
  870. GetTestState(ssl.get())->packeted_bio = packeted.get();
  871. BIO_push(packeted.get(), bio.release());
  872. bio = std::move(packeted);
  873. }
  874. if (config->async) {
  875. bssl::UniquePtr<BIO> async_scoped =
  876. config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
  877. if (!async_scoped) {
  878. return false;
  879. }
  880. BIO_push(async_scoped.get(), bio.release());
  881. GetTestState(ssl.get())->async_bio = async_scoped.get();
  882. bio = std::move(async_scoped);
  883. }
  884. SSL_set_bio(ssl.get(), bio.get(), bio.get());
  885. bio.release(); // SSL_set_bio takes ownership.
  886. if (session != NULL) {
  887. if (!config->is_server) {
  888. if (SSL_set_session(ssl.get(), session) != 1) {
  889. return false;
  890. }
  891. }
  892. }
  893. #if 0
  894. // KNOWN BUG: OpenSSL's SSL_get_current_cipher behaves incorrectly when
  895. // offering resumption.
  896. if (SSL_get_current_cipher(ssl.get()) != nullptr) {
  897. fprintf(stderr, "non-null cipher before handshake\n");
  898. return false;
  899. }
  900. #endif
  901. int ret;
  902. if (config->implicit_handshake) {
  903. if (config->is_server) {
  904. SSL_set_accept_state(ssl.get());
  905. } else {
  906. SSL_set_connect_state(ssl.get());
  907. }
  908. } else {
  909. do {
  910. if (config->is_server) {
  911. ret = SSL_accept(ssl.get());
  912. } else {
  913. ret = SSL_connect(ssl.get());
  914. }
  915. } while (config->async && RetryAsync(ssl.get(), ret));
  916. if (ret != 1 ||
  917. !CheckHandshakeProperties(ssl.get(), is_resume)) {
  918. return false;
  919. }
  920. // Reset the state to assert later that the callback isn't called in
  921. // renegotiations.
  922. GetTestState(ssl.get())->got_new_session = false;
  923. }
  924. if (config->export_keying_material > 0) {
  925. std::vector<uint8_t> result(
  926. static_cast<size_t>(config->export_keying_material));
  927. if (SSL_export_keying_material(
  928. ssl.get(), result.data(), result.size(),
  929. config->export_label.data(), config->export_label.size(),
  930. reinterpret_cast<const uint8_t*>(config->export_context.data()),
  931. config->export_context.size(), config->use_export_context) != 1) {
  932. fprintf(stderr, "failed to export keying material\n");
  933. return false;
  934. }
  935. if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
  936. return false;
  937. }
  938. }
  939. if (config->write_different_record_sizes) {
  940. if (config->is_dtls) {
  941. fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
  942. return false;
  943. }
  944. // This mode writes a number of different record sizes in an attempt to
  945. // trip up the CBC record splitting code.
  946. static const size_t kBufLen = 32769;
  947. std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
  948. memset(buf.get(), 0x42, kBufLen);
  949. static const size_t kRecordSizes[] = {
  950. 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
  951. for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
  952. const size_t len = kRecordSizes[i];
  953. if (len > kBufLen) {
  954. fprintf(stderr, "Bad kRecordSizes value.\n");
  955. return false;
  956. }
  957. if (WriteAll(ssl.get(), buf.get(), len) < 0) {
  958. return false;
  959. }
  960. }
  961. } else {
  962. if (config->shim_writes_first) {
  963. if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
  964. 5) < 0) {
  965. return false;
  966. }
  967. }
  968. if (!config->shim_shuts_down) {
  969. for (;;) {
  970. static const size_t kBufLen = 16384;
  971. std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
  972. // Read only 512 bytes at a time in TLS to ensure records may be
  973. // returned in multiple reads.
  974. int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
  975. int err = SSL_get_error(ssl.get(), n);
  976. if (err == SSL_ERROR_ZERO_RETURN ||
  977. (n == 0 && err == SSL_ERROR_SYSCALL)) {
  978. if (n != 0) {
  979. fprintf(stderr, "Invalid SSL_get_error output\n");
  980. return false;
  981. }
  982. // Stop on either clean or unclean shutdown.
  983. break;
  984. } else if (err != SSL_ERROR_NONE) {
  985. if (n > 0) {
  986. fprintf(stderr, "Invalid SSL_get_error output\n");
  987. return false;
  988. }
  989. return false;
  990. }
  991. // Successfully read data.
  992. if (n <= 0) {
  993. fprintf(stderr, "Invalid SSL_get_error output\n");
  994. return false;
  995. }
  996. // After a successful read, with or without False Start, the handshake
  997. // must be complete.
  998. if (!GetTestState(ssl.get())->handshake_done) {
  999. fprintf(stderr, "handshake was not completed after SSL_read\n");
  1000. return false;
  1001. }
  1002. for (int i = 0; i < n; i++) {
  1003. buf[i] ^= 0xff;
  1004. }
  1005. if (WriteAll(ssl.get(), buf.get(), n) < 0) {
  1006. return false;
  1007. }
  1008. }
  1009. }
  1010. }
  1011. if (!config->is_server &&
  1012. !config->implicit_handshake &&
  1013. // Session tickets are sent post-handshake in TLS 1.3.
  1014. GetProtocolVersion(ssl.get()) < TLS1_3_VERSION &&
  1015. GetTestState(ssl.get())->got_new_session) {
  1016. fprintf(stderr, "new session was established after the handshake\n");
  1017. return false;
  1018. }
  1019. if (GetProtocolVersion(ssl.get()) >= TLS1_3_VERSION && !config->is_server) {
  1020. bool expect_new_session =
  1021. !config->expect_no_session && !config->shim_shuts_down;
  1022. if (expect_new_session != GetTestState(ssl.get())->got_new_session) {
  1023. fprintf(stderr,
  1024. "new session was%s cached, but we expected the opposite\n",
  1025. GetTestState(ssl.get())->got_new_session ? "" : " not");
  1026. return false;
  1027. }
  1028. }
  1029. if (out_session) {
  1030. *out_session = std::move(GetTestState(ssl.get())->new_session);
  1031. }
  1032. ret = DoShutdown(ssl.get());
  1033. if (config->shim_shuts_down && config->check_close_notify) {
  1034. // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
  1035. // it returns zero when our close_notify is sent, then one when the peer's
  1036. // is received.
  1037. if (ret != 0) {
  1038. fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
  1039. return false;
  1040. }
  1041. ret = DoShutdown(ssl.get());
  1042. }
  1043. if (ret != 1) {
  1044. fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
  1045. return false;
  1046. }
  1047. if (SSL_total_renegotiations(ssl.get()) !=
  1048. config->expect_total_renegotiations) {
  1049. fprintf(stderr, "Expected %d renegotiations, got %ld\n",
  1050. config->expect_total_renegotiations,
  1051. SSL_total_renegotiations(ssl.get()));
  1052. return false;
  1053. }
  1054. return true;
  1055. }
  1056. class StderrDelimiter {
  1057. public:
  1058. ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
  1059. };
  1060. static int Main(int argc, char **argv) {
  1061. // To distinguish ASan's output from ours, add a trailing message to stderr.
  1062. // Anything following this line will be considered an error.
  1063. StderrDelimiter delimiter;
  1064. #if defined(OPENSSL_SYS_WINDOWS)
  1065. /* Initialize Winsock. */
  1066. WORD wsa_version = MAKEWORD(2, 2);
  1067. WSADATA wsa_data;
  1068. int wsa_err = WSAStartup(wsa_version, &wsa_data);
  1069. if (wsa_err != 0) {
  1070. fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
  1071. return 1;
  1072. }
  1073. if (wsa_data.wVersion != wsa_version) {
  1074. fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
  1075. return 1;
  1076. }
  1077. #else
  1078. signal(SIGPIPE, SIG_IGN);
  1079. #endif
  1080. OPENSSL_init_crypto(0, NULL);
  1081. OPENSSL_init_ssl(0, NULL);
  1082. g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  1083. g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
  1084. if (g_config_index < 0 || g_state_index < 0) {
  1085. return 1;
  1086. }
  1087. TestConfig config;
  1088. if (!ParseConfig(argc - 1, argv + 1, &config)) {
  1089. return Usage(argv[0]);
  1090. }
  1091. bssl::UniquePtr<SSL_CTX> ssl_ctx = SetupCtx(&config);
  1092. if (!ssl_ctx) {
  1093. ERR_print_errors_fp(stderr);
  1094. return 1;
  1095. }
  1096. bssl::UniquePtr<SSL_SESSION> session;
  1097. for (int i = 0; i < config.resume_count + 1; i++) {
  1098. bool is_resume = i > 0;
  1099. if (is_resume && !config.is_server && !session) {
  1100. fprintf(stderr, "No session to offer.\n");
  1101. return 1;
  1102. }
  1103. bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
  1104. if (!DoExchange(&session, ssl_ctx.get(), &config, is_resume,
  1105. offer_session.get())) {
  1106. fprintf(stderr, "Connection %d failed.\n", i + 1);
  1107. ERR_print_errors_fp(stderr);
  1108. return 1;
  1109. }
  1110. }
  1111. return 0;
  1112. }
  1113. } // namespace bssl
  1114. int main(int argc, char **argv) {
  1115. return bssl::Main(argc, argv);
  1116. }