Network security and pinning
Why it matters
- A mis-issued or rogue certificate from a trusted CA can let an attacker intercept TLS. Pinning the server's public key makes such a certificate useless against your app.
- A single pin with no backup turns a routine certificate change into an outage for every installed version. Interviewers probe whether you know this failure mode and how to avoid it.
- For apps targeting API 28 (Android 9) or higher, cleartext HTTP is blocked by default, yet teams still re-enable it by accident. Knowing the Network Security Configuration (NSC) XML keeps that from reaching production.
- Some security reviews and regulated apps ask for pinning. A senior engineer should be able to explain how it works and when its operational risk outweighs the benefit.
The simple explanation
- A pin is a fingerprint of the server's public key, stored inside your APK.
- During the TLS handshake the app compares the fingerprints in the server's certificate chain with its stored list.
- No match means the connection is refused, even if the chain is otherwise valid.
- Think of a hotel keycard: the door checks the chip ID, not only the printed room number.
- If the hotel re-issues every keycard and the door knows only one ID, you are locked out. That is the bricking risk of a pin with no backup.
What is Network Security Configuration in Android? It is an XML file (res/xml/network_security_config.xml, referenced from the manifest) that lets you set an app's network security rules without code: whether cleartext HTTP is allowed, which certificate authorities are trusted, which public keys are pinned for which domains, and extra trust for debug builds only. It is available from API 24.
During a TLS handshake the server presents an X.509 certificate chain, and Android checks it against the system trust anchors (the CA certificates installed with the OS). Certificate pinning adds a second check: the base64 SHA-256 hash of a certificate's public key (its DER-encoded SubjectPublicKeyInfo) must match one of your stored pins, for at least one certificate in the chain.
| Layer | Mechanism | Scope | Expiry |
|---|---|---|---|
| Platform | <pin-set> and <pin> in the NSC XML | Connections that use the platform's default trust manager, such as HttpsURLConnection and OkHttp | expiration attribute on <pin-set> |
| Library | OkHttp CertificatePinner | Only the OkHttpClient it is set on (and clients derived from it) | None built in; you ship new pins in an app update |
In NSC the <pin> element holds the base64 hash with a digest="SHA-256" attribute. In OkHttp the pin is written as sha256/ followed by the base64 hash.
The NSC file is wired in with android:networkSecurityConfig="@xml/network_security_config" on <application>. A <debug-overrides> block applies only when the app is debuggable, so it can trust user-installed CAs (Charles, mitmproxy) without changing release behaviour.
The main risk: if you pin a single key and the server's certificate is replaced with one that uses a different key, or comes from a different CA, every installed app rejects the server until users update. Always ship a backup pin (a spare key you keep offline, or the key of a CA you can switch to) and set an expiration on the NSC pin-set, after which the app falls back to normal certificate validation.
Notes
- For apps targeting API 28+,
cleartextTrafficPermitteddefaults to false: plainhttp://requests fail unless you allow them in NSC, ideally for one<domain-config>only. - A pin is the base64 SHA-256 of the DER-encoded SubjectPublicKeyInfo, not a hash of the whole certificate. Renewing a certificate with the same key keeps the pin valid.
- Ship at least two pins per host: the key in use now and a backup. Android's NSC documentation explicitly recommends a backup pin.
<pin-set expiration="2027-06-30">(formatyyyy-MM-dd) disables pinning for that domain after the date. OkHttp'sCertificatePinnerhas no expiry, so old builds keep enforcing old pins.<debug-overrides>is honoured only whenandroid:debuggableis true. Release builds ignore it.- When OkHttp pin verification fails the call throws
SSLPeerUnverifiedException, a subclass ofSSLExceptionand therefore ofIOException. - Without
android:networkSecurityConfigon<application>, the XML file does nothing. <domain includeSubdomains="true">api.example.com</domain>also coversv2.api.example.com. Without the attribute only the exact host matches.- Pinning a CA intermediate or root key instead of your own leaf key trades some protection for fewer outages: you survive leaf key changes, but any certificate that CA issues for your domain passes.
- NSC and OkHttp
CertificatePinnerare independent. If you configure both, both must pass. Libraries with their own TLS stack (for example native code) may ignore NSC entirely.
Code example
This Kotlin snippet builds an OkHttp client with two pins for one host (the current key and a backup), the kind of function you would put in a DI module. The matching NSC XML is in the comment below it.
import okhttp3.CertificatePinner
import okhttp3.OkHttpClient
import java.util.concurrent.TimeUnit
// Two pins per host. The connection succeeds if any certificate in the
// server's chain matches either pin, so a planned move to the backup key
// does not break installed apps.
fun buildPinnedHttpClient(): OkHttpClient {
val pinner = CertificatePinner.Builder()
.add(
"api.example.com",
"sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", // current key
"sha256/BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=", // backup key
)
.build()
return OkHttpClient.Builder()
.certificatePinner(pinner)
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
}
// Matching NSC (res/xml/network_security_config.xml):
// <network-security-config>
// <domain-config>
// <domain includeSubdomains="true">api.example.com</domain>
// <pin-set expiration="2027-06-30">
// <pin digest="SHA-256">AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</pin>
// <pin digest="SHA-256">BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=</pin>
// </pin-set>
// </domain-config>
// <debug-overrides>
// <trust-anchors>
// <certificates src="user" />
// </trust-anchors>
// </debug-overrides>
// </network-security-config>- Two pins per host means the server team can move to the backup key without breaking installed apps.
- In NSC, the
<pin>value is the bare base64 hash withdigest="SHA-256"; thesha256/prefix is OkHttp syntax only. expirationon the NSC<pin-set>turns pinning off after the date and falls back to the normal trust anchors. OkHttp'sCertificatePinnerhas no equivalent.debug-overrideswithsrc="user"lets developers use Charles or mitmproxy in debug builds without changing release behaviour.
Run the idea in plain Kotlin
data class PinEntry(val domain: String, val pins: List<String>, val expired: Boolean = false)
fun main() {
val pinStore = listOf(
PinEntry("api.example.com", listOf("sha256/AAA", "sha256/BBB")),
PinEntry("cdn.example.com", listOf("sha256/CCC")),
PinEntry("old.example.com", listOf("sha256/OLD"), expired = true)
)
val tests = listOf(
Triple("api.example.com", "sha256/BBB", "backup pin match"),
Triple("cdn.example.com", "sha256/DDD", "no pin match"),
Triple("api.example.com", "sha256/AAA", "primary pin match"),
Triple("old.example.com", "sha256/NEW", "expired pin-set")
)
for ((domain, presented, label) in tests) {
val entry = pinStore.find { it.domain == domain }
val result: String
if (entry == null) {
result = "no pin entry, allow (no pinning configured)"
} else if (entry.expired) {
result = "pin-set expired, fall back to system trust anchors"
} else if (entry.pins.contains(presented)) {
result = "pin verified, connection allowed"
} else {
result = "pin mismatch, connection REJECTED"
}
println("[" + label + "] " + domain + " -> " + result)
}
}Expected output:
[backup pin match] api.example.com -> pin verified, connection allowed
[no pin match] cdn.example.com -> pin mismatch, connection REJECTED
[primary pin match] api.example.com -> pin verified, connection allowed
[expired pin-set] old.example.com -> pin-set expired, fall back to system trust anchors
In production
- The team pinned only the leaf key's hash in OkHttp's
CertificatePinner, with no backup pin. - The server's certificate was replaced with one that used a new key pair, so the leaf key hash changed.
- From that moment every installed version failed its API calls with
SSLPeerUnverifiedException, and crash and error reporting filled with the same failure. - The only fix was a new release, and users stayed broken until they updated.
- Added a backup pin for a spare key held offline, so the next key change could use it.
- Agreed a process with the server team: any certificate change is checked against the app's pins before it is deployed.
- Added a scheduled CI job that computes the live server's key hashes and fails if none matches the pins in the current release.
- Moved the pins to NSC with an
expirationdate, so a forgotten old build stops pinning instead of failing forever.
- A developer set
cleartextTrafficPermitted="true"on<base-config>to test against a local HTTP server and committed it, together with anhttp://base URL in a build flavor. - The flavor was used for a beta release, so its API calls went over plain HTTP. Anyone on the same network could read requests, including the session token in the headers.
- A security review caught it; nothing crashed, which is why it went unnoticed.
- Removed the attribute from
<base-config>; for apps targeting API 28+ the default is alreadyfalse. - Kept local HTTP testing in a debug-only NSC file under
src/debug/res/xml, scoped to a<domain-config>for the local host. - Made Android Lint's
InsecureBaseConfigurationcheck an error for release builds, and added a unit test that asserts every base URL starts withhttps://.
Common mistakes
- One pin with no backup. Any change to the pinned key breaks every installed app. Always include a backup pin.
- Expecting a pin to change on every renewal. A pin is a hash of the public key. Renewing with the same key keeps it; a new key or a new CA changes it. Know which one your server team plans.
- Forgetting
<debug-overrides>. Developers cannot inspect traffic with Charles or mitmproxy, which leads to workarounds (such as trusting user CAs in<base-config>) that leak into release. - Pinning only in one OkHttp client. Another
OkHttpClient,HttpsURLConnectionor an SDK's own client is not covered. NSC pins cover every connection that uses the platform trust manager. - No expiry and no monitoring. Without an NSC
expirationand a check that the live server still matches the pins, the first sign of a problem is users failing to connect. - Setting
cleartextTrafficPermitted="true"globally. It allows HTTP to every host. Scope it to a<domain-config>for the one host that needs it, or remove it.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is certificate pinning and what is the main operational risk?”
“How do you configure Network Security Configuration in an Android app?”
“How do you test pinned connections in a debug build without weakening release?”
“When would you use OkHttp CertificatePinner instead of NSC, or both?”
Quiz
For an app targeting API 28 or higher, what is the default value of cleartextTrafficPermitted?
What does an OkHttp pin string like sha256/ABC123... represent?
What happens when the expiration date on an NSC pin-set passes?
Which exception does OkHttp throw when no pinned hash matches the server's certificate chain?
0 of 4 answered
Mini task
Add certificate pinning to an existing OkHttp client (15 min)
-
Get the live pin. Run
openssl s_client -connect api.example.com:443 -servername api.example.com 2>/dev/null | openssl x509 -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl base64. For the intermediate certificate, add-showcerts, save the second certificate in the output to a file, and run the same pipeline fromopenssl x509 -in intermediate.pem -pubkey -nooutonward. -
Create the pinner. In your DI module, build a
CertificatePinnerwith two pins:.add("api.example.com", "sha256/" + currentPin, "sha256/" + backupPin). Pass it toOkHttpClient.Builder().certificatePinner(pinner)for release builds only. -
Add the NSC file. Create
res/xml/network_security_config.xmlwith a<domain-config>forapi.example.com, a<pin-set expiration="...">about 12 months out with both pins as<pin digest="SHA-256">, and a<debug-overrides>block with<certificates src="user" />. Reference it inAndroidManifest.xml. -
Verify rejection. In a release-like build, temporarily replace both pins with
sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=. Confirm the API call fails withSSLPeerUnverifiedExceptionin logcat. Revert. -
Verify proxy testing. Install the debug build, start Charles or mitmproxy, and confirm the call succeeds. Install a release build signed for testing and confirm the same call fails through the proxy.
Done when: the debug build connects through a proxy, the release build does not, and a wrong pin produces SSLPeerUnverifiedException.