...
- Uses objects to store sensitive data whose contents are not cleared or garbage-collected after use.
- Has memory pages that can be swapped out to disk as required by the operating system (for example, to perform memory management tasks or to support hibernation).
- Holds sensitive data in a buffer (such as
BufferedReader
) that retains copies of the data in the OS cache or in memory. - Bases its control flow on reflection that allows circumventing countermeasures to limit circumvent the limiting of the lifetime of sensitive variables.
- Reveals sensitive data in debugging messages, log files, environment variables, or through thread and core dumps.
Sensitive data leaks become more likely if the memory containing the data is not cleared after using the data. To limit the risk of exposure, programs must minimize the lifetime of sensitive data.
...
Code Block | ||
---|---|---|
| ||
class Password { public static void main (String args[]) throws IOException { Console c = System.console(); if (c == null) { System.err.println("No console."); System.exit(1); } String username = c.readLine("Enter your user name: "); char[] password = c.readPassword("Enter your password: "); if (!verify(username, password)) { throw new SecurityException("Invalid Credentials"); } // Clear the password Arrays.fill(password, ' '); } // Dummy verify method, always returns true private static final boolean verify(String loginusername, char[] password) { return true; } } |
The Console.readPassword()
method allows the password to be returned as a sequence of characters rather than as a String
object. Consequently, the programmer can clear the password from the array immediately after use. This method also disables echoing of the password to the console.
...
Code Block | ||
---|---|---|
| ||
void readData() throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream("file"))); // Read from the file String data = br.readLine(); } |
The BufferedReader.readLine()
method returns the sensitive data as a String
object, which can persist long after the data is no longer needed. The BufferedReader. read(char[], int, int)
method can read and populate a char
array. However, it requires the programmer to manually clear the sensitive data in the array after use. Alternatively, even if the BufferedReader
were to wrap a FileReader
object, it would suffer from the same pitfalls.
...
Code Block | ||
---|---|---|
| ||
void readData() throws IOException{ ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024); try(FileChannel rdr = (new FileInputStream("file")).getChannel()){ while (rdr.read(buffer) > 0) { // Do something with the buffer buffer.clear(); } } catch (ExceptionThrowable e) { // Handle error } } |
Note that manual clearing of the buffer data is mandatory because direct buffers are not garbage collected.
...