client.cc 16 KB

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