Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android 2.3.x javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

Tags:

android

ssl

I am receiving this error only on (maybe some) 2.3.x devices. it works for any other devices running an Android version above that.

Here is my HTTPRequestController:

public class HttpRequestController {

private final static String TAG = "HttpRequestController";

private static HttpRequestController instance;

public enum Method {
    PUT, POST, DELETE, GET
}

private HttpRequestController() {

}

public static HttpRequestController getInstance() {
    if (instance == null)
        instance = new HttpRequestController();

    return instance;
}

public String doRequest(String url, HashMap<Object, Object> data,
        Method method, String token) throws Exception {

    InputStream certificateInputStream = null;
    if (MyApplication.PRODUCTION) {
        certificateInputStream = MyApplication.context
                .getResources().openRawResource(R.raw.production_cert);
        LogUtils.log("using production SSL certificate");
    } else {
        certificateInputStream = MyApplication.context
                .getResources().openRawResource(R.raw.staging_cert);
        LogUtils.log("using staging SSL certificate");
    }

    KeyStore trustStore = KeyStore.getInstance("BKS");
    try{
    trustStore.load(certificateInputStream,
            "re3d6Exe5HBsdskad8efj8CxZwv".toCharArray());
    } finally {
        certificateInputStream.close();
    }


    TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
    tmf.init(trustStore);
    LogUtils.log("SSL: did init TrustManagerFactory with trust keyStore");
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);
    LogUtils.log("SSL: did init context with trust keyStore");  


    URL request = new URL(url);
    HttpsURLConnection urlConnection = (HttpsURLConnection) request
            .openConnection();

    LogUtils.log("SSL: did open HttpsURLConnection");   

    urlConnection.setHostnameVerifier(new StrictHostnameVerifier());
    urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setConnectTimeout(15000);
    LogUtils.log("SSL: did set Factory and Timeout.");

    if (method != Method.GET){
        urlConnection.setDoOutput(true);
    }
        urlConnection.setDoInput(true);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Accept", "application/json");

    LogUtils.log("SSL: urlConnection did set request properties.");

    if (token != null) {
        urlConnection.setRequestProperty("Authorization", "Token " + token);
    }
        urlConnection.setRequestMethod(method.toString());
        urlConnection.connect();

        LogUtils.log("SSL: urlConnection did connect.");

    if (method != Method.GET) {
        ObjectMapper mapper = new ObjectMapper();
        String jsonValue = mapper.writeValueAsString(data);
        OutputStream os = urlConnection.getOutputStream();
        os.write(jsonValue.getBytes());
        os.flush();
        LogUtils.log(TAG, "Params: " + jsonValue);
    }

    LogUtils.log(TAG, method.toString() + ": " + url);

    InputStream in = null;
    if (urlConnection.getResponseCode() == 200) {
        in = urlConnection.getInputStream();
    } else {
        in = urlConnection.getErrorStream();
    }
    String response = convertStreamToString(in);

    LogUtils.log(TAG, "Got response : " + url);
    LogUtils.log(TAG, "Response : " + response);

    return response;
}

public String convertStreamToString(InputStream inputStream) {
    BufferedReader buffReader = new BufferedReader(new InputStreamReader(
            inputStream));
    StringBuilder stringBuilder = new StringBuilder();

    String line = null;
    try {
        while ((line = buffReader.readLine()) != null) {
            stringBuilder.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return stringBuilder.toString();
}

public HttpClient retrieveHttpClient() {
    return new MyHttpClient(MyApplication.context);
}

}

When i run the command:

openssl s_client -debug -connect www.mysitedomain.com:443

I get the response:

--
some key stuff 
--
Certificate chain
 0 s:/OU=Domain Control Validated/CN=www.mydomainname.com
   i:/C=BE/O=GlobalSign nv-sa/CN=GlobalSign Domain Validation CA - G2
 1 s:/C=BE/O=GlobalSign nv-sa/CN=GlobalSign Domain Validation CA - G2
   i:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA
 2 s:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA
   i:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA
---
Server certificate
-----BEGIN CERTIFICATE-----
 some more certificate stuff
-----END CERTIFICATE-----

ubject=/OU=Domain Control Validated/CN=www.mydomainname.com
issuer=/C=BE/O=GlobalSign nv-sa/CN=GlobalSign Domain Validation CA - G2
---
No client certificate CA names sent
---
SSL handshake has read 4091 bytes and written 328 bytes
---
New, TLSv1/SSLv3, Cipher is DHE-RSA-AES256-SHA
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
    Protocol  : TLSv1
    Cipher    : DHE-RSA-AES256-SHA
    Session-ID: 57C379C59483809A7FE1BF8E235C5BFA7789E62AAEBCA9BC14B5273F5D1304E7
    Session-ID-ctx: 
    Master-Key: 6FCD498D1294415A42B57420F0C05AB903EF8E56CB6F1530390F73AF5E4CBC22B359D5CDA09811E075A5C598002C380D
    Key-Arg   : None
    Start Time: 1390473282
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)
---

so it returns okay... But it still gives me this error for the 2.3.x devices I tested.

I get an exception after this point:

LogUtils.log("SSL: urlConnection did set request properties.");

Here is the exception:

01-23 10:20:28.459: W/System.err(1623): javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
01-23 10:20:28.459: W/System.err(1623):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:477)
01-23 10:20:28.459: W/System.err(1623):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:328)
01-23 10:20:28.459: W/System.err(1623):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.setupSecureSocket(HttpConnection.java:185)
01-23 10:20:28.459: W/System.err(1623):     at org.apache.harmony.luni.internal.net.www.protocol.https.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:433)
01-23 10:20:28.459: W/System.err(1623):     at org.apache.harmony.luni.internal.net.www.protocol.https.HttpsURLConnectionImpl$HttpsEngine.makeConnection(HttpsURLConnectionImpl.java:378)
01-23 10:20:28.459: W/System.err(1623):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:205)
01-23 10:20:28.459: W/System.err(1623):     at org.apache.harmony.luni.internal.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:152)

The way I am calling this is here:

String response = HttpRequestController
                            .getInstance()
                            .doRequest(ApiUrls.LOGIN, params, Method.POST, null);

It works for any other devices running an Android version above 2.3.x (from what I have tested).

The Android documentation appears to have nothing written on the subject of 2.3 compatibility.

like image 504
jimbob Avatar asked Jan 23 '14 11:01

jimbob


People also ask

What does trust anchor for certification path not found mean?

Trust anchor for certification path not found. That error is usually due to a misconfigured certificate or a misconfiguration with the webserver config files as it relates to certificates… I suggest going to this web page and checking your certificate for issues. https://www.digicert.com/help/

What is trust anchor certificate?

In a PKI, a trust anchor is a certification authority, which is represented by a certificate that is used to verify the signature on a certificate issued by that trust-anchor. The security of the validation process depends upon the authenticity and integrity of the trust anchor's certificate.

What is SSL certificate in Android?

The Secure Sockets Layer (SSL)—now technically known as Transport Layer Security (TLS)—is a common building block for encrypted communications between clients and servers. Using TLS incorrectly might let malicious entities intercept an app's data over the network.


1 Answers

You have to tell the Android system to trust your certificate. Your problem is that Android after 2.3 accepts your certificate because it has it included on the trusted certificates list, but on the previous versions is not included, so, there is the problem.

I recommend you doing like on the Android documentation:

// Load CAs from an InputStream
// (could be from a resource or ByteArrayInputStream or ...)
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// From https://www.washington.edu/itconnect/security/ca/load-der.crt
InputStream caInput = new BufferedInputStream(new FileInputStream("load-der.crt"));
Certificate ca;
try {
    ca = cf.generateCertificate(caInput);
    System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
    caInput.close();
}

// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);

// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);

// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);

// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = new URL("https://certs.cac.washington.edu/CAtest/");
HttpsURLConnection urlConnection =
    (HttpsURLConnection)url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
InputStream in = urlConnection.getInputStream();
copyInputStreamToOutputStream(in, System.out);

I am doing the same, and it is working properly on every devices, with Android 2.3 and below, and the certificate of my site is a private one.

Just try it, and tell me if it is working now.

Hope it helps you!

like image 184
zapotec Avatar answered Nov 02 '22 22:11

zapotec