diff --git a/Socket.cpp b/Socket.cpp index b20ee62..3f994ad 100644 --- a/Socket.cpp +++ b/Socket.cpp @@ -4,6 +4,8 @@ #include "Log.h" #include "ZString.h" #include +#include +#include namespace core { @@ -247,6 +249,28 @@ namespace core return ::write(descriptor, data, length); } + bool Socket::flushPlain(int timeoutMs) { + std::lock_guard 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() { outlock.lock(); // coreutils::Log(coreutils::LOG_DEBUG_3) << "writing data to socket " << getDescriptor(); diff --git a/Socket.h b/Socket.h index 399131d..72f28ab 100644 --- a/Socket.h +++ b/Socket.h @@ -211,6 +211,22 @@ namespace core { 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: std::string text; diff --git a/TCPServer.cpp b/TCPServer.cpp index 7f6f29e..a0c7377 100644 --- a/TCPServer.cpp +++ b/TCPServer.cpp @@ -25,12 +25,26 @@ namespace core { commands.add(subscriptions, "event"); commands.add(subscriptions, "invite"); - setDescriptor(socket(AF_INET, SOCK_STREAM, 0)); + // Bind, listen and register as a known listening socket BEFORE + // setDescriptor() adds the fd to epoll. setDescriptor() arms it + // immediately (EPOLLONESHOT), and a brand-new socket that isn't + // listening yet reports EPOLLHUP right away. That event used to race + // the rest of this constructor: whenever an epoll worker thread + // picked it up before the listeningSockets().insert() below, + // Thread::run() didn't recognize the pointer and skipped it without + // re-arming, so the one-shot registration was spent and the server + // never saw another connection - up, bound and listening, but + // silently accepting nothing for the life of the process. Reproduced + // on an unmodified build: roughly 3 startups in 8 dead on arrival. + int fd = socket(AF_INET, SOCK_STREAM, 0); int yes = 1; - setsockopt(getDescriptor(), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); - if (bind(getDescriptor(), address.getPointer(), address.addressLength) < 0) - throw coreutils::Exception("Error on bind to socket: " + std::to_string(errno)); + if (bind(fd, address.getPointer(), address.addressLength) < 0) { + int error = errno; + close(fd); + throw coreutils::Exception("Error on bind to socket: " + std::to_string(error)); + } // Was 20 - small enough that a burst of connection attempts // arriving faster than this process calls accept() (a port scan, @@ -39,16 +53,17 @@ namespace core { // application layer gets a chance to drain it, silently dropping // the overflow SYNs rather than queuing them. 128 gives real // bursts meaningfully more headroom; still bounded, not unlimited. - if (listen(getDescriptor(), 128) < 0) - throw coreutils::Exception("Error on listen to socket"); + if (listen(fd, 128) < 0) { + close(fd); + throw coreutils::Exception("Error on listen to socket"); + } - // See isKnownListeningSocket()'s own doc comment - registers this - // listening socket as safe for Thread::run() to dispatch to - // directly, distinct from the shared_ptr-owned TCPSession registry. { std::lock_guard guard(listeningSocketsMutex()); listeningSockets().insert(this); } + + setDescriptor(fd); } TCPServer::~TCPServer() { @@ -63,33 +78,12 @@ namespace core { // comment), and this mutex isn't recursive. sweepStaleSessions(); lock.lock(); - TCPSession *session = accept(); - // The shared_ptr constructed here IS the session's real, strong - // ownership from now on (see sessions' own doc comment). A second - // reference to the SAME shared_ptr (never a second, independent - // std::shared_ptr(session) call on the same raw - // pointer - that would create a second, competing control block - // and a guaranteed double-free) also goes into the tryGet() - // registry, which is what Thread::run()'s epoll dispatch actually - // uses to safely reach this object (see TCPSession::tryGet()'s - // own comment on why). - if (session) { - auto sessionPtr = std::shared_ptr(session); - sessions.push_back(sessionPtr); - TCPSession::registerLive(session, sessionPtr); - } - // Must run ON THE SESSION, not `this` (the listening server) - the - // unqualified registerSocket()/acceptSocket() calls this replaced - // built the SSL* handshake state on the SERVER's own TLS-base - // member instead of the newly accepted session's, leaving every - // session's own `ssl` uninitialized and segfaulting the first time - // real data arrived on it (SSL_read() against a never-SSL_new()'d - // pointer - confirmed via gdb). Sessions already correctly inherit - // this server's SSL_CTX at construction (TCPSession's own - // TLS(SSL_CTX*)-taking constructor) - performTLSHandshake() just - // needed to actually be invoked on that object. - if (session && tlsInfo) - session->performTLSHandshake(); + // accept() now adds the session to `sessions` and the live registry + // itself, before its fd is armed - see the comment there. + // accept() registers the session and, for an implicit-TLS listener, + // starts its TLS handshake (on the session, not on `this`) before + // arming the fd - see its own comment. + accept(); lock.unlock(); } @@ -120,6 +114,10 @@ namespace core { } } + void TCPServer::enableStartTLS(TLSInfo &tlsInfo) { + startTLSContext = TLS::buildContext(&tlsInfo); + } + void TCPServer::receiveData(coreutils::ZString &buffer) { // See this override's own doc comment in TCPServer.h - the // listening socket always uses the plain read()/ENOTCONN detection @@ -130,30 +128,74 @@ namespace core { TCPSession * TCPServer::accept() { - try - { + // Called with `lock` held (connectionRequest()). + // + // The session must be owned by `sessions` and registered with + // TCPSession::registerLive() BEFORE setDescriptor() adds its fd to + // epoll. setDescriptor() arms the fd and runs onConnected(), which + // queues the protocol greeting ("220 ..." for SMTP) and re-arms for + // EPOLLWRNORM; another epoll worker can pick that event up at once. + // Registration used to happen afterwards, back in + // connectionRequest(), so whenever a worker got there first + // Thread::run()'s TCPSession::tryGet() didn't know the pointer and + // dropped the event without re-arming (EPOLLONESHOT): the client + // was connected but never received a single byte. Reproduced on an + // unmodified build with 40 simultaneous plain-text SMTP + // connections - 4 to 6 per burst stuck before the greeting. For a + // mail server that is lost (well, deferred) inbound mail. + // + // Accepting into a local address first also means a failed + // ::accept() (EAGAIN on a spurious wakeup, EMFILE) no longer creates + // - and then leaks - a session object at all. - TCPSession *session = getSocketAccept(ePoll); - session->setDescriptor(::accept(getDescriptor(), (struct sockaddr *)&session->ipAddress.addr, &session->ipAddress.addressLength)); - // if(blackList && blackList->contains(session->ipAddress.getClientAddress())) { - // session->shutdown(); - // Log(LOG_WARN) << "Client at IP address " << session->ipAddress.getClientAddress() << " is blacklisted and was denied a connection."; - // return NULL; - // } - // if(whiteList && !whiteList->contains(session->ipAddress.getClientAddress())) { - // session->shutdown(); - // Log(LOG_WARN) << "Client at IP address " << session->ipAddress.getClientAddress() << " is not authorized and was denied a connection."; - // return NULL; - // } - return session; + struct sockaddr_in address; + socklen_t addressLength = sizeof(address); + int fd = ::accept(getDescriptor(), (struct sockaddr *)&address, &addressLength); + if (fd < 0) { + if (errno == EMFILE || errno == ENFILE) + coreutils::Log(coreutils::LOG_EXCEPT) << "Too many files open. Refusing connection."; + return NULL; } - catch (coreutils::Exception e) { - coreutils::Log(coreutils::LOG_EXCEPT) << "Major error on session initialization. Error is '" << e.text << "'."; + + TCPSession *session = NULL; + try { + session = getSocketAccept(ePoll); } catch (...) { - coreutils::Log(coreutils::LOG_EXCEPT) << "Unnspecified error on session initialization."; + coreutils::Log(coreutils::LOG_EXCEPT) << "Error creating session object; connection refused."; + close(fd); + return NULL; } - return NULL; + session->ipAddress.addr = address; + session->ipAddress.addressLength = addressLength; + + auto sessionPtr = std::shared_ptr(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) { diff --git a/TCPServer.h b/TCPServer.h index 254b437..2b0c794 100644 --- a/TCPServer.h +++ b/TCPServer.h @@ -140,6 +140,29 @@ namespace core { /// std::shared_ptr 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: /// diff --git a/TCPSession.cpp b/TCPSession.cpp index 0c70143..d9fba08 100644 --- a/TCPSession.cpp +++ b/TCPSession.cpp @@ -91,9 +91,27 @@ namespace core { } void TCPSession::send() { - if(out.tellp() > 0) - write(out.str()); - out.str(""); + // Take the data and clear `out` BEFORE write(). write() can re-arm + // 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(""); + write(data); + } + } + + bool TCPSession::startTLS(SSL_CTX *ctx) { + send(); + return TCPSocket::startTLS(ctx); } void TCPSession::terminate() { diff --git a/TCPSession.h b/TCPSession.h index e6e196c..341dfc1 100644 --- a/TCPSession.h +++ b/TCPSession.h @@ -170,6 +170,18 @@ namespace core { /// 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. diff --git a/TCPSocket.cpp b/TCPSocket.cpp index 9c0f83b..f3c39ed 100644 --- a/TCPSocket.cpp +++ b/TCPSocket.cpp @@ -40,18 +40,35 @@ namespace core { // session (set in TLS::createContext(), inherited by sessions via // TLS(SSL_CTX*)), safely NULL by default otherwise (see TLS.h). if(ctx) { - int len; - { - // Held only around the raw SSL_read call - released before - // onDataReceived() so the request-handling chain it triggers - // (which reaches Socket::write()/outlock) never runs while - // ioLock is held. See ioLock's own doc comment in TCPSocket.h. - std::lock_guard ioGuard(ioLock); - len = TLS::receiveData(buffer); - } - if(len >= 0) { - coreutils::ZString zbuffer(buffer.getData(), len); - onDataReceived(zbuffer); + // Loop until OpenSSL has nothing decrypted left over. A single TLS + // record carries up to 16KB, but `buffer` is 4KB, so one SSL_read() + // can leave the rest of a record sitting inside OpenSSL. This socket + // is edge-triggered (EPOLLET) and those bytes have already been + // pulled off the fd, so nothing would ever raise another EPOLLIN + // for them: the session would stall mid-stream until the peer + // happened to send something else. Small requests (HTTP headers, + // single commands) never fill a 4KB read, which is why this didn't + // show up before; an SMTP DATA body from another mail server - the + // common case once STARTTLS is offered - does on every message. + while(true) { + int len; + bool more; + { + // Held only around the raw SSL_read/SSL_pending calls - + // released before onDataReceived() so the request-handling + // chain it triggers (which reaches Socket::write()/outlock) + // never runs while ioLock is held. See ioLock's own doc + // comment in TCPSocket.h. + std::lock_guard ioGuard(ioLock); + len = TLS::receiveData(buffer); + more = len > 0 && pendingBytes() > 0; + } + if(len >= 0) { + coreutils::ZString zbuffer(buffer.getData(), len); + onDataReceived(zbuffer); + } + if(!more || shutDown) + break; } } else { Socket::receiveData(buffer); @@ -70,6 +87,21 @@ namespace core { return ctx && lastSendWantedRead; } + bool TCPSocket::startTLS(SSL_CTX *newCtx) { + if(ctx || !newCtx) + return false; + discardInput = true; + if(!flushPlain(10000)) { + coreutils::Log(coreutils::LOG_DEBUG_1) << "STARTTLS: ready reply could not be delivered; closing."; + shutdown("STARTTLS ready reply could not be delivered"); + return false; + } + ctx = newCtx; + performTLSHandshake(); + coreutils::Log(coreutils::LOG_DEBUG_1) << "STARTTLS: handshake started on socket " << getDescriptor() << "."; + return true; + } + void TCPSocket::performTLSHandshake() { // registerSocket() makes this fd eligible for epoll dispatch to ANY // worker thread immediately. ioLock MUST be acquired BEFORE that @@ -91,8 +123,12 @@ namespace core { // (WANT_READ/WANT_WRITE) - that's fine, OpenSSL transparently // finishes a pending handshake on the next SSL_read/SSL_write, // which ioLock already serializes against everything else. + performTLSHandshake(getDescriptor()); + } + + void TCPSocket::performTLSHandshake(int fd) { std::lock_guard ioGuard(ioLock); - registerSocket(getDescriptor()); + registerSocket(fd); acceptSocket(); } @@ -127,14 +163,37 @@ namespace core { // the bounded equivalent - it never looks past the length // given, so "no CRLF yet" correctly comes back as "not // found" instead of reading off the end of the allocation. - char *cr = (char *)memchr(lineBuffer, '\r', lineBufferSize); - char *nl = (char *)memchr(lineBuffer, '\n', lineBufferSize); - char *found = (cr && nl) ? std::min(cr, nl) : (cr ? cr : nl); + char *found; + if (strictCRLF) + found = (char *)memmem(lineBuffer, lineBufferSize, "\r\n", 2); + else { + char *cr = (char *)memchr(lineBuffer, '\r', lineBufferSize); + char *nl = (char *)memchr(lineBuffer, '\n', lineBufferSize); + found = (cr && nl) ? std::min(cr, nl) : (cr ? cr : nl); + } lineLength = found ? (int)(found - lineBuffer) : lineBufferSize; - if (lineLength == lineBufferSize) + if (!found) { + // No complete line yet. If it has already outgrown + // maxLineLength, drop what's buffered (keeping the last + // byte, which may be the CR of a CR LF whose LF is still + // in flight) and skip the rest of it - see maxLineLength. + if (maxLineLength && (size_t)lineBufferSize > maxLineLength) { + lineBuffer[0] = lineBuffer[lineBufferSize - 1]; + lineBufferSize = 1; + lineBuffer = (char *)realloc(lineBuffer, lineBufferSize); + skippingLongLine = true; + } + break; + } + if (skippingLongLine || (maxLineLength && (size_t)lineLength > maxLineLength)) { + skippingLongLine = false; + onLineTooLong(); + } else { + coreutils::ZString zLine(lineBuffer, lineLength); + onLineReceived(zLine); + } + if (discardInput) break; - coreutils::ZString zLine(lineBuffer, lineLength); - onLineReceived(zLine); // lineLength < lineBufferSize is guaranteed by the break // above, so this first index is always in bounds; bump // past a lone '\r' only if there's still at least one more @@ -143,10 +202,14 @@ namespace core { // after it yet) leave it for the next read to resolve, // rather than reading lineBuffer[lineBufferSize], one past // the allocation. - if (lineBuffer[lineLength] == '\r') - ++lineLength; - if (lineLength < lineBufferSize && lineBuffer[lineLength] == '\n') - ++lineLength; + if (strictCRLF) + lineLength += 2; + else { + if (lineBuffer[lineLength] == '\r') + ++lineLength; + if (lineLength < lineBufferSize && lineBuffer[lineLength] == '\n') + ++lineLength; + } lineBufferSize -= lineLength; if (lineBufferSize > 0) memmove(lineBuffer, lineBuffer + lineLength, lineBufferSize); @@ -155,6 +218,8 @@ namespace core { else if (lineBufferSize >= blockSize) { coreutils::ZString zBlock(lineBuffer, blockSize); onBlockReceived(zBlock); + if (discardInput) + break; lineBufferSize -= blockSize; if (lineBufferSize > 0) memmove(lineBuffer, lineBuffer + blockSize, lineBufferSize); @@ -171,7 +236,16 @@ namespace core { // changes, so the while(lineBufferSize > 0) loop above // never yields back to let more data arrive. break; - } + } + if (discardInput) { + // See startTLS(): whatever followed the upgrade command in this + // read is pre-handshake plain text and is dropped, not processed. + discardInput = false; + free(lineBuffer); + lineBuffer = NULL; + lineBufferSize = 0; + lineLength = 0; + } } } @@ -182,6 +256,10 @@ namespace core { void TCPSocket::onBlockReceived(coreutils::ZString &block) {} + void TCPSocket::onLineTooLong() { + shutdown("line exceeded maxLineLength"); + } + void TCPSocket::setBlockSize(int blockSize) { this->blockSize = blockSize; } diff --git a/TCPSocket.h b/TCPSocket.h index 5705f22..afc310c 100644 --- a/TCPSocket.h +++ b/TCPSocket.h @@ -151,6 +151,16 @@ namespace core { 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(), @@ -186,6 +196,40 @@ namespace core { 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: bool term = false; TLSInfo *tlsInfo; @@ -196,6 +240,53 @@ namespace core { int lineLength = 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 . + /// the only end-of-data sequence; a server that also accepts bare + /// or line endings can be made to end a message early on + /// "." 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 // writeSocket/the fifo) are two DIFFERENT mutexes - a thread // handling EPOLLIN and a different thread handling EPOLLWRNORM for diff --git a/TLS.cpp b/TLS.cpp index 103078a..3a19631 100644 --- a/TLS.cpp +++ b/TLS.cpp @@ -3,6 +3,7 @@ #include "Log.h" #include #include +#include namespace core { @@ -65,11 +66,25 @@ namespace core { 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) { - - if(tlsInfo) { + // The ONE-TIME, process-wide OpenSSL library init (SSL_library_init(), + // the lockarray, RAND seeding). Used to live in createContext(), which + // 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_load_error_strings(); lockarray = (pthread_mutex_t *)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t)); @@ -79,63 +94,77 @@ namespace core { CRYPTO_set_locking_callback((void (*)(int, int, const char *, int))lock_callback); SSLeay_add_ssl_algorithms(); RAND_load_file("/dev/hwrng", 1024); - ctx = buildContext(tlsInfo); - } + }); } - // The per-context cert/key/cipher/verify setup factored out of - // createContext() above so addSNIContext() (below) can build - // additional contexts - one per extra hostname - without repeating - // the ONE-TIME, process-wide OpenSSL library init that stays in - // createContext() itself (SSL_library_init(), the lockarray, RAND - // seeding): that part must only ever run once per process, not once - // per hostname. + 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."); - 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, - // not just the first. A real Let's Encrypt fullchain.pem is the - // leaf cert followed by the intermediate CA cert concatenated in - // one file specifically so a server can hand both to the client - // in one shot; SSL_CTX_use_certificate_file() only ever reads the - // first PEM block, silently dropping the intermediate - confirmed - // via a real handshake against this exact fullchain.pem: clients - // got "unable to get local issuer certificate" because the server - // only ever sent the leaf, never the intermediate needed to chain - // up to a root the client already trusts. - if(SSL_CTX_use_certificate_chain_file(newCtx, tlsInfo->certificate.c_str()) <= 0) - throw coreutils::Exception("Error looking up certificate."); - if(SSL_CTX_use_PrivateKey_file(newCtx, tlsInfo->key.c_str(), SSL_FILETYPE_PEM) < 0) - throw coreutils::Exception("Error with private key."); - if(SSL_CTX_check_private_key(newCtx) != 1) - throw coreutils::Exception("Private key does not match certificate."); - // Client-certificate verification (mutual TLS) is opt-in, not the - // default - a public-facing site (e.g. a real Let's Encrypt - // server cert with no corresponding client CA of its own) has no - // client certificate to hand out to ordinary visitors, so - // requesting one via SSL_VERIFY_PEER would surface a "select a - // certificate" prompt real browsers can't meaningfully answer. - // Only enable it when a caCertificate is actually configured - - // existing internal/mTLS use of this class (any config that DOES - // set tls.caCertificate) keeps behaving exactly as before. - if(tlsInfo->cACertificate.getLength() > 0) { - SSL_CTX_set_verify(newCtx, SSL_VERIFY_PEER, NULL); - SSL_CTX_set_verify_depth(newCtx, 1); - if(!SSL_CTX_load_verify_locations(newCtx, tlsInfo->cACertificate.c_str(), NULL)) - throw coreutils::Exception("Cannot verify locations."); - SSL_CTX_set_client_CA_list(newCtx, SSL_load_client_CA_file(tlsInfo->cACertificate.c_str())); - coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (client certificate required)."; - } else { - coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (no client certificate required)."; + // A caller may now catch a bad certificate/key and carry on without + // TLS (BARANTMail does, for STARTTLS) - don't leak the half-built + // context on the way out. + try { + 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, + // not just the first. A real Let's Encrypt fullchain.pem is the + // leaf cert followed by the intermediate CA cert concatenated in + // one file specifically so a server can hand both to the client + // in one shot; SSL_CTX_use_certificate_file() only ever reads the + // first PEM block, silently dropping the intermediate - confirmed + // via a real handshake against this exact fullchain.pem: clients + // got "unable to get local issuer certificate" because the server + // only ever sent the leaf, never the intermediate needed to chain + // up to a root the client already trusts. + if(SSL_CTX_use_certificate_chain_file(newCtx, tlsInfo->certificate.c_str()) <= 0) + throw coreutils::Exception("Error looking up certificate."); + if(SSL_CTX_use_PrivateKey_file(newCtx, tlsInfo->key.c_str(), SSL_FILETYPE_PEM) <= 0) + throw coreutils::Exception("Error with private key."); + if(SSL_CTX_check_private_key(newCtx) != 1) + throw coreutils::Exception("Private key does not match certificate."); + // Client-certificate verification (mutual TLS) is opt-in, not the + // default - a public-facing site (e.g. a real Let's Encrypt + // server cert with no corresponding client CA of its own) has no + // client certificate to hand out to ordinary visitors, so + // requesting one via SSL_VERIFY_PEER would surface a "select a + // certificate" prompt real browsers can't meaningfully answer. + // Only enable it when a caCertificate is actually configured - + // existing internal/mTLS use of this class (any config that DOES + // set tls.caCertificate) keeps behaving exactly as before. + if(tlsInfo->cACertificate.getLength() > 0) { + SSL_CTX_set_verify(newCtx, SSL_VERIFY_PEER, NULL); + SSL_CTX_set_verify_depth(newCtx, 1); + if(!SSL_CTX_load_verify_locations(newCtx, tlsInfo->cACertificate.c_str(), NULL)) + throw coreutils::Exception("Cannot verify locations."); + SSL_CTX_set_client_CA_list(newCtx, SSL_load_client_CA_file(tlsInfo->cACertificate.c_str())); + coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (client certificate required)."; + } else { + coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (no client certificate required)."; + } + } + catch(...) { + SSL_CTX_free(newCtx); + throw; } return newCtx; } + 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); diff --git a/TLS.h b/TLS.h index 0a51f7f..ed0322e 100644 --- a/TLS.h +++ b/TLS.h @@ -68,6 +68,16 @@ namespace core { /// 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 // itself when constructed with tlsInfo=NULL, or a TCPSession spawned // from one via TLS(SSL_CTX*)) must default to a real NULL here, not @@ -80,6 +90,16 @@ namespace core { int sendData(const char *data, int length); void registerSocket(int fd); 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: // Set by sendData() when the last SSL_write() failed specifically @@ -101,12 +121,6 @@ namespace core { bool initialized = false; SSL *ssl; - // The actual cert/key-loading + cipher/session-cache setup shared - // by both the base context (createContext(), unchanged) and every - // additional per-hostname context addSNIContext() builds - factored - // out so there's exactly one place that does this, not two copies - // drifting apart. - SSL_CTX *buildContext(TLSInfo *tlsInfo); // Owns every SSL_CTX* built by addSNIContext() (the base `ctx` is // owned/freed the same way it always was, untouched by this map).