In my application, users can upload files and store them in a
database.
I would like to prevent them from uploading executable files. The
question is: How do I detect if it is an executable file?
I am not asking about checking the .exe extension, which is easy, and
unreliable because one can easily rename malicious.exe to
prettygirl.jpg.
If you have used gmail attachment, you would know.
I googled, but cannot find anything helpful. Your hint is highly
appreciated.
The only reliable method for doing this is to work in the same way that
the UNIX 'file' command works, and inspect the file.
Many applications in the Windows world do _not_ do this (ironically,
some of them are _security_ applications). They'll block certain file
extensions or certain MIME types, which is just incorrect behavior.
Check out:
http://en.wikipedia.org/wiki/File_(Unix)
You can very likely use its database in your application and port the
"file" code into a library for C#. That way you can reliably detect
file types. The database is updated over time, as well, so if you
maintain the database external to your application instead of embedded
as a resource or something, you can deploy updates without rebuilding.
If you just want to catch the basic executable types, look for PE files
(a modification of the UNIX COFF executable format). To catch-all, you
can look for MZ, PE+, NE, and LE executables. If you want to filter
out executables that can be used on systems like most UNIX variants,
look for COFF, ELF, a.out/ZMAGIC/OMAGIC, etc. file types, too.
You then just open the file and detect what type it is based on the
information that you have. You can detect structured executables (and,
for example, whether or not they are CLR binaries or native code) and
data formats as well, so if you want to take the approach of
whitelisting file formats, you can do that as well.
You can't (reliably) catch straight binary programs (e.g., what used to
be known as .COM files for MS-DOS and compatible systems, but is also
the same sort of code that resides in a boot loader or master boot
record). However, these sorts of programs mostly cannot execute on
modern versions of Windows any longer, and do not present a danger
because most of the functionality that they use is prohibited by
Windows itself. Most of these types of programs are written to use
direct I/O or other hardware access.
--- Mike