Home > Back-end >  Using Insecure TLS in Java version of Eclipse Paho
Using Insecure TLS in Java version of Eclipse Paho

Time:08-24

I am trying to connect to an MQTT server without having to validate the TLS certs. I am using the latest version of Eclipse Paho from a Java program. I cannot find a way to turn off the validation.

In the Python version of Eclipse Paho, the vendor who is running the server uses the following code to turn off the validation:

        client = mqtt_client.Client(client_id, transport='websockets')
        client.tls_set("", cert_reqs=ssl.CERT_NONE)
        client.tls_insecure_set(True)

I don't see an equivalent for Java.

Does anyone know how I can accomplish this in Java?

CodePudding user response:

You will need to pass a custom SSLSocketFactory as part of the MqttConnectOptions object passed to the Paho client's connect() method.

This will come from on a SSLContext with a custom TrustManager e.g.

TrustManager [] trustAllCerts = new TrustManager [] {new X509ExtendedTrustManager () {
   @Override
   public void checkClientTrusted (X509Certificate [] chain, String authType, Socket socket) {

   }

   @Override
   public void checkServerTrusted (X509Certificate [] chain, String authType, Socket socket) {

   }

   @Override
   public void checkClientTrusted (X509Certificate [] chain, String authType, SSLEngine engine) {

   }

   @Override
   public void checkServerTrusted (X509Certificate [] chain, String authType, SSLEngine engine) {

   }

   @Override
   public java.security.cert.X509Certificate [] getAcceptedIssuers () {
      return null;
   }

   @Override
   public void checkClientTrusted (X509Certificate [] certs, String authType) {
   }

   @Override
   public void checkServerTrusted (X509Certificate [] certs, String authType) {
   }

}};

SSLContext sc = null;
try {
   sc = SSLContext.getInstance ("TLS");
   sc.init (null, trustAllCerts, new java.security.SecureRandom ());
} catch (KeyManagementException | NoSuchAlgorithmException e) {
   e.printStackTrace ();
}

String uri = "ssl://localhost:1884";
String clientId = "client-101";

MqttClient client = new MqttClient(uri, clientId))

final MqttConnectOptions options = new MqttConnectOptions();
options.setSocketFactory(sc.getSocketFactory());

client.connect(options)

This does basically the same as the python code, but you should probably implement some proper checks in the methods in the TrustManager to ensure you are actually connecting to the server you are expecting. Blindly disabling all the checking basically removes a lot of protection of a TLS connection.

  • Related