Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: improved nce so that it shows the race condition more clearly
Wiki Markup
A {{ThreadGroup}} is a group of threads as defined by the class {{java.lang.ThreadGroup}}. A group is assigned to a thread upon its creation. If the group name is not specified explicitly, the default group called {{main}} is assigned by the Java Virtual Machine (JVM). The convenience methods of the {{ThreadGroup}} class can be used to operate on all threads at once, such as, by using the {{interrupt()}} method. Another use is to reinforce layered security by confining threads into groups so that they do not interfere with each other. \[[JavaThreads 04|AA. Java References#JavaThreads 04]\]

...



While there may be a few benefits, the associated dangers demand deeper insight into the real utility of the {{ThreadGroup}} class. Several of the {{ThreadGroup}} APIs ({{allowThreadSuspension, resume, stop, suspend}}) have been deprecated and the remainder are seldom used because they offer little desirable functionality. Ironically, a few APIs are not even thread-safe. \[[Bloch 01|AA. Java References#Bloch 01]\]

...



A programmer may sometimes wish to enumerate all the threads in a group as a precursor to other operations. This is accomplished by using the {{activeCount()}} method that "Returns an estimate of the number of active threads in this thread group. " \[[API 06|AA. Java References#API 06]\]. Notice that there is no absolute word on whether it returns the exact count or not; the definition of _active_ also has a different connotation here. A thread that is constructed and not started is still counted by the {{activeCount()}} method as _active_. 

...



According to the Java API \[[API 06|AA. Java References#API 06]\], class {{ThreadGroup}} documentation:

...



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

Threads are removed from the thread array either when they are stopped or when their {{run()}} method has finished 

...

executing. As a result, if a thread is not started, it continues to reside in the array despite the loss of the original reference. \[[JavaThreads 99|AA. Java References#JavaThreads 99]\]

...



Using the {{ThreadGroup}} APIs to facilitate thread shutdown also has pitfalls. "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]\].

...



h2. Noncompliant Code Example

...



This noncompliant code example shows a {{NetworkHandler}} class that maintains a _controller_ thread. This thread is responsible for spawning a new thread every time a new network connection request is received. For the sake of brevity, it is assumed that the _controller_ thread invokes two methods ({{method1()}} and {{method2()}}) in succession and waits for a few milliseconds. The {{method1()}} method creates and starts two threads that are equivalent to two consequent connection requests, and so does the {{method2()}} method. All threads are defined to belong to the same group, {{Chief

...

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(), the total number of threads in the group will increase but the enumerated list ta will contain only two thread references. Print statements have been added before the invocation of activecount() and enumerate() to show this effect. Different runs of the program produce different values because of the race conditions and demonstrate how a few incoming requests can get completely ignored. Any subsequent use of the ta array may lead to undesirable object retention.

Code Block
bgColor#FFcccc
}}.

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

{code:bgColor=#FFcccc}
class NetworkHandler implements Runnable {
  private static ThreadGroup tg = new ThreadGroup("Chief");

  public void run() {
    try {
      method1();
      method2();
      Thread.sleep(5002000);		
    } catch(InterruptedException e) {
      // Forward to handler
    }
  }

  public static void method1() throws InterruptedException {
    Thread t1 = new Thread(tg, new HandleRequest(), "t1").start();
 // Start t1
 Thread t2 = new Thread(tg, new HandleRequest(), "t2");
    t1.start(); 
//   Start t2.start(); 	
  }

  public static void method2() {			  
    Thread t3 = new Thread(tg, new HandleRequest(), "t3").start();
 // Start t3
 Thread t4 = new Thread(tg, new HandleRequest(), "t4");		
    t3.start();
 //  Start t4.start();		
  }
	
  public static void main(String[] args) throws InterruptedException {
    Thread t = new Thread(tg, new NetworkHandler(), "t");
    t.start();
	    
    System.out.println("Active Threads in Thread Group at" point+ (1):"t.getThreadGroup().getName() + 
      t.getThreadGroup().getName()" at point(1):" + " " + Threadt.activeCount());

    Thread ta[] = new Thread[Threadt.activeCount()];
		
    for(int i = 0; i < 500000; i++) { } // Delay to demonstrate TOCTOU condition
		Thread.sleep(1000); // Delay to demonstrate TOCTOU condition

    // Changes after initiation of other threads while this thread is sleeping
    System.out.println("Active Threads in Thread Group at" point+ (2):"t.getThreadGroup().getName() + 
      " at t.getThreadGrouppoint().getName()2):" + " " + Threadt.activeCount());
			
    int n = Threadt.enumerate(ta); // Does not take into account the newly started threads
    System.out.println("Enumerating all threads...");
    for(int i = 0; i < n; i++) {
      System.out.println("Thread " + i + " = " + ta[i].getName());
    } 
  }
} 

class HandleRequest implements Runnable {
  public void run() {
    System.out.println("Active Threads in Thread Group (Handler" thread+ invoked this): "
 + 
    Thread.currentThread().getThreadGroup().getName() + 
      " (Handler thread invoked this): " + " " + Thread.activeCount());	

    while(true) {} // Infinite loop to keep threads active for demonstration	
  }
}
{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()}} (and start new threads), the total number of threads in the group will increase but the enumerated list {{ta}} will contain only two thread references, each corresponding to the thread group {{main}} and {{TG}}, respectively. Consequently, the program operates on stale data that constitutes metadata about the various thread groups and their respective member threads. 

Print statements have been added before the invocation of {{activecount()}} and {{enumerate()}} to show this effect. Different runs of the program produce different values of the number of threads in the thread group {{Chief}} because of the race conditions and demonstrate how a few incoming requests can get completely ignored. Any subsequent use of the {{ta}

Compliant Solution

...

} array may lead to undesirable object retention.

h2. Compliant Solution

To be compliant, avoid using the {{ThreadGroup}} class. Before Java 5.0, this class had to be extended as there was no other way to control the {{UncaughtExceptionHandler}}. The application provided handler {{UncaughtExceptionHandler}} comes into the picture when a thread exits because of an uncaught exception. In recent versions, the {{UncaughtExceptionHandler}} is maintained on a per-thread basis using an interface enclosed by the {{Thread}} class, leaving little to no functionality for the {{ThreadGroup}} class. \[[Goetz 06|AA. Java References#Goetz 06]\] 

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

low

P6

L2

Automated Detection

TODO

Related Vulnerabilities

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

References

...



|| Rule || Severity || Likelihood || Remediation Cost || Priority || Level ||
| CON17- J | low | probable | low | {color:#cc9900}{*}P6{*}{color} | {color:#cc9900}{*}L2{*}{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
\[[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() and yield() 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]