| 1 |
// Copyright (c) 2016 Sandstorm Development Group, Inc. and contributors |
| 2 |
// Licensed under the MIT License: |
| 3 |
// |
| 4 |
// Permission is hereby granted, free of charge, to any person obtaining a copy |
| 5 |
// of this software and associated documentation files (the "Software"), to deal |
| 6 |
// in the Software without restriction, including without limitation the rights |
| 7 |
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 8 |
// copies of the Software, and to permit persons to whom the Software is |
| 9 |
// furnished to do so, subject to the following conditions: |
| 10 |
// |
| 11 |
// The above copyright notice and this permission notice shall be included in |
| 12 |
// all copies or substantial portions of the Software. |
| 13 |
// |
| 14 |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 15 |
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 16 |
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 17 |
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 18 |
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 19 |
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 20 |
// THE SOFTWARE. |
| 21 |
|
| 22 |
#if KJ_HAS_OPENSSL |
| 23 |
|
| 24 |
#include "tls.h" |
| 25 |
|
| 26 |
#include "readiness-io.h" |
| 27 |
|
| 28 |
#include <openssl/bio.h> |
| 29 |
#include <openssl/conf.h> |
| 30 |
#include <openssl/err.h> |
| 31 |
#include <openssl/evp.h> |
| 32 |
#include <openssl/ssl.h> |
| 33 |
#include <openssl/tls1.h> |
| 34 |
#include <openssl/x509.h> |
| 35 |
#include <openssl/x509v3.h> |
| 36 |
|
| 37 |
#include <kj/async-queue.h> |
| 38 |
#include <kj/debug.h> |
| 39 |
#include <kj/vector.h> |
| 40 |
|
| 41 |
#if OPENSSL_VERSION_NUMBER < 0x10100000L |
| 42 |
#define BIO_set_init(x,v) (x->init=v) |
| 43 |
#define BIO_get_data(x) (x->ptr) |
| 44 |
#define BIO_set_data(x,v) (x->ptr=v) |
| 45 |
#endif |
| 46 |
|
| 47 |
namespace kj { |
| 48 |
|
| 49 |
// ======================================================================================= |
| 50 |
// misc helpers |
| 51 |
|
| 52 |
namespace { |
| 53 |
|
| 54 |
kj::Exception getOpensslError() { |
| 55 |
// Call when an OpenSSL function returns an error code to convert that into an exception. |
| 56 |
|
| 57 |
kj::Vector<kj::String> lines; |
| 58 |
while (unsigned long long error = ERR_get_error()) { |
| 59 |
#ifdef SSL_R_UNEXPECTED_EOF_WHILE_READING |
| 60 |
// OpenSSL 3.0+ reports unexpected disconnects this way. |
| 61 |
if (ERR_GET_REASON(error) == SSL_R_UNEXPECTED_EOF_WHILE_READING) { |
| 62 |
return KJ_EXCEPTION(DISCONNECTED, |
| 63 |
"peer disconnected without gracefully ending TLS session"); |
| 64 |
} |
| 65 |
#endif |
| 66 |
|
| 67 |
char message[1024]; |
| 68 |
ERR_error_string_n(error, message, sizeof(message)); |
| 69 |
lines.add(kj::heapString(message)); |
| 70 |
} |
| 71 |
kj::String message = kj::strArray(lines, "\n"); |
| 72 |
return KJ_EXCEPTION(FAILED, "OpenSSL error", message); |
| 73 |
} |
| 74 |
|
| 75 |
KJ_NORETURN(void throwOpensslError()); |
| 76 |
void throwOpensslError() { |
| 77 |
// Call when an OpenSSL function returns an error code to convert that into an exception and |
| 78 |
// throw it. |
| 79 |
|
| 80 |
kj::throwFatalException(getOpensslError()); |
| 81 |
} |
| 82 |
|
| 83 |
#if OPENSSL_VERSION_NUMBER < 0x10100000L && !defined(OPENSSL_IS_BORINGSSL) |
| 84 |
// Older versions of OpenSSL don't define _up_ref() functions. |
| 85 |
|
| 86 |
void EVP_PKEY_up_ref(EVP_PKEY* pkey) { |
| 87 |
CRYPTO_add(&pkey->references, 1, CRYPTO_LOCK_EVP_PKEY); |
| 88 |
} |
| 89 |
|
| 90 |
void X509_up_ref(X509* x509) { |
| 91 |
CRYPTO_add(&x509->references, 1, CRYPTO_LOCK_X509); |
| 92 |
} |
| 93 |
|
| 94 |
#endif |
| 95 |
|
| 96 |
#if OPENSSL_VERSION_NUMBER < 0x10100000L |
| 97 |
class OpenSslInit { |
| 98 |
// Initializes the OpenSSL library. |
| 99 |
public: |
| 100 |
OpenSslInit() { |
| 101 |
SSL_library_init(); |
| 102 |
SSL_load_error_strings(); |
| 103 |
OPENSSL_config(nullptr); |
| 104 |
} |
| 105 |
}; |
| 106 |
|
| 107 |
void ensureOpenSslInitialized() { |
| 108 |
// Initializes the OpenSSL library the first time it is called. |
| 109 |
static OpenSslInit init; |
| 110 |
} |
| 111 |
#else |
| 112 |
inline void ensureOpenSslInitialized() { |
| 113 |
// As of 1.1.0, no initialization is needed. |
| 114 |
} |
| 115 |
#endif |
| 116 |
|
| 117 |
bool isIpAddress(kj::StringPtr addr) { |
| 118 |
bool isPossiblyIp6 = true; |
| 119 |
bool isPossiblyIp4 = true; |
| 120 |
uint colonCount = 0; |
| 121 |
uint dotCount = 0; |
| 122 |
for (auto c: addr) { |
| 123 |
if (c == ':') { |
| 124 |
isPossiblyIp4 = false; |
| 125 |
++colonCount; |
| 126 |
} else if (c == '.') { |
| 127 |
isPossiblyIp6 = false; |
| 128 |
++dotCount; |
| 129 |
} else if ('0' <= c && c <= '9') { |
| 130 |
// Digit is valid for ipv4 or ipv6. |
| 131 |
} else if (('a' <= c && c <= 'f') || ('A' <= c && c <= 'F')) { |
| 132 |
// Hex digit could be ipv6 but not ipv4. |
| 133 |
isPossiblyIp4 = false; |
| 134 |
} else { |
| 135 |
// Nope. |
| 136 |
return false; |
| 137 |
} |
| 138 |
} |
| 139 |
|
| 140 |
// An IPv4 address has 3 dots. (Yes, I'm aware that technically IPv4 addresses can be formatted |
| 141 |
// with fewer dots, but it's not clear that we actually want to support TLS authentication of |
| 142 |
// non-canonical address formats, so for now I'm not. File a bug if you care.) An IPv6 address |
| 143 |
// has at least 2 and as many as 7 colons. |
| 144 |
return (isPossiblyIp4 && dotCount == 3) |
| 145 |
|| (isPossiblyIp6 && colonCount >= 2 && colonCount <= 7); |
| 146 |
} |
| 147 |
|
| 148 |
} // namespace |
| 149 |
|
| 150 |
// ======================================================================================= |
| 151 |
// Implementation of kj::AsyncIoStream that applies TLS on top of some other AsyncIoStream. |
| 152 |
// |
| 153 |
// TODO(perf): OpenSSL's I/O abstraction layer, "BIO", is readiness-based, but AsyncIoStream is |
| 154 |
// completion-based. This forces us to use an intermediate buffer which wastes memory and incurs |
| 155 |
// redundant copies. We could improve the situation by creating a way to detect if the underlying |
| 156 |
// AsyncIoStream is simply wrapping a file descriptor (or other readiness-based stream?) and use |
| 157 |
// that directly if so. |
| 158 |
|
| 159 |
class TlsConnection final: public kj::AsyncIoStream { |
| 160 |
public: |
| 161 |
TlsConnection(kj::Own<kj::AsyncIoStream> stream, SSL_CTX* ctx) |
| 162 |
: TlsConnection(*stream, ctx) { |
| 163 |
ownInner = kj::mv(stream); |
| 164 |
} |
| 165 |
|
| 166 |
TlsConnection(kj::AsyncIoStream& stream, SSL_CTX* ctx) |
| 167 |
: inner(stream), readBuffer(stream), writeBuffer(stream) { |
| 168 |
ssl = SSL_new(ctx); |
| 169 |
if (ssl == nullptr) { |
| 170 |
throwOpensslError(); |
| 171 |
} |
| 172 |
|
| 173 |
BIO* bio = BIO_new(const_cast<BIO_METHOD*>(getBioVtable())); |
| 174 |
if (bio == nullptr) { |
| 175 |
SSL_free(ssl); |
| 176 |
throwOpensslError(); |
| 177 |
} |
| 178 |
|
| 179 |
BIO_set_data(bio, this); |
| 180 |
BIO_set_init(bio, 1); |
| 181 |
SSL_set_bio(ssl, bio, bio); |
| 182 |
} |
| 183 |
|
| 184 |
kj::Promise<void> connect(kj::StringPtr expectedServerHostname) { |
| 185 |
if (!SSL_set_tlsext_host_name(ssl, expectedServerHostname.cStr())) { |
| 186 |
return getOpensslError(); |
| 187 |
} |
| 188 |
|
| 189 |
X509_VERIFY_PARAM* verify = SSL_get0_param(ssl); |
| 190 |
if (verify == nullptr) { |
| 191 |
return getOpensslError(); |
| 192 |
} |
| 193 |
|
| 194 |
if (isIpAddress(expectedServerHostname)) { |
| 195 |
if (X509_VERIFY_PARAM_set1_ip_asc(verify, expectedServerHostname.cStr()) <= 0) { |
| 196 |
return getOpensslError(); |
| 197 |
} |
| 198 |
} else { |
| 199 |
if (X509_VERIFY_PARAM_set1_host( |
| 200 |
verify, expectedServerHostname.cStr(), expectedServerHostname.size()) <= 0) { |
| 201 |
return getOpensslError(); |
| 202 |
} |
| 203 |
} |
| 204 |
|
| 205 |
// As of OpenSSL 1.1.0, X509_V_FLAG_TRUSTED_FIRST is on by default. Turning it on for older |
| 206 |
// versions -- as well as certain OpenSSL-compatible libraries -- fixes the problem described |
| 207 |
// here: https://community.letsencrypt.org/t/openssl-client-compatibility-changes-for-let-s-encrypt-certificates/143816 |
| 208 |
// |
| 209 |
// Otherwise, certificates issued by Let's Encrypt won't work as of September 30, 2021: |
| 210 |
// https://letsencrypt.org/docs/dst-root-ca-x3-expiration-september-2021/ |
| 211 |
X509_VERIFY_PARAM_set_flags(verify, X509_V_FLAG_TRUSTED_FIRST); |
| 212 |
|
| 213 |
return sslCall([this]() { return SSL_connect(ssl); }).then([this](size_t) { |
| 214 |
X509* cert = SSL_get_peer_certificate(ssl); |
| 215 |
KJ_REQUIRE(cert != nullptr, "TLS peer provided no certificate") { return; } |
| 216 |
X509_free(cert); |
| 217 |
|
| 218 |
auto result = SSL_get_verify_result(ssl); |
| 219 |
if (result != X509_V_OK) { |
| 220 |
const char* reason = X509_verify_cert_error_string(result); |
| 221 |
KJ_FAIL_REQUIRE("TLS peer's certificate is not trusted", reason) { break; } |
| 222 |
} |
| 223 |
}); |
| 224 |
} |
| 225 |
|
| 226 |
kj::Promise<void> accept() { |
| 227 |
// We are the server. Set SSL options to prefer server's cipher choice. |
| 228 |
SSL_set_options(ssl, SSL_OP_CIPHER_SERVER_PREFERENCE); |
| 229 |
|
| 230 |
auto acceptPromise = sslCall([this]() { |
| 231 |
return SSL_accept(ssl); |
| 232 |
}); |
| 233 |
return acceptPromise.then([](size_t ret) { |
| 234 |
if (ret == 0) { |
| 235 |
kj::throwRecoverableException( |
| 236 |
KJ_EXCEPTION(DISCONNECTED, "Client disconnected during SSL_accept()")); |
| 237 |
} |
| 238 |
}); |
| 239 |
} |
| 240 |
|
| 241 |
kj::Own<TlsPeerIdentity> getIdentity(kj::Own<kj::PeerIdentity> inner) { |
| 242 |
return kj::heap<TlsPeerIdentity>(SSL_get_peer_certificate(ssl), kj::mv(inner), |
| 243 |
kj::Badge<TlsConnection>()); |
| 244 |
} |
| 245 |
|
| 246 |
~TlsConnection() noexcept(false) { |
| 247 |
SSL_free(ssl); |
| 248 |
} |
| 249 |
|
| 250 |
kj::Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 251 |
return tryReadInternal(buffer, minBytes, maxBytes, 0); |
| 252 |
} |
| 253 |
|
| 254 |
Promise<void> write(const void* buffer, size_t size) override { |
| 255 |
return writeInternal(kj::arrayPtr(reinterpret_cast<const byte*>(buffer), size), nullptr); |
| 256 |
} |
| 257 |
|
| 258 |
Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override { |
| 259 |
auto cork = writeBuffer.cork(); |
| 260 |
return writeInternal(pieces[0], pieces.slice(1, pieces.size())).attach(kj::mv(cork)); |
| 261 |
} |
| 262 |
|
| 263 |
Promise<void> whenWriteDisconnected() override { |
| 264 |
return inner.whenWriteDisconnected(); |
| 265 |
} |
| 266 |
|
| 267 |
void shutdownWrite() override { |
| 268 |
KJ_REQUIRE(shutdownTask == nullptr, "already called shutdownWrite()"); |
| 269 |
|
| 270 |
// TODO(2.0): shutdownWrite() is problematic because it doesn't return a promise. It was |
| 271 |
// designed to assume that it would only be called after all writes are finished and that |
| 272 |
// there was no reason to block at that point, but SSL sessions don't fit this since they |
| 273 |
// actually have to send a shutdown message. |
| 274 |
shutdownTask = sslCall([this]() { |
| 275 |
// The first SSL_shutdown() call is expected to return 0 and may flag a misleading error. |
| 276 |
int result = SSL_shutdown(ssl); |
| 277 |
return result == 0 ? 1 : result; |
| 278 |
}).ignoreResult().eagerlyEvaluate([](kj::Exception&& e) { |
| 279 |
KJ_LOG(ERROR, e); |
| 280 |
}); |
| 281 |
} |
| 282 |
|
| 283 |
void abortRead() override { |
| 284 |
inner.abortRead(); |
| 285 |
} |
| 286 |
|
| 287 |
void getsockopt(int level, int option, void* value, uint* length) override { |
| 288 |
inner.getsockopt(level, option, value, length); |
| 289 |
} |
| 290 |
void setsockopt(int level, int option, const void* value, uint length) override { |
| 291 |
inner.setsockopt(level, option, value, length); |
| 292 |
} |
| 293 |
|
| 294 |
void getsockname(struct sockaddr* addr, uint* length) override { |
| 295 |
inner.getsockname(addr, length); |
| 296 |
} |
| 297 |
void getpeername(struct sockaddr* addr, uint* length) override { |
| 298 |
inner.getpeername(addr, length); |
| 299 |
} |
| 300 |
|
| 301 |
kj::Maybe<int> getFd() const override { |
| 302 |
return inner.getFd(); |
| 303 |
} |
| 304 |
|
| 305 |
private: |
| 306 |
SSL* ssl; |
| 307 |
kj::AsyncIoStream& inner; |
| 308 |
kj::Own<kj::AsyncIoStream> ownInner; |
| 309 |
|
| 310 |
kj::Maybe<kj::Promise<void>> shutdownTask; |
| 311 |
|
| 312 |
ReadyInputStreamWrapper readBuffer; |
| 313 |
ReadyOutputStreamWrapper writeBuffer; |
| 314 |
|
| 315 |
kj::Promise<size_t> tryReadInternal( |
| 316 |
void* buffer, size_t minBytes, size_t maxBytes, size_t alreadyDone) { |
| 317 |
return sslCall([this,buffer,maxBytes]() { return SSL_read(ssl, buffer, maxBytes); }) |
| 318 |
.then([this,buffer,minBytes,maxBytes,alreadyDone](size_t n) -> kj::Promise<size_t> { |
| 319 |
if (n >= minBytes || n == 0) { |
| 320 |
return alreadyDone + n; |
| 321 |
} else { |
| 322 |
return tryReadInternal(reinterpret_cast<byte*>(buffer) + n, |
| 323 |
minBytes - n, maxBytes - n, alreadyDone + n); |
| 324 |
} |
| 325 |
}); |
| 326 |
} |
| 327 |
|
| 328 |
Promise<void> writeInternal(kj::ArrayPtr<const byte> first, |
| 329 |
kj::ArrayPtr<const kj::ArrayPtr<const byte>> rest) { |
| 330 |
KJ_REQUIRE(shutdownTask == nullptr, "already called shutdownWrite()"); |
| 331 |
|
| 332 |
// SSL_write() with a zero-sized input returns 0, but a 0 return is documented as indicating |
| 333 |
// an error. So, we need to avoid zero-sized writes entirely. |
| 334 |
while (first.size() == 0) { |
| 335 |
if (rest.size() == 0) { |
| 336 |
return kj::READY_NOW; |
| 337 |
} |
| 338 |
first = rest.front(); |
| 339 |
rest = rest.slice(1, rest.size()); |
| 340 |
} |
| 341 |
|
| 342 |
return sslCall([this,first]() { return SSL_write(ssl, first.begin(), first.size()); }) |
| 343 |
.then([this,first,rest](size_t n) -> kj::Promise<void> { |
| 344 |
if (n == 0) { |
| 345 |
return KJ_EXCEPTION(DISCONNECTED, "ssl connection ended during write"); |
| 346 |
} else if (n < first.size()) { |
| 347 |
return writeInternal(first.slice(n, first.size()), rest); |
| 348 |
} else if (rest.size() > 0) { |
| 349 |
return writeInternal(rest[0], rest.slice(1, rest.size())); |
| 350 |
} else { |
| 351 |
return kj::READY_NOW; |
| 352 |
} |
| 353 |
}); |
| 354 |
} |
| 355 |
|
| 356 |
template <typename Func> |
| 357 |
kj::Promise<size_t> sslCall(Func&& func) { |
| 358 |
auto result = func(); |
| 359 |
|
| 360 |
if (result > 0) { |
| 361 |
return result; |
| 362 |
} else { |
| 363 |
int error = SSL_get_error(ssl, result); |
| 364 |
switch (error) { |
| 365 |
case SSL_ERROR_ZERO_RETURN: |
| 366 |
return constPromise<size_t, 0>(); |
| 367 |
case SSL_ERROR_WANT_READ: |
| 368 |
return readBuffer.whenReady().then( |
| 369 |
[this,func=kj::mv(func)]() mutable { return sslCall(kj::fwd<Func>(func)); }); |
| 370 |
case SSL_ERROR_WANT_WRITE: |
| 371 |
return writeBuffer.whenReady().then( |
| 372 |
[this,func=kj::mv(func)]() mutable { return sslCall(kj::fwd<Func>(func)); }); |
| 373 |
case SSL_ERROR_SSL: |
| 374 |
return getOpensslError(); |
| 375 |
case SSL_ERROR_SYSCALL: |
| 376 |
if (result == 0) { |
| 377 |
// OpenSSL pre-3.0 reports unexpected disconnects this way. Note that 3.0+ report it |
| 378 |
// as SSL_ERROR_SSL with the reason SSL_R_UNEXPECTED_EOF_WHILE_READING, which is |
| 379 |
// handled in throwOpensslError(). |
| 380 |
return KJ_EXCEPTION(DISCONNECTED, |
| 381 |
"peer disconnected without gracefully ending TLS session"); |
| 382 |
} else { |
| 383 |
// According to documentation we shouldn't get here, because our BIO never returns an |
| 384 |
// "error". But in practice we do get here sometimes when the peer disconnects |
| 385 |
// prematurely. |
| 386 |
return KJ_EXCEPTION(DISCONNECTED, "SSL unable to continue I/O"); |
| 387 |
} |
| 388 |
default: |
| 389 |
KJ_FAIL_ASSERT("unexpected SSL error code", error); |
| 390 |
} |
| 391 |
} |
| 392 |
} |
| 393 |
|
| 394 |
static int bioRead(BIO* b, char* out, int outl) { |
| 395 |
BIO_clear_retry_flags(b); |
| 396 |
KJ_IF_MAYBE(n, reinterpret_cast<TlsConnection*>(BIO_get_data(b))->readBuffer |
| 397 |
.read(kj::arrayPtr(out, outl).asBytes())) { |
| 398 |
return *n; |
| 399 |
} else { |
| 400 |
BIO_set_retry_read(b); |
| 401 |
return -1; |
| 402 |
} |
| 403 |
} |
| 404 |
|
| 405 |
static int bioWrite(BIO* b, const char* in, int inl) { |
| 406 |
BIO_clear_retry_flags(b); |
| 407 |
KJ_IF_MAYBE(n, reinterpret_cast<TlsConnection*>(BIO_get_data(b))->writeBuffer |
| 408 |
.write(kj::arrayPtr(in, inl).asBytes())) { |
| 409 |
return *n; |
| 410 |
} else { |
| 411 |
BIO_set_retry_write(b); |
| 412 |
return -1; |
| 413 |
} |
| 414 |
} |
| 415 |
|
| 416 |
static long bioCtrl(BIO* b, int cmd, long num, void* ptr) { |
| 417 |
switch (cmd) { |
| 418 |
case BIO_CTRL_EOF: |
| 419 |
return reinterpret_cast<TlsConnection*>(BIO_get_data(b))->readBuffer.isAtEnd(); |
| 420 |
case BIO_CTRL_FLUSH: |
| 421 |
return 1; |
| 422 |
case BIO_CTRL_PUSH: |
| 423 |
case BIO_CTRL_POP: |
| 424 |
// Informational? |
| 425 |
return 0; |
| 426 |
#ifdef BIO_CTRL_GET_KTLS_SEND |
| 427 |
case BIO_CTRL_GET_KTLS_SEND: |
| 428 |
case BIO_CTRL_GET_KTLS_RECV: |
| 429 |
// TODO(someday): Support kTLS if the underlying stream is a raw socket. |
| 430 |
return 0; |
| 431 |
#endif |
| 432 |
default: |
| 433 |
KJ_LOG(WARNING, "unimplemented bio_ctrl", cmd); |
| 434 |
return 0; |
| 435 |
} |
| 436 |
} |
| 437 |
|
| 438 |
static int bioCreate(BIO* b) { |
| 439 |
BIO_set_data(b, nullptr); |
| 440 |
return 1; |
| 441 |
} |
| 442 |
|
| 443 |
static int bioDestroy(BIO* b) { |
| 444 |
// The BIO does NOT own the TlsConnection. |
| 445 |
return 1; |
| 446 |
} |
| 447 |
|
| 448 |
#if OPENSSL_VERSION_NUMBER < 0x10100000L |
| 449 |
static const BIO_METHOD* getBioVtable() { |
| 450 |
static const BIO_METHOD VTABLE { |
| 451 |
BIO_TYPE_SOURCE_SINK, |
| 452 |
"KJ stream", |
| 453 |
TlsConnection::bioWrite, |
| 454 |
TlsConnection::bioRead, |
| 455 |
nullptr, // puts |
| 456 |
nullptr, // gets |
| 457 |
TlsConnection::bioCtrl, |
| 458 |
TlsConnection::bioCreate, |
| 459 |
TlsConnection::bioDestroy, |
| 460 |
nullptr |
| 461 |
}; |
| 462 |
return &VTABLE; |
| 463 |
} |
| 464 |
#else |
| 465 |
static const BIO_METHOD* getBioVtable() { |
| 466 |
static const BIO_METHOD* const vtable = makeBioVtable(); |
| 467 |
return vtable; |
| 468 |
} |
| 469 |
static const BIO_METHOD* makeBioVtable() { |
| 470 |
BIO_METHOD* vtable = BIO_meth_new(BIO_TYPE_SOURCE_SINK, "KJ stream"); |
| 471 |
BIO_meth_set_write(vtable, TlsConnection::bioWrite); |
| 472 |
BIO_meth_set_read(vtable, TlsConnection::bioRead); |
| 473 |
BIO_meth_set_ctrl(vtable, TlsConnection::bioCtrl); |
| 474 |
BIO_meth_set_create(vtable, TlsConnection::bioCreate); |
| 475 |
BIO_meth_set_destroy(vtable, TlsConnection::bioDestroy); |
| 476 |
return vtable; |
| 477 |
} |
| 478 |
#endif |
| 479 |
}; |
| 480 |
|
| 481 |
// ======================================================================================= |
| 482 |
// Implementations of ConnectionReceiver, NetworkAddress, and Network as wrappers adding TLS. |
| 483 |
|
| 484 |
class TlsConnectionReceiver final: public ConnectionReceiver, public TaskSet::ErrorHandler { |
| 485 |
public: |
| 486 |
TlsConnectionReceiver( |
| 487 |
TlsContext &tls, Own<ConnectionReceiver> inner, |
| 488 |
kj::Maybe<TlsErrorHandler> acceptErrorHandler) |
| 489 |
: tls(tls), inner(kj::mv(inner)), |
| 490 |
acceptLoopTask(acceptLoop().eagerlyEvaluate([this](Exception &&e) { |
| 491 |
onAcceptFailure(kj::mv(e)); |
| 492 |
})), |
| 493 |
acceptErrorHandler(kj::mv(acceptErrorHandler)), |
| 494 |
tasks(*this) {} |
| 495 |
|
| 496 |
void taskFailed(Exception&& e) override { |
| 497 |
KJ_IF_MAYBE(handler, acceptErrorHandler){ |
| 498 |
handler->operator()(kj::mv(e)); |
| 499 |
} else if (e.getType() != Exception::Type::DISCONNECTED) { |
| 500 |
KJ_LOG(ERROR, "error accepting tls connection", kj::mv(e)); |
| 501 |
} |
| 502 |
}; |
| 503 |
|
| 504 |
Promise<Own<AsyncIoStream>> accept() override { |
| 505 |
return acceptAuthenticated().then([](AuthenticatedStream&& stream) { |
| 506 |
return kj::mv(stream.stream); |
| 507 |
}); |
| 508 |
} |
| 509 |
|
| 510 |
Promise<AuthenticatedStream> acceptAuthenticated() override { |
| 511 |
KJ_IF_MAYBE(e, maybeInnerException) { |
| 512 |
// We've experienced an exception from the inner receiver, we consider this unrecoverable. |
| 513 |
return Exception(*e); |
| 514 |
} |
| 515 |
|
| 516 |
return queue.pop(); |
| 517 |
} |
| 518 |
|
| 519 |
uint getPort() override { |
| 520 |
return inner->getPort(); |
| 521 |
} |
| 522 |
|
| 523 |
void getsockopt(int level, int option, void* value, uint* length) override { |
| 524 |
return inner->getsockopt(level, option, value, length); |
| 525 |
} |
| 526 |
|
| 527 |
void setsockopt(int level, int option, const void* value, uint length) override { |
| 528 |
return inner->setsockopt(level, option, value, length); |
| 529 |
} |
| 530 |
|
| 531 |
private: |
| 532 |
void onAcceptSuccess(AuthenticatedStream&& stream) { |
| 533 |
// Queue this stream to go through SSL_accept. |
| 534 |
|
| 535 |
auto acceptPromise = kj::evalNow([&] { |
| 536 |
// Do the SSL acceptance procedure. |
| 537 |
return tls.wrapServer(kj::mv(stream)); |
| 538 |
}); |
| 539 |
|
| 540 |
auto sslPromise = acceptPromise.then([this](auto&& stream) -> Promise<void> { |
| 541 |
// This is only attached to the success path, thus the error handler will catch if our |
| 542 |
// promise fails. |
| 543 |
queue.push(kj::mv(stream)); |
| 544 |
return kj::READY_NOW; |
| 545 |
}); |
| 546 |
tasks.add(kj::mv(sslPromise)); |
| 547 |
} |
| 548 |
|
| 549 |
void onAcceptFailure(Exception&& e) { |
| 550 |
// Store this exception to reject all future calls to accept() and reject any unfulfilled |
| 551 |
// promises from the queue. |
| 552 |
maybeInnerException = kj::mv(e); |
| 553 |
queue.rejectAll(Exception(KJ_REQUIRE_NONNULL(maybeInnerException))); |
| 554 |
} |
| 555 |
|
| 556 |
Promise<void> acceptLoop() { |
| 557 |
// Accept one connection and queue up the next accept on our TaskSet. |
| 558 |
|
| 559 |
return inner->acceptAuthenticated().then( |
| 560 |
[this](AuthenticatedStream&& stream) { |
| 561 |
onAcceptSuccess(kj::mv(stream)); |
| 562 |
|
| 563 |
// Queue up the next accept loop immediately without waiting for SSL_accept()/wrapServer(). |
| 564 |
return acceptLoop(); |
| 565 |
}); |
| 566 |
} |
| 567 |
|
| 568 |
TlsContext& tls; |
| 569 |
Own<ConnectionReceiver> inner; |
| 570 |
|
| 571 |
Promise<void> acceptLoopTask; |
| 572 |
ProducerConsumerQueue<AuthenticatedStream> queue; |
| 573 |
kj::Maybe<TlsErrorHandler> acceptErrorHandler; |
| 574 |
TaskSet tasks; |
| 575 |
|
| 576 |
Maybe<Exception> maybeInnerException; |
| 577 |
}; |
| 578 |
|
| 579 |
class TlsNetworkAddress final: public kj::NetworkAddress { |
| 580 |
public: |
| 581 |
TlsNetworkAddress(TlsContext& tls, kj::String hostname, kj::Own<kj::NetworkAddress>&& inner) |
| 582 |
: tls(tls), hostname(kj::mv(hostname)), inner(kj::mv(inner)) {} |
| 583 |
|
| 584 |
Promise<Own<AsyncIoStream>> connect() override { |
| 585 |
// Note: It's unfortunately pretty common for people to assume they can drop the NetworkAddress |
| 586 |
// as soon as connect() returns, and this works with the native network implementation. |
| 587 |
// So, we make some copies here. |
| 588 |
auto& tlsRef = tls; |
| 589 |
auto hostnameCopy = kj::str(hostname); |
| 590 |
return inner->connect().then( |
| 591 |
[&tlsRef,hostname=kj::mv(hostnameCopy)](Own<AsyncIoStream>&& stream) { |
| 592 |
return tlsRef.wrapClient(kj::mv(stream), hostname); |
| 593 |
}); |
| 594 |
} |
| 595 |
|
| 596 |
Promise<kj::AuthenticatedStream> connectAuthenticated() override { |
| 597 |
// Note: It's unfortunately pretty common for people to assume they can drop the NetworkAddress |
| 598 |
// as soon as connect() returns, and this works with the native network implementation. |
| 599 |
// So, we make some copies here. |
| 600 |
auto& tlsRef = tls; |
| 601 |
auto hostnameCopy = kj::str(hostname); |
| 602 |
return inner->connectAuthenticated().then( |
| 603 |
[&tlsRef, hostname = kj::mv(hostnameCopy)](kj::AuthenticatedStream stream) { |
| 604 |
return tlsRef.wrapClient(kj::mv(stream), hostname); |
| 605 |
}); |
| 606 |
} |
| 607 |
|
| 608 |
Own<ConnectionReceiver> listen() override { |
| 609 |
return tls.wrapPort(inner->listen()); |
| 610 |
} |
| 611 |
|
| 612 |
Own<NetworkAddress> clone() override { |
| 613 |
return kj::heap<TlsNetworkAddress>(tls, kj::str(hostname), inner->clone()); |
| 614 |
} |
| 615 |
|
| 616 |
String toString() override { |
| 617 |
return kj::str("tls:", inner->toString()); |
| 618 |
} |
| 619 |
|
| 620 |
private: |
| 621 |
TlsContext& tls; |
| 622 |
kj::String hostname; |
| 623 |
kj::Own<kj::NetworkAddress> inner; |
| 624 |
}; |
| 625 |
|
| 626 |
class TlsNetwork final: public kj::Network { |
| 627 |
public: |
| 628 |
TlsNetwork(TlsContext& tls, kj::Network& inner): tls(tls), inner(inner) {} |
| 629 |
TlsNetwork(TlsContext& tls, kj::Own<kj::Network> inner) |
| 630 |
: tls(tls), inner(*inner), ownInner(kj::mv(inner)) {} |
| 631 |
|
| 632 |
Promise<Own<NetworkAddress>> parseAddress(StringPtr addr, uint portHint) override { |
| 633 |
// We want to parse the hostname or IP address out of `addr`. This is a bit complicated as |
| 634 |
// KJ's default network implementation has a fairly featureful grammar for these things. |
| 635 |
// In particular, we cannot just split on ':' because the address might be IPv6. |
| 636 |
|
| 637 |
kj::String hostname; |
| 638 |
|
| 639 |
if (addr.startsWith("[")) { |
| 640 |
// IPv6, like "[1234:5678::abcd]:123". Take the part between the brackets. |
| 641 |
KJ_IF_MAYBE(pos, addr.findFirst(']')) { |
| 642 |
hostname = kj::str(addr.slice(1, *pos)); |
| 643 |
} else { |
| 644 |
// Uhh??? Just take the whole thing, cert will fail later. |
| 645 |
hostname = kj::heapString(addr); |
| 646 |
} |
| 647 |
} else if (addr.startsWith("unix:") || addr.startsWith("unix-abstract:")) { |
| 648 |
// Unfortunately, `unix:123` is ambiguous (maybe there is a host named "unix"?), but the |
| 649 |
// default KJ network implementation will interpret it as a Unix domain socket address. |
| 650 |
// We don't want TLS to then try to authenticate that as a host named "unix". |
| 651 |
KJ_FAIL_REQUIRE("can't authenticate Unix domain socket with TLS", addr); |
| 652 |
} else { |
| 653 |
uint colons = 0; |
| 654 |
for (auto c: addr) { |
| 655 |
if (c == ':') { |
| 656 |
++colons; |
| 657 |
} |
| 658 |
} |
| 659 |
|
| 660 |
if (colons >= 2) { |
| 661 |
// Must be an IPv6 address. If it had a port, it would have been wrapped in []. So don't |
| 662 |
// strip the port. |
| 663 |
hostname = kj::heapString(addr); |
| 664 |
} else { |
| 665 |
// Assume host:port or ipv4:port. This is a shaky assumption, as the above hacks |
| 666 |
// demonstrate. |
| 667 |
// |
| 668 |
// In theory it might make sense to extend the NetworkAddress interface so that it can tell |
| 669 |
// us what the actual parser decided the hostname is. However, when I tried this it proved |
| 670 |
// rather cumbersome and actually broke code in the Workers Runtime that does complicated |
| 671 |
// stacking of kj::Network implementations. |
| 672 |
KJ_IF_MAYBE(pos, addr.findFirst(':')) { |
| 673 |
hostname = kj::heapString(addr.slice(0, *pos)); |
| 674 |
} else { |
| 675 |
hostname = kj::heapString(addr); |
| 676 |
} |
| 677 |
} |
| 678 |
} |
| 679 |
|
| 680 |
return inner.parseAddress(addr, portHint) |
| 681 |
.then([this, hostname=kj::mv(hostname)](kj::Own<NetworkAddress>&& addr) mutable |
| 682 |
-> kj::Own<kj::NetworkAddress> { |
| 683 |
return kj::heap<TlsNetworkAddress>(tls, kj::mv(hostname), kj::mv(addr)); |
| 684 |
}); |
| 685 |
} |
| 686 |
|
| 687 |
Own<NetworkAddress> getSockaddr(const void* sockaddr, uint len) override { |
| 688 |
KJ_UNIMPLEMENTED("TLS does not implement getSockaddr() because it needs to know hostnames"); |
| 689 |
} |
| 690 |
|
| 691 |
Own<Network> restrictPeers( |
| 692 |
kj::ArrayPtr<const kj::StringPtr> allow, |
| 693 |
kj::ArrayPtr<const kj::StringPtr> deny = nullptr) override { |
| 694 |
// TODO(someday): Maybe we could implement the ability to specify CA or hostname restrictions? |
| 695 |
// Or is it better to let people do that via the TlsContext? A neat thing about |
| 696 |
// restrictPeers() is that it's easy to make user-configurable. |
| 697 |
return kj::heap<TlsNetwork>(tls, inner.restrictPeers(allow, deny)); |
| 698 |
} |
| 699 |
|
| 700 |
private: |
| 701 |
TlsContext& tls; |
| 702 |
kj::Network& inner; |
| 703 |
kj::Own<kj::Network> ownInner; |
| 704 |
}; |
| 705 |
|
| 706 |
// ======================================================================================= |
| 707 |
// class TlsContext |
| 708 |
|
| 709 |
TlsContext::Options::Options() |
| 710 |
: useSystemTrustStore(true), |
| 711 |
verifyClients(false), |
| 712 |
minVersion(TlsVersion::TLS_1_2), |
| 713 |
cipherList("ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305") {} |
| 714 |
// Cipher list is Mozilla's "intermediate" list, except with classic DH removed since we don't |
| 715 |
// currently support setting dhparams. See: |
| 716 |
// https://mozilla.github.io/server-side-tls/ssl-config-generator/ |
| 717 |
// |
| 718 |
// Classic DH is arguably obsolete and will only become more so as time passes, so perhaps we'll |
| 719 |
// never bother. |
| 720 |
|
| 721 |
struct TlsContext::SniCallback { |
| 722 |
// struct SniCallback exists only so that callback() can be declared in the .c++ file, since it |
| 723 |
// references OpenSSL types. |
| 724 |
|
| 725 |
static int callback(SSL* ssl, int* ad, void* arg); |
| 726 |
}; |
| 727 |
|
| 728 |
TlsContext::TlsContext(Options options) { |
| 729 |
ensureOpenSslInitialized(); |
| 730 |
|
| 731 |
#if OPENSSL_VERSION_NUMBER >= 0x10100000L || defined(OPENSSL_IS_BORINGSSL) |
| 732 |
SSL_CTX* ctx = SSL_CTX_new(TLS_method()); |
| 733 |
#else |
| 734 |
SSL_CTX* ctx = SSL_CTX_new(SSLv23_method()); |
| 735 |
#endif |
| 736 |
|
| 737 |
if (ctx == nullptr) { |
| 738 |
throwOpensslError(); |
| 739 |
} |
| 740 |
KJ_ON_SCOPE_FAILURE(SSL_CTX_free(ctx)); |
| 741 |
|
| 742 |
// honor options.useSystemTrustStore |
| 743 |
if (options.useSystemTrustStore) { |
| 744 |
if (!SSL_CTX_set_default_verify_paths(ctx)) { |
| 745 |
throwOpensslError(); |
| 746 |
} |
| 747 |
} |
| 748 |
|
| 749 |
// honor options.trustedCertificates |
| 750 |
if (options.trustedCertificates.size() > 0) { |
| 751 |
X509_STORE* store = SSL_CTX_get_cert_store(ctx); |
| 752 |
if (store == nullptr) { |
| 753 |
throwOpensslError(); |
| 754 |
} |
| 755 |
for (auto& cert: options.trustedCertificates) { |
| 756 |
if (!X509_STORE_add_cert(store, reinterpret_cast<X509*>(cert.chain[0]))) { |
| 757 |
throwOpensslError(); |
| 758 |
} |
| 759 |
} |
| 760 |
} |
| 761 |
|
| 762 |
if (options.verifyClients) { |
| 763 |
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL); |
| 764 |
} |
| 765 |
|
| 766 |
// honor options.minVersion |
| 767 |
long optionFlags = 0; |
| 768 |
if (options.minVersion > TlsVersion::SSL_3) { |
| 769 |
optionFlags |= SSL_OP_NO_SSLv3; |
| 770 |
} |
| 771 |
if (options.minVersion > TlsVersion::TLS_1_0) { |
| 772 |
optionFlags |= SSL_OP_NO_TLSv1; |
| 773 |
} |
| 774 |
if (options.minVersion > TlsVersion::TLS_1_1) { |
| 775 |
optionFlags |= SSL_OP_NO_TLSv1_1; |
| 776 |
} |
| 777 |
if (options.minVersion > TlsVersion::TLS_1_2) { |
| 778 |
optionFlags |= SSL_OP_NO_TLSv1_2; |
| 779 |
} |
| 780 |
if (options.minVersion > TlsVersion::TLS_1_3) { |
| 781 |
#ifdef SSL_OP_NO_TLSv1_3 |
| 782 |
optionFlags |= SSL_OP_NO_TLSv1_3; |
| 783 |
#else |
| 784 |
KJ_FAIL_REQUIRE("OpenSSL headers don't support TLS 1.3"); |
| 785 |
#endif |
| 786 |
} |
| 787 |
SSL_CTX_set_options(ctx, optionFlags); // note: never fails; returns new options bitmask |
| 788 |
|
| 789 |
// honor options.cipherList |
| 790 |
if (!SSL_CTX_set_cipher_list(ctx, options.cipherList.cStr())) { |
| 791 |
throwOpensslError(); |
| 792 |
} |
| 793 |
|
| 794 |
// honor options.defaultKeypair |
| 795 |
KJ_IF_MAYBE(kp, options.defaultKeypair) { |
| 796 |
if (!SSL_CTX_use_PrivateKey(ctx, reinterpret_cast<EVP_PKEY*>(kp->privateKey.pkey))) { |
| 797 |
throwOpensslError(); |
| 798 |
} |
| 799 |
|
| 800 |
if (!SSL_CTX_use_certificate(ctx, reinterpret_cast<X509*>(kp->certificate.chain[0]))) { |
| 801 |
throwOpensslError(); |
| 802 |
} |
| 803 |
|
| 804 |
for (size_t i = 1; i < kj::size(kp->certificate.chain); i++) { |
| 805 |
X509* x509 = reinterpret_cast<X509*>(kp->certificate.chain[i]); |
| 806 |
if (x509 == nullptr) break; // end of chain |
| 807 |
|
| 808 |
if (!SSL_CTX_add_extra_chain_cert(ctx, x509)) { |
| 809 |
throwOpensslError(); |
| 810 |
} |
| 811 |
|
| 812 |
// SSL_CTX_add_extra_chain_cert() does NOT up the refcount itself. |
| 813 |
X509_up_ref(x509); |
| 814 |
} |
| 815 |
} |
| 816 |
|
| 817 |
// honor options.sniCallback |
| 818 |
KJ_IF_MAYBE(sni, options.sniCallback) { |
| 819 |
SSL_CTX_set_tlsext_servername_callback(ctx, &SniCallback::callback); |
| 820 |
SSL_CTX_set_tlsext_servername_arg(ctx, sni); |
| 821 |
} |
| 822 |
|
| 823 |
KJ_IF_MAYBE(timeout, options.acceptTimeout) { |
| 824 |
this->timer = KJ_REQUIRE_NONNULL(options.timer, |
| 825 |
"acceptTimeout option requires that a timer is also provided"); |
| 826 |
this->acceptTimeout = *timeout; |
| 827 |
} |
| 828 |
|
| 829 |
this->acceptErrorHandler = kj::mv(options.acceptErrorHandler); |
| 830 |
|
| 831 |
this->ctx = ctx; |
| 832 |
} |
| 833 |
|
| 834 |
int TlsContext::SniCallback::callback(SSL* ssl, int* ad, void* arg) { |
| 835 |
// The third parameter is actually type TlsSniCallback*. |
| 836 |
|
| 837 |
KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() { |
| 838 |
TlsSniCallback& sni = *reinterpret_cast<TlsSniCallback*>(arg); |
| 839 |
|
| 840 |
const char* name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); |
| 841 |
if (name != nullptr) { |
| 842 |
KJ_IF_MAYBE(kp, sni.getKey(name)) { |
| 843 |
if (!SSL_use_PrivateKey(ssl, reinterpret_cast<EVP_PKEY*>(kp->privateKey.pkey))) { |
| 844 |
throwOpensslError(); |
| 845 |
} |
| 846 |
|
| 847 |
if (!SSL_use_certificate(ssl, reinterpret_cast<X509*>(kp->certificate.chain[0]))) { |
| 848 |
throwOpensslError(); |
| 849 |
} |
| 850 |
|
| 851 |
if (!SSL_clear_chain_certs(ssl)) { |
| 852 |
throwOpensslError(); |
| 853 |
} |
| 854 |
|
| 855 |
for (size_t i = 1; i < kj::size(kp->certificate.chain); i++) { |
| 856 |
X509* x509 = reinterpret_cast<X509*>(kp->certificate.chain[i]); |
| 857 |
if (x509 == nullptr) break; // end of chain |
| 858 |
|
| 859 |
if (!SSL_add0_chain_cert(ssl, x509)) { |
| 860 |
throwOpensslError(); |
| 861 |
} |
| 862 |
|
| 863 |
// SSL_add0_chain_cert() does NOT up the refcount itself. |
| 864 |
X509_up_ref(x509); |
| 865 |
} |
| 866 |
} |
| 867 |
} |
| 868 |
})) { |
| 869 |
KJ_LOG(ERROR, "exception when invoking SNI callback", *exception); |
| 870 |
*ad = SSL_AD_INTERNAL_ERROR; |
| 871 |
return SSL_TLSEXT_ERR_ALERT_FATAL; |
| 872 |
} |
| 873 |
|
| 874 |
return SSL_TLSEXT_ERR_OK; |
| 875 |
} |
| 876 |
|
| 877 |
TlsContext::~TlsContext() noexcept(false) { |
| 878 |
SSL_CTX_free(reinterpret_cast<SSL_CTX*>(ctx)); |
| 879 |
} |
| 880 |
|
| 881 |
kj::Promise<kj::Own<kj::AsyncIoStream>> TlsContext::wrapClient( |
| 882 |
kj::Own<kj::AsyncIoStream> stream, kj::StringPtr expectedServerHostname) { |
| 883 |
auto conn = kj::heap<TlsConnection>(kj::mv(stream), reinterpret_cast<SSL_CTX*>(ctx)); |
| 884 |
auto promise = conn->connect(expectedServerHostname); |
| 885 |
return promise.then([conn=kj::mv(conn)]() mutable |
| 886 |
-> kj::Own<kj::AsyncIoStream> { |
| 887 |
return kj::mv(conn); |
| 888 |
}); |
| 889 |
} |
| 890 |
|
| 891 |
kj::Promise<kj::Own<kj::AsyncIoStream>> TlsContext::wrapServer(kj::Own<kj::AsyncIoStream> stream) { |
| 892 |
auto conn = kj::heap<TlsConnection>(kj::mv(stream), reinterpret_cast<SSL_CTX*>(ctx)); |
| 893 |
auto promise = conn->accept(); |
| 894 |
KJ_IF_MAYBE(timeout, acceptTimeout) { |
| 895 |
promise = KJ_REQUIRE_NONNULL(timer).afterDelay(*timeout).then([]() -> kj::Promise<void> { |
| 896 |
return KJ_EXCEPTION(DISCONNECTED, "timed out waiting for client during TLS handshake"); |
| 897 |
}).exclusiveJoin(kj::mv(promise)); |
| 898 |
} |
| 899 |
return promise.then([conn=kj::mv(conn)]() mutable |
| 900 |
-> kj::Own<kj::AsyncIoStream> { |
| 901 |
return kj::mv(conn); |
| 902 |
}); |
| 903 |
} |
| 904 |
|
| 905 |
kj::Promise<kj::AuthenticatedStream> TlsContext::wrapClient( |
| 906 |
kj::AuthenticatedStream stream, kj::StringPtr expectedServerHostname) { |
| 907 |
auto conn = kj::heap<TlsConnection>(kj::mv(stream.stream), reinterpret_cast<SSL_CTX*>(ctx)); |
| 908 |
auto promise = conn->connect(expectedServerHostname); |
| 909 |
return promise.then([conn=kj::mv(conn),innerId=kj::mv(stream.peerIdentity)]() mutable { |
| 910 |
auto id = conn->getIdentity(kj::mv(innerId)); |
| 911 |
return kj::AuthenticatedStream { kj::mv(conn), kj::mv(id) }; |
| 912 |
}); |
| 913 |
} |
| 914 |
|
| 915 |
kj::Promise<kj::AuthenticatedStream> TlsContext::wrapServer(kj::AuthenticatedStream stream) { |
| 916 |
auto conn = kj::heap<TlsConnection>(kj::mv(stream.stream), reinterpret_cast<SSL_CTX*>(ctx)); |
| 917 |
auto promise = conn->accept(); |
| 918 |
KJ_IF_MAYBE(timeout, acceptTimeout) { |
| 919 |
promise = KJ_REQUIRE_NONNULL(timer).afterDelay(*timeout).then([]() -> kj::Promise<void> { |
| 920 |
return KJ_EXCEPTION(DISCONNECTED, "timed out waiting for client during TLS handshake"); |
| 921 |
}).exclusiveJoin(kj::mv(promise)); |
| 922 |
} |
| 923 |
return promise.then([conn=kj::mv(conn),innerId=kj::mv(stream.peerIdentity)]() mutable { |
| 924 |
auto id = conn->getIdentity(kj::mv(innerId)); |
| 925 |
return kj::AuthenticatedStream { kj::mv(conn), kj::mv(id) }; |
| 926 |
}); |
| 927 |
} |
| 928 |
|
| 929 |
kj::Own<kj::ConnectionReceiver> TlsContext::wrapPort(kj::Own<kj::ConnectionReceiver> port) { |
| 930 |
auto handler = acceptErrorHandler.map([](TlsErrorHandler& handler) { |
| 931 |
return handler.reference(); |
| 932 |
}); |
| 933 |
return kj::heap<TlsConnectionReceiver>(*this, kj::mv(port), kj::mv(handler)); |
| 934 |
} |
| 935 |
|
| 936 |
kj::Own<kj::NetworkAddress> TlsContext::wrapAddress( |
| 937 |
kj::Own<kj::NetworkAddress> address, kj::StringPtr expectedServerHostname) { |
| 938 |
return kj::heap<TlsNetworkAddress>(*this, kj::str(expectedServerHostname), kj::mv(address)); |
| 939 |
} |
| 940 |
|
| 941 |
kj::Own<kj::Network> TlsContext::wrapNetwork(kj::Network& network) { |
| 942 |
return kj::heap<TlsNetwork>(*this, network); |
| 943 |
} |
| 944 |
|
| 945 |
// ======================================================================================= |
| 946 |
// class TlsPrivateKey |
| 947 |
|
| 948 |
TlsPrivateKey::TlsPrivateKey(kj::ArrayPtr<const byte> asn1) { |
| 949 |
ensureOpenSslInitialized(); |
| 950 |
|
| 951 |
const byte* ptr = asn1.begin(); |
| 952 |
pkey = d2i_AutoPrivateKey(nullptr, &ptr, asn1.size()); |
| 953 |
if (pkey == nullptr) { |
| 954 |
throwOpensslError(); |
| 955 |
} |
| 956 |
} |
| 957 |
|
| 958 |
TlsPrivateKey::TlsPrivateKey(kj::StringPtr pem, kj::Maybe<kj::StringPtr> password) { |
| 959 |
ensureOpenSslInitialized(); |
| 960 |
|
| 961 |
// const_cast apparently needed for older versions of OpenSSL. |
| 962 |
BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem.begin()), pem.size()); |
| 963 |
KJ_DEFER(BIO_free(bio)); |
| 964 |
|
| 965 |
pkey = PEM_read_bio_PrivateKey(bio, nullptr, &passwordCallback, &password); |
| 966 |
if (pkey == nullptr) { |
| 967 |
throwOpensslError(); |
| 968 |
} |
| 969 |
} |
| 970 |
|
| 971 |
TlsPrivateKey::TlsPrivateKey(const TlsPrivateKey& other) |
| 972 |
: pkey(other.pkey) { |
| 973 |
if (pkey != nullptr) EVP_PKEY_up_ref(reinterpret_cast<EVP_PKEY*>(pkey)); |
| 974 |
} |
| 975 |
|
| 976 |
TlsPrivateKey& TlsPrivateKey::operator=(const TlsPrivateKey& other) { |
| 977 |
if (pkey != other.pkey) { |
| 978 |
EVP_PKEY_free(reinterpret_cast<EVP_PKEY*>(pkey)); |
| 979 |
pkey = other.pkey; |
| 980 |
if (pkey != nullptr) EVP_PKEY_up_ref(reinterpret_cast<EVP_PKEY*>(pkey)); |
| 981 |
} |
| 982 |
return *this; |
| 983 |
} |
| 984 |
|
| 985 |
TlsPrivateKey::~TlsPrivateKey() noexcept(false) { |
| 986 |
EVP_PKEY_free(reinterpret_cast<EVP_PKEY*>(pkey)); |
| 987 |
} |
| 988 |
|
| 989 |
int TlsPrivateKey::passwordCallback(char* buf, int size, int rwflag, void* u) { |
| 990 |
auto& password = *reinterpret_cast<kj::Maybe<kj::StringPtr>*>(u); |
| 991 |
|
| 992 |
KJ_IF_MAYBE(p, password) { |
| 993 |
int result = kj::min(p->size(), size); |
| 994 |
memcpy(buf, p->begin(), result); |
| 995 |
return result; |
| 996 |
} else { |
| 997 |
return 0; |
| 998 |
} |
| 999 |
} |
| 1000 |
|
| 1001 |
// ======================================================================================= |
| 1002 |
// class TlsCertificate |
| 1003 |
|
| 1004 |
TlsCertificate::TlsCertificate(kj::ArrayPtr<const kj::ArrayPtr<const byte>> asn1) { |
| 1005 |
ensureOpenSslInitialized(); |
| 1006 |
|
| 1007 |
KJ_REQUIRE(asn1.size() > 0, "must provide at least one certificate in chain"); |
| 1008 |
KJ_REQUIRE(asn1.size() <= kj::size(chain), |
| 1009 |
"exceeded maximum certificate chain length of 10"); |
| 1010 |
|
| 1011 |
memset(chain, 0, sizeof(chain)); |
| 1012 |
|
| 1013 |
for (auto i: kj::indices(asn1)) { |
| 1014 |
auto p = asn1[i].begin(); |
| 1015 |
|
| 1016 |
// "_AUX" apparently refers to some auxiliary information that can be appended to the |
| 1017 |
// certificate, but should only be trusted for your own certificate, not the whole chain?? |
| 1018 |
// I don't really know, I'm just cargo-culting. |
| 1019 |
chain[i] = i == 0 ? d2i_X509_AUX(nullptr, &p, asn1[i].size()) |
| 1020 |
: d2i_X509(nullptr, &p, asn1[i].size()); |
| 1021 |
|
| 1022 |
if (chain[i] == nullptr) { |
| 1023 |
for (size_t j = 0; j < i; j++) { |
| 1024 |
X509_free(reinterpret_cast<X509*>(chain[j])); |
| 1025 |
} |
| 1026 |
throwOpensslError(); |
| 1027 |
} |
| 1028 |
} |
| 1029 |
} |
| 1030 |
|
| 1031 |
TlsCertificate::TlsCertificate(kj::ArrayPtr<const byte> asn1) |
| 1032 |
: TlsCertificate(kj::arrayPtr(&asn1, 1)) {} |
| 1033 |
|
| 1034 |
TlsCertificate::TlsCertificate(kj::StringPtr pem) { |
| 1035 |
ensureOpenSslInitialized(); |
| 1036 |
|
| 1037 |
memset(chain, 0, sizeof(chain)); |
| 1038 |
|
| 1039 |
// const_cast apparently needed for older versions of OpenSSL. |
| 1040 |
BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem.begin()), pem.size()); |
| 1041 |
KJ_DEFER(BIO_free(bio)); |
| 1042 |
|
| 1043 |
for (auto i: kj::indices(chain)) { |
| 1044 |
// "_AUX" apparently refers to some auxiliary information that can be appended to the |
| 1045 |
// certificate, but should only be trusted for your own certificate, not the whole chain?? |
| 1046 |
// I don't really know, I'm just cargo-culting. |
| 1047 |
chain[i] = i == 0 ? PEM_read_bio_X509_AUX(bio, nullptr, nullptr, nullptr) |
| 1048 |
: PEM_read_bio_X509(bio, nullptr, nullptr, nullptr); |
| 1049 |
|
| 1050 |
if (chain[i] == nullptr) { |
| 1051 |
auto error = ERR_peek_last_error(); |
| 1052 |
if (i > 0 && ERR_GET_LIB(error) == ERR_LIB_PEM && |
| 1053 |
ERR_GET_REASON(error) == PEM_R_NO_START_LINE) { |
| 1054 |
// EOF; we're done. |
| 1055 |
ERR_clear_error(); |
| 1056 |
return; |
| 1057 |
} else { |
| 1058 |
for (size_t j = 0; j < i; j++) { |
| 1059 |
X509_free(reinterpret_cast<X509*>(chain[j])); |
| 1060 |
} |
| 1061 |
throwOpensslError(); |
| 1062 |
} |
| 1063 |
} |
| 1064 |
} |
| 1065 |
|
| 1066 |
// We reached the chain length limit. Try to read one more to verify that the chain ends here. |
| 1067 |
X509* dummy = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr); |
| 1068 |
if (dummy != nullptr) { |
| 1069 |
X509_free(dummy); |
| 1070 |
for (auto i: kj::indices(chain)) { |
| 1071 |
X509_free(reinterpret_cast<X509*>(chain[i])); |
| 1072 |
} |
| 1073 |
KJ_FAIL_REQUIRE("exceeded maximum certificate chain length of 10"); |
| 1074 |
} |
| 1075 |
} |
| 1076 |
|
| 1077 |
TlsCertificate::TlsCertificate(const TlsCertificate& other) { |
| 1078 |
memcpy(chain, other.chain, sizeof(chain)); |
| 1079 |
for (void* p: chain) { |
| 1080 |
if (p == nullptr) break; // end of chain; quit early |
| 1081 |
X509_up_ref(reinterpret_cast<X509*>(p)); |
| 1082 |
} |
| 1083 |
} |
| 1084 |
|
| 1085 |
TlsCertificate& TlsCertificate::operator=(const TlsCertificate& other) { |
| 1086 |
for (auto i: kj::indices(chain)) { |
| 1087 |
if (chain[i] != other.chain[i]) { |
| 1088 |
EVP_PKEY_free(reinterpret_cast<EVP_PKEY*>(chain[i])); |
| 1089 |
chain[i] = other.chain[i]; |
| 1090 |
if (chain[i] != nullptr) X509_up_ref(reinterpret_cast<X509*>(chain[i])); |
| 1091 |
} else if (chain[i] == nullptr) { |
| 1092 |
// end of both chains; quit early |
| 1093 |
break; |
| 1094 |
} |
| 1095 |
} |
| 1096 |
return *this; |
| 1097 |
} |
| 1098 |
|
| 1099 |
TlsCertificate::~TlsCertificate() noexcept(false) { |
| 1100 |
for (void* p: chain) { |
| 1101 |
if (p == nullptr) break; // end of chain; quit early |
| 1102 |
X509_free(reinterpret_cast<X509*>(p)); |
| 1103 |
} |
| 1104 |
} |
| 1105 |
|
| 1106 |
// ======================================================================================= |
| 1107 |
// class TlsPeerIdentity |
| 1108 |
|
| 1109 |
TlsPeerIdentity::~TlsPeerIdentity() noexcept(false) { |
| 1110 |
if (cert != nullptr) { |
| 1111 |
X509_free(reinterpret_cast<X509*>(cert)); |
| 1112 |
} |
| 1113 |
} |
| 1114 |
|
| 1115 |
kj::String TlsPeerIdentity::toString() { |
| 1116 |
if (hasCertificate()) { |
| 1117 |
return getCommonName(); |
| 1118 |
} else { |
| 1119 |
return kj::str("(anonymous client)"); |
| 1120 |
} |
| 1121 |
} |
| 1122 |
|
| 1123 |
kj::String TlsPeerIdentity::getCommonName() { |
| 1124 |
if (cert == nullptr) { |
| 1125 |
KJ_FAIL_REQUIRE("client did not provide a certificate") { return nullptr; } |
| 1126 |
} |
| 1127 |
|
| 1128 |
X509_NAME* subj = X509_get_subject_name(reinterpret_cast<X509*>(cert)); |
| 1129 |
|
| 1130 |
int index = X509_NAME_get_index_by_NID(subj, NID_commonName, -1); |
| 1131 |
KJ_ASSERT(index != -1, "certificate has no common name?"); |
| 1132 |
X509_NAME_ENTRY* entry = X509_NAME_get_entry(subj, index); |
| 1133 |
KJ_ASSERT(entry != nullptr); |
| 1134 |
ASN1_STRING* data = X509_NAME_ENTRY_get_data(entry); |
| 1135 |
KJ_ASSERT(data != nullptr); |
| 1136 |
|
| 1137 |
unsigned char* out = nullptr; |
| 1138 |
int len = ASN1_STRING_to_UTF8(&out, data); |
| 1139 |
KJ_ASSERT(len >= 0); |
| 1140 |
KJ_DEFER(OPENSSL_free(out)); |
| 1141 |
|
| 1142 |
return kj::heapString(reinterpret_cast<char*>(out), len); |
| 1143 |
} |
| 1144 |
|
| 1145 |
} // namespace kj |
| 1146 |
|
| 1147 |
#endif // KJ_HAS_OPENSSL |