Skip to content
All posts
Laravel

Simple Laravel Rule for Image Content Validation

December 24, 2020·Read on Medium·

Been watching LaraconEU, i realized that i need to validate the content of the image. Currently use Clamav but somehow it’s not detect RCE injection tools in image.

RCE injection tools — https://github.com/ambionics/phpggc

When i use the RCE tools, i found that there is specific string injected to the file like __HALT_COMPILER, phar, $_GET, etc..

So, i came out a simple solution using only preg_match which check any malicious string inside the files.

ImageMaliciousDetectionRule.php View on GitHub
<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class ImageMaliciousDetectionRule implements Rule
{
    protected $malicious_keywords = [
        '\\/bin\\/bash',
        '__HALT_COMPILER',
        'Guzzle',
        'Laravel',
        'Monolog',
        'PendingRequest',
        '\\<script',
        'ThinkPHP',
        'phar',
        'phpinfo',
        '\\<\\?php',
        '\\$_GET',
        '\\$_POST',
        '\\$_SESSION',
        '\\$_REQUEST',
        'whoami',
        'python',
        'composer',
        'passthru',
        'shell_exe',
        'PHPShell',
        'FilesMan',
    ];

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     *
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
     */
    public function passes($attribute, $value)
    {
        if ($value instanceof UploadedFile) {
            return ! preg_match('/('.implode('|', $this->malicious_keywords).')/im', $value->get());
        }

        if (! request()->hasFile($attribute)) {
            return true;
        }

        return ! preg_match('/('.implode('|', $this->malicious_keywords).')/im', request()->file($attribute)->get());
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The system detected a malicious content in the attachment. Kindly check if your attachment is from the original sources';
    }
}

and for usage just put it in Rule validation array :-

'image' => ['required', new ImageMaliciousDetectionRule]

That’s it. Hope its help 😁

Found this helpful?

If this article saved you time or solved a problem, consider supporting — it helps keep the writing going.

Originally published on Medium.

View on Medium