ossl_shim.cc 39 KB

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