Django 阻止包含可能的 XSS 代码的图像上传

标签 django amazon-s3

我正在创建一个用户可以上传图片的网站。我正在使用 django-storages将这些图像转发到 S3 存储桶,但我最近阅读了 Django 站点上的安全文档:https://docs.djangoproject.com/en/3.0/topics/security/#user-uploaded-content

Django’s media upload handling poses some vulnerabilities when that media is served in ways that do not follow security best practices. Specifically, an HTML file can be uploaded as an image if that file contains a valid PNG header followed by malicious HTML. This file will pass verification of the library that Django uses for ImageField image processing (Pillow). When this file is subsequently displayed to a user, it may be displayed as HTML depending on the type and configuration of your web server.


它告诉我有关此漏洞的信息,但并没有为我提供防止这些漏洞的有效方法。这是网站中排名第三的最易受攻击的攻击。

Consider serving static files from a cloud service or CDN to avoid some of these issues.


我正在使用 S3 来提供我的媒体文件,它确实说要避免部分中描述的一些漏洞,但没有说明是哪一个。
我的问题:向 AWS S3 上传和提供图像是否容易受到这些攻击,如果没有,有什么有效的方法来清理图像内容?
编辑赏金:我在 S3 上托管图像,可能会发生哪些类型的攻击或漏洞?以及如何防止此类攻击?

最佳答案

为什么不验证文件是有效的图像?:

from PIL import Image
image = Image.open(file)
image.verify()
正如另一位海报所建议的那样,您确实可以尝试进行转换并检查是否抛出异常,但 verify() 可能会更快。
或者您可以尝试检测类型?:
import imghdr
path = 'Image.jpg'
imghdr.what(path)
或者
from PIL import Image
image = Image.open('myimage.png')
image.format
使用上述任何一种方法,您都可以确定该文件是否实际上是一个图像。如果它不是图像,则将该文件视为虚假文件,不要将其输出到您的任何网页上。通过不输出文件,不存在来自此向量的 XSS 风险,因为即使文件是 HTML,通过不在您的页面上输出它,它也不会损害您的页面。

关于Django 阻止包含可能的 XSS 代码的图像上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63292917/

相关文章:

python - 如何在 django 模板中将列表打印为单独的字符串

python - django.db.utils.IntegrityError : UNIQUE constraint failed 错误

python-3.x - AWS Lambda Python Jinja2 模板从 S3 加载 json

html - 跨域 CORS 和图像

scala - 使用正则表达式时 Spark S3 访问被拒绝

amazon-web-services - 配置 S3 url 的 Route 53

apache-spark - Spark 结构化流应用程序中的多个 S3 凭证

python - Django HttpRequest 与请求

python - Django:检查列表中是否存在行

python - 如何区分Django模板中的继承模型?