Android SPKI Pinning with TrustKit

Introduction

In this blog post, I will demonstrate how to perform SPKI (Subject Public Key Info) Pinning in an Android Application using TrustKit – a pinning library for Android.

Pinning Approaches

One of the most common approaches for pinning in a mobile app is to store the certificate in storage. However, when server certificates are rotated, a new update to the application would likely need to be pushed out since the certificate in the application is no longer valid, possibly preventing use of the app. As rotation is a reoccurring process, it’s cumbersome to pin the whole certificate in the app.

However, since the key pair used to generate certificates are usually the same, you can simply pin the SPKI Fingerprint of the x509 certificate instead. This approach will allow you to still perform pinning without the maintenance of having to push out new application updates when the certificates expire. Another advantage of using this approach is the anonymization of the certificate information as it’s being cloaked by a one-way hash function.

Pinning in Android N

Starting with Android N (API 24), there is a simplified way to specify pin sets in XML with a Network Security Configuration file. In this file, you can specify the domains you want to pin against. The pins should be defined as a Base64 encoded SPKI Fingerprint.

<network-security-config>
 <domain includeSubdomains="true">google.com</domain>
  <pin-set>
   <pin digest="SHA-256">GYK+80ic2IxHxZ+KYREJBTEZSmb90DyBKsn0UXOJ1EA=</pin>
  </pin-set>
 </domain-config>
</network-security-config>

Pinning with TrustKit

TrustKit is an Open Source library that provides the key benefit of allowing Android N style pinning to work on lower API levels. TrustKit supports Android N style pinning with API Level 17 and higher.

Installing

To add the TrustKit library to your project, reference the TrustKit library in your build.gradle file.

dependencies {
    compile 'com.datatheorem.android.trustkit:trustkit:1.0.1@aar'
}

Configuration

Create an XML file to hold your configuration under res/xml/network_security_config.xml.

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="false">
        <domain includeSubdomains="true">google.com</domain>
        <pin-set>
            <pin digest="SHA-256">GYK+80ic2IxHxZ+KYREJBTEZSmb90DyBKsn0UXOJ1EA=</pin>             
            <pin digest="SHA-256">XAoDAV3WG9IKcu0YJ1ZVTuEVqdcglfiQRqmfy3+ieoc=</pin>
        </pin-set>
        <trustkit-config enforcePinning="true"></trustkit-config>
    </domain-config>
</network-security-config>

Referencing

The next step is to reference the network_security_config.xml in your AndroidManifest.xml.

<application
....
android:networkSecurityConfig="@xml/network_security_config"
</application>

The last step required is to initialize TrustKit with the Network Security Configuration XML file in your code. It’s important that TrustKit is only initialized once.

public class SecureApplication extends Application {
    @Override
    public void onCreate() {
        ...
        TrustKit.initializeWithNetworkSecurityConfiguration(this, R.xml.network_security_config);
    }
...
}

Usage

Now that TrustKit has been configured and initialized, we are now able to perform SSL pinning using OkHttp.

public Call createRequest(okhttp3.Callback callback) { 

URL url = new URL("https://www.google.com"); 
String host = url.getHost(); 
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); 

SSLSocketFactory sslSocketFactory = TrustKit.getInstance().getSSLSocketFactory(host); 
X509TrustManager trustManager = TrustKit.getInstance().getTrustManager(host); 
connection.setSSLSocketFactory(sslSocketFactory); 

OkHttpClient client = new OkHttpClient().newBuilder() 
.sslSocketFactory(sslSocketFactory, trustManager) 
.build(); 

Request request = new Request.Builder() 
.url(url) 
.build(); 

Call call = client.newCall(request); 
call.enqueue(callback); 

return call; 

}

Once we have created a sample network request, we can add a check for certificate errors in our OkHttp callback response.

if (error.getCause().toString().contains("Certificate validation failed") ||
 error.getCause().toString().contains("Pin verification failed")) {
  // provide UI indication of an insecure connection
 }

Lastly, we provide some feedback to the user if there are certificate verification errors.

Conclusion

As can be seen in this post, TrustKit is a very useful library to perform pinning on lower API levels whilst still keeping the same configuration interface as Android N’s pinning. Using the SPKI for pinning also reduces the overheads with certificate management in mobile applications and can enhance security using the anonymized certificate information.

For more information and examples, check out the Feedhenry Secure Android Template.


Red Hat Mobile Application Platform is available for download, and you can read more at Red Hat Mobile Application Platform.

Join the Red Hat Developer Program (it’s free) and get access to related cheat sheets, books, and product downloads.

Share