How to write Secure Java Code


There are many young programmers who come up to me asking for guidelines on how to write secure Java code. Most of the time they are worried about SQL Injection and Cross Site Scripting (XSS) attacks. But these are not the only concerns related to Java Security. There are many more attacks possible on a Java Application. So this post is about some basic guidelines and/or rules that can be followed by the developer to safe guard against the most common attacks. Don’t take these as the defacto standard that will prevent all kind of attacks but they can serve as the stepping stone for secure applications.

Rule 1: Don’t depend on Initialization.

Many Java programmers thinks that calling the constructor is the only way to allocate objects in Java. But this is so NOT true. There are many ways to allocate objects w/o using the constructor, the most common being using Serialization – more on this later. The easiest way for guarding against this problem is to write your classes so that before any object does anything, it checks if it has been initialized. Heres how you can do this:

  1. First make all the variables private. If you want to allow outside access to these variable make getter and setters. This keeps outside code from accessing non-initialized variables.
  2. Add a new private boolean field, initialized, to the class.
  3. Have each constructor set initialized as the last action before returning.
  4. Have each non-constructor method check that initialized is true before doing anything.

If you class has static initializer than do the same at the class level. Here are the steps:

  1. Make all static variables private. To allow outside access use static getters and setters.
  2. Add new private static boolean field classInitialized to the class.
  3. Have the static initializer set the value of classInitialized as the last action before returning.
  4. Before doing anything have each static method and each constructor check if classInitialized is true.

Rule 2: Make everything private (unless there is a good reason not to do so)

Limit access to your classes, methods and variables. Every non private Class, Variable or Method is a potential entry point for the Attacker. By default make everything private. Make something non private if there is a good reason and document that reason. Basically we are limiting the attack area here.

Rule 3: Make everything final (unless there is a good reason not to do so)

If a class or method isn’t final, an attacker could try to extend it in a dangerous and unforeseen way. By default, everything should be final. Make something non final only if there is a good reason, and document that reason.

You might think you can prevent an attacker from extending your class or its methods by declaring the class nonpublic. But if a class isn’t public, it must be accessible from within the same package.

You might think that this is pretty insane as by doing so we are sacrificing one of the tenets of Object Oriented Programming but when it comes to Security extensibility is your Enemy. It provides more ways for the attacker to cause trouble.

UPDATE: 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:

<pre>    private static final String PACKAGE_ACCESS_KEY = "package.access";
    static {
        String packageAccess = java.security.Security.getProperty(
            PACKAGE_ACCESS_KEY
        );
        java.security.Security.setProperty(
            PACKAGE_ACCESS_KEY,
            (
                (packageAccess == null || packageAccess.trim().isEmpty()) ?
                "" :
                (packageAccess + ",")
            ) +
            "xx.example.product.implementation."
        );
    }</pre>

Rule 4: Don’t depend on Package Scope.

As i said earlier, don’t 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.)

As per Java 6 security guidelines – It is recommended that as a matter of course, packages are marked as sealed in the jar file manifest.

Package scope is good from the Software Engineering standpoint but is not recommended from the security point of view.

Rule 5: Don’t use Inner Classes.

It is a misconception that inner classes are only accessible to the outer class that defines them. There is no concept of inner class at the byte code level. So the compiler translates the inner class to a full flash outer class with a package private scope. As per Rule 4 we shouldn’t depend upon the package private scope.

But wait inner class also gets access to the variables of the outer class even if they are private so how does this happen. Well the compiler silently changes the access modifier from private to package private in the outer class. It’s bad enough that the inner class is exposed; but it’s even worse that the compiler is silently overruling your decision to make some fields private. Don’t use inner classes if you can help it.

Rule 6: Avoid signing your code.

Signed code runs with special privileges so has more power to cause trouble. Try to audit the areas that need special privileges for performing actions and Try to minimize the amount of privileged code.

Code that isn’t signed will run without any special privileges. And code with no special privileges is much less likely to do damage.

Rule 7: Put all the signed code in one archive.

By doing so we prevent mix-and-match attack, in which the attacker constructs a new applet or library that links some of your signed classes together with malicious classes, or links together signed classes that you never meant to be used together. By signing a group of classes together, you make such attacks more difficult.

Rule 8: Make classes non-cloneable.

If the class is cloneable the attacker can construct an instance of the class without using the constructor. If the class is not implementing the Cloneable interface the attacker can make a sub-class and make it implement the Cloneable interface and create a clone which will allow the attacker to create new instances of your class.

The new instances are made by copying the memory images of existing objects; though this is sometimes an acceptable way to make a new object, it often is not.

You can do this by defining the following method in each of your classes:

public final void clone() throws java.lang.CloneNotSupportedException {
         throw new java.lang.CloneNotSupportedException();
}

If you want your class to be cloneable, and you’ve considered the consequences of that choice, then you can still protect yourself. If you’re defining a clone method yourself, make it final. If you’re relying on a non final clone method in one of your superclasses, then define this method:

public final void clone() throws java.lang.CloneNotSupportedException {
          super.clone();
}

Rule 9: Make your classes nonserializable.

Serialization is dangerous as it allows the attacker to serialize your object in to byte array and read the internal state of your object be it private. Not only can the attacker see the internal fields but also of the objects it references. A class can be made nonserializable by declaring the following method in the class:

private final void writeObject(ObjectOutputStream out) throws java.io.IOException {
throw new java.io.IOException("Object cannot be serialized");
}

If this is not possible declare all the fields you want the attacker from examining as transient.

Rule 10: Make your classes nondesrializable.

Prevent Serialization doesn’t mean that the class cannot be deserialized. Attacker can make a byte array which can be deserialized as an instance of the class and will have the state that attacker wants. You can make it impossible for the attacker to do that by declaring the following method in your class:

private final void readObject(ObjectInputStream in) throws java.io.IOException {
throw new java.io.IOException("Class cannot be deserialized");
}

Rule 11: Don’t store secrets in your code.

It is a usual case that programmers store cryptographic keys and sometimes even license keys for third-party libraries inside the code or respective libraries. Secrets stored this was are completely accessible to the Attacker and don’t provide any Security.

Code Obfuscation can be used to protect against it but nothing is hidden from a dedicated Attacker armed with the correct tools.

I will sign-off for now. Again these are just some guidelines to get people started in the right direction. Feel free to comment by using the comments section.

Advertisements
How to write Secure Java Code

35 thoughts on “How to write Secure Java Code

  1. I would not nescessarily agree on increasing security by making everything private. The private modifier is very handy to tell (or rather not tell) codevelopers about code they should not touch, but it offers little to no protection against malicious intent as the reflection API allows you to bypass any modifiers.

    1. Faisal Feroz says:

      yea, with reflection private and in fact final also has lost its original meaning. But it is still better to have fields private then leaver them public for everyone to inspect and change.

      1. Faisal Feroz says:

        @Patrick I have updated the post about a solution for guarding against the use of Reflection API by using the package.access property. In short by doing so the attacker is prevented from using the Reflection API against the specified packager hierarchy.

  2. With regards to the idea of making lots of methods private, I’ll repeat an insightful statement that Michael Feathers made in “Working Effectively with Legacy Code”. If you have a class with lots of private methods, then you should probably look at moving that code into a public class and just using a private instance of it.

  3. I came across this blog through DZone.. I am confused in the type of attack you are trying to address.Since it is not very clear, I am not able to appreciate anything in here.

    Can you please explain what type of attack is being addressed here?

    1. Faisal Feroz says:

      The post is not about protecting against a particular attack. When it comes to gaining access to the application, the Attacker first tries to get into the application by using the most obvious attack patterns (these are obviously automated) and then build upon these security vulnerabilities to gain more access. The main purpose of this post is to highlight the most obvious security issues that are normally found in almost 80% of the code written.

      I hope I made my point clear here.

  4. Marco says:

    posts like those make me sad
    the user of your libraries is not your enemy!
    “privacy” should depends on “consenting adults'” levels of agreement – you can’t force it (any more than you can in real life;-)
    document how to use your libraries instead of forcing someone to do what you want

    1. Faisal Feroz says:

      What is your opinion about the user of a commercial third-party that requires a license key or something similar to work?

  5. Ran Biron says:

    “C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off.” [Stroustrup].
    Java makes it even harder – but not impossible. If someone wants to gain access to a field, there are numerous ways to do that (reflection, customized class loader, byte code manipulation…). The same goes for all of the other “rules”. The only thing that actually made sense in the entire article is the last rule – “don’t store secrets in your code”. Obscurity is not security, and obfuscation is not… (I don’t have anything that rhymes here) security either.

    1. Faisal Feroz says:

      The Rules outlined here don’t suggest that you application will be completely secure if you follow them but it does saves the code from obvious security flaws. There is a famous saying “The only code that is secure is the one that hasn’t been written.”

  6. Zenadatneda says:

    Generally I do not post on blogs, but I would love to mention that this post extremely forced me to try and do therefore! really nice post.

  7. Dmitriy Pichugin says:

    easiest way to check if object was created with constructor is to add a field below.

    private final transient boolean constructorUsed = true;

    instance will have this field initialized with true if constructor was used and with default false if serialization was used.

    my $0.02
    cheers,
    Dmitriy

  8. I am really glad I have found this information. Nowadays bloggers publish just about gossips and web and this is actually irritating. A good web site with exciting content, that’s what I need. Thank you for keeping this web-site, I’ll be visiting it.

  9. Amy Walter says:

    Faisal!
    I am new to Java .. I couldn’t understand the code with rule number 3. can you please explain it?
    In rule # 5 you said Inner classes are dangerous but all over the internet there is only one thing said about Inner classes that using inner classes is a good practice of Encapsulation and Encapsulation means security, right?

  10. Incredible! This blog looks exactly like
    my old one! It’s on a completely different topic but it has pretty much the same page layout and design. Excellent choice of colors!

  11. Broadcast satellite “in the Star on the 9th,” was successfully launched in June last year, it can be said is a milestone in
    the field of live satellite event. Much of your best players marketplaces in the united
    states are supervised. Another radio commercial production tip to chew on is to make sure the audio quality is excellent on any spot your produce.

  12. Believing that you are actually starving, it releases chemicals that actually make it harder to lose weight in an effort to conserve
    energy. Withdrawal from levothyroxine can be done but it takes 6 weeks of
    withdrawal for the remaining thyroid tissue to be completely starved.
    Many people don’t have the time to weight themselves every day, but checking the scale on a regular basis can definitely help when you’re working to lose weight and keep it off.

  13. That’s two years for a representative, six for a senator, four for a vice president and four for a president – if someone gets elected to terms in each of those offices, that’s a maximum total of sixteen years as an
    elected federal official. In the minority of minorities,
    his opinion of the Barack is that he will turn the USA into a liberal hippie haven where gays and blacks will
    be exalted like Angelina Jolie. You’ll be surprised at to how much this small step can help you through your healing process.

  14. An interesting discussion is definitely worth comment.
    I believe that you need to publish more about
    this subject matter, it might not be a taboo subject but
    typically folks don’t talk about these subjects. To the next! Many thanks!!

  15. Greetings I am so grateful I found your weblog, I really found you
    by mistake, while I was researching on Bing for something else, Regardless I am here now and would just
    like to say kudos for a marvelous post and a all round thrilling blog (I also love the theme/design),
    I don’t have time to look over it all at the minute but I have book-marked it and also included your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the superb job.

  16. Hi! I know this is kind of off topic but I was wondering which blog platform are you
    using for this website? I’m getting fed up of WordPress because I’ve had problems with hackers and I’m looking at options for another platform. I would be great if you could point me in the direction of a good platform.

  17. Superb site. Very nice web page short article concerning How to write Secure Java Code |
    My Blog – My Thoughts. You actually possess the blueprint for fulfillment occurring right here.
    Most definitely i’ll book mark your page and come once again afterwards.

  18. I leave a response each time I especially enjoy a post on a website or I have something
    to add to the conversation. Usually it is a
    result of the sincerness communicated in the post I browsed.
    And after this post How to write Secure Java Code | My Blog –
    My Thoughts. I was moved enough to post a leave a responsea response
    🙂 I actually do have a couple of questions for you if it’s okay. Is it simply me or does it look like like a few of these comments appear as if they are coming from brain dead people? 😛 And, if you are posting on additional places, I’d like to keep up with anything
    fresh you have to post. Would you make a list every one of your community
    sites like your linkedin profile, Facebook page or twitter feed?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s