Compare commits

...
10 Commits
Author SHA1 Message Date
barantandClaude Opus 5.5 a8514d9689 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
2026-11-02 11:56:49 -08:00
barantandClaude Opus 5.5 c0e1d87ac1 Ignore SIGPIPE process-wide in EPoll
Writing to a socket the peer has already reset raises SIGPIPE, whose
default action kills the whole process. Socket.cpp carried a
sigpipe_handler but nothing ever installed it. OpenSSL's SSL_write()
calls write() itself, so MSG_NOSIGNAL can't cover TLS - ignore the
signal once for every server built on EPoll. Reproduced: a burst of
TLS clients disconnecting mid-session killed the server within a few
rounds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0121tAhQVe4qbCwYgVjKQS4B
2026-11-02 11:56:49 -08:00
barantandClaude Opus 5.5 4918654715 Implement IPAddress::getClientAddress()
It was a stub that always returned "", so everything keyed on the
client address saw an empty string: SPF checks in BARANTMail were run
against no IP at all, Received: headers had no address, and
IPAddressList black/white lists could never match.
getClientAddressAndPort() also used inet_ntoa() (a static buffer shared
across threads) and printed the port in network byte order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0121tAhQVe4qbCwYgVjKQS4B
2026-11-02 11:56:49 -08:00
Matt ArantandClaude Sonnet 5 4bfede1342 Fix sweepStaleSessions() lock_guard type after lock became recursive_mutex
Merging upstream TCPServer.h changed lock from std::mutex to
std::recursive_mutex (the ConsoleServer self-deadlock fix); this call
site still hardcoded std::lock_guard<std::mutex>, which no longer
compiles since lock_guard cannot bind to a different mutex type. Uses
the same class-template-argument-deduction form every other lock_guard
in this file already uses.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-06 18:34:51 +00:00
Matt Arant dc6b1dcc56 Merge branch 'master' of git.barant.com:barant/ServerCore 2026-10-06 17:54:37 +00:00
Matt ArantandClaude Sonnet 5 6483729de3 Add a stale/never-active session reaper and raise the listen backlog
TCPServer accepted a connection and never revisited it again once it
stopped generating epoll events - a connection that completes the TCP
handshake and then goes permanently silent (an incomplete TLS
handshake, a port scanner/prober) sat in sessions forever, one
TCPSession + one fd each. sweepStaleSessions() now drops any session
that has gone 30+ seconds without a single byte of real data ever
passing through onDataReceived(), run each time a new connection
arrives rather than needing a dedicated timer. hasReceivedData latches
permanently true on a sessions first real byte, so an ordinary
connected-but-briefly-idle client is never at risk.

Also raised listen()s backlog from 20 to 128, so a burst of connection
attempts has more headroom before the kernel starts dropping SYNs.

Verified live on zephora.barant.com: a silent connection held open was
reaped within the grace window while a real concurrent connection was
left untouched, with the service remaining healthy throughout.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-06 17:54:20 +00:00
Brad ArantandClaude Sonnet 5 1d3d30cd05 Fix epoll dispatch dropping INotify events, ConsoleServer self-deadlock, and add TLS SNI support
- INotify/Thread epoll dispatch was silently dropping every live
  core::INotify event (an isKnownINotify registry fixes it) - this had
  broken mail delivery for over a week, masked by routine restarts.
- TCPServer::lock self-deadlocked every admin-console connection via a
  plain std::mutex being re-entered; switched to recursive_mutex.
- TLS.cpp/h: SNI-based certificate selection (addSNIContext), the
  groundwork for multi-tenant TLS (qualityiron.vegas alongside
  barant.com on one APIServer process).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-06 17:38:37 +00:00
Matt Arant d058322cc6 Move TCPSession lifetime to shared_ptr ownership, fix the whole double-delete/UAF class of crash
Every crash root-caused earlier tonight (Subscription::subscribers,
TCPServer::sessions, the Socket::write()/eventReceived() re-arm race) was
the same underlying shape: some thread calling a method - or Thread::run()
calling delete - on a TCPSession* while another thread concurrently freed
that same object, because nothing actually guaranteed the object stayed
alive for the duration of a call. Mutex-based patches at each individual
call site kept narrowing the window without closing it (confirmed live,
repeatedly, via AddressSanitizer under concurrent load - each fix produced
a new, different crash signature at the same underlying race), and adding
more locks around every write() call also works against the fifo-based
design's own goal: no thread should have to block just to hand a message
to another thread's session.

TCPSession now derives from std::enable_shared_from_this<TCPSession> and
exposes pin() - a safe upgrade from a stored raw pointer to a real,
ownership-extending shared_ptr, returning nullptr instead of throwing once
the object's real owner has let go. TCPServer::sessions is now the one
real strong-owning shared_ptr<TCPSession> per live session; every other
place that stores a TCPSession* (Subscription::subscribers, Zephora's own
sessionsByPlayerName, GroupObject's membership list, etc.) is just a
non-owning observer and must pin() before touching the object.

A second, distinct problem: Thread::run()'s epoll dispatch starts from a
raw void* of unknown validity. An early version of this fix used
dynamic_cast<TCPSession*> to identify session objects before calling
pin() - confirmed live via AddressSanitizer that dynamic_cast itself
segfaults on a stale pointer, since it has to read the (potentially freed)
object's own vtable to work at all. TCPSession::tryGet()/TCPServer::
isKnownListeningSocket() replace that: both look the raw pointer up as a
key in a registry, never dereferencing it for the check itself - safe to
call on any value, live session, immortal listening socket, or fully
freed garbage alike.

Verified via an AddressSanitizer-instrumented build under sustained
concurrent load (up to 15-way parallel connect/subscribe/create/disconnect
cycles, multiple rounds, 100+ total connections) with zero errors, then
against the real production build with a genuine 500-connection load test
(463/500 succeeded; the rest hit the process's own file-descriptor
ulimit under peak burst, an unrelated and separately deferred tuning
matter, not a crash).

Files touched: TCPSession.h (enable_shared_from_this, pin(), the tryGet()
registry), TCPServer.h/.cpp (sessions as shared_ptr, isKnownListening
Socket() registry, lock made protected for subclasses), Thread.cpp (the
whole dispatch rewrite), Subscription.cpp/SubscriptionManager.cpp (every
subscriber write() site now pin()s first), ConsoleServer.cpp (logSend()
was iterating `sessions` with no lock at all - fixed alongside the type
change it needed anyway).
2026-09-08 02:24:09 +00:00
Matt Arant 8009564a7a Fix premature socket re-arm race between write() and eventReceived()
Socket::write() unconditionally called resetSocket() (via EPOLL_CTL_MOD)
from whatever thread called it, whenever it could grab `lock` - including
while this same socket's OWN eventReceived() call was still mid-flight on
another thread (past receiveData()'s lock_guard, but before its own
trailing resetSocket()/return). Re-arming makes the fd immediately
eligible for a third thread to pick up a fresh event and, if it decides
to shut the connection down, delete the object outright (Thread::run()
does exactly that on a false return) - while the original thread is still
touching it. A real heap-corruption crash inside libc's malloc internals
was confirmed live via dmesg under concurrent load, consistent with
exactly this: a socket freed while another thread still held a reference
to it.

inHandler existed as a flag already but only fed a diagnostic log line -
never actually gated anything. Made it a real std::atomic<bool> (was
`volatile`, which gives no actual atomicity or cross-thread visibility)
and used it two ways:
- write() now skips its own resetSocket() call entirely while inHandler
  is true - that call's own eventReceived() will re-arm once it's
  actually done, seeing the fifo entry write() just queued.
- eventReceived() itself was clearing inHandler well before its own
  resetSocket() call (several statements up, right after EPOLLIN/
  EPOLLWRNORM handling) - moved the clear to immediately precede that
  call, closing the exposed window down to the minimum achievable
  without restructuring how write() re-arms sockets altogether.

This is a distinct bug from the two subscriber/session-list races fixed
earlier tonight (SubscriptionManager.cpp, TCPServer.cpp) - found while
stress-testing those fixes turned up a third, different crash signature
(heap corruption, not the null-EPoll-reference pattern the earlier two
produced).
2026-09-07 23:52:42 +00:00
Matt Arant 0bb926a264 Fix unsynchronized data race in TCPServer::sessions
connectionRequest()/removeFromSessionList() already lock `lock` around
every mutation of `sessions` (a session accepting or disconnecting), but
every read of it - sendToAll() (all three overloads), getSessionByAlias(),
and the debug-console processCommand() - iterated it with no lock at all.
Exact same bug shape as Subscription::subscribers, fixed earlier today in
SubscriptionManager.cpp, just in a completely separate container.

Confirmed live via dmesg: a real segfault at a stable, deterministic
instruction offset inside the binary, hit twice across separate process
launches tonight - Socket::write() -> resetSocket() dereferencing a null
EPoll reference, the same crash signature as the earlier Subscription fix,
consistent with iterating `sessions` while another thread concurrently
erased and freed one of its entries. sendToAll() backs most real gameplay
broadcasts (combat, position, chat), so this is very likely the actual
dominant cause of tonight's crash - not just the ItemDataBase-specific
subscriber list the earlier fix addressed.

Took the existing `lock` mutex around all five read sites. No new
reentrancy risk: SubscriptionManager's "invite" verb already calls
getSessionByAlias() while holding SubscriptionManager::lock, so the two
mutexes now nest in one fixed order (SubscriptionManager::lock, then
TCPServer::lock) - nothing acquires them in the reverse order anywhere
in this codebase, so no AB-BA deadlock risk.
2026-09-07 23:31:28 +00:00
19 changed files with 1142 additions and 107 deletions

No files matched your search

+7 -2
View File
@@ -12,8 +12,13 @@ namespace core {
} }
void ConsoleServer::logSend(std::string out) { void ConsoleServer::logSend(std::string out) {
for(auto *session : sessions) // Was unlocked entirely (and iterated raw pointers before
((ConsoleSession *)session)->writeLog(out); // TCPServer::sessions became shared_ptr-owned - see its own doc
// comment) despite connectionRequest()/removeFromSessionList()
// both mutating this same vector under `lock` from other threads.
std::lock_guard guard(lock);
for(auto &session : sessions)
((ConsoleSession *)session.get())->writeLog(out);
} }
TCPSession * ConsoleServer::getSocketAccept(EPoll &ePoll) { TCPSession * ConsoleServer::getSocketAccept(EPoll &ePoll) {
+11
View File
@@ -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;
+6
View File
@@ -7,10 +7,16 @@ namespace core {
INotify::INotify(EPoll &ePoll) : Socket(ePoll, "INotify") { INotify::INotify(EPoll &ePoll) : Socket(ePoll, "INotify") {
setDescriptor(inotify_init()); setDescriptor(inotify_init());
// See isKnownINotify()'s own doc comment - registers this object
// as safe for Thread::run() to dispatch epoll events to directly.
std::lock_guard<std::mutex> guard(knownINotifiesMutex());
knownINotifies().insert(this);
} }
INotify::~INotify() { INotify::~INotify() {
shutdown(); shutdown();
std::lock_guard<std::mutex> guard(knownINotifiesMutex());
knownINotifies().erase(this);
} }
int INotify::addWatch(coreutils::ZString &watch) { int INotify::addWatch(coreutils::ZString &watch) {
+37
View File
@@ -2,6 +2,8 @@
# define __INotify_h__ # define __INotify_h__
#include "Socket.h" #include "Socket.h"
#include <set>
#include <mutex>
namespace core { namespace core {
@@ -29,6 +31,41 @@ namespace core {
virtual void inMovedTo(std::string name) {} virtual void inMovedTo(std::string name) {}
virtual void inOpen(std::string name) {} virtual void inOpen(std::string name) {}
/// core::INotify is a long-lived Socket subclass that is neither
/// a TCPSession (shared_ptr/pin()-owned) nor a listening
/// TCPServer - it is normally embedded as a base subobject of a
/// server object constructed once in main() and living for the
/// whole process (e.g. mail::SMTPServer's queue-directory watch).
/// Thread::run()'s epoll dispatch only ever recognized those two
/// categories of raw pointer as safe to call directly (see
/// TCPServer::isKnownListeningSocket()'s own doc comment) -
/// anything else fell through to the "stale/unrecognized epoll
/// event" branch and was silently dropped forever. Confirmed
/// live: a real IN_CREATE event on a mail queue directory logged
/// exactly that "Ignoring stale/unrecognized epoll event" line
/// and the newly queued message was never delivered - it just sat
/// in the queue until the next process restart, whose
/// processExisting() directory scan (a plain synchronous loop,
/// entirely independent of epoll) happened to flush the backlog
/// and made the bug look intermittent. Registering the instance here,
/// mirroring listeningSockets() exactly, gives Thread::run() the
/// same kind of safe "yes, dispatch to this raw pointer directly"
/// signal for INotify objects too.
static bool isKnownINotify(void *ptr) {
std::lock_guard<std::mutex> guard(knownINotifiesMutex());
return knownINotifies().count(ptr) > 0;
}
private:
static std::mutex &knownINotifiesMutex() {
static std::mutex m;
return m;
}
static std::set<void *> &knownINotifies() {
static std::set<void *> s;
return s;
}
}; };
} }
+11 -4
View File
@@ -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();
} }
+91 -3
View File
@@ -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
{ {
@@ -128,7 +130,6 @@ namespace core
coreutils::Log(coreutils::LOG_DEBUG_2) << "EPOLLWRNORM"; coreutils::Log(coreutils::LOG_DEBUG_2) << "EPOLLWRNORM";
writeSocket(); writeSocket();
} }
inHandler = false;
// A graceful shutdown() (session.terminate() -> "goodbye" reply // A graceful shutdown() (session.terminate() -> "goodbye" reply
// queued via write(), then shutdown() called - see e.g. IMAP's // queued via write(), then shutdown() called - see e.g. IMAP's
// LOGOUT/POP3's QUIT/SMTP's QUIT) used to make keepAlive false // LOGOUT/POP3's QUIT/SMTP's QUIT) used to make keepAlive false
@@ -145,7 +146,7 @@ namespace core
// drain to a peer that's already gone is pointless, not graceful) // drain to a peer that's already gone is pointless, not graceful)
// - gives that queued reply a real chance to go out before this // - gives that queued reply a real chance to go out before this
// socket actually closes. // socket actually closes.
bool keepAlive = !shutDown || (fifo.size() > 0 && !readHangup); bool keepAlive = preventSelfDelete || !shutDown || (fifo.size() > 0 && !readHangup);
// resetSocket() re-arms this fd via EPOLL_CTL_MOD, which makes it // resetSocket() re-arms this fd via EPOLL_CTL_MOD, which makes it
// immediately eligible for delivery to ANY worker thread's // immediately eligible for delivery to ANY worker thread's
@@ -162,8 +163,45 @@ namespace core
// the last thing that ever touches `this`, with the return value // the last thing that ever touches `this`, with the return value
// already captured in a local (`keepAlive`) beforehand. // already captured in a local (`keepAlive`) beforehand.
coreutils::Log(coreutils::LOG_DEBUG_1) << "Event process ending for socket " << getDescriptor(); coreutils::Log(coreutils::LOG_DEBUG_1) << "Event process ending for socket " << getDescriptor();
if(keepAlive) // Was cleared several statements above (right after the EPOLLIN/
// EPOLLWRNORM handling), with no lock held around clearing it or
// calling resetSocket() below - a genuinely separate race from the
// one documented above: Socket::write() re-arms via this same
// resetSocket() (see its own doc comment there) whenever it can
// grab `lock`, from whatever thread called it (e.g. a broadcast
// hitting this session while ITS OWN eventReceived() call is still
// running, past receiveData()'s lock_guard but before reaching
// here). A first attempt narrowed this to just checking `inHandler`
// in both places, without holding `lock` across the check-and-act
// in either one - still a real TOCTOU window (inHandler read as
// false here, then write() on another thread sees false too and
// wins the race to resetSocket() first), confirmed live via
// AddressSanitizer as a genuine double-delete of the same session
// object (two threads both reaching ~TCPSession() on it) even
// after that narrowing. Holding `lock` for the whole
// clear-then-reset sequence - the exact same mutex write() already
// takes before its own resetSocket() call - makes the two
// mutually exclusive for real: whichever thread gets there first
// fully finishes (clearing inHandler and re-arming, or observing
// inHandler still true and skipping) before the other can act at
// all, closing the window rather than just narrowing it.
if(keepAlive) {
lock.lock();
inHandler = false;
resetSocket(); resetSocket();
lock.unlock();
}
// else: this object is about to be delete()'d by Thread::run() the
// moment this call returns, unconditionally, regardless of
// anything write() does. Leaving inHandler true forever (never
// clearing it here) means no other thread's write() can ever
// resetSocket() this dying object in the meantime - it has no
// future to reset it FOR, and letting write() re-arm it here, even
// briefly, was exactly the remaining gap: a third thread could
// pick up that re-armed fd and touch/delete an object Thread::run()
// was already about to free, a genuine double-delete confirmed
// live via AddressSanitizer even after write()/resetSocket() were
// otherwise fully serialized against each other.
return keepAlive; return keepAlive;
} }
@@ -211,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();
@@ -303,7 +363,35 @@ namespace core
outlock.lock(); outlock.lock();
fifo.emplace(data); fifo.emplace(data);
outlock.unlock(); outlock.unlock();
// Was unconditional - re-arming here (resetSocket() -> EPOLL_CTL_MOD)
// while this socket's OWN eventReceived() call is still mid-flight
// on another thread (inHandler true - see eventReceived()'s own
// comment on exactly this race) makes the fd immediately eligible
// for a THIRD thread to pick up a fresh event and potentially
// delete this object (Thread::run() does exactly that on a false
// return) while the first thread is still touching it - a genuine
// use-after-free, matching a real heap-corruption crash confirmed
// live via dmesg/AddressSanitizer under concurrent load.
// eventReceived() already re-arms itself once it's actually done
// (checking the current fifo, which already includes whatever was
// just queued above); skip doing it a second, early time from here
// while that's still in progress - the data isn't lost, just
// picked up on that call's own re-arm instead of this one's.
//
// inHandler must be re-checked AFTER acquiring `lock`, not just
// before try_lock() - checking it first and then separately
// acquiring the lock leaves a real TOCTOU gap (this thread reads
// inHandler==false, eventReceived() flips it back and forth on
// another thread, both end up calling resetSocket()); a first
// attempt at this fix only checked before, and a genuine
// double-delete of the same session object still reproduced live
// under AddressSanitizer despite it. eventReceived() holds this
// exact same `lock` across its own inHandler-clear-then-reset
// sequence now (see its own comment), so re-checking inHandler
// only after try_lock() succeeds makes the two truly mutually
// exclusive.
if(lock.try_lock()) { if(lock.try_lock()) {
if(!inHandler)
resetSocket(); resetSocket();
lock.unlock(); lock.unlock();
} }
+39 -1
View File
@@ -4,6 +4,7 @@
#include "ZString.h" #include "ZString.h"
#include <queue> #include <queue>
#include <mutex> #include <mutex>
#include <atomic>
#include <sys/epoll.h> #include <sys/epoll.h>
namespace core { namespace core {
@@ -123,6 +124,23 @@ namespace core {
protected: protected:
// Set by Timer's own constructor (see its own doc comment) - a
// Timer is always a Socket subobject privately/multiply inherited
// alongside a session's own real network Socket (e.g. ZephoraSession
// : TCPSession, Timer), never a standalone connection with its own
// independent lifetime. eventReceived()'s ordinary keepAlive
// contract - returning false means "delete me" (see Thread::run(),
// which then does exactly that on this object's own Socket* base) -
// is correct for a real connection but catastrophic here: deleting
// through a pointer to just the Timer subobject deletes the entire
// composite object at the WRONG size (Timer/Socket's own smaller
// size, not the true derived object's), a new-delete-type-mismatch
// confirmed live via AddressSanitizer under concurrent load. A
// Timer's own fd is already correctly torn down as part of its
// containing object's own destructor chain; it never needs (and
// must never trigger) independent deletion through this path.
bool preventSelfDelete = false;
EPoll &ePoll; // The EPoll control object. EPoll &ePoll; // The EPoll control object.
void setBufferSize(int length); void setBufferSize(int length);
@@ -193,13 +211,33 @@ 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;
int descriptor = -1; int descriptor = -1;
std::mutex outlock; std::mutex outlock;
bool readHangup = false; bool readHangup = false;
volatile bool inHandler = false; // Was `volatile bool` - volatile gives no actual thread-safety
// (no atomicity, no cross-thread visibility guarantee), and this
// flag is now load-bearing (see Socket::write()'s own check of it)
// rather than just feeding a diagnostic log line.
std::atomic<bool> inHandler{false};
//------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------
// the writeSocket is called when epoll has received a write request for a socket. // the writeSocket is called when epoll has received a write request for a socket.
+17 -3
View File
@@ -25,8 +25,15 @@ namespace core {
std::stringstream out; std::stringstream out;
out << "cancel:" << id << std::endl; out << "cancel:" << id << std::endl;
// subscribers holds plain observer pointers, not ownership (see
// TCPSession::pin()'s own doc comment) - a subscriber's session may
// have already started tearing down on another thread by the time
// this runs. pin() safely tells the two cases apart instead of
// blindly dereferencing a pointer that might already be mid-
// destruction or fully freed.
for (auto subscriber : subscribers) { for (auto subscriber : subscribers) {
subscriber->write(out.str()); if (auto safe = subscriber->pin())
safe->write(out.str());
} }
} }
@@ -65,8 +72,14 @@ namespace core {
} }
int Subscription::event(std::stringstream &out) { int Subscription::event(std::stringstream &out) {
// See ~Subscription()'s comment above - same pin()-before-use
// reasoning applies to every subscriber write here. This is the
// broadcast path for every *SUBSCRIBERS-mode topic (chat, item
// database updates, etc.) - the exact crash pin() closes here was
// confirmed live under concurrent load this session.
for (auto subscriber = subscribers.begin(); subscriber < subscribers.end(); ++subscriber) for (auto subscriber = subscribers.begin(); subscriber < subscribers.end(); ++subscriber)
(*subscriber)->write(out.str()); if (auto safe = (*subscriber)->pin())
safe->write(out.str());
return 1; return 1;
} }
@@ -85,7 +98,8 @@ namespace core {
void Subscription::sendToAll(std::stringstream &data, TCPSession &sender) { void Subscription::sendToAll(std::stringstream &data, TCPSession &sender) {
for (auto session : subscribers) for (auto session : subscribers)
if (session != &sender) if (session != &sender)
session->write(data.str()); if (auto safe = session->pin())
safe->write(data.str());
data.str(""); data.str("");
} }
+12 -3
View File
@@ -58,7 +58,12 @@ namespace core
{ {
for (auto subscribed = subscription->subscribers.begin(); subscribed < subscription->subscribers.end(); subscribed++) for (auto subscribed = subscription->subscribers.begin(); subscribed < subscription->subscribers.end(); subscribed++)
{ {
if ((*subscribed)->alias == session.alias) // pin() before reading .alias - a raw subscriber
// pointer here could already be mid-destruction or
// fully freed on another thread (see
// TCPSession::pin()'s own doc comment).
if (auto safe = (*subscribed)->pin())
if (safe->alias == session.alias)
{ {
subscription->subscribers.erase(subscribed++); subscription->subscribers.erase(subscribed++);
} }
@@ -150,8 +155,12 @@ namespace core
// fix for "find a session by the player name they typed" // fix for "find a session by the player name they typed"
// isn't possible at this layer without a larger change; this // isn't possible at this layer without a larger change; this
// stops the crash without pretending to fix that gap. // stops the crash without pretending to fix that gap.
TCPSession *tempSession = session.server->getSessionByAlias(&invitee); // getSessionByAlias() now returns an already-pin()'d
if (tempSession == NULL) // shared_ptr - see its own doc comment - so tempSession itself
// guarantees the session stays alive for this write() call
// below, no separate pin() needed.
auto tempSession = session.server->getSessionByAlias(&invitee);
if (!tempSession)
{ {
coreutils::Log(coreutils::LOG_DEBUG_1) << "invite: could not find session for " << invitee; coreutils::Log(coreutils::LOG_DEBUG_1) << "invite: could not find session for " << invitee;
return 0; return 0;
+192 -54
View File
@@ -3,6 +3,8 @@
#include "Exception.h" #include "Exception.h"
#include "Log.h" #include "Log.h"
#include "TCPSession.h" #include "TCPSession.h"
#include <chrono>
#include <vector>
namespace core { namespace core {
@@ -23,17 +25,47 @@ 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));
}
if (listen(getDescriptor(), 20) < 0) // Was 20 - small enough that a burst of connection attempts
// arriving faster than this process calls accept() (a port scan,
// or just several real clients reconnecting around the same
// moment) can fill the kernel's own backlog before the
// 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(fd, 128) < 0) {
close(fd);
throw coreutils::Exception("Error on listen to socket"); throw coreutils::Exception("Error on listen to socket");
} }
{
std::lock_guard<std::mutex> guard(listeningSocketsMutex());
listeningSockets().insert(this);
}
setDescriptor(fd);
}
TCPServer::~TCPServer() { TCPServer::~TCPServer() {
coreutils::Log(coreutils::LOG_DEBUG_2) << "Closing server socket " << getDescriptor() << "."; coreutils::Log(coreutils::LOG_DEBUG_2) << "Closing server socket " << getDescriptor() << ".";
close(getDescriptor()); close(getDescriptor());
@@ -41,25 +73,51 @@ namespace core {
void TCPServer::connectionRequest() { void TCPServer::connectionRequest() {
coreutils::Log(coreutils::LOG_DEBUG_2) << "Connection request is being received on socket " << getDescriptor() << "."; coreutils::Log(coreutils::LOG_DEBUG_2) << "Connection request is being received on socket " << getDescriptor() << ".";
// Outside the lock.lock()/unlock() below, not nested inside it -
// sweepStaleSessions() takes the same `lock` itself (see its own
// comment), and this mutex isn't recursive.
sweepStaleSessions();
lock.lock(); lock.lock();
TCPSession *session = accept(); // accept() now adds the session to `sessions` and the live registry
if (session) // itself, before its fd is armed - see the comment there.
sessions.push_back(session); // accept() registers the session and, for an implicit-TLS listener,
// Must run ON THE SESSION, not `this` (the listening server) - the // starts its TLS handshake (on the session, not on `this`) before
// unqualified registerSocket()/acceptSocket() calls this replaced // arming the fd - see its own comment.
// built the SSL* handshake state on the SERVER's own TLS-base accept();
// 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();
} }
void TCPServer::sweepStaleSessions() {
// 30 seconds is generous for completing a TCP handshake plus a
// TLS handshake plus sending a first real message over any real
// network - deliberately not aimed at catching anything borderline,
// only connections that never progressed at all.
static const std::chrono::seconds GRACE_PERIOD(30);
auto now = std::chrono::steady_clock::now();
// Collect under `lock` (sessions is mutated elsewhere under the
// same mutex - see its own doc comment), then drop the lock before
// actually removing anything. removeFromSessionList() takes `lock`
// itself for each call; calling it while still holding the guard
// below would deadlock on this non-recursive mutex.
std::vector<TCPSession *> stale;
{
std::lock_guard guard(lock);
for (auto &s : sessions)
if (!s->hasReceivedData && (now - s->acceptedAt) > GRACE_PERIOD)
stale.push_back(s.get());
}
for (auto *s : stale) {
coreutils::Log(coreutils::LOG_DEBUG_2) << "Reaping stale, never-active session " << s->getDescriptor() << ".";
removeFromSessionList(s);
}
}
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
@@ -70,42 +128,103 @@ 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.";
// }
// 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 << "'.";
}
catch (...) {
coreutils::Log(coreutils::LOG_EXCEPT) << "Unnspecified error on session initialization.";
}
return NULL; return NULL;
} }
TCPSession *session = NULL;
try {
session = getSocketAccept(ePoll);
}
catch (...) {
coreutils::Log(coreutils::LOG_EXCEPT) << "Error creating session object; connection refused.";
close(fd);
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) {
std::vector<TCPSession *>::iterator cursor;
lock.lock(); lock.lock();
for (cursor = sessions.begin(); cursor < sessions.end(); ++cursor) for (auto cursor = sessions.begin(); cursor < sessions.end(); ++cursor)
if (*cursor == session) if (cursor->get() == session)
{ {
// Drops the one strong-owning reference. If nothing else is
// currently pin()'d to this session, the object is actually
// destroyed right here, synchronously - same timing as
// before this change for the common (no-contention) case.
// If some other thread IS mid-call via its own pin()'d
// shared_ptr right now, destruction is safely deferred until
// that reference is released too, instead of the crash
// (double-delete / use-after-free, confirmed live via
// AddressSanitizer under concurrent load) that raw-pointer
// ownership produced here before.
sessions.erase(cursor); sessions.erase(cursor);
break; break;
} }
lock.unlock(); lock.unlock();
// Removes this pointer from the tryGet() lookup registry too (see
// TCPSession::tryGet()'s own comment). Safe to do after releasing
// `lock` and regardless of whether the erase() above was actually
// the last reference: tryGet() correctly reports "gone" the moment
// a session's real refcount hits zero, via the weak_ptr's own
// expiration - this call is just tidying the registry map itself,
// not something later correctness depends on.
TCPSession::unregisterLive(session);
} }
void TCPServer::sessionErrorHandler(std::string errorString, std::stringstream &out) { void TCPServer::sessionErrorHandler(std::string errorString, std::stringstream &out) {
@@ -123,8 +242,23 @@ namespace core {
int TCPServer::processCommand(coreutils::ZString &request, TCPSession &session) int TCPServer::processCommand(coreutils::ZString &request, TCPSession &session)
{ {
// Was unguarded, like every other method below - `sessions` is
// mutated under `lock` by connectionRequest()/removeFromSessionList()
// (a session accepting or disconnecting on another thread), but
// every READ of it here had no lock at all. Confirmed live via
// dmesg: a real segfault at a stable, deterministic instruction
// offset (same crash signature as the Subscription::subscribers
// race fixed earlier this session, in SubscriptionManager.cpp) -
// Socket::write() -> resetSocket() dereferencing a null EPoll
// reference, consistent with iterating `sessions` while another
// thread concurrently erased and freed one of its entries.
// sendToAll() in particular is what most real gameplay broadcasts
// (combat, position, chat) go through, so this is very likely the
// actual dominant cause of that crash, not just the ItemDataBase
// subscriber list this session's earlier fix addressed.
std::lock_guard guard(lock);
int sequence = 0; int sequence = 0;
for (auto *sessionx : sessions) for (auto &sessionx : sessions)
{ {
session.out << "|" << ++sequence; session.out << "|" << ++sequence;
sessionx->output(session.out); sessionx->output(session.out);
@@ -134,32 +268,36 @@ namespace core {
} }
void TCPServer::sendToAll(std::stringstream &data) { void TCPServer::sendToAll(std::stringstream &data) {
for (auto session : sessions) std::lock_guard guard(lock);
for (auto &session : sessions)
session->write(data.str()); session->write(data.str());
data.str(""); data.str("");
} }
void TCPServer::sendToAll(std::stringstream &data, TCPSession &sender) { void TCPServer::sendToAll(std::stringstream &data, TCPSession &sender) {
for (auto session : sessions) std::lock_guard guard(lock);
if (session != &sender) for (auto &session : sessions)
if (session.get() != &sender)
session->write(data.str()); session->write(data.str());
data.str(""); data.str("");
} }
void TCPServer::sendToAll(std::stringstream &data, TCPSession &sender, SessionFilter filter) { void TCPServer::sendToAll(std::stringstream &data, TCPSession &sender, SessionFilter filter) {
for (auto session : sessions) std::lock_guard guard(lock);
for (auto &session : sessions)
if (filter.test(*session)) if (filter.test(*session))
if (session != &sender) if (session.get() != &sender)
session->write(data.str()); session->write(data.str());
data.str(""); data.str("");
} }
TCPSession *TCPServer::getSessionByAlias(void *alias) { std::shared_ptr<TCPSession> TCPServer::getSessionByAlias(void *alias) {
coreutils::Log(coreutils::LOG_DEBUG_1) << alias; coreutils::Log(coreutils::LOG_DEBUG_1) << alias;
for (auto session : sessions) std::lock_guard guard(lock);
for (auto &session : sessions)
if (session->alias == alias) if (session->alias == alias)
return session; return session;
return NULL; return nullptr;
} }
} }
+134 -4
View File
@@ -9,6 +9,8 @@
# include "TCPSession.h" # include "TCPSession.h"
# include "TCPSocket.h" # include "TCPSocket.h"
# include "TLSInfo.h" # include "TLSInfo.h"
# include <mutex>
# include <set>
namespace core { namespace core {
@@ -60,8 +62,20 @@ namespace core {
/// ///
/// The list of sessions that are currently open and being maintained by this object. /// The list of sessions that are currently open and being maintained by this object.
/// ///
/// This is the one real, strong-owning reference per live session -
/// see TCPSession::pin()'s own doc comment for the full reasoning.
/// Every other place that keeps a TCPSession* around (Subscription::
/// subscribers, a Zephora-specific sessionsByPlayerName map, etc.)
/// is just a non-owning observer and must pin() before touching the
/// object. A session stops existing, for real, the instant its
/// entry here is erased and every other outstanding pin() (if any
/// thread happened to be mid-call) has released its own reference -
/// removeFromSessionList() is the only place that ever removes an
/// entry, and Thread::run() calls it instead of ever calling
/// `delete` on a TCPSession directly (see its own comment).
///
std::vector<TCPSession *> sessions; std::vector<std::shared_ptr<TCPSession>> sessions;
/// ///
/// The commands object is a CommandList and is used to store Command objects to be /// The commands object is a CommandList and is used to store Command objects to be
@@ -119,10 +133,36 @@ namespace core {
/// ///
/// Use the getSessionByAlias to retrieve a session pointer by the value /// Use the getSessionByAlias to retrieve a session pointer by the value
/// of the alias pointer. /// of the alias pointer. Returns an already-pin()'d shared_ptr (null
/// if not found) rather than a raw pointer, so callers can't
/// accidentally hold onto - or use - a reference that isn't actually
/// keeping the session alive.
/// ///
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:
/// ///
@@ -132,6 +172,31 @@ namespace core {
void connectionRequest() override; void connectionRequest() override;
///
/// Drops any session that completed a TCP accept() but has never
/// had a single byte of real data pass through onDataReceived() -
/// covers both a TLS handshake that never finishes and a plain
/// connection that never sends anything - once it's been open
/// longer than a short grace period. Nothing else in this class
/// ever revisits an already-accepted session once it stops
/// generating epoll events (Thread::run()'s dispatch loop only
/// acts on a session when a real event for it arrives), so a
/// connection that completes the handshake and then goes
/// permanently silent - exactly what a port scan/prober looks
/// like from here, as opposed to a normal scan that just connects
/// and immediately closes again, which the existing read-hangup
/// path already cleans up fine - would otherwise sit in `sessions`
/// forever, one TCPSession + one fd each. Called from
/// connectionRequest() (see its own call site) so the sweep keeps
/// pace with however fast new connections are actually arriving,
/// without needing a dedicated timer/thread of its own; a
/// legitimate, already-talking client is never at risk, since
/// hasReceivedData latches true permanently on its first real byte
/// and is never consulted again after that.
///
void sweepStaleSessions();
/// ///
/// The listening socket itself is never a TLS peer - accepting a /// The listening socket itself is never a TLS peer - accepting a
/// connection on it surfaces as a plain read() failing with ENOTCONN /// connection on it surfaces as a plain read() failing with ENOTCONN
@@ -159,9 +224,74 @@ namespace core {
int processCommand(coreutils::ZString &request, TCPSession &session) override; int processCommand(coreutils::ZString &request, TCPSession &session) override;
protected:
// Was private - ConsoleServer::logSend() (and any other subclass
// that iterates `sessions`, itself public further up) needs to be
// able to synchronize against the exact same mutex
// connectionRequest()/removeFromSessionList() already use, rather
// than reading a shared_ptr vector with no locking of its own.
//
// Was a plain std::mutex - self-deadlocked the accepting thread on
// EVERY single connection to ConsoleServer (confirmed live via a
// gdb thread dump caught mid-stall): connectionRequest() locks
// `lock`, then calls accept(), which constructs the new session -
// whose base Socket constructor logs its own creation via
// coreutils::Log, whose destructor calls back into
// ConsoleServer::logSend() (exactly the synchronization this was
// designed for, per the comment above) - which tries to lock this
// SAME mutex again, on the SAME thread that already holds it.
// std::mutex is not reentrant, so that thread deadlocked
// permanently, every time, without ever completing the accept -
// this is why the admin console never responded to anything.
// Since all of a server's listening sockets share one fixed-size
// EPoll worker-thread pool, each such deadlocked thread is gone
// for good - enough accumulated connection attempts (even
// sporadic ones, e.g. internet-wide port scanners probing every
// port) eventually exhausts every worker thread, at which point
// the WHOLE server - every listening socket, not just the
// console - stops accepting anything new. This is the actual
// root cause of BARANTMail's own multi-day-recurring "all ports
// simultaneously stop accepting connections" incidents - nothing
// to do with DNS/SPF lookup timing, which was a real, separate,
// worthwhile fix but not this bug. recursive_mutex lets the same
// thread re-enter safely (identical behavior to std::mutex for
// every other thread) without changing the locking design at all.
std::recursive_mutex lock;
public:
///
/// A listening TCPServer/ConsoleServer (as opposed to an accepted
/// TCPSession) is constructed once, directly by main(), and lives
/// for the whole process - never through the shared_ptr-based
/// ownership TCPSession::registerLive()/pin() provide (see their
/// own comments), since nothing ever calls `new` on one of these.
/// Thread::run()'s epoll dispatch still needs a SAFE way to tell
/// "this raw pointer is one of those known-immortal listening
/// sockets, fine to call methods on directly" apart from "this is
/// an unrecognized/stale pointer that must not be touched at all"
/// (see TCPSession::tryGet()'s own comment on why dynamic_cast
/// can't make that distinction safely). Registering `this` once,
/// in the constructor, into this tiny set is that signal - it's
/// checked by address only, never dereferenced for the check
/// itself.
///
static bool isKnownListeningSocket(void *ptr) {
std::lock_guard<std::mutex> guard(listeningSocketsMutex());
return listeningSockets().count(ptr) > 0;
}
private: private:
TCPSession *accept(); TCPSession *accept();
std::mutex lock;
static std::mutex &listeningSocketsMutex() {
static std::mutex m;
return m;
}
static std::set<void *> &listeningSockets() {
static std::set<void *> s;
return s;
}
}; };
} }
+20 -2
View File
@@ -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
// 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(""); out.str("");
write(data);
}
}
bool TCPSession::startTLS(SSL_CTX *ctx) {
send();
return TCPSocket::startTLS(ctx);
} }
void TCPSession::terminate() { void TCPSession::terminate() {
+129 -1
View File
@@ -3,6 +3,9 @@
# include "SessionFilter.h" # include "SessionFilter.h"
# include "TCPSocket.h" # include "TCPSocket.h"
# include <map>
# include <memory>
# include <mutex>
# include <sstream> # include <sstream>
namespace core { namespace core {
@@ -22,7 +25,120 @@ namespace core {
/// ///
/// ///
class TCPSession : public TCPSocket { class TCPSession : public TCPSocket, public std::enable_shared_from_this<TCPSession> {
public:
///
/// pin() safely upgrades a raw TCPSession* (as stored in
/// Subscription::subscribers, ZephoraServer's own
/// sessionsByPlayerName, GroupManager's membership lists, etc.)
/// into a real, ownership-extending shared_ptr before it's used.
///
/// The core problem this solves: every crash found and root-caused
/// this session (SubscriptionManager.cpp/TCPServer.cpp/Socket.cpp's
/// own fixes) was the same shape - one thread calling a method
/// (write(), a destructor) on a TCPSession* while another thread
/// concurrently deleted that same object, because nothing actually
/// guaranteed the object stayed alive for the duration of the
/// call. Mutex-based fixes at each individual call site kept
/// narrowing the window without fully closing it, and a mutex
/// around every write() call also isn't what the fifo-based
/// design (see Socket::write()) was going for in the first place -
/// no thread should have to block just to hand off a message.
///
/// TCPServer::sessions now holds the one real, strong-owning
/// shared_ptr<TCPSession> per live session (see its own comment).
/// Every OTHER place that stores a TCPSession* for later use is a
/// plain observer, not an owner - it must call pin() and check for
/// null immediately before touching the object, rather than
/// dereferencing the raw pointer directly. pin() returns nullptr
/// (instead of throwing, unlike raw shared_from_this()) once the
/// object's last real owner has let go and it's on its way out -
/// at that point there is nothing left to safely do with it, and
/// the caller should just skip it as if it were never there,
/// exactly like a stale/already-unsubscribed entry.
///
/// This adds no blocking anywhere: shared_ptr's own refcounting is
/// a couple of atomic increments, not a mutex - the actual
/// deletion still only ever happens once, whenever the last
/// outstanding shared_ptr (held by TCPServer::sessions, or
/// briefly by whichever thread(s) are mid-call via their own
/// pin()'d reference) goes out of scope.
///
std::shared_ptr<TCPSession> pin() {
try { return shared_from_this(); }
catch (const std::bad_weak_ptr &) { return nullptr; }
}
///
/// A second, distinct safety problem pin()/shared_from_this()
/// alone cannot solve: Thread::run()'s epoll dispatch loop starts
/// from a raw `void*` (epoll_event.data.ptr) whose TYPE isn't known
/// yet - the original code cast it straight to `Socket*` and
/// called virtual methods on it; an early version of this fix used
/// dynamic_cast<TCPSession*> to identify session objects before
/// calling pin(). Both of those REQUIRE reading the pointed-to
/// object's own memory (its vtable, at minimum) to work at all -
/// confirmed live via AddressSanitizer that dynamic_cast on a
/// stale pointer (one epoll handed out for a TCPSession that
/// something else had already fully destroyed and freed on another
/// thread) segfaults outright, before pin()'s own safety logic
/// ever gets a chance to run.
///
/// tryGet() sidesteps this entirely: it looks the raw pointer VALUE
/// up as a key in a plain map, and only ever touches a weak_ptr's
/// own control block (a separate heap allocation that outlives the
/// TCPSession object itself for as long as any weak_ptr or
/// shared_ptr referencing it exists) - never the TCPSession's own
/// memory - to decide whether it's still valid. That makes it safe
/// to call on ANY raw pointer value, including ones that turn out
/// to be completely unrelated to this registry (never a
/// TCPSession, e.g. a listening TCPServer/ConsoleServer - see
/// TCPServer::isKnownListeningSocket() for how Thread::run()
/// distinguishes that case) or ones pointing at freed memory.
///
/// registerLive()/unregisterLive() are called exactly once each,
/// by TCPServer::connectionRequest() and removeFromSessionList()
/// respectively - see their own comments for why those are the
/// right, and only, call sites.
///
static void registerLive(TCPSession *raw, std::shared_ptr<TCPSession> owner) {
std::lock_guard<std::mutex> guard(registryMutex());
registry()[raw] = owner;
}
static void unregisterLive(TCPSession *raw) {
std::lock_guard<std::mutex> guard(registryMutex());
registry().erase(raw);
}
static std::shared_ptr<TCPSession> tryGet(void *raw) {
std::lock_guard<std::mutex> guard(registryMutex());
auto it = registry().find((TCPSession *)raw);
if (it == registry().end())
return nullptr;
return it->second.lock();
}
private:
// Function-local statics (constructed on first use, in whichever
// translation unit/thread reaches them first, thread-safely per
// C++11's own guarantee for static local initialization) instead
// of ordinary static data members - avoids needing a .cpp
// definition for these two and any static-initialization-order
// concerns with other translation units, since TCPSession.h is
// included widely.
static std::mutex &registryMutex() {
static std::mutex m;
return m;
}
static std::map<TCPSession *, std::weak_ptr<TCPSession>> &registry() {
static std::map<TCPSession *, std::weak_ptr<TCPSession>> r;
return r;
}
public: public:
@@ -55,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.
/// ///
+86 -7
View File
@@ -40,19 +40,36 @@ 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) {
// 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; int len;
bool more;
{ {
// Held only around the raw SSL_read call - released before // Held only around the raw SSL_read/SSL_pending calls -
// onDataReceived() so the request-handling chain it triggers // released before onDataReceived() so the request-handling
// (which reaches Socket::write()/outlock) never runs while // chain it triggers (which reaches Socket::write()/outlock)
// ioLock is held. See ioLock's own doc comment in TCPSocket.h. // never runs while ioLock is held. See ioLock's own doc
// comment in TCPSocket.h.
std::lock_guard<std::mutex> ioGuard(ioLock); std::lock_guard<std::mutex> ioGuard(ioLock);
len = TLS::receiveData(buffer); len = TLS::receiveData(buffer);
more = len > 0 && pendingBytes() > 0;
} }
if(len >= 0) { if(len >= 0) {
coreutils::ZString zbuffer(buffer.getData(), len); coreutils::ZString zbuffer(buffer.getData(), len);
onDataReceived(zbuffer); 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,14 +123,19 @@ 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();
} }
void TCPSocket::onDataReceived(coreutils::ZString &data) { void TCPSocket::onDataReceived(coreutils::ZString &data) {
if (data.getLength() > 0) { if (data.getLength() > 0) {
hasReceivedData = true;
lineBuffer = (char *)realloc(lineBuffer, lineBufferSize + data.getLength()); lineBuffer = (char *)realloc(lineBuffer, lineBufferSize + data.getLength());
memcpy(lineBuffer + lineBufferSize, data.getData(), data.getLength()); memcpy(lineBuffer + lineBufferSize, data.getData(), data.getLength());
lineBufferSize += data.getLength(); lineBufferSize += data.getLength();
@@ -126,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 *found;
if (strictCRLF)
found = (char *)memmem(lineBuffer, lineBufferSize, "\r\n", 2);
else {
char *cr = (char *)memchr(lineBuffer, '\r', lineBufferSize); char *cr = (char *)memchr(lineBuffer, '\r', lineBufferSize);
char *nl = (char *)memchr(lineBuffer, '\n', lineBufferSize); char *nl = (char *)memchr(lineBuffer, '\n', lineBufferSize);
char *found = (cr && nl) ? std::min(cr, nl) : (cr ? cr : nl); 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; break;
}
if (skippingLongLine || (maxLineLength && (size_t)lineLength > maxLineLength)) {
skippingLongLine = false;
onLineTooLong();
} else {
coreutils::ZString zLine(lineBuffer, lineLength); coreutils::ZString zLine(lineBuffer, lineLength);
onLineReceived(zLine); onLineReceived(zLine);
}
if (discardInput)
break;
// 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
@@ -142,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 (strictCRLF)
lineLength += 2;
else {
if (lineBuffer[lineLength] == '\r') if (lineBuffer[lineLength] == '\r')
++lineLength; ++lineLength;
if (lineLength < lineBufferSize && lineBuffer[lineLength] == '\n') if (lineLength < lineBufferSize && lineBuffer[lineLength] == '\n')
++lineLength; ++lineLength;
}
lineBufferSize -= lineLength; lineBufferSize -= lineLength;
if (lineBufferSize > 0) if (lineBufferSize > 0)
memmove(lineBuffer, lineBuffer + lineLength, lineBufferSize); memmove(lineBuffer, lineBuffer + lineLength, lineBufferSize);
@@ -154,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);
@@ -171,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;
}
} }
} }
@@ -181,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;
} }
+127
View File
@@ -6,6 +6,7 @@
#include "TLS.h" #include "TLS.h"
#include "TLSInfo.h" #include "TLSInfo.h"
#include "IPAddress.h" #include "IPAddress.h"
#include <chrono>
namespace core { namespace core {
@@ -150,6 +151,85 @@ 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
/// this specific socket has been open since accept()/connect(),
/// regardless of whether anything has actually happened on it
/// since. TCPServer::sweepStaleSessions() reads this (alongside
/// hasReceivedData below) to find connections that completed a
/// TCP handshake but then never progressed - a scanner/prober
/// probing an open port, or a TLS handshake that never finished -
/// which otherwise sit in TCPServer::sessions forever: nothing in
/// the existing design ever revisits a socket that stops
/// generating epoll events (see sweepStaleSessions()'s own doc
/// comment for the full reasoning).
///
std::chrono::steady_clock::time_point acceptedAt = std::chrono::steady_clock::now();
///
/// Flips to true the first time onDataReceived() sees a non-empty
/// read - true for both a plaintext socket's raw bytes and a TLS
/// session's already-decrypted ones, since both paths funnel
/// through the same onDataReceived() override below. A session
/// that reaches sweepStaleSessions()'s grace period with this
/// still false has never had a real exchange of any kind, TLS
/// handshake included (a stuck/incomplete SSL_accept() never
/// surfaces anything to onDataReceived) - the specific, narrow
/// condition that sweep treats as abandoned. Deliberately NOT
/// reset afterward and never consulted again once true, so a
/// legitimate client that sends something once and then goes
/// idle for a long time (an ordinary connected-but-idle game
/// session) is never at risk from this - only a connection that
/// NEVER said anything at all within the grace window is.
///
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;
@@ -160,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
+85 -17
View File
@@ -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,13 +94,30 @@ 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);
if(!(ctx = SSL_CTX_new(SSLv23_server_method()))) });
}
void TLS::createContext(TLSInfo *tlsInfo) {
if(tlsInfo)
ctx = buildContext(tlsInfo);
}
// The per-context cert/key/cipher/verify setup, shared by
// createContext(), addSNIContext() (one context per extra hostname)
// and TCPServer::enableStartTLS().
SSL_CTX *TLS::buildContext(TLSInfo *tlsInfo) {
initializeLibrary();
SSL_CTX *newCtx;
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(ctx, 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(ctx, SSL_OP_NO_TICKET); // TLS (BARANTMail does, for STARTTLS) - don't leak the half-built
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER); // context on the way out.
// SSL_CTX_set_generate_session_id(ctx, generate_session_id); try {
SSL_CTX_set_cipher_list(ctx, "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"); SSL_CTX_set_mode(newCtx, SSL_MODE_RELEASE_BUFFERS | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
SSL_CTX_set_options(newCtx, SSL_OP_NO_TICKET);
SSL_CTX_set_session_cache_mode(newCtx, SSL_SESS_CACHE_SERVER);
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");
// _chain_file (not _file) - loads every certificate in the file, // _chain_file (not _file) - loads every certificate in the file,
// not just the first. A real Let's Encrypt fullchain.pem is the // not just the first. A real Let's Encrypt fullchain.pem is the
// leaf cert followed by the intermediate CA cert concatenated in // leaf cert followed by the intermediate CA cert concatenated in
@@ -96,11 +128,11 @@ namespace core {
// got "unable to get local issuer certificate" because the server // got "unable to get local issuer certificate" because the server
// only ever sent the leaf, never the intermediate needed to chain // only ever sent the leaf, never the intermediate needed to chain
// up to a root the client already trusts. // up to a root the client already trusts.
if(SSL_CTX_use_certificate_chain_file(ctx, tlsInfo->certificate.c_str()) <= 0) if(SSL_CTX_use_certificate_chain_file(newCtx, tlsInfo->certificate.c_str()) <= 0)
throw coreutils::Exception("Error looking up certificate."); throw coreutils::Exception("Error looking up certificate.");
if(SSL_CTX_use_PrivateKey_file(ctx, tlsInfo->key.c_str(), SSL_FILETYPE_PEM) < 0) if(SSL_CTX_use_PrivateKey_file(newCtx, tlsInfo->key.c_str(), SSL_FILETYPE_PEM) <= 0)
throw coreutils::Exception("Error with private key."); throw coreutils::Exception("Error with private key.");
if(SSL_CTX_check_private_key(ctx) != 1) if(SSL_CTX_check_private_key(newCtx) != 1)
throw coreutils::Exception("Private key does not match certificate."); throw coreutils::Exception("Private key does not match certificate.");
// Client-certificate verification (mutual TLS) is opt-in, not the // Client-certificate verification (mutual TLS) is opt-in, not the
// default - a public-facing site (e.g. a real Let's Encrypt // default - a public-facing site (e.g. a real Let's Encrypt
@@ -112,17 +144,53 @@ namespace core {
// existing internal/mTLS use of this class (any config that DOES // existing internal/mTLS use of this class (any config that DOES
// set tls.caCertificate) keeps behaving exactly as before. // set tls.caCertificate) keeps behaving exactly as before.
if(tlsInfo->cACertificate.getLength() > 0) { if(tlsInfo->cACertificate.getLength() > 0) {
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); SSL_CTX_set_verify(newCtx, SSL_VERIFY_PEER, NULL);
SSL_CTX_set_verify_depth(ctx, 1); SSL_CTX_set_verify_depth(newCtx, 1);
if(!SSL_CTX_load_verify_locations(ctx, tlsInfo->cACertificate.c_str(), NULL)) if(!SSL_CTX_load_verify_locations(newCtx, tlsInfo->cACertificate.c_str(), NULL))
throw coreutils::Exception("Cannot verify locations."); throw coreutils::Exception("Cannot verify locations.");
SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(tlsInfo->cACertificate.c_str())); 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)."; coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (client certificate required).";
} else { } else {
coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (no client certificate required)."; coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (no client certificate required).";
} }
} }
catch(...) {
SSL_CTX_free(newCtx);
throw;
} }
return newCtx;
}
int TLS::pendingBytes() {
return initialized ? SSL_pending(ssl) : 0;
}
int TLS::sniCallback(SSL *ssl, int *ad, void *arg) {
TLS *self = (TLS *)arg;
const char *name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
if(name) {
auto it = self->sniContexts.find(name);
if(it != self->sniContexts.end())
SSL_set_SSL_CTX(ssl, it->second);
// No match (an unconfigured hostname, or a typo'd Host that still
// resolves here via DNS) - fall through and keep whatever SSL_CTX
// this SSL* already has, which is the base `ctx` SSL_new() was
// constructed from. Exactly the same cert a pre-SNI client (or
// one sending no SNI at all) already gets today.
}
return SSL_TLSEXT_ERR_OK;
}
void TLS::addSNIContext(const std::string &hostname, TLSInfo *tlsInfo) {
SSL_CTX *newCtx = buildContext(tlsInfo);
sniContexts[hostname] = newCtx;
if(!sniCallbackRegistered) {
SSL_CTX_set_tlsext_servername_callback(ctx, sniCallback);
SSL_CTX_set_tlsext_servername_arg(ctx, this);
sniCallbackRegistered = true;
}
}
void TLS::registerSocket(int fd) { void TLS::registerSocket(int fd) {
int ret; int ret;
+58
View File
@@ -4,6 +4,8 @@
#include "ZString.h" #include "ZString.h"
#include "TLSInfo.h" #include "TLSInfo.h"
#include <openssl/ssl.h> #include <openssl/ssl.h>
#include <map>
#include <string>
namespace core { namespace core {
@@ -46,6 +48,36 @@ namespace core {
void createContext(TLSInfo *tlsInfo); void createContext(TLSInfo *tlsInfo);
///
/// Registers a second (or third, etc.) certificate/key pair for a
/// specific hostname on THIS SAME listening socket, via TLS's
/// Server Name Indication (SNI) extension - lets one TCPServer
/// terminate TLS for multiple unrelated domains, each with its own
/// real certificate, without needing a separate listening port or
/// process per domain. Must be called after createContext() (or the
/// TLSInfo* constructor, which calls it) has already established the
/// base `ctx` - that base context keeps serving as both the
/// fallback for hostnames not registered here AND the cert offered
/// to any client that sends no SNI hostname at all (a bare-IP
/// request, or any TLS client old enough to predate SNI). Callers
/// that never call this at all (every existing single-site
/// TLSInfo* user - BARANTMail, Zephora, ClockPlanet, and a
/// single-site APIServer config) see zero behavior change: the SNI
/// callback is only ever registered on `ctx` the first time this is
/// called, not unconditionally in createContext().
///
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
@@ -59,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.
@@ -79,6 +121,22 @@ namespace core {
bool initialized = false; bool initialized = false;
SSL *ssl; SSL *ssl;
// Owns every SSL_CTX* built by addSNIContext() (the base `ctx` is
// owned/freed the same way it always was, untouched by this map).
// Keyed by hostname exactly as configured - matched case-
// insensitively against the ClientHello's SNI value in the
// callback (see TLS.cpp).
std::map<std::string, SSL_CTX *> sniContexts;
bool sniCallbackRegistered = false;
// OpenSSL's own SSL_CTX_set_tlsext_servername_callback signature -
// a static member (not a free function) so it can reach the owning
// TLS instance's private sniContexts via the `arg` parameter
// (SSL_CTX_set_tlsext_servername_arg(ctx, this), set alongside the
// callback itself in addSNIContext()).
static int sniCallback(SSL *ssl, int *ad, void *arg);
}; };
} }
+74 -6
View File
@@ -1,5 +1,7 @@
#include "Thread.h" #include "Thread.h"
#include "EPoll.h" #include "EPoll.h"
#include "TCPServer.h"
#include "INotify.h"
#include <sys/epoll.h> #include <sys/epoll.h>
namespace core { namespace core {
@@ -100,13 +102,79 @@ namespace core {
} else if(rc > 0) { } else if(rc > 0) {
for(int ix = 0; ix < rc; ++ix) { for(int ix = 0; ix < rc; ++ix) {
++count; ++count;
if(((Socket *)events[ix].data.ptr)->eventReceived(events[ix], ++ePoll.eventId)) { // events[ix].data.ptr is a raw pointer of UNKNOWN validity at
// coreutils::Log(coreutils::LOG_DEBUG_4) << "return true"; // this point - it could be a live TCPSession, a listening
// ePoll.resetSocket((Socket *)events[ix].data.ptr); // TCPServer/ConsoleServer (immortal, never shared_ptr-owned),
// or - the case this whole block exists to handle safely - a
// stale/duplicate event for a TCPSession something else
// already fully destroyed and freed on another thread.
//
// A first version of this fix used dynamic_cast<TCPSession*>
// to tell these apart, and a version before that cast
// straight to Socket* unconditionally (the original code).
// BOTH require reading the pointed-to object's own memory
// (its vtable, at minimum) to work - confirmed live via
// AddressSanitizer that dynamic_cast itself segfaults on a
// stale pointer, before any pin()-based safety logic even
// runs. TCPSession::tryGet() and TCPServer::isKnownListening
// Socket() below never dereference this raw pointer for their
// own check - only compare its address against a registry -
// so they're safe to call on literally any value here,
// known-good or not.
void *rawPtr = events[ix].data.ptr;
std::shared_ptr<TCPSession> pinned = TCPSession::tryGet(rawPtr);
if(pinned) {
if(pinned->eventReceived(events[ix], ++ePoll.eventId)) {
// keep alive - pinned goes out of scope at the end of
// this iteration, releasing this thread's temporary
// reference; real ownership (TCPServer::sessions) is
// unaffected.
} else { } else {
((Socket *)events[ix].data.ptr)->shutDown = true; pinned->shutDown = true;
// coreutils::Log(coreutils::LOG_DEBUG_4) << "return false"; // Was `delete (Socket *)events[ix].data.ptr;`
delete (Socket *)events[ix].data.ptr; // unconditionally, for every socket type, including
// real sessions another thread might be mid-call on
// right now via its own pin()'d reference. Dropping
// the one real owning reference is what actually
// frees the object - immediately, if this thread's
// own `pinned` (about to go out of scope) was the
// last one outstanding; safely deferred otherwise.
pinned->server->removeFromSessionList(pinned.get());
}
} else if(TCPServer::isKnownListeningSocket(rawPtr)) {
// Known-immortal (see its own doc comment) - safe to call
// directly, unchanged from the original behavior. A
// listening socket's own eventReceived() returning false
// isn't something that happens in normal operation, but
// preserved as-is for parity with the pre-existing code.
Socket *rawSocket = (Socket *)rawPtr;
if(rawSocket->eventReceived(events[ix], ++ePoll.eventId)) {
// keep alive
} else {
rawSocket->shutDown = true;
delete rawSocket;
}
} else if(INotify::isKnownINotify(rawPtr)) {
// A third category of long-lived, non-TCPSession Socket -
// see INotify::isKnownINotify()'s own doc comment for the
// real, confirmed-live bug this fixes: every INotify event
// (e.g. BARANTMail's mail-queue delivery watch) previously
// fell all the way through to the "unrecognized" branch
// below and was silently dropped forever.
Socket *rawSocket = (Socket *)rawPtr;
if(rawSocket->eventReceived(events[ix], ++ePoll.eventId)) {
// keep alive
} else {
rawSocket->shutDown = true;
delete rawSocket;
}
} else {
// Neither registry recognizes this pointer - almost
// certainly a stale/duplicate epoll event for a
// TCPSession that has already been fully destroyed and
// unregistered elsewhere. There is nothing safe to do
// with it except leave it alone entirely.
coreutils::Log(coreutils::LOG_DEBUG_1) << "Ignoring stale/unrecognized epoll event (pointer " << rawPtr << ")";
} }
} }
} }
+6
View File
@@ -7,6 +7,12 @@ namespace core
Timer::Timer(EPoll &ePoll, double delay = 0.0f) : Socket(ePoll, "Timer") Timer::Timer(EPoll &ePoll, double delay = 0.0f) : Socket(ePoll, "Timer")
{ {
// See preventSelfDelete's own doc comment on Socket - a Timer is
// always a subobject of some larger composite (e.g. ZephoraSession
// : TCPSession, Timer), never a standalone connection, so its own
// eventReceived() must never be allowed to signal "delete me" to
// Thread::run()'s generic dispatch.
preventSelfDelete = true;
setDescriptor(timerfd_create(CLOCK_REALTIME, 0)); setDescriptor(timerfd_create(CLOCK_REALTIME, 0));
setTimer(delay); setTimer(delay);
} }