A little about Java security

A little about Java security

It is told in many guides we should work with passwords using char arrays. But why and what happens if we will work with a simple string? So, I dived through and found at least one interesting moment I want to share with you.


String Pool

The first thing we should know about is String Pool, located in the heap memory section where string literals are stored. Since Java 7 strings that will not be referenced by any variable in the running program will be removed by the garbage collector from the pool.

Read more: https://www.baeldung.com/java-string-pool


Stack

Whenever a new method containing primitive values or references to objects is called, a block of memory is allocated at the top of the stack for them. The stack stores values of primitive variables created in methods, as well as references to objects in the heap that the method refers to. When the method completes execution, the memory block (frame) allocated for its needs is cleared, and the place becomes available for the next method.

Read more: https://topjava.ru/blog/stack-and-heap-in-java


Actually, nothing is reset till the next method call. When memory is allocated for new variables, they will replace the old data, and until then the data will be in memory. It happens because whenever a method is executed, a pointer just will be returned to the original position and that's it. Garbage collector will then remove unused objects in the heap, but not primitive types of a called method.


The same for heap. Whenever space is allocated for a new object, 'counter' links to the place where the object had been located, and it begins to accumulate references to this one. When the garbage collector starts and sees no one else needs this object, it will free up the memory occupied by this. It means it will be possible to allocate memory for another object for this place, but until it is allocated, the bytes in the RAM chips will continue to store the deleted object.


Solution

The best way to process sensitive data is manual clearing. It is hard to remove objects and strings from the heap, but it is possible to use char or byte arrays and replace values with nulls or another symbols.


Conclusion

  1. While a data contain in the memory, everyone may get access to that. I would use strong passwords or certificates to protect a server;
  2. When the RAM is overflowed, it may use a reserved portion of a storage (pagefile) and store sensitive information in there, which is much easier to steal. You may use JVM flags and control consuming memory;
  3. It is still possible to cause buffer overflowing and receive a control over an application. So, be aware.

To view or add a comment, sign in

More articles by Dmitry Neversky

Explore content categories