Files
ServerCore/TCPSocket.h
T
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

315 lines
12 KiB
C++

#ifndef __TCPSocket_h__
#define __TCPSocket_h__
#include "Socket.h"
#include "TLS.h"
#include "TLSInfo.h"
#include "IPAddress.h"
#include <chrono>
namespace core {
///
/// TCPSocket
///
/// Provides a network TCP socket.
///
/// For accessing TCP network functions use this object. The connection oriented nature of TCP
/// provides a single client persistent connection with data error correction and a durable
/// synchronous data connection.
///
class TCPSocket : public Socket, public TLS {
public:
///
///
///
TCPSocket(EPoll &ePoll);
///
///
///
TCPSocket(EPoll &ePoll, std::string text);
///
///
///
TCPSocket(EPoll &ePoll, TLSInfo *tlsInfo, std::string text);
///
///
///
TCPSocket(EPoll &ePoll, SSL_CTX *ctx, std::string text);
///
///
///
virtual ~TCPSocket();
///
///
///
void connect(IPAddress &address);
IPAddress ipAddress;
///
/// The output method is called by a socket session (TCPSession) and
/// will output the detail information for the client socket. When extending
/// TCPSocket or TCPSession you can override the method to add attributes
/// to the list.
///
virtual void output(std::stringstream &out);
///
/// Override this method to receive data directly from the socket as data is
/// received. If you need data split by line termination characters then
/// override the onLineReceived method instead.
///
virtual void onDataReceived(coreutils::ZString &data) override;
///
/// Override the onLineReceived method to receive a string of characters that
/// represents a single line of data terminated by a LF or CRLF. If onDataReceived
/// was overriden this method will not be called unless the onDataReceived calls
/// this method explicitly using the class and member name.
///
virtual void onLineReceived(coreutils::ZString &line);
///
/// Override the onBlockReceived method to receive a string of characters that
/// represents a single block of data of length determined by the block length value. If
/// onDataReceived was overriden this method will not be called unless the onDataReceived
/// calls this method explicitly using the class and member name.
///
virtual void onBlockReceived(coreutils::ZString &block);
///
/// Use setBlockSize to set the amount of data that should be read at once from the
/// session data buffer.
/// If this value is set to 0 then the data will be retrieved
///
void setBlockSize(int size = 0);
///
/// Dispatches to TLS::receiveData (SSL_read) when this socket was constructed with a
/// TLSInfo/SSL_CTX, otherwise falls back to Socket::receiveData (plain ::read). Needed
/// because Socket and TLS both declare receiveData as unrelated sibling methods -
/// Socket::receiveData is virtual but TLS::receiveData does not override it, so without
/// this explicit override TLS::receiveData would never be reached and encrypted bytes
/// would be handed to onDataReceived as if they were plaintext.
///
virtual void receiveData(coreutils::ZString &buffer) override;
///
/// Dispatches to TLS::sendData (SSL_write) when this socket was constructed with a
/// TLSInfo/SSL_CTX, otherwise falls back to Socket::sendData (plain ::write). Mirrors
/// the receiveData override above for the write path.
///
virtual int sendData(const char *data, int length) override;
///
/// True only when this socket is actually TLS (ctx set) and the
/// last sendData() call failed specifically with
/// SSL_ERROR_WANT_READ - see TLS::lastSendWantedRead's own doc
/// comment for why Socket::writeSocket()/resetSocket() need this.
///
virtual bool sendNeedsRead() override;
///
/// Completes the TLS handshake (SSL_new/SSL_set_fd/SSL_accept) for
/// THIS socket's own ctx/descriptor. registerSocket()/acceptSocket()
/// are protected TLS members, reachable here via an ordinary
/// same-class call - the point of exposing this as a public wrapper
/// is so a sibling class (TCPServer, which does not inherit
/// TCPSocket-the-session's-particular-instance and so cannot reach
/// another object's protected members directly) can still trigger
/// the handshake on a specific accepted session from
/// TCPServer::connectionRequest(), rather than accidentally running
/// it against the listening server socket itself (see that call
/// site's own comment for the real, confirmed crash this replaces -
/// SSL_read() on an accepted session's never-initialized ssl
/// member).
///
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:
bool term = false;
TLSInfo *tlsInfo;
private:
char *lineBuffer = NULL;
int lineBufferSize = 0;
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 <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
// writeSocket/the fifo) are two DIFFERENT mutexes - a thread
// handling EPOLLIN and a different thread handling EPOLLWRNORM for
// the SAME connection can therefore call SSL_read and SSL_write on
// the SAME `ssl*` concurrently. OpenSSL does not support that: an
// SSL object must not be used by more than one thread at a time
// (even in 1.1.0+/3.x, which dropped the old app-supplied
// CRYPTO_set_locking_callback global-locking API entirely - that
// API never protected concurrent use of one SSL object anyway,
// only OpenSSL's own internal global state). Confirmed live via
// dmesg: "traps: apiserver[...] general protection fault ... in
// libssl.so.3" during ordinary interactive use. ioLock serializes
// just the raw SSL_read/SSL_write calls themselves (see
// receiveData/sendData below) - deliberately NOT the surrounding
// request-handling, which already nests `lock` before `outlock`
// (receiveData's call chain reaches Socket::write(), which takes
// outlock) - wrapping any larger scope in ioLock+lock+outlock
// together risks recreating that same ordering as a new cycle.
std::mutex ioLock;
};
}
#endif