How to safely prevent uploaded file from being run via PHP on any server?

后端 未结 10 2087
独厮守ぢ
独厮守ぢ 2021-02-15 13:13

I noticed that it\'s possible to run a file via PHP even if its extension wasn\'t .php, for example file test.xyz.php.whatever.zyx can be still run wit

相关标签:
10条回答
  • 2021-02-15 14:03

    A simple regex would do the job

    <?php
    $a = strtolower($_FILES["file"]["name"]);
    $replace = array(".php", ".phtml", ".php3", ".php4", ".php5");
    $_FILES["file"]["name"] = str_replace($replace, "", $a);
    ?>
    

    This works fine on any server

    0 讨论(0)
  • 2021-02-15 14:07

    this is not really good answer but hope useful in some special cases ...

    you can use mod_rewrite in .htaccess file like this :

    RewriteRule ^(.+).xyz.php.whatever.zyx$ index.php?openfile=$1 [NC,L]
    

    and inside your index.php file :

    $file = secure_this_string($_GET['openfile']);
    include($file.'.xyz.php.whatever.zyx');  # or some other files
    

    remember to see this answer for security reasons StackOverFlow

    and in test.xyz.php.whatever.zyx file :

    <?php echo 'hello';
    

    now if client requests /test.xyz.php.whatever.zyx file , out put should be 'hello'

    0 讨论(0)
  • 2021-02-15 14:11

    I could reproduce your issue quite easily on our server. There is a way to fix this, you need to edit /etc/mime.types and comment out lines

    #application/x-httpd-php                                phtml pht php
    #application/x-httpd-php-source                 phps
    #application/x-httpd-php3                       php3
    #application/x-httpd-php3-preprocessed          php3p
    #application/x-httpd-php4                       php4
    #application/x-httpd-php5                       php5
    

    These lines cause anything with .php in name to be processed. Once you comment out the entries in mime.types, mod_php config in /etc/apache2/mods-enabled/php5.conf has this entry which correctly only processes files ENDING with .php

    <FilesMatch "\.ph(p3?|tml)$">
        SetHandler application/x-httpd-php
    </FilesMatch>
    

    What is REALLY SCARY is that this is a default config (Ubuntu 10.04 in our case).


    EDIT

    On Windows the mime.types file should be in apache_home/conf/mime.types

    0 讨论(0)
  • 2021-02-15 14:12

    for uploading by users I suggest that you upload a folder in a layer above the root path in this case Only You Have Access To upload folder( In direct addressing) and an attacker have not access to any files in this folder Thus you disable an attacker action to run malicious file

    0 讨论(0)
提交回复
热议问题