每个文件都有与之关联的MIME类型吗?

时间:2015-10-29 17:39:16

标签: php security mime file-extension

我最近实现了一个安全系统,我们根据可接受的列表检查MIME类型和文件扩展名。如果扫描的文件在此列表中有MIME和扩展名,我们继续前进。我已经包含了我们扫描下面文件的功能。 ALLOWED_EXTENSIONSALLOWED_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;
}

2 个答案:

答案 0 :(得分:1)

OP自己的答案(并不试图回答实际问题)除此之外,这并不是很明确。内容类型application/octet-stream是通用的,因此可以分配给每个文件。另一方面,显然可以创建没有有用的内容类型的文件;如何根据MIME类型标记dd if=/dev/urandom的输出?

在这个问题的框架中,我倾向于" no" - 无法为每个可能的文件分配有用的MIME类型。

答案 1 :(得分:0)

经过几天的研究和建议后,问题的答案有点无关紧要,因为首先检查MIME类型作为安全功能是不可行的。不同操作系统上的MIME类型存在太多问题,不同的应用程序以不同的方式保存文件,一些文件根本没有MIME,最后,恶意用户或程序可能会更改扩展名和MIME。关闭。