Java Code Examples for javax.net.ssl.SSLSocket#getSession()

The following examples show how to use javax.net.ssl.SSLSocket#getSession() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SSLCertificateSocketFactory.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Verify the hostname of the certificate used by the other end of a
 * connected socket.  You MUST call this if you did not supply a hostname
 * to {@link #createSocket()}.  It is harmless to call this method
 * redundantly if the hostname has already been verified.
 *
 * <p>Wildcard certificates are allowed to verify any matching hostname,
 * so "foo.bar.example.com" is verified if the peer has a certificate
 * for "*.example.com".
 *
 * @param socket An SSL socket which has been connected to a server
 * @param hostname The expected hostname of the remote server
 * @throws IOException if something goes wrong handshaking with the server
 * @throws SSLPeerUnverifiedException if the server cannot prove its identity
 *
 * @hide
 */
public static void verifyHostname(Socket socket, String hostname) throws IOException {
    if (!(socket instanceof SSLSocket)) {
        throw new IllegalArgumentException("Attempt to verify non-SSL socket");
    }

    if (!isSslCheckRelaxed()) {
        // The code at the start of OpenSSLSocketImpl.startHandshake()
        // ensures that the call is idempotent, so we can safely call it.
        SSLSocket ssl = (SSLSocket) socket;
        ssl.startHandshake();

        SSLSession session = ssl.getSession();
        if (session == null) {
            throw new SSLException("Cannot verify SSL socket without session");
        }
        if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(hostname, session)) {
            throw new SSLPeerUnverifiedException("Cannot verify hostname: " + hostname);
        }
    }
}
 
Example 2
Source File: SslBrokerServiceTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void makeSSLConnection(SSLContext context,
                               String enabledSuites[],
                               TransportConnector connector) throws Exception, UnknownHostException, SocketException {
   SSLSocket sslSocket = (SSLSocket) context.getSocketFactory().createSocket("localhost", connector.getUri().getPort());

   if (enabledSuites != null) {
      sslSocket.setEnabledCipherSuites(enabledSuites);
   }
   sslSocket.setSoTimeout(5000);

   SSLSession session = sslSocket.getSession();
   sslSocket.startHandshake();
   LOG.info("cyphersuite: " + session.getCipherSuite());
   LOG.info("peer port: " + session.getPeerPort());
   LOG.info("peer cert: " + session.getPeerCertificateChain()[0].toString());
}
 
Example 3
Source File: SocketChannelWrapperBar.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the secure cipher algorithm.
 */
@Override
public String secureProtocol()
{
  SSLSocket sslSocket = _sslSocket;
  
  if (sslSocket == null) {
    return super.secureProtocol();
  }
  
  SSLSession sslSession = sslSocket.getSession();
  
  if (sslSession != null) {
    return sslSession.getProtocol();
  }
  else {
    return null;
  }
}
 
Example 4
Source File: SocketWrapperBar.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the bits in the socket.
 */
@Override
public int cipherBits()
{
  if (! (_s instanceof SSLSocket))
    return super.cipherBits();
  
  SSLSocket sslSocket = (SSLSocket) _s;
  
  SSLSession sslSession = sslSocket.getSession();
  
  if (sslSession != null)
    return _sslKeySizes.get(sslSession.getCipherSuite());
  else
    return 0;
}
 
Example 5
Source File: TLSSNISocketFactory.java    From buddycloud-android with Apache License 2.0 6 votes vote down vote up
@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 6
Source File: SocketConnector.java    From nv-websocket-client with Apache License 2.0 6 votes vote down vote up
private void verifyHostname(SSLSocket socket, String hostname) throws HostnameUnverifiedException
{
    if (mVerifyHostname == false)
    {
        // Skip hostname verification.
        return;
    }

    // Hostname verifier.
    OkHostnameVerifier verifier = OkHostnameVerifier.INSTANCE;

    // The SSL session.
    SSLSession session = socket.getSession();

    // Verify the hostname.
    if (verifier.verify(hostname, session))
    {
        // Verified. No problem.
        return;
    }

    // The certificate of the peer does not match the expected hostname.
    throw new HostnameUnverifiedException(socket, hostname);
}
 
Example 7
Source File: RubySSLSocketFactory.java    From PixivforMuzei3 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Socket createSocket(Socket plainSocket, String host, int port, boolean autoClose) throws IOException
{
    InetAddress address = plainSocket.getInetAddress();
    Log.i("!", "Address: " + address.getHostAddress());
    if (autoClose)
    {
        plainSocket.close();
    }
    SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
    SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(address, port);
    ssl.setEnabledProtocols(ssl.getSupportedProtocols());
    SSLSession session = ssl.getSession();
    Log.i("!", "Protocol " + session.getProtocol() + " PeerHost " + session.getPeerHost() +
            " CipherSuite " + session.getCipherSuite());
    return ssl;
}
 
Example 8
Source File: TLSProtocolSocketFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verifies the peer's hostname using the configured {@link HostnameVerifier}.
 * 
 * @param socket the socket connected to the peer whose hostname is to be verified.
 * 
 * @throws SSLException if the hostname does not verify against the peer's certificate, 
 *          or if there is an error in performing the evaluation
 */
protected void verifyHostname(Socket socket) throws SSLException {
    if (hostnameVerifier == null) {
        return;
    }
    
    if (!(socket instanceof SSLSocket)) {
        return;
    }
    
    SSLSocket sslSocket = (SSLSocket) socket;
    
    try {
        SSLSession sslSession = sslSocket.getSession();
        String hostname = sslSession.getPeerHost();
        
        if (!hostnameVerifier.verify(hostname, sslSession)) {
            throw new SSLPeerUnverifiedException("SSL peer failed hostname validation for name: " + hostname);
        }
    } catch (SSLException e) {
        cleanUpFailedSocket(sslSocket);
        throw e;
    } catch (Throwable t) {
        // Make sure we close the socket on any kind of Exception, RuntimeException or Error.
        cleanUpFailedSocket(sslSocket);
        throw new SSLException("Error in hostname verification", t);
    }
}
 
Example 9
Source File: SSLSocketTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_SSLSocket_SNIHostName() throws Exception {
    TestSSLContext c = TestSSLContext.create();

    final SSLSocket client = (SSLSocket) c.clientContext.getSocketFactory().createSocket();
    SSLParameters clientParams = client.getSSLParameters();
    clientParams.setServerNames(Collections.singletonList(
            (SNIServerName) new SNIHostName("www.example.com")));
    client.setSSLParameters(clientParams);

    SSLParameters serverParams = c.serverSocket.getSSLParameters();
    serverParams.setSNIMatchers(Collections.singletonList(
            SNIHostName.createSNIMatcher("www\\.example\\.com")));
    c.serverSocket.setSSLParameters(serverParams);

    client.connect(new InetSocketAddress(c.host, c.port));
    final SSLSocket server = (SSLSocket) c.serverSocket.accept();

    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<Void> future = executor.submit(new Callable<Void>() {
        @Override public Void call() throws Exception {
            client.startHandshake();
            return null;
        }
    });
    executor.shutdown();
    server.startHandshake();

    SSLSession serverSession = server.getSession();
    assertTrue(serverSession instanceof ExtendedSSLSession);
    ExtendedSSLSession extendedServerSession = (ExtendedSSLSession) serverSession;
    List<SNIServerName> requestedNames = extendedServerSession.getRequestedServerNames();
    assertNotNull(requestedNames);
    assertEquals(1, requestedNames.size());
    SNIServerName serverName = requestedNames.get(0);
    assertEquals(StandardConstants.SNI_HOST_NAME, serverName.getType());
    assertTrue(serverName instanceof SNIHostName);
    SNIHostName serverHostName = (SNIHostName) serverName;
    assertEquals("www.example.com", serverHostName.getAsciiName());
}
 
Example 10
Source File: SSLSocketTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_SSLSocket_getSession() throws Exception {
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket ssl = (SSLSocket) sf.createSocket();
    SSLSession session = ssl.getSession();
    assertNotNull(session);
    assertFalse(session.isValid());
}
 
Example 11
Source File: ConfirmingHostnameVerifier.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void verify(String host, SSLSocket ssl) throws IOException {
  if (host == null) {
    throw new NullPointerException("host to verify is null");
  }

  SSLSession session = ssl.getSession();
  if (session == null) {
    // In our experience this only happens under IBM 1.4.x when
    // spurious (unrelated) certificates show up in the server'
    // chain.  Hopefully this will unearth the real problem:
    final InputStream in = ssl.getInputStream();
    in.available();
    // If ssl.getInputStream().available() didn't cause an
    // exception, maybe at least now the session is available?
    session = ssl.getSession();
    if (session == null) {
      // If it's still null, probably a startHandshake() will
      // unearth the real problem.
      ssl.startHandshake();

      // Okay, if we still haven't managed to cause an exception,
      // might as well go for the NPE.  Or maybe we're okay now?
      session = ssl.getSession();
    }
  }

  final Certificate[] certs = session.getPeerCertificates();
  final X509Certificate x509 = (X509Certificate)certs[0];
  verify(host, x509);
}
 
Example 12
Source File: Https.java    From PacketProxy with Apache License 2.0 5 votes vote down vote up
public static String getCommonName(InetSocketAddress addr) throws Exception {
	SSLSocketFactory ssf = HttpsURLConnection.getDefaultSSLSocketFactory();
    SSLSocket socket = (SSLSocket) ssf.createSocket(addr.getAddress(), addr.getPort());
    socket.startHandshake();
    SSLSession session = socket.getSession();
    X509Certificate[] servercerts = (X509Certificate[]) session.getPeerCertificates();

    Pattern pattern = Pattern.compile("CN=([^,]+)", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(servercerts[0].getSubjectDN().getName());
    if (matcher.find()) {
    	return matcher.group(1);
    }
    return "";
}
 
Example 13
Source File: JSSESupport.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
JSSESupport(SSLSocket sock){
    ssl=sock;
    session = sock.getSession();
    sock.addHandshakeCompletedListener(listener);
}
 
Example 14
Source File: AbstractVerifierDef.java    From steady with Apache License 2.0 4 votes vote down vote up
public final void verify(final String host, final SSLSocket ssl)
      throws IOException {
    if(host == null) {
        throw new NullPointerException("host to verify is null");
    }

    SSLSession session = ssl.getSession();
    if(session == null) {
        // In our experience this only happens under IBM 1.4.x when
        // spurious (unrelated) certificates show up in the server'
        // chain.  Hopefully this will unearth the real problem:
        final InputStream in = ssl.getInputStream();
        in.available();
        /*
          If you're looking at the 2 lines of code above because
          you're running into a problem, you probably have two
          options:

            #1.  Clean up the certificate chain that your server
                 is presenting (e.g. edit "/etc/apache2/server.crt"
                 or wherever it is your server's certificate chain
                 is defined).

                                       OR

            #2.   Upgrade to an IBM 1.5.x or greater JVM, or switch
                  to a non-IBM JVM.
        */

        // If ssl.getInputStream().available() didn't cause an
        // exception, maybe at least now the session is available?
        session = ssl.getSession();
        if(session == null) {
            // If it's still null, probably a startHandshake() will
            // unearth the real problem.
            ssl.startHandshake();

            // Okay, if we still haven't managed to cause an exception,
            // might as well go for the NPE.  Or maybe we're okay now?
            session = ssl.getSession();
        }
    }

    final Certificate[] certs = session.getPeerCertificates();
    final X509Certificate x509 = (X509Certificate) certs[0];
    verify(host, x509);
}
 
Example 15
Source File: JSSESupport.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
JSSESupport(SSLSocket sock){
    ssl=sock;
    session = sock.getSession();
    sock.addHandshakeCompletedListener(listener);
}
 
Example 16
Source File: SSLSessionFinalizeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
SBListener doClientSide() throws Exception {

        /*
         * Wait for server to get started.
         */
        while (!serverReady) {
            Thread.sleep(50);
        }

        SSLSocketFactory sslsf =
            (SSLSocketFactory) SSLSocketFactory.getDefault();

        try {
                SSLSocket sslSocket = (SSLSocket)
                    sslsf.createSocket("localhost", serverPort);
                InputStream sslIS = sslSocket.getInputStream();
                OutputStream sslOS = sslSocket.getOutputStream();

            sslOS.write(280);
            sslOS.flush();
            sslIS.read();

            sslOS.close();
            sslIS.close();

            SSLSession sslSession = sslSocket.getSession();
            System.out.printf(" sslSession: %s %n   %s%n", sslSession, sslSession.getClass());
            SBListener sbListener = new SBListener(sslSession);

            sslSession.putValue("x", sbListener);

            sslSession.invalidate();

            sslSocket.close();

            sslOS = null;
            sslIS = null;
            sslSession = null;
            sslSocket = null;
            Reference.reachabilityFence(sslOS);
            Reference.reachabilityFence(sslIS);
            Reference.reachabilityFence(sslSession);
            Reference.reachabilityFence(sslSocket);

            return sbListener;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
    }
 
Example 17
Source File: WebTlsSniSocketFactory.java    From YCWebView with Apache License 2.0 4 votes vote down vote up
@Override
public Socket createSocket(Socket plainSocket, String host, int port, boolean autoClose)
        throws IOException {
    String peerHost = this.conn.getRequestProperty("Host");
    if (peerHost == null){
        peerHost = host;
    }
    X5LogUtils.i("customized createSocket. host: " + peerHost);
    InetAddress address = plainSocket.getInetAddress();
    if (autoClose) {
        // we don't need the plainSocket
        plainSocket.close();
    }
    // create and connect SSL socket, but don't do hostname/certificate verification yet
    SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory)
            SSLCertificateSocketFactory.getDefault(0);
    SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(address, 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) {
        X5LogUtils.i("Setting SNI hostname");
        sslSocketFactory.setHostname(ssl, peerHost);
    } else {
        X5LogUtils.d("No documented SNI support on Android <4.2, trying with reflection");
        try {
            java.lang.reflect.Method setHostnameMethod =
                    ssl.getClass().getMethod("setHostname", String.class);
            setHostnameMethod.invoke(ssl, peerHost);
        } catch (Exception e) {
            X5LogUtils.e("SNI not useable", e);
        }
    }
    // verify hostname and certificate
    SSLSession session = ssl.getSession();
    if (!hostnameVerifier.verify(peerHost, session)){
        throw new SSLPeerUnverifiedException("Cannot verify hostname: " + peerHost);
    }
    X5LogUtils.i("Established " + session.getProtocol() + " connection with " +
            session.getPeerHost() + " using " + session.getCipherSuite());
    return ssl;
}
 
Example 18
Source File: J_AbstractVerifier_F.java    From steady with Apache License 2.0 4 votes vote down vote up
public final void verify(final String host, final SSLSocket ssl)
      throws IOException {
    if(host == null) {
        throw new NullPointerException("host to verify is null");
    }

    SSLSession session = ssl.getSession();
    if(session == null) {
        // In our experience this only happens under IBM 1.4.x when
        // spurious (unrelated) certificates show up in the server'
        // chain.  Hopefully this will unearth the real problem:
        final InputStream in = ssl.getInputStream();
        in.available();
        /*
          If you're looking at the 2 lines of code above because
          you're running into a problem, you probably have two
          options:

            #1.  Clean up the certificate chain that your server
                 is presenting (e.g. edit "/etc/apache2/server.crt"
                 or wherever it is your server's certificate chain
                 is defined).

                                       OR

            #2.   Upgrade to an IBM 1.5.x or greater JVM, or switch
                  to a non-IBM JVM.
        */

        // If ssl.getInputStream().available() didn't cause an
        // exception, maybe at least now the session is available?
        session = ssl.getSession();
        if(session == null) {
            // If it's still null, probably a startHandshake() will
            // unearth the real problem.
            ssl.startHandshake();

            // Okay, if we still haven't managed to cause an exception,
            // might as well go for the NPE.  Or maybe we're okay now?
            session = ssl.getSession();
        }
    }

    final Certificate[] certs = session.getPeerCertificates();
    final X509Certificate x509 = (X509Certificate) certs[0];
    verify(host, x509);
}
 
Example 19
Source File: SSLSocketHelper.java    From Pix-Art-Messenger with GNU General Public License v3.0 4 votes vote down vote up
public static void log(Account account, SSLSocket socket) {
    SSLSession session = socket.getSession();
    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": protocol=" + session.getProtocol() + " cipher=" + session.getCipherSuite());
}
 
Example 20
Source File: RecordedRequest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public RecordedRequest(String requestLine, List<String> headers, List<Integer> chunkSizes,
        int bodySize, byte[] body, int sequenceNumber, Socket socket) {
    this.requestLine = requestLine;
    this.headers = headers;
    this.chunkSizes = chunkSizes;
    this.bodySize = bodySize;
    this.body = body;
    this.sequenceNumber = sequenceNumber;

    if (socket instanceof SSLSocket) {
        SSLSocket sslSocket = (SSLSocket) socket;
        SSLSession session = sslSocket.getSession();
        sslProtocol = session.getProtocol();
        sslCipherSuite = session.getCipherSuite();
        sslLocalPrincipal = session.getLocalPrincipal();
        sslLocalCertificates = session.getLocalCertificates();
        Principal peerPrincipal = null;
        Certificate[] peerCertificates = null;
        try {
            peerPrincipal = session.getPeerPrincipal();
            peerCertificates = session.getPeerCertificates();
        } catch (SSLPeerUnverifiedException e) {
            // No-op: use nulls instead
        }
        sslPeerPrincipal = peerPrincipal;
        sslPeerCertificates = peerCertificates;
    } else {
        sslProtocol = null;
        sslCipherSuite = null;
        sslLocalPrincipal = null;
        sslLocalCertificates = null;
        sslPeerPrincipal = null;
        sslPeerCertificates = null;
    }

    if (requestLine != null) {
        int methodEnd = requestLine.indexOf(' ');
        int pathEnd = requestLine.indexOf(' ', methodEnd + 1);
        this.method = requestLine.substring(0, methodEnd);
        this.path = requestLine.substring(methodEnd + 1, pathEnd);
    } else {
        this.method = null;
        this.path = null;
    }
}