Web security : Malicious file upload vulnerability
-
Every website which is made with backend frameworks like Laravel, Django & many others can be easily Hacked by this vulnerability.
-
If your site have file upload form then Hacker can upload a file with executable extension like .php, .py, .bat to your site.
-
In that file they can write any code which can be executed by simply going to url like "example.com/files/test.php"
-
By doing this hacker can get your all confidential files like api keys files or even can get your servers access & delete the whole database or files.
-
To prevent this type of attacks there are some way as following.
-
In file upload code check & block executable file extensions like .php, .py etc.
-
Even if you block file upload by checking extensions hacker can use tools to change file extension & bypass this check.
-
Change uploaded files permission to readonly so even if file gets uploaded it can't be executed.
-
Prevent direct access to your uploads directory. It can be achieved by htaccess files or your server settings.
If you are using Laravel then you should upload your all project files outside public_html/www folder & store uploaded file to storage directory.
-
Create routes to serve your files. upload files in a different directory like uploads and save filename without extension in database with random generated name.
-
So even if hacker uploads file like "test.php" it will be saved as "1245abc545"
-
Then create specific routes for specific features like if you have profile images upload system then create route like this
/profile_images/{file_name}
-
Now in controller / function check if file with given name is available in your private uploads folder.
then return file with Content-Type: image/png.
This way even if its an php file or other file it will be executed as Image file.
So its code will not be executed.
-
This way you can prevent this vulnerability.