0

I am new to android. I have written code for ios and want similar algo in android.

Here is the scene. I have 2 types of servers- 1. with self signed cert 2. with signed cert.

Now in ios I use following steps to decide whether it is signed or not.

STACK_OF(X509) *stX509Certificate = SSL_get_peer_cert_chain(ssl); int cert_num = sk_X509_num(stX509Certificate);

CFMutableArrayRef certArray = CFArrayCreateMutable(NULL, cert_num, NULL);

for (int i = 0; i < cert_num; i++) {
    unsigned char *raw = NULL;

    X509 *x509Certificate = sk_X509_value(stX509Certificate, i);
    int rawlen = i2d_X509(x509Certificate, &raw);
    CFDataRef cfcert = CFDataCreate(NULL, raw, rawlen);
    free(raw);

    SecCertificateRef secCertRef = SecCertificateCreateWithData(NULL, cfcert);
    CFRelease(cfcert);

    CFArrayAppendValue(certArray, secCertRef);
}

CFStringRef servAddr = CFStringCreateWithCString(NULL, [[srvSplit objectAtIndex:0] cStringUsingEncoding:NSUTF8StringEncoding], kCFStringEncodingUTF8);
SecPolicyRef secPolRef = SecPolicyCreateSSL(YES, servAddr);
CFRelease(servAddr);

SecTrustRef secTruRef ;
SecTrustResultType secTrustRes;
Boolean isCertTrusted = NO;
if(SecTrustCreateWithCertificates(certArray, secPolRef, &secTruRef) == errSecSuccess) {
    SecTrustSetAnchorCertificatesOnly(secTruRef, NO);
    if (SecTrustEvaluate(secTruRef,&secTrustRes) == errSecSuccess) {
        switch (secTrustRes) {
            case kSecTrustResultInvalid:
            case kSecTrustResultDeny:
            case kSecTrustResultRecoverableTrustFailure:
            case kSecTrustResultFatalTrustFailure:
            case kSecTrustResultOtherError:
                isCertTrusted = NO;
                break;
            case kSecTrustResultUnspecified:
            case kSecTrustResultProceed:
                isCertTrusted = YES;
                break;
        }
    }
}

In android I cant find such TrustEvaluate method. I tried getBasicConstraints and getKeyUsage. But I cant distinguish between signed and other certs.

Please help me.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Durgaprasad
  • 1,910
  • 2
  • 25
  • 44
  • I hope you are aware of what you are trying to do. Hope you have read [The most dangerous code in the world: validating SSL certificates in non-browser software](https://crypto.stanford.edu/~dabo/pubs/abstracts/ssl-client-bugs.html) – Gaurav Singh Faujdar Apr 11 '18 at 17:00

1 Answers1

0

Try this code, it may not similar to your IOS algo but it works fine.

  • Add your self signed certificate in /res/raw
  • First this code checks android system certificates(Trusted credentials) in this case if you are connecting to CA certified server, it verifies your certificate and allows you to connect the server
  • If you are trying to connect self signed server it checks your self signed certificate which is in /res/raw
  • If you are trying to connect self signed server with IP address then your certificate should contain subjectAltName

    public class CheckCertificate{
    
    private static class NewCustomTrustManager implements X509TrustManager{
    
    private X509TrustManager defaultTrustManager;
    private X509TrustManager localTrustManager;
    public NewCustomTrustManager(KeyStore localKeyStore) throws KeyStoreException {
        try {
            this.defaultTrustManager = createNewTrustManager(null);
            this.localTrustManager = createNewTrustManager(localKeyStore);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    private X509TrustManager createNewTrustManager(KeyStore store) throws NoSuchAlgorithmException, KeyStoreException {           
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();            
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(store);            
        TrustManager[] trustManagers = tmf.getTrustManagers();
        return (X509TrustManager) trustManagers[0];
    }
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        try {
            //Checks system certificate
            defaultTrustManager.checkServerTrusted(chain, authType);
        } catch (CertificateException ce) {
            //Checks your self signed certificate
            localTrustManager.checkServerTrusted(chain, authType);
        }
    }
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }
    
    
    
    @Override
    public X509Certificate[] getAcceptedIssuers() {
        X509Certificate[] first = defaultTrustManager.getAcceptedIssuers();
        X509Certificate[] second = localTrustManager.getAcceptedIssuers();
        X509Certificate[] result = Arrays.copyOf(first, first.length + second.length);
        return result;
      }
     }
     public static void setCustomCertificate(Context cn) {
    
    try {
        // Load CAs from an InputStream
        // (could be from a resource or ByteArrayInputStream or ...)
        CertificateFactory cf = CertificateFactory.getInstance("X.509");          
        InputStream caInput = new BufferedInputStream(cn.getResources().openRawResource(R.raw.apache_25));
    
        try {
            ca = cf.generateCertificate(caInput);
    
        }catch (Exception e){
            e.printStackTrace();
        }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("cacertificate", ca);
    
        // Create a TrustManager that trusts the CAs in our KeyStore and system CA
        NewCustomTrustManager trustManager = new NewCustomTrustManager(keyStore);
    
        // Create an SSLContext that uses our TrustManager
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new TrustManager[]{trustManager}, null);
    
        // Tell the URLConnection to use a SocketFactory from our SSLContext
        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    }
    
    }
    
sagar
  • 76
  • 8