static { String[] enabledCiphers = null; String[] enabledProtocols = null; try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, null, new SecureRandom()); SSLSocketFactory sf = sslContext.getSocketFactory(); SSLSocket sock = (SSLSocket) sf.createSocket(); enabledCiphers = sock.getEnabledCipherSuites(); enabledProtocols = sock.getEnabledProtocols(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (KeyManagementException kme) { kme.printStackTrace(); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } ENABLED_CIPHERS = (enabledCiphers == null) ? null : reorder(enabledCiphers, ORDERED_KNOWN_CIPHERS, BLACKLISTED_CIPHERS); ENABLED_PROTOCOLS = (enabledProtocols == null) ? null : reorder(enabledProtocols, ORDERED_KNOWN_PROTOCOLS, null); }
private CipherTest(PeerFactory peerFactory) throws IOException { THREADS = Integer.parseInt(System.getProperty("numThreads", "4")); factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket socket = (SSLSocket) factory.createSocket(); String[] cipherSuites = socket.getSupportedCipherSuites(); String[] protocols = socket.getSupportedProtocols(); // String[] clientAuths = {null, "RSA", "DSA"}; String[] clientAuths = {null}; tests = new ArrayList<TestParameters>(cipherSuites.length * protocols.length * clientAuths.length); for (int i = 0; i < cipherSuites.length; i++) { String cipherSuite = cipherSuites[i]; for (int j = 0; j < protocols.length; j++) { String protocol = protocols[j]; if (!peerFactory.isSupported(cipherSuite, protocol)) { continue; } for (int k = 0; k < clientAuths.length; k++) { String clientAuth = clientAuths[k]; if ((clientAuth != null) && (cipherSuite.indexOf("DH_anon") != -1)) { // no client with anonymous ciphersuites continue; } tests.add(new TestParameters(cipherSuite, protocol, clientAuth)); } } } testIterator = tests.iterator(); }
/** * Generates an SSL-enabled socket. * * @return the new socket * @throws GeneralSecurityException on error building the socket * @throws IOException on error loading the KeyStore */ private SSLSocket getSslSocket(RemoteDevice target) throws GeneralSecurityException, IOException { // Build a new key store based on the key store manager. KeyManager[] keyManagers = coreService.getKeyStoreManager().getKeyManagers(); TrustManager[] trustManagers = coreService.getKeyStoreManager().getTrustManagers(); if (keyManagers.length == 0) { throw new IllegalStateException("No key managers"); } // Create a new SSLContext, using the new KeyManagers and TrustManagers // as the sources of keys and trust decisions, respectively. SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, trustManagers, null); // Finally, build a new SSLSocketFactory from the SSLContext, and // then generate a new SSLSocket from it. SSLSocketFactory factory = sslContext.getSocketFactory(); SSLSocket sock = (SSLSocket) factory.createSocket(); sock.setNeedClientAuth(true); sock.setUseClientMode(true); sock.setKeepAlive(true); sock.setTcpNoDelay(true); InetSocketAddress fullAddr = new InetSocketAddress(target.getAddress(), target.getPort()); sock.connect(fullAddr, SOCKET_CREATION_TIMEOUT_MS); sock.startHandshake(); return sock; }
/* * Define the client side of the test. * * If the server prematurely exits, serverReady will be set to true * to avoid infinite hangs. */ void doClientSide() throws Exception { /* * Wait for server to get started. */ while (!serverReady) { Thread.sleep(50); } SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort); // enable TLSv1.1 only sslSocket.setEnabledProtocols(new String[] {"TLSv1.1"}); // enable a block cipher sslSocket.setEnabledCipherSuites(new String[] {"TLS_RSA_WITH_AES_128_CBC_SHA"}); InputStream sslIS = sslSocket.getInputStream(); OutputStream sslOS = sslSocket.getOutputStream(); sslOS.write('B'); sslOS.flush(); sslIS.read(); sslSocket.close(); }
@Override public void run() { SSLSocketFactory socFac = _sslCtx.getSocketFactory(); SSLSocket socket = null; try { socket = (SSLSocket) socFac.createSocket(_targetAddr.getAddress(), _targetAddr.getPort()); Utility.logOutConnection(socket, _selfId); // log connection BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), Utility.ENCODING)); Utility.XMLDocToWriter(_doc, out); if (_bExpectACK) { BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), Utility.ENCODING)); Document doc = Utility.ReaderToXMLDoc(in); if (!doc.getRootElement().getName().equals(ACK)) { // if not ACK _log.error("The Peer didn't send ACK back"); } } } catch (Exception e) { _log.error("SendJob failed", e); } finally { try { if (null != socket) socket.close(); } catch (IOException e) { _log.error("close sendjob socket failed", e); } } }
/* * Define the client side of the test. * * If the server prematurely exits, serverReady will be set to true * to avoid infinite hangs. */ void doClientSide() throws Exception { /* * Wait for server to get started. */ while (!serverReady) { Thread.sleep(50); } SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort); InputStream sslIS = sslSocket.getInputStream(); OutputStream sslOS = sslSocket.getOutputStream(); for (int i = 0; i < 10; i++) { sslOS.write(280); sslOS.flush(); sslIS.read(); } for (int i = 0; i < 10; i++) { sslOS.write(280); sslOS.flush(); sslIS.read(); } sslSocket.close(); }
/** * SSL/TLS negotiation. Acquires an SSL socket of a control connection and carries out handshake * processing. * * @throws IOException If server negotiation fails */ protected void sslNegotiation() throws IOException { plainSocket = _socket_; initSslContext(); SSLSocketFactory ssf = context.getSocketFactory(); String ip = _socket_.getInetAddress().getHostAddress(); int port = _socket_.getPort(); SSLSocket socket = (SSLSocket) ssf.createSocket(_socket_, ip, port, false); socket.setEnableSessionCreation(isCreation); socket.setUseClientMode(isClientMode); // server mode if (!isClientMode) { socket.setNeedClientAuth(isNeedClientAuth); socket.setWantClientAuth(isWantClientAuth); } if (protocols != null) { socket.setEnabledProtocols(protocols); } if (suites != null) { socket.setEnabledCipherSuites(suites); } socket.startHandshake(); _socket_ = socket; _controlInput_ = new BufferedReader(new InputStreamReader(socket.getInputStream(), getControlEncoding())); _controlOutput_ = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), getControlEncoding())); }
public boolean connect(int fd, boolean sslVerifyPeer, String hostname) { try { Logger.I(TAG, "SSL connect to " + hostname); RhoSockAddr remote = getRemoteSockAddr(fd); Socket s = new RhoSocket(fd, remote); SSLSocketFactory f = getFactory(sslVerifyPeer); StringTokenizer st = new StringTokenizer(hostname, ":"); String host = st.nextToken(); SSLSocket aSock = (SSLSocket) f.createSocket(s, host, remote.port, true); aSock.setUseClientMode(true); synchronized (this) { sock = aSock; os = sock.getOutputStream(); is = sock.getInputStream(); sockfd = fd; } return true; } catch (Exception e) { reportFail("connect", e); e.printStackTrace(); return false; } }
private Socket getSocket(String hostName, int port, boolean useSsl) throws IOException { if (useSsl) { try { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) {} public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) {} } }; SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); SSLSocketFactory factory = sc.getSocketFactory(); SSLSocket sslSocket = (SSLSocket) factory.createSocket(hostName, port); sslSocket.setUseClientMode(true); return sslSocket; } catch (Exception e) { log.error("Could not create SSL Connection", e); } return null; } else { return new Socket(hostName, port); } }
public void call() { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintStream out = System.out; SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getDefault(); try { SSLSocket c = (SSLSocket) f.createSocket("localhost", 8888); printSocketInfo(c); c.startHandshake(); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(c.getOutputStream())); BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream())); String m = null; while ((m = r.readLine()) != null) { out.println(m); m = in.readLine(); w.write(m, 0, m.length()); w.newLine(); w.flush(); } w.close(); r.close(); c.close(); } catch (IOException e) { System.err.println(e.toString()); } }
public HTTPSConnectSocket(String host, int port, String urlString) throws IOException { URL url = null; try { url = new URL(urlString); } catch (MalformedURLException me) { System.out.println("Malformed url"); System.exit(1); } SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault(); ssl = (SSLSocket) ssf.createSocket(host, port); ssl.startHandshake(); // Send the CONNECT request ssl.getOutputStream().write(("CONNECT " + url.getFile() + " HTTP/1.0\r\n\r\n").getBytes()); // Read the first line of the response DataInputStream is = new DataInputStream(ssl.getInputStream()); String str = is.readLine(); // Check the HTTP error code -- it should be "200" on success if (!str.startsWith("HTTP/1.1 200 ")) { if (str.startsWith("HTTP/1.1 ")) str = str.substring(9); throw new IOException("Proxy reports \"" + str + "\""); } // Success -- skip remaining HTTP headers do { str = is.readLine(); } while (str.length() != 0); }
public NetworkThread(String server, String channel, int port) { try { this.channel = channel; if (Settings.ssl) { SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); socket = (SSLSocket) sslsocketfactory.createSocket(); List<String> limited = new LinkedList<String>(); for (String suite : ((SSLSocket) socket).getEnabledCipherSuites()) { if (!suite.contains("_DHE_")) { limited.add(suite); } } ((SSLSocket) socket).setEnabledCipherSuites(limited.toArray(new String[limited.size()])); socket.connect(new InetSocketAddress(server, port)); } else { socket = new Socket(server, port); } writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); uc = new Utilities(); line = null; } catch (Exception e) { e.printStackTrace(); } }
private Socket getIncommingSocket() throws IOException { Socket s; if (info.isUseSSL()) { SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); s = sslsocketfactory.createSocket(info.getIncomingServerName(), info.getIncomingPort()); } else { s = new Socket(info.getIncomingServerName(), info.getIncomingPort()); } return s; }
public void afterConnect() throws IOException, UnknownHostException { if (!isCachedConnection()) { SSLSocket s = null; SSLSocketFactory factory; factory = sslSocketFactory; try { if (!(serverSocket instanceof SSLSocket)) { s = (SSLSocket) factory.createSocket(serverSocket, host, port, true); } else { s = (SSLSocket) serverSocket; } } catch (IOException ex) { // If we fail to connect through the tunnel, try it // locally, as a last resort. If this doesn't work, // throw the original exception. try { s = (SSLSocket) factory.createSocket(host, port); } catch (IOException ignored) { throw ex; } } SSLSocketFactoryImpl.checkCreate(s); // // Force handshaking, so that we get any authentication. // Register a handshake callback so our session state tracks any // later session renegotiations. // String[] protocols = getProtocols(); String[] ciphers = getCipherSuites(); if (protocols != null) s.setEnabledProtocols(protocols); if (ciphers != null) s.setEnabledCipherSuites(ciphers); s.addHandshakeCompletedListener(this); s.startHandshake(); session = s.getSession(); // change the serverSocket and serverOutput serverSocket = s; try { serverOutput = new PrintStream( new BufferedOutputStream(serverSocket.getOutputStream()), false, encoding); } catch (UnsupportedEncodingException e) { throw new InternalError(encoding + " encoding not found"); } // check URL spoofing checkURLSpoofing(hv); } else { // if we are reusing a cached https session, // we don't need to do handshaking etc. But we do need to // set the ssl session session = ((SSLSocket) serverSocket).getSession(); } }
public static void main(String args[]) throws Exception { // System.setProperty("javax.net.ssl.trustStore", // "clienttrust"); SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault(); Socket s = ssf.createSocket("127.0.0.1", 5432); BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); String x = in.readLine(); System.out.println(x); in.close(); }
/* * Define the client side of the test. * * If the server prematurely exits, serverReady will be set to true * to avoid infinite hangs. */ void doClientSide() throws Exception { /* * Wait for server to get started. */ while (!serverReady) { Thread.sleep(50); } /* * See if an unknown keystore actually gets checked ok. */ System.out.println("=============="); System.out.println("Starting test0"); KeyStore uks = KeyStore.getInstance("JKS"); SSLContext ctx = SSLContext.getInstance("TLS"); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); uks.load(new FileInputStream(unknownFilename), cpasswd); kmf.init(uks, cpasswd); TrustManager[] tms = new TrustManager[] {new MyJavaxX509TrustManager()}; ctx.init(kmf.getKeyManagers(), tms, null); SSLSocketFactory sslsf = (SSLSocketFactory) ctx.getSocketFactory(); System.out.println("Trying first socket " + serverPort); SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort); doTest(sslSocket); /* * Now try the other way. */ com.sun.net.ssl.SSLContext ctx1 = com.sun.net.ssl.SSLContext.getInstance("TLS"); com.sun.net.ssl.KeyManagerFactory kmf1 = com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509"); kmf1.init(uks, cpasswd); com.sun.net.ssl.TrustManager[] tms1 = new com.sun.net.ssl.TrustManager[] {new MyComX509TrustManager()}; ctx1.init(kmf1.getKeyManagers(), tms1, null); sslsf = (SSLSocketFactory) ctx1.getSocketFactory(); System.out.println("Trying second socket " + serverPort1); sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort1); doTest(sslSocket); System.out.println("Completed test1"); }
/** * Creates the ssl collection * * @param ip - ip of the server * @return */ private static SSLSocket handshake(String ip) { try { SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(ip, 9996); String[] enabledCipherSuites = {"SSL_DH_anon_WITH_RC4_128_MD5"}; sslsocket.setEnabledCipherSuites(enabledCipherSuites); return sslsocket; } catch (Exception exception) { exception.printStackTrace(); return null; } }
public static SSLSocket wrapSocket(Socket socket) throws Exception { // ssl socket factory SSLSocketFactory sslSocketFactory = sslContext().getSocketFactory(); // ssl socket SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket( socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true); sslSocket.setUseClientMode(true); sslSocket.startHandshake(); return sslSocket; }
protected void logSupportedParameters() { if (LOGGED.compareAndSet(false, true)) { try { final SSLContext context = SSLContext.getDefault(); final String[] protocols = context.getSupportedSSLParameters().getProtocols(); final SSLSocketFactory factory = context.getSocketFactory(); final String[] cipherSuites = factory.getSupportedCipherSuites(); LOGGER.info("Supported protocols: {}", Arrays.toString(protocols)); LOGGER.info("Supported cipher suites: {}", Arrays.toString(cipherSuites)); } catch (NoSuchAlgorithmException ignored) { } } }
/** * checks if a certificate is installed for given host:port * * @param context * @param host * @param port * @return */ public IOException checkCertificate() { SSLSocketFactory factory = context.getSocketFactory(); // System.out.println("Opening connection to " + host + ":" + port + "..."); try { SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); socket.startHandshake(); socket.close(); return null; } catch (IOException e) { return e; } }
private void processHandshakeFailure(Socket raw) throws Exception { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] {UNTRUSTED_TRUST_MANAGER}, new SecureRandom()); SSLSocketFactory sslSocketFactory = context.getSocketFactory(); SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket( raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true); try { socket.startHandshake(); // we're testing a handshake failure throw new AssertionError(); } catch (IOException expected) { } socket.close(); }
public void connect() throws UnknownHostException, IOException { if (ssl_choice) { if (http_choice) { SSLSocket s = (SSLSocket) ssl_factory.createSocket(getAddress(), getPort()); s.setTcpNoDelay(true); s.startHandshake(); socket = s; } else { socket = SSLSocketFactory.getDefault().createSocket(getAddress(), getPort()); } } else { socket = new Socket(getAddress(), getPort()); } this.stream = socket.getOutputStream(); }
@Override public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { SSLSocket sslSocket = (SSLSocket) socketFactory.createSocket(socket, host, port, autoClose); hostnameVerifier.verify(host, sslSocket); return sslSocket; }
private static SSLSocketFactory sslFactory(final boolean verify) { if (verify) { return (SSLSocketFactory) SSLSocketFactory.getDefault(); } else { return (SSLSocketFactory) BlindSSLSocketFactory.getDefault(); } }
private void connectToServer() { try { if (config.getServerSsl()) { this.connect( config.getServerAddress(), config.getServerPort(), config.getServerPassword(), config.getAcceptInvalidSsl() ? new UtilSSLSocketFactory().trustAllCertificates().disableDiffieHellman() : SSLSocketFactory.getDefault()); } else { this.connect(config.getServerAddress(), config.getServerPort(), config.getServerPassword()); } if (config.useNickserv()) { this.identify(config.getNickservPassword()); } } catch (IOException | IrcException ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); } for (String channel : config.getChannels()) { this.joinChannel(channel); } }
@Override public Socket createSocket(InetAddress inetaddress, int i, InetAddress inetaddress1, int j) throws IOException { SSLSocket result = (SSLSocket) factory.createSocket(inetaddress, i, inetaddress1, j); result.setEnabledProtocols(new String[] {"SSLv3"}); return result; }
@Before public void setUp() throws Exception { server = mock(Server.class); container = mock(Container.class); when(server.getContainer()).thenReturn(container); systemEnvironment = mock(SystemEnvironment.class); when(systemEnvironment.getServerPort()).thenReturn(1234); when(systemEnvironment.getSslServerPort()).thenReturn(4567); when(systemEnvironment.keystore()).thenReturn(temporaryFolder.newFolder()); when(systemEnvironment.truststore()).thenReturn(temporaryFolder.newFolder()); when(systemEnvironment.getWebappContextPath()).thenReturn("context"); when(systemEnvironment.getCruiseWar()).thenReturn("cruise.war"); when(systemEnvironment.getParentLoaderPriority()).thenReturn(true); when(systemEnvironment.useCompressedJs()).thenReturn(true); when(systemEnvironment.useNioSslSocket()).thenReturn(true); when(systemEnvironment.getListenHost()).thenReturn("localhost"); when(systemEnvironment.getParentLoaderPriority()).thenReturn(false); when(systemEnvironment.get(SystemEnvironment.RESPONSE_BUFFER_SIZE)).thenReturn(1000); when(systemEnvironment.get(SystemEnvironment.IDLE_TIMEOUT)).thenReturn(2000); when(systemEnvironment.getJettyConfigFile()).thenReturn(new File("foo")); sslSocketFactory = mock(SSLSocketFactory.class); when(sslSocketFactory.getSupportedCipherSuites()).thenReturn(new String[] {}); goJetty6CipherSuite = mock(GoJetty6CipherSuite.class); when(goJetty6CipherSuite.getExcludedCipherSuites()).thenReturn(new String[] {"CS1", "CS2"}); configuration = mock(Jetty6GoWebXmlConfiguration.class); jetty6Server = new Jetty6Server( systemEnvironment, "pwd", sslSocketFactory, server, goJetty6CipherSuite, configuration); }
/** * Run before every test. Chooses a vin number and makes the server speak https. * * @throws Exception */ @Override public void setUp() throws Exception { super.setUp(); server = new MockWebServer(); server.useHttps((SSLSocketFactory) SSLSocketFactory.getDefault(), true); collector.chooseBus("Ericsson$Vin_Num_001"); }
@Override public Socket createSocket( final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { final int timeout = params.getConnectionTimeout(); if (timeout == 0) { Socket socket = createSocket(host, port, localAddress, localPort); if (socket instanceof SSLSocket) { ((SSLSocket) socket) .setEnabledProtocols( SSLUtils.getSupportedProtocols(((SSLSocket) socket).getEnabledProtocols())); } return socket; } else { final Socket s = ssf.createSocket(); if (s instanceof SSLSocket) { ((SSLSocket) s) .setEnabledProtocols( SSLUtils.getSupportedProtocols(((SSLSocket) s).getEnabledProtocols())); } s.bind(new InetSocketAddress(localAddress, localPort)); s.connect(new InetSocketAddress(host, port), timeout); return s; } }
private static SocketFactory getSSLSocketFactory() { SocketFactory sslSocketFactory; try { final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} } }; final SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // Create an ssl socket factory with our all-trusting manager sslSocketFactory = sslContext.getSocketFactory(); return sslSocketFactory; } catch (Exception ex) { logger.warn( "Unable to build ssl socket factory without certificate validation, using default instead.", ex); } return SSLSocketFactory.getDefault(); }