CodeBlanks Logo Icon CodeBlanks

Certificate pinning

Learn certificate pinning.

What is certificate pinning?

Certificate pinning means the app trusts only specific SSL certificates. Normally the device's certificate store is trusted; but this is open to man-in-the-middle (MITM) attacks. With pinning the app accepts only your server's certificate.

In React Native it is done with TrustKit (iOS) and Network Security Config (Android). A certificate fingerprint (SHA-256) is embedded in the code. If the server carries this fingerprint the request passes; otherwise it is rejected. This stops someone from stepping in and listening to traffic. If the pin is not updated the app breaks when the certificate renews; that is why giving a backup pin is a good practice.

Network security config

On Android pinning is done with network_security_config.xml. This file defines a domain and one or more pins. A pin is the SHA-256 fingerprint of the certificate.

Example skeleton: <domain-config><domain includeSubdomains="true">api.example.com</domain><pin-set><pin digest="SHA-256">...</pin></pin-set></domain-config>. includeSubdomains also covers subdomains. If multiple pins are given in pin-set they serve as backup pins. This file is linked in AndroidManifest.xml with the android:networkSecurityConfig attribute.

Practice Write a pin configuration

Write a network_security_config.xml skeleton. The root is a <network-security-config> tag. Inside it have a <domain-config>, inside that a <pin-set> and a <pin> tag. The <pin> tag carries a digest="SHA-256" attribute.

Starter code

App.js
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <!-- add domain-config, pin-set and pin tags here -->
</network-security-config>

Sample solution

App.js
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <domain-config>
    <domain includeSubdomains="true">api.example.com</domain>
    <pin-set>
      <pin digest="SHA-256">abcdef1234567890</pin>
    </pin-set>
  </domain-config>
</network-security-config>

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 The pinning algorithm

Question
"pinningAlgorithm": "____"
Answer
"pinningAlgorithm": "sha256"

Explanation: sha256 is the common algorithm for pinning.

2 What does certificate pinning stop?

App.js
MITM attack
  • A man in the middle attack Correct answer
  • A memory leak
  • Battery drain
  • A screenshot

Explanation: Pinning stops a listener stepping in the middle.

3 Match each piece to its role

Term Meaning
pin-set Pin set
SHA-256 Fingerprint
domain-config Domain block
TrustKit iOS pinning

All lessons in Expert