Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java read actual file type by reading first few bytes (Forensic)

hello I need a way to read first four bytes of any file using Java. Why the first four bytes? Because it's forensic thumb print of the actual file type (File extension not reliable as it can be falsified)

http://en.wikipedia.org/wiki/File_carving

Now, reading a file this way (below, Java code) will read the file "content", I think it skips file header information...? I can't get the Magic Number (first four bytes) and thus unable to identify/confirm the true file type of a given specimen.

byte[] buffer = new byte[4];
InputStream is = new FileInputStream("somwhere.in.the.dark");
if (is.read(buffer) != buffer.length) { 
    // do something 
}
is.close();

Read First 4 Bytes of File

Suggestion please?


2 Answers

As Blank suggested, https://tika.apache.org

Here's the code - in this example, "test3_iamexe.txt" is an executable, with file extension renamed to "txt" by attacker.

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.parser.AbstractParser;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.sax.XHTMLContentHandler;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Set;
import org.apache.tika.metadata.Property;

public class TestTika {

    public static void main(String[] args) {
        File file = null;
    InputStream stream = null;
        String contentType = null;

        try
        {
            file = new File("C:\\tmp\\test3_iamexe.txt");
            stream = new FileInputStream(file);

            AutoDetectParser parser = new AutoDetectParser();
            BodyContentHandler handler = new BodyContentHandler();
            Metadata metadata = new Metadata();

            try {
                // This step here is a little expensive
                parser.parse(stream, handler, metadata);
            } finally {
                stream.close();
            }

            // metadata is a HashMap, you can loop over it see what you need. Alternatively, I think Content-Type is what you need
            contentType = metadata.get("Content-Type");

        } catch(...)
        {
            // handle it
        }

        return;
    }
}
like image 82
Jaye Avatar answered Jul 30 '26 09:07

Jaye


I think you can use:

IOUtils.toByteArray(InputStream is) 

See here : IOUtils.toByteArray to convert your InputStream to a byteArray, then get the first 4 bytes.

like image 37
yahya el fakir Avatar answered Jul 30 '26 07:07

yahya el fakir