Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

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