javax.net.ssl.SSLSession Java Examples

The following examples show how to use javax.net.ssl.SSLSession. 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: CertificateSniffingMitmManager.java    From CapturePacket with MIT License 6 votes vote down vote up
public SSLEngine clientSslEngineFor(HttpRequest httpRequest, SSLSession serverSslSession) {
    try {
        X509Certificate upstreamCert = getCertificateFromSession(serverSslSession);
        // TODO store the upstream cert by commonName to review it later

        // A reasons to not use the common name and the alternative names
        // from upstream certificate from serverSslSession to create the
        // dynamic certificate:
        //
        // It's not necessary. The host name is accepted by the browser.
        //
        String commonName = getCommonName(upstreamCert);

        SubjectAlternativeNameHolder san = new SubjectAlternativeNameHolder();

        san.addAll(upstreamCert.getSubjectAlternativeNames());

        LOG.debug("Subject Alternative Names: {}", san);
        return sslEngineSource.createCertForHost(commonName, san);

    } catch (Exception e) {
        throw new FakeCertificateException(
                "Creation dynamic certificate failed", e);
    }
}
 
Example #2
Source File: DefaultSslInfo.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Nullable
private static X509Certificate[] initCertificates(SSLSession session) {
	Certificate[] certificates;
	try {
		certificates = session.getPeerCertificates();
	}
	catch (Throwable ex) {
		return null;
	}

	List<X509Certificate> result = new ArrayList<>(certificates.length);
	for (Certificate certificate : certificates) {
		if (certificate instanceof X509Certificate) {
			result.add((X509Certificate) certificate);
		}
	}
	return (!result.isEmpty() ? result.toArray(new X509Certificate[0]) : null);
}
 
Example #3
Source File: SslUtil.java    From CapturePacket with MIT License 6 votes vote down vote up
/**
 * Returns the X509Certificate for the server this session is connected to. The certificate may be null.
 *
 * @param sslSession SSL session connected to upstream server
 * @return the X.509 certificate from the upstream server, or null if no certificate is available
 */
public static X509Certificate getServerCertificate(SSLSession sslSession) {
    Certificate[] peerCertificates;
    try {
        peerCertificates = sslSession.getPeerCertificates();
    } catch (SSLPeerUnverifiedException e) {
        peerCertificates = null;
    }

    if (peerCertificates != null && peerCertificates.length > 0) {
        Certificate peerCertificate = peerCertificates[0];
        if (peerCertificate != null && peerCertificate instanceof X509Certificate) {
            return (X509Certificate) peerCertificates[0];
        }
    }

    // no X.509 certificate was found for this server
    return null;
}
 
Example #4
Source File: DefaultSslInfo.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Nullable
private static String initSessionId(SSLSession session) {
	byte [] bytes = session.getId();
	if (bytes == null) {
		return null;
	}

	StringBuilder sb = new StringBuilder();
	for (byte b : bytes) {
		String digit = Integer.toHexString(b);
		if (digit.length() < 2) {
			sb.append('0');
		}
		if (digit.length() > 2) {
			digit = digit.substring(digit.length() - 2);
		}
		sb.append(digit);
	}
	return sb.toString();
}
 
Example #5
Source File: ProviderHostnameVerifierTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testHostnameVerifier() throws IOException {
    
    SSLSession session = Mockito.mock(SSLSession.class);
    Path path = Paths.get("src/test/resources/athenz.instanceid.pem");
    String pem = new String(Files.readAllBytes(path));
    X509Certificate cert = Crypto.loadX509Certificate(pem);
    
    Certificate[] certs = new Certificate[1];
    certs[0] = cert;
    Mockito.when(session.getPeerCertificates()).thenReturn(certs);
    
    ProviderHostnameVerifier verifier1 = new ProviderHostnameVerifier("athenz.production");
    assertTrue(verifier1.verify("athenz", session));
    
    ProviderHostnameVerifier verifier2 = new ProviderHostnameVerifier("athenz.production2");
    assertFalse(verifier2.verify("athenz", session));
}
 
Example #6
Source File: WebViewCacheWrapper.java    From YCWebView with Apache License 2.0 6 votes vote down vote up
/**
 * 创建okhttp,主要是用它进行缓存
 */
private void initHttpClient() {
    //设置缓存的位置,还有缓存的大小,默认是100M
    final Cache cache = new Cache(mCacheFile, mCacheSize);
    OkHttpClient.Builder builder = new OkHttpClient.Builder()
            .cache(cache)
            .connectTimeout(mConnectTimeout, TimeUnit.SECONDS)
            .readTimeout(mReadTimeout, TimeUnit.SECONDS)
            .addNetworkInterceptor(new HttpCacheInterceptor());
    if (mTrustAllHostname) {
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
    }
    if (mSSLSocketFactory != null && mX509TrustManager != null) {
        builder.sslSocketFactory(mSSLSocketFactory, mX509TrustManager);
    }
    if(mDns!=null){
        builder.dns(mDns);
    }
    mHttpClient = builder.build();
}
 
Example #7
Source File: MicronautServerHttpRequest.java    From micronaut-spring with Apache License 2.0 6 votes vote down vote up
@Nullable
private String initSessionId(SSLSession session) {
    byte [] bytes = session.getId();
    if (bytes == null) {
        return null;
    }

    StringBuilder sb = new StringBuilder();
    for (byte b : bytes) {
        String digit = Integer.toHexString(b);
        if (digit.length() < 2) {
            sb.append('0');
        }
        if (digit.length() > 2) {
            digit = digit.substring(digit.length() - 2);
        }
        sb.append(digit);
    }
    return sb.toString();
}
 
Example #8
Source File: SslUtil.java    From AndroidHttpCapture with MIT License 6 votes vote down vote up
/**
 * Returns the X509Certificate for the server this session is connected to. The certificate may be null.
 *
 * @param sslSession SSL session connected to upstream server
 * @return the X.509 certificate from the upstream server, or null if no certificate is available
 */
public static X509Certificate getServerCertificate(SSLSession sslSession) {
    Certificate[] peerCertificates;
    try {
        peerCertificates = sslSession.getPeerCertificates();
    } catch (SSLPeerUnverifiedException e) {
        peerCertificates = null;
    }

    if (peerCertificates != null && peerCertificates.length > 0) {
        Certificate peerCertificate = peerCertificates[0];
        if (peerCertificate != null && peerCertificate instanceof X509Certificate) {
            return (X509Certificate) peerCertificates[0];
        }
    }

    // no X.509 certificate was found for this server
    return null;
}
 
Example #9
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 #10
Source File: Application.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Named("cxfProducerEndpointRel")
@Produces
public CxfRsEndpoint createCxfProducerEndpointRel() {
    CxfRsEndpoint cxfProducerEndpoint = this.camelContext.getEndpoint("cxfrs:" + CXF_ENDPOINT_REL_BASE_URI, CxfRsEndpoint.class);
    cxfProducerEndpoint.setBeanId("cxfProducerEndpointRel");
    cxfProducerEndpoint.addResourceClass(GreetingsService.class);

    // Not for use in production
    HostnameVerifier hostnameVerifier = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    cxfProducerEndpoint.setHostnameVerifier(hostnameVerifier);

    return cxfProducerEndpoint;
}
 
Example #11
Source File: VertxClientCertificateLookup.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public X509Certificate[] getCertificateChain(HttpRequest httpRequest) {
    Instance<RoutingContext> instances = CDI.current().select(RoutingContext.class);

    if (instances.isResolvable()) {
        RoutingContext context = instances.get();

        try {
            SSLSession sslSession = context.request().sslSession();
            
            if (sslSession == null) {
                return null;
            }
            
            X509Certificate[] certificates = (X509Certificate[]) sslSession.getPeerCertificates();

            if (logger.isTraceEnabled() && certificates != null) {
                for (X509Certificate cert : certificates) {
                    logger.tracef("Certificate's SubjectDN => \"%s\"", cert.getSubjectDN().getName());
                }
            }

            return certificates;
        } catch (SSLPeerUnverifiedException ignore) {
            // client not authenticated
        }
    }

    return null;
}
 
Example #12
Source File: X509TrustManagerImpl.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
static List<SNIServerName> getRequestedServerNames(SSLEngine engine) {
    if (engine != null) {
        SSLSession session = engine.getHandshakeSession();

        if (session != null && (session instanceof ExtendedSSLSession)) {
            ExtendedSSLSession extSession = (ExtendedSSLSession)session;
            return extSession.getRequestedServerNames();
        }
    }

    return Collections.<SNIServerName>emptyList();
}
 
Example #13
Source File: ClientTlsChannel.java    From tls-channel with MIT License 5 votes vote down vote up
private ClientTlsChannel(
    ByteChannel underlying,
    SSLEngine engine,
    Consumer<SSLSession> sessionInitCallback,
    boolean runTasks,
    BufferAllocator plainBufAllocator,
    BufferAllocator encryptedBufAllocator,
    boolean releaseBuffers,
    boolean waitForCloseNotifyOnClose) {
  if (!engine.getUseClientMode())
    throw new IllegalArgumentException("SSLEngine must be in client mode");
  this.underlying = underlying;
  TrackingAllocator trackingPlainBufAllocator = new TrackingAllocator(plainBufAllocator);
  TrackingAllocator trackingEncryptedAllocator = new TrackingAllocator(encryptedBufAllocator);
  impl =
      new TlsChannelImpl(
          underlying,
          underlying,
          engine,
          Optional.empty(),
          sessionInitCallback,
          runTasks,
          trackingPlainBufAllocator,
          trackingEncryptedAllocator,
          releaseBuffers,
          waitForCloseNotifyOnClose);
}
 
Example #14
Source File: GridCommonAbstractTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override protected void beforeTest() throws Exception {
    // Disable SSL hostname verifier.
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override public boolean verify(String s, SSLSession sslSes) {
            return true;
        }
    });

    super.beforeTest();
}
 
Example #15
Source File: SSOAgentConfig.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private void doHostNameVerification(){
    if (!this.getEnableHostNameVerification()) {
        // Create empty HostnameVerifier
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }
}
 
Example #16
Source File: StartTlsResponseImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static Principal getPeerPrincipal(SSLSession session)
        throws SSLPeerUnverifiedException {
    Principal principal;
    try {
        principal = session.getPeerPrincipal();
    } catch (AbstractMethodError e) {
        // if the JSSE provider does not support it, return null, since
        // we need it only for Kerberos.
        principal = null;
    }
    return principal;
}
 
Example #17
Source File: CertificateSniffingMitmManager.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
private X509Certificate getCertificateFromSession(SSLSession sslSession)
        throws SSLPeerUnverifiedException {
    Certificate[] peerCerts = sslSession.getPeerCertificates();
    Certificate peerCert = peerCerts[0];
    if (peerCert instanceof X509Certificate) {
        return (X509Certificate) peerCert;
    }
    throw new IllegalStateException(
            "Required java.security.cert.X509Certificate, found: "
                    + peerCert);
}
 
Example #18
Source File: ProxyHandler.java    From AndServer with Apache License 2.0 5 votes vote down vote up
private Socket createSocket(HttpHost host) throws IOException {
    Socket socket = new Socket();
    socket.setSoTimeout(60 * 1000);
    socket.setReuseAddress(true);
    socket.setTcpNoDelay(true);
    socket.setKeepAlive(true);
    socket.setReceiveBufferSize(BUFFER);
    socket.setSendBufferSize(BUFFER);
    socket.setSoLinger(true, 0);

    String scheme = host.getSchemeName();
    String hostName = host.getHostName();
    int port = host.getPort();

    InetSocketAddress address = resolveAddress(scheme, hostName, port);
    socket.connect(address, 10 * 1000);

    if ("https".equalsIgnoreCase(scheme)) {
        SSLSocket sslSocket = (SSLSocket) mSocketFactory.createSocket(socket, hostName, port, true);
        try {
            sslSocket.startHandshake();
            final SSLSession session = sslSocket.getSession();
            if (session == null) {
                throw new SSLHandshakeException("SSL session not available.");
            }
        } catch (final IOException ex) {
            IOUtils.closeQuietly(sslSocket);
            throw ex;
        }
        return sslSocket;
    }
    return socket;
}
 
Example #19
Source File: StartTlsResponseImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static Principal getPeerPrincipal(SSLSession session)
        throws SSLPeerUnverifiedException {
    Principal principal;
    try {
        principal = session.getPeerPrincipal();
    } catch (AbstractMethodError e) {
        // if the JSSE provider does not support it, return null, since
        // we need it only for Kerberos.
        principal = null;
    }
    return principal;
}
 
Example #20
Source File: X509TrustManagerImpl.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
static void checkIdentity(SSLSession session,
        X509Certificate [] trustedChain,
        String algorithm,
        boolean checkClientTrusted) throws CertificateException {

    boolean identifiable = false;
    String peerHost = session.getPeerHost();
    if (!checkClientTrusted) {
        List<SNIServerName> sniNames = getRequestedServerNames(session);
        String sniHostName = getHostNameInSNI(sniNames);
        if (sniHostName != null) {
            try {
                checkIdentity(sniHostName,
                        trustedChain[0], algorithm);
                identifiable = true;
            } catch (CertificateException ce) {
                if (sniHostName.equalsIgnoreCase(peerHost)) {
                    throw ce;
                }

                // otherwisw, failover to check peer host
            }
        }
    }

    if (!identifiable) {
        checkIdentity(peerHost,
                trustedChain[0], algorithm);
    }
}
 
Example #21
Source File: X509TrustManagerImpl.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static List<SNIServerName> getRequestedServerNames(
        SSLSession session) {
    if (session != null && (session instanceof ExtendedSSLSession)) {
        return ((ExtendedSSLSession)session).getRequestedServerNames();
    }

    return Collections.<SNIServerName>emptyList();
}
 
Example #22
Source File: SSLSessionContextImpl.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
boolean isTimedout(SSLSession sess) {
    if (timeout == 0) {
        return false;
    }

    if ((sess != null) && ((sess.getCreationTime() + timeout * 1000L)
                                    <= (System.currentTimeMillis()))) {
        sess.invalidate();
        return true;
    }

    return false;
}
 
Example #23
Source File: X509TrustManagerImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
static List<SNIServerName> getRequestedServerNames(SSLEngine engine) {
    if (engine != null) {
        SSLSession session = engine.getHandshakeSession();

        if (session != null && (session instanceof ExtendedSSLSession)) {
            ExtendedSSLSession extSession = (ExtendedSSLSession)session;
            return extSession.getRequestedServerNames();
        }
    }

    return Collections.<SNIServerName>emptyList();
}
 
Example #24
Source File: ServerTlsChannel.java    From tls-channel with MIT License 5 votes vote down vote up
private ServerTlsChannel(
    ByteChannel underlying,
    SslContextStrategy internalSslContextFactory,
    Function<SSLContext, SSLEngine> engineFactory,
    Consumer<SSLSession> sessionInitCallback,
    boolean runTasks,
    BufferAllocator plainBufAllocator,
    BufferAllocator encryptedBufAllocator,
    boolean releaseBuffers,
    boolean waitForCloseConfirmation) {
  this.underlying = underlying;
  this.sslContextStrategy = internalSslContextFactory;
  this.engineFactory = engineFactory;
  this.sessionInitCallback = sessionInitCallback;
  this.runTasks = runTasks;
  this.plainBufAllocator = new TrackingAllocator(plainBufAllocator);
  this.encryptedBufAllocator = new TrackingAllocator(encryptedBufAllocator);
  this.releaseBuffers = releaseBuffers;
  this.waitForCloseConfirmation = waitForCloseConfirmation;
  inEncrypted =
      new BufferHolder(
          "inEncrypted",
          Optional.empty(),
          encryptedBufAllocator,
          TlsChannelImpl.buffersInitialSize,
          TlsChannelImpl.maxTlsPacketSize,
          false /* plainData */,
          releaseBuffers);
}
 
Example #25
Source File: ClientTlsChannel.java    From pgadba with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private ClientTlsChannel(
    ByteChannel underlying,
    SSLEngine engine,
    Consumer<SSLSession> sessionInitCallback,
    boolean runTasks,
    BufferAllocator plainBufAllocator,
    BufferAllocator encryptedBufAllocator,
    boolean releaseBuffers,
    boolean waitForCloseNotifyOnClose) {
  if (!engine.getUseClientMode()) {
    throw new IllegalArgumentException("SSLEngine must be in client mode");
  }
  this.underlying = underlying;
  TrackingAllocator trackingPlainBufAllocator = new TrackingAllocator(plainBufAllocator);
  TrackingAllocator trackingEncryptedAllocator = new TrackingAllocator(encryptedBufAllocator);
  impl = new TlsChannelImpl(underlying, underlying, engine, Optional.empty(), sessionInitCallback, runTasks,
      trackingPlainBufAllocator, trackingEncryptedAllocator, releaseBuffers, waitForCloseNotifyOnClose);
}
 
Example #26
Source File: X509TrustManagerImpl.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void checkIdentity(SSLSession session,
        X509Certificate cert,
        String algorithm,
        boolean isClient,
        List<SNIServerName> sniNames) throws CertificateException {

    boolean identifiable = false;
    String peerHost = session.getPeerHost();
    if (isClient) {
        String hostname = getHostNameInSNI(sniNames);
        if (hostname != null) {
            try {
                checkIdentity(hostname, cert, algorithm);
                identifiable = true;
            } catch (CertificateException ce) {
                if (hostname.equalsIgnoreCase(peerHost)) {
                    throw ce;
                }

                // otherwisw, failover to check peer host
            }
        }
    }

    if (!identifiable) {
        checkIdentity(peerHost, cert, algorithm);
    }
}
 
Example #27
Source File: OpenSslSessionContext.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
public SSLSession getSession(byte[] bytes) {
    if (bytes == null) {
        throw new NullPointerException("bytes");
    }
    return null;
}
 
Example #28
Source File: X509TrustManagerImpl.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
static void checkIdentity(SSLSession session,
        X509Certificate [] trustedChain,
        String algorithm,
        boolean checkClientTrusted) throws CertificateException {

    boolean identifiable = false;
    String peerHost = session.getPeerHost();
    if (!checkClientTrusted) {
        List<SNIServerName> sniNames = getRequestedServerNames(session);
        String sniHostName = getHostNameInSNI(sniNames);
        if (sniHostName != null) {
            try {
                checkIdentity(sniHostName,
                        trustedChain[0], algorithm);
                identifiable = true;
            } catch (CertificateException ce) {
                if (sniHostName.equalsIgnoreCase(peerHost)) {
                    throw ce;
                }

                // otherwisw, failover to check peer host
            }
        }
    }

    if (!identifiable) {
        checkIdentity(peerHost,
                trustedChain[0], algorithm);
    }
}
 
Example #29
Source File: SimpleHttpClientTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
private HostnameVerifier getFriendlyToAllHostnameVerifier() {
    final HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(final String hostname, final SSLSession session) { return true; }
    };
    return hv;
}
 
Example #30
Source File: SslInitializerTestUtils.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies tha the SSL channel is established as expected, and also sends a message to the server
 * and verifies if it is echoed back correctly.
 *
 * @param certs The certificate that the server should provide.
 * @return The SSL session in current channel, can be used for further validation.
 */
static SSLSession setUpSslChannel(Channel channel, X509Certificate... certs) throws Exception {
  SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
  // Wait till the handshake is complete.
  sslHandler.handshakeFuture().get();

  assertThat(channel.isActive()).isTrue();
  assertThat(sslHandler.handshakeFuture().isSuccess()).isTrue();
  assertThat(sslHandler.engine().getSession().isValid()).isTrue();
  assertThat(sslHandler.engine().getSession().getPeerCertificates())
      .asList()
      .containsExactlyElementsIn(certs);
  // Returns the SSL session for further assertion.
  return sslHandler.engine().getSession();
}