diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 2e8d1a629..e804a8bfd 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -53,6 +53,7 @@ The type attribute can be add,update,fix,remove. Fix int overflow in PCX image buffer sizing, now throws AllocationRequestException (#552). Fix int overflow in Allocator.array/arrayList size checks (#551). Add messages when throwing NullPointerException. + Read TIFF directory chains in a loop and limit the nesting depth of sub-directories, instead of failing with StackOverflowError (#584). Add unit tests (#553). diff --git a/src/main/java/org/apache/commons/imaging/formats/tiff/TiffReader.java b/src/main/java/org/apache/commons/imaging/formats/tiff/TiffReader.java index 8edd59df6..d812b76f4 100644 --- a/src/main/java/org/apache/commons/imaging/formats/tiff/TiffReader.java +++ b/src/main/java/org/apache/commons/imaging/formats/tiff/TiffReader.java @@ -25,7 +25,9 @@ import java.io.InputStream; import java.nio.ByteOrder; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; import org.apache.commons.imaging.FormatCompliance; import org.apache.commons.imaging.ImagingException; @@ -157,6 +159,12 @@ public interface Listener { boolean setTiffHeader(TiffHeader tiffHeader); } + /** + * Maximum nesting depth of sub-directories (EXIF, GPS, interoperability); the specifications only nest the interoperability directory in the EXIF + * directory. + */ + private static final int MAX_SUB_DIRECTORY_DEPTH = 8; + private final boolean strict; private boolean bigTiff; private boolean standardTiff; @@ -331,21 +339,45 @@ private void readDirectories(final ByteSource byteSource, final FormatCompliance final long offset = tiffHeader.offsetToFirstIFD; final int dirType = TiffDirectoryConstants.DIRECTORY_TYPE_ROOT; - final List visited = new ArrayList<>(); - readDirectory(byteSource, offset, dirType, formatCompliance, listener, visited); + final Set visited = new HashSet<>(); + readDirectory(byteSource, offset, dirType, formatCompliance, listener, 0, visited); } + /** + * Reads a directory and, for a top-level directory ({@code depth == 0}), the chain of directories that follows it. + * + * @param depth the nesting depth: {@code 0} for a top-level directory, the depth of the parent directory plus one for a sub-directory. + * @return {@code false} if the directory at {@code directoryOffset} was already read. + * @throws ImagingException if sub-directories are nested deeper than {@value #MAX_SUB_DIRECTORY_DEPTH}. + */ private boolean readDirectory(final ByteSource byteSource, final long directoryOffset, final int dirType, final FormatCompliance formatCompliance, - final Listener listener, final boolean ignoreNextDirectory, final List visited) throws ImagingException, IOException { - - if (visited.contains(directoryOffset)) { + final Listener listener, final int depth, final Set visited) throws ImagingException, IOException { + if (depth > MAX_SUB_DIRECTORY_DEPTH) { + throw new ImagingException("TIFF sub-directories are nested deeper than " + MAX_SUB_DIRECTORY_DEPTH); + } + if (!visited.add(directoryOffset)) { return false; } - visited.add(directoryOffset); + long nextDirectoryOffset = readSingleDirectory(byteSource, directoryOffset, dirType, formatCompliance, listener, depth, visited); + // Follow the chain of directories in a loop, since a recursive call per directory can overflow the stack. + int nextDirType = dirType; + while (depth == 0 && nextDirectoryOffset > 0 && visited.add(nextDirectoryOffset)) { + nextDirectoryOffset = readSingleDirectory(byteSource, nextDirectoryOffset, ++nextDirType, formatCompliance, listener, depth, visited); + } + return true; + } + /** + * Reads a single directory and its sub-directories. + * + * @param depth the nesting depth of the directory. + * @return the offset of the next directory, or {@code 0} if no further directory must be read. + */ + private long readSingleDirectory(final ByteSource byteSource, final long directoryOffset, final int dirType, final FormatCompliance formatCompliance, + final Listener listener, final int depth, final Set visited) throws ImagingException, IOException { try (InputStream is = byteSource.getInputStream()) { if (directoryOffset >= byteSource.size()) { - return true; + return 0; } BinaryFunctions.skipBytes(is, directoryOffset); @@ -363,7 +395,7 @@ private boolean readDirectory(final ByteSource byteSource, final long directoryO if (strict) { throw e; } - return true; + return 0; } for (int i = 0; i < entryCount; i++) { @@ -420,7 +452,7 @@ private boolean readDirectory(final ByteSource byteSource, final long directoryO fields.add(field); if (!listener.addField(field)) { - return true; + return 0; } } @@ -440,7 +472,7 @@ private boolean readDirectory(final ByteSource byteSource, final long directoryO } if (!listener.addDirectory(directory)) { - return true; + return 0; } if (listener.readOffsetDirectories()) { @@ -458,7 +490,7 @@ private boolean readDirectory(final ByteSource byteSource, final long directoryO try { subDirectoryOffset = directory.getFieldValue(offsetField); subDirectoryType = directoryTypes[i]; - subDirectoryRead = readDirectory(byteSource, subDirectoryOffset, subDirectoryType, formatCompliance, listener, true, visited); + subDirectoryRead = readDirectory(byteSource, subDirectoryOffset, subDirectoryType, formatCompliance, listener, depth + 1, visited); } catch (final ImagingException imageReadException) { if (strict) { @@ -472,21 +504,10 @@ private boolean readDirectory(final ByteSource byteSource, final long directoryO } } - if (!ignoreNextDirectory && directory.getNextDirectoryOffset() > 0) { - // Debug.debug("next dir", directory.nextDirectoryOffset ); - readDirectory(byteSource, directory.getNextDirectoryOffset(), dirType + 1, formatCompliance, listener, visited); - } - - return true; + return directory.getNextDirectoryOffset(); } } - private boolean readDirectory(final ByteSource byteSource, final long offset, final int dirType, final FormatCompliance formatCompliance, - final Listener listener, final List visited) throws ImagingException, IOException { - final boolean ignoreNextDirectory = false; - return readDirectory(byteSource, offset, dirType, formatCompliance, listener, ignoreNextDirectory, visited); - } - /** * Reads only the first directory from a TIFF file. * diff --git a/src/test/java/org/apache/commons/imaging/formats/tiff/TiffReaderTest.java b/src/test/java/org/apache/commons/imaging/formats/tiff/TiffReaderTest.java new file mode 100644 index 000000000..db61d8bc4 --- /dev/null +++ b/src/test/java/org/apache/commons/imaging/formats/tiff/TiffReaderTest.java @@ -0,0 +1,109 @@ +/* + * 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.imaging.formats.tiff; + +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.nio.ByteBuffer; +import java.nio.ByteOrder; + +import org.apache.commons.imaging.FormatCompliance; +import org.apache.commons.imaging.ImagingException; +import org.apache.commons.imaging.bytesource.ByteSource; +import org.junit.jupiter.api.Test; + +/** + * Tests {@link TiffReader} on crafted directory structures. + */ +class TiffReaderTest { + + private static final int HEADER_SIZE = 8; + + /** An empty directory: entry count and next directory offset. */ + private static final int EMPTY_DIRECTORY_SIZE = 6; + + /** A directory with one entry: entry count, one 12-byte entry and next directory offset. */ + private static final int EXIF_DIRECTORY_SIZE = 18; + + /** + * Builds a little-endian TIFF whose empty directories follow each other at the given offsets, in order. + */ + private static byte[] directoryChain(final int count, final int lastNextOffset) { + final ByteBuffer tiff = header(HEADER_SIZE + count * EMPTY_DIRECTORY_SIZE); + for (int i = 0; i < count; i++) { + tiff.putShort((short) 0); + tiff.putInt(i < count - 1 ? HEADER_SIZE + (i + 1) * EMPTY_DIRECTORY_SIZE : lastNextOffset); + } + return tiff.array(); + } + + private static ByteBuffer header(final int size) { + final ByteBuffer tiff = ByteBuffer.allocate(size).order(ByteOrder.LITTLE_ENDIAN); + tiff.put((byte) 'I').put((byte) 'I').putShort((short) 42).putInt(HEADER_SIZE); + return tiff; + } + + /** + * Builds a little-endian TIFF whose first directory contains an EXIF offset to a directory that contains an EXIF offset, and so on. + */ + private static byte[] nestedExifDirectories(final int depth) { + final ByteBuffer tiff = header(HEADER_SIZE + depth * EXIF_DIRECTORY_SIZE + EMPTY_DIRECTORY_SIZE); + for (int i = 0; i < depth; i++) { + tiff.putShort((short) 1); + tiff.putShort((short) 0x8769).putShort((short) 4).putInt(1).putInt(HEADER_SIZE + (i + 1) * EXIF_DIRECTORY_SIZE); + tiff.putInt(0); + } + tiff.putShort((short) 0).putInt(0); + return tiff.array(); + } + + private static TiffContents readDirectories(final byte[] tiff, final boolean strict) throws Exception { + return new TiffReader(strict).readDirectories(ByteSource.array(tiff), false, FormatCompliance.getDefault()); + } + + @Test + void testDirectoryChainLoop() throws Exception { + // The last directory points back to the first one. + assertEquals(3, readDirectories(directoryChain(3, HEADER_SIZE), false).directories.size()); + } + + @Test + void testLongDirectoryChain() throws Exception { + assertEquals(20_000, readDirectories(directoryChain(20_000, 0), false).directories.size()); + } + + @Test + void testNestedExifDirectoriesAtLimit() throws Exception { + // The root directory and 8 nested EXIF directories. + assertEquals(9, readDirectories(nestedExifDirectories(8), true).directories.size()); + } + + @Test + void testNestedExifDirectoriesBeyondLimit() throws Exception { + // Sub-directories beyond the limit are skipped and their offset field removed. + final TiffContents contents = readDirectories(nestedExifDirectories(20_000), false); + assertEquals(9, contents.directories.size()); + assertTrue(contents.directories.get(8).getDirectoryEntries().isEmpty()); + } + + @Test + void testNestedExifDirectoriesBeyondLimitStrict() { + assertThrows(ImagingException.class, () -> readDirectories(nestedExifDirectories(9), true)); + } +}