No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

563 líneas
17 KiB

  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. #include <stdio.h>
  16. #if !defined(OPENSSL_WINDOWS)
  17. #include <sys/select.h>
  18. #else
  19. OPENSSL_MSVC_PRAGMA(warning(push, 3))
  20. #include <winsock2.h>
  21. OPENSSL_MSVC_PRAGMA(warning(pop))
  22. #endif
  23. #include <openssl/err.h>
  24. #include <openssl/pem.h>
  25. #include <openssl/ssl.h>
  26. #include "../crypto/internal.h"
  27. #include "internal.h"
  28. #include "transport_common.h"
  29. static const struct argument kArguments[] = {
  30. {
  31. "-connect", kRequiredArgument,
  32. "The hostname and port of the server to connect to, e.g. foo.com:443",
  33. },
  34. {
  35. "-cipher", kOptionalArgument,
  36. "An OpenSSL-style cipher suite string that configures the offered "
  37. "ciphers",
  38. },
  39. {
  40. "-curves", kOptionalArgument,
  41. "An OpenSSL-style ECDH curves list that configures the offered curves",
  42. },
  43. {
  44. "-max-version", kOptionalArgument,
  45. "The maximum acceptable protocol version",
  46. },
  47. {
  48. "-min-version", kOptionalArgument,
  49. "The minimum acceptable protocol version",
  50. },
  51. {
  52. "-server-name", kOptionalArgument, "The server name to advertise",
  53. },
  54. {
  55. "-select-next-proto", kOptionalArgument,
  56. "An NPN protocol to select if the server supports NPN",
  57. },
  58. {
  59. "-alpn-protos", kOptionalArgument,
  60. "A comma-separated list of ALPN protocols to advertise",
  61. },
  62. {
  63. "-fallback-scsv", kBooleanArgument, "Enable FALLBACK_SCSV",
  64. },
  65. {
  66. "-ocsp-stapling", kBooleanArgument,
  67. "Advertise support for OCSP stabling",
  68. },
  69. {
  70. "-signed-certificate-timestamps", kBooleanArgument,
  71. "Advertise support for signed certificate timestamps",
  72. },
  73. {
  74. "-channel-id-key", kOptionalArgument,
  75. "The key to use for signing a channel ID",
  76. },
  77. {
  78. "-false-start", kBooleanArgument, "Enable False Start",
  79. },
  80. {
  81. "-session-in", kOptionalArgument,
  82. "A file containing a session to resume.",
  83. },
  84. {
  85. "-session-out", kOptionalArgument,
  86. "A file to write the negotiated session to.",
  87. },
  88. {
  89. "-key", kOptionalArgument,
  90. "PEM-encoded file containing the private key.",
  91. },
  92. {
  93. "-cert", kOptionalArgument,
  94. "PEM-encoded file containing the leaf certificate and optional "
  95. "certificate chain. This is taken from the -key argument if this "
  96. "argument is not provided.",
  97. },
  98. {
  99. "-starttls", kOptionalArgument,
  100. "A STARTTLS mini-protocol to run before the TLS handshake. Supported"
  101. " values: 'smtp'",
  102. },
  103. {
  104. "-grease", kBooleanArgument, "Enable GREASE",
  105. },
  106. {
  107. "-test-resumption", kBooleanArgument,
  108. "Connect to the server twice. The first connection is closed once a "
  109. "session is established. The second connection offers it.",
  110. },
  111. {
  112. "-root-certs", kOptionalArgument,
  113. "A filename containing one of more PEM root certificates. Implies that "
  114. "verification is required.",
  115. },
  116. {
  117. "-early-data", kOptionalArgument, "Enable early data. The argument to "
  118. "this flag is the early data to send or if it starts with '@', the "
  119. "file to read from for early data.",
  120. },
  121. {
  122. "-tls13-variant", kOptionalArgument,
  123. "Enable the specified experimental TLS 1.3 variant",
  124. },
  125. {
  126. "-ed25519", kBooleanArgument, "Advertise Ed25519 support",
  127. },
  128. {
  129. "-http-tunnel", kOptionalArgument,
  130. "An HTTP proxy server to tunnel the TCP connection through",
  131. },
  132. {
  133. "-renegotiate-freely", kBooleanArgument,
  134. "Allow renegotiations from the peer.",
  135. },
  136. {
  137. "-debug", kBooleanArgument,
  138. "Print debug information about the handshake",
  139. },
  140. {
  141. "", kOptionalArgument, "",
  142. },
  143. };
  144. static bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
  145. bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
  146. if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
  147. return nullptr;
  148. }
  149. bssl::UniquePtr<EVP_PKEY> pkey(PEM_read_bio_PrivateKey(bio.get(), nullptr,
  150. nullptr, nullptr));
  151. return pkey;
  152. }
  153. static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
  154. const uint8_t* in, unsigned inlen, void* arg) {
  155. *out = reinterpret_cast<uint8_t *>(arg);
  156. *outlen = strlen(reinterpret_cast<const char *>(arg));
  157. return SSL_TLSEXT_ERR_OK;
  158. }
  159. static FILE *g_keylog_file = nullptr;
  160. static void KeyLogCallback(const SSL *ssl, const char *line) {
  161. fprintf(g_keylog_file, "%s\n", line);
  162. fflush(g_keylog_file);
  163. }
  164. static bssl::UniquePtr<BIO> session_out;
  165. static bssl::UniquePtr<SSL_SESSION> resume_session;
  166. static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
  167. if (session_out) {
  168. if (!PEM_write_bio_SSL_SESSION(session_out.get(), session) ||
  169. BIO_flush(session_out.get()) <= 0) {
  170. fprintf(stderr, "Error while saving session:\n");
  171. ERR_print_errors_fp(stderr);
  172. return 0;
  173. }
  174. }
  175. resume_session = bssl::UniquePtr<SSL_SESSION>(session);
  176. return 1;
  177. }
  178. static bool WaitForSession(SSL *ssl, int sock) {
  179. fd_set read_fds;
  180. FD_ZERO(&read_fds);
  181. if (!SocketSetNonBlocking(sock, true)) {
  182. return false;
  183. }
  184. while (!resume_session) {
  185. #if defined(OPENSSL_WINDOWS)
  186. // Windows sockets are really of type SOCKET, not int, but everything here
  187. // casts them to ints. Clang gets unhappy about signed values as a result.
  188. //
  189. // TODO(davidben): Keep everything as the appropriate platform type.
  190. FD_SET(static_cast<SOCKET>(sock), &read_fds);
  191. #else
  192. FD_SET(sock, &read_fds);
  193. #endif
  194. int ret = select(sock + 1, &read_fds, NULL, NULL, NULL);
  195. if (ret <= 0) {
  196. perror("select");
  197. return false;
  198. }
  199. uint8_t buffer[512];
  200. int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer));
  201. if (ssl_ret <= 0) {
  202. int ssl_err = SSL_get_error(ssl, ssl_ret);
  203. if (ssl_err == SSL_ERROR_WANT_READ) {
  204. continue;
  205. }
  206. PrintSSLError(stderr, "Error while reading", ssl_err, ssl_ret);
  207. return false;
  208. }
  209. }
  210. return true;
  211. }
  212. static bool DoConnection(SSL_CTX *ctx,
  213. std::map<std::string, std::string> args_map,
  214. bool (*cb)(SSL *ssl, int sock)) {
  215. int sock = -1;
  216. if (args_map.count("-http-tunnel") != 0) {
  217. if (!Connect(&sock, args_map["-http-tunnel"]) ||
  218. !DoHTTPTunnel(sock, args_map["-connect"])) {
  219. return false;
  220. }
  221. } else if (!Connect(&sock, args_map["-connect"])) {
  222. return false;
  223. }
  224. if (args_map.count("-starttls") != 0) {
  225. const std::string& starttls = args_map["-starttls"];
  226. if (starttls == "smtp") {
  227. if (!DoSMTPStartTLS(sock)) {
  228. return false;
  229. }
  230. } else {
  231. fprintf(stderr, "Unknown value for -starttls: %s\n", starttls.c_str());
  232. return false;
  233. }
  234. }
  235. bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_CLOSE));
  236. bssl::UniquePtr<SSL> ssl(SSL_new(ctx));
  237. if (args_map.count("-server-name") != 0) {
  238. SSL_set_tlsext_host_name(ssl.get(), args_map["-server-name"].c_str());
  239. }
  240. if (args_map.count("-session-in") != 0) {
  241. bssl::UniquePtr<BIO> in(BIO_new_file(args_map["-session-in"].c_str(),
  242. "rb"));
  243. if (!in) {
  244. fprintf(stderr, "Error reading session\n");
  245. ERR_print_errors_fp(stderr);
  246. return false;
  247. }
  248. bssl::UniquePtr<SSL_SESSION> session(PEM_read_bio_SSL_SESSION(in.get(),
  249. nullptr, nullptr, nullptr));
  250. if (!session) {
  251. fprintf(stderr, "Error reading session\n");
  252. ERR_print_errors_fp(stderr);
  253. return false;
  254. }
  255. SSL_set_session(ssl.get(), session.get());
  256. }
  257. if (args_map.count("-renegotiate-freely") != 0) {
  258. SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
  259. }
  260. if (resume_session) {
  261. SSL_set_session(ssl.get(), resume_session.get());
  262. }
  263. SSL_set_bio(ssl.get(), bio.get(), bio.get());
  264. bio.release();
  265. int ret = SSL_connect(ssl.get());
  266. if (ret != 1) {
  267. int ssl_err = SSL_get_error(ssl.get(), ret);
  268. PrintSSLError(stderr, "Error while connecting", ssl_err, ret);
  269. return false;
  270. }
  271. if (args_map.count("-early-data") != 0 && SSL_in_early_data(ssl.get())) {
  272. std::string early_data = args_map["-early-data"];
  273. if (early_data.size() > 0 && early_data[0] == '@') {
  274. const char *filename = early_data.c_str() + 1;
  275. std::vector<uint8_t> data;
  276. ScopedFILE f(fopen(filename, "rb"));
  277. if (f == nullptr || !ReadAll(&data, f.get())) {
  278. fprintf(stderr, "Error reading %s.\n", filename);
  279. return false;
  280. }
  281. early_data = std::string(data.begin(), data.end());
  282. }
  283. int ed_size = early_data.size();
  284. int ssl_ret = SSL_write(ssl.get(), early_data.data(), ed_size);
  285. if (ssl_ret <= 0) {
  286. int ssl_err = SSL_get_error(ssl.get(), ssl_ret);
  287. PrintSSLError(stderr, "Error while writing", ssl_err, ssl_ret);
  288. return false;
  289. } else if (ssl_ret != ed_size) {
  290. fprintf(stderr, "Short write from SSL_write.\n");
  291. return false;
  292. }
  293. }
  294. fprintf(stderr, "Connected.\n");
  295. bssl::UniquePtr<BIO> bio_stderr(BIO_new_fp(stderr, BIO_NOCLOSE));
  296. PrintConnectionInfo(bio_stderr.get(), ssl.get());
  297. return cb(ssl.get(), sock);
  298. }
  299. static bool GetTLS13Variant(tls13_variant_t *out, const std::string &in) {
  300. if (in == "draft23") {
  301. *out = tls13_draft23;
  302. return true;
  303. }
  304. if (in == "draft28") {
  305. *out = tls13_draft28;
  306. return true;
  307. }
  308. if (in == "rfc") {
  309. *out = tls13_rfc;
  310. return true;
  311. }
  312. if (in == "all") {
  313. *out = tls13_all;
  314. return true;
  315. }
  316. return false;
  317. }
  318. static void InfoCallback(const SSL *ssl, int type, int value) {
  319. switch (type) {
  320. case SSL_CB_HANDSHAKE_START:
  321. fprintf(stderr, "Handshake started.\n");
  322. break;
  323. case SSL_CB_HANDSHAKE_DONE:
  324. fprintf(stderr, "Handshake done.\n");
  325. break;
  326. case SSL_CB_CONNECT_LOOP:
  327. fprintf(stderr, "Handshake progress: %s\n", SSL_state_string_long(ssl));
  328. break;
  329. }
  330. }
  331. bool Client(const std::vector<std::string> &args) {
  332. if (!InitSocketLibrary()) {
  333. return false;
  334. }
  335. std::map<std::string, std::string> args_map;
  336. if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
  337. PrintUsage(kArguments);
  338. return false;
  339. }
  340. bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
  341. const char *keylog_file = getenv("SSLKEYLOGFILE");
  342. if (keylog_file) {
  343. g_keylog_file = fopen(keylog_file, "a");
  344. if (g_keylog_file == nullptr) {
  345. perror("fopen");
  346. return false;
  347. }
  348. SSL_CTX_set_keylog_callback(ctx.get(), KeyLogCallback);
  349. }
  350. if (args_map.count("-cipher") != 0 &&
  351. !SSL_CTX_set_strict_cipher_list(ctx.get(), args_map["-cipher"].c_str())) {
  352. fprintf(stderr, "Failed setting cipher list\n");
  353. return false;
  354. }
  355. if (args_map.count("-curves") != 0 &&
  356. !SSL_CTX_set1_curves_list(ctx.get(), args_map["-curves"].c_str())) {
  357. fprintf(stderr, "Failed setting curves list\n");
  358. return false;
  359. }
  360. uint16_t max_version = TLS1_3_VERSION;
  361. if (args_map.count("-max-version") != 0 &&
  362. !VersionFromString(&max_version, args_map["-max-version"])) {
  363. fprintf(stderr, "Unknown protocol version: '%s'\n",
  364. args_map["-max-version"].c_str());
  365. return false;
  366. }
  367. if (!SSL_CTX_set_max_proto_version(ctx.get(), max_version)) {
  368. return false;
  369. }
  370. if (args_map.count("-min-version") != 0) {
  371. uint16_t version;
  372. if (!VersionFromString(&version, args_map["-min-version"])) {
  373. fprintf(stderr, "Unknown protocol version: '%s'\n",
  374. args_map["-min-version"].c_str());
  375. return false;
  376. }
  377. if (!SSL_CTX_set_min_proto_version(ctx.get(), version)) {
  378. return false;
  379. }
  380. }
  381. if (args_map.count("-select-next-proto") != 0) {
  382. const std::string &proto = args_map["-select-next-proto"];
  383. if (proto.size() > 255) {
  384. fprintf(stderr, "Bad NPN protocol: '%s'\n", proto.c_str());
  385. return false;
  386. }
  387. // |SSL_CTX_set_next_proto_select_cb| is not const-correct.
  388. SSL_CTX_set_next_proto_select_cb(ctx.get(), NextProtoSelectCallback,
  389. const_cast<char *>(proto.c_str()));
  390. }
  391. if (args_map.count("-alpn-protos") != 0) {
  392. const std::string &alpn_protos = args_map["-alpn-protos"];
  393. std::vector<uint8_t> wire;
  394. size_t i = 0;
  395. while (i <= alpn_protos.size()) {
  396. size_t j = alpn_protos.find(',', i);
  397. if (j == std::string::npos) {
  398. j = alpn_protos.size();
  399. }
  400. size_t len = j - i;
  401. if (len > 255) {
  402. fprintf(stderr, "Invalid ALPN protocols: '%s'\n", alpn_protos.c_str());
  403. return false;
  404. }
  405. wire.push_back(static_cast<uint8_t>(len));
  406. wire.resize(wire.size() + len);
  407. OPENSSL_memcpy(wire.data() + wire.size() - len, alpn_protos.data() + i,
  408. len);
  409. i = j + 1;
  410. }
  411. if (SSL_CTX_set_alpn_protos(ctx.get(), wire.data(), wire.size()) != 0) {
  412. return false;
  413. }
  414. }
  415. if (args_map.count("-fallback-scsv") != 0) {
  416. SSL_CTX_set_mode(ctx.get(), SSL_MODE_SEND_FALLBACK_SCSV);
  417. }
  418. if (args_map.count("-ocsp-stapling") != 0) {
  419. SSL_CTX_enable_ocsp_stapling(ctx.get());
  420. }
  421. if (args_map.count("-signed-certificate-timestamps") != 0) {
  422. SSL_CTX_enable_signed_cert_timestamps(ctx.get());
  423. }
  424. if (args_map.count("-channel-id-key") != 0) {
  425. bssl::UniquePtr<EVP_PKEY> pkey =
  426. LoadPrivateKey(args_map["-channel-id-key"]);
  427. if (!pkey || !SSL_CTX_set1_tls_channel_id(ctx.get(), pkey.get())) {
  428. return false;
  429. }
  430. }
  431. if (args_map.count("-false-start") != 0) {
  432. SSL_CTX_set_mode(ctx.get(), SSL_MODE_ENABLE_FALSE_START);
  433. }
  434. if (args_map.count("-key") != 0) {
  435. const std::string &key = args_map["-key"];
  436. if (!SSL_CTX_use_PrivateKey_file(ctx.get(), key.c_str(),
  437. SSL_FILETYPE_PEM)) {
  438. fprintf(stderr, "Failed to load private key: %s\n", key.c_str());
  439. return false;
  440. }
  441. const std::string &cert =
  442. args_map.count("-cert") != 0 ? args_map["-cert"] : key;
  443. if (!SSL_CTX_use_certificate_chain_file(ctx.get(), cert.c_str())) {
  444. fprintf(stderr, "Failed to load cert chain: %s\n", cert.c_str());
  445. return false;
  446. }
  447. }
  448. SSL_CTX_set_session_cache_mode(ctx.get(), SSL_SESS_CACHE_CLIENT);
  449. SSL_CTX_sess_set_new_cb(ctx.get(), NewSessionCallback);
  450. if (args_map.count("-session-out") != 0) {
  451. session_out.reset(BIO_new_file(args_map["-session-out"].c_str(), "wb"));
  452. if (!session_out) {
  453. fprintf(stderr, "Error while opening %s:\n",
  454. args_map["-session-out"].c_str());
  455. ERR_print_errors_fp(stderr);
  456. return false;
  457. }
  458. }
  459. if (args_map.count("-grease") != 0) {
  460. SSL_CTX_set_grease_enabled(ctx.get(), 1);
  461. }
  462. if (args_map.count("-root-certs") != 0) {
  463. if (!SSL_CTX_load_verify_locations(
  464. ctx.get(), args_map["-root-certs"].c_str(), nullptr)) {
  465. fprintf(stderr, "Failed to load root certificates.\n");
  466. ERR_print_errors_fp(stderr);
  467. return false;
  468. }
  469. SSL_CTX_set_verify(ctx.get(), SSL_VERIFY_PEER, nullptr);
  470. }
  471. if (args_map.count("-early-data") != 0) {
  472. SSL_CTX_set_early_data_enabled(ctx.get(), 1);
  473. }
  474. if (args_map.count("-tls13-variant") != 0) {
  475. tls13_variant_t variant;
  476. if (!GetTLS13Variant(&variant, args_map["-tls13-variant"])) {
  477. fprintf(stderr, "Unknown TLS 1.3 variant: %s\n",
  478. args_map["-tls13-variant"].c_str());
  479. return false;
  480. }
  481. SSL_CTX_set_tls13_variant(ctx.get(), variant);
  482. }
  483. if (args_map.count("-ed25519") != 0) {
  484. SSL_CTX_set_ed25519_enabled(ctx.get(), 1);
  485. }
  486. if (args_map.count("-debug") != 0) {
  487. SSL_CTX_set_info_callback(ctx.get(), InfoCallback);
  488. }
  489. if (args_map.count("-test-resumption") != 0) {
  490. if (args_map.count("-session-in") != 0) {
  491. fprintf(stderr,
  492. "Flags -session-in and -test-resumption are incompatible.\n");
  493. return false;
  494. }
  495. if (!DoConnection(ctx.get(), args_map, &WaitForSession)) {
  496. return false;
  497. }
  498. }
  499. return DoConnection(ctx.get(), args_map, &TransferData);
  500. }