In an ASP.NET Core 2.2 app I have the ability to upload a ZIP file. The contents of the ZIP file are extracted and saved in a directory. However, before saving the files on the server, I want to check their MIME types (a.k.a. content-types) to ensure that none of them are potentially dangerous files to store, such as EXE. If the ZIP file contains an unwanted file, I'd like to just show a model error on the page.
I tried to loop through the files within the zip to check their MIME types after storing the ZIP file in the directory. With this method, while I can see the file name with extension, I can't see the MIME type. Going by the extension alone isn't a good idea because it can be spoofed.
Directory.GetFiles(directory, "*.zip", SearchOption.TopDirectoryOnly).ToList()
.ForEach(zipFilePath =>
{
using (FileStream zipToOpen = new FileStream(zipFilePath, FileMode.Open))
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
//entry does not contain MIME type, only filename with extension
}
}
}
});
Another solution would be to set the folder's permissions to deny execution, but I don't want to do that because it's something easy to forget.
Lastly, there is some way of storing files in an App_Data folder which isn't publicly available and so files in it can't be directly executed. The issue with that is I just can't find such a folder. It doesn't seem to be created automatically with my app. I'm thinking this must be a difference between ASP.NET and ASP.NET Core.