Java Examples for javax.net.ssl.SSLSocket

The following java examples will help you to understand the usage of javax.net.ssl.SSLSocket. These source code samples are taken from different open source projects.

Example 1
Project: android-15-master  File: SSLSocketImpl.java View source code
/**
     * This method works according to the specification of implemented class.
     * @see javax.net.ssl.SSLSocket#close()
     * method documentation for more information
     */
@Override
public void close() throws IOException {
    if (logger != null) {
        logger.println("SSLSocket.close " + socket_was_closed);
    }
    if (!socket_was_closed) {
        if (handshake_started) {
            alertProtocol.alert(AlertProtocol.WARNING, AlertProtocol.CLOSE_NOTIFY);
            try {
                output.write(alertProtocol.wrap());
            } catch (IOException ex) {
            }
            alertProtocol.setProcessed();
        }
        shutdown();
        closeTransportLayer();
        socket_was_closed = true;
    }
}
Example 2
Project: android-libcore64-master  File: TestSSLSocketPair.java View source code
/**
     * Create a new connected server/client socket pair within a
     * existing SSLContext. Optionally specify clientCipherSuites to
     * allow forcing new SSLSession to test SSLSessionContext
     * caching. Optionally specify serverCipherSuites for testing
     * cipher suite negotiation.
     */
public static SSLSocket[] connect(final TestSSLContext context, final String[] clientCipherSuites, final String[] serverCipherSuites) {
    try {
        final SSLSocket client = (SSLSocket) context.clientContext.getSocketFactory().createSocket(context.host, context.port);
        final SSLSocket server = (SSLSocket) context.serverSocket.accept();
        ExecutorService executor = Executors.newFixedThreadPool(2);
        Future s = executor.submit(new Callable<Void>() {

            public Void call() throws Exception {
                if (serverCipherSuites != null) {
                    server.setEnabledCipherSuites(serverCipherSuites);
                }
                server.startHandshake();
                return null;
            }
        });
        Future c = executor.submit(new Callable<Void>() {

            public Void call() throws Exception {
                if (clientCipherSuites != null) {
                    client.setEnabledCipherSuites(clientCipherSuites);
                }
                client.startHandshake();
                return null;
            }
        });
        executor.shutdown();
        // catch client and server exceptions separately so we can
        // potentially log both.
        Exception serverException;
        try {
            s.get(30, TimeUnit.SECONDS);
            serverException = null;
        } catch (Exception e) {
            serverException = e;
            e.printStackTrace();
        }
        Exception clientException;
        try {
            c.get(30, TimeUnit.SECONDS);
            clientException = null;
        } catch (Exception e) {
            clientException = e;
            e.printStackTrace();
        }
        if (serverException != null) {
            throw serverException;
        }
        if (clientException != null) {
            throw clientException;
        }
        return new SSLSocket[] { server, client };
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 3
Project: android_platform_libcore-master  File: TestSSLSocketPair.java View source code
/**
     * Create a new connected server/client socket pair within a
     * existing SSLContext. Optionally specify clientCipherSuites to
     * allow forcing new SSLSession to test SSLSessionContext
     * caching. Optionally specify serverCipherSuites for testing
     * cipher suite negotiation.
     */
public static SSLSocket[] connect(final TestSSLContext context, final String[] clientCipherSuites, final String[] serverCipherSuites) {
    try {
        final SSLSocket client = (SSLSocket) context.clientContext.getSocketFactory().createSocket(context.host, context.port);
        final SSLSocket server = (SSLSocket) context.serverSocket.accept();
        ExecutorService executor = Executors.newFixedThreadPool(2);
        Future s = executor.submit(new Callable<Void>() {

            public Void call() throws Exception {
                if (serverCipherSuites != null) {
                    server.setEnabledCipherSuites(serverCipherSuites);
                }
                server.startHandshake();
                return null;
            }
        });
        Future c = executor.submit(new Callable<Void>() {

            public Void call() throws Exception {
                if (clientCipherSuites != null) {
                    client.setEnabledCipherSuites(clientCipherSuites);
                }
                client.startHandshake();
                return null;
            }
        });
        executor.shutdown();
        // catch client and server exceptions separately so we can
        // potentially log both.
        Exception serverException;
        try {
            s.get(30, TimeUnit.SECONDS);
            serverException = null;
        } catch (Exception e) {
            serverException = e;
            e.printStackTrace();
        }
        Exception clientException;
        try {
            c.get(30, TimeUnit.SECONDS);
            clientException = null;
        } catch (Exception e) {
            clientException = e;
            e.printStackTrace();
        }
        if (serverException != null) {
            throw serverException;
        }
        if (clientException != null) {
            throw clientException;
        }
        return new SSLSocket[] { server, client };
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 4
Project: bugvm-master  File: SSLSocketImpl.java View source code
/**
     * This method works according to the specification of implemented class.
     * @see javax.net.ssl.SSLSocket#close()
     * method documentation for more information
     */
@Override
public void close() throws IOException {
    if (logger != null) {
        logger.println("SSLSocket.close " + socket_was_closed);
    }
    if (!socket_was_closed) {
        if (handshake_started) {
            alertProtocol.alert(AlertProtocol.WARNING, AlertProtocol.CLOSE_NOTIFY);
            try {
                output.write(alertProtocol.wrap());
            } catch (IOException ex) {
            }
            alertProtocol.setProcessed();
        }
        shutdown();
        closeTransportLayer();
        socket_was_closed = true;
    }
}
Example 5
Project: property-db-master  File: SSLSocketImpl.java View source code
/**
     * This method works according to the specification of implemented class.
     * @see javax.net.ssl.SSLSocket#close()
     * method documentation for more information
     */
@Override
public void close() throws IOException {
    if (logger != null) {
        logger.println("SSLSocket.close " + socket_was_closed);
    }
    if (!socket_was_closed) {
        if (handshake_started) {
            alertProtocol.alert(AlertProtocol.WARNING, AlertProtocol.CLOSE_NOTIFY);
            try {
                output.write(alertProtocol.wrap());
            } catch (IOException ex) {
            }
            alertProtocol.setProcessed();
        }
        shutdown();
        closeTransportLayer();
        socket_was_closed = true;
    }
}
Example 6
Project: robovm-master  File: TestSSLSessions.java View source code
public static final TestSSLSessions create() {
    try {
        SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
        SSLSocket ssl = (SSLSocket) sf.createSocket();
        SSLSession invalid = ssl.getSession();
        TestSSLSocketPair s = TestSSLSocketPair.create();
        return new TestSSLSessions(invalid, s.server.getSession(), s.client.getSession(), s);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 7
Project: XobotOS-master  File: SSLSocketImpl.java View source code
/**
     * This method works according to the specification of implemented class.
     * @see javax.net.ssl.SSLSocket#close()
     * method documentation for more information
     */
@Override
public void close() throws IOException {
    if (logger != null) {
        logger.println("SSLSocket.close " + socket_was_closed);
    }
    if (!socket_was_closed) {
        if (handshake_started) {
            alertProtocol.alert(AlertProtocol.WARNING, AlertProtocol.CLOSE_NOTIFY);
            try {
                output.write(alertProtocol.wrap());
            } catch (IOException ex) {
            }
            alertProtocol.setProcessed();
        }
        shutdown();
        closeTransportLayer();
        socket_was_closed = true;
    }
}
Example 8
Project: android-sdk-sources-for-api-level-23-master  File: SSLSessionBindingListenerTest.java View source code
/**
     * @throws IOException
     * @throws UnknownHostException
     * javax.net.ssl.SSLSessionBindingListener#valueUnbound(SSLSessionBindingEvent event)
     */
public void test_valueUnbound() throws UnknownHostException, IOException {
    SSLSocket sock = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
    SSLSession ss = sock.getSession();
    mySSLSessionBindingListener sbl = new mySSLSessionBindingListener();
    ss.putValue("test", sbl);
    ss.removeValue("test");
    assertTrue("valueUnbound was not called.", sbl.unboundDone);
}
Example 9
Project: ARTPart-master  File: TestSSLSocketPair.java View source code
/**
     * Create a new connected server/client socket pair within a
     * existing SSLContext. Optionally specify clientCipherSuites to
     * allow forcing new SSLSession to test SSLSessionContext
     * caching. Optionally specify serverCipherSuites for testing
     * cipher suite negotiation.
     */
public static SSLSocket[] connect(final TestSSLContext context, final String[] clientCipherSuites, final String[] serverCipherSuites) {
    try {
        final SSLSocket client = (SSLSocket) context.clientContext.getSocketFactory().createSocket(context.host, context.port);
        final SSLSocket server = (SSLSocket) context.serverSocket.accept();
        ExecutorService executor = Executors.newFixedThreadPool(2);
        Future s = executor.submit(new Callable<Void>() {

            public Void call() throws Exception {
                if (serverCipherSuites != null) {
                    server.setEnabledCipherSuites(serverCipherSuites);
                }
                server.startHandshake();
                return null;
            }
        });
        Future c = executor.submit(new Callable<Void>() {

            public Void call() throws Exception {
                if (clientCipherSuites != null) {
                    client.setEnabledCipherSuites(clientCipherSuites);
                }
                client.startHandshake();
                return null;
            }
        });
        executor.shutdown();
        // catch client and server exceptions separately so we can
        // potentially log both.
        Exception serverException;
        try {
            s.get(30, TimeUnit.SECONDS);
            serverException = null;
        } catch (Exception e) {
            serverException = e;
            e.printStackTrace();
        }
        Exception clientException;
        try {
            c.get(30, TimeUnit.SECONDS);
            clientException = null;
        } catch (Exception e) {
            clientException = e;
            e.printStackTrace();
        }
        if (serverException != null) {
            throw serverException;
        }
        if (clientException != null) {
            throw clientException;
        }
        return new SSLSocket[] { server, client };
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 10
Project: mongo-java-driver-master  File: SocketStreamHelper.java View source code
static void initialize(final Socket socket, final ServerAddress address, final SocketSettings settings, final SslSettings sslSettings) throws IOException {
    socket.setTcpNoDelay(true);
    socket.setSoTimeout(settings.getReadTimeout(MILLISECONDS));
    socket.setKeepAlive(settings.isKeepAlive());
    if (settings.getReceiveBufferSize() > 0) {
        socket.setReceiveBufferSize(settings.getReceiveBufferSize());
    }
    if (settings.getSendBufferSize() > 0) {
        socket.setSendBufferSize(settings.getSendBufferSize());
    }
    if (sslSettings.isEnabled() || socket instanceof SSLSocket) {
        if (!(socket instanceof SSLSocket)) {
            throw new MongoInternalException("SSL is enabled but the socket is not an instance of javax.net.ssl.SSLSocket");
        }
        SSLSocket sslSocket = (SSLSocket) socket;
        SSLParameters sslParameters = sslSocket.getSSLParameters();
        enableSni(address, sslParameters);
        if (!sslSettings.isInvalidHostNameAllowed()) {
            enableHostNameVerification(sslParameters);
        }
        sslSocket.setSSLParameters(sslParameters);
    }
    socket.connect(address.getSocketAddress(), settings.getConnectTimeout(MILLISECONDS));
}
Example 11
Project: mireka-master  File: JsseDefaultTlsConfiguration.java View source code
@Override
public SSLSocket createSSLSocket(Socket socket) throws IOException {
    SSLSocketFactory socketFactory = ((SSLSocketFactory) SSLSocketFactory.getDefault());
    InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
    SSLSocket sslSocket = (SSLSocket) (socketFactory.createSocket(socket, remoteAddress.getHostName(), socket.getPort(), true));
    // we are a server
    sslSocket.setUseClientMode(false);
    return sslSocket;
}
Example 12
Project: mobicents-master  File: TLSTransportClient.java View source code
public void initialize() throws IOException, NotInitializedException {
    if (destAddress == null)
        throw new NotInitializedException("Destination address is not set");
    SSLSocketFactory cltFct = parentConnection.getSSLFactory();
    SSLSocket sck = (SSLSocket) cltFct.createSocket(destAddress.getAddress(), destAddress.getPort());
    sck.setEnableSessionCreation(parentConnection.getSSLConfig().getBooleanValue(SDEnableSessionCreation.ordinal(), true));
    sck.setUseClientMode(!parentConnection.getSSLConfig().getBooleanValue(SDUseClientMode.ordinal(), true));
    if (parentConnection.getSSLConfig().getStringValue(CipherSuites.ordinal(), "") != null) {
        sck.setEnabledCipherSuites(parentConnection.getSSLConfig().getStringValue(CipherSuites.ordinal(), "").split(","));
    }
    socketChannel = sck.getChannel();
    socketChannel.connect(destAddress);
    socketChannel.configureBlocking(true);
    parentConnection.onConnected();
}
Example 13
Project: android_libcore-master  File: SSLSessionBindingListenerTest.java View source code
/**
     * @throws IOException 
     * @throws UnknownHostException 
     * @tests javax.net.ssl.SSLSessionBindingListener#valueUnbound(SSLSessionBindingEvent event)
     */
@TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "valueUnbound", args = { SSLSessionBindingEvent.class })
public void test_valueUnbound() throws UnknownHostException, IOException {
    SSLSocket sock = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
    SSLSession ss = sock.getSession();
    mySSLSessionBindingListener sbl = new mySSLSessionBindingListener();
    ss.putValue("test", sbl);
    ss.removeValue("test");
    assertTrue("valueUnbound was not called.", sbl.unboundDone);
}
Example 14
Project: TotalCrossSDK-master  File: SSL.java View source code
/**
    * Return the SSL cipher id.
    * @return The cipher id which is one of:
    * - TLS_RSA_WITH_AES_128_CBC_SHA  (0x2f)
    * - TLS_RSA_WITH_AES_256_CBC_SHA  (0x35)
    * - TLS_RSA_WITH_RC4_128_SHA      (0x05)
    * - TLS_RSA_WITH_RC4_128_MD5      (0x04)
    */
public final byte getCipherId() {
    if (ssl != null) {
        String cs = ((javax.net.ssl.SSLSocket) ssl).getSession().getCipherSuite();
        if (cs.equals("TLS_RSA_WITH_AES_128_CBC_SHA"))
            return Constants.TLS_RSA_WITH_AES_128_CBC_SHA;
        else if (cs.equals("TLS_RSA_WITH_AES_256_CBC_SHA"))
            return Constants.TLS_RSA_WITH_AES_256_CBC_SHA;
        else if (cs.equals("TLS_RSA_WITH_RC4_128_SHA"))
            return Constants.TLS_RSA_WITH_RC4_128_SHA;
        else if (cs.equals("TLS_RSA_WITH_RC4_128_MD5"))
            return Constants.TLS_RSA_WITH_RC4_128_MD5;
    }
    return -1;
}
Example 15
Project: agile4techos-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws CommunicationsException {
    javax.net.ssl.SSLSocketFactory sslFact = (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory.getDefault();
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw new CommunicationsException(mysqlIO.connection, mysqlIO.lastPacketSentTimeMs, ioEx);
    }
}
Example 16
Project: GestionBibliotheque-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws CommunicationsException {
    javax.net.ssl.SSLSocketFactory sslFact = (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory.getDefault();
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw new CommunicationsException(mysqlIO.connection, mysqlIO.lastPacketSentTimeMs, ioEx);
    }
}
Example 17
Project: StreamFS-master  File: ExportControlled.java View source code
/**
	 * Converts the socket being used in the given MysqlIO to an SSLSocket by
	 * performing the SSL/TLS handshake.
	 * 
	 * @param mysqlIO
	 *            the MysqlIO instance containing the socket to convert to an
	 *            SSLSocket.
	 * 
	 * @throws CommunicationsException
	 *             if the handshake fails, or if this distribution of
	 *             Connector/J doesn't contain the SSL crytpo hooks needed to
	 *             perform the handshake.
	 */
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws CommunicationsException {
    javax.net.ssl.SSLSocketFactory sslFact = (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory.getDefault();
    try {
        mysqlIO.mysqlConnection = sslFact.createSocket(mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true);
        // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake
        // which MySQL doesn't understand
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).setEnabledProtocols(new //$NON-NLS-1$
        String[] //$NON-NLS-1$
        { "TLSv1" });
        ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection).startHandshake();
        if (mysqlIO.connection.getUseUnbufferedInput()) {
            mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
        } else {
            mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
        }
        mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
        mysqlIO.mysqlOutput.flush();
    } catch (IOException ioEx) {
        throw new CommunicationsException(mysqlIO.connection, mysqlIO.lastPacketSentTimeMs, ioEx);
    }
}
Example 18
Project: activemq-artemis-master  File: SslSocketHelper.java View source code
public static SSLSocket createSSLSocket(String certDistinguishedName, boolean wantAuth, boolean needAuth) throws IOException {
    JMXPrincipal principal = new JMXPrincipal(certDistinguishedName);
    X509Certificate cert = new StubX509Certificate(principal);
    StubSSLSession sslSession = new StubSSLSession(cert);
    StubSSLSocket sslSocket = new StubSSLSocket(sslSession);
    sslSocket.setWantClientAuth(wantAuth);
    sslSocket.setNeedClientAuth(needAuth);
    return sslSocket;
}
Example 19
Project: activemq-master  File: SslSocketHelper.java View source code
public static SSLSocket createSSLSocket(String certDistinguishedName, boolean wantAuth, boolean needAuth) throws IOException {
    JMXPrincipal principal = new JMXPrincipal(certDistinguishedName);
    X509Certificate cert = new StubX509Certificate(principal);
    StubSSLSession sslSession = new StubSSLSession(cert);
    StubSSLSocket sslSocket = new StubSSLSocket(sslSession);
    sslSocket.setWantClientAuth(wantAuth);
    sslSocket.setNeedClientAuth(needAuth);
    return sslSocket;
}
Example 20
Project: alchemy-os-master  File: SecureConnectionImpl.java View source code
@Override
public SecurityInfo getSecurityInfo() throws IOException {
    SSLSession session = ((SSLSocket) socket).getSession();
    if (session.getPeerCertificates().length == 0) {
        throw new IOException("No certificates");
    }
    X509Certificate cert = (X509Certificate) session.getPeerCertificates()[0];
    return new SecurityInfoImpl(session.getProtocol(), session.getCipherSuite(), cert);
}
Example 21
Project: aws-java-sdk-master  File: PrivilegedMasterSecretValidator.java View source code
/**
     * 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;
}
Example 22
Project: aws-sdk-java-master  File: PrivilegedMasterSecretValidator.java View source code
/**
     * 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;
}
Example 23
Project: gyingpan-master  File: NoGCMSslSocketFactory.java View source code
private static void removeGCM(Socket sock) {
    SSLSocket socket = (SSLSocket) sock;
    String[] available = socket.getEnabledCipherSuites();
    ArrayList<String> allowed = new ArrayList<String>();
    for (String s : available) {
        if (// ignore
        s.contains("_GCM_")) {
        } else {
            allowed.add(s);
        }
    }
    socket.setEnabledCipherSuites(allowed.toArray(new String[0]));
}
Example 24
Project: hbase-master  File: SslRMIServerSocketFactorySecure.java View source code
public Socket accept() throws IOException {
    Socket socket = super.accept();
    SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, socket.getInetAddress().getHostName(), socket.getPort(), true);
    sslSocket.setUseClientMode(false);
    sslSocket.setNeedClientAuth(false);
    ArrayList<String> secureProtocols = new ArrayList<>();
    for (String p : sslSocket.getEnabledProtocols()) {
        if (!p.contains("SSLv3")) {
            secureProtocols.add(p);
        }
    }
    sslSocket.setEnabledProtocols(secureProtocols.toArray(new String[secureProtocols.size()]));
    return sslSocket;
}
Example 25
Project: java-pinning-master  File: IntegrationTest.java View source code
public static void main(String[] args) throws UnknownHostException, IOException, KeyManagementException, NoSuchAlgorithmException {
    SSLContext sc = JavaPinning.forPin("CERTSHA256:83F9171E06A313118889F7D79302BD1B7A2042EE0CFD029ABF8DD06FFA6CD9D3");
    Socket socket = new Socket("geekplace.eu", 443);
    SSLSocket sslSocket = (SSLSocket) sc.getSocketFactory().createSocket(socket, "geekplace.eu", 443, true);
    sslSocket.startHandshake();
    String name = sslSocket.getSession().getPeerPrincipal().getName();
    System.out.println(name);
    OutputStream os = sslSocket.getOutputStream();
    os.write("GET /".getBytes());
    os.flush();
}
Example 26
Project: jetty-alpn-master  File: TestServer.java View source code
public static void main(String[] args) throws Exception {
    ALPN.debug = true;
    SSLContext context = SSLSupport.newSSLContext();
    SSLServerSocket server = (SSLServerSocket) context.getServerSocketFactory().createServerSocket(8443);
    while (true) {
        SSLSocket socket = (SSLSocket) server.accept();
        socket.setUseClientMode(false);
        ALPN.put(socket, new ALPN.ServerProvider() {

            @Override
            public void unsupported() {
            }

            @Override
            public String select(List<String> protocols) {
                System.err.println("client protocols: " + protocols);
                return "spdy/3";
            }
        });
        try {
            socket.startHandshake();
        } catch (IOException x) {
            x.printStackTrace();
        }
    }
}
Example 27
Project: jetty-npn-master  File: TestServer.java View source code
public static void main(String[] args) throws Exception {
    SSLContext context = SSLSupport.newSSLContext();
    SSLServerSocket server = (SSLServerSocket) context.getServerSocketFactory().createServerSocket(8443);
    while (true) {
        SSLSocket socket = (SSLSocket) server.accept();
        socket.setUseClientMode(false);
        NextProtoNego.put(socket, new NextProtoNego.ServerProvider() {

            @Override
            public void unsupported() {
            }

            @Override
            public List<String> protocols() {
                return Arrays.asList("spdy/2", "http/1.1");
            }

            @Override
            public void protocolSelected(String protocol) {
                System.err.println("protocol = " + protocol);
            }
        });
        try {
            socket.startHandshake();
        } catch (IOException x) {
            x.printStackTrace();
        }
    }
}
Example 28
Project: mysql-binlog-connector-java-master  File: DefaultSSLSocketFactory.java View source code
@Override
public SSLSocket createSocket(Socket socket) throws SocketException {
    SSLContext sc;
    try {
        sc = SSLContext.getInstance(this.protocol);
        initSSLContext(sc);
    } catch (GeneralSecurityException e) {
        throw new SocketException(e.getMessage());
    }
    try {
        return (SSLSocket) sc.getSocketFactory().createSocket(socket, socket.getInetAddress().getHostName(), socket.getPort(), true);
    } catch (IOException e) {
        throw new SocketException(e.getMessage());
    }
}
Example 29
Project: remote-desktop-clients-master  File: TLSTunnelBase.java View source code
public void setup(RfbProto cc) throws Exception {
    try {
        SSLSocketFactory sslfactory;
        SSLSocket sslsock;
        SSLContext sc = SSLContext.getInstance("TLS");
        Log.i(TAG, "Generating TLS context");
        initContext(sc);
        Log.i(TAG, "Doing TLS handshake");
        sslfactory = sc.getSocketFactory();
        sslsock = (SSLSocket) sslfactory.createSocket(sock, sock.getInetAddress().getHostName(), sock.getPort(), true);
        sslsock.setTcpNoDelay(true);
        sslsock.setSoTimeout(Constants.SOCKET_CONN_TIMEOUT);
        setParam(sslsock);
        sslsock.setSoTimeout(0);
        /* Not necessary - just ensures that we know what cipher
       * suite we are using for the output of toString()
       */
        sslsock.startHandshake();
        Log.i(TAG, "TLS done");
        cc.setStreams(sslsock.getInputStream(), sslsock.getOutputStream());
    } catch (java.io.IOException e) {
        throw new Exception("TLS handshake failed " + e.toString());
    } catch (java.security.GeneralSecurityException e) {
        throw new Exception("TLS handshake failed " + e.toString());
    }
}
Example 30
Project: RobolectricSample-master  File: CertificateIgnoringSSLSocketFactory.java View source code
@Override
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException {
    SSLSocket sslSocket = (SSLSocket) ((sock != null) ? sock : createSocket());
    if ((localAddress != null) || (localPort > 0)) {
        if (localPort < 0) {
            localPort = 0;
        }
        sslSocket.bind(new InetSocketAddress(localAddress, localPort));
    }
    sslSocket.connect(new InetSocketAddress(host, port), HttpConnectionParams.getConnectionTimeout(params));
    sslSocket.setSoTimeout(HttpConnectionParams.getSoTimeout(params));
    return sslSocket;
}
Example 31
Project: scalampp-master  File: SecurityHelper.java View source code
/**
     * Use this method for the TLS negotiation step referred in the XMPP Core RFC (Section 5.3).
     * Use the streams of the resulting socket to proceed with communication.
     * @param socket Your currently open socket to the destiny XMPP server
     * @param server Your destiny XMPP server
     * @param port The port of the destiny XMPP server 
     * @return A secure socket
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws IOException
     */
public static Socket executeTLSNegotiation(Socket socket, String server, int port) throws NoSuchAlgorithmException, KeyManagementException, IOException {
    Socket result;
    SSLContext context = SSLContext.getInstance("TLS");
    // Verify certificate presented by the server
    context.init(// KeyManager not required
    null, new javax.net.ssl.TrustManager[] { new ServerTrustManager(server, new ConnectionConfiguration(server, port)) }, new java.security.SecureRandom());
    Socket plain = socket;
    // Secure the plain connection
    result = context.getSocketFactory().createSocket(plain, plain.getInetAddress().getHostName(), plain.getPort(), true);
    result.setSoTimeout(0);
    result.setKeepAlive(true);
    // Proceed to do the handshake
    ((SSLSocket) result).startHandshake();
    return result;
}
Example 32
Project: SparkleShare-Android-master  File: FakeSocketFactory.java View source code
@Override
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);
    InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
    if ((localAddress != null) || (localPort > 0)) {
        // we need to bind explicitly
        if (localPort < 0) {
            // indicates "any"
            localPort = 0;
        }
        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }
    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);
    return sslsock;
}
Example 33
Project: svmp-android-client-master  File: SvmpSSLSocketFactory.java View source code
private void setExtras(Socket socket) throws IOException {
    if (socket instanceof SSLSocket) {
        SSLSocket sslSocket = (SSLSocket) socket;
        sslSocket.setEnabledCipherSuites(enabledCiphers);
        sslSocket.setEnabledProtocols(enabledProtocols);
        // starts the handshake to verify the server cert before continuing
        sslSocket.startHandshake();
    }
}
Example 34
Project: transdroid-master  File: TlsSniSocketFactory.java View source code
// TLS layer
@Override
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public Socket createSocket(Socket plainSocket, String host, int port, boolean autoClose) throws IOException {
    if (autoClose) {
        // we don't need the plainSocket
        plainSocket.close();
    }
    SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
    // For self-signed certificates use a custom trust manager
    if (acceptAllCertificates) {
        sslSocketFactory.setTrustManagers(new TrustManager[] { new IgnoreSSLTrustManager() });
    } else if (selfSignedCertificateKey != null) {
        sslSocketFactory.setTrustManagers(new TrustManager[] { new SelfSignedTrustManager(selfSignedCertificateKey) });
    }
    // create and connect SSL socket, but don't do hostname/certificate verification yet
    SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
    // enable TLSv1.1/1.2 if available
    ssl.setEnabledProtocols(ssl.getSupportedProtocols());
    // set up SNI before the handshake
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        sslSocketFactory.setHostname(ssl, host);
    } else {
        try {
            java.lang.reflect.Method setHostnameMethod = ssl.getClass().getMethod("setHostname", String.class);
            setHostnameMethod.invoke(ssl, host);
        } catch (Exception e) {
            Log.d(TlsSniSocketFactory.class.getSimpleName(), "SNI not usable: " + e);
        }
    }
    // verify hostname and certificate
    SSLSession session = ssl.getSession();
    if (!(acceptAllCertificates || selfSignedCertificateKey != null) && !hostnameVerifier.verify(host, session)) {
        throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
    }
    return ssl;
}
Example 35
Project: transdroid-search-master  File: TlsSniSocketFactory.java View source code
// TLS layer
@Override
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public Socket createSocket(Socket plainSocket, String host, int port, boolean autoClose) throws IOException {
    if (autoClose) {
        // we don't need the plainSocket
        plainSocket.close();
    }
    SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
    // create and connect SSL socket, but don't do hostname/certificate verification yet
    SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
    // enable TLSv1.1/1.2 if available
    ssl.setEnabledProtocols(ssl.getSupportedProtocols());
    // set up SNI before the handshake
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        sslSocketFactory.setHostname(ssl, host);
    } else {
        try {
            java.lang.reflect.Method setHostnameMethod = ssl.getClass().getMethod("setHostname", String.class);
            setHostnameMethod.invoke(ssl, host);
        } catch (Exception e) {
            Log.d(TlsSniSocketFactory.class.getSimpleName(), "SNI not usable: " + e);
        }
    }
    // verify hostname and certificate
    SSLSession session = ssl.getSession();
    if (!hostnameVerifier.verify(host, session)) {
        throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
    }
    return ssl;
}
Example 36
Project: an2linuxclient-master  File: TcpPairingConnection.java View source code
@Override
public void run() {
    try {
        Socket s = new Socket();
        try {
            s.connect(new InetSocketAddress(serverAddress, serverPort), 5000);
        } catch (UnknownHostExceptionIllegalArgumentException |  e) {
            notifyObservers(new PairingConnectionCallbackMessage(UNKNOWN_HOST));
            try {
                s.close();
            } catch (IOException e2) {
            }
            return;
        } catch (SocketTimeoutException e) {
            notifyObservers(new PairingConnectionCallbackMessage(TIMED_OUT));
            try {
                s.close();
            } catch (IOException e2) {
            }
            return;
        } catch (SocketException e) {
            notifyObservers(new PairingConnectionCallbackMessage(FAILED_TO_CONNECT));
            try {
                s.close();
            } catch (IOException e2) {
            }
            return;
        }
        mOut = s.getOutputStream();
        mOut.write(INITIATE_PAIRING);
        SSLSocket tlsSocket = (SSLSocket) TlsHelper.getPairingTlsContext().getSocketFactory().createSocket(s, serverAddress, serverPort, true);
        tlsSocket.setUseClientMode(true);
        tlsSocket.setEnabledProtocols(TlsHelper.TLS_VERSIONS);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
            tlsSocket.setEnabledCipherSuites(TlsHelper.TLS_CIPHERS);
        } else {
            tlsSocket.setEnabledCipherSuites(TlsHelper.TLS_CIPHERS_COMPAT);
        }
        final byte[] clientCertBytes = TlsHelper.getCertificateBytes(c);
        tlsSocket.addHandshakeCompletedListener(new HandshakeCompletedListener() {

            @Override
            public void handshakeCompleted(HandshakeCompletedEvent event) {
                try {
                    Certificate serverCert = event.getPeerCertificates()[0];
                    byte[] sha256 = Sha256Helper.sha256(clientCertBytes, serverCert.getEncoded());
                    notifyObservers(new PairingConnectionCallbackMessage(TLS_HANDSHAKE_COMPLETED, Sha256Helper.getFourLineHexString(sha256), serverCert));
                } catch (Exception e) {
                    Log.e("TcpPairingConnection", "run:handshakeCompleted");
                    Log.e("StackTrace", Log.getStackTraceString(e));
                }
            }
        });
        try {
            tlsSocket.startHandshake();
        } catch (IOException e) {
            notifyObservers(new PairingConnectionCallbackMessage(FAILED_TO_CONNECT));
            try {
                mOut.close();
                tlsSocket.close();
            } catch (IOException e2) {
            }
            return;
        }
        mOut = tlsSocket.getOutputStream();
        mIn = tlsSocket.getInputStream();
        mOut.write(ConnectionHelper.intToByteArray(clientCertBytes.length));
        mOut.write(clientCertBytes);
        tlsSocket.setSoTimeout(1000);
        while (!mCancel) {
            try {
                int serverPairResponse = mIn.read();
                if (serverPairResponse == ACCEPT_PAIRING) {
                    notifyObservers(new PairingConnectionCallbackMessage(SERVER_ACCEPTED_PAIR));
                    while (!mCancel && !mPairResponseSent) {
                        try {
                            if (mIn.read() == -1) {
                                // socket closed
                                notifyObservers(new PairingConnectionCallbackMessage(SOCKET_CLOSED));
                                mCancel = true;
                            }
                        } catch (SocketTimeoutException e) {
                        }
                    }
                    mCancel = true;
                } else if (serverPairResponse == DENY_PAIRING) {
                    notifyObservers(new PairingConnectionCallbackMessage(SERVER_DENIED_PAIR));
                    mCancel = true;
                } else {
                    // socket closed or recieved something strange
                    notifyObservers(new PairingConnectionCallbackMessage(SOCKET_CLOSED));
                    mCancel = true;
                }
            } catch (SocketTimeoutException ste) {
            }
        }
        mIn.close();
        mOut.close();
        tlsSocket.close();
    } catch (Exception e) {
        Log.e("TcpPairingConnection", "run");
        Log.e("StackTrace", Log.getStackTraceString(e));
    }
}
Example 37
Project: andbase-master  File: EasySSLProtocolSocketFactory.java View source code
@Override
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);
    InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
    if ((localAddress != null) || (localPort > 0)) {
        // we need to bind explicitly
        if (localPort < 0) {
            // indicates "any"
            localPort = 0;
        }
        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }
    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);
    return sslsock;
}
Example 38
Project: Android-MQTT-Websocket-Client-master  File: SSLNetworkModule.java View source code
/**
	 * Sets the enabled cipher suites on the underlying network socket.
	 */
public void setEnabledCiphers(String[] enabledCiphers) {
    final String methodName = "setEnabledCiphers";
    this.enabledCiphers = enabledCiphers;
    if ((socket != null) && (enabledCiphers != null)) {
        if (log.isLoggable(Logger.FINE)) {
            String ciphers = "";
            for (int i = 0; i < enabledCiphers.length; i++) {
                if (i > 0) {
                    ciphers += ",";
                }
                ciphers += enabledCiphers[i];
            }
            //@TRACE 260=setEnabledCiphers ciphers={0}
            log.fine(CLASS_NAME, methodName, "260", new Object[] { ciphers });
        }
        ((SSLSocket) socket).setEnabledCipherSuites(enabledCiphers);
    }
}
Example 39
Project: android-sync-master  File: TLSSocketFactory.java View source code
/**
   * Attempt to specify the cipher suites to use for a connection. If
   * setting fails (as it will on Android 2.2, because the wrong names
   * are in use to specify ciphers), attempt to set the defaults.
   *
   * We store the list of cipher suites in `cipherSuites`, which
   * avoids this fallback handling having to be executed more than once.
   *
   * This method is synchronized to ensure correct use of that member.
   *
   * See Bug 717691 for more details.
   *
   * @param socket
   *        The SSLSocket on which to operate.
   */
public static synchronized void setEnabledCipherSuites(SSLSocket socket) {
    try {
        socket.setEnabledCipherSuites(cipherSuites);
    } catch (IllegalArgumentException e) {
        cipherSuites = socket.getSupportedCipherSuites();
        Logger.warn(LOG_TAG, "Setting enabled cipher suites failed: " + e.getMessage());
        Logger.warn(LOG_TAG, "Using " + cipherSuites.length + " supported suites.");
        socket.setEnabledCipherSuites(cipherSuites);
    }
}
Example 40
Project: AppMall-master  File: AppStoreSSLSocketFactory.java View source code
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);
    InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
    if ((localAddress != null) || (localPort > 0)) {
        // we need to bind explicitly
        if (localPort < 0) {
            // indicates "any"
            localPort = 0;
        }
        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }
    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);
    return sslsock;
}
Example 41
Project: bbb-java-master  File: FakeSocketFactory.java View source code
@Override
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);
    InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
    if ((localAddress != null) || (localPort > 0)) {
        // we need to bind explicitly
        if (localPort < 0) {
            // indicates "any"
            localPort = 0;
        }
        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }
    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);
    return sslsock;
}
Example 42
Project: bc-java-master  File: CipherSuitesTestCase.java View source code
public Exception call() throws Exception {
    try {
        TrustManagerFactory trustMgrFact = TrustManagerFactory.getInstance("PKIX", BouncyCastleJsseProvider.PROVIDER_NAME);
        trustMgrFact.init(config.clientTrustStore);
        SSLContext clientContext = SSLContext.getInstance("TLS", BouncyCastleJsseProvider.PROVIDER_NAME);
        clientContext.init(null, trustMgrFact.getTrustManagers(), SecureRandom.getInstance("DEFAULT", BouncyCastleProvider.PROVIDER_NAME));
        SSLSocketFactory fact = clientContext.getSocketFactory();
        SSLSocket cSock = (SSLSocket) fact.createSocket(HOST, port);
        cSock.setEnabledCipherSuites(new String[] { config.cipherSuite });
        this.tlsUnique = TestUtils.getChannelBinding(cSock, "tls-unique");
        TestProtocolUtil.doClientProtocol(cSock, "Hello");
    } finally {
        latch.countDown();
    }
    return null;
}
Example 43
Project: bigbluebutton-bot-master  File: FakeSocketFactory.java View source code
@Override
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);
    InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
    if ((localAddress != null) || (localPort > 0)) {
        // we need to bind explicitly
        if (localPort < 0) {
            // indicates "any"
            localPort = 0;
        }
        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }
    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);
    return sslsock;
}
Example 44
Project: buddycloud-android-master  File: TLSSNISocketFactory.java View source code
// TLS layer
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
    SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(s, host, port, autoClose);
    // set SNI before the handshake
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        Logger.info(TAG, "Setting SNI hostname");
        sslSocketFactory.setHostname(ssl, host);
    } else {
        Logger.warn(TAG, "No SNI support below Android 4.2!");
    }
    // now do the TLS handshake
    ssl.startHandshake();
    SSLSession session = ssl.getSession();
    if (session == null)
        throw new SSLException("Cannot verify SSL socket without session");
    // verify host name (important!)
    if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(host, session))
        throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
    return ssl;
}
Example 45
Project: chbosync4android-master  File: RelaxedSSLSocketFactory.java View source code
@Override
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);
    InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
    if ((localAddress != null) || (localPort > 0)) {
        // we need to bind explicitly
        if (localPort < 0) {
            // indicates "any"
            localPort = 0;
        }
        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }
    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);
    return sslsock;
}
Example 46
Project: dc---master  File: HTTPSServerThread.java View source code
public void run() {
    try {
        SSLContext sslContext = createSSLContext();
        SSLServerSocketFactory fact = sslContext.getServerSocketFactory();
        SSLServerSocket sSock = (SSLServerSocket) fact.createServerSocket(PORT_NO);
        SSLSocket sslSock = (SSLSocket) sSock.accept();
        sslSock.startHandshake();
        readRequest(sslSock.getInputStream());
        SSLSession session = sslSock.getSession();
        sendResponse(sslSock.getOutputStream());
        sslSock.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 47
Project: drftpd-master  File: PassiveConnection.java View source code
public Socket connect(String[] cipherSuites, int bufferSize) throws IOException {
    if (_serverSocket == null) {
        // can happen if abort() is called before connect()
        throw new SocketException("abort() was called before connect()");
    }
    Socket sock = null;
    try {
        sock = _serverSocket.accept();
    } finally {
        if (_serverSocket != null) {
            _serverSocket.close();
        }
        _serverSocket = null;
    }
    if (sock == null) {
        // waiting
        throw new SocketException("abort() was called while waiting for accept()");
    }
    setSockOpts(sock);
    if (sock instanceof SSLSocket) {
        SSLSocket sslsock = (SSLSocket) sock;
        if (cipherSuites != null && cipherSuites.length != 0) {
            sslsock.setEnabledCipherSuites(cipherSuites);
        }
        sslsock.setUseClientMode(_useSSLClientMode);
        sslsock.startHandshake();
    }
    return sock;
}
Example 48
Project: drftpd3-extended-master  File: PassiveConnection.java View source code
public Socket connect(String[] cipherSuites, int bufferSize) throws IOException {
    if (_serverSocket == null) {
        // can happen if abort() is called before connect()
        throw new SocketException("abort() was called before connect()");
    }
    Socket sock = null;
    try {
        sock = _serverSocket.accept();
    } finally {
        if (_serverSocket != null) {
            _serverSocket.close();
        }
        _serverSocket = null;
    }
    if (sock == null) {
        // waiting
        throw new SocketException("abort() was called while waiting for accept()");
    }
    setSockOpts(sock);
    if (sock instanceof SSLSocket) {
        SSLSocket sslsock = (SSLSocket) sock;
        if (cipherSuites != null && cipherSuites.length != 0) {
            sslsock.setEnabledCipherSuites(cipherSuites);
        }
        sslsock.setUseClientMode(_useSSLClientMode);
        sslsock.startHandshake();
    }
    return sock;
}
Example 49
Project: ecf-master  File: SNIAwareHttpClient.java View source code
@Override
public Socket connectSocket(int connectTimeout, Socket socket, HttpHost host, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpContext context) throws IOException, ConnectTimeoutException {
    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=478655
    if (socket instanceof SSLSocket) {
        try {
            final Method mSetHost = socket.getClass().getMethod("setHost", String.class);
            mSetHost.setAccessible(true);
            mSetHost.invoke(socket, host.getHostName());
        } catch (NoSuchMethodException ex) {
        } catch (IllegalAccessException ex) {
        } catch (InvocationTargetException ex) {
        } catch (RuntimeException ex) {
        }
    }
    return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
}
Example 50
Project: EiraIRC-master  File: IRCConnectionSSLImpl.java View source code
@Override
protected Socket connect() throws Exception {
    if (!SharedGlobalConfig.sslCustomTrustStore.get().isEmpty()) {
        System.setProperty("javax.net.ssl.trustStore", SharedGlobalConfig.sslCustomTrustStore.get());
    }
    SSLSocketFactory socketFactory;
    if (SharedGlobalConfig.sslTrustAllCerts.get()) {
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new TrustManager[] { new NaiveTrustManager() }, null);
        socketFactory = context.getSocketFactory();
    } else {
        socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    }
    Proxy proxy = createProxy();
    for (int i = 0; i < ports.length; i++) {
        try {
            SSLSocket sslSocket;
            if (proxy != null) {
                Socket underlying = new Socket(proxy);
                underlying.connect(new InetSocketAddress(host, ports[i]));
                sslSocket = (SSLSocket) socketFactory.createSocket(underlying, Utils.extractHost(SharedGlobalConfig.proxyHost.get()), Utils.extractPorts(SharedGlobalConfig.proxyHost.get(), DEFAULT_PROXY_PORT)[0], true);
            } else {
                sslSocket = (SSLSocket) socketFactory.createSocket(host, ports[i]);
            }
            if (!SharedGlobalConfig.bindIP.get().isEmpty()) {
                sslSocket.bind(new InetSocketAddress(SharedGlobalConfig.bindIP.get(), ports[i]));
            }
            if (SharedGlobalConfig.sslDisableDiffieHellman.get()) {
                disableDiffieHellman(sslSocket);
            }
            sslSocket.startHandshake();
            writer = new BufferedWriter(new OutputStreamWriter(sslSocket.getOutputStream(), serverConfig.getCharset()));
            reader = new BufferedReader(new InputStreamReader(sslSocket.getInputStream(), serverConfig.getCharset()));
            sender.setWriter(writer);
            return sslSocket;
        } catch (UnknownHostException e) {
            throw e;
        } catch (IOException e) {
            if (i == ports.length - 1) {
                throw e;
            }
        }
    }
    return null;
}
Example 51
Project: emf.emfstore.core-master  File: EMFStoreWebServer.java View source code
/**
	 * {@inheritDoc}
	 *
	 * @see org.apache.xmlrpc.webserver.WebServer#allowConnection(java.net.Socket)
	 */
@Override
protected boolean allowConnection(Socket socket) {
    final String[] validCiphers = ServerConfiguration.getSplittedProperty(ServerConfiguration.SSL_CIPHERS);
    if (SSLSocket.class.isInstance(socket) && validCiphers != null) {
        final SSLSocket ss = (SSLSocket) socket;
        ss.setEnabledCipherSuites(validCiphers);
    }
    return super.allowConnection(socket);
}
Example 52
Project: encryption-jvm-bootcamp-master  File: HTTPClient.java View source code
public static void main(String[] args) throws Exception {
    try {
        SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        SSLSocket socket = (SSLSocket) factory.createSocket("localhost", 2001);
        /*
			 * send http request
			 *
			 * Before any application data is sent or received, the
			 * SSL socket will do SSL handshaking first to set up
			 * the security attributes.
			 *
			 * SSL handshaking can be initiated by either flushing data
			 * down the pipe, or by starting the handshaking by hand.
			 *
			 * Handshaking is started manually in this example because
			 * PrintWriter catches all IOExceptions (including
			 * SSLExceptions), sets an internal error flag, and then
			 * returns without rethrowing the exception.
			 *
			 * Unfortunately, this means any error messages are lost,
			 * which caused lots of confusion for others using this
			 * code.  The only way to tell there was an error is to call
			 * PrintWriter.checkError().
			 */
        socket.startHandshake();
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
        String filepath = "/samplemessage.txt";
        out.println("GET " + filepath + " HTTP/1.0");
        out.println("");
        out.flush();
        /*
			 * Make sure there were no surprises
			 */
        if (out.checkError())
            System.out.println("SSLSocketClient:  java.io.PrintWriter error");
        /* read response */
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) System.out.println(inputLine);
        in.close();
        out.close();
        socket.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 53
Project: gcf-master  File: SSLSecurityInfoImpl.java View source code
static SSLSecurityInfoImpl create(SSLSocket socket) throws IOException {
    SSLSession session = socket.getSession();
    java.security.cert.Certificate[] certs = session.getPeerCertificates();
    CertificateImpl ci = null;
    if (certs != null && certs.length > 0 && certs[0] instanceof X509Certificate) {
        // TODO: is this the right way?
        ci = new CertificateImpl((X509Certificate) certs[0]);
    }
    // parse protocol name and version
    final String protocol = session.getProtocol();
    String protocolName = null;
    String protocolVersion = null;
    if (protocol.startsWith("TLS")) {
        protocolName = "TLS";
        protocolVersion = "3.1";
    } else if (protocol.startsWith("SSL")) {
        protocolName = "SSL";
        protocolVersion = "3.0";
    }
    return new SSLSecurityInfoImpl(session.getCipherSuite(), protocolName, protocolVersion, ci);
}
Example 54
Project: hestia-engine-dev-master  File: SSLNetworkModule.java View source code
/**
	 * Sets the enabled cipher suites on the underlying network socket.
	 */
public void setEnabledCiphers(String[] enabledCiphers) {
    final String methodName = "setEnabledCiphers";
    this.enabledCiphers = enabledCiphers;
    if ((socket != null) && (enabledCiphers != null)) {
        if (log.isLoggable(Logger.FINE)) {
            String ciphers = "";
            for (int i = 0; i < enabledCiphers.length; i++) {
                if (i > 0) {
                    ciphers += ",";
                }
                ciphers += enabledCiphers[i];
            }
            //@TRACE 260=setEnabledCiphers ciphers={0}
            log.fine(CLASS_NAME, methodName, "260", new Object[] { ciphers });
        }
        ((SSLSocket) socket).setEnabledCipherSuites(enabledCiphers);
    }
}
Example 55
Project: Hybrid-SDK-Android-master  File: EasySSLSocketFactory.java View source code
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);
    InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
    if ((localAddress != null) || (localPort > 0)) {
        // we need to bind explicitly  
        if (localPort < 0) {
            // indicates "any"  
            localPort = 0;
        }
        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }
    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);
    return sslsock;
}
Example 56
Project: iCreate2012-Team-CM-master  File: FakeSocketFactory.java View source code
@Override
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);
    InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
    if ((localAddress != null) || (localPort > 0)) {
        // we need to bind explicitly
        if (localPort < 0) {
            // indicates "any"
            localPort = 0;
        }
        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }
    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);
    return sslsock;
}
Example 57
Project: irma_future_id-master  File: HTTPSServerThread.java View source code
public void run() {
    try {
        SSLContext sslContext = createSSLContext();
        SSLServerSocketFactory fact = sslContext.getServerSocketFactory();
        SSLServerSocket sSock = (SSLServerSocket) fact.createServerSocket(PORT_NO);
        SSLSocket sslSock = (SSLSocket) sSock.accept();
        sslSock.startHandshake();
        readRequest(sslSock.getInputStream());
        SSLSession session = sslSock.getSession();
        sendResponse(sslSock.getOutputStream());
        sslSock.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 58
Project: jacorb-master  File: OrbWithoutListenerTest.java View source code
@Test
public void testORBDoesNotOpenListenSocket() throws Exception {
    server.ping();
    Socket socket = new Socket();
    try {
        socket.connect(new InetSocketAddress("localhost", port), TestUtils.isWindows() ? 5000 : 1000);
        if (!(socket instanceof SSLSocket) && !socket.isClosed()) {
            socket.shutdownOutput();
        }
        fail();
    } catch (ConnectException e) {
    }
    socket.close();
}
Example 59
Project: jdk7u-jdk-master  File: PrintSSL.java View source code
public static void main(String[] args) throws Exception {
    System.setProperty("javax.net.ssl.keyStorePassword", "passphrase");
    System.setProperty("javax.net.ssl.keyStore", System.getProperty("test.src", "./") + "/../../ssl/etc/keystore");
    SSLServerSocketFactory sslssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    final ServerSocket server = sslssf.createServerSocket(0);
    System.out.println(server.getLocalPort());
    System.out.flush();
    Thread t = new Thread() {

        public void run() {
            try {
                Thread.sleep(30000);
                server.close();
            } catch (Exception e) {
                ;
            }
            throw new RuntimeException("Timeout");
        }
    };
    t.setDaemon(true);
    t.start();
    ((SSLSocket) server.accept()).startHandshake();
}
Example 60
Project: le_java-master  File: LogentriesClient.java View source code
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();
}
Example 61
Project: log4mqtt-master  File: SSLNetworkModule.java View source code
/**
	 * Sets the enabled cipher suites on the underlying network socket.
	 */
public void setEnabledCiphers(String[] enabledCiphers) {
    this.enabledCiphers = enabledCiphers;
    if ((socket != null) && (enabledCiphers != null)) {
        if (trace.isOn()) {
            String ciphers = "";
            for (int i = 0; i < enabledCiphers.length; i++) {
                if (i > 0) {
                    ciphers += ",";
                }
                ciphers += enabledCiphers[i];
            }
            //@TRACE 260=setEnabledCiphers ciphers={0}
            trace.trace(Trace.FINE, 260, new Object[] { ciphers });
        }
        ((SSLSocket) socket).setEnabledCipherSuites(enabledCiphers);
    }
}
Example 62
Project: MobileSDK-master  File: SSLNetworkModule.java View source code
/**
	 * Sets the enabled cipher suites on the underlying network socket.
	 */
public void setEnabledCiphers(String[] enabledCiphers) {
    final String methodName = "setEnabledCiphers";
    this.enabledCiphers = enabledCiphers;
    if ((socket != null) && (enabledCiphers != null)) {
        if (log.isLoggable(Logger.FINE)) {
            String ciphers = "";
            for (int i = 0; i < enabledCiphers.length; i++) {
                if (i > 0) {
                    ciphers += ",";
                }
                ciphers += enabledCiphers[i];
            }
            //@TRACE 260=setEnabledCiphers ciphers={0}
            log.fine(className, methodName, "260", new Object[] { ciphers });
        }
        ((SSLSocket) socket).setEnabledCipherSuites(enabledCiphers);
    }
}
Example 63
Project: MobilSecurity-master  File: Client.java View source code
public void init(Context context) {
    try {
        SSLContext sslContext = SSLContext.getInstance(CLIENT_AGREEMENT);
        KeyManagerFactory keyManager = KeyManagerFactory.getInstance(CLIENT_KEY_MANAGER);
        TrustManagerFactory trustManager = TrustManagerFactory.getInstance(CLIENT_TRUST_MANAGER);
        KeyStore kks = KeyStore.getInstance(CLIENT_KEY_KEYSTORE);
        KeyStore tks = KeyStore.getInstance(CLIENT_TRUST_KEYSTORE);
        kks.load(context.getResources().openRawResource(R.raw.debug), CLIENT_KET_PASSWORD.toCharArray());
        tks.load(context.getResources().openRawResource(R.raw.debug), CLIENT_TRUST_PASSWORD.toCharArray());
        keyManager.init(kks, CLIENT_KET_PASSWORD.toCharArray());
        trustManager.init(tks);
        sslContext.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
        sslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(SERVER_IP, SERVER_PORT);
    } catch (Exception e) {
        Log.v("TAG", e.toString());
    }
}
Example 64
Project: multibit-hd-master  File: FixtureCallable.java View source code
@Override
public Boolean call() {
    if (serverSocket.isClosed()) {
        log.warn("Server socket is closed. Aborting.");
        return false;
    } else {
        try {
            // Wait for a client connection
            log.debug("Await client connection to SSLSocket");
            SSLSocket socket = (SSLSocket) serverSocket.accept();
            socket.startHandshake();
            log.debug("Serving fixture: {}", fixture);
            InputStream inputStream = PaymentProtocolServiceTest.class.getResourceAsStream(fixture);
            OutputStream outputStream = socket.getOutputStream();
            // Write the HTTP header
            outputStream.write("HTTP/1.0 200 OK\n".getBytes(Charsets.UTF_8));
            outputStream.write("Content-Type: ".getBytes(Charsets.UTF_8));
            outputStream.write(contentType.getBytes(Charsets.UTF_8));
            outputStream.write("\n\n".getBytes(Charsets.UTF_8));
            // Write HTTP entity
            ByteStreams.copy(inputStream, outputStream);
            // Release resources
            log.debug("Flush then close client socket...");
            socket.getOutputStream().flush();
            socket.close();
            return true;
        } catch (IOException e) {
            throw new IllegalStateException("Unexpected IOException", e);
        }
    }
}
Example 65
Project: okhttp-master  File: Jdk9Platform.java View source code
@Override
public void configureTlsExtensions(SSLSocket sslSocket, String hostname, List<Protocol> protocols) {
    try {
        SSLParameters sslParameters = sslSocket.getSSLParameters();
        List<String> names = alpnProtocolNames(protocols);
        setProtocolMethod.invoke(sslParameters, new Object[] { names.toArray(new String[names.size()]) });
        sslSocket.setSSLParameters(sslParameters);
    } catch (IllegalAccessExceptionInvocationTargetException |  e) {
        throw new AssertionError();
    }
}
Example 66
Project: openjdk-master  File: JSSEServer.java View source code
@Override
public void run() {
    try {
        System.out.println("Server: started");
        try (SSLSocket socket = (SSLSocket) server.accept()) {
            socket.setSoTimeout(TLSRestrictions.TIMEOUT);
            InputStream sslIS = socket.getInputStream();
            OutputStream sslOS = socket.getOutputStream();
            sslIS.read();
            sslOS.write('S');
            sslOS.flush();
            System.out.println("Server: finished");
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        exception = e;
    }
}
Example 67
Project: openjdk8-jdk-master  File: PrintSSL.java View source code
public static void main(String[] args) throws Exception {
    System.setProperty("javax.net.ssl.keyStorePassword", "passphrase");
    System.setProperty("javax.net.ssl.keyStore", System.getProperty("test.src", "./") + "/../../ssl/etc/keystore");
    SSLServerSocketFactory sslssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    final ServerSocket server = sslssf.createServerSocket(0);
    System.out.println(server.getLocalPort());
    System.out.flush();
    Thread t = new Thread() {

        public void run() {
            try {
                Thread.sleep(30000);
                server.close();
            } catch (Exception e) {
                ;
            }
            throw new RuntimeException("Timeout");
        }
    };
    t.setDaemon(true);
    t.start();
    ((SSLSocket) server.accept()).startHandshake();
}
Example 68
Project: org.eclipse.e4.paho.client-master  File: SSLNetworkModule.java View source code
/**
	 * Sets the enabled cipher suites on the underlying network socket.
	 */
public void setEnabledCiphers(String[] enabledCiphers) {
    this.enabledCiphers = enabledCiphers;
    if ((socket != null) && (enabledCiphers != null)) {
        if (trace.isOn()) {
            String ciphers = "";
            for (int i = 0; i < enabledCiphers.length; i++) {
                if (i > 0) {
                    ciphers += ",";
                }
                ciphers += enabledCiphers[i];
            }
            //@TRACE 260=setEnabledCiphers ciphers={0}
            trace.trace(Trace.FINE, 260, new Object[] { ciphers });
        }
        ((SSLSocket) socket).setEnabledCipherSuites(enabledCiphers);
    }
}
Example 69
Project: OrionMqtt-master  File: SSLNetworkModule.java View source code
/**
	 * Sets the enabled cipher suites on the underlying network socket.
	 */
public void setEnabledCiphers(String[] enabledCiphers) {
//		this.enabledCiphers = enabledCiphers; //m2mgo
//		if ((socket != null) && (enabledCiphers != null)) {
//			if (trace.isOn()) {
//				String ciphers = "";
//				for (int i=0;i<enabledCiphers.length;i++) {
//					if (i>0) {
//						ciphers+=",";
//					}
//					ciphers+=enabledCiphers[i];
//				}
//				//@TRACE 260=setEnabledCiphers ciphers={0}
//				trace.trace(Trace.FINE,260,new Object[]{ciphers});
//			}
//			((SSLSocket) socket).setEnabledCipherSuites(enabledCiphers);
//		}
}
Example 70
Project: oxAuth-master  File: Utils.java View source code
public static HttpClient createHttpClientTrustAll() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() {

        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    }, new X509HostnameVerifier() {

        @Override
        public void verify(String host, SSLSocket ssl) throws IOException {
        }

        @Override
        public void verify(String host, X509Certificate cert) throws SSLException {
        }

        @Override
        public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
        }

        @Override
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    registry.register(new Scheme("https", 443, sf));
    ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
    return new DefaultHttpClient(ccm);
}
Example 71
Project: paho-android-master  File: SSLNetworkModule.java View source code
/**
	 * Sets the enabled cipher suites on the underlying network socket.
	 */
public void setEnabledCiphers(String[] enabledCiphers) {
    this.enabledCiphers = enabledCiphers;
    if ((socket != null) && (enabledCiphers != null)) {
        if (trace.isOn()) {
            String ciphers = "";
            for (int i = 0; i < enabledCiphers.length; i++) {
                if (i > 0) {
                    ciphers += ",";
                }
                ciphers += enabledCiphers[i];
            }
            //@TRACE 260=setEnabledCiphers ciphers={0}
            trace.trace(Trace.FINE, 260, new Object[] { ciphers });
        }
        ((SSLSocket) socket).setEnabledCipherSuites(enabledCiphers);
    }
}
Example 72
Project: paho-for-android-master  File: SSLNetworkModule.java View source code
/**
	 * Sets the enabled cipher suites on the underlying network socket.
	 */
public void setEnabledCiphers(String[] enabledCiphers) {
    final String methodName = "setEnabledCiphers";
    this.enabledCiphers = enabledCiphers;
    if ((socket != null) && (enabledCiphers != null)) {
        if (log.isLoggable(Logger.FINE)) {
            String ciphers = "";
            for (int i = 0; i < enabledCiphers.length; i++) {
                if (i > 0) {
                    ciphers += ",";
                }
                ciphers += enabledCiphers[i];
            }
            //@TRACE 260=setEnabledCiphers ciphers={0}
            log.fine(className, methodName, "260", new Object[] { ciphers });
        }
        ((SSLSocket) socket).setEnabledCipherSuites(enabledCiphers);
    }
}
Example 73
Project: protodroid-master  File: FakeSocketFactory.java View source code
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);
    InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
    if ((localAddress != null) || (localPort > 0)) {
        // we need to bind explicitly
        if (localPort < 0) {
            // indicates "any"
            localPort = 0;
        }
        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }
    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);
    return sslsock;
}
Example 74
Project: Smack-master  File: MiniDnsDaneVerifier.java View source code
@Override
public void finish(SSLSocket sslSocket) throws CertificateException {
    if (VERIFIER.verify(sslSocket)) {
        // DANE verification was the only requirement according to the TLSA RR. We can return here.
        return;
    }
    // DANE verification was successful, but according to the TLSA RR we also must perform PKIX validation.
    if (expectingTrustManager.hasException()) {
        // PKIX validation has failed. Throw an exception but close the socket first.
        try {
            sslSocket.close();
        } catch (IOException e) {
            LOGGER.log(Level.FINER, "Closing TLS socket failed", e);
        }
        throw expectingTrustManager.getException();
    }
}
Example 75
Project: SOAP-master  File: JettyServer.java View source code
@Override
public void handle(final org.mortbay.jetty.HttpConnection connection) throws IOException, ServletException {
    final Request request = connection.getRequest();
    if (request.getMethod().equals("CONNECT")) {
        final String uri = request.getUri().toString();
        final int c = uri.indexOf(':');
        final String port = uri.substring(c + 1);
        final String host = uri.substring(0, c);
        final InetSocketAddress inetAddress = new InetSocketAddress(host, Integer.parseInt(port));
        final Socket clientSocket = connection.getEndPoint().getTransport() instanceof Socket ? (Socket) connection.getEndPoint().getTransport() : ((SocketChannel) connection.getEndPoint().getTransport()).socket();
        final InputStream in = clientSocket.getInputStream();
        final OutputStream out = clientSocket.getOutputStream();
        final SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(inetAddress.getAddress(), inetAddress.getPort());
        final Response response = connection.getResponse();
        response.setStatus(200);
        // response.setHeader("Connection", "close");
        response.flushBuffer();
        IO.copyThread(socket.getInputStream(), out);
        IO.copyThread(in, socket.getOutputStream());
    } else {
        super.handle(connection);
    }
}
Example 76
Project: soapui-master  File: JettyServer.java View source code
@Override
public void handle(final org.mortbay.jetty.HttpConnection connection) throws IOException, ServletException {
    final Request request = connection.getRequest();
    if (request.getMethod().equals("CONNECT")) {
        final String uri = request.getUri().toString();
        final int c = uri.indexOf(':');
        final String port = uri.substring(c + 1);
        final String host = uri.substring(0, c);
        final InetSocketAddress inetAddress = new InetSocketAddress(host, Integer.parseInt(port));
        final Socket clientSocket = connection.getEndPoint().getTransport() instanceof Socket ? (Socket) connection.getEndPoint().getTransport() : ((SocketChannel) connection.getEndPoint().getTransport()).socket();
        final InputStream in = clientSocket.getInputStream();
        final OutputStream out = clientSocket.getOutputStream();
        final SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(inetAddress.getAddress(), inetAddress.getPort());
        final Response response = connection.getResponse();
        response.setStatus(200);
        // response.setHeader("Connection", "close");
        response.flushBuffer();
        IO.copyThread(socket.getInputStream(), out);
        IO.copyThread(in, socket.getOutputStream());
    } else {
        super.handle(connection);
    }
}
Example 77
Project: stripe-java-master  File: StripeSSLSocketFactory.java View source code
private Socket fixupSocket(Socket sock) {
    if (!(sock instanceof SSLSocket)) {
        return sock;
    }
    SSLSocket sslSock = (SSLSocket) sock;
    Set<String> protos = new HashSet<String>(Arrays.asList(sslSock.getEnabledProtocols()));
    if (tlsv11Supported) {
        protos.add(TLSv11Proto);
    }
    if (tlsv12Supported) {
        protos.add(TLSv12Proto);
    }
    sslSock.setEnabledProtocols(protos.toArray(new String[0]));
    return sslSock;
}
Example 78
Project: subethasmtp-master  File: StartTLSCommand.java View source code
/** */
@Override
public void execute(String commandString, Session sess) throws IOException {
    if (!commandString.trim().toUpperCase(Locale.ENGLISH).equals(this.getName())) {
        sess.sendResponse("501 Syntax error (no parameters allowed)");
        return;
    }
    if (!sess.getServer().getEnableTLS()) {
        sess.sendResponse("454 TLS not supported");
        return;
    }
    try {
        Socket socket = sess.getSocket();
        if (socket instanceof SSLSocket) {
            sess.sendResponse("454 TLS not available due to temporary reason: TLS already active");
            return;
        }
        sess.sendResponse("220 Ready to start TLS");
        SSLSocket s = sess.getServer().createSSLSocket(socket);
        s.startHandshake();
        log.debug("Cipher suite: " + s.getSession().getCipherSuite());
        sess.setSocket(s);
        // clean state
        sess.resetSmtpProtocol();
        sess.setTlsStarted(true);
        if (s.getNeedClientAuth()) {
            try {
                Certificate[] peerCertificates = s.getSession().getPeerCertificates();
                sess.setTlsPeerCertificates(peerCertificates);
            } catch (SSLPeerUnverifiedException e) {
            }
        }
    } catch (SSLHandshakeException ex) {
        log.warn("startTLS() failed: " + ex);
    } catch (IOException ex) {
        log.warn("startTLS() failed: " + ex.getMessage(), ex);
    }
}
Example 79
Project: thinking-master  File: FakeSocketFactory.java View source code
@Override
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException {
    final int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    final int soTimeout = HttpConnectionParams.getSoTimeout(params);
    final InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
    final SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
    if ((localAddress != null) || (localPort > 0)) {
        // we need to bind explicitly
        if (localPort < 0) {
            // indicates "any"
            localPort = 0;
        }
        final InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }
    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);
    return sslsock;
}
Example 80
Project: uma-master  File: Utils.java View source code
public static HttpClient createHttpClientTrustAll() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() {

        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    }, new X509HostnameVerifier() {

        @Override
        public void verify(String host, SSLSocket ssl) throws IOException {
        }

        @Override
        public void verify(String host, X509Certificate cert) throws SSLException {
        }

        @Override
        public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
        }

        @Override
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    registry.register(new Scheme("https", 443, sf));
    ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
    return new DefaultHttpClient(ccm);
}
Example 81
Project: vconsole-master  File: Server.java View source code
@Override
public void run() {
    SSLSocket sslsocket = null;
    try {
        out.printf(AbstractServer.WAIT_FOR_CLIENT, new Date());
        sslsocket = (SSLSocket) serverSocket.accept();
        out.println("Client Connected !");
        sslsocket.addHandshakeCompletedListener(new CustomerCertified(ident++));
    } catch (IOException ex) {
        out.printf(AbstractServer.ERROR_SOCKET, new Date(), ex);
        ex.printStackTrace(out.getPrintStream());
    }
    newListener();
    SocketAbstractIOStream saios = null;
    try {
        saios = new SocketAbstractIOStream(sslsocket);
        saios.println("Welcome to server");
        //delete this var !!! (only for preview test)
        SocketAbstractIOStream.message = "[Server] ";
        System.out.println("create console");
        mc = new MyConsole(saios);
    } catch (IOException ex) {
        out.printf("IOStream Error %s", ex.getMessage());
        out.println("Client disconnected !");
        ex.printStackTrace(out.getPrintStream());
    } finally {
        try {
            sslsocket.close();
        } catch (IOException ex) {
        }
        out.println("Close client " + sslsocket);
    }
}
Example 82
Project: websms-api-master  File: FakeSocketFactory.java View source code
/**
	 * {@inheritDoc}
	 */
@Override
public Socket connectSocket(final Socket sock, final String host, final int port, final InetAddress localAddress, final int localPort, final HttpParams params) throws IOException {
    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);
    InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
    SSLSocket sslsock = (SSLSocket) sock;
    if (sslsock == null) {
        this.createSocket();
    }
    if ((localAddress != null) || (localPort > 0)) {
        int lp = localPort;
        // we need to bind explicitly
        if (lp < 0) {
            // indicates "any"
            lp = 0;
        }
        InetSocketAddress isa = new InetSocketAddress(localAddress, lp);
        sslsock.bind(isa);
    }
    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);
    return sslsock;
}
Example 83
Project: XPagesToolkit-master  File: ClientSSLResistanceExtender.java View source code
public static HttpClient wrapClient(HttpClient base) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLSv1");
        X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        X509HostnameVerifier verifier = new X509HostnameVerifier() {

            public void verify(String arg0, SSLSocket arg1) throws IOException {
            }

            public void verify(String arg0, X509Certificate arg1) throws SSLException {
            }

            public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {
            }

            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, verifier);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}
Example 84
Project: ambry-master  File: EchoServer.java View source code
@Override
public void run() {
    try {
        DataInputStream input = new DataInputStream(socket.getInputStream());
        DataOutputStream output = new DataOutputStream(socket.getOutputStream());
        while (socket.isConnected() && !socket.isClosed()) {
            long size = input.readLong();
            if (renegotiate.compareAndSet(true, false)) {
                ((SSLSocket) socket).startHandshake();
            }
            byte[] bytes = new byte[(int) size - 8];
            input.readFully(bytes);
            output.writeLong(size);
            output.write(bytes);
            output.flush();
        }
    } catch (IOException e) {
    } finally {
        try {
            socket.close();
        } catch (IOException e) {
            exceptions.add(e);
        }
    }
}
Example 85
Project: android-rcs-ims-stack-master  File: EasySSLSocketFactory.java View source code
/**
         * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,
         *      java.lang.String, int, java.net.InetAddress, int,
         *      org.apache.http.params.HttpParams)
         */
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);
    InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
    if ((localAddress != null) || (localPort > 0)) {
        // we need to bind explicitly
        if (localPort < 0) {
            // indicates "any"
            localPort = 0;
        }
        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }
    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);
    return sslsock;
}
Example 86
Project: Anki-Android-master  File: EasySSLSocketFactory.java View source code
/**
     * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket, java.lang.String, int,
     *      java.net.InetAddress, int, org.apache.http.params.HttpParams)
     */
@Override
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);
    InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
    if ((localAddress != null) || (localPort > 0)) {
        // we need to bind explicitly
        if (localPort < 0) {
            // indicates "any"
            localPort = 0;
        }
        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }
    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);
    return sslsock;
}
Example 87
Project: atlas-lb-master  File: EasySSLSocketFactory.java View source code
/**
     * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,
     *      String, int, java.net.InetAddress, int,
     *      org.apache.http.params.HttpParams)
     */
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);
    InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
    if ((localAddress != null) || (localPort > 0)) {
        // we need to bind explicitly
        if (localPort < 0) {
            // indicates "any"
            localPort = 0;
        }
        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }
    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);
    return sslsock;
}
Example 88
Project: camel-master  File: CamelSSLIRCConnection.java View source code
@Override
public void connect() throws IOException {
    if (sslContextParameters == null) {
        super.connect();
    } else {
        if (level != 0) {
            throw new SocketException("Socket closed or already open (" + level + ")");
        }
        IOException exception = null;
        final SSLContext sslContext;
        try {
            sslContext = sslContextParameters.createSSLContext(camelContext);
        } catch (GeneralSecurityException e) {
            throw new RuntimeCamelException("Error in SSLContextParameters configuration or instantiation.", e);
        }
        final SSLSocketFactory sf = sslContext.getSocketFactory();
        SSLSocket s = null;
        for (int i = 0; i < ports.length && s == null; i++) {
            try {
                s = (SSLSocket) sf.createSocket(host, ports[i]);
                s.startHandshake();
                exception = null;
            } catch (SSLNotSupportedException exc) {
                if (s != null) {
                    s.close();
                }
                s = null;
                throw exc;
            } catch (IOException exc) {
                if (s != null) {
                    s.close();
                }
                s = null;
                exception = exc;
            }
        }
        if (exception != null) {
            // connection wasn't successful at any port
            throw exception;
        }
        prepare(s);
    }
}
Example 89
Project: carbon-analytics-master  File: ThriftSecureClientPoolFactory.java View source code
@Override
public Object createClient(String protocol, String hostName, int port) throws DataEndpointSecurityException, DataEndpointAgentConfigurationException {
    if (protocol.equalsIgnoreCase(DataEndpointConfiguration.Protocol.SSL.toString())) {
        int timeout = AgentHolder.getInstance().getDataEndpointAgent(DataEndpointConstants.THRIFT_DATA_AGENT_TYPE).getAgentConfiguration().getSocketTimeoutMS();
        String sslProtocols = AgentHolder.getInstance().getDataEndpointAgent(DataEndpointConstants.THRIFT_DATA_AGENT_TYPE).getAgentConfiguration().getSslEnabledProtocols();
        String ciphers = AgentHolder.getInstance().getDataEndpointAgent(DataEndpointConstants.THRIFT_DATA_AGENT_TYPE).getAgentConfiguration().getCiphers();
        try {
            TTransport receiverTransport = TSSLTransportFactory.getClientSocket(hostName, port, timeout, params);
            TSocket tSocket = (TSocket) receiverTransport;
            SSLSocket sslSocket = (SSLSocket) tSocket.getSocket();
            if (sslProtocols != null && sslProtocols.length() != 0) {
                String[] sslProtocolsArray = sslProtocols.split(",");
                sslSocket.setEnabledProtocols(sslProtocolsArray);
            }
            if (ciphers != null && ciphers.length() != 0) {
                String[] ciphersArray = ciphers.split(",");
                sslSocket.setEnabledCipherSuites(ciphersArray);
            }
            TProtocol tProtocol = new TBinaryProtocol(receiverTransport);
            return new ThriftSecureEventTransmissionService.Client(tProtocol);
        } catch (TTransportException e) {
            throw new DataEndpointSecurityException("Error while trying to connect to " + protocol + "://" + hostName + ":" + port, e);
        }
    }
    throw new DataEndpointSecurityException("Unsupported protocol :" + protocol + " used to authenticate the client, only " + DataEndpointConfiguration.Protocol.SSL.toString() + " is supported");
}
Example 90
Project: cloudstack-master  File: HttpClientWrapper.java View source code
public static HttpClient wrapClient(HttpClient base) {
    try {
        SSLContext ctx = SSLUtils.getSSLContext();
        X509TrustManager tm = new X509TrustManager() {

            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        X509HostnameVerifier verifier = new X509HostnameVerifier() {

            @Override
            public void verify(String string, SSLSocket ssls) throws IOException {
            }

            @Override
            public void verify(String string, X509Certificate xc) throws SSLException {
            }

            @Override
            public void verify(String string, String[] strings, String[] strings1) throws SSLException {
            }

            @Override
            public boolean verify(String string, SSLSession ssls) {
                return true;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(verifier);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}
Example 91
Project: conversation-master  File: SSLSocketHelper.java View source code
public static void setSecurity(final SSLSocket sslSocket) throws NoSuchAlgorithmException {
    final String[] supportProtocols;
    final Collection<String> supportedProtocols = new LinkedList<>(Arrays.asList(sslSocket.getSupportedProtocols()));
    supportedProtocols.remove("SSLv3");
    supportProtocols = supportedProtocols.toArray(new String[supportedProtocols.size()]);
    sslSocket.setEnabledProtocols(supportProtocols);
    final String[] cipherSuites = CryptoHelper.getOrderedCipherSuites(sslSocket.getSupportedCipherSuites());
    if (cipherSuites.length > 0) {
        sslSocket.setEnabledCipherSuites(cipherSuites);
    }
}
Example 92
Project: Conversations-master  File: SSLSocketHelper.java View source code
public static void setSecurity(final SSLSocket sslSocket) throws NoSuchAlgorithmException {
    final String[] supportProtocols;
    final Collection<String> supportedProtocols = new LinkedList<>(Arrays.asList(sslSocket.getSupportedProtocols()));
    supportedProtocols.remove("SSLv3");
    supportProtocols = supportedProtocols.toArray(new String[supportedProtocols.size()]);
    sslSocket.setEnabledProtocols(supportProtocols);
    final String[] cipherSuites = CryptoHelper.getOrderedCipherSuites(sslSocket.getSupportedCipherSuites());
    if (cipherSuites.length > 0) {
        sslSocket.setEnabledCipherSuites(cipherSuites);
    }
}
Example 93
Project: crawler-master  File: HTTPSFaker.java View source code
/**
   * Get a HttpClient that accept any HTTP certificate.
   *
   * @param cm the connection manager to use when creating the new HttpClient
   * @return a httpClient that accept any HTTP certificate
   */
@SuppressWarnings("deprecation")
public static DefaultHttpClient getClientThatAllowAnyHTTPS(ThreadSafeClientConnManager cm) {
    final TrustManager easyTrustManager = new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    final X509HostnameVerifier easyVerifier = new X509HostnameVerifier() {

        public boolean verify(String string, SSLSession ssls) {
            return true;
        }

        public void verify(String string, SSLSocket ssls) throws IOException {
        }

        public void verify(String string, String[] strings, String[] strings1) throws SSLException {
        }

        public void verify(String string, X509Certificate xc) throws SSLException {
        }
    };
    SSLContext ctx = null;
    try {
        ctx = SSLContext.getInstance("TLS");
        ctx.init(null, new TrustManager[] { easyTrustManager }, null);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (KeyManagementException e) {
        throw new RuntimeException(e);
    }
    final SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    ssf.setHostnameVerifier(easyVerifier);
    cm.getSchemeRegistry().register(new Scheme(HTTPS, ssf, HTTPS_PORT));
    return new DefaultHttpClient(cm);
}
Example 94
Project: deskcon-android-master  File: Connection.java View source code
public static SSLSocket createSSLSocket(Context context, String host, int port) throws UnknownHostException, IOException {
    // init SSL Context
    SSLContext sslcontext = null;
    try {
        sslcontext = initSSLContext(context);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // make secure Connection
    SSLSocketFactory factory = (SSLSocketFactory) sslcontext.getSocketFactory();
    SSLSocket sslsocket = (SSLSocket) factory.createSocket();
    sslsocket.setUseClientMode(true);
    sslsocket.connect(new InetSocketAddress(host, port), 500);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        sslsocket.setEnabledProtocols(new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" });
    } else {
        sslsocket.setEnabledProtocols(new String[] { "TLSv1" });
    }
    Log.d("Connection: ", "using Protocol " + sslsocket.getSession().getProtocol());
    Log.d("Connection: ", "Session valid  " + sslsocket.getSession().isValid());
    return sslsocket;
}
Example 95
Project: DroidBeard-master  File: TlsSocketFactory.java View source code
@Override
public Socket createSocket(Socket plainSocket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
    // Create and connect SSL socket, but don't do hostname/certificate verification yet
    SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
    // Setup custom trust manager if we are trusting all certificates
    if (mTrustAllCertificates) {
        TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        sslSocketFactory.setTrustManagers(new TrustManager[] { tm });
    }
    SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
    // Enable TLSv1.1/1.2 if available
    // (see https://github.com/rfc2822/davdroid/issues/229)
    ssl.setEnabledProtocols(ssl.getSupportedProtocols());
    SSLSession session = ssl.getSession();
    // Verify hostname and certificate if we aren't trusting all certificates
    if (!mTrustAllCertificates) {
        if (!hostnameVerifier.verify(host, session))
            throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
    }
    Log.i("droidbeard", "Established " + session.getProtocol() + " connection with " + session.getPeerHost() + " using " + session.getCipherSuite());
    return ssl;
}
Example 96
Project: ftpapi-master  File: ImplicitSSLControlConnection.java View source code
/**
	 * Connects to the specified remote host on the specified port number.
	 * 
	 * @param host
	 *            Host name or IP address of the remote host.
	 * @param port
	 *            Port number to connect to.
	 * @exception ConnectionException
	 *                If unable to connect to the specified host.
	 */
@Override
public void connect(String host, int port) throws ConnectionException, FTPException {
    try {
        SSLContext ctx = client.getSSLContext();
        SSLSocketFactory factory = ctx.getSocketFactory();
        socket = factory.createSocket(host, port);
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer = new PrintStream(socket.getOutputStream(), true);
        ((SSLSocket) socket).startHandshake();
    } catch (UnknownHostException exp) {
        throw new ConnectionException(exp.toString());
    } catch (NoRouteToHostException exp) {
        throw new ConnectionException(exp.toString());
    } catch (SocketException exp) {
        throw new ConnectionException(exp.toString());
    } catch (IOException exp) {
        throw new ConnectionException(exp.toString());
    } catch (Exception exp) {
        throw new ConnectionException(exp.toString());
    }
    try {
        socket.setSoTimeout(client.getTimeout());
    // socket.setKeepAlive(true);
    } catch (SocketException exp) {
        stderr("Could not set timeout for the socket. Original exception " + "below. \n" + exp.getMessage());
    }
    String reply = getReply();
    if (reply.charAt(0) == '5' || reply.charAt(0) == '4') {
        throw new FTPException(reply);
    }
    reply = executeCommand("PBSZ 0");
    if (reply.charAt(0) == '5' || reply.charAt(0) == '4') {
        throw new FTPException(reply);
    }
    reply = executeCommand("PROT " + (client.isDataChannelUnencrypted() ? "C" : "P"));
    if (reply.charAt(0) == '5' || reply.charAt(0) == '4') {
        throw new FTPException(reply);
    }
}
Example 97
Project: google-tv-remote-jb-master  File: PairingContext.java View source code
/**
   * Constructs a new instance from an {@link SSLSocket}.
   * 
   * @param   socket          the socket to use
   * @param   isServer        {@code true} if this endpoint is the server
   * @return  the new instance
   * @throws PoloException  if certificates could not be obtained
   * @throws IOException    if the socket's streams could not be obtained
   */
public static PairingContext fromSslSocket(SSLSocket socket, boolean isServer) throws PoloException, IOException {
    Certificate localCert = PoloUtil.getLocalCert(socket.getSession());
    Certificate peerCert = PoloUtil.getPeerCert(socket.getSession());
    InputStream input = socket.getInputStream();
    OutputStream output = socket.getOutputStream();
    return new PairingContext(localCert, peerCert, input, output, isServer);
}
Example 98
Project: haox-master  File: TestKeyMaterial.java View source code
private static void examineKeyStore(String dir, String fileName, String file2) throws Exception {
    String FILENAME = fileName.toUpperCase(Locale.ENGLISH);
    boolean hasMultiPassword = FILENAME.contains(".2PASS.");
    System.out.print("Testing KeyMaterial: " + dir + "/" + fileName);
    char[] pass1 = PASSWORD1;
    char[] pass2 = PASSWORD1;
    if (hasMultiPassword) {
        pass2 = PASSWORD2;
    }
    file2 = file2 != null ? dir + "/" + file2 : null;
    Date today = new Date();
    KeyMaterial km;
    try {
        km = new KeyMaterial(dir + "/" + fileName, file2, pass1, pass2);
    } catch (ProbablyBadPasswordException pbpe) {
        System.out.println("  WARN:  " + pbpe);
        return;
    }
    assertEquals("keymaterial-contains-1-alias", 1, km.getAliases().size());
    for (X509Certificate[] cert : (List<X509Certificate[]>) km.getAssociatedCertificateChains()) {
        for (X509Certificate c : cert) {
            assertTrue("certchain-valid-dates", c.getNotAfter().after(today));
        }
    }
    SSLServer server = new SSLServer();
    server.setKeyMaterial(km);
    ServerSocket ss = server.createServerSocket(0);
    int port = ss.getLocalPort();
    startServerThread(ss);
    Thread.sleep(1);
    SSLClient client = new SSLClient();
    client.setTrustMaterial(TrustMaterial.TRUST_ALL);
    client.setCheckHostname(false);
    SSLSocket s = (SSLSocket) client.createSocket("localhost", port);
    s.getSession().getPeerCertificates();
    InputStream in = s.getInputStream();
    Util.streamToBytes(in);
    in.close();
    // System.out.println(Certificates.toString((X509Certificate) certs[0]));
    s.close();
    System.out.println("\t SUCCESS! ");
}
Example 99
Project: hermesftp-master  File: ActiveModeSocketProvider.java View source code
private Socket createClientSocket() throws IOException {
    Socket dataSocket;
    Boolean dataProtection = (Boolean) ctx.getAttribute(FtpConstants.ATTR_DATA_PROT);
    boolean ssl = dataProtection != null && dataProtection;
    if (ssl) {
        SSLSocketFactory factory;
        try {
            factory = ctx.getOptions().getSslContext().getSocketFactory();
        } catch (FtpConfigException e) {
            throw new IOException("Setting up SSL failed.");
        }
        SSLSocket sslSocket = (SSLSocket) factory.createSocket(dataChannelInfo.getAddress(), dataChannelInfo.getPort());
        sslSocket.setUseClientMode(false);
        enableCipherSuites(sslSocket);
        dataSocket = sslSocket;
    } else {
        dataSocket = SocketFactory.getDefault().createSocket(dataChannelInfo.getAddress(), dataChannelInfo.getPort());
    }
    return dataSocket;
}
Example 100
Project: identityconnectors-master  File: RemoteFrameworkConnection.java View source code
private void init(RemoteFrameworkConnectionInfo connectionInfo) throws Exception {
    Socket socket = new Socket();
    socket.setSoTimeout(connectionInfo.getTimeout());
    socket.connect(new InetSocketAddress(connectionInfo.getHost(), connectionInfo.getPort()), connectionInfo.getTimeout());
    try {
        if (connectionInfo.getUseSSL()) {
            List<TrustManager> trustManagers = connectionInfo.getTrustManagers();
            TrustManager[] trustManagerArr = null;
            if (trustManagers.size() > 0) {
                //convert empty to null
                trustManagerArr = trustManagers.toArray(new TrustManager[trustManagers.size()]);
            }
            SSLSocketFactory factory;
            //the only way to get the default keystore is this way
            if (trustManagers == null) {
                factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            } else {
                SSLContext context = SSLContext.getInstance("TLS");
                context.init(null, trustManagerArr, null);
                factory = context.getSocketFactory();
            }
            socket = factory.createSocket(socket, connectionInfo.getHost(), connectionInfo.getPort(), true);
            ((SSLSocket) socket).startHandshake();
        }
    } catch (Exception e) {
        try {
            socket.close();
        } catch (Exception e2) {
        }
        throw e;
    }
    init(socket);
}
Example 101
Project: IPCPlayer-master  File: QSSLSocketFactory.java View source code
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);
    InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
    if ((localAddress != null) || (localPort > 0)) {
        if (localPort < 0) {
            localPort = 0;
        }
        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }
    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);
    return sslsock;
}