Search in sources :

Example 1 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project vert.x by eclipse.

the class NetTest method testTLS.

void testTLS(boolean clientCert, boolean clientTrust, boolean serverCert, boolean serverTrust, boolean requireClientAuth, boolean clientTrustAll, boolean shouldPass, boolean startTLS, String[] enabledCipherSuites, String[] enabledSecureTransportProtocols) throws Exception {
    server.close();
    NetServerOptions options = new NetServerOptions();
    if (!startTLS) {
        options.setSsl(true);
    }
    if (serverTrust) {
        options.setTrustStoreOptions(new JksOptions().setPath("tls/server-truststore.jks").setPassword("wibble"));
    }
    if (serverCert) {
        options.setKeyStoreOptions(new JksOptions().setPath("tls/server-keystore.jks").setPassword("wibble"));
    }
    if (requireClientAuth) {
        options.setClientAuth(ClientAuth.REQUIRED);
    }
    for (String suite : enabledCipherSuites) {
        options.addEnabledCipherSuite(suite);
    }
    for (String protocol : enabledSecureTransportProtocols) {
        options.addEnabledSecureTransportProtocol(protocol);
    }
    Consumer<NetSocket> certificateChainChecker = socket -> {
        try {
            X509Certificate[] certs = socket.peerCertificateChain();
            if (clientCert) {
                assertNotNull(certs);
                assertEquals(1, certs.length);
            } else {
                assertNull(certs);
            }
        } catch (SSLPeerUnverifiedException e) {
            assertTrue(clientTrust || clientTrustAll);
        }
    };
    options.setPort(4043);
    server = vertx.createNetServer(options);
    Handler<NetSocket> serverHandler = socket -> {
        if (socket.isSsl()) {
            certificateChainChecker.accept(socket);
        }
        AtomicBoolean upgradedServer = new AtomicBoolean();
        AtomicInteger upgradedServerCount = new AtomicInteger();
        socket.handler(buff -> {
            socket.write(buff);
            if (startTLS) {
                if (upgradedServer.compareAndSet(false, true)) {
                    assertFalse(socket.isSsl());
                    socket.upgradeToSsl(v -> {
                        certificateChainChecker.accept(socket);
                        upgradedServerCount.incrementAndGet();
                        assertTrue(socket.isSsl());
                    });
                } else {
                    assertTrue(socket.isSsl());
                    assertEquals(1, upgradedServerCount.get());
                }
            } else {
                assertTrue(socket.isSsl());
            }
        });
    };
    server.connectHandler(serverHandler).listen(ar -> {
        client.close();
        NetClientOptions clientOptions = new NetClientOptions();
        if (!startTLS) {
            clientOptions.setSsl(true);
        }
        if (clientTrustAll) {
            clientOptions.setTrustAll(true);
        }
        if (clientTrust) {
            clientOptions.setTrustStoreOptions(new JksOptions().setPath("tls/client-truststore.jks").setPassword("wibble"));
        }
        if (clientCert) {
            clientOptions.setKeyStoreOptions(new JksOptions().setPath("tls/client-keystore.jks").setPassword("wibble"));
        }
        for (String suite : enabledCipherSuites) {
            clientOptions.addEnabledCipherSuite(suite);
        }
        for (String protocol : enabledSecureTransportProtocols) {
            clientOptions.addEnabledSecureTransportProtocol(protocol);
        }
        client = vertx.createNetClient(clientOptions);
        client.connect(4043, "localhost", ar2 -> {
            if (ar2.succeeded()) {
                if (!shouldPass) {
                    fail("Should not connect");
                    return;
                }
                final int numChunks = 100;
                final int chunkSize = 100;
                final List<Buffer> toSend = new ArrayList<>();
                final Buffer expected = Buffer.buffer();
                for (int i = 0; i < numChunks; i++) {
                    Buffer chunk = TestUtils.randomBuffer(chunkSize);
                    toSend.add(chunk);
                    expected.appendBuffer(chunk);
                }
                final Buffer received = Buffer.buffer();
                final NetSocket socket = ar2.result();
                final AtomicBoolean upgradedClient = new AtomicBoolean();
                socket.handler(buffer -> {
                    received.appendBuffer(buffer);
                    if (received.length() == expected.length()) {
                        assertEquals(expected, received);
                        testComplete();
                    }
                    if (startTLS && !upgradedClient.get()) {
                        upgradedClient.set(true);
                        assertFalse(socket.isSsl());
                        socket.upgradeToSsl(v -> {
                            assertTrue(socket.isSsl());
                            for (int i = 1; i < numChunks; i++) {
                                socket.write(toSend.get(i));
                            }
                        });
                    } else {
                        assertTrue(socket.isSsl());
                    }
                });
                int numToSend = startTLS ? 1 : numChunks;
                for (int i = 0; i < numToSend; i++) {
                    socket.write(toSend.get(i));
                }
            } else {
                if (shouldPass) {
                    fail("Should not fail to connect");
                } else {
                    testComplete();
                }
            }
        });
    });
    await();
}
Also used : java.util(java.util) io.vertx.core(io.vertx.core) io.vertx.core.impl(io.vertx.core.impl) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cert(io.vertx.test.core.tls.Cert) TestUtils.assertNullPointerException(io.vertx.test.core.TestUtils.assertNullPointerException) AtomicReference(java.util.concurrent.atomic.AtomicReference) LoggerFactory(io.vertx.core.logging.LoggerFactory) InetAddress(java.net.InetAddress) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ReadStream(io.vertx.core.streams.ReadStream) OutputStreamWriter(java.io.OutputStreamWriter) JsonObject(io.vertx.core.json.JsonObject) Assume(org.junit.Assume) Logger(io.vertx.core.logging.Logger) TestLoggerFactory(io.vertx.test.netty.TestLoggerFactory) BufferedWriter(java.io.BufferedWriter) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Message(io.vertx.core.eventbus.Message) FileOutputStream(java.io.FileOutputStream) Test(org.junit.Test) X509Certificate(javax.security.cert.X509Certificate) io.vertx.core.net(io.vertx.core.net) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) JsonArray(io.vertx.core.json.JsonArray) CountDownLatch(java.util.concurrent.CountDownLatch) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) ClientAuth(io.vertx.core.http.ClientAuth) InternalLoggerFactory(io.netty.util.internal.logging.InternalLoggerFactory) MessageConsumer(io.vertx.core.eventbus.MessageConsumer) SocketAddressImpl(io.vertx.core.net.impl.SocketAddressImpl) TemporaryFolder(org.junit.rules.TemporaryFolder) Trust(io.vertx.test.core.tls.Trust) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) TestUtils.assertIllegalArgumentException(io.vertx.test.core.TestUtils.assertIllegalArgumentException) Buffer(io.vertx.core.buffer.Buffer) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 2 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project jetty.project by eclipse.

the class SslContextFactory method getCertChain.

public static X509Certificate[] getCertChain(SSLSession sslSession) {
    try {
        Certificate[] javaxCerts = sslSession.getPeerCertificates();
        if (javaxCerts == null || javaxCerts.length == 0)
            return null;
        int length = javaxCerts.length;
        X509Certificate[] javaCerts = new X509Certificate[length];
        java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509");
        for (int i = 0; i < length; i++) {
            byte[] bytes = javaxCerts[i].getEncoded();
            ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
            javaCerts[i] = (X509Certificate) cf.generateCertificate(stream);
        }
        return javaCerts;
    } catch (SSLPeerUnverifiedException pue) {
        return null;
    } catch (Exception e) {
        LOG.warn(Log.EXCEPTION, e);
        return null;
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) X509Certificate(java.security.cert.X509Certificate) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 3 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project android_frameworks_base by ParanoidAndroid.

the class SSLCertificateSocketFactory method verifyHostname.

/**
     * 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);
        }
    }
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) SSLSession(javax.net.ssl.SSLSession) SSLException(javax.net.ssl.SSLException)

Example 4 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project azure-sdk-for-java by Azure.

the class HostnameSslTests method canBindHostnameAndSsl.

@Test
@Ignore("Need a domain and a certificate")
public void canBindHostnameAndSsl() throws Exception {
    // hostname binding
    appServiceManager.webApps().define(WEBAPP_NAME).withRegion(Region.US_WEST).withNewResourceGroup(RG_NAME).withNewWindowsPlan(PricingTier.BASIC_B1).defineHostnameBinding().withAzureManagedDomain(domain).withSubDomain(WEBAPP_NAME).withDnsRecordType(CustomHostNameDnsRecordType.CNAME).attach().create();
    WebApp webApp = appServiceManager.webApps().getByResourceGroup(RG_NAME, WEBAPP_NAME);
    Assert.assertNotNull(webApp);
    if (!IS_MOCKED) {
        Response response = curl("http://" + WEBAPP_NAME + "." + DOMAIN);
        Assert.assertEquals(200, response.code());
        Assert.assertNotNull(response.body().string());
    }
    // hostname binding shortcut
    webApp.update().withManagedHostnameBindings(domain, WEBAPP_NAME + "-1", WEBAPP_NAME + "-2").apply();
    if (!IS_MOCKED) {
        Response response = curl("http://" + WEBAPP_NAME + "-1." + DOMAIN);
        Assert.assertEquals(200, response.code());
        Assert.assertNotNull(response.body().string());
        response = curl("http://" + WEBAPP_NAME + "-2." + DOMAIN);
        Assert.assertEquals(200, response.code());
        Assert.assertNotNull(response.body().string());
    }
    // SSL binding
    webApp.update().defineSslBinding().forHostname(WEBAPP_NAME + "." + DOMAIN).withExistingAppServiceCertificateOrder(certificateOrder).withSniBasedSsl().attach().apply();
    if (!IS_MOCKED) {
        Response response = null;
        int retryCount = 3;
        while (response == null && retryCount > 0) {
            try {
                response = curl("https://" + WEBAPP_NAME + "." + DOMAIN);
            } catch (SSLPeerUnverifiedException e) {
                retryCount--;
                Thread.sleep(5000);
            }
        }
        if (retryCount == 0) {
            fail();
        }
        Assert.assertEquals(200, response.code());
        Assert.assertNotNull(response.body().string());
    }
}
Also used : Response(okhttp3.Response) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 5 with SSLPeerUnverifiedException

use of javax.net.ssl.SSLPeerUnverifiedException in project wildfly by wildfly.

the class RemotingLoginModule method login.

@SuppressWarnings("unchecked")
@Override
public boolean login() throws LoginException {
    if (super.login() == true) {
        log.debug("super.login()==true");
        return true;
    }
    Object credential = getCredential();
    if (credential instanceof RemotingConnectionCredential) {
        Connection con = ((RemotingConnectionCredential) credential).getConnection();
        Principal up = null;
        SecurityIdentity localIdentity = con.getLocalIdentity();
        if (localIdentity != null) {
            up = new RealmUser(localIdentity.getPrincipal().getName());
        }
        // If we found a principal from the connection then authentication succeeded.
        if (up != null) {
            identity = up;
            if (getUseFirstPass()) {
                String userName = identity.getName();
                log.debugf("Storing username '%s'", userName);
                // Add the username to the shared state map
                sharedState.put("javax.security.auth.login.name", identity);
                if (useNewClientCert) {
                    SSLSession session = con.getSslSession();
                    if (session != null) {
                        try {
                            credential = session.getPeerCertificates()[0];
                            log.debug("Using new certificate as credential.");
                        } catch (SSLPeerUnverifiedException e) {
                            log.debugf("No peer certificate available for '%s'", userName);
                        }
                    }
                } else if (useClientCert) {
                    SSLSession session = con.getSslSession();
                    if (session != null) {
                        try {
                            credential = session.getPeerCertificateChain()[0];
                            log.debug("Using certificate as credential.");
                        } catch (SSLPeerUnverifiedException e) {
                            log.debugf("No peer certificate available for '%s'", userName);
                        }
                    }
                }
                sharedState.put("javax.security.auth.login.password", credential);
            }
            loginOk = true;
            return true;
        }
    }
    // username and password has been supplied to a web auth.
    return false;
}
Also used : SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) Connection(org.jboss.remoting3.Connection) RealmUser(org.jboss.as.core.security.RealmUser) SSLSession(javax.net.ssl.SSLSession) Principal(java.security.Principal)

Aggregations

SSLPeerUnverifiedException (javax.net.ssl.SSLPeerUnverifiedException)109 X509Certificate (java.security.cert.X509Certificate)40 Certificate (java.security.cert.Certificate)39 SSLSession (javax.net.ssl.SSLSession)27 SSLSocket (javax.net.ssl.SSLSocket)23 IOException (java.io.IOException)18 CertificateException (java.security.cert.CertificateException)14 SSLException (javax.net.ssl.SSLException)14 X509Certificate (javax.security.cert.X509Certificate)12 Principal (java.security.Principal)11 Test (org.junit.jupiter.api.Test)11 Test (org.junit.Test)8 InetSocketAddress (java.net.InetSocketAddress)7 SSLHandshakeException (javax.net.ssl.SSLHandshakeException)7 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)7 CertificateEncodingException (java.security.cert.CertificateEncodingException)6 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)6 MockResponse (mockwebserver3.MockResponse)6 Request (okhttp3.Request)6 UnknownHostException (java.net.UnknownHostException)5