Search in sources :

Example 16 with SSLHandshakeException

use of javax.net.ssl.SSLHandshakeException in project robovm by robovm.

the class HandshakeIODataStream method check.

// checks if the data can be written in the buffer
private void check(int length) {
    // 2. all written data was demanded by getData methods
    if (write_pos == write_pos_beg) {
        // just started to write after the reading
        if (read_pos != read_pos_end) {
            // all the inbound handshake data had been read
            throw new AlertException(AlertProtocol.INTERNAL_ERROR, new SSLHandshakeException("Data was not fully read: " + read_pos + " " + read_pos_end));
        }
        // set up the write positions
        if (write_pos_beg < read_pos_end) {
            write_pos_beg = read_pos_end;
            write_pos = write_pos_beg;
        }
    }
    // if there is not enought free space in the buffer - enlarge it:
    if (write_pos + length >= buff_size) {
        enlargeBuffer(length);
    }
}
Also used : SSLHandshakeException(javax.net.ssl.SSLHandshakeException)

Example 17 with SSLHandshakeException

use of javax.net.ssl.SSLHandshakeException in project hudson-2.x by hudson.

the class Launcher method parseJnlpArguments.

/**
     * Parses the connection arguments from JNLP file given in the URL.
     */
public List<String> parseJnlpArguments() throws ParserConfigurationException, SAXException, IOException, InterruptedException {
    while (true) {
        try {
            URLConnection con = slaveJnlpURL.openConnection();
            if (con instanceof HttpURLConnection && slaveJnlpCredentials != null) {
                HttpURLConnection http = (HttpURLConnection) con;
                String userPassword = slaveJnlpCredentials;
                String encoding = new String(Base64.encodeBase64(userPassword.getBytes()));
                http.setRequestProperty("Authorization", "Basic " + encoding);
            }
            con.connect();
            if (con instanceof HttpURLConnection) {
                HttpURLConnection http = (HttpURLConnection) con;
                if (http.getResponseCode() >= 400)
                    // got the error code. report that (such as 401)
                    throw new IOException("Failed to load " + slaveJnlpURL + ": " + http.getResponseCode() + " " + http.getResponseMessage());
            }
            Document dom;
            // check if this URL points to a .jnlp file
            String contentType = con.getHeaderField("Content-Type");
            if (contentType == null || !contentType.startsWith("application/x-java-jnlp-file")) {
                // load DOM anyway, but if it fails to parse, that's probably because this is not an XML file to begin with.
                try {
                    dom = loadDom(slaveJnlpURL, con);
                } catch (SAXException e) {
                    throw new IOException(slaveJnlpURL + " doesn't look like a JNLP file; content type was " + contentType);
                } catch (IOException e) {
                    throw new IOException(slaveJnlpURL + " doesn't look like a JNLP file; content type was " + contentType);
                }
            } else {
                dom = loadDom(slaveJnlpURL, con);
            }
            // exec into the JNLP launcher, to fetch the connection parameter through JNLP.
            NodeList argElements = dom.getElementsByTagName("argument");
            List<String> jnlpArgs = new ArrayList<String>();
            for (int i = 0; i < argElements.getLength(); i++) jnlpArgs.add(argElements.item(i).getTextContent());
            if (slaveJnlpCredentials != null) {
                jnlpArgs.add("-credentials");
                jnlpArgs.add(slaveJnlpCredentials);
            }
            // force a headless mode
            jnlpArgs.add("-headless");
            return jnlpArgs;
        } catch (SSLHandshakeException e) {
            if (e.getMessage().contains("PKIX path building failed")) {
                // invalid SSL certificate. One reason this happens is when the certificate is self-signed
                IOException x = new IOException("Failed to validate a server certificate. If you are using a self-signed certificate, you can use the -noCertificateCheck option to bypass this check.");
                x.initCause(e);
                throw x;
            } else
                throw e;
        } catch (IOException e) {
            System.err.println("Failing to obtain " + slaveJnlpURL);
            e.printStackTrace(System.err);
            System.err.println("Waiting 10 seconds before retry");
            Thread.sleep(10 * 1000);
        // retry
        }
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) NodeList(org.w3c.dom.NodeList) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Document(org.w3c.dom.Document) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SAXException(org.xml.sax.SAXException)

Example 18 with SSLHandshakeException

use of javax.net.ssl.SSLHandshakeException in project Openfire by igniterealtime.

the class LocalOutgoingServerSession method createOutgoingSession.

/**
     * Establishes a new outgoing session to a remote domain. If the remote domain supports TLS and SASL then the new
     * outgoing connection will be secured with TLS and authenticated  using SASL. However, if TLS or SASL is not
     * supported by the remote domain or if an error occurred while securing or authenticating the connection using SASL
     * then server dialback will be used.
     *
     * @param localDomain the local domain to authenticate with the remote domain.
     * @param remoteDomain the remote domain.
     * @param port default port to use to establish the connection.
     * @return new outgoing session to a remote domain, or null.
     */
private static LocalOutgoingServerSession createOutgoingSession(String localDomain, String remoteDomain, int port) {
    final Logger log = LoggerFactory.getLogger(Log.getName() + "[Create outgoing session for: " + localDomain + " to " + remoteDomain + "]");
    log.debug("Creating new session...");
    // Connect to remote server using XMPP 1.0 (TLS + SASL EXTERNAL or TLS + server dialback or server dialback)
    log.debug("Creating plain socket connection to a host that belongs to the remote XMPP domain.");
    final Socket socket = SocketUtil.createSocketToXmppDomain(remoteDomain, port);
    if (socket == null) {
        log.info("Unable to create new session: Cannot create a plain socket connection with any applicable remote host.");
        return null;
    }
    SocketConnection connection = null;
    try {
        connection = new SocketConnection(XMPPServer.getInstance().getPacketDeliverer(), socket, false);
        log.debug("Send the stream header and wait for response...");
        StringBuilder openingStream = new StringBuilder();
        openingStream.append("<stream:stream");
        openingStream.append(" xmlns:db=\"jabber:server:dialback\"");
        openingStream.append(" xmlns:stream=\"http://etherx.jabber.org/streams\"");
        openingStream.append(" xmlns=\"jabber:server\"");
        // OF-673
        openingStream.append(" from=\"").append(localDomain).append("\"");
        openingStream.append(" to=\"").append(remoteDomain).append("\"");
        openingStream.append(" version=\"1.0\">");
        connection.deliverRawText(openingStream.toString());
        // Set a read timeout (of 5 seconds) so we don't keep waiting forever
        int soTimeout = socket.getSoTimeout();
        socket.setSoTimeout(5000);
        XMPPPacketReader reader = new XMPPPacketReader();
        reader.getXPPParser().setInput(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
        // Get the answer from the Receiving Server
        XmlPullParser xpp = reader.getXPPParser();
        for (int eventType = xpp.getEventType(); eventType != XmlPullParser.START_TAG; ) {
            eventType = xpp.next();
        }
        String serverVersion = xpp.getAttributeValue("", "version");
        String id = xpp.getAttributeValue("", "id");
        log.debug("Got a response (stream ID: {}, version: {}). Check if the remote server is XMPP 1.0 compliant...", id, serverVersion);
        if (serverVersion != null && decodeVersion(serverVersion)[0] >= 1) {
            log.debug("The remote server is XMPP 1.0 compliant (or at least reports to be).");
            // Restore default timeout
            socket.setSoTimeout(soTimeout);
            log.debug("Processing stream features of the remote domain...");
            Element features = reader.parseDocument().getRootElement();
            if (features != null) {
                log.debug("Check if both us as well as the remote server have enabled STARTTLS and/or dialback ...");
                final boolean useTLS = JiveGlobals.getBooleanProperty(ConnectionSettings.Server.TLS_ENABLED, true);
                if (useTLS && features.element("starttls") != null) {
                    log.debug("Both us and the remote server support the STARTTLS feature. Secure and authenticate the connection with TLS & SASL...");
                    LocalOutgoingServerSession answer = secureAndAuthenticate(remoteDomain, connection, reader, openingStream, localDomain);
                    if (answer != null) {
                        log.debug("Successfully secured/authenticated the connection with TLS/SASL)!");
                        // Everything went fine so return the secured and
                        // authenticated connection
                        log.debug("Successfully created new session!");
                        return answer;
                    }
                    log.debug("Unable to secure and authenticate the connection with TLS & SASL.");
                } else if (connection.getTlsPolicy() == Connection.TLSPolicy.required) {
                    log.debug("I have no StartTLS yet I must TLS");
                    connection.close();
                    return null;
                } else // Check if we are going to try server dialback (XMPP 1.0)
                if (ServerDialback.isEnabled() && features.element("dialback") != null) {
                    log.debug("Both us and the remote server support the 'dialback' feature. Authenticate the connection with dialback...");
                    ServerDialback method = new ServerDialback(connection, localDomain);
                    OutgoingServerSocketReader newSocketReader = new OutgoingServerSocketReader(reader);
                    if (method.authenticateDomain(newSocketReader, localDomain, remoteDomain, id)) {
                        log.debug("Successfully authenticated the connection with dialback!");
                        StreamID streamID = new BasicStreamIDFactory().createStreamID(id);
                        LocalOutgoingServerSession session = new LocalOutgoingServerSession(localDomain, connection, newSocketReader, streamID);
                        connection.init(session);
                        // Set the hostname as the address of the session
                        session.setAddress(new JID(null, remoteDomain, null));
                        log.debug("Successfully created new session!");
                        return session;
                    } else {
                        log.debug("Unable to authenticate the connection with dialback.");
                    }
                }
            } else {
                log.debug("Error! No data from the remote server (expected a 'feature' element).");
            }
        } else {
            log.debug("The remote server is not XMPP 1.0 compliant.");
        }
        log.debug("Something went wrong so close the connection and try server dialback over a plain connection");
        if (connection.getTlsPolicy() == Connection.TLSPolicy.required) {
            log.debug("I have no StartTLS yet I must TLS");
            connection.close();
            return null;
        }
        connection.close();
    } catch (SSLHandshakeException e) {
        // This is a failure as described in RFC3620, section 5.4.3.2 "STARTTLS Failure".
        log.info("STARTTLS negotiation failed. Closing connection (without sending any data such as <failure/> or </stream>).", e);
        // It is probably (see OF-794) best if we, as the initiating entity, therefor don't send any data either.
        if (connection != null) {
            connection.forceClose();
        }
    } catch (Exception e) {
        // This might be RFC3620, section 5.4.2.2 "Failure Case" or even an unrelated problem. Handle 'normally'.
        log.warn("An exception occurred while creating an encrypted session. Closing connection.", e);
        if (connection != null) {
            connection.close();
        }
    }
    if (ServerDialback.isEnabled()) {
        log.debug("Unable to create a new session. Going to try connecting using server dialback as a fallback.");
        // Use server dialback (pre XMPP 1.0) over a plain connection
        final LocalOutgoingServerSession outgoingSession = new ServerDialback().createOutgoingSession(localDomain, remoteDomain, port);
        if (outgoingSession != null) {
            // TODO this success handler behaves differently from a similar success handler above. Shouldn't those be the same?
            log.debug("Successfully created new session (using dialback as a fallback)!");
            return outgoingSession;
        } else {
            log.warn("Unable to create a new session: Dialback (as a fallback) failed.");
            return null;
        }
    } else {
        log.warn("Unable to create a new session: exhausted all options (not trying dialback as a fallback, as server dialback is disabled by configuration.");
        return null;
    }
}
Also used : StreamID(org.jivesoftware.openfire.StreamID) XMPPPacketReader(org.dom4j.io.XMPPPacketReader) InputStreamReader(java.io.InputStreamReader) JID(org.xmpp.packet.JID) Element(org.dom4j.Element) XmlPullParser(org.xmlpull.v1.XmlPullParser) Logger(org.slf4j.Logger) ServerDialback(org.jivesoftware.openfire.server.ServerDialback) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) DocumentException(org.dom4j.DocumentException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) OutgoingServerSocketReader(org.jivesoftware.openfire.server.OutgoingServerSocketReader) BasicStreamIDFactory(org.jivesoftware.openfire.spi.BasicStreamIDFactory) Socket(java.net.Socket)

Example 19 with SSLHandshakeException

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

the class SslContextParametersMailRouteTest method testSendAndReceiveMailsWithCustomTrustStore.

@Test
public void testSendAndReceiveMailsWithCustomTrustStore() throws Exception {
    context.addRoutes(new RouteBuilder() {

        public void configure() {
            from("direct:in").to("smtps://" + smtpHost + "?username=" + username + "&password=" + password + "&sslContextParameters=#sslContextParameters");
        }
    });
    context.start();
    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put("To", email);
    headers.put("From", email);
    headers.put("Reply-to", email);
    headers.put("Subject", "SSL/TLS Test");
    try {
        template.sendBodyAndHeaders("direct:in", "Test Email Body", headers);
        fail("Should have thrown exception");
    } catch (CamelExecutionException e) {
        assertTrue(e.getCause().getCause() instanceof SSLHandshakeException);
        assertTrue(e.getCause().getCause().getMessage().contains("unable to find valid certification path to requested target"));
    }
}
Also used : CamelExecutionException(org.apache.camel.CamelExecutionException) RouteBuilder(org.apache.camel.builder.RouteBuilder) HashMap(java.util.HashMap) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) Test(org.junit.Test)

Example 20 with SSLHandshakeException

use of javax.net.ssl.SSLHandshakeException in project hadoop by apache.

the class TestSSLHttpServer method testExcludedCiphers.

/**
   * Test that verifies that excluded ciphers (SSL_RSA_WITH_RC4_128_SHA,
   * TLS_ECDH_ECDSA_WITH_RC4_128_SHA,TLS_ECDH_RSA_WITH_RC4_128_SHA,
   * TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,TLS_ECDHE_RSA_WITH_RC4_128_SHA) are not
   * available for negotiation during SSL connection.
   */
@Test
public void testExcludedCiphers() throws Exception {
    URL url = new URL(baseUrl, "/echo?a=b&c=d");
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory();
    PrefferedCipherSSLSocketFactory testPreferredCipherSSLSocketF = new PrefferedCipherSSLSocketFactory(sslSocketF, excludeCiphers.split(","));
    conn.setSSLSocketFactory(testPreferredCipherSSLSocketF);
    assertFalse("excludedCipher list is empty", excludeCiphers.isEmpty());
    try {
        InputStream in = conn.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        IOUtils.copyBytes(in, out, 1024);
        fail("No Ciphers in common, SSLHandshake must fail.");
    } catch (SSLHandshakeException ex) {
        LOG.info("No Ciphers in common, expected succesful test result.", ex);
    }
}
Also used : InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) Test(org.junit.Test)

Aggregations

SSLHandshakeException (javax.net.ssl.SSLHandshakeException)90 IOException (java.io.IOException)29 Test (org.junit.Test)22 CertificateException (java.security.cert.CertificateException)18 URL (java.net.URL)15 SSLException (javax.net.ssl.SSLException)15 SocketException (java.net.SocketException)13 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)12 SSLProtocolException (javax.net.ssl.SSLProtocolException)10 Socket (java.net.Socket)9 SSLSocket (javax.net.ssl.SSLSocket)9 SSLPeerUnverifiedException (javax.net.ssl.SSLPeerUnverifiedException)8 SocketTimeoutException (java.net.SocketTimeoutException)7 SSLSession (javax.net.ssl.SSLSession)7 InputStream (java.io.InputStream)6 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)6 Channel (io.netty.channel.Channel)5 InetSocketAddress (java.net.InetSocketAddress)5 MalformedURLException (java.net.MalformedURLException)5 ClosedChannelException (java.nio.channels.ClosedChannelException)5