This is an automated email from the ASF dual-hosted git repository.

garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-compress.git


The following commit(s) were added to refs/heads/master by this push:
     new b488058dd Validate unencrypted STORED ZIP entry sizes (f012) (#869)
b488058dd is described below

commit b488058dd3657369b5f606d1a39355bfc6dbeda5
Author: Gary Gregory <[email protected]>
AuthorDate: Thu Dec 3 20:35:22 2026 -0500

    Validate unencrypted STORED ZIP entry sizes (f012) (#869)
    
    Reject inconsistent compressed and uncompressed sizes after ZIP64
    resolution. Preserve encrypted-entry skipping and data-descriptor
    handling, and use compressed size consistently when reading STORED data.
    
    Document the validation and add regression coverage for size mismatches,
    ZIP64 entries, entry boundaries, and encrypted entries.
---
 src/changes/changes.xml                            |   1 +
 .../archivers/zip/ZipArchiveInputStream.java       |  15 +-
 .../zip/ZipArchiveInputStreamStoredTest.java       | 269 +++++++++++++++++++++
 .../archivers/zip/ZipArchiveInputStreamTest.java   |   7 +-
 src/test/resources/zip-stored-encrypted.zip        | Bin 0 -> 226 bytes
 5 files changed, 288 insertions(+), 4 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 509d14d8a..7ae279b2a 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -102,6 +102,7 @@ The <action> type attribute can be add,update,fix,remove.
       <action type="fix" dev="ggregory" due-to="Gary Gregory">[Zip] 
UnshrinkingInputStreamnow now throws CompressorException instead of 
IllegalArgumetException/IllegalStateException.</action>
       <action type="fix" dev="ggregory">[Zip] Apply the 1 GiB XZ decoder 
memory limit when reading XZ-compressed entries with ZipFile or 
ZipArchiveInputStream; these ZIP APIs do not expose a memory-limit 
override.</action>
       <action type="fix" dev="ggregory" due-to="Claude Security, Gary 
Gregory">[Zip] Validate local file header signatures when ZipFile resolves 
entry data offsets, including deferred and raw reads.</action>
+      <action type="fix" dev="ggregory" due-to="Claude Security, Gary 
Gregory">[Zip] Reject inconsistent sizes in unencrypted STORED entries in 
ZipArchiveInputStream while preserving encrypted-entry skipping.</action>
       <!-- FIX TAR -->
       <action type="fix" dev="pkarwasz" due-to="Tyler Nighswander, Piotr P. 
Karwasz, Gary Gregory">>[TAR] Uniform handling of special tar records in 
TarFile and TarArchiveInputStream.</action>
       <action type="fix" dev="ggregory" due-to="Gary Gregory, Stanislav 
Fort">[TAR] TarArchiveOutputStream now throws a ArchiveException instead of an 
OutOfMemoryError.</action>
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStream.java
 
b/src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStream.java
index 59750f36a..2a8e3b9bf 100644
--- 
a/src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStream.java
+++ 
b/src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStream.java
@@ -810,6 +810,11 @@ public long getCompressedCount() throws IOException {
         return -1;
     }
 
+    /**
+     * {@inheritDoc}
+     *
+     * @throws ZipException if an unencrypted STORED entry without a data 
descriptor declares different compressed and uncompressed sizes.
+     */
     @Override
     public ZipArchiveEntry getNextEntry() throws IOException {
         return getNextZipEntry();
@@ -820,6 +825,7 @@ public ZipArchiveEntry getNextEntry() throws IOException {
      *
      * @return The next entry.
      * @throws IOException if an I/O error occurs.
+     * @throws ZipException if an unencrypted STORED entry without a data 
descriptor declares different compressed and uncompressed sizes.
      * @deprecated Use {@link #getNextEntry()}.
      */
     @Deprecated
@@ -909,6 +915,12 @@ public ZipArchiveEntry getNextZipEntry() throws 
IOException {
         current.entry.setDataOffset(getBytesRead());
         current.entry.setStreamContiguous(true);
         final ZipMethod m = 
ZipMethod.getMethodByCode(current.entry.getMethod());
+        // Unencrypted STORED entries must have equal sizes so reading and 
skipping agree on the next entry's position.
+        // Encrypted entries may include encryption overhead in the compressed 
size and must remain skippable.
+        if (m == ZipMethod.STORED && !current.hasDataDescriptor && 
!gpFlag.usesEncryption()
+                && current.entry.getCompressedSize() != 
current.entry.getSize()) {
+            throw new ZipException("Compressed and uncompressed size don't 
match for STORED entry " + ArchiveUtils.sanitize(current.entry.getName()));
+        }
         if (current.entry.getCompressedSize() != ArchiveEntry.SIZE_UNKNOWN) {
             if (ZipUtil.canHandleEntryData(current.entry) && m != 
ZipMethod.STORED && m != ZipMethod.DEFLATED) {
                 final InputStream bis = new BoundCountInputStream(in, 
current.entry.getCompressedSize());
@@ -1259,7 +1271,8 @@ private int readStored(final byte[] buffer, final int 
offset, final int length)
             }
             return lastStoredEntry.read(buffer, offset, length);
         }
-        final long csize = current.entry.getSize();
+        // Use the same bound as drainCurrentEntryData(). Sizes were checked 
when the header was read.
+        final long csize = current.entry.getCompressedSize();
         if (current.bytesRead >= csize) {
             return -1;
         }
diff --git 
a/src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamStoredTest.java
 
b/src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamStoredTest.java
new file mode 100644
index 000000000..bb0659b6f
--- /dev/null
+++ 
b/src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamStoredTest.java
@@ -0,0 +1,269 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.commons.compress.archivers.zip;
+
+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.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.stream.Stream;
+import java.util.zip.CRC32;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+
+import org.apache.commons.compress.AbstractTest;
+import org.apache.commons.compress.archivers.ArchiveEntry;
+import org.apache.commons.io.IOUtils;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Tests size validation and entry boundaries for STORED entries.
+ */
+class ZipArchiveInputStreamStoredTest extends AbstractTest {
+
+    private static final byte[] FIRST_CONTENT = 
"HELLO".getBytes(StandardCharsets.US_ASCII);
+    private static final byte[] SECOND_CONTENT = "second 
entry".getBytes(StandardCharsets.US_ASCII);
+
+    /**
+     * Creates two STORED entries with ordinary or ZIP64 sizes and no data 
descriptors.
+     *
+     * @param firstContent the first entry's contents.
+     * @param zip64Mode the ZIP64 mode.
+     * @return the archive bytes.
+     * @throws IOException if writing fails.
+     */
+    private static byte[] createArchive(final byte[] firstContent, final 
Zip64Mode zip64Mode) throws IOException {
+        final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+        try (ZipArchiveOutputStream out = new ZipArchiveOutputStream(bytes)) {
+            out.setUseZip64(zip64Mode);
+            writeEntry(out, "first.txt", firstContent);
+            writeEntry(out, "second.txt", SECOND_CONTENT);
+        }
+        return bytes.toByteArray();
+    }
+
+    /**
+     * Gets the data offset following a local file header.
+     *
+     * @param archive the archive bytes.
+     * @param headerOffset the local file header offset.
+     * @return the data offset.
+     */
+    private static int getDataOffset(final byte[] archive, final int 
headerOffset) {
+        return headerOffset + 30 + ZipShort.getValue(archive, headerOffset + 
26) + ZipShort.getValue(archive, headerOffset + 28);
+    }
+
+    /**
+     * Supplies mismatches in both directions, including zero and sizes 
requiring more than 32 bits.
+     *
+     * @return the test arguments.
+     */
+    private static Stream<Arguments> mismatchedSizes() {
+        return Stream.concat(Stream.of(Zip64Mode.Never, 
Zip64Mode.Always).flatMap(mode -> Stream.of(
+                Arguments.of(mode, 0, 1), Arguments.of(mode, 1, 0), 
Arguments.of(mode, 3, 5),
+                Arguments.of(mode, 5, 3), Arguments.of(mode, 5, 100))),
+                Stream.of(Arguments.of(Zip64Mode.Always, 5, 0x100000005L), 
Arguments.of(Zip64Mode.Always, 0x100000005L, 5)));
+    }
+
+    /**
+     * Reads all, part, or none of the first entry before advancing.
+     *
+     * @param in the archive stream positioned at the first entry.
+     * @param content the expected entry contents.
+     * @param readMode zero to skip, one to read a byte, or two to read 
everything.
+     * @throws IOException if reading fails.
+     */
+    private static void readFirstEntry(final ZipArchiveInputStream in, final 
byte[] content, final int readMode) throws IOException {
+        if (readMode == 1) {
+            assertEquals(content.length == 0 ? -1 : content[0] & 0xff, 
in.read());
+        } else if (readMode == 2) {
+            assertArrayEquals(content, IOUtils.toByteArray(in));
+            assertEquals(-1, in.read());
+        }
+    }
+
+    /**
+     * Changes only the local header's sizes, leaving the central directory 
intact.
+     *
+     * @param archive the archive bytes.
+     * @param headerOffset the local file header offset.
+     * @param zip64Mode the ZIP64 mode used to write the archive.
+     * @param compressedSize the compressed size to declare.
+     * @param size the uncompressed size to declare.
+     */
+    private static void setSizes(final byte[] archive, final int headerOffset, 
final Zip64Mode zip64Mode,
+            final long compressedSize, final long size) {
+        if (zip64Mode == Zip64Mode.Always) {
+            assertEquals(ZipConstants.ZIP64_MAGIC, ZipLong.getValue(archive, 
headerOffset + 18));
+            assertEquals(ZipConstants.ZIP64_MAGIC, ZipLong.getValue(archive, 
headerOffset + 22));
+            final int extraOffset = headerOffset + 30 + 
ZipShort.getValue(archive, headerOffset + 26);
+            
assertEquals(Zip64ExtendedInformationExtraField.HEADER_ID.getValue(), 
ZipShort.getValue(archive, extraOffset));
+            final ByteBuffer buffer = 
ByteBuffer.wrap(archive).order(ByteOrder.LITTLE_ENDIAN);
+            buffer.putLong(extraOffset + 4, size);
+            buffer.putLong(extraOffset + 12, compressedSize);
+        } else {
+            ZipLong.putLong(compressedSize, archive, headerOffset + 18);
+            ZipLong.putLong(size, archive, headerOffset + 22);
+        }
+    }
+
+    /**
+     * Supplies empty, small, and multi-buffer entries with each way of 
advancing to the next entry.
+     *
+     * @return the test arguments.
+     */
+    private static Stream<Arguments> validEntries() {
+        return Stream.of(Zip64Mode.Never, Zip64Mode.Always).flatMap(mode -> 
Stream.of(0, 5, 8192)
+                .flatMap(size -> Stream.of(0, 1, 2).map(readMode -> 
Arguments.of(mode, size, readMode))));
+    }
+
+    /**
+     * Writes a STORED entry with known size and CRC.
+     *
+     * @param out the archive output stream.
+     * @param name the entry name.
+     * @param content the entry contents.
+     * @throws IOException if writing fails.
+     */
+    private static void writeEntry(final ZipArchiveOutputStream out, final 
String name, final byte[] content) throws IOException {
+        final CRC32 crc = new CRC32();
+        crc.update(content);
+        final ZipArchiveEntry entry = new ZipArchiveEntry(name);
+        entry.setMethod(ZipEntry.STORED);
+        entry.setSize(content.length);
+        entry.setCrc(crc.getValue());
+        entry.setTime(Instant.parse("2020-01-01T00:00:00Z").toEpochMilli());
+        out.putArchiveEntry(entry);
+        out.write(content);
+        out.closeArchiveEntry();
+    }
+
+    @ParameterizedTest
+    @CsvSource({ "Never, 0", "Never, 1", "Never, 2", "Always, 0", "Always, 1", 
"Always, 2" })
+    void testRejectsInconsistentNextEntryAfterReadingOrSkipping(final 
Zip64Mode zip64Mode, final int readMode) throws IOException {
+        final byte[] archive = createArchive(FIRST_CONTENT, zip64Mode);
+        final int secondHeaderOffset = getDataOffset(archive, 0) + 
FIRST_CONTENT.length;
+        setSizes(archive, secondHeaderOffset, zip64Mode, 
SECOND_CONTENT.length, SECOND_CONTENT.length + 1);
+        try (ZipArchiveInputStream in = 
ZipArchiveInputStream.builder().setByteArray(archive).get()) {
+            assertEquals("first.txt", in.getNextEntry().getName());
+            readFirstEntry(in, FIRST_CONTENT, readMode);
+            final ZipException ex = assertThrows(ZipException.class, 
in::getNextEntry);
+            assertEquals("Compressed and uncompressed size don't match for 
STORED entry second.txt", ex.getMessage());
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("mismatchedSizes")
+    void testRejectsInconsistentSizesAtHeader(final Zip64Mode zip64Mode, final 
long compressedSize, final long size) throws IOException {
+        final byte[] archive = createArchive(FIRST_CONTENT, zip64Mode);
+        setSizes(archive, 0, zip64Mode, compressedSize, size);
+        try (ZipArchiveInputStream in = 
ZipArchiveInputStream.builder().setByteArray(archive).get()) {
+            final ZipException ex = assertThrows(ZipException.class, 
in::getNextEntry);
+            assertEquals("Compressed and uncompressed size don't match for 
STORED entry first.txt", ex.getMessage());
+            assertEquals(getDataOffset(archive, 0), in.getBytesRead());
+        }
+    }
+
+    @Test
+    void testRejectsInconsistentStoredFixture() throws IOException {
+        // This fixture declares compressedSize=5 and size=10 without a data 
descriptor.
+        try (ZipArchiveInputStream in = 
ZipArchiveInputStream.builder().setURI(getURI("org/apache/commons/compress/zip/ZipFile-method.zip")).get())
 {
+            final ZipException ex = assertThrows(ZipException.class, 
in::getNextEntry);
+            assertTrue(ex.getMessage().startsWith("Compressed and uncompressed 
size don't match for STORED entry "));
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = { false, true })
+    void testSkipsEncryptedStoredEntry(final boolean 
supportStoredEntryDataDescriptor) throws IOException {
+        // Traditional ZIP encryption, password "review-password": secret.txt 
contains HELLO, followed by unencrypted b.txt containing WORLD.
+        try (ZipArchiveInputStream in = 
ZipArchiveInputStream.builder().setURI(getURI("zip-stored-encrypted.zip"))
+                
.setSupportStoredEntryDataDescriptor(supportStoredEntryDataDescriptor).get()) {
+            final ZipArchiveEntry entry = in.getNextEntry();
+            assertEquals("secret.txt", entry.getName());
+            assertEquals(ZipEntry.STORED, entry.getMethod());
+            assertTrue(entry.getGeneralPurposeBit().usesEncryption());
+            assertFalse(entry.getGeneralPurposeBit().usesDataDescriptor());
+            assertEquals(17, entry.getCompressedSize());
+            assertEquals(5, entry.getSize());
+            assertFalse(in.canReadEntryData(entry));
+            final UnsupportedZipFeatureException ex = 
assertThrows(UnsupportedZipFeatureException.class, in::read);
+            assertSame(UnsupportedZipFeatureException.Feature.ENCRYPTION, 
ex.getFeature());
+            assertEquals("b.txt", in.getNextEntry().getName());
+            assertArrayEquals("WORLD".getBytes(StandardCharsets.US_ASCII), 
IOUtils.toByteArray(in));
+            assertNull(in.getNextEntry());
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = { "bla-stored-dd.zip", "bla-stored-dd-nosig.zip" })
+    void testStoredDataDescriptorIgnoresLocalHeaderSizes(final String fixture) 
throws IOException {
+        final byte[] archive = Files.readAllBytes(getPath(fixture));
+        ZipLong.putLong(5, archive, 18);
+        ZipLong.putLong(3, archive, 22);
+        try (ZipArchiveInputStream in = 
ZipArchiveInputStream.builder().setByteArray(archive).setSupportStoredEntryDataDescriptor(true).get())
 {
+            final ZipArchiveEntry entry = in.getNextEntry();
+            assertNotNull(entry);
+            assertTrue(entry.getGeneralPurposeBit().usesDataDescriptor());
+            assertEquals(ArchiveEntry.SIZE_UNKNOWN, entry.getSize());
+            assertEquals(ArchiveEntry.SIZE_UNKNOWN, entry.getCompressedSize());
+            assertEquals(610, IOUtils.toByteArray(in).length);
+            assertEquals(610, entry.getSize());
+            assertEquals(610, entry.getCompressedSize());
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("validEntries")
+    void testValidEntryBoundaries(final Zip64Mode zip64Mode, final int size, 
final int readMode) throws IOException {
+        final byte[] content = new byte[size];
+        Arrays.fill(content, (byte) 'A');
+        final byte[] archive = createArchive(content, zip64Mode);
+        try (ZipArchiveInputStream in = 
ZipArchiveInputStream.builder().setByteArray(archive).get()) {
+            final ZipArchiveEntry entry = in.getNextEntry();
+            assertEquals("first.txt", entry.getName());
+            assertEquals(size, entry.getSize());
+            assertEquals(size, entry.getCompressedSize());
+            assertFalse(entry.getGeneralPurposeBit().usesDataDescriptor());
+            readFirstEntry(in, content, readMode);
+            assertEquals("second.txt", in.getNextEntry().getName());
+            assertArrayEquals(SECOND_CONTENT, IOUtils.toByteArray(in));
+            assertNull(in.getNextEntry());
+        }
+    }
+}
diff --git 
a/src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamTest.java
 
b/src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamTest.java
index 3bf3b7bab..697e98046 100644
--- 
a/src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamTest.java
+++ 
b/src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamTest.java
@@ -209,9 +209,10 @@ void testDecompressNextSymbol() throws IOException {
 
     @Test
     void testEmptyCentralDirectory() throws Exception {
-        try (ZipArchiveInputStream inputStream = 
ZipArchiveInputStream.builder()
-                
.setURI(getURI("org/apache/commons/compress/zip/ZipFile-method.zip"))
-                .get()) {
+        final byte[] zip = 
Files.readAllBytes(getPath("org/apache/commons/compress/zip/ZipFile-method.zip"));
+        // Correct this fixture's unrelated STORED size mismatch to keep 
testing its empty central directory.
+        ZipLong.putLong(ZipLong.getValue(zip, 18), zip, 22);
+        try (ZipArchiveInputStream inputStream = 
ZipArchiveInputStream.builder().setByteArray(zip).get()) {
             inputStream.forEach(IOConsumer.noop());
         }
     }
diff --git a/src/test/resources/zip-stored-encrypted.zip 
b/src/test/resources/zip-stored-encrypted.zip
new file mode 100644
index 000000000..f82d9bbbc
Binary files /dev/null and b/src/test/resources/zip-stored-encrypted.zip differ

Reply via email to