使用htaccess使PHP文件上传安全

时间:2011-12-09 07:30:11

标签: php security file .htaccess upload

我正在开展一项任务,使PHP文件上传安全,我的客户希望遵循网站http://www.acunetix.com/websitesecurity/upload-forms-threat.htm

上的指南提示

我们可以遵循本网站上提到的所有指南,接受htaccess规则。他们提到要做以下事。

Define a .htaccess file that will only allow access to files with allowed extensions.
Do not place the .htaccess file in the same directory where the uploaded files will be stored. It should be placed in the parent directory.
A typical .htaccess which allows only gif, jpg, jpeg and png files should include the following (adapt it for your own need). This will also prevent double extension attacks.

deny from all
<Files ~ "^\w+\.(gif|jpe?g|png)$">
order deny,allow
allow from all
</Files>
If possible, upload the files in a directory outside the server root.
Prevent overwriting of existing files (to prevent the .htaccess overwrite attack).
Create a list of accepted mime-types (map extensions from these mime types).
Generate a random file name and add the previously generated extension.
Don’t rely on client-side validation only, since it is not enough. Ideally one should have both server-side and client-side validation implemented.

这样就不会执行除gif,jpg和png之外的其他文件了。但是他们不希望htaccess位于我们上传图像的文件夹中,因为该文件夹具有权限并且htaccess可以被覆盖。因此,他们告诉将文件保持在根级别。

我想知道如果我们将文件保留在根级别并且只允许图像类型执行,那么我的php脚本将如何执行?当我在根级别添加此htaccess时,当然我的php脚本不起作用并返回权限错误。努力解决这个问题。

您能帮助我完成此工作或其他任何有效的方法来执行此安全检查。我们不希望在系统上留下安全漏洞。

任何帮助将不胜感激。

谢谢大家。

1 个答案:

答案 0 :(得分:4)

代码可以编码为图像文件,因此您应该禁用此目录的PHP引擎:

<IfModule mod_php5.c>
    php_flag engine off
</IfModule>

或者,如果你不能在.htaccess文件中设置它,那么你可以在httpd.conf或vhost conf文件中进行设置:

<VirtualHost *:80>
    # ...

    <Directory /path/to/webroot/path/to/upload/folder>
        deny from all
        <Files ~ "^\w+\.(gif|jpe?g|png)$">
            order deny,allow
            allow from all
        </Files>  
        <IfModule mod_php5.c>
            php_flag engine off
        </IfModule>      
    </Directory>
</VirtualHost>