【问题标题】:Making PHP file upload secure with htaccess使用 htaccess 使 PHP 文件上传安全
【发布时间】:2012-01-16 13:27:24
【问题描述】:

我正在执行一项确保 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 脚本当然不起作用并返回权限错误。努力完成这项工作。

您能帮我完成这项工作或以任何其他有效的方式进行此安全检查吗?我们不想在系统上留下安全漏洞。

任何帮助将不胜感激。

谢谢大家。

【问题讨论】:

    标签: php security file .htaccess upload


    【解决方案1】:

    代码可以编码成图像文件,所以你应该禁用这个目录的 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>
    

    【讨论】:

    • 感谢 mmmshuddup 的解决方案,我可以访问 .htaccess 文件。只想知道是否可以将其限制在文件夹中。我的意思是,我可以在 public_html 文件夹中拥有 .htaccess,并且我想阻止 public_html/user_uploaded_files 文件夹中的脚本。所以 php_flag 引擎关闭代码应该只在 user_uploaded_files 文件夹中阻止它。非常感谢。
    • 为 public_html/user_uploaded_files 目录创建一个 new .htaccess 文件,使其路径为:public_html/user_uploaded_files/.htaccess 并将php_flag engine off 放入其中。
    • 这就是重点。实际上我之前也这么认为,但是很多人建议我们不应该将 .htaccess 文件保留在具有写入权限的 forlder 中,因为它可能被黑客覆盖。我想将 htaccess 保持在根级别并阻止 user_uploaded_files 文件夹中的内容。那可行吗?感谢您的回复。
    • 对不起,是的。我忘记了,因为当你给我发这些最后的信息时,我的脑海里已经没有什么新鲜事了。好吧,这是您的两个选择(除非某些大师有更好的主意):要么将 .htaccess 文件放在该文件夹中,要么在 apache conf 中更改它。
    • 是的,我想我会走 apache conf 路线。谢谢你的帮助。 :)
    猜你喜欢
    • 2013-10-18
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 2012-04-14
    • 2018-03-28
    • 2012-09-18
    • 1970-01-01
    • 2023-01-18
    相关资源
    最近更新 更多