Shell – Script to determine if files are Images

filesimagesshell-script

I would like to create a shell script that will check to make sure all files in a directory are image files.

We recently had an issue where a hacker was able to generate a file in a directory and mask it as a .jpg file. I would like to create a shell script to check all files in the directory to make sure they are real jpg, gif or png files.

Best Answer

I think you want to be very careful about using file in a circumstance where you give it completely untrusted input. For instance, RHEL 5 file will identify this:

GIF87a
<?php
echo "Hello from PHP!\n";
?>

As "GIF image data, version 87a, 15370 x 28735". The PHP interpreter has no trouble executing that input. That lack of trouble is the basis for "local file inclusion" (LFI) problems.

Second, file (and even strings) actually parse input files to tell you what you want to know. These parsers are complicated and have problems.

I'm going to suggest the identify command out of the ImageMagick suite. It isn't fooled by my simple example above, and it only parses image files correctly, so it should be less prone to security flaws than file.

Related Question