Skip to main content

kanidmd_lib/valueset/image/
jpg.rs

1use std::io::Cursor;
2
3use image::{codecs::jpeg::JpegDecoder, ImageDecoder};
4use sketching::*;
5
6use super::ImageValidationError;
7
8const JPEG_MAGIC: [u8; 2] = [0xff, 0xd8];
9const EOI_MAGIC: [u8; 2] = [0xff, 0xd9];
10const SOS_MARKER: [u8; 2] = [0xff, 0xda];
11
12/// Checks to see if it has a valid JPEG magic bytes header
13pub fn check_jpg_header(contents: &[u8]) -> Result<(), ImageValidationError> {
14    if !contents.starts_with(&JPEG_MAGIC) {
15        return Err(ImageValidationError::InvalidImage(
16            "Failed to parse JPEG file, invalid magic bytes".to_string(),
17        ));
18    }
19    Ok(())
20}
21
22// It's public so we can use it in benchmarking
23/// Check to see if JPG is affected by acropalypse issues, returns `Ok(true)` if it is
24/// based on <https://github.com/lordofpipes/acropadetect/blob/main/src/detect.ts>
25pub fn has_trailer(contents: &Vec<u8>) -> Result<bool, ImageValidationError> {
26    let buf = contents.as_slice();
27
28    let mut pos = JPEG_MAGIC.len();
29
30    while pos < buf.len() && pos + 4 < buf.len() {
31        // We assert pos and pos+4 are both in bounds during
32        // while iteration.
33        #[allow(clippy::indexing_slicing)]
34        let marker = &buf[pos..pos + 2];
35        pos += 2;
36
37        // pos was shifted by 2, so this is relative to +4 from
38        // where the loop started.
39        #[allow(clippy::indexing_slicing)]
40        let segment_size_bytes: &[u8] = &buf[pos..pos + 2];
41        let segment_size = u16::from_be_bytes(segment_size_bytes.try_into().map_err(|_| {
42            ImageValidationError::InvalidImage("JPEG segment size bytes were invalid!".to_string())
43        })?);
44        // we do not add 2 because the size prefix includes the size of the size prefix
45        pos += segment_size as usize;
46
47        if marker == SOS_MARKER {
48            break;
49        }
50    }
51
52    let mut eoi_index = 0;
53    let mut eoi_index_found = false;
54    trace!("buffer length: {}", buf.len());
55
56    // iterate through the file looking for the EOI_MAGIC bytes
57
58    let buf_limit = buf.len() - EOI_MAGIC.len();
59
60    for i in pos..=buf_limit {
61        if buf.get(i..(i + EOI_MAGIC.len())) == Some(&EOI_MAGIC) {
62            eoi_index_found = true;
63            eoi_index = i;
64            break;
65        }
66    }
67
68    if !eoi_index_found {
69        Err(ImageValidationError::InvalidImage(
70            "End of image magic bytes not found in JPEG".to_string(),
71        ))
72    } else if (eoi_index + 2) < buf.len() {
73        // there's still bytes in the buffer after the EOI magic bytes
74        debug!(
75            "we're at pos: {} and buf len is {}, is not OK",
76            eoi_index,
77            buf.len()
78        );
79        Ok(true)
80    } else {
81        debug!(
82            "we're at pos: {} and buf len is {}, is OK",
83            eoi_index,
84            buf.len()
85        );
86        Ok(false)
87    }
88}
89
90pub fn validate_decoding(
91    filename: &str,
92    contents: &[u8],
93    limits: image::Limits,
94) -> Result<(), ImageValidationError> {
95    let mut decoder = match JpegDecoder::new(Cursor::new(contents)) {
96        Ok(val) => val,
97        Err(err) => {
98            return Err(ImageValidationError::InvalidImage(format!(
99                "Failed to parse {filename} as JPG: {err:?}"
100            )))
101        }
102    };
103
104    match decoder.set_limits(limits) {
105        Err(err) => {
106            sketching::admin_warn!(
107                "Image validation failed while validating {}: {:?}",
108                filename,
109                err
110            );
111            Err(ImageValidationError::ExceedsMaxDimensions)
112        }
113        Ok(_) => Ok(()),
114    }
115}
116
117#[test]
118fn test_jpg_has_trailer() {
119    let file_contents = std::fs::read(format!(
120        "{}/src/valueset/image/test_images/oversize_dimensions.jpg",
121        env!("CARGO_MANIFEST_DIR")
122    ))
123    .expect("Failed to read file");
124    assert!(!has_trailer(&file_contents).expect("Failed to check for JPEG trailer"));
125
126    // checking a known bad image
127    let file_contents = std::fs::read(format!(
128        "{}/src/valueset/image/test_images/windows11_3_cropped.jpg",
129        env!("CARGO_MANIFEST_DIR")
130    ))
131    .expect("Failed to read file");
132    // let test_bytes = vec![0xff, 0xd8, 0xff, 0xda, 0xff, 0xd9];
133
134    assert!(has_trailer(&file_contents).expect("Failed to check for JPEG trailer"));
135}