Backporting Android N Network Security Configuration

The N Developer Preview gave us the network security configuration feature. This makes it rather easy to:

  • Use self-signed certificates for your HTTPS requests, such as for debug builds
  • Supporting unusual certificate authorities, ones that Android itself lacks support for
  • Limiting HTTPS requests to a specific authority, such as tying requests to your server to an authority that you use, to help reduce the odds that someone will be able to generate fraudlent certificates and implement a Martian-in-the-middle (MITM) attack
  • Going one step further and pinning your HTTPS requests to a specific certificate
  • And so on

The v24 edition of the Android Support Library does not appear to contain a backport of network security configuration. With luck, someday, it will have one.

In the meantime, though, I backported it myself.

The CWAC-NetSecurity library is the home of this backport. It uses the NDP4 code from the AOSP for the network security configuration implementation, with minor adjustments to get it to build going back to API Level 17 (Android 4.2). Adding it to your project is a matter of:

  • Getting the native network security configuration working on an Android N test environment
  • Adding the CWAC-NetSecurity library to your project
  • Adding a few lines of code to configure OkHttp3 or HttpURLConnection to apply the network security configuration rules

Along the way, I added a few more options, such as the ability to choose the configuration to use on the fly, rather than have to use the one defined in the manifest, as the native implementation requires.

CWAC-NetSecurity is optimized for use with OkHttp3. Some network security configuration features are available to HttpURLConnection, and there are instructions for building bridges to other HTTP client APIs. Or, use the backport directly, bypassing my TrustManagerBuilder wrapper.

TrustManagerBuilder had resided in the CWAC-Security library. I moved it into CWAC-NetSecurity, deprecating the version in CWAC-Security.

Until Android N transmogrifies into a nougat-flavored Android 7.0, CWAC-NetSecurity is in a pre-release state. I will upgrade CWAC-NetSecurity to use newer AOSP code as it is released, such as when the AOSP code for Android 7.0 ships. A table in the project README tracks library versions and corresponding AOSP code bases

Bug reports are welcome, if I can reproduce the bugs. :-)

Want an expert opinion on your Android app architecture decisions? Perhaps Mark Murphy can help!