Checking file types at startup and browser dependency issues

I am creating a php file loader and I have some security issues. For example, I do not want to allow the download of ".php" files. As I know, the only way to check the file type is $_FILES['file']['type'], and its value depends on the browser.

I check with multiple browsers and find that when choosing a regular .php file, different browsers return these values:

firefox: application/x-download
chrome: text/plain
safari: text/plain
IE: text/plain
opera: application/octet-stream

I also tried the same experiment with regular .txt files, and all views return text/plainas a mime type.

So the problem is: if I want to allow the download of the .txt file, what should I do to prevent the download of the .php files?

+3
source share
3

:

function Mime($path)
{
    $result = false;

    if (is_file($path) === true)
    {
        if (function_exists('finfo_open') === true)
        {
            $finfo = finfo_open(FILEINFO_MIME_TYPE);

            if (is_resource($finfo) === true)
            {
                $result = finfo_file($finfo, $path);
            }

            finfo_close($finfo);
        }

        else if (function_exists('mime_content_type') === true)
        {
            $result = preg_replace('~^(.+);.*$~', '$1', mime_content_type($path));
        }

        else if (function_exists('exif_imagetype') === true)
        {
            $result = image_type_to_mime_type(exif_imagetype($path));
        }
    }

    return $result;
}

mime .

+2

, . , , .

PHP, .php .txt:

if (strtolower(strrchr($_FILES['file']['name'], '.')) == '.php') {
    // has file extension .php
}
+3

. FAR , . , .php( ), , - "do_evil.php.txt", ( )

$file_ext = substr($_FILES['userfile']['name'], -3);
if($file_ext == 'php') {
   //REJECT FILE
}
else {
   // allow upload and once the file has been upload to the temp directory
   // have a peice of code move the file to the final location and rename 
   // the file and specify a new file extension, using $file_ext as the extension
   // so even if the file was 'do_evil.php.txt' when it comes to rest at the 
   // final location it will be 'do_evil.txt' and thus treated by the server as a
   // text file and not PHP
}

I used the above in the past with the results of the descent. This is by no means proof of a bullet, but it should at least help. I think I can have a code lying around that does all this, if you need it, look for it, but there are no promises, I can find it

0
source

Source: https://habr.com/ru/post/1727770/


All Articles