add some logging
[ghsmtp.git] / TLS-OpenSSL.cpp
blob370befdfcd59133446c9852f7f37cee0dc75874f
1 #include "TLS-OpenSSL.hpp"
3 #include <iomanip>
4 #include <span>
5 #include <string>
7 #include <openssl/err.h>
8 #include <openssl/rand.h>
10 #include <openssl/x509.h>
11 #include <openssl/x509v3.h>
13 #include <gflags/gflags.h>
14 #include <glog/logging.h>
16 #define FMT_STRING_ALIAS 1
17 #include <fmt/format.h>
19 #include "DNS.hpp"
20 #include "POSIX.hpp"
21 #include "osutil.hpp"
23 DEFINE_bool(support_all_tls_versions,
24 true,
25 "lift restrictions on TLS versions");
27 // <https://tools.ietf.org/html/rfc7919>
28 // <https://wiki.mozilla.org/Security/Server_Side_TLS#DHE_handshake_and_dhparam>
29 constexpr char ffdhe4096[] = R"(
30 -----BEGIN DH PARAMETERS-----
31 MIICCAKCAgEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz
32 +8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a
33 87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7
34 YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi
35 7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD
36 ssbzSibBsu/6iGtCOGEfz9zeNVs7ZRkDW7w09N75nAI4YbRvydbmyQd62R0mkff3
37 7lmMsPrBhtkcrv4TCYUTknC0EwyTvEN5RPT9RFLi103TZPLiHnH1S/9croKrnJ32
38 nuhtK8UiNjoNq8Uhl5sN6todv5pC1cRITgq80Gv6U93vPBsg7j/VnXwl5B0rZp4e
39 8W5vUsMWTfT7eTDp5OWIV7asfV9C1p9tGHdjzx1VA0AEh/VbpX4xzHpxNciG77Qx
40 iu1qHgEtnmgyqQdgCpGBMMRtx3j5ca0AOAkpmaMzy4t6Gh25PXFAADwqTs6p+Y0K
41 zAqCkc3OyX3Pjsm1Wn+IpGtNtahR9EGC4caKAH5eZV9q//////////8CAQI=
42 -----END DH PARAMETERS-----
43 )";
45 // convert binary input into a std::string of hex digits
47 auto bin2hexstring(std::span<unsigned char const> const data) -> std::string
49 std::string ret;
50 ret.reserve(2 * data.size());
52 for (auto const& ch : data) {
53 auto const lo = ch & 0xF;
54 auto const hi = (ch >> 4) & 0xF;
56 auto constexpr hex_digits = "0123456789abcdef";
58 ret += hex_digits[static_cast<int>(hi)];
59 ret += hex_digits[static_cast<int>(lo)];
62 return ret;
65 TLS::TLS(std::function<void(void)> read_hook)
66 : read_hook_(read_hook)
70 TLS::~TLS()
72 for (auto& ctx : cert_ctx_) {
73 if (ctx.ctx) {
74 SSL_CTX_free(ctx.ctx);
77 if (ssl_) {
78 SSL_free(ssl_);
82 struct session_context {
85 static int session_context_index = -1;
87 static int verify_callback(int preverify_ok, X509_STORE_CTX* ctx)
89 auto const cert = X509_STORE_CTX_get_current_cert(ctx);
90 if (cert == nullptr)
91 return 1;
93 auto err = X509_STORE_CTX_get_error(ctx);
95 // auto const ssl = reinterpret_cast<SSL*>(
96 // X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
98 CHECK_GE(session_context_index, 0);
100 // auto unused = reinterpret_cast<session_context*>(SSL_get_ex_data(ssl,
101 // session_context_index));
103 auto const depth = X509_STORE_CTX_get_error_depth(ctx);
105 char buf[256];
106 X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
108 if (depth > Config::cert_verify_depth) {
109 preverify_ok = 0;
110 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
111 X509_STORE_CTX_set_error(ctx, err);
113 if (!preverify_ok) {
114 LOG(INFO) << "verify error:num=" << err << ':'
115 << X509_verify_cert_error_string(err) << ": depth=" << depth
116 << ':' << buf;
118 else {
119 LOG(INFO) << "preverify_ok; depth=" << depth << " subject_name=«" << buf
120 << "»";
123 if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT)) {
124 if (cert) {
125 X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf));
126 LOG(INFO) << "issuer=" << buf;
128 else {
129 LOG(INFO) << "issuer=<unknown>";
133 return 1; // always continue
136 static int ssl_servername_callback(SSL* s, int* ad, void* arg)
138 auto cert_ctx_ptr =
139 CHECK_NOTNULL(static_cast<std::vector<TLS::per_cert_ctx>*>(arg));
140 auto const& cert_ctx = *cert_ctx_ptr;
142 auto const servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
144 if (servername && *servername) {
145 LOG(INFO) << "servername requested " << servername;
146 Domain const sn{servername};
147 for (auto const& ctx : cert_ctx) {
148 if (auto const& c = std::find(begin(ctx.cn), end(ctx.cn), sn);
149 c != end(ctx.cn)) {
150 if (size(cert_ctx) > 1)
151 SSL_set_SSL_CTX(s, ctx.ctx);
152 return SSL_TLSEXT_ERR_OK;
155 LOG(INFO) << "no cert found for server " << servername;
156 return SSL_TLSEXT_ERR_ALERT_WARNING;
159 // LOG(INFO) << "no specific server name requested";
160 return SSL_TLSEXT_ERR_OK;
163 bool TLS::starttls_client(fs::path config_path,
164 int fd_in,
165 int fd_out,
166 char const* client_name,
167 char const* server_name,
168 DNS::RR_collection const& tlsa_rrs,
169 bool enforce_dane,
170 std::chrono::milliseconds timeout)
172 SSL_load_error_strings();
173 SSL_library_init();
175 CHECK(RAND_status()); // Be sure the PRNG has been seeded with enough data.
177 auto const method = CHECK_NOTNULL(SSLv23_client_method());
179 if (client_name) {
180 auto const certs = osutil::list_directory(config_path, Config::cert_fn_re);
182 CHECK_GE(certs.size(), 1) << "no client cert(s) found";
184 for (auto const& cert : certs) {
186 auto ctx = CHECK_NOTNULL(SSL_CTX_new(method));
187 std::vector<Domain> cn;
189 // Allow any old and crufty protocol version.
190 if (FLAGS_support_all_tls_versions) {
191 CHECK_GT(SSL_CTX_set_min_proto_version(ctx, 0), 0)
192 << "unable to set min proto version";
193 CHECK_GT(SSL_CTX_set_max_proto_version(ctx, 0), 0)
194 << "unable to set max proto version";
197 CHECK_GT(SSL_CTX_dane_enable(ctx), 0)
198 << "unable to enable DANE on SSL context";
200 // you'd think if it's the default, you'd not have to call this
201 CHECK_EQ(SSL_CTX_set_default_verify_paths(ctx), 1);
203 CHECK_GT(SSL_CTX_use_certificate_chain_file(ctx, cert.string().c_str()),
205 << "Can't load certificate chain file " << cert;
207 auto const key = fs::path(cert).replace_extension(Config::key_ext);
209 if (fs::exists(key)) {
211 CHECK_GT(SSL_CTX_use_PrivateKey_file(ctx, key.string().c_str(),
212 SSL_FILETYPE_PEM),
214 << "Can't load private key file " << key;
216 CHECK(SSL_CTX_check_private_key(ctx))
217 << "SSL_CTX_check_private_key failed for " << key;
220 SSL_CTX_set_verify_depth(ctx, Config::cert_verify_depth + 1);
221 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
222 verify_callback);
224 //.......................................................
226 auto const x509 = CHECK_NOTNULL(SSL_CTX_get0_certificate(ctx));
228 X509_NAME* subj = X509_get_subject_name(x509);
230 int lastpos = -1;
231 for (;;) {
232 lastpos = X509_NAME_get_index_by_NID(subj, NID_commonName, lastpos);
233 if (lastpos == -1)
234 break;
235 auto e = X509_NAME_get_entry(subj, lastpos);
236 ASN1_STRING* d = X509_NAME_ENTRY_get_data(e);
237 auto str = ASN1_STRING_get0_data(d);
238 // LOG(INFO) << "client cert found for " << str;
239 cn.emplace_back(reinterpret_cast<const char*>(str));
242 auto subject_alt_names = static_cast<GENERAL_NAMES*>(
243 X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
245 for (int i = 0; i < sk_GENERAL_NAME_num(subject_alt_names); ++i) {
247 GENERAL_NAME* gen = sk_GENERAL_NAME_value(subject_alt_names, i);
249 if (gen->type == GEN_URI || gen->type == GEN_EMAIL) {
250 ASN1_IA5STRING* asn1_str = gen->d.uniformResourceIdentifier;
252 std::string const str(
253 reinterpret_cast<char const*>(ASN1_STRING_get0_data(asn1_str)),
254 ASN1_STRING_length(asn1_str));
256 LOG(INFO) << "email or uri alt name " << str;
258 else if (gen->type == GEN_DNS) {
259 ASN1_IA5STRING* asn1_str = gen->d.uniformResourceIdentifier;
261 std::string_view str(
262 reinterpret_cast<char const*>(ASN1_STRING_get0_data(asn1_str)),
263 ASN1_STRING_length(asn1_str));
264 Domain const dom{str};
265 if (std::find(begin(cn), end(cn), dom) == end(cn)) {
266 // LOG(INFO) << "additional name found " << str;
267 cn.emplace_back(dom);
269 else {
270 // LOG(INFO) << "duplicate name " << str << " ignored";
273 else if (gen->type == GEN_IPADD) {
274 unsigned char* p = gen->d.ip->data;
275 if (gen->d.ip->length == 4) {
276 auto const ip = fmt::format(FMT_STRING("{:d}.{:d}.{:d}.{:d}"), p[0],
277 p[1], p[2], p[3]);
278 LOG(INFO) << "alt name IP4 address " << ip;
280 else if (gen->d.ip->length == 16) {
281 LOG(ERROR) << "IPv6 not implemented";
283 else {
284 LOG(ERROR) << "unknown IP type";
287 else {
288 LOG(ERROR) << "unknown alt name type";
292 GENERAL_NAMES_free(subject_alt_names);
294 //.......................................................
296 if (std::find(begin(cn), end(cn), Domain{client_name}) != end(cn)) {
297 // LOG(INFO) << "**** using cert for " << client_name;
298 cert_ctx_.emplace_back(ctx, cn);
303 if (cert_ctx_.empty()) {
304 LOG(INFO) << "no cert found for client " << client_name;
306 auto ctx = CHECK_NOTNULL(SSL_CTX_new(method));
307 CHECK_GT(SSL_CTX_dane_enable(ctx), 0)
308 << "unable to enable DANE on SSL context";
310 // you'd think if it's the default, you'd not have to call this
311 CHECK_EQ(SSL_CTX_set_default_verify_paths(ctx), 1);
313 SSL_CTX_set_verify_depth(ctx, Config::cert_verify_depth + 1);
314 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
315 verify_callback);
317 LOG(INFO) << "**** using no client cert";
319 std::vector<Domain> cn;
320 cert_ctx_.emplace_back(ctx, cn);
323 ssl_ = CHECK_NOTNULL(SSL_new(cert_ctx_.back().ctx));
325 SSL_set_rfd(ssl_, fd_in);
326 SSL_set_wfd(ssl_, fd_out);
328 // LOG(INFO) << "tlsa_rrs.size() == " << tlsa_rrs.size();
330 if (tlsa_rrs.size()) {
331 CHECK_GE(SSL_dane_enable(ssl_, server_name), 0)
332 << "SSL_dane_enable() failed";
333 LOG(INFO) << "SSL_dane_enable(ssl_, " << server_name << ")";
335 else {
336 CHECK_EQ(SSL_set1_host(ssl_, server_name), 1);
338 // SSL_set_tlsext_host_name(ssl_, server_name);
339 // same as:
340 CHECK_EQ(SSL_ctrl(ssl_, SSL_CTRL_SET_TLSEXT_HOSTNAME,
341 TLSEXT_NAMETYPE_host_name,
342 const_cast<char*>(server_name)),
344 // LOG(INFO) << "SSL_set1_host and SSL_set_tlsext_host_name " <<
345 // server_name;
348 // No partial label wildcards
349 SSL_set_hostflags(ssl_, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
351 auto usable_TLSA_records = 0;
353 for (auto const& tlsa_rr : tlsa_rrs) {
354 if (std::holds_alternative<DNS::RR_TLSA>(tlsa_rr)) {
355 auto const rp = std::get<DNS::RR_TLSA>(tlsa_rr);
356 auto data = rp.assoc_data();
357 auto rc = SSL_dane_tlsa_add(ssl_, rp.cert_usage(), rp.selector(),
358 rp.matching_type(), data.data(), data.size());
360 if (rc < 0) {
361 auto const cp = bin2hexstring(data);
362 LOG(ERROR) << "SSL_dane_tlsa_add() failed.";
363 LOG(ERROR) << "failed record: " << rp.cert_usage() << " "
364 << rp.selector() << " " << rp.matching_type() << " " << cp;
366 else if (rc == 0) {
367 auto const cp = bin2hexstring(data);
368 LOG(ERROR) << "unusable TLSA record: " << rp.cert_usage() << " "
369 << rp.selector() << " " << rp.matching_type() << " " << cp;
371 else {
372 // auto const cp = bin2hexstring(data);
373 // LOG(INFO) << "added TLSA record: " << rp.cert_usage() << " "
374 // << rp.selector() << " " << rp.matching_type() << " " << cp;
375 ++usable_TLSA_records;
380 // CHECK_EQ(SSL_set_tlsext_host_name(ssl_, server_name), 1);
381 // same as:
382 // CHECK_EQ(SSL_ctrl(ssl_, SSL_CTRL_SET_TLSEXT_HOSTNAME,
383 // TLSEXT_NAMETYPE_host_name,
384 // const_cast<char*>(server_name)),
385 // 1);
386 // LOG(INFO) << "SSL_set_tlsext_host_name == " << server_name;
388 if (session_context_index < 0) {
389 session_context_index =
390 SSL_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
392 session_context context;
393 SSL_set_ex_data(ssl_, session_context_index, &context);
395 auto const start = std::chrono::system_clock::now();
397 ERR_clear_error();
399 int rc;
400 while ((rc = SSL_connect(ssl_)) < 0) {
402 auto const now = std::chrono::system_clock::now();
404 CHECK(now < (start + timeout)) << "starttls timed out";
406 auto time_left = std::chrono::duration_cast<std::chrono::milliseconds>(
407 (start + timeout) - now);
409 int n_get_err;
410 switch (n_get_err = SSL_get_error(ssl_, rc)) {
411 case SSL_ERROR_WANT_READ:
412 CHECK(POSIX::input_ready(fd_in, time_left))
413 << "starttls timed out on input_ready";
414 ERR_clear_error();
415 continue; // try SSL_accept again
417 case SSL_ERROR_WANT_WRITE:
418 CHECK(POSIX::output_ready(fd_out, time_left))
419 << "starttls timed out on output_ready";
420 ERR_clear_error();
421 continue; // try SSL_accept again
423 case SSL_ERROR_SYSCALL:
424 LOG(WARNING) << "errno == " << errno << ": " << strerror(errno);
425 [[fallthrough]];
427 default: ssl_error(n_get_err);
431 if (SSL_get_verify_result(ssl_) == X509_V_OK) {
432 LOG(INFO) << "server certificate verified";
433 verified_ = true;
435 char const* const peername = SSL_get0_peername(ssl_);
436 if (peername != nullptr) {
437 // Name checks were in scope and matched the peername
438 verified_peername_ = peername;
439 LOG(INFO) << "verified peername: " << peername;
441 else {
442 LOG(INFO) << "no verified peername";
445 EVP_PKEY* mspki = nullptr;
446 int depth = SSL_get0_dane_authority(ssl_, nullptr, &mspki);
447 if (depth >= 0) {
449 uint8_t usage, selector, mtype;
450 const unsigned char* certdata;
451 size_t certdata_len;
453 SSL_get0_dane_tlsa(ssl_, &usage, &selector, &mtype, &certdata,
454 &certdata_len);
456 LOG(INFO) << "DANE TLSA " << unsigned(usage) << " " << unsigned(selector)
457 << " " << unsigned(mtype) << " ["
458 << bin2hexstring({certdata, 6}) << "...] "
459 << ((mspki != nullptr) ? "TA public key verified certificate"
460 : depth ? "matched TA certificate"
461 : "matched EE certificate")
462 << " at depth " << depth;
464 else if (usable_TLSA_records && enforce_dane) {
465 LOG(WARNING) << "enforcing DANE; failing starttls";
466 return false;
469 else {
470 LOG(WARNING) << "server certificate failed to verify";
473 return true;
476 bool TLS::starttls_server(fs::path config_path,
477 int fd_in,
478 int fd_out,
479 std::chrono::milliseconds timeout)
481 SSL_load_error_strings();
482 SSL_library_init();
484 CHECK(RAND_status()); // Be sure the PRNG has been seeded with enough data.
486 auto const method = CHECK_NOTNULL(SSLv23_server_method());
488 auto const bio =
489 CHECK_NOTNULL(BIO_new_mem_buf(const_cast<char*>(ffdhe4096), -1));
491 auto const certs = osutil::list_directory(config_path, Config::cert_fn_re);
493 CHECK_GE(certs.size(), 1) << "no server cert(s) found";
495 for (auto const& cert : certs) {
497 auto ctx = CHECK_NOTNULL(SSL_CTX_new(method));
498 std::vector<Domain> names;
500 SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
502 // Allow any old and crufty protocol version.
503 if (FLAGS_support_all_tls_versions) {
504 CHECK_GT(SSL_CTX_set_min_proto_version(ctx, 0), 0)
505 << "unable to set min proto version";
506 CHECK_GT(SSL_CTX_set_max_proto_version(ctx, 0), 0)
507 << "unable to set max proto version";
510 CHECK_GT(SSL_CTX_dane_enable(ctx), 0)
511 << "unable to enable DANE on SSL context";
513 // you'd think if it's the default, you'd not have to call this
514 CHECK_EQ(SSL_CTX_set_default_verify_paths(ctx), 1);
516 CHECK_GT(SSL_CTX_use_certificate_chain_file(ctx, cert.string().c_str()), 0)
517 << "Can't load certificate chain file " << cert;
519 auto const key = fs::path(cert).replace_extension(Config::key_ext);
521 if (fs::exists(key)) {
523 CHECK_GT(SSL_CTX_use_PrivateKey_file(ctx, key.string().c_str(),
524 SSL_FILETYPE_PEM),
526 << "Can't load private key file " << key;
528 CHECK(SSL_CTX_check_private_key(ctx))
529 << "SSL_CTX_check_private_key failed for " << key;
532 SSL_CTX_set_verify_depth(ctx, Config::cert_verify_depth + 1);
534 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
535 verify_callback);
537 // SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_callback);
538 // same as:
539 SSL_CTX_callback_ctrl(
540 ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_CB,
541 reinterpret_cast<void (*)()>(ssl_servername_callback));
543 // SSL_CTX_set_tlsext_servername_arg(ctx, &cert_ctx_);
544 // same as:
545 SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0,
546 reinterpret_cast<void*>(&cert_ctx_));
548 // SSL_CTX_dane_set_flags(ctx, DANE_FLAG_NO_DANE_EE_NAMECHECKS);
550 //.......................................................
552 auto const x509 = CHECK_NOTNULL(SSL_CTX_get0_certificate(ctx));
554 X509_NAME* subj = X509_get_subject_name(x509);
556 int lastpos = -1;
557 for (;;) {
558 lastpos = X509_NAME_get_index_by_NID(subj, NID_commonName, lastpos);
559 if (lastpos == -1)
560 break;
561 auto e = X509_NAME_get_entry(subj, lastpos);
562 ASN1_STRING* d = X509_NAME_ENTRY_get_data(e);
563 auto str = ASN1_STRING_get0_data(d);
564 // LOG(INFO) << "server cert found for " << str;
565 names.emplace_back(reinterpret_cast<const char*>(str));
568 // auto ext_stack = X509_get0_extensions(x509);
569 // for (int i = 0; i < sk_X509_EXTENSION_num(ext_stack); i++) {
570 // X509_EXTENSION* ext
571 // = CHECK_NOTNULL(sk_X509_EXTENSION_value(ext_stack, i));
572 // ASN1_OBJECT* asn1_obj =
573 // CHECK_NOTNULL(X509_EXTENSION_get_object(ext)); unsigned nid =
574 // OBJ_obj2nid(asn1_obj); if (nid == NID_undef) {
575 // // no lookup found for the provided OID so nid came back as
576 // undefined. char extname[256]; OBJ_obj2txt(extname, sizeof(extname),
577 // asn1_obj, 1); LOG(INFO) << "undef extension name is " << extname;
578 // } else {
579 // // the OID translated to a NID which implies that the OID has a
580 // known
581 // // sn/ln
582 // const char* c_ext_name = CHECK_NOTNULL(OBJ_nid2ln(nid));
583 // LOG(INFO) << "extension " << c_ext_name;
584 // }
585 // }
587 auto subject_alt_names = static_cast<GENERAL_NAMES*>(
588 X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
590 for (int i = 0; i < sk_GENERAL_NAME_num(subject_alt_names); ++i) {
592 GENERAL_NAME* gen = sk_GENERAL_NAME_value(subject_alt_names, i);
594 if (gen->type == GEN_URI || gen->type == GEN_EMAIL) {
595 ASN1_IA5STRING* asn1_str = gen->d.uniformResourceIdentifier;
597 std::string str(
598 reinterpret_cast<char const*>(ASN1_STRING_get0_data(asn1_str)),
599 ASN1_STRING_length(asn1_str));
601 LOG(INFO) << "email or uri alt name " << str;
603 else if (gen->type == GEN_DNS) {
604 ASN1_IA5STRING* asn1_str = gen->d.uniformResourceIdentifier;
606 std::string str(
607 reinterpret_cast<char const*>(ASN1_STRING_get0_data(asn1_str)),
608 ASN1_STRING_length(asn1_str));
610 Domain const dom{str};
611 if (std::find(begin(names), end(names), dom) == end(names)) {
612 // LOG(INFO) << "additional name found " << str;
613 names.emplace_back(dom);
615 else {
616 // LOG(INFO) << "duplicate name " << str << " ignored";
619 else if (gen->type == GEN_IPADD) {
620 unsigned char* p = gen->d.ip->data;
621 if (gen->d.ip->length == 4) {
622 auto const ip = fmt::format(FMT_STRING("{:d}.{:d}.{:d}.{:d}"), p[0],
623 p[1], p[2], p[3]);
624 LOG(INFO) << "alt name IP4 address " << ip;
625 names.emplace_back(ip);
627 else if (gen->d.ip->length == 16) {
628 // FIXME!
629 LOG(ERROR) << "IPv6 not implemented";
631 else {
632 LOG(ERROR) << "unknown IP type";
635 else {
636 LOG(ERROR) << "unknown alt name type";
640 GENERAL_NAMES_free(subject_alt_names);
642 //.......................................................
644 cert_ctx_.emplace_back(ctx, names);
647 BIO_free(bio);
649 ssl_ = CHECK_NOTNULL(SSL_new(cert_ctx_.back().ctx));
651 SSL_set_rfd(ssl_, fd_in);
652 SSL_set_wfd(ssl_, fd_out);
654 if (session_context_index < 0) {
655 session_context_index =
656 SSL_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
658 session_context context;
659 SSL_set_ex_data(ssl_, session_context_index, &context);
661 auto const start = std::chrono::system_clock::now();
663 ERR_clear_error();
665 int rc;
666 while ((rc = SSL_accept(ssl_)) < 0) {
668 auto const now = std::chrono::system_clock::now();
670 CHECK(now < (start + timeout)) << "starttls timed out";
672 auto const time_left =
673 std::chrono::duration_cast<std::chrono::milliseconds>(
674 (start + timeout) - now);
676 int n_get_err;
677 switch (n_get_err = SSL_get_error(ssl_, rc)) {
678 case SSL_ERROR_WANT_READ:
679 CHECK(POSIX::input_ready(fd_in, time_left))
680 << "starttls timed out on input_ready";
681 ERR_clear_error();
682 continue; // try SSL_accept again
684 case SSL_ERROR_WANT_WRITE:
685 CHECK(POSIX::output_ready(fd_out, time_left))
686 << "starttls timed out on output_ready";
687 ERR_clear_error();
688 continue; // try SSL_accept again
690 case SSL_ERROR_SYSCALL:
691 LOG(WARNING) << "errno == " << errno << ": " << strerror(errno);
692 [[fallthrough]];
694 default: ssl_error(n_get_err);
698 if (auto const peer_cert = SSL_get_peer_certificate(ssl_); peer_cert) {
699 if (SSL_get_verify_result(ssl_) == X509_V_OK) {
700 LOG(INFO) << "client certificate verified";
701 verified_ = true;
703 char const* const peername = SSL_get0_peername(ssl_);
704 if (peername != nullptr) {
705 // name checks were in scope and matched the peername
706 verified_peername_ = peername;
707 LOG(INFO) << "verified peername: " << peername;
709 else {
710 LOG(INFO) << "no verified peername";
713 EVP_PKEY* mspki = nullptr;
714 int depth = SSL_get0_dane_authority(ssl_, nullptr, &mspki);
715 if (depth >= 0) {
717 uint8_t usage, selector, mtype;
718 const unsigned char* certdata;
719 size_t certdata_len;
721 SSL_get0_dane_tlsa(ssl_, &usage, &selector, &mtype, &certdata,
722 &certdata_len);
724 LOG(INFO) << "DANE TLSA " << usage << " " << selector << " " << mtype
725 << " [" << bin2hexstring({certdata, 6}) << "...] "
726 << ((mspki != nullptr) ? "TA public key verified certificate"
727 : depth ? "matched TA certificate"
728 : "matched EE certificate")
729 << " at depth " << depth;
732 else {
733 LOG(WARNING) << "client certificate failed to verify";
736 else {
737 // LOG(INFO) << "no client certificate offerd to us";
740 return true;
743 std::string TLS::info() const
745 // same as SSL_CIPHER_get_version() below
746 // info << SSL_get_version(ssl_);
748 auto const c = SSL_get_current_cipher(ssl_);
749 if (c) {
750 int alg_bits;
751 int bits = SSL_CIPHER_get_bits(c, &alg_bits);
752 return fmt::format("version={} cipher={} bits={}/{}{}",
753 SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c), bits,
754 alg_bits, (verified_ ? " verified" : ""));
757 return "";
760 std::streamsize TLS::io_tls_(char const* fn,
761 std::function<int(SSL*, void*, int)> io_fnc,
762 char* s,
763 std::streamsize n,
764 std::chrono::milliseconds timeout,
765 bool& t_o)
767 auto const start = std::chrono::system_clock::now();
768 auto const end_time = start + timeout;
770 ERR_clear_error();
772 int n_ret;
773 while ((n_ret = io_fnc(ssl_, static_cast<void*>(s), static_cast<int>(n))) <
774 0) {
775 auto const now = std::chrono::system_clock::now();
776 if (now > end_time) {
777 LOG(WARNING) << fn << " timed out";
778 t_o = true;
779 return static_cast<std::streamsize>(-1);
782 auto const time_left =
783 std::chrono::duration_cast<std::chrono::milliseconds>(end_time - now);
785 int n_get_err;
786 switch (n_get_err = SSL_get_error(ssl_, n_ret)) {
787 case SSL_ERROR_WANT_READ: {
788 int fd = SSL_get_rfd(ssl_);
789 CHECK_NE(-1, fd);
790 read_hook_();
791 if (POSIX::input_ready(fd, time_left)) {
792 ERR_clear_error();
793 continue; // try io_fnc again
795 LOG(WARNING) << fn << " timed out";
796 t_o = true;
797 return static_cast<std::streamsize>(-1);
800 case SSL_ERROR_WANT_WRITE: {
801 int fd = SSL_get_wfd(ssl_);
802 CHECK_NE(-1, fd);
803 if (POSIX::output_ready(fd, time_left)) {
804 ERR_clear_error();
805 continue; // try io_fnc again
807 LOG(WARNING) << fn << " timed out";
808 t_o = true;
809 return static_cast<std::streamsize>(-1);
812 case SSL_ERROR_SYSCALL:
813 LOG(WARNING) << "errno == " << errno << ": " << strerror(errno);
814 [[fallthrough]];
816 default: ssl_error(n_get_err);
820 return static_cast<std::streamsize>(n_ret);
823 void TLS::ssl_error(int n_get_err)
825 LOG(WARNING) << "n_get_err == " << n_get_err;
826 switch (n_get_err) {
827 case SSL_ERROR_NONE: LOG(WARNING) << "SSL_ERROR_NONE"; break;
828 case SSL_ERROR_ZERO_RETURN: LOG(WARNING) << "SSL_ERROR_ZERO_RETURN"; break;
829 case SSL_ERROR_WANT_READ: LOG(WARNING) << "SSL_ERROR_WANT_READ"; break;
830 case SSL_ERROR_WANT_WRITE: LOG(WARNING) << "SSL_ERROR_WANT_WRITE"; break;
831 case SSL_ERROR_WANT_CONNECT: LOG(WARNING) << "SSL_ERROR_WANT_CONNECT"; break;
832 case SSL_ERROR_WANT_ACCEPT: LOG(WARNING) << "SSL_ERROR_WANT_ACCEPT"; break;
833 case SSL_ERROR_WANT_X509_LOOKUP:
834 LOG(WARNING) << "SSL_ERROR_WANT_X509_LOOKUP";
835 break;
836 case SSL_ERROR_SSL: LOG(WARNING) << "SSL_ERROR_SSL"; break;
838 unsigned long er;
839 while (0 != (er = ERR_get_error()))
840 LOG(WARNING) << ERR_error_string(er, nullptr);
841 LOG(WARNING) << "fatal OpenSSL error";
842 exit(1);