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.
 
 
 
 
 
 

490 lines
15 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, "Allow early data",
  118. },
  119. {
  120. "-tls13-variant", kOptionalArgument,
  121. "Enable the specified experimental TLS 1.3 variant",
  122. },
  123. {
  124. "-ed25519", kBooleanArgument, "Advertise Ed25519 support",
  125. },
  126. {
  127. "-http-tunnel", kOptionalArgument,
  128. "An HTTP proxy server to tunnel the TCP connection through",
  129. },
  130. {
  131. "", kOptionalArgument, "",
  132. },
  133. };
  134. static bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
  135. bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
  136. if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
  137. return nullptr;
  138. }
  139. bssl::UniquePtr<EVP_PKEY> pkey(PEM_read_bio_PrivateKey(bio.get(), nullptr,
  140. nullptr, nullptr));
  141. return pkey;
  142. }
  143. static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
  144. const uint8_t* in, unsigned inlen, void* arg) {
  145. *out = reinterpret_cast<uint8_t *>(arg);
  146. *outlen = strlen(reinterpret_cast<const char *>(arg));
  147. return SSL_TLSEXT_ERR_OK;
  148. }
  149. static FILE *g_keylog_file = nullptr;
  150. static void KeyLogCallback(const SSL *ssl, const char *line) {
  151. fprintf(g_keylog_file, "%s\n", line);
  152. fflush(g_keylog_file);
  153. }
  154. static bssl::UniquePtr<BIO> session_out;
  155. static bssl::UniquePtr<SSL_SESSION> resume_session;
  156. static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
  157. if (session_out) {
  158. if (!PEM_write_bio_SSL_SESSION(session_out.get(), session) ||
  159. BIO_flush(session_out.get()) <= 0) {
  160. fprintf(stderr, "Error while saving session:\n");
  161. ERR_print_errors_cb(PrintErrorCallback, stderr);
  162. return 0;
  163. }
  164. }
  165. resume_session = bssl::UniquePtr<SSL_SESSION>(session);
  166. return 1;
  167. }
  168. static bool WaitForSession(SSL *ssl, int sock) {
  169. fd_set read_fds;
  170. FD_ZERO(&read_fds);
  171. if (!SocketSetNonBlocking(sock, true)) {
  172. return false;
  173. }
  174. while (!resume_session) {
  175. FD_SET(sock, &read_fds);
  176. int ret = select(sock + 1, &read_fds, NULL, NULL, NULL);
  177. if (ret <= 0) {
  178. perror("select");
  179. return false;
  180. }
  181. uint8_t buffer[512];
  182. int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer));
  183. if (ssl_ret <= 0) {
  184. int ssl_err = SSL_get_error(ssl, ssl_ret);
  185. if (ssl_err == SSL_ERROR_WANT_READ) {
  186. continue;
  187. }
  188. fprintf(stderr, "Error while reading: %d\n", ssl_err);
  189. ERR_print_errors_cb(PrintErrorCallback, stderr);
  190. return false;
  191. }
  192. }
  193. return true;
  194. }
  195. static bool DoConnection(SSL_CTX *ctx,
  196. std::map<std::string, std::string> args_map,
  197. bool (*cb)(SSL *ssl, int sock)) {
  198. int sock = -1;
  199. if (args_map.count("-http-tunnel") != 0) {
  200. if (!Connect(&sock, args_map["-http-tunnel"]) ||
  201. !DoHTTPTunnel(sock, args_map["-connect"])) {
  202. return false;
  203. }
  204. } else if (!Connect(&sock, args_map["-connect"])) {
  205. return false;
  206. }
  207. if (args_map.count("-starttls") != 0) {
  208. const std::string& starttls = args_map["-starttls"];
  209. if (starttls == "smtp") {
  210. if (!DoSMTPStartTLS(sock)) {
  211. return false;
  212. }
  213. } else {
  214. fprintf(stderr, "Unknown value for -starttls: %s\n", starttls.c_str());
  215. return false;
  216. }
  217. }
  218. bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_CLOSE));
  219. bssl::UniquePtr<SSL> ssl(SSL_new(ctx));
  220. if (args_map.count("-server-name") != 0) {
  221. SSL_set_tlsext_host_name(ssl.get(), args_map["-server-name"].c_str());
  222. }
  223. if (args_map.count("-session-in") != 0) {
  224. bssl::UniquePtr<BIO> in(BIO_new_file(args_map["-session-in"].c_str(),
  225. "rb"));
  226. if (!in) {
  227. fprintf(stderr, "Error reading session\n");
  228. ERR_print_errors_cb(PrintErrorCallback, stderr);
  229. return false;
  230. }
  231. bssl::UniquePtr<SSL_SESSION> session(PEM_read_bio_SSL_SESSION(in.get(),
  232. nullptr, nullptr, nullptr));
  233. if (!session) {
  234. fprintf(stderr, "Error reading session\n");
  235. ERR_print_errors_cb(PrintErrorCallback, stderr);
  236. return false;
  237. }
  238. SSL_set_session(ssl.get(), session.get());
  239. }
  240. if (resume_session) {
  241. SSL_set_session(ssl.get(), resume_session.get());
  242. }
  243. SSL_set_bio(ssl.get(), bio.get(), bio.get());
  244. bio.release();
  245. int ret = SSL_connect(ssl.get());
  246. if (ret != 1) {
  247. int ssl_err = SSL_get_error(ssl.get(), ret);
  248. fprintf(stderr, "Error while connecting: %d\n", ssl_err);
  249. ERR_print_errors_cb(PrintErrorCallback, stderr);
  250. return false;
  251. }
  252. if (args_map.count("-early-data") != 0 && SSL_in_early_data(ssl.get())) {
  253. int ed_size = args_map["-early-data"].size();
  254. int ssl_ret = SSL_write(ssl.get(), args_map["-early-data"].data(), ed_size);
  255. if (ssl_ret <= 0) {
  256. int ssl_err = SSL_get_error(ssl.get(), ssl_ret);
  257. fprintf(stderr, "Error while writing: %d\n", ssl_err);
  258. ERR_print_errors_cb(PrintErrorCallback, stderr);
  259. return false;
  260. } else if (ssl_ret != ed_size) {
  261. fprintf(stderr, "Short write from SSL_write.\n");
  262. return false;
  263. }
  264. }
  265. fprintf(stderr, "Connected.\n");
  266. PrintConnectionInfo(ssl.get());
  267. return cb(ssl.get(), sock);
  268. }
  269. bool Client(const std::vector<std::string> &args) {
  270. if (!InitSocketLibrary()) {
  271. return false;
  272. }
  273. std::map<std::string, std::string> args_map;
  274. if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
  275. PrintUsage(kArguments);
  276. return false;
  277. }
  278. bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(SSLv23_client_method()));
  279. const char *keylog_file = getenv("SSLKEYLOGFILE");
  280. if (keylog_file) {
  281. g_keylog_file = fopen(keylog_file, "a");
  282. if (g_keylog_file == nullptr) {
  283. perror("fopen");
  284. return false;
  285. }
  286. SSL_CTX_set_keylog_callback(ctx.get(), KeyLogCallback);
  287. }
  288. if (args_map.count("-cipher") != 0 &&
  289. !SSL_CTX_set_strict_cipher_list(ctx.get(), args_map["-cipher"].c_str())) {
  290. fprintf(stderr, "Failed setting cipher list\n");
  291. return false;
  292. }
  293. if (args_map.count("-curves") != 0 &&
  294. !SSL_CTX_set1_curves_list(ctx.get(), args_map["-curves"].c_str())) {
  295. fprintf(stderr, "Failed setting curves list\n");
  296. return false;
  297. }
  298. uint16_t max_version = TLS1_3_VERSION;
  299. if (args_map.count("-max-version") != 0 &&
  300. !VersionFromString(&max_version, args_map["-max-version"])) {
  301. fprintf(stderr, "Unknown protocol version: '%s'\n",
  302. args_map["-max-version"].c_str());
  303. return false;
  304. }
  305. if (!SSL_CTX_set_max_proto_version(ctx.get(), max_version)) {
  306. return false;
  307. }
  308. if (args_map.count("-min-version") != 0) {
  309. uint16_t version;
  310. if (!VersionFromString(&version, args_map["-min-version"])) {
  311. fprintf(stderr, "Unknown protocol version: '%s'\n",
  312. args_map["-min-version"].c_str());
  313. return false;
  314. }
  315. if (!SSL_CTX_set_min_proto_version(ctx.get(), version)) {
  316. return false;
  317. }
  318. }
  319. if (args_map.count("-select-next-proto") != 0) {
  320. const std::string &proto = args_map["-select-next-proto"];
  321. if (proto.size() > 255) {
  322. fprintf(stderr, "Bad NPN protocol: '%s'\n", proto.c_str());
  323. return false;
  324. }
  325. // |SSL_CTX_set_next_proto_select_cb| is not const-correct.
  326. SSL_CTX_set_next_proto_select_cb(ctx.get(), NextProtoSelectCallback,
  327. const_cast<char *>(proto.c_str()));
  328. }
  329. if (args_map.count("-alpn-protos") != 0) {
  330. const std::string &alpn_protos = args_map["-alpn-protos"];
  331. std::vector<uint8_t> wire;
  332. size_t i = 0;
  333. while (i <= alpn_protos.size()) {
  334. size_t j = alpn_protos.find(',', i);
  335. if (j == std::string::npos) {
  336. j = alpn_protos.size();
  337. }
  338. size_t len = j - i;
  339. if (len > 255) {
  340. fprintf(stderr, "Invalid ALPN protocols: '%s'\n", alpn_protos.c_str());
  341. return false;
  342. }
  343. wire.push_back(static_cast<uint8_t>(len));
  344. wire.resize(wire.size() + len);
  345. OPENSSL_memcpy(wire.data() + wire.size() - len, alpn_protos.data() + i,
  346. len);
  347. i = j + 1;
  348. }
  349. if (SSL_CTX_set_alpn_protos(ctx.get(), wire.data(), wire.size()) != 0) {
  350. return false;
  351. }
  352. }
  353. if (args_map.count("-fallback-scsv") != 0) {
  354. SSL_CTX_set_mode(ctx.get(), SSL_MODE_SEND_FALLBACK_SCSV);
  355. }
  356. if (args_map.count("-ocsp-stapling") != 0) {
  357. SSL_CTX_enable_ocsp_stapling(ctx.get());
  358. }
  359. if (args_map.count("-signed-certificate-timestamps") != 0) {
  360. SSL_CTX_enable_signed_cert_timestamps(ctx.get());
  361. }
  362. if (args_map.count("-channel-id-key") != 0) {
  363. bssl::UniquePtr<EVP_PKEY> pkey =
  364. LoadPrivateKey(args_map["-channel-id-key"]);
  365. if (!pkey || !SSL_CTX_set1_tls_channel_id(ctx.get(), pkey.get())) {
  366. return false;
  367. }
  368. }
  369. if (args_map.count("-false-start") != 0) {
  370. SSL_CTX_set_mode(ctx.get(), SSL_MODE_ENABLE_FALSE_START);
  371. }
  372. if (args_map.count("-key") != 0) {
  373. const std::string &key = args_map["-key"];
  374. if (!SSL_CTX_use_PrivateKey_file(ctx.get(), key.c_str(),
  375. SSL_FILETYPE_PEM)) {
  376. fprintf(stderr, "Failed to load private key: %s\n", key.c_str());
  377. return false;
  378. }
  379. const std::string &cert =
  380. args_map.count("-cert") != 0 ? args_map["-cert"] : key;
  381. if (!SSL_CTX_use_certificate_chain_file(ctx.get(), cert.c_str())) {
  382. fprintf(stderr, "Failed to load cert chain: %s\n", cert.c_str());
  383. return false;
  384. }
  385. }
  386. SSL_CTX_set_session_cache_mode(ctx.get(), SSL_SESS_CACHE_CLIENT);
  387. SSL_CTX_sess_set_new_cb(ctx.get(), NewSessionCallback);
  388. if (args_map.count("-session-out") != 0) {
  389. session_out.reset(BIO_new_file(args_map["-session-out"].c_str(), "wb"));
  390. if (!session_out) {
  391. fprintf(stderr, "Error while opening %s:\n",
  392. args_map["-session-out"].c_str());
  393. ERR_print_errors_cb(PrintErrorCallback, stderr);
  394. return false;
  395. }
  396. }
  397. if (args_map.count("-grease") != 0) {
  398. SSL_CTX_set_grease_enabled(ctx.get(), 1);
  399. }
  400. if (args_map.count("-root-certs") != 0) {
  401. if (!SSL_CTX_load_verify_locations(
  402. ctx.get(), args_map["-root-certs"].c_str(), nullptr)) {
  403. fprintf(stderr, "Failed to load root certificates.\n");
  404. ERR_print_errors_cb(PrintErrorCallback, stderr);
  405. return false;
  406. }
  407. SSL_CTX_set_verify(ctx.get(), SSL_VERIFY_PEER, nullptr);
  408. }
  409. if (args_map.count("-early-data") != 0) {
  410. SSL_CTX_set_early_data_enabled(ctx.get(), 1);
  411. }
  412. if (args_map.count("-tls13-variant") != 0) {
  413. SSL_CTX_set_tls13_variant(ctx.get(),
  414. static_cast<enum tls13_variant_t>(
  415. atoi(args_map["-tls13-variant"].c_str())));
  416. }
  417. if (args_map.count("-ed25519") != 0) {
  418. SSL_CTX_set_ed25519_enabled(ctx.get(), 1);
  419. }
  420. if (args_map.count("-test-resumption") != 0) {
  421. if (args_map.count("-session-in") != 0) {
  422. fprintf(stderr,
  423. "Flags -session-in and -test-resumption are incompatible.\n");
  424. return false;
  425. }
  426. if (!DoConnection(ctx.get(), args_map, &WaitForSession)) {
  427. return false;
  428. }
  429. }
  430. return DoConnection(ctx.get(), args_map, &TransferData);
  431. }