Monday, December 29, 2014

Java Garbage Collection is Not Instant

So over the weekend I had some experiment with Java GC and decided to write something about it. I was just mingling around to prove that just because a Java object or variable is eligible for garbage collection does not mean it gets collected right away.

That momentary moment becomes a window of opportunity for a hacker/attacker to sniff into maybe a sensitive data from your application through a heap memory dump. 

To prove this, I created a simple console application for this experimentation.

1. Create Java program:

public class HelloWorld {
    private static void readData() {
        System.out.println("Enter password here : ");
        Scanner scanIn = new Scanner(;
        char[] sesitiveData = scanIn.nextLine().toCharArray();

    public static void main(String[] args) throws Exception {

        Thread.sleep(1000 * 3600);

2. Compile: javac
3. Run: java HelloWorld
4. Enter any data (for example 'hacked'), hit enter
5. Find the PID: 'ps -efa | grep java' or you could do it in other way you prefer to
7. Create a heap dump: jmap -dump:format=b, file=myapp.bin 100 (given that 100 is the application PID)
8. Open VisualVM profiler, go to File/Load and select the heap dump you created earlier.
9. Next go to the OQL console and run the query bellow:

select a from char[] a where a.length == 6 && a[0] == 'h'

As you can see below, the query result to the screenshot. The array containing data you provided on console was found to think that it is already not referenced and unused, and the object was due for garbage collection. This proves that even objects referenced locally stays on heap until garbage collected.

To get that data out of heap, you just have to null-out the declared array variable and try the procedure again. The array containing your data should disappear. 

Important to note here is after using even a locally referenced objects, you should manually zero the returned character array after processing to minimize the lifetime of sensitive data in memory.

I hope this article is helpful. Enjoy!

No comments:

Post a Comment