PHP / curl / file_get_contents. Security and file size and type checking when retrieving deleted files

I want users to be able to copy or download images from a remote URL or upload files (which may include PDF and txt files, etc.) from their computer. To do this, I experimented with the get_contents_file and hung, both of which support my host. For local downloads, I just use php. They perform the main task of transmitting data. However, I am trying to find the best way to check the contents of a file in order to avoid spreading malicious code or loading my server with excessively large files.

In many cases, the file will be dynamically generated and, therefore, does not end with a known extension, so checking for file extensions is not an option, except for insecurity.

Using the mime type from the headers is one option, and I have code for this.

$file_info = new finfo(FILEINFO_MIME); // object oriented approach! $mime_type = $file_info->buffer(file_get_contents($file)); // eg gives "image/jpeg" switch($mime_type) { case "image/jpeg": // your actions go here... } 

However, it is obviously not too difficult to replace the mime type.

Several messages suggest sniffing magic numbers at the beginning of files, but they can also be faked.

For a limited case of images, you can use

 $imginfo_array = getimagesize($tempFile); 

As far as I know, this does not work for PDF files, documents, etc.

Even collectively, these methods do not seem very reliable. However, many sites regularly allow you to download, upload, or otherwise retrieve deleted files and somehow manage security issues.

You will need suggestions on the best security and verification methods - as in curl vs. file_get_contents vs. wd - as well as other libraries or other methods of getting the file size and file type before transferring it to my server.

Note. I want to allow the transfer of major image formats, such as .jpg and .gif, and downloads of PDF files, doc and docx files, xls files and similar common formats.

Thank you in advance for your recommendations and recommendations.

+4
source share
1 answer

However, I am trying to find a better way to check the contents of a file in order to avoid the spread of malicious code.

File uploading is one of the attack surfaces that I want to eliminate in the PHP ecosystem. If you upload files using cURL or allow users to submit them from a web form, the solution does not change much.

To allow remote code execution: upload files to a folder not accessible to the public outside your web root, then execute them with a proxy script (hint: readfile() or file_get_contents() ) instead of allowing direct access.

Then even if there is malicious code, Apache / nginx will not think to execute it.

... or loading my server with excessively large files

If you use cURL, this is easy to do .

0
source

All Articles