Files
BARANTMail/SMTPSyntax.cpp
T
barantandClaude Opus 5.5 d3d7e5f3e5 SMTP: STARTTLS, smuggling fix, and RFC 5321 conformance
Security:
- SMTP smuggling (CVE-2023-51764 family): only <CRLF>.<CRLF> ends DATA
  (strict CRLF framing); bare CR/LF in the text is stored as CR LF.
  Before, '<LF>.<LF>' and four other variants ended the message and the
  rest ran as fresh commands - a second, forged message was delivered.
- STARTTLS on port 25 (RFC 3207), using the configured tls cert; AUTH
  is only offered/accepted once encrypted (538 5.7.11 otherwise).
- The 250 reply no longer discloses the queue file's full path.
- Queue file names %-encode the addresses ('/' or '|' in an address
  broke the name or pointed it into another directory).

Conformance (RFC 5321, 1870, 2034, 2920, 3207, 3463, 3848, 4616, 4954,
6152):
- 500 for unknown/empty/over-long commands (no reply at all before -
  clients hung); 501 for missing/invalid arguments (bare MAIL/RCPT/HELO
  were out-of-bounds reads).
- HELO/EHLO required before MAIL; nested MAIL refused; EHLO/HELO/RSET/
  end-of-DATA reset the transaction.
- MAIL: SIZE= (552 when over the limit), BODY=7BIT|8BITMIME, AUTH=;
  555 for anything else; case-insensitive keywords; address syntax
  checked.
- RCPT: postmaster (bare and any case) accepted; case-insensitive
  domain and local-part; 550 5.1.1 unknown user vs 550 5.7.1 relay
  denied; aliases accepted (they were rejected at RCPT before); 1000
  recipient cap (452 4.5.3).
- ENHANCEDSTATUSCODES advertised and used on every reply.
- AUTH PLAIN added alongside LOGIN; strict base64; 535 5.7.8 on
  failure; 503 before EHLO, during a transaction, or when already
  authenticated (the last one sent no reply before).
- Received: per RFC 5321 4.4 with client IP, protocol per RFC 3848
  (ESMTP/ESMTPS/ESMTPSA) and queue id; Return-Path: added at local
  delivery.

tests/smtp_conformance.py: 112 checks. origin/master passes 37 of the
72 it can reach before the server stops answering; this passes 112/112.
tests/imap_pop3_regression.py: IMAPS/POP3S unaffected (3/3).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0121tAhQVe4qbCwYgVjKQS4B
2026-11-02 11:56:41 -08:00

288 lines
10 KiB
C++

#include "SMTPSyntax.h"
#include <cctype>
namespace mail {
namespace SMTPSyntax {
bool iequals(const std::string &a, const std::string &b) {
if (a.size() != b.size())
return false;
for (size_t i = 0; i < a.size(); ++i)
if (std::tolower((unsigned char)a[i]) != std::tolower((unsigned char)b[i]))
return false;
return true;
}
std::string upper(std::string s) {
for (char &c : s) c = std::toupper((unsigned char)c);
return s;
}
std::string lower(std::string s) {
for (char &c : s) c = std::tolower((unsigned char)c);
return s;
}
std::string argument(const std::string &line) {
size_t sp = line.find(' ');
if (sp == std::string::npos)
return "";
size_t start = line.find_first_not_of(' ', sp);
if (start == std::string::npos)
return "";
size_t end = line.find_last_not_of(' ');
return line.substr(start, end - start + 1);
}
// RFC 5322 3.2.3 atext
static bool atext(unsigned char c) {
return std::isalnum(c) || (c && std::string("!#$%&'*+-/=?^_`{|}~").find(c) != std::string::npos);
}
static bool validDotString(const std::string &s) {
if (s.empty() || s.front() == '.' || s.back() == '.')
return false;
for (size_t i = 0; i < s.size(); ++i) {
unsigned char c = s[i];
if (c == '.') {
if (s[i + 1] == '.')
return false;
} else if (!atext(c) && c < 0x80) {
return false;
}
// c >= 0x80: tolerated (UTF-8 local-parts, RFC 6531 style);
// the server doesn't advertise SMTPUTF8 but rejecting them
// outright helps nobody.
}
return true;
}
static bool validQuotedString(const std::string &s) {
if (s.size() < 2 || s.front() != '"' || s.back() != '"')
return false;
for (size_t i = 1; i + 1 < s.size(); ++i) {
unsigned char c = s[i];
if (c == '\\') {
if (i + 2 >= s.size())
return false;
unsigned char n = s[++i];
if (n < 32 || n > 126)
return false;
} else if (c == '"' || c < 32 || c == 127) {
return false;
}
}
return true;
}
static bool validDomain(const std::string &d) {
if (d.empty() || d.size() > 255)
return false;
if (d.front() == '[')
return d.back() == ']' && d.size() > 2 &&
d.find_first_of("[]\\", 1) == d.size() - 1; // address-literal; content not interpreted
size_t start = 0;
while (true) {
size_t dot = d.find('.', start);
std::string label = d.substr(start, dot == std::string::npos ? std::string::npos : dot - start);
if (label.empty() || label.size() > 63 || label.front() == '-' || label.back() == '-')
return false;
for (unsigned char c : label)
if (!std::isalnum(c) && c != '-' && c < 0x80)
return false;
if (dot == std::string::npos)
return true;
start = dot + 1;
}
}
void splitAddress(const std::string &address, std::string &local, std::string &domain) {
size_t at = address.rfind('@');
if (at == std::string::npos) {
local = address;
domain = "";
} else {
local = address.substr(0, at);
domain = lower(address.substr(at + 1));
}
}
bool validMailbox(const std::string &address) {
std::string local, domain;
splitAddress(address, local, domain);
if (address.find('@') == std::string::npos || local.empty() || local.size() > 64)
return false;
if (!(local.front() == '"' ? validQuotedString(local) : validDotString(local)))
return false;
return validDomain(domain);
}
bool safePathComponent(const std::string &s) {
return !s.empty() && s != "." && s != ".." && s.front() != '.' &&
s.find('/') == std::string::npos && s.find('\0') == std::string::npos;
}
PathArgument parsePath(const std::string &arg, const std::string &keyword, bool allowEmpty) {
PathArgument result;
std::string usage = keyword == "FROM:" ? "501 5.5.4 Syntax: MAIL FROM:<address> [parameters]"
: "501 5.5.4 Syntax: RCPT TO:<address> [parameters]";
if (arg.size() < keyword.size() || !iequals(arg.substr(0, keyword.size()), keyword)) {
result.reply = usage;
return result;
}
size_t pos = keyword.size();
if (pos < arg.size() && arg[pos] == ' ')
++pos;
if (pos >= arg.size() || arg[pos] != '<') {
result.reply = usage;
return result;
}
// Find the closing '>' - not inside a quoted local-part.
size_t i = pos + 1;
bool quoted = false;
for (; i < arg.size(); ++i) {
char c = arg[i];
if (quoted && c == '\\') { ++i; continue; }
if (c == '"') quoted = !quoted;
else if (c == '>' && !quoted) break;
}
if (i >= arg.size()) {
result.reply = usage;
return result;
}
std::string path = arg.substr(pos + 1, i - pos - 1);
// RFC 5321 4.1.2 / 3.3: a source route ("@a,@b:user@c") MUST be
// accepted and SHOULD be ignored.
if (!path.empty() && path.front() == '@') {
size_t colon = path.find(':');
if (colon == std::string::npos) {
result.reply = usage;
return result;
}
path = path.substr(colon + 1);
}
if (path.size() > 254) {
result.reply = "501 5.1.3 Path too long";
return result;
}
if (path.empty()) {
if (!allowEmpty) {
result.reply = "501 5.1.3 Empty forward-path";
return result;
}
} else if (!(keyword == "TO:" && iequals(path, "postmaster")) && !validMailbox(path)) {
result.reply = keyword == "FROM:" ? "501 5.1.7 Bad sender address syntax"
: "501 5.1.3 Bad recipient address syntax";
return result;
}
result.address = path;
// esmtp-param *(SP esmtp-param); esmtp-param = esmtp-keyword ["=" esmtp-value]
size_t p = i + 1;
while (p < arg.size()) {
if (arg[p] != ' ') {
result.reply = usage;
return result;
}
while (p < arg.size() && arg[p] == ' ')
++p;
if (p >= arg.size())
break;
size_t end = arg.find(' ', p);
std::string param = arg.substr(p, end == std::string::npos ? std::string::npos : end - p);
p = end == std::string::npos ? arg.size() : end;
size_t eq = param.find('=');
std::string key = param.substr(0, eq), value = eq == std::string::npos ? "" : param.substr(eq + 1);
bool keyOk = !key.empty() && std::isalnum((unsigned char)key[0]);
for (unsigned char c : key)
if (!std::isalnum(c) && c != '-')
keyOk = false;
bool valueOk = eq == std::string::npos || !value.empty();
for (unsigned char c : value)
if (c < 33 || c > 126 || c == '=')
valueOk = false;
if (!keyOk || !valueOk) {
result.reply = "501 5.5.4 Malformed parameter";
return result;
}
std::string K = upper(key);
for (auto &existing : result.params)
if (existing.first == K) {
result.reply = "501 5.5.4 Duplicate parameter " + K;
return result;
}
result.params.push_back({K, value});
}
result.ok = true;
return result;
}
bool decodeBase64(const std::string &in, std::string &out) {
out.clear();
if (in.size() % 4 != 0)
return false;
auto val = [](char c) -> int {
if (c >= 'A' && c <= 'Z') return c - 'A';
if (c >= 'a' && c <= 'z') return c - 'a' + 26;
if (c >= '0' && c <= '9') return c - '0' + 52;
if (c == '+') return 62;
if (c == '/') return 63;
return -1;
};
for (size_t i = 0; i < in.size(); i += 4) {
int v[4];
int pad = 0;
for (int k = 0; k < 4; ++k) {
char c = in[i + k];
if (c == '=') {
// only in the last group, only in the last two places, only trailing
if (i + 4 != in.size() || k < 2)
return false;
v[k] = 0;
++pad;
} else {
if (pad)
return false;
v[k] = val(c);
if (v[k] < 0)
return false;
}
}
unsigned int n = (v[0] << 18) | (v[1] << 12) | (v[2] << 6) | v[3];
out += (char)((n >> 16) & 0xff);
if (pad < 2) out += (char)((n >> 8) & 0xff);
if (pad < 1) out += (char)(n & 0xff);
}
return true;
}
std::string encodeQueueField(const std::string &s) {
std::string out;
for (char c : s) {
if (c == '%') out += "%25";
else if (c == '/') out += "%2F";
else if (c == '|') out += "%7C";
else out += c;
}
return out;
}
std::string decodeQueueField(const std::string &s) {
std::string out;
for (size_t i = 0; i < s.size(); ++i) {
if (s[i] == '%' && i + 2 < s.size()) {
std::string h = upper(s.substr(i + 1, 2));
if (h == "25") { out += '%'; i += 2; continue; }
if (h == "2F") { out += '/'; i += 2; continue; }
if (h == "7C") { out += '|'; i += 2; continue; }
}
out += s[i];
}
return out;
}
}
}