選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

558 行
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_cb(PrintErrorCallback, 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. fprintf(stderr, "Error while reading: %d\n", ssl_err);
  207. ERR_print_errors_cb(PrintErrorCallback, stderr);
  208. return false;
  209. }
  210. }
  211. return true;
  212. }
  213. static bool DoConnection(SSL_CTX *ctx,
  214. std::map<std::string, std::string> args_map,
  215. bool (*cb)(SSL *ssl, int sock)) {
  216. int sock = -1;
  217. if (args_map.count("-http-tunnel") != 0) {
  218. if (!Connect(&sock, args_map["-http-tunnel"]) ||
  219. !DoHTTPTunnel(sock, args_map["-connect"])) {
  220. return false;
  221. }
  222. } else if (!Connect(&sock, args_map["-connect"])) {
  223. return false;
  224. }
  225. if (args_map.count("-starttls") != 0) {
  226. const std::string& starttls = args_map["-starttls"];
  227. if (starttls == "smtp") {
  228. if (!DoSMTPStartTLS(sock)) {
  229. return false;
  230. }
  231. } else {
  232. fprintf(stderr, "Unknown value for -starttls: %s\n", starttls.c_str());
  233. return false;
  234. }
  235. }
  236. bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_CLOSE));
  237. bssl::UniquePtr<SSL> ssl(SSL_new(ctx));
  238. if (args_map.count("-server-name") != 0) {
  239. SSL_set_tlsext_host_name(ssl.get(), args_map["-server-name"].c_str());
  240. }
  241. if (args_map.count("-session-in") != 0) {
  242. bssl::UniquePtr<BIO> in(BIO_new_file(args_map["-session-in"].c_str(),
  243. "rb"));
  244. if (!in) {
  245. fprintf(stderr, "Error reading session\n");
  246. ERR_print_errors_cb(PrintErrorCallback, stderr);
  247. return false;
  248. }
  249. bssl::UniquePtr<SSL_SESSION> session(PEM_read_bio_SSL_SESSION(in.get(),
  250. nullptr, nullptr, nullptr));
  251. if (!session) {
  252. fprintf(stderr, "Error reading session\n");
  253. ERR_print_errors_cb(PrintErrorCallback, stderr);
  254. return false;
  255. }
  256. SSL_set_session(ssl.get(), session.get());
  257. }
  258. if (args_map.count("-renegotiate-freely") != 0) {
  259. SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
  260. }
  261. if (resume_session) {
  262. SSL_set_session(ssl.get(), resume_session.get());
  263. }
  264. SSL_set_bio(ssl.get(), bio.get(), bio.get());
  265. bio.release();
  266. int ret = SSL_connect(ssl.get());
  267. if (ret != 1) {
  268. int ssl_err = SSL_get_error(ssl.get(), ret);
  269. fprintf(stderr, "Error while connecting: %d\n", ssl_err);
  270. ERR_print_errors_cb(PrintErrorCallback, stderr);
  271. return false;
  272. }
  273. if (args_map.count("-early-data") != 0 && SSL_in_early_data(ssl.get())) {
  274. std::string early_data = args_map["-early-data"];
  275. if (early_data.size() > 0 && early_data[0] == '@') {
  276. const char *filename = early_data.c_str() + 1;
  277. std::vector<uint8_t> data;
  278. ScopedFILE f(fopen(filename, "rb"));
  279. if (f == nullptr || !ReadAll(&data, f.get())) {
  280. fprintf(stderr, "Error reading %s.\n", filename);
  281. return false;
  282. }
  283. early_data = std::string(data.begin(), data.end());
  284. }
  285. int ed_size = early_data.size();
  286. int ssl_ret = SSL_write(ssl.get(), early_data.data(), ed_size);
  287. if (ssl_ret <= 0) {
  288. int ssl_err = SSL_get_error(ssl.get(), ssl_ret);
  289. fprintf(stderr, "Error while writing: %d\n", ssl_err);
  290. ERR_print_errors_cb(PrintErrorCallback, stderr);
  291. return false;
  292. } else if (ssl_ret != ed_size) {
  293. fprintf(stderr, "Short write from SSL_write.\n");
  294. return false;
  295. }
  296. }
  297. fprintf(stderr, "Connected.\n");
  298. bssl::UniquePtr<BIO> bio_stderr(BIO_new_fp(stderr, BIO_NOCLOSE));
  299. PrintConnectionInfo(bio_stderr.get(), ssl.get());
  300. return cb(ssl.get(), sock);
  301. }
  302. static bool GetTLS13Variant(tls13_variant_t *out, const std::string &in) {
  303. if (in == "draft23") {
  304. *out = tls13_default;
  305. return true;
  306. }
  307. if (in == "draft28") {
  308. *out = tls13_draft28;
  309. return true;
  310. }
  311. return false;
  312. }
  313. static void InfoCallback(const SSL *ssl, int type, int value) {
  314. switch (type) {
  315. case SSL_CB_HANDSHAKE_START:
  316. fprintf(stderr, "Handshake started.\n");
  317. break;
  318. case SSL_CB_HANDSHAKE_DONE:
  319. fprintf(stderr, "Handshake done.\n");
  320. break;
  321. case SSL_CB_CONNECT_LOOP:
  322. fprintf(stderr, "Handshake progress: %s\n", SSL_state_string_long(ssl));
  323. break;
  324. }
  325. }
  326. bool Client(const std::vector<std::string> &args) {
  327. if (!InitSocketLibrary()) {
  328. return false;
  329. }
  330. std::map<std::string, std::string> args_map;
  331. if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
  332. PrintUsage(kArguments);
  333. return false;
  334. }
  335. bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
  336. const char *keylog_file = getenv("SSLKEYLOGFILE");
  337. if (keylog_file) {
  338. g_keylog_file = fopen(keylog_file, "a");
  339. if (g_keylog_file == nullptr) {
  340. perror("fopen");
  341. return false;
  342. }
  343. SSL_CTX_set_keylog_callback(ctx.get(), KeyLogCallback);
  344. }
  345. if (args_map.count("-cipher") != 0 &&
  346. !SSL_CTX_set_strict_cipher_list(ctx.get(), args_map["-cipher"].c_str())) {
  347. fprintf(stderr, "Failed setting cipher list\n");
  348. return false;
  349. }
  350. if (args_map.count("-curves") != 0 &&
  351. !SSL_CTX_set1_curves_list(ctx.get(), args_map["-curves"].c_str())) {
  352. fprintf(stderr, "Failed setting curves list\n");
  353. return false;
  354. }
  355. uint16_t max_version = TLS1_3_VERSION;
  356. if (args_map.count("-max-version") != 0 &&
  357. !VersionFromString(&max_version, args_map["-max-version"])) {
  358. fprintf(stderr, "Unknown protocol version: '%s'\n",
  359. args_map["-max-version"].c_str());
  360. return false;
  361. }
  362. if (!SSL_CTX_set_max_proto_version(ctx.get(), max_version)) {
  363. return false;
  364. }
  365. if (args_map.count("-min-version") != 0) {
  366. uint16_t version;
  367. if (!VersionFromString(&version, args_map["-min-version"])) {
  368. fprintf(stderr, "Unknown protocol version: '%s'\n",
  369. args_map["-min-version"].c_str());
  370. return false;
  371. }
  372. if (!SSL_CTX_set_min_proto_version(ctx.get(), version)) {
  373. return false;
  374. }
  375. }
  376. if (args_map.count("-select-next-proto") != 0) {
  377. const std::string &proto = args_map["-select-next-proto"];
  378. if (proto.size() > 255) {
  379. fprintf(stderr, "Bad NPN protocol: '%s'\n", proto.c_str());
  380. return false;
  381. }
  382. // |SSL_CTX_set_next_proto_select_cb| is not const-correct.
  383. SSL_CTX_set_next_proto_select_cb(ctx.get(), NextProtoSelectCallback,
  384. const_cast<char *>(proto.c_str()));
  385. }
  386. if (args_map.count("-alpn-protos") != 0) {
  387. const std::string &alpn_protos = args_map["-alpn-protos"];
  388. std::vector<uint8_t> wire;
  389. size_t i = 0;
  390. while (i <= alpn_protos.size()) {
  391. size_t j = alpn_protos.find(',', i);
  392. if (j == std::string::npos) {
  393. j = alpn_protos.size();
  394. }
  395. size_t len = j - i;
  396. if (len > 255) {
  397. fprintf(stderr, "Invalid ALPN protocols: '%s'\n", alpn_protos.c_str());
  398. return false;
  399. }
  400. wire.push_back(static_cast<uint8_t>(len));
  401. wire.resize(wire.size() + len);
  402. OPENSSL_memcpy(wire.data() + wire.size() - len, alpn_protos.data() + i,
  403. len);
  404. i = j + 1;
  405. }
  406. if (SSL_CTX_set_alpn_protos(ctx.get(), wire.data(), wire.size()) != 0) {
  407. return false;
  408. }
  409. }
  410. if (args_map.count("-fallback-scsv") != 0) {
  411. SSL_CTX_set_mode(ctx.get(), SSL_MODE_SEND_FALLBACK_SCSV);
  412. }
  413. if (args_map.count("-ocsp-stapling") != 0) {
  414. SSL_CTX_enable_ocsp_stapling(ctx.get());
  415. }
  416. if (args_map.count("-signed-certificate-timestamps") != 0) {
  417. SSL_CTX_enable_signed_cert_timestamps(ctx.get());
  418. }
  419. if (args_map.count("-channel-id-key") != 0) {
  420. bssl::UniquePtr<EVP_PKEY> pkey =
  421. LoadPrivateKey(args_map["-channel-id-key"]);
  422. if (!pkey || !SSL_CTX_set1_tls_channel_id(ctx.get(), pkey.get())) {
  423. return false;
  424. }
  425. }
  426. if (args_map.count("-false-start") != 0) {
  427. SSL_CTX_set_mode(ctx.get(), SSL_MODE_ENABLE_FALSE_START);
  428. }
  429. if (args_map.count("-key") != 0) {
  430. const std::string &key = args_map["-key"];
  431. if (!SSL_CTX_use_PrivateKey_file(ctx.get(), key.c_str(),
  432. SSL_FILETYPE_PEM)) {
  433. fprintf(stderr, "Failed to load private key: %s\n", key.c_str());
  434. return false;
  435. }
  436. const std::string &cert =
  437. args_map.count("-cert") != 0 ? args_map["-cert"] : key;
  438. if (!SSL_CTX_use_certificate_chain_file(ctx.get(), cert.c_str())) {
  439. fprintf(stderr, "Failed to load cert chain: %s\n", cert.c_str());
  440. return false;
  441. }
  442. }
  443. SSL_CTX_set_session_cache_mode(ctx.get(), SSL_SESS_CACHE_CLIENT);
  444. SSL_CTX_sess_set_new_cb(ctx.get(), NewSessionCallback);
  445. if (args_map.count("-session-out") != 0) {
  446. session_out.reset(BIO_new_file(args_map["-session-out"].c_str(), "wb"));
  447. if (!session_out) {
  448. fprintf(stderr, "Error while opening %s:\n",
  449. args_map["-session-out"].c_str());
  450. ERR_print_errors_cb(PrintErrorCallback, stderr);
  451. return false;
  452. }
  453. }
  454. if (args_map.count("-grease") != 0) {
  455. SSL_CTX_set_grease_enabled(ctx.get(), 1);
  456. }
  457. if (args_map.count("-root-certs") != 0) {
  458. if (!SSL_CTX_load_verify_locations(
  459. ctx.get(), args_map["-root-certs"].c_str(), nullptr)) {
  460. fprintf(stderr, "Failed to load root certificates.\n");
  461. ERR_print_errors_cb(PrintErrorCallback, stderr);
  462. return false;
  463. }
  464. SSL_CTX_set_verify(ctx.get(), SSL_VERIFY_PEER, nullptr);
  465. }
  466. if (args_map.count("-early-data") != 0) {
  467. SSL_CTX_set_early_data_enabled(ctx.get(), 1);
  468. }
  469. if (args_map.count("-tls13-variant") != 0) {
  470. tls13_variant_t variant;
  471. if (!GetTLS13Variant(&variant, args_map["-tls13-variant"])) {
  472. fprintf(stderr, "Unknown TLS 1.3 variant: %s\n",
  473. args_map["-tls13-variant"].c_str());
  474. return false;
  475. }
  476. SSL_CTX_set_tls13_variant(ctx.get(), variant);
  477. }
  478. if (args_map.count("-ed25519") != 0) {
  479. SSL_CTX_set_ed25519_enabled(ctx.get(), 1);
  480. }
  481. if (args_map.count("-debug") != 0) {
  482. SSL_CTX_set_info_callback(ctx.get(), InfoCallback);
  483. }
  484. if (args_map.count("-test-resumption") != 0) {
  485. if (args_map.count("-session-in") != 0) {
  486. fprintf(stderr,
  487. "Flags -session-in and -test-resumption are incompatible.\n");
  488. return false;
  489. }
  490. if (!DoConnection(ctx.get(), args_map, &WaitForSession)) {
  491. return false;
  492. }
  493. }
  494. return DoConnection(ctx.get(), args_map, &TransferData);
  495. }