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.

server.cc 12 KiB

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