Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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. There are two ways to synchronize access to shared mutable variables: method synchronization and block synchronization. A method Methods declared as synchronized always uses the object’s monitor (intrinsic lock), as does code that synchronizes on the this reference using a synchronized block. Poorly synchronized code is prone to contention and deadlockand 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 these conditions and cause a denial of service 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 Wiki MarkupThis vulnerability can be prevented using a {{java.lang.Object}} declared {{private}} and {{final}} within the class. The object must be used explicitly for locking purposes in synchronized blocks within the class’s methods. This intrinsic lock is associated with the instance of the private object and not the class. Consequently, there is no lock contention between this class’s methods and the methods of a hostile class. Bloch refers to this technique as the “private lock object” idiom \[[Bloch 2001|AA. Bibliography#Bloch 01]\].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 Static state has the same potential problem. If a static method is declared synchronized, it acquires the intrinsic lock of the class object is acquired before any statements in its body are executed, and it releases the intrinsic lock is released when the method completes. Any untrusted Untrusted code that can 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. Static Protect static data can be protected by locking on a private static final Object. Reducing the accessibility of the class to package-private adds provides further protection against untrusted callers.

This The private lock object idiom is also suitable for classes that are designed for inheritance. If When a superclass thread requests a lock on the object’s object's monitor, a subclass thread can interfere with its operation. For example, a subclass may use the superclass object’s object's intrinsic lock for performing unrelated operations, caus-ing significant 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 . It and also permits fine-grained locking because by supporting the use of multiple lock objects can be used for unrelated operations, increasing . This increases the overall responsiveness of the application.

An object should use a private final Objects that require synchronization must use the private lock object idiom rather than its their own intrinsic lock unless the class can guarantee that in any case where untrusted code cannotcould:

  • subclass Subclass the class or its superclass (trusted code is allowed to subclass the class).
  • Create create an object of the class , its superclass, or of a subclass.access
  • Access or acquire an object instance of the class , its superclass, or of a subclass.

Subclasses whose superclasses use the private lock object idiom must themselves use the idiom. However, when If a class uses a private final lock to synchronize shared data, subclasses must also use a private final lock. However, if a class uses intrinsic synchronization over on the class object without documenting its locking policy, subclasses may must not use intrinsic synchronization over on their own class object, unless they explicitly document their locking policy. If . When the superclass documents its policy by stating that client-side locking is supported, the subclasses have the option of choosing to choose between intrinsic locking over the class object and a and using the private lock . Regardless of which is chosen, subclasses object idiom. Subclasses must document their locking policy regardless of which locking option is chosen. See guideline rule TSM00-J. Do not override thread-safe methods with methods that are not thread-safe for related information.

If all When any of these restrictions are not metviolated, the object’s object's intrinsic lock is not trustworthy. If they are met, the object gains no significant security from using a private final lock object and may synchronize using its 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, it is still best to use block synchronization with a using the private final lock object instead of method synchronization when the method contains non-atomic operations that either do not require any synchronization or can 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 . Non-atomic 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. For Both for this reason and maintainability reasonsfor simplification of maintenance, block synchronization using a the private final lock object idiom is generally recommendedpreferred over intrinsic synchronization.

Noncompliant Code Example (Method Synchronization)

This noncompliant code example exposes instances of the SomeObject class to untrusted code.

Code Block
bgColor#FFCCCC

public class SomeObject {

  // Locks on the object's monitor
  public synchronized void changeValue() { 
    // Locks on the object's monitor ...
  }
 
  public static SomeObject lookup(String name) {
    // ...
  }
}

// Untrusted code
String name = // ...
SomeObject someObject = new SomeObject.lookup(name);
if (someObject == null) {
  // ... handle error
}
synchronized (someObject) {
  while (true) {
    // Indefinitely lock someObject
    Thread.sleep(Integer.MAX_VALUE); // Indefinitely delay someObject
  }
}

The untrusted code attempts to acquire a lock on the object’s 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 guideline 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 non-final nonfinal object in an attempt to use a lock other than {{SomeObject}}’s 's intrinsic lock.

Code Block
bgColor#FFcccc

public class SomeObject {
  public Object lock = new Object();

  public void changeValue() {
    synchronized (lock) {
      // ...
    }
  }
}

However, it is possible for untrusted code to change 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 and disrupt proper synchronization.

Noncompliant Code Example (Publicly Accessible Non-

...

final Lock Object)

This noncompliant code example synchronizes on a private but non-final fieldpublicly accessible but nonfinal field. The lock field is declared volatile so that changes are visible to other threads.

Code Block
bgColor#FFcccc

public class SomeObject {
  private volatile Object lock = new Object();

  public void changeValue() {
    synchronized (lock) {
      // ...
    }
  }

  public void setLock(Object lockValue) {
    lock = lockValue;
  }
}

Any thread can modify the field’s 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 enabling permitting them to execute the two critical sections in an unsafe manner. For example, if the lock were changed when one thread is was in its critical section and the lock is changed, a second thread will would lock on the new object instead of the old one and would enter its critical section erroneously.

A class that does not provide any lacks accessible methods to change the lock is secure against untrusted manipulation. However, it is remains susceptible to inadvertent modification by the programmer. For maintainability reasons, eliminating the accessor method (which is presumably needed for other reasons) is not the preferred solution.

Noncompliant Code Example (Public Final Lock Object)

This noncompliant code example uses a public final lock object.

Code Block
bgColor#FFcccc

public class SomeObject {
  public final Object lock = new Object();

  public void changeValue() {
    synchronized (lock) {
      // ...
    }
  }
}

// Untrusted code
SomeObject someObject = new SomeObject();
someObject.lock.wait()

This noncompliant code example also violates rule OBJ01-J. Limit accessibility of fields.Untrusted code that has the ability to create an instance of the class or has access to an already created instance can invoke the wait() method on the publicly accessible lock, causing the lock in the changeValue() method to be released immediately. Furthermore, if the method invokes lock.wait() from its body and does not test a condition predicate, it will be vulnerable to malicious notifications. (See guideline THI03-J. Always invoke wait() and await() methods inside a loop for more information.)

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 from to callers that are outside the class's scope.

Code Block
bgColor#ccccff

public class SomeObject {
  private final Object lock = new Object(); // private final lock object

  public void changeValue() {
    synchronized (lock) { // Locks on the private Object
      // ...
    }
  }
}

A private final lock object can only be used only with block synchronization. Block synchronization is preferred over method synchronization , because operations that do not require without a requirement for synchronization can be moved outside the synchronized region, reducing lock contention and blocking. Note that there it is no need unnecessary to declare the lock field volatile because of the strong visibility semantics of final fields. Instead of using setter methods to change the lockWhen 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
bgColor#FFCCCC

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 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 guideline rule LCK05-J. Synchronize access to static fields that can be modified by untrusted code. However, in
In the untrusted code, the attacker intentionally violates guideline rule LCK09-J. Do not perform operations that can block while holding a lock.

...

Thread-safe public classes that may interact with untrusted code and 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
bgColor#ccccff

public class SomeObject {
  private static final Object lock = new Object(); // private final lock object

  public static void changeValue() {
    synchronized (lock) { // Locks on the private Object
      // ...
    }
  }
}

In this compliant solution, changeValue() obtains a lock on a private static Object that is inaccessible to the caller.

Exceptions

LCK00-EX1J-EX0: A class may violate this guideline, if 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 does not cannot invoke methods, directly or indirectly, on objects of any untrusted classes that violate this guide-line directly or indirectlyrule.
  • The synchronization policy of the class is documented properly.

A client may Clients are permitted to use a class that violates this guideline, if rule when all of the following conditions are met:

  • The class does not pass objects of this Neither the client class nor any other class in the system passes objects of the violating class to untrusted code.
  • The class does not use any violating class cannot invoke methods, directly or indirectly, from untrusted classes that violate this guideline directly or indirectlyrule.

LCK00-J-EX2EX1: If 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-EX3EX2: A package-private class may violate this guideline because its 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 condition exemption should be documented explicitly so to ensure that trusted code within the same package does not reuse or change neither reuses the lock object nor changes the lock object inadvertently.

Risk Assessment

Exposing the class lock object to untrusted code can result in denial of serviceDoS.

Guideline

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

LCK00-J

low

probable

medium

P4

L3

Bibliography

Wiki Markup
\[[Bloch 2001|AA. Bibliography#Bloch 01]\] Item 52: "Document Thread Safety"

Automated Detection

ToolVersionCheckerDescription
The Checker Framework

Include Page
The Checker Framework_V
The Checker Framework_V

Lock CheckerConcurrency and lock errors (see Chapter 6)
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

JAVA.CONCURRENCY.LOCK.ISTR

Synchronization on Interned String (Java)

Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.LCK00.SOPFDo not synchronize on "public" fields since doing so may cause deadlocks
SonarQube
Include Page
SonarQube_V
SonarQube_V
S2445

Related Guidelines

MITRE CWE

CWE-412. Unrestricted externally accessible lock


CWE-413. Improper resource locking

Bibliography

[Bloch 2001]

Item 52. Document Thread Safety


Image Added      Image AddedLocking (LCK)      Locking (LCK)