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