Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added normative text. tweaked some grammar for better exposition
Wiki Markup
Each thread in Java is assigned to a thread group upon the thread's creation. These groups are implemented by the {{java.lang.ThreadGroup}} class. IfWhen the thread group name is not specified explicitly, the {{main}} default group is assigned by the JVM \[[Tutorials 2008|AA. Bibliography#Tutorials 08]\]. The convenience methods of the {{ThreadGroup}} class can be used to operate on all threads belonging to a thread group at once. For instance, the {{ThreadGroup.interrupt()}} method interrupts all threads in the thread group. Thread groups also help reinforce layered security by confining threads into groups so that they doavoid not interfereinterference with threads in other groups \[[JavaThreads 2004|AA. Bibliography#JavaThreads 04]\].

Even though thread groups are useful for keeping threads organized, programmers seldom benefit from their use because many of the methods of the {{ThreadGroup}} class are deprecated (for example, {{allowThreadSuspension(), resume(), stop() and suspend()}}). Furthermore, many non-deprecated methods are obsolete in that they offer little desirable functionality. Ironically, a few {{ThreadGroup}} methods are not even thread-safe \[[Bloch 2001|AA. Bibliography#Bloch 01]\].

Insecure, yet non-deprecated methods, include

* {{ThreadGroup.activeCount()}}
According to the Java API, the {{activeCount()}} method \[[API 2006|AA. Bibliography#API 06]\]  
{quote}
returns an estimate of the number of active threads in this thread group.
{quote}
This method is often used as a precursor to thread enumeration. IfThreads athat threadhave is notnever started, it continues tonevertheless reside in the thread group and isare considered to be active. Furthermore, theThe active count is also affected by the presence of certain system threads \[[API 2006|AA. Bibliography#API 06]\]. Consequently, the _{{activeCount()}}_ method might fail notto reflect the actual number of running tasks in the thread group.

* {{ThreadGroup.enumerate()}}
According to the Java API, {{ThreadGroup}} class documentation \[[API 2006|AA. Bibliography#API 06]\]
{quote}
\[The {{enumerate()}} method\] copies into the specified array every active thread in this thread group and its subgroups. An application should use the {{activeCount}} method to get an estimate of how big the array should be. If the array is too short to hold all the threads, the extra threads are silently ignored.
{quote}

Using the {{ThreadGroup}} APIs to shut down threads also has pitfalls. Because the {{stop()}} method is deprecated, alternativeprograms waysrequire arealternate requiredmethods to stop threads. According to The Java Programming Language \[[JPL 2006|AA. Bibliography#JPL 06]\]
{quote}
One way is for the thread initiating the termination to join the other threads and so know when those threads have terminated. However, an application may have to maintain its own list of the threads it creates because simply inspecting the {{ThreadGroup}} may return library threads that do not terminate and for which join will not return.
{quote}

The {{Executor}} framework both provides a better API for managing a logical grouping of threads and also offers secure facilities for handling shutdown and thread exceptions \[[Bloch 2008|AA. Bibliography#Bloch 08]\].


h2. Noncompliant Code Example
 Consequently, programs in general should never -- and security-critical programs must never -- invoke {{ThreadGroup}} methods.


h2. Noncompliant Code Example

This noncompliant code example contains a {{NetworkHandler}} class that maintains a {{controller}} thread. The Thiscontroller thread delegates aeach new request to a worker thread. To demonstrate the race condition in this example, the {{controller}} thread servicesserves three requests by starting three threads in succession from its {{run()}} method. All threads are defined to belong to the {{Chief}} thread group.

{code:bgColor=#FFcccc}
final class HandleRequest implements Runnable {
  public void run() {
    // Do something
  }
}


public final class NetworkHandler implements Runnable {
  private static ThreadGroup tg = new ThreadGroup("Chief");

  @Override public void run() {
    new Thread(tg, new HandleRequest(), "thread1").start(); // Start thread 1
    new Thread(tg, new HandleRequest(), "thread2").start(); // Start thread 2
    new Thread(tg, new HandleRequest(), "thread3").start(); // Start thread 3
  }

  public static void printActiveCount(int point) {
    System.out.println("Active Threads in Thread Group " + tg.getName() +
      " at point(" + point + "):" + " " + tg.activeCount());
  }

  public static void printEnumeratedThreads(Thread[] ta, int len) {
    System.out.println("Enumerating all threads...");
    for(int i = 0; i < len; i++) {
      System.out.println("Thread " + i + " = " + ta[i].getName());
    }
  }

  public static void main(String[] args) throws InterruptedException {
    // Start thread controller
    Thread thread = new Thread(tg, new NetworkHandler(), "controller"); 
    thread.start();

    Thread[] ta = new Thread[tg.activeCount()]; // Gets the active count (insecure)

    printActiveCount(1);           // P1
    Thread.sleep(1000);            // Delay to demonstrate TOCTOU condition (race window)
    printActiveCount(2);           // P2: the thread count changes as new threads are initiated
     // Incorrectly uses the (now stale) thread count obtained at P1
    int n = tg.enumerate(ta);  
    printEnumeratedThreads(ta, n); // Silently ignores newly initiated threads
                                   // (between P1 and P2)

    // This code destroys the thread group if it does not have any alive threads
    for (Thread thr : ta) {
      thr.interrupt();
      while(thr.isAlive());
    }
    tg.destroy();
  }
}
{code}

ThereThis implementation iscontains a time-of-check-time-of-use (TOCTOU) vulnerability, inbecause this implementation because obtainingit obtains the count and enumeratingenumerates the list dowithout notensuring constituteatomicity. anIf atomicone operation.or Ifmore new requests were to occur after the call to {{activeCount()}} and before the call to {{enumerate()}} in the {{main()}} method, the total number of threads in the group willwould increase, but the enumerated list {{ta}} willwould contain only the initial number, that is, two thread references: ({{main}} and {{controller}}). Consequently, the program willwould fail to account for the newly started threads in the {{Chief}} thread group.

Any subsequent use of the {{ta}} array would isbe insecure. For example, calling the {{destroy()}} method to destroy the thread group and its sub-groups willwould not work as expected. The precondition to calling {{destroy()}} is that the thread group must isbe empty with no executing threads. The code attempts to comply with accomplishthe thisprecondition by interrupting every thread in the thread group. However, when the {{destroy()}} method is called, the thread group is not empty, which causes thread group would not empty when the {{destroy()}} method was called, causing a {{java.lang.IllegalThreadStateException}} to be thrown.

{mc} The other surprise is that after enumerating array ta, Chief also consists of a thread called "main" {mc} 

h2. Compliant Solution

This compliant solution uses a fixed thread pool, rather than a {{ThreadGroup}}, to group its three tasks. The {{java.util.concurrent.ExecutorService}} interface provides methods to manage the thread pool. Note thatthe therelack are noof methods for finding the number of actively executing threads or for enumerating throughthe themthreads. HoweverNevertheless, the logical grouping can help control the behavior of the group as a whole. For instance, invoking the {{shutdownPool()}} method terminates all threads belonging to a particular thread pool can be terminated by invoking the {{shutdownPool()}} methodthread pool.

{code:bgColor=#ccccff}
public final class NetworkHandler {
  private final ExecutorService executor;

  NetworkHandler(int poolSize) {
    this.executor = Executors.newFixedThreadPool(poolSize);
  }

  public void startThreads() {
    for(int i = 0; i < 3; i++) {
      executor.execute(new HandleRequest());
    }
  }

  public void shutdownPool() {
    executor.shutdown();
  }

  public static void main(String[] args)  {
    NetworkHandler nh = new NetworkHandler(3);
    nh.startThreads();
    nh.shutdownPool();
  }
}
{code}

Before Java SE 5.0, the {{ThreadGroup}} class hadapplications that needed to becatch extendedan becauseuncaught thereexception wasin noa otherseparate directthread wayhad to catch an uncaught exception in a separate thread. If the application had installed an extend the {{ThreadGroup}} class, because this was the only direct approach to provide the required functionality. Specifically, an application's {{UncaughtExceptionHandler}}, it could only be controlled by subclassing {{ThreadGroup}}. In more recent versions of Java, {{UncaughtExceptionHandler}} is maintained on a per-thread basis using an interface enclosed by the {{Thread}} class, which leaves little to no functionality for. Consequently, the {{ThreadGroup}} class provides very little unique functionality \[[Goetz 2006|AA. Bibliography#Goetz 06]\], \[[Bloch 2008|AA. Bibliography#Bloch 08]\].

Refer to rule [TPS03-J. Ensure that tasks executing in a thread pool do not fail silently] for more information on using uncaught exception handlers in thread pools.


h2. Risk Assessment

Using the {{ThreadGroup}} APIs may result in race conditions, memory leaks, and inconsistent object state.

|| Rule || Severity || Likelihood || Remediation Cost || Priority || Level ||
| THI01-J | low | probable | medium | {color:green}{*}P4{*}{color} | {color:green}{*}L3{*}{color} |


h3. Automated Detection 

TODO 

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+CON01-J].


h2. Bibliography

| \[[API 2006|AA. Bibliography#API 06]\] | Methods {{activeCount}} and {{enumerate}}, Classes ThreadGroup and Thread |
| \[[Bloch 01|AA. Bibliography#Bloch 01]\] | Item 53: Avoid thread groups |
| \[[Bloch 2008|AA. Bibliography#Bloch 08]\] | Item 73: Avoid thread groups |
| \[[Goetz 2006|AA. Bibliography#Goetz 06]\] | Section 7.3.1, "Uncaught Exception Handlers" |
| \[[JavaThreads 04|AA. Bibliography#JavaThreads 04]\] | 13.1 ThreadGroups |
| \[[JPL 2006|AA. Bibliography#JPL 06]\] | 23.3.3. Shutdown Strategies |
| \[[SDN 2006|AA. Bibliography#SDN 06]\] | Bug ID: 4089701 and 4229558 |
| \[[Tutorials 2008|AA. Bibliography#Tutorials 08]\] | |

----
[!The CERT Oracle Secure Coding Standard for Java^button_arrow_left.png!|THI00-J. Do not assume that the sleep(), yield() or getState() methods provide synchronization semantics]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[!The CERT Oracle Secure Coding Standard for Java^button_arrow_up.png!|09. Thread APIs (THI)]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[!The CERT Oracle Secure Coding Standard for Java^button_arrow_right.png!|THI02-J. Do not invoke Thread.run()]