List of usage examples for javax.net.ssl SSLSocket setEnabledProtocols
public abstract void setEnabledProtocols(String protocols[]);
From source file:github.popeen.dsub.service.ssl.SSLSocketFactory.java
@SuppressWarnings("cast") public Socket createSocket() throws IOException { // the cast makes sure that the factory is working as expected SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket(); sslSocket.setEnabledProtocols(getProtocols(sslSocket)); sslSocket.setEnabledCipherSuites(getCiphers(sslSocket)); return sslSocket; }
From source file:github.popeen.dsub.service.ssl.SSLSocketFactory.java
/** * @param params Optional parameters. Parameters passed to this method will have no effect. * This method will create a unconnected instance of {@link Socket} class * using {@link javax.net.ssl.SSLSocketFactory#createSocket()} method. * @since 4.1// ww w . j a v a2 s . c o m */ @SuppressWarnings("cast") public Socket createSocket(final HttpParams params) throws IOException { // the cast makes sure that the factory is working as expected SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket(); sslSocket.setEnabledProtocols(getProtocols(sslSocket)); sslSocket.setEnabledCipherSuites(getCiphers(sslSocket)); return sslSocket; }
From source file:com.irccloud.android.HTTPFetcher.java
private void http_thread() { try {//from ww w .j a v a 2 s.co m mThread.setName("http-stream-thread"); int port = (mURI.getPort() != -1) ? mURI.getPort() : (mURI.getProtocol().equals("https") ? 443 : 80); String path = TextUtils.isEmpty(mURI.getPath()) ? "/" : mURI.getPath(); if (!TextUtils.isEmpty(mURI.getQuery())) { path += "?" + mURI.getQuery(); } PrintWriter out = new PrintWriter(mSocket.getOutputStream()); if (mProxyHost != null && mProxyHost.length() > 0 && mProxyPort > 0) { out.print("CONNECT " + mURI.getHost() + ":" + port + " HTTP/1.0\r\n"); out.print("\r\n"); out.flush(); HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream( mSocket.getInputStream()); // Read HTTP response status line. StatusLine statusLine = parseStatusLine(readLine(stream)); if (statusLine == null) { throw new HttpException("Received no reply from server."); } else if (statusLine.getStatusCode() != HttpStatus.SC_OK) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } // Read HTTP response headers. while (!TextUtils.isEmpty(readLine(stream))) ; if (mURI.getProtocol().equals("https")) { mSocket = getSSLSocketFactory().createSocket(mSocket, mURI.getHost(), port, false); SSLSocket s = (SSLSocket) mSocket; try { s.setEnabledProtocols(ENABLED_PROTOCOLS); } catch (IllegalArgumentException e) { //Not supported on older Android versions } try { s.setEnabledCipherSuites(ENABLED_CIPHERS); } catch (IllegalArgumentException e) { //Not supported on older Android versions } out = new PrintWriter(mSocket.getOutputStream()); } } if (mURI.getProtocol().equals("https")) { SSLSocket s = (SSLSocket) mSocket; StrictHostnameVerifier verifier = new StrictHostnameVerifier(); if (!verifier.verify(mURI.getHost(), s.getSession())) throw new SSLException("Hostname mismatch"); } Crashlytics.log(Log.DEBUG, TAG, "Sending HTTP request"); out.print("GET " + path + " HTTP/1.0\r\n"); out.print("Host: " + mURI.getHost() + "\r\n"); if (mURI.getHost().equals(NetworkConnection.IRCCLOUD_HOST) && NetworkConnection.getInstance().session != null && NetworkConnection.getInstance().session.length() > 0) out.print("Cookie: session=" + NetworkConnection.getInstance().session + "\r\n"); out.print("Connection: close\r\n"); out.print("Accept-Encoding: gzip\r\n"); out.print("User-Agent: " + NetworkConnection.getInstance().useragent + "\r\n"); out.print("\r\n"); out.flush(); HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(mSocket.getInputStream()); // Read HTTP response status line. StatusLine statusLine = parseStatusLine(readLine(stream)); if (statusLine != null) Crashlytics.log(Log.DEBUG, TAG, "Got HTTP response: " + statusLine); if (statusLine == null) { throw new HttpException("Received no reply from server."); } else if (statusLine.getStatusCode() != HttpStatus.SC_OK && statusLine.getStatusCode() != HttpStatus.SC_MOVED_PERMANENTLY) { Crashlytics.log(Log.ERROR, TAG, "Failure: " + mURI + ": " + statusLine.getStatusCode() + " " + statusLine.getReasonPhrase()); throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } // Read HTTP response headers. String line; boolean gzipped = false; while (!TextUtils.isEmpty(line = readLine(stream))) { Header header = parseHeader(line); if (header.getName().equalsIgnoreCase("content-encoding") && header.getValue().equalsIgnoreCase("gzip")) gzipped = true; if (statusLine.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY && header.getName().equalsIgnoreCase("location")) { Crashlytics.log(Log.INFO, TAG, "Redirecting to: " + header.getValue()); mURI = new URL(header.getValue()); mSocket.close(); mSocket = null; mThread = null; connect(); return; } } if (gzipped) onStreamConnected(new GZIPInputStream(mSocket.getInputStream())); else onStreamConnected(mSocket.getInputStream()); onFetchComplete(); } catch (Exception ex) { NetworkConnection.printStackTraceToCrashlytics(ex); onFetchFailed(); } }
From source file:com.predic8.membrane.core.transport.ssl.SSLContext.java
public Socket createSocket(InetAddress host, int port, InetAddress addr, int localPort, int connectTimeout) throws IOException { Socket s = new Socket(); s.bind(new InetSocketAddress(addr, localPort)); s.connect(new InetSocketAddress(host, port), connectTimeout); SSLSocketFactory sslsf = sslc.getSocketFactory(); SSLSocket ssls = (SSLSocket) sslsf.createSocket(s, host.getHostName(), port, true); applyCiphers(ssls);//www . j a va 2 s. c o m if (protocols != null) { ssls.setEnabledProtocols(protocols); } else { String[] protocols = ssls.getEnabledProtocols(); Set<String> set = new HashSet<String>(); for (String protocol : protocols) { if (protocol.equals("SSLv3") || protocol.equals("SSLv2Hello")) { continue; } set.add(protocol); } ssls.setEnabledProtocols(set.toArray(new String[0])); } return ssls; }
From source file:github.popeen.dsub.service.ssl.SSLSocketFactory.java
/** * @deprecated Use {@link #createLayeredSocket(Socket, String, int, boolean)} *///w w w. j a va 2 s . c o m @Deprecated public Socket createSocket(final Socket socket, final String host, int port, boolean autoClose) throws IOException, UnknownHostException { SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket(socket, host, port, autoClose); sslSocket.setEnabledProtocols(getProtocols(sslSocket)); sslSocket.setEnabledCipherSuites(getCiphers(sslSocket)); setHostName(sslSocket, host); return sslSocket; }
From source file:github.popeen.dsub.service.ssl.SSLSocketFactory.java
/** * @since 4.1/* w w w . jav a 2s . c om*/ */ public Socket createLayeredSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException { SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket(socket, host, port, autoClose); sslSocket.setEnabledProtocols(getProtocols(sslSocket)); sslSocket.setEnabledCipherSuites(getCiphers(sslSocket)); if (this.hostnameVerifier != null) { this.hostnameVerifier.verify(host, sslSocket); } // verifyHostName() didn't blowup - good! return sslSocket; }
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 {/*from w ww . ja v a 2 s . 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: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 {/* www . j a va2 s . 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); // 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);/* w ww .j a v a 2 s . co 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:com.predic8.membrane.core.transport.ssl.SSLContextCollection.java
@Override public Socket wrapAcceptedSocket(Socket socket) throws IOException { InputStream ins = socket.getInputStream(); byte[] buffer = new byte[0xFF]; int position = 0; SSLCapabilities capabilities = null; // Read the header of TLS record while (position < SSLExplorer.RECORD_HEADER_SIZE) { int count = SSLExplorer.RECORD_HEADER_SIZE - position; int n = ins.read(buffer, position, count); if (n < 0) { throw new IOException("unexpected end of stream!"); }/*from w w w. j a va 2 s . co m*/ position += n; } // Get the required size to explore the SSL capabilities int recordLength = SSLExplorer.getRequiredSize(buffer, 0, position); if (buffer.length < recordLength) { buffer = Arrays.copyOf(buffer, recordLength); } while (position < recordLength) { int count = recordLength - position; int n = ins.read(buffer, position, count); if (n < 0) { throw new IOException("unexpected end of stream!"); } position += n; } capabilities = SSLExplorer.explore(buffer, 0, recordLength); SSLContext sslContext = null; if (capabilities != null) { List<SNIServerName> serverNames = capabilities.getServerNames(); if (serverNames != null && serverNames.size() > 0) { OUTER: for (SNIServerName snisn : serverNames) { String hostname = new String(snisn.getEncoded(), "UTF-8"); for (int i = 0; i < dnsNames.size(); i++) if (dnsNames.get(i).matcher(hostname).matches()) { sslContext = sslContexts.get(i); break OUTER; } } if (sslContext == null) { // no hostname matched: send 'unrecognized_name' alert and close socket byte[] alert_unrecognized_name = { 21 /* alert */, 3, 1 /* TLS 1.0 */, 0, 2 /* length: 2 bytes */, 2 /* fatal */, 112 /* unrecognized_name */ }; try { socket.getOutputStream().write(alert_unrecognized_name); } finally { socket.close(); } StringBuilder hostname = null; for (SNIServerName snisn : serverNames) { if (hostname == null) hostname = new StringBuilder(); else hostname.append(", "); hostname.append(new String(snisn.getEncoded(), "UTF-8")); } throw new RuntimeException( "no certificate configured (sending unrecognized_name alert) for hostname \"" + hostname + "\""); } } } // no Server Name Indication used by the client: fall back to first sslContext if (sslContext == null) sslContext = sslContexts.get(0); SSLSocketFactory serviceSocketFac = sslContext.getSocketFactory(); ByteArrayInputStream bais = new ByteArrayInputStream(buffer, 0, position); SSLSocket serviceSocket; // "serviceSocket = (SSLSocket)serviceSocketFac.createSocket(socket, bais, true);" only compileable with Java 1.8 try { serviceSocket = (SSLSocket) createSocketMethod.invoke(serviceSocketFac, new Object[] { socket, bais, true }); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } sslContext.applyCiphers(serviceSocket); if (sslContext.getProtocols() != null) { serviceSocket.setEnabledProtocols(sslContext.getProtocols()); } else { String[] protocols = serviceSocket.getEnabledProtocols(); Set<String> set = new HashSet<String>(); for (String protocol : protocols) { if (protocol.equals("SSLv3") || protocol.equals("SSLv2Hello")) { continue; } set.add(protocol); } serviceSocket.setEnabledProtocols(set.toArray(new String[0])); } serviceSocket.setWantClientAuth(sslContext.isWantClientAuth()); serviceSocket.setNeedClientAuth(sslContext.isNeedClientAuth()); return serviceSocket; }