1package eu.siacs.conversations.utils;
2
3import java.lang.reflect.Method;
4import java.security.NoSuchAlgorithmException;
5import java.util.Arrays;
6import java.util.Collection;
7import java.util.LinkedList;
8
9import javax.net.ssl.SSLSocket;
10import javax.net.ssl.SSLSocketFactory;
11
12public class SSLSocketHelper {
13
14 public static void setSecurity(final SSLSocket sslSocket) throws NoSuchAlgorithmException {
15 final String[] supportProtocols;
16 final Collection<String> supportedProtocols = new LinkedList<>(
17 Arrays.asList(sslSocket.getSupportedProtocols()));
18 supportedProtocols.remove("SSLv3");
19 supportProtocols = supportedProtocols.toArray(new String[supportedProtocols.size()]);
20
21 sslSocket.setEnabledProtocols(supportProtocols);
22
23 final String[] cipherSuites = CryptoHelper.getOrderedCipherSuites(
24 sslSocket.getSupportedCipherSuites());
25 if (cipherSuites.length > 0) {
26 sslSocket.setEnabledCipherSuites(cipherSuites);
27 }
28 }
29
30 public static void setSNIHost(final SSLSocketFactory factory, final SSLSocket socket, final String hostname) {
31 if (factory instanceof android.net.SSLCertificateSocketFactory && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
32 ((android.net.SSLCertificateSocketFactory) factory).setHostname(socket, hostname);
33 } else {
34 try {
35 socket.getClass().getMethod("setHostname", String.class).invoke(socket, hostname);
36 } catch (Throwable e) {
37 // ignore any error, we just can't set the hostname...
38 }
39 }
40 }
41
42 public static void setAlpnProtocol(final SSLSocketFactory factory, final SSLSocket socket, final String protocol) {
43 try {
44 if (factory instanceof android.net.SSLCertificateSocketFactory && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
45 // can't call directly because of @hide?
46 //((android.net.SSLCertificateSocketFactory)factory).setAlpnProtocols(new byte[][]{protocol.getBytes("UTF-8")});
47 android.net.SSLCertificateSocketFactory.class.getMethod("setAlpnProtocols", byte[][].class).invoke(socket, new Object[]{new byte[][]{protocol.getBytes("UTF-8")}});
48 } else {
49 final Method method = socket.getClass().getMethod("setAlpnProtocols", byte[].class);
50 // the concatenation of 8-bit, length prefixed protocol names, just one in our case...
51 // http://tools.ietf.org/html/draft-agl-tls-nextprotoneg-04#page-4
52 final byte[] protocolUTF8Bytes = protocol.getBytes("UTF-8");
53 final byte[] lengthPrefixedProtocols = new byte[protocolUTF8Bytes.length + 1];
54 lengthPrefixedProtocols[0] = (byte) protocol.length(); // cannot be over 255 anyhow
55 System.arraycopy(protocolUTF8Bytes, 0, lengthPrefixedProtocols, 1, protocolUTF8Bytes.length);
56 method.invoke(socket, new Object[]{lengthPrefixedProtocols});
57 }
58 } catch (Throwable e) {
59 // ignore any error, we just can't set the alpn protocol...
60 }
61 }
62}