You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

554 line
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. return false;
  308. }
  309. static void InfoCallback(const SSL *ssl, int type, int value) {
  310. switch (type) {
  311. case SSL_CB_HANDSHAKE_START:
  312. fprintf(stderr, "Handshake started.\n");
  313. break;
  314. case SSL_CB_HANDSHAKE_DONE:
  315. fprintf(stderr, "Handshake done.\n");
  316. break;
  317. case SSL_CB_CONNECT_LOOP:
  318. fprintf(stderr, "Handshake progress: %s\n", SSL_state_string_long(ssl));
  319. break;
  320. }
  321. }
  322. bool Client(const std::vector<std::string> &args) {
  323. if (!InitSocketLibrary()) {
  324. return false;
  325. }
  326. std::map<std::string, std::string> args_map;
  327. if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
  328. PrintUsage(kArguments);
  329. return false;
  330. }
  331. bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
  332. const char *keylog_file = getenv("SSLKEYLOGFILE");
  333. if (keylog_file) {
  334. g_keylog_file = fopen(keylog_file, "a");
  335. if (g_keylog_file == nullptr) {
  336. perror("fopen");
  337. return false;
  338. }
  339. SSL_CTX_set_keylog_callback(ctx.get(), KeyLogCallback);
  340. }
  341. if (args_map.count("-cipher") != 0 &&
  342. !SSL_CTX_set_strict_cipher_list(ctx.get(), args_map["-cipher"].c_str())) {
  343. fprintf(stderr, "Failed setting cipher list\n");
  344. return false;
  345. }
  346. if (args_map.count("-curves") != 0 &&
  347. !SSL_CTX_set1_curves_list(ctx.get(), args_map["-curves"].c_str())) {
  348. fprintf(stderr, "Failed setting curves list\n");
  349. return false;
  350. }
  351. uint16_t max_version = TLS1_3_VERSION;
  352. if (args_map.count("-max-version") != 0 &&
  353. !VersionFromString(&max_version, args_map["-max-version"])) {
  354. fprintf(stderr, "Unknown protocol version: '%s'\n",
  355. args_map["-max-version"].c_str());
  356. return false;
  357. }
  358. if (!SSL_CTX_set_max_proto_version(ctx.get(), max_version)) {
  359. return false;
  360. }
  361. if (args_map.count("-min-version") != 0) {
  362. uint16_t version;
  363. if (!VersionFromString(&version, args_map["-min-version"])) {
  364. fprintf(stderr, "Unknown protocol version: '%s'\n",
  365. args_map["-min-version"].c_str());
  366. return false;
  367. }
  368. if (!SSL_CTX_set_min_proto_version(ctx.get(), version)) {
  369. return false;
  370. }
  371. }
  372. if (args_map.count("-select-next-proto") != 0) {
  373. const std::string &proto = args_map["-select-next-proto"];
  374. if (proto.size() > 255) {
  375. fprintf(stderr, "Bad NPN protocol: '%s'\n", proto.c_str());
  376. return false;
  377. }
  378. // |SSL_CTX_set_next_proto_select_cb| is not const-correct.
  379. SSL_CTX_set_next_proto_select_cb(ctx.get(), NextProtoSelectCallback,
  380. const_cast<char *>(proto.c_str()));
  381. }
  382. if (args_map.count("-alpn-protos") != 0) {
  383. const std::string &alpn_protos = args_map["-alpn-protos"];
  384. std::vector<uint8_t> wire;
  385. size_t i = 0;
  386. while (i <= alpn_protos.size()) {
  387. size_t j = alpn_protos.find(',', i);
  388. if (j == std::string::npos) {
  389. j = alpn_protos.size();
  390. }
  391. size_t len = j - i;
  392. if (len > 255) {
  393. fprintf(stderr, "Invalid ALPN protocols: '%s'\n", alpn_protos.c_str());
  394. return false;
  395. }
  396. wire.push_back(static_cast<uint8_t>(len));
  397. wire.resize(wire.size() + len);
  398. OPENSSL_memcpy(wire.data() + wire.size() - len, alpn_protos.data() + i,
  399. len);
  400. i = j + 1;
  401. }
  402. if (SSL_CTX_set_alpn_protos(ctx.get(), wire.data(), wire.size()) != 0) {
  403. return false;
  404. }
  405. }
  406. if (args_map.count("-fallback-scsv") != 0) {
  407. SSL_CTX_set_mode(ctx.get(), SSL_MODE_SEND_FALLBACK_SCSV);
  408. }
  409. if (args_map.count("-ocsp-stapling") != 0) {
  410. SSL_CTX_enable_ocsp_stapling(ctx.get());
  411. }
  412. if (args_map.count("-signed-certificate-timestamps") != 0) {
  413. SSL_CTX_enable_signed_cert_timestamps(ctx.get());
  414. }
  415. if (args_map.count("-channel-id-key") != 0) {
  416. bssl::UniquePtr<EVP_PKEY> pkey =
  417. LoadPrivateKey(args_map["-channel-id-key"]);
  418. if (!pkey || !SSL_CTX_set1_tls_channel_id(ctx.get(), pkey.get())) {
  419. return false;
  420. }
  421. }
  422. if (args_map.count("-false-start") != 0) {
  423. SSL_CTX_set_mode(ctx.get(), SSL_MODE_ENABLE_FALSE_START);
  424. }
  425. if (args_map.count("-key") != 0) {
  426. const std::string &key = args_map["-key"];
  427. if (!SSL_CTX_use_PrivateKey_file(ctx.get(), key.c_str(),
  428. SSL_FILETYPE_PEM)) {
  429. fprintf(stderr, "Failed to load private key: %s\n", key.c_str());
  430. return false;
  431. }
  432. const std::string &cert =
  433. args_map.count("-cert") != 0 ? args_map["-cert"] : key;
  434. if (!SSL_CTX_use_certificate_chain_file(ctx.get(), cert.c_str())) {
  435. fprintf(stderr, "Failed to load cert chain: %s\n", cert.c_str());
  436. return false;
  437. }
  438. }
  439. SSL_CTX_set_session_cache_mode(ctx.get(), SSL_SESS_CACHE_CLIENT);
  440. SSL_CTX_sess_set_new_cb(ctx.get(), NewSessionCallback);
  441. if (args_map.count("-session-out") != 0) {
  442. session_out.reset(BIO_new_file(args_map["-session-out"].c_str(), "wb"));
  443. if (!session_out) {
  444. fprintf(stderr, "Error while opening %s:\n",
  445. args_map["-session-out"].c_str());
  446. ERR_print_errors_cb(PrintErrorCallback, stderr);
  447. return false;
  448. }
  449. }
  450. if (args_map.count("-grease") != 0) {
  451. SSL_CTX_set_grease_enabled(ctx.get(), 1);
  452. }
  453. if (args_map.count("-root-certs") != 0) {
  454. if (!SSL_CTX_load_verify_locations(
  455. ctx.get(), args_map["-root-certs"].c_str(), nullptr)) {
  456. fprintf(stderr, "Failed to load root certificates.\n");
  457. ERR_print_errors_cb(PrintErrorCallback, stderr);
  458. return false;
  459. }
  460. SSL_CTX_set_verify(ctx.get(), SSL_VERIFY_PEER, nullptr);
  461. }
  462. if (args_map.count("-early-data") != 0) {
  463. SSL_CTX_set_early_data_enabled(ctx.get(), 1);
  464. }
  465. if (args_map.count("-tls13-variant") != 0) {
  466. tls13_variant_t variant;
  467. if (!GetTLS13Variant(&variant, args_map["-tls13-variant"])) {
  468. fprintf(stderr, "Unknown TLS 1.3 variant: %s\n",
  469. args_map["-tls13-variant"].c_str());
  470. return false;
  471. }
  472. SSL_CTX_set_tls13_variant(ctx.get(), variant);
  473. }
  474. if (args_map.count("-ed25519") != 0) {
  475. SSL_CTX_set_ed25519_enabled(ctx.get(), 1);
  476. }
  477. if (args_map.count("-debug") != 0) {
  478. SSL_CTX_set_info_callback(ctx.get(), InfoCallback);
  479. }
  480. if (args_map.count("-test-resumption") != 0) {
  481. if (args_map.count("-session-in") != 0) {
  482. fprintf(stderr,
  483. "Flags -session-in and -test-resumption are incompatible.\n");
  484. return false;
  485. }
  486. if (!DoConnection(ctx.get(), args_map, &WaitForSession)) {
  487. return false;
  488. }
  489. }
  490. return DoConnection(ctx.get(), args_map, &TransferData);
  491. }