Module 10 — Network & API Security

Safety & scope reminder: everything in this module is intended for authorized, lab-only testing against apps you own or have explicit written permission to test. The guidance is designed to help ethical testers and defenders harden mobile apps and their backends (particularly banking apps). Never perform interception, manipulation, or unauthorized scanning against systems outside your written scope.

This module covers how mobile apps communicate with servers, common API-level vulnerabilities, how to analyze and test network behavior safely, how to reason about certificate pinning and attestation from a defensive standpoint, and practical controls for developers and operations teams to secure APIs used by mobile apps.

10.0 Learning objectives

After completing Module 10 you will be able to:

  • Map a mobile app’s network footprint and identify all protocol and data flows.
  • Detect insecure transport, weak TLS configurations, and leaking of sensitive data in transit.
  • Understand certificate pinning approaches and design robust, auditable pinning strategies.
  • Identify server-side API issues (broken authentication, authorization, inadequate validation).
  • Test APIs safely with proxies and replay tools in a lab and collect forensic evidence.
  • Recommend concrete mitigations (TLS hardening, token binding, rate-limiting, anomaly detection).
  • Create a prioritized remediation plan and CI checks for API security.

10.1 The network threat model for mobile apps

Before testing or hardening, define the relevant threat models:

  • Man-in-the-Middle (MitM) on user network (public Wi-Fi, mobile networks) — attacker can intercept TLS if pinning absent.
  • Device-compromise adversary (rooted device, Frida) — attacker controls client and can inspect or modify requests before encryption.
  • Server-side threat — compromised server or API misconfiguration that exposes data.
  • Insider/third-party SDK abuse — SDKs embedded in app may send PII to unexpected destinations.

Design defenses that consider these models; in particular, do not place full trust in the client.

10.2 Inventory & mapping of network surfaces

Start by producing a comprehensive map of all endpoints the app communicates with:

  • Static sources: strings, res/values, assets, decompiled code (Module 3).
  • Dynamic sources: proxy captures, PCAPs, DNS logs (Module 5 & 6).
  • Third-party hosts: analytics, crash reporting, ad networks, CDN domains.
  • Push / realtime services: WebSocket, MQTT, FCM endpoints.

Produce a table with:
| Hostname | Service | Owner | Protocol | Notes (pinning/attestation?) |

Example:
| api.bank.com | Banking API | Own | HTTPS (REST/JSON) | certificate pinned (client) |

10.3 Intercepting and analyzing traffic (lab)

10.3.1 Tools

  • Burp Suite (Proxy) — intercept, inspect, modify requests & responses.
  • mitmproxy — scriptable proxy, useful for automation.
  • tcpdump / tshark / Wireshark — raw packet capture and offline analysis.
  • openssl s_client / sslyze / testssl.sh — TLS configuration and cipher analysis.
  • Postman / curl — replay requests and craft test inputs.

10.3.2 Lab proxy setup (high-level)

  1. Configure lab proxy (Burp/mitmproxy) and create a lab CA.
  2. Install CA in emulator/device user store (lab-only).
  3. Route app traffic through proxy.
  4. Capture flows while exercising app features.

Important: If the app uses certificate pinning, the proxy will not be able to intercept TLS; record the handshake failure and proceed with static & server-side verification (see Section 10.6).

10.3.3 What to look for in captured traffic

  • Plaintext credentials or PII in request bodies or headers.
  • Authorization tokens (Bearer, Basic) sent over non-TLS or visible in URLs.
  • Long-lived tokens, refresh tokens sent frequently without binding to device.
  • Sensitive data in query parameters or referer headers.
  • Cookies without Secure/HttpOnly flags (if the app uses cookies).
  • Mobile-specific headers (X-Device-ID, X-Client-Version) that may be mutable.

10.4 TLS & server-side transport hardening

10.4.1 TLS version & cipher score

  • Target minimum TLS 1.2 (TLS 1.3 preferred).
  • Disable insecure ciphers (RC4, 3DES, export ciphers).
  • Prefer forward secrecy suites (ECDHE).
  • Scan endpoints with sslyze or testssl.sh and remediate weak configs.

10.4.2 Certificate validation & hostname matching

  • Enforce proper hostname validation and do not rely on default permissive hostname verifiers.
  • Ensure server presents a certificate signed by a trusted CA and includes correct Subject Alternative Names (SANs).
  • Avoid wildcard pins unless strictly necessary; document the roll-over process.

10.4.3 HSTS and other HTTP security headers

  • Apply Strict-Transport-Security with an appropriate max-age and includeSubDomains (after verifying coverage).
  • Set X-Content-Type-Options: nosniff, X-Frame-Options, and appropriate Content-Security-Policy for any webviews.

10.5 Certificate pinning — strategies and trade-offs

Pinning reduces MitM risk but must be implemented carefully.

10.5.1 Pin types

  • Leaf certificate pin — brittle on renewals.
  • Public key pin (SPKI) — more robust to certificate reissuance.
  • CA pin — broader scope but less secure if CA compromised.
  • Delegated pins via server — server supplies pin set to client securely (requires bootstrapping).

10.5.2 Recommended approach for banking apps

  • Use SPKI pinning with multiple pins (primary + backup).
  • Support pin rollover using a pre-published backup pin (at least one additional trusted key).
  • Validate pins in native layer (NDK) to raise attack cost, but still require server-side attestation & anomaly detection — do not depend solely on pinning for security.

10.5.3 Auditable pinning & rotation

  • Publish pin metadata in a secure place (internal release notes or a signed manifest).
  • Implement a secure rollout plan: server-side flag to enable new pin after verification, staged rollout by region.
  • Provide fallback behavior and user-friendly error messages (do not silently fail open).

10.6 Attestation tokens in network flows (Play Integrity / Key Attestation)

Mobile apps often send attestation tokens to backends as proof of device/app integrity.

10.6.1 What to capture and validate (when you see attestation tokens)

  • Raw token (base64/JWT) sent in request body or header — capture and archive for server-side validation.
  • Nonce used by the client — ensure the server issued it and it was single-use.
  • Timestamp and validity period inside the token.
  • Fields: package name, certificate digest, ctsProfileMatch, advice flags.

10.6.2 Server-side validation checklist

  • Verify token signature against platform CA.
  • Ensure nonce matches and has not expired.
  • Validate package name & certificate fingerprint fields match expected values.
  • Check device integrity fields (ctsProfileMatch) and act on anomalies.
  • Log full verification result and keep token artifact for audits.

If you capture a token during dynamic testing, the appropriate follow-up is to provide it to the backend validation component (or have the vendor show server logs verifying it). Do not attempt to forge or replay tokens outside lab; instead request server verification evidence.

10.7 API authentication & session management pitfalls

Mobile APIs commonly use tokens — secure design patterns are critical.

10.7.1 Token types & lifecycle

  • Access tokens: short-lived, used for API auth.
  • Refresh tokens: longer-lived, used to obtain new access tokens (must be protected).
  • Device-bound tokens: tokens tied to device identity or attestation results (more secure).
  • Mutual TLS (mTLS): client certificates for high-security use cases (complex but robust).

10.7.2 Common mistakes

  • Using long-lived access tokens without revocation.
  • Storing tokens insecurely (unencrypted SharedPreferences or files).
  • Accepting client-supplied attestation results without server validation.
  • Using weak or predictable token formats (self-signed JWTs without key rotation).
  • Not invalidating tokens on logout or device change.

10.7.3 Recommended design

  • Use short-lived access tokens (minutes to hours) and rotate frequently.
  • Require refresh tokens to be used from the same device fingerprint (combine with attestation or device identifier).
  • Implement server-side token revocation and detection of token replay.
  • Use PKCE for OAuth flows where applicable to defend against interception.
  • Consider mTLS for critical inter-service communication or high-value banking operations.

10.8 Authorization testing (common logical faults)

Even if authentication is correct, authorization issues are common and serious.

10.8.1 Vertical privilege escalation

  • Test whether user can access admin or other higher-privilege endpoints by changing identifiers (user_id) or using another user’s token.

10.8.2 Horizontal privilege escalation

  • Check whether one legitimate user can access another user’s data by altering request parameters or IDs.

10.8.3 Insecure direct object references (IDOR)

  • Alter resource IDs in requests to confirm lack of server-side ownership checks. Use predictable sequences in lab only.

10.8.4 Broken function-level authorization

  • Ensure operations check that the token has the required scope/role. Example: transaction approval should verify user role, recent authentication, and transaction limits.

Testing approach (lab):

  • Use a controlled test account A and account B. Request protected resource for B using A’s credentials and confirm the server denies or returns only authorized data. Record request/response, status codes, and server-side error messages.

10.9 Input validation & common API bugs

APIs must validate all inputs despite client-side checks.

Typical flaws

  • SQL/NoSQL injection via unsanitized inputs.
  • Improper JSON parsing leading to object injection (e.g., type confusion).
  • Overly permissive CORS allowing origin spoofing.
  • Unvalidated redirects or open endpoints that can be abused.

Tests to run

  • Boundary testing (oversized payloads).
  • Malformed JSON and unexpected fields.
  • Parameter tampering (unexpected types, nulls).
  • Injection payload testing (in lab with safe payloads).

Always capture server response codes, timings, and stack traces (from server logs if available under authorization).

10.10 Rate limiting, brute force, and abuse controls

APIs must resist automated abuse.

Recommendations

  • Implement per-account and per-device rate limits (burst + sustained).
  • Apply CAPTCHA or progressive throttling for abnormal auth attempts.
  • Use device reputation and attestation signals to increase scrutiny on suspicious devices.
  • Log and alert on high-frequency behaviors (many account lookups, repeated password attempts).

Testing in lab

  • Simulate burst traffic from test harness and observe server rate-limiting behavior and error codes (429). Ensure the server enforces limits properly and logs incidents.

10.11 API logging & observability (forensics & incident response)

Design API logging to support detection and post-incident validation:

  • Log the attestation verification result and token trace ID for every sensitive operation.
  • Log request metadata: client certificate (if mTLS), client IP, device hash (non-PII), user agent, app version.
  • Record failed authorization attempts, rate limit hits, and token verification failures.
  • Store logs in an immutable or append-only store with RBAC access to facilitate audits.

Ensure log retention, privacy compliance, and a plan to securely share logs with authorized auditors during validated incidents.

10.12 Defense-in-depth: combined mitigations (recommended stack)

  1. Transport security: TLS 1.2+/1.3, strong cipher suites, HSTS.
  2. Pinning + Attestation: client-side SPKI pin + server-side token validation with nonce.
  3. Short-lived tokens + device-binding: token rotation and refresh policies.
  4. Server-side authorization & input validation: never trust client data.
  5. Rate-limiting & anomaly detection: behavioral defenses and device reputation scoring.
  6. Robust logging & forensics: store verification tokens & logs for audits.
  7. CI Security checks: automate TLS scans, API contract checks, and security tests.

10.13 Practical labs (authorized, reproducible)

All labs below assume a safe lab environment with a mock backend you control.

Lab 10-A — Endpoint inventory & TLS scan

  • Run the recon script from Module 2 to list endpoints.
  • For each endpoint, run openssl s_client -connect host:443 -servername host and sslyze to determine TLS config.
  • Produce a TLS report with vulnerabilities and remediation actions.

Lab 10-B — Proxy capture & sensitive-data hunt

  • Configure emulator to use Burp (lab CA installed).
  • Execute flows: login, funds transfer, profile update.
  • Search Burp logs for tokens, PII, and sensitive headers. Produce a leakage report.

Lab 10-C — Attestation validation exercise (server-side)

  • Using test server code (sandbox), implement nonce issuance and validation of Play Integrity-like tokens (use sample token format or vendor-provided test flow).
  • Demonstrate server rejecting token with invalid nonce or mismatched package name. Log verification artifact.

Lab 10-D — Authorization fuzzing

  • Use Postman or a scripted client to attempt IDOR checks (with test accounts), try accessing other account resources, and record results. Ensure server denies unauthorized access.

10.14 Example commands & snippets (lab-only)

  • Grab TLS cert details:
echo | openssl s_client -connect api.banklab.local:443 -servername api.banklab.local 2>/dev/null | openssl x509 -noout -text
  • Run sslyze (example):
sslyze --regular api.banklab.local:443
  • Basic curl replay (use with care and auth):
curl -v -X POST https://api.banklab.local/v1/login \
  -H "Content-Type: application/json" \
  -d '{"username":"test","password":"password"}'
  • Capture traffic with tcpdump (proxy box):
sudo tcpdump -i eth0 host api.banklab.local -w banklab.pcap
  • Example JSON for nonce-based attestation request:
# Request nonce
GET /attest/nonce
# Client receives {"nonce":"abc123","ttl":60}

# Client calls platform attestation and posts token
POST /attest/verify
Content-Type: application/json
{
  "nonce": "abc123",
  "attestation_token": "BASE64_JWT"
}

10.15 Remediation checklist (developer & ops)

For each finding, the following actions should be prioritized:

  1. Plaintext or weak TLS → enforce TLS 1.2+ server-side, fix cipher suites, enable HSTS.
  2. Token leakage → move tokens to secure storage, ensure tokens are sent only in Authorization header over HTTPS, set Secure/HttpOnly for cookies.
  3. No server-side attestation validation → implement server validation for attestation tokens and record verification artifacts.
  4. IDOR / broken authorization → add ownership checks, and implement role/scope-based access controls for each endpoint.
  5. Missing rate-limits → implement per-user and per-IP rate limiting with monitoring/alerts.
  6. Insufficient logging → add attestation and token trace logging; secure retention.

10.16 Deliverables for Module 10

  • Network security assessment report: endpoint inventory, TLS scores, captured evidence, and prioritized remediation.
  • API attack surface matrix: endpoints, auth model, sensitive operations, recommended defenses.
  • Attestation verification spec: nonce flow, JWT validation steps, sample responses, and error codes.
  • Rate-limiting & anomaly policy: thresholds, escalation flow, and sample signatures for alerts.
  • Playbook: how to validate vendor claims about bypasses (what artifacts to request and how to verify them).

10.17 Common mistakes & pitfalls in mobile network testing

  • Relying only on emulator captures (some protections differ on real devices).
  • Attempting to bypass pinning on production — instead collect evidence and ask vendors for server validation artifacts.
  • Forgetting to sanitize or redact PII in captured artifacts before sharing with stakeholders.
  • Not correlating client-side behaviors with server-side logs — always ask for server logs when validating serious claims.

10.18 Final notes & next steps

  • Network and API security is where many real-world compromises occur; protect transport, tokens, and server-side business logic aggressively.
  • Combine client-side defenses (pinning, attestation) with rigorous server-side verification, logging, and anomaly detection.
  • Use the labs in this module to validate controls and to produce reproducible evidence for auditors and vendors.