Certificate Pinning
TLS certificate validation asks one question: was this certificate issued, for this name, by any CA the device trusts? On a phone that set of CAs is large, and it can grow: a user can install a CA to debug their traffic, a company profile can add one, malware or a malicious "Wi-Fi configuration" can trick a user into adding one. Any of them makes a machine in the middle pass validation. Pinning adds a second question: is one of these specific keys in the chain? For an app that talks only to its own backend, and especially one that controls devices in people's homes, that turns "any trusted CA" into "our CA". This lesson computes pins, implements the pinning decision, and covers the operational risk that makes pinning dangerous when done carelessly.
What is pinned
- The SPKI (SubjectPublicKeyInfo: the public key with its algorithm), hashed with SHA-256 and Base64-encoded, is the usual pin:
sha256/…. Pinning the key rather than the whole certificate lets the certificate be renewed with the same key. - Which certificate: the leaf (tightest, but every key change of the server breaks the app), or an intermediate/CA key (survives leaf renewals, still excludes every other CA). Most apps pin the issuing CA or their own private CA, plus a backup pin.
- Backup pins: at least one pin of a key that is not in use yet (a spare CA or leaf key kept offline), so the server can switch keys without breaking installed apps.
Computing pins
In the sandbox, OpenSSL computes the pins of the lab sample certificates: extract the public key, convert it to DER (that is the SPKI), hash with SHA-256, Base64-encode. The sample keys are fixed lab keys, so the pins are stable:
S=/opt/sec-samples/pki
for c in lab.test ca; do
printf '%-9s sha256/' "$c"
openssl x509 -in $S/$c.crt -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64
done
openssl x509 -in $S/lab.test.crt -noout -subject -issuerlab.test sha256/i4MkChDHQNOGnXYmfxxCOBwA0l4KXJN8W5R9+shLHN0=
ca sha256/EFAYMt5700h2rQLdhNIkIsz+ytNSMgKJgrh8c2s0MfA=
subject=C = XX, O = ExcelTAD Lab, OU = Web, CN = lab.test
issuer=C = XX, O = ExcelTAD Lab, CN = ExcelTAD Lab Root CA
The pinning decision
The program builds a small PKI with fixed Ed25519 keys: a public root, the lab's issuing CA, the API's leaf certificate; a debugging proxy's CA that the user has installed on the device; and a 2027 leaf with a new key. It then connects three times with three policies: no pinning, a leaf pin, and a CA pin with a backup.
import base64, datetime, hashlib
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
def key(label): # deterministic lab keys so the pins below are stable; real keys come from a secure generator
return Ed25519PrivateKey.from_private_bytes(hashlib.sha256(label.encode()).digest())
def name(cn): return x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, cn)])
def cert(subject, subject_key, issuer, issuer_key, ca=False):
return (x509.CertificateBuilder().subject_name(name(subject)).issuer_name(name(issuer))
.public_key(subject_key.public_key()).serial_number(0x4001)
.not_valid_before(datetime.datetime(2026, 1, 1)).not_valid_after(datetime.datetime(2028, 1, 1))
.add_extension(x509.BasicConstraints(ca=ca, path_length=None), critical=True)
.sign(issuer_key, None))
def pin(c): # SPKI pin as used by OkHttp and Android's network security config: base64(SHA-256(SubjectPublicKeyInfo))
spki = c.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo)
return "sha256/" + base64.b64encode(hashlib.sha256(spki).digest()).decode()
def signed_by(c, issuer):
try:
issuer.public_key().verify(c.signature, c.tbs_certificate_bytes); return c.issuer == issuer.subject
except Exception:
return False
root, inter = key("public root"), key("lab issuing CA 2026")
ROOT = cert("Public Root CA", root, "Public Root CA", root, ca=True)
INTER = cert("Lab Issuing CA 2026", inter, "Public Root CA", root, ca=True)
api_key_2026 = key("api.lab.test 2026")
chains = {
"normal connection": [cert("api.lab.test", api_key_2026, "Lab Issuing CA 2026", inter), INTER],
"proxy with a user-added CA": None,
"new leaf key, same CA (2027)": [cert("api.lab.test", key("api.lab.test 2027"), "Lab Issuing CA 2026", inter), INTER],
}
proxy = key("debug proxy CA")
PROXY_CA = cert("Debug Proxy CA", proxy, "Debug Proxy CA", proxy, ca=True)
chains["proxy with a user-added CA"] = [cert("api.lab.test", key("proxy leaf"), "Debug Proxy CA", proxy), PROXY_CA]
TRUSTED = [ROOT, PROXY_CA] # the OS trusts the public root, and the user has installed the proxy's CA
LEAF_ONLY_PINS = {pin(chains["normal connection"][0])}
CA_PINS = {pin(INTER), "sha256/BACKUP+pin+of+a+spare+CA+key+kept+offline+0000="}
print("intermediate pin:", pin(INTER))
def connect(chain, pins):
leaf, *rest = chain
path = [leaf] + rest
if not all(signed_by(a, b) for a, b in zip(path, path[1:])) or not any(signed_by(path[-1], t) or path[-1] == t for t in TRUSTED):
return "FAIL (untrusted)"
if pins and not any(pin(c) in pins for c in path):
return "FAIL (no pin matches)"
return "OK"
for label, chain in chains.items():
print(f"{label:29} no pins: {connect(chain, set()):4} | leaf pin: {connect(chain, LEAF_ONLY_PINS):21} | CA pin: {connect(chain, CA_PINS)}")intermediate pin: sha256/Dh5PsS+RiAL+1sQalQRfHGqvT+7evm9dppR6axkbJUg=
normal connection no pins: OK | leaf pin: OK | CA pin: OK
proxy with a user-added CA no pins: OK | leaf pin: FAIL (no pin matches) | CA pin: FAIL (no pin matches)
new leaf key, same CA (2027) no pins: OK | leaf pin: FAIL (no pin matches) | CA pin: OK
- Without pins, the proxy passes: its CA is in the trust store, so the platform accepts its certificate for
api.lab.test. That is correct behaviour for a browser and the reason pinning exists for apps. - With either pin, the proxy fails: none of its keys is pinned.
- The leaf pin breaks the app when the server rotates its key in 2027, although nothing malicious happened. The CA pin survives, because the new leaf comes from the same issuing CA.
The real implementations follow the same logic: on Android a <pin-set> in the Network Security Configuration (with an expiration date after which pins are ignored) or OkHttp's CertificatePinner; on iOS NSPinnedDomains in Info.plist (iOS 14+) or a URLSession delegate that checks the SPKI after the system's evaluation succeeds. Pins add to normal validation; they never replace it.
<network-security-config>
<domain-config>
<domain includeSubdomains="false">api.lab.test</domain>
<pin-set expiration="2027-06-30">
<pin digest="SHA-256">Dh5PsS+RiAL+1sQalQRfHGqvT+7evm9dppR6axkbJUg=</pin> <!-- Lab Issuing CA 2026 -->
<pin digest="SHA-256">BACKUP+pin+of+a+spare+CA+key+kept+offline+0000=</pin> <!-- spare key, offline -->
</pin-set>
</domain-config>
</network-security-config>When to pin, and when not
| Pin | Don't pin |
|---|---|
| the app talks to your own API domains, which you control end to end | domains of third parties (CDNs, analytics, payment providers) whose keys you don't control |
| high-value actions: controlling locks, payments, health data (MASVS-NETWORK-2, MAS-L2) | when you can't commit to a key-rotation process |
| you can ship app updates before the pin expiry | browsers or apps that must work behind corporate inspection proxies by design |
Pinning protects against a mis-issued or rogue CA and against user-installed CAs. It doesn't help if the device itself is compromised (an attacker with root can patch the app's check), which is why pinning is a network control, not an anti-tampering one.
How pinning problems are detected
- Testing on a test device with an intercepting proxy whose CA is installed: a pinned app must refuse the connection, and the failure must be visible (logged, reported to the backend) rather than silently retried without pins (mobile app testing).
- Code review: custom trust managers or
URLSessiondelegates that accept everything (checkServerTrusteddoing nothing,completionHandler(.useCredential, …)without evaluation) are critical findings, far worse than no pinning. - Operational checks: pin expiry dates, presence of a backup pin, documented rotation; monitoring of pin-failure reports after server changes.
How it is fixed and kept safe
- Pin your own CA or intermediate key plus at least one offline backup; set an expiry.
- Plan rotation: introduce the new key's pin in an app release months before the server switches.
- Keep normal validation on; pins only narrow it. Use the platform mechanisms, not custom trust code.
- Allow testers to intercept debug builds through
debug-overrides, never by weakening release builds.
Pitfalls
- Pinning a leaf certificate without a backup: the next certificate renewal with a new key takes the app offline for every user.
- A trust manager that "pins" but accepts the chain when the pin check throws an exception.
- Pinning third-party domains whose keys change without notice.
Practice
1. In the program, what happens if the server moves to a new issuing CA in 2027 and the app only has CA_PINS?
The new chain doesn't contain the pinned intermediate key, and the backup pin isn't the new CA's key, so the connection fails. The backup pin must be the spare key that the server will actually move to; that's why it has to be planned, not invented.
2. Why are pins computed over the SPKI rather than the whole certificate?
A certificate changes at every renewal (dates, serial, signature) even when the key stays the same; the SPKI stays constant as long as the key does. Pinning the key lets certificates be renewed without app updates.
3. A colleague proposes disabling certificate validation in release builds "so our QA proxy works". What do you answer?
That makes every user's traffic interceptable by anyone on the network: a critical finding (MASVS-NETWORK-1). QA uses debug builds with debug-overrides trusting the proxy's CA, and release builds keep full validation and pins.
Test yourself
What does an SPKI pin hash?
- The whole certificate
- The certificate's public key with its algorithm (SubjectPublicKeyInfo)
- The domain name
- The private key
Why did the proxy connection pass without pins?
- Its certificate was self-signed
- Its CA was installed in the device's trust store
- TLS was off
- The proxy knew the server's key
What broke the app with a leaf pin in the program?
- An attack
- A routine server key rotation
- An expired CA
- A wrong domain
Which is the worst 'pinning' implementation?
- Pinning the intermediate with a backup
- A custom trust manager that accepts every certificate
- Using the network security config
- Pinning with an expiry date