I suspect that, in addition to the extension verification method mentioned above, it will not be possible to catch all possible cases. Executable files are ultimately sequences of machine instructions that make them largely indistinguishable from any other data.
Despite this, some types of executables have things you can find. For example:
- Windows uses the Portable Executable format , which should always start with the magic number
4d5a (ASCII MZ characters) - Linux ELF executable file starts with
7f454c46 - Java class files always start with
cafebabe (it's hex, not ASCII!). - As far as I can tell, the Mach-O files used by Mac-OSX have a magic
feedface number (hex again)
I suggest you create a FileInputStream or the like and read the first few bytes of the file, checking these magic numbers. It does not detect any file that contains executable code, but it should prevent access to files in these standard executable formats, which, I think, is what you hoped for.
So for example:
public static boolean isExecutable(File file) { byte[] firstBytes = new byte[4]; try { FileInputStream input = new FileInputStream(file); input.read(firstBytes); // Check for Windows executable if (firstBytes[0] == 0x4d && firstBytes[1] == 0x5a) { return true; } return false; } catch (Exception e) { e.printStackTrace(); } }
Also be careful that you get a false positive when you reject a file that was not executed. I donโt know what type of file you are going to download, so you should consider how likely it is to happen.
jazzbassrob
source share