ASP.NET file upload: how can I make sure that the downloaded file is really a jpeg?

Criminals can fake the type of content of the file that it downloads. Therefore, if I receive a file on the server through my page, I can’t just check its MIME type and file extension. Is there a reliable way to check if the downloaded file is really a JPEG, GIF or PNG? I need to reject all other formats. I might try to read the file in parts, but what am I looking for? Thanks for any suggestions or ideas!

+5
source share
4 answers

The easiest way is to check the input stream header and see specific signatures:

  • JPEG: FF D8 in hexadecimal
  • GIF: "GIF"
  • PNG: 137 80 78 71 13 10 26 10

ASP.NET

        bool isValid = false;
        char[] header = new char[10];
        StreamReader sr = new StreamReader(Request.InputStream);
        sr.Read(header, 0, 10);

        // check if JPG
        if (header[0] == 0xFF && header[1] == 0xD8)
        {
            isValid = true;
        }
        // check if GIF
        else if (header[0] == 'G' && header[1] == 'I' && header[2] == 'F')
        {
            isValid = true;
        }
        // check if PNG
        else if (header[0] == 137 && header[1] == 80 && header[2] == 78 && header[3] == 71 && header[4] == 13 && header[5] == 10 && header[6] == 26 && header[7] == 10)
        {
            isValid = true;
        }

,

+5

try-catch Bitmap.FromStream(stream), . , , . , .

+6

, JPEG/GIF/PNG . ( , , exe). Windows Forms , , .

+3

, MIME, . - (IE), MIME, "" , , , , . , , mimic IE type type detection; , , .

"" (, , ). . (, , - .)

In addition, re-encoding an image will usually transmit metadata (for example, the serial number of the camera), which is good for privacy. This is especially useful when the user thinks they have trimmed something, but the image editor leaves it in miniature .

+2
source

All Articles