blob: ebecee03d004d5bcf2fdfcef6c5e01c00e491d16 [file] [log] [blame]
Dave Tapuskab8a824d2014-12-10 19:09:52 -05001/* 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
15#include <openssl/base.h>
16
David Benjamin4e78e302017-03-30 10:16:07 -050017#include <memory>
18
Dave Tapuskab8a824d2014-12-10 19:09:52 -050019#include <openssl/err.h>
David Benjaminc890ae52021-06-06 13:32:29 -040020#include <openssl/hpke.h>
Martin Kreichgauerce1f62c2016-11-29 14:04:13 -080021#include <openssl/rand.h>
Dave Tapuskab8a824d2014-12-10 19:09:52 -050022#include <openssl/ssl.h>
23
24#include "internal.h"
25#include "transport_common.h"
26
27
28static const struct argument kArguments[] = {
29 {
Steven Valdez87c0bb22016-12-07 10:31:16 -050030 "-accept", kRequiredArgument,
31 "The port of the server to bind on; eg 45102",
Dave Tapuskab8a824d2014-12-10 19:09:52 -050032 },
33 {
Steven Valdez87c0bb22016-12-07 10:31:16 -050034 "-cipher", kOptionalArgument,
35 "An OpenSSL-style cipher suite string that configures the offered "
36 "ciphers",
Dave Tapuskab8a824d2014-12-10 19:09:52 -050037 },
38 {
Piotr Sikorad0757062017-04-14 02:59:34 -070039 "-curves", kOptionalArgument,
40 "An OpenSSL-style ECDH curves list that configures the offered curves",
41 },
42 {
Steven Valdez87c0bb22016-12-07 10:31:16 -050043 "-max-version", kOptionalArgument,
44 "The maximum acceptable protocol version",
David Benjamin225e5ad2016-07-16 14:51:58 +020045 },
46 {
Steven Valdez87c0bb22016-12-07 10:31:16 -050047 "-min-version", kOptionalArgument,
48 "The minimum acceptable protocol version",
David Benjamin225e5ad2016-07-16 14:51:58 +020049 },
50 {
Steven Valdez87c0bb22016-12-07 10:31:16 -050051 "-key", kOptionalArgument,
David Benjamincb3af3e2017-04-09 09:52:47 -040052 "PEM-encoded file containing the private key. A self-signed "
53 "certificate is generated at runtime if this argument is not provided.",
54 },
55 {
56 "-cert", kOptionalArgument,
57 "PEM-encoded file containing the leaf certificate and optional "
58 "certificate chain. This is taken from the -key argument if this "
59 "argument is not provided.",
Dave Tapuskab8a824d2014-12-10 19:09:52 -050060 },
61 {
Steven Valdez87c0bb22016-12-07 10:31:16 -050062 "-ocsp-response", kOptionalArgument, "OCSP response file to send",
Paul Lietaraeeff2c2015-08-12 11:47:11 +010063 },
64 {
David Benjaminc890ae52021-06-06 13:32:29 -040065 "-ech-key",
Daniel McArdle00e434d2021-02-18 11:47:18 -050066 kOptionalArgument,
67 "File containing the private key corresponding to the ECHConfig.",
68 },
69 {
David Benjaminc890ae52021-06-06 13:32:29 -040070 "-ech-config",
Daniel McArdle00e434d2021-02-18 11:47:18 -050071 kOptionalArgument,
72 "File containing one ECHConfig.",
73 },
74 {
Steven Valdez87c0bb22016-12-07 10:31:16 -050075 "-loop", kBooleanArgument,
76 "The server will continue accepting new sequential connections.",
77 },
78 {
Steven Valdez2d850622017-01-11 11:34:52 -050079 "-early-data", kBooleanArgument, "Allow early data",
80 },
81 {
Peter Wu40b24c82017-09-15 15:18:03 +010082 "-www", kBooleanArgument,
83 "The server will print connection information in response to a "
84 "HTTP GET request.",
85 },
86 {
David Benjaminf60bcfb2017-08-18 15:23:44 -040087 "-debug", kBooleanArgument,
88 "Print debug information about the handshake",
89 },
90 {
David Benjamin5b90eb92017-11-04 22:57:54 -040091 "-require-any-client-cert", kBooleanArgument,
92 "The server will require a client certificate.",
93 },
94 {
David Benjamin6965d252018-11-19 15:49:56 -060095 "-jdk11-workaround", kBooleanArgument,
96 "Enable the JDK 11 workaround",
97 },
98 {
Steven Valdez87c0bb22016-12-07 10:31:16 -050099 "", kOptionalArgument, "",
Dave Tapuskab8a824d2014-12-10 19:09:52 -0500100 },
101};
102
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100103static bool LoadOCSPResponse(SSL_CTX *ctx, const char *filename) {
David Benjamin4e78e302017-03-30 10:16:07 -0500104 ScopedFILE f(fopen(filename, "rb"));
105 std::vector<uint8_t> data;
106 if (f == nullptr ||
107 !ReadAll(&data, f.get())) {
108 fprintf(stderr, "Error reading %s.\n", filename);
109 return false;
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100110 }
111
David Benjamin4e78e302017-03-30 10:16:07 -0500112 if (!SSL_CTX_set_ocsp_response(ctx, data.data(), data.size())) {
113 return false;
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100114 }
115
David Benjamin4e78e302017-03-30 10:16:07 -0500116 return true;
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100117}
118
Martin Kreichgauerce1f62c2016-11-29 14:04:13 -0800119static bssl::UniquePtr<EVP_PKEY> MakeKeyPairForSelfSignedCert() {
120 bssl::UniquePtr<EC_KEY> ec_key(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
121 if (!ec_key || !EC_KEY_generate_key(ec_key.get())) {
122 fprintf(stderr, "Failed to generate key pair.\n");
123 return nullptr;
124 }
125 bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
126 if (!evp_pkey || !EVP_PKEY_assign_EC_KEY(evp_pkey.get(), ec_key.release())) {
127 fprintf(stderr, "Failed to assign key pair.\n");
128 return nullptr;
129 }
130 return evp_pkey;
131}
132
133static bssl::UniquePtr<X509> MakeSelfSignedCert(EVP_PKEY *evp_pkey,
134 const int valid_days) {
David Benjamin08970b32022-02-22 15:14:17 -0500135 uint64_t serial;
Martin Kreichgauerce1f62c2016-11-29 14:04:13 -0800136 bssl::UniquePtr<X509> x509(X509_new());
David Benjamin08970b32022-02-22 15:14:17 -0500137 if (!x509 || //
138 !X509_set_version(x509.get(), X509_VERSION_3) ||
139 !RAND_bytes(reinterpret_cast<uint8_t *>(&serial), sizeof(serial)) ||
140 !ASN1_INTEGER_set_uint64(X509_get_serialNumber(x509.get()), serial) ||
141 !X509_gmtime_adj(X509_get_notBefore(x509.get()), 0) ||
142 !X509_gmtime_adj(X509_get_notAfter(x509.get()),
143 60 * 60 * 24 * valid_days)) {
144 return nullptr;
145 }
Martin Kreichgauerce1f62c2016-11-29 14:04:13 -0800146
David Benjamin08970b32022-02-22 15:14:17 -0500147 X509_NAME *subject = X509_get_subject_name(x509.get());
148 if (!X509_NAME_add_entry_by_txt(subject, "C", MBSTRING_ASC,
149 reinterpret_cast<const uint8_t *>("US"), -1,
150 -1, 0) ||
151 !X509_NAME_add_entry_by_txt(
152 subject, "O", MBSTRING_ASC,
153 reinterpret_cast<const uint8_t *>("BoringSSL"), -1, -1, 0) ||
154 !X509_set_issuer_name(x509.get(), subject)) {
155 return nullptr;
156 }
157
158 // macOS requires an explicit EKU extension.
159 bssl::UniquePtr<STACK_OF(ASN1_OBJECT)> ekus(sk_ASN1_OBJECT_new_null());
160 if (!ekus ||
161 !sk_ASN1_OBJECT_push(ekus.get(), OBJ_nid2obj(NID_server_auth)) ||
162 !X509_add1_ext_i2d(x509.get(), NID_ext_key_usage, ekus.get(), /*crit=*/1,
163 /*flags=*/0)) {
164 return nullptr;
165 }
Martin Kreichgauerce1f62c2016-11-29 14:04:13 -0800166
167 if (!X509_set_pubkey(x509.get(), evp_pkey)) {
168 fprintf(stderr, "Failed to set public key.\n");
169 return nullptr;
170 }
171 if (!X509_sign(x509.get(), evp_pkey, EVP_sha256())) {
172 fprintf(stderr, "Failed to sign certificate.\n");
173 return nullptr;
174 }
175 return x509;
176}
177
David Benjaminf60bcfb2017-08-18 15:23:44 -0400178static void InfoCallback(const SSL *ssl, int type, int value) {
179 switch (type) {
180 case SSL_CB_HANDSHAKE_START:
181 fprintf(stderr, "Handshake started.\n");
182 break;
183 case SSL_CB_HANDSHAKE_DONE:
184 fprintf(stderr, "Handshake done.\n");
185 break;
186 case SSL_CB_ACCEPT_LOOP:
187 fprintf(stderr, "Handshake progress: %s\n", SSL_state_string_long(ssl));
188 break;
189 }
190}
191
Peter Wu368cc3b2017-09-13 19:02:51 +0100192static FILE *g_keylog_file = nullptr;
193
194static void KeyLogCallback(const SSL *ssl, const char *line) {
195 fprintf(g_keylog_file, "%s\n", line);
196 fflush(g_keylog_file);
197}
198
Peter Wu40b24c82017-09-15 15:18:03 +0100199static bool HandleWWW(SSL *ssl) {
200 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem()));
201 if (!bio) {
202 fprintf(stderr, "Cannot create BIO for response\n");
203 return false;
204 }
205
206 BIO_puts(bio.get(), "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n");
207 PrintConnectionInfo(bio.get(), ssl);
208
209 char request[4];
210 size_t request_len = 0;
211 while (request_len < sizeof(request)) {
212 int ssl_ret =
213 SSL_read(ssl, request + request_len, sizeof(request) - request_len);
214 if (ssl_ret <= 0) {
215 int ssl_err = SSL_get_error(ssl, ssl_ret);
David Benjamin3c37d0a2018-05-05 00:42:23 -0400216 PrintSSLError(stderr, "Error while reading", ssl_err, ssl_ret);
Peter Wu40b24c82017-09-15 15:18:03 +0100217 return false;
218 }
219 request_len += static_cast<size_t>(ssl_ret);
220 }
221
222 // Assume simple HTTP request, print status.
223 if (memcmp(request, "GET ", 4) == 0) {
224 const uint8_t *response;
225 size_t response_len;
226 if (BIO_mem_contents(bio.get(), &response, &response_len)) {
227 SSL_write(ssl, response, response_len);
228 }
229 }
230 return true;
231}
232
Dave Tapuskab8a824d2014-12-10 19:09:52 -0500233bool Server(const std::vector<std::string> &args) {
Brian Smith33970e62015-01-27 22:32:08 -0800234 if (!InitSocketLibrary()) {
235 return false;
236 }
237
Dave Tapuskab8a824d2014-12-10 19:09:52 -0500238 std::map<std::string, std::string> args_map;
239
240 if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
241 PrintUsage(kArguments);
242 return false;
243 }
244
David Benjamin0cce8632016-10-20 15:13:26 -0400245 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
Dave Tapuskab8a824d2014-12-10 19:09:52 -0500246
Peter Wu368cc3b2017-09-13 19:02:51 +0100247 const char *keylog_file = getenv("SSLKEYLOGFILE");
248 if (keylog_file) {
249 g_keylog_file = fopen(keylog_file, "a");
250 if (g_keylog_file == nullptr) {
251 perror("fopen");
252 return false;
253 }
254 SSL_CTX_set_keylog_callback(ctx.get(), KeyLogCallback);
255 }
256
Dave Tapuskab8a824d2014-12-10 19:09:52 -0500257 // Server authentication is required.
Dave Tapuskab8a824d2014-12-10 19:09:52 -0500258 if (args_map.count("-key") != 0) {
David Benjamincb3af3e2017-04-09 09:52:47 -0400259 std::string key = args_map["-key"];
260 if (!SSL_CTX_use_PrivateKey_file(ctx.get(), key.c_str(),
261 SSL_FILETYPE_PEM)) {
262 fprintf(stderr, "Failed to load private key: %s\n", key.c_str());
Martin Kreichgauerce1f62c2016-11-29 14:04:13 -0800263 return false;
264 }
David Benjamincb3af3e2017-04-09 09:52:47 -0400265 const std::string &cert =
266 args_map.count("-cert") != 0 ? args_map["-cert"] : key;
267 if (!SSL_CTX_use_certificate_chain_file(ctx.get(), cert.c_str())) {
268 fprintf(stderr, "Failed to load cert chain: %s\n", cert.c_str());
Martin Kreichgauerce1f62c2016-11-29 14:04:13 -0800269 return false;
270 }
271 } else {
272 bssl::UniquePtr<EVP_PKEY> evp_pkey = MakeKeyPairForSelfSignedCert();
273 if (!evp_pkey) {
274 return false;
275 }
276 bssl::UniquePtr<X509> cert =
277 MakeSelfSignedCert(evp_pkey.get(), 365 /* valid_days */);
278 if (!cert) {
279 return false;
280 }
281 if (!SSL_CTX_use_PrivateKey(ctx.get(), evp_pkey.get())) {
282 fprintf(stderr, "Failed to set private key.\n");
283 return false;
284 }
285 if (!SSL_CTX_use_certificate(ctx.get(), cert.get())) {
286 fprintf(stderr, "Failed to set certificate.\n");
287 return false;
288 }
Dave Tapuskab8a824d2014-12-10 19:09:52 -0500289 }
290
David Benjaminc890ae52021-06-06 13:32:29 -0400291 if (args_map.count("-ech-key") + args_map.count("-ech-config") == 1) {
Daniel McArdle00e434d2021-02-18 11:47:18 -0500292 fprintf(stderr,
David Benjaminc890ae52021-06-06 13:32:29 -0400293 "-ech-config and -ech-key must be specified together.\n");
Daniel McArdle00e434d2021-02-18 11:47:18 -0500294 return false;
295 }
296
David Benjaminc890ae52021-06-06 13:32:29 -0400297 if (args_map.count("-ech-key") != 0) {
Daniel McArdle00e434d2021-02-18 11:47:18 -0500298 // Load the ECH private key.
David Benjaminc890ae52021-06-06 13:32:29 -0400299 std::string ech_key_path = args_map["-ech-key"];
300 ScopedFILE ech_key_file(fopen(ech_key_path.c_str(), "rb"));
301 std::vector<uint8_t> ech_key;
302 if (ech_key_file == nullptr ||
303 !ReadAll(&ech_key, ech_key_file.get())) {
304 fprintf(stderr, "Error reading %s\n", ech_key_path.c_str());
Daniel McArdle00e434d2021-02-18 11:47:18 -0500305 return false;
306 }
307
308 // Load the ECHConfig.
David Benjaminc890ae52021-06-06 13:32:29 -0400309 std::string ech_config_path = args_map["-ech-config"];
310 ScopedFILE ech_config_file(fopen(ech_config_path.c_str(), "rb"));
311 std::vector<uint8_t> ech_config;
312 if (ech_config_file == nullptr ||
313 !ReadAll(&ech_config, ech_config_file.get())) {
314 fprintf(stderr, "Error reading %s\n", ech_config_path.c_str());
Daniel McArdle00e434d2021-02-18 11:47:18 -0500315 return false;
316 }
317
David Benjaminc3b373b2021-06-06 13:04:26 -0400318 bssl::UniquePtr<SSL_ECH_KEYS> keys(SSL_ECH_KEYS_new());
David Benjaminc890ae52021-06-06 13:32:29 -0400319 bssl::ScopedEVP_HPKE_KEY key;
David Benjaminc3b373b2021-06-06 13:04:26 -0400320 if (!keys ||
David Benjaminc890ae52021-06-06 13:32:29 -0400321 !EVP_HPKE_KEY_init(key.get(), EVP_hpke_x25519_hkdf_sha256(),
322 ech_key.data(), ech_key.size()) ||
David Benjaminc3b373b2021-06-06 13:04:26 -0400323 !SSL_ECH_KEYS_add(keys.get(),
David Benjaminc890ae52021-06-06 13:32:29 -0400324 /*is_retry_config=*/1, ech_config.data(),
325 ech_config.size(), key.get()) ||
David Benjaminc3b373b2021-06-06 13:04:26 -0400326 !SSL_CTX_set1_ech_keys(ctx.get(), keys.get())) {
Daniel McArdle00e434d2021-02-18 11:47:18 -0500327 fprintf(stderr, "Error setting server's ECHConfig and private key\n");
328 return false;
329 }
330 }
331
Dave Tapuskab8a824d2014-12-10 19:09:52 -0500332 if (args_map.count("-cipher") != 0 &&
Matthew Braithwaitea57dcfb2017-02-17 22:08:23 -0800333 !SSL_CTX_set_strict_cipher_list(ctx.get(), args_map["-cipher"].c_str())) {
Dave Tapuskab8a824d2014-12-10 19:09:52 -0500334 fprintf(stderr, "Failed setting cipher list\n");
335 return false;
336 }
337
Piotr Sikorad0757062017-04-14 02:59:34 -0700338 if (args_map.count("-curves") != 0 &&
339 !SSL_CTX_set1_curves_list(ctx.get(), args_map["-curves"].c_str())) {
340 fprintf(stderr, "Failed setting curves list\n");
341 return false;
342 }
343
Adam Langley040bc492017-02-09 15:30:52 -0800344 uint16_t max_version = TLS1_3_VERSION;
345 if (args_map.count("-max-version") != 0 &&
346 !VersionFromString(&max_version, args_map["-max-version"])) {
347 fprintf(stderr, "Unknown protocol version: '%s'\n",
348 args_map["-max-version"].c_str());
349 return false;
350 }
351
352 if (!SSL_CTX_set_max_proto_version(ctx.get(), max_version)) {
353 return false;
David Benjamin225e5ad2016-07-16 14:51:58 +0200354 }
355
356 if (args_map.count("-min-version") != 0) {
357 uint16_t version;
358 if (!VersionFromString(&version, args_map["-min-version"])) {
359 fprintf(stderr, "Unknown protocol version: '%s'\n",
360 args_map["-min-version"].c_str());
361 return false;
362 }
David Benjamin0cce8632016-10-20 15:13:26 -0400363 if (!SSL_CTX_set_min_proto_version(ctx.get(), version)) {
David Benjamin2dc02042016-09-19 19:57:37 -0400364 return false;
365 }
David Benjamin225e5ad2016-07-16 14:51:58 +0200366 }
367
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100368 if (args_map.count("-ocsp-response") != 0 &&
David Benjamin0cce8632016-10-20 15:13:26 -0400369 !LoadOCSPResponse(ctx.get(), args_map["-ocsp-response"].c_str())) {
Paul Lietaraeeff2c2015-08-12 11:47:11 +0100370 fprintf(stderr, "Failed to load OCSP response: %s\n", args_map["-ocsp-response"].c_str());
371 return false;
372 }
373
Steven Valdez2d850622017-01-11 11:34:52 -0500374 if (args_map.count("-early-data") != 0) {
375 SSL_CTX_set_early_data_enabled(ctx.get(), 1);
376 }
377
David Benjaminf60bcfb2017-08-18 15:23:44 -0400378 if (args_map.count("-debug") != 0) {
379 SSL_CTX_set_info_callback(ctx.get(), InfoCallback);
380 }
381
David Benjamin5b90eb92017-11-04 22:57:54 -0400382 if (args_map.count("-require-any-client-cert") != 0) {
383 SSL_CTX_set_verify(
384 ctx.get(), SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
385 SSL_CTX_set_cert_verify_callback(
386 ctx.get(), [](X509_STORE_CTX *store, void *arg) -> int { return 1; },
387 nullptr);
388 }
389
David Benjamin2b0444e2017-06-27 17:29:27 -0400390 Listener listener;
391 if (!listener.Init(args_map["-accept"])) {
392 return false;
393 }
394
Steven Valdez87c0bb22016-12-07 10:31:16 -0500395 bool result = true;
396 do {
397 int sock = -1;
David Benjamin2b0444e2017-06-27 17:29:27 -0400398 if (!listener.Accept(&sock)) {
Steven Valdez87c0bb22016-12-07 10:31:16 -0500399 return false;
400 }
Dave Tapuskab8a824d2014-12-10 19:09:52 -0500401
Steven Valdez87c0bb22016-12-07 10:31:16 -0500402 BIO *bio = BIO_new_socket(sock, BIO_CLOSE);
403 bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
404 SSL_set_bio(ssl.get(), bio, bio);
Dave Tapuskab8a824d2014-12-10 19:09:52 -0500405
David Benjamin6965d252018-11-19 15:49:56 -0600406 if (args_map.count("-jdk11-workaround") != 0) {
407 SSL_set_jdk11_workaround(ssl.get(), 1);
408 }
409
Steven Valdez87c0bb22016-12-07 10:31:16 -0500410 int ret = SSL_accept(ssl.get());
411 if (ret != 1) {
412 int ssl_err = SSL_get_error(ssl.get(), ret);
David Benjamin3c37d0a2018-05-05 00:42:23 -0400413 PrintSSLError(stderr, "Error while connecting", ssl_err, ret);
David Benjamin1ddd6e52017-04-14 19:27:48 -0400414 result = false;
415 continue;
Steven Valdez87c0bb22016-12-07 10:31:16 -0500416 }
Dave Tapuskab8a824d2014-12-10 19:09:52 -0500417
Steven Valdez87c0bb22016-12-07 10:31:16 -0500418 fprintf(stderr, "Connected.\n");
Peter Wu5663b632017-09-15 15:09:03 +0100419 bssl::UniquePtr<BIO> bio_stderr(BIO_new_fp(stderr, BIO_NOCLOSE));
420 PrintConnectionInfo(bio_stderr.get(), ssl.get());
Dave Tapuskab8a824d2014-12-10 19:09:52 -0500421
Peter Wu40b24c82017-09-15 15:18:03 +0100422 if (args_map.count("-www") != 0) {
423 result = HandleWWW(ssl.get());
424 } else {
425 result = TransferData(ssl.get(), sock);
426 }
David Benjamin1ddd6e52017-04-14 19:27:48 -0400427 } while (args_map.count("-loop") != 0);
Steven Valdez87c0bb22016-12-07 10:31:16 -0500428
429 return result;
Dave Tapuskab8a824d2014-12-10 19:09:52 -0500430}