Contents · Forum Home · StreamSec Tools 4.1.5.363 documentation

StreamSec.Mail.SMTPEngine

The server side of RFC 5321, with no socket, no TLS and no threads in it:
  octets go in through Receive, reply octets come out through OnOutput, and a
  completed message is handed to an iSmtpServerPolicy. That is the same shape as
  StreamSec.Http.Http2Conn and it exists for the same reason - SMTP framing is
  the security-critical half of an SMTP server, every smuggling technique is an
  attack on exactly these rules, and a parser that cannot be driven without a
  socket is one whose hostile-input cases never get tested. SmtpServerSelfTest at
  the bottom drives them.

  WHAT SPEAKS IT. StreamSec.Mail.SMTPServer wraps one of these per connection for
  TsmAsyncTLSServer, which is implicit TLS from byte 0 - so the deployment is
  SMTPS on port 465 (RFC 8314) and STARTTLS never appears. The engine itself
  carries no such assumption: it is TOLD what its channel is (SecureChannel,
  TransportInfo) and enforces policy against that.

  THE END-OF-DATA RULE, WHICH IS THE WHOLE OF SMTP SMUGGLING. A message body ends
  at <CRLF>.<CRLF> and at nothing else. This engine finds line boundaries in the
  DATA phase by scanning for CRLF ONLY - never for a bare CR, never for a bare
  LF - so <LF>.<LF> and <CR>.<CR> cannot terminate a message however they are
  spelled, and a downstream MTA with a laxer rule cannot be fed a second envelope
  through this one (CVE-2023-51764 and the family around it). A bare CR or LF
  inside DATA is then a separate question - what to STORE - and BareNewlinePolicy
  answers it; it can never be a question of where the message ended.

  DELIVERY IS NOT HERE. The engine accepts or refuses; what happens to an
  accepted message is iSmtpServerPolicy.MessageComplete's business - an event, a
  spool file, an onward SMTP session. See StreamSec.Mail.SMTPSpool and
  StreamSec.Mail.SMTPServer.

Feature notes: Mail subsystem notes (SMTP / POP3 / IMAP)

Classes, interfaces and records

classeSmtpServerError

inherits from Exception

(no public members)

interfaceiSmtpEnvelope

WHAT THE SESSION AGREED, separate from the message it carried: the SMTP envelope is not the RFC 5322 header block and the two routinely disagree - that is what a Bcc IS. Delivery is decided by this, never by the To: line.

EVERY STRING HERE IS PEER-SUPPLIED except RemoteAddress, TransportInfo and SecureChannel, which the transport fills in. HeloName in particular is whatever the client typed and is verified against nothing.

function GetId: string; function GetHeloName: string; function GetMailFrom: string; function GetRecipientCount: Integer; function GetRecipient(aIndex: Integer): string; function GetAuthUser: string; function GetAuthenticated: Boolean; function GetRemoteAddress: string; function GetTransportInfo: string; function GetSecureChannel: Boolean; function GetDeclaredSize: Int64; function GetEightBitMime: Boolean; function GetSmtpUtf8: Boolean; function GetReceivedAt: TDateTime; property Id: string read GetId;
A queue identifier minted when the transaction begins. Unique within this process run; it is what the Received stamp carries and what the spool names its files after, so a message can be followed from a log line to the disk.
property HeloName: string read GetHeloName;
The argument of EHLO/HELO, unverified.
property MailFrom: string read GetMailFrom;
The reverse-path, bare (no angle brackets). EMPTY IS LEGAL AND MEANINGFUL: MAIL FROM:<> is the null sender that bounces and delivery notifications carry, and a relay that treats it as "no sender given" and refuses it creates mail loops.
property RecipientCount: Integer read GetRecipientCount; property Recipients[aIndex: Integer]: string read GetRecipient; property AuthUser: string read GetAuthUser;
The identity that authenticated, '' when none did.
property Authenticated: Boolean read GetAuthenticated; property RemoteAddress: string read GetRemoteAddress;
The peer, as the transport reports it.
property TransportInfo: string read GetTransportInfo;
Free text for the Received stamp's "with" clause, e.g. 'ESMTPS (TLS 1.3 with TLS_AES_128_GCM_SHA256)'.
property SecureChannel: Boolean read GetSecureChannel;
True when the channel was encrypted. Set by the transport, and what the AUTH gate tests - this engine neither advertises nor runs a password mechanism over a channel that says False, whatever else is configured.
property DeclaredSize: Int64 read GetDeclaredSize;
The SIZE parameter the client declared on MAIL FROM, 0 when it declared none. ADVISORY: it is checked before the transaction as a courtesy so a client learns early, and the real bound is enforced on the octets.
property EightBitMime: Boolean read GetEightBitMime;
BODY=8BITMIME was requested.
property SmtpUtf8: Boolean read GetSmtpUtf8;
SMTPUTF8 was requested (RFC 6531), so the paths above may be UTF-8.
property ReceivedAt: TDateTime read GetReceivedAt;
When the transaction began, UTC.

classtSmtpEnvelope

inherits from TInterfacedObject

implements iSmtpEnvelope

The implementation, and the spool's serialization format. The setters belong to the engine; a consumer holds the interface, which is read-only.

constructor Create; destructor Destroy; override; procedure ResetTransaction;
Clears the TRANSACTION - reverse path, forward paths, body parameters - and keeps what belongs to the SESSION: the greeting name, the authenticated identity, the peer. That is exactly what RSET does, and exactly what must survive it - except an identity that AuthForTransaction says was the transaction's own, which goes with it.
function AddRecipient(const aPath: string): Boolean;
False when the path was already listed, which is not an error - see the body for why a duplicate is dropped rather than refused.
procedure Assign(aSource: tSmtpEnvelope); procedure SaveToStream(aDest: TStream);
Line-oriented text, because the spool is a file an operator has to be able to read when something has gone wrong at three in the morning. Unknown keys are ignored on load, so a spool written by a later build still opens.
procedure LoadFromStream(aSource: TStream); property Id: string read fId write fId; property HeloName: string read fHeloName write fHeloName; property MailFrom: string read fMailFrom write fMailFrom; property MailFromSet: Boolean read fMailFromSet write fMailFromSet;
True once MAIL FROM has been accepted - which is NOT the same as MailFrom being non-empty, because <> is a legal reverse path.
property Recipients: TStringList read fRecipients; property RecipientCount: Integer read GetRecipientCount; property AuthUser: string read fAuthUser write fAuthUser; property Authenticated: Boolean read fAuthenticated write fAuthenticated; property AuthForTransaction: Boolean read fAuthForTransaction write fAuthForTransaction;
THE IDENTITY ABOVE BELONGS TO THIS TRANSACTION ALONE: a client certificate that names this reverse path, which says nothing about the next one. ResetTransaction - RSET, the end of a message, the next MAIL - withdraws Authenticated and AuthUser with it, and SMTP AUTH may then be used on the session. SMTP AUTH's own identity is the session's, and clears this.
property RemoteAddress: string read fRemoteAddress write fRemoteAddress; property TransportInfo: string read fTransportInfo write fTransportInfo; property SecureChannel: Boolean read fSecureChannel write fSecureChannel; property DeclaredSize: Int64 read fDeclaredSize write fDeclaredSize; property EightBitMime: Boolean read fEightBitMime write fEightBitMime; property SmtpUtf8: Boolean read fSmtpUtf8 write fSmtpUtf8; property ReceivedAt: TDateTime read fReceivedAt write fReceivedAt;

classtSmtpLimits

inherits from TPersistent

The bounds one session enforces, as a TPersistent so a component can publish it as a sub-object - the tCustomHTTPLimits pattern, and for the same reason: an operator who needs a 50 MiB message limit should not have to recompile. 0 MEANS UNBOUNDED on every one of them and is a decision to take deliberately; a negative normalises to 0 on the way in.

constructor Create(aOwner: TComponent); virtual; procedure AssignTo(Dest: TPersistent); override; property MessageBytes: Integer read fMessageBytes write SetMessageBytes default cSmtpDefaultMaxMessageBytes;
Largest message this server will take, in octets, counted on the DOT-UNSTUFFED body plus the Received stamp - i.e. on what is stored, which is what costs memory. Over it is 552. Also advertised as the SIZE parameter, where 0 correctly means "no fixed maximum" (RFC 1870).
property Recipients: Integer read fRecipients write SetRecipients default cSmtpDefaultMaxRecipients;
Forward paths per transaction; over it is 452, not 550 - RFC 5321 sec.4.5.3.1.10 is explicit that the recipient is fine and the server is merely full, so the client should retry it in another transaction.
property MessagesPerConnection: Integer read fMessagesPerConnection write SetMessagesPerConnection default cSmtpDefaultMaxMessagesPerConnection;
Messages one connection may deliver. The last is accepted normally and the connection then closes, so a client simply opens another - which makes it pay for TCP and TLS again.
property TextLineBytes: Integer read fTextLineBytes write SetTextLineBytes default cSmtpDefaultMaxTextLine;
Longest line accepted inside DATA. See cSmtpDefaultMaxTextLine for why this is far above the RFC's 1000.
property Errors: Integer read fErrors write SetErrors default cSmtpDefaultMaxErrors;
Protocol errors before the connection is dropped with 421.
property AuthFailures: Integer read fAuthFailures write SetAuthFailures default cSmtpDefaultMaxAuthFailures;
Failed authentications before the connection is dropped. Much smaller than Errors on purpose: this is the password-guessing bound.

classtSmtpSession

(no public members)

interfaceiSmtpServerPolicy

EVERY DECISION THE ENGINE DOES NOT MAKE ITSELF. The engine owns framing, sequencing and the bounds; who may send, who may be sent to, and what happens to an accepted message are the application's, and they arrive here.

aCode AND aText ARRIVE PRE-LOADED with the answer that applies if the implementor does nothing, so a policy that cares about one question can leave the rest alone. Returning False sends the refusal; returning True sends the success reply. Where the pre-loaded answer is a REFUSAL this is said on the method - CheckRecipient is the one that matters.

CALLED ON WHATEVER THREAD DROVE Receive. Under the async TLS server that is a reactor I/O thread with the connection's gate held, so an implementation must not block - see AsyncTLSServer.txt section 6.

function CheckConnection(const aSession: tSmtpSession; var aCode: Integer; var aText: string): Boolean;
THE CONNECTION ITSELF, asked before the banner is composed and before the peer has said a word. The envelope already carries RemoteAddress, TransportInfo and SecureChannel, so this is the earliest - and by a wide margin the cheapest - place to decide that a peer is not welcome: a refusal here cos... Full description »
function Greeting(const aSession: tSmtpSession): string;
The 220 banner text, without the code. '' takes the engine's default.
function CheckHelo(const aSession: tSmtpSession; const aName: string; var aCode: Integer; var aText: string): Boolean;
EHLO/HELO. Refusing here refuses the whole session.
function Authenticate(const aSession: tSmtpSession; const aUser: string; const aPassword: iSecretKey; var aAuthorizedAs: string; var aCode: Integer; var aText: string): Boolean;
The credential, in wiped storage. RUN ONLY OVER A SECURE CHANNEL - the engine refuses the mechanism outright otherwise, so an implementation never sees a password that crossed cleartext. Set aAuthorizedAs to the identity to record on the envelope; leaving it '' records aUser.
function CheckSender(const aSession: tSmtpSession; const aPath: string; var aCode: Integer; var aText: string): Boolean;
MAIL FROM. aPath is the bare reverse path and MAY be '' (the null sender).
function CheckRecipient(const aSession: tSmtpSession; const aPath: string; var aCode: Integer; var aText: string): Boolean;
RCPT TO - THE RELAY GATE. This is the call that decides whether the server is an open relay, so it arrives pre-loaded with a REFUSAL (550) and an implementation must say yes deliberately. Returning True without touching aCode sends 250 OK.
function MessageComplete(const aSession: tSmtpSession; const aEnvelope: iSmtpEnvelope; const aData: tBytes; var aCode: Integer; var aText: string): Boolean;
The message, dot-unstuffed, with the Received stamp already prepended. Returning True is a promise to the client that the message is accepted - so anything that has to be durable must be durable BEFORE this returns. Full description »
procedure SessionClosed(const aSession: tSmtpSession);
Told, not asked: this session object is going away.

classtSmtpSession

ONE CONNECTION'S SMTP CONVERSATION.

Drive it with Start (which queues the banner) and then Receive for every octet the peer sends. Replies leave through OnOutput, COALESCED: everything a single Receive produced is emitted in one call, so a pipelined batch of commands (RFC 2920) costs one write and one TLS record rather than one per reply.

NOT THREAD-SAFE, and does not need to be: it belongs to one connection, and the async TLS server serializes that connection's callbacks behind its per-connection gate.

constructor Create(const aPolicy: iSmtpServerPolicy; aLimits: tSmtpLimits = nil); destructor Destroy; override; procedure Start;
Queues the 220 banner. Call it once, after the transport facts below are set - the banner is the first thing the peer sees, and the policy that writes it may want to know who it is talking to.
procedure Receive(aData: Pointer; aLen: Integer);
Peer octets. Safe to call with the session already closing; the data is discarded.
procedure SecureChannelEstablished(const aTransportInfo: string);
THE TRANSPORT HAS COMPLETED THE STARTTLS HANDSHAKE. Call it once, and only after OnStartTLSRequested fired and the handshake actually succeeded; a failed handshake must close the connection instead (RFC 3207 sec.4 permits either, and closing removes any question about what state the session is in). Full description »
property Envelope: tSmtpEnvelope read fEnvelope;
The transaction in progress, live. A policy reads it during any of its own calls; it is not valid afterwards.
property State: tSmtpState read fState; property Limits: tSmtpLimits read fLimits; property PendingInputLen: Integer read fInLen;
Octets received but not yet consumed as a complete line. Exposed because it is the only way to prove from outside that the STARTTLS input discard actually happened - a smuggled command that is still buffered is a smuggled command that will run.
property MessagesServed: Integer read fMessagesServed;
Messages this connection has delivered so far.
property SecureChannel: Boolean read fSecureChannel write fSecureChannel;
Set these before Start. True when the channel is encrypted. THE AUTH GATE: with this False the engine neither advertises nor runs a password mechanism, whatever AuthMechanisms says - the TsmCustomSMTPClient posture, in the other direction.
property RemoteAddress: string read fRemoteAddress write fRemoteAddress; property TransportInfo: string read fTransportInfo write SetTransportInfo;
The "with" clause of the Received stamp. Set it before Start; it may also be set again later, when what is known about the session changes (AUTH succeeding turns ESMTPS into ESMTPSA), and the next stamp then says so.
property ServerName: string read fServerName write fServerName;
This server's own name, as it appears in the banner, the EHLO response and the Received stamp. Set it to the public FQDN.
property AuthMechanisms: tSmtpServerAuths read fAuthMechanisms write fAuthMechanisms;
Which SASL mechanisms are advertised and accepted. Empty means AUTH is not offered at all - and so does a cleartext channel, see SecureChannel.
property RequireAuth: Boolean read fRequireAuth write fRequireAuth;
Refuse MAIL FROM until the session has authenticated (530). The submission posture (RFC 6409). IT IS NOT THE RELAY GATE - that is iSmtpServerPolicy.CheckRecipient, which decides per recipient and refuses by default; this only shortens the conversation.
property BareNewlinePolicy: tSmtpBareNewlinePolicy read fBareNewlinePolicy write fBareNewlinePolicy; property OfferStartTLS: Boolean read fOfferStartTLS write fOfferStartTLS;
Advertise and honour STARTTLS (RFC 3207). It takes BOTH this and an assigned OnStartTLSRequested: a transport that cannot upgrade must never cause a 220 nobody can honour, so the advertisement and the command share one condition and a half-wired transport answers 502. Meaningless once SecureChannel is True, and suppressed there - RFC 3207 sec.4.2 forbids re-advertising it on an upgraded session.
property RequireSecureChannel: Boolean read fRequireSecureChannel write fRequireSecureChannel;
Refuse MAIL FROM until the channel is encrypted (530). The submission posture for port 587, and the RFC 3207 sec.4 refusal. Distinct from RequireAuth: this one says the TRANSPORT is wrong, which is a different thing from the credentials being wrong and deserves its own answer.
property OfferSmtpUtf8: Boolean read fOfferSmtpUtf8 write fOfferSmtpUtf8;
Advertise SMTPUTF8 (RFC 6531). Off by default: accepting UTF-8 paths commits every downstream hop to handling them.
property OnOutput: tSmtpOutputEvent read fOnOutput write fOnOutput; property OnException: tSmtpExceptionEvent read fOnException write fOnException; property OnStoreUnavailable: tSmtpStoreUnavailableEvent read fOnStoreUnavailable write fOnStoreUnavailable;
Queries this session's store; exception classes do not identify it.
property OnCloseRequested: TNotifyEvent read fOnCloseRequested write fOnCloseRequested;
Raised after the final reply has been flushed. The owner closes the transport; the engine has no way to.
property OnStartTLSRequested: TNotifyEvent read fOnStartTLSRequested write fOnStartTLSRequested;
Raised after the 220 has been flushed IN CLEARTEXT, which is the whole of RFC 3207 sec.2: the reply that promises the handshake is itself the last cleartext octets. Full description »

Types (enumerations, sets, aliases)

enumtSmtpState

Where the session is in RFC 5321 sec.4.1. smsGreeting is the state before Start has emitted the banner; smsClosing is set once a reply has been queued that ends the session, and every further octet from the peer is discarded (the close is asynchronous, so bytes already in flight arrive after it).
smsStartTLS is the window between the 220 that promises a handshake and the handshake itself. It exists to STOP the line loop dead: every octet the peer pipelined behind STARTTLS has already been destroyed by then, and no further command may be read from a buffer that is about to stop being cleartext. Appended rather than inserted so every existing ordinal stays put.

  tSmtpState = (smsGreeting, smsCommand, smsData,
                smsAuthUser, smsAuthPassword, smsAuthPlain, smsClosing,
                smsStartTLS);

enumtSmtpServerAuth

The SASL mechanisms this engine can run. Named ssa* rather than sam* because StreamSec.Mail.SMTPClient already has a tSMTPAuthMechanism whose members are sam*, and a relay unit uses BOTH - Delphi would resolve the duplicate to whichever unit came last in the uses clause, silently.

  tSmtpServerAuth  = (ssaPlain, ssaLogin);

settSmtpServerAuths

  tSmtpServerAuths = set of tSmtpServerAuth;

enumtSmtpBareNewlinePolicy

What to do about a bare CR or bare LF inside DATA. It is never a question of where the message ENDS - see the unit header - only of what is stored.
sbnReject answer 521 and drop the connection, which is what Postfix's smtpd_forbid_bare_newline does and the safe default: a peer sending bare newlines is either broken or probing, and passing the message on unchanged would hand the ambiguity to the next hop.
sbnNormalize store it as CRLF and carry on. Accepts mail from sloppy clients at the cost of rewriting their octets - which breaks any signature computed over the original (DKIM, S/MIME), and can turn an embedded <LF>.<LF> into a stored line holding a single dot. That is safe HERE because everything this library re-transmits is dot-stuffed on the way out (TsmCustomSMTPClient), and it is exactly what would not be safe in a pipeline that re-emits the octets raw.

  tSmtpBareNewlinePolicy = (sbnReject, sbnNormalize);

proctSmtpOutputEvent

Reply octets. No Sender, because this is an engine rather than a component - the same shape as tHttp2OutputEvent.

  tSmtpOutputEvent = procedure (aData: Pointer; aLen: Integer) of object;

proctSmtpExceptionEvent

  tSmtpExceptionEvent = procedure(aException: Exception) of object;

proctSmtpStoreUnavailableEvent

  tSmtpStoreUnavailableEvent = function: Boolean of object;

Routines