Threads and tasks that block on operations involving network or file input/output (I/O) must provide callers with an explicit termination mechanism to prevent denial-of-service vulnerabilities.
h2. Noncompliant Code Example (Blocking I/O, Volatile Flag)
This noncompliant code example uses a volatile {{done}} flag to indicate that itwhether is safe to shut down the thread, as suggested in rule [THI05-J. Do not use Thread.stop() to terminate threads]. However, setting the flag does not terminate when the thread if it is blocked on network I/O as a consequence of invoking the {{readLine()}} method, it cannot respond to the newly-set flag until the network I/O is complete. Consequently, thread termination may be delayed for an arbitrary duration.
{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
@Override 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 I/O, Interruptible)
This noncompliant code example is similar to the preceding one, but uses thread interruption to shut down the thread. Network I/O is not responsive to thread interruption when on a {{java.net.Socket}} is being usedunresponsive to thread interruption. The {{readData()}} and {{main()}} methods are modified as follows:
{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 resumesterminates the threadblocking network I/O by having closing the socket in the {{shutdown()}} method close the socket. The {{readLine()}} method throws a {{SocketException}} when the socket is closed, whichconsequently letsallowing the thread to proceed. Note that thereit is noimpossible way to keep the connection alive ifwhile simultaneously halting the thread is to beboth cleanly haltedand 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("somehost", 25);
Thread thread = new Thread(reader);
thread.start();
Thread.sleep(1000);
reader.shutdown();
}
}
{code}
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, thiswhen secondthe callsocket has noalready effectbeen ifclosed, thethis socketsecond hascall alreadyis been closedineffective.
When performing asynchronous I/O, a {{java.nio.channels.Selector}} may alsocan be broughtunblocked outby of the blocked state by either invokinginvoking either its {{close()}} or its {{wakeup()}} method.
A {{boolean}} flag can be used if method.
When additional operations need tomust 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.
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 I/O 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 interrupted 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));
}
@Override 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 only because the code polls the thread's interrupted status with the {{Thread.interrupted()}} method and terminates 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, even despitethough the read beingis a blocking operation. Similarly, invoking the {{interrupt()}} method of a thread that is blocked becauseon ofa {{java.nio.channels.Selector}} also causes that thread to awaken.
h2. Noncompliant Code Example (Database Connection)
This noncompliant code example shows a thread-safe {{DBConnector}} class that creates one Java Database Connectivity (JDBC) connection per thread. Each connection belongs to one thread and is notunshared shared by other threads. This is a common use case because JDBC connections are not meantintended to be shared by multiple threadssingle-threaded.
{code:bgColor=#FFcccc}
public final class DBConnector implements Runnable {
private final String query;
DBConnector(String query) {
this.query = query;
}
@Override 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}
Database connections, like sockets, arelack notinherent inherentlyinterruptibility interruptible. Consequently, this design does notfails permitto asupport client's attempts to cancel a task by closing the resource ifwhen the corresponding thread is blocked on a long-running query, such as a join.
h2. 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. TheThis advantageapproach ofallows thisprovision approachof is that a {{cancelStatement()}} method can be provided , so that other threads or clients can interrupt a long-running query when required. The {{cancelStatement()}} method invokes the {{Statement.cancel()}} method.
{code:bgColor=#ccccff}
public final class DBConnector implements Runnable {
private final String query;
private volatile Statement stmt;
DBConnector(String query) {
this.query = query;
if(getConnection() != null) {
try {
stmt = getConnection().createStatement();
} catch (SQLException e) {
// Forward to handler
}
}
}
private static final ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() {
Connection connection = null;
@Override public Connection initialValue() {
try {
// ...
connection = DriverManager.getConnection(
"jdbc:driver:name",
"username",
"password"
);
} catch (SQLException e) {
// Forward to handler
}
return connection;
}
};
public Connection getConnection() {
return connectionHolder.get();
}
public boolean cancelStatement() { // Allows client to cancel statement
if(stmt != null) {
try {
stmt.cancel();
return true;
} catch (SQLException e) {
// Forward to handler
}
}
return false;
}
@Override public void run() {
try {
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();
}
}
{code}
The {{Statement.cancel()}} method cancels the query, provided that the database management system (DBMS) and driver both support cancellation. It is notimpossible possible to conform with this rule if they do not when either DBMS or driver fails to support cancellation.
According to the Java API, interface {{Statement}} documentation \[[API 2006|AA. Bibliography#API 06]\]
{quote}
By default, only one {{ResultSet}} object per {{Statement}} object can be open at the same time. Therefore, if the reading of one {{ResultSet}} object is interleaved with the reading of another, each must have been generated by different {{Statement}} objects.
{quote}
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.
{mc} // Complete code for connecting to DB
String userName = "user";
String password = "pass";
String url = "jdbc:mysql://localhost:3306/dbname";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
connection = DriverManager.getConnection (url, userName, password);
{mc}
h2. Risk Assessment
Failing to provide facilities for thread termination can cause non-responsiveness and denial of service.
|| Rule || Severity || Likelihood || Remediation Cost || Priority || Level ||
| THI06-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+CON26-J].
h2. Bibliography
| \[[API 2006|AA. Bibliography#API 06]\] | Class Thread, method {{stop}}, interface ExecutorService |
| \[[Darwin 2004|AA. Bibliography#Darwin 04]\] | 24.3 Stopping a Thread |
| \[[JDK7 2008|AA. Bibliography#JDK7 08]\] | Concurrency Utilities, More information: Java Thread Primitive Deprecation |
| \[[JPL 2006|AA. Bibliography#JPL 06]\] | 14.12.1. Don't stop and 23.3.3. Shutdown Strategies |
| \[[JavaThreads 2004|AA. Bibliography#JavaThreads 04]\] | 2.4 Two Approaches to Stopping a Thread |
| \[[Goetz 2006|AA. Bibliography#Goetz 06]\] | Chapter 7: Cancellation and shutdown |
----
[!The CERT Oracle Secure Coding Standard for Java^button_arrow_left.png!|THI05-J. Do not use Thread.stop() to terminate threads] [!The CERT Oracle Secure Coding Standard for Java^button_arrow_up.png!|09. Thread APIs (THI)] [!The CERT Oracle Secure Coding Standard for Java^button_arrow_right.png!|10. Thread Pools (TPS)]
|