2 * nghttp2 - HTTP/2 C Library
4 * Copyright (c) 2012 Tatsuhiro Tsujikawa
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:
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
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.
25 #include "shrpx_tls.h"
27 #ifdef HAVE_SYS_SOCKET_H
28 # include <sys/socket.h>
29 #endif // HAVE_SYS_SOCKET_H
32 #endif // HAVE_NETDB_H
33 #include <netinet/tcp.h>
35 #include <sys/types.h>
43 #include "ssl_compat.h"
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
54 # include <openssl/params.h>
55 # include <openssl/core_names.h>
56 # include <openssl/decoder.h>
57 #endif // OPENSSL_3_0_0_API
59 #include <nghttp2/nghttp2.h>
62 # include <ngtcp2/ngtcp2.h>
63 # include <ngtcp2/ngtcp2_crypto.h>
64 # ifdef HAVE_LIBNGTCP2_CRYPTO_OPENSSL
65 # include <ngtcp2/ngtcp2_crypto_openssl.h>
66 # endif // HAVE_LIBNGTCP2_CRYPTO_OPENSSL
67 # ifdef HAVE_LIBNGTCP2_CRYPTO_BORINGSSL
68 # include <ngtcp2/ngtcp2_crypto_boringssl.h>
69 # endif // HAVE_LIBNGTCP2_CRYPTO_BORINGSSL
70 #endif // ENABLE_HTTP3
72 #include "shrpx_log.h"
73 #include "shrpx_client_handler.h"
74 #include "shrpx_config.h"
75 #include "shrpx_worker.h"
76 #include "shrpx_downstream_connection_pool.h"
77 #include "shrpx_http2_session.h"
78 #include "shrpx_memcached_request.h"
79 #include "shrpx_memcached_dispatcher.h"
80 #include "shrpx_connection_handler.h"
82 # include "shrpx_http3_upstream.h"
83 #endif // ENABLE_HTTP3
89 using namespace nghttp2;
97 const unsigned char *ASN1_STRING_get0_data(ASN1_STRING *x) {
98 return ASN1_STRING_data(x);
101 #endif // !OPENSSL_1_1_API
103 #ifndef OPENSSL_NO_NEXTPROTONEG
105 int next_proto_cb(SSL *s, const unsigned char **data, unsigned int *len,
107 auto &prefs = get_config()->tls.alpn_prefs;
108 *data = prefs.data();
110 return SSL_TLSEXT_ERR_OK;
113 #endif // !OPENSSL_NO_NEXTPROTONEG
116 int verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
118 int err = X509_STORE_CTX_get_error(ctx);
119 int depth = X509_STORE_CTX_get_error_depth(ctx);
120 if (err == X509_V_ERR_CERT_HAS_EXPIRED && depth == 0 &&
121 get_config()->tls.client_verify.tolerate_expired) {
122 LOG(INFO) << "The client certificate has expired, but is accepted by "
126 LOG(ERROR) << "client certificate verify error:num=" << err << ":"
127 << X509_verify_cert_error_string(err) << ":depth=" << depth;
133 int set_alpn_prefs(std::vector<unsigned char> &out,
134 const std::vector<StringRef> &protos) {
137 for (const auto &proto : protos) {
138 if (proto.size() > 255) {
139 LOG(FATAL) << "Too long ALPN identifier: " << proto.size();
143 len += 1 + proto.size();
146 if (len > (1 << 16) - 1) {
147 LOG(FATAL) << "Too long ALPN identifier list: " << len;
152 auto ptr = out.data();
154 for (const auto &proto : protos) {
155 *ptr++ = proto.size();
156 ptr = std::copy(std::begin(proto), std::end(proto), ptr);
163 int ssl_pem_passwd_cb(char *buf, int size, int rwflag, void *user_data) {
164 auto config = static_cast<Config *>(user_data);
165 auto len = static_cast<int>(config->tls.private_key_passwd.size());
166 if (size < len + 1) {
167 LOG(ERROR) << "ssl_pem_passwd_cb: buf is too small " << size;
170 // Copy string including last '\0'.
171 memcpy(buf, config->tls.private_key_passwd.c_str(), len + 1);
177 // *al is set to SSL_AD_UNRECOGNIZED_NAME by openssl, so we don't have
178 // to set it explicitly.
179 int servername_callback(SSL *ssl, int *al, void *arg) {
180 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
181 auto handler = static_cast<ClientHandler *>(conn->data);
182 auto worker = handler->get_worker();
184 auto rawhost = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
185 if (rawhost == nullptr) {
186 return SSL_TLSEXT_ERR_NOACK;
189 auto len = strlen(rawhost);
190 // NI_MAXHOST includes terminal NULL.
191 if (len == 0 || len + 1 > NI_MAXHOST) {
192 return SSL_TLSEXT_ERR_NOACK;
195 std::array<uint8_t, NI_MAXHOST> buf;
197 auto end_buf = std::copy_n(rawhost, len, std::begin(buf));
199 util::inp_strlower(std::begin(buf), end_buf);
201 auto hostname = StringRef{std::begin(buf), end_buf};
204 auto cert_tree = conn->proto == Proto::HTTP3
205 ? worker->get_quic_cert_lookup_tree()
206 : worker->get_cert_lookup_tree();
207 #else // !ENABLE_HTTP3
208 auto cert_tree = worker->get_cert_lookup_tree();
209 #endif // !ENABLE_HTTP3
211 auto idx = cert_tree->lookup(hostname);
213 return SSL_TLSEXT_ERR_NOACK;
216 handler->set_tls_sni(hostname);
218 auto conn_handler = worker->get_connection_handler();
221 const auto &ssl_ctx_list = conn->proto == Proto::HTTP3
222 ? conn_handler->get_quic_indexed_ssl_ctx(idx)
223 : conn_handler->get_indexed_ssl_ctx(idx);
224 #else // !ENABLE_HTTP3
225 const auto &ssl_ctx_list = conn_handler->get_indexed_ssl_ctx(idx);
226 #endif // !ENABLE_HTTP3
228 assert(!ssl_ctx_list.empty());
230 #if !defined(OPENSSL_IS_BORINGSSL) && !LIBRESSL_IN_USE && \
231 OPENSSL_VERSION_NUMBER >= 0x10002000L
233 SSL_get_sigalgs(ssl, 0, nullptr, nullptr, nullptr, nullptr, nullptr);
235 for (idx = 0; idx < num_sigalgs; ++idx) {
238 SSL_get_sigalgs(ssl, idx, nullptr, nullptr, &signhash, nullptr, nullptr);
240 case NID_ecdsa_with_SHA256:
241 case NID_ecdsa_with_SHA384:
242 case NID_ecdsa_with_SHA512:
251 if (idx == num_sigalgs) {
252 SSL_set_SSL_CTX(ssl, ssl_ctx_list[0]);
254 return SSL_TLSEXT_ERR_OK;
257 auto num_shared_curves = SSL_get_shared_curve(ssl, -1);
259 for (auto i = 0; i < num_shared_curves; ++i) {
260 auto shared_curve = SSL_get_shared_curve(ssl, i);
261 # if OPENSSL_3_0_0_API
262 // It looks like only short name is defined in OpenSSL. No idea
263 // which one to use because it is unknown that which one
264 // EVP_PKEY_get_utf8_string_param("group") returns.
265 auto shared_curve_name = OBJ_nid2sn(shared_curve);
266 if (shared_curve_name == nullptr) {
269 # endif // OPENSSL_3_0_0_API
271 for (auto ssl_ctx : ssl_ctx_list) {
272 auto cert = SSL_CTX_get0_certificate(ssl_ctx);
275 auto pubkey = X509_get0_pubkey(cert);
276 # else // !OPENSSL_1_1_API
277 auto pubkey = X509_get_pubkey(cert);
278 # endif // !OPENSSL_1_1_API
280 if (EVP_PKEY_base_id(pubkey) != EVP_PKEY_EC) {
284 # if OPENSSL_3_0_0_API
285 std::array<char, 64> curve_name;
286 if (!EVP_PKEY_get_utf8_string_param(pubkey, "group", curve_name.data(),
287 curve_name.size(), nullptr)) {
291 if (strcmp(shared_curve_name, curve_name.data()) == 0) {
292 SSL_set_SSL_CTX(ssl, ssl_ctx);
293 return SSL_TLSEXT_ERR_OK;
295 # else // !OPENSSL_3_0_0_API
297 auto eckey = EVP_PKEY_get0_EC_KEY(pubkey);
298 # else // !OPENSSL_1_1_API
299 auto eckey = EVP_PKEY_get1_EC_KEY(pubkey);
300 # endif // !OPENSSL_1_1_API
302 if (eckey == nullptr) {
306 auto ecgroup = EC_KEY_get0_group(eckey);
307 auto cert_curve = EC_GROUP_get_curve_name(ecgroup);
309 # if !OPENSSL_1_1_API
311 EVP_PKEY_free(pubkey);
312 # endif // !OPENSSL_1_1_API
314 if (shared_curve == cert_curve) {
315 SSL_set_SSL_CTX(ssl, ssl_ctx);
316 return SSL_TLSEXT_ERR_OK;
318 # endif // !OPENSSL_3_0_0_API
321 #endif // !defined(OPENSSL_IS_BORINGSSL) && !LIBRESSL_IN_USE &&
322 // OPENSSL_VERSION_NUMBER >= 0x10002000L
324 SSL_set_SSL_CTX(ssl, ssl_ctx_list[0]);
326 return SSL_TLSEXT_ERR_OK;
330 #ifndef OPENSSL_IS_BORINGSSL
332 std::shared_ptr<std::vector<uint8_t>>
333 get_ocsp_data(TLSContextData *tls_ctx_data) {
334 # ifdef HAVE_ATOMIC_STD_SHARED_PTR
335 return std::atomic_load_explicit(&tls_ctx_data->ocsp_data,
336 std::memory_order_acquire);
337 # else // !HAVE_ATOMIC_STD_SHARED_PTR
338 std::lock_guard<std::mutex> g(tls_ctx_data->mu);
339 return tls_ctx_data->ocsp_data;
340 # endif // !HAVE_ATOMIC_STD_SHARED_PTR
345 int ocsp_resp_cb(SSL *ssl, void *arg) {
346 auto ssl_ctx = SSL_get_SSL_CTX(ssl);
348 static_cast<TLSContextData *>(SSL_CTX_get_app_data(ssl_ctx));
350 auto data = get_ocsp_data(tls_ctx_data);
353 return SSL_TLSEXT_ERR_OK;
357 static_cast<uint8_t *>(CRYPTO_malloc(data->size(), __FILE__, __LINE__));
360 return SSL_TLSEXT_ERR_OK;
363 std::copy(std::begin(*data), std::end(*data), buf);
365 SSL_set_tlsext_status_ocsp_resp(ssl, buf, data->size());
367 return SSL_TLSEXT_ERR_OK;
370 #endif // OPENSSL_IS_BORINGSSL
372 constexpr auto MEMCACHED_SESSION_CACHE_KEY_PREFIX =
373 StringRef::from_lit("nghttpx:tls-session-cache:");
376 int tls_session_client_new_cb(SSL *ssl, SSL_SESSION *session) {
377 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
378 if (conn->tls.client_session_cache == nullptr) {
382 try_cache_tls_session(conn->tls.client_session_cache, session,
390 int tls_session_new_cb(SSL *ssl, SSL_SESSION *session) {
391 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
392 auto handler = static_cast<ClientHandler *>(conn->data);
393 auto worker = handler->get_worker();
394 auto dispatcher = worker->get_session_cache_memcached_dispatcher();
395 auto &balloc = handler->get_block_allocator();
397 #ifdef TLS1_3_VERSION
398 if (SSL_version(ssl) == TLS1_3_VERSION) {
401 #endif // TLS1_3_VERSION
403 const unsigned char *id;
406 id = SSL_SESSION_get_id(session, &idlen);
408 if (LOG_ENABLED(INFO)) {
409 LOG(INFO) << "Memcached: cache session, id=" << util::format_hex(id, idlen);
412 auto req = std::make_unique<MemcachedRequest>();
413 req->op = MemcachedOp::ADD;
414 req->key = MEMCACHED_SESSION_CACHE_KEY_PREFIX.str();
416 util::format_hex(balloc, StringRef{id, static_cast<size_t>(idlen)});
418 auto sessionlen = i2d_SSL_SESSION(session, nullptr);
419 req->value.resize(sessionlen);
420 auto buf = &req->value[0];
421 i2d_SSL_SESSION(session, &buf);
423 req->cb = [](MemcachedRequest *req, MemcachedResult res) {
424 if (LOG_ENABLED(INFO)) {
425 LOG(INFO) << "Memcached: session cache done. key=" << req->key
426 << ", status_code=" << static_cast<uint16_t>(res.status_code)
428 << std::string(std::begin(res.value), std::end(res.value));
430 if (res.status_code != MemcachedStatusCode::NO_ERROR) {
431 LOG(WARN) << "Memcached: failed to cache session key=" << req->key
432 << ", status_code=" << static_cast<uint16_t>(res.status_code)
434 << std::string(std::begin(res.value), std::end(res.value));
437 assert(!req->canceled);
439 dispatcher->add_request(std::move(req));
446 SSL_SESSION *tls_session_get_cb(SSL *ssl,
447 #if OPENSSL_1_1_API || LIBRESSL_2_7_API
448 const unsigned char *id,
449 #else // !(OPENSSL_1_1_API || LIBRESSL_2_7_API)
451 #endif // !(OPENSSL_1_1_API || LIBRESSL_2_7_API)
452 int idlen, int *copy) {
453 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
454 auto handler = static_cast<ClientHandler *>(conn->data);
455 auto worker = handler->get_worker();
456 auto dispatcher = worker->get_session_cache_memcached_dispatcher();
457 auto &balloc = handler->get_block_allocator();
463 if (conn->tls.cached_session) {
464 if (LOG_ENABLED(INFO)) {
465 LOG(INFO) << "Memcached: found cached session, id="
466 << util::format_hex(id, idlen);
469 // This is required, without this, memory leak occurs.
472 auto session = conn->tls.cached_session;
473 conn->tls.cached_session = nullptr;
477 if (LOG_ENABLED(INFO)) {
478 LOG(INFO) << "Memcached: get cached session, id="
479 << util::format_hex(id, idlen);
482 auto req = std::make_unique<MemcachedRequest>();
483 req->op = MemcachedOp::GET;
484 req->key = MEMCACHED_SESSION_CACHE_KEY_PREFIX.str();
486 util::format_hex(balloc, StringRef{id, static_cast<size_t>(idlen)});
487 req->cb = [conn](MemcachedRequest *, MemcachedResult res) {
488 if (LOG_ENABLED(INFO)) {
489 LOG(INFO) << "Memcached: returned status code "
490 << static_cast<uint16_t>(res.status_code);
493 // We might stop reading, so start it again
494 conn->rlimit.startw();
495 ev_timer_again(conn->loop, &conn->rt);
497 conn->wlimit.startw();
498 ev_timer_again(conn->loop, &conn->wt);
500 conn->tls.cached_session_lookup_req = nullptr;
501 if (res.status_code != MemcachedStatusCode::NO_ERROR) {
502 conn->tls.handshake_state = TLSHandshakeState::CANCEL_SESSION_CACHE;
506 const uint8_t *p = res.value.data();
508 auto session = d2i_SSL_SESSION(nullptr, &p, res.value.size());
510 if (LOG_ENABLED(INFO)) {
511 LOG(INFO) << "cannot materialize session";
513 conn->tls.handshake_state = TLSHandshakeState::CANCEL_SESSION_CACHE;
517 conn->tls.cached_session = session;
518 conn->tls.handshake_state = TLSHandshakeState::GOT_SESSION_CACHE;
521 conn->tls.handshake_state = TLSHandshakeState::WAIT_FOR_SESSION_CACHE;
522 conn->tls.cached_session_lookup_req = req.get();
524 dispatcher->add_request(std::move(req));
531 int ticket_key_cb(SSL *ssl, unsigned char *key_name, unsigned char *iv,
533 #if OPENSSL_3_0_0_API
535 #else // !OPENSSL_3_0_0_API
537 #endif // !OPENSSL_3_0_0_API
539 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
540 auto handler = static_cast<ClientHandler *>(conn->data);
541 auto worker = handler->get_worker();
542 auto ticket_keys = worker->get_ticket_keys();
545 // No ticket keys available.
549 auto &keys = ticket_keys->keys;
550 assert(!keys.empty());
553 if (RAND_bytes(iv, EVP_MAX_IV_LENGTH) == 0) {
554 if (LOG_ENABLED(INFO)) {
555 CLOG(INFO, handler) << "session ticket key: RAND_bytes failed";
562 if (LOG_ENABLED(INFO)) {
563 CLOG(INFO, handler) << "encrypt session ticket key: "
564 << util::format_hex(key.data.name);
567 std::copy(std::begin(key.data.name), std::end(key.data.name), key_name);
569 EVP_EncryptInit_ex(ctx, get_config()->tls.ticket.cipher, nullptr,
570 key.data.enc_key.data(), iv);
571 #if OPENSSL_3_0_0_API
572 std::array<OSSL_PARAM, 3> params{
573 OSSL_PARAM_construct_octet_string(
574 OSSL_MAC_PARAM_KEY, key.data.hmac_key.data(), key.hmac_keylen),
575 OSSL_PARAM_construct_utf8_string(
576 OSSL_MAC_PARAM_DIGEST,
577 const_cast<char *>(EVP_MD_get0_name(key.hmac)), 0),
578 OSSL_PARAM_construct_end(),
580 if (!EVP_MAC_CTX_set_params(hctx, params.data())) {
581 if (LOG_ENABLED(INFO)) {
582 CLOG(INFO, handler) << "EVP_MAC_CTX_set_params failed";
586 #else // !OPENSSL_3_0_0_API
587 HMAC_Init_ex(hctx, key.data.hmac_key.data(), key.hmac_keylen, key.hmac,
589 #endif // !OPENSSL_3_0_0_API
594 for (i = 0; i < keys.size(); ++i) {
596 if (std::equal(std::begin(key.data.name), std::end(key.data.name),
602 if (i == keys.size()) {
603 if (LOG_ENABLED(INFO)) {
604 CLOG(INFO, handler) << "session ticket key "
605 << util::format_hex(key_name, 16) << " not found";
610 if (LOG_ENABLED(INFO)) {
611 CLOG(INFO, handler) << "decrypt session ticket key: "
612 << util::format_hex(key_name, 16);
616 #if OPENSSL_3_0_0_API
617 std::array<OSSL_PARAM, 3> params{
618 OSSL_PARAM_construct_octet_string(
619 OSSL_MAC_PARAM_KEY, key.data.hmac_key.data(), key.hmac_keylen),
620 OSSL_PARAM_construct_utf8_string(
621 OSSL_MAC_PARAM_DIGEST, const_cast<char *>(EVP_MD_get0_name(key.hmac)),
623 OSSL_PARAM_construct_end(),
625 if (!EVP_MAC_CTX_set_params(hctx, params.data())) {
626 if (LOG_ENABLED(INFO)) {
627 CLOG(INFO, handler) << "EVP_MAC_CTX_set_params failed";
631 #else // !OPENSSL_3_0_0_API
632 HMAC_Init_ex(hctx, key.data.hmac_key.data(), key.hmac_keylen, key.hmac,
634 #endif // !OPENSSL_3_0_0_API
635 EVP_DecryptInit_ex(ctx, key.cipher, nullptr, key.data.enc_key.data(), iv);
637 #ifdef TLS1_3_VERSION
638 // If ticket_key_cb is not set, OpenSSL always renew ticket for
640 if (SSL_version(ssl) == TLS1_3_VERSION) {
643 #endif // TLS1_3_VERSION
645 return i == 0 ? 1 : 2;
650 void info_callback(const SSL *ssl, int where, int ret) {
651 #ifdef TLS1_3_VERSION
652 // TLSv1.3 has no renegotiation.
653 if (SSL_version(ssl) == TLS1_3_VERSION) {
656 #endif // TLS1_3_VERSION
658 // To mitigate possible DOS attack using lots of renegotiations, we
659 // disable renegotiation. Since OpenSSL does not provide an easy way
660 // to disable it, we check that renegotiation is started in this
662 if (where & SSL_CB_HANDSHAKE_START) {
663 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
664 if (conn && conn->tls.initial_handshake_done) {
665 auto handler = static_cast<ClientHandler *>(conn->data);
666 if (LOG_ENABLED(INFO)) {
667 CLOG(INFO, handler) << "TLS renegotiation started";
669 handler->start_immediate_shutdown();
675 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
677 int alpn_select_proto_cb(SSL *ssl, const unsigned char **out,
678 unsigned char *outlen, const unsigned char *in,
679 unsigned int inlen, void *arg) {
680 // We assume that get_config()->npn_list contains ALPN protocol
681 // identifier sorted by preference order. So we just break when we
682 // found the first overlap.
683 for (const auto &target_proto_id : get_config()->tls.npn_list) {
684 for (auto p = in, end = in + inlen; p < end;) {
685 auto proto_id = p + 1;
688 if (proto_id + proto_len <= end &&
689 util::streq(target_proto_id, StringRef{proto_id, proto_len})) {
691 *out = reinterpret_cast<const unsigned char *>(proto_id);
694 return SSL_TLSEXT_ERR_OK;
701 return SSL_TLSEXT_ERR_NOACK;
704 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
707 # if OPENSSL_VERSION_NUMBER >= 0x10002000L
709 int quic_alpn_select_proto_cb(SSL *ssl, const unsigned char **out,
710 unsigned char *outlen, const unsigned char *in,
711 unsigned int inlen, void *arg) {
712 constexpr StringRef alpnlist[] = {
713 StringRef::from_lit("h3"),
714 StringRef::from_lit("h3-29"),
717 for (auto &alpn : alpnlist) {
718 for (auto p = in, end = in + inlen; p < end;) {
719 auto proto_id = p + 1;
722 if (alpn.size() == proto_len &&
723 memcmp(alpn.byte(), proto_id, alpn.size()) == 0) {
727 return SSL_TLSEXT_ERR_OK;
734 return SSL_TLSEXT_ERR_ALERT_FATAL;
737 # endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
738 #endif // ENABLE_HTTP3
740 #if !LIBRESSL_IN_USE && OPENSSL_VERSION_NUMBER >= 0x10002000L && \
741 !defined(OPENSSL_IS_BORINGSSL)
743 # ifndef TLSEXT_TYPE_signed_certificate_timestamp
744 # define TLSEXT_TYPE_signed_certificate_timestamp 18
745 # endif // !TLSEXT_TYPE_signed_certificate_timestamp
748 int sct_add_cb(SSL *ssl, unsigned int ext_type, unsigned int context,
749 const unsigned char **out, size_t *outlen, X509 *x,
750 size_t chainidx, int *al, void *add_arg) {
751 assert(ext_type == TLSEXT_TYPE_signed_certificate_timestamp);
753 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
754 if (!conn->tls.sct_requested) {
758 if (LOG_ENABLED(INFO)) {
759 LOG(INFO) << "sct_add_cb is called, chainidx=" << chainidx << ", x=" << x
760 << ", context=" << log::hex << context;
763 // We only have SCTs for leaf certificate.
768 auto ssl_ctx = SSL_get_SSL_CTX(ssl);
770 static_cast<TLSContextData *>(SSL_CTX_get_app_data(ssl_ctx));
772 *out = tls_ctx_data->sct_data.data();
773 *outlen = tls_ctx_data->sct_data.size();
780 void sct_free_cb(SSL *ssl, unsigned int ext_type, unsigned int context,
781 const unsigned char *out, void *add_arg) {
782 assert(ext_type == TLSEXT_TYPE_signed_certificate_timestamp);
787 int sct_parse_cb(SSL *ssl, unsigned int ext_type, unsigned int context,
788 const unsigned char *in, size_t inlen, X509 *x,
789 size_t chainidx, int *al, void *parse_arg) {
790 assert(ext_type == TLSEXT_TYPE_signed_certificate_timestamp);
791 // client SHOULD send 0 length extension_data, but it is still
792 // SHOULD, and not MUST.
794 // For TLSv1.3 Certificate message, sct_add_cb is called even if
795 // client has not sent signed_certificate_timestamp extension in its
796 // ClientHello. Explicitly remember that client has included it
798 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
799 conn->tls.sct_requested = true;
805 # if !OPENSSL_1_1_1_API
808 int legacy_sct_add_cb(SSL *ssl, unsigned int ext_type,
809 const unsigned char **out, size_t *outlen, int *al,
811 return sct_add_cb(ssl, ext_type, 0, out, outlen, nullptr, 0, al, add_arg);
816 void legacy_sct_free_cb(SSL *ssl, unsigned int ext_type,
817 const unsigned char *out, void *add_arg) {
818 sct_free_cb(ssl, ext_type, 0, out, add_arg);
823 int legacy_sct_parse_cb(SSL *ssl, unsigned int ext_type,
824 const unsigned char *in, size_t inlen, int *al,
826 return sct_parse_cb(ssl, ext_type, 0, in, inlen, nullptr, 0, al, parse_arg);
830 # endif // !OPENSSL_1_1_1_API
831 #endif // !LIBRESSL_IN_USE && OPENSSL_VERSION_NUMBER >= 0x10002000L &&
832 // !defined(OPENSSL_IS_BORINGSSL)
834 #ifndef OPENSSL_NO_PSK
836 unsigned int psk_server_cb(SSL *ssl, const char *identity, unsigned char *psk,
837 unsigned int max_psk_len) {
838 auto config = get_config();
839 auto &tlsconf = config->tls;
841 auto it = tlsconf.psk_secrets.find(StringRef{identity});
842 if (it == std::end(tlsconf.psk_secrets)) {
846 auto &secret = (*it).second;
847 if (secret.size() > max_psk_len) {
848 LOG(ERROR) << "The size of PSK secret is " << secret.size()
849 << ", but the acceptable maximum size is" << max_psk_len;
853 std::copy(std::begin(secret), std::end(secret), psk);
855 return static_cast<unsigned int>(secret.size());
858 #endif // !OPENSSL_NO_PSK
860 #ifndef OPENSSL_NO_PSK
862 unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity_out,
863 unsigned int max_identity_len, unsigned char *psk,
864 unsigned int max_psk_len) {
865 auto config = get_config();
866 auto &tlsconf = config->tls;
868 auto &identity = tlsconf.client.psk.identity;
869 auto &secret = tlsconf.client.psk.secret;
871 if (identity.empty()) {
875 if (identity.size() + 1 > max_identity_len) {
876 LOG(ERROR) << "The size of PSK identity is " << identity.size()
877 << ", but the acceptable maximum size is " << max_identity_len;
881 if (secret.size() > max_psk_len) {
882 LOG(ERROR) << "The size of PSK secret is " << secret.size()
883 << ", but the acceptable maximum size is " << max_psk_len;
887 *std::copy(std::begin(identity), std::end(identity), identity_out) = '\0';
888 std::copy(std::begin(secret), std::end(secret), psk);
890 return static_cast<unsigned int>(secret.size());
893 #endif // !OPENSSL_NO_PSK
900 constexpr TLSProtocol TLS_PROTOS[] = {
901 TLSProtocol{StringRef::from_lit("TLSv1.2"), SSL_OP_NO_TLSv1_2},
902 TLSProtocol{StringRef::from_lit("TLSv1.1"), SSL_OP_NO_TLSv1_1},
903 TLSProtocol{StringRef::from_lit("TLSv1.0"), SSL_OP_NO_TLSv1}};
905 long int create_tls_proto_mask(const std::vector<StringRef> &tls_proto_list) {
908 for (auto &supported : TLS_PROTOS) {
910 for (auto &name : tls_proto_list) {
911 if (util::strieq(supported.name, name)) {
917 res |= supported.mask;
923 SSL_CTX *create_ssl_context(const char *private_key_file, const char *cert_file,
924 const std::vector<uint8_t> &sct_data
925 #ifdef HAVE_NEVERBLEED
928 #endif // HAVE_NEVERBLEED
930 auto ssl_ctx = SSL_CTX_new(TLS_server_method());
932 LOG(FATAL) << ERR_error_string(ERR_get_error(), nullptr);
936 constexpr auto ssl_opts =
937 (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) | SSL_OP_NO_SSLv2 |
938 SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION |
939 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | SSL_OP_SINGLE_ECDH_USE |
940 SSL_OP_SINGLE_DH_USE |
941 SSL_OP_CIPHER_SERVER_PREFERENCE
942 #if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
943 // The reason for disabling built-in anti-replay in OpenSSL is
944 // that it only works if client gets back to the same server.
945 // The freshness check described in
946 // https://tools.ietf.org/html/rfc8446#section-8.3 is still
948 | SSL_OP_NO_ANTI_REPLAY
949 #endif // OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
952 auto config = mod_config();
953 auto &tlsconf = config->tls;
955 SSL_CTX_set_options(ssl_ctx, ssl_opts | tlsconf.tls_proto_mask);
957 if (nghttp2::tls::ssl_ctx_set_proto_versions(
958 ssl_ctx, tlsconf.min_proto_version, tlsconf.max_proto_version) != 0) {
959 LOG(FATAL) << "Could not set TLS protocol version";
963 const unsigned char sid_ctx[] = "shrpx";
964 SSL_CTX_set_session_id_context(ssl_ctx, sid_ctx, sizeof(sid_ctx) - 1);
965 SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_SERVER);
967 if (!tlsconf.session_cache.memcached.host.empty()) {
968 SSL_CTX_sess_set_new_cb(ssl_ctx, tls_session_new_cb);
969 SSL_CTX_sess_set_get_cb(ssl_ctx, tls_session_get_cb);
972 SSL_CTX_set_timeout(ssl_ctx, tlsconf.session_timeout.count());
974 if (SSL_CTX_set_cipher_list(ssl_ctx, tlsconf.ciphers.c_str()) == 0) {
975 LOG(FATAL) << "SSL_CTX_set_cipher_list " << tlsconf.ciphers
976 << " failed: " << ERR_error_string(ERR_get_error(), nullptr);
980 #if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
981 if (SSL_CTX_set_ciphersuites(ssl_ctx, tlsconf.tls13_ciphers.c_str()) == 0) {
982 LOG(FATAL) << "SSL_CTX_set_ciphersuites " << tlsconf.tls13_ciphers
983 << " failed: " << ERR_error_string(ERR_get_error(), nullptr);
986 #endif // OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
988 #ifndef OPENSSL_NO_EC
989 # if !LIBRESSL_LEGACY_API && OPENSSL_VERSION_NUMBER >= 0x10002000L
990 if (SSL_CTX_set1_curves_list(ssl_ctx, tlsconf.ecdh_curves.c_str()) != 1) {
991 LOG(FATAL) << "SSL_CTX_set1_curves_list " << tlsconf.ecdh_curves
995 # if !defined(OPENSSL_IS_BORINGSSL) && !OPENSSL_1_1_API
996 // It looks like we need this function call for OpenSSL 1.0.2. This
997 // function was deprecated in OpenSSL 1.1.0 and BoringSSL.
998 SSL_CTX_set_ecdh_auto(ssl_ctx, 1);
999 # endif // !defined(OPENSSL_IS_BORINGSSL) && !OPENSSL_1_1_API
1000 # else // LIBRESSL_LEGACY_API || OPENSSL_VERSION_NUBMER < 0x10002000L
1001 // Use P-256, which is sufficiently secure at the time of this
1003 auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
1004 if (ecdh == nullptr) {
1005 LOG(FATAL) << "EC_KEY_new_by_curv_name failed: "
1006 << ERR_error_string(ERR_get_error(), nullptr);
1009 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecdh);
1011 # endif // LIBRESSL_LEGACY_API || OPENSSL_VERSION_NUBMER < 0x10002000L
1012 #endif // OPENSSL_NO_EC
1014 if (!tlsconf.dh_param_file.empty()) {
1015 // Read DH parameters from file
1016 auto bio = BIO_new_file(tlsconf.dh_param_file.c_str(), "rb");
1017 if (bio == nullptr) {
1018 LOG(FATAL) << "BIO_new_file() failed: "
1019 << ERR_error_string(ERR_get_error(), nullptr);
1022 #if OPENSSL_3_0_0_API
1023 EVP_PKEY *dh = nullptr;
1024 auto dctx = OSSL_DECODER_CTX_new_for_pkey(
1025 &dh, "PEM", nullptr, "DH", OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
1028 if (!OSSL_DECODER_from_bio(dctx, bio)) {
1029 LOG(FATAL) << "OSSL_DECODER_from_bio() failed: "
1030 << ERR_error_string(ERR_get_error(), nullptr);
1034 if (SSL_CTX_set0_tmp_dh_pkey(ssl_ctx, dh) != 1) {
1035 LOG(FATAL) << "SSL_CTX_set0_tmp_dh_pkey failed: "
1036 << ERR_error_string(ERR_get_error(), nullptr);
1039 #else // !OPENSSL_3_0_0_API
1040 auto dh = PEM_read_bio_DHparams(bio, nullptr, nullptr, nullptr);
1041 if (dh == nullptr) {
1042 LOG(FATAL) << "PEM_read_bio_DHparams() failed: "
1043 << ERR_error_string(ERR_get_error(), nullptr);
1046 SSL_CTX_set_tmp_dh(ssl_ctx, dh);
1048 #endif // !OPENSSL_3_0_0_API
1052 SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS);
1054 if (SSL_CTX_set_default_verify_paths(ssl_ctx) != 1) {
1055 LOG(WARN) << "Could not load system trusted ca certificates: "
1056 << ERR_error_string(ERR_get_error(), nullptr);
1059 if (!tlsconf.cacert.empty()) {
1060 if (SSL_CTX_load_verify_locations(ssl_ctx, tlsconf.cacert.c_str(),
1062 LOG(FATAL) << "Could not load trusted ca certificates from "
1063 << tlsconf.cacert << ": "
1064 << ERR_error_string(ERR_get_error(), nullptr);
1069 if (!tlsconf.private_key_passwd.empty()) {
1070 SSL_CTX_set_default_passwd_cb(ssl_ctx, ssl_pem_passwd_cb);
1071 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, config);
1074 #ifndef HAVE_NEVERBLEED
1075 if (SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key_file,
1076 SSL_FILETYPE_PEM) != 1) {
1077 LOG(FATAL) << "SSL_CTX_use_PrivateKey_file failed: "
1078 << ERR_error_string(ERR_get_error(), nullptr);
1080 #else // HAVE_NEVERBLEED
1081 std::array<char, NEVERBLEED_ERRBUF_SIZE> errbuf;
1082 if (neverbleed_load_private_key_file(nb, ssl_ctx, private_key_file,
1083 errbuf.data()) != 1) {
1084 LOG(FATAL) << "neverbleed_load_private_key_file failed: " << errbuf.data();
1087 #endif // HAVE_NEVERBLEED
1089 if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_file) != 1) {
1090 LOG(FATAL) << "SSL_CTX_use_certificate_file failed: "
1091 << ERR_error_string(ERR_get_error(), nullptr);
1094 if (SSL_CTX_check_private_key(ssl_ctx) != 1) {
1095 LOG(FATAL) << "SSL_CTX_check_private_key failed: "
1096 << ERR_error_string(ERR_get_error(), nullptr);
1099 if (tlsconf.client_verify.enabled) {
1100 if (!tlsconf.client_verify.cacert.empty()) {
1101 if (SSL_CTX_load_verify_locations(
1102 ssl_ctx, tlsconf.client_verify.cacert.c_str(), nullptr) != 1) {
1104 LOG(FATAL) << "Could not load trusted ca certificates from "
1105 << tlsconf.client_verify.cacert << ": "
1106 << ERR_error_string(ERR_get_error(), nullptr);
1109 // It is heard that SSL_CTX_load_verify_locations() may leave
1110 // error even though it returns success. See
1111 // http://forum.nginx.org/read.php?29,242540
1113 auto list = SSL_load_client_CA_file(tlsconf.client_verify.cacert.c_str());
1115 LOG(FATAL) << "Could not load ca certificates from "
1116 << tlsconf.client_verify.cacert << ": "
1117 << ERR_error_string(ERR_get_error(), nullptr);
1120 SSL_CTX_set_client_CA_list(ssl_ctx, list);
1122 SSL_CTX_set_verify(ssl_ctx,
1123 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE |
1124 SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1127 SSL_CTX_set_tlsext_servername_callback(ssl_ctx, servername_callback);
1128 #if OPENSSL_3_0_0_API
1129 SSL_CTX_set_tlsext_ticket_key_evp_cb(ssl_ctx, ticket_key_cb);
1130 #else // !OPENSSL_3_0_0_API
1131 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx, ticket_key_cb);
1132 #endif // !OPENSSL_3_0_0_API
1133 #ifndef OPENSSL_IS_BORINGSSL
1134 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
1135 #endif // OPENSSL_IS_BORINGSSL
1136 SSL_CTX_set_info_callback(ssl_ctx, info_callback);
1138 #ifdef OPENSSL_IS_BORINGSSL
1139 SSL_CTX_set_early_data_enabled(ssl_ctx, 1);
1140 #endif // OPENSSL_IS_BORINGSSL
1142 // NPN advertisement
1143 #ifndef OPENSSL_NO_NEXTPROTONEG
1144 SSL_CTX_set_next_protos_advertised_cb(ssl_ctx, next_proto_cb, nullptr);
1145 #endif // !OPENSSL_NO_NEXTPROTONEG
1146 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
1147 // ALPN selection callback
1148 SSL_CTX_set_alpn_select_cb(ssl_ctx, alpn_select_proto_cb, nullptr);
1149 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
1151 auto tls_ctx_data = new TLSContextData();
1152 tls_ctx_data->cert_file = cert_file;
1153 tls_ctx_data->sct_data = sct_data;
1155 SSL_CTX_set_app_data(ssl_ctx, tls_ctx_data);
1157 #if !LIBRESSL_IN_USE && OPENSSL_VERSION_NUMBER >= 0x10002000L && \
1158 !defined(OPENSSL_IS_BORINGSSL)
1159 // SSL_extension_supported(TLSEXT_TYPE_signed_certificate_timestamp)
1160 // returns 1, which means OpenSSL internally handles it. But
1161 // OpenSSL handles signed_certificate_timestamp extension specially,
1162 // and it lets custom handler to process the extension.
1163 if (!sct_data.empty()) {
1164 # if OPENSSL_1_1_1_API
1165 // It is not entirely clear to me that SSL_EXT_CLIENT_HELLO is
1166 // required here. sct_parse_cb is called without
1167 // SSL_EXT_CLIENT_HELLO being set. But the passed context value
1168 // is SSL_EXT_CLIENT_HELLO.
1169 if (SSL_CTX_add_custom_ext(
1170 ssl_ctx, TLSEXT_TYPE_signed_certificate_timestamp,
1171 SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO |
1172 SSL_EXT_TLS1_3_CERTIFICATE | SSL_EXT_IGNORE_ON_RESUMPTION,
1173 sct_add_cb, sct_free_cb, nullptr, sct_parse_cb, nullptr) != 1) {
1174 LOG(FATAL) << "SSL_CTX_add_custom_ext failed: "
1175 << ERR_error_string(ERR_get_error(), nullptr);
1178 # else // !OPENSSL_1_1_1_API
1179 if (SSL_CTX_add_server_custom_ext(
1180 ssl_ctx, TLSEXT_TYPE_signed_certificate_timestamp,
1181 legacy_sct_add_cb, legacy_sct_free_cb, nullptr, legacy_sct_parse_cb,
1183 LOG(FATAL) << "SSL_CTX_add_server_custom_ext failed: "
1184 << ERR_error_string(ERR_get_error(), nullptr);
1187 # endif // !OPENSSL_1_1_1_API
1189 #elif defined(OPENSSL_IS_BORINGSSL)
1190 if (!tls_ctx_data->sct_data.empty() &&
1191 SSL_CTX_set_signed_cert_timestamp_list(
1192 ssl_ctx, tls_ctx_data->sct_data.data(),
1193 tls_ctx_data->sct_data.size()) != 1) {
1194 LOG(FATAL) << "SSL_CTX_set_signed_cert_timestamp_list failed: "
1195 << ERR_error_string(ERR_get_error(), nullptr);
1198 #endif // defined(OPENSSL_IS_BORINGSSL)
1200 #if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1201 if (SSL_CTX_set_max_early_data(ssl_ctx, tlsconf.max_early_data) != 1) {
1202 LOG(FATAL) << "SSL_CTX_set_max_early_data failed: "
1203 << ERR_error_string(ERR_get_error(), nullptr);
1206 #endif // OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1208 #ifndef OPENSSL_NO_PSK
1209 SSL_CTX_set_psk_server_callback(ssl_ctx, psk_server_cb);
1210 #endif // !LIBRESSL_NO_PSK
1216 # ifdef HAVE_LIBNGTCP2_CRYPTO_OPENSSL
1218 int quic_set_encryption_secrets(SSL *ssl, OSSL_ENCRYPTION_LEVEL ossl_level,
1219 const uint8_t *rx_secret,
1220 const uint8_t *tx_secret, size_t secretlen) {
1221 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
1222 auto handler = static_cast<ClientHandler *>(conn->data);
1223 auto upstream = static_cast<Http3Upstream *>(handler->get_upstream());
1224 auto level = ngtcp2_crypto_openssl_from_ossl_encryption_level(ossl_level);
1226 if (upstream->on_rx_secret(level, rx_secret, secretlen) != 0) {
1230 if (tx_secret && upstream->on_tx_secret(level, tx_secret, secretlen) != 0) {
1239 int quic_add_handshake_data(SSL *ssl, OSSL_ENCRYPTION_LEVEL ossl_level,
1240 const uint8_t *data, size_t len) {
1241 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
1242 auto handler = static_cast<ClientHandler *>(conn->data);
1243 auto upstream = static_cast<Http3Upstream *>(handler->get_upstream());
1244 auto level = ngtcp2_crypto_openssl_from_ossl_encryption_level(ossl_level);
1246 upstream->add_crypto_data(level, data, len);
1253 int quic_flush_flight(SSL *ssl) { return 1; }
1257 int quic_send_alert(SSL *ssl, OSSL_ENCRYPTION_LEVEL ossl_level, uint8_t alert) {
1258 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
1259 auto handler = static_cast<ClientHandler *>(conn->data);
1260 auto upstream = static_cast<Http3Upstream *>(handler->get_upstream());
1266 upstream->set_tls_alert(alert);
1273 auto quic_method = SSL_QUIC_METHOD{
1274 quic_set_encryption_secrets,
1275 quic_add_handshake_data,
1280 # endif // HAVE_LIBNGTCP2_CRYPTO_OPENSSL
1282 # ifdef HAVE_LIBNGTCP2_CRYPTO_BORINGSSL
1284 int quic_set_read_secret(SSL *ssl, ssl_encryption_level_t ssl_level,
1285 const SSL_CIPHER *cipher, const uint8_t *secret,
1287 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
1288 auto handler = static_cast<ClientHandler *>(conn->data);
1289 auto upstream = static_cast<Http3Upstream *>(handler->get_upstream());
1290 auto level = ngtcp2_crypto_boringssl_from_ssl_encryption_level(ssl_level);
1292 if (upstream->on_rx_secret(level, secret, secretlen) != 0) {
1301 int quic_set_write_secret(SSL *ssl, ssl_encryption_level_t ssl_level,
1302 const SSL_CIPHER *cipher, const uint8_t *secret,
1304 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
1305 auto handler = static_cast<ClientHandler *>(conn->data);
1306 auto upstream = static_cast<Http3Upstream *>(handler->get_upstream());
1307 auto level = ngtcp2_crypto_boringssl_from_ssl_encryption_level(ssl_level);
1309 if (upstream->on_tx_secret(level, secret, secretlen) != 0) {
1318 int quic_add_handshake_data(SSL *ssl, ssl_encryption_level_t ssl_level,
1319 const uint8_t *data, size_t len) {
1320 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
1321 auto handler = static_cast<ClientHandler *>(conn->data);
1322 auto upstream = static_cast<Http3Upstream *>(handler->get_upstream());
1323 auto level = ngtcp2_crypto_boringssl_from_ssl_encryption_level(ssl_level);
1325 upstream->add_crypto_data(level, data, len);
1332 int quic_flush_flight(SSL *ssl) { return 1; }
1336 int quic_send_alert(SSL *ssl, ssl_encryption_level_t level, uint8_t alert) {
1337 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
1338 auto handler = static_cast<ClientHandler *>(conn->data);
1339 auto upstream = static_cast<Http3Upstream *>(handler->get_upstream());
1345 upstream->set_tls_alert(alert);
1352 auto quic_method = SSL_QUIC_METHOD{
1353 quic_set_read_secret, quic_set_write_secret, quic_add_handshake_data,
1354 quic_flush_flight, quic_send_alert,
1357 # endif // HAVE_LIBNGTCP2_CRYPTO_BORINGSSL
1359 SSL_CTX *create_quic_ssl_context(const char *private_key_file,
1360 const char *cert_file,
1361 const std::vector<uint8_t> &sct_data
1362 # ifdef HAVE_NEVERBLEED
1365 # endif // HAVE_NEVERBLEED
1367 auto ssl_ctx = SSL_CTX_new(TLS_server_method());
1369 LOG(FATAL) << ERR_error_string(ERR_get_error(), nullptr);
1373 constexpr auto ssl_opts =
1374 (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
1375 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | SSL_OP_SINGLE_ECDH_USE |
1376 SSL_OP_SINGLE_DH_USE |
1377 SSL_OP_CIPHER_SERVER_PREFERENCE
1378 # if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1379 // The reason for disabling built-in anti-replay in OpenSSL is
1380 // that it only works if client gets back to the same server.
1381 // The freshness check described in
1382 // https://tools.ietf.org/html/rfc8446#section-8.3 is still
1384 | SSL_OP_NO_ANTI_REPLAY
1385 # endif // OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1388 auto config = mod_config();
1389 auto &tlsconf = config->tls;
1391 SSL_CTX_set_options(ssl_ctx, ssl_opts);
1393 SSL_CTX_set_min_proto_version(ssl_ctx, TLS1_3_VERSION);
1394 SSL_CTX_set_max_proto_version(ssl_ctx, TLS1_3_VERSION);
1396 const unsigned char sid_ctx[] = "shrpx";
1397 SSL_CTX_set_session_id_context(ssl_ctx, sid_ctx, sizeof(sid_ctx) - 1);
1398 SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_OFF);
1400 SSL_CTX_set_timeout(ssl_ctx, tlsconf.session_timeout.count());
1402 if (SSL_CTX_set_cipher_list(ssl_ctx, tlsconf.ciphers.c_str()) == 0) {
1403 LOG(FATAL) << "SSL_CTX_set_cipher_list " << tlsconf.ciphers
1404 << " failed: " << ERR_error_string(ERR_get_error(), nullptr);
1408 # if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1409 if (SSL_CTX_set_ciphersuites(ssl_ctx, tlsconf.tls13_ciphers.c_str()) == 0) {
1410 LOG(FATAL) << "SSL_CTX_set_ciphersuites " << tlsconf.tls13_ciphers
1411 << " failed: " << ERR_error_string(ERR_get_error(), nullptr);
1414 # endif // OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1416 # ifndef OPENSSL_NO_EC
1417 # if !LIBRESSL_LEGACY_API && OPENSSL_VERSION_NUMBER >= 0x10002000L
1418 if (SSL_CTX_set1_curves_list(ssl_ctx, tlsconf.ecdh_curves.c_str()) != 1) {
1419 LOG(FATAL) << "SSL_CTX_set1_curves_list " << tlsconf.ecdh_curves
1423 # if !defined(OPENSSL_IS_BORINGSSL) && !OPENSSL_1_1_API
1424 // It looks like we need this function call for OpenSSL 1.0.2. This
1425 // function was deprecated in OpenSSL 1.1.0 and BoringSSL.
1426 SSL_CTX_set_ecdh_auto(ssl_ctx, 1);
1427 # endif // !defined(OPENSSL_IS_BORINGSSL) && !OPENSSL_1_1_API
1428 # else // LIBRESSL_LEGACY_API || OPENSSL_VERSION_NUBMER < 0x10002000L
1429 // Use P-256, which is sufficiently secure at the time of this
1431 auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
1432 if (ecdh == nullptr) {
1433 LOG(FATAL) << "EC_KEY_new_by_curv_name failed: "
1434 << ERR_error_string(ERR_get_error(), nullptr);
1437 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecdh);
1439 # endif // LIBRESSL_LEGACY_API || OPENSSL_VERSION_NUBMER < 0x10002000L
1440 # endif // OPENSSL_NO_EC
1442 if (!tlsconf.dh_param_file.empty()) {
1443 // Read DH parameters from file
1444 auto bio = BIO_new_file(tlsconf.dh_param_file.c_str(), "rb");
1445 if (bio == nullptr) {
1446 LOG(FATAL) << "BIO_new_file() failed: "
1447 << ERR_error_string(ERR_get_error(), nullptr);
1450 # if OPENSSL_3_0_0_API
1451 EVP_PKEY *dh = nullptr;
1452 auto dctx = OSSL_DECODER_CTX_new_for_pkey(
1453 &dh, "PEM", nullptr, "DH", OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
1456 if (!OSSL_DECODER_from_bio(dctx, bio)) {
1457 LOG(FATAL) << "OSSL_DECODER_from_bio() failed: "
1458 << ERR_error_string(ERR_get_error(), nullptr);
1462 if (SSL_CTX_set0_tmp_dh_pkey(ssl_ctx, dh) != 1) {
1463 LOG(FATAL) << "SSL_CTX_set0_tmp_dh_pkey failed: "
1464 << ERR_error_string(ERR_get_error(), nullptr);
1467 # else // !OPENSSL_3_0_0_API
1468 auto dh = PEM_read_bio_DHparams(bio, nullptr, nullptr, nullptr);
1469 if (dh == nullptr) {
1470 LOG(FATAL) << "PEM_read_bio_DHparams() failed: "
1471 << ERR_error_string(ERR_get_error(), nullptr);
1474 SSL_CTX_set_tmp_dh(ssl_ctx, dh);
1476 # endif // !OPENSSL_3_0_0_API
1480 SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS);
1482 if (SSL_CTX_set_default_verify_paths(ssl_ctx) != 1) {
1483 LOG(WARN) << "Could not load system trusted ca certificates: "
1484 << ERR_error_string(ERR_get_error(), nullptr);
1487 if (!tlsconf.cacert.empty()) {
1488 if (SSL_CTX_load_verify_locations(ssl_ctx, tlsconf.cacert.c_str(),
1490 LOG(FATAL) << "Could not load trusted ca certificates from "
1491 << tlsconf.cacert << ": "
1492 << ERR_error_string(ERR_get_error(), nullptr);
1497 if (!tlsconf.private_key_passwd.empty()) {
1498 SSL_CTX_set_default_passwd_cb(ssl_ctx, ssl_pem_passwd_cb);
1499 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, config);
1502 # ifndef HAVE_NEVERBLEED
1503 if (SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key_file,
1504 SSL_FILETYPE_PEM) != 1) {
1505 LOG(FATAL) << "SSL_CTX_use_PrivateKey_file failed: "
1506 << ERR_error_string(ERR_get_error(), nullptr);
1508 # else // HAVE_NEVERBLEED
1509 std::array<char, NEVERBLEED_ERRBUF_SIZE> errbuf;
1510 if (neverbleed_load_private_key_file(nb, ssl_ctx, private_key_file,
1511 errbuf.data()) != 1) {
1512 LOG(FATAL) << "neverbleed_load_private_key_file failed: " << errbuf.data();
1515 # endif // HAVE_NEVERBLEED
1517 if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_file) != 1) {
1518 LOG(FATAL) << "SSL_CTX_use_certificate_file failed: "
1519 << ERR_error_string(ERR_get_error(), nullptr);
1522 if (SSL_CTX_check_private_key(ssl_ctx) != 1) {
1523 LOG(FATAL) << "SSL_CTX_check_private_key failed: "
1524 << ERR_error_string(ERR_get_error(), nullptr);
1527 if (tlsconf.client_verify.enabled) {
1528 if (!tlsconf.client_verify.cacert.empty()) {
1529 if (SSL_CTX_load_verify_locations(
1530 ssl_ctx, tlsconf.client_verify.cacert.c_str(), nullptr) != 1) {
1532 LOG(FATAL) << "Could not load trusted ca certificates from "
1533 << tlsconf.client_verify.cacert << ": "
1534 << ERR_error_string(ERR_get_error(), nullptr);
1537 // It is heard that SSL_CTX_load_verify_locations() may leave
1538 // error even though it returns success. See
1539 // http://forum.nginx.org/read.php?29,242540
1541 auto list = SSL_load_client_CA_file(tlsconf.client_verify.cacert.c_str());
1543 LOG(FATAL) << "Could not load ca certificates from "
1544 << tlsconf.client_verify.cacert << ": "
1545 << ERR_error_string(ERR_get_error(), nullptr);
1548 SSL_CTX_set_client_CA_list(ssl_ctx, list);
1550 SSL_CTX_set_verify(ssl_ctx,
1551 SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE |
1552 SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1555 SSL_CTX_set_tlsext_servername_callback(ssl_ctx, servername_callback);
1556 # if OPENSSL_3_0_0_API
1557 SSL_CTX_set_tlsext_ticket_key_evp_cb(ssl_ctx, ticket_key_cb);
1558 # else // !OPENSSL_3_0_0_API
1559 SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx, ticket_key_cb);
1560 # endif // !OPENSSL_3_0_0_API
1561 # ifndef OPENSSL_IS_BORINGSSL
1562 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
1563 # endif // OPENSSL_IS_BORINGSSL
1565 # if OPENSSL_VERSION_NUMBER >= 0x10002000L
1566 // ALPN selection callback
1567 SSL_CTX_set_alpn_select_cb(ssl_ctx, quic_alpn_select_proto_cb, nullptr);
1568 # endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
1570 auto tls_ctx_data = new TLSContextData();
1571 tls_ctx_data->cert_file = cert_file;
1572 tls_ctx_data->sct_data = sct_data;
1574 SSL_CTX_set_app_data(ssl_ctx, tls_ctx_data);
1576 # if !LIBRESSL_IN_USE && OPENSSL_VERSION_NUMBER >= 0x10002000L && \
1577 !defined(OPENSSL_IS_BORINGSSL)
1578 // SSL_extension_supported(TLSEXT_TYPE_signed_certificate_timestamp)
1579 // returns 1, which means OpenSSL internally handles it. But
1580 // OpenSSL handles signed_certificate_timestamp extension specially,
1581 // and it lets custom handler to process the extension.
1582 if (!sct_data.empty()) {
1583 # if OPENSSL_1_1_1_API
1584 // It is not entirely clear to me that SSL_EXT_CLIENT_HELLO is
1585 // required here. sct_parse_cb is called without
1586 // SSL_EXT_CLIENT_HELLO being set. But the passed context value
1587 // is SSL_EXT_CLIENT_HELLO.
1588 if (SSL_CTX_add_custom_ext(
1589 ssl_ctx, TLSEXT_TYPE_signed_certificate_timestamp,
1590 SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO |
1591 SSL_EXT_TLS1_3_CERTIFICATE | SSL_EXT_IGNORE_ON_RESUMPTION,
1592 sct_add_cb, sct_free_cb, nullptr, sct_parse_cb, nullptr) != 1) {
1593 LOG(FATAL) << "SSL_CTX_add_custom_ext failed: "
1594 << ERR_error_string(ERR_get_error(), nullptr);
1597 # else // !OPENSSL_1_1_1_API
1598 if (SSL_CTX_add_server_custom_ext(
1599 ssl_ctx, TLSEXT_TYPE_signed_certificate_timestamp,
1600 legacy_sct_add_cb, legacy_sct_free_cb, nullptr, legacy_sct_parse_cb,
1602 LOG(FATAL) << "SSL_CTX_add_server_custom_ext failed: "
1603 << ERR_error_string(ERR_get_error(), nullptr);
1606 # endif // !OPENSSL_1_1_1_API
1608 # elif defined(OPENSSL_IS_BORINGSSL)
1609 if (!tls_ctx_data->sct_data.empty() &&
1610 SSL_CTX_set_signed_cert_timestamp_list(
1611 ssl_ctx, tls_ctx_data->sct_data.data(),
1612 tls_ctx_data->sct_data.size()) != 1) {
1613 LOG(FATAL) << "SSL_CTX_set_signed_cert_timestamp_list failed: "
1614 << ERR_error_string(ERR_get_error(), nullptr);
1617 # endif // defined(OPENSSL_IS_BORINGSSL)
1619 # if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1620 auto &quicconf = config->quic;
1622 if (quicconf.upstream.early_data &&
1623 SSL_CTX_set_max_early_data(ssl_ctx,
1624 std::numeric_limits<uint32_t>::max()) != 1) {
1625 LOG(FATAL) << "SSL_CTX_set_max_early_data failed: "
1626 << ERR_error_string(ERR_get_error(), nullptr);
1629 # endif // OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1631 # ifndef OPENSSL_NO_PSK
1632 SSL_CTX_set_psk_server_callback(ssl_ctx, psk_server_cb);
1633 # endif // !LIBRESSL_NO_PSK
1635 SSL_CTX_set_quic_method(ssl_ctx, &quic_method);
1639 #endif // ENABLE_HTTP3
1642 int select_h2_next_proto_cb(SSL *ssl, unsigned char **out,
1643 unsigned char *outlen, const unsigned char *in,
1644 unsigned int inlen, void *arg) {
1645 if (!util::select_h2(const_cast<const unsigned char **>(out), outlen, in,
1647 return SSL_TLSEXT_ERR_NOACK;
1650 return SSL_TLSEXT_ERR_OK;
1655 int select_h1_next_proto_cb(SSL *ssl, unsigned char **out,
1656 unsigned char *outlen, const unsigned char *in,
1657 unsigned int inlen, void *arg) {
1658 auto end = in + inlen;
1660 if (util::streq(NGHTTP2_H1_1_ALPN, StringRef{in, in + (in[0] + 1)})) {
1661 *out = const_cast<unsigned char *>(in) + 1;
1663 return SSL_TLSEXT_ERR_OK;
1668 return SSL_TLSEXT_ERR_NOACK;
1673 int select_next_proto_cb(SSL *ssl, unsigned char **out, unsigned char *outlen,
1674 const unsigned char *in, unsigned int inlen,
1676 auto conn = static_cast<Connection *>(SSL_get_app_data(ssl));
1677 switch (conn->proto) {
1679 return select_h1_next_proto_cb(ssl, out, outlen, in, inlen, arg);
1681 return select_h2_next_proto_cb(ssl, out, outlen, in, inlen, arg);
1683 return SSL_TLSEXT_ERR_NOACK;
1688 SSL_CTX *create_ssl_client_context(
1689 #ifdef HAVE_NEVERBLEED
1691 #endif // HAVE_NEVERBLEED
1692 const StringRef &cacert, const StringRef &cert_file,
1693 const StringRef &private_key_file,
1694 int (*next_proto_select_cb)(SSL *s, unsigned char **out,
1695 unsigned char *outlen, const unsigned char *in,
1696 unsigned int inlen, void *arg)) {
1697 auto ssl_ctx = SSL_CTX_new(TLS_client_method());
1699 LOG(FATAL) << ERR_error_string(ERR_get_error(), nullptr);
1703 constexpr auto ssl_opts = (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
1704 SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
1705 SSL_OP_NO_COMPRESSION |
1706 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION;
1708 auto &tlsconf = get_config()->tls;
1710 SSL_CTX_set_options(ssl_ctx, ssl_opts | tlsconf.tls_proto_mask);
1712 SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_CLIENT |
1713 SSL_SESS_CACHE_NO_INTERNAL_STORE);
1714 SSL_CTX_sess_set_new_cb(ssl_ctx, tls_session_client_new_cb);
1716 if (nghttp2::tls::ssl_ctx_set_proto_versions(
1717 ssl_ctx, tlsconf.min_proto_version, tlsconf.max_proto_version) != 0) {
1718 LOG(FATAL) << "Could not set TLS protocol version";
1722 if (SSL_CTX_set_cipher_list(ssl_ctx, tlsconf.client.ciphers.c_str()) == 0) {
1723 LOG(FATAL) << "SSL_CTX_set_cipher_list " << tlsconf.client.ciphers
1724 << " failed: " << ERR_error_string(ERR_get_error(), nullptr);
1728 #if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1729 if (SSL_CTX_set_ciphersuites(ssl_ctx, tlsconf.client.tls13_ciphers.c_str()) ==
1731 LOG(FATAL) << "SSL_CTX_set_ciphersuites " << tlsconf.client.tls13_ciphers
1732 << " failed: " << ERR_error_string(ERR_get_error(), nullptr);
1735 #endif // OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
1737 SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS);
1739 if (SSL_CTX_set_default_verify_paths(ssl_ctx) != 1) {
1740 LOG(WARN) << "Could not load system trusted ca certificates: "
1741 << ERR_error_string(ERR_get_error(), nullptr);
1744 if (!cacert.empty()) {
1745 if (SSL_CTX_load_verify_locations(ssl_ctx, cacert.c_str(), nullptr) != 1) {
1747 LOG(FATAL) << "Could not load trusted ca certificates from " << cacert
1748 << ": " << ERR_error_string(ERR_get_error(), nullptr);
1753 if (!tlsconf.insecure) {
1754 SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
1757 if (!cert_file.empty()) {
1758 if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_file.c_str()) != 1) {
1760 LOG(FATAL) << "Could not load client certificate from " << cert_file
1761 << ": " << ERR_error_string(ERR_get_error(), nullptr);
1766 if (!private_key_file.empty()) {
1767 #ifndef HAVE_NEVERBLEED
1768 if (SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key_file.c_str(),
1769 SSL_FILETYPE_PEM) != 1) {
1770 LOG(FATAL) << "Could not load client private key from "
1771 << private_key_file << ": "
1772 << ERR_error_string(ERR_get_error(), nullptr);
1775 #else // HAVE_NEVERBLEED
1776 std::array<char, NEVERBLEED_ERRBUF_SIZE> errbuf;
1777 if (neverbleed_load_private_key_file(nb, ssl_ctx, private_key_file.c_str(),
1778 errbuf.data()) != 1) {
1779 LOG(FATAL) << "neverbleed_load_private_key_file: could not load client "
1781 << private_key_file << ": " << errbuf.data();
1784 #endif // HAVE_NEVERBLEED
1787 #ifndef OPENSSL_NO_PSK
1788 SSL_CTX_set_psk_client_callback(ssl_ctx, psk_client_cb);
1789 #endif // !OPENSSL_NO_PSK
1791 // NPN selection callback. This is required to set SSL_CTX because
1792 // OpenSSL does not offer SSL_set_next_proto_select_cb.
1793 #ifndef OPENSSL_NO_NEXTPROTONEG
1794 SSL_CTX_set_next_proto_select_cb(ssl_ctx, next_proto_select_cb, nullptr);
1795 #endif // !OPENSSL_NO_NEXTPROTONEG
1800 SSL *create_ssl(SSL_CTX *ssl_ctx) {
1801 auto ssl = SSL_new(ssl_ctx);
1803 LOG(ERROR) << "SSL_new() failed: "
1804 << ERR_error_string(ERR_get_error(), nullptr);
1811 ClientHandler *accept_connection(Worker *worker, int fd, sockaddr *addr,
1812 int addrlen, const UpstreamAddr *faddr) {
1813 std::array<char, NI_MAXHOST> host;
1814 std::array<char, NI_MAXSERV> service;
1817 if (addr->sa_family == AF_UNIX) {
1818 std::copy_n("localhost", sizeof("localhost"), std::begin(host));
1821 rv = getnameinfo(addr, addrlen, host.data(), host.size(), service.data(),
1822 service.size(), NI_NUMERICHOST | NI_NUMERICSERV);
1824 LOG(ERROR) << "getnameinfo() failed: " << gai_strerror(rv);
1829 rv = util::make_socket_nodelay(fd);
1831 LOG(WARN) << "Setting option TCP_NODELAY failed: errno=" << errno;
1836 auto ssl_ctx = worker->get_sv_ssl_ctx();
1840 ssl = create_ssl(ssl_ctx);
1844 // Disable TLS session ticket if we don't have working ticket
1846 if (!worker->get_ticket_keys()) {
1847 SSL_set_options(ssl, SSL_OP_NO_TICKET);
1851 return new ClientHandler(worker, fd, ssl, StringRef{host.data()},
1852 StringRef{service.data()}, addr->sa_family, faddr);
1855 bool tls_hostname_match(const StringRef &pattern, const StringRef &hostname) {
1856 auto ptWildcard = std::find(std::begin(pattern), std::end(pattern), '*');
1857 if (ptWildcard == std::end(pattern)) {
1858 return util::strieq(pattern, hostname);
1861 auto ptLeftLabelEnd = std::find(std::begin(pattern), std::end(pattern), '.');
1862 auto wildcardEnabled = true;
1863 // Do case-insensitive match. At least 2 dots are required to enable
1864 // wildcard match. Also wildcard must be in the left-most label.
1865 // Don't attempt to match a presented identifier where the wildcard
1866 // character is embedded within an A-label.
1867 if (ptLeftLabelEnd == std::end(pattern) ||
1868 std::find(ptLeftLabelEnd + 1, std::end(pattern), '.') ==
1869 std::end(pattern) ||
1870 ptLeftLabelEnd < ptWildcard || util::istarts_with_l(pattern, "xn--")) {
1871 wildcardEnabled = false;
1874 if (!wildcardEnabled) {
1875 return util::strieq(pattern, hostname);
1878 auto hnLeftLabelEnd =
1879 std::find(std::begin(hostname), std::end(hostname), '.');
1880 if (hnLeftLabelEnd == std::end(hostname) ||
1881 !util::strieq(StringRef{ptLeftLabelEnd, std::end(pattern)},
1882 StringRef{hnLeftLabelEnd, std::end(hostname)})) {
1885 // Perform wildcard match. Here '*' must match at least one
1887 if (hnLeftLabelEnd - std::begin(hostname) <
1888 ptLeftLabelEnd - std::begin(pattern)) {
1891 return util::istarts_with(StringRef{std::begin(hostname), hnLeftLabelEnd},
1892 StringRef{std::begin(pattern), ptWildcard}) &&
1893 util::iends_with(StringRef{std::begin(hostname), hnLeftLabelEnd},
1894 StringRef{ptWildcard + 1, ptLeftLabelEnd});
1898 // if return value is not empty, StringRef.c_str() must be freed using
1900 StringRef get_common_name(X509 *cert) {
1901 auto subjectname = X509_get_subject_name(cert);
1903 LOG(WARN) << "Could not get X509 name object from the certificate.";
1908 lastpos = X509_NAME_get_index_by_NID(subjectname, NID_commonName, lastpos);
1909 if (lastpos == -1) {
1912 auto entry = X509_NAME_get_entry(subjectname, lastpos);
1915 auto plen = ASN1_STRING_to_UTF8(&p, X509_NAME_ENTRY_get_data(entry));
1919 if (std::find(p, p + plen, '\0') != p + plen) {
1920 // Embedded NULL is not permitted.
1924 LOG(WARN) << "X509 name is empty";
1929 return StringRef{p, static_cast<size_t>(plen)};
1936 int verify_numeric_hostname(X509 *cert, const StringRef &hostname,
1937 const Address *addr) {
1939 switch (addr->su.storage.ss_family) {
1941 saddr = &addr->su.in.sin_addr;
1944 saddr = &addr->su.in6.sin6_addr;
1950 auto altnames = static_cast<GENERAL_NAMES *>(
1951 X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
1953 auto altnames_deleter = defer(GENERAL_NAMES_free, altnames);
1954 size_t n = sk_GENERAL_NAME_num(altnames);
1955 auto ip_found = false;
1956 for (size_t i = 0; i < n; ++i) {
1957 auto altname = sk_GENERAL_NAME_value(altnames, i);
1958 if (altname->type != GEN_IPADD) {
1962 auto ip_addr = altname->d.iPAddress->data;
1966 size_t ip_addrlen = altname->d.iPAddress->length;
1969 if (addr->len == ip_addrlen && memcmp(saddr, ip_addr, ip_addrlen) == 0) {
1979 auto cn = get_common_name(cert);
1984 // cn is not NULL terminated
1985 auto rv = util::streq(hostname, cn);
1986 OPENSSL_free(const_cast<char *>(cn.c_str()));
1997 int verify_hostname(X509 *cert, const StringRef &hostname,
1998 const Address *addr) {
1999 if (util::numeric_host(hostname.c_str())) {
2000 return verify_numeric_hostname(cert, hostname, addr);
2003 auto altnames = static_cast<GENERAL_NAMES *>(
2004 X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
2006 auto dns_found = false;
2007 auto altnames_deleter = defer(GENERAL_NAMES_free, altnames);
2008 size_t n = sk_GENERAL_NAME_num(altnames);
2009 for (size_t i = 0; i < n; ++i) {
2010 auto altname = sk_GENERAL_NAME_value(altnames, i);
2011 if (altname->type != GEN_DNS) {
2015 auto name = ASN1_STRING_get0_data(altname->d.ia5);
2020 auto len = ASN1_STRING_length(altname->d.ia5);
2024 if (std::find(name, name + len, '\0') != name + len) {
2025 // Embedded NULL is not permitted.
2029 if (name[len - 1] == '.') {
2038 if (tls_hostname_match(StringRef{name, static_cast<size_t>(len)},
2044 // RFC 6125, section 6.4.4. says that client MUST not seek a match
2045 // for CN if a dns dNSName is found.
2051 auto cn = get_common_name(cert);
2056 if (cn[cn.size() - 1] == '.') {
2057 if (cn.size() == 1) {
2058 OPENSSL_free(const_cast<char *>(cn.c_str()));
2062 cn = StringRef{cn.c_str(), cn.size() - 1};
2065 auto rv = tls_hostname_match(cn, hostname);
2066 OPENSSL_free(const_cast<char *>(cn.c_str()));
2072 int check_cert(SSL *ssl, const Address *addr, const StringRef &host) {
2073 #if OPENSSL_3_0_0_API
2074 auto cert = SSL_get0_peer_certificate(ssl);
2075 #else // !OPENSSL_3_0_0_API
2076 auto cert = SSL_get_peer_certificate(ssl);
2077 #endif // !OPENSSL_3_0_0_API
2079 // By the protocol definition, TLS server always sends certificate
2080 // if it has. If certificate cannot be retrieved, authentication
2081 // without certificate is used, such as PSK.
2084 #if !OPENSSL_3_0_0_API
2085 auto cert_deleter = defer(X509_free, cert);
2086 #endif // !OPENSSL_3_0_0_API
2088 if (verify_hostname(cert, host, addr) != 0) {
2089 LOG(ERROR) << "Certificate verification failed: hostname does not match";
2095 int check_cert(SSL *ssl, const DownstreamAddr *addr, const Address *raddr) {
2097 addr->sni.empty() ? StringRef{addr->host} : StringRef{addr->sni};
2098 return check_cert(ssl, raddr, hostname);
2101 CertLookupTree::CertLookupTree() {}
2103 ssize_t CertLookupTree::add_cert(const StringRef &hostname, size_t idx) {
2104 std::array<uint8_t, NI_MAXHOST> buf;
2106 // NI_MAXHOST includes terminal NULL byte
2107 if (hostname.empty() || hostname.size() + 1 > buf.size()) {
2111 auto wildcard_it = std::find(std::begin(hostname), std::end(hostname), '*');
2112 if (wildcard_it != std::end(hostname) &&
2113 wildcard_it + 1 != std::end(hostname)) {
2114 auto wildcard_prefix = StringRef{std::begin(hostname), wildcard_it};
2115 auto wildcard_suffix = StringRef{wildcard_it + 1, std::end(hostname)};
2117 auto rev_suffix = StringRef{std::begin(buf),
2118 std::reverse_copy(std::begin(wildcard_suffix),
2119 std::end(wildcard_suffix),
2122 WildcardPattern *wpat;
2124 if (wildcard_patterns_.size() !=
2125 rev_wildcard_router_.add_route(rev_suffix, wildcard_patterns_.size())) {
2126 auto wcidx = rev_wildcard_router_.match(rev_suffix);
2128 assert(wcidx != -1);
2130 wpat = &wildcard_patterns_[wcidx];
2132 wildcard_patterns_.emplace_back();
2133 wpat = &wildcard_patterns_.back();
2136 auto rev_prefix = StringRef{std::begin(buf),
2137 std::reverse_copy(std::begin(wildcard_prefix),
2138 std::end(wildcard_prefix),
2141 for (auto &p : wpat->rev_prefix) {
2142 if (p.prefix == rev_prefix) {
2147 wpat->rev_prefix.emplace_back(rev_prefix, idx);
2152 return router_.add_route(hostname, idx);
2155 ssize_t CertLookupTree::lookup(const StringRef &hostname) {
2156 std::array<uint8_t, NI_MAXHOST> buf;
2158 // NI_MAXHOST includes terminal NULL byte
2159 if (hostname.empty() || hostname.size() + 1 > buf.size()) {
2163 // Always prefer exact match
2164 auto idx = router_.match(hostname);
2169 if (wildcard_patterns_.empty()) {
2173 ssize_t best_idx = -1;
2174 size_t best_prefixlen = 0;
2175 const RNode *last_node = nullptr;
2177 auto rev_host = StringRef{
2178 std::begin(buf), std::reverse_copy(std::begin(hostname),
2179 std::end(hostname), std::begin(buf))};
2185 rev_wildcard_router_.match_prefix(&nread, &last_node, rev_host);
2190 // '*' must match at least one byte
2191 if (nread == rev_host.size()) {
2195 rev_host = StringRef{std::begin(rev_host) + nread, std::end(rev_host)};
2197 auto rev_prefix = StringRef{std::begin(rev_host) + 1, std::end(rev_host)};
2199 auto &wpat = wildcard_patterns_[wcidx];
2200 for (auto &wprefix : wpat.rev_prefix) {
2201 if (!util::ends_with(rev_prefix, wprefix.prefix)) {
2206 wprefix.prefix.size() +
2207 (reinterpret_cast<const uint8_t *>(&rev_host[0]) - &buf[0]);
2209 // Breaking a tie with longer suffix
2210 if (prefixlen < best_prefixlen) {
2214 best_idx = wprefix.idx;
2215 best_prefixlen = prefixlen;
2220 void CertLookupTree::dump() const {
2221 std::cerr << "exact:" << std::endl;
2223 std::cerr << "wildcard suffix (reversed):" << std::endl;
2224 rev_wildcard_router_.dump();
2227 int cert_lookup_tree_add_ssl_ctx(
2228 CertLookupTree *lt, std::vector<std::vector<SSL_CTX *>> &indexed_ssl_ctx,
2230 std::array<uint8_t, NI_MAXHOST> buf;
2232 #if LIBRESSL_2_7_API || \
2233 (!LIBRESSL_IN_USE && OPENSSL_VERSION_NUMBER >= 0x10002000L)
2234 auto cert = SSL_CTX_get0_certificate(ssl_ctx);
2235 #else // !LIBRESSL_2_7_API && OPENSSL_VERSION_NUMBER < 0x10002000L
2237 static_cast<TLSContextData *>(SSL_CTX_get_app_data(ssl_ctx));
2238 auto cert = load_certificate(tls_ctx_data->cert_file);
2239 auto cert_deleter = defer(X509_free, cert);
2240 #endif // !LIBRESSL_2_7_API && OPENSSL_VERSION_NUMBER < 0x10002000L
2242 auto altnames = static_cast<GENERAL_NAMES *>(
2243 X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
2245 auto altnames_deleter = defer(GENERAL_NAMES_free, altnames);
2246 size_t n = sk_GENERAL_NAME_num(altnames);
2247 auto dns_found = false;
2248 for (size_t i = 0; i < n; ++i) {
2249 auto altname = sk_GENERAL_NAME_value(altnames, i);
2250 if (altname->type != GEN_DNS) {
2254 auto name = ASN1_STRING_get0_data(altname->d.ia5);
2259 auto len = ASN1_STRING_length(altname->d.ia5);
2263 if (std::find(name, name + len, '\0') != name + len) {
2264 // Embedded NULL is not permitted.
2268 if (name[len - 1] == '.') {
2277 if (static_cast<size_t>(len) + 1 > buf.size()) {
2281 auto end_buf = std::copy_n(name, len, std::begin(buf));
2282 util::inp_strlower(std::begin(buf), end_buf);
2284 auto idx = lt->add_cert(StringRef{std::begin(buf), end_buf},
2285 indexed_ssl_ctx.size());
2290 if (static_cast<size_t>(idx) < indexed_ssl_ctx.size()) {
2291 indexed_ssl_ctx[idx].push_back(ssl_ctx);
2293 assert(static_cast<size_t>(idx) == indexed_ssl_ctx.size());
2294 indexed_ssl_ctx.emplace_back(std::vector<SSL_CTX *>{ssl_ctx});
2298 // Don't bother CN if we have dNSName.
2304 auto cn = get_common_name(cert);
2309 if (cn[cn.size() - 1] == '.') {
2310 if (cn.size() == 1) {
2311 OPENSSL_free(const_cast<char *>(cn.c_str()));
2316 cn = StringRef{cn.c_str(), cn.size() - 1};
2319 auto end_buf = std::copy(std::begin(cn), std::end(cn), std::begin(buf));
2321 OPENSSL_free(const_cast<char *>(cn.c_str()));
2323 util::inp_strlower(std::begin(buf), end_buf);
2326 lt->add_cert(StringRef{std::begin(buf), end_buf}, indexed_ssl_ctx.size());
2331 if (static_cast<size_t>(idx) < indexed_ssl_ctx.size()) {
2332 indexed_ssl_ctx[idx].push_back(ssl_ctx);
2334 assert(static_cast<size_t>(idx) == indexed_ssl_ctx.size());
2335 indexed_ssl_ctx.emplace_back(std::vector<SSL_CTX *>{ssl_ctx});
2341 bool in_proto_list(const std::vector<StringRef> &protos,
2342 const StringRef &needle) {
2343 for (auto &proto : protos) {
2344 if (util::streq(proto, needle)) {
2351 bool upstream_tls_enabled(const ConnectionConfig &connconf) {
2353 if (connconf.quic_listener.addrs.size()) {
2356 #endif // ENABLE_HTTP3
2358 const auto &faddrs = connconf.listener.addrs;
2359 return std::any_of(std::begin(faddrs), std::end(faddrs),
2360 [](const UpstreamAddr &faddr) { return faddr.tls; });
2363 X509 *load_certificate(const char *filename) {
2364 auto bio = BIO_new(BIO_s_file());
2366 fprintf(stderr, "BIO_new() failed\n");
2369 auto bio_deleter = defer(BIO_vfree, bio);
2370 if (!BIO_read_filename(bio, filename)) {
2371 fprintf(stderr, "Could not read certificate file '%s'\n", filename);
2374 auto cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
2376 fprintf(stderr, "Could not read X509 structure from file '%s'\n", filename);
2384 setup_server_ssl_context(std::vector<SSL_CTX *> &all_ssl_ctx,
2385 std::vector<std::vector<SSL_CTX *>> &indexed_ssl_ctx,
2386 CertLookupTree *cert_tree
2387 #ifdef HAVE_NEVERBLEED
2390 #endif // HAVE_NEVERBLEED
2392 auto config = get_config();
2394 if (!upstream_tls_enabled(config->conn)) {
2398 auto &tlsconf = config->tls;
2400 auto ssl_ctx = create_ssl_context(tlsconf.private_key_file.c_str(),
2401 tlsconf.cert_file.c_str(), tlsconf.sct_data
2402 #ifdef HAVE_NEVERBLEED
2405 #endif // HAVE_NEVERBLEED
2408 all_ssl_ctx.push_back(ssl_ctx);
2412 if (cert_lookup_tree_add_ssl_ctx(cert_tree, indexed_ssl_ctx, ssl_ctx) == -1) {
2413 LOG(FATAL) << "Failed to add default certificate.";
2417 for (auto &c : tlsconf.subcerts) {
2418 auto ssl_ctx = create_ssl_context(c.private_key_file.c_str(),
2419 c.cert_file.c_str(), c.sct_data
2420 #ifdef HAVE_NEVERBLEED
2423 #endif // HAVE_NEVERBLEED
2425 all_ssl_ctx.push_back(ssl_ctx);
2427 if (cert_lookup_tree_add_ssl_ctx(cert_tree, indexed_ssl_ctx, ssl_ctx) ==
2429 LOG(FATAL) << "Failed to add sub certificate.";
2438 SSL_CTX *setup_quic_server_ssl_context(
2439 std::vector<SSL_CTX *> &all_ssl_ctx,
2440 std::vector<std::vector<SSL_CTX *>> &indexed_ssl_ctx,
2441 CertLookupTree *cert_tree
2442 # ifdef HAVE_NEVERBLEED
2445 # endif // HAVE_NEVERBLEED
2447 auto config = get_config();
2449 if (!upstream_tls_enabled(config->conn)) {
2453 auto &tlsconf = config->tls;
2456 create_quic_ssl_context(tlsconf.private_key_file.c_str(),
2457 tlsconf.cert_file.c_str(), tlsconf.sct_data
2458 # ifdef HAVE_NEVERBLEED
2461 # endif // HAVE_NEVERBLEED
2464 all_ssl_ctx.push_back(ssl_ctx);
2468 if (cert_lookup_tree_add_ssl_ctx(cert_tree, indexed_ssl_ctx, ssl_ctx) == -1) {
2469 LOG(FATAL) << "Failed to add default certificate.";
2473 for (auto &c : tlsconf.subcerts) {
2474 auto ssl_ctx = create_quic_ssl_context(c.private_key_file.c_str(),
2475 c.cert_file.c_str(), c.sct_data
2476 # ifdef HAVE_NEVERBLEED
2479 # endif // HAVE_NEVERBLEED
2481 all_ssl_ctx.push_back(ssl_ctx);
2483 if (cert_lookup_tree_add_ssl_ctx(cert_tree, indexed_ssl_ctx, ssl_ctx) ==
2485 LOG(FATAL) << "Failed to add sub certificate.";
2492 #endif // ENABLE_HTTP3
2494 SSL_CTX *setup_downstream_client_ssl_context(
2495 #ifdef HAVE_NEVERBLEED
2497 #endif // HAVE_NEVERBLEED
2499 auto &tlsconf = get_config()->tls;
2501 return create_ssl_client_context(
2502 #ifdef HAVE_NEVERBLEED
2504 #endif // HAVE_NEVERBLEED
2505 tlsconf.cacert, tlsconf.client.cert_file, tlsconf.client.private_key_file,
2506 select_next_proto_cb);
2509 void setup_downstream_http2_alpn(SSL *ssl) {
2510 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
2511 // ALPN advertisement
2512 auto alpn = util::get_default_alpn();
2513 SSL_set_alpn_protos(ssl, alpn.data(), alpn.size());
2514 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
2517 void setup_downstream_http1_alpn(SSL *ssl) {
2518 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
2519 // ALPN advertisement
2520 SSL_set_alpn_protos(ssl, NGHTTP2_H1_1_ALPN.byte(), NGHTTP2_H1_1_ALPN.size());
2521 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
2524 std::unique_ptr<CertLookupTree> create_cert_lookup_tree() {
2525 auto config = get_config();
2526 if (!upstream_tls_enabled(config->conn)) {
2529 return std::make_unique<CertLookupTree>();
2533 std::vector<uint8_t> serialize_ssl_session(SSL_SESSION *session) {
2534 auto len = i2d_SSL_SESSION(session, nullptr);
2535 auto buf = std::vector<uint8_t>(len);
2536 auto p = buf.data();
2537 i2d_SSL_SESSION(session, &p);
2543 void try_cache_tls_session(TLSSessionCache *cache, SSL_SESSION *session,
2545 if (cache->last_updated + 1_min > t) {
2546 if (LOG_ENABLED(INFO)) {
2547 LOG(INFO) << "Client session cache entry is still fresh.";
2552 if (LOG_ENABLED(INFO)) {
2553 LOG(INFO) << "Update client cache entry "
2554 << "timestamp = " << t;
2557 cache->session_data = serialize_ssl_session(session);
2558 cache->last_updated = t;
2561 SSL_SESSION *reuse_tls_session(const TLSSessionCache &cache) {
2562 if (cache.session_data.empty()) {
2566 auto p = cache.session_data.data();
2567 return d2i_SSL_SESSION(nullptr, &p, cache.session_data.size());
2570 int proto_version_from_string(const StringRef &v) {
2571 #ifdef TLS1_3_VERSION
2572 if (util::strieq_l("TLSv1.3", v)) {
2573 return TLS1_3_VERSION;
2575 #endif // TLS1_3_VERSION
2576 if (util::strieq_l("TLSv1.2", v)) {
2577 return TLS1_2_VERSION;
2579 if (util::strieq_l("TLSv1.1", v)) {
2580 return TLS1_1_VERSION;
2582 if (util::strieq_l("TLSv1.0", v)) {
2583 return TLS1_VERSION;
2588 int verify_ocsp_response(SSL_CTX *ssl_ctx, const uint8_t *ocsp_resp,
2589 size_t ocsp_resplen) {
2591 #if !defined(OPENSSL_NO_OCSP) && !LIBRESSL_IN_USE && \
2592 OPENSSL_VERSION_NUMBER >= 0x10002000L
2595 STACK_OF(X509) * chain_certs;
2596 SSL_CTX_get0_chain_certs(ssl_ctx, &chain_certs);
2598 auto resp = d2i_OCSP_RESPONSE(nullptr, &ocsp_resp, ocsp_resplen);
2599 if (resp == nullptr) {
2600 LOG(ERROR) << "d2i_OCSP_RESPONSE failed";
2603 auto resp_deleter = defer(OCSP_RESPONSE_free, resp);
2605 if (OCSP_response_status(resp) != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
2606 LOG(ERROR) << "OCSP response status is not successful";
2612 auto bs = OCSP_response_get1_basic(resp);
2613 if (bs == nullptr) {
2614 LOG(ERROR) << "OCSP_response_get1_basic failed: "
2615 << ERR_error_string(ERR_get_error(), nullptr);
2618 auto bs_deleter = defer(OCSP_BASICRESP_free, bs);
2620 auto store = SSL_CTX_get_cert_store(ssl_ctx);
2624 rv = OCSP_basic_verify(bs, chain_certs, store, 0);
2627 LOG(ERROR) << "OCSP_basic_verify failed: "
2628 << ERR_error_string(ERR_get_error(), nullptr);
2632 auto sresp = OCSP_resp_get0(bs, 0);
2633 if (sresp == nullptr) {
2634 LOG(ERROR) << "OCSP response verification failed: no single response";
2638 # if OPENSSL_1_1_API
2639 auto certid = OCSP_SINGLERESP_get0_id(sresp);
2640 # else // !OPENSSL_1_1_API
2641 auto certid = sresp->certId;
2642 # endif // !OPENSSL_1_1_API
2643 assert(certid != nullptr);
2645 ASN1_INTEGER *serial;
2646 rv = OCSP_id_get0_info(nullptr, nullptr, nullptr, &serial,
2647 const_cast<OCSP_CERTID *>(certid));
2649 LOG(ERROR) << "OCSP_id_get0_info failed";
2653 if (serial == nullptr) {
2654 LOG(ERROR) << "OCSP response does not contain serial number";
2658 auto cert = SSL_CTX_get0_certificate(ssl_ctx);
2659 auto cert_serial = X509_get_serialNumber(cert);
2661 if (ASN1_INTEGER_cmp(cert_serial, serial)) {
2662 LOG(ERROR) << "OCSP verification serial numbers do not match";
2666 if (LOG_ENABLED(INFO)) {
2667 LOG(INFO) << "OCSP verification succeeded";
2669 #endif // !defined(OPENSSL_NO_OCSP) && !LIBRESSL_IN_USE
2670 // && OPENSSL_VERSION_NUMBER >= 0x10002000L
2675 ssize_t get_x509_fingerprint(uint8_t *dst, size_t dstlen, const X509 *x,
2677 unsigned int len = dstlen;
2678 if (X509_digest(x, md, dst, &len) != 1) {
2685 StringRef get_x509_name(BlockAllocator &balloc, X509_NAME *nm) {
2686 auto b = BIO_new(BIO_s_mem());
2691 auto b_deleter = defer(BIO_free, b);
2693 // Not documented, but it seems that X509_NAME_print_ex returns the
2694 // number of bytes written into b.
2695 auto slen = X509_NAME_print_ex(b, nm, 0, XN_FLAG_RFC2253);
2700 auto iov = make_byte_ref(balloc, slen + 1);
2701 BIO_read(b, iov.base, slen);
2702 iov.base[slen] = '\0';
2703 return StringRef{iov.base, static_cast<size_t>(slen)};
2707 StringRef get_x509_subject_name(BlockAllocator &balloc, X509 *x) {
2708 return get_x509_name(balloc, X509_get_subject_name(x));
2711 StringRef get_x509_issuer_name(BlockAllocator &balloc, X509 *x) {
2712 return get_x509_name(balloc, X509_get_issuer_name(x));
2715 #ifdef WORDS_BIGENDIAN
2716 # define bswap64(N) (N)
2717 #else /* !WORDS_BIGENDIAN */
2718 # define bswap64(N) \
2719 ((uint64_t)(ntohl((uint32_t)(N))) << 32 | ntohl((uint32_t)((N) >> 32)))
2720 #endif /* !WORDS_BIGENDIAN */
2722 StringRef get_x509_serial(BlockAllocator &balloc, X509 *x) {
2723 auto sn = X509_get_serialNumber(x);
2725 auto bn_d = defer(BN_free, bn);
2726 if (!ASN1_INTEGER_to_BN(sn, bn) || BN_num_bytes(bn) > 20) {
2730 std::array<uint8_t, 20> b;
2731 auto n = BN_bn2bin(bn, b.data());
2734 return util::format_hex(balloc, StringRef{b.data(), static_cast<size_t>(n)});
2738 // Performs conversion from |at| to time_t. The result is stored in
2739 // |t|. This function returns 0 if it succeeds, or -1.
2740 int time_t_from_asn1_time(time_t &t, const ASN1_TIME *at) {
2743 #if OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL)
2745 rv = ASN1_TIME_to_tm(at, &tm);
2750 t = nghttp2_timegm(&tm);
2751 #else // !(OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL))
2752 auto b = BIO_new(BIO_s_mem());
2757 auto bio_deleter = defer(BIO_free, b);
2759 rv = ASN1_TIME_print(b, at);
2764 # ifdef OPENSSL_IS_BORINGSSL
2769 auto slen = BIO_get_mem_data(b, &s);
2770 auto tt = util::parse_openssl_asn1_time_print(
2771 StringRef{s, static_cast<size_t>(slen)});
2777 #endif // !(OPENSSL_1_1_1_API && !defined(OPENSSL_IS_BORINGSSL))
2783 int get_x509_not_before(time_t &t, X509 *x) {
2785 auto at = X509_get0_notBefore(x);
2786 #else // !OPENSSL_1_1_API
2787 auto at = X509_get_notBefore(x);
2788 #endif // !OPENSSL_1_1_API
2793 return time_t_from_asn1_time(t, at);
2796 int get_x509_not_after(time_t &t, X509 *x) {
2798 auto at = X509_get0_notAfter(x);
2799 #else // !OPENSSL_1_1_API
2800 auto at = X509_get_notAfter(x);
2801 #endif // !OPENSSL_1_1_API
2806 return time_t_from_asn1_time(t, at);
2811 } // namespace shrpx