Recommendations discussed in the guideline CON13-J. Ensure that threads are stopped cleanly are insufficient to terminate a thread that is blocked on a blocking operation such as network or file input-output (IO). Consequently, threads and tasks should Threads and tasks that block on operations involving network or file I/O must provide callers with an explicit termination mechanism to prevent denial-of-service (DoS) vulnerabilities.
Noncompliant Code Example (
...
Blocking I/O, Volatile Flag)
This noncompliant code example uses a volatile done
flag to indicate that it whether is safe to shutdown shut down the thread, as suggested in CON13THI05-J. Ensure that threads are stopped cleanlyDo not use Thread.stop() to terminate threads. However, this does not help in terminating when the thread because it is blocked on some network IO I/O as a consequence of using invoking the readLine()
method, it cannot respond to the newly set flag until the network I/O is complete. Consequently, thread termination may be indefinitely delayed.
Code Block | ||
---|---|---|
| ||
// Thread-safe class public final class SocketReader implements Runnable { private final Socket socket; private final BufferedReader in; private volatile boolean done = false; private final Object lock = new Object(); privatepublic boolean isRunning = false; // Reduces the need to synchronize time consuming operations public static class MultipleUseException extends RuntimeException {}; public SocketReader() throws IOException { this.socket = new Socket("somehost", 25); this.in = new BufferedReader(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 @Override public void run() { try { synchronized (lock) { if readData(isRunning) {; throw new MultipleUseException(); } } isRunning = true; } execute(); } catch (IOException ie) { // Forward to handler } } public void executereadData() 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 { throws IOException, InterruptedException { SocketReader reader = new SocketReader("somehost", 25); Thread thread = new Thread(reader); thread.start(); Thread.sleep(1000); reader.shutdown(); // Shut down the thread } } |
Note that the Runnable
object prevents itself from being run in multiple threads using an isRunning
flag. If one thread tries to invoke run()
after another thread has already done so, an unchecked exception is thrown.
...
Noncompliant Code Example (Blocking I/O, Interruptible)
This noncompliant code example is similar to the preceding example but uses thread interruption to indicate that it is safe to shutdown shut down the thread, as suggested in CON13-J. Ensure that threads are stopped cleanly. However, this is not useful because the thread is blocked on some network IO as a consequence of using the readLine()
method. Network I/O is not responsive on a java.net.Socket
is unresponsive to thread interruption.
Code Block | ||
---|---|---|
| ||
// Thread-safe class public final class SocketReader implements Runnable { // Other methods... public void executereadData() 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 } } |
Compliant Solution (
...
Close Socket Connection)
This compliant solution closes the socket connection, by having the shutdown()
method close the socket. As a result, the thread is bound to stop because of a SocketException
. Note that there is no way terminates the blocking network I/O by closing the socket in the shutdown()
method. The readLine()
method throws a SocketException
when the socket is closed, consequently allowing the thread to proceed. Note that it is impossible to keep the connection alive if while simultaneously halting the thread is to be both cleanly halted and immediately.
Code Block | ||
---|---|---|
| ||
public final class SocketReader implements Runnable { // Other methods... public void executereadData() 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 throws IOException, InterruptedException { SocketReader reader = new SocketReader("somehost", 25); Thread thread = new Thread(reader); thread.start(); Thread.sleep(1000); reader.shutdown(); } } |
After the shutdown()
method is called from main()
, the finally
block in readData()
executes and calls shutdown()
again, closing the socket for a second time. However, when the socket has already been closed, this second call does nothing.
A boolean
flag can be used (as described earlier) if additional clean-up operations need to be performed. When performing asynchronous I/O, a java.nio.channels.Selector
may also be brought out of the blocked state by either invoking can be unblocked by invoking either its close()
or its wakeup()
method.
...
When additional operations must be performed after emerging from the blocked state, use a boolean
flag to indicate pending termination. 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)
This compliant solution uses an interruptible channel, java.nio.channels.SocketChannel
, instead of a Socket
connection. If the thread performing the network IO I/O is interrupted using the Thread.interrupt()
method , for instance, while it is reading the data, the thread receives a ClosedByInterruptException
, and the channel is closed immediately. The thread's interrupt interrupted status is also set.
Code Block | ||
---|---|---|
| ||
public final class SocketReader implements Runnable { private final SocketChannel sc; private final Object lock = new Object(); private boolean isRunning = false; privatepublic class MultipleUseException extends RuntimeException {}; public SocketReader(SocketReader(String host, int port) throws IOException { sc = SocketChannel.open(new InetSocketAddress("somehost"host, 25port)); } @Override public void run() { ByteBuffer buf = ByteBuffer.allocate(1024); try { synchronized (lock) { if (isRunning while (!Thread.interrupted()) { throw new MultipleUseExceptionsc.read(buf); } // ... isRunning = true; } ByteBuffer buf } = ByteBuffer.allocate(1024); } catch try(IOException ie) { // synchronizedForward (lock)to {handler } } public static whilevoid (!Thread.interrupted()main(String[] args) { sc.read(buf); // ... throws IOException, InterruptedException }{ SocketReader reader } = } catch (IOException ie) {new SocketReader("somehost", 25); Thread thread //= Forward to handlernew Thread(reader); } } thread.start(); public static void main(String[] args) throws IOException, InterruptedException { SocketReader reader = new SocketReader(); Thread thread = new Thread(reader Thread.sleep(1000); thread.interrupt(); thread.start(); Thread.sleep(1000); thread.interrupt(); } } } } |
This technique interrupts the current thread. However, it stops the thread only This method interrupts the current thread, however, it only stops the thread because the code polls the interrupted flag using the method thread's interrupted status with the Thread.interrupted()
, method and shuts down terminates the thread when it is interrupted. Invoking the Using a SocketChannel
ensures that the condition in the while
loop is tested as soon as an interruption is received, even though the read is normally a blocking operation. Similarly, invoking the interrupt()
method of a thread that is blocked because of on a java.nio.channels.Selector
also causes the that thread to awaken.
Noncompliant Code Example (
...
Database Connection)
This noncompliant code example shows a thread-safe DBConnector
class DBConnector
that creates a one JDBC connection per thread, that is, the connection belonging . 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 intended to be shared by multiplesingle-threadsthreaded.
Code Block | ||
---|---|---|
| ||
public final class DBConnector implements Runnable { private final String query; private final Object lock = new Object(); private boolean isRunning = false; private class MultipleUseException extends RuntimeException {}; DBConnector(String query) { this.query = query; } @Override public void run() { synchronized (lock) {Connection connection; try { if (isRunning) { // Username and password are hard throwcoded new MultipleUseException(); for brevity connection = }DriverManager.getConnection( isRunning = true; "jdbc:driver:name", } Connection con; try"username", { // Username and password are hard coded for brevity"password" con = DriverManager.getConnection("jdbc:driver:name", "username","password"); Statement stmt = conconnection.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 suitable query */"); Thread thread = new Thread(connector); thread.start(); Thread.sleep(5000); thread.interrupt(); } } |
Unfortunately database Database connections, like sockets, are not inherently interruptible. So this design does not permit a client lack inherent interruptibility. Consequently, this design fails to support the client's attempts to cancel a task by closing it if the resource when the corresponding thread is blocked on a long-running activity query, such as a join query. Furthermore, it is important to provide a mechanism to close connections to prevent thread starvation caused because of the limited number of database connections available in the pool. Similar task cancellation mechanisms are required when using objects local to a method, such as sockets.
Noncompliant Code Example (database connection)
This noncompliant code example shows a thread-safe class DBConnector
that creates a JDBC connection per thread, that is, the connection belonging to one thread is not shared by other threads. This is a common use-case because JDBC connections are not meant to be shared by multiple-threads.
.
Compliant Solution (Statement.cancel()
)
This compliant solution uses a ThreadLocal
wrapper around the connection so that a thread calling the initialValue()
method obtains a unique connection instance. This approach allows provision of a cancelStatement()
so that other threads or clients can interrupt a long-running query when required. The cancelStatement()
method invokes the Statement.cancel()
method.
Code Block | ||
---|---|---|
| ||
public final | ||
Code Block | ||
| ||
class DBConnector implements Runnable { private final String query; private finalvolatile Object lock = new Object();Statement stmt; DBConnector(String query) { private boolean isRunningthis.query = falsequery; } private classstatic MultipleUseExceptionfinal extendsThreadLocal<Connection> RuntimeException {}; connectionHolder = DBConnector(String query) { this.query = query; } public void run() { synchronized (lock) { if (isRunning) { throw new MultipleUseExceptionThreadLocal<Connection>(); } { Connection isRunningconnection = truenull; @Override } public Connection initialValue() { Connection con; try { // Username and password are hard coded for brevity ... connection = DriverManager.getConnection( con = DriverManager.getConnection("jdbc:myDriverdriver:name", "username","password"); Statement stmt = con.createStatement(); "username", ResultSet rs = stmt.executeQuery(query "password" ); } catch (SQLException e) { // Forward to handler } // ...return connection; } }; public staticConnection void main(String[] argsgetConnection() throws InterruptedException {{ return connectionHolder.get(); } DBConnectorpublic connectorboolean =cancelStatement() new{ DBConnector(/* suitable query */);// Allows client to cancel statement ThreadStatement threadtmpStmt = new Thread(connector)stmt; if thread.start(); Thread.sleep(5000); thread.interrupt(); } } |
Unfortunately database connections, like sockets, are not inherently interruptible. So this design does not permit a client to cancel a task by closing it if the corresponding thread is blocked on a long running activity such as a join query. Furthermore, it is important to provide a mechanism to close connections to prevent thread starvation caused because of the limited number of database connections available in the pool. Similar task cancellation mechanisms are required when using objects local to a method, such as sockets.
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 | ||
---|---|---|
| ||
class DBConnector implements Runnable {
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) {
// Forward to handler
}
return connection;
}
@Override public void set(Connection con) {
if(connection == null) { // Shuts down connection when null value is passed
try {
connection.close();
} catch (SQLException e) {
// Forward to handler
}
} else {
connection = con;
}
}
};
public static Connection getConnection() {
return connectionHolder.get();
}
public static void shutdownConnection() { // Allows client to close connection anytime
connectionHolder.set(null);
}
public void run() {
Connection dbConnection = getConnection();
Statement stmt;
try {
stmt = dbConnection.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);
connector.shutdown();
}
}
|
Risk Assessment
(tmpStmt != null) {
try {
tmpStmt.cancel();
return true;
} catch (SQLException e) {
// Forward to handler
}
}
return false;
}
@Override public void run() {
try {
if (getConnection() != null) {
stmt = getConnection().createStatement();
}
if (stmt == null || (stmt.getConnection() != getConnection())) {
throw new IllegalStateException();
}
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);
connector.cancelStatement();
}
}
|
The Statement.cancel()
method cancels the query, provided the database management system (DBMS) and driver both support cancellation. It is impossible to cancel the query if either the DBMS or the driver fail to support cancellation.
According to the Java API, Interface Statement
documentation [API 2014]
By default, only one
ResultSet
object perStatement
object can be open at the same time. As a result, if the reading of oneResultSet
object is interleaved with the reading of another, each must have been generated by differentStatement
objects.
This compliant solution ensures that only one ResultSet
is associated with the Statement
belonging to an instance, and, consequently, only one thread can access the query results.
Risk Assessment
Failure to provide facilities for thread termination can cause nonresponsiveness and DoSFailing 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
Wiki Markup |
---|
\[[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 |
THI04-J | Low | Probable | Medium | P4 | L3 |
Bibliography
[API 2014] | |
Section 24.3, "Stopping a Thread" | |
Chapter 7, "Cancellation and Shutdown" | |
Section 2.4, "Two Approaches to Stopping a Thread" | |
Java Thread Primitive Deprecation | |
[JPL 2006] | Section 14.12.1, "Don't Stop" |
...
CON12-J. Avoid deadlock by requesting and releasing locks in the same order 11. Concurrency (CON) VOID CON14-J. Ensure atomicity of 64-bit operations