问题描述:

I will be accepting user uploads on a new website in .NET Core 1.0.1. I only want to allow images, however, not just any file. How can I perform this verification in .NET Core? Is it possible to do without System.Drawing, as it is not implemented?

This answer looks promising, but it ultimately uses System.Drawing. Is it enough to check the content type and extension?


EDIT: The accepted answer is what I needed, but I'll share my actual implementation here. I'm doing this in .NET Core but I'm pretty sure the same code works on the full framework.

static bool IsJpeg(Stream stream)

{

using (var br = new BinaryReader(stream))

{

var soi = br.ReadUInt16();

var marker = br.ReadUInt16();

return soi == 0xd8ff && (marker & 0xe0ff) == 0xe0ff;

}

}

static bool IsPng(Stream stream)

{

using (var br = new BinaryReader(stream))

{

var soi = br.ReadUInt64();

return soi == 0x0a1a0a0d474e5089;

}

}

static bool IsGif(Stream stream)

{

using (var br = new BinaryReader(stream))

{

var soi = br.ReadUInt32();

var p2 = br.ReadUInt16();

return soi == 0x38464947 && (p2 == 0x6137 || p2 == 0x6139);

}

}

网友答案:

It is not enough to just check the file extension. I could make a ZIP file, and then just renamed the extension to .jpg and you'd assume it was a valid file.

Image formats do have "magic bytes" at the start of them that you could use to potentially identify that a file is, in fact, an image. This Wikipedia entry here has a list of magic numbers you could check against.

Note also that the content-type can be spoofed.

So you have 2 things you can do. The content-type as specified in the original answer, combined with checking the "magic numbers" of the file. If someone really wants to upload duff data that is not an image and bypassed both these checks, you might have to do something else.

So, you have 3 known guards you can implement:

  1. Does the file have an extension on your whitelist? (.jpg/.jpeg/etc...)
  2. Does the content-type match an entry on your whitelist? (image/jpeg)
  3. Once you've ascertained which kind of file it is via the first 2 steps, do the magic numbers match also?
相关阅读:
Top