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;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s