Showing posts with label Secure coding. Show all posts
Showing posts with label Secure coding. Show all posts

Wednesday, 18 May 2016

Sonar Violation: Security - Array is stored directly


      public void setMyArray(String[] array) {
            this.array = array;
      }
     
Solution

      public void setMyArray1(String[] newArray) {
            if(newArray == null) {
                  this.newArray = new String[0];
            } else {
                  this.newArray = Arrays.copyOf(newArray, newArray.length);
            }
      }

Why should we avoid to store array directly?
Array stored by your object also held by the caller and the caller subsequently modifies this array, the array stored in the object (and hence the object itself) will change.

The solution is to make a copy within the object when it gets passed. This is called defensive copying. A subsequent modification of the collection won't affect the array stored within the object.

It's also good practice to normally do this when returning a collection. Otherwise the receiver could perform a modification and affect the stored instance.

Note
This obviously applies to all mutable collections (and in fact all mutable objects) - not just arrays. Note also that this has a performance impact which needs to be assessed alongside other concerns.


Tuesday, 10 May 2016

Make your classes nondeserializeable - Secure Coding in Java

Even if class isn't serializeable, it may still be deserializeable. An adversary can create a sequence of bytes that happens to deserialize to an instance of class. This is dangerous, since do not have control over what state the deserialized object is in. We can think of deserialization as another kind of public constructor for our object; unfortunately it's a kind of constructor that is difficult for us to control.

We can prevent this kind of attack by making it impossible to deserialize a byte stream into an instance of our class. We can do this by throwing IOException from readObject method.



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

Make your classes nonserializeable

Serialization is dangerous because it allows adversaries to get their hands on the internal state of objects. An adversary can serialize one of your objects into a byte array that can be read. This allows the adversary to inspect the full internal state of object, including any fields marked private, and including the internal state of any objects reference.

To prevent this, we can make object impossible to serialize. To achieve this goal, we will throw IOException from writeObject() method:



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

Related Posts Plugin for WordPress, Blogger...