Network Security

Network Security

1. What Is Network Security?

Android network security protects data exchanged between an Android application and a backend server.

It mainly ensures:

* Confidentiality: Other people cannot read the data.

* Integrity: Data cannot be modified during transmission.

* Authentication: The app verifies that it is communicating with the correct server.

Android App
     |
     | Secure HTTPS connection
     v
Backend Server

---

2. HTTPS

HTTPS means HTTP over TLS.

HTTP defines how requests and responses are exchanged, while TLS protects that communication.

HTTP Request
     |
     v
TLS encryption
     |
     v
Internet
     |
     v
TLS decryption
     |
     v
Backend Server

HTTP vs HTTPS

HTTPHTTPS
Data is not protected by TLSData is protected by TLS
Vulnerable to interceptionHelps prevent interception
Uses http://Uses https://
Not suitable for sensitive APIsRequired for production APIs

Example:

Avoid:
http://api.example.com

Use:
https://api.example.com

---

3. TLS

TLS stands for Transport Layer Security.

It provides:

1. Data encryption

2. Server certificate validation

3. Message integrity

Simplified TLS flow

App connects to server
        |
        v
Server sends certificate
        |
        v
App validates certificate
        |
     Valid?
     /    \
   No      Yes
   |        |
 Block   Create secure session

The device normally checks that:

* The certificate is signed by a trusted Certificate Authority.

* The certificate belongs to the requested hostname.

* The certificate has not expired.

* The certificate chain is valid.

HTTPS uses TLS to secure HTTP communication.

---

4. Network Security Config

Network Security Config is an Android XML configuration used to define an app’s network-security rules without writing custom certificate-validation code. It can control cleartext traffic, trusted certificates, debug certificates and certificate pins.

Configuration file

Create:

res/xml/network_security_config.xml

Example:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>

    <base-config cleartextTrafficPermitted="false">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>

</network-security-config>

Connect it in AndroidManifest.xml:

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

Working

Network request
      |
      v
Network Security Config
      |
      +-- Is cleartext allowed?
      +-- Is certificate trusted?
      +-- Does certificate match a pin?
      |
      v
Allow or block connection

---

5. Domain-Specific Configuration

Different rules can be applied to specific domains.

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>

    <base-config cleartextTrafficPermitted="false" />

    <domain-config cleartextTrafficPermitted="false">

        <domain includeSubdomains="true">
            api.example.com
        </domain>

        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>

    </domain-config>

</network-security-config>
base-config
    |
    +-- Default policy for the application

domain-config
    |
    +-- Policy for a particular domain

---

6. Certificate Pinning

Certificate pinning restricts the app to specific server public keys.

Normal TLS accepts any valid certificate chain trusted by the device. Pinning adds another check: at least one public key in the server’s certificate chain must match a pin stored in the application.

Normal TLS vs Pinning

Normal TLS:

Certificate valid and trusted?
          |
         Yes
          |
        Allow
Certificate pinning:

Certificate valid and trusted?
          |
         Yes
          |
Does public-key hash match a pin?
       /       \
     No         Yes
     |           |
   Block       Allow

Network Security Config pinning example

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>

    <domain-config cleartextTrafficPermitted="false">

        <domain includeSubdomains="true">
            api.example.com
        </domain>

        <pin-set expiration="2027-12-31">

            <pin digest="SHA-256">
                PRIMARY_PUBLIC_KEY_HASH
            </pin>

            <pin digest="SHA-256">
                BACKUP_PUBLIC_KEY_HASH
            </pin>

        </pin-set>

    </domain-config>

</network-security-config>

The pin value is normally a Base64-encoded SHA-256 hash of the certificate’s SubjectPublicKeyInfo.

---

7. Certificate Pinning Classification

A pin can target a public key belonging to:

Pin typeMeaning
Leaf certificatePins the server certificate
Intermediate CAPins an intermediate certificate authority
Root CAPins the root certificate authority
Root CA
   |
   v
Intermediate CA
   |
   v
Server/Leaf Certificate

Comparison

Leaf pinningIntermediate/CA pinning
More restrictiveMore flexible
Rotation is harderCertificates under the CA may continue working
Smaller trust scopeWider trust scope
Requires careful release planningEasier certificate renewal

---

8. Backup Pins

A backup pin is an additional valid public-key hash stored in the application but not currently used by the production server.

Pin set
  |
  +-- Primary pin: current server key
  |
  +-- Backup pin: future emergency key
If the primary certificate or key must be replaced, the server can switch to the backup key without immediately breaking installed applications.

Android documentation recommends always including backup keys when pinning. Without a valid backup pin, an unexpected certificate or CA change may require an application update before connectivity can be restored.

Primary vs backup pin

Primary pinBackup pin
Matches the current certificate chainReserved for future rotation
Actively usedNot currently active
Required for the current connectionPrevents failure during key changes

A backup pin must use a genuinely different private key. Hashing the same key again does not provide a real backup.

---

9. Certificate Rotation

Certificate rotation means replacing an old certificate or key with a new one before the old certificate expires or becomes unsafe.

Safe rotation flow

App version 1
Pins: Key A + Backup Key B
          |
          v
Server currently uses Key A
          |
          v
Server changes to Key B
          |
          v
Installed app still connects
          |
          v
App version 2 released
Pins: Key B + New Backup Key C

Rotation steps

1. Include the current key and a backup key in the application.

2. Release the application and allow users to update.

3. Configure the server to use the backup key.

4. Verify that existing applications still connect.

5. Release another application version with the new current pin and a new backup pin.

---

10. Unsafe Certificate Rotation

App contains only Key A
        |
        v
Server immediately changes to Key B
        |
        v
Pin mismatch
        |
        v
All API connections fail

This creates a serious production outage because an affected app may not be able to contact the server to recover.

---

11. Pin Expiration

Network Security Config allows a pin set to have an expiration date.

<pin-set expiration="2027-12-31">
    ...
</pin-set>

After this date, Android stops enforcing that pin set. This can prevent permanently breaking old application versions, but it also weakens pinning after expiration.

Before expiration
      |
      v
Pin validation enforced

After expiration
      |
      v
Normal certificate validation continues

Pin expiration is a recovery mechanism, not a replacement for proper certificate-rotation planning.

---

12. Should Every App Use Certificate Pinning?

Not necessarily.

Current Android guidance warns that certificate pinning is generally not recommended because changes to the server certificate, public key or Certificate Authority can break connectivity for installed applications until they receive an update. When pinning is required, multiple backup pins and careful expiration and rotation planning are essential.

Pinning may be considered when:

* The application handles highly sensitive information.

* Security requirements explicitly demand it.

* The organization controls certificate rotation.

* Backup pins and emergency recovery are properly planned.

---

13. Common Mistakes

1. Allowing cleartext HTTP

android:usesCleartextTraffic="true"

Production APIs should use HTTPS.

2. Trusting every certificate

Avoid custom code that accepts all hostnames or certificates. It removes TLS server verification.

3. Using only one pin

If that certificate key changes, all network connections may fail.

4. Using the same key as both pins

A backup pin must represent a different key.

5. Rotating the server key before releasing backup pins

Users with older app versions will lose connectivity.

6. Pinning without an emergency plan

Plan backup keys, expiration, staged rotation and app-update timing.

7. Pinning only in debug testing

The complete production certificate chain and rotation process must be tested before release.

8. Assuming HTTPS and pinning are identical

HTTPS performs standard TLS certificate validation. Pinning adds an extra restriction on accepted public keys.

---

14. Interview Questions and Answers

Q1. What is HTTPS?

HTTPS is HTTP communication protected by TLS. It provides encryption, server authentication and data integrity.

Q2. What is TLS?

TLS is the security protocol used to create an encrypted and authenticated connection between the app and server.

Q3. What is Network Security Config?

It is an Android XML configuration that defines cleartext-traffic rules, trusted certificates and certificate pins.

Q4. How do you disable cleartext traffic?

Set cleartextTrafficPermitted="false" in Network Security Config and android:usesCleartextTraffic="false" in the manifest.

Q5. What is certificate pinning?

Certificate pinning limits a domain to specific public-key hashes. The connection fails when the server certificate chain does not contain a matching key.

Q6. HTTPS vs certificate pinning?

HTTPS validates the server certificate against trusted Certificate Authorities. Pinning adds another check that the public key matches a value stored in the app.

Q7. What is a backup pin?

A backup pin is a second valid public-key hash that allows the server certificate or key to be safely changed without breaking installed apps.

Q8. Why are backup pins important?

Without backup pins, an expired, compromised or unexpectedly changed certificate key can block all API communication until users install an updated application.

Q9. What is certificate rotation?

Certificate rotation is the controlled replacement of an old certificate or key with a new one.

Q10. How do you safely rotate pinned certificates?

Ship the future key as a backup pin first, allow users to update, switch the server to that key, and then release another app version containing a new backup key.

Q11. What happens when no pin matches?

TLS authentication fails and the network connection is blocked, even when the certificate is otherwise trusted.

Q12. Is certificate pinning recommended for every Android app?

No. Android guidance warns against general use because server certificate changes can break installed apps. Use it only with a clear security requirement and a reliable backup and rotation process.

---

15. Final Interview Answer

> HTTPS uses TLS to encrypt communication, validate the server and protect data integrity. Android Network Security Config lets us disable cleartext traffic, configure trusted certificates and define certificate pins through XML. Certificate pinning adds an extra check by allowing only specific public-key hashes. We should always include a different backup pin so the server can safely rotate to a new key. During rotation, the future key is first shipped as a backup pin, then activated on the server, and finally replaced with another backup in a later app release. Pinning must be used carefully because incorrect pins or unplanned certificate rotation can block all API communication.