• caglararli@hotmail.com
  • 05386281520

How to handle mime types, file extension and magic number on file upload, renaming and file download?

Çağlar Arlı      -    18 Views

How to handle mime types, file extension and magic number on file upload, renaming and file download?

I am writing a simple server for file uploading. I want to be able to rename uploaded files (including the file extension) and download files.

For validating the file to upload my plan was to check if the mime type, the file extension and the magic number match. Only then the file will be uploaded to the server, assigned a UUID, stored on the server under its UUID. In the db I will store the file name, size and mime type.

Now, when a user renames a file which changes the file extension, the magic number of the actual file content does not change. So when the user then tries to download that file and upload it again, the upload will fail, because the magic number and the mime type/file extension dont match.

Isnt this an antipattern? The feature of renaming a file and sometimes changing the file extension is something I really dont want to miss on my server, so just restricting renaming to the file name (and force the extension to stay the same) is not an option.

Another question also rises: should I update the mime type stored in the db to match the new file extension when a file is renamed? If I dont do this and preserve the original mime type, the download request will have a Content-Type header that does not match the extension of the download file, which again seems like bad practice to me. However, if I update the mime type of the db, I will lose the information what the file actual says it contains.

How would you design this system?

I wont make this server public (for now) and even if I would, only authenticated users (only me) will be able to upload, rename and download stuff, so I dont need super bullet proof security checks. However I am wondering how this is handled in professional software (like onedrive) and would like to know how to properly build a decent line of defense against such attacks.

Thanks in advance for your insights