另一个测试是使用file 命令。它检查文件中是否存在“幻数”以确定其类型。在我的系统上,file 包包括 libmagic 以及基于 ctypes 的包装器 /usr/lib64/python2.7/site-packages/magic.py。看起来你像这样使用它:
import magic
ms = magic.open(magic.MAGIC_NONE)
ms.load()
type = ms.file("/path/to/some/file")
print type
f = file("/path/to/some/file", "r")
buffer = f.read(4096)
f.close()
type = ms.buffer(buffer)
print type
ms.close()
(来自here的代码。)
关于您最初的问题:“卢克,请阅读源代码。”
django/core/files/images.py:
"""
Utility functions for handling images.
Requires PIL, as you might imagine.
"""
from django.core.files import File
class ImageFile(File):
"""
A mixin for use alongside django.core.files.base.File, which provides
additional features for dealing with images.
"""
def _get_width(self):
return self._get_image_dimensions()[0]
width = property(_get_width)
def _get_height(self):
return self._get_image_dimensions()[1]
height = property(_get_height)
def _get_image_dimensions(self):
if not hasattr(self, '_dimensions_cache'):
close = self.closed
self.open()
self._dimensions_cache = get_image_dimensions(self, close=close)
return self._dimensions_cache
def get_image_dimensions(file_or_path, close=False):
"""
Returns the (width, height) of an image, given an open file or a path. Set
'close' to True to close the file at the end if it is initially in an open
state.
"""
# Try to import PIL in either of the two ways it can end up installed.
try:
from PIL import ImageFile as PILImageFile
except ImportError:
import ImageFile as PILImageFile
p = PILImageFile.Parser()
if hasattr(file_or_path, 'read'):
file = file_or_path
file_pos = file.tell()
file.seek(0)
else:
file = open(file_or_path, 'rb')
close = True
try:
while 1:
data = file.read(1024)
if not data:
break
p.feed(data)
if p.image:
return p.image.size
return None
finally:
if close:
file.close()
else:
file.seek(file_pos)
所以看起来它只是一次读取文件 1024 个字节,直到 PIL 说它是一个图像,然后停止。这显然不会检查整个文件的完整性,因此它实际上取决于您所说的“覆盖我的图像上传安全”的意思:非法数据可以附加到图像并通过您的站点传递。有人可以通过上传大量垃圾文件或非常大的文件来入侵您的网站。如果您不检查任何上传的字幕或对图像的上传文件名做出假设,您可能容易受到注入攻击。以此类推。