3

I'm storing some files in my database and since I'm storing them in binary format and not keeping any other information, I have to make sure that all of them are in the same format so that I'll be able to "serve" them later (If there's a simple way to infer the file type from a byte array, please tell, but that's not the focus here).

So, what I need to do is validate every file that is uploaded to make sure it's on the required format.

I've set up a FieldTemplate with a FileUpload control and a CustomValidator:

<asp:FileUpload ID="FileUpload" runat="server" />&nbsp;


<asp:CustomValidator
    ID="CustomValidator1"
    runat="server"
    ErrorMessage="PDF only."
    ControlToValidate="FileUpload"
    OnServerValidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>

What I'm missing is the code to place in that CustomValidator1_ServerValidate method that checks the uploaded file to make sure it's in the right format (PDF in this case).

Thanks in advance.

Farinha
  • 17,636
  • 21
  • 64
  • 80

4 Answers4

4

Use the FileUpload.PostedFile.ContentType property to validate the MIME type ( should be application/pdf ). For security reasons, also validate that the file extension is appropriate ( .pdf ). You could have a static hashtable containing mappings from MIME type to file extension(s) and use as lookup to validate an extension.

baretta
  • 7,385
  • 1
  • 25
  • 25
4

Like ary said. This can all be spoofed. Take a .txt file, rename it to a pdf file and try getting the content type. It will be "application\pdf".

However there is one solution that I have used before. During my brief test with the PDF files, I figured out that the first 3 bytes were always the same. I tried only the first 3 bytes because it seemed enough. The value for the first three bytes is : 37, 80, 68.

So I read the bytes (InputFile1.FileContent.ReadByte()), compared them to the 3 bytes above and if they were the same, then I had a PDF file. Also I read somewhere that you should turn off the script execution for the upload directory in IIS. Hope it helps.

MindLoggedOut
  • 300
  • 2
  • 7
2

User can spoof it. In the solution above has no validation of the actual bytes content. I can send you executable and disguise it as pdf and this will not catch it.

2

The FileUpload.PostedFile.ContentType was exactly what I was looking for.

Just a heads-up to whoever is trying to do the same thing: it seems that the MIME type for PDF files can be "application/pdf" or "text/pdf", so be sure to check for both.

Farinha
  • 17,636
  • 21
  • 64
  • 80