Wednesday, April 2, 2014

Java Security Guidelines: Developing and Using Java More Securely


Rule 1: Don't Depend on Initialization
Most Java developers think that there is no way to allocate an object without running a constructor. This is not true: There are several ways to allocate uninitialized objects.
The easy way to protect yourself against this problem is to write your classes so that before any object does anything, it verifies that it has been initialized. You can do this as follows:
  • Make all variables private. If you want to allow outside code to access variables in an object, this should be done via get/set methods. (This keeps outside code from accessing uninitialized variables.) If you're following Rule 3, you'll make the get and set methods final.
  • Add a new private boolean variable, called initialized, to each object.
  • Have each constructor set the initialized variable as its last action before returning.
  • Have each nonconstructor method verify that initialized is true, before doing anything. (Note that you may have to make exceptions to this rule for methods that are called by your constructors. If you do this, it is best to make the constructors call only private methods.)
  • If your class has a static initializer, you will need to do the same thing at the class level. Specifically, for any class that has a static initializer, follow these steps:
  • Make all static variables private. If you want to allow outside code to access static variables in the class, this should be done via static get/set methods. This keeps outside code from accessing uninitialized static variables. If you're following Rule 3, you'll make the get and set methods final.
  • Add a new private static boolean variable, called classInitialized to the class.
  • Have the static constructor set the classInitialized variable as its last action before returning.
  • Have each static method, and each constructor, verify that classInitialized is true, before doing anything. (Note: Constructors are required to call a constructor of the superclass or another constructor of the same class as their first action. Therefore, you will have to do that before you check classInitialized.)


Rule 2: Limit Access to Your Classes, Methods, and Variables
Every class, method, and variable that is not private provides a potential entry point for an attacker. By default, everything should be private. Make something non-private only if there is a good reason, and document that reason.


Rule 3: Make Everything Final, Unless There's a Good Reason Not To
If a class or method is non-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 that you can prevent an attacker from extending your class or its methods by declaring the class non-public. However, if a class is not public, it must be accessible from within the same package, and as we shall see, Rule 4 says not to rely on package-scope access restrictions for security.
This advice may seem harsh. After all, the rule is asking you to give up extensibility, which is one of the main benefits of using an object-oriented language like Java. When you're trying to provide security, however, extensibility is your enemy; it just provides an attacker with more ways to cause trouble.


Rule 4: Don't Depend on Package Scope
Classes, methods, and variables that are not explicitly labeled as public, private, or protected are accessible within the same package. Don't rely on this for security. Java classes are not closed, so an attacker could introduce a new class inside your package, and use this new class to access the things you thought you were hiding. (A few packages, such as java.lang, are closed by default, and a few JVMs let you close your own packages. However, you're better off assuming that packages are not closed.)
Package scope makes a lot of sense from a software-engineering standpoint, since it prevents innocent, accidental access to things that you want to hide. But don't depend on it for security. Maybe we'll get sealed classes in the future.


Rule 5: Don't Use Inner Classes
Some Java language books say that inner classes can only be accessed by the outer classes that enclose them. This is not true. Java byte code has no concept of inner classes, so inner classes are translated by the compiler into ordinary classes that happen to be accessible to any code in the same package. And Rule 4 says not to depend on package scope for protection.
But wait, it gets worse. An inner class gets access to the fields of the enclosing outer class, even if these fields are declared private. And the inner class is translated into a separate class. In order to allow this separate class access to the fields of the outer class, the compiler silently changes these fields from private to package scope! 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. (Ironically, the new Java 2 doPrivileged() API usage guidelines suggest that you use an inner class to write privileged code. That's one reason we don't like the doPrivileged() API.)


Rule 6: Avoid Signing Your Code
Code that is not signed will run without any special privileges. And if your code has no special privileges, then it is much less likely to do damage.
Of course, some of your code might have to acquire and use privileges to perform some dangerous operation. Work hard to minimize the amount of privileged code, and audit the privileged code more carefully than the rest.


Rule 7: If You Must Sign Your Code, Put It All in One Archive File
The goal of this rule is to prevent an attacker from carrying out a 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 this attack more difficult.
Existing code-signing systems do an inadequate job of preventing mix-and-match attacks, so this rule cannot prevent such attacks completely. But using a single archive can't hurt.
Some code-signing systems let you examine other classes to see who signed them. If you are using a code-signing system that allows this, you can put code into the static constructors of your classes to verify that the "surrounding" classes have been signed by the same person as expected. Examining signers is one way to avoid the example shown in Figure 7.1. This doesn't completely prevent mix-and-match attacks, since an adversary can still mix together classes that you signed at different times; for example, by mixing version 1 of Class A with version 2 of Class B. If you're worried about this kind of interversion mix-and-match attack, you can put each class's "version stamp" in a public final variable and then have each class check the version stamps of its surrounding classes.

Fig 7.1
Figure 7.1 A mix and match attack.

In one type of mix and match attack, signed code with special privilege is linked or otherwise grouped together with unsigned code. The danger is that the unsigned code will be replaced in the group, leading to undefined and possibly dangerous behavior.


Rule 8: Make Your Classes Uncloneable
Java's object-cloning mechanism can allow an attacker to manufacture new instances of classes you define, without executing any of your constructors. If your class is not cloneable, the attacker can define a subclass of your class, and make the subclass implement java.lang.Cloneable. This allows the attacker to make new instances of your class. The new instances are made by copying the memory images of existing objects; although this is sometimes an acceptable way to make a new object, it often is not.
Rather than worry about this, you're better off making your objects uncloneable. 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 nonfinal clone method in one of your superclasses, then define this method:

public final void clone() throws java.lang.CloneNotSupportedException {
     super.clone();
}
This prevents an attacker from redefining your clone method.


Rule 9: Make Your Classes Unserializeable
Serialization is dangerous because it allows adversaries to get their hands on the internal state of your 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 your object, including any fields you marked private as well as the internal state of any objects you reference.
To prevent this, you can make your object impossible to serialize. The way to do this is to declare the writeObject method:

private final void writeObject(ObjectOutputStream out)
throws java.io.IOException {
     throw new java.io.IOException("Object cannot be serialized");
}
This method is declared final so that a subclass defined by the adversary cannot override it.


Rule 10: Make Your Classes Undeserializeable
This rule is even more important than the preceding one. Even if your class is not serializeable, it may still be deserializeable. An adversary can create a sequence of bytes that happens to deserialize to an instance of your class. This is dangerous, since you do not have control over what state the deserialized object is in. You can think of deserialization as another kind of public constructor for your object; unfortunately, it is a kind of constructor that is difficult for you to control.
You can prevent this kind of attack by making it impossible to deserialize a byte stream into an instance of your class. You can do this by declaring the readObject method:

private final void readObject(ObjectInputStream in)
throws java.io.IOException {
     throw new java.io.IOException("Class cannot be deserialized");
}
As in Rule 9, this method is declared final to prevent the adversary from overriding it.


Rule 11: Don't Compare Classes by Name
Sometimes you want to compare the classes of two objects to see whether they are the same, or you want to see whether an object has a particular class. When you do this, you need to be aware that there can be multiple classes with the same name in a JVM. It is a mistake to compare classes by name since different classes can have the same name.
A better way is to compare class objects for equality directly. For example, given two objects, a and b, if you want to see whether they are the same class, you should use this code:

if(a.getClass() == b.getClass()){
     // objects have the same class
}else{
     // objects have different classes
}
You should also be on the lookout for cases of less-direct by-name comparisons. Suppose, for example, you want to see whether an object "has the class Foo." Here is the wrong way to do it:

if(obj.getClass().getName().equals("Foo"))   // Wrong!
     // objects class is named Foo
}else{
     // object's class has some other name
}
Here is a better way to do it:

if(obj.getClass() == this.getClassLoader().loadClass("Foo")){
     // object's class is equal to the class that this class calls "Foo"
}else{
     // object's class is not equal to the class that 
     // this class calls "Foo"
}
Note the legalistic comments in the last example. Whenever you use classnames, you are opening yourself up to mix-and-match attacks, as described in Rule 7. You should also know that the Java language forces you to use classnames all the time: in variable declarations, instanceof expressions, and exception-catching blocks. Only the designers of Java can prevent mix-and-match attacks, but you can avoid making the problem worse by avoiding by-name class comparisons.


Rule 12: Secrets Stored in Your Code Won't Protect You
You might be tempted to store secrets such as cryptographic keys in the code for your application or library. Secrets stored in this way are completely accessible to anyone who runs your code. There is nothing to stop a malicious programmer or virtual machine from looking inside your code and learning its secrets.
Code obfuscation is another way to store a secret in your code; in the case of obfuscation, the secret is simply the algorithm used by your code. There's not much harm in using an obfuscator, but you shouldn't believe that it provides strong protection. There is no real evidence that it is possible to obfuscate Java source code or byte code so that a dedicated adversary with good tools cannot reverse the obfuscation.

Wednesday, March 19, 2014

Volatile keyword in Java

Local Variables in the Thread

If you are working with the multithreaded programming, the volatile keyword will be more useful. When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it’s updating the value, it is actually updated in the local cache not in the main variable memory. The other thread which is using the same variable doesn’t know anything about the values changed by the another thread. To avoid this problem, if you declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the values, it is updated to the main memory. So, other threads can access the updated value.

When should we use intern method of String on String constants

According to String#intern(), intern method is supposed to return the String from the String pool if the String is found in String pool, otherwise a new string object will be added in String pool and the reference of this String is returned.

String s = "Example";

String s1 = new String("Example"); // will create new object

String s2 = new String("Example").intern(); // this will create new object
 // but as we are calling intern we will get reference of pooled string "Example

Hibernate EhCache configuration tutorial

Caching is facility provided by ORM frameworks which help users to get fast running web application, while help framework itself to reduce number of queries made to database in a single transaction. Hibernate also provide this caching functionality, in two layers.
  • Fist level cache: This is enabled by default and works in session scope. Read more about hibernate first level cache.
  • Second level cache: This is apart from first level cache which is available to be used globally in session factory scope.
In this tutorial, I am giving an example using ehcache configuration as second level cache in hibernate.
Hibernate with EhCache
Hibernate with EhCache
Sections in this post:
How second level cache works
About EhCache
Configuring EhCache
Configuring entity objects
Query caching
Example application
Sourcecode download

How second level cache works

Lets write all the facts point by point:
  1. Whenever hibernate session try to load an entity, the very first place it look for cached copy of entity in first level cache (associated with particular hibernate session).
  2. If cached copy of entity is present in first level cache, it is returned as result of load method.
  3. If there is no cached entity in first level cache, then second level cache is looked up for cached entity.
  4. If second level cache has cached entity, it is returned as result of load method. But, before returning the entity, it is stored in first level cache also so that next invocation to load method for entity will return the entity from first level cache itself, and there will not be need to go to second level cache again.
  5. If entity is not found in first level cache and second level cache also, then database query is executed and entity is stored in both cache levels, before returning as response of load() method.
  6. Second level cache validate itself for modified entities, if modification has been done through hibernate session APIs.
  7. If some user or process make changes directly in database, the there is no way that second level cache update itself until “timeToLiveSeconds” duration has passed for that cache region. In this case, it is good idea to invalidate whole cache and let hibernate build its cache once again. You can use below code snippet to invalidate whole hibernate second level cache.

About EhCache

Terracotta Ehcache is a popular open source Java cache that can be used as a Hibernate second level cache. It can be used as a standalone second level cache, or can be configured for clustering to provide a replicated coherent second level cache.
Hibernate ships with the ehcache library. If you want any particular version of ehcache, visit the Terracotta Ehcache download site:
http://www.terracotta.org/products/enterprise-ehcache
The maven dependency is for Ehcache 2.0 and any upgrades is:
?
1
2
3
4
5
6
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>[2.0.0]</version>
    <type>pom</type>
</dependency>

Configuring EhCache

To configure ehcache, you need to do two steps:
  1. configure Hibernate for second level caching
  2. specify the second level cache provider
Hibernate 3.3 and above
?
1
2
<property key="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>
Hibernate 3.2 and below
?
1
2
<property key="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property>

Configuring entity objects

This may done in two ways.
1) If you are using hbm.xml files then use below configuration:
?
1
2
3
<class name="com.application.entity.DepartmentEntity" table="...">
    <cache usage="read-write"/>
</class>
2) Otherwise, if you are using annotations, use these annotations:
?
1
2
3
4
5
6
7
@Entity
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY,
region="department")
public class DepartmentEntity implements Serializable
{
    //code
}
For both options, caching strategy can be of following types:
  • none : No caching will happen.
  • read-only : If your application needs to read, but not modify, instances of a persistent class, a read-only cache can be used.
  • read-write : If the application needs to update data, a read-write cache might be appropriate.
  • nonstrict-read-write : If the application only occasionally needs to update data (i.e. if it is extremely unlikely that two transactions would try to update the same item simultaneously), and strict transaction isolation is not required, a nonstrict-read-write cache might be appropriate.
  • transactional : The transactional cache strategy provides support for fully transactional cache providers such as JBoss TreeCache. Such a cache can only be used in a JTA environment and you must specify hibernate.transaction.manager_lookup_class.

Query caching

You can also enable query caching. To do so configure it in your hbm.xml:
?
1
<property key="hibernate.cache.use_query_cache">true</property>
and where queries are defined in your code, add the method call setCacheable(true) to the queries that should be cached:
?
1
sessionFactory.getCurrentSession().createQuery("...").setCacheable(true).list();
By default, Ehcache will create separate cache regions for each entity that you configure for caching. You can change the defaults for these regions by adding the configuration to your ehcache.xml. To provide this configuration file, use this property in hibernate configuration:
?
1
<property name="net.sf.ehcache.configurationResourceName">/ehcache.xml</property>
And use below configuration to override the default configuration:
?
1
2
3
4
5
6
7
8
<cache
    name="com.somecompany.someproject.domain.Country"
    maxElementsInMemory="10000"
    eternal="false"
    timeToIdleSeconds="300"
    timeToLiveSeconds="600"
    overflowToDisk="true"
/>
Please note that in ehcache.xml, if eternal=”true” then we should not write timeToIdealSeconds, timeToLiveSeconds, hibernate will take care about those values
So if you want to give values manually better use eternal=”false” always, so that we can assign values into timeToIdealSeconds, timeToLiveSeconds manually.
timeToIdealSeconds=”seconds” means, if the object in the global cache is ideal, means not using by any other class or object then it will be waited for some time we specified and deleted from the global cache if time is exceeds more than timeToIdealSeconds value.
timeToLiveSeconds=”seconds” means, the other Session or class using this object or not, i mean may be it is using by other sessions or may not, what ever the situation might be, once it competed the time specified timeToLiveSeconds, then it will be removed from the global cache by hibernate.

Hibernate second level cache

The second level cache is used across sessions, which also differentiates it from the session cache, which only – as the name says – has session scope. Hibernate provides a flexible concept to exchange cache providers for the second-level cache. By default Hibernate uses Ehcache as caching provider, however JBoss AS 6 and 7 use Infinispan as caching provider.

One difference with the first level cache is that it's not on by default but it needs some configuration in your persistence.xml to tell Hibernate to turn on the cache. The configuration differs depending on the version of JBoss AS used. Let's see each configuration in detail.

Using second level cache with JBoss AS 5


JBoss AS 5 uses JBoss Cache as caching provider. This is the configuration required to turn on the 2nd level cache on JBoss 5:
01.<properties>
02. 
03.<property name="hibernate.cache.use_second_level_cache" value="true"/>
04.<property name="hibernate.cache.use_query_cache" value="true"/>
05. 
06.<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.jbc2.JndiMultiplexedJBossCacheRegionFactory"/>
07.<property name="hibernate.cache.region.jbc2.cachefactory" value="java:CacheManager"/>
08.<property name="hibernate.cache.region.jbc2.cfg.entity" value="mvcc-entity"/>
09.<property name="hibernate.cache.region.jbc2.cfg.collection" value="mvcc-entity"/>
10.</properties>

By setting the property hibernate.cache.use_second_level_cache to true we are turning on the second-level cache mechanism. The cache, by default, is activated only for entities, so we also need to explicitly set hibernate.cache.use_query_cache to true if we want to cache queries as well.
The second-level cache can be implemented using several different schemas—open source and commercial. In the next property, hibernate.cache.region.factory_class, we are telling Hibernate to use JBoss Cache as the second-level cache implementation.

The next parameter, hibernate.cache.region.jbc2.cachefactory, is specific to the JBoss Cache implementation. It specifies the JNDI name under which the CacheManager to be used is bound. There is no default value, thus the user must specify the property.

The hibernate.cache.region.jbc2.cfg.collection property is also specific to JBoss Cache and details the name of the configuration that should be used for collection caches (in our configuration, mvcc-entity).

Using second level cache with JBoss AS 6



JBoss AS 6 uses Infinispan 4 as cache provider. The required properties for persistence.xml follows here:
1.<properties>
2.<property name="hibernate.cache.use_second_level_cache">true</property>
3.<property name="hibernate.cache.use_query_cache">true</property>
4.<property name="hibernate.cache.region.factory_class">org.hibernate.cache.infinispan.JndiInfinispanRegionFactory</property>
5.<property name="hibernate.cache.infinispan.cachemanager">java:CacheManager/entity</property>
6.</properties>
  
The relevant part of this configuration is the cache manager which is bound in the JNDI tree under the name java:CacheManager/entity
The JNDI name to which the hibernate cache container is bound is defined in infinispan-configs.xml:

1.<infinispan-config name="hibernate" jndi-name="java:CacheManager/entity">
2.<infinispan-config xmlns="urn:infinispan:config:4.2">
3....
4.</infinispan-config>
5.</persistence>

Using second level cache with JBoss AS 7


JBoss AS 7 uses Infinispan 5 as caching provider. Here's the suggested configuration:
1.<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
2.<properties>
3.<property name="hibernate.cache.use_second_level_cache" value="true" />
4.<property name="hibernate.cache.use_query_cache" value="true" />    
5.<property name="hibernate.cache.infinispan.cachemanager" value="java:jboss/infinispan/hibernate"/>
6.<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.infinispan.JndiInfinispanRegionFactory"/>        
7.</properties>

In JBoss 7 the Infinispan cache manager is bound under the java:jboss/infinispan/hibernate name and is configured into the standalone-ha.xml or domain.xml inside the infinispan subsystem:
01.<subsystem xmlns="urn:jboss:domain:infinispan:1.0" default-cache-container="cluster">
02.. . . . . .
03.<cache-container name="hibernate" default-cache="local-query">
04.<invalidation-cache mode="SYNC" name="entity">
05.<locking isolation="REPEATABLE_READ"/>
06.<eviction strategy="LRU" max-entries="10000"/>
07.<expiration max-idle="100000"/>
08.</invalidation-cache>
09.<local-cache name="local-query">
10.<eviction strategy="LRU" max-entries="10000"/>
11.<expiration max-idle="100000"/>
12.</local-cache>
13.<replicated-cache mode="ASYNC" name="timestamps">
14.<eviction strategy="NONE"/>
15.</replicated-cache>
16.</cache-container>
17.</subsystem>

Disadvantages of Hibernate

• Debugging- Sometimes debugging and performance tuning becomes difficult.

• Slower than JDBC-
Hibernate is slower than pure JDBC as it is generating lots of SQL statements in runtime.

• Not suitable for Batch processing- It advisable to use pure JDBC for batch processing.

• Overhead-
Use of Hibernate is an overhead for the applications which are : simple and use one database that never change, need to put data to database tables, no further SQL queries and  there are no objects which are mapped to two different tables. Hibernate increases extra layers and complexity. So for these types of applications JDBC is the best choice.

• Difficult to maintain- Anybody wanting to maintain application using Hibernate will need to know Hibernate.

• Performance decreases in complex data-For complex data, mapping from Object-to-tables and vice versa reduces performance and increases time of conversion.

• Not allow all queries- Hibernate does not allow some type of queries which are supported by JDBC. For example it does not allow inserting multiple objects to same table using single query. Developer has to write separate query to insert each object.

• High memory consumption- Loading a large number of objects from the database which then reside in memory cause to waste the memory. One approach to resolving this is by using lazy loading, which has a few of its own caveats.

• Difficulties in legacy databases- Hibernate works best and easiest with a brand new database, attempting to use it on an existing legacy database can be quite a difficult task.

• Learning difficulties
– In here you may mess with advantages. Note that  it is quite easy to do the basics in hibernate but to really use hibernate well you need a good knowledge of ORM concepts, the way mappings and the session works and also more advanced concepts such as caching, lazy loading and fetching strategies.

• Performance optimization -Trying to optimize performance at the database level is a bit trickier with Hibernate due to the fact the SQL that is executed is actually generated by Hibernate, hence user  not able to just go in and adjust the SQL accordingly.

Thursday, February 27, 2014

Where is primitive data stored in java memory?

It does not depend on whether it is a primitive data type or not, It depends on whether it is an Instance variable or a local variable.
All local variables are stored in the stack along with their methods within which they are declared.
All instance variables/objects which contain primitive types are stored on the heap even if they are declared inside a method.Only their references stay in the stack if declared inside a method.