【发布时间】:2016-01-29 23:59:17
【问题描述】:
我最近实施了一个安全系统,我们根据可接受的列表检查 MIME 类型和文件扩展名。如果扫描的文件在此列表中有 MIME 和扩展名,我们将继续前进。我已经包含了我们扫描下面文件的功能。 ALLOWED_EXTENSIONS 和 ALLOWED_MIME_TYPES 只是字符串,例如“txt,pdf,jpeg....”。
我假设您知道 MIME 类型的工作原理和工作原理,但最近我们收到了根本没有 MIME 类型的 PDF 上传。顺便说一句,这段代码大部分时间都有效。我已经看到 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;
}
【问题讨论】:
-
content-type 是对接收端发送内容的提示。没有说必须提供或准确的提示。在某些系统的cough 窗口中,文件的类型完全由其文件扩展名决定。如果您上传无扩展名的文件,则无法正确设置任何内容类型,除了通用类型,如 application/octet-stream。
-
这个,连同我从同事那里得到的一些其他建议,让我找到了答案。使用 MIME 类型进行安全检查是不可行的。期间。
-
它们不是安全检查,期间。但他们确实告诉你文件的外层就是它声称的那样。但仅仅说“这真的是一个 pdf”是不够的。 pdf 本质上是一个后记程序,也可以包含其他“活动”内容。
标签: php security mime file-extension