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