server.cc 13 KB

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