使用htaccess使PHP文件上传更加安全

5
我正在处理一个任务,使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个回答

5

代码可以被编码成图像文件,因此您应该禁用这些目录的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 engine off代码应该仅在user_uploaded_files文件夹中阻止它。非常感谢。 - Harshal
创建一个新的.htaccess文件,用于public_html/user_uploaded_files目录,其路径应为:public_html/user_uploaded_files/.htaccess,并在其中添加php_flag engine off - Yes Barry
那正是重点。我之前也有同样的想法,但很多人建议我们不要让带有写权限的文件夹中保留 .htaccess 文件,因为它可能会被黑客覆盖。我想把 htaccess 保存在根目录,并阻止 user_uploaded_files 文件夹中的内容。这可行吗?谢谢你们的回复。 - Harshal
对不起,没错。我忘记了,因为你发送这些最后的消息时我的脑海中已经没有新鲜感了。好吧,这是你的两个选择(除非有什么大师有更好的主意):要么将.htaccess文件放在那个文件夹中,要么在apache配置文件中进行更改。 - Yes Barry
是的,我认为我会选择Apache配置路线。谢谢你的帮助 :) - Harshal
随时可以!如果您需要其他帮助,请告诉我。干杯! - Yes Barry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接