Skip to content

Commit

Permalink
Validate lengths before parsing JPEG data
Browse files Browse the repository at this point in the history
Allows for more precise error messages. Matches output of .NET library.
  • Loading branch information
drewnoakes committed Feb 4, 2024
1 parent 7e76f45 commit c1d3320
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions Source/com/drew/metadata/jpeg/JpegReader.java
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,13 @@ public void extract(byte[] segmentBytes, Metadata metadata, JpegSegmentType segm
// The value of TAG_COMPRESSION_TYPE is determined by the segment type found
directory.setInt(JpegDirectory.TAG_COMPRESSION_TYPE, segmentType.byteValue - JpegSegmentType.SOF0.byteValue);

final int JPEG_HEADER_SIZE = 1 + 2 + 2 + 1;

if (segmentBytes.length < JPEG_HEADER_SIZE) {
directory.addError("Insufficient bytes for JPEG segment header.");
return;
}

SequentialReader reader = new SequentialByteArrayReader(segmentBytes);

try {
Expand All @@ -86,6 +93,13 @@ public void extract(byte[] segmentBytes, Metadata metadata, JpegSegmentType segm
short componentCount = reader.getUInt8();
directory.setInt(JpegDirectory.TAG_NUMBER_OF_COMPONENTS, componentCount);

final int JPEG_COMPONENT_SIZE = 1 + 1 + 1;

if (reader.available() < componentCount * JPEG_COMPONENT_SIZE) {
directory.addError("Insufficient bytes for JPEG the requested number of JPEG components.");
return;
}

// for each component, there are three bytes of data:
// 1 - Component ID: 1 = Y, 2 = Cb, 3 = Cr, 4 = I, 5 = Q
// 2 - Sampling factors: bit 0-3 vertical, 4-7 horizontal
Expand Down

0 comments on commit c1d3320

Please sign in to comment.