Search in sources :

Example 51 with SSLException

use of javax.net.ssl.SSLException in project android_frameworks_base by DirtyUnicorns.

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 52 with SSLException

use of javax.net.ssl.SSLException in project geode by apache.

the class TcpClient method getServerVersion.

private Short getServerVersion(InetSocketAddress ipAddr, int timeout) throws IOException, ClassNotFoundException {
    int gossipVersion = TcpServer.getCurrentGossipVersion();
    Short serverVersion = null;
    // Get GemFire version of TcpServer first, before sending any other request.
    synchronized (serverVersions) {
        serverVersion = serverVersions.get(ipAddr);
    }
    if (serverVersion != null) {
        return serverVersion;
    }
    gossipVersion = TcpServer.getOldGossipVersion();
    Socket sock = null;
    try {
        sock = socketCreator.connect(ipAddr.getAddress(), ipAddr.getPort(), timeout, null, false);
        sock.setSoTimeout(timeout);
    } catch (SSLException e) {
        throw new LocatorCancelException("Unable to form SSL connection", e);
    }
    try {
        DataOutputStream out = new DataOutputStream(sock.getOutputStream());
        out = new VersionedDataOutputStream(out, Version.GFE_57);
        out.writeInt(gossipVersion);
        VersionRequest verRequest = new VersionRequest();
        DataSerializer.writeObject(verRequest, out);
        out.flush();
        InputStream inputStream = sock.getInputStream();
        DataInputStream in = new DataInputStream(inputStream);
        in = new VersionedDataInputStream(in, Version.GFE_57);
        try {
            Object readObject = DataSerializer.readObject(in);
            if (!(readObject instanceof VersionResponse)) {
                throw new LocatorCancelException("Unrecognisable response received: object is null. This could be the result of trying to connect a non-SSL-enabled locator to an SSL-enabled locator.");
            }
            VersionResponse response = (VersionResponse) readObject;
            if (response != null) {
                serverVersion = Short.valueOf(response.getVersionOrdinal());
                synchronized (serverVersions) {
                    serverVersions.put(ipAddr, serverVersion);
                }
                return serverVersion;
            }
        } catch (EOFException ex) {
        // old locators will not recognize the version request and will close the connection
        }
    } finally {
        try {
            // initiate an abort on close to shut down the server's socket
            sock.setSoLinger(true, 0);
            sock.close();
        } catch (Exception e) {
            logger.error("Error closing socket ", e);
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Locator " + ipAddr + " did not respond to a request for its version.  I will assume it is using v5.7 for safety.");
    }
    synchronized (serverVersions) {
        serverVersions.put(ipAddr, Version.GFE_57.ordinal());
    }
    return Short.valueOf(Version.GFE_57.ordinal());
}
Also used : DataOutputStream(java.io.DataOutputStream) VersionedDataOutputStream(org.apache.geode.internal.VersionedDataOutputStream) DataInputStream(java.io.DataInputStream) VersionedDataInputStream(org.apache.geode.internal.VersionedDataInputStream) InputStream(java.io.InputStream) DataInputStream(java.io.DataInputStream) VersionedDataInputStream(org.apache.geode.internal.VersionedDataInputStream) SSLException(javax.net.ssl.SSLException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) EOFException(java.io.EOFException) SSLException(javax.net.ssl.SSLException) UnsupportedVersionException(org.apache.geode.cache.UnsupportedVersionException) VersionedDataOutputStream(org.apache.geode.internal.VersionedDataOutputStream) EOFException(java.io.EOFException) Socket(java.net.Socket) VersionedDataInputStream(org.apache.geode.internal.VersionedDataInputStream)

Example 53 with SSLException

use of javax.net.ssl.SSLException in project geode by apache.

the class TcpServer method run.

protected void run() {
    Socket sock = null;
    while (!shuttingDown) {
        if (SystemFailure.getFailure() != null) {
            // Allocate no objects here!
            try {
                srv_sock.close();
            } catch (IOException ignore) {
            // ignore
            }
            // throws
            SystemFailure.checkFailure();
        }
        try {
            try {
                sock = srv_sock.accept();
            } catch (SSLException ex) {
                // SW: This is the case when there is a problem in locator
                // SSL configuration, so need to exit otherwise goes into an
                // infinite loop just filling the logs
                log.error("Locator stopping due to SSL configuration problem.", ex);
                shuttingDown = true;
                continue;
            }
            processRequest(sock);
        // looping=false; GemStoneAddition change
        } catch (Exception ex) {
            if (!shuttingDown) {
                log.error("exception=", ex);
            }
            continue;
        }
    }
    try {
        srv_sock.close();
    } catch (java.io.IOException ex) {
        log.warn("exception closing server socket during shutdown", ex);
    }
    if (shuttingDown) {
        log.info("locator shutting down");
        executor.shutdown();
        try {
            executor.awaitTermination(SHUTDOWN_WAIT_TIME, TimeUnit.MILLISECONDS);
        } catch (InterruptedException ignore) {
            Thread.currentThread().interrupt();
        }
        handler.shutDown();
        synchronized (this) {
            // this.shutDown = true;
            this.notifyAll();
        }
    }
}
Also used : IOException(java.io.IOException) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) CancelException(org.apache.geode.CancelException) StreamCorruptedException(java.io.StreamCorruptedException) IOException(java.io.IOException) EOFException(java.io.EOFException) SSLException(javax.net.ssl.SSLException)

Example 54 with SSLException

use of javax.net.ssl.SSLException in project geode by apache.

the class AcceptorImpl method accept.

/**
   * {@linkplain ServerSocket#accept Listens}for a client to connect and then creates a new
   * {@link ServerConnection}to handle messages from that client.
   */
@Override
public void accept() {
    while (isRunning()) {
        if (SystemFailure.getFailure() != null) {
            // Allocate no objects here!
            ServerSocket s = serverSock;
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                // don't care
                }
            }
            // throws
            SystemFailure.checkFailure();
        }
        // moved this check out of the try. If we are cancelled then we need
        // to break out of this while loop.
        // throws
        crHelper.checkCancelInProgress(null);
        Socket s = null;
        try {
            s = serverSock.accept();
            // throws
            crHelper.checkCancelInProgress(null);
            // Optionally enable SO_KEEPALIVE in the OS network protocol.
            s.setKeepAlive(SocketCreator.ENABLE_TCP_KEEP_ALIVE);
            synchronized (this.syncLock) {
                if (!isRunning()) {
                    closeSocket(s);
                    break;
                }
            }
            this.loggedAcceptError = false;
            handOffNewClientConnection(s);
        } catch (InterruptedIOException e) {
            // Solaris only
            closeSocket(s);
            if (isRunning()) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Aborted due to interrupt: {}", e);
                }
            }
        } catch (IOException e) {
            if (isRunning()) {
                if (e instanceof SSLException) {
                    try {
                        // Try to send a proper rejection message
                        ServerHandShakeProcessor.refuse(s.getOutputStream(), e.toString(), HandShake.REPLY_EXCEPTION_AUTHENTICATION_FAILED);
                    } catch (IOException ex) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Bridge server: Unable to write SSL error");
                        }
                    }
                }
            }
            closeSocket(s);
            if (isRunning()) {
                if (!this.loggedAcceptError) {
                    this.loggedAcceptError = true;
                    logger.error(LocalizedMessage.create(LocalizedStrings.AcceptorImpl_CACHE_SERVER_UNEXPECTED_IOEXCEPTION_FROM_ACCEPT, e));
                }
            // Why sleep?
            // try {Thread.sleep(3000);} catch (InterruptedException ie) {}
            }
        } catch (CancelException e) {
            closeSocket(s);
            throw e;
        } catch (Exception e) {
            closeSocket(s);
            if (isRunning()) {
                logger.fatal(LocalizedMessage.create(LocalizedStrings.AcceptorImpl_CACHE_SERVER_UNEXPECTED_EXCEPTION, e));
            }
        }
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) ServerSocket(java.net.ServerSocket) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CancelException(org.apache.geode.CancelException) SSLException(javax.net.ssl.SSLException) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) CancelException(org.apache.geode.CancelException) EOFException(java.io.EOFException) SSLException(javax.net.ssl.SSLException) CancelledKeyException(java.nio.channels.CancelledKeyException) BindException(java.net.BindException) InterruptedIOException(java.io.InterruptedIOException) SocketException(java.net.SocketException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) SocketTimeoutException(java.net.SocketTimeoutException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) ClosedSelectorException(java.nio.channels.ClosedSelectorException) ToDataException(org.apache.geode.ToDataException)

Example 55 with SSLException

use of javax.net.ssl.SSLException in project geode by apache.

the class TCPConduit method run.

/**
   * this is the server socket listener thread's run loop
   */
public void run() {
    ConnectionTable.threadWantsSharedResources();
    if (logger.isTraceEnabled(LogMarker.DM)) {
        logger.trace(LogMarker.DM, "Starting P2P Listener on  {}", id);
    }
    for (; ; ) {
        SystemFailure.checkFailure();
        if (stopper.isCancelInProgress()) {
            break;
        }
        if (stopped) {
            break;
        }
        if (Thread.currentThread().isInterrupted()) {
            break;
        }
        if (stopper.isCancelInProgress()) {
            // part of bug 37271
            break;
        }
        Socket othersock = null;
        try {
            if (this.useNIO) {
                SocketChannel otherChannel = channel.accept();
                othersock = otherChannel.socket();
            } else {
                try {
                    othersock = socket.accept();
                } catch (SSLException ex) {
                    // SW: This is the case when there is a problem in P2P
                    // SSL configuration, so need to exit otherwise goes into an
                    // infinite loop just filling the logs
                    logger.warn(LocalizedMessage.create(LocalizedStrings.TCPConduit_STOPPING_P2P_LISTENER_DUE_TO_SSL_CONFIGURATION_PROBLEM), ex);
                    break;
                }
                socketCreator.configureServerSSLSocket(othersock);
            }
            if (stopped) {
                try {
                    if (othersock != null) {
                        othersock.close();
                    }
                } catch (Exception e) {
                }
                continue;
            }
            acceptConnection(othersock);
        } catch (ClosedByInterruptException cbie) {
        // safe to ignore
        } catch (ClosedChannelException e) {
            // we're dead
            break;
        } catch (CancelException e) {
            break;
        } catch (Exception e) {
            if (!stopped) {
                if (e instanceof SocketException && "Socket closed".equalsIgnoreCase(e.getMessage())) {
                    // safe to ignore; see bug 31156
                    if (!socket.isClosed()) {
                        logger.warn(LocalizedMessage.create(LocalizedStrings.TCPConduit_SERVERSOCKET_THREW_SOCKET_CLOSED_EXCEPTION_BUT_SAYS_IT_IS_NOT_CLOSED), e);
                        try {
                            socket.close();
                            createServerSocket();
                        } catch (IOException ioe) {
                            logger.fatal(LocalizedMessage.create(LocalizedStrings.TCPConduit_UNABLE_TO_CLOSE_AND_RECREATE_SERVER_SOCKET), ioe);
                            // post 5.1.0x, this should force shutdown
                            try {
                                Thread.sleep(5000);
                            } catch (InterruptedException ie) {
                                // Don't reset; we're just exiting the thread
                                logger.info(LocalizedMessage.create(LocalizedStrings.TCPConduit_INTERRUPTED_AND_EXITING_WHILE_TRYING_TO_RECREATE_LISTENER_SOCKETS));
                                return;
                            }
                        }
                    }
                } else {
                    this.stats.incFailedAccept();
                    if (e instanceof IOException && "Too many open files".equals(e.getMessage())) {
                        getConTable().fileDescriptorsExhausted();
                    } else {
                        logger.warn(e.getMessage(), e);
                    }
                }
            }
        // connections.cleanupLowWater();
        }
        if (!stopped && socket.isClosed()) {
            // NOTE: do not check for distributed system closing here. Messaging
            // may need to occur during the closing of the DS or cache
            logger.warn(LocalizedMessage.create(LocalizedStrings.TCPConduit_SERVERSOCKET_CLOSED_REOPENING));
            try {
                createServerSocket();
            } catch (ConnectionException ex) {
                logger.warn(ex.getMessage(), ex);
            }
        }
    }
    if (logger.isTraceEnabled(LogMarker.DM)) {
        logger.debug("Stopped P2P Listener on  {}", id);
    }
}
Also used : ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) ClosedChannelException(java.nio.channels.ClosedChannelException) SocketException(java.net.SocketException) CancelException(org.apache.geode.CancelException) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) SocketException(java.net.SocketException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) DistributedSystemDisconnectedException(org.apache.geode.distributed.DistributedSystemDisconnectedException) CancelException(org.apache.geode.CancelException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) SSLException(javax.net.ssl.SSLException)

Aggregations

SSLException (javax.net.ssl.SSLException)158 IOException (java.io.IOException)46 X509Certificate (java.security.cert.X509Certificate)26 SSLEngineResult (javax.net.ssl.SSLEngineResult)23 SocketException (java.net.SocketException)20 SSLSocket (javax.net.ssl.SSLSocket)20 ByteBuffer (java.nio.ByteBuffer)19 CertificateException (java.security.cert.CertificateException)19 Test (org.junit.Test)19 SSLHandshakeException (javax.net.ssl.SSLHandshakeException)18 SSLContext (javax.net.ssl.SSLContext)15 SSLPeerUnverifiedException (javax.net.ssl.SSLPeerUnverifiedException)15 SSLSession (javax.net.ssl.SSLSession)15 InetSocketAddress (java.net.InetSocketAddress)14 SSLEngine (javax.net.ssl.SSLEngine)14 X509TrustManager (javax.net.ssl.X509TrustManager)12 Bootstrap (io.netty.bootstrap.Bootstrap)11 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)11 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)11 Socket (java.net.Socket)11