Search code examples
phpsecuritymimefile-extension

Does every file have a MIME type associated with it?


I recently implemented a security system where we check MIME types and file extensions against a list of acceptable ones. If the scanned file has a MIME and an extension in this list, we move forward. I have included the function where we scan the file below. The ALLOWED_EXTENSIONS and ALLOWED_MIME_TYPES are just strings such as "txt,pdf,jpeg....".

I will assume you know what and how MIME types work, but lately we have been getting PDF uploads with no MIME type at all. This code works most of the time by the way. I have seen PDFs go through fine, as well as images, text files, ect.

Is it possible a file would not have a MIME type at all?

 /**
 * 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;
}

Solution

  • After a few days of research and advice, the answer to the question is kind of irrelevant due to the fact that checking for MIME types as a security feature is not feasible in the first place. There are too many issues with MIME types on different operating systems, different applications saving files differently, some files not having a MIME at all, and lastly, the fact that the extension and MIME could be altered by a malicious user or program. Closing.