2
0

ossl_shim.cc 38 KB

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