2
0

ossl_shim.cc 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  1. /*
  2. * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (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 "packeted_bio.h"
  13. #include <openssl/e_os2.h>
  14. #if !defined(OPENSSL_SYS_WINDOWS)
  15. #include <arpa/inet.h>
  16. #include <netinet/in.h>
  17. #include <netinet/tcp.h>
  18. #include <signal.h>
  19. #include <sys/socket.h>
  20. #include <sys/time.h>
  21. #include <unistd.h>
  22. #else
  23. #include <io.h>
  24. OPENSSL_MSVC_PRAGMA(warning(push, 3))
  25. #include <winsock2.h>
  26. #include <ws2tcpip.h>
  27. OPENSSL_MSVC_PRAGMA(warning(pop))
  28. OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
  29. #endif
  30. #include <assert.h>
  31. #include <inttypes.h>
  32. #include <string.h>
  33. #include <openssl/bio.h>
  34. #include <openssl/buffer.h>
  35. #include <openssl/bn.h>
  36. #include <openssl/crypto.h>
  37. #include <openssl/dh.h>
  38. #include <openssl/err.h>
  39. #include <openssl/evp.h>
  40. #include <openssl/hmac.h>
  41. #include <openssl/objects.h>
  42. #include <openssl/rand.h>
  43. #include <openssl/ssl.h>
  44. #include <openssl/x509.h>
  45. #include <memory>
  46. #include <string>
  47. #include <vector>
  48. #include "async_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. static int ServerNameCallback(SSL *ssl, int *out_alert, void *arg) {
  389. // SNI must be accessible from the SNI callback.
  390. const TestConfig *config = GetTestConfig(ssl);
  391. const char *server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  392. if (server_name == nullptr ||
  393. std::string(server_name) != config->expected_server_name) {
  394. fprintf(stderr, "servername mismatch (got %s; want %s)\n", server_name,
  395. config->expected_server_name.c_str());
  396. return SSL_TLSEXT_ERR_ALERT_FATAL;
  397. }
  398. return SSL_TLSEXT_ERR_OK;
  399. }
  400. // Connect returns a new socket connected to localhost on |port| or -1 on
  401. // error.
  402. static int Connect(uint16_t port) {
  403. int sock = socket(AF_INET, SOCK_STREAM, 0);
  404. if (sock == -1) {
  405. PrintSocketError("socket");
  406. return -1;
  407. }
  408. int nodelay = 1;
  409. if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  410. reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
  411. PrintSocketError("setsockopt");
  412. closesocket(sock);
  413. return -1;
  414. }
  415. sockaddr_in sin;
  416. memset(&sin, 0, sizeof(sin));
  417. sin.sin_family = AF_INET;
  418. sin.sin_port = htons(port);
  419. if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
  420. PrintSocketError("inet_pton");
  421. closesocket(sock);
  422. return -1;
  423. }
  424. if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
  425. sizeof(sin)) != 0) {
  426. PrintSocketError("connect");
  427. closesocket(sock);
  428. return -1;
  429. }
  430. return sock;
  431. }
  432. class SocketCloser {
  433. public:
  434. explicit SocketCloser(int sock) : sock_(sock) {}
  435. ~SocketCloser() {
  436. // Half-close and drain the socket before releasing it. This seems to be
  437. // necessary for graceful shutdown on Windows. It will also avoid write
  438. // failures in the test runner.
  439. #if defined(OPENSSL_SYS_WINDOWS)
  440. shutdown(sock_, SD_SEND);
  441. #else
  442. shutdown(sock_, SHUT_WR);
  443. #endif
  444. while (true) {
  445. char buf[1024];
  446. if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
  447. break;
  448. }
  449. }
  450. closesocket(sock_);
  451. }
  452. private:
  453. const int sock_;
  454. };
  455. static bssl::UniquePtr<SSL_CTX> SetupCtx(const TestConfig *config) {
  456. const char sess_id_ctx[] = "ossl_shim";
  457. bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(
  458. config->is_dtls ? DTLS_method() : TLS_method()));
  459. if (!ssl_ctx) {
  460. return nullptr;
  461. }
  462. SSL_CTX_set_security_level(ssl_ctx.get(), 0);
  463. #if 0
  464. /* Disabled for now until we have some TLS1.3 support */
  465. // Enable TLS 1.3 for tests.
  466. if (!config->is_dtls &&
  467. !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION)) {
  468. return nullptr;
  469. }
  470. #else
  471. /* Ensure we don't negotiate TLSv1.3 until we can handle it */
  472. if (!config->is_dtls &&
  473. !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_2_VERSION)) {
  474. return nullptr;
  475. }
  476. #endif
  477. std::string cipher_list = "ALL";
  478. if (!config->cipher.empty()) {
  479. cipher_list = config->cipher;
  480. SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
  481. }
  482. if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
  483. return nullptr;
  484. }
  485. DH *tmpdh;
  486. if (config->use_sparse_dh_prime) {
  487. BIGNUM *p, *g;
  488. p = BN_new();
  489. g = BN_new();
  490. tmpdh = DH_new();
  491. if (p == NULL || g == NULL || tmpdh == NULL) {
  492. BN_free(p);
  493. BN_free(g);
  494. DH_free(tmpdh);
  495. return nullptr;
  496. }
  497. // This prime number is 2^1024 + 643 – a value just above a power of two.
  498. // Because of its form, values modulo it are essentially certain to be one
  499. // byte shorter. This is used to test padding of these values.
  500. if (BN_hex2bn(
  501. &p,
  502. "1000000000000000000000000000000000000000000000000000000000000000"
  503. "0000000000000000000000000000000000000000000000000000000000000000"
  504. "0000000000000000000000000000000000000000000000000000000000000000"
  505. "0000000000000000000000000000000000000000000000000000000000000028"
  506. "3") == 0 ||
  507. !BN_set_word(g, 2)) {
  508. BN_free(p);
  509. BN_free(g);
  510. DH_free(tmpdh);
  511. return nullptr;
  512. }
  513. DH_set0_pqg(tmpdh, p, NULL, g);
  514. } else {
  515. tmpdh = DH_get_2048_256();
  516. }
  517. bssl::UniquePtr<DH> dh(tmpdh);
  518. if (!dh || !SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
  519. return nullptr;
  520. }
  521. SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
  522. if (config->use_old_client_cert_callback) {
  523. SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
  524. }
  525. SSL_CTX_set_npn_advertised_cb(
  526. ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
  527. if (!config->select_next_proto.empty()) {
  528. SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
  529. NULL);
  530. }
  531. if (!config->select_alpn.empty() || config->decline_alpn) {
  532. SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
  533. }
  534. SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
  535. SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
  536. if (config->use_ticket_callback) {
  537. SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
  538. }
  539. if (config->enable_client_custom_extension &&
  540. !SSL_CTX_add_client_custom_ext(
  541. ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
  542. CustomExtensionFreeCallback, kCustomExtensionAddArg,
  543. CustomExtensionParseCallback, kCustomExtensionParseArg)) {
  544. return nullptr;
  545. }
  546. if (config->enable_server_custom_extension &&
  547. !SSL_CTX_add_server_custom_ext(
  548. ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
  549. CustomExtensionFreeCallback, kCustomExtensionAddArg,
  550. CustomExtensionParseCallback, kCustomExtensionParseArg)) {
  551. return nullptr;
  552. }
  553. if (config->verify_fail) {
  554. SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
  555. } else {
  556. SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
  557. }
  558. if (config->use_null_client_ca_list) {
  559. SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
  560. }
  561. if (!SSL_CTX_set_session_id_context(ssl_ctx.get(),
  562. (const unsigned char *)sess_id_ctx,
  563. sizeof(sess_id_ctx) - 1))
  564. return nullptr;
  565. if (!config->expected_server_name.empty()) {
  566. SSL_CTX_set_tlsext_servername_callback(ssl_ctx.get(), ServerNameCallback);
  567. }
  568. return ssl_ctx;
  569. }
  570. // RetryAsync is called after a failed operation on |ssl| with return code
  571. // |ret|. If the operation should be retried, it simulates one asynchronous
  572. // event and returns true. Otherwise it returns false.
  573. static bool RetryAsync(SSL *ssl, int ret) {
  574. // No error; don't retry.
  575. if (ret >= 0) {
  576. return false;
  577. }
  578. TestState *test_state = GetTestState(ssl);
  579. assert(GetTestConfig(ssl)->async);
  580. if (test_state->packeted_bio != nullptr &&
  581. PacketedBioAdvanceClock(test_state->packeted_bio)) {
  582. // The DTLS retransmit logic silently ignores write failures. So the test
  583. // may progress, allow writes through synchronously.
  584. AsyncBioEnforceWriteQuota(test_state->async_bio, false);
  585. int timeout_ret = DTLSv1_handle_timeout(ssl);
  586. AsyncBioEnforceWriteQuota(test_state->async_bio, true);
  587. if (timeout_ret < 0) {
  588. fprintf(stderr, "Error retransmitting.\n");
  589. return false;
  590. }
  591. return true;
  592. }
  593. // See if we needed to read or write more. If so, allow one byte through on
  594. // the appropriate end to maximally stress the state machine.
  595. switch (SSL_get_error(ssl, ret)) {
  596. case SSL_ERROR_WANT_READ:
  597. AsyncBioAllowRead(test_state->async_bio, 1);
  598. return true;
  599. case SSL_ERROR_WANT_WRITE:
  600. AsyncBioAllowWrite(test_state->async_bio, 1);
  601. return true;
  602. case SSL_ERROR_WANT_X509_LOOKUP:
  603. test_state->cert_ready = true;
  604. return true;
  605. default:
  606. return false;
  607. }
  608. }
  609. // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
  610. // the result value of the final |SSL_read| call.
  611. static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
  612. const TestConfig *config = GetTestConfig(ssl);
  613. TestState *test_state = GetTestState(ssl);
  614. int ret;
  615. do {
  616. if (config->async) {
  617. // The DTLS retransmit logic silently ignores write failures. So the test
  618. // may progress, allow writes through synchronously. |SSL_read| may
  619. // trigger a retransmit, so disconnect the write quota.
  620. AsyncBioEnforceWriteQuota(test_state->async_bio, false);
  621. }
  622. ret = config->peek_then_read ? SSL_peek(ssl, out, max_out)
  623. : SSL_read(ssl, out, max_out);
  624. if (config->async) {
  625. AsyncBioEnforceWriteQuota(test_state->async_bio, true);
  626. }
  627. } while (config->async && RetryAsync(ssl, ret));
  628. if (config->peek_then_read && ret > 0) {
  629. std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
  630. // SSL_peek should synchronously return the same data.
  631. int ret2 = SSL_peek(ssl, buf.get(), ret);
  632. if (ret2 != ret ||
  633. memcmp(buf.get(), out, ret) != 0) {
  634. fprintf(stderr, "First and second SSL_peek did not match.\n");
  635. return -1;
  636. }
  637. // SSL_read should synchronously return the same data and consume it.
  638. ret2 = SSL_read(ssl, buf.get(), ret);
  639. if (ret2 != ret ||
  640. memcmp(buf.get(), out, ret) != 0) {
  641. fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
  642. return -1;
  643. }
  644. }
  645. return ret;
  646. }
  647. // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
  648. // operations. It returns the result of the final |SSL_write| call.
  649. static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
  650. const TestConfig *config = GetTestConfig(ssl);
  651. int ret;
  652. do {
  653. ret = SSL_write(ssl, in, in_len);
  654. if (ret > 0) {
  655. in += ret;
  656. in_len -= ret;
  657. }
  658. } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
  659. return ret;
  660. }
  661. // DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
  662. // returns the result of the final |SSL_shutdown| call.
  663. static int DoShutdown(SSL *ssl) {
  664. const TestConfig *config = GetTestConfig(ssl);
  665. int ret;
  666. do {
  667. ret = SSL_shutdown(ssl);
  668. } while (config->async && RetryAsync(ssl, ret));
  669. return ret;
  670. }
  671. static uint16_t GetProtocolVersion(const SSL *ssl) {
  672. uint16_t version = SSL_version(ssl);
  673. if (!SSL_is_dtls(ssl)) {
  674. return version;
  675. }
  676. return 0x0201 + ~version;
  677. }
  678. // CheckHandshakeProperties checks, immediately after |ssl| completes its
  679. // initial handshake (or False Starts), whether all the properties are
  680. // consistent with the test configuration and invariants.
  681. static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
  682. const TestConfig *config = GetTestConfig(ssl);
  683. if (SSL_get_current_cipher(ssl) == nullptr) {
  684. fprintf(stderr, "null cipher after handshake\n");
  685. return false;
  686. }
  687. if (is_resume &&
  688. (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
  689. fprintf(stderr, "session was%s reused\n",
  690. SSL_session_reused(ssl) ? "" : " not");
  691. return false;
  692. }
  693. if (!GetTestState(ssl)->handshake_done) {
  694. fprintf(stderr, "handshake was not completed\n");
  695. return false;
  696. }
  697. if (!config->is_server) {
  698. bool expect_new_session =
  699. !config->expect_no_session &&
  700. (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
  701. // Session tickets are sent post-handshake in TLS 1.3.
  702. GetProtocolVersion(ssl) < TLS1_3_VERSION;
  703. if (expect_new_session != GetTestState(ssl)->got_new_session) {
  704. fprintf(stderr,
  705. "new session was%s cached, but we expected the opposite\n",
  706. GetTestState(ssl)->got_new_session ? "" : " not");
  707. return false;
  708. }
  709. }
  710. if (!config->expected_server_name.empty()) {
  711. const char *server_name =
  712. SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  713. if (server_name == nullptr ||
  714. std::string(server_name) != config->expected_server_name) {
  715. fprintf(stderr, "servername mismatch (got %s; want %s)\n",
  716. server_name, config->expected_server_name.c_str());
  717. return false;
  718. }
  719. }
  720. if (!config->expected_next_proto.empty()) {
  721. const uint8_t *next_proto;
  722. unsigned next_proto_len;
  723. SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
  724. if (next_proto_len != config->expected_next_proto.size() ||
  725. memcmp(next_proto, config->expected_next_proto.data(),
  726. next_proto_len) != 0) {
  727. fprintf(stderr, "negotiated next proto mismatch\n");
  728. return false;
  729. }
  730. }
  731. if (!config->expected_alpn.empty()) {
  732. const uint8_t *alpn_proto;
  733. unsigned alpn_proto_len;
  734. SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
  735. if (alpn_proto_len != config->expected_alpn.size() ||
  736. memcmp(alpn_proto, config->expected_alpn.data(),
  737. alpn_proto_len) != 0) {
  738. fprintf(stderr, "negotiated alpn proto mismatch\n");
  739. return false;
  740. }
  741. }
  742. if (config->expect_extended_master_secret) {
  743. if (!SSL_get_extms_support(ssl)) {
  744. fprintf(stderr, "No EMS for connection when expected");
  745. return false;
  746. }
  747. }
  748. if (config->expect_verify_result) {
  749. int expected_verify_result = config->verify_fail ?
  750. X509_V_ERR_APPLICATION_VERIFICATION :
  751. X509_V_OK;
  752. if (SSL_get_verify_result(ssl) != expected_verify_result) {
  753. fprintf(stderr, "Wrong certificate verification result\n");
  754. return false;
  755. }
  756. }
  757. if (!config->psk.empty()) {
  758. if (SSL_get_peer_cert_chain(ssl) != nullptr) {
  759. fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
  760. return false;
  761. }
  762. } else if (!config->is_server || config->require_any_client_certificate) {
  763. if (SSL_get_peer_certificate(ssl) == nullptr) {
  764. fprintf(stderr, "Received no peer certificate but expected one.\n");
  765. return false;
  766. }
  767. }
  768. return true;
  769. }
  770. // DoExchange runs a test SSL exchange against the peer. On success, it returns
  771. // true and sets |*out_session| to the negotiated SSL session. If the test is a
  772. // resumption attempt, |is_resume| is true and |session| is the session from the
  773. // previous exchange.
  774. static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
  775. SSL_CTX *ssl_ctx, const TestConfig *config,
  776. bool is_resume, SSL_SESSION *session) {
  777. bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
  778. if (!ssl) {
  779. return false;
  780. }
  781. if (!SetTestConfig(ssl.get(), config) ||
  782. !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
  783. return false;
  784. }
  785. if (config->fallback_scsv &&
  786. !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
  787. return false;
  788. }
  789. // Install the certificate synchronously if nothing else will handle it.
  790. if (!config->use_old_client_cert_callback &&
  791. !config->async &&
  792. !InstallCertificate(ssl.get())) {
  793. return false;
  794. }
  795. SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
  796. if (config->require_any_client_certificate) {
  797. SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  798. NULL);
  799. }
  800. if (config->verify_peer) {
  801. SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
  802. }
  803. if (config->partial_write) {
  804. SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
  805. }
  806. if (config->no_tls13) {
  807. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
  808. }
  809. if (config->no_tls12) {
  810. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
  811. }
  812. if (config->no_tls11) {
  813. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
  814. }
  815. if (config->no_tls1) {
  816. SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
  817. }
  818. if (config->no_ssl3) {
  819. SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
  820. }
  821. if (!config->host_name.empty() &&
  822. !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
  823. return false;
  824. }
  825. if (!config->advertise_alpn.empty() &&
  826. SSL_set_alpn_protos(ssl.get(),
  827. (const uint8_t *)config->advertise_alpn.data(),
  828. config->advertise_alpn.size()) != 0) {
  829. return false;
  830. }
  831. if (!config->psk.empty()) {
  832. SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
  833. SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
  834. }
  835. if (!config->psk_identity.empty() &&
  836. !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
  837. return false;
  838. }
  839. if (!config->srtp_profiles.empty() &&
  840. SSL_set_tlsext_use_srtp(ssl.get(), config->srtp_profiles.c_str())) {
  841. return false;
  842. }
  843. if (config->min_version != 0 &&
  844. !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) {
  845. return false;
  846. }
  847. if (config->max_version != 0 &&
  848. !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) {
  849. return false;
  850. }
  851. if (config->mtu != 0) {
  852. SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
  853. SSL_set_mtu(ssl.get(), config->mtu);
  854. }
  855. if (config->renegotiate_freely) {
  856. // This is always on for OpenSSL.
  857. }
  858. if (!config->check_close_notify) {
  859. SSL_set_quiet_shutdown(ssl.get(), 1);
  860. }
  861. if (config->p384_only) {
  862. int nid = NID_secp384r1;
  863. if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
  864. return false;
  865. }
  866. }
  867. if (config->enable_all_curves) {
  868. static const int kAllCurves[] = {
  869. NID_X25519, NID_X9_62_prime256v1, NID_X448, NID_secp521r1, NID_secp384r1
  870. };
  871. if (!SSL_set1_curves(ssl.get(), kAllCurves,
  872. OPENSSL_ARRAY_SIZE(kAllCurves))) {
  873. return false;
  874. }
  875. }
  876. if (config->max_cert_list > 0) {
  877. SSL_set_max_cert_list(ssl.get(), config->max_cert_list);
  878. }
  879. if (!config->async) {
  880. SSL_set_mode(ssl.get(), SSL_MODE_AUTO_RETRY);
  881. }
  882. int sock = Connect(config->port);
  883. if (sock == -1) {
  884. return false;
  885. }
  886. SocketCloser closer(sock);
  887. bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
  888. if (!bio) {
  889. return false;
  890. }
  891. if (config->is_dtls) {
  892. bssl::UniquePtr<BIO> packeted = PacketedBioCreate(!config->async);
  893. if (!packeted) {
  894. return false;
  895. }
  896. GetTestState(ssl.get())->packeted_bio = packeted.get();
  897. BIO_push(packeted.get(), bio.release());
  898. bio = std::move(packeted);
  899. }
  900. if (config->async) {
  901. bssl::UniquePtr<BIO> async_scoped =
  902. config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
  903. if (!async_scoped) {
  904. return false;
  905. }
  906. BIO_push(async_scoped.get(), bio.release());
  907. GetTestState(ssl.get())->async_bio = async_scoped.get();
  908. bio = std::move(async_scoped);
  909. }
  910. SSL_set_bio(ssl.get(), bio.get(), bio.get());
  911. bio.release(); // SSL_set_bio takes ownership.
  912. if (session != NULL) {
  913. if (!config->is_server) {
  914. if (SSL_set_session(ssl.get(), session) != 1) {
  915. return false;
  916. }
  917. }
  918. }
  919. #if 0
  920. // KNOWN BUG: OpenSSL's SSL_get_current_cipher behaves incorrectly when
  921. // offering resumption.
  922. if (SSL_get_current_cipher(ssl.get()) != nullptr) {
  923. fprintf(stderr, "non-null cipher before handshake\n");
  924. return false;
  925. }
  926. #endif
  927. int ret;
  928. if (config->implicit_handshake) {
  929. if (config->is_server) {
  930. SSL_set_accept_state(ssl.get());
  931. } else {
  932. SSL_set_connect_state(ssl.get());
  933. }
  934. } else {
  935. do {
  936. if (config->is_server) {
  937. ret = SSL_accept(ssl.get());
  938. } else {
  939. ret = SSL_connect(ssl.get());
  940. }
  941. } while (config->async && RetryAsync(ssl.get(), ret));
  942. if (ret != 1 ||
  943. !CheckHandshakeProperties(ssl.get(), is_resume)) {
  944. return false;
  945. }
  946. // Reset the state to assert later that the callback isn't called in
  947. // renegotiations.
  948. GetTestState(ssl.get())->got_new_session = false;
  949. }
  950. if (config->export_keying_material > 0) {
  951. std::vector<uint8_t> result(
  952. static_cast<size_t>(config->export_keying_material));
  953. if (SSL_export_keying_material(
  954. ssl.get(), result.data(), result.size(),
  955. config->export_label.data(), config->export_label.size(),
  956. reinterpret_cast<const uint8_t*>(config->export_context.data()),
  957. config->export_context.size(), config->use_export_context) != 1) {
  958. fprintf(stderr, "failed to export keying material\n");
  959. return false;
  960. }
  961. if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
  962. return false;
  963. }
  964. }
  965. if (config->write_different_record_sizes) {
  966. if (config->is_dtls) {
  967. fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
  968. return false;
  969. }
  970. // This mode writes a number of different record sizes in an attempt to
  971. // trip up the CBC record splitting code.
  972. static const size_t kBufLen = 32769;
  973. std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
  974. memset(buf.get(), 0x42, kBufLen);
  975. static const size_t kRecordSizes[] = {
  976. 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
  977. for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
  978. const size_t len = kRecordSizes[i];
  979. if (len > kBufLen) {
  980. fprintf(stderr, "Bad kRecordSizes value.\n");
  981. return false;
  982. }
  983. if (WriteAll(ssl.get(), buf.get(), len) < 0) {
  984. return false;
  985. }
  986. }
  987. } else {
  988. if (config->shim_writes_first) {
  989. if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
  990. 5) < 0) {
  991. return false;
  992. }
  993. }
  994. if (!config->shim_shuts_down) {
  995. for (;;) {
  996. static const size_t kBufLen = 16384;
  997. std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
  998. // Read only 512 bytes at a time in TLS to ensure records may be
  999. // returned in multiple reads.
  1000. int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
  1001. int err = SSL_get_error(ssl.get(), n);
  1002. if (err == SSL_ERROR_ZERO_RETURN ||
  1003. (n == 0 && err == SSL_ERROR_SYSCALL)) {
  1004. if (n != 0) {
  1005. fprintf(stderr, "Invalid SSL_get_error output\n");
  1006. return false;
  1007. }
  1008. // Stop on either clean or unclean shutdown.
  1009. break;
  1010. } else if (err != SSL_ERROR_NONE) {
  1011. if (n > 0) {
  1012. fprintf(stderr, "Invalid SSL_get_error output\n");
  1013. return false;
  1014. }
  1015. return false;
  1016. }
  1017. // Successfully read data.
  1018. if (n <= 0) {
  1019. fprintf(stderr, "Invalid SSL_get_error output\n");
  1020. return false;
  1021. }
  1022. // After a successful read, with or without False Start, the handshake
  1023. // must be complete.
  1024. if (!GetTestState(ssl.get())->handshake_done) {
  1025. fprintf(stderr, "handshake was not completed after SSL_read\n");
  1026. return false;
  1027. }
  1028. for (int i = 0; i < n; i++) {
  1029. buf[i] ^= 0xff;
  1030. }
  1031. if (WriteAll(ssl.get(), buf.get(), n) < 0) {
  1032. return false;
  1033. }
  1034. }
  1035. }
  1036. }
  1037. if (!config->is_server &&
  1038. !config->implicit_handshake &&
  1039. // Session tickets are sent post-handshake in TLS 1.3.
  1040. GetProtocolVersion(ssl.get()) < TLS1_3_VERSION &&
  1041. GetTestState(ssl.get())->got_new_session) {
  1042. fprintf(stderr, "new session was established after the handshake\n");
  1043. return false;
  1044. }
  1045. if (GetProtocolVersion(ssl.get()) >= TLS1_3_VERSION && !config->is_server) {
  1046. bool expect_new_session =
  1047. !config->expect_no_session && !config->shim_shuts_down;
  1048. if (expect_new_session != GetTestState(ssl.get())->got_new_session) {
  1049. fprintf(stderr,
  1050. "new session was%s cached, but we expected the opposite\n",
  1051. GetTestState(ssl.get())->got_new_session ? "" : " not");
  1052. return false;
  1053. }
  1054. }
  1055. if (out_session) {
  1056. *out_session = std::move(GetTestState(ssl.get())->new_session);
  1057. }
  1058. ret = DoShutdown(ssl.get());
  1059. if (config->shim_shuts_down && config->check_close_notify) {
  1060. // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
  1061. // it returns zero when our close_notify is sent, then one when the peer's
  1062. // is received.
  1063. if (ret != 0) {
  1064. fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
  1065. return false;
  1066. }
  1067. ret = DoShutdown(ssl.get());
  1068. }
  1069. if (ret != 1) {
  1070. fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
  1071. return false;
  1072. }
  1073. if (SSL_total_renegotiations(ssl.get()) !=
  1074. config->expect_total_renegotiations) {
  1075. fprintf(stderr, "Expected %d renegotiations, got %ld\n",
  1076. config->expect_total_renegotiations,
  1077. SSL_total_renegotiations(ssl.get()));
  1078. return false;
  1079. }
  1080. return true;
  1081. }
  1082. class StderrDelimiter {
  1083. public:
  1084. ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
  1085. };
  1086. static int Main(int argc, char **argv) {
  1087. // To distinguish ASan's output from ours, add a trailing message to stderr.
  1088. // Anything following this line will be considered an error.
  1089. StderrDelimiter delimiter;
  1090. #if defined(OPENSSL_SYS_WINDOWS)
  1091. /* Initialize Winsock. */
  1092. WORD wsa_version = MAKEWORD(2, 2);
  1093. WSADATA wsa_data;
  1094. int wsa_err = WSAStartup(wsa_version, &wsa_data);
  1095. if (wsa_err != 0) {
  1096. fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
  1097. return 1;
  1098. }
  1099. if (wsa_data.wVersion != wsa_version) {
  1100. fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
  1101. return 1;
  1102. }
  1103. #else
  1104. signal(SIGPIPE, SIG_IGN);
  1105. #endif
  1106. OPENSSL_init_crypto(0, NULL);
  1107. OPENSSL_init_ssl(0, NULL);
  1108. g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  1109. g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
  1110. if (g_config_index < 0 || g_state_index < 0) {
  1111. return 1;
  1112. }
  1113. TestConfig config;
  1114. if (!ParseConfig(argc - 1, argv + 1, &config)) {
  1115. return Usage(argv[0]);
  1116. }
  1117. bssl::UniquePtr<SSL_CTX> ssl_ctx = SetupCtx(&config);
  1118. if (!ssl_ctx) {
  1119. ERR_print_errors_fp(stderr);
  1120. return 1;
  1121. }
  1122. bssl::UniquePtr<SSL_SESSION> session;
  1123. for (int i = 0; i < config.resume_count + 1; i++) {
  1124. bool is_resume = i > 0;
  1125. if (is_resume && !config.is_server && !session) {
  1126. fprintf(stderr, "No session to offer.\n");
  1127. return 1;
  1128. }
  1129. bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
  1130. if (!DoExchange(&session, ssl_ctx.get(), &config, is_resume,
  1131. offer_session.get())) {
  1132. fprintf(stderr, "Connection %d failed.\n", i + 1);
  1133. ERR_print_errors_fp(stderr);
  1134. return 1;
  1135. }
  1136. }
  1137. return 0;
  1138. }
  1139. } // namespace bssl
  1140. int main(int argc, char **argv) {
  1141. return bssl::Main(argc, argv);
  1142. }