Wiki Markup |
---|
Misuse of synchronization primitives is a common source of concurrency issues. A significant number of concurrency vulnerabilities arise from locking on the wrong kind of object. An analysis of the JDK 1.6.0 source code discovered 31 bugs that fell into this category \[[Pugh 08|AA. Java References#Pugh 08]\]. It is important to recognize the entities with whom synchronization is required rather than indiscreetly scavenging for objects to synchronize on. |
...
{color: |
...
red |
...
}we need a more precise statement about what specifically this guideline |
...
Noncompliant Code Example (Boolean
lock object)
This noncompliant code example synchronizes on the (initialized
) boolean.
Code Block | ||
---|---|---|
| ||
requires{color} {mc} any suggestions? {mc}
h2. Noncompliant Code Example ({{Boolean}} lock object)
This noncompliant code example synchronizes on the ({{initialized}}) boolean.
{code:bgColor=#FFcccc}
private final Boolean initialized = Boolean.FALSE;
public void doSomething() {
synchronized(initialized) {
// ...
}
}
|
...
{code} The {{initialized}} variable can only assume the values {{true}} and {{false}}. Consequently, any other code that synchronizes on a {{Boolean}} variable with the same value, may induce unresponsiveness and deadlocks \[[Findbugs 08|AA. Java References#Findbugs 08]\]. |
...
{color: |
...
red |
...
}Not sure I completely understand this. Is the problem that there are only two actual objects that allocated so that if two different threads syncrhronize on thesse objects they'll stomp on each other? |
...
Noncompliant Code Example (Boxed primitive)
This noncompliant code example locks on a boxed Integer
object.
Code Block | ||
---|---|---|
| ||
{color} {mc} yes {mc} h2. Noncompliant Code Example (Boxed primitive) This noncompliant code example locks on a boxed {{Integer}} object. {code:bgColor=#FFcccc} int lock = 0; private final Integer Lock = lock; // Boxed primitive Lock ia shared public void doSomething() { synchronized(Lock) { // ... } } {code} Boxed types may use the same instance for a range of integer values and consequently, suffer from the same problem as {{Boolean}} constants. If the value of the primitive can be represented as a byte, the wrapper object is reused. Note that the use of the boxed {{Integer}} wrapper object is insecure; instances of the {{Integer}} object constructed using the {{new}} operator ({{new Integer(value)}}) are unique and not reused. In general, holding a lock on any data type that contains a boxed value is insecure. |
...
h2. Compliant Solution (Integer) |
...
This compliant solution recommends locking on a non-boxed Integer. The {{doSomething()}} method synchronizes using the intrinsic lock of the {{Integer}} instance, {{Lock}}. |
...
{code | ||
:bgColor | =#ccccff | } int lock = 0; private final Integer Lock = new Integer(lock); public void doSomething() { synchronized(Lock) { // ... } } {code} When explicitly constructed, an {{Integer}} object has a unique reference and its own intrinsic lock that is not shared with other {{Integer}} objects or boxed integers having the same value. While this is an acceptable solution, it may cause maintenance problems. |
...
Compliant Solution (internal private final lock Object
)
This compliant solution uses an internal private final lock object. This is one of the few cases where a java.lang.Object
instance is useful.
Code Block | ||
---|---|---|
| ||
{color:red}why?{color} {mc} because developers might assume all Integers are ok for locking and some unaware developer might mistakenly use a boxed type {mc} A more appropriate solution is to synchronize on an internal private final lock {{Object}} as described in the following compliant solution.
h2. Compliant Solution (internal private final lock {{Object}})
This compliant solution uses an internal private final lock object. This is one of the few cases where a {{java.lang.Object}} instance is useful.
{code:bgColor=#ccccff}
private final Object lock = new Object();
public void doSomething() {
synchronized(lock) {
// ...
}
}
|
...
{code} For more information on using an {{Object}} as a lock, see [CON04-J. Synchronize using an internal private final lock object]. h2. |
...
Noncompliant Code Example (interned {{String}} object) |
...
This noncompliant code example locks on an interned {{String}} object. |
...
{code | ||
:bgColor | =#FFcccc | } private final String _lock = new String("LOCK").intern(); public void doSomething() { synchronized(_lock) { // ... } } {code} |
...
According to the Java API \[[API 06|AA. Java References#API 06]\], class {{java.lang.String}} documentation: |
...
{quote} When the {{intern()}} method is invoked, if the pool already contains a string equal to this {{String}} object as determined by the {{equals(Object)}} method, then the string from the pool is returned. Otherwise, this {{String}} object is added to the pool and a reference to this {{String}} object is returned. |
...
{quote} Consequently, an interned {{String}} object behaves like a global variable in the Java Virtual Machine (JVM). As demonstrated in this noncompliant code example, even if every instance of an object maintains its own |
...
Noncompliant Code Example (String
literal)
This noncompliant code example locks on a final String
literal.
Code Block | ||
---|---|---|
| ||
field {{lock}}, the field points to a common {{String}} constant in the JVM. Trusted code that locks on the same {{String}} constant renders all synchronization attempts inadequate. Similarly, hostile code from any other package can exploit this vulnerability if the class is accessible. h2. Noncompliant Code Example ({{String}} literal) This noncompliant code example locks on a final {{String}} literal. {code:bgColor=#FFcccc} // This bug was found in jetty-6.1.3 BoundedThreadPool private final String _lock = "LOCK"; // ... synchronized(_lock) { // ... } // ... {code} A {{String}} literal is a constant and is interned. Consequently, it suffers from the same pitfalls as the preceding |
...
Compliant Solution (String
instance)
This compliant solution locks on a String
instance that is not interned.
Code Block | ||
---|---|---|
| ||
noncompliant code example.
h2. Compliant Solution ({{String}} instance)
This compliant solution locks on a {{String}} instance that is not interned.
{code:bgColor=#ccccff}
private final String _lock = new String("LOCK");
public void doSomething() {
synchronized(_lock) {
// ...
}
}
|
A String
instance differs from a String
literal. The instance has a unique reference and its own intrinsic lock that is not shared by other string object instances or literals. A more suitable approach is to use an internal private lock as discussed earlier.
Noncompliant Code Example (getClass()
lock object)
Synchronizing on return values of the Object.getClass()
method, rather than a class literal can also be counterproductive. Whenever the implementing class is subclassed, the subclass locks on a completely different Class
object (subclass's type).
Code Block | ||
---|---|---|
| ||
{code}
A {{String}} instance differs from a {{String}} literal. The instance has a unique reference and its own intrinsic lock that is not shared by other string object instances or literals. A more suitable approach is to use an internal private lock as discussed earlier.
h2. Noncompliant Code Example ({{getClass()}} lock object)
Synchronizing on return values of the {{Object.getClass()}} method, rather than a class literal can also be counterproductive. Whenever the implementing class is subclassed, the subclass locks on a completely different {{Class}} object (subclass's type).
{code:bgColor=#FFcccc}
public void doSomething() {
synchronized(getClass()) {
// ...
}
}
|
...
{code} Section 4.3.2 "The Class Object" of the Java Language specification \[[JLS 05|AA. Java References#JLS 05]\] describes how method synchronization works: |
...
A class method that is declared
synchronized
synchronizes on the lock associated with theClass
object of the class.
This does not mean that a subclass using getClass()
can only synchronize on the Class
object of the base class. In fact, it will lock on its own Class
object, which may or may not be what the programmer had in mind. The intent should be clearly documented or annotated.
Compliant Solution (class name qualification)
Explicitly define the name of the class through name qualification (superclass in this compliant solution) in the synchronized block.
Code Block | ||
---|---|---|
| ||
{quote} A class method that is declared {{synchronized}} synchronizes on the lock associated with the {{Class}} object of the class. {quote} This does not mean that a subclass using {{getClass()}} can only synchronize on the {{Class}} object of the base class. In fact, it will lock on its own {{Class}} object, which may or may not be what the programmer had in mind. The intent should be clearly documented or annotated. h2. Compliant Solution (class name qualification) Explicitly define the name of the class through name qualification (superclass in this compliant solution) in the synchronized block. {code:bgColor=#ccccff} public void doSomething() { synchronized(SuperclassName.class) { // ... } } {code} The class object that is being used for synchronization should not be accessible to hostile code. If the class is package-private, callers from other packages may not access the class object, ensuring its trustworthiness as an intrinsic lock object. For more information, see [CON04-J. Synchronize using an internal private final lock object |
...
]. h2. Compliant Solution ({{Class.forName()}}) |
...
This compliant solution uses the {{Class.forName()}} method to synchronize on the superclass's {{Class}} object. |
...
{code | ||
:bgColor | =#ccccff | } public void doSomething() { synchronized(Class.forName("SuperclassName")) { // ... } } {code} The class object that is being used for synchronization should not be accessible to hostile code, as discussed in the previous compliant solution. Furthermore, care must be taken to ensure that untrusted inputs are not accepted as arguments while loading classes using {{Class.forname()}}. (See [SEC05-J. Do not expose standard APIs that use the immediate caller's class loader instance to untrusted code] for more information.) |
...
h2. Noncompliant Code Example ({{ReentrantLock}} lock object) |
...
This noncompliant code example incorrectly uses a {{ReentrantLock}} as the lock object. |
...
{code | ||
:bgColor | =#FFcccc | } private final Lock lock = new ReentrantLock(); public void doSomething() { synchronized(lock) { // ... } } {code} Similarly, it is inappropriate to lock on an object of a class that implements either the {{Lock}} or {{Condition}} interface (or both) of package {{java.util.concurrent.locks}}. Using intrinsic locks of these classes is a questionable practice even though the code may appear to function correctly. This problem usually comes up in practice when refactoring from intrinsic locking to the {{java.util.concurrent}} dynamic locking utilities. |
...
h2. Compliant Solution ({{lock()}} and {{unlock()}}) |
...
Instead of using the intrinsic locks of objects that implement the {{Lock}} interface, such as {{ReentrantLock}}, use the {{lock()}} and {{unlock()}} methods provided by the {{Lock}} interface. |
...
{code | ||
:bgColor | =#ccccff | } private final Lock lock = new ReentrantLock(); public void doSomething() { lock.lock(); try { // ... } finally { lock.unlock(); } } {code} If there is no requirement of using the advanced functionality of the dynamic locking utilities of package {{java.util.concurrent}}, prefer using the {{Executor}} framework or other concurrency primitives such as synchronization and atomic classes. h2. |
...
Noncompliant Code Example (collection view) |
...
This noncompliant code example synchronizes on the view of a synchronized map. |
...
{code | ||
:bgColor | =#FFcccc | } // map has package-private accessibility final Map<Integer, String> map = Collections.synchronizedMap(new HashMap<Integer, String>()); private final Set<Integer> set = map.keySet(); public void doSomething() { synchronized(set) { // Incorrectly synchronizes on set for(Integer k : set) { // ... } } } {code} |
...
When using synchronization wrappers, the synchronization object should be the {{Collection}} object. The synchronization is necessary to enforce atomicity ([CON07-J. Do not assume that a grouping of calls to independently atomic methods is atomic]). This noncompliant code example demonstrates inappropriate synchronization resulting from locking on a Collection view instead of the Collection object itself \[[Tutorials 08|AA. Java References#Tutorials 08]\]. |
...
The {{java.util.Collections}} interface's documentation \[[API 06|AA. Java References#API 06]\] warns about the consequences of following this practice: |
...
{quote} It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views... Failure to follow this advice may result in non-deterministic behavior |
...
Compliant Solution (collection lock object)
This compliant solution correctly synchronizes on the Collection
object instead of the Collection
view.
Code Block | ||
---|---|---|
| ||
.
{quote}
h2. Compliant Solution (collection lock object)
This compliant solution correctly synchronizes on the {{Collection}} object instead of the {{Collection}} view.
{code:bgColor=#ccccff}
// map has package-private accessibility
final Map<Integer, String> map = Collections.synchronizedMap(new HashMap<Integer, String>());
private final Set<Integer> set = map.keySet();
public void doSomething() {
synchronized(map) { // Synchronize on map, not set
for(Integer k : set) {
// ...
}
}
}
|
Risk Assessment
Synchronizing on an inappropriate object can provide a false sense of thread safety and result in non-deterministic behavior.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
CON02- J | medium | probable | medium | P8 | L2 |
Automated Detection
The following table summarizes the examples flagged as violations by FindBugs:
...
Noncompliant Code Example
...
Flagged
...
Checker
...
Message
...
Boolean
lock object
...
Yes
{code} h2. Risk Assessment Synchronizing on an inappropriate object can provide a false sense of thread safety and result in non-deterministic behavior. || Rule || Severity || Likelihood || Remediation Cost || Priority || Level || | CON02- J | medium | probable | medium | {color:#cc9900}{*}P8{*}{color} | {color:#cc9900}{*}L2{*}{color} | h3. Automated Detection The following table summarizes the examples flagged as violations by FindBugs: ||Noncompliant Code Example||Flagged||Checker||Message|| |{{Boolean}} lock object|Yes|DL_SYNCHRONIZATION_ON_BOOLEAN |
...
|Synchronization on Boolean could deadlock |
...
| |Boxed primitive |
...
|Yes |
...
|DL_SYNCHRONIZATION_ON_BOXED_PRIMITIVE |
...
|Synchronization on Integer could deadlock |
...
interned String
object
...
No
| |interned {{String}} object|No|DL_SYNCHRONIZATION_ON_SHARED_CONSTANT |
...
|n/a |
...
| |String literal |
...
|Yes |
...
||Synchronization on interned String could deadlock |
...
| |{{getClass()}} lock object |
...
|No |
...
|WL_USING_GETCLASS_RATHER_THAN_CLASS_LITERAL |
...
|n/a |
...
ReentrantLock
lock object
...
No
| |{{ReentrantLock}} lock object|No||n/a |
...
| |Collection view |
...
|No |
...
|n/a |
...
| The following table summarizes the examples flagged as violations by [SureLogic Flashlight |
...
Noncompliant Code Example | Flagged | Message |
---|---|---|
| No | No obvious issues |
Boxed primitive | No | No obvious issues |
interned | No | No obvious issues |
String literal | No | No data available about field accesses |
| No | No data available about field accesses |
| No | No obvious issues |
Collection view | No | No obvious issues |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
...
|http://www.surelogic.com/]: ||Noncompliant Code Example||Flagged||Message|| |{{Boolean}} lock object|No|No obvious issues| |Boxed primitive|No|No obvious issues| |interned {{String}} object|No|No obvious issues| |String literal|No||No data available about field accesses| |{{getClass()}} lock object|No|No data available about field accesses| |{{ReentrantLock}} lock object|No|No obvious issues| |Collection view|No|No obvious issues| h3. Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rule on the [CERT website|https://www.kb.cert.org/vulnotes/bymetric?searchview&query=FIELD+KEYWORDS+contains+CON36-J]. h2. References \[[API 06|AA. Java References#API 06]\] Class String, Collections \[[Pugh 08|AA. Java References#Pugh 08]\] "Synchronization" \[[Miller 09|AA. Java References#Miller 09]\] Locking \[[Tutorials 08|AA. Java References#Tutorials 08]\] [Wrapper Implementations|http://java.sun.com/docs/books/tutorial/collections |
...
/implementations/wrapper.html] ---- [!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_left.png!|VOID CON00-J. Synchronize access to |
...
shared mutable variables] [!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_up.png!|11. Concurrency (CON)] [!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_right.png!|CON03-J. Do not use background threads during class initialization] |