Skip to end of metadata
Go to start of metadata

Programs must use the javax.net.ssl.SSLSocket class rather than the java.net.Socket class when transferring sensitive data over insecure communication channels. The class SSLSocket provides security protocols such as Secure Sockets Layer/Transport Layer Security (SSL/TLS) to ensure that the channel is not vulnerable to eavesdropping and malicious tampering.

The principal protections included in SSLSocket that are not provided by the Socket class are [API 2014]:

  • Integrity Protection: SSL protects against modification of messages by an active wiretapper.
  • Authentication: In most modes, SSL provides peer authentication. Servers are usually authenticated, and clients may be authenticated as requested by servers.
  • Confidentiality (privacy protection): In most modes, SSL encrypts data being sent between client and server. This protects the confidentiality of data so that passive wiretappers won't see sensitive data such as financial information or personal information of many kinds.

It is also important to use SSL for secure remote method invocation (RMI) communications because RMI depends on object serialization, and serialized data must be safeguarded in transit. Gong, Ellison, and Dageforde [Gong 2003] describe how to secure RMI communications using SSLSocket.

Note that this rule lacks any assumptions about the integrity of the data being sent down a socket. For information about ensuring data integrity, see SER02-J. Sign then seal objects before sending them outside a trust boundary.

Noncompliant Code Example

This noncompliant code example shows the use of regular sockets for a server application that fails to protect sensitive information in transit. The insecure code for the corresponding client application follows the server's code.

  
// Exception handling has been omitted for the sake of brevity
class EchoServer { 
  public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = null;
    try {
      serverSocket = new ServerSocket(9999); 
      Socket socket = serverSocket.accept();
      PrintWriter out = new PrintWriter(socket.getOutputStream(), true); 
      BufferedReader in = new BufferedReader(
          new InputStreamReader(socket.getInputStream())); 
      String inputLine; 
      while ((inputLine = in.readLine()) != null) { 
        System.out.println(inputLine); 
        out.println(inputLine); 
      }
    } finally {
      if (serverSocket != null) {
        try {
          serverSocket.close();
        } catch (IOException x) {
          // Handle error
        }
      }
    }
  }
}

class EchoClient {
  public static void main(String[] args) 
                          throws UnknownHostException, IOException {
    Socket socket = null;
    try {
      socket = new Socket("localhost", 9999);
      PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
      BufferedReader in = new BufferedReader(
          new InputStreamReader(socket.getInputStream()));
      BufferedReader stdIn = new BufferedReader(
          new InputStreamReader(System.in));
      String userInput;
      while ((userInput = stdIn.readLine()) != null) {
        out.println(userInput);
        System.out.println(in.readLine());
      } 
    } finally {
      if (socket != null) {
        try {
          socket.close();
        } catch (IOException x) {
          // Handle error
        }
      }
    }
  }
}

Note that the sockets are properly closed in accordance with ERR05-J. Do not let checked exceptions escape from a finally block.

Compliant Solution

This compliant solution uses SSLSocket to protect packets using the SSL/TLS security protocols:

// Exception handling has been omitted for the sake of brevity
class EchoServer {
  public static void main(String[] args) throws IOException {
    SSLServerSocket sslServerSocket = null;
    try {
      SSLServerSocketFactory sslServerSocketFactory =
          (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
      sslServerSocket = (SSLServerSocket) sslServerSocketFactory.
                        createServerSocket(9999);
      SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
      PrintWriter out = new PrintWriter(sslSocket.getOutputStream(),true);
      BufferedReader in = new BufferedReader(
          new InputStreamReader(sslSocket.getInputStream()));
      String inputLine;
      while ((inputLine = in.readLine()) != null) { 
        System.out.println(inputLine); 
        out.println(inputLine); 
      } 
    } finally {
      if (sslServerSocket != null) {
        try {
          sslServerSocket.close();
        } catch (IOException x) {
          // Handle error
        }
      }
    }
  }
}

class EchoClient {
  public static void main(String[] args) throws IOException {
    SSLSocket sslSocket = null;
    try {
      SSLSocketFactory sslSocketFactory =
          (SSLSocketFactory) SSLSocketFactory.getDefault();
      sslSocket = 
          (SSLSocket) sslSocketFactory.createSocket("localhost", 9999);
      PrintWriter out = new PrintWriter(sslSocket.getOutputStream(), true);
      BufferedReader in = new BufferedReader(
          new InputStreamReader(sslSocket.getInputStream()));
      BufferedReader stdIn = new BufferedReader(
          new InputStreamReader(System.in));
      String userInput;
      while ((userInput = stdIn.readLine()) != null) {
        out.println(userInput);
        System.out.println(in.readLine());
      }
    } finally {
      if (sslSocket != null) {
        try {
          sslSocket.close();
        } catch (IOException x) {
          // Handle error
        }
      }
    }
  }
}

Programs that use SSLSocket will block indefinitely if they attempt to connect to a port that is not using SSL. Similarly, a program that does not use SSLSocket will block when attempting to establish a connection through a port that does use SSL.

Note that SSLSocket does not validate host names, so providing an arbitrary host name to an SSLSocket is still vulnerable to a man-in-the-middle attack. Host names should be validated separately. The HttpsURLConnection class validates host names and is a suitable solution for secure web sockets.

Exceptions

MSC00-J-EX0: Because of the mechanisms that SSLSocket provides to ensure the secure transfer of packets, significant performance overhead may result. Regular sockets are sufficient under the following circumstances:

  • The data being sent over the socket is not sensitive.
  • The data is sensitive but properly encrypted (see SER02-J. Sign then seal objects before sending them outside a trust boundary for more information).
  • The network path of the socket never crosses a trust boundary. This could happen when, for example, the two endpoints of the socket are within the same local network and the entire network is trusted.

Risk Assessment

Use of plain sockets fails to provide any guarantee of the confidentiality and integrity of data transmitted over those sockets.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MSC00-J

Medium

Likely

High

P6

L2

Automated Detection

The general case of automated detection appears to be infeasible because determining which specific data may be passed through the socket is not statically computable. An approach that introduces a custom API for passing sensitive data via secure sockets may be feasible. User tagging of sensitive data is a necessary requirement for such an approach.

ToolVersionCheckerDescription
Parasoft Jtest 10.3 SECURITY.WSC.USCImplemented

Related Guidelines

MITRE CWE

CWE-311, Failure to Encrypt Sensitive Data

Bibliography

[API 2014]

Class Socket

[Gong 2003]

Section 11.3.3, "Securing RMI Communications"

[Ware 2008]

 

 


10 Comments

  1. Jose, this looks like the beginnings of a valid rule. You might want to study this rule: SEC19-J. Do not rely on the default automatic signature verification provided by URLClassLoader and java.util.jar. That rule is deprecated, and will eventually deal merely with how to securely 'sign' code. Feel free to cannibalize that rule in building your rule.

    I suppose your rule should go in the Serialization section or the Security section.

      • Security section would be a good place as David recommends.
      • Are there any exceptions to this advice? Should you use SSL and completely dump sockets? The title, general flow and the examples should be chosen to reflect the answer.
      • As David says, if you can provide a correct SSL compliant solution for the preexisting noncompliant example in SEC05-J (updating software, patches etc.), I can't see why this wouldn't be a solid rule.
        • This rule is approachig completion. It still needs to follow my style guidelines (eg code background color, and a rule identifier.)
        • I suspect there are exceptions to this rec...should we never use plain Sockets anymore?
        1. The style guidelines also indicate that this rule should be part of the Security section, not linked from the Java toplevel page.

          Also, this looks more like a rec, not a rule, and should be numbered accordingly.

          1. OK I think this rule is complete now.

  2. Normative, but prob belongs elsewhere. Current best guess: Serialization. This is about staying within trust boundaries.

  3. I just see a plain old socket close and am not sure why we need to retain the following lines which sound a bit out of context:

    Note that the sockets are closed in accordance with ERR05-J. Do not let checked exceptions escape from a finally block. While merely printing close exceptions is frowned upon, the exceptions may be suppressed as per ERR00-EX0 of ERR00-J. Do not suppress or ignore checked exceptions.

    1. Because at first glance, the socket.close() looks like it violates ERR05-J. It's still safe, as there is nothing else in the finally block, and the function throws IOException.

  4. SSLSocket does not validate the hostname (check whether the name of the host to which your program is connecting matches the name in the SSL certificate). This leaves the compliant solution vulnerable to Man-in-the-Middle attacks. This rule should at least warn people that they will have the implement their own hostname checking. Better yet, it should suggest that the HttpsURLConnection class be used instead.

    1. Thanks. I added this info to the compliant solution. (which is not vulnerable because the only hostname used is "localhost").