简体   繁体   中英

Is 'image' rule secure enough?

So I'm trying to create a upload profile picture for my website... And I'm wondering if the image rule is secure enough in Laravel.

Consider the following code:

input = [
    'profile_picture' => Input::file('profile_picture'),
];

$rules = ['profile_picture' => 'required|image'];

$validator = Validator::make($input, $rules);

if ($validator->fails()) {
    return 'It\'s not an image!';
} 

Pretty simple, The thing I want you to focus on is the image rule in the rules array.

It seems like Laravel validates image by their MIME type. As we know, It can be edited from the client and then send to the server by using something like Tamper Data or Burp Proxy.

And you say how do you know It validates image by their MIME type? Well... Take a look at this code below, This is the Validator.php class that Laravel uses for validation. It contains every rule I think. And to be specific, This is the validateImage function, Which is the image rule.

Validator/validateImage():

/**
* Validate the MIME type of a file is an image MIME type.
*
* @param  string  $attribute
* @param  mixed   $value
* @return bool
*/
protected function validateImage($attribute, $value)
{
    return $this->validateMimes($attribute, $value, array('jpeg', 'png', 'gif', 'bmp'));
}

As the Doc-block says, It validates it by their MIME type.

So is it secure enough? Any questions are welcome!

No it's not secure. At least you can't be sure if it is a real image as the MIME type can be manipulated. What usually helps is to use getimagesize() which will return false if the file is not an image. So you could extend the validator with this rule:

Validator::extend('real_image', function($attribute, $value, $parameters){
    if($value instanceof Symfony\Component\HttpFoundation\File\UploadedFile){
        if(getimagesize($value->getRealPath() !== false){
            return true;
        }
    }
    return false;
}

And add that to your validation rules:

$rules = ['profile_picture' => 'required|image|real_image'];

To answer your question We can't say anything as secured or not.

But Yes Laravel validates image only few format which you specified . It is also mentioned here .

If you think it is a basic validation, then you shall use the third party package like this which validates image by aspect ratio (Which only a real image can have it)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM