我最近实现了一个安全系统,在该系统中,我们根据可接受的MIME类型和文件扩展名列表进行检查。如果扫描的文件在此列表中具有MIME和扩展名,我们将继续前进。我已经包含了我们扫描下面文件的功能。ALLOWED_EXTENSIONS
和ALLOWED_MIME_TYPES
只是字符串,如"txt,pdf,jpeg…."。
我想你知道MIME类型是什么以及如何工作的,但最近我们上传的PDF根本没有MIME类型。顺便说一下,这段代码大部分时间都能正常工作。我见过PDF经过精细处理,还有图像、文本文件等。
一个文件可能根本没有MIME类型吗?
/**
* scan the file before upload to do our various security checks
*
* @param tmpName the file's location in /tmp, used for MIME type scan
* @param name the filename as it was uploaded, used for extension scan
* @param oid the order id, passed along to notifyStaffIllegalFileUpload() if email needs to be sent
* @return true on success, error string on failure
*/
function scanFile($tmpName, $name, $oid) {
global $_email;
// get lists from config
$allowedExtensions = explode(",", ALLOWED_EXTENSIONS);
$allowedMIMEs = explode(",", ALLOWED_MIME_TYPES);
// get extension
$ext = pathinfo($name, PATHINFO_EXTENSION);
// get MIME type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $tmpName);
finfo_close($finfo);
// check against allowed
if (!in_array(strtolower($ext), $allowedExtensions) || !in_array(strtolower($mime), $allowedMIMEs)) {
capDebug(__FILE__, __LINE__, "Order #" . $oid . " - A user attempted to upload a file with extension '" . $ext . "' and MIME type '" . $mime . "'. The attempt was blocked.'n", "/tmp/file_errors.log");
$_email->notifyStaffIllegalFileUpload($oid, $name, $ext, $mime);
return "Our security systems detected an illegal file type/mime type. The file upload was cancelled.";
}
return true;
}
OP自己的答案(不试图回答实际问题)除外,这并不是真正定义明确的。内容类型application/octet-stream
是通用的,因此可以分配给每个文件。另一方面,显然可以创建没有有用内容类型的文件;如何根据MIME类型标记dd if=/dev/urandom
的输出?
在这个问题的框架中,我倾向于"否"——不可能为每个可能的文件分配一个有用的MIME类型。
经过几天的研究和建议,这个问题的答案有点无关紧要,因为首先检查MIME类型作为一种安全功能是不可行的。不同操作系统上的MIME类型有太多问题,不同的应用程序以不同的方式保存文件,有些文件根本没有MIME,最后,恶意用户或程序可能会更改扩展名和MIME。交割。