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 2131ffcf3 Implemented signature validation in ZipFile (#868) (f011)
2131ffcf3 is described below
commit 2131ffcf3b1054ad9f5708c7195e174b2e72b104
Author: Gary Gregory <[email protected]>
AuthorDate: Thu Dec 3 19:31:52 2026 -0500
Implemented signature validation in ZipFile (#868) (f011)
Using one reusable 30-byte header buffer.
Added regression test cases covering corrupt signatures, deferred/raw
access, copying, cleanup, truncation, ZIP64, preambles, and split
boundaries. Javadoc and release notes describe the behavior and its
limits, including continued acceptance of overlapping entries.
---
src/changes/changes.xml | 1 +
.../commons/compress/archivers/zip/ZipFile.java | 53 ++-
.../archivers/zip/ZipFileLocalFileHeaderTest.java | 453 +++++++++++++++++++++
3 files changed, 494 insertions(+), 13 deletions(-)
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index fcafaf32c..509d14d8a 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -101,6 +101,7 @@ The <action> type attribute can be add,update,fix,remove.
<action type="fix" dev="ggregory" due-to="KALI 834X, Gary Gregory">[Zip]
Reject negative ZIP64 offsets in positionAtCentralDirectory64 (#794).</action>
<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>
<!-- 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/ZipFile.java
b/src/main/java/org/apache/commons/compress/archivers/zip/ZipFile.java
index bf197ae3f..dc549b236 100644
--- a/src/main/java/org/apache/commons/compress/archivers/zip/ZipFile.java
+++ b/src/main/java/org/apache/commons/compress/archivers/zip/ZipFile.java
@@ -88,6 +88,11 @@
* <li>getEntries and getEntry return {@code
org.apache.commons.compress.archivers.zip.ZipArchiveEntry} instances.</li>
* <li>close is allowed to throw IOException.</li>
* </ul>
+ *
+ * <p>
+ * Local file header signatures are checked when resolving entry data offsets.
This check does not reject overlapping entries or verify the CRC of their
+ * contents, and does not guarantee that a sequential reader such as {@link
ZipArchiveInputStream} exposes the same entries.
+ * </p>
*/
public class ZipFile implements ArchiveFile<ZipArchiveEntry> {
@@ -167,6 +172,13 @@ String getName() {
/**
* Sets whether to ignore information stored inside the local file
header.
*
+ * <p>
+ * When {@code true}, local file headers are not read while opening
the archive. Their signatures and lengths are still read when an entry's data
+ * offset is first needed, including by {@link
ZipFile#getInputStream(ZipArchiveEntry)}, {@link
ZipFile#getRawInputStream(ZipArchiveEntry)}, and
+ * {@link ZipFile#copyRawEntries(ZipArchiveOutputStream,
ZipArchiveEntryPredicate)}. An invalid signature causes an {@link
ArchiveException} at that
+ * point. When {@code false}, an invalid signature causes {@link
#get()} to fail instead.
+ * </p>
+ *
* @param ignoreLocalFileHeader whether to ignore information stored
inside.
* @return {@code this} instance.
*/
@@ -488,7 +500,7 @@ public long getUncompressedCount() {
/**
* Number of bytes in local file header up to the "length of file
name" entry.
*/
- private static final long LFH_OFFSET_FOR_FILENAME_LENGTH =
+ private static final int LFH_OFFSET_FOR_FILENAME_LENGTH =
// @formatter:off
/* local file header signature */ ZipConstants.WORD
/* version needed to extract */ + ZipConstants.SHORT
@@ -498,9 +510,14 @@ public long getUncompressedCount() {
/* last mod file date */ + ZipConstants.SHORT
/* CRC-32 */ + ZipConstants.WORD
/* compressed size */ + ZipConstants.WORD
- /* uncompressed size */ + (long) ZipConstants.WORD;
+ /* uncompressed size */ + ZipConstants.WORD;
// @formatter:on
+ /**
+ * Length of the fixed part of a local file header, including the file
name and extra field lengths.
+ */
+ private static final int LFH_LEN = LFH_OFFSET_FOR_FILENAME_LENGTH +
ZipConstants.SHORT + ZipConstants.SHORT;
+
/**
* Compares two ZipArchiveEntries based on their offset within the archive.
* <p>
@@ -745,6 +762,11 @@ private static boolean tryToLocateSignature(final
SeekableByteChannel channel, f
private final byte[] cfhBuf = new byte[CFH_LEN];
+ /**
+ * Reusable storage for the fixed part of a local file header.
+ */
+ private final byte[] lfhBuf = new byte[LFH_LEN];
+
private final byte[] shortBuf = new byte[ZipConstants.SHORT];
private final ByteBuffer dwordBbuf = ByteBuffer.wrap(dwordBuf);
@@ -753,6 +775,11 @@ private static boolean tryToLocateSignature(final
SeekableByteChannel channel, f
private final ByteBuffer cfhBbuf = ByteBuffer.wrap(cfhBuf);
+ /**
+ * Channel read buffer backed by {@link #lfhBuf}.
+ */
+ private final ByteBuffer lfhBbuf = ByteBuffer.wrap(lfhBuf);
+
private final ByteBuffer shortBbuf = ByteBuffer.wrap(shortBuf);
private final IOFunction<InputStream, InputStream> zstdInputStreamFactory;
@@ -1658,20 +1685,20 @@ private void sanityCheckLFHOffset(final ZipArchiveEntry
entry) throws IOExceptio
private int[] setDataOffset(final ZipArchiveEntry entry) throws
IOException {
long offset = entry.getLocalHeaderOffset();
if (isSplitZipArchive) {
- ((ZipSplitReadOnlySeekableByteChannel)
archive).position(entry.getDiskNumberStart(), offset +
LFH_OFFSET_FOR_FILENAME_LENGTH);
+ ((ZipSplitReadOnlySeekableByteChannel)
archive).position(entry.getDiskNumberStart(), offset);
// the offset should be updated to the global offset
- offset = archive.position() - LFH_OFFSET_FOR_FILENAME_LENGTH;
+ offset = archive.position();
} else {
- archive.position(offset + LFH_OFFSET_FOR_FILENAME_LENGTH);
+ archive.position(offset);
}
- wordBbuf.rewind();
- IOUtils.readFully(archive, wordBbuf);
- wordBbuf.flip();
- wordBbuf.get(shortBuf);
- final int fileNameLen = ZipShort.getValue(shortBuf);
- wordBbuf.get(shortBuf);
- final int extraFieldLen = ZipShort.getValue(shortBuf);
- entry.setDataOffset(offset + LFH_OFFSET_FOR_FILENAME_LENGTH +
ZipConstants.SHORT + ZipConstants.SHORT + fileNameLen + extraFieldLen);
+ lfhBbuf.rewind();
+ IOUtils.readFully(archive, lfhBbuf);
+ if (ZipLong.getValue(lfhBuf) != ZipLong.LFH_SIG.getValue()) {
+ throw new ArchiveException("Local file header signature not found
at offset %,d for entry '%s'", entry.getLocalHeaderOffset(), entry.getName());
+ }
+ final int fileNameLen = ZipShort.getValue(lfhBuf,
LFH_OFFSET_FOR_FILENAME_LENGTH);
+ final int extraFieldLen = ZipShort.getValue(lfhBuf,
LFH_OFFSET_FOR_FILENAME_LENGTH + ZipConstants.SHORT);
+ entry.setDataOffset(offset + LFH_LEN + fileNameLen + extraFieldLen);
if (entry.getDataOffset() + entry.getCompressedSize() >
centralDirectoryStartOffset) {
throw new ArchiveException("Data for '%s' overlaps with central
directory.", entry.getName());
}
diff --git
a/src/test/java/org/apache/commons/compress/archivers/zip/ZipFileLocalFileHeaderTest.java
b/src/test/java/org/apache/commons/compress/archivers/zip/ZipFileLocalFileHeaderTest.java
new file mode 100644
index 000000000..125dd5566
--- /dev/null
+++
b/src/test/java/org/apache/commons/compress/archivers/zip/ZipFileLocalFileHeaderTest.java
@@ -0,0 +1,453 @@
+/*
+ * 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 java.nio.charset.StandardCharsets.UTF_8;
+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.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.zip.CRC32;
+import java.util.zip.ZipException;
+import java.util.zip.ZipInputStream;
+
+import org.apache.commons.compress.AbstractTempDirTest;
+import org.apache.commons.compress.archivers.ArchiveException;
+import org.apache.commons.compress.archivers.EntryStreamOffsets;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.io.channels.ByteArraySeekableByteChannel;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Tests local file header validation and its limits independently of central
directory parsing.
+ */
+class ZipFileLocalFileHeaderTest extends AbstractTempDirTest {
+
+ private static final String FIRST_NAME = "first.txt";
+ private static final String SECOND_NAME = "second-\u00e9.txt";
+ private static final byte[] EXTRA = { 13, (byte) 240, 3, 0, 1, 2, 3 };
+
+ /**
+ * Checks the extracted bytes and their recorded CRC.
+ */
+ private static void assertContent(final ZipFile zip, final String name,
final byte[] expected) throws IOException {
+ final ZipArchiveEntry entry = zip.getEntry(name);
+ assertNotNull(entry);
+ try (InputStream in = zip.getInputStream(entry)) {
+ final byte[] actual = IOUtils.toByteArray(in);
+ assertArrayEquals(expected, actual);
+ assertEquals(crc(actual), entry.getCrc());
+ }
+ }
+
+ /**
+ * Gets the central directory offset from a non-ZIP64 archive's end record.
+ */
+ private static int centralDirectoryOffset(final byte[] data) {
+ return Math.toIntExact(ZipLong.getValue(data, data.length - 22 + 16));
+ }
+
+ /**
+ * Creates an archive with a central directory entry pointing into another
STORED entry's payload.
+ */
+ private static byte[] createOverlappingZip(final boolean validSignature)
throws IOException {
+ final byte[] inner = createZip("inner.txt", "nested
content".getBytes(UTF_8));
+ final int innerCentralOffset = centralDirectoryOffset(inner);
+ final byte[] embeddedHeaderAndData = Arrays.copyOf(inner,
innerCentralOffset);
+ if (!validSignature) {
+ embeddedHeaderAndData[0] ^= 1;
+ }
+ // Recompute the outer CRC after corrupting the embedded signature, so
both entries retain correct CRCs.
+ final byte[] outer = createZip("outer.txt", embeddedHeaderAndData);
+ final byte[] innerCentralHeader = Arrays.copyOfRange(inner,
innerCentralOffset, inner.length - 22);
+ ZipLong.putLong(dataOffset(outer, 0), innerCentralHeader, 42);
+ final byte[] end = Arrays.copyOfRange(outer, outer.length - 22,
outer.length);
+ ZipShort.putShort(2, end, 8);
+ ZipShort.putShort(2, end, 10);
+ ZipLong.putLong(ZipLong.getValue(end, 12) + innerCentralHeader.length,
end, 12);
+ final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ bytes.write(outer, 0, outer.length - 22);
+ bytes.write(innerCentralHeader);
+ bytes.write(end);
+ return bytes.toByteArray();
+ }
+
+ /**
+ * Splits a two-entry archive so the first entry's data crosses disks and
the second header starts at offset three on disk one.
+ */
+ private static ZipSplitReadOnlySeekableByteChannel
createSplitChannel(final byte[] source) throws IOException {
+ return createSplitChannel(source, -3);
+ }
+
+ /**
+ * Splits an archive at the given offset relative to its second local file
header.
+ */
+ private static ZipSplitReadOnlySeekableByteChannel
createSplitChannel(final byte[] source, final int relativeSplitOffset) throws
IOException {
+ final byte[] data = source.clone();
+ final int centralOffset = centralDirectoryOffset(data);
+ final int secondCentralOffset = centralOffset + 46 +
ZipShort.getValue(data, centralOffset + 28)
+ + ZipShort.getValue(data, centralOffset + 30) +
ZipShort.getValue(data, centralOffset + 32);
+ final int secondHeaderOffset = Math.toIntExact(ZipLong.getValue(data,
secondCentralOffset + 42));
+ final int splitOffset = secondHeaderOffset + relativeSplitOffset;
+ ZipLong.putLong(ZipLong.getValue(data, centralOffset + 42) + 4, data,
centralOffset + 42);
+ ZipShort.putShort(relativeSplitOffset <= 0 ? 1 : 0, data,
secondCentralOffset + 34);
+ ZipLong.putLong(relativeSplitOffset <= 0 ? -relativeSplitOffset :
secondHeaderOffset + 4, data, secondCentralOffset + 42);
+ final int endOffset = data.length - 22;
+ ZipShort.putShort(1, data, endOffset + 4);
+ ZipShort.putShort(1, data, endOffset + 6);
+ ZipLong.putLong(centralOffset - splitOffset, data, endOffset + 16);
+ final ByteArrayOutputStream first = new ByteArrayOutputStream();
+ first.write(ZipLong.DD_SIG.getBytes());
+ first.write(data, 0, splitOffset);
+ return new
ZipSplitReadOnlySeekableByteChannel(Arrays.asList(ByteArraySeekableByteChannel.wrap(first.toByteArray()),
+ ByteArraySeekableByteChannel.wrap(Arrays.copyOfRange(data,
splitOffset, data.length))));
+ }
+
+ /**
+ * Creates two entries with extra fields and different file name lengths.
+ */
+ private static byte[] createZip(final int method, final Zip64Mode zip64)
throws IOException {
+ final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ try (ZipArchiveOutputStream out = new ZipArchiveOutputStream(bytes)) {
+ out.setMethod(method);
+ out.setUseZip64(zip64);
+ writeEntry(out, FIRST_NAME, FIRST_NAME.getBytes(UTF_8));
+ writeEntry(out, SECOND_NAME, SECOND_NAME.getBytes(UTF_8));
+ }
+ return bytes.toByteArray();
+ }
+
+ /**
+ * Creates one STORED entry with an extra field.
+ */
+ private static byte[] createZip(final String name, final byte[] content)
throws IOException {
+ final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ try (ZipArchiveOutputStream out = new ZipArchiveOutputStream(bytes)) {
+ out.setMethod(ZipArchiveOutputStream.STORED);
+ out.setUseZip64(Zip64Mode.Never);
+ writeEntry(out, name, content);
+ }
+ return bytes.toByteArray();
+ }
+
+ /**
+ * Computes the CRC for an entry's content.
+ */
+ private static long crc(final byte[] content) {
+ final CRC32 crc = new CRC32();
+ crc.update(content);
+ return crc.getValue();
+ }
+
+ /**
+ * Gets the expected data offset directly from a fixture's local header
lengths.
+ */
+ private static int dataOffset(final byte[] data, final int headerOffset) {
+ return headerOffset + 30 + ZipShort.getValue(data, headerOffset + 26)
+ ZipShort.getValue(data, headerOffset + 28);
+ }
+
+ /**
+ * Gets an entry's header offset without reading its local header.
+ */
+ private static int localHeaderOffset(final byte[] data, final String name)
throws IOException {
+ try (ZipFile zip =
ZipFile.builder().setByteArray(data).setIgnoreLocalFileHeader(true).get()) {
+ return Math.toIntExact(zip.getEntry(name).getLocalHeaderOffset());
+ }
+ }
+
+ /**
+ * Writes an entry with known size and CRC so STORED and DEFLATED fixtures
share the same content.
+ */
+ private static void writeEntry(final ZipArchiveOutputStream out, final
String name, final byte[] content) throws IOException {
+ final ZipArchiveEntry entry = new ZipArchiveEntry(name);
+ entry.setSize(content.length);
+ entry.setCrc(crc(content));
+ entry.setExtra(EXTRA);
+ out.putArchiveEntry(entry);
+ out.write(content);
+ out.closeArchiveEntry();
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = { 0, 1, 2, 3 })
+ void testCorruptSignatureClosesChannelDuringOpen(final int signatureByte)
throws IOException {
+ for (final String name : new String[] { FIRST_NAME, SECOND_NAME }) {
+ final byte[] data = createZip(ZipArchiveOutputStream.STORED,
Zip64Mode.Never);
+ final int offset = localHeaderOffset(data, name);
+ data[offset + signatureByte] ^= 1;
+ try (ByteArraySeekableByteChannel channel =
ByteArraySeekableByteChannel.wrap(data)) {
+ final ArchiveException exception =
assertThrows(ArchiveException.class, () ->
ZipFile.builder().setChannel(channel).get());
+ assertEquals("Local file header signature not found at offset
" + offset + " for entry '" + name + "'", exception.getMessage());
+ assertFalse(channel.isOpen());
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = { 0, 1, 2, 3 })
+ void testCorruptSignatureIsCheckedOnEveryFailedDeferredAccess(final int
signatureByte) throws IOException {
+ final byte[] data = createZip(ZipArchiveOutputStream.STORED,
Zip64Mode.Never);
+ data[localHeaderOffset(data, SECOND_NAME) + signatureByte] ^= 1;
+ try (ByteArraySeekableByteChannel channel =
ByteArraySeekableByteChannel.wrap(data);
+ ZipFile zip =
ZipFile.builder().setChannel(channel).setIgnoreLocalFileHeader(true).get()) {
+ assertEquals(2, zip.stream().count());
+ final ZipArchiveEntry entry = zip.getEntry(SECOND_NAME);
+ for (int retry = 0; retry < 2; retry++) {
+ assertThrows(ArchiveException.class, () ->
zip.getInputStream(entry));
+ assertThrows(ArchiveException.class, () ->
zip.getRawInputStream(entry));
+ assertEquals(EntryStreamOffsets.OFFSET_UNKNOWN,
entry.getDataOffset());
+ }
+ assertTrue(channel.isOpen());
+ assertContent(zip, FIRST_NAME, FIRST_NAME.getBytes(UTF_8));
+ }
+ }
+
+ @Test
+ void testDeferredRawCopyValidatesOnlySelectedEntries() throws IOException {
+ final byte[] data = createZip(ZipArchiveOutputStream.STORED,
Zip64Mode.Never);
+ data[localHeaderOffset(data, SECOND_NAME)] ^= 1;
+ final ByteArrayOutputStream copied = new ByteArrayOutputStream();
+ try (ZipFile zip =
ZipFile.builder().setByteArray(data).setIgnoreLocalFileHeader(true).get();
+ ZipArchiveOutputStream out = new
ZipArchiveOutputStream(copied)) {
+ zip.copyRawEntries(out, entry ->
FIRST_NAME.equals(entry.getName()));
+ assertThrows(ArchiveException.class, () -> zip.copyRawEntries(out,
entry -> SECOND_NAME.equals(entry.getName())));
+ }
+ try (ZipFile zip =
ZipFile.builder().setByteArray(copied.toByteArray()).get()) {
+ assertEquals(1, zip.stream().count());
+ assertContent(zip, FIRST_NAME, FIRST_NAME.getBytes(UTF_8));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void testEmptyArchiveNeedsNoLocalHeader(final boolean
ignoreLocalFileHeader) throws IOException {
+ final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ try (ZipArchiveOutputStream out = new ZipArchiveOutputStream(bytes)) {
+ out.finish();
+ }
+ try (ZipFile zip =
ZipFile.builder().setByteArray(bytes.toByteArray()).setIgnoreLocalFileHeader(ignoreLocalFileHeader).get())
{
+ assertEquals(0, zip.stream().count());
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void testEmptyEntryStillRequiresSignature(final boolean
ignoreLocalFileHeader) throws IOException {
+ final byte[] data = createZip(FIRST_NAME, new byte[0]);
+ try (ZipFile zip =
ZipFile.builder().setByteArray(data).setIgnoreLocalFileHeader(ignoreLocalFileHeader).get())
{
+ assertContent(zip, FIRST_NAME, new byte[0]);
+ }
+ data[0] ^= 1;
+ if (ignoreLocalFileHeader) {
+ try (ZipFile zip =
ZipFile.builder().setByteArray(data).setIgnoreLocalFileHeader(true).get()) {
+ assertThrows(ArchiveException.class, () ->
zip.getInputStream(zip.getEntry(FIRST_NAME)));
+ }
+ } else {
+ assertThrows(ArchiveException.class, () ->
ZipFile.builder().setByteArray(data).get());
+ }
+ }
+
+ @Test
+ void testJdkAlsoRejectsBadSignatureWhenReadingEntry() throws IOException {
+ final byte[] data = createZip(ZipArchiveOutputStream.STORED,
Zip64Mode.Never);
+ data[localHeaderOffset(data, SECOND_NAME)] ^= 1;
+ final Path path = createTempPath("local-header", ".zip");
+ Files.write(path, data);
+ try (java.util.zip.ZipFile zip = new
java.util.zip.ZipFile(path.toFile())) {
+ // The JDK can still open and list the archive and read an
unaffected entry.
+ assertEquals(2, zip.size());
+ try (InputStream in =
zip.getInputStream(zip.getEntry(FIRST_NAME))) {
+ assertArrayEquals(FIRST_NAME.getBytes(UTF_8),
IOUtils.toByteArray(in));
+ }
+ assertThrows(ZipException.class, () -> {
+ try (InputStream in =
zip.getInputStream(zip.getEntry(SECOND_NAME))) {
+ IOUtils.toByteArray(in);
+ }
+ });
+ }
+ assertThrows(ArchiveException.class, () ->
ZipFile.builder().setPath(path).get());
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void testPreamblePreservesHeaderAndDataOffsets(final boolean
ignoreLocalFileHeader) throws IOException {
+ final byte[] data = createZip(ZipArchiveOutputStream.STORED,
Zip64Mode.Never);
+ final byte[] preamble = "#!/usr/bin/unzip\n".getBytes(UTF_8);
+ final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ bytes.write(preamble);
+ bytes.write(data);
+ final byte[] archive = bytes.toByteArray();
+ try (ZipFile zip =
ZipFile.builder().setByteArray(archive).setIgnoreLocalFileHeader(ignoreLocalFileHeader).get())
{
+ assertEquals(preamble.length, zip.getFirstLocalFileHeaderOffset());
+ for (final String name : new String[] { FIRST_NAME, SECOND_NAME })
{
+ assertContent(zip, name, name.getBytes(UTF_8));
+ assertEquals(preamble.length + dataOffset(data,
localHeaderOffset(data, name)), zip.getEntry(name).getDataOffset());
+ }
+ }
+ archive[preamble.length + localHeaderOffset(data, SECOND_NAME)] ^= 1;
+ if (ignoreLocalFileHeader) {
+ try (ZipFile zip =
ZipFile.builder().setByteArray(archive).setIgnoreLocalFileHeader(true).get()) {
+ assertThrows(ArchiveException.class, () ->
zip.getRawInputStream(zip.getEntry(SECOND_NAME)));
+ }
+ } else {
+ assertThrows(ArchiveException.class, () ->
ZipFile.builder().setByteArray(archive).get());
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = { 1, 3, 4, 26, 29 })
+ void testReadsLocalHeaderAcrossSplitChannels(final int
relativeSplitOffset) throws IOException {
+ final byte[] data = createZip(ZipArchiveOutputStream.STORED,
Zip64Mode.Never);
+ final int headerOffset = localHeaderOffset(data, SECOND_NAME);
+ for (final boolean ignoreLocalFileHeader : new boolean[] { false, true
}) {
+ try (ZipSplitReadOnlySeekableByteChannel channel =
createSplitChannel(data, relativeSplitOffset);
+ ZipFile zip =
ZipFile.builder().setChannel(channel).setIgnoreLocalFileHeader(ignoreLocalFileHeader).get())
{
+ assertEquals(0,
zip.getEntry(SECOND_NAME).getDiskNumberStart());
+ assertEquals(headerOffset + 4,
zip.getEntry(SECOND_NAME).getLocalHeaderOffset());
+ assertContent(zip, FIRST_NAME, FIRST_NAME.getBytes(UTF_8));
+ assertContent(zip, SECOND_NAME, SECOND_NAME.getBytes(UTF_8));
+ assertEquals(4 + dataOffset(data, headerOffset),
zip.getEntry(SECOND_NAME).getDataOffset());
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void testSignatureDoesNotRejectOverlappingEntries(final boolean
ignoreLocalFileHeader) throws IOException {
+ final byte[] data = createOverlappingZip(true);
+ final byte[] content = "nested content".getBytes(UTF_8);
+ try (ZipFile zip =
ZipFile.builder().setByteArray(data).setIgnoreLocalFileHeader(ignoreLocalFileHeader)
+ .setRejectLocalFileHeaderNameDivergence(true).get()) {
+ assertEquals(2, zip.stream().count());
+ assertContent(zip, "inner.txt", content);
+ assertContent(zip, "outer.txt", Arrays.copyOfRange(data,
dataOffset(data, 0), centralDirectoryOffset(data)));
+
assertFalse(zip.getEntry("inner.txt").isLocalFileHeaderNameDivergent());
+ assertTrue(zip.getEntry("inner.txt").getLocalHeaderOffset() <
zip.getEntry("outer.txt").getDataOffset()
+ + zip.getEntry("outer.txt").getSize());
+ }
+ final Path path = createTempPath("overlapping", ".zip");
+ Files.write(path, data);
+ try (java.util.zip.ZipFile zip = new
java.util.zip.ZipFile(path.toFile()); InputStream in =
zip.getInputStream(zip.getEntry("inner.txt"))) {
+ assertArrayEquals(content, IOUtils.toByteArray(in));
+ }
+ // Sequential readers see the embedded header as part of the outer
entry's data, not as a separate entry.
+ final byte[] outerContent;
+ try (ZipArchiveInputStream in =
ZipArchiveInputStream.builder().setByteArray(data).get()) {
+ assertEquals("outer.txt", in.getNextEntry().getName());
+ outerContent = IOUtils.toByteArray(in);
+ assertNull(in.getNextEntry());
+ }
+ try (ZipInputStream in = new ZipInputStream(new
ByteArrayInputStream(data))) {
+ assertEquals("outer.txt", in.getNextEntry().getName());
+ assertArrayEquals(outerContent, IOUtils.toByteArray(in));
+ assertNull(in.getNextEntry()); // The JDK also verifies the outer
entry's CRC.
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void testSplitArchiveUsesDiskRelativeHeaderOffset(final boolean
ignoreLocalFileHeader) throws IOException {
+ final byte[] data = createZip(ZipArchiveOutputStream.STORED,
Zip64Mode.Never);
+ try (ZipSplitReadOnlySeekableByteChannel channel =
createSplitChannel(data);
+ ZipFile zip =
ZipFile.builder().setChannel(channel).setIgnoreLocalFileHeader(ignoreLocalFileHeader).get())
{
+ assertEquals(1, zip.getEntry(SECOND_NAME).getDiskNumberStart());
+ assertEquals(3, zip.getEntry(SECOND_NAME).getLocalHeaderOffset());
+ for (final String name : new String[] { FIRST_NAME, SECOND_NAME })
{
+ assertContent(zip, name, name.getBytes(UTF_8));
+ assertEquals(4 + dataOffset(data, localHeaderOffset(data,
name)), zip.getEntry(name).getDataOffset());
+ }
+ }
+ data[localHeaderOffset(data, SECOND_NAME)] ^= 1;
+ try (ZipSplitReadOnlySeekableByteChannel channel =
createSplitChannel(data)) {
+ final ZipFile.Builder builder =
ZipFile.builder().setChannel(channel).setIgnoreLocalFileHeader(ignoreLocalFileHeader);
+ if (ignoreLocalFileHeader) {
+ try (ZipFile zip = builder.get()) {
+ assertContent(zip, FIRST_NAME, FIRST_NAME.getBytes(UTF_8));
+ assertThrows(ArchiveException.class, () ->
zip.getInputStream(zip.getEntry(SECOND_NAME)));
+ assertThrows(ArchiveException.class, () ->
zip.getRawInputStream(zip.getEntry(SECOND_NAME)));
+ }
+ } else {
+ assertThrows(ArchiveException.class, builder::get);
+ }
+ assertFalse(channel.isOpen());
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = { 0, 1, 3, 4, 26, 29 })
+ void testTruncatedDeferredHeaderDoesNotCacheDataOffset(final int
remaining) throws IOException {
+ final byte[] data = createZip(ZipArchiveOutputStream.STORED,
Zip64Mode.Never);
+ try (ByteArraySeekableByteChannel channel =
ByteArraySeekableByteChannel.wrap(data);
+ ZipFile zip =
ZipFile.builder().setChannel(channel).setIgnoreLocalFileHeader(true).get()) {
+ final ZipArchiveEntry entry = zip.getEntry(SECOND_NAME);
+ channel.truncate(entry.getLocalHeaderOffset() + remaining);
+ assertThrows(EOFException.class, () -> zip.getInputStream(entry));
+ assertThrows(EOFException.class, () ->
zip.getRawInputStream(entry));
+ assertEquals(EntryStreamOffsets.OFFSET_UNKNOWN,
entry.getDataOffset());
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void testUnsignedHeaderInsidePayloadIsRejected(final boolean
ignoreLocalFileHeader) throws IOException {
+ final byte[] data = createOverlappingZip(false);
+ if (ignoreLocalFileHeader) {
+ try (ZipFile zip =
ZipFile.builder().setByteArray(data).setIgnoreLocalFileHeader(true).get()) {
+ assertEquals(2, zip.stream().count());
+ assertThrows(ArchiveException.class, () ->
zip.getInputStream(zip.getEntry("inner.txt")));
+ assertThrows(ArchiveException.class, () ->
zip.getRawInputStream(zip.getEntry("inner.txt")));
+ }
+ } else {
+ assertThrows(ArchiveException.class, () ->
ZipFile.builder().setByteArray(data).get());
+ }
+ }
+
+ @ParameterizedTest
+ @CsvSource({ "0,Never,false", "0,Never,true", "0,Always,false",
"0,Always,true", "8,Never,false", "8,Never,true", "8,Always,false",
"8,Always,true" })
+ void testValidHeadersWithExtraFields(final int method, final Zip64Mode
zip64, final boolean ignoreLocalFileHeader) throws IOException {
+ final byte[] data = createZip(method, zip64);
+ try (ZipFile zip =
ZipFile.builder().setByteArray(data).setIgnoreLocalFileHeader(ignoreLocalFileHeader).get())
{
+ for (final String name : new String[] { FIRST_NAME, SECOND_NAME })
{
+ assertContent(zip, name, name.getBytes(UTF_8));
+ final int headerOffset = localHeaderOffset(data, name);
+ assertEquals(dataOffset(data, headerOffset),
zip.getEntry(name).getDataOffset());
+ assertTrue(ZipShort.getValue(data, headerOffset + 28) > 0);
+ try (InputStream raw =
zip.getRawInputStream(zip.getEntry(name))) {
+ assertEquals(zip.getEntry(name).getCompressedSize(),
IOUtils.toByteArray(raw).length);
+ }
+ }
+ }
+ }
+}