Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/changes/changes.xml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ The <action> type attribute can be add,update,fix,remove.
<action type="fix" dev="ggregory" due-to="alhuda, Gary Gregory">Fix int overflow in PCX image buffer sizing, now throws AllocationRequestException (#552).</action>
<action type="fix" dev="ggregory" due-to="alhuda, Gary Gregory">Fix int overflow in Allocator.array/arrayList size checks (#551).</action>
<action type="fix" dev="ggregory" due-to="Gary Gregory">Add messages when throwing NullPointerException.</action>
<action issue="IMAGING-401" type="fix" dev="pkarwasz" due-to="Piotr P. Karwasz, Gary Gregory">Read TIFF directory chains in a loop and limit the nesting depth of sub-directories, instead of failing with StackOverflowError (#584).</action>
<!-- ADD -->
<action type="fix" dev="ggregory" due-to="Sean R, Gary Gregory">Add unit tests (#553).</action>
<!-- UPDATE -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<Number> visited = new ArrayList<>();
readDirectory(byteSource, offset, dirType, formatCompliance, listener, visited);
final Set<Long> 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<Number> visited) throws ImagingException, IOException {

if (visited.contains(directoryOffset)) {
final Listener listener, final int depth, final Set<Long> 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<Long> visited) throws ImagingException, IOException {
try (InputStream is = byteSource.getInputStream()) {
if (directoryOffset >= byteSource.size()) {
return true;
return 0;
}

BinaryFunctions.skipBytes(is, directoryOffset);
Expand All @@ -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++) {
Expand Down Expand Up @@ -420,7 +452,7 @@ private boolean readDirectory(final ByteSource byteSource, final long directoryO
fields.add(field);

if (!listener.addField(field)) {
return true;
return 0;
}
}

Expand All @@ -440,7 +472,7 @@ private boolean readDirectory(final ByteSource byteSource, final long directoryO
}

if (!listener.addDirectory(directory)) {
return true;
return 0;
}

if (listener.readOffsetDirectories()) {
Expand All @@ -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) {
Expand All @@ -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<Number> 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.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -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));
}
}
Loading