Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: wordsmithing
Wiki Markup
A {{ThreadGroup}} is a group of threads as definedEach thread in Java is assigned to a thread group upon the thread's creation.  These groups are represented by the class {{java.lang.ThreadGroup}} class. A thread is assigned to a thread group upon {mc}If the thread's creation. If the group name is not specified explicitly, the default group called {{main}} is assigned by the Java Virtual Machine (JVM). <- In what context? ~DS{mc} 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 do not interfere with each other. \[[JavaThreads 04|AA. Java References#JavaThreads 04]\]

Even though thread groups are useful for organizingkeeping threads into a hierarchyorganized, programmers seldom benefit from theirthe use of thread groups because many of the methods of the class {{ThreadGroup}} are deprecated  ({{allowThreadSuspension(), resume(), stop() and suspend()}} are a few examples). 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 01|AA. Java References#Bloch 01]\]

Some of the insecure, yet non-deprecated methods are:

*{{ThreadGroup.activeCount()}}:* This method provides a way to enumerate all threads in a group as a precursor to performing other operations., yet non-deprecated methods are:

*{{ThreadGroup.activeCount()}}:* The {{activeCount()}} method "Returns an estimate of the number of active threads in this thread group." \[[API 06|AA. Java References#API 06]\]. This method can often used as a precursor to enumerating through the threads.  If a thread is not started, it continues to reside in the thread group and is considered to be active. Furthermore, the active count is affected by the presence of certain system threads \[[API 06|AA. Java References#API 06]\]. Consequently, the {{activeCount()}} method may not reflect the actual number of running tasks in the thread group.  

*{{ThreadGroup.enumerate()}}:* According to the Java API, class {{ThreadGroup}} documentation \[[API 06|AA. Java References#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 facilitate thread shutdown also has pitfalls. Because the {{stop()}} method is deprecated, alternative ways are required to stop threads. "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." \[[JPL 06|AA. Java References#JPL 06]\].

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


h2. Noncompliant Code Example

This noncompliant code example shows a {{NetworkHandler}} class that maintains a _controller_ thread {{controller}}. This thread delegates a new request to a corresponding worker thread. To demonstrate the race condition in this example, the {{controller}} thread services 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");

  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 {
    Thread thread = new Thread(tg, new NetworkHandler(), "controller"); // Start thread controller
    thread.start();
	     
    Thread[] ta = new Thread[tg.activeCount()]; // Gets the active count (insecure) 		

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

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

There is a Time of Check-Time of Use (TOCTOU) vulnerability in this implementation because obtaining the count and enumerating the list do not constitute an atomic operation. If new requests come in during the time interval between calling {{activeCount()}} and {{enumerate()}} in the {{main()}} method, the total number of threads in the group will increase but the enumerated list {{ta}} will contain only the initial number, that is two thread references ({{main}} and {{controller}}). Consequently, the program will operate on stale data instead of taking into account the newly started threads in the thread group {{Chief}}.

Any subsequent use of the {{ta}} array is insecure. For example, using the {{destroy()}} method to destroy the thread group and its sub-groups does not work as expected. The precondition to calling {{destroy()}} is that the thread group is empty with no executing threads. The code tries to ensure this by interrupting every thread in the thread group. However, when the {{destroy()}} method is called, the thread group is not empty, which raisescuases 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 to group its three tasks, instead of a {{ThreadGroup}}. The {{java.util.concurrent.ExecutorService}} interface provides methods to manage the thread pool. Note that there is no method available for finding the number of actively executing threads or for enumerating through them. However, the logical grouping can help control the behavior of the group as a whole. For instance, all threads belonging to a particular thread pool can be terminated as required.

{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 had to be extended because there was no other direct way to catch an uncaught exception in a separate thread.  If the application had an installed exception handler {{UncaughtExceptionHandler}}, the only way to control it was to subclass {{ThreadGroup}}. In recent versions, the {{UncaughtExceptionHandler}} is maintained on a per-thread basis using an interface enclosed by the {{Thread}} class, which leaves little to no functionality for the {{ThreadGroup}} class. \[[Goetz 06|AA. Java References#Goetz 06]\], \[[Bloch 08|AA. Java References#Bloch 08]\]

Refer to [CON37-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 ||
| CON17- 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. References

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

----
[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_left.png!|CON16-J. Do not expect sleep(), yield() and getState() methods to have any synchronization semantics]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_up.png!|11. Concurrency (CON)]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_right.png!|CON18-J. Always invoke wait() and await() methods inside a loop]