@Before public void setUp() throws Exception { DummySocket dummySocket = new DummySocket(); socket = spy(dummySocket); socketFactory = mock(SocketFactory.class); when(socketFactory.createSocket()).thenReturn(socket); sslSocket = mock(SSLSocket.class); when(sslSocket.getInputStream()).thenReturn(dummySocket.getInputStream()); when(sslSocket.getOutputStream()).thenReturn(dummySocket.getOutputStream()); sslSocketFactory = mock(SSLSocketFactory.class); when(sslSocketFactory.createSocket(any(Socket.class), anyString(), anyInt(), anyBoolean())) .thenReturn(sslSocket); hostnameVerifier = mock(HostnameVerifier.class); when(hostnameVerifier.verify(anyString(), any(SSLSession.class))).thenReturn(true); }
public static void main(String[] args) throws Exception { try (Server server = new Server()) { new Thread(server).start(); SocketFactory factory = SSLSocketFactory.getDefault(); try (SSLSocket socket = (SSLSocket) factory.createSocket("localhost", server.getPort())) { socket.setSoTimeout(2000); System.out.println("Client established TCP connection"); boolean failed = false; for (TestCase testCase : testCases) { try { testCase.test(socket); System.out.println("ERROR: no exception"); failed = true; } catch (IOException e) { System.out.println("Failed as expected: " + e); } } if (failed) { throw new Exception("One or more tests failed"); } } } }
private void upgradeToTls(Socket socket) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException { KeyStore keyStore = keyStoreProvider.getKeyStore(); String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm(); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(defaultAlgorithm); keyManagerFactory.init(keyStore, keyStoreProvider.getPassword()); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), null, null); SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket( socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true); sslSocket.setUseClientMode(false); sslSocket.startHandshake(); input = Okio.buffer(Okio.source(sslSocket.getInputStream())); output = Okio.buffer(Okio.sink(sslSocket.getOutputStream())); }
@Override protected void runClientApplication(SSLSocket socket) throws Exception { String ciphers[] = { "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA", "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA"}; socket.setEnabledCipherSuites(ciphers); socket.setUseClientMode(true); InputStream sslIS = socket.getInputStream(); OutputStream sslOS = socket.getOutputStream(); sslOS.write(280); sslOS.flush(); sslIS.read(); }
@Override public Socket connectSocket( final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException { if (log.isDebugEnabled()) { log.debug("Connecting to {}:{}", remoteAddress.getAddress(), remoteAddress.getPort()); } Socket connectedSocket = super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context); if (connectedSocket instanceof SSLSocket) { return new SdkSslSocket((SSLSocket) connectedSocket); } return new SdkSocket(connectedSocket); }
void doServerSide() throws Exception { SSLServerSocketFactory sslssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort); serverPort = sslServerSocket.getLocalPort(); /* * Signal Client, we're ready for his connect. */ serverReady = true; SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); InputStream sslIS = sslSocket.getInputStream(); OutputStream sslOS = sslSocket.getOutputStream(); sslIS.read(); sslOS.write('A'); sslOS.flush(); sslSocket.close(); }
public void handshakeCompleted(HandshakeCompletedEvent evt) { SSLSession session; String sessionId; SSLSocket socket; if (Trace.TRACE) { socket = evt.getSocket(); session = evt.getSession(); Trace.printSystemOut("SSL handshake completed:"); Trace.printSystemOut( "------------------------------------------------"); Trace.printSystemOut("socket: : " + socket); Trace.printSystemOut("cipher suite : " + session.getCipherSuite()); sessionId = StringConverter.byteToHex(session.getId()); Trace.printSystemOut("session id : " + sessionId); Trace.printSystemOut( "------------------------------------------------"); } }
/** * Returns a copy of this that omits cipher suites and TLS versions not enabled by {@code * sslSocket}. */ private ConnectionSpec supportedSpec(SSLSocket sslSocket, boolean isFallback) { String[] cipherSuitesIntersection = cipherSuites != null ? intersect(CipherSuite.ORDER_BY_NAME, sslSocket.getEnabledCipherSuites(), cipherSuites) : sslSocket.getEnabledCipherSuites(); String[] tlsVersionsIntersection = tlsVersions != null ? intersect(Util.NATURAL_ORDER, sslSocket.getEnabledProtocols(), tlsVersions) : sslSocket.getEnabledProtocols(); // In accordance with https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00 // the SCSV cipher is added to signal that a protocol fallback has taken place. String[] supportedCipherSuites = sslSocket.getSupportedCipherSuites(); int indexOfFallbackScsv = indexOf( CipherSuite.ORDER_BY_NAME, supportedCipherSuites, "TLS_FALLBACK_SCSV"); if (isFallback && indexOfFallbackScsv != -1) { cipherSuitesIntersection = concat( cipherSuitesIntersection, supportedCipherSuites[indexOfFallbackScsv]); } return new Builder(this) .cipherSuites(cipherSuitesIntersection) .tlsVersions(tlsVersionsIntersection) .build(); }
/** * Returns {@code true} if the socket, as currently configured, supports this connection spec. In * order for a socket to be compatible the enabled cipher suites and protocols must intersect. * * <p>For cipher suites, at least one of the {@link #cipherSuites() required cipher suites} must * match the socket's enabled cipher suites. If there are no required cipher suites the socket * must have at least one cipher suite enabled. * * <p>For protocols, at least one of the {@link #tlsVersions() required protocols} must match the * socket's enabled protocols. */ public boolean isCompatible(SSLSocket socket) { if (!tls) { return false; } if (tlsVersions != null && !nonEmptyIntersection( Util.NATURAL_ORDER, tlsVersions, socket.getEnabledProtocols())) { return false; } if (cipherSuites != null && !nonEmptyIntersection( CipherSuite.ORDER_BY_NAME, cipherSuites, socket.getEnabledCipherSuites())) { return false; } return true; }
public boolean check_nickname(String nickname) throws ClassNotFoundException { //connect to Registrar to check if nickname is unique boolean check = false; try { SSLSocket sslSocket=Client.get_SSLSock(); //Socket s1 = new Socket("localhost", 5999); ObjectOutputStream out = new ObjectOutputStream(sslSocket.getOutputStream()); ObjectInputStream in = new ObjectInputStream(sslSocket.getInputStream()); out.writeObject(new Message(nickname, "null"));//here goes nickname out.flush(); check = (boolean)in.readObject(); sslSocket.close(); } catch (IOException ex) { Logger.getLogger(NewConnection.class.getName()).log(Level.SEVERE, null, ex); } return check; }
@Override protected void initSocket() throws IOException { SSLSocket sslSocket = (SSLSocket) socketFactory.createSocket(destination.getAddress(), destination.getPort()); sslSocket.addHandshakeCompletedListener(handshakeCompletedEvent -> { try { LOGGER.debug("Connected [" + handshakeCompletedEvent.getSource() + ", " + sslSocket.getSession().getPeerCertificateChain()[0].getSubjectDN() + "]"); } catch (SSLPeerUnverifiedException e) { LOGGER.warn(e.getMessage(), e); } } ); sslSocket.startHandshake(); this.socket = sslSocket; }
/** * Returns the DN extracted from the peer certificate (the server DN if run on the client; the client DN (if available) if run on the server). * * If the client auth setting is WANT or NONE and a client certificate is not present, this method will return {@code null}. * If the client auth is NEED, it will throw a {@link CertificateException}. * * @param socket the SSL Socket * @return the extracted DN * @throws CertificateException if there is a problem parsing the certificate */ public static String extractPeerDNFromSSLSocket(Socket socket) throws CertificateException { String dn = null; if (socket instanceof SSLSocket) { final SSLSocket sslSocket = (SSLSocket) socket; boolean clientMode = sslSocket.getUseClientMode(); logger.debug("SSL Socket in {} mode", clientMode ? "client" : "server"); ClientAuth clientAuth = getClientAuthStatus(sslSocket); logger.debug("SSL Socket client auth status: {}", clientAuth); if (clientMode) { logger.debug("This socket is in client mode, so attempting to extract certificate from remote 'server' socket"); dn = extractPeerDNFromServerSSLSocket(sslSocket); } else { logger.debug("This socket is in server mode, so attempting to extract certificate from remote 'client' socket"); dn = extractPeerDNFromClientSSLSocket(sslSocket); } } return dn; }
public void handshakeCompleted(HandshakeCompletedEvent evt) { SSLSession session; String sessionId; SSLSocket socket; if (Error.TRACESYSTEMOUT) { socket = evt.getSocket(); session = evt.getSession(); Error.printSystemOut("SSL handshake completed:"); Error.printSystemOut( "------------------------------------------------"); Error.printSystemOut("socket: : " + socket); Error.printSystemOut("cipher suite : " + session.getCipherSuite()); sessionId = StringConverter.byteArrayToHexString(session.getId()); Error.printSystemOut("session id : " + sessionId); Error.printSystemOut( "------------------------------------------------"); } }
public Entry(URI uri, RawHeaders varyHeaders, HttpURLConnection httpConnection) throws IOException { this.uri = uri.toString(); this.varyHeaders = varyHeaders; this.requestMethod = httpConnection.getRequestMethod(); this.responseHeaders = RawHeaders.fromMultimap(httpConnection.getHeaderFields(), true); SSLSocket sslSocket = getSslSocket(httpConnection); if (sslSocket != null) { cipherSuite = sslSocket.getSession().getCipherSuite(); Certificate[] peerCertificatesNonFinal = null; try { peerCertificatesNonFinal = sslSocket.getSession().getPeerCertificates(); } catch (SSLPeerUnverifiedException ignored) { } peerCertificates = peerCertificatesNonFinal; localCertificates = sslSocket.getSession().getLocalCertificates(); } else { cipherSuite = null; peerCertificates = null; localCertificates = null; } }
private ConnectionSpec supportedSpec(SSLSocket sslSocket, boolean isFallback) { String[] cipherSuitesIntersection; String[] tlsVersionsIntersection; if (this.cipherSuites != null) { cipherSuitesIntersection = (String[]) Util.intersect(String.class, this.cipherSuites, sslSocket.getEnabledCipherSuites()); } else { cipherSuitesIntersection = sslSocket.getEnabledCipherSuites(); } if (this.tlsVersions != null) { tlsVersionsIntersection = (String[]) Util.intersect(String.class, this.tlsVersions, sslSocket.getEnabledProtocols()); } else { tlsVersionsIntersection = sslSocket.getEnabledProtocols(); } if (isFallback && Util.contains(sslSocket.getSupportedCipherSuites(), "TLS_FALLBACK_SCSV")) { cipherSuitesIntersection = Util.concat(cipherSuitesIntersection, "TLS_FALLBACK_SCSV"); } return new Builder(this).cipherSuites(cipherSuitesIntersection).tlsVersions (tlsVersionsIntersection).build(); }
@Override public String getSelectedProtocol(SSLSocket socket) { try { String protocol = (String) getProtocolMethod.invoke(socket); // SSLSocket.getApplicationProtocol returns "" if application protocols values will not // be used. Observed if you didn't specify SSLParameters.setApplicationProtocols if (protocol == null || protocol.equals("")) { return null; } return protocol; } catch (IllegalAccessException | InvocationTargetException e) { throw assertionError("unable to get selected protocols", e); } }
public static void printInfo(SSLSocket socket) { System.out.println(); System.out.println("--- SSL Socket Info ---"); System.out.print(" SupportedProtocols : "); printStringArray(socket.getSupportedProtocols()); System.out.println(" EnabledProtocols : " + socket.getEnabledProtocols()[0]); System.out.print(" SupportedCipherSuites : "); String[] supportedCipherSuites = socket.getEnabledCipherSuites(); Arrays.sort(supportedCipherSuites); printStringArray(supportedCipherSuites); System.out.println(" EnabledCipherSuites : " + socket.getEnabledCipherSuites()[0]); System.out.println(" NeedClientAuth : " + socket.getNeedClientAuth()); System.out.println(" WantClientAuth : " + socket.getWantClientAuth()); System.out.println("-----------------------"); }
/** * Checks the validity of an SSLSession's master secret. Should be run within a doPrivileged * block */ private boolean privilegedIsMasterSecretValid(final Socket socket) { if (socket instanceof SSLSocket) { SSLSession session = getSslSession(socket); if (session != null) { String className = session.getClass().getName(); if ("sun.security.ssl.SSLSessionImpl".equals(className)) { try { Object masterSecret = getMasterSecret(session, className); if (masterSecret == null) { session.invalidate(); if (LOG.isDebugEnabled()) { LOG.debug("Invalidated session " + session); } return false; } } catch (Exception e) { failedToVerifyMasterSecret(e); } } } } return true; }
/** * <p>Creates a server socket that accepts SSL connections * configured according to this factory's SSL socket configuration * parameters.</p> */ public ServerSocket createServerSocket(int port) throws IOException { final SSLSocketFactory sslSocketFactory = context == null ? getDefaultSSLSocketFactory() : context.getSocketFactory(); return new ServerSocket(port) { public Socket accept() throws IOException { Socket socket = super.accept(); SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket( socket, socket.getInetAddress().getHostName(), socket.getPort(), true); sslSocket.setUseClientMode(false); if (enabledCipherSuites != null) { sslSocket.setEnabledCipherSuites(enabledCipherSuites); } if (enabledProtocols != null) { sslSocket.setEnabledProtocols(enabledProtocols); } sslSocket.setNeedClientAuth(needClientAuth); return sslSocket; } }; }
@Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { if (!option.isAuthPeer()) { return; } String ip = null; if (socket != null && socket.isConnected() && socket instanceof SSLSocket) { InetAddress inetAddress = socket.getInetAddress(); if (inetAddress != null) { ip = inetAddress.getHostAddress(); } } checkTrustedCustom(chain, ip); trustManager.checkClientTrusted(chain, authType, socket); }
@Override public Socket accept() throws IOException { final SSLSocketFactory sslSocketFactory = context == null ? getDefaultSSLSocketFactory() : context.getSocketFactory(); Socket socket = super.accept(); SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket( socket, socket.getInetAddress().getHostName(), socket.getPort(), true); sslSocket.setUseClientMode(false); if (enabledCipherSuites != null) { sslSocket.setEnabledCipherSuites(enabledCipherSuites); } if (enabledProtocols != null) { sslSocket.setEnabledProtocols(enabledProtocols); } sslSocket.setNeedClientAuth(needClientAuth); return sslSocket; }
public SSLSocket createSSLSocket(InetAddress address, int port, InetAddress myAddress) throws IOException { SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(); if (myAddress != null) { // trying to bind to the correct ipaddress (in case of multiple vip addresses by example) // and let the JDK pick an ephemeral port sock.bind(new InetSocketAddress(myAddress, 0)); } try { sock.connect(new InetSocketAddress(address, port), 8000); } catch (SocketTimeoutException e) { throw new ConnectException("Socket timeout error (8sec)" + address + ":" + port); } return sock; }
static SSLClient init(int port, String ciphersuite) throws NoSuchAlgorithmException, IOException { SSLContext context = SSLContext.getDefault(); SSLSocketFactory ssf = (SSLSocketFactory) context.getSocketFactory(); SSLSocket socket = (SSLSocket) ssf.createSocket("localhost", port); if (ciphersuite != null) { System.out.println("Client: enable cipher suite: " + ciphersuite); socket.setEnabledCipherSuites(new String[] { ciphersuite }); } return new SSLClient(socket); }
@Override public String getCipherSuite() { SecureCacheResponse cacheResponse = delegate.getSecureCacheResponse(); if (cacheResponse != null) { return cacheResponse.getCipherSuite(); } SSLSocket sslSocket = getSslSocket(); if (sslSocket != null) { return sslSocket.getSession().getCipherSuite(); } return null; }
@Override public Socket createSocket(String string, int i) throws IOException, UnknownHostException { SSLSocket sslSocket = (SSLSocket) delegateSocketFactory.createSocket( string, i); if (null != enabledCipherSuites) { sslSocket.setEnabledCipherSuites(enabledCipherSuites); } return sslSocket; }
/** * Create a client socket. * @param serviceUrl jmx service url * @return client socket * @throws IOException if an I/O error occurs when creating the socket */ @Override public Socket createSocket(final JMXServiceURL serviceUrl) throws IOException { final SSLSocket baseSslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(serviceUrl.getHost(), serviceUrl.getPort()); baseSslSocket.setKeepAlive(true); LOGGER.log(Level.FINE, "Created client socket"); return baseSslSocket; }
private static void hardenSocket(SSLSocket sock) { if (ENABLED_CIPHERS != null) { sock.setEnabledCipherSuites(ENABLED_CIPHERS); } if (ENABLED_PROTOCOLS != null) { sock.setEnabledProtocols(ENABLED_PROTOCOLS); } }
private Socket enableTLSOnSocket(Socket socket) { if (socket != null && (socket instanceof SSLSocket)) { SSLSocket sslSocket = (SSLSocket) socket; sslSocket.setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"}); } return socket; }
public Socket connectSocket( final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException { Args.notNull(host, "HTTP host"); Args.notNull(remoteAddress, "Remote address"); final Socket sock = socket != null ? socket : createSocket(context); if (localAddress != null) { sock.bind(localAddress); } try { sock.connect(remoteAddress, connectTimeout); } catch (final IOException ex) { try { sock.close(); } catch (final IOException ignore) { } throw ex; } // Setup SSL layering if necessary if (sock instanceof SSLSocket) { final SSLSocket sslsock = (SSLSocket) sock; sslsock.startHandshake(); verifyHostname(sslsock, host.getHostName()); return sock; } else { return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context); } }
@Override protected void finalize() throws Throwable { if (secureSocket != null) { ((SSLSocket)secureSocket).removeHandshakeCompletedListener(this); } super.finalize(); }
public SSLSocket getSSLSocket() { if(mSSLSocket == null) { KeyStore keyStore = getKeyStore(); CertificateTrustManager certificateTrustManager = getCertificateTrustManager(keyStore); mSSLSocket = getSSLSocket(certificateTrustManager); } return mSSLSocket; }
@Override public Socket createSocket(Socket socket, String string, int i, boolean bln) throws IOException { SSLSocket sslSocket = (SSLSocket) delegateSocketFactory.createSocket( socket, string, i, bln); if (null != enabledCipherSuites) { sslSocket.setEnabledCipherSuites(enabledCipherSuites); } return sslSocket; }
public String getApplicationProtocol() { try { return (String) SSLSocket.class.getMethod("getApplicationProtocol").invoke(delegate); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new AssertionError(); } }
@Test public void testSetMetrics() throws IOException { SSLSocket sock = mock(SSLSocket.class); InputStream inputStream = mock(InputStream.class); when(sock.getInputStream()).thenReturn(inputStream); SdkSSLMetricsSocket sdkSSLMetricsSocket = new SdkSSLMetricsSocket(sock); sdkSSLMetricsSocket.setMetrics(new AWSRequestMetrics()); Assert.assertThat(sdkSSLMetricsSocket.getMetricsInputStream(), not(nullValue())); }
@Override public void afterHandshake(SSLSocket sslSocket) { try { removeMethod.invoke(null, sslSocket); } catch (IllegalAccessException | InvocationTargetException ignored) { throw new AssertionError(); } }
/** * Configures the supplied {@link SSLSocket} to connect to the specified host using an appropriate * {@link ConnectionSpec}. Returns the chosen {@link ConnectionSpec}, never {@code null}. * * @throws IOException if the socket does not support any of the TLS modes available */ public ConnectionSpec configureSecureSocket(SSLSocket sslSocket) throws IOException { ConnectionSpec tlsConfiguration = null; for (int i = nextModeIndex, size = connectionSpecs.size(); i < size; i++) { ConnectionSpec connectionSpec = connectionSpecs.get(i); if (connectionSpec.isCompatible(sslSocket)) { tlsConfiguration = connectionSpec; nextModeIndex = i + 1; break; } } if (tlsConfiguration == null) { // This may be the first time a connection has been attempted and the socket does not support // any the required protocols, or it may be a retry (but this socket supports fewer // protocols than was suggested by a prior socket). throw new UnknownServiceException( "Unable to find acceptable protocols. isFallback=" + isFallback + ", modes=" + connectionSpecs + ", supported protocols=" + Arrays.toString(sslSocket.getEnabledProtocols())); } isFallbackPossible = isFallbackPossible(sslSocket); Internal.instance.apply(tlsConfiguration, sslSocket, isFallback); return tlsConfiguration; }
/** Applies this spec to {@code sslSocket}. */ void apply(SSLSocket sslSocket, boolean isFallback) { ConnectionSpec specToApply = supportedSpec(sslSocket, isFallback); if (specToApply.tlsVersions != null) { sslSocket.setEnabledProtocols(specToApply.tlsVersions); } if (specToApply.cipherSuites != null) { sslSocket.setEnabledCipherSuites(specToApply.cipherSuites); } }
/** * Verify hostname against certificate * @param sslSocket Socket * @param host Host name * @throws IOException Exception if host name is not verified */ private void verifyHostname(SSLSocket sslSocket, String host) throws IOException { // Make sure we started handshake before verifying sslSocket.startHandshake(); SSLSession session = sslSocket.getSession(); if (session == null) { throw new SSLException("Hostname '" + host + "' was not verified (no session)"); } if (!hostnameVerifier.verify(host, session)) { throw new SSLPeerUnverifiedException("Hostname '" + host + "' was not verified (" + session.getPeerPrincipal() + ")"); } if (Logger.DEBUG) { Log.d(TAG, "Connected to " + session.getPeerHost() + " using " + session.getProtocol() + " (" + session.getCipherSuite() + ")"); } }
@Test public void retryableSSLHandshakeException() throws Exception { ConnectionSpecSelector connectionSpecSelector = createConnectionSpecSelector(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS); SSLSocket socket = createSocketWithEnabledProtocols(TlsVersion.TLS_1_1, TlsVersion.TLS_1_0); connectionSpecSelector.configureSecureSocket(socket); boolean retry = connectionSpecSelector.connectionFailed(RETRYABLE_EXCEPTION); assertTrue(retry); socket.close(); }