TLSUtils.java

  1. /**
  2.  *
  3.  * Copyright 2014 Florian Schmaus
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.jivesoftware.smack.util;

  18. import java.security.KeyManagementException;
  19. import java.security.NoSuchAlgorithmException;
  20. import java.security.SecureRandom;
  21. import java.security.cert.CertificateException;
  22. import java.security.cert.X509Certificate;
  23. import java.util.Arrays;
  24. import java.util.HashSet;
  25. import java.util.Set;

  26. import javax.net.ssl.HostnameVerifier;
  27. import javax.net.ssl.SSLContext;
  28. import javax.net.ssl.SSLSession;
  29. import javax.net.ssl.SSLSocket;
  30. import javax.net.ssl.TrustManager;
  31. import javax.net.ssl.X509TrustManager;

  32. import org.jivesoftware.smack.ConnectionConfiguration;
  33. import org.jivesoftware.smack.SmackException.SecurityNotPossibleException;


  34. public class TLSUtils {

  35.     public static final String SSL = "SSL";
  36.     public static final String TLS = "TLS";
  37.     public static final String PROTO_SSL3 = SSL + "v3";
  38.     public static final String PROTO_TLSV1 = TLS + "v1";
  39.     public static final String PROTO_TLSV1_1 = TLS + "v1.1";
  40.     public static final String PROTO_TLSV1_2 = TLS + "v1.2";

  41.     /**
  42.      * Enable only TLS. Connections created with the given ConnectionConfiguration will only support TLS.
  43.      * <p>
  44.      * According to the <a
  45.      * href="https://raw.githubusercontent.com/stpeter/manifesto/master/manifesto.txt">Encrypted
  46.      * XMPP Manifesto</a>, TLSv1.2 shall be deployed, providing fallback support for SSLv3 and
  47.      * TLSv1.1. This method goes one step boyond and upgrades the handshake to use TLSv1 or better.
  48.      * This method requires the underlying OS to support all of TLSv1.2 , 1.1 and 1.0.
  49.      * </p>
  50.      *
  51.      * @param builder the configuration builder to apply this setting to
  52.      */
  53.     public static <B extends ConnectionConfiguration.Builder<B,?>> B setTLSOnly(B builder) {
  54.         builder.setEnabledSSLProtocols(new String[] { PROTO_TLSV1_2,  PROTO_TLSV1_1, PROTO_TLSV1 });
  55.         return builder;
  56.     }

  57.     /**
  58.      * Enable only TLS and SSLv3. Connections created with the given ConnectionConfiguration will
  59.      * only support TLS and SSLv3.
  60.      * <p>
  61.      * According to the <a
  62.      * href="https://raw.githubusercontent.com/stpeter/manifesto/master/manifesto.txt">Encrypted
  63.      * XMPP Manifesto</a>, TLSv1.2 shall be deployed, providing fallback support for SSLv3 and
  64.      * TLSv1.1.
  65.      * </p>
  66.      *
  67.      * @param builder the configuration builder to apply this setting to
  68.      */
  69.     public static <B extends ConnectionConfiguration.Builder<B,?>> B setSSLv3AndTLSOnly(B builder) {
  70.         builder.setEnabledSSLProtocols(new String[] { PROTO_TLSV1_2,  PROTO_TLSV1_1, PROTO_TLSV1, PROTO_SSL3 });
  71.         return builder;
  72.     }

  73.     /**
  74.      * Accept all TLS certificates.
  75.      * <p>
  76.      * <b>Warning:</b> Use with care. This method make the Connection use {@link AcceptAllTrustManager} and essentially
  77.      * <b>invalidates all security guarantees provided by TLS</b>. Only use this method if you understand the
  78.      * implications.
  79.      * </p>
  80.      *
  81.      * @param builder a connection configuration builder.
  82.      * @throws NoSuchAlgorithmException
  83.      * @throws KeyManagementException
  84.      * @return the given builder.
  85.      */
  86.     public static <B extends ConnectionConfiguration.Builder<B,?>> B acceptAllCertificates(B builder) throws NoSuchAlgorithmException, KeyManagementException {
  87.         SSLContext context = SSLContext.getInstance(TLS);
  88.         context.init(null, new TrustManager[] { new AcceptAllTrustManager() }, new SecureRandom());
  89.         builder.setCustomSSLContext(context);
  90.         return builder;
  91.     }

  92.     private static final HostnameVerifier DOES_NOT_VERIFY_VERIFIER = new HostnameVerifier() {
  93.         @Override
  94.         public boolean verify(String hostname, SSLSession session) {
  95.             // This verifier doesn't verify the hostname, it always returns true.
  96.             return true;
  97.         }
  98.     };

  99.     /**
  100.      * Disable the hostname verification of TLS certificates.
  101.      * <p>
  102.      * <b>Warning:</b> Use with care. This disables hostname verification of TLS certificates and essentially
  103.      * <b>invalidates all security guarantees provided by TLS</b>. Only use this method if you understand the
  104.      * implications.
  105.      * </p>
  106.      *
  107.      * @param builder a connection configuration builder.
  108.      * @return the given builder.
  109.      */
  110.     public static <B extends ConnectionConfiguration.Builder<B,?>> B disableHostnameVerificationForTlsCertificicates(B builder) {
  111.         builder.setHostnameVerifier(DOES_NOT_VERIFY_VERIFIER);
  112.         return builder;
  113.     }

  114.     public static void setEnabledProtocolsAndCiphers(final SSLSocket sslSocket,
  115.                     String[] enabledProtocols, String[] enabledCiphers)
  116.                     throws SecurityNotPossibleException {
  117.         if (enabledProtocols != null) {
  118.             Set<String> enabledProtocolsSet = new HashSet<String>(Arrays.asList(enabledProtocols));
  119.             Set<String> supportedProtocolsSet = new HashSet<String>(
  120.                             Arrays.asList(sslSocket.getSupportedProtocols()));
  121.             Set<String> protocolsIntersection = new HashSet<String>(supportedProtocolsSet);
  122.             protocolsIntersection.retainAll(enabledProtocolsSet);
  123.             if (protocolsIntersection.isEmpty()) {
  124.                 throw new SecurityNotPossibleException("Request to enable SSL/TLS protocols '"
  125.                                 + StringUtils.collectionToString(enabledProtocolsSet)
  126.                                 + "', but only '"
  127.                                 + StringUtils.collectionToString(supportedProtocolsSet)
  128.                                 + "' are supported.");
  129.             }

  130.             // Set the enabled protocols
  131.             enabledProtocols = new String[protocolsIntersection.size()];
  132.             enabledProtocols = protocolsIntersection.toArray(enabledProtocols);
  133.             sslSocket.setEnabledProtocols(enabledProtocols);
  134.         }

  135.         if (enabledCiphers != null) {
  136.             Set<String> enabledCiphersSet = new HashSet<String>(Arrays.asList(enabledCiphers));
  137.             Set<String> supportedCiphersSet = new HashSet<String>(
  138.                             Arrays.asList(sslSocket.getEnabledCipherSuites()));
  139.             Set<String> ciphersIntersection = new HashSet<String>(supportedCiphersSet);
  140.             ciphersIntersection.retainAll(enabledCiphersSet);
  141.             if (ciphersIntersection.isEmpty()) {
  142.                 throw new SecurityNotPossibleException("Request to enable SSL/TLS ciphers '"
  143.                                 + StringUtils.collectionToString(enabledCiphersSet)
  144.                                 + "', but only '"
  145.                                 + StringUtils.collectionToString(supportedCiphersSet)
  146.                                 + "' are supported.");
  147.             }

  148.             enabledCiphers = new String[ciphersIntersection.size()];
  149.             enabledCiphers = ciphersIntersection.toArray(enabledCiphers);
  150.             sslSocket.setEnabledCipherSuites(enabledCiphers);
  151.         }
  152.     }

  153.     /**
  154.      * A {@link X509TrustManager} that <b>doesn't validate</b> X.509 certificates.
  155.      * <p>
  156.      * Connections that use this TrustManager will just be encrypted, without any guarantee that the
  157.      * counter part is actually the intended one. Man-in-the-Middle attacks will be possible, since
  158.      * any certificate presented by the attacker will be considered valid.
  159.      * </p>
  160.      */
  161.     public static class AcceptAllTrustManager implements X509TrustManager {

  162.         @Override
  163.         public void checkClientTrusted(X509Certificate[] arg0, String arg1)
  164.                         throws CertificateException {
  165.             // Nothing to do here
  166.         }

  167.         @Override
  168.         public void checkServerTrusted(X509Certificate[] arg0, String arg1)
  169.                         throws CertificateException {
  170.             // Nothing to do here
  171.         }

  172.         @Override
  173.         public X509Certificate[] getAcceptedIssuers() {
  174.             return new X509Certificate[0];
  175.         }
  176.     }
  177. }