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