Search in sources :

Example 91 with SSLSession

use of javax.net.ssl.SSLSession in project camel by apache.

the class NettySSLTest method testSSLInOutWithNettyConsumer.

@Test
public void testSSLInOutWithNettyConsumer() throws Exception {
    // ibm jdks dont have sun security algorithms
    if (isJavaVendor("ibm")) {
        return;
    }
    context.addRoutes(new RouteBuilder() {

        public void configure() {
            // needClientAuth=true so we can get the client certificate details
            from("netty:tcp://localhost:{{port}}?sync=true&ssl=true&passphrase=changeit&keyStoreFile=#ksf&trustStoreFile=#tsf&needClientAuth=true").process(new Processor() {

                public void process(Exchange exchange) throws Exception {
                    SSLSession session = exchange.getIn().getHeader(NettyConstants.NETTY_SSL_SESSION, SSLSession.class);
                    if (session != null) {
                        javax.security.cert.X509Certificate cert = session.getPeerCertificateChain()[0];
                        Principal principal = cert.getSubjectDN();
                        log.info("Client Cert SubjectDN: {}", principal.getName());
                        exchange.getOut().setBody("When You Go Home, Tell Them Of Us And Say, For Your Tomorrow, We Gave Our Today.");
                    } else {
                        exchange.getOut().setBody("Cannot start conversion without SSLSession");
                    }
                }
            });
        }
    });
    context.start();
    String response = template.requestBody("netty:tcp://localhost:{{port}}?sync=true&ssl=true&passphrase=changeit&keyStoreFile=#ksf&trustStoreFile=#tsf", "Epitaph in Kohima, India marking the WWII Battle of Kohima and Imphal, Burma Campaign - Attributed to John Maxwell Edmonds", String.class);
    assertEquals("When You Go Home, Tell Them Of Us And Say, For Your Tomorrow, We Gave Our Today.", response);
}
Also used : Exchange(org.apache.camel.Exchange) Processor(org.apache.camel.Processor) RouteBuilder(org.apache.camel.builder.RouteBuilder) SSLSession(javax.net.ssl.SSLSession) Principal(java.security.Principal) Test(org.junit.Test)

Example 92 with SSLSession

use of javax.net.ssl.SSLSession in project camel by apache.

the class NettyEndpoint method getSSLSession.

protected SSLSession getSSLSession(ChannelHandlerContext ctx) {
    final SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
    SSLSession sslSession = null;
    if (sslHandler != null) {
        sslSession = sslHandler.engine().getSession();
    }
    return sslSession;
}
Also used : SSLSession(javax.net.ssl.SSLSession) SslHandler(io.netty.handler.ssl.SslHandler)

Example 93 with SSLSession

use of javax.net.ssl.SSLSession in project jersey by jersey.

the class HelloWorldTest method testConnectionClosingOnExceptionsForErrorResponses.

/**
     * JERSEY-2157 reproducer.
     * <p>
     * The test ensures that entities of the error responses which cause
     * WebApplicationException being thrown by a JAX-RS client are buffered
     * and that the underlying input connections are automatically released
     * in such case.
     */
@Test
public void testConnectionClosingOnExceptionsForErrorResponses() {
    final BasicClientConnectionManager cm = new BasicClientConnectionManager();
    final AtomicInteger connectionCounter = new AtomicInteger(0);
    final ClientConfig config = new ClientConfig().property(ApacheClientProperties.CONNECTION_MANAGER, new ClientConnectionManager() {

        @Override
        public SchemeRegistry getSchemeRegistry() {
            return cm.getSchemeRegistry();
        }

        @Override
        public ClientConnectionRequest requestConnection(final HttpRoute route, final Object state) {
            connectionCounter.incrementAndGet();
            final ClientConnectionRequest wrappedRequest = cm.requestConnection(route, state);
            /**
                         * To explain the following long piece of code:
                         *
                         * All the code does is to just create a wrapper implementations
                         * for the AHC connection management interfaces.
                         *
                         * The only really important piece of code is the
                         * {@link org.apache.http.conn.ManagedClientConnection#releaseConnection()} implementation,
                         * where the connectionCounter is decremented when a managed connection instance
                         * is released by AHC runtime. In our test, this is expected to happen
                         * as soon as the exception is created for an error response
                         * (as the error response entity gets buffered in
                         * {@link org.glassfish.jersey.client.JerseyInvocation#convertToException(javax.ws.rs.core.Response)}).
                         */
            return new ClientConnectionRequest() {

                @Override
                public ManagedClientConnection getConnection(long timeout, TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException {
                    final ManagedClientConnection wrappedConnection = wrappedRequest.getConnection(timeout, tunit);
                    return new ManagedClientConnection() {

                        @Override
                        public boolean isSecure() {
                            return wrappedConnection.isSecure();
                        }

                        @Override
                        public HttpRoute getRoute() {
                            return wrappedConnection.getRoute();
                        }

                        @Override
                        public SSLSession getSSLSession() {
                            return wrappedConnection.getSSLSession();
                        }

                        @Override
                        public void open(HttpRoute route, HttpContext context, HttpParams params) throws IOException {
                            wrappedConnection.open(route, context, params);
                        }

                        @Override
                        public void tunnelTarget(boolean secure, HttpParams params) throws IOException {
                            wrappedConnection.tunnelTarget(secure, params);
                        }

                        @Override
                        public void tunnelProxy(HttpHost next, boolean secure, HttpParams params) throws IOException {
                            wrappedConnection.tunnelProxy(next, secure, params);
                        }

                        @Override
                        public void layerProtocol(HttpContext context, HttpParams params) throws IOException {
                            wrappedConnection.layerProtocol(context, params);
                        }

                        @Override
                        public void markReusable() {
                            wrappedConnection.markReusable();
                        }

                        @Override
                        public void unmarkReusable() {
                            wrappedConnection.unmarkReusable();
                        }

                        @Override
                        public boolean isMarkedReusable() {
                            return wrappedConnection.isMarkedReusable();
                        }

                        @Override
                        public void setState(Object state) {
                            wrappedConnection.setState(state);
                        }

                        @Override
                        public Object getState() {
                            return wrappedConnection.getState();
                        }

                        @Override
                        public void setIdleDuration(long duration, TimeUnit unit) {
                            wrappedConnection.setIdleDuration(duration, unit);
                        }

                        @Override
                        public boolean isResponseAvailable(int timeout) throws IOException {
                            return wrappedConnection.isResponseAvailable(timeout);
                        }

                        @Override
                        public void sendRequestHeader(HttpRequest request) throws HttpException, IOException {
                            wrappedConnection.sendRequestHeader(request);
                        }

                        @Override
                        public void sendRequestEntity(HttpEntityEnclosingRequest request) throws HttpException, IOException {
                            wrappedConnection.sendRequestEntity(request);
                        }

                        @Override
                        public HttpResponse receiveResponseHeader() throws HttpException, IOException {
                            return wrappedConnection.receiveResponseHeader();
                        }

                        @Override
                        public void receiveResponseEntity(HttpResponse response) throws HttpException, IOException {
                            wrappedConnection.receiveResponseEntity(response);
                        }

                        @Override
                        public void flush() throws IOException {
                            wrappedConnection.flush();
                        }

                        @Override
                        public void close() throws IOException {
                            wrappedConnection.close();
                        }

                        @Override
                        public boolean isOpen() {
                            return wrappedConnection.isOpen();
                        }

                        @Override
                        public boolean isStale() {
                            return wrappedConnection.isStale();
                        }

                        @Override
                        public void setSocketTimeout(int timeout) {
                            wrappedConnection.setSocketTimeout(timeout);
                        }

                        @Override
                        public int getSocketTimeout() {
                            return wrappedConnection.getSocketTimeout();
                        }

                        @Override
                        public void shutdown() throws IOException {
                            wrappedConnection.shutdown();
                        }

                        @Override
                        public HttpConnectionMetrics getMetrics() {
                            return wrappedConnection.getMetrics();
                        }

                        @Override
                        public InetAddress getLocalAddress() {
                            return wrappedConnection.getLocalAddress();
                        }

                        @Override
                        public int getLocalPort() {
                            return wrappedConnection.getLocalPort();
                        }

                        @Override
                        public InetAddress getRemoteAddress() {
                            return wrappedConnection.getRemoteAddress();
                        }

                        @Override
                        public int getRemotePort() {
                            return wrappedConnection.getRemotePort();
                        }

                        @Override
                        public void releaseConnection() throws IOException {
                            connectionCounter.decrementAndGet();
                            wrappedConnection.releaseConnection();
                        }

                        @Override
                        public void abortConnection() throws IOException {
                            wrappedConnection.abortConnection();
                        }

                        @Override
                        public String getId() {
                            return wrappedConnection.getId();
                        }

                        @Override
                        public void bind(Socket socket) throws IOException {
                            wrappedConnection.bind(socket);
                        }

                        @Override
                        public Socket getSocket() {
                            return wrappedConnection.getSocket();
                        }
                    };
                }

                @Override
                public void abortRequest() {
                    wrappedRequest.abortRequest();
                }
            };
        }

        @Override
        public void releaseConnection(ManagedClientConnection conn, long keepalive, TimeUnit tunit) {
            cm.releaseConnection(conn, keepalive, tunit);
        }

        @Override
        public void closeExpiredConnections() {
            cm.closeExpiredConnections();
        }

        @Override
        public void closeIdleConnections(long idletime, TimeUnit tunit) {
            cm.closeIdleConnections(idletime, tunit);
        }

        @Override
        public void shutdown() {
            cm.shutdown();
        }
    });
    config.connectorProvider(new ApacheConnectorProvider());
    final Client client = ClientBuilder.newClient(config);
    final WebTarget rootTarget = client.target(getBaseUri()).path(ROOT_PATH);
    // Test that connection is getting closed properly for error responses.
    try {
        final String response = rootTarget.path("error").request().get(String.class);
        fail("Exception expected. Received: " + response);
    } catch (InternalServerErrorException isee) {
    // do nothing - connection should be closed properly by now
    }
    // Fail if the previous connection has not been closed automatically.
    assertEquals(0, connectionCounter.get());
    try {
        final String response = rootTarget.path("error2").request().get(String.class);
        fail("Exception expected. Received: " + response);
    } catch (InternalServerErrorException isee) {
        assertEquals("Received unexpected data.", "Error2.", isee.getResponse().readEntity(String.class));
        // Test buffering:
        // second read would fail if entity was not buffered
        assertEquals("Unexpected data in the entity buffer.", "Error2.", isee.getResponse().readEntity(String.class));
    }
    assertEquals(0, connectionCounter.get());
}
Also used : ClientConnectionRequest(org.apache.http.conn.ClientConnectionRequest) ConnectionPoolTimeoutException(org.apache.http.conn.ConnectionPoolTimeoutException) HttpConnectionMetrics(org.apache.http.HttpConnectionMetrics) HttpHost(org.apache.http.HttpHost) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) TimeUnit(java.util.concurrent.TimeUnit) HttpException(org.apache.http.HttpException) ClientConfig(org.glassfish.jersey.client.ClientConfig) Client(javax.ws.rs.client.Client) HttpRequest(org.apache.http.HttpRequest) ManagedClientConnection(org.apache.http.conn.ManagedClientConnection) SSLSession(javax.net.ssl.SSLSession) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) HttpRoute(org.apache.http.conn.routing.HttpRoute) HttpParams(org.apache.http.params.HttpParams) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) WebTarget(javax.ws.rs.client.WebTarget) InetAddress(java.net.InetAddress) Socket(java.net.Socket) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 94 with SSLSession

use of javax.net.ssl.SSLSession in project jersey by jersey.

the class SslFilterTest method testCustomHostameVerificationPass.

@Test
public void testCustomHostameVerificationPass() throws Throwable {
    CountDownLatch latch = new CountDownLatch(1);
    SslEchoServer server = new SslEchoServer();
    try {
        server.start();
        HostnameVerifier verifier = new HostnameVerifier() {

            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
        openClientSocket("127.0.0.1", ByteBuffer.allocate(0), latch, verifier);
    } finally {
        server.stop();
    }
}
Also used : SSLSession(javax.net.ssl.SSLSession) CountDownLatch(java.util.concurrent.CountDownLatch) HostnameVerifier(javax.net.ssl.HostnameVerifier) Test(org.junit.Test)

Example 95 with SSLSession

use of javax.net.ssl.SSLSession in project apjp by jvansteirteghem.

the class HTTPRequest method open.

public void open() throws HTTPRequestException {
    try {
        url = new URL(APJP.APJP_REMOTE_HTTP_SERVER_REQUEST_URL[i]);
        Proxy proxy = Proxy.NO_PROXY;
        if (url.getProtocol().equalsIgnoreCase("HTTP") == true) {
            if (APJP.APJP_HTTP_PROXY_SERVER_ADDRESS.equalsIgnoreCase("") == false) {
                proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(APJP.APJP_HTTP_PROXY_SERVER_ADDRESS, APJP.APJP_HTTP_PROXY_SERVER_PORT));
            }
        } else {
            if (url.getProtocol().equalsIgnoreCase("HTTPS") == true) {
                if (APJP.APJP_HTTPS_PROXY_SERVER_ADDRESS.equalsIgnoreCase("") == false) {
                    proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(APJP.APJP_HTTPS_PROXY_SERVER_ADDRESS, APJP.APJP_HTTPS_PROXY_SERVER_PORT));
                }
            }
        }
        urlConnection = url.openConnection(proxy);
        if (urlConnection instanceof HttpsURLConnection) {
            ((HttpsURLConnection) urlConnection).setHostnameVerifier(new HostnameVerifier() {

                public boolean verify(String hostname, SSLSession sslSession) {
                    String value1 = APJP.APJP_REMOTE_HTTP_SERVER_REQUEST_URL[i];
                    String[] values1 = value1.split("/", -1);
                    String value2 = values1[2];
                    String[] values2 = value2.split(":");
                    String value3 = values2[0];
                    if (value3.equalsIgnoreCase(hostname)) {
                        return true;
                    } else {
                        return false;
                    }
                }
            });
        }
        if (url.getProtocol().equalsIgnoreCase("HTTP") == true) {
            if (APJP.APJP_HTTP_PROXY_SERVER_ADDRESS.equalsIgnoreCase("") == false && APJP.APJP_HTTP_PROXY_SERVER_USERNAME.equalsIgnoreCase("") == false) {
                urlConnection.setRequestProperty("Proxy-Authorization", "Basic " + new String(BASE64.encode((APJP.APJP_HTTP_PROXY_SERVER_USERNAME + ":" + APJP.APJP_HTTP_PROXY_SERVER_PASSWORD).getBytes())));
            }
        } else {
            if (url.getProtocol().equalsIgnoreCase("HTTPS") == true) {
                if (APJP.APJP_HTTPS_PROXY_SERVER_ADDRESS.equalsIgnoreCase("") == false && APJP.APJP_HTTPS_PROXY_SERVER_USERNAME.equalsIgnoreCase("") == false) {
                    urlConnection.setRequestProperty("Proxy-Authorization", "Basic " + new String(BASE64.encode((APJP.APJP_HTTPS_PROXY_SERVER_USERNAME + ":" + APJP.APJP_HTTPS_PROXY_SERVER_PASSWORD).getBytes())));
                }
            }
        }
        for (int j = 0; j < APJP.APJP_REMOTE_HTTP_SERVER_REQUEST_PROPERTY_KEY[i].length; j = j + 1) {
            if (APJP.APJP_REMOTE_HTTP_SERVER_REQUEST_PROPERTY_KEY[i][j].equalsIgnoreCase("") == false) {
                urlConnection.setRequestProperty(APJP.APJP_REMOTE_HTTP_SERVER_REQUEST_PROPERTY_KEY[i][j], APJP.APJP_REMOTE_HTTP_SERVER_REQUEST_PROPERTY_VALUE[i][j]);
            }
        }
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.connect();
    } catch (Exception e) {
        throw new HTTPRequestException("HTTP_REQUEST/OPEN", e);
    }
}
Also used : Proxy(java.net.Proxy) InetSocketAddress(java.net.InetSocketAddress) SSLSession(javax.net.ssl.SSLSession) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) HostnameVerifier(javax.net.ssl.HostnameVerifier)

Aggregations

SSLSession (javax.net.ssl.SSLSession)187 HostnameVerifier (javax.net.ssl.HostnameVerifier)50 SSLSocket (javax.net.ssl.SSLSocket)34 X509Certificate (java.security.cert.X509Certificate)32 IOException (java.io.IOException)31 SSLContext (javax.net.ssl.SSLContext)30 Test (org.junit.Test)29 CertificateException (java.security.cert.CertificateException)27 Certificate (java.security.cert.Certificate)20 SSLException (javax.net.ssl.SSLException)17 X509TrustManager (javax.net.ssl.X509TrustManager)16 URL (java.net.URL)14 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)14 SSLPeerUnverifiedException (javax.net.ssl.SSLPeerUnverifiedException)14 TrustManager (javax.net.ssl.TrustManager)14 SecureRandom (java.security.SecureRandom)13 FakeSSLSession (okhttp3.FakeSSLSession)13 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)12 InputStream (java.io.InputStream)11 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)11