#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Bound decompression when reading untrusted archives (#7813)
Anthony Stirling59857652613f
diff --git a/app/common/src/main/java/stirling/software/common/util/CbzUtils.java b/app/common/src/main/java/stirling/software/common/util/CbzUtils.javaindex b6c756746f..2f2b0d21c6 100644--- a/app/common/src/main/java/stirling/software/common/util/CbzUtils.java+++ b/app/common/src/main/java/stirling/software/common/util/CbzUtils.java@@ -1,7 +1,6 @@package stirling.software.common.util;import java.io.BufferedInputStream;-import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.nio.file.Files;@@ -74,12 +73,11 @@ public class CbzUtils {}// Pass 2: load ONE image at a time peak memory = max(single image)+ ZipBombGuard.Budget budget = new ZipBombGuard.Budget();for (String imageName : sortedImageNames) {ZipEntry entry = zipFile.getEntry(imageName);try (InputStream is = zipFile.getInputStream(entry)) {- ByteArrayOutputStream imgBaos = new ByteArrayOutputStream();- is.transferTo(imgBaos);- byte[] imageBytes = imgBaos.toByteArray();+ byte[] imageBytes = budget.readEntry(is);try {PDImageXObject pdImage =PDImageXObject.createFromByteArray(@@ -102,6 +100,8 @@ public class CbzUtils {log.warn("Error processing image {}: {}", imageName, e.getMessage());}// imageBytes eligible for GC after each iteration+ } catch (ZipBombGuard.ZipBombException e) {+ throw ExceptionUtils.createCbzInvalidFormatException(e);} catch (IOException e) {log.warn("Error reading image {}: {}", imageName, e.getMessage());}diff --git a/app/common/src/main/java/stirling/software/common/util/FileToPdf.java b/app/common/src/main/java/stirling/software/common/util/FileToPdf.javaindex 83bc0e35bc..00d431e9f4 100644--- a/app/common/src/main/java/stirling/software/common/util/FileToPdf.java+++ b/app/common/src/main/java/stirling/software/common/util/FileToPdf.java@@ -83,6 +83,7 @@ public class FileToPdf {try (TempDirectory tempUnzippedDir = new TempDirectory(tempFileManager)) {try (ZipInputStream zipIn =ZipSecurity.createHardenedInputStream(Files.newInputStream(zipFilePath))) {+ ZipBombGuard.Budget budget = new ZipBombGuard.Budget();ZipEntry entry = zipIn.getNextEntry();while (entry != null) {Path filePath =@@ -99,12 +100,12 @@ public class FileToPdf {if (entry.getName().toLowerCase(Locale.ROOT).endsWith(".html")|| entry.getName().toLowerCase(Locale.ROOT).endsWith(".htm")) {String content =- new String(zipIn.readAllBytes(), StandardCharsets.UTF_8);+ new String(budget.readEntry(zipIn), StandardCharsets.UTF_8);String sanitizedContent =sanitizeHtmlContent(content, customHtmlSanitizer);Files.writeString(filePath, sanitizedContent);} else {- Files.copy(zipIn, filePath);+ budget.copyEntry(zipIn, filePath);}}zipIn.closeEntry();diff --git a/app/common/src/main/java/stirling/software/common/util/OfficeDocumentSanitizer.java b/app/common/src/main/java/stirling/software/common/util/OfficeDocumentSanitizer.javaindex 9cdf8cf53b..11cd32a18f 100644--- a/app/common/src/main/java/stirling/software/common/util/OfficeDocumentSanitizer.java+++ b/app/common/src/main/java/stirling/software/common/util/OfficeDocumentSanitizer.java@@ -91,10 +91,11 @@ public class OfficeDocumentSanitizer {new ByteArrayInputStream(documentBytes));ZipOutputStream zipOut = new ZipOutputStream(out)) {+ ZipBombGuard.Budget budget = new ZipBombGuard.Budget();ZipEntry entry;while ((entry = zipIn.getNextEntry()) != null) {String name = entry.getName();- byte[] bytes = entry.isDirectory() ? new byte[0] : zipIn.readAllBytes();+ byte[] bytes = entry.isDirectory() ? new byte[0] : budget.readEntry(zipIn);if (!entry.isDirectory()) {bytes = sanitizeEntry(name, bytes);diff --git a/app/common/src/main/java/stirling/software/common/util/ZipBombGuard.java b/app/common/src/main/java/stirling/software/common/util/ZipBombGuard.javanew file mode 100644index 0000000000..24c240727e--- /dev/null+++ b/app/common/src/main/java/stirling/software/common/util/ZipBombGuard.java@@ -0,0 +1,110 @@+package stirling.software.common.util;++import java.io.ByteArrayOutputStream;+import java.io.IOException;+import java.io.InputStream;+import java.io.OutputStream;+import java.nio.file.Files;+import java.nio.file.Path;++import lombok.experimental.UtilityClass;++@UtilityClass+public class ZipBombGuard {++ public static final long MAX_ENTRY_BYTES = 100L * 1024 * 1024;+ public static final long MAX_TOTAL_BYTES = 500L * 1024 * 1024;+ public static final int MAX_ENTRIES = 10_000;++ private static final int BUFFER_SIZE = 8192;++ public static class ZipBombException extends IOException {+ public ZipBombException(String message) {+ super(message);+ }+ }++ public static byte[] readEntry(InputStream entryStream) throws IOException {+ return readEntry(entryStream, MAX_ENTRY_BYTES);+ }++ public static byte[] readEntry(InputStream entryStream, long maxBytes) throws IOException {+ ByteArrayOutputStream out = new ByteArrayOutputStream();+ byte[] buffer = new byte[BUFFER_SIZE];+ long total = 0;+ int read;+ while ((read = entryStream.read(buffer)) != -1) {+ total += read;+ if (total > maxBytes) {+ throw new ZipBombException(+ "Archive entry exceeds the maximum allowed size of " + maxBytes + " bytes");+ }+ out.write(buffer, 0, read);+ }+ return out.toByteArray();+ }++ public static class Budget {+ private final long maxEntryBytes;+ private final long maxTotalBytes;+ private final int maxEntries;+ private long totalBytes;+ private int entryCount;++ public Budget() {+ this(MAX_ENTRY_BYTES, MAX_TOTAL_BYTES, MAX_ENTRIES);+ }++ public Budget(long maxEntryBytes, long maxTotalBytes, int maxEntries) {+ this.maxEntryBytes = maxEntryBytes;+ this.maxTotalBytes = maxTotalBytes;+ this.maxEntries = maxEntries;+ }++ public byte[] readEntry(InputStream entryStream) throws IOException {+ countEntry();+ byte[] bytes = ZipBombGuard.readEntry(entryStream, maxEntryBytes);+ addToTotal(bytes.length);+ return bytes;+ }++ public void copyEntry(InputStream entryStream, Path target) throws IOException {+ countEntry();+ long written = 0;+ byte[] buffer = new byte[BUFFER_SIZE];+ try (OutputStream out = Files.newOutputStream(target)) {+ int read;+ while ((read = entryStream.read(buffer)) != -1) {+ written += read;+ if (written > maxEntryBytes) {+ throw new ZipBombException(+ "Archive entry exceeds the maximum allowed size of "+ + maxEntryBytes+ + " bytes");+ }+ out.write(buffer, 0, read);+ }+ }+ addToTotal(written);+ }++ private void countEntry() throws ZipBombException {+ if (++entryCount > maxEntries) {+ throw new ZipBombException(+ "Archive contains more than the maximum allowed "+ + maxEntries+ + " entries");+ }+ }++ private void addToTotal(long bytes) throws ZipBombException {+ totalBytes += bytes;+ if (totalBytes > maxTotalBytes) {+ throw new ZipBombException(+ "Archive decompresses to more than the maximum allowed "+ + maxTotalBytes+ + " bytes");+ }+ }+ }+}diff --git a/app/common/src/test/java/stirling/software/common/util/ZipBombGuardTest.java b/app/common/src/test/java/stirling/software/common/util/ZipBombGuardTest.javanew file mode 100644index 0000000000..67d89f56b6--- /dev/null+++ b/app/common/src/test/java/stirling/software/common/util/ZipBombGuardTest.java@@ -0,0 +1,84 @@+package stirling.software.common.util;++import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++import java.io.ByteArrayInputStream;+import java.nio.file.Files;+import java.nio.file.Path;++import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;++class ZipBombGuardTest {++ @Test+ void readEntry_underLimit_returnsBytes() throws Exception {+ byte[] data = new byte[1024];+ byte[] out = ZipBombGuard.readEntry(new ByteArrayInputStream(data), 4096);+ assertArrayEquals(data, out);+ }++ @Test+ void readEntry_overLimit_throwsZipBomb() {+ byte[] data = new byte[5000];+ ZipBombGuard.ZipBombException ex =+ assertThrows(+ ZipBombGuard.ZipBombException.class,+ () -> ZipBombGuard.readEntry(new ByteArrayInputStream(data), 4096));+ assertTrue(ex.getMessage().contains("maximum allowed"));+ }++ @Test+ void budget_perEntryCap_throws() {+ ZipBombGuard.Budget budget = new ZipBombGuard.Budget(1000, 1_000_000, 100);+ assertThrows(+ ZipBombGuard.ZipBombException.class,+ () -> budget.readEntry(new ByteArrayInputStream(new byte[2000])));+ }++ @Test+ void budget_cumulativeTotal_throwsAcrossEntries() throws Exception {+ ZipBombGuard.Budget budget = new ZipBombGuard.Budget(1000, 2500, 100);+ budget.readEntry(new ByteArrayInputStream(new byte[1000]));+ budget.readEntry(new ByteArrayInputStream(new byte[1000]));+ assertThrows(+ ZipBombGuard.ZipBombException.class,+ () -> budget.readEntry(new ByteArrayInputStream(new byte[1000])));+ }++ @Test+ void budget_entryCount_throws() throws Exception {+ ZipBombGuard.Budget budget = new ZipBombGuard.Budget(1000, 1_000_000, 2);+ budget.readEntry(new ByteArrayInputStream(new byte[10]));+ budget.readEntry(new ByteArrayInputStream(new byte[10]));+ assertThrows(+ ZipBombGuard.ZipBombException.class,+ () -> budget.readEntry(new ByteArrayInputStream(new byte[10])));+ }++ @Test+ void copyEntry_underLimit_writesFile(@TempDir Path dir) throws Exception {+ Path target = dir.resolve("out.bin");+ byte[] data = "hello world".getBytes();+ new ZipBombGuard.Budget().copyEntry(new ByteArrayInputStream(data), target);+ assertArrayEquals(data, Files.readAllBytes(target));+ }++ @Test+ void copyEntry_overLimit_throws(@TempDir Path dir) {+ Path target = dir.resolve("big.bin");+ ZipBombGuard.Budget budget = new ZipBombGuard.Budget(1000, 1_000_000, 100);+ assertThrows(+ ZipBombGuard.ZipBombException.class,+ () -> budget.copyEntry(new ByteArrayInputStream(new byte[2000]), target));+ }++ @Test+ void defaults_matchAttachmentServiceLimits() {+ assertEquals(100L * 1024 * 1024, ZipBombGuard.MAX_ENTRY_BYTES);+ assertEquals(500L * 1024 * 1024, ZipBombGuard.MAX_TOTAL_BYTES);+ }+}