You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 92 Next »

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 synchronized always uses the object's monitor (intrinsic lock) and so does code that synchronizes on the this reference using a synchronized block. This lock is available to any code that the object is available to; consequently, any code can lock on the object, and potentially cause a denial of service (DoS). An inappropriate synchronization policy can induce 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 hostile class.

The private lock object idiom can be used to prevent this vulnerability. The idiom consists of a private object declared as an instance field. The private 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 is not with the class itself. Consequently, there is no lock contention between this class's methods and methods of a hostile class. [[Bloch 01]]

The idiom can also be extended to protect static state by declaring the lock as private, static and final. 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 obtain access to the Class object. Reducing the accessibility of the class to package-private may offer some reprieve 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 increase 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 as opposed to coarse grained because multiple lock objects can then be used for seemingly unrelated operations. This increases overall responsiveness of the application.

An object should use a private internal final lock object rather than its own intrinsic lock unless the class can guarantee that untrusted code cannot:

  • 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 it uses intrinsic synchronization over the class object without documenting this policy, subclasses may not use intrinsic synchronization over their own class object, unless they explicitly document this locking policy. If the superclass documents this 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 the locking policy. Refer to the guideline CON10-J. Do not override thread-safe methods with thread-unsafe methods 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.

Noncompliant Code Example (method synchronization)

This noncompliant code example exposes the object someObject to untrusted code.

public class SomeObject {
  public synchronized void changeValue() { // Locks on the object's monitor
    // ...   
  }
}

// Untrusted code
synchronized (someObject) {
  while (true) {
    Thread.sleep(Integer.MAX_VALUE); // Indefinitely delay someObject
  }
}

The untrusted code attempts to acquire a lock on the object's monitor and upon succeeding, introduces an indefinite delay which holds up 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.

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.

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

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

However, it is possible for untrusted code to change the value of the lock object and foil all attempts to synchronize.

Noncompliant Code Example (publicly-accessible final lock object)

This noncompliant code example synchronizes on a private but non-final field.

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 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.

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 adapting them to use block synchronization. In this compliant solution, if the method changeValue() is called, the lock is obtained on a private final Object instance that is inaccessible from the caller.

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

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

Using a private final lock can only be achieved with block synchronization. Block synchronization is sometimes preferred over method synchronization, because operations that do not require synchronization can be moved outside the synchronized region which reduces 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.

Noncompliant Code Example (static)

This noncompliant code example exposes the class object of someObject to untrusted code.

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
  }
}

The untrusted code attempts to acquire a lock on the class object's monitor and upon succeeding, introduces an indefinite delay which holds up the synchronized changeValue() method from acquiring the same lock.

A complete implementation of this noncompliant code example would be in compliance 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.

Compliant Solution (static)

Thread-safe classes that use intrinsic synchronization over the class object should be refactored to use a static private lock object and block synchronization.

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

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

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.

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 it uses an internal private lock, it should document its inconsistent locking policy.

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

P4

L3

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

[[Bloch 01]] Item 52: "Document Thread Safety"


CON03-J. Do not use background threads during class initialization      11. Concurrency (CON)      CON05-J. Do not invoke Thread.run()

  • No labels