Example usage for javax.net.ssl SSLSocket setEnabledCipherSuites

List of usage examples for javax.net.ssl SSLSocket setEnabledCipherSuites

Introduction

In this page you can find the example usage for javax.net.ssl SSLSocket setEnabledCipherSuites.

Prototype

public abstract void setEnabledCipherSuites(String suites[]);

Source Link

Document

Sets the cipher suites enabled for use on this connection.

Usage

From source file:org.dcache.srm.client.FlexibleCredentialSSLConnectionSocketFactory.java

@Override
public Socket createLayeredSocket(final Socket socket, final String target, final int port,
        final HttpContext context) throws IOException {

    final X509Credential credential = (X509Credential) context
            .getAttribute(HttpClientTransport.TRANSPORT_HTTP_CREDENTIALS);
    if (credential == null) {
        throw new IOException("Client credentials are missing from context.");
    }/* www .j a va  2s  . c o m*/
    final SSLContext sslContext;
    try {
        sslContext = contextProvider.getContext(credential);
    } catch (GeneralSecurityException e) {
        throw new IOException("Failed to create SSLContext: " + e.getMessage(), e);
    }
    final SSLSocket sslsock = (SSLSocket) sslContext.getSocketFactory().createSocket(socket, target, port,
            true);
    if (supportedProtocols != null) {
        sslsock.setEnabledProtocols(supportedProtocols);
    } else {
        // If supported protocols are not explicitly set, remove all SSL protocol versions
        final String[] allProtocols = sslsock.getEnabledProtocols();
        final List<String> enabledProtocols = new ArrayList<String>(allProtocols.length);
        for (String protocol : allProtocols) {
            if (!protocol.startsWith("SSL")) {
                enabledProtocols.add(protocol);
            }
        }
        if (!enabledProtocols.isEmpty()) {
            sslsock.setEnabledProtocols(enabledProtocols.toArray(new String[enabledProtocols.size()]));
        }
    }
    if (supportedCipherSuites != null) {
        sslsock.setEnabledCipherSuites(supportedCipherSuites);
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Enabled protocols: {}", Arrays.asList(sslsock.getEnabledProtocols()));
        LOGGER.debug("Enabled cipher suites: {}", Arrays.asList(sslsock.getEnabledCipherSuites()));
    }

    prepareSocket(sslsock);
    LOGGER.debug("Starting handshake");
    sslsock.startHandshake();
    verifyHostname(sslsock, target);
    return sslsock;
}

From source file:com.newrelic.agent.deps.org.apache.http.conn.ssl.SSLConnectionSocketFactory.java

@Override
public Socket createLayeredSocket(final Socket socket, final String target, final int port,
        final HttpContext context) throws IOException {
    final SSLSocket sslsock = (SSLSocket) this.socketfactory.createSocket(socket, target, port, true);
    if (supportedProtocols != null) {
        sslsock.setEnabledProtocols(supportedProtocols);
    } else {//  w  w  w  .j a v  a 2s .  c  o m
        // If supported protocols are not explicitly set, remove all SSL protocol versions
        final String[] allProtocols = sslsock.getEnabledProtocols();
        final List<String> enabledProtocols = new ArrayList<String>(allProtocols.length);
        for (String protocol : allProtocols) {
            if (!protocol.startsWith("SSL")) {
                enabledProtocols.add(protocol);
            }
        }
        if (!enabledProtocols.isEmpty()) {
            sslsock.setEnabledProtocols(enabledProtocols.toArray(new String[enabledProtocols.size()]));
        }
    }
    if (supportedCipherSuites != null) {
        sslsock.setEnabledCipherSuites(supportedCipherSuites);
    }

    if (this.log.isDebugEnabled()) {
        this.log.debug("Enabled protocols: " + Arrays.asList(sslsock.getEnabledProtocols()));
        this.log.debug("Enabled cipher suites:" + Arrays.asList(sslsock.getEnabledCipherSuites()));
    }

    prepareSocket(sslsock);
    this.log.debug("Starting handshake");
    sslsock.startHandshake();
    verifyHostname(sslsock, target);
    return sslsock;
}

From source file:com.digitalpebble.storm.crawler.protocol.http.HttpResponse.java

/**
 * Default public constructor./*from  w w w  .j a va2  s .co  m*/
 * 
 * @param http
 * @param url
 * @param knownMetadata
 * @throws IOException
 * @throws HttpException
 */
public HttpResponse(HttpProtocol http, URL url, Metadata knownMetadata) throws IOException, HttpException {

    this.http = http;
    this.url = url;

    Scheme scheme = null;

    if ("http".equals(url.getProtocol())) {
        scheme = Scheme.HTTP;
    } else if ("https".equals(url.getProtocol())) {
        scheme = Scheme.HTTPS;
    } else {
        throw new IOException("Unknown scheme (not http/https) for url:" + url);
    }

    String path = "".equals(url.getFile()) ? "/" : url.getFile();

    // some servers will redirect a request with a host line like
    // "Host: <hostname>:80" to "http://<hpstname>/<orig_path>"- they
    // don't want the :80...

    String host = url.getHost();
    int port;
    String portString;
    if (url.getPort() == -1) {
        if (scheme == Scheme.HTTP) {
            port = 80;
        } else {
            port = 443;
        }
        portString = "";
    } else {
        port = url.getPort();
        portString = ":" + port;
    }
    Socket socket = null;

    try {
        socket = new Socket(); // create the socket
        socket.setSoTimeout(http.getTimeout());

        // connect
        String sockHost = http.useProxy() ? http.getProxyHost() : host;
        int sockPort = http.useProxy() ? http.getProxyPort() : port;
        InetSocketAddress sockAddr = new InetSocketAddress(sockHost, sockPort);
        socket.connect(sockAddr, http.getTimeout());

        if (scheme == Scheme.HTTPS) {
            SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, sockHost, sockPort, true);
            sslsocket.setUseClientMode(true);

            // Get the protocols and ciphers supported by this JVM
            Set<String> protocols = new HashSet<String>(Arrays.asList(sslsocket.getSupportedProtocols()));
            Set<String> ciphers = new HashSet<String>(Arrays.asList(sslsocket.getSupportedCipherSuites()));

            // Intersect with preferred protocols and ciphers
            protocols.retainAll(http.getTlsPreferredProtocols());
            ciphers.retainAll(http.getTlsPreferredCipherSuites());

            sslsocket.setEnabledProtocols(protocols.toArray(new String[protocols.size()]));
            sslsocket.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()]));

            sslsocket.startHandshake();
            socket = sslsocket;
        }

        this.conf = http.getConf();
        if (ConfUtils.getBoolean(conf, "store.ip.address", false) == true) {
            headers.setValue("_ip_", sockAddr.getAddress().getHostAddress());
        }

        // make request
        OutputStream req = socket.getOutputStream();

        StringBuffer reqStr = new StringBuffer("GET ");
        if (http.useProxy()) {
            reqStr.append(url.getProtocol() + "://" + host + portString + path);
        } else {
            reqStr.append(path);
        }

        reqStr.append(" HTTP/1.0\r\n");

        reqStr.append("Host: ");
        reqStr.append(host);
        reqStr.append(portString);
        reqStr.append("\r\n");

        reqStr.append("Accept-Encoding: x-gzip, gzip, deflate\r\n");

        String userAgent = http.getUserAgent();
        if ((userAgent == null) || (userAgent.length() == 0)) {
            if (HttpProtocol.LOGGER.isErrorEnabled()) {
                HttpProtocol.LOGGER.error("User-agent is not set!");
            }
        } else {
            reqStr.append("User-Agent: ");
            reqStr.append(userAgent);
            reqStr.append("\r\n");
        }

        reqStr.append("Accept-Language: ");
        reqStr.append(this.http.getAcceptLanguage());
        reqStr.append("\r\n");

        reqStr.append("Accept: ");
        reqStr.append(this.http.getAccept());
        reqStr.append("\r\n");

        if (knownMetadata != null) {
            String ifModifiedSince = knownMetadata.getFirstValue("cachedLastModified");
            if (StringUtils.isNotBlank(ifModifiedSince)) {
                reqStr.append("If-Modified-Since: ");
                reqStr.append(ifModifiedSince);
                reqStr.append("\r\n");
            }

            String ifNoneMatch = knownMetadata.getFirstValue("cachedEtag");
            if (StringUtils.isNotBlank(ifNoneMatch)) {
                reqStr.append("If-None-Match: ");
                reqStr.append(ifNoneMatch);
                reqStr.append("\r\n");
            }
        }

        reqStr.append("\r\n");

        // @see http://www.w3.org/Protocols/rfc2068/rfc2068.txt for default
        // charset
        // TODO use UTF-8 and set a charset value explicitely
        byte[] reqBytes = reqStr.toString().getBytes(StandardCharsets.ISO_8859_1);

        req.write(reqBytes);
        req.flush();

        PushbackInputStream in = // process response
                new PushbackInputStream(
                        new BufferedInputStream(socket.getInputStream(), HttpProtocol.BUFFER_SIZE),
                        HttpProtocol.BUFFER_SIZE);

        StringBuffer line = new StringBuffer();

        boolean haveSeenNonContinueStatus = false;
        while (!haveSeenNonContinueStatus) {
            // parse status code line
            this.code = parseStatusLine(in, line);
            // parse headers
            parseHeaders(in, line);
            haveSeenNonContinueStatus = code != 100; // 100 is
                                                     // "Continue"
        }
        String transferEncoding = getHeader(HttpHeaders.TRANSFER_ENCODING);
        if (transferEncoding != null && "chunked".equalsIgnoreCase(transferEncoding.trim())) {
            readChunkedContent(in, line);
        } else {
            readPlainContent(in);
        }

        String contentEncoding = getHeader(HttpHeaders.CONTENT_ENCODING);
        if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) {
            content = http.processGzipEncoded(content, url);
        } else if ("deflate".equals(contentEncoding)) {
            content = http.processDeflateEncoded(content, url);
        } else {
            HttpProtocol.LOGGER.trace("fetched {}  bytes from {}", content.length, url);
        }

    } finally {
        if (socket != null)
            socket.close();
    }

}

From source file:info.guardianproject.netcipher.client.SSLConnectionSocketFactory.java

@Override
public Socket createLayeredSocket(final Socket socket, final String target, final int port,
        final HttpContext context) throws IOException {
    final SSLSocket sslsock = (SSLSocket) this.socketfactory.createSocket(socket, target, port, true);
    if (supportedProtocols != null) {
        sslsock.setEnabledProtocols(supportedProtocols);
    } else {/*from   ww w  .j  a va  2  s .co m*/
        // If supported protocols are not explicitly set, remove all SSL protocol versions
        final String[] allProtocols = sslsock.getEnabledProtocols();
        final List<String> enabledProtocols = new ArrayList<String>(allProtocols.length);
        for (String protocol : allProtocols) {
            if (!protocol.startsWith("SSL")) {
                enabledProtocols.add(protocol);
            }
        }
        if (!enabledProtocols.isEmpty()) {
            sslsock.setEnabledProtocols(enabledProtocols.toArray(new String[enabledProtocols.size()]));
        }
    }
    if (supportedCipherSuites != null) {
        sslsock.setEnabledCipherSuites(supportedCipherSuites);
    }

    /*
        if (this.log.isDebugEnabled()) {
          this.log.debug("Enabled protocols: " + Arrays.asList(sslsock.getEnabledProtocols()));
          this.log.debug("Enabled cipher suites:" + Arrays.asList(sslsock.getEnabledCipherSuites()));
        }
    */

    prepareSocket(sslsock);

    // Android specific code to enable SNI
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "Enabling SNI for " + target);
        }
        try {
            Method method = sslsock.getClass().getMethod("setHostname", String.class);
            method.invoke(sslsock, target);
        } catch (Exception ex) {
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "SNI configuration failed", ex);
            }
        }
    }
    // End of Android specific code

    //    this.log.debug("Starting handshake");
    sslsock.startHandshake();
    verifyHostname(sslsock, target);
    return sslsock;
}

From source file:at.bitfire.davdroid.mirakel.webdav.TlsSniSocketFactory.java

@SuppressLint("DefaultLocale")
private void setReasonableEncryption(SSLSocket ssl) {
    // set reasonable SSL/TLS settings before the handshake

    // Android 5.0+ (API level21) provides reasonable default settings
    // but it still allows SSLv3
    // https://developer.android.com/about/versions/android-5.0-changes.html#ssl

    // - enable all supported protocols (enables TLSv1.1 and TLSv1.2 on Android <5.0, if available)
    // - remove all SSL versions (especially SSLv3) because they're insecure now
    List<String> protocols = new LinkedList<String>();
    for (String protocol : ssl.getSupportedProtocols())
        if (!protocol.toUpperCase().contains("SSL"))
            protocols.add(protocol);//from   ww w . j a  v  a2  s .c o  m
    Log.v(TAG, "Setting allowed TLS protocols: " + StringUtils.join(protocols, ", "));
    ssl.setEnabledProtocols(protocols.toArray(new String[0]));

    if (android.os.Build.VERSION.SDK_INT < 21) {
        // choose secure cipher suites
        List<String> allowedCiphers = Arrays.asList(// TLS 1.2
                "TLS_RSA_WITH_AES_256_GCM_SHA384", "TLS_RSA_WITH_AES_128_GCM_SHA256",
                "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
                "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
                "TLS_ECHDE_RSA_WITH_AES_128_GCM_SHA256",
                // maximum interoperability
                "TLS_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_RSA_WITH_AES_128_CBC_SHA",
                // additionally
                "TLS_RSA_WITH_AES_256_CBC_SHA", "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA",
                "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
                "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA");

        List<String> availableCiphers = Arrays.asList(ssl.getSupportedCipherSuites());

        // preferred ciphers = allowed Ciphers \ availableCiphers
        HashSet<String> preferredCiphers = new HashSet<String>(allowedCiphers);
        preferredCiphers.retainAll(availableCiphers);

        // add preferred ciphers to enabled ciphers
        // for maximum security, preferred ciphers should *replace* enabled ciphers,
        // but I guess for the security level of DAVdroid, disabling of insecure
        // ciphers should be a server-side task
        HashSet<String> enabledCiphers = preferredCiphers;
        enabledCiphers.addAll(new HashSet<String>(Arrays.asList(ssl.getEnabledCipherSuites())));

        Log.v(TAG, "Setting allowed TLS ciphers: " + StringUtils.join(enabledCiphers, ", "));
        ssl.setEnabledCipherSuites(enabledCiphers.toArray(new String[0]));
    }
}

From source file:org.apache.cassandra.security.SSLFactory.java

/** Create a socket and connect */
public static SSLSocket getSocket(EncryptionOptions options, InetAddress address, int port,
        InetAddress localAddress, int localPort) throws IOException {
    SSLContext ctx = createSSLContext(options, true);
    SSLSocket socket = (SSLSocket) ctx.getSocketFactory().createSocket(address, port, localAddress, localPort);
    String[] suits = filterCipherSuites(socket.getSupportedCipherSuites(), options.cipher_suites);
    socket.setEnabledCipherSuites(suits);
    socket.setEnabledProtocols(ACCEPTED_PROTOCOLS);
    return socket;
}

From source file:org.apache.cassandra.security.SSLFactory.java

/** Create a socket and connect, using any local address */
public static SSLSocket getSocket(EncryptionOptions options, InetAddress address, int port) throws IOException {
    SSLContext ctx = createSSLContext(options, true);
    SSLSocket socket = (SSLSocket) ctx.getSocketFactory().createSocket(address, port);
    String[] suits = filterCipherSuites(socket.getSupportedCipherSuites(), options.cipher_suites);
    socket.setEnabledCipherSuites(suits);
    socket.setEnabledProtocols(ACCEPTED_PROTOCOLS);
    return socket;
}

From source file:org.apache.cassandra.security.SSLFactory.java

/** Just create a socket */
public static SSLSocket getSocket(EncryptionOptions options) throws IOException {
    SSLContext ctx = createSSLContext(options, true);
    SSLSocket socket = (SSLSocket) ctx.getSocketFactory().createSocket();
    String[] suits = filterCipherSuites(socket.getSupportedCipherSuites(), options.cipher_suites);
    socket.setEnabledCipherSuites(suits);
    socket.setEnabledProtocols(ACCEPTED_PROTOCOLS);
    return socket;
}

From source file:org.apache.ftpserver.ssl.Ssl.java

/**
 * Returns a socket layered over an existing socket.
 *//*from w w w. j a v a  2 s.  c om*/
public Socket createSocket(String protocol, Socket soc, boolean clientMode) throws Exception {

    // already wrapped - no need to do anything
    if (soc instanceof SSLSocket) {
        return soc;
    }

    // get socket factory
    SSLContext ctx = getSSLContext(protocol);
    SSLSocketFactory socFactory = ctx.getSocketFactory();

    // create socket
    String host = soc.getInetAddress().getHostAddress();
    int port = soc.getLocalPort();
    SSLSocket ssoc = (SSLSocket) socFactory.createSocket(soc, host, port, true);
    ssoc.setUseClientMode(clientMode);

    // initialize socket
    String cipherSuites[] = ssoc.getSupportedCipherSuites();
    ssoc.setEnabledCipherSuites(cipherSuites);
    ssoc.setNeedClientAuth(m_clientAuthReqd);

    return ssoc;
}

From source file:org.apache.ftpserver.ssl.Ssl.java

/**
 * Create a secure socket./*from   w ww.j a va 2  s  .  co m*/
 */
public Socket createSocket(String protocol, InetAddress addr, int port, boolean clientMode) throws Exception {

    // get socket factory
    SSLContext ctx = getSSLContext(protocol);
    SSLSocketFactory socFactory = ctx.getSocketFactory();

    // create socket
    SSLSocket ssoc = (SSLSocket) socFactory.createSocket(addr, port);
    ssoc.setUseClientMode(clientMode);

    // initialize socket
    String cipherSuites[] = ssoc.getSupportedCipherSuites();
    ssoc.setEnabledCipherSuites(cipherSuites);
    return ssoc;
}