Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

415 строки
12 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 ciphers",
  37. },
  38. {
  39. "-max-version", kOptionalArgument,
  40. "The maximum acceptable protocol version",
  41. },
  42. {
  43. "-min-version", kOptionalArgument,
  44. "The minimum acceptable protocol version",
  45. },
  46. {
  47. "-server-name", kOptionalArgument,
  48. "The server name to advertise",
  49. },
  50. {
  51. "-select-next-proto", kOptionalArgument,
  52. "An NPN protocol to select if the server supports NPN",
  53. },
  54. {
  55. "-alpn-protos", kOptionalArgument,
  56. "A comma-separated list of ALPN protocols to advertise",
  57. },
  58. {
  59. "-fallback-scsv", kBooleanArgument,
  60. "Enable FALLBACK_SCSV",
  61. },
  62. {
  63. "-ocsp-stapling", kBooleanArgument,
  64. "Advertise support for OCSP stabling",
  65. },
  66. {
  67. "-signed-certificate-timestamps", kBooleanArgument,
  68. "Advertise support for signed certificate timestamps",
  69. },
  70. {
  71. "-channel-id-key", kOptionalArgument,
  72. "The key to use for signing a channel ID",
  73. },
  74. {
  75. "-false-start", kBooleanArgument,
  76. "Enable False Start",
  77. },
  78. { "-session-in", kOptionalArgument,
  79. "A file containing a session to resume.",
  80. },
  81. { "-session-out", kOptionalArgument,
  82. "A file to write the negotiated session to.",
  83. },
  84. {
  85. "-key", kOptionalArgument,
  86. "Private-key file to use (default is no client certificate)",
  87. },
  88. {
  89. "-starttls", kOptionalArgument,
  90. "A STARTTLS mini-protocol to run before the TLS handshake. Supported"
  91. " values: 'smtp'",
  92. },
  93. {
  94. "-grease", kBooleanArgument,
  95. "Enable GREASE",
  96. },
  97. {
  98. "-resume", kBooleanArgument,
  99. "Establish a second connection resuming the original connection.",
  100. },
  101. {
  102. "-root-certs", kOptionalArgument,
  103. "A filename containing one of more PEM root certificates. Implies that"
  104. "verification is required.",
  105. },
  106. {
  107. "", kOptionalArgument, "",
  108. },
  109. };
  110. static bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
  111. bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
  112. if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
  113. return nullptr;
  114. }
  115. bssl::UniquePtr<EVP_PKEY> pkey(PEM_read_bio_PrivateKey(bio.get(), nullptr,
  116. nullptr, nullptr));
  117. return pkey;
  118. }
  119. static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
  120. const uint8_t* in, unsigned inlen, void* arg) {
  121. *out = reinterpret_cast<uint8_t *>(arg);
  122. *outlen = strlen(reinterpret_cast<const char *>(arg));
  123. return SSL_TLSEXT_ERR_OK;
  124. }
  125. static FILE *g_keylog_file = nullptr;
  126. static void KeyLogCallback(const SSL *ssl, const char *line) {
  127. fprintf(g_keylog_file, "%s\n", line);
  128. fflush(g_keylog_file);
  129. }
  130. static bssl::UniquePtr<BIO> session_out;
  131. static bssl::UniquePtr<SSL_SESSION> resume_session;
  132. static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
  133. if (session_out) {
  134. if (!PEM_write_bio_SSL_SESSION(session_out.get(), session) ||
  135. BIO_flush(session_out.get()) <= 0) {
  136. fprintf(stderr, "Error while saving session:\n");
  137. ERR_print_errors_cb(PrintErrorCallback, stderr);
  138. return 0;
  139. }
  140. }
  141. resume_session = bssl::UniquePtr<SSL_SESSION>(session);
  142. return 1;
  143. }
  144. static bool WaitForSession(SSL *ssl, int sock) {
  145. fd_set read_fds;
  146. FD_ZERO(&read_fds);
  147. if (!SocketSetNonBlocking(sock, true)) {
  148. return false;
  149. }
  150. while (!resume_session) {
  151. FD_SET(sock, &read_fds);
  152. int ret = select(sock + 1, &read_fds, NULL, NULL, NULL);
  153. if (ret <= 0) {
  154. perror("select");
  155. return false;
  156. }
  157. uint8_t buffer[512];
  158. int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer));
  159. if (ssl_ret <= 0) {
  160. int ssl_err = SSL_get_error(ssl, ssl_ret);
  161. if (ssl_err == SSL_ERROR_WANT_READ) {
  162. continue;
  163. }
  164. fprintf(stderr, "Error while reading: %d\n", ssl_err);
  165. ERR_print_errors_cb(PrintErrorCallback, stderr);
  166. return false;
  167. }
  168. }
  169. return true;
  170. }
  171. static bool DoConnection(SSL_CTX *ctx,
  172. std::map<std::string, std::string> args_map,
  173. bool (*cb)(SSL *ssl, int sock)) {
  174. int sock = -1;
  175. if (!Connect(&sock, args_map["-connect"])) {
  176. return false;
  177. }
  178. if (args_map.count("-starttls") != 0) {
  179. const std::string& starttls = args_map["-starttls"];
  180. if (starttls == "smtp") {
  181. if (!DoSMTPStartTLS(sock)) {
  182. return false;
  183. }
  184. } else {
  185. fprintf(stderr, "Unknown value for -starttls: %s\n", starttls.c_str());
  186. return false;
  187. }
  188. }
  189. bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_CLOSE));
  190. bssl::UniquePtr<SSL> ssl(SSL_new(ctx));
  191. if (args_map.count("-server-name") != 0) {
  192. SSL_set_tlsext_host_name(ssl.get(), args_map["-server-name"].c_str());
  193. }
  194. if (args_map.count("-session-in") != 0) {
  195. bssl::UniquePtr<BIO> in(BIO_new_file(args_map["-session-in"].c_str(),
  196. "rb"));
  197. if (!in) {
  198. fprintf(stderr, "Error reading session\n");
  199. ERR_print_errors_cb(PrintErrorCallback, stderr);
  200. return false;
  201. }
  202. bssl::UniquePtr<SSL_SESSION> session(PEM_read_bio_SSL_SESSION(in.get(),
  203. nullptr, nullptr, nullptr));
  204. if (!session) {
  205. fprintf(stderr, "Error reading session\n");
  206. ERR_print_errors_cb(PrintErrorCallback, stderr);
  207. return false;
  208. }
  209. SSL_set_session(ssl.get(), session.get());
  210. } else if (resume_session) {
  211. SSL_set_session(ssl.get(), resume_session.get());
  212. }
  213. SSL_set_bio(ssl.get(), bio.get(), bio.get());
  214. bio.release();
  215. int ret = SSL_connect(ssl.get());
  216. if (ret != 1) {
  217. int ssl_err = SSL_get_error(ssl.get(), ret);
  218. fprintf(stderr, "Error while connecting: %d\n", ssl_err);
  219. ERR_print_errors_cb(PrintErrorCallback, stderr);
  220. return false;
  221. }
  222. fprintf(stderr, "Connected.\n");
  223. PrintConnectionInfo(ssl.get());
  224. return cb(ssl.get(), sock);
  225. }
  226. bool Client(const std::vector<std::string> &args) {
  227. if (!InitSocketLibrary()) {
  228. return false;
  229. }
  230. std::map<std::string, std::string> args_map;
  231. if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
  232. PrintUsage(kArguments);
  233. return false;
  234. }
  235. bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(SSLv23_client_method()));
  236. const char *keylog_file = getenv("SSLKEYLOGFILE");
  237. if (keylog_file) {
  238. g_keylog_file = fopen(keylog_file, "a");
  239. if (g_keylog_file == nullptr) {
  240. perror("fopen");
  241. return false;
  242. }
  243. SSL_CTX_set_keylog_callback(ctx.get(), KeyLogCallback);
  244. }
  245. if (args_map.count("-cipher") != 0 &&
  246. !SSL_CTX_set_strict_cipher_list(ctx.get(), args_map["-cipher"].c_str())) {
  247. fprintf(stderr, "Failed setting cipher list\n");
  248. return false;
  249. }
  250. uint16_t max_version = TLS1_3_VERSION;
  251. if (args_map.count("-max-version") != 0 &&
  252. !VersionFromString(&max_version, args_map["-max-version"])) {
  253. fprintf(stderr, "Unknown protocol version: '%s'\n",
  254. args_map["-max-version"].c_str());
  255. return false;
  256. }
  257. if (!SSL_CTX_set_max_proto_version(ctx.get(), max_version)) {
  258. return false;
  259. }
  260. if (args_map.count("-min-version") != 0) {
  261. uint16_t version;
  262. if (!VersionFromString(&version, args_map["-min-version"])) {
  263. fprintf(stderr, "Unknown protocol version: '%s'\n",
  264. args_map["-min-version"].c_str());
  265. return false;
  266. }
  267. if (!SSL_CTX_set_min_proto_version(ctx.get(), version)) {
  268. return false;
  269. }
  270. }
  271. if (args_map.count("-select-next-proto") != 0) {
  272. const std::string &proto = args_map["-select-next-proto"];
  273. if (proto.size() > 255) {
  274. fprintf(stderr, "Bad NPN protocol: '%s'\n", proto.c_str());
  275. return false;
  276. }
  277. // |SSL_CTX_set_next_proto_select_cb| is not const-correct.
  278. SSL_CTX_set_next_proto_select_cb(ctx.get(), NextProtoSelectCallback,
  279. const_cast<char *>(proto.c_str()));
  280. }
  281. if (args_map.count("-alpn-protos") != 0) {
  282. const std::string &alpn_protos = args_map["-alpn-protos"];
  283. std::vector<uint8_t> wire;
  284. size_t i = 0;
  285. while (i <= alpn_protos.size()) {
  286. size_t j = alpn_protos.find(',', i);
  287. if (j == std::string::npos) {
  288. j = alpn_protos.size();
  289. }
  290. size_t len = j - i;
  291. if (len > 255) {
  292. fprintf(stderr, "Invalid ALPN protocols: '%s'\n", alpn_protos.c_str());
  293. return false;
  294. }
  295. wire.push_back(static_cast<uint8_t>(len));
  296. wire.resize(wire.size() + len);
  297. OPENSSL_memcpy(wire.data() + wire.size() - len, alpn_protos.data() + i,
  298. len);
  299. i = j + 1;
  300. }
  301. if (SSL_CTX_set_alpn_protos(ctx.get(), wire.data(), wire.size()) != 0) {
  302. return false;
  303. }
  304. }
  305. if (args_map.count("-fallback-scsv") != 0) {
  306. SSL_CTX_set_mode(ctx.get(), SSL_MODE_SEND_FALLBACK_SCSV);
  307. }
  308. if (args_map.count("-ocsp-stapling") != 0) {
  309. SSL_CTX_enable_ocsp_stapling(ctx.get());
  310. }
  311. if (args_map.count("-signed-certificate-timestamps") != 0) {
  312. SSL_CTX_enable_signed_cert_timestamps(ctx.get());
  313. }
  314. if (args_map.count("-channel-id-key") != 0) {
  315. bssl::UniquePtr<EVP_PKEY> pkey =
  316. LoadPrivateKey(args_map["-channel-id-key"]);
  317. if (!pkey || !SSL_CTX_set1_tls_channel_id(ctx.get(), pkey.get())) {
  318. return false;
  319. }
  320. }
  321. if (args_map.count("-false-start") != 0) {
  322. SSL_CTX_set_mode(ctx.get(), SSL_MODE_ENABLE_FALSE_START);
  323. }
  324. if (args_map.count("-key") != 0) {
  325. const std::string &key = args_map["-key"];
  326. if (!SSL_CTX_use_PrivateKey_file(ctx.get(), key.c_str(), SSL_FILETYPE_PEM)) {
  327. fprintf(stderr, "Failed to load private key: %s\n", key.c_str());
  328. return false;
  329. }
  330. if (!SSL_CTX_use_certificate_chain_file(ctx.get(), key.c_str())) {
  331. fprintf(stderr, "Failed to load cert chain: %s\n", key.c_str());
  332. return false;
  333. }
  334. }
  335. SSL_CTX_set_session_cache_mode(ctx.get(), SSL_SESS_CACHE_CLIENT);
  336. SSL_CTX_sess_set_new_cb(ctx.get(), NewSessionCallback);
  337. if (args_map.count("-session-out") != 0) {
  338. session_out.reset(BIO_new_file(args_map["-session-out"].c_str(), "wb"));
  339. if (!session_out) {
  340. fprintf(stderr, "Error while opening %s:\n",
  341. args_map["-session-out"].c_str());
  342. ERR_print_errors_cb(PrintErrorCallback, stderr);
  343. return false;
  344. }
  345. }
  346. if (args_map.count("-grease") != 0) {
  347. SSL_CTX_set_grease_enabled(ctx.get(), 1);
  348. }
  349. if (args_map.count("-root-certs") != 0) {
  350. if (!SSL_CTX_load_verify_locations(
  351. ctx.get(), args_map["-root-certs"].c_str(), nullptr)) {
  352. fprintf(stderr, "Failed to load root certificates.\n");
  353. ERR_print_errors_cb(PrintErrorCallback, stderr);
  354. return false;
  355. }
  356. SSL_CTX_set_verify(ctx.get(), SSL_VERIFY_PEER, nullptr);
  357. }
  358. if (args_map.count("-resume") != 0 &&
  359. !DoConnection(ctx.get(), args_map, &WaitForSession)) {
  360. return false;
  361. }
  362. return DoConnection(ctx.get(), args_map, &TransferData);
  363. }