Monday, April 25, 2011

How to write a secure code in Java

The Java programmers thinks that most efficient way to initialize objects is calling the constructor but thats not true . There are multiple ways to do that and one we will discuss here right now is serialization . The easiest way to guard against this problem is to write your classes so that before any object does anything it check if object has been initialized or not. You can do this by different ways

a) Always declare your variables as Private.
b) If you want to make outside access to these variables make getter and setter for them.
c) Add a new boolean  field  initialized to this class.
d) Initialize your constructor as the last action before running.
e) Check if the non constructor methods in class is initialized to true or not before doing anything.
f) If your class has static initializers then do same steps described above.

Make everything private if you can and make something non private only when if there is a good reason and document that reason.
If a class is not final then there is more chances to extend it in a dangerous and unforeseen way. By default everything should be final.Make something non final if there is  good reason to do so and document that reason.
There is a possibility that the attacker can use Reflection APIs to change and inspect the values of the private/final fields as well. Java provides a solution for this by adding the package.access security property. This prevents untrusted parties from using the Reflection API on the specified package hierarchy. Here is a code sample for setting the property:
Never depend on package scope. As the attacker can simply make another class in the same package which can access your classes, methods and variables (A few packages, such as java.lang, are closed by default, and a few Java virtual machines (JVMs) let you close your own packages. But you’re better off assuming packages aren’t closed.