server.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. "-www", kBooleanArgument,
  66. "The server will print connection information in response to a "
  67. "HTTP GET request.",
  68. },
  69. {
  70. "-debug", kBooleanArgument,
  71. "Print debug information about the handshake",
  72. },
  73. {
  74. "-require-any-client-cert", kBooleanArgument,
  75. "The server will require a client certificate.",
  76. },
  77. {
  78. "-jdk11-workaround", kBooleanArgument,
  79. "Enable the JDK 11 workaround",
  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 void InfoCallback(const SSL *ssl, int type, int value) {
  138. switch (type) {
  139. case SSL_CB_HANDSHAKE_START:
  140. fprintf(stderr, "Handshake started.\n");
  141. break;
  142. case SSL_CB_HANDSHAKE_DONE:
  143. fprintf(stderr, "Handshake done.\n");
  144. break;
  145. case SSL_CB_ACCEPT_LOOP:
  146. fprintf(stderr, "Handshake progress: %s\n", SSL_state_string_long(ssl));
  147. break;
  148. }
  149. }
  150. static FILE *g_keylog_file = nullptr;
  151. static void KeyLogCallback(const SSL *ssl, const char *line) {
  152. fprintf(g_keylog_file, "%s\n", line);
  153. fflush(g_keylog_file);
  154. }
  155. static bool HandleWWW(SSL *ssl) {
  156. bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem()));
  157. if (!bio) {
  158. fprintf(stderr, "Cannot create BIO for response\n");
  159. return false;
  160. }
  161. BIO_puts(bio.get(), "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n");
  162. PrintConnectionInfo(bio.get(), ssl);
  163. char request[4];
  164. size_t request_len = 0;
  165. while (request_len < sizeof(request)) {
  166. int ssl_ret =
  167. SSL_read(ssl, request + request_len, sizeof(request) - request_len);
  168. if (ssl_ret <= 0) {
  169. int ssl_err = SSL_get_error(ssl, ssl_ret);
  170. PrintSSLError(stderr, "Error while reading", ssl_err, ssl_ret);
  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("-debug") != 0) {
  277. SSL_CTX_set_info_callback(ctx.get(), InfoCallback);
  278. }
  279. if (args_map.count("-require-any-client-cert") != 0) {
  280. SSL_CTX_set_verify(
  281. ctx.get(), SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  282. SSL_CTX_set_cert_verify_callback(
  283. ctx.get(), [](X509_STORE_CTX *store, void *arg) -> int { return 1; },
  284. nullptr);
  285. }
  286. Listener listener;
  287. if (!listener.Init(args_map["-accept"])) {
  288. return false;
  289. }
  290. bool result = true;
  291. do {
  292. int sock = -1;
  293. if (!listener.Accept(&sock)) {
  294. return false;
  295. }
  296. BIO *bio = BIO_new_socket(sock, BIO_CLOSE);
  297. bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
  298. SSL_set_bio(ssl.get(), bio, bio);
  299. if (args_map.count("-jdk11-workaround") != 0) {
  300. SSL_set_jdk11_workaround(ssl.get(), 1);
  301. }
  302. int ret = SSL_accept(ssl.get());
  303. if (ret != 1) {
  304. int ssl_err = SSL_get_error(ssl.get(), ret);
  305. PrintSSLError(stderr, "Error while connecting", ssl_err, ret);
  306. result = false;
  307. continue;
  308. }
  309. fprintf(stderr, "Connected.\n");
  310. bssl::UniquePtr<BIO> bio_stderr(BIO_new_fp(stderr, BIO_NOCLOSE));
  311. PrintConnectionInfo(bio_stderr.get(), ssl.get());
  312. if (args_map.count("-www") != 0) {
  313. result = HandleWWW(ssl.get());
  314. } else {
  315. result = TransferData(ssl.get(), sock);
  316. }
  317. } while (args_map.count("-loop") != 0);
  318. return result;
  319. }