保护文件上传

发布于 2025-01-07 16:27:56 字数 275 浏览 0 评论 0原文

几年前,我在学习期间为一家小公司编写了一个网站。我意识到我的安全技能并没有达到应有的水平,最近该网站遭到黑客攻击,并且使用用于图像上传的表单上传了恶意 php 代码。

此后,我进入了 .NET 世界,虽然我知道如何保护 .NET 中的文件上传,但我真的不知道如何使用 PHP 来做到这一点。很抱歉,我无法提供任何源代码,因此我不希望任何人为我的代码发布任何直接修复。

我希望有人可以向我展示一种服务器端分析的好方法,以确保上传的 $FILES 数组内容实际上是图像或音频文件,或者至少不是 php 文件。

I wrote a web site for a small company several years ago, while I was studying. I have come to the realization that my security skills were not as good as they should have been, and recently the site was hacked and malicious php-code was uploaded using a form which was meant for image uploads.

I have since moved on to the .NET world and whilst I know how to secure file uploads in .NET I really have no idea how to do it using PHP. I am sorry that I can not provide any source code, and I am therefore not expecting anyone to post any direct fixes for my code.

What I hope is that someone can show me a good approach to server-side analysis to ensure that the uploaded $FILES array content is in fact an image or an audio-file, or at the very least that it is not a php-file.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

卷耳 2025-01-14 16:27:56

很高兴你问了。这是一个棘手的话题,很少有应用程序开发人员意识到安全风险。

我将为您提供应该采取的方法的摘要,并阅读一些内容以了解更多信息。请务必阅读附加阅读材料,因为我的总结不完整。

摘要:

  1. 将用户上传的内容托管在单独的域上。这是您可以采取的最重要、最可靠的防御措施。

  2. 上传文件时检查其 MIME 类型,以确保其位于安全 MIME 类型白名单中。生成一个新的随机文件名来保存它。对于某些文件类型(例如图像),请考虑重新编码(例如,转换为 PNG,或使用 ImageMagick 将其从文件类型转换为相同的文件类型),因为这可能会阻止某些攻击。

  3. 下载/检索文件时,请确保将 Content-Type: 标头显式设置为安全 MIME 类型。还设置一个 X-Content-Type-Options: nosniff 标头。 中查看该文件,也请发送 Content-Disposition:attachment 标头,以使浏览器将其视为文件下载。

  4. 扫描上传的文件是否有病毒或恶意软件。

阅读:

Glad you asked. This is a tricky subject, and few application developers are aware of the security risks.

I'll give you a summary of the approaches you should take, and some reading to learn more. Make sure you read the additional reading, because my summary is incomplete.

Summary:

  1. Host the user-uploaded content on a separate domain. This is the most important and reliable defense you can take.

  2. Check the MIME type of the uploaded file, when it is uploaded, to make sure it is on a whitelist of safe MIME types. Generate a new random filename to save it under. In the case of some file types, such as images, Consider re-coding it (e.g., transform to PNG, or use ImageMagick to convert it from its filetype to the same filetype), as this may defeat some attacks.

  3. When the file is downloaded/retrieved, make sure to set the Content-Type: header explicitly to the safe MIME type. Also set a X-Content-Type-Options: nosniff header. If you don't intend for the file to be viewed in the browser, send a Content-Disposition: attachment header, too, to make the browser treat it as a file download.

  4. Scan file uploads for viruses or malware.

Reading:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文