There are two ways to synchronize access to shared mutable variables: method synchronization and block synchronization. Methods declared as synchronized and blocks that synchronize on the this
reference both use the object as a monitor (that is, its intrinsic lock). An attacker can manipulate the system to trigger contention and deadlock by obtaining and indefinitely holding the intrinsic lock of an accessible class, consequently causing a denial of service (DoS).
One technique for preventing this vulnerability is the private lock object idiom [Bloch 2001]. This idiom uses the intrinsic lock associated with the instance of a private final java.lang.Object
declared within the class instead of the intrinsic lock of the object itself. This idiom requires the use of synchronized blocks within the class's methods rather than the use of synchronized methods. Lock contention between the class's methods and those of a hostile class becomes impossible because the hostile class cannot access the private final lock object.
Static methods and state also share this vulnerability. When a static method is declared synchronized
, it acquires the intrinsic lock of the class object before any statements in its body are executed, and it releases the intrinsic lock when the method completes. Untrusted code that has access to an object of the class, or of a subclass, can use the getClass()
method to gain access to the class object and consequently manipulate the class object's intrinsic lock. Protect static data by locking on a private static final Object
. Reducing the accessibility of the class to package-private provides further protection against untrusted callers.
The private lock object idiom is also suitable for classes that are designed for inheritance. When a superclass requests a lock on the object's monitor, a subclass can interfere with its operation. For example, a subclass may use the superclass object's intrinsic lock for performing unrelated operations, causing lock contention and deadlock. Separating the locking strategy of the superclass from that of the subclass ensures that they do not share a common lock and also permits fine-grained locking by supporting the use of multiple lock objects for unrelated operations. This increases the overall responsiveness of the application.
Objects that require synchronization must use the private lock object idiom rather than their own intrinsic lock in any case where untrusted code could:
- Subclass the class.
- Create an object of the class or of a subclass.
- Access or acquire an object instance of the class or of a subclass.
Subclasses whose superclasses use the private lock object idiom must themselves use the idiom. However, when a class uses intrinsic synchronization on the class object without documenting its locking policy, subclasses must not use intrinsic synchronization on their own class object. When the superclass documents its policy by stating that client-side locking is supported, the subclasses have the option to choose between intrinsic locking and using the private lock object idiom. Subclasses must document their locking policy regardless of which locking option is chosen. See rule TSM00-J. Do not override thread-safe methods with methods that are not thread-safe for related information.
When any of these restrictions are violated, the object's intrinsic lock cannot be trusted. But when these restrictions are obeyed, the private lock object idiom fails to add any additional security. Consequently, objects that comply with all of the restrictions are permitted to synchronize using their own intrinsic lock. However, block synchronization using the private lock object idiom is superior to method synchronization for methods that contain nonatomic operations that could either use a more fine-grained locking scheme involving multiple private final lock objects or that lack a requirement for synchronization. Nonatomic operations can be decoupled from those that require synchronization and can be executed outside the synchronized block. Both for this reason and for simplification of maintenance, block synchronization using the private lock object idiom is generally preferred over intrinsic synchronization.
Noncompliant Code Example (Method Synchronization)
This noncompliant code example exposes instances of the SomeObject
class to untrusted code.
Code Block | ||
---|---|---|
| ||
public class SomeObject {
// Locks on the object's monitor
public synchronized void changeValue() {
// ...
}
public static SomeObject lookup(String name) {
// ...
}
}
// Untrusted code
String name = // ...
SomeObject someObject = SomeObject.lookup(name);
if (someObject == null) {
// ... handle error
}
synchronized (someObject) {
while (true) {
// Indefinitely lock someObject
Thread.sleep(Integer.MAX_VALUE);
}
}
|
The untrusted code attempts to acquire a lock on the object's monitor and, upon succeeding, introduces an indefinite delay that prevents the synchronized changeValue()
method from acquiring the same lock. Furthermore, the object locked is publicly available via the lookup()
method.
Alternatively, an attacker could create a private SomeObject
object and make it available to trusted code to use it before the attacker code grabs and holds the lock.
Note that in the untrusted code, the attacker intentionally violates rule LCK09-J. Do not perform operations that can block while holding a lock.
Noncompliant Code Example (Public Non-final Lock Object)
This noncompliant code example locks on a public nonfinal object in an attempt to use a lock other than {{SomeObject}}'s intrinsic lock.
Code Block | ||
---|---|---|
| ||
public class SomeObject {
public Object lock = new Object();
public void changeValue() {
synchronized (lock) {
// ...
}
}
}
|
This change fails to protect against malicious code. For example, untrusted or malicious code could disrupt proper synchronization by changing the value of the lock object.
Noncompliant Code Example (Publicly Accessible Non-final Lock Object)
This noncompliant code example synchronizes on a publicly accessible but nonfinal field. The lock
field is declared volatile so that changes are visible to other threads.
Code Block | ||
---|---|---|
| ||
Wiki Markup | ||
The {{synchronized}} keyword is used to acquire a mutual-exclusion lock so that no other thread can acquire the lock while it is being held by the executing thread. Recall that there are two ways to synchronize access to shared mutable variables, method synchronization and block synchronization. A method declared as {{synchronized}} always uses the object's monitor (intrinsic lock) and so does code that synchronizes on the {{this}} reference using a synchronized block. Because this lock is available to any code that the object is available to, any code that can lock on the object can potentially cause a denial of service (DoS). An inappropriate synchronization policy can create a DoS vulnerability because another class whose member locks on the same object, can fail to release the lock promptly. However, this requires the victim class to be accessible from the offending class. Untrusted callers may purposely exploit this vulnerability to cause DoS. {mc} note that even trusted classes can leave the code vulnerable {mc} The _private lock object_ idiom can be used to prevent this vulnerability. The idiom consists of a raw {{Object}} declared within the class as {{private}} and {{final}}. The object must be explicitly used for locking purposes in {{synchronized}} blocks, within the class's methods. This intrinsic lock is associated with the instance of the internal private object and not with the class itself. Consequently, there is no lock contention between this class's methods and methods of a hostile class. \[[Bloch 01|AA. Java References#Bloch 01]\] Static state has the same potential problem. If a static method is declared {{synchronized}}, the intrinsic lock of the Class object is acquired before executing the statements in its body, and released when the method completes. Any untrusted code that can access an object of the class, or a subclass, can use the {{getClass()}} method to gain access to the Class object. The private internal lock object idiom can be used to protect static data by declaring the lock as {{private}}, {{static}} and {{final}}. Reducing the accessibility of the class to package-private may offer some reprieve from untrusted callers when using strategies other than internal locking. This idiom can also be suitably used by classes designed for inheritance. If a superclass thread requests a lock on the object's monitor, a subclass thread can interfere with its operation. For example, a subclass may use the superclass object's intrinsic lock for unrelated operations, causing significant increases in lock contention. Also, excessive use of the same lock frequently results in deadlocks. This idiom separates the locking strategy of the superclass from that of the subclass. It also permits fine-grained locking because multiple lock objects can then be used for seemingly unrelated operations. This increases the overall responsiveness of the application. An object should use an internal private lock object rather than its own intrinsic lock unless the class can guarantee that untrusted code can not: * Subclass the class or its superclass (trusted code is allowed to subclass the class) * Create an object of the class (or its superclass, or subclass) * Access or acquire an object instance of the class (or its superclass, or subclass) If a superclass uses an internal private lock to synchronize shared data, subclasses must also use an internal private lock. However, if a class uses intrinsic synchronization over the class object without documenting its locking policy, subclasses may not use intrinsic synchronization over their own class object, unless they explicitly document their locking policy. If the superclass documents its policy by stating that client-side locking is supported, the subclasses have the option of choosing between intrinsic locking over the class object and an internal private lock. Regardless of what is chosen, subclasses must document their locking policy. Refer to the guideline [CON10-J. Do not override thread-safe methods with methods that are not thread-safe] for related information. If these restrictions are not met, the object's intrinsic lock is not trustworthy. If all conditions are satisfied, then the object gains no significant security from using a private internal lock object, and may synchronize using its own intrinsic lock. h2. Noncompliant Code Example (method synchronization) This noncompliant code example exposes the object {{someObject}} to untrusted code. {code:bgColor=#FFCCCC} public class SomeObject { publicprivate volatile synchronizedObject voidlock changeValue()= { // Locks on the object's monitor new Object(); public void changeValue() { synchronized (lock) { // ... } } } // Untrustedpublic code synchronizedvoid setLock(someObjectObject lockValue) { while (true) { lock Thread.sleep(Integer.MAX_VALUE); // Indefinitely delay someObject= lockValue; } } {code} The untrusted code attempts to acquire a lock on the object's monitor and upon succeeding, introduces an indefinite delay which prevents the {{synchronized}} {{changeValue()}} method from acquiring the same lock. Note that the untrusted code also violates [CON20-J. Do not perform operations that may block while holding a lock]. h2. Noncompliant Code Example ({{public}} non-final lock object) This noncompliant code example locks on a {{public}} non-final object in an attempt to use a lock that differs from {{SomeObject}}'s own intrinsic lock. {code:bgColor=#FFcccc} |
Any thread can modify the field's value to refer to a different object in the presence of an accessor such as setLock()
. That modification might cause two threads that intend to lock on the same object to lock on different objects, thereby permitting them to execute two critical sections in an unsafe manner. For example, if the lock were changed when one thread was in its critical section, a second thread would lock on the new object instead of the old one and would enter its critical section erroneously.
A class that lacks accessible methods to change the lock is secure against untrusted manipulation. However, it remains susceptible to inadvertent modification by the programmer.
Noncompliant Code Example (Public Final Lock Object)
This noncompliant code example uses a public final lock object.
Code Block | ||
---|---|---|
| ||
public class SomeObject { public final Object lock = new Object(); public void changeValue() { synchronized (lock) { // ... } } } {code} However, it is possible for untrusted code to change the value of the lock object and foil all attempts to synchronize on the correct object. h2. Noncompliant Code Example (publicly-accessible final lock object) This noncompliant code example synchronizes on |
This noncompliant code example also violates rule OBJ01-J. Limit accessibility of fields.
Compliant Solution (Private Final Lock Object)
Thread-safe public classes that may interact with untrusted code must use a private final lock object. Existing classes that use intrinsic synchronization must be refactored to use block synchronization on such an object. In this compliant solution, calling changeValue()
obtains a lock on a private final Object
instance that is inaccessible to callers that are outside the class's scope.
Code Block | ||
---|---|---|
| ||
public class SomeObject { private final Object lock = new Object(); // private final lock objecta private but non-final field. {code:bgColor=#FFcccc} public class SomeObject { private volatile Object lock = new Object(); public void changeValue() { synchronized (lock) { // Locks on the private // ... Object } // }... public void setLock(Object lockValue) { lock = lockValue; } } } {code} Any thread can modify the field's value to refer to some other object in the presence of an accessor such as {{setLock()}}. This might cause two threads that intend to lock on the same object to lock on different objects, enabling them to execute the two critical sections in an unsafe manner. For example, if one thread is in its critical section and the lock is changed, a second thread would lock on the new reference instead of the old one. h2. Compliant Solution (private final internal lock object) Thread-safe classes that use the intrinsic synchronization of their respective objects may be protected by using the _private lock object idiom_ and refactoring them to use block synchronization. In this compliant solution, if the method |
A private final lock object can be used only with block synchronization. Block synchronization is preferred over method synchronization because operations without a requirement for synchronization can be moved outside the synchronized region, reducing lock contention and blocking. Note that it is unnecessary to declare the lock
field volatile because of the strong visibility semantics of final fields. When granularity issues require the use of multiple locks, declare and use multiple private final lock objects to satisfy the granularity requirements rather than using a mutable reference to a lock object along with a setter method.
Noncompliant Code Example (Static)
This noncompliant code example exposes the class object of SomeObject
to untrusted code.
Code Block | ||
---|---|---|
| ||
public class SomeObject {
//changeValue locks on the class object's monitor
public static synchronized void changeValue() {
// ...
}
}
// Untrusted code
synchronized (SomeObject.class) {
while (true) {
Thread.sleep(Integer.MAX_VALUE); // Indefinitely delay someObject
}
}
|
The untrusted code attempts to acquire a lock on the class object''s monitor and, upon succeeding, introduces an indefinite delay that prevents the synchronized changeValue()
method from acquiring the same lock.
A compliant solution must also comply with rule LCK05-J. Synchronize access to static fields that can be modified by untrusted code.
In the untrusted code, the attacker intentionally violates rule LCK09-J. Do not perform operations that can block while holding a lock.
Compliant Solution (Static)
Thread-safe public classes that both use intrinsic synchronization over the class object and may interact with untrusted code must be refactored to use a static private final lock object and block synchronization.
Code Block | ||
---|---|---|
| ||
public class SomeObject { private static {{changeValue()}} is called, the lock is obtained on a {{private final}} {{Object}} instance that is inaccessible from the caller. {code:bgColor=#ccccff} public class SomeObject { private final Object lock = new Object(); // private lock object public static void changeValue() { synchronized (lock) { // Locks on the private Object // ... } } } {code} A private final lock can only be used with block synchronization. Block synchronization is preferred over method synchronization, because operations that do not require synchronization can be moved outside the synchronized region, reducing the overall execution time. Note that there is no need to declare {{lock}} as volatile because of the strong visibility semantics of final fields. Instead of using setter methods to change the lock, declare and use multiple internal lock objects to achieve the necessary fine-grained locking semantics. h2. Noncompliant Code Example (static) This noncompliant code example exposes the class object of {{someObject}} to untrusted code. {code:bgColor=#FFCCCC} public class SomeObject { public static synchronized void ChangeValue() { // Locks on the class object's monitor // ... } } // Untrusted code synchronized (someObject.getClass()) { while (true) { Thread.sleep(Integer.MAX_VALUE); // Indefinitely delay someObject } } {code} The untrusted code attempts to acquire a lock on the class object's monitor and upon succeeding, introduces an indefinite delay which prevents the {{synchronized}} {{changeValue()}} method from acquiring the same lock. A complete implementation of this noncompliant code example would comply with [CON32-J. Internally synchronize classes containing accessible mutable static fields]. However, the untrusted code violates [CON20-J. Do not perform operations that may block while holding a lock]. h2. Compliant Solution (static) Thread-safe classes that use intrinsic synchronization over the class object should be refactored to use a static private internal lock object and block synchronization. {code:bgColor=#ccccff} public class SomeObject { private static final Object lock = new Object(); // private lock object public static void ChangeValue() { synchronized (lock) { // Locks on the private Object // ... } } } {code} In this compliant solution, if the method {{ChangeValue()}} is called, the lock is obtained on a {{static}} {{private}} {{Object}} that is inaccessible from the caller. h2. Exceptions *EX1:* A class may violate this guideline, if all the following conditions are met: * it sufficiently documents that callers must not pass objects of this class to untrusted code, * the class does not invoke methods on objects of any untrusted classes that violate this guideline directly or indirectly, * the synchronization policy of the class is properly documented. Classes that claim to support client-side locking should be used with care. A client may use a class that violates this guideline, if all the following conditions are met: * it does not not pass objects of this class to untrusted code by using suitable encapsulation * it does not use any untrusted classes that violate this guideline directly or indirectly *EX2:* If a superclass of the class documents that it supports client-side locking and synchronizes on its class object, the class should also support client-side locking in the same way and document this policy. If instead the superclass uses an internal private lock, the derived class should document its own locking policy. h2. Risk Assessment Exposing the class object to untrusted code can result in denial-of-service. || Recommendation || Severity || Likelihood || Remediation Cost || Priority || Level || | CON04-J | low | probable | medium | {color:green}{*}P4{*}{color} | {color:green}{*}L3{*}{color} | 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+CON03-J]. h2. References \[[Bloch 01|AA. Java References#Bloch 01]\] Item 52: "Document Thread Safety" ---- [!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_left.png!|CON03-J. Do not use background threads during class initialization] [!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!|CON05-J. Do not invoke Thread.run()] |
In this compliant solution, changeValue()
obtains a lock on a private static Object
that is inaccessible to the caller.
Exceptions
LCK00-J-EX0: A class may violate this rule when all of the following conditions are met:
- It sufficiently documents that callers must not pass objects of this class to untrusted code.
- The class cannot invoke methods, directly or indirectly, on objects of any untrusted classes that violate this rule.
- The synchronization policy of the class is documented properly.
Clients are permitted to use a class that violates this rule when all of the following conditions are met:
- Neither the client class nor any other class in the system passes objects of the violating class to untrusted code.
- The violating class cannot invoke methods, directly or indirectly, from untrusted classes that violate this rule.
LCK00-J-EX1: When a superclass of the class documents that it supports client-side locking and synchronizes on its class object, the class can support client-side locking in the same way and document this policy.
LCK00-J-EX2: Package-private classes that are never exposed to untrusted code are exempt from this rule because their accessibility protects against untrusted callers. However, use of this exemption should be documented explicitly to ensure that trusted code within the same package neither reuses the lock object nor changes the lock object inadvertently.
Risk Assessment
Exposing the lock object to untrusted code can result in DoS.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
LCK00-J | low | probable | medium | P4 | L3 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
The Checker Framework |
| Lock Checker | Concurrency and lock errors (see Chapter 6) | ||||||
CodeSonar |
| JAVA.CONCURRENCY.LOCK.ISTR | Synchronization on Interned String (Java) | ||||||
Parasoft Jtest |
| CERT.LCK00.SOPF | Do not synchronize on "public" fields since doing so may cause deadlocks | ||||||
SonarQube |
| S2445 |
Related Guidelines
Bibliography
Item 52. Document Thread Safety |