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 1f6c16be7 [7-Zip] Enforce memory limits on decoded headers (f007) 
(#863)
1f6c16be7 is described below

commit 1f6c16be790521bbfec1c21181318d52c6e1fa3d
Author: Gary Gregory <[email protected]>
AuthorDate: Wed Dec 2 14:30:51 2026 -0500

    [7-Zip] Enforce memory limits on decoded headers (f007) (#863)
    
    Check decoded header sizes before creating decoders, rounding up to KiB.
    Close archive channels on I/O failures during construction.
    
    Add regression tests for size boundaries, early rejection, and channel
    cleanup. Update Javadoc, user documentation.
---
 src/changes/changes.xml                            |   1 +
 .../compress/archivers/sevenz/SevenZFile.java      |  10 +-
 src/site/xdoc/examples.xml                         |   5 +-
 .../archivers/sevenz/SevenZEncodedHeaderTest.java  | 233 +++++++++++++++++++++
 4 files changed, 245 insertions(+), 4 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 37c2c3090..498dbbba7 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -68,6 +68,7 @@ The <action> type attribute can be add,update,fix,remove.
       <action type="fix" dev="ggregory" due-to="Gary Gregory">[7-Zip] 
SevenZMethodConfiguration now throws ArchiveException instead of 
IllegalArgumetException/IllegalStateException.</action>
       <action type="fix" dev="ggregory" due-to="Gary Gregory">[7-Zip] 
SevenZOutputFile now throws ArchiveException instead of 
IllegalArgumetException/IllegalStateException.</action>
       <action type="fix" dev="ggregory" due-to="Claude Security, Gary 
Gregory">[7-Zip] Correct substream memory accounting, enforce the configured 
memory limit, and reject missing substream sizes.</action>
+      <action type="fix" dev="ggregory" due-to="Claude Security, Gary 
Gregory">[7-Zip] Enforce the configured memory limit on decoded header sizes 
before creating decoders, and close archive channels on I/O failures during 
construction.</action>
       <!-- FIX bzip2 -->
       <action type="fix" dev="ggregory" due-to="Tyler Nighswander, Gary 
Gregory">[BZip2] BZip2CompressorInputStream now throws CompressorException 
instead of IllegalArgumetException/IllegalStateException.</action>
       <action type="fix" dev="pkarwasz" due-to="Tyler Nighswander, Piotr P. 
Karwasz">[BZip2] BZip2 input streams treat Huffman codes longer than 20 bits as 
corrupted data, matching the behavior of the reference implementation.</action>
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZFile.java 
b/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZFile.java
index 38a667abb..a04179321 100644
--- a/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZFile.java
+++ b/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZFile.java
@@ -174,8 +174,8 @@ public String toString() {
      * </p>
      *
      * <p>
-     * Archive metadata usage is estimated, including the arrays holding 
substream sizes, CRCs, and CRC flags. The limit is not an exact bound on total 
JVM heap
-     * usage.
+     * Archive metadata usage is estimated, including the arrays holding 
substream sizes, CRCs, and CRC flags. Since 1.29.0, the declared decoded header 
size
+     * is also checked against the limit before creating its decoders, 
regardless of the codec. The limit is not an exact bound on total JVM heap 
usage.
      * </p>
      *
      * @since 1.26.0
@@ -644,6 +644,8 @@ private SevenZFile(final Builder builder) throws 
IOException {
             final byte[] password = builder.password;
             archive = readHeaders(password);
             this.password = password != null ? Arrays.copyOf(password, 
password.length) : null;
+        } catch (final IOException e) {
+            throw IOUtils.closeQuietlySuppress(channel, e);
         } catch (final ArithmeticException | IllegalArgumentException e) {
             throw IOUtils.closeQuietlySuppress(channel, new 
ArchiveException(e));
         }
@@ -1420,6 +1422,9 @@ private ByteBuffer readEncodedHeader(final ByteBuffer 
header, final Archive arch
         }
         // FIXME: merge with buildDecodingStream()/buildDecoderStack() at some 
stage?
         final Folder folder = archive.folders[0];
+        final int unpackSize = toNonNegativeInt("header", 
folder.getUnpackSize());
+        // Check the decoded header size, rounded up to KiB, before allocating 
decoder buffers.
+        MemoryLimitException.checkKiB((unpackSize + 1023L) / 1024, 
maxMemoryLimitKiB);
         final int firstPackStreamIndex = 0;
         final long folderOffset = SIGNATURE_HEADER_SIZE + archive.packPos;
         channel.position(folderOffset);
@@ -1441,7 +1446,6 @@ private ByteBuffer readEncodedHeader(final ByteBuffer 
header, final Archive arch
                     .get();
             // @formatter:on
         }
-        final int unpackSize = toNonNegativeInt("header", 
folder.getUnpackSize());
         final byte[] nextHeader = 
org.apache.commons.compress.utils.IOUtils.readRange(inputStreamStack, 
unpackSize);
         if (nextHeader.length < unpackSize) {
             throw new ArchiveException("Premature end of stream");
diff --git a/src/site/xdoc/examples.xml b/src/site/xdoc/examples.xml
index 03aaea472..78c5a8ddc 100644
--- a/src/site/xdoc/examples.xml
+++ b/src/site/xdoc/examples.xml
@@ -123,7 +123,10 @@ CompressorInputStream input = new CompressorStreamFactory()
         <p>Since Compress 1.19 <code>SevenZFile</code> also has an
         optional constructor to pass an upper memory limit which is supported
         in LZMA compressed streams. Since Compress 1.21 this setting
-        also is taken into account when reading the metadata of an archive.</p>
+        also is taken into account when reading the metadata of an archive.
+        Since 1.29.0, the declared decoded header size, rounded up to KiB, is
+        checked against this limit before creating the header decoders, 
regardless
+        of their codec. The limit is not an exact bound on total JVM heap 
usage.</p>
         <p>For the Snappy and LZ4 formats the amount of memory used
         during compression is directly proportional to the window
         size.</p>
diff --git 
a/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZEncodedHeaderTest.java
 
b/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZEncodedHeaderTest.java
new file mode 100644
index 000000000..6d0c2f697
--- /dev/null
+++ 
b/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZEncodedHeaderTest.java
@@ -0,0 +1,233 @@
+/*
+ * 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.sevenz;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.channels.SeekableByteChannel;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.zip.CRC32;
+
+import org.apache.commons.compress.AbstractTest;
+import org.apache.commons.compress.MemoryLimitException;
+import org.apache.commons.compress.archivers.ArchiveException;
+import org.apache.commons.io.channels.ByteArraySeekableByteChannel;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Tests decoded header memory limits and channel cleanup during archive 
construction.
+ */
+class SevenZEncodedHeaderTest extends AbstractTest {
+
+    private static final int MEMORY_LIMIT_KIB = 256;
+    private static final int HEADER_SIZE = MEMORY_LIMIT_KIB * 1024;
+
+    /**
+     * Builds an archive whose encoded header has the supplied contents and 
declared size.
+     *
+     * @param method     the header codec.
+     * @param decoded    the decoded header bytes.
+     * @param unpackSize the declared decoded header size.
+     * @return the archive bytes.
+     * @throws IOException if encoding fails.
+     */
+    private static byte[] archive(final SevenZMethod method, final byte[] 
decoded, final int unpackSize) throws IOException {
+        final Object options = method == SevenZMethod.LZMA || method == 
SevenZMethod.LZMA2 ? Integer.valueOf(64 * 1024) : null;
+        final UnsynchronizedByteArrayOutputStream packed = 
UnsynchronizedByteArrayOutputStream.builder().get();
+        try (OutputStream encoder = Coders.addEncoder(packed, method, 
options)) {
+            encoder.write(decoded);
+        }
+        final byte[] data = packed.toByteArray();
+        final byte[] properties = 
Coders.findByMethod(method).getOptionsAsProperties(options);
+        final byte[] methodId = method.getId();
+        final UnsynchronizedByteArrayOutputStream header = 
UnsynchronizedByteArrayOutputStream.builder().get();
+        header.write(NID.kEncodedHeader);
+        header.write(NID.kPackInfo);
+        header.write(0); // packPos
+        header.write(1); // one packed stream
+        header.write(NID.kSize);
+        writeUint64(header, data.length);
+        header.write(NID.kEnd);
+        header.write(NID.kUnpackInfo);
+        header.write(NID.kFolder);
+        header.write(1); // one folder
+        header.write(0); // not external
+        header.write(1); // one coder
+        header.write(methodId.length | (properties.length == 0 ? 0 : 0x20));
+        header.write(methodId);
+        if (properties.length != 0) {
+            writeUint64(header, properties.length);
+            header.write(properties);
+        }
+        header.write(NID.kCodersUnpackSize);
+        writeUint64(header, unpackSize);
+        header.write(NID.kCRC);
+        header.write(1); // folder CRC defined
+        
header.write(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(crc32(decoded)).array());
+        header.write(NID.kEnd);
+        header.write(NID.kEnd);
+        final byte[] encoded = header.toByteArray();
+        final ByteBuffer start = 
ByteBuffer.allocate(20).order(ByteOrder.LITTLE_ENDIAN);
+        
start.putLong(data.length).putLong(encoded.length).putInt(crc32(encoded));
+        final ByteBuffer result = ByteBuffer.allocate(32 + data.length + 
encoded.length).order(ByteOrder.LITTLE_ENDIAN);
+        result.put(SevenZFile.SIGNATURE).put((byte) 0).put((byte) 
4).putInt(crc32(start.array()));
+        result.put(start.array()).put(data).put(encoded);
+        return result.array();
+    }
+
+    private static int crc32(final byte[] bytes) {
+        final CRC32 crc = new CRC32();
+        crc.update(bytes);
+        return (int) crc.getValue();
+    }
+
+    /**
+     * Builds an empty archive header with zero padding to reach the requested 
size.
+     *
+     * @param size the header size, at least 15 bytes.
+     * @return the decoded header bytes.
+     */
+    private static byte[] decodedHeader(final int size) {
+        final UnsynchronizedByteArrayOutputStream header = 
UnsynchronizedByteArrayOutputStream.builder().get();
+        header.write(NID.kHeader);
+        header.write(NID.kFilesInfo);
+        header.write(0); // no files
+        header.write(NID.kDummy);
+        // Four leading bytes, nine size bytes, and two end markers.
+        writeUint64(header, size - 15);
+        header.write(new byte[size - 15], 0, size - 15);
+        header.write(NID.kEnd);
+        header.write(NID.kEnd);
+        return header.toByteArray();
+    }
+
+    private static void writeUint64(final UnsynchronizedByteArrayOutputStream 
out, final long value) {
+        out.write(0xff);
+        for (int i = 0; i < Long.BYTES; i++) {
+            out.write((int) (value >>> (i * Byte.SIZE)) & 0xff);
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(value = SevenZMethod.class, names = {"COPY", "LZMA", "LZMA2", 
"DEFLATE"})
+    void testDefaultLimit(final SevenZMethod method) throws IOException {
+        final byte[] bytes = archive(method, decodedHeader(HEADER_SIZE + 1), 
HEADER_SIZE + 1);
+        try (SevenZFile file = 
SevenZFile.builder().setChannel(ByteArraySeekableByteChannel.wrap(bytes)).get())
 {
+            assertNull(file.getNextEntry());
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(value = SevenZMethod.class, names = {"COPY", "LZMA", "LZMA2", 
"DEFLATE"})
+    void testHeaderAtLimit(final SevenZMethod method) throws IOException {
+        final byte[] bytes = archive(method, decodedHeader(HEADER_SIZE), 
HEADER_SIZE);
+        try (ByteArraySeekableByteChannel channel = 
ByteArraySeekableByteChannel.wrap(bytes)) {
+            try (SevenZFile file = 
SevenZFile.builder().setChannel(channel).setMaxMemoryLimitKiB(MEMORY_LIMIT_KIB).get())
 {
+                assertNull(file.getNextEntry());
+                assertTrue(channel.isOpen());
+            }
+            assertFalse(channel.isOpen());
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(value = SevenZMethod.class, names = {"COPY", "LZMA", "LZMA2", 
"DEFLATE"})
+    void testHeaderOverLimitBeforeReadingPackedData(final SevenZMethod method) 
throws IOException {
+        final byte[] bytes = archive(method, decodedHeader(HEADER_SIZE + 1), 
HEADER_SIZE + 1);
+        final long packedEnd = 32 + 
ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getLong(12);
+        try (ByteArraySeekableByteChannel channel = new 
ByteArraySeekableByteChannel() {
+            @Override
+            public int read(final ByteBuffer dst) throws IOException {
+                assertTrue(position() < 32 || position() >= packedEnd, "Must 
reject the header before reading packed data");
+                return super.read(dst);
+            }
+        }) {
+            channel.write(ByteBuffer.wrap(bytes));
+            channel.position(0);
+            final MemoryLimitException exception = 
assertThrows(MemoryLimitException.class,
+                    () -> 
SevenZFile.builder().setChannel(channel).setMaxMemoryLimitKiB(MEMORY_LIMIT_KIB).get().close());
+            assertEquals(MEMORY_LIMIT_KIB + 1, 
exception.getMemoryNeededInKb());
+            assertEquals(MEMORY_LIMIT_KIB, 
exception.getMemoryLimitInKiBLong());
+            assertFalse(channel.isOpen());
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = {1, 1023, 1024, HEADER_SIZE})
+    void testHeaderSizeRoundsUp(final int extraBytes) throws IOException {
+        final int size = HEADER_SIZE + extraBytes;
+        final byte[] bytes = archive(SevenZMethod.LZMA, decodedHeader(size), 
size);
+        final int neededKiB = (size + 1023) / 1024;
+        try (ByteArraySeekableByteChannel channel = 
ByteArraySeekableByteChannel.wrap(bytes)) {
+            final MemoryLimitException exception = 
assertThrows(MemoryLimitException.class,
+                    () -> 
SevenZFile.builder().setChannel(channel).setMaxMemoryLimitKiB(MEMORY_LIMIT_KIB).get().close());
+            assertEquals(neededKiB, exception.getMemoryNeededInKb());
+            assertEquals(MEMORY_LIMIT_KIB, 
exception.getMemoryLimitInKiBLong());
+            assertFalse(channel.isOpen());
+        }
+        try (SevenZFile file = 
SevenZFile.builder().setChannel(ByteArraySeekableByteChannel.wrap(bytes)).setMaxMemoryLimitKiB(neededKiB).get())
 {
+            assertNull(file.getNextEntry());
+        }
+    }
+
+    @Test
+    void testInvalidArchiveClosesChannel() throws IOException {
+        try (ByteArraySeekableByteChannel channel = 
ByteArraySeekableByteChannel.wrap(new byte[32])) {
+            assertThrows(ArchiveException.class, () -> 
SevenZFile.builder().setChannel(channel).get().close());
+            assertFalse(channel.isOpen());
+        }
+    }
+
+    @Test
+    void testLargestDeclaredHeader() throws IOException {
+        // A tiny packed stream is sufficient: the declared size must be 
rejected before decoding it.
+        final byte[] bytes = archive(SevenZMethod.LZMA, decodedHeader(16), 
Integer.MAX_VALUE);
+        try (ByteArraySeekableByteChannel channel = 
ByteArraySeekableByteChannel.wrap(bytes)) {
+            final MemoryLimitException exception = 
assertThrows(MemoryLimitException.class,
+                    () -> 
SevenZFile.builder().setChannel(channel).setMaxMemoryLimitKiB(MEMORY_LIMIT_KIB).get().close());
+            assertEquals(2_097_152, exception.getMemoryNeededInKb());
+            assertEquals(MEMORY_LIMIT_KIB, 
exception.getMemoryLimitInKiBLong());
+            assertFalse(channel.isOpen());
+        }
+    }
+
+    @Test
+    void testRejectedHeaderClosesFileChannel() throws IOException {
+        final Path path = createTempPath("encoded-header", ".7z");
+        Files.write(path, archive(SevenZMethod.LZMA, decodedHeader(HEADER_SIZE 
+ 1), HEADER_SIZE + 1));
+        try (SeekableByteChannel channel = Files.newByteChannel(path)) {
+            assertThrows(MemoryLimitException.class, () -> 
SevenZFile.builder().setChannel(channel).setMaxMemoryLimitKiB(MEMORY_LIMIT_KIB).get().close());
+            assertFalse(channel.isOpen());
+        }
+    }
+}

Reply via email to