Compare commits
3
Commits
4bfede1342
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a8514d9689 | ||
|
|
c0e1d87ac1 | ||
|
|
4918654715 |
No files matched your search
@@ -11,6 +11,17 @@ namespace core {
|
|||||||
|
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_2) << "EPoll starting.";
|
coreutils::Log(coreutils::LOG_DEBUG_2) << "EPoll starting.";
|
||||||
|
|
||||||
|
// Writing to a socket whose peer has already reset it raises
|
||||||
|
// SIGPIPE, and the default action terminates the whole process -
|
||||||
|
// every connection, not just the dead one. Socket.cpp has carried a
|
||||||
|
// sigpipe_handler for this but nothing ever installed it. Plain
|
||||||
|
// writes could use MSG_NOSIGNAL, but OpenSSL's SSL_write() calls
|
||||||
|
// write() itself, so the signal has to be ignored process-wide; the
|
||||||
|
// failed write then just returns EPIPE and that one connection is
|
||||||
|
// closed normally. Reproduced: a burst of STARTTLS clients
|
||||||
|
// disconnecting mid-session killed the server within a few rounds.
|
||||||
|
signal(SIGPIPE, SIG_IGN);
|
||||||
|
|
||||||
maxSockets = 1000;
|
maxSockets = 1000;
|
||||||
epfd = epoll_create1(0);
|
epfd = epoll_create1(0);
|
||||||
terminateThreads = false;
|
terminateThreads = false;
|
||||||
|
|||||||
+11
-4
@@ -38,15 +38,22 @@ namespace core {
|
|||||||
return (sockaddr *)&addr;
|
return (sockaddr *)&addr;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Was a stub that always returned "" - so everything keyed on the
|
||||||
|
// client address (SPF checks in BARANTMail, Received: headers,
|
||||||
|
// IPAddressList black/white lists) silently saw an empty string.
|
||||||
std::string IPAddress::getClientAddress() {
|
std::string IPAddress::getClientAddress() {
|
||||||
std::string result;
|
char text[INET_ADDRSTRLEN];
|
||||||
return result;
|
if (!inet_ntop(AF_INET, &addr.sin_addr, text, sizeof(text)))
|
||||||
|
return "";
|
||||||
|
return text;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string IPAddress::getClientAddressAndPort() {
|
std::string IPAddress::getClientAddressAndPort() {
|
||||||
std::stringstream out;
|
std::stringstream out;
|
||||||
out << inet_ntoa(addr.sin_addr);
|
// inet_ntoa() returns a static buffer shared by every thread, and
|
||||||
out << ":" << addr.sin_port;
|
// sin_port is in network byte order.
|
||||||
|
out << getClientAddress();
|
||||||
|
out << ":" << ntohs(addr.sin_port);
|
||||||
return out.str();
|
return out.str();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+24
@@ -4,6 +4,8 @@
|
|||||||
#include "Log.h"
|
#include "Log.h"
|
||||||
#include "ZString.h"
|
#include "ZString.h"
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
#include <poll.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
|
|
||||||
namespace core
|
namespace core
|
||||||
{
|
{
|
||||||
@@ -247,6 +249,28 @@ namespace core
|
|||||||
return ::write(descriptor, data, length);
|
return ::write(descriptor, data, length);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool Socket::flushPlain(int timeoutMs) {
|
||||||
|
std::lock_guard<std::mutex> guard(outlock);
|
||||||
|
while(fifo.size() > 0) {
|
||||||
|
std::string &front = fifo.front();
|
||||||
|
ssize_t sent = ::send(descriptor, front.data(), front.length(), MSG_NOSIGNAL);
|
||||||
|
if(sent > 0) {
|
||||||
|
if((size_t)sent >= front.length())
|
||||||
|
fifo.pop();
|
||||||
|
else
|
||||||
|
front.erase(0, sent);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if(sent < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) {
|
||||||
|
struct pollfd pfd = { descriptor, POLLOUT, 0 };
|
||||||
|
if(::poll(&pfd, 1, timeoutMs) > 0)
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
void Socket::writeSocket() {
|
void Socket::writeSocket() {
|
||||||
outlock.lock();
|
outlock.lock();
|
||||||
// coreutils::Log(coreutils::LOG_DEBUG_3) << "writing data to socket " << getDescriptor();
|
// coreutils::Log(coreutils::LOG_DEBUG_3) << "writing data to socket " << getDescriptor();
|
||||||
|
|||||||
@@ -211,6 +211,22 @@ namespace core {
|
|||||||
|
|
||||||
virtual bool sendNeedsRead() { return false; }
|
virtual bool sendNeedsRead() { return false; }
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Synchronously write everything queued in the outbound fifo as
|
||||||
|
/// plain bytes (never through a TLS layer), waiting up to timeoutMs
|
||||||
|
/// for the socket to accept it. Returns false if it couldn't.
|
||||||
|
///
|
||||||
|
/// Only for protocol upgrades (STARTTLS): the server's "go ahead"
|
||||||
|
/// reply has to reach the client in clear text, and the switch to
|
||||||
|
/// TLS has to happen right after the last byte of it - not whenever
|
||||||
|
/// a later EPOLLWRNORM gets around to draining the fifo, by which
|
||||||
|
/// point the session would already be reading TLS. Must be called
|
||||||
|
/// from inside this socket's own eventReceived() (EPOLLONESHOT then
|
||||||
|
/// guarantees no other thread is writing to the fd).
|
||||||
|
///
|
||||||
|
|
||||||
|
bool flushPlain(int timeoutMs);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|
||||||
std::string text;
|
std::string text;
|
||||||
|
|||||||
+97
-55
@@ -25,12 +25,26 @@ namespace core {
|
|||||||
commands.add(subscriptions, "event");
|
commands.add(subscriptions, "event");
|
||||||
commands.add(subscriptions, "invite");
|
commands.add(subscriptions, "invite");
|
||||||
|
|
||||||
setDescriptor(socket(AF_INET, SOCK_STREAM, 0));
|
// Bind, listen and register as a known listening socket BEFORE
|
||||||
|
// setDescriptor() adds the fd to epoll. setDescriptor() arms it
|
||||||
|
// immediately (EPOLLONESHOT), and a brand-new socket that isn't
|
||||||
|
// listening yet reports EPOLLHUP right away. That event used to race
|
||||||
|
// the rest of this constructor: whenever an epoll worker thread
|
||||||
|
// picked it up before the listeningSockets().insert() below,
|
||||||
|
// Thread::run() didn't recognize the pointer and skipped it without
|
||||||
|
// re-arming, so the one-shot registration was spent and the server
|
||||||
|
// never saw another connection - up, bound and listening, but
|
||||||
|
// silently accepting nothing for the life of the process. Reproduced
|
||||||
|
// on an unmodified build: roughly 3 startups in 8 dead on arrival.
|
||||||
|
int fd = socket(AF_INET, SOCK_STREAM, 0);
|
||||||
int yes = 1;
|
int yes = 1;
|
||||||
setsockopt(getDescriptor(), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
|
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
|
||||||
|
|
||||||
if (bind(getDescriptor(), address.getPointer(), address.addressLength) < 0)
|
if (bind(fd, address.getPointer(), address.addressLength) < 0) {
|
||||||
throw coreutils::Exception("Error on bind to socket: " + std::to_string(errno));
|
int error = errno;
|
||||||
|
close(fd);
|
||||||
|
throw coreutils::Exception("Error on bind to socket: " + std::to_string(error));
|
||||||
|
}
|
||||||
|
|
||||||
// Was 20 - small enough that a burst of connection attempts
|
// Was 20 - small enough that a burst of connection attempts
|
||||||
// arriving faster than this process calls accept() (a port scan,
|
// arriving faster than this process calls accept() (a port scan,
|
||||||
@@ -39,16 +53,17 @@ namespace core {
|
|||||||
// application layer gets a chance to drain it, silently dropping
|
// application layer gets a chance to drain it, silently dropping
|
||||||
// the overflow SYNs rather than queuing them. 128 gives real
|
// the overflow SYNs rather than queuing them. 128 gives real
|
||||||
// bursts meaningfully more headroom; still bounded, not unlimited.
|
// bursts meaningfully more headroom; still bounded, not unlimited.
|
||||||
if (listen(getDescriptor(), 128) < 0)
|
if (listen(fd, 128) < 0) {
|
||||||
throw coreutils::Exception("Error on listen to socket");
|
close(fd);
|
||||||
|
throw coreutils::Exception("Error on listen to socket");
|
||||||
|
}
|
||||||
|
|
||||||
// See isKnownListeningSocket()'s own doc comment - registers this
|
|
||||||
// listening socket as safe for Thread::run() to dispatch to
|
|
||||||
// directly, distinct from the shared_ptr-owned TCPSession registry.
|
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> guard(listeningSocketsMutex());
|
std::lock_guard<std::mutex> guard(listeningSocketsMutex());
|
||||||
listeningSockets().insert(this);
|
listeningSockets().insert(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setDescriptor(fd);
|
||||||
}
|
}
|
||||||
|
|
||||||
TCPServer::~TCPServer() {
|
TCPServer::~TCPServer() {
|
||||||
@@ -63,33 +78,12 @@ namespace core {
|
|||||||
// comment), and this mutex isn't recursive.
|
// comment), and this mutex isn't recursive.
|
||||||
sweepStaleSessions();
|
sweepStaleSessions();
|
||||||
lock.lock();
|
lock.lock();
|
||||||
TCPSession *session = accept();
|
// accept() now adds the session to `sessions` and the live registry
|
||||||
// The shared_ptr constructed here IS the session's real, strong
|
// itself, before its fd is armed - see the comment there.
|
||||||
// ownership from now on (see sessions' own doc comment). A second
|
// accept() registers the session and, for an implicit-TLS listener,
|
||||||
// reference to the SAME shared_ptr (never a second, independent
|
// starts its TLS handshake (on the session, not on `this`) before
|
||||||
// std::shared_ptr<TCPSession>(session) call on the same raw
|
// arming the fd - see its own comment.
|
||||||
// pointer - that would create a second, competing control block
|
accept();
|
||||||
// and a guaranteed double-free) also goes into the tryGet()
|
|
||||||
// registry, which is what Thread::run()'s epoll dispatch actually
|
|
||||||
// uses to safely reach this object (see TCPSession::tryGet()'s
|
|
||||||
// own comment on why).
|
|
||||||
if (session) {
|
|
||||||
auto sessionPtr = std::shared_ptr<TCPSession>(session);
|
|
||||||
sessions.push_back(sessionPtr);
|
|
||||||
TCPSession::registerLive(session, sessionPtr);
|
|
||||||
}
|
|
||||||
// Must run ON THE SESSION, not `this` (the listening server) - the
|
|
||||||
// unqualified registerSocket()/acceptSocket() calls this replaced
|
|
||||||
// built the SSL* handshake state on the SERVER's own TLS-base
|
|
||||||
// member instead of the newly accepted session's, leaving every
|
|
||||||
// session's own `ssl` uninitialized and segfaulting the first time
|
|
||||||
// real data arrived on it (SSL_read() against a never-SSL_new()'d
|
|
||||||
// pointer - confirmed via gdb). Sessions already correctly inherit
|
|
||||||
// this server's SSL_CTX at construction (TCPSession's own
|
|
||||||
// TLS(SSL_CTX*)-taking constructor) - performTLSHandshake() just
|
|
||||||
// needed to actually be invoked on that object.
|
|
||||||
if (session && tlsInfo)
|
|
||||||
session->performTLSHandshake();
|
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,6 +114,10 @@ namespace core {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void TCPServer::enableStartTLS(TLSInfo &tlsInfo) {
|
||||||
|
startTLSContext = TLS::buildContext(&tlsInfo);
|
||||||
|
}
|
||||||
|
|
||||||
void TCPServer::receiveData(coreutils::ZString &buffer) {
|
void TCPServer::receiveData(coreutils::ZString &buffer) {
|
||||||
// See this override's own doc comment in TCPServer.h - the
|
// See this override's own doc comment in TCPServer.h - the
|
||||||
// listening socket always uses the plain read()/ENOTCONN detection
|
// listening socket always uses the plain read()/ENOTCONN detection
|
||||||
@@ -130,30 +128,74 @@ namespace core {
|
|||||||
|
|
||||||
TCPSession * TCPServer::accept() {
|
TCPSession * TCPServer::accept() {
|
||||||
|
|
||||||
try
|
// Called with `lock` held (connectionRequest()).
|
||||||
{
|
//
|
||||||
|
// The session must be owned by `sessions` and registered with
|
||||||
|
// TCPSession::registerLive() BEFORE setDescriptor() adds its fd to
|
||||||
|
// epoll. setDescriptor() arms the fd and runs onConnected(), which
|
||||||
|
// queues the protocol greeting ("220 ..." for SMTP) and re-arms for
|
||||||
|
// EPOLLWRNORM; another epoll worker can pick that event up at once.
|
||||||
|
// Registration used to happen afterwards, back in
|
||||||
|
// connectionRequest(), so whenever a worker got there first
|
||||||
|
// Thread::run()'s TCPSession::tryGet() didn't know the pointer and
|
||||||
|
// dropped the event without re-arming (EPOLLONESHOT): the client
|
||||||
|
// was connected but never received a single byte. Reproduced on an
|
||||||
|
// unmodified build with 40 simultaneous plain-text SMTP
|
||||||
|
// connections - 4 to 6 per burst stuck before the greeting. For a
|
||||||
|
// mail server that is lost (well, deferred) inbound mail.
|
||||||
|
//
|
||||||
|
// Accepting into a local address first also means a failed
|
||||||
|
// ::accept() (EAGAIN on a spurious wakeup, EMFILE) no longer creates
|
||||||
|
// - and then leaks - a session object at all.
|
||||||
|
|
||||||
TCPSession *session = getSocketAccept(ePoll);
|
struct sockaddr_in address;
|
||||||
session->setDescriptor(::accept(getDescriptor(), (struct sockaddr *)&session->ipAddress.addr, &session->ipAddress.addressLength));
|
socklen_t addressLength = sizeof(address);
|
||||||
// if(blackList && blackList->contains(session->ipAddress.getClientAddress())) {
|
int fd = ::accept(getDescriptor(), (struct sockaddr *)&address, &addressLength);
|
||||||
// session->shutdown();
|
if (fd < 0) {
|
||||||
// Log(LOG_WARN) << "Client at IP address " << session->ipAddress.getClientAddress() << " is blacklisted and was denied a connection.";
|
if (errno == EMFILE || errno == ENFILE)
|
||||||
// return NULL;
|
coreutils::Log(coreutils::LOG_EXCEPT) << "Too many files open. Refusing connection.";
|
||||||
// }
|
return NULL;
|
||||||
// if(whiteList && !whiteList->contains(session->ipAddress.getClientAddress())) {
|
|
||||||
// session->shutdown();
|
|
||||||
// Log(LOG_WARN) << "Client at IP address " << session->ipAddress.getClientAddress() << " is not authorized and was denied a connection.";
|
|
||||||
// return NULL;
|
|
||||||
// }
|
|
||||||
return session;
|
|
||||||
}
|
}
|
||||||
catch (coreutils::Exception e) {
|
|
||||||
coreutils::Log(coreutils::LOG_EXCEPT) << "Major error on session initialization. Error is '" << e.text << "'.";
|
TCPSession *session = NULL;
|
||||||
|
try {
|
||||||
|
session = getSocketAccept(ePoll);
|
||||||
}
|
}
|
||||||
catch (...) {
|
catch (...) {
|
||||||
coreutils::Log(coreutils::LOG_EXCEPT) << "Unnspecified error on session initialization.";
|
coreutils::Log(coreutils::LOG_EXCEPT) << "Error creating session object; connection refused.";
|
||||||
|
close(fd);
|
||||||
|
return NULL;
|
||||||
}
|
}
|
||||||
return NULL;
|
session->ipAddress.addr = address;
|
||||||
|
session->ipAddress.addressLength = addressLength;
|
||||||
|
|
||||||
|
auto sessionPtr = std::shared_ptr<TCPSession>(session);
|
||||||
|
sessions.push_back(sessionPtr);
|
||||||
|
TCPSession::registerLive(session, sessionPtr);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Implicit TLS (this listener was built with a TLSInfo): create
|
||||||
|
// the session's SSL object and start SSL_accept() before the fd
|
||||||
|
// goes into epoll, for the same reason registration comes first -
|
||||||
|
// otherwise a worker can pick up the greeting onConnected() queues
|
||||||
|
// and reach TLS::sendData() before there's an SSL object to send
|
||||||
|
// it through.
|
||||||
|
if (tlsInfo)
|
||||||
|
session->performTLSHandshake(fd);
|
||||||
|
session->setDescriptor(fd);
|
||||||
|
}
|
||||||
|
catch (coreutils::Exception e) {
|
||||||
|
// Already owned and registered, so it is cleaned up through the
|
||||||
|
// normal shutdown path rather than deleted here (deleting would
|
||||||
|
// re-enter removeFromSessionList() while `lock` is held).
|
||||||
|
coreutils::Log(coreutils::LOG_EXCEPT) << "Major error on session initialization. Error is '" << e.text << "'.";
|
||||||
|
session->shutdown("session initialization failed");
|
||||||
|
}
|
||||||
|
catch (...) {
|
||||||
|
coreutils::Log(coreutils::LOG_EXCEPT) << "Unnspecified error on session initialization.";
|
||||||
|
session->shutdown("session initialization failed");
|
||||||
|
}
|
||||||
|
return session;
|
||||||
}
|
}
|
||||||
|
|
||||||
void TCPServer::removeFromSessionList(TCPSession *session) {
|
void TCPServer::removeFromSessionList(TCPSession *session) {
|
||||||
|
|||||||
+23
@@ -141,6 +141,29 @@ namespace core {
|
|||||||
|
|
||||||
std::shared_ptr<TCPSession> getSessionByAlias(void *alias);
|
std::shared_ptr<TCPSession> getSessionByAlias(void *alias);
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Offer TLS as an in-session upgrade (STARTTLS) on an otherwise
|
||||||
|
/// plain-text listener, as SMTP on port 25 requires. Unlike passing
|
||||||
|
/// tlsInfo to the constructor (implicit TLS - the handshake starts
|
||||||
|
/// the moment a connection is accepted, as on ports 465/993/995),
|
||||||
|
/// sessions here start in clear text and switch only when a command
|
||||||
|
/// handler calls TCPSession::startTLS(server->startTLSContext).
|
||||||
|
///
|
||||||
|
/// Throws coreutils::Exception if the certificate or key can't be
|
||||||
|
/// loaded; startTLSContext stays NULL in that case, so a caller that
|
||||||
|
/// catches it can keep serving without STARTTLS.
|
||||||
|
///
|
||||||
|
|
||||||
|
void enableStartTLS(TLSInfo &tlsInfo);
|
||||||
|
|
||||||
|
///
|
||||||
|
/// The context sessions switch to on STARTTLS. NULL until
|
||||||
|
/// enableStartTLS() succeeds - protocol code should only advertise
|
||||||
|
/// STARTTLS when this is set.
|
||||||
|
///
|
||||||
|
|
||||||
|
SSL_CTX *startTLSContext = NULL;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
///
|
///
|
||||||
/// This method is called by the lower socket when a connection request comes into
|
/// This method is called by the lower socket when a connection request comes into
|
||||||
|
|||||||
+21
-3
@@ -91,9 +91,27 @@ namespace core {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void TCPSession::send() {
|
void TCPSession::send() {
|
||||||
if(out.tellp() > 0)
|
// Take the data and clear `out` BEFORE write(). write() can re-arm
|
||||||
write(out.str());
|
// the fd, and from that moment another epoll worker may send what
|
||||||
out.str("");
|
// was queued, receive the client's next command and run its handler
|
||||||
|
// - which appends to this same `out`. When `out` was only cleared
|
||||||
|
// after write() returned, a handler running in that window saw the
|
||||||
|
// previous text still there and sent it a second time. Reproduced
|
||||||
|
// with the protocol greeting (queued from onRegistered() on the
|
||||||
|
// accepting thread): under a burst of connections some clients got
|
||||||
|
// "220 ..." twice, every later reply then lined up with the wrong
|
||||||
|
// command, and STARTTLS clients read the plain "220 Ready" as their
|
||||||
|
// TLS ServerHello.
|
||||||
|
if(out.tellp() > 0) {
|
||||||
|
std::string data = out.str();
|
||||||
|
out.str("");
|
||||||
|
write(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool TCPSession::startTLS(SSL_CTX *ctx) {
|
||||||
|
send();
|
||||||
|
return TCPSocket::startTLS(ctx);
|
||||||
}
|
}
|
||||||
|
|
||||||
void TCPSession::terminate() {
|
void TCPSession::terminate() {
|
||||||
|
|||||||
@@ -171,6 +171,18 @@ namespace core {
|
|||||||
|
|
||||||
void send();
|
void send();
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Upgrade this session to TLS (STARTTLS/STLS). Put the protocol's
|
||||||
|
/// "ready" reply in `out` first, then call this from the command
|
||||||
|
/// handler; it sends that reply in clear text, drops any input
|
||||||
|
/// pipelined behind the command, and starts the handshake. See
|
||||||
|
/// TCPSocket::startTLS() for the details and return value.
|
||||||
|
///
|
||||||
|
/// Pass server->startTLSContext (see TCPServer::enableStartTLS()).
|
||||||
|
///
|
||||||
|
|
||||||
|
bool startTLS(SSL_CTX *ctx);
|
||||||
|
|
||||||
///
|
///
|
||||||
/// Use this method to terminate this TCPSession.
|
/// Use this method to terminate this TCPSession.
|
||||||
///
|
///
|
||||||
|
|||||||
+101
-23
@@ -40,18 +40,35 @@ namespace core {
|
|||||||
// session (set in TLS::createContext(), inherited by sessions via
|
// session (set in TLS::createContext(), inherited by sessions via
|
||||||
// TLS(SSL_CTX*)), safely NULL by default otherwise (see TLS.h).
|
// TLS(SSL_CTX*)), safely NULL by default otherwise (see TLS.h).
|
||||||
if(ctx) {
|
if(ctx) {
|
||||||
int len;
|
// Loop until OpenSSL has nothing decrypted left over. A single TLS
|
||||||
{
|
// record carries up to 16KB, but `buffer` is 4KB, so one SSL_read()
|
||||||
// Held only around the raw SSL_read call - released before
|
// can leave the rest of a record sitting inside OpenSSL. This socket
|
||||||
// onDataReceived() so the request-handling chain it triggers
|
// is edge-triggered (EPOLLET) and those bytes have already been
|
||||||
// (which reaches Socket::write()/outlock) never runs while
|
// pulled off the fd, so nothing would ever raise another EPOLLIN
|
||||||
// ioLock is held. See ioLock's own doc comment in TCPSocket.h.
|
// for them: the session would stall mid-stream until the peer
|
||||||
std::lock_guard<std::mutex> ioGuard(ioLock);
|
// happened to send something else. Small requests (HTTP headers,
|
||||||
len = TLS::receiveData(buffer);
|
// single commands) never fill a 4KB read, which is why this didn't
|
||||||
}
|
// show up before; an SMTP DATA body from another mail server - the
|
||||||
if(len >= 0) {
|
// common case once STARTTLS is offered - does on every message.
|
||||||
coreutils::ZString zbuffer(buffer.getData(), len);
|
while(true) {
|
||||||
onDataReceived(zbuffer);
|
int len;
|
||||||
|
bool more;
|
||||||
|
{
|
||||||
|
// Held only around the raw SSL_read/SSL_pending calls -
|
||||||
|
// released before onDataReceived() so the request-handling
|
||||||
|
// chain it triggers (which reaches Socket::write()/outlock)
|
||||||
|
// never runs while ioLock is held. See ioLock's own doc
|
||||||
|
// comment in TCPSocket.h.
|
||||||
|
std::lock_guard<std::mutex> ioGuard(ioLock);
|
||||||
|
len = TLS::receiveData(buffer);
|
||||||
|
more = len > 0 && pendingBytes() > 0;
|
||||||
|
}
|
||||||
|
if(len >= 0) {
|
||||||
|
coreutils::ZString zbuffer(buffer.getData(), len);
|
||||||
|
onDataReceived(zbuffer);
|
||||||
|
}
|
||||||
|
if(!more || shutDown)
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Socket::receiveData(buffer);
|
Socket::receiveData(buffer);
|
||||||
@@ -70,6 +87,21 @@ namespace core {
|
|||||||
return ctx && lastSendWantedRead;
|
return ctx && lastSendWantedRead;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool TCPSocket::startTLS(SSL_CTX *newCtx) {
|
||||||
|
if(ctx || !newCtx)
|
||||||
|
return false;
|
||||||
|
discardInput = true;
|
||||||
|
if(!flushPlain(10000)) {
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_1) << "STARTTLS: ready reply could not be delivered; closing.";
|
||||||
|
shutdown("STARTTLS ready reply could not be delivered");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
ctx = newCtx;
|
||||||
|
performTLSHandshake();
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_1) << "STARTTLS: handshake started on socket " << getDescriptor() << ".";
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
void TCPSocket::performTLSHandshake() {
|
void TCPSocket::performTLSHandshake() {
|
||||||
// registerSocket() makes this fd eligible for epoll dispatch to ANY
|
// registerSocket() makes this fd eligible for epoll dispatch to ANY
|
||||||
// worker thread immediately. ioLock MUST be acquired BEFORE that
|
// worker thread immediately. ioLock MUST be acquired BEFORE that
|
||||||
@@ -91,8 +123,12 @@ namespace core {
|
|||||||
// (WANT_READ/WANT_WRITE) - that's fine, OpenSSL transparently
|
// (WANT_READ/WANT_WRITE) - that's fine, OpenSSL transparently
|
||||||
// finishes a pending handshake on the next SSL_read/SSL_write,
|
// finishes a pending handshake on the next SSL_read/SSL_write,
|
||||||
// which ioLock already serializes against everything else.
|
// which ioLock already serializes against everything else.
|
||||||
|
performTLSHandshake(getDescriptor());
|
||||||
|
}
|
||||||
|
|
||||||
|
void TCPSocket::performTLSHandshake(int fd) {
|
||||||
std::lock_guard<std::mutex> ioGuard(ioLock);
|
std::lock_guard<std::mutex> ioGuard(ioLock);
|
||||||
registerSocket(getDescriptor());
|
registerSocket(fd);
|
||||||
acceptSocket();
|
acceptSocket();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,14 +163,37 @@ namespace core {
|
|||||||
// the bounded equivalent - it never looks past the length
|
// the bounded equivalent - it never looks past the length
|
||||||
// given, so "no CRLF yet" correctly comes back as "not
|
// given, so "no CRLF yet" correctly comes back as "not
|
||||||
// found" instead of reading off the end of the allocation.
|
// found" instead of reading off the end of the allocation.
|
||||||
char *cr = (char *)memchr(lineBuffer, '\r', lineBufferSize);
|
char *found;
|
||||||
char *nl = (char *)memchr(lineBuffer, '\n', lineBufferSize);
|
if (strictCRLF)
|
||||||
char *found = (cr && nl) ? std::min(cr, nl) : (cr ? cr : nl);
|
found = (char *)memmem(lineBuffer, lineBufferSize, "\r\n", 2);
|
||||||
|
else {
|
||||||
|
char *cr = (char *)memchr(lineBuffer, '\r', lineBufferSize);
|
||||||
|
char *nl = (char *)memchr(lineBuffer, '\n', lineBufferSize);
|
||||||
|
found = (cr && nl) ? std::min(cr, nl) : (cr ? cr : nl);
|
||||||
|
}
|
||||||
lineLength = found ? (int)(found - lineBuffer) : lineBufferSize;
|
lineLength = found ? (int)(found - lineBuffer) : lineBufferSize;
|
||||||
if (lineLength == lineBufferSize)
|
if (!found) {
|
||||||
|
// No complete line yet. If it has already outgrown
|
||||||
|
// maxLineLength, drop what's buffered (keeping the last
|
||||||
|
// byte, which may be the CR of a CR LF whose LF is still
|
||||||
|
// in flight) and skip the rest of it - see maxLineLength.
|
||||||
|
if (maxLineLength && (size_t)lineBufferSize > maxLineLength) {
|
||||||
|
lineBuffer[0] = lineBuffer[lineBufferSize - 1];
|
||||||
|
lineBufferSize = 1;
|
||||||
|
lineBuffer = (char *)realloc(lineBuffer, lineBufferSize);
|
||||||
|
skippingLongLine = true;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (skippingLongLine || (maxLineLength && (size_t)lineLength > maxLineLength)) {
|
||||||
|
skippingLongLine = false;
|
||||||
|
onLineTooLong();
|
||||||
|
} else {
|
||||||
|
coreutils::ZString zLine(lineBuffer, lineLength);
|
||||||
|
onLineReceived(zLine);
|
||||||
|
}
|
||||||
|
if (discardInput)
|
||||||
break;
|
break;
|
||||||
coreutils::ZString zLine(lineBuffer, lineLength);
|
|
||||||
onLineReceived(zLine);
|
|
||||||
// lineLength < lineBufferSize is guaranteed by the break
|
// lineLength < lineBufferSize is guaranteed by the break
|
||||||
// above, so this first index is always in bounds; bump
|
// above, so this first index is always in bounds; bump
|
||||||
// past a lone '\r' only if there's still at least one more
|
// past a lone '\r' only if there's still at least one more
|
||||||
@@ -143,10 +202,14 @@ namespace core {
|
|||||||
// after it yet) leave it for the next read to resolve,
|
// after it yet) leave it for the next read to resolve,
|
||||||
// rather than reading lineBuffer[lineBufferSize], one past
|
// rather than reading lineBuffer[lineBufferSize], one past
|
||||||
// the allocation.
|
// the allocation.
|
||||||
if (lineBuffer[lineLength] == '\r')
|
if (strictCRLF)
|
||||||
++lineLength;
|
lineLength += 2;
|
||||||
if (lineLength < lineBufferSize && lineBuffer[lineLength] == '\n')
|
else {
|
||||||
++lineLength;
|
if (lineBuffer[lineLength] == '\r')
|
||||||
|
++lineLength;
|
||||||
|
if (lineLength < lineBufferSize && lineBuffer[lineLength] == '\n')
|
||||||
|
++lineLength;
|
||||||
|
}
|
||||||
lineBufferSize -= lineLength;
|
lineBufferSize -= lineLength;
|
||||||
if (lineBufferSize > 0)
|
if (lineBufferSize > 0)
|
||||||
memmove(lineBuffer, lineBuffer + lineLength, lineBufferSize);
|
memmove(lineBuffer, lineBuffer + lineLength, lineBufferSize);
|
||||||
@@ -155,6 +218,8 @@ namespace core {
|
|||||||
else if (lineBufferSize >= blockSize) {
|
else if (lineBufferSize >= blockSize) {
|
||||||
coreutils::ZString zBlock(lineBuffer, blockSize);
|
coreutils::ZString zBlock(lineBuffer, blockSize);
|
||||||
onBlockReceived(zBlock);
|
onBlockReceived(zBlock);
|
||||||
|
if (discardInput)
|
||||||
|
break;
|
||||||
lineBufferSize -= blockSize;
|
lineBufferSize -= blockSize;
|
||||||
if (lineBufferSize > 0)
|
if (lineBufferSize > 0)
|
||||||
memmove(lineBuffer, lineBuffer + blockSize, lineBufferSize);
|
memmove(lineBuffer, lineBuffer + blockSize, lineBufferSize);
|
||||||
@@ -172,6 +237,15 @@ namespace core {
|
|||||||
// never yields back to let more data arrive.
|
// never yields back to let more data arrive.
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
if (discardInput) {
|
||||||
|
// See startTLS(): whatever followed the upgrade command in this
|
||||||
|
// read is pre-handshake plain text and is dropped, not processed.
|
||||||
|
discardInput = false;
|
||||||
|
free(lineBuffer);
|
||||||
|
lineBuffer = NULL;
|
||||||
|
lineBufferSize = 0;
|
||||||
|
lineLength = 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -182,6 +256,10 @@ namespace core {
|
|||||||
|
|
||||||
void TCPSocket::onBlockReceived(coreutils::ZString &block) {}
|
void TCPSocket::onBlockReceived(coreutils::ZString &block) {}
|
||||||
|
|
||||||
|
void TCPSocket::onLineTooLong() {
|
||||||
|
shutdown("line exceeded maxLineLength");
|
||||||
|
}
|
||||||
|
|
||||||
void TCPSocket::setBlockSize(int blockSize) {
|
void TCPSocket::setBlockSize(int blockSize) {
|
||||||
this->blockSize = blockSize;
|
this->blockSize = blockSize;
|
||||||
}
|
}
|
||||||
|
|||||||
+91
@@ -151,6 +151,16 @@ namespace core {
|
|||||||
|
|
||||||
void performTLSHandshake();
|
void performTLSHandshake();
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Same, on an fd that hasn't been handed to setDescriptor() yet.
|
||||||
|
/// TCPServer::accept() uses this for implicit-TLS listeners so the
|
||||||
|
/// SSL object exists before the fd is armed in epoll - otherwise the
|
||||||
|
/// greeting queued by onConnected() can reach TLS::sendData() on
|
||||||
|
/// another worker before there is anything to send it through.
|
||||||
|
///
|
||||||
|
|
||||||
|
void performTLSHandshake(int fd);
|
||||||
|
|
||||||
///
|
///
|
||||||
/// Set once, at construction, and never touched again - how long
|
/// Set once, at construction, and never touched again - how long
|
||||||
/// this specific socket has been open since accept()/connect(),
|
/// this specific socket has been open since accept()/connect(),
|
||||||
@@ -186,6 +196,40 @@ namespace core {
|
|||||||
|
|
||||||
bool hasReceivedData = false;
|
bool hasReceivedData = false;
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Upgrade this plain-text connection to TLS in place (SMTP
|
||||||
|
/// STARTTLS, IMAP STARTTLS, POP3 STLS). Call it from the command
|
||||||
|
/// handler that accepted the upgrade, AFTER queuing that command's
|
||||||
|
/// "ready" reply - TCPSession::startTLS() does both for you.
|
||||||
|
///
|
||||||
|
/// In order, it:
|
||||||
|
/// 1. writes everything queued so far (the ready reply included)
|
||||||
|
/// to the socket in clear text and waits for it to go out;
|
||||||
|
/// 2. throws away any other input the client already sent in the
|
||||||
|
/// same read as the upgrade command. RFC 3207 section 4 forbids
|
||||||
|
/// a client from pipelining anything after STARTTLS, and acting
|
||||||
|
/// on such bytes is the classic STARTTLS command-injection hole
|
||||||
|
/// (CVE-2011-0411 and its many relatives): an attacker on the
|
||||||
|
/// path appends plain-text commands that the server would then
|
||||||
|
/// treat as if they arrived over the encrypted channel;
|
||||||
|
/// 3. switches this socket to `ctx` and starts the server side of
|
||||||
|
/// the handshake. The client's ClientHello and everything after
|
||||||
|
/// it are read through TLS by the normal receiveData() path.
|
||||||
|
///
|
||||||
|
/// Returns false (and changes nothing) if TLS is already active or
|
||||||
|
/// ctx is NULL; returns false and shuts the connection down if the
|
||||||
|
/// ready reply couldn't be delivered.
|
||||||
|
///
|
||||||
|
|
||||||
|
bool startTLS(SSL_CTX *ctx);
|
||||||
|
|
||||||
|
///
|
||||||
|
/// True once this connection is encrypted, whether it was accepted
|
||||||
|
/// on an implicit-TLS listener or upgraded with startTLS().
|
||||||
|
///
|
||||||
|
|
||||||
|
bool isTLS() { return ctx != NULL; }
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
bool term = false;
|
bool term = false;
|
||||||
TLSInfo *tlsInfo;
|
TLSInfo *tlsInfo;
|
||||||
@@ -196,6 +240,53 @@ namespace core {
|
|||||||
int lineLength = 0;
|
int lineLength = 0;
|
||||||
int blockSize = 0;
|
int blockSize = 0;
|
||||||
|
|
||||||
|
// Set by startTLS(); tells the onDataReceived() loop that the line
|
||||||
|
// it just dispatched was the upgrade command and everything still
|
||||||
|
// in lineBuffer is pre-handshake plain text that must be dropped,
|
||||||
|
// not processed. See startTLS()'s step 2.
|
||||||
|
bool discardInput = false;
|
||||||
|
|
||||||
|
// Set by the line loop while it is dropping the rest of a line that
|
||||||
|
// already exceeded maxLineLength; see onLineTooLong().
|
||||||
|
bool skippingLongLine = false;
|
||||||
|
|
||||||
|
protected:
|
||||||
|
///
|
||||||
|
/// When true, only CR LF ends a line; a bare CR or bare LF is kept
|
||||||
|
/// as part of the line's content. Default false (a CR, an LF, or CR
|
||||||
|
/// LF each end a line), which existing line protocols rely on.
|
||||||
|
///
|
||||||
|
/// SMTP must use true. RFC 5321 2.3.8 and 4.1.1.4 make <CRLF>.<CRLF>
|
||||||
|
/// the only end-of-data sequence; a server that also accepts bare
|
||||||
|
/// <LF> or <CR> line endings can be made to end a message early on
|
||||||
|
/// "<LF>.<LF>" and then run whatever follows in the same message as
|
||||||
|
/// fresh SMTP commands - "SMTP smuggling" (CVE-2023-51764/-51765/
|
||||||
|
/// -51766), which lets a sender forge mail from any domain that
|
||||||
|
/// relays through the server. The lenient mode also splits a CR LF
|
||||||
|
/// that straddles two reads into two lines, the second one empty.
|
||||||
|
///
|
||||||
|
|
||||||
|
bool strictCRLF = false;
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Upper bound on bytes buffered for a single line (0 = no limit).
|
||||||
|
/// When a line grows past it, the buffered part is dropped, the rest
|
||||||
|
/// of that line is skipped up to its terminator, and onLineTooLong()
|
||||||
|
/// is called once in place of onLineReceived() for it. Without a
|
||||||
|
/// bound, a peer that never sends a line terminator grows lineBuffer
|
||||||
|
/// until the process runs out of memory.
|
||||||
|
///
|
||||||
|
|
||||||
|
size_t maxLineLength = 0;
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Called once for each line that exceeded maxLineLength. The default
|
||||||
|
/// closes the connection; protocols that can recover override it to
|
||||||
|
/// reply with an error instead.
|
||||||
|
///
|
||||||
|
|
||||||
|
virtual void onLineTooLong();
|
||||||
|
|
||||||
// Socket's own `lock` (guards receiveData) and `outlock` (guards
|
// Socket's own `lock` (guards receiveData) and `outlock` (guards
|
||||||
// writeSocket/the fifo) are two DIFFERENT mutexes - a thread
|
// writeSocket/the fifo) are two DIFFERENT mutexes - a thread
|
||||||
// handling EPOLLIN and a different thread handling EPOLLWRNORM for
|
// handling EPOLLIN and a different thread handling EPOLLWRNORM for
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
#include "Log.h"
|
#include "Log.h"
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <openssl/rand.h>
|
#include <openssl/rand.h>
|
||||||
|
#include <mutex>
|
||||||
|
|
||||||
namespace core {
|
namespace core {
|
||||||
|
|
||||||
@@ -65,11 +66,25 @@ namespace core {
|
|||||||
|
|
||||||
TLS::TLS(SSL_CTX *ctx) : ctx(ctx) {}
|
TLS::TLS(SSL_CTX *ctx) : ctx(ctx) {}
|
||||||
|
|
||||||
TLS::~TLS() {}
|
// Each accepted TLS connection gets its own SSL object in
|
||||||
|
// registerSocket(); it was never freed, so every TLS session leaked
|
||||||
|
// one. Harmless for a handful of long-lived connections, but a mail
|
||||||
|
// server opens one per delivery, all day. The fd itself is still
|
||||||
|
// closed by ~Socket() as before - SSL_free() doesn't touch it.
|
||||||
|
TLS::~TLS() {
|
||||||
|
if(initialized)
|
||||||
|
SSL_free(ssl);
|
||||||
|
}
|
||||||
|
|
||||||
void TLS::createContext(TLSInfo *tlsInfo) {
|
// The ONE-TIME, process-wide OpenSSL library init (SSL_library_init(),
|
||||||
|
// the lockarray, RAND seeding). Used to live in createContext(), which
|
||||||
if(tlsInfo) {
|
// was fine while that was the only way a context got built; now that
|
||||||
|
// buildContext() is also reached directly - TCPServer::enableStartTLS()
|
||||||
|
// for STARTTLS, and addSNIContext() - it runs exactly once from there,
|
||||||
|
// whichever path gets to it first.
|
||||||
|
static void initializeLibrary() {
|
||||||
|
static std::once_flag once;
|
||||||
|
std::call_once(once, [] {
|
||||||
SSL_library_init();
|
SSL_library_init();
|
||||||
SSL_load_error_strings();
|
SSL_load_error_strings();
|
||||||
lockarray = (pthread_mutex_t *)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
|
lockarray = (pthread_mutex_t *)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
|
||||||
@@ -79,63 +94,77 @@ namespace core {
|
|||||||
CRYPTO_set_locking_callback((void (*)(int, int, const char *, int))lock_callback);
|
CRYPTO_set_locking_callback((void (*)(int, int, const char *, int))lock_callback);
|
||||||
SSLeay_add_ssl_algorithms();
|
SSLeay_add_ssl_algorithms();
|
||||||
RAND_load_file("/dev/hwrng", 1024);
|
RAND_load_file("/dev/hwrng", 1024);
|
||||||
ctx = buildContext(tlsInfo);
|
});
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// The per-context cert/key/cipher/verify setup factored out of
|
void TLS::createContext(TLSInfo *tlsInfo) {
|
||||||
// createContext() above so addSNIContext() (below) can build
|
if(tlsInfo)
|
||||||
// additional contexts - one per extra hostname - without repeating
|
ctx = buildContext(tlsInfo);
|
||||||
// the ONE-TIME, process-wide OpenSSL library init that stays in
|
}
|
||||||
// createContext() itself (SSL_library_init(), the lockarray, RAND
|
|
||||||
// seeding): that part must only ever run once per process, not once
|
// The per-context cert/key/cipher/verify setup, shared by
|
||||||
// per hostname.
|
// createContext(), addSNIContext() (one context per extra hostname)
|
||||||
|
// and TCPServer::enableStartTLS().
|
||||||
SSL_CTX *TLS::buildContext(TLSInfo *tlsInfo) {
|
SSL_CTX *TLS::buildContext(TLSInfo *tlsInfo) {
|
||||||
|
initializeLibrary();
|
||||||
SSL_CTX *newCtx;
|
SSL_CTX *newCtx;
|
||||||
if(!(newCtx = SSL_CTX_new(SSLv23_server_method())))
|
if(!(newCtx = SSL_CTX_new(SSLv23_server_method())))
|
||||||
throw coreutils::Exception("Error while setting server method SSLv23.");
|
throw coreutils::Exception("Error while setting server method SSLv23.");
|
||||||
SSL_CTX_set_mode(newCtx, SSL_MODE_RELEASE_BUFFERS | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
|
// A caller may now catch a bad certificate/key and carry on without
|
||||||
SSL_CTX_set_options(newCtx, SSL_OP_NO_TICKET);
|
// TLS (BARANTMail does, for STARTTLS) - don't leak the half-built
|
||||||
SSL_CTX_set_session_cache_mode(newCtx, SSL_SESS_CACHE_SERVER);
|
// context on the way out.
|
||||||
SSL_CTX_set_cipher_list(newCtx, "ECDH-ECDSA-AES256-GCM-SHA384:DHE-DSS-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA256:DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA");
|
try {
|
||||||
// _chain_file (not _file) - loads every certificate in the file,
|
SSL_CTX_set_mode(newCtx, SSL_MODE_RELEASE_BUFFERS | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
|
||||||
// not just the first. A real Let's Encrypt fullchain.pem is the
|
SSL_CTX_set_options(newCtx, SSL_OP_NO_TICKET);
|
||||||
// leaf cert followed by the intermediate CA cert concatenated in
|
SSL_CTX_set_session_cache_mode(newCtx, SSL_SESS_CACHE_SERVER);
|
||||||
// one file specifically so a server can hand both to the client
|
SSL_CTX_set_cipher_list(newCtx, "ECDH-ECDSA-AES256-GCM-SHA384:DHE-DSS-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA256:DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA");
|
||||||
// in one shot; SSL_CTX_use_certificate_file() only ever reads the
|
// _chain_file (not _file) - loads every certificate in the file,
|
||||||
// first PEM block, silently dropping the intermediate - confirmed
|
// not just the first. A real Let's Encrypt fullchain.pem is the
|
||||||
// via a real handshake against this exact fullchain.pem: clients
|
// leaf cert followed by the intermediate CA cert concatenated in
|
||||||
// got "unable to get local issuer certificate" because the server
|
// one file specifically so a server can hand both to the client
|
||||||
// only ever sent the leaf, never the intermediate needed to chain
|
// in one shot; SSL_CTX_use_certificate_file() only ever reads the
|
||||||
// up to a root the client already trusts.
|
// first PEM block, silently dropping the intermediate - confirmed
|
||||||
if(SSL_CTX_use_certificate_chain_file(newCtx, tlsInfo->certificate.c_str()) <= 0)
|
// via a real handshake against this exact fullchain.pem: clients
|
||||||
throw coreutils::Exception("Error looking up certificate.");
|
// got "unable to get local issuer certificate" because the server
|
||||||
if(SSL_CTX_use_PrivateKey_file(newCtx, tlsInfo->key.c_str(), SSL_FILETYPE_PEM) < 0)
|
// only ever sent the leaf, never the intermediate needed to chain
|
||||||
throw coreutils::Exception("Error with private key.");
|
// up to a root the client already trusts.
|
||||||
if(SSL_CTX_check_private_key(newCtx) != 1)
|
if(SSL_CTX_use_certificate_chain_file(newCtx, tlsInfo->certificate.c_str()) <= 0)
|
||||||
throw coreutils::Exception("Private key does not match certificate.");
|
throw coreutils::Exception("Error looking up certificate.");
|
||||||
// Client-certificate verification (mutual TLS) is opt-in, not the
|
if(SSL_CTX_use_PrivateKey_file(newCtx, tlsInfo->key.c_str(), SSL_FILETYPE_PEM) <= 0)
|
||||||
// default - a public-facing site (e.g. a real Let's Encrypt
|
throw coreutils::Exception("Error with private key.");
|
||||||
// server cert with no corresponding client CA of its own) has no
|
if(SSL_CTX_check_private_key(newCtx) != 1)
|
||||||
// client certificate to hand out to ordinary visitors, so
|
throw coreutils::Exception("Private key does not match certificate.");
|
||||||
// requesting one via SSL_VERIFY_PEER would surface a "select a
|
// Client-certificate verification (mutual TLS) is opt-in, not the
|
||||||
// certificate" prompt real browsers can't meaningfully answer.
|
// default - a public-facing site (e.g. a real Let's Encrypt
|
||||||
// Only enable it when a caCertificate is actually configured -
|
// server cert with no corresponding client CA of its own) has no
|
||||||
// existing internal/mTLS use of this class (any config that DOES
|
// client certificate to hand out to ordinary visitors, so
|
||||||
// set tls.caCertificate) keeps behaving exactly as before.
|
// requesting one via SSL_VERIFY_PEER would surface a "select a
|
||||||
if(tlsInfo->cACertificate.getLength() > 0) {
|
// certificate" prompt real browsers can't meaningfully answer.
|
||||||
SSL_CTX_set_verify(newCtx, SSL_VERIFY_PEER, NULL);
|
// Only enable it when a caCertificate is actually configured -
|
||||||
SSL_CTX_set_verify_depth(newCtx, 1);
|
// existing internal/mTLS use of this class (any config that DOES
|
||||||
if(!SSL_CTX_load_verify_locations(newCtx, tlsInfo->cACertificate.c_str(), NULL))
|
// set tls.caCertificate) keeps behaving exactly as before.
|
||||||
throw coreutils::Exception("Cannot verify locations.");
|
if(tlsInfo->cACertificate.getLength() > 0) {
|
||||||
SSL_CTX_set_client_CA_list(newCtx, SSL_load_client_CA_file(tlsInfo->cACertificate.c_str()));
|
SSL_CTX_set_verify(newCtx, SSL_VERIFY_PEER, NULL);
|
||||||
coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (client certificate required).";
|
SSL_CTX_set_verify_depth(newCtx, 1);
|
||||||
} else {
|
if(!SSL_CTX_load_verify_locations(newCtx, tlsInfo->cACertificate.c_str(), NULL))
|
||||||
coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (no client certificate required).";
|
throw coreutils::Exception("Cannot verify locations.");
|
||||||
|
SSL_CTX_set_client_CA_list(newCtx, SSL_load_client_CA_file(tlsInfo->cACertificate.c_str()));
|
||||||
|
coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (client certificate required).";
|
||||||
|
} else {
|
||||||
|
coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (no client certificate required).";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch(...) {
|
||||||
|
SSL_CTX_free(newCtx);
|
||||||
|
throw;
|
||||||
}
|
}
|
||||||
return newCtx;
|
return newCtx;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int TLS::pendingBytes() {
|
||||||
|
return initialized ? SSL_pending(ssl) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
int TLS::sniCallback(SSL *ssl, int *ad, void *arg) {
|
int TLS::sniCallback(SSL *ssl, int *ad, void *arg) {
|
||||||
TLS *self = (TLS *)arg;
|
TLS *self = (TLS *)arg;
|
||||||
const char *name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
|
const char *name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
|
||||||
|
|||||||
@@ -68,6 +68,16 @@ namespace core {
|
|||||||
///
|
///
|
||||||
void addSNIContext(const std::string &hostname, TLSInfo *tlsInfo);
|
void addSNIContext(const std::string &hostname, TLSInfo *tlsInfo);
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Build a server SSL_CTX from tlsInfo without attaching it to any
|
||||||
|
/// object. Used by createContext() for implicit-TLS listeners and by
|
||||||
|
/// TCPServer::enableStartTLS() for a context that plain-text sessions
|
||||||
|
/// only switch to on request (STARTTLS). Throws coreutils::Exception
|
||||||
|
/// if the certificate or key can't be loaded.
|
||||||
|
///
|
||||||
|
|
||||||
|
static SSL_CTX *buildContext(TLSInfo *tlsInfo);
|
||||||
|
|
||||||
// A never-configured TLS object (either the listening TCPServer
|
// A never-configured TLS object (either the listening TCPServer
|
||||||
// itself when constructed with tlsInfo=NULL, or a TCPSession spawned
|
// itself when constructed with tlsInfo=NULL, or a TCPSession spawned
|
||||||
// from one via TLS(SSL_CTX*)) must default to a real NULL here, not
|
// from one via TLS(SSL_CTX*)) must default to a real NULL here, not
|
||||||
@@ -81,6 +91,16 @@ namespace core {
|
|||||||
void registerSocket(int fd);
|
void registerSocket(int fd);
|
||||||
void acceptSocket();
|
void acceptSocket();
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Bytes OpenSSL has already decrypted and is holding for this
|
||||||
|
/// connection but that haven't been returned by receiveData() yet.
|
||||||
|
/// The socket is edge-triggered (EPOLLET), so these never generate
|
||||||
|
/// another EPOLLIN on their own - TCPSocket::receiveData() drains
|
||||||
|
/// them before giving the event back. See its own comment.
|
||||||
|
///
|
||||||
|
|
||||||
|
int pendingBytes();
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
// Set by sendData() when the last SSL_write() failed specifically
|
// Set by sendData() when the last SSL_write() failed specifically
|
||||||
// with SSL_ERROR_WANT_READ (needs a READ to make progress - e.g.
|
// with SSL_ERROR_WANT_READ (needs a READ to make progress - e.g.
|
||||||
@@ -101,12 +121,6 @@ namespace core {
|
|||||||
bool initialized = false;
|
bool initialized = false;
|
||||||
SSL *ssl;
|
SSL *ssl;
|
||||||
|
|
||||||
// The actual cert/key-loading + cipher/session-cache setup shared
|
|
||||||
// by both the base context (createContext(), unchanged) and every
|
|
||||||
// additional per-hostname context addSNIContext() builds - factored
|
|
||||||
// out so there's exactly one place that does this, not two copies
|
|
||||||
// drifting apart.
|
|
||||||
SSL_CTX *buildContext(TLSInfo *tlsInfo);
|
|
||||||
|
|
||||||
// Owns every SSL_CTX* built by addSNIContext() (the base `ctx` is
|
// Owns every SSL_CTX* built by addSNIContext() (the base `ctx` is
|
||||||
// owned/freed the same way it always was, untouched by this map).
|
// owned/freed the same way it always was, untouched by this map).
|
||||||
|
|||||||
Reference in new issue
Block a user