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.
 
 
 
 
 
 

381 regels
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", kOptionalArgument,
  66. "Enable the specified experimental TLS 1.3 variant",
  67. },
  68. {
  69. "-www", kBooleanArgument,
  70. "The server will print connection information in response to a "
  71. "HTTP GET request.",
  72. },
  73. {
  74. "-debug", kBooleanArgument,
  75. "Print debug information about the handshake",
  76. },
  77. {
  78. "-require-any-client-cert", kBooleanArgument,
  79. "The server will require a client certificate.",
  80. },
  81. {
  82. "", kOptionalArgument, "",
  83. },
  84. };
  85. static bool LoadOCSPResponse(SSL_CTX *ctx, const char *filename) {
  86. ScopedFILE f(fopen(filename, "rb"));
  87. std::vector<uint8_t> data;
  88. if (f == nullptr ||
  89. !ReadAll(&data, f.get())) {
  90. fprintf(stderr, "Error reading %s.\n", filename);
  91. return false;
  92. }
  93. if (!SSL_CTX_set_ocsp_response(ctx, data.data(), data.size())) {
  94. return false;
  95. }
  96. return true;
  97. }
  98. static bssl::UniquePtr<EVP_PKEY> MakeKeyPairForSelfSignedCert() {
  99. bssl::UniquePtr<EC_KEY> ec_key(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
  100. if (!ec_key || !EC_KEY_generate_key(ec_key.get())) {
  101. fprintf(stderr, "Failed to generate key pair.\n");
  102. return nullptr;
  103. }
  104. bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
  105. if (!evp_pkey || !EVP_PKEY_assign_EC_KEY(evp_pkey.get(), ec_key.release())) {
  106. fprintf(stderr, "Failed to assign key pair.\n");
  107. return nullptr;
  108. }
  109. return evp_pkey;
  110. }
  111. static bssl::UniquePtr<X509> MakeSelfSignedCert(EVP_PKEY *evp_pkey,
  112. const int valid_days) {
  113. bssl::UniquePtr<X509> x509(X509_new());
  114. uint32_t serial;
  115. RAND_bytes(reinterpret_cast<uint8_t*>(&serial), sizeof(serial));
  116. ASN1_INTEGER_set(X509_get_serialNumber(x509.get()), serial >> 1);
  117. X509_gmtime_adj(X509_get_notBefore(x509.get()), 0);
  118. X509_gmtime_adj(X509_get_notAfter(x509.get()), 60 * 60 * 24 * valid_days);
  119. X509_NAME* subject = X509_get_subject_name(x509.get());
  120. X509_NAME_add_entry_by_txt(subject, "C", MBSTRING_ASC,
  121. reinterpret_cast<const uint8_t *>("US"), -1, -1,
  122. 0);
  123. X509_NAME_add_entry_by_txt(subject, "O", MBSTRING_ASC,
  124. reinterpret_cast<const uint8_t *>("BoringSSL"), -1,
  125. -1, 0);
  126. X509_set_issuer_name(x509.get(), subject);
  127. if (!X509_set_pubkey(x509.get(), evp_pkey)) {
  128. fprintf(stderr, "Failed to set public key.\n");
  129. return nullptr;
  130. }
  131. if (!X509_sign(x509.get(), evp_pkey, EVP_sha256())) {
  132. fprintf(stderr, "Failed to sign certificate.\n");
  133. return nullptr;
  134. }
  135. return x509;
  136. }
  137. static bool GetTLS13Variant(tls13_variant_t *out, const std::string &in) {
  138. if (in == "draft23") {
  139. *out = tls13_draft23;
  140. return true;
  141. }
  142. if (in == "draft28") {
  143. *out = tls13_draft28;
  144. return true;
  145. }
  146. return false;
  147. }
  148. static void InfoCallback(const SSL *ssl, int type, int value) {
  149. switch (type) {
  150. case SSL_CB_HANDSHAKE_START:
  151. fprintf(stderr, "Handshake started.\n");
  152. break;
  153. case SSL_CB_HANDSHAKE_DONE:
  154. fprintf(stderr, "Handshake done.\n");
  155. break;
  156. case SSL_CB_ACCEPT_LOOP:
  157. fprintf(stderr, "Handshake progress: %s\n", SSL_state_string_long(ssl));
  158. break;
  159. }
  160. }
  161. static FILE *g_keylog_file = nullptr;
  162. static void KeyLogCallback(const SSL *ssl, const char *line) {
  163. fprintf(g_keylog_file, "%s\n", line);
  164. fflush(g_keylog_file);
  165. }
  166. static bool HandleWWW(SSL *ssl) {
  167. bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem()));
  168. if (!bio) {
  169. fprintf(stderr, "Cannot create BIO for response\n");
  170. return false;
  171. }
  172. BIO_puts(bio.get(), "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n");
  173. PrintConnectionInfo(bio.get(), ssl);
  174. char request[4];
  175. size_t request_len = 0;
  176. while (request_len < sizeof(request)) {
  177. int ssl_ret =
  178. SSL_read(ssl, request + request_len, sizeof(request) - request_len);
  179. if (ssl_ret <= 0) {
  180. int ssl_err = SSL_get_error(ssl, ssl_ret);
  181. PrintSSLError(stderr, "Error while reading", ssl_err, ssl_ret);
  182. return false;
  183. }
  184. request_len += static_cast<size_t>(ssl_ret);
  185. }
  186. // Assume simple HTTP request, print status.
  187. if (memcmp(request, "GET ", 4) == 0) {
  188. const uint8_t *response;
  189. size_t response_len;
  190. if (BIO_mem_contents(bio.get(), &response, &response_len)) {
  191. SSL_write(ssl, response, response_len);
  192. }
  193. }
  194. return true;
  195. }
  196. bool Server(const std::vector<std::string> &args) {
  197. if (!InitSocketLibrary()) {
  198. return false;
  199. }
  200. std::map<std::string, std::string> args_map;
  201. if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
  202. PrintUsage(kArguments);
  203. return false;
  204. }
  205. bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
  206. const char *keylog_file = getenv("SSLKEYLOGFILE");
  207. if (keylog_file) {
  208. g_keylog_file = fopen(keylog_file, "a");
  209. if (g_keylog_file == nullptr) {
  210. perror("fopen");
  211. return false;
  212. }
  213. SSL_CTX_set_keylog_callback(ctx.get(), KeyLogCallback);
  214. }
  215. // Server authentication is required.
  216. if (args_map.count("-key") != 0) {
  217. std::string key = args_map["-key"];
  218. if (!SSL_CTX_use_PrivateKey_file(ctx.get(), key.c_str(),
  219. SSL_FILETYPE_PEM)) {
  220. fprintf(stderr, "Failed to load private key: %s\n", key.c_str());
  221. return false;
  222. }
  223. const std::string &cert =
  224. args_map.count("-cert") != 0 ? args_map["-cert"] : key;
  225. if (!SSL_CTX_use_certificate_chain_file(ctx.get(), cert.c_str())) {
  226. fprintf(stderr, "Failed to load cert chain: %s\n", cert.c_str());
  227. return false;
  228. }
  229. } else {
  230. bssl::UniquePtr<EVP_PKEY> evp_pkey = MakeKeyPairForSelfSignedCert();
  231. if (!evp_pkey) {
  232. return false;
  233. }
  234. bssl::UniquePtr<X509> cert =
  235. MakeSelfSignedCert(evp_pkey.get(), 365 /* valid_days */);
  236. if (!cert) {
  237. return false;
  238. }
  239. if (!SSL_CTX_use_PrivateKey(ctx.get(), evp_pkey.get())) {
  240. fprintf(stderr, "Failed to set private key.\n");
  241. return false;
  242. }
  243. if (!SSL_CTX_use_certificate(ctx.get(), cert.get())) {
  244. fprintf(stderr, "Failed to set certificate.\n");
  245. return false;
  246. }
  247. }
  248. if (args_map.count("-cipher") != 0 &&
  249. !SSL_CTX_set_strict_cipher_list(ctx.get(), args_map["-cipher"].c_str())) {
  250. fprintf(stderr, "Failed setting cipher list\n");
  251. return false;
  252. }
  253. if (args_map.count("-curves") != 0 &&
  254. !SSL_CTX_set1_curves_list(ctx.get(), args_map["-curves"].c_str())) {
  255. fprintf(stderr, "Failed setting curves list\n");
  256. return false;
  257. }
  258. uint16_t max_version = TLS1_3_VERSION;
  259. if (args_map.count("-max-version") != 0 &&
  260. !VersionFromString(&max_version, args_map["-max-version"])) {
  261. fprintf(stderr, "Unknown protocol version: '%s'\n",
  262. args_map["-max-version"].c_str());
  263. return false;
  264. }
  265. if (!SSL_CTX_set_max_proto_version(ctx.get(), max_version)) {
  266. return false;
  267. }
  268. if (args_map.count("-min-version") != 0) {
  269. uint16_t version;
  270. if (!VersionFromString(&version, args_map["-min-version"])) {
  271. fprintf(stderr, "Unknown protocol version: '%s'\n",
  272. args_map["-min-version"].c_str());
  273. return false;
  274. }
  275. if (!SSL_CTX_set_min_proto_version(ctx.get(), version)) {
  276. return false;
  277. }
  278. }
  279. if (args_map.count("-ocsp-response") != 0 &&
  280. !LoadOCSPResponse(ctx.get(), args_map["-ocsp-response"].c_str())) {
  281. fprintf(stderr, "Failed to load OCSP response: %s\n", args_map["-ocsp-response"].c_str());
  282. return false;
  283. }
  284. if (args_map.count("-early-data") != 0) {
  285. SSL_CTX_set_early_data_enabled(ctx.get(), 1);
  286. }
  287. if (args_map.count("-tls13-variant") != 0) {
  288. tls13_variant_t variant;
  289. if (!GetTLS13Variant(&variant, args_map["-tls13-variant"])) {
  290. fprintf(stderr, "Unknown TLS 1.3 variant: %s\n",
  291. args_map["-tls13-variant"].c_str());
  292. return false;
  293. }
  294. SSL_CTX_set_tls13_variant(ctx.get(), variant);
  295. }
  296. if (args_map.count("-debug") != 0) {
  297. SSL_CTX_set_info_callback(ctx.get(), InfoCallback);
  298. }
  299. if (args_map.count("-require-any-client-cert") != 0) {
  300. SSL_CTX_set_verify(
  301. ctx.get(), SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  302. SSL_CTX_set_cert_verify_callback(
  303. ctx.get(), [](X509_STORE_CTX *store, void *arg) -> int { return 1; },
  304. nullptr);
  305. }
  306. Listener listener;
  307. if (!listener.Init(args_map["-accept"])) {
  308. return false;
  309. }
  310. bool result = true;
  311. do {
  312. int sock = -1;
  313. if (!listener.Accept(&sock)) {
  314. return false;
  315. }
  316. BIO *bio = BIO_new_socket(sock, BIO_CLOSE);
  317. bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
  318. SSL_set_bio(ssl.get(), bio, bio);
  319. int ret = SSL_accept(ssl.get());
  320. if (ret != 1) {
  321. int ssl_err = SSL_get_error(ssl.get(), ret);
  322. PrintSSLError(stderr, "Error while connecting", ssl_err, ret);
  323. result = false;
  324. continue;
  325. }
  326. fprintf(stderr, "Connected.\n");
  327. bssl::UniquePtr<BIO> bio_stderr(BIO_new_fp(stderr, BIO_NOCLOSE));
  328. PrintConnectionInfo(bio_stderr.get(), ssl.get());
  329. if (args_map.count("-www") != 0) {
  330. result = HandleWWW(ssl.get());
  331. } else {
  332. result = TransferData(ssl.get(), sock);
  333. }
  334. } while (args_map.count("-loop") != 0);
  335. return result;
  336. }