Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Improve EML to PDF robustness with large and unusual inputs (#8683)

EthanHealy01623d079d0308
diff --git a/app/common/src/main/java/stirling/software/common/util/EmlParser.java b/app/common/src/main/java/stirling/software/common/util/EmlParser.java
index 09d55a02c2..556767fa60 100644
--- a/app/common/src/main/java/stirling/software/common/util/EmlParser.java
+++ b/app/common/src/main/java/stirling/software/common/util/EmlParser.java
@@ -13,6 +13,10 @@ import java.util.Locale;
import java.util.Objects;
import java.util.stream.Collectors;
+import org.apache.poi.poifs.filesystem.DirectoryEntry;
+import org.apache.poi.poifs.filesystem.DocumentEntry;
+import org.apache.poi.poifs.filesystem.Entry;
+import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.simplejavamail.api.email.AttachmentResource;
import org.simplejavamail.api.email.Email;
import org.simplejavamail.api.email.Recipient;
@@ -34,6 +38,11 @@ public class EmlParser {
// Configuration constants
private final int DEFAULT_MAX_ATTACHMENT_MB = 10;
private final long MAX_SIZE_ESTIMATION_BYTES = 500L * 1024 * 1024; // 500MB
+ private final int MAX_ATTACHMENTS = ZipBombGuard.MAX_ENTRIES;
+ final int MAX_FILENAME_LENGTH = 255;
+ private final int MAX_EXTENSION_LENGTH = 16; // including the dot
+ private final int MAX_MSG_PROPERTY_STREAM_BYTES = 64 * 1024;
+ private final String MSG_PROPERTY_STREAM_PREFIX = "__properties_version1.0";
// Message constants
private final String NO_CONTENT_MESSAGE = "Email content could not be parsed";
@@ -55,6 +64,7 @@ public class EmlParser {
Email email;
if (isMsgFile) {
try {
+ validateMsgStreamSizes(emlBytes);
email = EmailConverter.outlookMsgToEmail(input);
} catch (Exception e) {
// OLE2 magic bytes match but parsing failed - might be DOC/XLS/other OLE2 file
@@ -79,6 +89,39 @@ public class EmlParser {
}
}
+ /**
+ * Rejects a compound file whose directory declares more stream data than the file holds, or
+ * whose property streams are larger than a message needs. The MSG parser reads both in full, so
+ * the check runs first.
+ */
+ private void validateMsgStreamSizes(byte[] msgBytes) throws IOException {
+ try (POIFSFileSystem fileSystem = new POIFSFileSystem(new ByteArrayInputStream(msgBytes))) {
+ if (sumStreamSizes(fileSystem.getRoot()) > msgBytes.length) {
+ throw new IOException("MSG streams add up to more data than the file contains");
+ }
+ }
+ }
+
+ private long sumStreamSizes(DirectoryEntry directory) throws IOException {
+ long total = 0;
+ for (Entry entry : directory) {
+ if (entry instanceof DirectoryEntry child) {
+ total += sumStreamSizes(child);
+ } else if (entry instanceof DocumentEntry stream) {
+ int size = stream.getSize();
+ if (size < 0) {
+ throw new IOException("MSG stream has a negative size");
+ }
+ if (size > MAX_MSG_PROPERTY_STREAM_BYTES
+ && stream.getName().startsWith(MSG_PROPERTY_STREAM_PREFIX)) {
+ throw new IOException("MSG property stream is too large");
+ }
+ total += size;
+ }
+ }
+ return total;
+ }
+
private EmailContent buildEmailContent(
Email email, EmlToPdfRequest request, CustomHtmlSanitizer customHtmlSanitizer)
throws IOException {
@@ -112,6 +155,20 @@ public class EmlParser {
content.setTextBody(NO_CONTENT_MESSAGE);
}
+ // Embedding is capped like the archive readers; listing alone is not. Counted before
+ // mapping so a rejected message reads nothing.
+ if (request != null && request.isIncludeAttachments()) {
+ int resourceCount =
+ countResources(email.getEmbeddedImages())
+ + countResources(email.getAttachments());
+ if (resourceCount > MAX_ATTACHMENTS) {
+ throw new IOException(
+ "Email contains more than the maximum allowed "
+ + MAX_ATTACHMENTS
+ + " attachments");
+ }
+ }
+
List<EmailAttachment> attachments = new ArrayList<>();
attachments.addAll(mapResources(email.getEmbeddedImages(), request, true));
attachments.addAll(mapResources(email.getAttachments(), request, false));
@@ -121,6 +178,19 @@ public class EmlParser {
return content;
}
+ private int countResources(List<AttachmentResource> resources) {
+ if (resources == null) {
+ return 0;
+ }
+ int count = 0;
+ for (AttachmentResource resource : resources) {
+ if (resource != null) {
+ count++;
+ }
+ }
+ return count;
+ }
+
private List<EmailAttachment> mapResources(
List<AttachmentResource> resources, EmlToPdfRequest request, boolean embedded)
throws IOException {
@@ -456,5 +526,30 @@ public class EmlParser {
this.sizeBytes = data.length;
}
}
+
+ /**
+ * Names over {@code MAX_FILENAME_LENGTH} UTF-16 units are shortened, keeping an extension
+ * of up to {@code MAX_EXTENSION_LENGTH} characters and never splitting a surrogate pair, so
+ * every consumer sees the same bounded name.
+ */
+ public void setFilename(String filename) {
+ this.filename = limitFilenameLength(filename);
+ }
+ }
+
+ static String limitFilenameLength(String filename) {
+ if (filename == null || filename.length() <= MAX_FILENAME_LENGTH) {
+ return filename;
+ }
+ String extension = "";
+ int lastDot = filename.lastIndexOf('.');
+ if (lastDot > 0 && filename.length() - lastDot <= MAX_EXTENSION_LENGTH) {
+ extension = filename.substring(lastDot);
+ }
+ int keep = MAX_FILENAME_LENGTH - extension.length();
+ if (Character.isHighSurrogate(filename.charAt(keep - 1))) {
+ keep--;
+ }
+ return filename.substring(0, keep) + extension;
}
}
diff --git a/app/common/src/main/java/stirling/software/common/util/PdfAttachmentHandler.java b/app/common/src/main/java/stirling/software/common/util/PdfAttachmentHandler.java
index f2c902211e..846ed5d0d6 100644
--- a/app/common/src/main/java/stirling/software/common/util/PdfAttachmentHandler.java
+++ b/app/common/src/main/java/stirling/software/common/util/PdfAttachmentHandler.java
@@ -16,6 +16,8 @@ import java.util.Base64;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -156,7 +158,8 @@ public class PdfAttachmentHandler {
};
}
- private static String ensureUniqueFilename(String filename, Set<String> existingNames) {
+ private static String ensureUniqueFilename(
+ String filename, Set<String> existingNames, Map<String, Integer> nextCounters) {
if (!existingNames.contains(filename)) {
return filename;
}
@@ -171,16 +174,31 @@ public class PdfAttachmentHandler {
baseName = filename;
}
- int counter = 1;
+ // Resume after the last suffix handed out for this name; lower ones are taken
+ int counter = nextCounters.getOrDefault(filename, 1);
String uniqueName;
do {
- uniqueName = baseName + "_" + counter + extension;
+ String suffix = "_" + counter + extension;
+ uniqueName = fitWithSuffix(baseName, suffix);
counter++;
} while (existingNames.contains(uniqueName));
+ nextCounters.put(filename, counter);
return uniqueName;
}
+ /** Shortens the base so the suffixed name fits the attachment name limit. */
+ private static String fitWithSuffix(String baseName, String suffix) {
+ int keep = EmlParser.MAX_FILENAME_LENGTH - suffix.length();
+ if (baseName.length() <= keep || keep < 1) {
+ return baseName + suffix;
+ }
+ if (Character.isHighSurrogate(baseName.charAt(keep - 1))) {
+ keep--;
+ }
+ return baseName.substring(0, keep) + suffix;
+ }
+
private static @NotNull PDRectangle calculateAnnotationRectangle(
PDPage page, float x, float y) {
PDRectangle cropBox = page.getCropBox();
@@ -362,6 +380,7 @@ public class PdfAttachmentHandler {
}
Map<Integer, String> indexToFilenameMap = new HashMap<>();
+ Map<String, Integer> nextCounters = new HashMap<>();
for (int i = 0; i < attachments.size(); i++) {
MultipartFile attachment = attachments.get(i);
@@ -376,7 +395,7 @@ public class PdfAttachmentHandler {
: java.text.Normalizer.normalize(
filename, java.text.Normalizer.Form.NFC);
String uniqueFilename =
- ensureUniqueFilename(normalizedFilename, existingNames.keySet());
+ ensureUniqueFilename(normalizedFilename, existingNames.keySet(), nextCounters);
indexToFilenameMap.put(i, uniqueFilename);
@@ -425,17 +444,31 @@ public class PdfAttachmentHandler {
int annotationsToAdd = Math.min(markerPositions.size(), attachments.size());
+ // The lookup tables are the same for every marker, so build them once.
+ Map<String, EmlParser.EmailAttachment> attachmentsByNormalizedFilename =
+ new LinkedHashMap<>();
+ for (EmlParser.EmailAttachment attachment : attachments) {
+ if (attachment.getFilename() != null) {
+ attachmentsByNormalizedFilename.putIfAbsent(
+ normalizeFilename(attachment.getFilename()), attachment);
+ }
+ }
+ Set<String> embeddedFilenames = new LinkedHashSet<>(indexToFilenameMap.values());
+ PDEmbeddedFilesNameTreeNode efTree =
+ document.getDocumentCatalog().getNames().getEmbeddedFiles();
+ Map<String, PDComplexFileSpecification> efMap = efTree != null ? efTree.getNames() : null;
+
for (int i = 0; i < annotationsToAdd; i++) {
MarkerPosition position = markerPositions.get(i);
String filenameNearMarker = position.getFilename();
EmlParser.EmailAttachment matchingAttachment =
- findAttachmentByFilename(attachments, filenameNearMarker);
+ findAttachmentByFilename(attachmentsByNormalizedFilename, filenameNearMarker);
if (matchingAttachment != null) {
String embeddedFilename =
- findEmbeddedFilenameForAttachment(matchingAttachment, indexToFilenameMap);
+ findEmbeddedFilenameForAttachment(matchingAttachment, embeddedFilenames);
if (embeddedFilename != null) {
PDPage page = document.getPage(position.getPageIndex());
@@ -444,6 +477,7 @@ public class PdfAttachmentHandler {
page,
matchingAttachment,
embeddedFilename,
+ efMap,
position.getX(),
position.getY(),
i);
@@ -457,7 +491,8 @@ public class PdfAttachmentHandler {
}
private static EmlParser.EmailAttachment findAttachmentByFilename(
- List<EmlParser.EmailAttachment> attachments, String targetFilename) {
+ Map<String, EmlParser.EmailAttachment> attachmentsByNormalizedFilename,
+ String targetFilename) {
if (targetFilename == null || targetFilename.trim().isEmpty()) {
return null;
}
@@ -465,23 +500,19 @@ public class PdfAttachmentHandler {
String normalizedTarget = normalizeFilename(targetFilename);
// First try exact match
- for (EmlParser.EmailAttachment attachment : attachments) {
- if (attachment.getFilename() != null) {
- String normalizedAttachment = normalizeFilename(attachment.getFilename());
- if (normalizedAttachment.equals(normalizedTarget)) {
- return attachment;
- }
- }
+ EmlParser.EmailAttachment exactMatch =
+ attachmentsByNormalizedFilename.get(normalizedTarget);
+ if (exactMatch != null) {
+ return exactMatch;
}
// Then try contains match
- for (EmlParser.EmailAttachment attachment : attachments) {
- if (attachment.getFilename() != null) {
- String normalizedAttachment = normalizeFilename(attachment.getFilename());
- if (normalizedAttachment.contains(normalizedTarget)
- || normalizedTarget.contains(normalizedAttachment)) {
- return attachment;
- }
+ for (Map.Entry<String, EmlParser.EmailAttachment> entry :
+ attachmentsByNormalizedFilename.entrySet()) {
+ String normalizedAttachment = entry.getKey();
+ if (normalizedAttachment.contains(normalizedTarget)
+ || normalizedTarget.contains(normalizedAttachment)) {
+ return entry.getValue();
}
}
@@ -489,18 +520,22 @@ public class PdfAttachmentHandler {
}
private static String findEmbeddedFilenameForAttachment(
- EmlParser.EmailAttachment attachment, Map<Integer, String> indexToFilenameMap) {
+ EmlParser.EmailAttachment attachment, Set<String> embeddedFilenames) {
String attachmentFilename = attachment.getFilename();
if (attachmentFilename == null) {
return null;
}
- for (Map.Entry<Integer, String> entry : indexToFilenameMap.entrySet()) {
- String embeddedFilename = entry.getValue();
+ // First try exact match
+ if (embeddedFilenames.contains(attachmentFilename)) {
+ return attachmentFilename;
+ }
+
+ // Then try contains match
+ for (String embeddedFilename : embeddedFilenames) {
if (embeddedFilename != null
- && (embeddedFilename.equals(attachmentFilename)
- || embeddedFilename.contains(attachmentFilename)
+ && (embeddedFilename.contains(attachmentFilename)
|| attachmentFilename.contains(embeddedFilename))) {
return embeddedFilename;
}
@@ -579,21 +614,22 @@ public class PdfAttachmentHandler {
if (isInAttachmentSection) {
currentText.append(string);
- for (int i = 0; (i = string.indexOf(ATTACHMENT_MARKER, i)) != -1; i++) {
- if (i < textPositions.size()) {
- TextPosition textPosition = textPositions.get(i);
-
- String filename = extractFilenameAfterMarker(string, i);
-
- MarkerPosition position =
- new MarkerPosition(
- currentPageIndex,
- textPosition.getXDirAdj(),
- textPosition.getYDirAdj(),
- ATTACHMENT_MARKER,
- filename);
- positions.add(position);
- }
+ // The attachments template prints one marker per entry, so only the first "@" in a
+ // run is the marker; later ones belong to the filename ([email protected]).
+ int i = string.indexOf(ATTACHMENT_MARKER);
+ if (i != -1 && i < textPositions.size()) {
+ TextPosition textPosition = textPositions.get(i);
+
+ String filename = extractFilenameAfterMarker(string, i);
+
+ MarkerPosition position =
+ new MarkerPosition(
+ currentPageIndex,
+ textPosition.getXDirAdj(),
+ textPosition.getYDirAdj(),
+ ATTACHMENT_MARKER,
+ filename);
+ positions.add(position);
}
}
super.writeString(string, textPositions);
@@ -632,6 +668,7 @@ public class PdfAttachmentHandler {
PDPage page,
EmlParser.EmailAttachment attachment,
String embeddedFilename,
+ Map<String, PDComplexFileSpecification> efMap,
float x,
float y,
int attachmentIndex)
@@ -658,17 +695,12 @@ public class PdfAttachmentHandler {
fileAnnotation.setAppearance(null);
}
- PDEmbeddedFilesNameTreeNode efTree =
- document.getDocumentCatalog().getNames().getEmbeddedFiles();
- if (efTree != null) {
- Map<String, PDComplexFileSpecification> efMap = efTree.getNames();
- if (efMap != null) {
- PDComplexFileSpecification fileSpec = efMap.get(embeddedFilename);
- if (fileSpec != null) {
- fileAnnotation.setFile(fileSpec);
- } else {
- // Could not find embedded file
- }
+ if (efMap != null) {
+ PDComplexFileSpecification fileSpec = efMap.get(embeddedFilename);
+ if (fileSpec != null) {
+ fileAnnotation.setFile(fileSpec);
+ } else {
+ // Could not find embedded file
}
}
diff --git a/app/common/src/main/java/stirling/software/common/util/RegexPatternUtils.java b/app/common/src/main/java/stirling/software/common/util/RegexPatternUtils.java
index 6c4321cf5a..7010746ecb 100644
--- a/app/common/src/main/java/stirling/software/common/util/RegexPatternUtils.java
+++ b/app/common/src/main/java/stirling/software/common/util/RegexPatternUtils.java
@@ -443,9 +443,13 @@ public final class RegexPatternUtils {
return getPattern("(https?://[\\w\\-._~:/?#\\[\\]@!$&'()*+,;=%]+)");
}
- /** Pattern for matching email addresses in text for link creation */
+ /**
+ * Pattern for matching email addresses in text for link creation. Anchored to the start of a
+ * local-part run so each run is scanned once.
+ */
public Pattern getEmailLinkPattern() {
- return getPattern("([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,63})");
+ return getPattern(
+ "(?<![a-zA-Z0-9._%+-])([a-zA-Z0-9._%+-]++@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,63})");
}
/** Pattern for removing script tags from HTML */
@@ -458,14 +462,14 @@ public final class RegexPatternUtils {
return getPattern("(?i)<style[^>]*>.*?</style>");
}
- /** Pattern for removing fixed position CSS */
+ /** Pattern for removing fixed position CSS. Anchored to the start of a whitespace run. */
public Pattern getFixedPositionCssPattern() {
- return getPattern("(?i)\\s*position\\s*:\\s*fixed[^;]*;?");
+ return getPattern("(?i)(?<!\\s)\\s*+position\\s*:\\s*fixed[^;]*;?");
}
- /** Pattern for removing absolute position CSS */
+ /** Pattern for removing absolute position CSS. Anchored to the start of a whitespace run. */
public Pattern getAbsolutePositionCssPattern() {
- return getPattern("(?i)\\s*position\\s*:\\s*absolute[^;]*;?");
+ return getPattern("(?i)(?<!\\s)\\s*+position\\s*:\\s*absolute[^;]*;?");
}
/** Pattern for matching size unit suffixes (KB, MB, GB, etc.) */
@@ -488,9 +492,12 @@ public final class RegexPatternUtils {
return getPattern("[\\s\\(\\)]+");
}
- /** Pattern for MIME header whitespace cleanup before encoded sequences */
+ /**
+ * Pattern for MIME header whitespace cleanup before encoded sequences. Anchored to the start of
+ * a whitespace run.
+ */
public Pattern getMimeHeaderWhitespacePattern() {
- return getPattern("\\s+(?==\\?)");
+ return getPattern("(?<!\\s)\\s++(?==\\?)");
}
/** Pattern for font name validation (6 uppercase letters + plus + rest) */
diff --git a/app/common/src/test/java/stirling/software/common/util/EmlParserMoreTest.java b/app/common/src/test/java/stirling/software/common/util/EmlParserMoreTest.java
index aa2b1bc2ab..00e37844e9 100644
--- a/app/common/src/test/java/stirling/software/common/util/EmlParserMoreTest.java
+++ b/app/common/src/test/java/stirling/software/common/util/EmlParserMoreTest.java
@@ -3,11 +3,18 @@ package stirling.software.common.util;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.ZonedDateTime;
import java.util.Base64;
+import java.util.LinkedHashMap;
import java.util.Locale;
+import java.util.Map;
+import org.apache.poi.poifs.filesystem.POIFSFileSystem;
+import org.apache.poi.util.LittleEndian;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
@@ -189,6 +196,164 @@ class EmlParserMoreTest {
}
}
+ @Nested
+ @DisplayName("attachment filename length")
+ class FilenameLengthTests {
+
+ @Test
+ @DisplayName("a long name is shortened and keeps a short extension")
+ void longNameKeepsExtension() {
+ EmailAttachment att = new EmailAttachment();
+ att.setFilename("a".repeat(400) + ".pdf");
+ assertThat(att.getFilename()).hasSize(255).endsWith(".pdf");
+ }
+
+ @Test
+ @DisplayName("a long extension is not preserved")
+ void longExtensionDropped() {
+ EmailAttachment att = new EmailAttachment();
+ att.setFilename("a".repeat(300) + "." + "b".repeat(40));
+ assertThat(att.getFilename()).hasSize(255).doesNotContain(".");
+ }
+
+ @Test
+ @DisplayName("shortening never splits a surrogate pair")
+ void surrogatePairKept() {
+ EmailAttachment att = new EmailAttachment();
+ att.setFilename("\uD83D\uDE00".repeat(200));
+ String name = att.getFilename();
+ assertThat(name.length()).isLessThanOrEqualTo(255);
+ assertThat(Character.isHighSurrogate(name.charAt(name.length() - 1))).isFalse();
+ }
+
+ @Test
+ @DisplayName("short names and null pass through unchanged")
+ void shortNameUnchanged() {
+ EmailAttachment att = new EmailAttachment();
+ att.setFilename("notes.txt");
+ assertThat(att.getFilename()).isEqualTo("notes.txt");
+ att.setFilename(null);
+ assertThat(att.getFilename()).isNull();
+ }
+
+ @Test
+ @DisplayName("a long name in a Content-Disposition header is shortened on parse")
+ void parsedNameShortened() throws Exception {
+ EmailContent content =
+ EmlParser.extractEmailContent(
+ eml(
+ multipartWithAttachment(
+ "----b9", "body", "n".repeat(600) + ".txt", "x")),
+ requestWithAttachments(10),
+ null);
+ assertThat(content.getAttachments().get(0).getFilename()).hasSize(255).endsWith(".txt");
+ }
+ }
+
+ @Nested
+ @DisplayName("extractEmailContent - MSG files")
+ class MsgTests {
+
+ private static final int DIRECTORY_ENTRY_SIZE = 128;
+ private static final int ENTRY_NAME_LENGTH_OFFSET = 64;
+ private static final int ENTRY_START_SECTOR_OFFSET = 116;
+ private static final int ENTRY_SIZE_OFFSET = 120;
+
+ private static byte[] compoundFile(Map<String, Integer> streamSizes) throws Exception {
+ try (POIFSFileSystem fs = new POIFSFileSystem();
+ ByteArrayOutputStream out = new ByteArrayOutputStream()) {
+ for (Map.Entry<String, Integer> e : streamSizes.entrySet()) {
+ fs.getRoot()
+ .createDocument(
+ e.getKey(), new ByteArrayInputStream(new byte[e.getValue()]));
+ }
+ fs.writeFilesystem(out);
+ return out.toByteArray();
+ }
+ }
+
+ /** Offset of the named directory entry; the directory fits in one sector. */
+ private static int directoryEntryOffset(byte[] file, String name) {
+ int sectorSize = 1 << LittleEndian.getShort(file, 30);
+ int directoryStartSector = LittleEndian.getInt(file, 48);
+ int base = sectorSize + directoryStartSector * sectorSize;
+ for (int i = 0; i < sectorSize / DIRECTORY_ENTRY_SIZE; i++) {
+ int offset = base + i * DIRECTORY_ENTRY_SIZE;
+ int nameBytes = LittleEndian.getShort(file, offset + ENTRY_NAME_LENGTH_OFFSET);
+ if (nameBytes < 2) continue;
+ String entryName =
+ new String(file, offset, nameBytes - 2, StandardCharsets.UTF_16LE);
+ if (entryName.equals(name)) return offset;
+ }
+ throw new IllegalStateException("no directory entry named " + name);
+ }
+
+ private static Map<String, Integer> streams(String n1, int s1, String n2, int s2) {
+ Map<String, Integer> m = new LinkedHashMap<>();
+ m.put(n1, s1);
+ m.put(n2, s2);
+ return m;
+ }
+
+ @Test
+ @DisplayName("a well-formed MSG parses")
+ void wellFormedMsgParses() throws Exception {
+ byte[] msg;
+ try (InputStream in = getClass().getResourceAsStream("/eml/example.msg")) {
+ assertThat(in).isNotNull();
+ msg = in.readAllBytes();
+ }
+ EmailContent content = EmlParser.extractEmailContent(msg, null, null);
+ assertThat(content).isNotNull();
+ assertThat(content.getSubject()).isNotNull();
+ }
+
+ @Test
+ @DisplayName("two directory entries pointing at the same data are rejected")
+ void sharedStreamDataRejected() throws Exception {
+ byte[] file =
+ compoundFile(
+ streams("__substg1.0_37010102", 100_000, "__substg1.0_3707001F", 10));
+ int big = directoryEntryOffset(file, "__substg1.0_37010102");
+ int small = directoryEntryOffset(file, "__substg1.0_3707001F");
+ System.arraycopy(
+ file,
+ big + ENTRY_START_SECTOR_OFFSET,
+ file,
+ small + ENTRY_START_SECTOR_OFFSET,
+ 8);
+
+ assertThatThrownBy(() -> EmlParser.extractEmailContent(file, null, null))
+ .isInstanceOf(java.io.IOException.class)
+ .hasMessageContaining("more data than the file contains");
+ }
+
+ @Test
+ @DisplayName("a negative stream size is rejected")
+ void negativeStreamSizeRejected() throws Exception {
+ byte[] file =
+ compoundFile(
+ streams("__substg1.0_37010102", 5_000, "__substg1.0_3707001F", 10));
+ int small = directoryEntryOffset(file, "__substg1.0_3707001F");
+ LittleEndian.putInt(file, small + ENTRY_SIZE_OFFSET, -1);
+
+ assertThatThrownBy(() -> EmlParser.extractEmailContent(file, null, null))
+ .isInstanceOf(java.io.IOException.class);
+ }
+
+ @Test
+ @DisplayName("an oversized property stream is rejected")
+ void oversizedPropertyStreamRejected() throws Exception {
+ byte[] file =
+ compoundFile(
+ streams("__properties_version1.0", 70_000, "__substg1.0_3707001F", 10));
+
+ assertThatThrownBy(() -> EmlParser.extractEmailContent(file, null, null))
+ .isInstanceOf(java.io.IOException.class)
+ .hasMessageContaining("property stream");
+ }
+ }
+
@Nested
@DisplayName("extractEmailContent - failure paths")
class FailureTests {
@@ -218,6 +383,35 @@ class EmlParserMoreTest {
assertThatThrownBy(() -> EmlParser.extractEmailContent(fakeMsg, null, null))
.isInstanceOf(java.io.IOException.class);
}
+
+ @Test
+ @DisplayName("more attachments than allowed raises an IOException only when embedding")
+ void tooManyAttachments() throws Exception {
+ StringBuilder content =
+ new StringBuilder(
+ "From: [email protected]\nTo: [email protected]\nSubject: Many\n"
+ + "Content-Type: multipart/mixed; boundary=\"b\"\n\n"
+ + "--b\nContent-Type: text/plain\n\nbody\n");
+ for (int i = 0; i <= ZipBombGuard.MAX_ENTRIES; i++) {
+ content.append("--b\nContent-Disposition: attachment; filename=f")
+ .append(i)
+ .append(".txt\n\nx\n");
+ }
+ content.append("--b--\n");
+ byte[] message = eml(content.toString());
+
+ assertThatThrownBy(
+ () ->
+ EmlParser.extractEmailContent(
+ message, requestWithAttachments(10), null))
+ .isInstanceOf(java.io.IOException.class)
+ .hasMessageContaining("attachments");
+
+ EmlToPdfRequest listingOnly = new EmlToPdfRequest();
+ listingOnly.setIncludeAttachments(false);
+ EmailContent listed = EmlParser.extractEmailContent(message, listingOnly, null);
+ assertThat(listed.getAttachmentCount()).isEqualTo(ZipBombGuard.MAX_ENTRIES + 1);
+ }
}
@Nested
diff --git a/app/common/src/test/java/stirling/software/common/util/EmlProcessingUtilsTest.java b/app/common/src/test/java/stirling/software/common/util/EmlProcessingUtilsTest.java
index 336f27ad85..1271d771bb 100644
--- a/app/common/src/test/java/stirling/software/common/util/EmlProcessingUtilsTest.java
+++ b/app/common/src/test/java/stirling/software/common/util/EmlProcessingUtilsTest.java
@@ -2,6 +2,8 @@ package stirling.software.common.util;
import static org.junit.jupiter.api.Assertions.*;
+import java.time.Duration;
+
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
@@ -150,12 +152,34 @@ class EmlProcessingUtilsTest {
String result = EmlProcessingUtils.convertTextToHtml("Contact [email protected]", null);
assertTrue(result.contains("mailto:[email protected]"));
}
+
+ @Test
+ @DisplayName("a long run of letters with no address converts promptly")
+ void longLetterRun() {
+ String text = "a".repeat(200_000);
+ String result =
+ assertTimeoutPreemptively(
+ Duration.ofSeconds(5),
+ () -> EmlProcessingUtils.convertTextToHtml(text, null));
+ assertFalse(result.contains("mailto:"));
+ }
}
@Nested
@DisplayName("decodeMimeHeader")
class DecodeMimeHeaderTests {
+ @Test
+ @DisplayName("a long whitespace run inside an encoded word decodes promptly")
+ void longWhitespaceInEncodedWord() {
+ String header = "=?utf-8?Q?" + " ".repeat(200_000) + "x?==?utf-8?Q?y?=";
+ String result =
+ assertTimeoutPreemptively(
+ Duration.ofSeconds(5),
+ () -> EmlProcessingUtils.decodeMimeHeader(header));
+ assertNotNull(result);
+ }
+
@Test
@DisplayName("should return null for null input")
void nullInput() {
@@ -271,6 +295,25 @@ class EmlProcessingUtilsTest {
String result = EmlProcessingUtils.processEmailHtmlBody(html, null, null);
assertFalse(result.contains("position:fixed"));
}
+
+ @Test
+ @DisplayName("whitespace before position CSS is removed with the declaration")
+ void stripsLeadingWhitespaceWithDeclaration() {
+ String html = "<div style=\"color:red; position: fixed; top:0\">x</div>";
+ String result = EmlProcessingUtils.processEmailHtmlBody(html, null, null);
+ assertEquals("<div style=\"color:red; top:0\">x</div>", result);
+ }
+
+ @Test
+ @DisplayName("a long whitespace run converts promptly")
+ void longWhitespaceRun() {
+ String html = "<p>hello</p>" + " ".repeat(200_000);
+ String result =
+ assertTimeoutPreemptively(
+ Duration.ofSeconds(5),
+ () -> EmlProcessingUtils.processEmailHtmlBody(html, null, null));
+ assertTrue(result.startsWith("<p>hello</p>"));
+ }
}
@Nested
diff --git a/app/common/src/test/java/stirling/software/common/util/PdfAttachmentHandlerGapTest.java b/app/common/src/test/java/stirling/software/common/util/PdfAttachmentHandlerGapTest.java
index 01d9128f26..a34a05adbb 100644
--- a/app/common/src/test/java/stirling/software/common/util/PdfAttachmentHandlerGapTest.java
+++ b/app/common/src/test/java/stirling/software/common/util/PdfAttachmentHandlerGapTest.java
@@ -266,6 +266,57 @@ class PdfAttachmentHandlerGapTest {
}
}
+ @Nested
+ @DisplayName("attachment names")
+ class FilenameLengthTests {
+
+ @Test
+ @DisplayName("a long attachment name is embedded under a bounded name")
+ void longNameEmbeddedUnderBoundedName() throws Exception {
+ byte[] pdfBytes = pdfWithLines("Attachments (1)", "@n.txt (1 KB)");
+ when(pdfDocumentFactory.load(pdfBytes)).thenReturn(Loader.loadPDF(pdfBytes));
+
+ List<EmlParser.EmailAttachment> attachments = new ArrayList<>();
+ attachments.add(
+ attachment(
+ "x" + "\u0301".repeat(600) + ".txt",
+ "data".getBytes(StandardCharsets.UTF_8)));
+
+ byte[] result =
+ PdfAttachmentHandler.attachFilesToPdf(
+ pdfBytes, attachments, pdfDocumentFactory);
+
+ List<String> names = embeddedFileNames(result);
+ assertEquals(1, names.size());
+ assertTrue(names.get(0).length() <= 255);
+ assertTrue(names.get(0).endsWith(".txt"));
+ }
+
+ @Test
+ @DisplayName("two attachments with the same long name get distinct bounded names")
+ void duplicateLongNamesStayBounded() throws Exception {
+ byte[] pdfBytes = pdfWithLines("Attachments (2)", "@a.txt (1 KB)", "@a.txt (1 KB)");
+ when(pdfDocumentFactory.load(pdfBytes)).thenReturn(Loader.loadPDF(pdfBytes));
+
+ String longName = "n".repeat(251) + ".txt";
+ List<EmlParser.EmailAttachment> attachments = new ArrayList<>();
+ attachments.add(attachment(longName, "one".getBytes(StandardCharsets.UTF_8)));
+ attachments.add(attachment(longName, "two".getBytes(StandardCharsets.UTF_8)));
+
+ byte[] result =
+ PdfAttachmentHandler.attachFilesToPdf(
+ pdfBytes, attachments, pdfDocumentFactory);
+
+ List<String> names = embeddedFileNames(result);
+ assertEquals(2, names.size());
+ assertNotEquals(names.get(0), names.get(1));
+ for (String name : names) {
+ assertTrue(name.length() <= 255);
+ assertTrue(name.endsWith(".txt"));
+ }
+ }
+ }
+
// ----- AttachmentMarkerPositionFinder --------------------------------
@Nested
@@ -308,6 +359,25 @@ class PdfAttachmentHandlerGapTest {
}
}
+ @Test
+ @DisplayName("treats an @ inside a filename as part of the name, not as another marker")
+ void markerCharacterInFilename_singlePosition() throws Exception {
+ byte[] pdfBytes =
+ pdfWithLines(
+ "Attachments (2)", "@[email protected] (1 KB)", "@" + "@".repeat(500));
+
+ try (PDDocument doc = Loader.loadPDF(pdfBytes)) {
+ PdfAttachmentHandler.AttachmentMarkerPositionFinder finder =
+ new PdfAttachmentHandler.AttachmentMarkerPositionFinder();
+ finder.getText(doc);
+
+ List<PdfAttachmentHandler.MarkerPosition> positions = finder.getPositions();
+ assertEquals(2, positions.size());
+ assertEquals("[email protected]", positions.get(0).getFilename());
+ assertEquals("@".repeat(500), positions.get(1).getFilename());
+ }
+ }
+
@Test
@DisplayName("collects no positions when there is no attachments section")
void noAttachmentSection_noPositions() throws Exception {
diff --git a/app/common/src/test/resources/eml/example.msg b/app/common/src/test/resources/eml/example.msg
new file mode 100644
index 0000000000..ffb7f03983
Binary files /dev/null and b/app/common/src/test/resources/eml/example.msg differ
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEmlToPDF.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEmlToPDF.java
index 446892b0fc..c8a7b710f5 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEmlToPDF.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEmlToPDF.java
@@ -103,9 +103,12 @@ public class ConvertEmlToPDF {
tempOut, baseFilename + ".html", MediaType.TEXT_HTML);
} catch (IOException | IllegalArgumentException e) {
log.error("HTML conversion failed for {}", originalFilename, e);
+ String detail =
+ e.getMessage() == null
+ ? "Unknown error"
+ : HtmlUtils.htmlEscape(e.getMessage());
return errorResponse(
- HttpStatus.INTERNAL_SERVER_ERROR,
- "HTML conversion failed: " + e.getMessage());
+ HttpStatus.INTERNAL_SERVER_ERROR, "HTML conversion failed: " + detail);
}
}
@@ -166,9 +169,11 @@ public class ConvertEmlToPDF {
}
}
+ /** Error bodies are plain text whatever the request negotiates. */
private ResponseEntity<Resource> errorResponse(HttpStatus status, String message) {
byte[] body = message.getBytes(StandardCharsets.UTF_8);
return ResponseEntity.status(status)
+ .contentType(new MediaType(MediaType.TEXT_PLAIN, StandardCharsets.UTF_8))
.contentLength(body.length)
.body(new ByteArrayResource(body));
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertSvgToPDF.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertSvgToPDF.java
index 5018de308f..bfc3e98734 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertSvgToPDF.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertSvgToPDF.java
@@ -136,9 +136,11 @@ public class ConvertSvgToPDF {
}
}
+ /** Error bodies are plain text whatever the request negotiates. */
private ResponseEntity<Resource> errorResponse(HttpStatus status, String message) {
byte[] body = message.getBytes(StandardCharsets.UTF_8);
return ResponseEntity.status(status)
+ .contentType(new MediaType(MediaType.TEXT_PLAIN, StandardCharsets.UTF_8))
.contentLength(body.length)
.body(new ByteArrayResource(body));
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEmlToPDFTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEmlToPDFTest.java
index ce0b91e0f2..605c4edce8 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEmlToPDFTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEmlToPDFTest.java
@@ -2,6 +2,7 @@ package stirling.software.SPDF.controller.api.converters;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
@@ -235,14 +236,18 @@ class ConvertEmlToPDFTest {
any(byte[].class),
eq(request),
eq(customHtmlSanitizer)))
- .thenThrow(new IOException("Parse error"));
+ .thenThrow(new IOException("Parse error: <b>&</b>"));
ResponseEntity<Resource> response = controller.convertEmlToPdf(request);
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode());
- assertTrue(
- new String(drainBody(response), StandardCharsets.UTF_8)
- .contains("HTML conversion failed"));
+ assertEquals(
+ new MediaType(MediaType.TEXT_PLAIN, StandardCharsets.UTF_8),
+ response.getHeaders().getContentType());
+ String body = new String(drainBody(response), StandardCharsets.UTF_8);
+ assertTrue(body.contains("HTML conversion failed"));
+ assertTrue(body.contains("&lt;b&gt;&amp;&lt;/b&gt;"));
+ assertFalse(body.contains("<b>"));
}
}