Add STARTTLS and strict CRLF framing; fix accept races and TLS stalls

STARTTLS (in-session TLS upgrade, RFC 3207 / 2595 style):
- TCPServer::enableStartTLS(TLSInfo&) builds startTLSContext for a
  plain-text listener; TCPSession::startTLS(ctx) sends the queued
  ready reply in clear (Socket::flushPlain), discards any input
  pipelined after the command (CVE-2011-0411 injection class), then
  switches the socket to TLS and starts the handshake.
- TLS::buildContext() is static and runs process-wide OpenSSL init
  exactly once, so it can be called from createContext(),
  addSNIContext() and enableStartTLS(); frees a half-built context on
  error; SSL_CTX_use_PrivateKey_file() failure is detected (<= 0).
- ~TLS() frees the per-connection SSL object (leaked one per TLS
  connection before).

TLS receive stall:
- TCPSocket::receiveData() drains SSL_pending() before returning. A
  TLS record holds up to 16KB but reads are 4KB; with EPOLLET the rest
  of a record sat inside OpenSSL with no event to wake it, stalling
  large uploads (e.g. SMTP DATA) mid-stream.

Line framing (opt-in, defaults unchanged):
- TCPSocket::strictCRLF: only CR LF ends a line. SMTP needs this:
  accepting bare CR/LF as line ends is what makes SMTP smuggling
  (CVE-2023-51764/51765/51766) possible, and the lenient mode also
  split a CR LF straddling two reads into two lines, inserting a blank
  line into message bodies.
- TCPSocket::maxLineLength + onLineTooLong(): bound the line buffer so
  a peer that never sends a terminator can't exhaust memory.

Races that silently dropped connections (EPOLLONESHOT event delivered
before the object was registered, so Thread::run() ignored it and the
one-shot registration was spent):
- TCPServer constructor binds, listens and registers the listener
  before setDescriptor() arms it (about 3 startups in 8 accepted
  nothing, ever).
- TCPServer::accept() registers the session (sessions +
  registerLive) and, for implicit TLS, creates its SSL object before
  arming the fd (10-15% of a 40-connection burst never got a
  greeting). A failed ::accept() no longer creates and leaks a session.

Duplicate output:
- TCPSession::send() clears `out` before write() re-arms the socket;
  a handler running on another worker in that window re-sent the
  previous text (clients saw the greeting twice and every later reply
  shifted by one).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0121tAhQVe4qbCwYgVjKQS4B
This commit is contained in:
barantandClaude Opus 5.5 authored and brad Arant committed 2026-11-02 11:56:49 -08:00
1 parent c0e1d87ac1
commit a8514d9689
10 files changed
+486 -139

No files matched your search

+97 -55
View File
@@ -25,12 +25,26 @@ namespace core {
commands.add(subscriptions, "event");
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;
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)
throw coreutils::Exception("Error on bind to socket: " + std::to_string(errno));
if (bind(fd, address.getPointer(), address.addressLength) < 0) {
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
// 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
// the overflow SYNs rather than queuing them. 128 gives real
// bursts meaningfully more headroom; still bounded, not unlimited.
if (listen(getDescriptor(), 128) < 0)
throw coreutils::Exception("Error on listen to socket");
if (listen(fd, 128) < 0) {
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());
listeningSockets().insert(this);
}
setDescriptor(fd);
}
TCPServer::~TCPServer() {
@@ -63,33 +78,12 @@ namespace core {
// comment), and this mutex isn't recursive.
sweepStaleSessions();
lock.lock();
TCPSession *session = accept();
// The shared_ptr constructed here IS the session's real, strong
// ownership from now on (see sessions' own doc comment). A second
// reference to the SAME shared_ptr (never a second, independent
// std::shared_ptr<TCPSession>(session) call on the same raw
// pointer - that would create a second, competing control block
// 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();
// accept() now adds the session to `sessions` and the live registry
// itself, before its fd is armed - see the comment there.
// accept() registers the session and, for an implicit-TLS listener,
// starts its TLS handshake (on the session, not on `this`) before
// arming the fd - see its own comment.
accept();
lock.unlock();
}
@@ -120,6 +114,10 @@ namespace core {
}
}
void TCPServer::enableStartTLS(TLSInfo &tlsInfo) {
startTLSContext = TLS::buildContext(&tlsInfo);
}
void TCPServer::receiveData(coreutils::ZString &buffer) {
// See this override's own doc comment in TCPServer.h - the
// listening socket always uses the plain read()/ENOTCONN detection
@@ -130,30 +128,74 @@ namespace core {
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);
session->setDescriptor(::accept(getDescriptor(), (struct sockaddr *)&session->ipAddress.addr, &session->ipAddress.addressLength));
// if(blackList && blackList->contains(session->ipAddress.getClientAddress())) {
// session->shutdown();
// Log(LOG_WARN) << "Client at IP address " << session->ipAddress.getClientAddress() << " is blacklisted and was denied a 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;
struct sockaddr_in address;
socklen_t addressLength = sizeof(address);
int fd = ::accept(getDescriptor(), (struct sockaddr *)&address, &addressLength);
if (fd < 0) {
if (errno == EMFILE || errno == ENFILE)
coreutils::Log(coreutils::LOG_EXCEPT) << "Too many files open. Refusing connection.";
return NULL;
}
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 (...) {
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) {