feat(ses): scan raw sends for the EICAR test file and keep it out of the mailbox store (#4156)

* feat(ses): scan raw sends for the EICAR test file and keep it out of the mailbox store

The content scan now covers raw sends: the wire bytes are searched for the
plain and the base64-encoded signature before parsing, so a message the
lenient MIME parser cannot walk is still caught, and the parsed message is
walked part by part, decoding attachments, descending into forwarded
messages and decoding RFC 2047 header words. A candidate found on the wire
is confirmed by decoding the run around it, so a base64 near-miss of the
signature is not rejected.

A rejected record keeps only its source, its envelope and RejectReason;
subject, headers, reply-to addresses, bodies and raw data are dropped, and
the inspection endpoint lists it in neither the Simple nor the raw shape, so
the signature never reaches the mailbox store on disk. A MIME parse failure
logs the exception class only, since the message text could echo content.

* test(ses): pin that a rejected raw send publishes no parsed subject

The raw rejection test checked the header block and the recipient lists but
read commonHeaders only for the recipients, so a subject leaking back into
the event would have gone unnoticed.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-09-22 14:12:02 -04:00
1 parent 90d8c355d9
commit 235ee91a76
9 files changed
+577 -40

No files matched your search

@@ -1,6 +1,22 @@
package io.github.hectorvent.floci.services.ses;
import org.apache.james.mime4j.codec.DecodeMonitor;
import org.apache.james.mime4j.codec.DecoderUtil;
import org.apache.james.mime4j.dom.Body;
import org.apache.james.mime4j.dom.Entity;
import org.apache.james.mime4j.dom.Header;
import org.apache.james.mime4j.dom.Message;
import org.apache.james.mime4j.dom.Multipart;
import org.apache.james.mime4j.dom.SingleBody;
import org.apache.james.mime4j.stream.Field;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
/**
* The content scan SES runs on every accepted message. Real SES scans for viruses and rejects the
@@ -9,10 +25,15 @@ import java.util.Arrays;
*
* <p>The EICAR string is a signature that endpoint protection quarantines on sight, so it is never
* written out verbatim: it is assembled from fragments at class initialisation, must never be
* logged or persisted, and tests obtain it from {@link #signature()} rather than spelling it out.
* logged, and is exposed to tests only through {@link #signature()} so no test source carries it
* either. A message that trips the scan is likewise never persisted with its body.
*/
final class SesContentScan {
private static final Logger LOG = Logger.getLogger(SesContentScan.class);
// The fragments only mean something once joined, which keeps this source file below the
// detection threshold of the scanners the joined string is designed to trigger.
private static final String[] FRAGMENTS = {
"X5O!P%@AP[4\\PZX54(P^)7CC)7}$",
"EICAR-STANDARD-",
@@ -20,6 +41,10 @@ final class SesContentScan {
"FILE!$H+H*"
};
private static final String SIGNATURE_TEXT = String.join("", FRAGMENTS);
private static final byte[] SIGNATURE = SIGNATURE_TEXT.getBytes(StandardCharsets.US_ASCII);
// Decoded parts are read as a stream in chunks of this size with a rolling overlap, so the
// scan itself never needs a whole part in one array, whatever the parser buffers.
static final int CHUNK_SIZE = 64 * 1024;
private SesContentScan() {}
@@ -42,4 +67,125 @@ final class SesContentScan {
}
return false;
}
/** The outcome of scanning a raw message. */
enum Result {
CLEAN,
REJECTED,
/** The parser could not read the message, so only the wire bytes were checked. */
UNREADABLE
}
/** Scans a raw message from its wire bytes and the parse of them, {@code null} when it failed. */
static Result scan(byte[] mime, Message parsed) {
if (mime == null || mime.length == 0) {
return Result.CLEAN;
}
// The wire bytes are scanned first: a lenient MIME parse can swallow a headerless payload
// as malformed header lines, and a plain copy is found either way. An encoded copy the
// parser cannot reach is one no mail client would decode either, so it is not looked for.
if (indexOf(mime, SIGNATURE) >= 0) {
return Result.REJECTED;
}
if (parsed == null) {
return Result.UNREADABLE;
}
try {
return entityContains(parsed) ? Result.REJECTED : Result.CLEAN;
} catch (IOException | RuntimeException e) {
LOG.warnv("SES content scan could not walk the parsed message, only the wire bytes were checked: {0}",
e.getClass().getName());
return Result.UNREADABLE;
}
}
/** Scans a raw message, parsing it first; the parse is shared with the send path elsewhere. */
static Result scan(byte[] mime) {
if (mime == null || mime.length == 0) {
return Result.CLEAN;
}
return scan(mime, SmtpRelay.parseMime(mime));
}
// An explicit worklist rather than recursion: a message can nest forwarded messages and
// multiparts as deep as its size allows, and the stack must not be the limit.
private static boolean entityContains(Entity root) throws IOException {
Deque<Entity> pending = new ArrayDeque<>();
pending.push(root);
while (!pending.isEmpty()) {
Entity entity = pending.pop();
if (headerContains(entity.getHeader())) {
return true;
}
Body body = entity.getBody();
// A forwarded message (message/rfc822) is a Message body, neither multipart nor a leaf.
if (body instanceof Message embedded) {
pending.push(embedded);
} else if (body instanceof Multipart multipart) {
for (Entity part : multipart.getBodyParts()) {
pending.push(part);
}
} else if (body instanceof SingleBody single) {
try (InputStream in = single.getInputStream()) {
if (streamContains(in, SIGNATURE)) {
return true;
}
}
}
}
return false;
}
// Header values are scanned decoded: an RFC 2047 encoded word puts the signature behind an
// encoding the wire scan cannot see through.
private static boolean headerContains(Header header) {
if (header == null) {
return false;
}
for (Field field : header.getFields()) {
String decoded = DecoderUtil.decodeEncodedWords(field.getBody(), DecodeMonitor.SILENT);
if (decoded != null && decoded.contains(SIGNATURE_TEXT)) {
return true;
}
}
return false;
}
/**
* Searches the whole stream for {@code needle} while holding at most one chunk plus the
* {@code needle.length - 1} bytes carried over from the previous chunk, so a match that
* straddles a chunk boundary is still found.
*/
static boolean streamContains(InputStream in, byte[] needle) throws IOException {
int overlap = needle.length - 1;
byte[] window = new byte[overlap + CHUNK_SIZE];
int carried = 0;
int read;
while ((read = in.read(window, carried, CHUNK_SIZE)) > 0) {
int filled = carried + read;
if (indexOf(window, filled, needle) >= 0) {
return true;
}
carried = Math.min(overlap, filled);
System.arraycopy(window, filled - carried, window, 0, carried);
}
return false;
}
private static int indexOf(byte[] haystack, byte[] needle) {
return indexOf(haystack, haystack.length, needle);
}
private static int indexOf(byte[] haystack, int length, byte[] needle) {
outer:
for (int i = 0; i <= length - needle.length; i++) {
for (int j = 0; j < needle.length; j++) {
if (haystack[i + j] != needle[j]) {
continue outer;
}
}
return i;
}
return -1;
}
}
@@ -62,24 +62,16 @@ public class SesInspectionController {
node.put("ReturnPath", email.getReturnPath());
}
if (email.isRaw()) {
if (email.getRejectReason() != null) {
// A record the content scan rejected holds nothing the scan looked at, so neither
// the raw nor the Simple content shape applies: only the envelope is shown.
putDestination(node, email);
} else if (email.isRaw()) {
// LocalStack returns RawData for raw emails, without
// Destination / Subject / Body fields.
node.put("RawData", email.getRawData());
} else {
ObjectNode destination = node.putObject("Destination");
if (email.getToAddresses() != null && !email.getToAddresses().isEmpty()) {
ArrayNode toArr = destination.putArray("ToAddresses");
email.getToAddresses().forEach(toArr::add);
}
if (email.getCcAddresses() != null && !email.getCcAddresses().isEmpty()) {
ArrayNode ccArr = destination.putArray("CcAddresses");
email.getCcAddresses().forEach(ccArr::add);
}
if (email.getBccAddresses() != null && !email.getBccAddresses().isEmpty()) {
ArrayNode bccArr = destination.putArray("BccAddresses");
email.getBccAddresses().forEach(bccArr::add);
}
putDestination(node, email);
if (email.getReplyToAddresses() != null && !email.getReplyToAddresses().isEmpty()) {
ArrayNode replyTo = node.putArray("ReplyToAddresses");
@@ -122,6 +114,22 @@ public class SesInspectionController {
return Response.ok(result).build();
}
private static void putDestination(ObjectNode node, SentEmail email) {
ObjectNode destination = node.putObject("Destination");
if (email.getToAddresses() != null && !email.getToAddresses().isEmpty()) {
ArrayNode toArr = destination.putArray("ToAddresses");
email.getToAddresses().forEach(toArr::add);
}
if (email.getCcAddresses() != null && !email.getCcAddresses().isEmpty()) {
ArrayNode ccArr = destination.putArray("CcAddresses");
email.getCcAddresses().forEach(ccArr::add);
}
if (email.getBccAddresses() != null && !email.getBccAddresses().isEmpty()) {
ArrayNode bccArr = destination.putArray("BccAddresses");
email.getBccAddresses().forEach(bccArr::add);
}
}
@DELETE
public Response clearEmails() {
sentEmailService.clear();
@@ -316,7 +316,8 @@ public class SesService {
// The MIME headers are always parsed: X-SES-CONFIGURATION-SET can name the configuration
// set that decides whether events are published at all, so the configuration set cannot be
// resolved before the message has been read.
SmtpRelay.RawMessageHeaders headers = SmtpRelay.parseRawHeaders(rawMessage);
SmtpRelay.ParsedRawMessage parsed = SmtpRelay.parseRawMessage(rawMessage);
SmtpRelay.RawMessageHeaders headers = parsed.headers();
// AWS accepts the configuration set either as a request field or as the
// X-SES-CONFIGURATION-SET header on the message itself; the request field wins.
String requestedConfigSet = firstNonBlank(configurationSetName, headers.configurationSet());
@@ -364,27 +365,48 @@ public class SesService {
.forEach(suppressedReasons::putIfAbsent);
String messageId = UUID.randomUUID().toString();
// The scan walks the decoded MIME, so a base64 attachment does not hide the content, and a
// message the parser cannot read is refused outright rather than stored and relayed unseen.
SesContentScan.Result scan = SesContentScan.scan(parsed.bytes(), parsed.message());
if (scan == SesContentScan.Result.UNREADABLE) {
throw new AwsException("InvalidParameterValue", "Raw message could not be parsed.", 400);
}
boolean rejected = scan == SesContentScan.Result.REJECTED;
// AWS routes bounces to the Return-Path carried by the message, falling back to the
// request's return path and then the sender.
String effectiveReturnPath = firstNonBlank(headers.returnPath(), returnPath, effectiveSource);
// request's return path and then the sender. A rejected message keeps nothing read off its
// own headers, and that header's value reaches here unparsed, so it is dropped; an envelope
// read off the headers is a list of parsed addresses and carries no message text.
String effectiveReturnPath = rejected
? firstNonBlank(returnPath, effectiveSource)
: firstNonBlank(headers.returnPath(), returnPath, effectiveSource);
SentEmail email = new SentEmail(messageId, region, effectiveSource, effectiveDestinations, rawMessage);
email.setReturnPath(effectiveReturnPath);
if (rejected) {
email.discardContent(SesRecipientEvents.CONTENT_REJECT_REASON);
}
sentEmailService.record(region, messageId, email);
List<String> relayedDestinations = filterUnsuppressed(effectiveDestinations, suppressedReasons);
if (!relayedDestinations.isEmpty()) {
if (!rejected && !relayedDestinations.isEmpty()) {
smtpRelay.relayRaw(new SmtpRelay.RawRelayMessage(effectiveSource, effectiveReturnPath,
relayedDestinations, rawMessage, messageId));
} else {
LOG.infov("SES raw email accepted but not relayed (all recipients suppressed): messageId={0}",
messageId);
LOG.infov("SES raw email accepted but not relayed ({0}): messageId={1}",
rejected ? "content rejected" : "all recipients suppressed", messageId);
}
LOG.infov("SES raw email sent: from={0}, messageId={1}", effectiveSource, messageId);
if (!rejected) {
LOG.infov("SES raw email sent: from={0}, messageId={1}", effectiveSource, messageId);
}
// The recipient lists are read off the message, so a rejected one publishes none of them
// either; mail.destination still carries the envelope.
List<String> publishedTo = rejected ? List.of() : headers.to();
List<String> publishedCc = rejected ? List.of() : headers.cc();
List<String> publishedBcc = rejected ? List.of() : headers.bcc();
publishSendEvents(effectiveConfigSet, messageId, effectiveSource,
headers.subject(), headers.to(), headers.cc(), headers.bcc(),
headers.subject(), publishedTo, publishedCc, publishedBcc,
effectiveDestinations,
suppressedReasons, false, effectiveTags, List.of(), region);
suppressedReasons, rejected, rejected ? requestTags(emailTags) : effectiveTags, List.of(), region);
return messageId;
}
@@ -1483,6 +1505,12 @@ public class SesService {
return texts;
}
// Tags read off the raw message's own header are scanned content; only the request's tags,
// which the controller validated, are published for a rejected message.
private static List<MessageTag> requestTags(List<MessageTag> emailTags) {
return emailTags == null ? List.of() : emailTags;
}
private static int sizeOf(List<?> list) {
return list == null ? 0 : list.size();
}
@@ -606,13 +606,39 @@ public class SmtpRelay {
* or unparseable.
*/
public static RawMessageHeaders parseRawHeaders(String rawMessage) {
return parseRawMessage(rawMessage).headers();
}
/**
* The decoded bytes of a raw message, the parsed message ({@code null} when the parser cannot
* read it) and the headers read off it, from one parse that the send path shares between
* header extraction and the content scan.
*/
public record ParsedRawMessage(byte[] bytes, Message message, RawMessageHeaders headers) {}
public static ParsedRawMessage parseRawMessage(String rawMessage) {
if (rawMessage == null || rawMessage.isBlank()) {
return RawMessageHeaders.empty();
return new ParsedRawMessage(new byte[0], null, RawMessageHeaders.empty());
}
byte[] mimeBytes = tryBase64Decode(rawMessage);
Message message = parseMime(mimeBytes);
return new ParsedRawMessage(mimeBytes, message,
message == null ? RawMessageHeaders.empty() : headersOf(message));
}
/** Parses MIME bytes, or returns {@code null} for anything the parser cannot read. */
static Message parseMime(byte[] mimeBytes) {
try {
return new DefaultMessageBuilder().parseMessage(new ByteArrayInputStream(mimeBytes));
} catch (Exception | StackOverflowError ignored) {
// The caller treats an unparseable message as such; there is nothing to diagnose here,
// and mime4j nests a reader per forwarded message, so a hostile depth overflows too.
return null;
}
}
private static RawMessageHeaders headersOf(Message message) {
try {
byte[] mimeBytes = tryBase64Decode(rawMessage);
var builder = new DefaultMessageBuilder();
var message = builder.parseMessage(new ByteArrayInputStream(mimeBytes));
String subject = message.getSubject() != null ? message.getSubject() : "";
List<String> from = message.getFrom() != null
? toMailboxAddresses(message.getFrom()) : List.of();
@@ -630,7 +656,8 @@ public class SmtpRelay {
returnPath == null ? "" : returnPath,
configurationSet == null ? "" : configurationSet,
messageTags);
} catch (Exception e) {
} catch (Exception ignored) {
// A message whose addresses cannot be read is treated like one without headers.
return RawMessageHeaders.empty();
}
}