Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Wiki Markup
The recommendations suggested in the guideline [CON13-J. Do not use Thread.stop() to terminate threads] are insufficient to terminate a thread that is blocked on an operation involving network or file input

...

 or output (IO). Threads and tasks should provide callers with an explicit termination mechanism to prevent denial of service vulnerabilities.

...




h2. Noncompliant Code Example (blocking IO, volatile flag)

...



This noncompliant code example uses a volatile {{done}} flag to indicate that it is safe to shut down the thread, as suggested in [CON13-J. Do not use Thread.stop() to terminate threads]. However, setting the flag does not terminate the thread because the thread is blocked on network IO as a consequence of using the {{readLine()}} method.

...

Code Block
bgColor#FFcccc
 

{code:bgColor=#FFcccc}
public final class SocketReader implements Runnable { // Thread-safe class
  private final Socket socket;
  private final BufferedReader in;
  private volatile boolean done = false;
  private final Object lock = new Object();

  public SocketReader(String host, int port) throws IOException {
    this.socket = new Socket(host, port);
    this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
  }
  
  // Only one thread can use the socket at a particular time
  public void run() {
    try {
      synchronized (lock) {
        readData(); 
      }      
    } catch (IOException ie) {
      // Forward to handler
    }
  }

  public void readData() throws IOException {
    String string;
    while (!done && (string = in.readLine()) != null) {
      // Blocks until end of stream (null)
    }
  }

  public void shutdown() {
    done = true;
  }

  public static void main(String[] args) throws IOException, InterruptedException {
    SocketReader reader = new SocketReader("somehost", 25);
    Thread thread = new Thread(reader);
    thread.start();
    Thread.sleep(1000);
    reader.shutdown(); // Shutdown the thread
  }
}
{code}


h2. Noncompliant Code Example (blocking IO, interruptible)

...



This noncompliant code example is similar to the preceding one, but uses thread interruption to shut down the thread. Network IO is not responsive to thread interruption when a {{java.net.Socket}} is being used.

...

Code Block
bgColor#FFcccc
 

{code:bgColor=#FFcccc}
public final class SocketReader implements Runnable { // Thread-safe class
  // ...
  
  public void readData() throws IOException {
    String string;
    while (!Thread.interrupted() && (string = in.readLine()) != null) { 
      // Blocks until end of stream (null)
    }
  }
  
  public static void main(String[] args) throws IOException, InterruptedException {
    SocketReader reader = new SocketReader("somehost", 25);
    Thread thread = new Thread(reader);
    thread.start();
    Thread.sleep(1000); 
    thread.interrupt(); // Interrupt the thread
  }
}
{code}


h2. Compliant Solution (close socket connection)

...



This compliant solution resumes the thread by having the {{shutdown()}} method close the socket. The {{readLine()}} method throws a {{SocketException}} when the socket is closed which lets the thread proceed. Note that there is no way to keep the connection alive if the thread is to be cleanly halted immediately.

...



{code
:bgColor
=#ccccff
}
public final class SocketReader implements Runnable {
  // ...
  
  public void readData() throws IOException {
    String string;
    try {
      while ((string = in.readLine()) != null) { 
        // Blocks until end of stream (null)
      }
    } finally {
      shutdown();
    }
  }
  
  public void shutdown() throws IOException {
    socket.close();
  }

  public static void main(String[] args) throws IOException, InterruptedException {
    SocketReader reader = new SocketReader();
    Thread thread = new Thread(reader);
    thread.start();
    Thread.sleep(1000); 
    reader.shutdown();
  }
}
{code}

The {{finally}} block executes after {{shutdown()}} is called. Because the {{finally}} block also calls {{shutdown()}}, the socket will be closed twice. The second call has no effect if the socket has already been closed.

...



When performing asynchronous IO, a {{java.nio.channels.Selector}} may also be brought out of the blocked state by either invoking its {{close()}} or {{wakeup()}} method.

...

A boolean flag can be used (as shown earlier) if additional operations need to be performed after emerging from the blocked state. When supplementing the code with such a flag, the shutdown() method should also set the flag to false so that the thread can cleanly exit from the while loop.

Compliant Solution (interruptible channel)

...

 

A {{boolean}} flag can be used (as shown earlier) if additional operations need to be performed after emerging from the blocked state. When supplementing the code with such a flag, the {{shutdown()}} method should also set the flag to false so that the thread can cleanly exit from the while loop. 


h2. Compliant Solution (interruptible channel)

This compliant solution uses an interruptible channel, {{java.nio.channels.SocketChannel}}, instead of a {{Socket}} connection. If the thread performing the network IO is interrupted using the {{Thread.interrupt()}} method while it is reading the data, the thread receives a {{ClosedByInterruptException}} and the channel is closed immediately. The thread's interrupt status is also set.

...



{code
:bgColor
=#ccccff
}
public final class SocketReader implements Runnable {
  private final SocketChannel sc;
  private final Object lock = new Object();
  
  public SocketReader(String host, int port) throws IOException {
    sc = SocketChannel.open(new InetSocketAddress(host, port));    
  }
  
  public void run() {
    ByteBuffer buf = ByteBuffer.allocate(1024);
    try {
      synchronized (lock) {
        while (!Thread.interrupted()) {
          sc.read(buf);
          // ...
        }
      }
    } catch (IOException ie) {
      // Forward to handler
    }
  }

  public static void main(String[] args) throws IOException, InterruptedException {
    SocketReader reader = new SocketReader("somehost", 25);
    Thread thread = new Thread(reader);
    thread.start();
    Thread.sleep(1000);
    thread.interrupt();
  }
}
{code}

This technique interrupts the current thread, however, it only stops the thread because the code polls the interrupted flag using the method {{Thread.interrupted()}}, and shuts down the thread when it is interrupted. Using a {{SocketChannel}} ensures that the condition in the while loop is tested as soon as an interruption is received, despite the read operation being a blocking operation. Similarly, invoking the {{interrupt()}} method of a thread that is blocked because of a {{java.nio.channels.Selector}} also causes that thread to awaken.

...

 


h2. Noncompliant Code Example (database connection)

...



This noncompliant code example shows a thread-safe class {{DBConnector}} that creates one JDBC connection per thread.  Each connection belongs to one thread, and is not shared by other threads. This is a common use-case because JDBC connections are not meant to be shared by multiple-threads.

...

Code Block
bgColor#FFcccc
 

{code:bgColor=#FFcccc}
public final class DBConnector implements Runnable {
  private final String query;
  
  DBConnector(String query) {
    this.query = query; 
  }
	
  public void run() {
    Connection connection;
    try {
      // Username and password are hard coded for brevity
      connection = DriverManager.getConnection("jdbc:driver:name", "username", "password");  
      Statement stmt = connection.createStatement();
      ResultSet rs = stmt.executeQuery(query);
      // ...
    } catch (SQLException e) {
      // Forward to handler
    }
    // ... 
  }  

  public static void main(String[] args) throws InterruptedException {
    DBConnector connector = new DBConnector("suitable query");
    Thread thread = new Thread(connector);
    thread.start();
    Thread.sleep(5000);
    thread.interrupt();
  }
}
{code}

Other than helping thread cancellation, a mechanism to close connections also prevents thread starvation because threads can be allowed to fairly share the limited number of database connections available in the pool. A similar mechanism is required for task cancellation when using socket objects that are local to a method.

Unfortunately database connections, like sockets, are not inherently interruptible. Consequently, this design does not permit a client to cancel a task by closing the resource if the corresponding thread is blocked on a long running activity such as a join query.

Compliant Solution (ThreadLocal)

This compliant solution uses a ThreadLocal wrapper around the connection so that a thread that calls initialValue() obtains a unique connection instance. The advantage of this approach is that a shutdownConnection() method can be provided so that clients external to the class can also close the connection when the corresponding thread is blocked, or is performing some time consuming activity.

Code Block
bgColor#ccccff

public final class DBConnector implements Runnable {
  private final String query;
  
  DBConnector(String query) {
    this.query = query;
  }
	
  private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() {
    Connection connection = null;

    @Override public Connection initialValue() {		
      try {
        // Username and password are hard coded for brevity
        connection = DriverManager.getConnection
          ("jdbc:driver:name", "username", "password");  	    	      
      } catch (SQLException e

Unfortunately database connections, like sockets, are not inherently interruptible. Consequently, this design does not permit a client to cancel a task by closing the resource if the corresponding thread is blocked on a long running activity such as a join query. 

{mc}Not sure what to do with the following text. ~DS :
Other than helping thread cancellation, a mechanism to close connections also prevents thread starvation because threads can be allowed to fairly share the limited number of database connections available in the pool. A similar mechanism is required for task cancellation when using socket objects that are local to a method. {mc}


h2. Compliant Solution (ThreadLocal)

This compliant solution uses a {{ThreadLocal}} wrapper around the connection so that a thread that calls {{initialValue()}} obtains a unique connection instance. The advantage of this approach is that a {{shutdownConnection()}} method can be provided so that clients external to the class can also close the connection when the corresponding thread is blocked, or is performing some time consuming activity.

{code:bgColor=#ccccff}
public final class DBConnector implements Runnable {
  private final String query;
  
  DBConnector(String query) {
    this.query = query;
  // Forward to handler
      }}
	
  private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() {
    Connection connection return= connection;
    }
		null;

    @Override public voidConnection setinitialValue(Connection con) {		
      if(connection == null) { // Shuts down connection when con = null		       try {
        // Username and password are hard coded for brevity
        try {connection = DriverManager.getConnection
          connection.close();
  ("jdbc:driver:name", "username", "password");  	    	      
      } catch (SQLException e) {
          // Forward to handler
 
     }
    }	  return connection;
    }
		
    @Override public void set(Connection con) {
      } else {
        connection = con; 
      }
if(connection == null) { // Shuts down connection when con = null		       
       }
 try };
{
  public static Connection getConnection() {
    return connectionHolderconnection.getclose();
  }

  public static void shutdownConnection( } catch (SQLException e) {
          // AllowsForward clientto tohandler close
 connection anytime
    connectionHolder.set(null);
  }

	  public void run() {
  		  Connection dbConnection = getConnection();
  
  Statement stmt;
   } tryelse {
      stmt  connection = dbConnection.createStatement();		
con; 
      }
  ResultSet  rs}
 = stmt.executeQuery(query); };

  public static }Connection catch getConnection(SQLException e) {
    return  // Forward to handler	 
    }    connectionHolder.get();
  }

  public static void shutdownConnection() { // Allows client to close connection anytime
    // ...connectionHolder.set(null);
  }

  public static void mainrun(String[] args) throws InterruptedException {
    DBConnectorConnection connectordbConnection = new DBConnector("suitable query"getConnection();
    Statement Threadstmt;
  thread = new Thread(connector);try {
    thread.start  stmt = dbConnection.createStatement();		
      ResultSet rs Thread= stmt.sleepexecuteQuery(5000query);
      // connector.shutdown();
  }
}

Risk Assessment

Failing to provide facilities for thread shutdown can cause non-responsiveness and denial of service.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

CON24- J

low

probable

medium

P4

L3

Automated Detection

TODO

Related Vulnerabilities

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

References

...

...
    } catch (SQLException e) {
      // Forward to handler	 
    }    
    // ...
  }

  public static void main(String[] args) throws InterruptedException {
    DBConnector connector = new DBConnector("suitable query");
    Thread thread = new Thread(connector);
    thread.start();
    Thread.sleep(5000);
    connector.shutdown();
  }
}
{code}


h2. Risk Assessment

Failing to provide facilities for thread shutdown can cause non-responsiveness and denial of service.

|| Rule || Severity || Likelihood || Remediation Cost || Priority || Level ||
| CON24- 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+CON24-J].

h2. References

\[[API 06|AA. Java References#API 06]\] Class Thread, method {{stop}}, interface ExecutorService
\[[Darwin 04|AA. Java References#Darwin 04]\] 24.3 Stopping a Thread
\[[JDK7 08|AA. Java References#JDK7 08]\] Concurrency Utilities, More information: Java Thread Primitive Deprecation 
\[[JPL 06|AA. Java 

...

References#JPL 06]\] 

...

14.12.1. Don't stop and 23.3.3. Shutdown Strategies
\[[

...

JavaThreads 04|AA. Java 

...

References#JavaThreads 04]\] 

...

2.4 Two Approaches to Stopping a Thread
\[[

...

Goetz 

...

06|AA. Java 

...

References#Goetz 

...

06]\] 

...

Chapter 

...

7: 

...

Cancellation 

...

and shutdown

----
[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_left.png!|CON23-J. Address the shortcomings of the Singleton design pattern]&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!|CON25-J. Ensure atomicity when reading and writing 64-bit values]