diff --git a/src/main/java/org/apache/commons/compress/archivers/zip/ExplodingInputStream.java b/src/main/java/org/apache/commons/compress/archivers/zip/ExplodingInputStream.java index 80899901e24..9c6c59a878a 100644 --- a/src/main/java/org/apache/commons/compress/archivers/zip/ExplodingInputStream.java +++ b/src/main/java/org/apache/commons/compress/archivers/zip/ExplodingInputStream.java @@ -136,6 +136,10 @@ private void fillBuffer() throws IOException { final int distance = distanceHigh << distanceLowSize | distanceLow; int length = lengthTree.read(bits); + if (length == -1) { + // end of stream reached in the length code, nothing left to decode + return; + } if (length == 63) { final long nextByte = bits.nextBits(8); if (nextByte == -1) { diff --git a/src/test/java/org/apache/commons/compress/archivers/zip/ExplodingInputStreamTest.java b/src/test/java/org/apache/commons/compress/archivers/zip/ExplodingInputStreamTest.java index ea6283a5624..2fed9e4d21b 100644 --- a/src/test/java/org/apache/commons/compress/archivers/zip/ExplodingInputStreamTest.java +++ b/src/test/java/org/apache/commons/compress/archivers/zip/ExplodingInputStreamTest.java @@ -19,8 +19,11 @@ package org.apache.commons.compress.archivers.zip; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.ByteArrayInputStream; + import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.compress.AbstractTest; import org.apache.commons.io.IOUtils; @@ -40,4 +43,22 @@ void testDecompress() throws Exception { assertEquals("a00c4f3f36515c96b2faef71c054e7f3e86a4f0f4ed4824cb7c5293bb455d28a", DigestUtils.sha256Hex(data)); } } + + /** + * Tests that a stream ending inside the length code of a back reference ends the data, without copying a byte from the empty dictionary. + */ + @Test + void testTruncatedBackReferenceLength() throws Exception { + // two Shannon-Fano trees, each: 64 values with a bit length of 6 + final byte[] tree = { 0x03, (byte) 0xF5, (byte) 0xF5, (byte) 0xF5, (byte) 0xF5 }; + final byte[] data = new byte[2 * tree.length + 2]; + System.arraycopy(tree, 0, data, 0, tree.length); + System.arraycopy(tree, 0, data, tree.length, tree.length); + // a back reference: flag bit 0, distance low bits 3, distance high code, then the end of the stream before the length code + data[2 * tree.length] = (byte) 0x86; + data[2 * tree.length + 1] = 0x00; + try (ExplodingInputStream in = new ExplodingInputStream(4096, 2, new ByteArrayInputStream(data))) { + assertArrayEquals(new byte[0], IOUtils.toByteArray(in)); + } + } }