Search in sources :

Example 96 with SSLException

use of javax.net.ssl.SSLException in project netty by netty.

the class OpenSslKeyMaterialManager method keyMaterial.

CertificateRequestedCallback.KeyMaterial keyMaterial(ReferenceCountedOpenSslEngine engine, String[] keyTypes, X500Principal[] issuer) throws SSLException {
    String alias = chooseClientAlias(engine, keyTypes, issuer);
    long keyBio = 0;
    long keyCertChainBio = 0;
    long pkey = 0;
    long certChain = 0;
    try {
        // TODO: Should we cache these and so not need to do a memory copy all the time ?
        X509Certificate[] certificates = keyManager.getCertificateChain(alias);
        if (certificates == null || certificates.length == 0) {
            return null;
        }
        PrivateKey key = keyManager.getPrivateKey(alias);
        keyCertChainBio = toBIO(certificates);
        certChain = SSL.parseX509Chain(keyCertChainBio);
        if (key != null) {
            keyBio = toBIO(key);
            pkey = SSL.parsePrivateKey(keyBio, password);
        }
        CertificateRequestedCallback.KeyMaterial material = new CertificateRequestedCallback.KeyMaterial(certChain, pkey);
        // Reset to 0 so we do not free these. This is needed as the client certificate callback takes ownership
        // of both the key and the certificate if they are returned from this method, and thus must not
        // be freed here.
        certChain = pkey = 0;
        return material;
    } catch (SSLException e) {
        throw e;
    } catch (Exception e) {
        throw new SSLException(e);
    } finally {
        freeBio(keyBio);
        freeBio(keyCertChainBio);
        SSL.freePrivateKey(pkey);
        SSL.freeX509Chain(certChain);
    }
}
Also used : CertificateRequestedCallback(io.netty.internal.tcnative.CertificateRequestedCallback) PrivateKey(java.security.PrivateKey) SSLException(javax.net.ssl.SSLException) X509Certificate(java.security.cert.X509Certificate) SSLException(javax.net.ssl.SSLException)

Example 97 with SSLException

use of javax.net.ssl.SSLException in project netty by netty.

the class OpenSslKeyMaterialManager method setKeyMaterial.

private void setKeyMaterial(long ssl, String alias) throws SSLException {
    long keyBio = 0;
    long keyCertChainBio = 0;
    long keyCertChainBio2 = 0;
    try {
        // TODO: Should we cache these and so not need to do a memory copy all the time ?
        X509Certificate[] certificates = keyManager.getCertificateChain(alias);
        if (certificates == null || certificates.length == 0) {
            return;
        }
        PrivateKey key = keyManager.getPrivateKey(alias);
        // Only encode one time
        PemEncoded encoded = PemX509Certificate.toPEM(ByteBufAllocator.DEFAULT, true, certificates);
        try {
            keyCertChainBio = toBIO(ByteBufAllocator.DEFAULT, encoded.retain());
            keyCertChainBio2 = toBIO(ByteBufAllocator.DEFAULT, encoded.retain());
            if (key != null) {
                keyBio = toBIO(key);
            }
            SSL.setCertificateBio(ssl, keyCertChainBio, keyBio, password);
            // We may have more then one cert in the chain so add all of them now.
            SSL.setCertificateChainBio(ssl, keyCertChainBio2, true);
        } finally {
            encoded.release();
        }
    } catch (SSLException e) {
        throw e;
    } catch (Exception e) {
        throw new SSLException(e);
    } finally {
        freeBio(keyBio);
        freeBio(keyCertChainBio);
        freeBio(keyCertChainBio2);
    }
}
Also used : PrivateKey(java.security.PrivateKey) SSLException(javax.net.ssl.SSLException) X509Certificate(java.security.cert.X509Certificate) SSLException(javax.net.ssl.SSLException)

Example 98 with SSLException

use of javax.net.ssl.SSLException in project nanohttpd by NanoHttpd.

the class HTTPSession method execute.

@Override
public void execute() throws IOException {
    Response r = null;
    try {
        // Read the first 8192 bytes.
        // The full header should fit in here.
        // Apache's default header limit is 8KB.
        // Do NOT assume that a single read will get the entire header
        // at once!
        byte[] buf = new byte[HTTPSession.BUFSIZE];
        this.splitbyte = 0;
        this.rlen = 0;
        int read = -1;
        this.inputStream.mark(HTTPSession.BUFSIZE);
        try {
            read = this.inputStream.read(buf, 0, HTTPSession.BUFSIZE);
        } catch (SSLException e) {
            throw e;
        } catch (IOException e) {
            NanoHTTPD.safeClose(this.inputStream);
            NanoHTTPD.safeClose(this.outputStream);
            throw new SocketException("NanoHttpd Shutdown");
        }
        if (read == -1) {
            // socket was been closed
            NanoHTTPD.safeClose(this.inputStream);
            NanoHTTPD.safeClose(this.outputStream);
            throw new SocketException("NanoHttpd Shutdown");
        }
        while (read > 0) {
            this.rlen += read;
            this.splitbyte = findHeaderEnd(buf, this.rlen);
            if (this.splitbyte > 0) {
                break;
            }
            read = this.inputStream.read(buf, this.rlen, HTTPSession.BUFSIZE - this.rlen);
        }
        if (this.splitbyte < this.rlen) {
            this.inputStream.reset();
            this.inputStream.skip(this.splitbyte);
        }
        this.parms = new HashMap<String, List<String>>();
        if (null == this.headers) {
            this.headers = new HashMap<String, String>();
        } else {
            this.headers.clear();
        }
        // Create a BufferedReader for parsing the header.
        BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, this.rlen)));
        // Decode the header into parms and header java properties
        Map<String, String> pre = new HashMap<String, String>();
        decodeHeader(hin, pre, this.parms, this.headers);
        if (null != this.remoteIp) {
            this.headers.put("remote-addr", this.remoteIp);
            this.headers.put("http-client-ip", this.remoteIp);
        }
        this.method = Method.lookup(pre.get("method"));
        if (this.method == null) {
            throw new ResponseException(Status.BAD_REQUEST, "BAD REQUEST: Syntax error. HTTP verb " + pre.get("method") + " unhandled.");
        }
        this.uri = pre.get("uri");
        this.cookies = new CookieHandler(this.headers);
        String connection = this.headers.get("connection");
        boolean keepAlive = "HTTP/1.1".equals(protocolVersion) && (connection == null || !connection.matches("(?i).*close.*"));
        // Ok, now do the serve()
        // TODO: long body_size = getBodySize();
        // TODO: long pos_before_serve = this.inputStream.totalRead()
        // (requires implementation for totalRead())
        r = httpd.handle(this);
        if (r == null) {
            throw new ResponseException(Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: Serve() returned a null response.");
        } else {
            String acceptEncoding = this.headers.get("accept-encoding");
            this.cookies.unloadQueue(r);
            r.setRequestMethod(this.method);
            if (acceptEncoding == null || !acceptEncoding.contains("gzip")) {
                r.setUseGzip(false);
            }
            r.setKeepAlive(keepAlive);
            r.send(this.outputStream);
        }
        if (!keepAlive || r.isCloseConnection()) {
            throw new SocketException("NanoHttpd Shutdown");
        }
    } catch (SocketException e) {
        // throw it out to close socket object (finalAccept)
        throw e;
    } catch (SocketTimeoutException ste) {
        // exception up the call stack.
        throw ste;
    } catch (SSLException ssle) {
        Response resp = Response.newFixedLengthResponse(Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SSL PROTOCOL FAILURE: " + ssle.getMessage());
        resp.send(this.outputStream);
        NanoHTTPD.safeClose(this.outputStream);
    } catch (IOException ioe) {
        Response resp = Response.newFixedLengthResponse(Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
        resp.send(this.outputStream);
        NanoHTTPD.safeClose(this.outputStream);
    } catch (ResponseException re) {
        Response resp = Response.newFixedLengthResponse(re.getStatus(), NanoHTTPD.MIME_PLAINTEXT, re.getMessage());
        resp.send(this.outputStream);
        NanoHTTPD.safeClose(this.outputStream);
    } finally {
        NanoHTTPD.safeClose(r);
        this.tempFileManager.clear();
    }
}
Also used : SocketException(java.net.SocketException) InputStreamReader(java.io.InputStreamReader) HashMap(java.util.HashMap) ResponseException(org.nanohttpd.protocols.http.NanoHTTPD.ResponseException) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) Response(org.nanohttpd.protocols.http.response.Response) SocketTimeoutException(java.net.SocketTimeoutException) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedReader(java.io.BufferedReader) ArrayList(java.util.ArrayList) List(java.util.List) CookieHandler(org.nanohttpd.protocols.http.content.CookieHandler)

Example 99 with SSLException

use of javax.net.ssl.SSLException in project graylog2-server by Graylog2.

the class AbstractTcpTransport method buildSslHandlerCallable.

private Callable<ChannelHandler> buildSslHandlerCallable() {
    return new Callable<ChannelHandler>() {

        @Override
        public ChannelHandler call() throws Exception {
            try {
                return new SslHandler(createSslEngine());
            } catch (SSLException e) {
                LOG.error("Error creating SSL context. Make sure the certificate and key are in the correct format: cert=X.509 key=PKCS#8");
                throw e;
            }
        }

        private SSLEngine createSslEngine() throws IOException, GeneralSecurityException {
            final SSLContext instance = SSLContext.getInstance("TLS");
            TrustManager[] initTrustStore = new TrustManager[0];
            if (TLS_CLIENT_AUTH_OPTIONAL.equals(tlsClientAuth) || TLS_CLIENT_AUTH_REQUIRED.equals(tlsClientAuth)) {
                if (tlsClientAuthCertFile.exists()) {
                    initTrustStore = KeyUtil.initTrustStore(tlsClientAuthCertFile);
                } else {
                    LOG.warn("client auth configured, but no authorized certificates / certificate authorities configured");
                }
            }
            instance.init(KeyUtil.initKeyStore(tlsKeyFile, tlsCertFile, tlsKeyPassword), initTrustStore, new SecureRandom());
            final SSLEngine engine = instance.createSSLEngine();
            engine.setUseClientMode(false);
            switch(tlsClientAuth) {
                case TLS_CLIENT_AUTH_DISABLED:
                    LOG.debug("Not using TLS client authentication");
                    break;
                case TLS_CLIENT_AUTH_OPTIONAL:
                    LOG.debug("Using optional TLS client authentication");
                    engine.setWantClientAuth(true);
                    break;
                case TLS_CLIENT_AUTH_REQUIRED:
                    LOG.debug("Using mandatory TLS client authentication");
                    engine.setNeedClientAuth(true);
                    break;
                default:
                    throw new IllegalArgumentException("Unknown TLS client authentication mode: " + tlsClientAuth);
            }
            return engine;
        }
    };
}
Also used : SSLEngine(javax.net.ssl.SSLEngine) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) SSLException(javax.net.ssl.SSLException) Callable(java.util.concurrent.Callable) SslHandler(org.jboss.netty.handler.ssl.SslHandler) TrustManager(javax.net.ssl.TrustManager)

Example 100 with SSLException

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

the class TestAMWebApp method testMRWebAppSSLDisabled.

@Test
public void testMRWebAppSSLDisabled() throws Exception {
    MRApp app = new MRApp(2, 2, true, this.getClass().getName(), true) {

        @Override
        protected ClientService createClientService(AppContext context) {
            return new MRClientService(context);
        }
    };
    Configuration conf = new Configuration();
    // MR is explicitly disabling SSL, even though setting as HTTPS_ONLY
    conf.set(YarnConfiguration.YARN_HTTP_POLICY_KEY, Policy.HTTPS_ONLY.name());
    Job job = app.submit(conf);
    String hostPort = NetUtils.getHostPortString(((MRClientService) app.getClientService()).getWebApp().getListenerAddress());
    // http:// should be accessible
    URL httpUrl = new URL("http://" + hostPort);
    HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
    InputStream in = conn.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    IOUtils.copyBytes(in, out, 1024);
    Assert.assertTrue(out.toString().contains("MapReduce Application"));
    // https:// is not accessible.
    URL httpsUrl = new URL("https://" + hostPort);
    try {
        HttpURLConnection httpsConn = (HttpURLConnection) httpsUrl.openConnection();
        httpsConn.getInputStream();
        Assert.fail("https:// is not accessible, expected to fail");
    } catch (Exception e) {
        Assert.assertTrue(e instanceof SSLException);
    }
    app.waitForState(job, JobState.SUCCEEDED);
    app.verifyCompleted();
}
Also used : HttpURLConnection(java.net.HttpURLConnection) YarnConfiguration(org.apache.hadoop.yarn.conf.YarnConfiguration) Configuration(org.apache.hadoop.conf.Configuration) InputStream(java.io.InputStream) AppContext(org.apache.hadoop.mapreduce.v2.app.AppContext) MockAppContext(org.apache.hadoop.mapreduce.v2.app.MockAppContext) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MRClientService(org.apache.hadoop.mapreduce.v2.app.client.MRClientService) Job(org.apache.hadoop.mapreduce.v2.app.job.Job) SSLException(javax.net.ssl.SSLException) URL(java.net.URL) SSLException(javax.net.ssl.SSLException) MRApp(org.apache.hadoop.mapreduce.v2.app.MRApp) Test(org.junit.Test)

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