gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:32:49 25 4
gpt4 key购买 nike

我正在创建一个用户可以上传图片的网站。我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com