From 78ac29752ee0fd418a310cfe4bf0e6149b5aa736 Mon Sep 17 00:00:00 2001 From: Mikael Roos Date: Fri, 21 Nov 2014 19:57:11 +0100 Subject: [PATCH] Adding security check that image filename is always below the path `image_path` as specified in `img_config.php` #37. --- README.md | 1 + webroot/img.php | 23 +++++++++++++++++++++++ webroot/img_config.php | 7 +++++++ 3 files changed, 31 insertions(+) diff --git a/README.md b/README.md index d2295d0..c8660d8 100644 --- a/README.md +++ b/README.md @@ -133,6 +133,7 @@ Revision history v0.5.x (latest) +* Adding security check that image filename is always below the path `image_path` as specified in `img_config.php` #37. * Adding configuration item in `img_config.php` for setting valid characters in image filename. * Moving `webroot/test*` into directory `webroot/test`. * `webroot/check_system.php` now outputs if extension for exif is loaded. diff --git a/webroot/img.php b/webroot/img.php index b86543d..cb1008e 100644 --- a/webroot/img.php +++ b/webroot/img.php @@ -128,9 +128,32 @@ $verbose = getDefined(array('verbose', 'v'), true, false); $srcImage = get('src') or errorPage('Must set src-attribute.'); + +// Check for valid/invalid characters preg_match($config['valid_filename'], $srcImage) or errorPage('Filename contains invalid characters.'); + +// Check that the image is a file below the directory 'image_path'. +if ($config['image_path_constraint']) { + + $pathToImage = realpath($config['image_path'] . $srcImage); + $imageDir = realpath($config['image_path']); + + is_file($pathToImage) + or errorPage( + 'Source image is not a valid file, check the filename and that a + matching file exists on the filesystem.' + ); + + substr_compare($imageDir, $pathToImage, 0, strlen($imageDir)) == 0 + or errorPage( + 'Security constraint: Source image is not below the directory "image_path" + as specified in the config file img_config.php.' + ); +} + + verbose("src = $srcImage"); diff --git a/webroot/img_config.php b/webroot/img_config.php index c9b5a4b..23b482e 100644 --- a/webroot/img_config.php +++ b/webroot/img_config.php @@ -17,6 +17,13 @@ return array( + /** + * Check that the imagefile is a file below 'image_path' using realpath(). + */ + 'image_path_constraint' => true, + + + /** * A regexp for validating characters in the image filename. */