Year Of Security for Java – Week 21 – Anti-Caching Headers

No Gravatar

What is it and why should I care?
Caching is a mechanism by which browsers and proxy servers store local copies of remote objects in order to improve performance of the system by not having to fetch these items repeatedly. (That’s actually a decent description of caching in general.) Caching is wonderful for performance, assuming it’s tuned properly and you know what you’re doing. For security, however, it can be a very bad thing indeed.

Imagine you have your bank account information or maybe your medical records up on the screen. Later another person (or maybe a piece of malware) is on your machine and is able to access the data you were viewing on that screen without you even being logged into the site anymore. Not good!

Luckily, we can use the caching directives available to enable or prevent caching, or some of both, depending on what we want.

What should I do about it?

From a security perspective, you should disable caching altogether on sensitive resources. It’s up to you to figure out what those are, but that’s a simple enough problem to solve generally.

As for actually setting these directives, that’s commonly done using HTTP headers, Cache-Control, Expires, and Pragma. The example below shows the setting of caching headers in Java to prevent caching altogether.

// for HTTP 1.1
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); 
// for HTTP 1.0
response.setHeader("Pragma", "no-cache"); 
// setting to 0 means epoch + 0 seconds, or expired in 1970, thus invalid now. 
// the setDateHeader method sets a date in the RFC-required date format
response.setDateHeader("Expires", 0); 

Just a few LOC and you’ve prevented caching. Many folks I’ve worked with find it helpful to put this code into a J2EE filter, or at least a convenient utility method. However works best for you, cache prevention is a helpful security measure that helps protect users and the data in your application, so use it!

———– (setNoCacheHeaders method)

Be Sociable, Share!

Technorati Tags: ,