Are @imagecreatefromjpeg and imagejpeg() effective for preventing users from uploading images with malicious php code within them?

荒凉一梦 提交于 2019-12-13 04:03:15

问题


Here is the code in upload_processor.php:

include_once 'functions.php';

$name = $_FILES['upload-image']['name'];
$type = $_FILES['upload-image']['type'];
$size = $_FILES['upload-image']['size'];
$temp = $_FILES['upload-image']['tmp_name'];
$error = $_FILES['upload-image']['error'];

img_processor($temp, $error, $size)

And here is functions.php:

function img_processor($img_temp, $img_error, $img_size){
    if($img_error===0){
        if($img_size < 4194304){
            if( $proc_img = @imagecreatefromjpeg($img_temp) ){
                imagejpeg($proc_img,'../uploaded/something.jpeg');
            } elseif( $proc_img = @imagecreatefrompng($img_temp) ){
                imagepng($proc_img,'../uploaded/something.png');
            } elseif( $proc_img = @imagecreatefromgif($img_temp) ){
                imagegif($proc_img,'../uploaded/something.gif');
            } else {
                echo("Only JPEGs, PNGs, and GIFs are allowed");
            }

            if(isset($proc_img)){
                echo("upload complete");                
            }

        } else {
            echo("Your file was too big. Only images that are 4MB or less are allowed");
        }
    } else {
        echo('Error uploading file! Code '.$img_error);
    }
}

The basic idea is to recreate the image, then rename it so that no one can upload something like malicious_code.php.jpg.

What are the holes in this code? Are there better ways to protect my site from PHP-injected images?


回答1:


  1. The imagegreatefrom* will return false if there's an error so the @ operator isn't really doing much in this situation.

  2. Instead of calling imagecreatefrom*, you can check to see if the input file is valid using exif_imagetype and then call an appropriate handler. I am not sure if there are security implications (although intuitively it sounds like there could be security problems with the above code), but the performance should improve, as you're not having to create an image resource every time a truth test fails.

    $handlers = array(
        IMAGETYPE_GIF => 'imagecreatefromgif',
        IMAGETYPE_JPEG => 'imagecreatefromjpeg',
        IMAGETYPE_PNG => 'imagecreatefrompng'
    );
    $type = exif_imagetype($img_temp);
    
    if(array_key_exists($type,$handlers)){
           $proc_img = call_user_func_array($handlers[$type],array($img_temp));
    } else {
        // do error logic here
    }
    

The other added benefit is that you can add handlers without having to make a giant if statement. See http://www.php.net/manual/en/function.exif-imagetype.php for more info.



来源:https://stackoverflow.com/questions/21718688/are-imagecreatefromjpeg-and-imagejpeg-effective-for-preventing-users-from-upl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!