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

+102 -24
View File
@@ -40,18 +40,35 @@ namespace core {
// session (set in TLS::createContext(), inherited by sessions via
// TLS(SSL_CTX*)), safely NULL by default otherwise (see TLS.h).
if(ctx) {
int len;
{
// Held only around the raw SSL_read call - 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);
}
if(len >= 0) {
coreutils::ZString zbuffer(buffer.getData(), len);
onDataReceived(zbuffer);
// Loop until OpenSSL has nothing decrypted left over. A single TLS
// record carries up to 16KB, but `buffer` is 4KB, so one SSL_read()
// can leave the rest of a record sitting inside OpenSSL. This socket
// is edge-triggered (EPOLLET) and those bytes have already been
// pulled off the fd, so nothing would ever raise another EPOLLIN
// for them: the session would stall mid-stream until the peer
// happened to send something else. Small requests (HTTP headers,
// 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
// common case once STARTTLS is offered - does on every message.
while(true) {
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 {
Socket::receiveData(buffer);
@@ -70,6 +87,21 @@ namespace core {
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() {
// registerSocket() makes this fd eligible for epoll dispatch to ANY
// worker thread immediately. ioLock MUST be acquired BEFORE that
@@ -91,8 +123,12 @@ namespace core {
// (WANT_READ/WANT_WRITE) - that's fine, OpenSSL transparently
// finishes a pending handshake on the next SSL_read/SSL_write,
// which ioLock already serializes against everything else.
performTLSHandshake(getDescriptor());
}
void TCPSocket::performTLSHandshake(int fd) {
std::lock_guard<std::mutex> ioGuard(ioLock);
registerSocket(getDescriptor());
registerSocket(fd);
acceptSocket();
}
@@ -127,14 +163,37 @@ namespace core {
// the bounded equivalent - it never looks past the length
// given, so "no CRLF yet" correctly comes back as "not
// found" instead of reading off the end of the allocation.
char *cr = (char *)memchr(lineBuffer, '\r', lineBufferSize);
char *nl = (char *)memchr(lineBuffer, '\n', lineBufferSize);
char *found = (cr && nl) ? std::min(cr, nl) : (cr ? cr : nl);
char *found;
if (strictCRLF)
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;
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;
coreutils::ZString zLine(lineBuffer, lineLength);
onLineReceived(zLine);
// lineLength < lineBufferSize is guaranteed by the break
// above, so this first index is always in bounds; bump
// 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,
// rather than reading lineBuffer[lineBufferSize], one past
// the allocation.
if (lineBuffer[lineLength] == '\r')
++lineLength;
if (lineLength < lineBufferSize && lineBuffer[lineLength] == '\n')
++lineLength;
if (strictCRLF)
lineLength += 2;
else {
if (lineBuffer[lineLength] == '\r')
++lineLength;
if (lineLength < lineBufferSize && lineBuffer[lineLength] == '\n')
++lineLength;
}
lineBufferSize -= lineLength;
if (lineBufferSize > 0)
memmove(lineBuffer, lineBuffer + lineLength, lineBufferSize);
@@ -155,6 +218,8 @@ namespace core {
else if (lineBufferSize >= blockSize) {
coreutils::ZString zBlock(lineBuffer, blockSize);
onBlockReceived(zBlock);
if (discardInput)
break;
lineBufferSize -= blockSize;
if (lineBufferSize > 0)
memmove(lineBuffer, lineBuffer + blockSize, lineBufferSize);
@@ -171,7 +236,16 @@ namespace core {
// changes, so the while(lineBufferSize > 0) loop above
// never yields back to let more data arrive.
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::onLineTooLong() {
shutdown("line exceeded maxLineLength");
}
void TCPSocket::setBlockSize(int blockSize) {
this->blockSize = blockSize;
}