Tuesday, March 31, 2015

SSL Implementations for Android Application


When we try to access a Web Service hosted on HTTPS and is secured over SSL, Host Verification and/or Peer Verification are to be handled in our application



SSL implementation in Android, 4 key points you have to keep in mind - 

1. Creating keystore
2. Create a Class to Use Our Store for HTTPS Connections
3. Copy mystore File
4. Process for Host Verification





Android has security features built into the operating system that significantly reduce the frequency and impact of application security issues. The system is designed so you can typically build your apps with default system and file permissions and avoid difficult decisions about security.


Most of the security implementations - key points


  • The Android Application Sandbox, which isolates your app data and code execution from other apps.
  • An application framework with robust implementations of common security functionality such as cryptography, permissions, and secure IPC.
  • Technologies like ASLR, NX, ProPolice, safe_iop, OpenBSD dlmalloc, OpenBSD calloc, and Linux mmap_min_addr to mitigate risks associated with common memory management errors.
  • An encrypted filesystem that can be enabled to protect data on lost or stolen devices.
  • User-granted permissions to restrict access to system features and user data.
  • Application-defined permissions to control application data on a per-app basis.
Android supports the java.net and org.apache packages to access Web Services. 
I use Apache packages as I find them more useful and easier than using Java packages.

Use  Bouncy Castle lib for creating keystore or you can use java to generate keystore.

SSL implementation in Android, 4 key points you have to keep in mind - 

1. Creating keystore
2. Create a Class to Use Our Store for HTTPS Connections
3. Copy mystore File
4. Process for Host Verification

How to configure Boucy Castle - 

  • Download and unzip Bouncy Castle in a proper location 
  • Add the .jar file to the class path. 



Lets discuss step by step by step procedure for SSL implementation for Android 

1. Creating keystore

Open cmd, go to the application folder, and type the following command:

keytool -import -v -trustcacerts -alias 0 -file mycertificate.crt 
  -keystore res/raw/mystore.bks -storetype BKS -provider 
  org.bouncycastle.jce.provider.BouncyCastleProvider -storepass mypassword


  • file parameter points to your certificate file that you want to add
  • keystore => gives the store name that you want to give
  • storepass => password to access the keystore

2. Create a Class to Use Our Store for HTTPS Connections

To enable SSL for Android, to use the store that we created above, we have to create a custom Apache DefaultHttpClient that knows to use the store for HTTPS requests.


public class MyHttpClient extends DefaultHttpClient {

    final Context context;
    public MyHttpClient(Context context) {
        this.context = context;
    }

    @Override
    protected ClientConnectionManager createClientConnectionManager {
        SchemeRegistry registry = new SchemeRegistry();
        registry.register("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register("https", newSslSocketFactory(), 443));
        return new SingleClientConnManager(getParams(), registry);
    }

    private SSLSocketFactory newSslSocketFactory() {
        try {
             KeyStore trusted = KeyStore.getInstance("BKS");
             InputStream in = context.getResources().openRawResource(R.raw.mystore);
             try {
                 trusted.load(in, "mypassword".toCharArray());
             }
             finally {
                  in.close();
             }

             SSLSocketFactory mySslFact = new SslFactory(trusted);
             //mySslFact.setHostNameVerifier(new MyHstNameVerifier());
             return mySslFact;
         } catch(Exception e) {
         throw new AssertionError(e);
        }
    }
}


This code helps us to accept a server certificate and sets the certificate for verification. You can see how we are using our -storename parameter "BKS" to get the instance of the KeyStore, loading the certificate filemystore from R.raw, and setting its password that was used while adding it to the store.


3. Copy mystore File

Most important points for SSL implementation in Android, keep generated file in raw folder, steps are - 

  • Import the generated mystore.bks file to the res/raw folder. 
  • So our above class can access it from there.
  • With this, SSL Peer Verification is taken care of. 
  • We just have to create an instance of MyHttpClient in place ofDefaultHttpClient and Peer Verification will be handled by itself.

4. Process for Host Verification

Android supports only the host/domain via which the web service is being called - if any other host is tried to connect it throws exception. For example, if our application connects to a host, and then tries to connect another host for any reason, Android won't allow to do that. For this to be allowed, we got to set the hostnames that we want to allow the application to access


public class MyHostVerifier extends org.apache.http.conn.ssl.AbstractVerifier {

    String[] allowHost = {"my.ultra.com", "your.ultra.com", "ours.ultra.com"}; 

    @Override

    public void verify(String host, String[] cns, 
 String[] subjectAlts) throws SSLException {
        // If the host is any the hosts to be allowed, return, else throw exception 
        for (int i=0; i < allowHost.length; i++) {
             if (host == allowHost[i])
                return;
        }
         throw SSLException;
    }
}


License - 

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)