Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

364 wiersze
11 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 <memory>
  16. #include <openssl/err.h>
  17. #include <openssl/rand.h>
  18. #include <openssl/ssl.h>
  19. #include "internal.h"
  20. #include "transport_common.h"
  21. static const struct argument kArguments[] = {
  22. {
  23. "-accept", kRequiredArgument,
  24. "The port of the server to bind on; eg 45102",
  25. },
  26. {
  27. "-cipher", kOptionalArgument,
  28. "An OpenSSL-style cipher suite string that configures the offered "
  29. "ciphers",
  30. },
  31. {
  32. "-curves", kOptionalArgument,
  33. "An OpenSSL-style ECDH curves list that configures the offered curves",
  34. },
  35. {
  36. "-max-version", kOptionalArgument,
  37. "The maximum acceptable protocol version",
  38. },
  39. {
  40. "-min-version", kOptionalArgument,
  41. "The minimum acceptable protocol version",
  42. },
  43. {
  44. "-key", kOptionalArgument,
  45. "PEM-encoded file containing the private key. A self-signed "
  46. "certificate is generated at runtime if this argument is not provided.",
  47. },
  48. {
  49. "-cert", kOptionalArgument,
  50. "PEM-encoded file containing the leaf certificate and optional "
  51. "certificate chain. This is taken from the -key argument if this "
  52. "argument is not provided.",
  53. },
  54. {
  55. "-ocsp-response", kOptionalArgument, "OCSP response file to send",
  56. },
  57. {
  58. "-loop", kBooleanArgument,
  59. "The server will continue accepting new sequential connections.",
  60. },
  61. {
  62. "-early-data", kBooleanArgument, "Allow early data",
  63. },
  64. {
  65. "-tls13-variant", kBooleanArgument, "Enables all TLS 1.3 variants",
  66. },
  67. {
  68. "-www", kBooleanArgument,
  69. "The server will print connection information in response to a "
  70. "HTTP GET request.",
  71. },
  72. {
  73. "-debug", kBooleanArgument,
  74. "Print debug information about the handshake",
  75. },
  76. {
  77. "-require-any-client-cert", kBooleanArgument,
  78. "The server will require a client certificate.",
  79. },
  80. {
  81. "", kOptionalArgument, "",
  82. },
  83. };
  84. static bool LoadOCSPResponse(SSL_CTX *ctx, const char *filename) {
  85. ScopedFILE f(fopen(filename, "rb"));
  86. std::vector<uint8_t> data;
  87. if (f == nullptr ||
  88. !ReadAll(&data, f.get())) {
  89. fprintf(stderr, "Error reading %s.\n", filename);
  90. return false;
  91. }
  92. if (!SSL_CTX_set_ocsp_response(ctx, data.data(), data.size())) {
  93. return false;
  94. }
  95. return true;
  96. }
  97. static bssl::UniquePtr<EVP_PKEY> MakeKeyPairForSelfSignedCert() {
  98. bssl::UniquePtr<EC_KEY> ec_key(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
  99. if (!ec_key || !EC_KEY_generate_key(ec_key.get())) {
  100. fprintf(stderr, "Failed to generate key pair.\n");
  101. return nullptr;
  102. }
  103. bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
  104. if (!evp_pkey || !EVP_PKEY_assign_EC_KEY(evp_pkey.get(), ec_key.release())) {
  105. fprintf(stderr, "Failed to assign key pair.\n");
  106. return nullptr;
  107. }
  108. return evp_pkey;
  109. }
  110. static bssl::UniquePtr<X509> MakeSelfSignedCert(EVP_PKEY *evp_pkey,
  111. const int valid_days) {
  112. bssl::UniquePtr<X509> x509(X509_new());
  113. uint32_t serial;
  114. RAND_bytes(reinterpret_cast<uint8_t*>(&serial), sizeof(serial));
  115. ASN1_INTEGER_set(X509_get_serialNumber(x509.get()), serial >> 1);
  116. X509_gmtime_adj(X509_get_notBefore(x509.get()), 0);
  117. X509_gmtime_adj(X509_get_notAfter(x509.get()), 60 * 60 * 24 * valid_days);
  118. X509_NAME* subject = X509_get_subject_name(x509.get());
  119. X509_NAME_add_entry_by_txt(subject, "C", MBSTRING_ASC,
  120. reinterpret_cast<const uint8_t *>("US"), -1, -1,
  121. 0);
  122. X509_NAME_add_entry_by_txt(subject, "O", MBSTRING_ASC,
  123. reinterpret_cast<const uint8_t *>("BoringSSL"), -1,
  124. -1, 0);
  125. X509_set_issuer_name(x509.get(), subject);
  126. if (!X509_set_pubkey(x509.get(), evp_pkey)) {
  127. fprintf(stderr, "Failed to set public key.\n");
  128. return nullptr;
  129. }
  130. if (!X509_sign(x509.get(), evp_pkey, EVP_sha256())) {
  131. fprintf(stderr, "Failed to sign certificate.\n");
  132. return nullptr;
  133. }
  134. return x509;
  135. }
  136. static void InfoCallback(const SSL *ssl, int type, int value) {
  137. switch (type) {
  138. case SSL_CB_HANDSHAKE_START:
  139. fprintf(stderr, "Handshake started.\n");
  140. break;
  141. case SSL_CB_HANDSHAKE_DONE:
  142. fprintf(stderr, "Handshake done.\n");
  143. break;
  144. case SSL_CB_ACCEPT_LOOP:
  145. fprintf(stderr, "Handshake progress: %s\n", SSL_state_string_long(ssl));
  146. break;
  147. }
  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 bool HandleWWW(SSL *ssl) {
  155. bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem()));
  156. if (!bio) {
  157. fprintf(stderr, "Cannot create BIO for response\n");
  158. return false;
  159. }
  160. BIO_puts(bio.get(), "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n");
  161. PrintConnectionInfo(bio.get(), ssl);
  162. char request[4];
  163. size_t request_len = 0;
  164. while (request_len < sizeof(request)) {
  165. int ssl_ret =
  166. SSL_read(ssl, request + request_len, sizeof(request) - request_len);
  167. if (ssl_ret <= 0) {
  168. int ssl_err = SSL_get_error(ssl, ssl_ret);
  169. fprintf(stderr, "Error while reading: %d\n", ssl_err);
  170. ERR_print_errors_cb(PrintErrorCallback, stderr);
  171. return false;
  172. }
  173. request_len += static_cast<size_t>(ssl_ret);
  174. }
  175. // Assume simple HTTP request, print status.
  176. if (memcmp(request, "GET ", 4) == 0) {
  177. const uint8_t *response;
  178. size_t response_len;
  179. if (BIO_mem_contents(bio.get(), &response, &response_len)) {
  180. SSL_write(ssl, response, response_len);
  181. }
  182. }
  183. return true;
  184. }
  185. bool Server(const std::vector<std::string> &args) {
  186. if (!InitSocketLibrary()) {
  187. return false;
  188. }
  189. std::map<std::string, std::string> args_map;
  190. if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
  191. PrintUsage(kArguments);
  192. return false;
  193. }
  194. bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
  195. const char *keylog_file = getenv("SSLKEYLOGFILE");
  196. if (keylog_file) {
  197. g_keylog_file = fopen(keylog_file, "a");
  198. if (g_keylog_file == nullptr) {
  199. perror("fopen");
  200. return false;
  201. }
  202. SSL_CTX_set_keylog_callback(ctx.get(), KeyLogCallback);
  203. }
  204. // Server authentication is required.
  205. if (args_map.count("-key") != 0) {
  206. std::string key = args_map["-key"];
  207. if (!SSL_CTX_use_PrivateKey_file(ctx.get(), key.c_str(),
  208. SSL_FILETYPE_PEM)) {
  209. fprintf(stderr, "Failed to load private key: %s\n", key.c_str());
  210. return false;
  211. }
  212. const std::string &cert =
  213. args_map.count("-cert") != 0 ? args_map["-cert"] : key;
  214. if (!SSL_CTX_use_certificate_chain_file(ctx.get(), cert.c_str())) {
  215. fprintf(stderr, "Failed to load cert chain: %s\n", cert.c_str());
  216. return false;
  217. }
  218. } else {
  219. bssl::UniquePtr<EVP_PKEY> evp_pkey = MakeKeyPairForSelfSignedCert();
  220. if (!evp_pkey) {
  221. return false;
  222. }
  223. bssl::UniquePtr<X509> cert =
  224. MakeSelfSignedCert(evp_pkey.get(), 365 /* valid_days */);
  225. if (!cert) {
  226. return false;
  227. }
  228. if (!SSL_CTX_use_PrivateKey(ctx.get(), evp_pkey.get())) {
  229. fprintf(stderr, "Failed to set private key.\n");
  230. return false;
  231. }
  232. if (!SSL_CTX_use_certificate(ctx.get(), cert.get())) {
  233. fprintf(stderr, "Failed to set certificate.\n");
  234. return false;
  235. }
  236. }
  237. if (args_map.count("-cipher") != 0 &&
  238. !SSL_CTX_set_strict_cipher_list(ctx.get(), args_map["-cipher"].c_str())) {
  239. fprintf(stderr, "Failed setting cipher list\n");
  240. return false;
  241. }
  242. if (args_map.count("-curves") != 0 &&
  243. !SSL_CTX_set1_curves_list(ctx.get(), args_map["-curves"].c_str())) {
  244. fprintf(stderr, "Failed setting curves list\n");
  245. return false;
  246. }
  247. uint16_t max_version = TLS1_3_VERSION;
  248. if (args_map.count("-max-version") != 0 &&
  249. !VersionFromString(&max_version, args_map["-max-version"])) {
  250. fprintf(stderr, "Unknown protocol version: '%s'\n",
  251. args_map["-max-version"].c_str());
  252. return false;
  253. }
  254. if (!SSL_CTX_set_max_proto_version(ctx.get(), max_version)) {
  255. return false;
  256. }
  257. if (args_map.count("-min-version") != 0) {
  258. uint16_t version;
  259. if (!VersionFromString(&version, args_map["-min-version"])) {
  260. fprintf(stderr, "Unknown protocol version: '%s'\n",
  261. args_map["-min-version"].c_str());
  262. return false;
  263. }
  264. if (!SSL_CTX_set_min_proto_version(ctx.get(), version)) {
  265. return false;
  266. }
  267. }
  268. if (args_map.count("-ocsp-response") != 0 &&
  269. !LoadOCSPResponse(ctx.get(), args_map["-ocsp-response"].c_str())) {
  270. fprintf(stderr, "Failed to load OCSP response: %s\n", args_map["-ocsp-response"].c_str());
  271. return false;
  272. }
  273. if (args_map.count("-early-data") != 0) {
  274. SSL_CTX_set_early_data_enabled(ctx.get(), 1);
  275. }
  276. if (args_map.count("-tls13-variant") != 0) {
  277. SSL_CTX_set_tls13_variant(ctx.get(), tls13_draft28);
  278. }
  279. if (args_map.count("-debug") != 0) {
  280. SSL_CTX_set_info_callback(ctx.get(), InfoCallback);
  281. }
  282. if (args_map.count("-require-any-client-cert") != 0) {
  283. SSL_CTX_set_verify(
  284. ctx.get(), SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  285. SSL_CTX_set_cert_verify_callback(
  286. ctx.get(), [](X509_STORE_CTX *store, void *arg) -> int { return 1; },
  287. nullptr);
  288. }
  289. Listener listener;
  290. if (!listener.Init(args_map["-accept"])) {
  291. return false;
  292. }
  293. bool result = true;
  294. do {
  295. int sock = -1;
  296. if (!listener.Accept(&sock)) {
  297. return false;
  298. }
  299. BIO *bio = BIO_new_socket(sock, BIO_CLOSE);
  300. bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
  301. SSL_set_bio(ssl.get(), bio, bio);
  302. int ret = SSL_accept(ssl.get());
  303. if (ret != 1) {
  304. int ssl_err = SSL_get_error(ssl.get(), ret);
  305. fprintf(stderr, "Error while connecting: %d\n", ssl_err);
  306. ERR_print_errors_cb(PrintErrorCallback, stderr);
  307. result = false;
  308. continue;
  309. }
  310. fprintf(stderr, "Connected.\n");
  311. bssl::UniquePtr<BIO> bio_stderr(BIO_new_fp(stderr, BIO_NOCLOSE));
  312. PrintConnectionInfo(bio_stderr.get(), ssl.get());
  313. if (args_map.count("-www") != 0) {
  314. result = HandleWWW(ssl.get());
  315. } else {
  316. result = TransferData(ssl.get(), sock);
  317. }
  318. } while (args_map.count("-loop") != 0);
  319. return result;
  320. }