Example usage for javax.net.ssl SSLPeerUnverifiedException getMessage

List of usage examples for javax.net.ssl SSLPeerUnverifiedException getMessage

Introduction

In this page you can find the example usage for javax.net.ssl SSLPeerUnverifiedException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.apache.nifi.registry.security.util.CertificateUtils.java

/**
 * Returns the DN extracted from the server certificate.
 *
 * @param socket the SSL Socket//from w  w  w .j  a  v a 2 s  .  com
 * @return the extracted DN
 * @throws CertificateException if there is a problem parsing the certificate
 */
private static String extractPeerDNFromServerSSLSocket(Socket socket) throws CertificateException {
    String dn = null;
    if (socket instanceof SSLSocket) {
        final SSLSocket sslSocket = (SSLSocket) socket;
        try {
            final Certificate[] certChains = sslSocket.getSession().getPeerCertificates();
            if (certChains != null && certChains.length > 0) {
                X509Certificate x509Certificate = convertAbstractX509Certificate(certChains[0]);
                dn = x509Certificate.getSubjectDN().getName().trim();
                logger.debug("Extracted DN={} from server certificate", dn);
            }
        } catch (SSLPeerUnverifiedException e) {
            if (e.getMessage().equals(PEER_NOT_AUTHENTICATED_MSG)) {
                logger.error("The server did not present a certificate and thus the DN cannot"
                        + " be extracted. Check that the other endpoint is providing a complete certificate chain");
            }
            throw new CertificateException(e);
        }
    }
    return dn;
}

From source file:org.apache.nifi.registry.security.util.CertificateUtils.java

/**
 * Returns the DN extracted from the client certificate.
 *
 * If the client auth setting is WANT or NONE and a certificate is not present (and {@code respectClientAuth} is {@code true}), this method will return {@code null}.
 * If the client auth is NEED, it will throw a {@link CertificateException}.
 *
 * @param sslSocket the SSL Socket//ww w . j a v a 2s .c  om
 * @return the extracted DN
 * @throws CertificateException if there is a problem parsing the certificate
 */
private static String extractPeerDNFromClientSSLSocket(SSLSocket sslSocket) throws CertificateException {
    String dn = null;

    /** The clientAuth value can be "need", "want", or "none"
     * A client must send client certificates for need, should for want, and will not for none.
     * This method should throw an exception if none are provided for need, return null if none are provided for want, and return null (without checking) for none.
     */

    ClientAuth clientAuth = getClientAuthStatus(sslSocket);
    logger.debug("SSL Socket client auth status: {}", clientAuth);

    if (clientAuth != ClientAuth.NONE) {
        try {
            final Certificate[] certChains = sslSocket.getSession().getPeerCertificates();
            if (certChains != null && certChains.length > 0) {
                X509Certificate x509Certificate = convertAbstractX509Certificate(certChains[0]);
                dn = x509Certificate.getSubjectDN().getName().trim();
                logger.debug("Extracted DN={} from client certificate", dn);
            }
        } catch (SSLPeerUnverifiedException e) {
            if (e.getMessage().equals(PEER_NOT_AUTHENTICATED_MSG)) {
                logger.error("The incoming request did not contain client certificates and thus the DN cannot"
                        + " be extracted. Check that the other endpoint is providing a complete client certificate chain");
            }
            if (clientAuth == ClientAuth.WANT) {
                logger.warn(
                        "Suppressing missing client certificate exception because client auth is set to 'want'");
                return dn;
            }
            throw new CertificateException(e);
        }
    }
    return dn;
}

From source file:com.odoo.core.support.OdooServerTester.java

public boolean testConnection(String serverURL, Boolean forceConnect)
        throws SSLPeerUnverifiedException, OVersionException {
    mForceConnect = forceConnect;/*w w  w . j  a v a  2s .  c  o m*/
    if (!TextUtils.isEmpty(serverURL)) {
        try {
            mOdoo = new Odoo(mContext, serverURL, forceConnect);
            mDatabases = mOdoo.getDatabaseList();
            if (mDatabases == null) {
                mDatabases = new JSONArray();
                if (mOdoo.getDatabaseName() != null) {
                    mDatabases.put(mOdoo.getDatabaseName());
                }
            }
            if (mDatabases.length() > 0)
                return true;
        } catch (SSLPeerUnverifiedException peer) {
            throw new SSLPeerUnverifiedException(peer.getMessage());
        } catch (OVersionException version) {
            throw new OVersionException(version.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return false;
}

From source file:com.openerp.support.OpenERPServerConnection.java

/**
 * Test connection./*from  ww w  . ja  v  a  2 s. c  om*/
 * 
 * @param context
 *            the context
 * @param serverURL
 *            the server url
 * @param mForceConnect
 * @return true, if successful
 * @throws OEVersionException
 * @throws SSLPeerUnverifiedException
 */
public boolean testConnection(Context context, String serverURL)
        throws OEVersionException, SSLPeerUnverifiedException {
    Log.d(TAG, "OpenERPServerConnection->testConnection()");
    if (TextUtils.isEmpty(serverURL)) {
        return false;
    }
    try {
        openerp = new OpenERP(serverURL);
        openerp.getDatabaseList();
    } catch (SSLPeerUnverifiedException ssl) {
        Log.d(TAG, "Throw SSLPeerUnverifiedException ");
        throw new SSLPeerUnverifiedException(ssl.getMessage());
    } catch (OEVersionException version) {
        throw new OEVersionException(version.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.odoo.support.OdooServerConnection.java

/**
 * Test connection./*  ww  w. j a  va 2  s .co m*/
 * 
 * @param context
 *            the context
 * @param serverURL
 *            the server url
 * @param mForceConnect
 * @return true, if successful
 * @throws OVersionException
 * @throws SSLPeerUnverifiedException
 */
public boolean testConnection(Context context, String serverURL)
        throws OVersionException, SSLPeerUnverifiedException {
    Log.d(TAG, "OdooServerConnection->testConnection()");
    if (TextUtils.isEmpty(serverURL) && !serverURL.contains(".")) {
        return false;
    }
    try {
        odoo = new Odoo(context, serverURL, mAllowSelfSignedSSL);
        mDbLists = odoo.getDatabaseList();
        if (mDbLists == null) {
            mDbLists = new JSONArray();
            if (odoo.getDatabaseName() != null)
                mDbLists.put(odoo.getDatabaseName());
        }
    } catch (SSLPeerUnverifiedException ssl) {
        Log.d(TAG, "Throw SSLPeerUnverifiedException ");
        throw new SSLPeerUnverifiedException(ssl.getMessage());
    } catch (OVersionException version) {
        throw new OVersionException(version.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:org.mule.transport.http.HttpServerConnection.java

@Override
public void handshakeCompleted(HandshakeCompletedEvent handshakeCompletedEvent) {
    try {/*from w  ww  .j a  v  a 2 s . c o m*/
        localCertificateChain = handshakeCompletedEvent.getLocalCertificates();
        try {
            peerCertificateChain = handshakeCompletedEvent.getPeerCertificates();
        } catch (SSLPeerUnverifiedException e) {
            logger.debug("Cannot get peer certificate chain: " + e.getMessage());
        }
    } finally {
        sslSocketHandshakeComplete.release();
    }
}

From source file:org.ttrssreader.net.JavaJSONConnector.java

protected InputStream doRequest(Map<String, String> params) {
    try {/*from  w  w  w  .  j av a 2s  .c  om*/
        if (sessionId != null)
            params.put(SID, sessionId);

        JSONObject json = new JSONObject(params);
        byte[] outputBytes = json.toString().getBytes("UTF-8");

        logRequest(json);

        URL url = Controller.getInstance().url();
        HttpURLConnection con = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);

        // Content
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");
        con.setRequestProperty("Content-Length", Integer.toString(outputBytes.length));

        // Timeouts
        long timeoutSocket = (Controller.getInstance().lazyServer()) ? 15 * Utils.MINUTE : 10 * Utils.SECOND;
        con.setReadTimeout((int) timeoutSocket);
        con.setConnectTimeout((int) (8 * Utils.SECOND));

        // HTTP-Basic Authentication
        if (base64NameAndPw != null)
            con.setRequestProperty("Authorization", "Basic " + base64NameAndPw);

        // Add POST data
        con.getOutputStream().write(outputBytes);

        // Try to check for HTTP Status codes
        int code = con.getResponseCode();
        if (code >= 400 && code < 600) {
            hasLastError = true;
            lastError = "Server returned status: " + code + " (Message: " + con.getResponseMessage() + ")";
            return null;
        }

        // Everything is fine!
        return con.getInputStream();

    } catch (SSLPeerUnverifiedException e) {
        // Probably related: http://stackoverflow.com/questions/6035171/no-peer-cert-not-sure-which-route-to-take
        // Not doing anything here since this error should happen only when no certificate is received from the
        // server.
        Log.w(TAG, "SSLPeerUnverifiedException in doRequest(): " + formatException(e));
    } catch (SSLException e) {
        if ("No peer certificate".equals(e.getMessage())) {
            // Handle this by ignoring it, this occurrs very often when the connection is instable.
            Log.w(TAG, "SSLException in doRequest(): " + formatException(e));
        } else {
            hasLastError = true;
            lastError = "SSLException in doRequest(): " + formatException(e);
        }
    } catch (InterruptedIOException e) {
        Log.w(TAG, "InterruptedIOException in doRequest(): " + formatException(e));
    } catch (SocketException e) {
        // http://stackoverflow.com/questions/693997/how-to-set-httpresponse-timeout-for-android-in-java/1565243
        // #1565243
        Log.w(TAG, "SocketException in doRequest(): " + formatException(e));
    } catch (Exception e) {
        hasLastError = true;
        lastError = "Exception in doRequest(): " + formatException(e);
    }

    return null;
}

From source file:de.geeksfactory.opacclient.apis.BaseApi.java

/**
 * Perform a HTTP POST request to a given URL
 *
 * @param url           URL to fetch/*from ww  w  . ja v a2 s  .c o m*/
 * @param data          POST data to send
 * @param encoding      Expected encoding of the response body
 * @param ignore_errors If true, status codes above 400 do not raise an exception
 * @param cookieStore   If set, the given cookieStore is used instead of the built-in one.
 * @return Answer content
 * @throws NotReachableException Thrown when server returns a HTTP status code greater or equal
 *                               than 400.
 */
public String httpPost(String url, HttpEntity data, String encoding, boolean ignore_errors,
        CookieStore cookieStore) throws IOException {
    HttpPost httppost = new HttpPost(cleanUrl(url));
    httppost.setEntity(data);
    httppost.setHeader("Accept", "*/*");

    HttpResponse response;
    String html;
    try {
        if (cookieStore != null) {
            // Create local HTTP context
            HttpContext localContext = new BasicHttpContext();
            // Bind custom cookie store to the local context
            localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

            response = http_client.execute(httppost, localContext);
        } else {
            response = http_client.execute(httppost);
        }

        if (!ignore_errors && response.getStatusLine().getStatusCode() >= 400) {
            throw new NotReachableException(response.getStatusLine().getReasonPhrase());
        }
        html = convertStreamToString(response.getEntity().getContent(), encoding);
        HttpUtils.consume(response.getEntity());
    } catch (javax.net.ssl.SSLPeerUnverifiedException e) {
        logHttpError(e);
        throw new SSLSecurityException(e.getMessage());
    } catch (javax.net.ssl.SSLException e) {
        // Can be "Not trusted server certificate" or can be a
        // aborted/interrupted handshake/connection
        if (e.getMessage().contains("timed out") || e.getMessage().contains("reset by")) {
            logHttpError(e);
            throw new NotReachableException(e.getMessage());
        } else {
            logHttpError(e);
            throw new SSLSecurityException(e.getMessage());
        }
    } catch (InterruptedIOException e) {
        logHttpError(e);
        throw new NotReachableException(e.getMessage());
    } catch (UnknownHostException e) {
        throw new NotReachableException(e.getMessage());
    } catch (IOException e) {
        if (e.getMessage() != null && e.getMessage().contains("Request aborted")) {
            logHttpError(e);
            throw new NotReachableException(e.getMessage());
        } else {
            throw e;
        }
    }
    return html;
}

From source file:de.geeksfactory.opacclient.apis.BaseApi.java

/**
 * Perform a HTTP GET request to a given URL
 *
 * @param url           URL to fetch//from w  ww.j  a  v a  2 s . c o  m
 * @param encoding      Expected encoding of the response body
 * @param ignore_errors If true, status codes above 400 do not raise an exception
 * @param cookieStore   If set, the given cookieStore is used instead of the built-in one.
 * @return Answer content
 * @throws NotReachableException Thrown when server returns a HTTP status code greater or equal
 *                               than 400.
 */
public String httpGet(String url, String encoding, boolean ignore_errors, CookieStore cookieStore)
        throws IOException {

    HttpGet httpget = new HttpGet(cleanUrl(url));
    HttpResponse response;
    String html;
    httpget.setHeader("Accept", "*/*");

    try {
        if (cookieStore != null) {
            // Create local HTTP context
            HttpContext localContext = new BasicHttpContext();
            // Bind custom cookie store to the local context
            localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

            response = http_client.execute(httpget, localContext);
        } else {
            response = http_client.execute(httpget);
        }

        if (!ignore_errors && response.getStatusLine().getStatusCode() >= 400) {
            HttpUtils.consume(response.getEntity());
            throw new NotReachableException(response.getStatusLine().getReasonPhrase());
        }

        html = convertStreamToString(response.getEntity().getContent(), encoding);
        HttpUtils.consume(response.getEntity());
    } catch (javax.net.ssl.SSLPeerUnverifiedException e) {
        logHttpError(e);
        throw new SSLSecurityException(e.getMessage());
    } catch (javax.net.ssl.SSLException e) {
        // Can be "Not trusted server certificate" or can be a
        // aborted/interrupted handshake/connection
        if (e.getMessage().contains("timed out") || e.getMessage().contains("reset by")) {
            logHttpError(e);
            throw new NotReachableException(e.getMessage());
        } else {
            logHttpError(e);
            throw new SSLSecurityException(e.getMessage());
        }
    } catch (InterruptedIOException e) {
        logHttpError(e);
        throw new NotReachableException(e.getMessage());
    } catch (UnknownHostException e) {
        throw new NotReachableException(e.getMessage());
    } catch (IOException e) {
        if (e.getMessage() != null && e.getMessage().contains("Request aborted")) {
            logHttpError(e);
            throw new NotReachableException(e.getMessage());
        } else {
            throw e;
        }
    }
    return html;
}

From source file:org.apache.hc.client5.http.impl.auth.CredSspScheme.java

private Certificate getPeerServerCertificate() throws AuthenticationException {
    final Certificate[] peerCertificates;
    try {/*from w ww. j a  va2  s  . c  o m*/
        peerCertificates = sslEngine.getSession().getPeerCertificates();
    } catch (final SSLPeerUnverifiedException e) {
        throw new AuthenticationException(e.getMessage(), e);
    }
    for (final Certificate peerCertificate : peerCertificates) {
        if (!(peerCertificate instanceof X509Certificate)) {
            continue;
        }
        final X509Certificate peerX509Cerificate = (X509Certificate) peerCertificate;
        if (peerX509Cerificate.getBasicConstraints() != -1) {
            continue;
        }
        return peerX509Cerificate;
    }
    return null;
}