bssl_shim.cc 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  1. /* Copyright (c) 2014, Google Inc.
  2. *
  3. * Permission to use, copy, modify, and/or distribute this software for any
  4. * purpose with or without fee is hereby granted, provided that the above
  5. * copyright notice and this permission notice appear in all copies.
  6. *
  7. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  10. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  12. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  14. #include <openssl/base.h>
  15. #if !defined(OPENSSL_WINDOWS)
  16. #include <arpa/inet.h>
  17. #include <netinet/in.h>
  18. #include <netinet/tcp.h>
  19. #include <signal.h>
  20. #include <sys/socket.h>
  21. #include <sys/time.h>
  22. #include <unistd.h>
  23. #else
  24. #include <io.h>
  25. OPENSSL_MSVC_PRAGMA(warning(push, 3))
  26. #include <winsock2.h>
  27. #include <ws2tcpip.h>
  28. OPENSSL_MSVC_PRAGMA(warning(pop))
  29. OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
  30. #endif
  31. #include <assert.h>
  32. #include <inttypes.h>
  33. #include <string.h>
  34. #include <time.h>
  35. #include <openssl/aead.h>
  36. #include <openssl/bio.h>
  37. #include <openssl/buf.h>
  38. #include <openssl/bytestring.h>
  39. #include <openssl/cipher.h>
  40. #include <openssl/crypto.h>
  41. #include <openssl/digest.h>
  42. #include <openssl/err.h>
  43. #include <openssl/evp.h>
  44. #include <openssl/hmac.h>
  45. #include <openssl/nid.h>
  46. #include <openssl/rand.h>
  47. #include <openssl/ssl.h>
  48. #include <openssl/x509.h>
  49. #include <functional>
  50. #include <memory>
  51. #include <string>
  52. #include <vector>
  53. #include "../../crypto/internal.h"
  54. #include "../internal.h"
  55. #include "async_bio.h"
  56. #include "handshake_util.h"
  57. #include "packeted_bio.h"
  58. #include "settings_writer.h"
  59. #include "test_config.h"
  60. #include "test_state.h"
  61. #if defined(OPENSSL_LINUX) && !defined(OPENSSL_ANDROID)
  62. #define HANDSHAKER_SUPPORTED
  63. #endif
  64. #if !defined(OPENSSL_WINDOWS)
  65. static int closesocket(int sock) {
  66. return close(sock);
  67. }
  68. static void PrintSocketError(const char *func) {
  69. perror(func);
  70. }
  71. #else
  72. static void PrintSocketError(const char *func) {
  73. fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
  74. }
  75. #endif
  76. static int Usage(const char *program) {
  77. fprintf(stderr, "Usage: %s [flags...]\n", program);
  78. return 1;
  79. }
  80. template<typename T>
  81. struct Free {
  82. void operator()(T *buf) {
  83. free(buf);
  84. }
  85. };
  86. // Connect returns a new socket connected to localhost on |port| or -1 on
  87. // error.
  88. static int Connect(uint16_t port) {
  89. for (int af : { AF_INET6, AF_INET }) {
  90. int sock = socket(af, SOCK_STREAM, 0);
  91. if (sock == -1) {
  92. PrintSocketError("socket");
  93. return -1;
  94. }
  95. int nodelay = 1;
  96. if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  97. reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
  98. PrintSocketError("setsockopt");
  99. closesocket(sock);
  100. return -1;
  101. }
  102. sockaddr_storage ss;
  103. OPENSSL_memset(&ss, 0, sizeof(ss));
  104. ss.ss_family = af;
  105. socklen_t len = 0;
  106. if (af == AF_INET6) {
  107. sockaddr_in6 *sin6 = (sockaddr_in6 *) &ss;
  108. len = sizeof(*sin6);
  109. sin6->sin6_port = htons(port);
  110. if (!inet_pton(AF_INET6, "::1", &sin6->sin6_addr)) {
  111. PrintSocketError("inet_pton");
  112. closesocket(sock);
  113. return -1;
  114. }
  115. } else if (af == AF_INET) {
  116. sockaddr_in *sin = (sockaddr_in *) &ss;
  117. len = sizeof(*sin);
  118. sin->sin_port = htons(port);
  119. if (!inet_pton(AF_INET, "127.0.0.1", &sin->sin_addr)) {
  120. PrintSocketError("inet_pton");
  121. closesocket(sock);
  122. return -1;
  123. }
  124. }
  125. if (connect(sock, reinterpret_cast<const sockaddr*>(&ss), len) == 0) {
  126. return sock;
  127. }
  128. closesocket(sock);
  129. }
  130. PrintSocketError("connect");
  131. return -1;
  132. }
  133. class SocketCloser {
  134. public:
  135. explicit SocketCloser(int sock) : sock_(sock) {}
  136. ~SocketCloser() {
  137. // Half-close and drain the socket before releasing it. This seems to be
  138. // necessary for graceful shutdown on Windows. It will also avoid write
  139. // failures in the test runner.
  140. #if defined(OPENSSL_WINDOWS)
  141. shutdown(sock_, SD_SEND);
  142. #else
  143. shutdown(sock_, SHUT_WR);
  144. #endif
  145. while (true) {
  146. char buf[1024];
  147. if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
  148. break;
  149. }
  150. }
  151. closesocket(sock_);
  152. }
  153. private:
  154. const int sock_;
  155. };
  156. // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
  157. // the result value of the final |SSL_read| call.
  158. static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
  159. const TestConfig *config = GetTestConfig(ssl);
  160. TestState *test_state = GetTestState(ssl);
  161. int ret;
  162. do {
  163. if (config->async) {
  164. // The DTLS retransmit logic silently ignores write failures. So the test
  165. // may progress, allow writes through synchronously. |SSL_read| may
  166. // trigger a retransmit, so disconnect the write quota.
  167. AsyncBioEnforceWriteQuota(test_state->async_bio, false);
  168. }
  169. ret = CheckIdempotentError("SSL_peek/SSL_read", ssl, [&]() -> int {
  170. return config->peek_then_read ? SSL_peek(ssl, out, max_out)
  171. : SSL_read(ssl, out, max_out);
  172. });
  173. if (config->async) {
  174. AsyncBioEnforceWriteQuota(test_state->async_bio, true);
  175. }
  176. // Run the exporter after each read. This is to test that the exporter fails
  177. // during a renegotiation.
  178. if (config->use_exporter_between_reads) {
  179. uint8_t buf;
  180. if (!SSL_export_keying_material(ssl, &buf, 1, NULL, 0, NULL, 0, 0)) {
  181. fprintf(stderr, "failed to export keying material\n");
  182. return -1;
  183. }
  184. }
  185. } while (RetryAsync(ssl, ret));
  186. if (config->peek_then_read && ret > 0) {
  187. std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
  188. // SSL_peek should synchronously return the same data.
  189. int ret2 = SSL_peek(ssl, buf.get(), ret);
  190. if (ret2 != ret ||
  191. OPENSSL_memcmp(buf.get(), out, ret) != 0) {
  192. fprintf(stderr, "First and second SSL_peek did not match.\n");
  193. return -1;
  194. }
  195. // SSL_read should synchronously return the same data and consume it.
  196. ret2 = SSL_read(ssl, buf.get(), ret);
  197. if (ret2 != ret ||
  198. OPENSSL_memcmp(buf.get(), out, ret) != 0) {
  199. fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
  200. return -1;
  201. }
  202. }
  203. return ret;
  204. }
  205. // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
  206. // operations. It returns the result of the final |SSL_write| call.
  207. static int WriteAll(SSL *ssl, const void *in_, size_t in_len) {
  208. const uint8_t *in = reinterpret_cast<const uint8_t *>(in_);
  209. int ret;
  210. do {
  211. ret = SSL_write(ssl, in, in_len);
  212. if (ret > 0) {
  213. in += ret;
  214. in_len -= ret;
  215. }
  216. } while (RetryAsync(ssl, ret) || (ret > 0 && in_len > 0));
  217. return ret;
  218. }
  219. // DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
  220. // returns the result of the final |SSL_shutdown| call.
  221. static int DoShutdown(SSL *ssl) {
  222. int ret;
  223. do {
  224. ret = SSL_shutdown(ssl);
  225. } while (RetryAsync(ssl, ret));
  226. return ret;
  227. }
  228. // DoSendFatalAlert calls |SSL_send_fatal_alert|, resolving any asynchronous
  229. // operations. It returns the result of the final |SSL_send_fatal_alert| call.
  230. static int DoSendFatalAlert(SSL *ssl, uint8_t alert) {
  231. int ret;
  232. do {
  233. ret = SSL_send_fatal_alert(ssl, alert);
  234. } while (RetryAsync(ssl, ret));
  235. return ret;
  236. }
  237. static uint16_t GetProtocolVersion(const SSL *ssl) {
  238. uint16_t version = SSL_version(ssl);
  239. if (!SSL_is_dtls(ssl)) {
  240. return version;
  241. }
  242. return 0x0201 + ~version;
  243. }
  244. // CheckAuthProperties checks, after the initial handshake is completed or
  245. // after a renegotiation, that authentication-related properties match |config|.
  246. static bool CheckAuthProperties(SSL *ssl, bool is_resume,
  247. const TestConfig *config) {
  248. if (!config->expect_ocsp_response.empty()) {
  249. const uint8_t *data;
  250. size_t len;
  251. SSL_get0_ocsp_response(ssl, &data, &len);
  252. if (config->expect_ocsp_response.size() != len ||
  253. OPENSSL_memcmp(config->expect_ocsp_response.data(), data, len) != 0) {
  254. fprintf(stderr, "OCSP response mismatch\n");
  255. return false;
  256. }
  257. }
  258. if (!config->expect_signed_cert_timestamps.empty()) {
  259. const uint8_t *data;
  260. size_t len;
  261. SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
  262. if (config->expect_signed_cert_timestamps.size() != len ||
  263. OPENSSL_memcmp(config->expect_signed_cert_timestamps.data(), data,
  264. len) != 0) {
  265. fprintf(stderr, "SCT list mismatch\n");
  266. return false;
  267. }
  268. }
  269. if (config->expect_verify_result) {
  270. int expected_verify_result = config->verify_fail ?
  271. X509_V_ERR_APPLICATION_VERIFICATION :
  272. X509_V_OK;
  273. if (SSL_get_verify_result(ssl) != expected_verify_result) {
  274. fprintf(stderr, "Wrong certificate verification result\n");
  275. return false;
  276. }
  277. }
  278. if (!config->expect_peer_cert_file.empty()) {
  279. bssl::UniquePtr<X509> expect_leaf;
  280. bssl::UniquePtr<STACK_OF(X509)> expect_chain;
  281. if (!LoadCertificate(&expect_leaf, &expect_chain,
  282. config->expect_peer_cert_file)) {
  283. return false;
  284. }
  285. // For historical reasons, clients report a chain with a leaf and servers
  286. // without.
  287. if (!config->is_server) {
  288. if (!sk_X509_insert(expect_chain.get(), expect_leaf.get(), 0)) {
  289. return false;
  290. }
  291. X509_up_ref(expect_leaf.get()); // sk_X509_insert takes ownership.
  292. }
  293. bssl::UniquePtr<X509> leaf(SSL_get_peer_certificate(ssl));
  294. STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl);
  295. if (X509_cmp(leaf.get(), expect_leaf.get()) != 0) {
  296. fprintf(stderr, "Received a different leaf certificate than expected.\n");
  297. return false;
  298. }
  299. if (sk_X509_num(chain) != sk_X509_num(expect_chain.get())) {
  300. fprintf(stderr, "Received a chain of length %zu instead of %zu.\n",
  301. sk_X509_num(chain), sk_X509_num(expect_chain.get()));
  302. return false;
  303. }
  304. for (size_t i = 0; i < sk_X509_num(chain); i++) {
  305. if (X509_cmp(sk_X509_value(chain, i),
  306. sk_X509_value(expect_chain.get(), i)) != 0) {
  307. fprintf(stderr, "Chain certificate %zu did not match.\n",
  308. i + 1);
  309. return false;
  310. }
  311. }
  312. }
  313. if (!!SSL_SESSION_has_peer_sha256(SSL_get_session(ssl)) !=
  314. config->expect_sha256_client_cert) {
  315. fprintf(stderr,
  316. "Unexpected SHA-256 client cert state: expected:%d is_resume:%d.\n",
  317. config->expect_sha256_client_cert, is_resume);
  318. return false;
  319. }
  320. if (config->expect_sha256_client_cert &&
  321. SSL_SESSION_get0_peer_certificates(SSL_get_session(ssl)) != nullptr) {
  322. fprintf(stderr, "Have both client cert and SHA-256 hash: is_resume:%d.\n",
  323. is_resume);
  324. return false;
  325. }
  326. const uint8_t *peer_sha256;
  327. size_t peer_sha256_len;
  328. SSL_SESSION_get0_peer_sha256(SSL_get_session(ssl), &peer_sha256,
  329. &peer_sha256_len);
  330. if (SSL_SESSION_has_peer_sha256(SSL_get_session(ssl))) {
  331. if (peer_sha256_len != 32) {
  332. fprintf(stderr, "Peer SHA-256 hash had length %zu instead of 32\n",
  333. peer_sha256_len);
  334. return false;
  335. }
  336. } else {
  337. if (peer_sha256_len != 0) {
  338. fprintf(stderr, "Unexpected peer SHA-256 hash of length %zu\n",
  339. peer_sha256_len);
  340. return false;
  341. }
  342. }
  343. return true;
  344. }
  345. static const char *EarlyDataReasonToString(ssl_early_data_reason_t reason) {
  346. switch (reason) {
  347. case ssl_early_data_unknown:
  348. return "unknown";
  349. case ssl_early_data_disabled:
  350. return "disabled";
  351. case ssl_early_data_accepted:
  352. return "accepted";
  353. case ssl_early_data_protocol_version:
  354. return "protocol_version";
  355. case ssl_early_data_peer_declined:
  356. return "peer_declined";
  357. case ssl_early_data_no_session_offered:
  358. return "no_session_offered";
  359. case ssl_early_data_session_not_resumed:
  360. return "session_not_resumed";
  361. case ssl_early_data_unsupported_for_session:
  362. return "unsupported_for_session";
  363. case ssl_early_data_hello_retry_request:
  364. return "hello_retry_request";
  365. case ssl_early_data_alpn_mismatch:
  366. return "alpn_mismatch";
  367. case ssl_early_data_channel_id:
  368. return "channel_id";
  369. case ssl_early_data_token_binding:
  370. return "token_binding";
  371. case ssl_early_data_ticket_age_skew:
  372. return "ticket_age_skew";
  373. }
  374. abort();
  375. }
  376. // CheckHandshakeProperties checks, immediately after |ssl| completes its
  377. // initial handshake (or False Starts), whether all the properties are
  378. // consistent with the test configuration and invariants.
  379. static bool CheckHandshakeProperties(SSL *ssl, bool is_resume,
  380. const TestConfig *config) {
  381. if (!CheckAuthProperties(ssl, is_resume, config)) {
  382. return false;
  383. }
  384. if (SSL_get_current_cipher(ssl) == nullptr) {
  385. fprintf(stderr, "null cipher after handshake\n");
  386. return false;
  387. }
  388. if (config->expect_version != 0 &&
  389. SSL_version(ssl) != config->expect_version) {
  390. fprintf(stderr, "want version %04x, got %04x\n", config->expect_version,
  391. SSL_version(ssl));
  392. return false;
  393. }
  394. bool expect_resume =
  395. is_resume && (!config->expect_session_miss || SSL_in_early_data(ssl));
  396. if (!!SSL_session_reused(ssl) != expect_resume) {
  397. fprintf(stderr, "session unexpectedly was%s reused\n",
  398. SSL_session_reused(ssl) ? "" : " not");
  399. return false;
  400. }
  401. bool expect_handshake_done =
  402. (is_resume || !config->false_start) && !SSL_in_early_data(ssl);
  403. if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
  404. fprintf(stderr, "handshake was%s completed\n",
  405. GetTestState(ssl)->handshake_done ? "" : " not");
  406. return false;
  407. }
  408. if (expect_handshake_done && !config->is_server) {
  409. bool expect_new_session =
  410. !config->expect_no_session &&
  411. (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
  412. // Session tickets are sent post-handshake in TLS 1.3.
  413. GetProtocolVersion(ssl) < TLS1_3_VERSION;
  414. if (expect_new_session != GetTestState(ssl)->got_new_session) {
  415. fprintf(stderr,
  416. "new session was%s cached, but we expected the opposite\n",
  417. GetTestState(ssl)->got_new_session ? "" : " not");
  418. return false;
  419. }
  420. }
  421. if (!is_resume) {
  422. if (config->expect_session_id && !GetTestState(ssl)->got_new_session) {
  423. fprintf(stderr, "session was not cached on the server.\n");
  424. return false;
  425. }
  426. if (config->expect_no_session_id && GetTestState(ssl)->got_new_session) {
  427. fprintf(stderr, "session was unexpectedly cached on the server.\n");
  428. return false;
  429. }
  430. }
  431. // early_callback_called is updated in the handshaker, so we don't see it
  432. // here.
  433. if (!config->handoff && config->is_server &&
  434. !GetTestState(ssl)->early_callback_called) {
  435. fprintf(stderr, "early callback not called\n");
  436. return false;
  437. }
  438. if (!config->expect_server_name.empty()) {
  439. const char *server_name =
  440. SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  441. if (server_name == nullptr ||
  442. server_name != config->expect_server_name) {
  443. fprintf(stderr, "servername mismatch (got %s; want %s)\n",
  444. server_name, config->expect_server_name.c_str());
  445. return false;
  446. }
  447. }
  448. if (!config->expect_next_proto.empty()) {
  449. const uint8_t *next_proto;
  450. unsigned next_proto_len;
  451. SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
  452. if (next_proto_len != config->expect_next_proto.size() ||
  453. OPENSSL_memcmp(next_proto, config->expect_next_proto.data(),
  454. next_proto_len) != 0) {
  455. fprintf(stderr, "negotiated next proto mismatch\n");
  456. return false;
  457. }
  458. }
  459. if (!config->is_server) {
  460. const uint8_t *alpn_proto;
  461. unsigned alpn_proto_len;
  462. SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
  463. if (alpn_proto_len != config->expect_alpn.size() ||
  464. OPENSSL_memcmp(alpn_proto, config->expect_alpn.data(),
  465. alpn_proto_len) != 0) {
  466. fprintf(stderr, "negotiated alpn proto mismatch\n");
  467. return false;
  468. }
  469. }
  470. if (!config->expect_quic_transport_params.empty()) {
  471. const uint8_t *peer_params;
  472. size_t peer_params_len;
  473. SSL_get_peer_quic_transport_params(ssl, &peer_params, &peer_params_len);
  474. if (peer_params_len != config->expect_quic_transport_params.size() ||
  475. OPENSSL_memcmp(peer_params,
  476. config->expect_quic_transport_params.data(),
  477. peer_params_len) != 0) {
  478. fprintf(stderr, "QUIC transport params mismatch\n");
  479. return false;
  480. }
  481. }
  482. if (!config->expect_channel_id.empty()) {
  483. uint8_t channel_id[64];
  484. if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
  485. fprintf(stderr, "no channel id negotiated\n");
  486. return false;
  487. }
  488. if (config->expect_channel_id.size() != 64 ||
  489. OPENSSL_memcmp(config->expect_channel_id.data(), channel_id, 64) !=
  490. 0) {
  491. fprintf(stderr, "channel id mismatch\n");
  492. return false;
  493. }
  494. }
  495. if (config->expect_token_binding_param != -1) {
  496. if (!SSL_is_token_binding_negotiated(ssl)) {
  497. fprintf(stderr, "no Token Binding negotiated\n");
  498. return false;
  499. }
  500. if (SSL_get_negotiated_token_binding_param(ssl) !=
  501. static_cast<uint8_t>(config->expect_token_binding_param)) {
  502. fprintf(stderr, "Token Binding param mismatch\n");
  503. return false;
  504. }
  505. }
  506. if (config->expect_extended_master_secret && !SSL_get_extms_support(ssl)) {
  507. fprintf(stderr, "No EMS for connection when expected\n");
  508. return false;
  509. }
  510. if (config->expect_secure_renegotiation &&
  511. !SSL_get_secure_renegotiation_support(ssl)) {
  512. fprintf(stderr, "No secure renegotiation for connection when expected\n");
  513. return false;
  514. }
  515. if (config->expect_no_secure_renegotiation &&
  516. SSL_get_secure_renegotiation_support(ssl)) {
  517. fprintf(stderr,
  518. "Secure renegotiation unexpectedly negotiated for connection\n");
  519. return false;
  520. }
  521. if (config->expect_peer_signature_algorithm != 0 &&
  522. config->expect_peer_signature_algorithm !=
  523. SSL_get_peer_signature_algorithm(ssl)) {
  524. fprintf(stderr, "Peer signature algorithm was %04x, wanted %04x.\n",
  525. SSL_get_peer_signature_algorithm(ssl),
  526. config->expect_peer_signature_algorithm);
  527. return false;
  528. }
  529. if (config->expect_curve_id != 0) {
  530. uint16_t curve_id = SSL_get_curve_id(ssl);
  531. if (static_cast<uint16_t>(config->expect_curve_id) != curve_id) {
  532. fprintf(stderr, "curve_id was %04x, wanted %04x\n", curve_id,
  533. static_cast<uint16_t>(config->expect_curve_id));
  534. return false;
  535. }
  536. }
  537. uint16_t cipher_id =
  538. static_cast<uint16_t>(SSL_CIPHER_get_id(SSL_get_current_cipher(ssl)));
  539. if (config->expect_cipher_aes != 0 &&
  540. EVP_has_aes_hardware() &&
  541. static_cast<uint16_t>(config->expect_cipher_aes) != cipher_id) {
  542. fprintf(stderr, "Cipher ID was %04x, wanted %04x (has AES hardware)\n",
  543. cipher_id, static_cast<uint16_t>(config->expect_cipher_aes));
  544. return false;
  545. }
  546. if (config->expect_cipher_no_aes != 0 &&
  547. !EVP_has_aes_hardware() &&
  548. static_cast<uint16_t>(config->expect_cipher_no_aes) != cipher_id) {
  549. fprintf(stderr, "Cipher ID was %04x, wanted %04x (no AES hardware)\n",
  550. cipher_id, static_cast<uint16_t>(config->expect_cipher_no_aes));
  551. return false;
  552. }
  553. // The early data status is only applicable after the handshake is confirmed.
  554. if (!SSL_in_early_data(ssl)) {
  555. if ((config->expect_accept_early_data && !SSL_early_data_accepted(ssl)) ||
  556. (config->expect_reject_early_data && SSL_early_data_accepted(ssl))) {
  557. fprintf(stderr,
  558. "Early data was%s accepted, but we expected the opposite\n",
  559. SSL_early_data_accepted(ssl) ? "" : " not");
  560. return false;
  561. }
  562. const char *early_data_reason =
  563. EarlyDataReasonToString(SSL_get_early_data_reason(ssl));
  564. if (!config->expect_early_data_reason.empty() &&
  565. config->expect_early_data_reason != early_data_reason) {
  566. fprintf(stderr, "Early data reason was \"%s\", expected \"%s\"\n",
  567. early_data_reason, config->expect_early_data_reason.c_str());
  568. return false;
  569. }
  570. }
  571. if (!config->psk.empty()) {
  572. if (SSL_get_peer_cert_chain(ssl) != nullptr) {
  573. fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
  574. return false;
  575. }
  576. } else if (!config->is_server || config->require_any_client_certificate) {
  577. if (SSL_get_peer_cert_chain(ssl) == nullptr) {
  578. fprintf(stderr, "Received no peer certificate but expected one.\n");
  579. return false;
  580. }
  581. }
  582. if (is_resume && config->expect_ticket_age_skew != 0 &&
  583. SSL_get_ticket_age_skew(ssl) != config->expect_ticket_age_skew) {
  584. fprintf(stderr, "Ticket age skew was %" PRId32 ", wanted %d\n",
  585. SSL_get_ticket_age_skew(ssl), config->expect_ticket_age_skew);
  586. return false;
  587. }
  588. if (config->expect_tls13_downgrade != !!SSL_is_tls13_downgrade(ssl)) {
  589. fprintf(stderr, "Got %s downgrade signal, but wanted the opposite.\n",
  590. SSL_is_tls13_downgrade(ssl) ? "" : "no ");
  591. return false;
  592. }
  593. if (config->expect_delegated_credential_used !=
  594. !!SSL_delegated_credential_used(ssl)) {
  595. fprintf(stderr,
  596. "Got %s delegated credential usage, but wanted opposite. \n",
  597. SSL_delegated_credential_used(ssl) ? "" : "no");
  598. return false;
  599. }
  600. if (config->expect_pq_experiment_signal !=
  601. !!SSL_pq_experiment_signal_seen(ssl)) {
  602. fprintf(stderr, "Got %sPQ experiment signal, but wanted opposite. \n",
  603. SSL_pq_experiment_signal_seen(ssl) ? "" : "no ");
  604. return false;
  605. }
  606. return true;
  607. }
  608. static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
  609. bssl::UniquePtr<SSL> *ssl_uniqueptr,
  610. const TestConfig *config, bool is_resume, bool is_retry,
  611. SettingsWriter *writer);
  612. // DoConnection tests an SSL connection against the peer. On success, it returns
  613. // true and sets |*out_session| to the negotiated SSL session. If the test is a
  614. // resumption attempt, |is_resume| is true and |session| is the session from the
  615. // previous exchange.
  616. static bool DoConnection(bssl::UniquePtr<SSL_SESSION> *out_session,
  617. SSL_CTX *ssl_ctx, const TestConfig *config,
  618. const TestConfig *retry_config, bool is_resume,
  619. SSL_SESSION *session, SettingsWriter *writer) {
  620. bssl::UniquePtr<SSL> ssl = config->NewSSL(
  621. ssl_ctx, session, is_resume, std::unique_ptr<TestState>(new TestState));
  622. if (!ssl) {
  623. return false;
  624. }
  625. if (config->is_server) {
  626. SSL_set_accept_state(ssl.get());
  627. } else {
  628. SSL_set_connect_state(ssl.get());
  629. }
  630. int sock = Connect(config->port);
  631. if (sock == -1) {
  632. return false;
  633. }
  634. SocketCloser closer(sock);
  635. bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
  636. if (!bio) {
  637. return false;
  638. }
  639. if (config->is_dtls) {
  640. bssl::UniquePtr<BIO> packeted = PacketedBioCreate(GetClock());
  641. if (!packeted) {
  642. return false;
  643. }
  644. GetTestState(ssl.get())->packeted_bio = packeted.get();
  645. BIO_push(packeted.get(), bio.release());
  646. bio = std::move(packeted);
  647. }
  648. if (config->async) {
  649. bssl::UniquePtr<BIO> async_scoped =
  650. config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
  651. if (!async_scoped) {
  652. return false;
  653. }
  654. BIO_push(async_scoped.get(), bio.release());
  655. GetTestState(ssl.get())->async_bio = async_scoped.get();
  656. bio = std::move(async_scoped);
  657. }
  658. SSL_set_bio(ssl.get(), bio.get(), bio.get());
  659. bio.release(); // SSL_set_bio takes ownership.
  660. bool ret = DoExchange(out_session, &ssl, config, is_resume, false, writer);
  661. if (!config->is_server && is_resume && config->expect_reject_early_data) {
  662. // We must have failed due to an early data rejection.
  663. if (ret) {
  664. fprintf(stderr, "0-RTT exchange unexpected succeeded.\n");
  665. return false;
  666. }
  667. if (SSL_get_error(ssl.get(), -1) != SSL_ERROR_EARLY_DATA_REJECTED) {
  668. fprintf(stderr,
  669. "SSL_get_error did not signal SSL_ERROR_EARLY_DATA_REJECTED.\n");
  670. return false;
  671. }
  672. // Before reseting, early state should still be available.
  673. if (!SSL_in_early_data(ssl.get()) ||
  674. !CheckHandshakeProperties(ssl.get(), is_resume, config)) {
  675. fprintf(stderr, "SSL_in_early_data returned false before reset.\n");
  676. return false;
  677. }
  678. // Client pre- and post-0-RTT reject states are considered logically
  679. // different connections with different test expections. Check that the test
  680. // did not mistakenly configure reason expectations on the wrong one.
  681. if (!config->expect_early_data_reason.empty()) {
  682. fprintf(stderr,
  683. "Test error: client reject -expect-early-data-reason flags "
  684. "should be configured with -on-retry, not -on-resume.\n");
  685. return false;
  686. }
  687. // Reset the connection and try again at 1-RTT.
  688. SSL_reset_early_data_reject(ssl.get());
  689. GetTestState(ssl.get())->cert_verified = false;
  690. // After reseting, the socket should report it is no longer in an early data
  691. // state.
  692. if (SSL_in_early_data(ssl.get())) {
  693. fprintf(stderr, "SSL_in_early_data returned true after reset.\n");
  694. return false;
  695. }
  696. if (!SetTestConfig(ssl.get(), retry_config)) {
  697. return false;
  698. }
  699. assert(!config->handoff);
  700. ret = DoExchange(out_session, &ssl, retry_config, is_resume, true, writer);
  701. }
  702. if (!ret) {
  703. return false;
  704. }
  705. if (!GetTestState(ssl.get())->msg_callback_ok) {
  706. return false;
  707. }
  708. if (!config->expect_msg_callback.empty() &&
  709. GetTestState(ssl.get())->msg_callback_text !=
  710. config->expect_msg_callback) {
  711. fprintf(stderr, "Bad message callback trace. Wanted:\n%s\nGot:\n%s\n",
  712. config->expect_msg_callback.c_str(),
  713. GetTestState(ssl.get())->msg_callback_text.c_str());
  714. return false;
  715. }
  716. return true;
  717. }
  718. static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
  719. bssl::UniquePtr<SSL> *ssl_uniqueptr,
  720. const TestConfig *config, bool is_resume, bool is_retry,
  721. SettingsWriter *writer) {
  722. int ret;
  723. SSL *ssl = ssl_uniqueptr->get();
  724. SSL_CTX *session_ctx = SSL_get_SSL_CTX(ssl);
  725. if (!config->implicit_handshake) {
  726. if (config->handoff) {
  727. #if defined(HANDSHAKER_SUPPORTED)
  728. if (!DoSplitHandshake(ssl_uniqueptr, writer, is_resume)) {
  729. return false;
  730. }
  731. ssl = ssl_uniqueptr->get();
  732. #else
  733. fprintf(stderr, "The external handshaker can only be used on Linux\n");
  734. return false;
  735. #endif
  736. }
  737. do {
  738. ret = CheckIdempotentError("SSL_do_handshake", ssl, [&]() -> int {
  739. return SSL_do_handshake(ssl);
  740. });
  741. } while (RetryAsync(ssl, ret));
  742. if (config->forbid_renegotiation_after_handshake) {
  743. SSL_set_renegotiate_mode(ssl, ssl_renegotiate_never);
  744. }
  745. if (ret != 1 || !CheckHandshakeProperties(ssl, is_resume, config)) {
  746. return false;
  747. }
  748. CopySessions(session_ctx, SSL_get_SSL_CTX(ssl));
  749. if (is_resume && !is_retry && !config->is_server &&
  750. config->expect_no_offer_early_data && SSL_in_early_data(ssl)) {
  751. fprintf(stderr, "Client unexpectedly offered early data.\n");
  752. return false;
  753. }
  754. if (config->handshake_twice) {
  755. do {
  756. ret = SSL_do_handshake(ssl);
  757. } while (RetryAsync(ssl, ret));
  758. if (ret != 1) {
  759. return false;
  760. }
  761. }
  762. // Skip the |config->async| logic as this should be a no-op.
  763. if (config->no_op_extra_handshake &&
  764. SSL_do_handshake(ssl) != 1) {
  765. fprintf(stderr, "Extra SSL_do_handshake was not a no-op.\n");
  766. return false;
  767. }
  768. // Reset the state to assert later that the callback isn't called in
  769. // renegotations.
  770. GetTestState(ssl)->got_new_session = false;
  771. }
  772. if (config->export_keying_material > 0) {
  773. std::vector<uint8_t> result(
  774. static_cast<size_t>(config->export_keying_material));
  775. if (!SSL_export_keying_material(
  776. ssl, result.data(), result.size(), config->export_label.data(),
  777. config->export_label.size(),
  778. reinterpret_cast<const uint8_t *>(config->export_context.data()),
  779. config->export_context.size(), config->use_export_context)) {
  780. fprintf(stderr, "failed to export keying material\n");
  781. return false;
  782. }
  783. if (WriteAll(ssl, result.data(), result.size()) < 0) {
  784. return false;
  785. }
  786. }
  787. if (config->export_traffic_secrets) {
  788. bssl::Span<const uint8_t> read_secret, write_secret;
  789. if (!SSL_get_traffic_secrets(ssl, &read_secret, &write_secret)) {
  790. fprintf(stderr, "failed to export traffic secrets\n");
  791. return false;
  792. }
  793. assert(read_secret.size() <= 0xffff);
  794. assert(write_secret.size() == read_secret.size());
  795. const uint16_t secret_len = read_secret.size();
  796. if (WriteAll(ssl, &secret_len, sizeof(secret_len)) < 0 ||
  797. WriteAll(ssl, read_secret.data(), read_secret.size()) < 0 ||
  798. WriteAll(ssl, write_secret.data(), write_secret.size()) < 0) {
  799. return false;
  800. }
  801. }
  802. if (config->tls_unique) {
  803. uint8_t tls_unique[16];
  804. size_t tls_unique_len;
  805. if (!SSL_get_tls_unique(ssl, tls_unique, &tls_unique_len,
  806. sizeof(tls_unique))) {
  807. fprintf(stderr, "failed to get tls-unique\n");
  808. return false;
  809. }
  810. if (tls_unique_len != 12) {
  811. fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
  812. static_cast<unsigned>(tls_unique_len));
  813. return false;
  814. }
  815. if (WriteAll(ssl, tls_unique, tls_unique_len) < 0) {
  816. return false;
  817. }
  818. }
  819. if (config->send_alert) {
  820. if (DoSendFatalAlert(ssl, SSL_AD_DECOMPRESSION_FAILURE) < 0) {
  821. return false;
  822. }
  823. return true;
  824. }
  825. if (config->write_different_record_sizes) {
  826. if (config->is_dtls) {
  827. fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
  828. return false;
  829. }
  830. // This mode writes a number of different record sizes in an attempt to
  831. // trip up the CBC record splitting code.
  832. static const size_t kBufLen = 32769;
  833. std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
  834. OPENSSL_memset(buf.get(), 0x42, kBufLen);
  835. static const size_t kRecordSizes[] = {
  836. 0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
  837. for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
  838. const size_t len = kRecordSizes[i];
  839. if (len > kBufLen) {
  840. fprintf(stderr, "Bad kRecordSizes value.\n");
  841. return false;
  842. }
  843. if (WriteAll(ssl, buf.get(), len) < 0) {
  844. return false;
  845. }
  846. }
  847. } else {
  848. static const char kInitialWrite[] = "hello";
  849. bool pending_initial_write = false;
  850. if (config->read_with_unfinished_write) {
  851. if (!config->async) {
  852. fprintf(stderr, "-read-with-unfinished-write requires -async.\n");
  853. return false;
  854. }
  855. // Let only one byte of the record through.
  856. AsyncBioAllowWrite(GetTestState(ssl)->async_bio, 1);
  857. int write_ret =
  858. SSL_write(ssl, kInitialWrite, strlen(kInitialWrite));
  859. if (SSL_get_error(ssl, write_ret) != SSL_ERROR_WANT_WRITE) {
  860. fprintf(stderr, "Failed to leave unfinished write.\n");
  861. return false;
  862. }
  863. pending_initial_write = true;
  864. } else if (config->shim_writes_first) {
  865. if (WriteAll(ssl, kInitialWrite, strlen(kInitialWrite)) < 0) {
  866. return false;
  867. }
  868. }
  869. if (!config->shim_shuts_down) {
  870. for (;;) {
  871. // Read only 512 bytes at a time in TLS to ensure records may be
  872. // returned in multiple reads.
  873. size_t read_size = config->is_dtls ? 16384 : 512;
  874. if (config->read_size > 0) {
  875. read_size = config->read_size;
  876. }
  877. std::unique_ptr<uint8_t[]> buf(new uint8_t[read_size]);
  878. int n = DoRead(ssl, buf.get(), read_size);
  879. int err = SSL_get_error(ssl, n);
  880. if (err == SSL_ERROR_ZERO_RETURN ||
  881. (n == 0 && err == SSL_ERROR_SYSCALL)) {
  882. if (n != 0) {
  883. fprintf(stderr, "Invalid SSL_get_error output\n");
  884. return false;
  885. }
  886. // Stop on either clean or unclean shutdown.
  887. break;
  888. } else if (err != SSL_ERROR_NONE) {
  889. if (n > 0) {
  890. fprintf(stderr, "Invalid SSL_get_error output\n");
  891. return false;
  892. }
  893. return false;
  894. }
  895. // Successfully read data.
  896. if (n <= 0) {
  897. fprintf(stderr, "Invalid SSL_get_error output\n");
  898. return false;
  899. }
  900. if (!config->is_server && is_resume && !is_retry &&
  901. config->expect_reject_early_data) {
  902. fprintf(stderr,
  903. "Unexpectedly received data instead of 0-RTT reject.\n");
  904. return false;
  905. }
  906. // After a successful read, with or without False Start, the handshake
  907. // must be complete unless we are doing early data.
  908. if (!GetTestState(ssl)->handshake_done &&
  909. !SSL_early_data_accepted(ssl)) {
  910. fprintf(stderr, "handshake was not completed after SSL_read\n");
  911. return false;
  912. }
  913. // Clear the initial write, if unfinished.
  914. if (pending_initial_write) {
  915. if (WriteAll(ssl, kInitialWrite, strlen(kInitialWrite)) < 0) {
  916. return false;
  917. }
  918. pending_initial_write = false;
  919. }
  920. if (config->key_update &&
  921. !SSL_key_update(ssl, SSL_KEY_UPDATE_NOT_REQUESTED)) {
  922. fprintf(stderr, "SSL_key_update failed.\n");
  923. return false;
  924. }
  925. for (int i = 0; i < n; i++) {
  926. buf[i] ^= 0xff;
  927. }
  928. if (WriteAll(ssl, buf.get(), n) < 0) {
  929. return false;
  930. }
  931. }
  932. }
  933. }
  934. if (!config->is_server && !config->false_start &&
  935. !config->implicit_handshake &&
  936. // Session tickets are sent post-handshake in TLS 1.3.
  937. GetProtocolVersion(ssl) < TLS1_3_VERSION &&
  938. GetTestState(ssl)->got_new_session) {
  939. fprintf(stderr, "new session was established after the handshake\n");
  940. return false;
  941. }
  942. if (GetProtocolVersion(ssl) >= TLS1_3_VERSION && !config->is_server) {
  943. bool expect_new_session =
  944. !config->expect_no_session && !config->shim_shuts_down;
  945. if (expect_new_session != GetTestState(ssl)->got_new_session) {
  946. fprintf(stderr,
  947. "new session was%s cached, but we expected the opposite\n",
  948. GetTestState(ssl)->got_new_session ? "" : " not");
  949. return false;
  950. }
  951. if (expect_new_session) {
  952. bool got_early_data =
  953. GetTestState(ssl)->new_session->ticket_max_early_data != 0;
  954. if (config->expect_ticket_supports_early_data != got_early_data) {
  955. fprintf(stderr,
  956. "new session did%s support early data, but we expected the "
  957. "opposite\n",
  958. got_early_data ? "" : " not");
  959. return false;
  960. }
  961. }
  962. }
  963. if (out_session) {
  964. *out_session = std::move(GetTestState(ssl)->new_session);
  965. }
  966. ret = DoShutdown(ssl);
  967. if (config->shim_shuts_down && config->check_close_notify) {
  968. // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
  969. // it returns zero when our close_notify is sent, then one when the peer's
  970. // is received.
  971. if (ret != 0) {
  972. fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
  973. return false;
  974. }
  975. ret = DoShutdown(ssl);
  976. }
  977. if (ret != 1) {
  978. fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
  979. return false;
  980. }
  981. if (SSL_total_renegotiations(ssl) > 0) {
  982. if (!SSL_get_session(ssl)->not_resumable) {
  983. fprintf(stderr,
  984. "Renegotiations should never produce resumable sessions.\n");
  985. return false;
  986. }
  987. if (SSL_session_reused(ssl)) {
  988. fprintf(stderr, "Renegotiations should never resume sessions.\n");
  989. return false;
  990. }
  991. // Re-check authentication properties after a renegotiation. The reported
  992. // values should remain unchanged even if the server sent different SCT
  993. // lists.
  994. if (!CheckAuthProperties(ssl, is_resume, config)) {
  995. return false;
  996. }
  997. }
  998. if (SSL_total_renegotiations(ssl) != config->expect_total_renegotiations) {
  999. fprintf(stderr, "Expected %d renegotiations, got %d\n",
  1000. config->expect_total_renegotiations, SSL_total_renegotiations(ssl));
  1001. return false;
  1002. }
  1003. return true;
  1004. }
  1005. class StderrDelimiter {
  1006. public:
  1007. ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
  1008. };
  1009. int main(int argc, char **argv) {
  1010. // To distinguish ASan's output from ours, add a trailing message to stderr.
  1011. // Anything following this line will be considered an error.
  1012. StderrDelimiter delimiter;
  1013. #if defined(OPENSSL_WINDOWS)
  1014. // Initialize Winsock.
  1015. WORD wsa_version = MAKEWORD(2, 2);
  1016. WSADATA wsa_data;
  1017. int wsa_err = WSAStartup(wsa_version, &wsa_data);
  1018. if (wsa_err != 0) {
  1019. fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
  1020. return 1;
  1021. }
  1022. if (wsa_data.wVersion != wsa_version) {
  1023. fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
  1024. return 1;
  1025. }
  1026. #else
  1027. signal(SIGPIPE, SIG_IGN);
  1028. #endif
  1029. CRYPTO_library_init();
  1030. TestConfig initial_config, resume_config, retry_config;
  1031. if (!ParseConfig(argc - 1, argv + 1, &initial_config, &resume_config,
  1032. &retry_config)) {
  1033. return Usage(argv[0]);
  1034. }
  1035. if (initial_config.is_handshaker_supported) {
  1036. #if defined(HANDSHAKER_SUPPORTED)
  1037. printf("Yes\n");
  1038. #else
  1039. printf("No\n");
  1040. #endif
  1041. return 0;
  1042. }
  1043. bssl::UniquePtr<SSL_CTX> ssl_ctx;
  1044. bssl::UniquePtr<SSL_SESSION> session;
  1045. for (int i = 0; i < initial_config.resume_count + 1; i++) {
  1046. bool is_resume = i > 0;
  1047. TestConfig *config = is_resume ? &resume_config : &initial_config;
  1048. ssl_ctx = config->SetupCtx(ssl_ctx.get());
  1049. if (!ssl_ctx) {
  1050. ERR_print_errors_fp(stderr);
  1051. return 1;
  1052. }
  1053. if (is_resume && !initial_config.is_server && !session) {
  1054. fprintf(stderr, "No session to offer.\n");
  1055. return 1;
  1056. }
  1057. bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
  1058. SettingsWriter writer;
  1059. if (!writer.Init(i, config, offer_session.get())) {
  1060. fprintf(stderr, "Error writing settings.\n");
  1061. return 1;
  1062. }
  1063. bool ok = DoConnection(&session, ssl_ctx.get(), config, &retry_config,
  1064. is_resume, offer_session.get(), &writer);
  1065. if (!writer.Commit()) {
  1066. fprintf(stderr, "Error writing settings.\n");
  1067. return 1;
  1068. }
  1069. if (!ok) {
  1070. fprintf(stderr, "Connection %d failed.\n", i + 1);
  1071. ERR_print_errors_fp(stderr);
  1072. return 1;
  1073. }
  1074. if (config->resumption_delay != 0) {
  1075. AdvanceClock(config->resumption_delay);
  1076. }
  1077. }
  1078. return 0;
  1079. }