To complete the response of devrobf:
Each executable file (by which I mean that the file contains machine instructions) can be identified by the magic number contained in the file's metadata.
The magic number is identified by it's size (in byte) and by it's offset (which can be different depending on the type of file). You can find a database that contains this information HERE.
For example EXE file :
Extension : EXE
Signature : 4D 5A
Description : Windows|DOS executable file
MZ (ASCII)
Sizet : 2 Bytes
Offset: 0 Bytes
As you will surely understand, doing a check only on the extension does not make it possible to determine with certainty what kind of executable file. As the proposed Cratylus.
Why? because the following example:
touch notAnExecutableWithExtensionExe.exe
This command just create file with as extension "exe", but it's just file data.
Implementation in Java to make a correct check of any kind of file :
public enum ExecutableSignatures{
WINDOWS_EXE("Windows|DOS executable file", (byte) 0x00, (byte) 0x02,
new byte[]{(byte)0x4d, (byte)0x5a}),
JAVA_BYTECODE("Java Bytecode", (byte) 0x00, (byte) 0x04,
new byte[]{(byte)0xca, (byte)0xfe, (byte)0xba, (byte)0xbe});
/* Here more enumeration */
private String description;
private byte offset;
private byte size;
private byte[] magicNumber;
private ExecutableSignatures(String description, byte offset, byte size, byte [] magicNumber){
this.description = description;
this.offset = offset;
this.size = size;
this.magicNumber = magicNumber;
}
public String getDescription(){
return this.description;
}
public byte getOffset(){
return this.offset;
}
public byte getSize(){
return this.size;
}
public byte[] getMagicNumbers(){
return this.magicNumber;
}
After you can create a method to make this check by using apache librairies see HERE
see @Filters - MagicNumberFilter.
This constructor can take 2 paramaters; the magicNumbers(byte array) and the offset(byte).
/**
* Perform a check of what kind of executable is by checking the signature
* of file.
* If it's an executable that is enumerate then the attributes
* magicNumber and executableDescription are updated with their corresponding
* values.
* @return true if is an executable supported by the program otherwise false
*/
public boolean isExecutableFile(){
MagicNumberFileFilter mnff = null;
for(ExecutableSignatures es : EnumSet.allOf(ExecutableSignatures.class)){
mnff = new
MagicNumberFileFilter(es.getMagicNumbers(), es.getOffset());
if(mnff.accept(this.file)){
this.magicNumber = es.getMagicNumbers();
this.executableDescription = es.getDescription();
return true;
}
}
return false;
}