1 /*
2 * nghttp2 - HTTP/2 C Library
3 *
4 * Copyright (c) 2012 Tatsuhiro Tsujikawa
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining
7 * a copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sublicense, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 */
25 #include "shrpx_tls.h"
26
27 #ifdef HAVE_SYS_SOCKET_H
28 # include <sys/socket.h>
29 #endif // HAVE_SYS_SOCKET_H
30 #ifdef HAVE_NETDB_H
31 # include <netdb.h>
32 #endif // HAVE_NETDB_H
33 #include <netinet/tcp.h>
34 #include <pthread.h>
35 #include <sys/types.h>
36
37 #include <vector>
38 #include <string>
39 #include <iomanip>
40
41 #include <iostream>
42
43 #include "ssl_compat.h"
44
45 #include <openssl/crypto.h>
46 #include <openssl/x509.h>
47 #include <openssl/x509v3.h>
48 #include <openssl/rand.h>
49 #include <openssl/dh.h>
50 #ifndef OPENSSL_NO_OCSP
51 # include <openssl/ocsp.h>
52 #endif // OPENSSL_NO_OCSP
53 #if OPENSSL_3_0_0_API
54 # include <openssl/params.h>
55 # include <openssl/core_names.h>
56 # include <openssl/decoder.h>
57 #endif // OPENSSL_3_0_0_API
58 #ifdef OPENSSL_IS_BORINGSSL
59 # include <openssl/hmac.h>
60 #endif // OPENSSL_IS_BORINGSSL
61
62 #include <nghttp2/nghttp2.h>
63
64 #ifdef ENABLE_HTTP3
65 # include <ngtcp2/ngtcp2.h>
66 # include <ngtcp2/ngtcp2_crypto.h>
67 # ifdef HAVE_LIBNGTCP2_CRYPTO_OPENSSL
68 # include <ngtcp2/ngtcp2_crypto_openssl.h>
69 # endif // HAVE_LIBNGTCP2_CRYPTO_OPENSSL
70 # ifdef HAVE_LIBNGTCP2_CRYPTO_BORINGSSL
71 # include <ngtcp2/ngtcp2_crypto_boringssl.h>
72 # endif // HAVE_LIBNGTCP2_CRYPTO_BORINGSSL
73 #endif // ENABLE_HTTP3
74
75 #include "shrpx_log.h"
76 #include "shrpx_client_handler.h"
77 #include "shrpx_config.h"
78 #include "shrpx_worker.h"
79 #include "shrpx_downstream_connection_pool.h"
80 #include "shrpx_http2_session.h"
81 #include "shrpx_memcached_request.h"
82 #include "shrpx_memcached_dispatcher.h"
83 #include "shrpx_connection_handler.h"
84 #ifdef ENABLE_HTTP3
85 # include "shrpx_http3_upstream.h"
86 #endif // ENABLE_HTTP3
87 #include "util.h"
88 #include "tls.h"
89 #include "template.h"
90 #include "timegm.h"
91
92 using namespace nghttp2;
93
94 namespace shrpx {
95
96 namespace tls {
97
98 #if !OPENSSL_1_1_API
99 namespace {
ASN1_STRING_get0_data(ASN1_STRING * x)100 const unsigned char *ASN1_STRING_get0_data(ASN1_STRING *x) {
101 return ASN1_STRING_data(x);
102 }
103 } // namespace
104 #endif // !OPENSSL_1_1_API
105
106 #ifndef OPENSSL_NO_NEXTPROTONEG
107 namespace {
next_proto_cb(SSL * s,const unsigned char ** data,unsigned int * len,void * arg)108 int next_proto_cb(SSL *s, const unsigned char **data, unsigned int *len,
109 void *arg) {
110 auto &prefs = get_config()->tls.alpn_prefs;
111 *data = prefs.data();
112 *len = prefs.size();
113 return SSL_TLSEXT_ERR_OK;
114 }
115 } // namespace
116 #endif // !OPENSSL_NO_NEXTPROTONEG
117
118 namespace {
verify_callback(int preverify_ok,X509_STORE_CTX * ctx)119 int verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
120 if (!preverify_ok) {
121 int err = X509_STORE_CTX_get_error(ctx);
122 int depth = X509_STORE_CTX_get_error_depth(ctx);
123 if (err == X509_V_ERR_CERT_HAS_EXPIRED && depth == 0 &&
124 get_config()->tls.client_verify.tolerate_expired) {
125 LOG(INFO) << "The client certificate has expired, but is accepted by "
126 "configuration";
127 return 1;
128 }
129 LOG(ERROR) << "client certificate verify error:num=" << err << ":"
130 << X509_verify_cert_error_string(err) << ":depth=" << depth;
131 }
132 return preverify_ok;
133 }
134 } // namespace
135
set_alpn_prefs(std::vector<unsigned char> & out,const std::vector<StringRef> & protos)136 int set_alpn_prefs(std::vector<unsigned char> &out,
137 const std::vector<StringRef> &protos) {
138 size_t len = 0;
139
140 for (const auto &proto : protos) {
141 if (proto.size() > 255) {
142 LOG(FATAL) << "Too long ALPN identifier: " << proto.size();
143 return -1;
144 }
145
146 len += 1 + proto.size();
147 }
148
149 if (len > (1 << 16) - 1) {
150 LOG(FATAL) << "Too long ALPN identifier list: " << len;
151 return -1;
152 }
153
154 out.resize(len);
155 auto ptr = out.data();
156
157 for (const auto &proto : protos) {
158 *ptr++ = proto.size();
159 ptr = std::copy(std::begin(proto), std::end(proto), ptr);
160 }
161
162 return 0;
163 }
164
165 namespace {
ssl_pem_passwd_cb(char * buf,int size,int rwflag,void * user_data)166 int ssl_pem_passwd_cb(char *buf, int size, int rwflag, void *user_data) {
167 auto config = static_cast<Config *>(user_data);
168 auto len = static_cast<int>(config->tls.private_key_passwd.size());
169 if (size < len + 1) {
170 LOG(ERROR) << "ssl_pem_passwd_cb: buf is too small " << size;
171 return 0;
172 }
173 // Copy string including last '\0'.
174 memcpy(buf, config->tls.private_key_passwd.c_str(), len + 1);
175 return len;
176 }
177 } // namespace
178
179 namespace {
180 // *al is set to SSL_AD_UNRECOGNIZED_NAME by openssl, so we don't have
181 // to set it explicitly.
servername_callback(SSL * ssl,int * al,void * arg)182 int servername_callback(SSL *ssl, int *al, void *arg) {
183 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
184 auto handler = static_cast<ClientHandler *>(conn->data);
185 auto worker = handler->get_worker();
186
187 auto rawhost = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
188 if (rawhost == nullptr) {
189 return SSL_TLSEXT_ERR_NOACK;
190 }
191
192 auto len = strlen(rawhost);
193 // NI_MAXHOST includes terminal NULL.
194 if (len == 0 || len + 1 > NI_MAXHOST) {
195 return SSL_TLSEXT_ERR_NOACK;
196 }
197
198 std::array<uint8_t, NI_MAXHOST> buf;
199
200 auto end_buf = std::copy_n(rawhost, len, std::begin(buf));
201
202 util::inp_strlower(std::begin(buf), end_buf);
203
204 auto hostname = StringRef{std::begin(buf), end_buf};
205
206 #ifdef ENABLE_HTTP3
207 auto cert_tree = conn->proto == Proto::HTTP3
208 ? worker->get_quic_cert_lookup_tree()
209 : worker->get_cert_lookup_tree();
210 #else // !ENABLE_HTTP3
211 auto cert_tree = worker->get_cert_lookup_tree();
212 #endif // !ENABLE_HTTP3
213
214 auto idx = cert_tree->lookup(hostname);
215 if (idx == -1) {
216 return SSL_TLSEXT_ERR_NOACK;
217 }
218
219 handler->set_tls_sni(hostname);
220
221 auto conn_handler = worker->get_connection_handler();
222
223 #ifdef ENABLE_HTTP3
224 const auto &ssl_ctx_list = conn->proto == Proto::HTTP3
225 ? conn_handler->get_quic_indexed_ssl_ctx(idx)
226 : conn_handler->get_indexed_ssl_ctx(idx);
227 #else // !ENABLE_HTTP3
228 const auto &ssl_ctx_list = conn_handler->get_indexed_ssl_ctx(idx);
229 #endif // !ENABLE_HTTP3
230
231 assert(!ssl_ctx_list.empty());
232
233 #if !defined(OPENSSL_IS_BORINGSSL) && !LIBRESSL_IN_USE && \
234 OPENSSL_VERSION_NUMBER >= 0x10002000L
235 auto num_sigalgs =
236 SSL_get_sigalgs(ssl, 0, nullptr, nullptr, nullptr, nullptr, nullptr);
237
238 for (idx = 0; idx < num_sigalgs; ++idx) {
239 int signhash;
240
241 SSL_get_sigalgs(ssl, idx, nullptr, nullptr, &signhash, nullptr, nullptr);
242 switch (signhash) {
243 case NID_ecdsa_with_SHA256:
244 case NID_ecdsa_with_SHA384:
245 case NID_ecdsa_with_SHA512:
246 break;
247 default:
248 continue;
249 }
250
251 break;
252 }
253
254 if (idx == num_sigalgs) {
255 SSL_set_SSL_CTX(ssl, ssl_ctx_list[0]);
256
257 return SSL_TLSEXT_ERR_OK;
258 }
259
260 auto num_shared_curves = SSL_get_shared_curve(ssl, -1);
261
262 for (auto i = 0; i < num_shared_curves; ++i) {
263 auto shared_curve = SSL_get_shared_curve(ssl, i);
264 # if OPENSSL_3_0_0_API
265 // It looks like only short name is defined in OpenSSL. No idea
266 // which one to use because it is unknown that which one
267 // EVP_PKEY_get_utf8_string_param("group") returns.
268 auto shared_curve_name = OBJ_nid2sn(shared_curve);
269 if (shared_curve_name == nullptr) {
270 continue;
271 }
272 # endif // OPENSSL_3_0_0_API
273
274 for (auto ssl_ctx : ssl_ctx_list) {
275 auto cert = SSL_CTX_get0_certificate(ssl_ctx);
276
277 # if OPENSSL_1_1_API
278 auto pubkey = X509_get0_pubkey(cert);
279 # else // !OPENSSL_1_1_API
280 auto pubkey = X509_get_pubkey(cert);
281 # endif // !OPENSSL_1_1_API
282
283 if (EVP_PKEY_base_id(pubkey) != EVP_PKEY_EC) {
284 continue;
285 }
286
287 # if OPENSSL_3_0_0_API
288 std::array<char, 64> curve_name;
289 if (!EVP_PKEY_get_utf8_string_param(pubkey, "group", curve_name.data(),
290 curve_name.size(), nullptr)) {
291 continue;
292 }
293
294 if (strcmp(shared_curve_name, curve_name.data()) == 0) {
295 SSL_set_SSL_CTX(ssl, ssl_ctx);
296 return SSL_TLSEXT_ERR_OK;
297 }
298 # else // !OPENSSL_3_0_0_API
299 # if OPENSSL_1_1_API
300 auto eckey = EVP_PKEY_get0_EC_KEY(pubkey);
301 # else // !OPENSSL_1_1_API
302 auto eckey = EVP_PKEY_get1_EC_KEY(pubkey);
303 # endif // !OPENSSL_1_1_API
304
305 if (eckey == nullptr) {
306 continue;
307 }
308
309 auto ecgroup = EC_KEY_get0_group(eckey);
310 auto cert_curve = EC_GROUP_get_curve_name(ecgroup);
311
312 # if !OPENSSL_1_1_API
313 EC_KEY_free(eckey);
314 EVP_PKEY_free(pubkey);
315 # endif // !OPENSSL_1_1_API
316
317 if (shared_curve == cert_curve) {
318 SSL_set_SSL_CTX(ssl, ssl_ctx);
319 return SSL_TLSEXT_ERR_OK;
320 }
321 # endif // !OPENSSL_3_0_0_API
322 }
323 }
324 #endif // !defined(OPENSSL_IS_BORINGSSL) && !LIBRESSL_IN_USE &&
325 // OPENSSL_VERSION_NUMBER >= 0x10002000L
326
327 SSL_set_SSL_CTX(ssl, ssl_ctx_list[0]);
328
329 return SSL_TLSEXT_ERR_OK;
330 }
331 } // namespace
332
333 #ifndef OPENSSL_IS_BORINGSSL
334 namespace {
335 std::shared_ptr<std::vector<uint8_t>>
get_ocsp_data(TLSContextData * tls_ctx_data)336 get_ocsp_data(TLSContextData *tls_ctx_data) {
337 # ifdef HAVE_ATOMIC_STD_SHARED_PTR
338 return std::atomic_load_explicit(&tls_ctx_data->ocsp_data,
339 std::memory_order_acquire);
340 # else // !HAVE_ATOMIC_STD_SHARED_PTR
341 std::lock_guard<std::mutex> g(tls_ctx_data->mu);
342 return tls_ctx_data->ocsp_data;
343 # endif // !HAVE_ATOMIC_STD_SHARED_PTR
344 }
345 } // namespace
346
347 namespace {
ocsp_resp_cb(SSL * ssl,void * arg)348 int ocsp_resp_cb(SSL *ssl, void *arg) {
349 auto ssl_ctx = SSL_get_SSL_CTX(ssl);
350 auto tls_ctx_data =
351 static_cast<TLSContextData *>(SSL_CTX_get_app_data(ssl_ctx));
352
353 auto data = get_ocsp_data(tls_ctx_data);
354
355 if (!data) {
356 return SSL_TLSEXT_ERR_OK;
357 }
358
359 auto buf =
360 static_cast<uint8_t *>(CRYPTO_malloc(data->size(), __FILE__, __LINE__));
361
362 if (!buf) {
363 return SSL_TLSEXT_ERR_OK;
364 }
365
366 std::copy(std::begin(*data), std::end(*data), buf);
367
368 SSL_set_tlsext_status_ocsp_resp(ssl, buf, data->size());
369
370 return SSL_TLSEXT_ERR_OK;
371 }
372 } // namespace
373 #endif // OPENSSL_IS_BORINGSSL
374
375 constexpr auto MEMCACHED_SESSION_CACHE_KEY_PREFIX =
376 StringRef::from_lit("nghttpx:tls-session-cache:");
377
378 namespace {
tls_session_client_new_cb(SSL * ssl,SSL_SESSION * session)379 int tls_session_client_new_cb(SSL *ssl, SSL_SESSION *session) {
380 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
381 if (conn->tls.client_session_cache == nullptr) {
382 return 0;
383 }
384
385 try_cache_tls_session(conn->tls.client_session_cache, session,
386 ev_now(conn->loop));
387
388 return 0;
389 }
390 } // namespace
391
392 namespace {
tls_session_new_cb(SSL * ssl,SSL_SESSION * session)393 int tls_session_new_cb(SSL *ssl, SSL_SESSION *session) {
394 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
395 auto handler = static_cast<ClientHandler *>(conn->data);
396 auto worker = handler->get_worker();
397 auto dispatcher = worker->get_session_cache_memcached_dispatcher();
398 auto &balloc = handler->get_block_allocator();
399
400 #ifdef TLS1_3_VERSION
401 if (SSL_version(ssl) == TLS1_3_VERSION) {
402 return 0;
403 }
404 #endif // TLS1_3_VERSION
405
406 const unsigned char *id;
407 unsigned int idlen;
408
409 id = SSL_SESSION_get_id(session, &idlen);
410
411 if (LOG_ENABLED(INFO)) {
412 LOG(INFO) << "Memcached: cache session, id=" << util::format_hex(id, idlen);
413 }
414
415 auto req = std::make_unique<MemcachedRequest>();
416 req->op = MemcachedOp::ADD;
417 req->key = MEMCACHED_SESSION_CACHE_KEY_PREFIX.str();
418 req->key +=
419 util::format_hex(balloc, StringRef{id, static_cast<size_t>(idlen)});
420
421 auto sessionlen = i2d_SSL_SESSION(session, nullptr);
422 req->value.resize(sessionlen);
423 auto buf = &req->value[0];
424 i2d_SSL_SESSION(session, &buf);
425 req->expiry = 12_h;
426 req->cb = [](MemcachedRequest *req, MemcachedResult res) {
427 if (LOG_ENABLED(INFO)) {
428 LOG(INFO) << "Memcached: session cache done. key=" << req->key
429 << ", status_code=" << static_cast<uint16_t>(res.status_code)
430 << ", value="
431 << std::string(std::begin(res.value), std::end(res.value));
432 }
433 if (res.status_code != MemcachedStatusCode::NO_ERROR) {
434 LOG(WARN) << "Memcached: failed to cache session key=" << req->key
435 << ", status_code=" << static_cast<uint16_t>(res.status_code)
436 << ", value="
437 << std::string(std::begin(res.value), std::end(res.value));
438 }
439 };
440 assert(!req->canceled);
441
442 dispatcher->add_request(std::move(req));
443
444 return 0;
445 }
446 } // namespace
447
448 namespace {
tls_session_get_cb(SSL * ssl,const unsigned char * id,int idlen,int * copy)449 SSL_SESSION *tls_session_get_cb(SSL *ssl,
450 #if OPENSSL_1_1_API || LIBRESSL_2_7_API
451 const unsigned char *id,
452 #else // !(OPENSSL_1_1_API || LIBRESSL_2_7_API)
453 unsigned char *id,
454 #endif // !(OPENSSL_1_1_API || LIBRESSL_2_7_API)
455 int idlen, int *copy) {
456 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
457 auto handler = static_cast<ClientHandler *>(conn->data);
458 auto worker = handler->get_worker();
459 auto dispatcher = worker->get_session_cache_memcached_dispatcher();
460 auto &balloc = handler->get_block_allocator();
461
462 if (idlen == 0) {
463 return nullptr;
464 }
465
466 if (conn->tls.cached_session) {
467 if (LOG_ENABLED(INFO)) {
468 LOG(INFO) << "Memcached: found cached session, id="
469 << util::format_hex(id, idlen);
470 }
471
472 // This is required, without this, memory leak occurs.
473 *copy = 0;
474
475 auto session = conn->tls.cached_session;
476 conn->tls.cached_session = nullptr;
477 return session;
478 }
479
480 if (LOG_ENABLED(INFO)) {
481 LOG(INFO) << "Memcached: get cached session, id="
482 << util::format_hex(id, idlen);
483 }
484
485 auto req = std::make_unique<MemcachedRequest>();
486 req->op = MemcachedOp::GET;
487 req->key = MEMCACHED_SESSION_CACHE_KEY_PREFIX.str();
488 req->key +=
489 util::format_hex(balloc, StringRef{id, static_cast<size_t>(idlen)});
490 req->cb = [conn](MemcachedRequest *, MemcachedResult res) {
491 if (LOG_ENABLED(INFO)) {
492 LOG(INFO) << "Memcached: returned status code "
493 << static_cast<uint16_t>(res.status_code);
494 }
495
496 // We might stop reading, so start it again
497 conn->rlimit.startw();
498 ev_timer_again(conn->loop, &conn->rt);
499
500 conn->wlimit.startw();
501 ev_timer_again(conn->loop, &conn->wt);
502
503 conn->tls.cached_session_lookup_req = nullptr;
504 if (res.status_code != MemcachedStatusCode::NO_ERROR) {
505 conn->tls.handshake_state = TLSHandshakeState::CANCEL_SESSION_CACHE;
506 return;
507 }
508
509 const uint8_t *p = res.value.data();
510
511 auto session = d2i_SSL_SESSION(nullptr, &p, res.value.size());
512 if (!session) {
513 if (LOG_ENABLED(INFO)) {
514 LOG(INFO) << "cannot materialize session";
515 }
516 conn->tls.handshake_state = TLSHandshakeState::CANCEL_SESSION_CACHE;
517 return;
518 }
519
520 conn->tls.cached_session = session;
521 conn->tls.handshake_state = TLSHandshakeState::GOT_SESSION_CACHE;
522 };
523
524 conn->tls.handshake_state = TLSHandshakeState::WAIT_FOR_SESSION_CACHE;
525 conn->tls.cached_session_lookup_req = req.get();
526
527 dispatcher->add_request(std::move(req));
528
529 return nullptr;
530 }
531 } // namespace
532
533 namespace {
ticket_key_cb(SSL * ssl,unsigned char * key_name,unsigned char * iv,EVP_CIPHER_CTX * ctx,EVP_MAC_CTX * hctx,int enc)534 int ticket_key_cb(SSL *ssl, unsigned char *key_name, unsigned char *iv,
535 EVP_CIPHER_CTX *ctx,
536 #if OPENSSL_3_0_0_API
537 EVP_MAC_CTX *hctx,
538 #else // !OPENSSL_3_0_0_API
539 HMAC_CTX *hctx,
540 #endif // !OPENSSL_3_0_0_API
541 int enc) {
542 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
543 auto handler = static_cast<ClientHandler *>(conn->data);
544 auto worker = handler->get_worker();
545 auto ticket_keys = worker->get_ticket_keys();
546
547 if (!ticket_keys) {
548 // No ticket keys available.
549 return -1;
550 }
551
552 auto &keys = ticket_keys->keys;
553 assert(!keys.empty());
554
555 if (enc) {
556 if (RAND_bytes(iv, EVP_MAX_IV_LENGTH) == 0) {
557 if (LOG_ENABLED(INFO)) {
558 CLOG(INFO, handler) << "session ticket key: RAND_bytes failed";
559 }
560 return -1;
561 }
562
563 auto &key = keys[0];
564
565 if (LOG_ENABLED(INFO)) {
566 CLOG(INFO, handler) << "encrypt session ticket key: "
567 << util::format_hex(key.data.name);
568 }
569
570 std::copy(std::begin(key.data.name), std::end(key.data.name), key_name);
571
572 EVP_EncryptInit_ex(ctx, get_config()->tls.ticket.cipher, nullptr,
573 key.data.enc_key.data(), iv);
574 #if OPENSSL_3_0_0_API
575 std::array<OSSL_PARAM, 3> params{
576 OSSL_PARAM_construct_octet_string(
577 OSSL_MAC_PARAM_KEY, key.data.hmac_key.data(), key.hmac_keylen),
578 OSSL_PARAM_construct_utf8_string(
579 OSSL_MAC_PARAM_DIGEST,
580 const_cast<char *>(EVP_MD_get0_name(key.hmac)), 0),
581 OSSL_PARAM_construct_end(),
582 };
583 if (!EVP_MAC_CTX_set_params(hctx, params.data())) {
584 if (LOG_ENABLED(INFO)) {
585 CLOG(INFO, handler) << "EVP_MAC_CTX_set_params failed";
586 }
587 return -1;
588 }
589 #else // !OPENSSL_3_0_0_API
590 HMAC_Init_ex(hctx, key.data.hmac_key.data(), key.hmac_keylen, key.hmac,
591 nullptr);
592 #endif // !OPENSSL_3_0_0_API
593 return 1;
594 }
595
596 size_t i;
597 for (i = 0; i < keys.size(); ++i) {
598 auto &key = keys[i];
599 if (std::equal(std::begin(key.data.name), std::end(key.data.name),
600 key_name)) {
601 break;
602 }
603 }
604
605 if (i == keys.size()) {
606 if (LOG_ENABLED(INFO)) {
607 CLOG(INFO, handler) << "session ticket key "
608 << util::format_hex(key_name, 16) << " not found";
609 }
610 return 0;
611 }
612
613 if (LOG_ENABLED(INFO)) {
614 CLOG(INFO, handler) << "decrypt session ticket key: "
615 << util::format_hex(key_name, 16);
616 }
617
618 auto &key = keys[i];
619 #if OPENSSL_3_0_0_API
620 std::array<OSSL_PARAM, 3> params{
621 OSSL_PARAM_construct_octet_string(
622 OSSL_MAC_PARAM_KEY, key.data.hmac_key.data(), key.hmac_keylen),
623 OSSL_PARAM_construct_utf8_string(
624 OSSL_MAC_PARAM_DIGEST, const_cast<char *>(EVP_MD_get0_name(key.hmac)),
625 0),
626 OSSL_PARAM_construct_end(),
627 };
628 if (!EVP_MAC_CTX_set_params(hctx, params.data())) {
629 if (LOG_ENABLED(INFO)) {
630 CLOG(INFO, handler) << "EVP_MAC_CTX_set_params failed";
631 }
632 return -1;
633 }
634 #else // !OPENSSL_3_0_0_API
635 HMAC_Init_ex(hctx, key.data.hmac_key.data(), key.hmac_keylen, key.hmac,
636 nullptr);
637 #endif // !OPENSSL_3_0_0_API
638 EVP_DecryptInit_ex(ctx, key.cipher, nullptr, key.data.enc_key.data(), iv);
639
640 #ifdef TLS1_3_VERSION
641 // If ticket_key_cb is not set, OpenSSL always renew ticket for
642 // TLSv1.3.
643 if (SSL_version(ssl) == TLS1_3_VERSION) {
644 return 2;
645 }
646 #endif // TLS1_3_VERSION
647
648 return i == 0 ? 1 : 2;
649 }
650 } // namespace
651
652 namespace {
info_callback(const SSL * ssl,int where,int ret)653 void info_callback(const SSL *ssl, int where, int ret) {
654 #ifdef TLS1_3_VERSION
655 // TLSv1.3 has no renegotiation.
656 if (SSL_version(ssl) == TLS1_3_VERSION) {
657 return;
658 }
659 #endif // TLS1_3_VERSION
660
661 // To mitigate possible DOS attack using lots of renegotiations, we
662 // disable renegotiation. Since OpenSSL does not provide an easy way
663 // to disable it, we check that renegotiation is started in this
664 // callback.
665 if (where & SSL_CB_HANDSHAKE_START) {
666 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
667 if (conn && conn->tls.initial_handshake_done) {
668 auto handler = static_cast<ClientHandler *>(conn->data);
669 if (LOG_ENABLED(INFO)) {
670 CLOG(INFO, handler) << "TLS renegotiation started";
671 }
672 handler->start_immediate_shutdown();
673 }
674 }
675 }
676 } // namespace
677
678 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
679 namespace {
alpn_select_proto_cb(SSL * ssl,const unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)680 int alpn_select_proto_cb(SSL *ssl, const unsigned char **out,
681 unsigned char *outlen, const unsigned char *in,
682 unsigned int inlen, void *arg) {
683 // We assume that get_config()->npn_list contains ALPN protocol
684 // identifier sorted by preference order. So we just break when we
685 // found the first overlap.
686 for (const auto &target_proto_id : get_config()->tls.npn_list) {
687 for (auto p = in, end = in + inlen; p < end;) {
688 auto proto_id = p + 1;
689 auto proto_len = *p;
690
691 if (proto_id + proto_len <= end &&
692 util::streq(target_proto_id, StringRef{proto_id, proto_len})) {
693
694 *out = reinterpret_cast<const unsigned char *>(proto_id);
695 *outlen = proto_len;
696
697 return SSL_TLSEXT_ERR_OK;
698 }
699
700 p += 1 + proto_len;
701 }
702 }
703
704 return SSL_TLSEXT_ERR_NOACK;
705 }
706 } // namespace
707 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
708
709 #ifdef ENABLE_HTTP3
710 # if OPENSSL_VERSION_NUMBER >= 0x10002000L
711 namespace {
quic_alpn_select_proto_cb(SSL * ssl,const unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)712 int quic_alpn_select_proto_cb(SSL *ssl, const unsigned char **out,
713 unsigned char *outlen, const unsigned char *in,
714 unsigned int inlen, void *arg) {
715 constexpr StringRef alpnlist[] = {
716 StringRef::from_lit("h3"),
717 StringRef::from_lit("h3-29"),
718 };
719
720 for (auto &alpn : alpnlist) {
721 for (auto p = in, end = in + inlen; p < end;) {
722 auto proto_id = p + 1;
723 auto proto_len = *p;
724
725 if (alpn.size() == proto_len &&
726 memcmp(alpn.byte(), proto_id, alpn.size()) == 0) {
727 *out = proto_id;
728 *outlen = proto_len;
729
730 return SSL_TLSEXT_ERR_OK;
731 }
732
733 p += 1 + proto_len;
734 }
735 }
736
737 return SSL_TLSEXT_ERR_ALERT_FATAL;
738 }
739 } // namespace
740 # endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
741 #endif // ENABLE_HTTP3
742
743 #if !LIBRESSL_IN_USE && OPENSSL_VERSION_NUMBER >= 0x10002000L && \
744 !defined(OPENSSL_IS_BORINGSSL)
745
746 # ifndef TLSEXT_TYPE_signed_certificate_timestamp
747 # define TLSEXT_TYPE_signed_certificate_timestamp 18
748 # endif // !TLSEXT_TYPE_signed_certificate_timestamp
749
750 namespace {
sct_add_cb(SSL * ssl,unsigned int ext_type,unsigned int context,const unsigned char ** out,size_t * outlen,X509 * x,size_t chainidx,int * al,void * add_arg)751 int sct_add_cb(SSL *ssl, unsigned int ext_type, unsigned int context,
752 const unsigned char **out, size_t *outlen, X509 *x,
753 size_t chainidx, int *al, void *add_arg) {
754 assert(ext_type == TLSEXT_TYPE_signed_certificate_timestamp);
755
756 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
757 if (!conn->tls.sct_requested) {
758 return 0;
759 }
760
761 if (LOG_ENABLED(INFO)) {
762 LOG(INFO) << "sct_add_cb is called, chainidx=" << chainidx << ", x=" << x
763 << ", context=" << log::hex << context;
764 }
765
766 // We only have SCTs for leaf certificate.
767 if (chainidx != 0) {
768 return 0;
769 }
770
771 auto ssl_ctx = SSL_get_SSL_CTX(ssl);
772 auto tls_ctx_data =
773 static_cast<TLSContextData *>(SSL_CTX_get_app_data(ssl_ctx));
774
775 *out = tls_ctx_data->sct_data.data();
776 *outlen = tls_ctx_data->sct_data.size();
777
778 return 1;
779 }
780 } // namespace
781
782 namespace {
sct_free_cb(SSL * ssl,unsigned int ext_type,unsigned int context,const unsigned char * out,void * add_arg)783 void sct_free_cb(SSL *ssl, unsigned int ext_type, unsigned int context,
784 const unsigned char *out, void *add_arg) {
785 assert(ext_type == TLSEXT_TYPE_signed_certificate_timestamp);
786 }
787 } // namespace
788
789 namespace {
sct_parse_cb(SSL * ssl,unsigned int ext_type,unsigned int context,const unsigned char * in,size_t inlen,X509 * x,size_t chainidx,int * al,void * parse_arg)790 int sct_parse_cb(SSL *ssl, unsigned int ext_type, unsigned int context,
791 const unsigned char *in, size_t inlen, X509 *x,
792 size_t chainidx, int *al, void *parse_arg) {
793 assert(ext_type == TLSEXT_TYPE_signed_certificate_timestamp);
794 // client SHOULD send 0 length extension_data, but it is still
795 // SHOULD, and not MUST.
796
797 // For TLSv1.3 Certificate message, sct_add_cb is called even if
798 // client has not sent signed_certificate_timestamp extension in its
799 // ClientHello. Explicitly remember that client has included it
800 // here.
801 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
802 conn->tls.sct_requested = true;
803
804 return 1;
805 }
806 } // namespace
807
808 # if !OPENSSL_1_1_1_API
809
810 namespace {
legacy_sct_add_cb(SSL * ssl,unsigned int ext_type,const unsigned char ** out,size_t * outlen,int * al,void * add_arg)811 int legacy_sct_add_cb(SSL *ssl, unsigned int ext_type,
812 const unsigned char **out, size_t *outlen, int *al,
813 void *add_arg) {
814 return sct_add_cb(ssl, ext_type, 0, out, outlen, nullptr, 0, al, add_arg);
815 }
816 } // namespace
817
818 namespace {
legacy_sct_free_cb(SSL * ssl,unsigned int ext_type,const unsigned char * out,void * add_arg)819 void legacy_sct_free_cb(SSL *ssl, unsigned int ext_type,
820 const unsigned char *out, void *add_arg) {
821 sct_free_cb(ssl, ext_type, 0, out, add_arg);
822 }
823 } // namespace
824
825 namespace {
legacy_sct_parse_cb(SSL * ssl,unsigned int ext_type,const unsigned char * in,size_t inlen,int * al,void * parse_arg)826 int legacy_sct_parse_cb(SSL *ssl, unsigned int ext_type,
827 const unsigned char *in, size_t inlen, int *al,
828 void *parse_arg) {
829 return sct_parse_cb(ssl, ext_type, 0, in, inlen, nullptr, 0, al, parse_arg);
830 }
831 } // namespace
832
833 # endif // !OPENSSL_1_1_1_API
834 #endif // !LIBRESSL_IN_USE && OPENSSL_VERSION_NUMBER >= 0x10002000L &&
835 // !defined(OPENSSL_IS_BORINGSSL)
836
837 #ifndef OPENSSL_NO_PSK
838 namespace {
psk_server_cb(SSL * ssl,const char * identity,unsigned char * psk,unsigned int max_psk_len)839 unsigned int psk_server_cb(SSL *ssl, const char *identity, unsigned char *psk,
840 unsigned int max_psk_len) {
841 auto config = get_config();
842 auto &tlsconf = config->tls;
843
844 auto it = tlsconf.psk_secrets.find(StringRef{identity});
845 if (it == std::end(tlsconf.psk_secrets)) {
846 return 0;
847 }
848
849 auto &secret = (*it).second;
850 if (secret.size() > max_psk_len) {
851 LOG(ERROR) << "The size of PSK secret is " << secret.size()
852 << ", but the acceptable maximum size is" << max_psk_len;
853 return 0;
854 }
855
856 std::copy(std::begin(secret), std::end(secret), psk);
857
858 return static_cast<unsigned int>(secret.size());
859 }
860 } // namespace
861 #endif // !OPENSSL_NO_PSK
862
863 #ifndef OPENSSL_NO_PSK
864 namespace {
psk_client_cb(SSL * ssl,const char * hint,char * identity_out,unsigned int max_identity_len,unsigned char * psk,unsigned int max_psk_len)865 unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity_out,
866 unsigned int max_identity_len, unsigned char *psk,
867 unsigned int max_psk_len) {
868 auto config = get_config();
869 auto &tlsconf = config->tls;
870
871 auto &identity = tlsconf.client.psk.identity;
872 auto &secret = tlsconf.client.psk.secret;
873
874 if (identity.empty()) {
875 return 0;
876 }
877
878 if (identity.size() + 1 > max_identity_len) {
879 LOG(ERROR) << "The size of PSK identity is " << identity.size()
880 << ", but the acceptable maximum size is " << max_identity_len;
881 return 0;
882 }
883
884 if (secret.size() > max_psk_len) {
885 LOG(ERROR) << "The size of PSK secret is " << secret.size()
886 << ", but the acceptable maximum size is " << max_psk_len;
887 return 0;
888 }
889
890 *std::copy(std::begin(identity), std::end(identity), identity_out) = '\0';
891 std::copy(std::begin(secret), std::end(secret), psk);
892
893 return static_cast<unsigned int>(secret.size());
894 }
895 } // namespace
896 #endif // !OPENSSL_NO_PSK
897
898 struct TLSProtocol {
899 StringRef name;
900 long int mask;
901 };
902
903 constexpr TLSProtocol TLS_PROTOS[] = {
904 TLSProtocol{StringRef::from_lit("TLSv1.2"), SSL_OP_NO_TLSv1_2},
905 TLSProtocol{StringRef::from_lit("TLSv1.1"), SSL_OP_NO_TLSv1_1},
906 TLSProtocol{StringRef::from_lit("TLSv1.0"), SSL_OP_NO_TLSv1}};
907
create_tls_proto_mask(const std::vector<StringRef> & tls_proto_list)908 long int create_tls_proto_mask(const std::vector<StringRef> &tls_proto_list) {
909 long int res = 0;
910
911 for (auto &supported : TLS_PROTOS) {
912 auto ok = false;
913 for (auto &name : tls_proto_list) {
914 if (util::strieq(supported.name, name)) {
915 ok = true;
916 break;
917 }
918 }
919 if (!ok) {
920 res |= supported.mask;
921 }
922 }
923 return res;
924 }
925
create_ssl_context(const char * private_key_file,const char * cert_file,const std::vector<uint8_t> & sct_data,neverbleed_t * nb)926 SSL_CTX *create_ssl_context(const char *private_key_file, const char *cert_file,
927 const std::vector<uint8_t> &sct_data
928 #ifdef HAVE_NEVERBLEED
929 ,
930 neverbleed_t *nb
931 #endif // HAVE_NEVERBLEED
932 ) {
933 auto ssl_ctx = SSL_CTX_new(TLS_server_method());
934 if (!ssl_ctx) {
935 LOG(FATAL) << ERR_error_string(ERR_get_error(), nullptr);
936 DIE();
937 }
938
939 auto ssl_opts = (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
940 SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION |
941 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
942 SSL_OP_SINGLE_ECDH_USE | SSL_OP_SINGLE_DH_USE |
943 SSL_OP_CIPHER_SERVER_PREFERENCE
944 #if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
945 // The reason for disabling built-in anti-replay in
946 // OpenSSL is that it only works if client gets back
947 // to the same server. The freshness check
948 // described in
949 // https://tools.ietf.org/html/rfc8446#section-8.3
950 // is still performed.
951 | SSL_OP_NO_ANTI_REPLAY
952 #endif // OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
953 ;
954
955 auto config = mod_config();
956 auto &tlsconf = config->tls;
957
958 #ifdef SSL_OP_ENABLE_KTLS
959 if (tlsconf.ktls) {
960 ssl_opts |= SSL_OP_ENABLE_KTLS;
961 }
962 #endif // SSL_OP_ENABLE_KTLS
963
964 SSL_CTX_set_options(ssl_ctx, ssl_opts | tlsconf.tls_proto_mask);
965
966 if (nghttp2::tls::ssl_ctx_set_proto_versions(
967 ssl_ctx, tlsconf.min_proto_version, tlsconf.max_proto_version) != 0) {
968 LOG(FATAL) << "Could not set TLS protocol version";
969 DIE();
970 }
971
972 const unsigned char sid_ctx[] = "shrpx";
973 SSL_CTX_set_session_id_context(ssl_ctx, sid_ctx, sizeof(sid_ctx) - 1);
974 SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_SERVER);
975
976 if (!tlsconf.session_cache.memcached.host.empty()) {
977 SSL_CTX_sess_set_new_cb(ssl_ctx, tls_session_new_cb);
978 SSL_CTX_sess_set_get_cb(ssl_ctx, tls_session_get_cb);
979 }
980
981 SSL_CTX_set_timeout(ssl_ctx, tlsconf.session_timeout.count());
982
983 if (SSL_CTX_set_cipher_list(ssl_ctx, tlsconf.ciphers.c_str()) == 0) {
984 LOG(FATAL) << "SSL_CTX_set_cipher_list " << tlsconf.ciphers
985 << " failed: " << ERR_error_string(ERR_get_error(), nullptr);
986 DIE();
987 }
988
989 #if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
990 if (SSL_CTX_set_ciphersuites(ssl_ctx, tlsconf.tls13_ciphers.c_str()) == 0) {
991 LOG(FATAL) << "SSL_CTX_set_ciphersuites " << tlsconf.tls13_ciphers
992 << " failed: " << ERR_error_string(ERR_get_error(), nullptr);
993 DIE();
994 }
995 #endif // OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
996
997 #ifndef OPENSSL_NO_EC
998 # if !LIBRESSL_LEGACY_API && OPENSSL_VERSION_NUMBER >= 0x10002000L
999 if (SSL_CTX_set1_curves_list(ssl_ctx, tlsconf.ecdh_curves.c_str()) != 1) {
1000 LOG(FATAL) << "SSL_CTX_set1_curves_list " << tlsconf.ecdh_curves
1001 << " failed";
1002 DIE();
1003 }
1004 # if !defined(OPENSSL_IS_BORINGSSL) && !OPENSSL_1_1_API
1005 // It looks like we need this function call for OpenSSL 1.0.2. This
1006 // function was deprecated in OpenSSL 1.1.0 and BoringSSL.
1007 SSL_CTX_set_ecdh_auto(ssl_ctx, 1);
1008 # endif // !defined(OPENSSL_IS_BORINGSSL) && !OPENSSL_1_1_API
1009 # else // LIBRESSL_LEGACY_API || OPENSSL_VERSION_NUBMER < 0x10002000L
1010 // Use P-256, which is sufficiently secure at the time of this
1011 // writing.
1012 auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
1013 if (ecdh == nullptr) {
1014 LOG(FATAL) << "EC_KEY_new_by_curv_name failed: "
1015 << ERR_error_string(ERR_get_error(), nullptr);
1016 DIE();
1017 }
1018 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecdh);
1019 EC_KEY_free(ecdh);
1020 # endif // LIBRESSL_LEGACY_API || OPENSSL_VERSION_NUBMER < 0x10002000L
1021 #endif // OPENSSL_NO_EC
1022
1023 if (!tlsconf.dh_param_file.empty()) {
1024 // Read DH parameters from file
1025 auto bio = BIO_new_file(tlsconf.dh_param_file.c_str(), "rb");
1026 if (bio == nullptr) {
1027 LOG(FATAL) << "BIO_new_file() failed: "
1028 << ERR_error_string(ERR_get_error(), nullptr);
1029 DIE();
1030 }
1031 #if OPENSSL_3_0_0_API
1032 EVP_PKEY *dh = nullptr;
1033 auto dctx = OSSL_DECODER_CTX_new_for_pkey(
1034 &dh, "PEM", nullptr, "DH", OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
1035 nullptr, nullptr);
1036
1037 if (!OSSL_DECODER_from_bio(dctx, bio)) {
1038 LOG(FATAL) << "OSSL_DECODER_from_bio() failed: "
1039 << ERR_error_string(ERR_get_error(), nullptr);
1040 DIE();
1041 }
1042
1043 if (SSL_CTX_set0_tmp_dh_pkey(ssl_ctx, dh) != 1) {
1044 LOG(FATAL) << "SSL_CTX_set0_tmp_dh_pkey failed: "
1045 << ERR_error_string(ERR_get_error(), nullptr);
1046 DIE();
1047 }
1048 #else // !OPENSSL_3_0_0_API
1049 auto dh = PEM_read_bio_DHparams(bio, nullptr, nullptr, nullptr);
1050 if (dh == nullptr) {
1051 LOG(FATAL) << "PEM_read_bio_DHparams() failed: "
1052 << ERR_error_string(ERR_get_error(), nullptr);
1053 DIE();
1054 }
1055 SSL_CTX_set_tmp_dh(ssl_ctx, dh);
1056 DH_free(dh);
1057 #endif // !OPENSSL_3_0_0_API
1058 BIO_free(bio);
1059 }
1060
1061 SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS);
1062
1063 if (SSL_CTX_set_default_verify_paths(ssl_ctx) != 1) {
1064 LOG(WARN) << "Could not load system trusted ca certificates: "
1065 << ERR_error_string(ERR_get_error(), nullptr);
1066 }
1067
1068 if (!tlsconf.cacert.empty()) {
1069 if (SSL_CTX_load_verify_locations(ssl_ctx, tlsconf.cacert.c_str(),
1070 nullptr) != 1) {
1071 LOG(FATAL) << "Could not load trusted ca certificates from "
1072 << tlsconf.cacert << ": "
1073 << ERR_error_string(ERR_get_error(), nullptr);
1074 DIE();
1075 }
1076 }
1077
1078 if (!tlsconf.private_key_passwd.empty()) {
1079 SSL_CTX_set_default_passwd_cb(ssl_ctx, ssl_pem_passwd_cb);
1080 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, config);
1081 }
1082
1083 #ifndef HAVE_NEVERBLEED
1084 if (SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key_file,
1085 SSL_FILETYPE_PEM) != 1) {
1086 LOG(FATAL) << "SSL_CTX_use_PrivateKey_file failed: "
1087 << ERR_error_string(ERR_get_error(), nullptr);
1088 DIE();
1089 }
1090 #else // HAVE_NEVERBLEED
1091 std::array<char, NEVERBLEED_ERRBUF_SIZE> errbuf;
1092 if (neverbleed_load_private_key_file(nb, ssl_ctx, private_key_file,
1093 errbuf.data()) != 1) {
1094 LOG(FATAL) << "neverbleed_load_private_key_file failed: " << errbuf.data();
1095 DIE();
1096 }
1097 #endif // HAVE_NEVERBLEED
1098
1099 if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_file) != 1) {
1100 LOG(FATAL) << "SSL_CTX_use_certificate_file failed: "
1101 << ERR_error_string(ERR_get_error(), nullptr);
1102 DIE();
1103 }
1104 if (SSL_CTX_check_private_key(ssl_ctx) != 1) {
1105 LOG(FATAL) << "SSL_CTX_check_private_key failed: "
1106 << ERR_error_string(ERR_get_error(), nullptr);
1107 DIE();
1108 }
1109 if (tlsconf.client_verify.enabled) {
1110 if (!tlsconf.client_verify.cacert.empty()) {
1111 if (SSL_CTX_load_verify_locations(
1112 ssl_ctx, tlsconf.client_verify.cacert.c_str(), nullptr) != 1) {
1113
1114 LOG(FATAL) << "Could not load trusted ca certificates from "
1115 << tlsconf.client_verify.cacert << ": "
1116 << ERR_error_string(ERR_get_error(), nullptr);
1117 DIE();
1118 }
1119 // It is heard that SSL_CTX_load_verify_locations() may leave
1120 // error even though it returns success. See
1121 // http://forum.nginx.org/read.php?29,242540
1122 ERR_clear_error();
1123 auto list = SSL_load_client_CA_file(tlsconf.client_verify.cacert.c_str());
1124 if (!list) {
1125 LOG(FATAL) << "Could not load ca certificates from "
1126 << tlsconf.client_verify.cacert << ": "
1127 << ERR_error_string(ERR_get_error(), nullptr);
1128 DIE();
1129 }
1130 SSL_CTX_set_client_CA_list(ssl_ctx, list);
1131 }
1132 SSL_CTX_set_verify(ssl_ctx,
1133 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE |
1134 SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1135 verify_callback);
1136 }
1137 SSL_CTX_set_tlsext_servername_callback(ssl_ctx, servername_callback);
1138 #if OPENSSL_3_0_0_API
1139 SSL_CTX_set_tlsext_ticket_key_evp_cb(ssl_ctx, ticket_key_cb);
1140 #else // !OPENSSL_3_0_0_API
1141 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx, ticket_key_cb);
1142 #endif // !OPENSSL_3_0_0_API
1143 #ifndef OPENSSL_IS_BORINGSSL
1144 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
1145 #endif // OPENSSL_IS_BORINGSSL
1146 SSL_CTX_set_info_callback(ssl_ctx, info_callback);
1147
1148 #ifdef OPENSSL_IS_BORINGSSL
1149 SSL_CTX_set_early_data_enabled(ssl_ctx, 1);
1150 #endif // OPENSSL_IS_BORINGSSL
1151
1152 // NPN advertisement
1153 #ifndef OPENSSL_NO_NEXTPROTONEG
1154 SSL_CTX_set_next_protos_advertised_cb(ssl_ctx, next_proto_cb, nullptr);
1155 #endif // !OPENSSL_NO_NEXTPROTONEG
1156 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
1157 // ALPN selection callback
1158 SSL_CTX_set_alpn_select_cb(ssl_ctx, alpn_select_proto_cb, nullptr);
1159 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
1160
1161 auto tls_ctx_data = new TLSContextData();
1162 tls_ctx_data->cert_file = cert_file;
1163 tls_ctx_data->sct_data = sct_data;
1164
1165 SSL_CTX_set_app_data(ssl_ctx, tls_ctx_data);
1166
1167 #if !LIBRESSL_IN_USE && OPENSSL_VERSION_NUMBER >= 0x10002000L && \
1168 !defined(OPENSSL_IS_BORINGSSL)
1169 // SSL_extension_supported(TLSEXT_TYPE_signed_certificate_timestamp)
1170 // returns 1, which means OpenSSL internally handles it. But
1171 // OpenSSL handles signed_certificate_timestamp extension specially,
1172 // and it lets custom handler to process the extension.
1173 if (!sct_data.empty()) {
1174 # if OPENSSL_1_1_1_API
1175 // It is not entirely clear to me that SSL_EXT_CLIENT_HELLO is
1176 // required here. sct_parse_cb is called without
1177 // SSL_EXT_CLIENT_HELLO being set. But the passed context value
1178 // is SSL_EXT_CLIENT_HELLO.
1179 if (SSL_CTX_add_custom_ext(
1180 ssl_ctx, TLSEXT_TYPE_signed_certificate_timestamp,
1181 SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO |
1182 SSL_EXT_TLS1_3_CERTIFICATE | SSL_EXT_IGNORE_ON_RESUMPTION,
1183 sct_add_cb, sct_free_cb, nullptr, sct_parse_cb, nullptr) != 1) {
1184 LOG(FATAL) << "SSL_CTX_add_custom_ext failed: "
1185 << ERR_error_string(ERR_get_error(), nullptr);
1186 DIE();
1187 }
1188 # else // !OPENSSL_1_1_1_API
1189 if (SSL_CTX_add_server_custom_ext(
1190 ssl_ctx, TLSEXT_TYPE_signed_certificate_timestamp,
1191 legacy_sct_add_cb, legacy_sct_free_cb, nullptr, legacy_sct_parse_cb,
1192 nullptr) != 1) {
1193 LOG(FATAL) << "SSL_CTX_add_server_custom_ext failed: "
1194 << ERR_error_string(ERR_get_error(), nullptr);
1195 DIE();
1196 }
1197 # endif // !OPENSSL_1_1_1_API
1198 }
1199 #elif defined(OPENSSL_IS_BORINGSSL)
1200 if (!tls_ctx_data->sct_data.empty() &&
1201 SSL_CTX_set_signed_cert_timestamp_list(
1202 ssl_ctx, tls_ctx_data->sct_data.data(),
1203 tls_ctx_data->sct_data.size()) != 1) {
1204 LOG(FATAL) << "SSL_CTX_set_signed_cert_timestamp_list failed: "
1205 << ERR_error_string(ERR_get_error(), nullptr);
1206 DIE();
1207 }
1208 #endif // defined(OPENSSL_IS_BORINGSSL)
1209
1210 #if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1211 if (SSL_CTX_set_max_early_data(ssl_ctx, tlsconf.max_early_data) != 1) {
1212 LOG(FATAL) << "SSL_CTX_set_max_early_data failed: "
1213 << ERR_error_string(ERR_get_error(), nullptr);
1214 DIE();
1215 }
1216 #endif // OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1217
1218 #ifndef OPENSSL_NO_PSK
1219 SSL_CTX_set_psk_server_callback(ssl_ctx, psk_server_cb);
1220 #endif // !LIBRESSL_NO_PSK
1221
1222 return ssl_ctx;
1223 }
1224
1225 #ifdef ENABLE_HTTP3
create_quic_ssl_context(const char * private_key_file,const char * cert_file,const std::vector<uint8_t> & sct_data,neverbleed_t * nb)1226 SSL_CTX *create_quic_ssl_context(const char *private_key_file,
1227 const char *cert_file,
1228 const std::vector<uint8_t> &sct_data
1229 # ifdef HAVE_NEVERBLEED
1230 ,
1231 neverbleed_t *nb
1232 # endif // HAVE_NEVERBLEED
1233 ) {
1234 auto ssl_ctx = SSL_CTX_new(TLS_server_method());
1235 if (!ssl_ctx) {
1236 LOG(FATAL) << ERR_error_string(ERR_get_error(), nullptr);
1237 DIE();
1238 }
1239
1240 constexpr auto ssl_opts =
1241 (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
1242 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | SSL_OP_SINGLE_ECDH_USE |
1243 SSL_OP_SINGLE_DH_USE |
1244 SSL_OP_CIPHER_SERVER_PREFERENCE
1245 # if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1246 // The reason for disabling built-in anti-replay in OpenSSL is
1247 // that it only works if client gets back to the same server.
1248 // The freshness check described in
1249 // https://tools.ietf.org/html/rfc8446#section-8.3 is still
1250 // performed.
1251 | SSL_OP_NO_ANTI_REPLAY
1252 # endif // OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1253 ;
1254
1255 auto config = mod_config();
1256 auto &tlsconf = config->tls;
1257
1258 SSL_CTX_set_options(ssl_ctx, ssl_opts);
1259
1260 # ifdef HAVE_LIBNGTCP2_CRYPTO_OPENSSL
1261 if (ngtcp2_crypto_openssl_configure_server_context(ssl_ctx) != 0) {
1262 LOG(FATAL) << "ngtcp2_crypto_openssl_configure_server_context failed";
1263 DIE();
1264 }
1265 # endif // HAVE_LIBNGTCP2_CRYPTO_OPENSSL
1266 # ifdef HAVE_LIBNGTCP2_CRYPTO_BORINGSSL
1267 if (ngtcp2_crypto_boringssl_configure_server_context(ssl_ctx) != 0) {
1268 LOG(FATAL) << "ngtcp2_crypto_boringssl_configure_server_context failed";
1269 DIE();
1270 }
1271 # endif // HAVE_LIBNGTCP2_CRYPTO_BORINGSSL
1272
1273 const unsigned char sid_ctx[] = "shrpx";
1274 SSL_CTX_set_session_id_context(ssl_ctx, sid_ctx, sizeof(sid_ctx) - 1);
1275 SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_OFF);
1276
1277 SSL_CTX_set_timeout(ssl_ctx, tlsconf.session_timeout.count());
1278
1279 if (SSL_CTX_set_cipher_list(ssl_ctx, tlsconf.ciphers.c_str()) == 0) {
1280 LOG(FATAL) << "SSL_CTX_set_cipher_list " << tlsconf.ciphers
1281 << " failed: " << ERR_error_string(ERR_get_error(), nullptr);
1282 DIE();
1283 }
1284
1285 # if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1286 if (SSL_CTX_set_ciphersuites(ssl_ctx, tlsconf.tls13_ciphers.c_str()) == 0) {
1287 LOG(FATAL) << "SSL_CTX_set_ciphersuites " << tlsconf.tls13_ciphers
1288 << " failed: " << ERR_error_string(ERR_get_error(), nullptr);
1289 DIE();
1290 }
1291 # endif // OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1292
1293 # ifndef OPENSSL_NO_EC
1294 # if !LIBRESSL_LEGACY_API && OPENSSL_VERSION_NUMBER >= 0x10002000L
1295 if (SSL_CTX_set1_curves_list(ssl_ctx, tlsconf.ecdh_curves.c_str()) != 1) {
1296 LOG(FATAL) << "SSL_CTX_set1_curves_list " << tlsconf.ecdh_curves
1297 << " failed";
1298 DIE();
1299 }
1300 # if !defined(OPENSSL_IS_BORINGSSL) && !OPENSSL_1_1_API
1301 // It looks like we need this function call for OpenSSL 1.0.2. This
1302 // function was deprecated in OpenSSL 1.1.0 and BoringSSL.
1303 SSL_CTX_set_ecdh_auto(ssl_ctx, 1);
1304 # endif // !defined(OPENSSL_IS_BORINGSSL) && !OPENSSL_1_1_API
1305 # else // LIBRESSL_LEGACY_API || OPENSSL_VERSION_NUBMER < 0x10002000L
1306 // Use P-256, which is sufficiently secure at the time of this
1307 // writing.
1308 auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
1309 if (ecdh == nullptr) {
1310 LOG(FATAL) << "EC_KEY_new_by_curv_name failed: "
1311 << ERR_error_string(ERR_get_error(), nullptr);
1312 DIE();
1313 }
1314 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecdh);
1315 EC_KEY_free(ecdh);
1316 # endif // LIBRESSL_LEGACY_API || OPENSSL_VERSION_NUBMER < 0x10002000L
1317 # endif // OPENSSL_NO_EC
1318
1319 if (!tlsconf.dh_param_file.empty()) {
1320 // Read DH parameters from file
1321 auto bio = BIO_new_file(tlsconf.dh_param_file.c_str(), "rb");
1322 if (bio == nullptr) {
1323 LOG(FATAL) << "BIO_new_file() failed: "
1324 << ERR_error_string(ERR_get_error(), nullptr);
1325 DIE();
1326 }
1327 # if OPENSSL_3_0_0_API
1328 EVP_PKEY *dh = nullptr;
1329 auto dctx = OSSL_DECODER_CTX_new_for_pkey(
1330 &dh, "PEM", nullptr, "DH", OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
1331 nullptr, nullptr);
1332
1333 if (!OSSL_DECODER_from_bio(dctx, bio)) {
1334 LOG(FATAL) << "OSSL_DECODER_from_bio() failed: "
1335 << ERR_error_string(ERR_get_error(), nullptr);
1336 DIE();
1337 }
1338
1339 if (SSL_CTX_set0_tmp_dh_pkey(ssl_ctx, dh) != 1) {
1340 LOG(FATAL) << "SSL_CTX_set0_tmp_dh_pkey failed: "
1341 << ERR_error_string(ERR_get_error(), nullptr);
1342 DIE();
1343 }
1344 # else // !OPENSSL_3_0_0_API
1345 auto dh = PEM_read_bio_DHparams(bio, nullptr, nullptr, nullptr);
1346 if (dh == nullptr) {
1347 LOG(FATAL) << "PEM_read_bio_DHparams() failed: "
1348 << ERR_error_string(ERR_get_error(), nullptr);
1349 DIE();
1350 }
1351 SSL_CTX_set_tmp_dh(ssl_ctx, dh);
1352 DH_free(dh);
1353 # endif // !OPENSSL_3_0_0_API
1354 BIO_free(bio);
1355 }
1356
1357 SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS);
1358
1359 if (SSL_CTX_set_default_verify_paths(ssl_ctx) != 1) {
1360 LOG(WARN) << "Could not load system trusted ca certificates: "
1361 << ERR_error_string(ERR_get_error(), nullptr);
1362 }
1363
1364 if (!tlsconf.cacert.empty()) {
1365 if (SSL_CTX_load_verify_locations(ssl_ctx, tlsconf.cacert.c_str(),
1366 nullptr) != 1) {
1367 LOG(FATAL) << "Could not load trusted ca certificates from "
1368 << tlsconf.cacert << ": "
1369 << ERR_error_string(ERR_get_error(), nullptr);
1370 DIE();
1371 }
1372 }
1373
1374 if (!tlsconf.private_key_passwd.empty()) {
1375 SSL_CTX_set_default_passwd_cb(ssl_ctx, ssl_pem_passwd_cb);
1376 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, config);
1377 }
1378
1379 # ifndef HAVE_NEVERBLEED
1380 if (SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key_file,
1381 SSL_FILETYPE_PEM) != 1) {
1382 LOG(FATAL) << "SSL_CTX_use_PrivateKey_file failed: "
1383 << ERR_error_string(ERR_get_error(), nullptr);
1384 DIE();
1385 }
1386 # else // HAVE_NEVERBLEED
1387 std::array<char, NEVERBLEED_ERRBUF_SIZE> errbuf;
1388 if (neverbleed_load_private_key_file(nb, ssl_ctx, private_key_file,
1389 errbuf.data()) != 1) {
1390 LOG(FATAL) << "neverbleed_load_private_key_file failed: " << errbuf.data();
1391 DIE();
1392 }
1393 # endif // HAVE_NEVERBLEED
1394
1395 if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_file) != 1) {
1396 LOG(FATAL) << "SSL_CTX_use_certificate_file failed: "
1397 << ERR_error_string(ERR_get_error(), nullptr);
1398 DIE();
1399 }
1400 if (SSL_CTX_check_private_key(ssl_ctx) != 1) {
1401 LOG(FATAL) << "SSL_CTX_check_private_key failed: "
1402 << ERR_error_string(ERR_get_error(), nullptr);
1403 DIE();
1404 }
1405 if (tlsconf.client_verify.enabled) {
1406 if (!tlsconf.client_verify.cacert.empty()) {
1407 if (SSL_CTX_load_verify_locations(
1408 ssl_ctx, tlsconf.client_verify.cacert.c_str(), nullptr) != 1) {
1409
1410 LOG(FATAL) << "Could not load trusted ca certificates from "
1411 << tlsconf.client_verify.cacert << ": "
1412 << ERR_error_string(ERR_get_error(), nullptr);
1413 DIE();
1414 }
1415 // It is heard that SSL_CTX_load_verify_locations() may leave
1416 // error even though it returns success. See
1417 // http://forum.nginx.org/read.php?29,242540
1418 ERR_clear_error();
1419 auto list = SSL_load_client_CA_file(tlsconf.client_verify.cacert.c_str());
1420 if (!list) {
1421 LOG(FATAL) << "Could not load ca certificates from "
1422 << tlsconf.client_verify.cacert << ": "
1423 << ERR_error_string(ERR_get_error(), nullptr);
1424 DIE();
1425 }
1426 SSL_CTX_set_client_CA_list(ssl_ctx, list);
1427 }
1428 SSL_CTX_set_verify(ssl_ctx,
1429 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE |
1430 SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1431 verify_callback);
1432 }
1433 SSL_CTX_set_tlsext_servername_callback(ssl_ctx, servername_callback);
1434 # if OPENSSL_3_0_0_API
1435 SSL_CTX_set_tlsext_ticket_key_evp_cb(ssl_ctx, ticket_key_cb);
1436 # else // !OPENSSL_3_0_0_API
1437 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx, ticket_key_cb);
1438 # endif // !OPENSSL_3_0_0_API
1439 # ifndef OPENSSL_IS_BORINGSSL
1440 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
1441 # endif // OPENSSL_IS_BORINGSSL
1442
1443 # if OPENSSL_VERSION_NUMBER >= 0x10002000L
1444 // ALPN selection callback
1445 SSL_CTX_set_alpn_select_cb(ssl_ctx, quic_alpn_select_proto_cb, nullptr);
1446 # endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
1447
1448 auto tls_ctx_data = new TLSContextData();
1449 tls_ctx_data->cert_file = cert_file;
1450 tls_ctx_data->sct_data = sct_data;
1451
1452 SSL_CTX_set_app_data(ssl_ctx, tls_ctx_data);
1453
1454 # if !LIBRESSL_IN_USE && OPENSSL_VERSION_NUMBER >= 0x10002000L && \
1455 !defined(OPENSSL_IS_BORINGSSL)
1456 // SSL_extension_supported(TLSEXT_TYPE_signed_certificate_timestamp)
1457 // returns 1, which means OpenSSL internally handles it. But
1458 // OpenSSL handles signed_certificate_timestamp extension specially,
1459 // and it lets custom handler to process the extension.
1460 if (!sct_data.empty()) {
1461 # if OPENSSL_1_1_1_API
1462 // It is not entirely clear to me that SSL_EXT_CLIENT_HELLO is
1463 // required here. sct_parse_cb is called without
1464 // SSL_EXT_CLIENT_HELLO being set. But the passed context value
1465 // is SSL_EXT_CLIENT_HELLO.
1466 if (SSL_CTX_add_custom_ext(
1467 ssl_ctx, TLSEXT_TYPE_signed_certificate_timestamp,
1468 SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO |
1469 SSL_EXT_TLS1_3_CERTIFICATE | SSL_EXT_IGNORE_ON_RESUMPTION,
1470 sct_add_cb, sct_free_cb, nullptr, sct_parse_cb, nullptr) != 1) {
1471 LOG(FATAL) << "SSL_CTX_add_custom_ext failed: "
1472 << ERR_error_string(ERR_get_error(), nullptr);
1473 DIE();
1474 }
1475 # else // !OPENSSL_1_1_1_API
1476 if (SSL_CTX_add_server_custom_ext(
1477 ssl_ctx, TLSEXT_TYPE_signed_certificate_timestamp,
1478 legacy_sct_add_cb, legacy_sct_free_cb, nullptr, legacy_sct_parse_cb,
1479 nullptr) != 1) {
1480 LOG(FATAL) << "SSL_CTX_add_server_custom_ext failed: "
1481 << ERR_error_string(ERR_get_error(), nullptr);
1482 DIE();
1483 }
1484 # endif // !OPENSSL_1_1_1_API
1485 }
1486 # elif defined(OPENSSL_IS_BORINGSSL)
1487 if (!tls_ctx_data->sct_data.empty() &&
1488 SSL_CTX_set_signed_cert_timestamp_list(
1489 ssl_ctx, tls_ctx_data->sct_data.data(),
1490 tls_ctx_data->sct_data.size()) != 1) {
1491 LOG(FATAL) << "SSL_CTX_set_signed_cert_timestamp_list failed: "
1492 << ERR_error_string(ERR_get_error(), nullptr);
1493 DIE();
1494 }
1495 # endif // defined(OPENSSL_IS_BORINGSSL)
1496
1497 # if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1498 auto &quicconf = config->quic;
1499
1500 if (quicconf.upstream.early_data &&
1501 SSL_CTX_set_max_early_data(ssl_ctx,
1502 std::numeric_limits<uint32_t>::max()) != 1) {
1503 LOG(FATAL) << "SSL_CTX_set_max_early_data failed: "
1504 << ERR_error_string(ERR_get_error(), nullptr);
1505 DIE();
1506 }
1507 # endif // OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1508
1509 # ifndef OPENSSL_NO_PSK
1510 SSL_CTX_set_psk_server_callback(ssl_ctx, psk_server_cb);
1511 # endif // !LIBRESSL_NO_PSK
1512
1513 return ssl_ctx;
1514 }
1515 #endif // ENABLE_HTTP3
1516
1517 namespace {
select_h2_next_proto_cb(SSL * ssl,unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)1518 int select_h2_next_proto_cb(SSL *ssl, unsigned char **out,
1519 unsigned char *outlen, const unsigned char *in,
1520 unsigned int inlen, void *arg) {
1521 if (!util::select_h2(const_cast<const unsigned char **>(out), outlen, in,
1522 inlen)) {
1523 return SSL_TLSEXT_ERR_NOACK;
1524 }
1525
1526 return SSL_TLSEXT_ERR_OK;
1527 }
1528 } // namespace
1529
1530 namespace {
select_h1_next_proto_cb(SSL * ssl,unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)1531 int select_h1_next_proto_cb(SSL *ssl, unsigned char **out,
1532 unsigned char *outlen, const unsigned char *in,
1533 unsigned int inlen, void *arg) {
1534 auto end = in + inlen;
1535 for (; in < end;) {
1536 if (util::streq(NGHTTP2_H1_1_ALPN, StringRef{in, in + (in[0] + 1)})) {
1537 *out = const_cast<unsigned char *>(in) + 1;
1538 *outlen = in[0];
1539 return SSL_TLSEXT_ERR_OK;
1540 }
1541 in += in[0] + 1;
1542 }
1543
1544 return SSL_TLSEXT_ERR_NOACK;
1545 }
1546 } // namespace
1547
1548 namespace {
select_next_proto_cb(SSL * ssl,unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)1549 int select_next_proto_cb(SSL *ssl, unsigned char **out, unsigned char *outlen,
1550 const unsigned char *in, unsigned int inlen,
1551 void *arg) {
1552 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
1553 switch (conn->proto) {
1554 case Proto::HTTP1:
1555 return select_h1_next_proto_cb(ssl, out, outlen, in, inlen, arg);
1556 case Proto::HTTP2:
1557 return select_h2_next_proto_cb(ssl, out, outlen, in, inlen, arg);
1558 default:
1559 return SSL_TLSEXT_ERR_NOACK;
1560 }
1561 }
1562 } // namespace
1563
create_ssl_client_context(neverbleed_t * nb,const StringRef & cacert,const StringRef & cert_file,const StringRef & private_key_file,int (* next_proto_select_cb)(SSL * s,unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg))1564 SSL_CTX *create_ssl_client_context(
1565 #ifdef HAVE_NEVERBLEED
1566 neverbleed_t *nb,
1567 #endif // HAVE_NEVERBLEED
1568 const StringRef &cacert, const StringRef &cert_file,
1569 const StringRef &private_key_file,
1570 int (*next_proto_select_cb)(SSL *s, unsigned char **out,
1571 unsigned char *outlen, const unsigned char *in,
1572 unsigned int inlen, void *arg)) {
1573 auto ssl_ctx = SSL_CTX_new(TLS_client_method());
1574 if (!ssl_ctx) {
1575 LOG(FATAL) << ERR_error_string(ERR_get_error(), nullptr);
1576 DIE();
1577 }
1578
1579 auto ssl_opts = (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
1580 SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION |
1581 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION;
1582
1583 auto &tlsconf = get_config()->tls;
1584
1585 #ifdef SSL_OP_ENABLE_KTLS
1586 if (tlsconf.ktls) {
1587 ssl_opts |= SSL_OP_ENABLE_KTLS;
1588 }
1589 #endif // SSL_OP_ENABLE_KTLS
1590
1591 SSL_CTX_set_options(ssl_ctx, ssl_opts | tlsconf.tls_proto_mask);
1592
1593 SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_CLIENT |
1594 SSL_SESS_CACHE_NO_INTERNAL_STORE);
1595 SSL_CTX_sess_set_new_cb(ssl_ctx, tls_session_client_new_cb);
1596
1597 if (nghttp2::tls::ssl_ctx_set_proto_versions(
1598 ssl_ctx, tlsconf.min_proto_version, tlsconf.max_proto_version) != 0) {
1599 LOG(FATAL) << "Could not set TLS protocol version";
1600 DIE();
1601 }
1602
1603 if (SSL_CTX_set_cipher_list(ssl_ctx, tlsconf.client.ciphers.c_str()) == 0) {
1604 LOG(FATAL) << "SSL_CTX_set_cipher_list " << tlsconf.client.ciphers
1605 << " failed: " << ERR_error_string(ERR_get_error(), nullptr);
1606 DIE();
1607 }
1608
1609 #if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1610 if (SSL_CTX_set_ciphersuites(ssl_ctx, tlsconf.client.tls13_ciphers.c_str()) ==
1611 0) {
1612 LOG(FATAL) << "SSL_CTX_set_ciphersuites " << tlsconf.client.tls13_ciphers
1613 << " failed: " << ERR_error_string(ERR_get_error(), nullptr);
1614 DIE();
1615 }
1616 #endif // OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1617
1618 SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS);
1619
1620 if (SSL_CTX_set_default_verify_paths(ssl_ctx) != 1) {
1621 LOG(WARN) << "Could not load system trusted ca certificates: "
1622 << ERR_error_string(ERR_get_error(), nullptr);
1623 }
1624
1625 if (!cacert.empty()) {
1626 if (SSL_CTX_load_verify_locations(ssl_ctx, cacert.c_str(), nullptr) != 1) {
1627
1628 LOG(FATAL) << "Could not load trusted ca certificates from " << cacert
1629 << ": " << ERR_error_string(ERR_get_error(), nullptr);
1630 DIE();
1631 }
1632 }
1633
1634 if (!tlsconf.insecure) {
1635 SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
1636 }
1637
1638 if (!cert_file.empty()) {
1639 if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_file.c_str()) != 1) {
1640
1641 LOG(FATAL) << "Could not load client certificate from " << cert_file
1642 << ": " << ERR_error_string(ERR_get_error(), nullptr);
1643 DIE();
1644 }
1645 }
1646
1647 if (!private_key_file.empty()) {
1648 #ifndef HAVE_NEVERBLEED
1649 if (SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key_file.c_str(),
1650 SSL_FILETYPE_PEM) != 1) {
1651 LOG(FATAL) << "Could not load client private key from "
1652 << private_key_file << ": "
1653 << ERR_error_string(ERR_get_error(), nullptr);
1654 DIE();
1655 }
1656 #else // HAVE_NEVERBLEED
1657 std::array<char, NEVERBLEED_ERRBUF_SIZE> errbuf;
1658 if (neverbleed_load_private_key_file(nb, ssl_ctx, private_key_file.c_str(),
1659 errbuf.data()) != 1) {
1660 LOG(FATAL) << "neverbleed_load_private_key_file: could not load client "
1661 "private key from "
1662 << private_key_file << ": " << errbuf.data();
1663 DIE();
1664 }
1665 #endif // HAVE_NEVERBLEED
1666 }
1667
1668 #ifndef OPENSSL_NO_PSK
1669 SSL_CTX_set_psk_client_callback(ssl_ctx, psk_client_cb);
1670 #endif // !OPENSSL_NO_PSK
1671
1672 // NPN selection callback. This is required to set SSL_CTX because
1673 // OpenSSL does not offer SSL_set_next_proto_select_cb.
1674 #ifndef OPENSSL_NO_NEXTPROTONEG
1675 SSL_CTX_set_next_proto_select_cb(ssl_ctx, next_proto_select_cb, nullptr);
1676 #endif // !OPENSSL_NO_NEXTPROTONEG
1677
1678 return ssl_ctx;
1679 }
1680
create_ssl(SSL_CTX * ssl_ctx)1681 SSL *create_ssl(SSL_CTX *ssl_ctx) {
1682 auto ssl = SSL_new(ssl_ctx);
1683 if (!ssl) {
1684 LOG(ERROR) << "SSL_new() failed: "
1685 << ERR_error_string(ERR_get_error(), nullptr);
1686 return nullptr;
1687 }
1688
1689 return ssl;
1690 }
1691
accept_connection(Worker * worker,int fd,sockaddr * addr,int addrlen,const UpstreamAddr * faddr)1692 ClientHandler *accept_connection(Worker *worker, int fd, sockaddr *addr,
1693 int addrlen, const UpstreamAddr *faddr) {
1694 std::array<char, NI_MAXHOST> host;
1695 std::array<char, NI_MAXSERV> service;
1696 int rv;
1697
1698 if (addr->sa_family == AF_UNIX) {
1699 std::copy_n("localhost", sizeof("localhost"), std::begin(host));
1700 service[0] = '\0';
1701 } else {
1702 rv = getnameinfo(addr, addrlen, host.data(), host.size(), service.data(),
1703 service.size(), NI_NUMERICHOST | NI_NUMERICSERV);
1704 if (rv != 0) {
1705 LOG(ERROR) << "getnameinfo() failed: " << gai_strerror(rv);
1706
1707 return nullptr;
1708 }
1709
1710 rv = util::make_socket_nodelay(fd);
1711 if (rv == -1) {
1712 LOG(WARN) << "Setting option TCP_NODELAY failed: errno=" << errno;
1713 }
1714 }
1715 SSL *ssl = nullptr;
1716 if (faddr->tls) {
1717 auto ssl_ctx = worker->get_sv_ssl_ctx();
1718
1719 assert(ssl_ctx);
1720
1721 ssl = create_ssl(ssl_ctx);
1722 if (!ssl) {
1723 return nullptr;
1724 }
1725 // Disable TLS session ticket if we don't have working ticket
1726 // keys.
1727 if (!worker->get_ticket_keys()) {
1728 SSL_set_options(ssl, SSL_OP_NO_TICKET);
1729 }
1730 }
1731
1732 return new ClientHandler(worker, fd, ssl, StringRef{host.data()},
1733 StringRef{service.data()}, addr->sa_family, faddr);
1734 }
1735
tls_hostname_match(const StringRef & pattern,const StringRef & hostname)1736 bool tls_hostname_match(const StringRef &pattern, const StringRef &hostname) {
1737 auto ptWildcard = std::find(std::begin(pattern), std::end(pattern), '*');
1738 if (ptWildcard == std::end(pattern)) {
1739 return util::strieq(pattern, hostname);
1740 }
1741
1742 auto ptLeftLabelEnd = std::find(std::begin(pattern), std::end(pattern), '.');
1743 auto wildcardEnabled = true;
1744 // Do case-insensitive match. At least 2 dots are required to enable
1745 // wildcard match. Also wildcard must be in the left-most label.
1746 // Don't attempt to match a presented identifier where the wildcard
1747 // character is embedded within an A-label.
1748 if (ptLeftLabelEnd == std::end(pattern) ||
1749 std::find(ptLeftLabelEnd + 1, std::end(pattern), '.') ==
1750 std::end(pattern) ||
1751 ptLeftLabelEnd < ptWildcard || util::istarts_with_l(pattern, "xn--")) {
1752 wildcardEnabled = false;
1753 }
1754
1755 if (!wildcardEnabled) {
1756 return util::strieq(pattern, hostname);
1757 }
1758
1759 auto hnLeftLabelEnd =
1760 std::find(std::begin(hostname), std::end(hostname), '.');
1761 if (hnLeftLabelEnd == std::end(hostname) ||
1762 !util::strieq(StringRef{ptLeftLabelEnd, std::end(pattern)},
1763 StringRef{hnLeftLabelEnd, std::end(hostname)})) {
1764 return false;
1765 }
1766 // Perform wildcard match. Here '*' must match at least one
1767 // character.
1768 if (hnLeftLabelEnd - std::begin(hostname) <
1769 ptLeftLabelEnd - std::begin(pattern)) {
1770 return false;
1771 }
1772 return util::istarts_with(StringRef{std::begin(hostname), hnLeftLabelEnd},
1773 StringRef{std::begin(pattern), ptWildcard}) &&
1774 util::iends_with(StringRef{std::begin(hostname), hnLeftLabelEnd},
1775 StringRef{ptWildcard + 1, ptLeftLabelEnd});
1776 }
1777
1778 namespace {
1779 // if return value is not empty, StringRef.c_str() must be freed using
1780 // OPENSSL_free().
get_common_name(X509 * cert)1781 StringRef get_common_name(X509 *cert) {
1782 auto subjectname = X509_get_subject_name(cert);
1783 if (!subjectname) {
1784 LOG(WARN) << "Could not get X509 name object from the certificate.";
1785 return StringRef{};
1786 }
1787 int lastpos = -1;
1788 for (;;) {
1789 lastpos = X509_NAME_get_index_by_NID(subjectname, NID_commonName, lastpos);
1790 if (lastpos == -1) {
1791 break;
1792 }
1793 auto entry = X509_NAME_get_entry(subjectname, lastpos);
1794
1795 unsigned char *p;
1796 auto plen = ASN1_STRING_to_UTF8(&p, X509_NAME_ENTRY_get_data(entry));
1797 if (plen < 0) {
1798 continue;
1799 }
1800 if (std::find(p, p + plen, '\0') != p + plen) {
1801 // Embedded NULL is not permitted.
1802 continue;
1803 }
1804 if (plen == 0) {
1805 LOG(WARN) << "X509 name is empty";
1806 OPENSSL_free(p);
1807 continue;
1808 }
1809
1810 return StringRef{p, static_cast<size_t>(plen)};
1811 }
1812 return StringRef{};
1813 }
1814 } // namespace
1815
1816 namespace {
verify_numeric_hostname(X509 * cert,const StringRef & hostname,const Address * addr)1817 int verify_numeric_hostname(X509 *cert, const StringRef &hostname,
1818 const Address *addr) {
1819 const void *saddr;
1820 switch (addr->su.storage.ss_family) {
1821 case AF_INET:
1822 saddr = &addr->su.in.sin_addr;
1823 break;
1824 case AF_INET6:
1825 saddr = &addr->su.in6.sin6_addr;
1826 break;
1827 default:
1828 return -1;
1829 }
1830
1831 auto altnames = static_cast<GENERAL_NAMES *>(
1832 X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
1833 if (altnames) {
1834 auto altnames_deleter = defer(GENERAL_NAMES_free, altnames);
1835 size_t n = sk_GENERAL_NAME_num(altnames);
1836 auto ip_found = false;
1837 for (size_t i = 0; i < n; ++i) {
1838 auto altname = sk_GENERAL_NAME_value(altnames, i);
1839 if (altname->type != GEN_IPADD) {
1840 continue;
1841 }
1842
1843 auto ip_addr = altname->d.iPAddress->data;
1844 if (!ip_addr) {
1845 continue;
1846 }
1847 size_t ip_addrlen = altname->d.iPAddress->length;
1848
1849 ip_found = true;
1850 if (addr->len == ip_addrlen && memcmp(saddr, ip_addr, ip_addrlen) == 0) {
1851 return 0;
1852 }
1853 }
1854
1855 if (ip_found) {
1856 return -1;
1857 }
1858 }
1859
1860 auto cn = get_common_name(cert);
1861 if (cn.empty()) {
1862 return -1;
1863 }
1864
1865 // cn is not NULL terminated
1866 auto rv = util::streq(hostname, cn);
1867 OPENSSL_free(const_cast<char *>(cn.c_str()));
1868
1869 if (rv) {
1870 return 0;
1871 }
1872
1873 return -1;
1874 }
1875 } // namespace
1876
1877 namespace {
verify_hostname(X509 * cert,const StringRef & hostname,const Address * addr)1878 int verify_hostname(X509 *cert, const StringRef &hostname,
1879 const Address *addr) {
1880 if (util::numeric_host(hostname.c_str())) {
1881 return verify_numeric_hostname(cert, hostname, addr);
1882 }
1883
1884 auto altnames = static_cast<GENERAL_NAMES *>(
1885 X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
1886 if (altnames) {
1887 auto dns_found = false;
1888 auto altnames_deleter = defer(GENERAL_NAMES_free, altnames);
1889 size_t n = sk_GENERAL_NAME_num(altnames);
1890 for (size_t i = 0; i < n; ++i) {
1891 auto altname = sk_GENERAL_NAME_value(altnames, i);
1892 if (altname->type != GEN_DNS) {
1893 continue;
1894 }
1895
1896 auto name = ASN1_STRING_get0_data(altname->d.ia5);
1897 if (!name) {
1898 continue;
1899 }
1900
1901 auto len = ASN1_STRING_length(altname->d.ia5);
1902 if (len == 0) {
1903 continue;
1904 }
1905 if (std::find(name, name + len, '\0') != name + len) {
1906 // Embedded NULL is not permitted.
1907 continue;
1908 }
1909
1910 if (name[len - 1] == '.') {
1911 --len;
1912 if (len == 0) {
1913 continue;
1914 }
1915 }
1916
1917 dns_found = true;
1918
1919 if (tls_hostname_match(StringRef{name, static_cast<size_t>(len)},
1920 hostname)) {
1921 return 0;
1922 }
1923 }
1924
1925 // RFC 6125, section 6.4.4. says that client MUST not seek a match
1926 // for CN if a dns dNSName is found.
1927 if (dns_found) {
1928 return -1;
1929 }
1930 }
1931
1932 auto cn = get_common_name(cert);
1933 if (cn.empty()) {
1934 return -1;
1935 }
1936
1937 if (cn[cn.size() - 1] == '.') {
1938 if (cn.size() == 1) {
1939 OPENSSL_free(const_cast<char *>(cn.c_str()));
1940
1941 return -1;
1942 }
1943 cn = StringRef{cn.c_str(), cn.size() - 1};
1944 }
1945
1946 auto rv = tls_hostname_match(cn, hostname);
1947 OPENSSL_free(const_cast<char *>(cn.c_str()));
1948
1949 return rv ? 0 : -1;
1950 }
1951 } // namespace
1952
check_cert(SSL * ssl,const Address * addr,const StringRef & host)1953 int check_cert(SSL *ssl, const Address *addr, const StringRef &host) {
1954 #if OPENSSL_3_0_0_API
1955 auto cert = SSL_get0_peer_certificate(ssl);
1956 #else // !OPENSSL_3_0_0_API
1957 auto cert = SSL_get_peer_certificate(ssl);
1958 #endif // !OPENSSL_3_0_0_API
1959 if (!cert) {
1960 // By the protocol definition, TLS server always sends certificate
1961 // if it has. If certificate cannot be retrieved, authentication
1962 // without certificate is used, such as PSK.
1963 return 0;
1964 }
1965 #if !OPENSSL_3_0_0_API
1966 auto cert_deleter = defer(X509_free, cert);
1967 #endif // !OPENSSL_3_0_0_API
1968
1969 if (verify_hostname(cert, host, addr) != 0) {
1970 LOG(ERROR) << "Certificate verification failed: hostname does not match";
1971 return -1;
1972 }
1973 return 0;
1974 }
1975
check_cert(SSL * ssl,const DownstreamAddr * addr,const Address * raddr)1976 int check_cert(SSL *ssl, const DownstreamAddr *addr, const Address *raddr) {
1977 auto hostname =
1978 addr->sni.empty() ? StringRef{addr->host} : StringRef{addr->sni};
1979 return check_cert(ssl, raddr, hostname);
1980 }
1981
CertLookupTree()1982 CertLookupTree::CertLookupTree() {}
1983
add_cert(const StringRef & hostname,size_t idx)1984 ssize_t CertLookupTree::add_cert(const StringRef &hostname, size_t idx) {
1985 std::array<uint8_t, NI_MAXHOST> buf;
1986
1987 // NI_MAXHOST includes terminal NULL byte
1988 if (hostname.empty() || hostname.size() + 1 > buf.size()) {
1989 return -1;
1990 }
1991
1992 auto wildcard_it = std::find(std::begin(hostname), std::end(hostname), '*');
1993 if (wildcard_it != std::end(hostname) &&
1994 wildcard_it + 1 != std::end(hostname)) {
1995 auto wildcard_prefix = StringRef{std::begin(hostname), wildcard_it};
1996 auto wildcard_suffix = StringRef{wildcard_it + 1, std::end(hostname)};
1997
1998 auto rev_suffix = StringRef{std::begin(buf),
1999 std::reverse_copy(std::begin(wildcard_suffix),
2000 std::end(wildcard_suffix),
2001 std::begin(buf))};
2002
2003 WildcardPattern *wpat;
2004
2005 if (wildcard_patterns_.size() !=
2006 rev_wildcard_router_.add_route(rev_suffix, wildcard_patterns_.size())) {
2007 auto wcidx = rev_wildcard_router_.match(rev_suffix);
2008
2009 assert(wcidx != -1);
2010
2011 wpat = &wildcard_patterns_[wcidx];
2012 } else {
2013 wildcard_patterns_.emplace_back();
2014 wpat = &wildcard_patterns_.back();
2015 }
2016
2017 auto rev_prefix = StringRef{std::begin(buf),
2018 std::reverse_copy(std::begin(wildcard_prefix),
2019 std::end(wildcard_prefix),
2020 std::begin(buf))};
2021
2022 for (auto &p : wpat->rev_prefix) {
2023 if (p.prefix == rev_prefix) {
2024 return p.idx;
2025 }
2026 }
2027
2028 wpat->rev_prefix.emplace_back(rev_prefix, idx);
2029
2030 return idx;
2031 }
2032
2033 return router_.add_route(hostname, idx);
2034 }
2035
lookup(const StringRef & hostname)2036 ssize_t CertLookupTree::lookup(const StringRef &hostname) {
2037 std::array<uint8_t, NI_MAXHOST> buf;
2038
2039 // NI_MAXHOST includes terminal NULL byte
2040 if (hostname.empty() || hostname.size() + 1 > buf.size()) {
2041 return -1;
2042 }
2043
2044 // Always prefer exact match
2045 auto idx = router_.match(hostname);
2046 if (idx != -1) {
2047 return idx;
2048 }
2049
2050 if (wildcard_patterns_.empty()) {
2051 return -1;
2052 }
2053
2054 ssize_t best_idx = -1;
2055 size_t best_prefixlen = 0;
2056 const RNode *last_node = nullptr;
2057
2058 auto rev_host = StringRef{
2059 std::begin(buf), std::reverse_copy(std::begin(hostname),
2060 std::end(hostname), std::begin(buf))};
2061
2062 for (;;) {
2063 size_t nread = 0;
2064
2065 auto wcidx =
2066 rev_wildcard_router_.match_prefix(&nread, &last_node, rev_host);
2067 if (wcidx == -1) {
2068 return best_idx;
2069 }
2070
2071 // '*' must match at least one byte
2072 if (nread == rev_host.size()) {
2073 return best_idx;
2074 }
2075
2076 rev_host = StringRef{std::begin(rev_host) + nread, std::end(rev_host)};
2077
2078 auto rev_prefix = StringRef{std::begin(rev_host) + 1, std::end(rev_host)};
2079
2080 auto &wpat = wildcard_patterns_[wcidx];
2081 for (auto &wprefix : wpat.rev_prefix) {
2082 if (!util::ends_with(rev_prefix, wprefix.prefix)) {
2083 continue;
2084 }
2085
2086 auto prefixlen =
2087 wprefix.prefix.size() +
2088 (reinterpret_cast<const uint8_t *>(&rev_host[0]) - &buf[0]);
2089
2090 // Breaking a tie with longer suffix
2091 if (prefixlen < best_prefixlen) {
2092 continue;
2093 }
2094
2095 best_idx = wprefix.idx;
2096 best_prefixlen = prefixlen;
2097 }
2098 }
2099 }
2100
dump() const2101 void CertLookupTree::dump() const {
2102 std::cerr << "exact:" << std::endl;
2103 router_.dump();
2104 std::cerr << "wildcard suffix (reversed):" << std::endl;
2105 rev_wildcard_router_.dump();
2106 }
2107
cert_lookup_tree_add_ssl_ctx(CertLookupTree * lt,std::vector<std::vector<SSL_CTX * >> & indexed_ssl_ctx,SSL_CTX * ssl_ctx)2108 int cert_lookup_tree_add_ssl_ctx(
2109 CertLookupTree *lt, std::vector<std::vector<SSL_CTX *>> &indexed_ssl_ctx,
2110 SSL_CTX *ssl_ctx) {
2111 std::array<uint8_t, NI_MAXHOST> buf;
2112
2113 #if LIBRESSL_2_7_API || \
2114 (!LIBRESSL_IN_USE && OPENSSL_VERSION_NUMBER >= 0x10002000L)
2115 auto cert = SSL_CTX_get0_certificate(ssl_ctx);
2116 #else // !LIBRESSL_2_7_API && OPENSSL_VERSION_NUMBER < 0x10002000L
2117 auto tls_ctx_data =
2118 static_cast<TLSContextData *>(SSL_CTX_get_app_data(ssl_ctx));
2119 auto cert = load_certificate(tls_ctx_data->cert_file);
2120 auto cert_deleter = defer(X509_free, cert);
2121 #endif // !LIBRESSL_2_7_API && OPENSSL_VERSION_NUMBER < 0x10002000L
2122
2123 auto altnames = static_cast<GENERAL_NAMES *>(
2124 X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
2125 if (altnames) {
2126 auto altnames_deleter = defer(GENERAL_NAMES_free, altnames);
2127 size_t n = sk_GENERAL_NAME_num(altnames);
2128 auto dns_found = false;
2129 for (size_t i = 0; i < n; ++i) {
2130 auto altname = sk_GENERAL_NAME_value(altnames, i);
2131 if (altname->type != GEN_DNS) {
2132 continue;
2133 }
2134
2135 auto name = ASN1_STRING_get0_data(altname->d.ia5);
2136 if (!name) {
2137 continue;
2138 }
2139
2140 auto len = ASN1_STRING_length(altname->d.ia5);
2141 if (len == 0) {
2142 continue;
2143 }
2144 if (std::find(name, name + len, '\0') != name + len) {
2145 // Embedded NULL is not permitted.
2146 continue;
2147 }
2148
2149 if (name[len - 1] == '.') {
2150 --len;
2151 if (len == 0) {
2152 continue;
2153 }
2154 }
2155
2156 dns_found = true;
2157
2158 if (static_cast<size_t>(len) + 1 > buf.size()) {
2159 continue;
2160 }
2161
2162 auto end_buf = std::copy_n(name, len, std::begin(buf));
2163 util::inp_strlower(std::begin(buf), end_buf);
2164
2165 auto idx = lt->add_cert(StringRef{std::begin(buf), end_buf},
2166 indexed_ssl_ctx.size());
2167 if (idx == -1) {
2168 continue;
2169 }
2170
2171 if (static_cast<size_t>(idx) < indexed_ssl_ctx.size()) {
2172 indexed_ssl_ctx[idx].push_back(ssl_ctx);
2173 } else {
2174 assert(static_cast<size_t>(idx) == indexed_ssl_ctx.size());
2175 indexed_ssl_ctx.emplace_back(std::vector<SSL_CTX *>{ssl_ctx});
2176 }
2177 }
2178
2179 // Don't bother CN if we have dNSName.
2180 if (dns_found) {
2181 return 0;
2182 }
2183 }
2184
2185 auto cn = get_common_name(cert);
2186 if (cn.empty()) {
2187 return 0;
2188 }
2189
2190 if (cn[cn.size() - 1] == '.') {
2191 if (cn.size() == 1) {
2192 OPENSSL_free(const_cast<char *>(cn.c_str()));
2193
2194 return 0;
2195 }
2196
2197 cn = StringRef{cn.c_str(), cn.size() - 1};
2198 }
2199
2200 auto end_buf = std::copy(std::begin(cn), std::end(cn), std::begin(buf));
2201
2202 OPENSSL_free(const_cast<char *>(cn.c_str()));
2203
2204 util::inp_strlower(std::begin(buf), end_buf);
2205
2206 auto idx =
2207 lt->add_cert(StringRef{std::begin(buf), end_buf}, indexed_ssl_ctx.size());
2208 if (idx == -1) {
2209 return 0;
2210 }
2211
2212 if (static_cast<size_t>(idx) < indexed_ssl_ctx.size()) {
2213 indexed_ssl_ctx[idx].push_back(ssl_ctx);
2214 } else {
2215 assert(static_cast<size_t>(idx) == indexed_ssl_ctx.size());
2216 indexed_ssl_ctx.emplace_back(std::vector<SSL_CTX *>{ssl_ctx});
2217 }
2218
2219 return 0;
2220 }
2221
in_proto_list(const std::vector<StringRef> & protos,const StringRef & needle)2222 bool in_proto_list(const std::vector<StringRef> &protos,
2223 const StringRef &needle) {
2224 for (auto &proto : protos) {
2225 if (util::streq(proto, needle)) {
2226 return true;
2227 }
2228 }
2229 return false;
2230 }
2231
upstream_tls_enabled(const ConnectionConfig & connconf)2232 bool upstream_tls_enabled(const ConnectionConfig &connconf) {
2233 #ifdef ENABLE_HTTP3
2234 if (connconf.quic_listener.addrs.size()) {
2235 return true;
2236 }
2237 #endif // ENABLE_HTTP3
2238
2239 const auto &faddrs = connconf.listener.addrs;
2240 return std::any_of(std::begin(faddrs), std::end(faddrs),
2241 [](const UpstreamAddr &faddr) { return faddr.tls; });
2242 }
2243
load_certificate(const char * filename)2244 X509 *load_certificate(const char *filename) {
2245 auto bio = BIO_new(BIO_s_file());
2246 if (!bio) {
2247 fprintf(stderr, "BIO_new() failed\n");
2248 return nullptr;
2249 }
2250 auto bio_deleter = defer(BIO_vfree, bio);
2251 if (!BIO_read_filename(bio, filename)) {
2252 fprintf(stderr, "Could not read certificate file '%s'\n", filename);
2253 return nullptr;
2254 }
2255 auto cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
2256 if (!cert) {
2257 fprintf(stderr, "Could not read X509 structure from file '%s'\n", filename);
2258 return nullptr;
2259 }
2260
2261 return cert;
2262 }
2263
2264 SSL_CTX *
setup_server_ssl_context(std::vector<SSL_CTX * > & all_ssl_ctx,std::vector<std::vector<SSL_CTX * >> & indexed_ssl_ctx,CertLookupTree * cert_tree,neverbleed_t * nb)2265 setup_server_ssl_context(std::vector<SSL_CTX *> &all_ssl_ctx,
2266 std::vector<std::vector<SSL_CTX *>> &indexed_ssl_ctx,
2267 CertLookupTree *cert_tree
2268 #ifdef HAVE_NEVERBLEED
2269 ,
2270 neverbleed_t *nb
2271 #endif // HAVE_NEVERBLEED
2272 ) {
2273 auto config = get_config();
2274
2275 if (!upstream_tls_enabled(config->conn)) {
2276 return nullptr;
2277 }
2278
2279 auto &tlsconf = config->tls;
2280
2281 auto ssl_ctx = create_ssl_context(tlsconf.private_key_file.c_str(),
2282 tlsconf.cert_file.c_str(), tlsconf.sct_data
2283 #ifdef HAVE_NEVERBLEED
2284 ,
2285 nb
2286 #endif // HAVE_NEVERBLEED
2287 );
2288
2289 all_ssl_ctx.push_back(ssl_ctx);
2290
2291 assert(cert_tree);
2292
2293 if (cert_lookup_tree_add_ssl_ctx(cert_tree, indexed_ssl_ctx, ssl_ctx) == -1) {
2294 LOG(FATAL) << "Failed to add default certificate.";
2295 DIE();
2296 }
2297
2298 for (auto &c : tlsconf.subcerts) {
2299 auto ssl_ctx = create_ssl_context(c.private_key_file.c_str(),
2300 c.cert_file.c_str(), c.sct_data
2301 #ifdef HAVE_NEVERBLEED
2302 ,
2303 nb
2304 #endif // HAVE_NEVERBLEED
2305 );
2306 all_ssl_ctx.push_back(ssl_ctx);
2307
2308 if (cert_lookup_tree_add_ssl_ctx(cert_tree, indexed_ssl_ctx, ssl_ctx) ==
2309 -1) {
2310 LOG(FATAL) << "Failed to add sub certificate.";
2311 DIE();
2312 }
2313 }
2314
2315 return ssl_ctx;
2316 }
2317
2318 #ifdef ENABLE_HTTP3
setup_quic_server_ssl_context(std::vector<SSL_CTX * > & all_ssl_ctx,std::vector<std::vector<SSL_CTX * >> & indexed_ssl_ctx,CertLookupTree * cert_tree,neverbleed_t * nb)2319 SSL_CTX *setup_quic_server_ssl_context(
2320 std::vector<SSL_CTX *> &all_ssl_ctx,
2321 std::vector<std::vector<SSL_CTX *>> &indexed_ssl_ctx,
2322 CertLookupTree *cert_tree
2323 # ifdef HAVE_NEVERBLEED
2324 ,
2325 neverbleed_t *nb
2326 # endif // HAVE_NEVERBLEED
2327 ) {
2328 auto config = get_config();
2329
2330 if (!upstream_tls_enabled(config->conn)) {
2331 return nullptr;
2332 }
2333
2334 auto &tlsconf = config->tls;
2335
2336 auto ssl_ctx =
2337 create_quic_ssl_context(tlsconf.private_key_file.c_str(),
2338 tlsconf.cert_file.c_str(), tlsconf.sct_data
2339 # ifdef HAVE_NEVERBLEED
2340 ,
2341 nb
2342 # endif // HAVE_NEVERBLEED
2343 );
2344
2345 all_ssl_ctx.push_back(ssl_ctx);
2346
2347 assert(cert_tree);
2348
2349 if (cert_lookup_tree_add_ssl_ctx(cert_tree, indexed_ssl_ctx, ssl_ctx) == -1) {
2350 LOG(FATAL) << "Failed to add default certificate.";
2351 DIE();
2352 }
2353
2354 for (auto &c : tlsconf.subcerts) {
2355 auto ssl_ctx = create_quic_ssl_context(c.private_key_file.c_str(),
2356 c.cert_file.c_str(), c.sct_data
2357 # ifdef HAVE_NEVERBLEED
2358 ,
2359 nb
2360 # endif // HAVE_NEVERBLEED
2361 );
2362 all_ssl_ctx.push_back(ssl_ctx);
2363
2364 if (cert_lookup_tree_add_ssl_ctx(cert_tree, indexed_ssl_ctx, ssl_ctx) ==
2365 -1) {
2366 LOG(FATAL) << "Failed to add sub certificate.";
2367 DIE();
2368 }
2369 }
2370
2371 return ssl_ctx;
2372 }
2373 #endif // ENABLE_HTTP3
2374
setup_downstream_client_ssl_context(neverbleed_t * nb)2375 SSL_CTX *setup_downstream_client_ssl_context(
2376 #ifdef HAVE_NEVERBLEED
2377 neverbleed_t *nb
2378 #endif // HAVE_NEVERBLEED
2379 ) {
2380 auto &tlsconf = get_config()->tls;
2381
2382 return create_ssl_client_context(
2383 #ifdef HAVE_NEVERBLEED
2384 nb,
2385 #endif // HAVE_NEVERBLEED
2386 tlsconf.cacert, tlsconf.client.cert_file, tlsconf.client.private_key_file,
2387 select_next_proto_cb);
2388 }
2389
setup_downstream_http2_alpn(SSL * ssl)2390 void setup_downstream_http2_alpn(SSL *ssl) {
2391 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
2392 // ALPN advertisement
2393 auto alpn = util::get_default_alpn();
2394 SSL_set_alpn_protos(ssl, alpn.data(), alpn.size());
2395 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
2396 }
2397
setup_downstream_http1_alpn(SSL * ssl)2398 void setup_downstream_http1_alpn(SSL *ssl) {
2399 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
2400 // ALPN advertisement
2401 SSL_set_alpn_protos(ssl, NGHTTP2_H1_1_ALPN.byte(), NGHTTP2_H1_1_ALPN.size());
2402 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
2403 }
2404
create_cert_lookup_tree()2405 std::unique_ptr<CertLookupTree> create_cert_lookup_tree() {
2406 auto config = get_config();
2407 if (!upstream_tls_enabled(config->conn)) {
2408 return nullptr;
2409 }
2410 return std::make_unique<CertLookupTree>();
2411 }
2412
2413 namespace {
serialize_ssl_session(SSL_SESSION * session)2414 std::vector<uint8_t> serialize_ssl_session(SSL_SESSION *session) {
2415 auto len = i2d_SSL_SESSION(session, nullptr);
2416 auto buf = std::vector<uint8_t>(len);
2417 auto p = buf.data();
2418 i2d_SSL_SESSION(session, &p);
2419
2420 return buf;
2421 }
2422 } // namespace
2423
try_cache_tls_session(TLSSessionCache * cache,SSL_SESSION * session,ev_tstamp t)2424 void try_cache_tls_session(TLSSessionCache *cache, SSL_SESSION *session,
2425 ev_tstamp t) {
2426 if (cache->last_updated + 1_min > t) {
2427 if (LOG_ENABLED(INFO)) {
2428 LOG(INFO) << "Client session cache entry is still fresh.";
2429 }
2430 return;
2431 }
2432
2433 if (LOG_ENABLED(INFO)) {
2434 LOG(INFO) << "Update client cache entry "
2435 << "timestamp = " << t;
2436 }
2437
2438 cache->session_data = serialize_ssl_session(session);
2439 cache->last_updated = t;
2440 }
2441
reuse_tls_session(const TLSSessionCache & cache)2442 SSL_SESSION *reuse_tls_session(const TLSSessionCache &cache) {
2443 if (cache.session_data.empty()) {
2444 return nullptr;
2445 }
2446
2447 auto p = cache.session_data.data();
2448 return d2i_SSL_SESSION(nullptr, &p, cache.session_data.size());
2449 }
2450
proto_version_from_string(const StringRef & v)2451 int proto_version_from_string(const StringRef &v) {
2452 #ifdef TLS1_3_VERSION
2453 if (util::strieq_l("TLSv1.3", v)) {
2454 return TLS1_3_VERSION;
2455 }
2456 #endif // TLS1_3_VERSION
2457 if (util::strieq_l("TLSv1.2", v)) {
2458 return TLS1_2_VERSION;
2459 }
2460 if (util::strieq_l("TLSv1.1", v)) {
2461 return TLS1_1_VERSION;
2462 }
2463 if (util::strieq_l("TLSv1.0", v)) {
2464 return TLS1_VERSION;
2465 }
2466 return -1;
2467 }
2468
verify_ocsp_response(SSL_CTX * ssl_ctx,const uint8_t * ocsp_resp,size_t ocsp_resplen)2469 int verify_ocsp_response(SSL_CTX *ssl_ctx, const uint8_t *ocsp_resp,
2470 size_t ocsp_resplen) {
2471
2472 #if !defined(OPENSSL_NO_OCSP) && !LIBRESSL_IN_USE && \
2473 OPENSSL_VERSION_NUMBER >= 0x10002000L
2474 int rv;
2475
2476 STACK_OF(X509) * chain_certs;
2477 SSL_CTX_get0_chain_certs(ssl_ctx, &chain_certs);
2478
2479 auto resp = d2i_OCSP_RESPONSE(nullptr, &ocsp_resp, ocsp_resplen);
2480 if (resp == nullptr) {
2481 LOG(ERROR) << "d2i_OCSP_RESPONSE failed";
2482 return -1;
2483 }
2484 auto resp_deleter = defer(OCSP_RESPONSE_free, resp);
2485
2486 if (OCSP_response_status(resp) != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
2487 LOG(ERROR) << "OCSP response status is not successful";
2488 return -1;
2489 }
2490
2491 ERR_clear_error();
2492
2493 auto bs = OCSP_response_get1_basic(resp);
2494 if (bs == nullptr) {
2495 LOG(ERROR) << "OCSP_response_get1_basic failed: "
2496 << ERR_error_string(ERR_get_error(), nullptr);
2497 return -1;
2498 }
2499 auto bs_deleter = defer(OCSP_BASICRESP_free, bs);
2500
2501 auto store = SSL_CTX_get_cert_store(ssl_ctx);
2502
2503 ERR_clear_error();
2504
2505 rv = OCSP_basic_verify(bs, chain_certs, store, 0);
2506
2507 if (rv != 1) {
2508 LOG(ERROR) << "OCSP_basic_verify failed: "
2509 << ERR_error_string(ERR_get_error(), nullptr);
2510 return -1;
2511 }
2512
2513 auto sresp = OCSP_resp_get0(bs, 0);
2514 if (sresp == nullptr) {
2515 LOG(ERROR) << "OCSP response verification failed: no single response";
2516 return -1;
2517 }
2518
2519 # if OPENSSL_1_1_API
2520 auto certid = OCSP_SINGLERESP_get0_id(sresp);
2521 # else // !OPENSSL_1_1_API
2522 auto certid = sresp->certId;
2523 # endif // !OPENSSL_1_1_API
2524 assert(certid != nullptr);
2525
2526 ASN1_INTEGER *serial;
2527 rv = OCSP_id_get0_info(nullptr, nullptr, nullptr, &serial,
2528 const_cast<OCSP_CERTID *>(certid));
2529 if (rv != 1) {
2530 LOG(ERROR) << "OCSP_id_get0_info failed";
2531 return -1;
2532 }
2533
2534 if (serial == nullptr) {
2535 LOG(ERROR) << "OCSP response does not contain serial number";
2536 return -1;
2537 }
2538
2539 auto cert = SSL_CTX_get0_certificate(ssl_ctx);
2540 auto cert_serial = X509_get_serialNumber(cert);
2541
2542 if (ASN1_INTEGER_cmp(cert_serial, serial)) {
2543 LOG(ERROR) << "OCSP verification serial numbers do not match";
2544 return -1;
2545 }
2546
2547 if (LOG_ENABLED(INFO)) {
2548 LOG(INFO) << "OCSP verification succeeded";
2549 }
2550 #endif // !defined(OPENSSL_NO_OCSP) && !LIBRESSL_IN_USE
2551 // && OPENSSL_VERSION_NUMBER >= 0x10002000L
2552
2553 return 0;
2554 }
2555
get_x509_fingerprint(uint8_t * dst,size_t dstlen,const X509 * x,const EVP_MD * md)2556 ssize_t get_x509_fingerprint(uint8_t *dst, size_t dstlen, const X509 *x,
2557 const EVP_MD *md) {
2558 unsigned int len = dstlen;
2559 if (X509_digest(x, md, dst, &len) != 1) {
2560 return -1;
2561 }
2562 return len;
2563 }
2564
2565 namespace {
get_x509_name(BlockAllocator & balloc,X509_NAME * nm)2566 StringRef get_x509_name(BlockAllocator &balloc, X509_NAME *nm) {
2567 auto b = BIO_new(BIO_s_mem());
2568 if (!b) {
2569 return StringRef{};
2570 }
2571
2572 auto b_deleter = defer(BIO_free, b);
2573
2574 // Not documented, but it seems that X509_NAME_print_ex returns the
2575 // number of bytes written into b.
2576 auto slen = X509_NAME_print_ex(b, nm, 0, XN_FLAG_RFC2253);
2577 if (slen <= 0) {
2578 return StringRef{};
2579 }
2580
2581 auto iov = make_byte_ref(balloc, slen + 1);
2582 BIO_read(b, iov.base, slen);
2583 iov.base[slen] = '\0';
2584 return StringRef{iov.base, static_cast<size_t>(slen)};
2585 }
2586 } // namespace
2587
get_x509_subject_name(BlockAllocator & balloc,X509 * x)2588 StringRef get_x509_subject_name(BlockAllocator &balloc, X509 *x) {
2589 return get_x509_name(balloc, X509_get_subject_name(x));
2590 }
2591
get_x509_issuer_name(BlockAllocator & balloc,X509 * x)2592 StringRef get_x509_issuer_name(BlockAllocator &balloc, X509 *x) {
2593 return get_x509_name(balloc, X509_get_issuer_name(x));
2594 }
2595
2596 #ifdef WORDS_BIGENDIAN
2597 # define bswap64(N) (N)
2598 #else /* !WORDS_BIGENDIAN */
2599 # define bswap64(N) \
2600 ((uint64_t)(ntohl((uint32_t)(N))) << 32 | ntohl((uint32_t)((N) >> 32)))
2601 #endif /* !WORDS_BIGENDIAN */
2602
get_x509_serial(BlockAllocator & balloc,X509 * x)2603 StringRef get_x509_serial(BlockAllocator &balloc, X509 *x) {
2604 auto sn = X509_get_serialNumber(x);
2605 auto bn = BN_new();
2606 auto bn_d = defer(BN_free, bn);
2607 if (!ASN1_INTEGER_to_BN(sn, bn) || BN_num_bytes(bn) > 20) {
2608 return StringRef{};
2609 }
2610
2611 std::array<uint8_t, 20> b;
2612 auto n = BN_bn2bin(bn, b.data());
2613 assert(n <= 20);
2614
2615 return util::format_hex(balloc, StringRef{b.data(), static_cast<size_t>(n)});
2616 }
2617
2618 namespace {
2619 // Performs conversion from |at| to time_t. The result is stored in
2620 // |t|. This function returns 0 if it succeeds, or -1.
time_t_from_asn1_time(time_t & t,const ASN1_TIME * at)2621 int time_t_from_asn1_time(time_t &t, const ASN1_TIME *at) {
2622 int rv;
2623
2624 #if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
2625 struct tm tm;
2626 rv = ASN1_TIME_to_tm(at, &tm);
2627 if (rv != 1) {
2628 return -1;
2629 }
2630
2631 t = nghttp2_timegm(&tm);
2632 #else // !(OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL))
2633 auto b = BIO_new(BIO_s_mem());
2634 if (!b) {
2635 return -1;
2636 }
2637
2638 auto bio_deleter = defer(BIO_free, b);
2639
2640 rv = ASN1_TIME_print(b, at);
2641 if (rv != 1) {
2642 return -1;
2643 }
2644
2645 # ifdef OPENSSL_IS_BORINGSSL
2646 char *s;
2647 # else
2648 unsigned char *s;
2649 # endif
2650 auto slen = BIO_get_mem_data(b, &s);
2651 auto tt = util::parse_openssl_asn1_time_print(
2652 StringRef{s, static_cast<size_t>(slen)});
2653 if (tt == 0) {
2654 return -1;
2655 }
2656
2657 t = tt;
2658 #endif // !(OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL))
2659
2660 return 0;
2661 }
2662 } // namespace
2663
get_x509_not_before(time_t & t,X509 * x)2664 int get_x509_not_before(time_t &t, X509 *x) {
2665 #if OPENSSL_1_1_API
2666 auto at = X509_get0_notBefore(x);
2667 #else // !OPENSSL_1_1_API
2668 auto at = X509_get_notBefore(x);
2669 #endif // !OPENSSL_1_1_API
2670 if (!at) {
2671 return -1;
2672 }
2673
2674 return time_t_from_asn1_time(t, at);
2675 }
2676
get_x509_not_after(time_t & t,X509 * x)2677 int get_x509_not_after(time_t &t, X509 *x) {
2678 #if OPENSSL_1_1_API
2679 auto at = X509_get0_notAfter(x);
2680 #else // !OPENSSL_1_1_API
2681 auto at = X509_get_notAfter(x);
2682 #endif // !OPENSSL_1_1_API
2683 if (!at) {
2684 return -1;
2685 }
2686
2687 return time_t_from_asn1_time(t, at);
2688 }
2689
2690 } // namespace tls
2691
2692 } // namespace shrpx
2693