YuMp's avatar
Level 2

Doubt about sending and processing and uploading possible jpg, mp4, gif files contaminated by malware

Doubt about sending and processing and uploading possible jpg, mp4, gif files contaminated by malware

Using these validation rules in the controller of a laravel application restricts the sending of a file infected by a virus, be it an image, video or gif?

protected $rules = [ 'image' => 'nullable|image|mimes:jpeg,jpg,png|max:18048', 'video' => 'nullable|mimes:mp4|max:950048', 'gif' => 'nullable|image|mimes:gif|max:18048',

];

$this->validate([

        'image' => 'nullable|image|mimes:jpeg,jpg,png|max:18048',
        'video' => 'nullable|mimes:mp4,ogx,oga,ogv,ogg,webm|max:950048',
		'gif' => 'nullable|image|mimes:gif|max:18048',
		 ]);

If yes, what would be the solution to prevent this from happening?

thanks in advance

0 likes
1 reply
LaryAI's avatar
Level 58

The validation rules provided in the question are a good start to prevent the uploading of infected files, but they are not foolproof. It is possible for a file to pass these rules and still contain malware.

To further protect against malware, it is recommended to use a virus scanner to scan the uploaded files before storing them on the server. There are several virus scanners available that can be integrated into a Laravel application, such as ClamAV or Sophos.

Here's an example of how to use ClamAV in a Laravel application:

  1. Install ClamAV on your server. This can usually be done using your server's package manager (e.g. apt-get on Ubuntu).

  2. Install the ClamAV PHP extension using PECL:

    pecl install clamav
    
  3. Add the following line to your php.ini file to enable the ClamAV extension:

    extension=clamav.so
    
  4. In your Laravel controller, use the ClamAV scanner to scan the uploaded file before storing it:

    use ClamAV;
    
    ...
    
    $file = $request->file('image');
    
    if (ClamAV::isClean($file->getPathname())) {
        // File is clean, store it on the server
        $file->store('images');
    } else {
        // File is infected, reject it
        return redirect()->back()->withErrors(['image' => 'File is infected with malware']);
    }
    

This code uses the ClamAV::isClean() method to scan the uploaded file for malware. If the file is clean, it is stored on the server. If it is infected, an error message is returned to the user.

Note that using a virus scanner can add some overhead to the file upload process, so it may not be suitable for all applications.

Please or to participate in this conversation.