mobile security

Intercepting Mobile Traffic with Burp Suite

Intercepts and analyzes HTTP/HTTPS traffic from mobile applications using Burp Suite proxy to identify insecure API communications, authentication flaws, data leakage, and server-side vulnerabilities. Use when performing mobile application penetration testing, assessing API security, or evaluating client-server communication patterns. Activates for requests involving mobile traffic interception, Burp Suite mobile proxy, API security testing, or mobile HTTPS analysis.

androidburp-suiteiosmobile-securitypenetration-testingtraffic-interception
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

When to Use

Use this skill when:

  • Testing mobile application API endpoints for authentication, authorization, and injection vulnerabilities
  • Analyzing data transmitted between mobile apps and backend servers during penetration tests
  • Evaluating certificate pinning implementations and their bypass difficulty
  • Identifying sensitive data leakage in mobile network traffic

Do not use this skill to intercept traffic from applications you are not authorized to test -- traffic interception without authorization violates computer fraud laws.

Prerequisites

  • Burp Suite Professional or Community Edition installed on testing workstation
  • Android device/emulator or iOS device on the same network as Burp Suite host
  • Burp Suite CA certificate installed on the target device
  • For Android 7+: Network security config modification or Magisk module for system CA trust
  • For SSL pinning bypass: Frida + Objection or custom Frida scripts
  • Wi-Fi network where proxy configuration is possible

Workflow

Step 1: Configure Burp Suite Proxy Listener

Burp Suite > Proxy > Options > Proxy Listeners:
- Bind to address: All interfaces (or specific IP)
- Bind to port: 8080
- Enable "Support invisible proxying"

Verify the listener is active and note the workstation's IP address on the shared network.

Step 2: Configure Mobile Device Proxy

Android:

Settings > Wi-Fi > [Network] > Advanced > Manual Proxy
- Host: <burp_workstation_ip>
- Port: 8080

iOS:

Settings > Wi-Fi > [Network] > Configure Proxy > Manual
- Server: <burp_workstation_ip>
- Port: 8080

Step 3: Install Burp Suite CA Certificate

Android (below API 24):

# Export Burp CA from Proxy > Options > Import/Export CA Certificate
# Transfer to device and install via Settings > Security > Install from storage

Android (API 24+ / Android 7+): Apps targeting API 24+ do not trust user-installed CAs by default. Options:

# Option A: Modify app's network_security_config.xml (requires APK rebuild)
# Add to res/xml/network_security_config.xml:
# <network-security-config>
#   <debug-overrides>
#     <trust-anchors>
#       <certificates src="user" />
#     </trust-anchors>
#   </debug-overrides>
# </network-security-config>
 
# Option B: Install as system CA (rooted device)
openssl x509 -inform DER -in burp-ca.der -out burp-ca.pem
HASH=$(openssl x509 -inform PEM -subject_hash_old -in burp-ca.pem | head -1)
cp burp-ca.pem "$HASH.0"
adb push "$HASH.0" /system/etc/security/cacerts/
adb shell chmod 644 /system/etc/security/cacerts/$HASH.0
 
# Option C: Magisk module (MagiskTrustUserCerts)

iOS:

1. Navigate to http://<burp_ip>:8080 in Safari
2. Download Burp CA certificate
3. Settings > General > VPN & Device Management > Install profile
4. Settings > General > About > Certificate Trust Settings > Enable full trust

Step 4: Intercept and Analyze Traffic

With proxy configured, open the target app and navigate through its functionality:

Burp Suite > Proxy > HTTP History: Review all captured requests and responses.

Key areas to analyze:

  • Authentication tokens: JWT structure, token expiration, refresh mechanisms
  • API endpoints: RESTful paths, GraphQL queries, parameter patterns
  • Sensitive data in transit: PII, credentials, financial data
  • Response headers: Security headers (HSTS, CSP, X-Frame-Options)
  • Error responses: Stack traces, debug information, internal paths

Step 5: Test API Vulnerabilities Using Burp Repeater

Forward intercepted requests to Repeater for manual testing:

Right-click request > Send to Repeater
 
Test categories:
- Authentication bypass: Remove/modify auth tokens
- IDOR: Modify user IDs, object references
- Injection: SQL injection, NoSQL injection in parameters
- Rate limiting: Rapid request replay for brute force assessment
- Business logic: Modify prices, quantities, permissions in requests

Step 6: Automate Testing with Burp Scanner

Right-click request > Do active scan (Professional only)
 
Scanner checks:
- SQL injection (error-based, blind, time-based)
- XSS (reflected, stored)
- Command injection
- Path traversal
- XML/JSON injection
- Authentication flaws

Step 7: Handle Certificate Pinning

If traffic is not visible due to certificate pinning:

# Frida-based bypass (generic)
frida -U -f com.target.app -l ssl-pinning-bypass.js
 
# Objection bypass
objection --gadget com.target.app explore
ios sslpinning disable  # or
android sslpinning disable

Key Concepts

Term Definition
MITM Proxy Man-in-the-middle proxy that terminates and re-establishes TLS connections to inspect encrypted traffic
Certificate Pinning Client-side validation that restricts accepted server certificates beyond the OS trust store
Network Security Config Android XML configuration controlling app trust anchors, cleartext traffic policy, and certificate pinning
Invisible Proxying Burp feature handling non-proxy-aware clients that don't send CONNECT requests
IDOR Insecure Direct Object Reference -- accessing resources by manipulating identifiers without authorization checks

Tools & Systems

  • Burp Suite Professional: Full-featured web application security testing proxy with active scanner
  • Burp Suite Community: Free version with manual interception and basic tools
  • Frida: Dynamic instrumentation for runtime SSL pinning bypass
  • mitmproxy: Open-source alternative to Burp Suite for programmatic traffic analysis
  • Charles Proxy: Alternative HTTP proxy with mobile-friendly certificate installation

Common Pitfalls

  • Android 7+ CA trust: User-installed certificates are not trusted by apps targeting API 24+. Must use system CA installation or app modification.
  • Certificate transparency: Some apps use Certificate Transparency logs to detect MITM. Check for CT enforcement in the app.
  • Non-HTTP protocols: Burp Suite only handles HTTP/HTTPS. Use Wireshark for WebSocket, MQTT, gRPC, or custom binary protocols.
  • VPN-based apps: Apps using VPN tunnels bypass device proxy settings. May need iptables rules on a rooted device to redirect traffic.
Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 3

api-reference.md1.7 KB

API Reference: Mobile Traffic Interception with Burp Suite

HAR (HTTP Archive) Format

Structure

{"log": {"entries": [{"request": {"method": "GET", "url": "https://...",
  "headers": [{"name": "Authorization", "value": "Bearer ..."}],
  "postData": {"text": "..."}},
  "response": {"status": 200, "headers": [...],
  "content": {"text": "..."}}}]}}

Key HAR Fields

Field Description
request.url Full request URL
request.method HTTP method
request.headers Request headers array
request.postData.text POST body content
response.status HTTP status code
response.content.text Response body

Burp Suite Proxy Setup for Mobile

  1. Set proxy listener: 127.0.0.1:8080
  2. Configure device WiFi proxy to Burp IP:8080
  3. Install Burp CA: http://burp/cert
  4. Export traffic as HAR: Proxy > HTTP History > Save Items

mitmproxy Alternative

mitmproxy --mode regular --listen-port 8080
mitmdump -w output.flow --set flow_detail=3
# Convert to HAR:
mitmproxy2har output.flow > capture.har

Certificate Pinning Bypass

Platform Tool
Android Frida + objection (objection explore --startup-command 'android sslpinning disable')
iOS SSL Kill Switch 2 (Cydia)

Sensitive Data Patterns

Type Regex Pattern
Email [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}
Credit Card `\b(?:4\d{3}
JWT eyJ[a-zA-Z0-9_-]+\.eyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+

References

standards.md2.3 KB

Standards Reference: Mobile Traffic Interception with Burp Suite

OWASP Mobile Top 10 2024 Mapping

OWASP ID Risk Burp Suite Testing Coverage
M1 Improper Credential Usage Identify credentials in plaintext, weak token formats in API traffic
M3 Insecure Authentication/Authorization Test auth bypass, session management, IDOR via request manipulation
M4 Insufficient Input/Output Validation SQL injection, XSS, command injection via Burp Scanner/Repeater
M5 Insecure Communication Detect cleartext HTTP, weak TLS, missing HSTS, certificate validation
M8 Security Misconfiguration Identify verbose error messages, debug endpoints, missing security headers

OWASP MASVS v2.0 Control Mapping

MASVS Category Burp Suite Assessment Test Method
MASVS-NETWORK TLS configuration, certificate pinning, cleartext detection Proxy interception, SSL scan
MASVS-AUTH Token validation, session handling, credential transmission Repeater manipulation
MASVS-STORAGE Sensitive data in API responses cached client-side Response header analysis
MASVS-PLATFORM Deep link parameter injection, WebView URL loading Request crafting

OWASP API Security Top 10 2023

API Risk Burp Suite Test
API1: Broken Object Level Authorization Modify object IDs in intercepted requests
API2: Broken Authentication Replay tokens, test token expiration
API3: Broken Object Property Level Auth Modify response/request properties
API5: Broken Function Level Authorization Access admin endpoints with user tokens
API8: Security Misconfiguration Check response headers, error handling

CWE Mappings

CWE ID Title Detection Method
CWE-200 Exposure of Sensitive Information Inspect API responses for data leakage
CWE-295 Improper Certificate Validation Test with self-signed proxy certificate
CWE-319 Cleartext Transmission Monitor for HTTP (non-HTTPS) requests
CWE-352 Cross-Site Request Forgery Check for anti-CSRF tokens in requests
CWE-613 Insufficient Session Expiration Test token validity after logout
workflows.md4.1 KB

Workflows: Mobile Traffic Interception with Burp Suite

Workflow 1: Standard Mobile API Testing

[Configure Burp Listener] --> [Set Device Proxy] --> [Install CA Cert] --> [Open Target App]
                                                                                |
                                                                                v
                                                                     [Capture HTTP History]
                                                                                |
                                                          +---------------------+---------------------+
                                                          |                     |                     |
                                                   [Map API surface]    [Identify auth flow]   [Check data exposure]
                                                          |                     |                     |
                                                          v                     v                     v
                                                   [Send to Scanner]    [Token analysis]       [PII in responses]
                                                   [Active scan]        [Session testing]      [Sensitive headers]
                                                          |                     |                     |
                                                          +---------------------+---------------------+
                                                                                |
                                                                         [Compile findings]
                                                                         [Generate report]

Workflow 2: SSL Pinning Bypass Pipeline

[Set Proxy] --> [Open App] --> [Connection fails?]
                                    |
                              [Yes: Pinning active]
                                    |
                     +--------------+--------------+
                     |              |              |
              [Frida bypass]  [Objection]   [APK repackage]
              [Generic script] [sslpinning] [Remove pinning code]
                     |         [disable]          |
                     +--------------+--------------+
                                    |
                           [Verify traffic flows]
                           [Continue assessment]

Workflow 3: Authentication Testing

[Intercept login request] --> [Capture auth token] --> [Analyze token format]
                                                              |
                                                   +----------+----------+
                                                   |                     |
                                            [JWT analysis]        [Opaque token]
                                            [Decode payload]      [Session management]
                                            [Check signature]     [Timeout testing]
                                            [Modify claims]       [Concurrent session]
                                                   |                     |
                                                   +----------+----------+
                                                              |
                                                    [Test IDOR with user IDs]
                                                    [Test privilege escalation]
                                                    [Test token replay after logout]

Decision Matrix: Traffic Interception Approach

Scenario Android iOS
No pinning, API < 24 Standard proxy + user CA Standard proxy + profile install
No pinning, API 24+ System CA or network_security_config mod Standard proxy + profile install
Pinning implemented Frida/Objection bypass + system CA Frida/Objection bypass
Custom protocol Wireshark + custom Frida hooks Wireshark + custom Frida hooks
VPN tunnel iptables redirect on rooted device Not feasible without jailbreak

Scripts 2

agent.py6.4 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Agent for analyzing intercepted mobile app traffic via mitmproxy for security testing."""

import json
import argparse
import re
from datetime import datetime
from urllib.parse import urlparse


def load_har_file(har_path):
    """Load and parse an HTTP Archive (HAR) file from proxy capture."""
    with open(har_path) as f:
        data = json.load(f)
    entries = data.get("log", {}).get("entries", [])
    print(f"[*] Loaded {len(entries)} requests from {har_path}")
    return entries


def find_insecure_requests(entries):
    """Identify HTTP (non-HTTPS) requests from mobile app."""
    findings = []
    for e in entries:
        url = e.get("request", {}).get("url", "")
        if url.startswith("http://"):
            findings.append({"url": url, "method": e["request"].get("method"),
                             "issue": "Cleartext HTTP request", "severity": "HIGH"})
    print(f"\n[*] Insecure HTTP requests: {len(findings)}")
    for f in findings[:10]:
        print(f"  [!] {f['method']} {f['url'][:80]}")
    return findings


def detect_sensitive_data_leakage(entries):
    """Scan request/response bodies for sensitive data patterns."""
    patterns = {
        "email": r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}",
        "phone": r"\b\d{3}[-.]?\d{3}[-.]?\d{4}\b",
        "ssn": r"\b\d{3}-\d{2}-\d{4}\b",
        "credit_card": r"\b(?:4\d{3}|5[1-5]\d{2}|3[47]\d{2}|6011)\d{12}\b",
        "api_key": r"(?:api[_-]?key|apikey|token)[\"']?\s*[:=]\s*[\"']?([a-zA-Z0-9_-]{20,})",
        "jwt": r"eyJ[a-zA-Z0-9_-]+\.eyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+",
    }
    findings = []
    for e in entries:
        url = e.get("request", {}).get("url", "")
        body = e.get("request", {}).get("postData", {}).get("text", "")
        resp_body = e.get("response", {}).get("content", {}).get("text", "")
        combined = f"{body} {resp_body}"
        for name, pattern in patterns.items():
            matches = re.findall(pattern, combined)
            if matches:
                findings.append({"url": url[:80], "data_type": name,
                                 "count": len(matches), "severity": "HIGH"})
    print(f"\n[*] Sensitive data leakage findings: {len(findings)}")
    for f in findings[:10]:
        print(f"  [!] {f['data_type']} in {f['url']} ({f['count']} occurrences)")
    return findings


def check_auth_headers(entries):
    """Analyze authentication headers and token handling."""
    findings = []
    for e in entries:
        headers = {h["name"].lower(): h["value"] for h in e.get("request", {}).get("headers", [])}
        url = e.get("request", {}).get("url", "")
        if "authorization" in headers:
            auth = headers["authorization"]
            if auth.startswith("Basic "):
                findings.append({"url": url[:80], "issue": "Basic auth over network",
                                 "severity": "HIGH"})
            elif auth.startswith("Bearer "):
                token = auth.split(" ", 1)[1]
                if len(token) < 20:
                    findings.append({"url": url[:80], "issue": "Short bearer token",
                                     "severity": "MEDIUM"})
        resp_headers = {h["name"].lower(): h["value"]
                        for h in e.get("response", {}).get("headers", [])}
        if "set-cookie" in resp_headers:
            cookie = resp_headers["set-cookie"]
            if "secure" not in cookie.lower() or "httponly" not in cookie.lower():
                findings.append({"url": url[:80], "issue": "Cookie missing Secure/HttpOnly",
                                 "severity": "MEDIUM"})
    print(f"\n[*] Auth/cookie findings: {len(findings)}")
    return findings


def check_certificate_pinning(entries):
    """Check for certificate pinning indicators in traffic."""
    domains = set()
    for e in entries:
        url = e.get("request", {}).get("url", "")
        parsed = urlparse(url)
        if parsed.scheme == "https":
            domains.add(parsed.hostname)
    print(f"\n[*] HTTPS domains contacted: {len(domains)}")
    for d in sorted(domains)[:20]:
        print(f"  {d}")
    print("  [*] Note: Certificate pinning bypass verified by successful interception")
    return list(domains)


def check_api_security_headers(entries):
    """Check API response security headers."""
    findings = []
    checked_hosts = set()
    for e in entries:
        url = e.get("request", {}).get("url", "")
        host = urlparse(url).hostname
        if host in checked_hosts:
            continue
        checked_hosts.add(host)
        resp_headers = {h["name"].lower(): h["value"]
                        for h in e.get("response", {}).get("headers", [])}
        missing = []
        for hdr in ["strict-transport-security", "x-content-type-options",
                     "x-frame-options", "content-security-policy"]:
            if hdr not in resp_headers:
                missing.append(hdr)
        if missing:
            findings.append({"host": host, "missing_headers": missing, "severity": "MEDIUM"})
    print(f"\n[*] Security header findings: {len(findings)}")
    return findings


def generate_report(all_findings, output_path):
    """Generate mobile traffic analysis report."""
    report = {"analysis_date": datetime.now().isoformat(), "total_findings": len(all_findings),
              "findings": all_findings}
    with open(output_path, "w") as f:
        json.dump(report, f, indent=2, default=str)
    print(f"\n[*] Report saved to {output_path}")


def main():
    parser = argparse.ArgumentParser(description="Mobile Traffic Interception Analysis Agent")
    parser.add_argument("action", choices=["analyze", "insecure", "leakage", "auth", "full"])
    parser.add_argument("--har", required=True, help="Path to HAR file from proxy capture")
    parser.add_argument("-o", "--output", default="mobile_traffic_report.json")
    args = parser.parse_args()

    entries = load_har_file(args.har)
    findings = []
    if args.action in ("insecure", "full"):
        findings.extend(find_insecure_requests(entries))
    if args.action in ("leakage", "full"):
        findings.extend(detect_sensitive_data_leakage(entries))
    if args.action in ("auth", "full"):
        findings.extend(check_auth_headers(entries))
    if args.action in ("analyze", "full"):
        check_certificate_pinning(entries)
        findings.extend(check_api_security_headers(entries))
    if args.action == "full":
        generate_report(findings, args.output)


if __name__ == "__main__":
    main()
process.py9.7 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Mobile Traffic Analysis Pipeline for Burp Suite Exports

Parses Burp Suite XML export files to identify security findings in mobile API traffic.
Analyzes authentication patterns, sensitive data exposure, and security header compliance.

Usage:
    python process.py --burp-xml export.xml [--output report.json]
"""

import argparse
import json
import sys
import base64
import re
import xml.etree.ElementTree as ET
from collections import Counter
from datetime import datetime
from pathlib import Path
from urllib.parse import urlparse, parse_qs


class BurpTrafficAnalyzer:
    """Analyzes Burp Suite XML exports for mobile security findings."""

    SENSITIVE_PATTERNS = {
        "email": r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}",
        "phone": r"\b\d{3}[-.]?\d{3}[-.]?\d{4}\b",
        "ssn": r"\b\d{3}-\d{2}-\d{4}\b",
        "credit_card": r"\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b",
        "jwt": r"eyJ[a-zA-Z0-9_-]+\.eyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+",
        "api_key": r"(?:api[_-]?key|apikey)['\"]?\s*[:=]\s*['\"]?([a-zA-Z0-9_-]{20,})",
        "bearer_token": r"Bearer\s+[a-zA-Z0-9_.-]+",
    }

    SECURITY_HEADERS = [
        "Strict-Transport-Security",
        "Content-Security-Policy",
        "X-Content-Type-Options",
        "X-Frame-Options",
        "X-XSS-Protection",
        "Referrer-Policy",
        "Cache-Control",
    ]

    def __init__(self, xml_path: str):
        self.xml_path = xml_path
        self.requests = []
        self.findings = []

    def parse_burp_xml(self) -> int:
        """Parse Burp Suite XML export file."""
        tree = ET.parse(self.xml_path)
        root = tree.getroot()

        for item in root.findall(".//item"):
            request_data = {
                "url": item.findtext("url", ""),
                "host": item.findtext("host", ""),
                "port": item.findtext("port", ""),
                "protocol": item.findtext("protocol", ""),
                "method": item.findtext("method", ""),
                "path": item.findtext("path", ""),
                "status": item.findtext("status", ""),
                "mime_type": item.findtext("mimetype", ""),
            }

            # Decode request
            req_elem = item.find("request")
            if req_elem is not None and req_elem.text:
                is_base64 = req_elem.get("base64", "false") == "true"
                request_data["request_body"] = (
                    base64.b64decode(req_elem.text).decode("utf-8", errors="replace")
                    if is_base64 else req_elem.text
                )
            else:
                request_data["request_body"] = ""

            # Decode response
            resp_elem = item.find("response")
            if resp_elem is not None and resp_elem.text:
                is_base64 = resp_elem.get("base64", "false") == "true"
                request_data["response_body"] = (
                    base64.b64decode(resp_elem.text).decode("utf-8", errors="replace")
                    if is_base64 else resp_elem.text
                )
            else:
                request_data["response_body"] = ""

            self.requests.append(request_data)

        return len(self.requests)

    def analyze_cleartext_traffic(self) -> list:
        """Identify HTTP (non-HTTPS) traffic."""
        cleartext = [
            r for r in self.requests
            if r["protocol"].lower() == "http"
        ]

        if cleartext:
            self.findings.append({
                "type": "cleartext_traffic",
                "severity": "HIGH",
                "owasp_mobile": "M5",
                "count": len(cleartext),
                "urls": list(set(r["url"] for r in cleartext))[:10],
                "description": f"{len(cleartext)} requests sent over unencrypted HTTP",
            })
        return cleartext

    def analyze_sensitive_data(self) -> list:
        """Scan traffic for sensitive data patterns."""
        sensitive_findings = []

        for req in self.requests:
            combined_text = req.get("response_body", "") + req.get("request_body", "")
            for pattern_name, pattern_regex in self.SENSITIVE_PATTERNS.items():
                matches = re.findall(pattern_regex, combined_text)
                if matches:
                    sensitive_findings.append({
                        "url": req["url"],
                        "pattern": pattern_name,
                        "match_count": len(matches),
                        "sample": matches[0][:20] + "..." if matches else "",
                    })

        if sensitive_findings:
            self.findings.append({
                "type": "sensitive_data_exposure",
                "severity": "HIGH",
                "owasp_mobile": "M9",
                "count": len(sensitive_findings),
                "details": sensitive_findings[:20],
                "description": f"Sensitive data patterns found in {len(sensitive_findings)} request/response pairs",
            })
        return sensitive_findings

    def analyze_security_headers(self) -> dict:
        """Check for missing security headers in responses."""
        header_coverage = {h: 0 for h in self.SECURITY_HEADERS}
        total_responses = 0

        for req in self.requests:
            resp = req.get("response_body", "")
            if resp:
                total_responses += 1
                for header in self.SECURITY_HEADERS:
                    if header.lower() in resp.lower():
                        header_coverage[header] += 1

        missing = [h for h, count in header_coverage.items() if count == 0]

        if missing:
            self.findings.append({
                "type": "missing_security_headers",
                "severity": "MEDIUM",
                "owasp_mobile": "M8",
                "missing_headers": missing,
                "total_responses": total_responses,
                "description": f"Missing security headers: {', '.join(missing)}",
            })
        return header_coverage

    def analyze_authentication(self) -> list:
        """Analyze authentication patterns in traffic."""
        auth_findings = []

        for req in self.requests:
            body = req.get("request_body", "")

            # Check for credentials in URL parameters
            parsed = urlparse(req["url"])
            params = parse_qs(parsed.query)
            sensitive_params = [
                k for k in params
                if any(s in k.lower() for s in ["password", "token", "key", "secret", "auth"])
            ]
            if sensitive_params:
                auth_findings.append({
                    "url": req["url"],
                    "issue": "credentials_in_url",
                    "parameters": sensitive_params,
                })

            # Check for basic auth
            if "Authorization: Basic" in body:
                auth_findings.append({
                    "url": req["url"],
                    "issue": "basic_auth_used",
                })

        if auth_findings:
            self.findings.append({
                "type": "authentication_issues",
                "severity": "HIGH",
                "owasp_mobile": "M1",
                "count": len(auth_findings),
                "details": auth_findings[:10],
                "description": f"{len(auth_findings)} authentication-related issues found",
            })
        return auth_findings

    def analyze_api_surface(self) -> dict:
        """Map the API surface area from captured traffic."""
        endpoints = Counter()
        methods = Counter()
        hosts = Counter()

        for req in self.requests:
            parsed = urlparse(req["url"])
            path = re.sub(r"\d+", "{id}", parsed.path)
            endpoints[f"{req['method']} {path}"] += 1
            methods[req["method"]] += 1
            hosts[req["host"]] += 1

        return {
            "unique_endpoints": len(endpoints),
            "top_endpoints": endpoints.most_common(20),
            "methods": dict(methods),
            "hosts": dict(hosts),
        }

    def generate_report(self) -> dict:
        """Generate comprehensive traffic analysis report."""
        api_surface = self.analyze_api_surface()

        return {
            "analysis": {
                "source_file": self.xml_path,
                "date": datetime.now().isoformat(),
                "total_requests": len(self.requests),
                "tool": "Burp Suite Traffic Analyzer",
            },
            "api_surface": api_surface,
            "findings": self.findings,
            "summary": {
                "total_findings": len(self.findings),
                "by_severity": Counter(f["severity"] for f in self.findings),
            },
        }


def main():
    parser = argparse.ArgumentParser(
        description="Analyze Burp Suite XML exports for mobile security findings"
    )
    parser.add_argument("--burp-xml", required=True, help="Path to Burp Suite XML export")
    parser.add_argument("--output", default="traffic_analysis.json", help="Output report path")
    args = parser.parse_args()

    if not Path(args.burp_xml).exists():
        print(f"[-] File not found: {args.burp_xml}")
        sys.exit(1)

    analyzer = BurpTrafficAnalyzer(args.burp_xml)

    # Parse
    count = analyzer.parse_burp_xml()
    print(f"[+] Parsed {count} requests from Burp export")

    # Run analyses
    analyzer.analyze_cleartext_traffic()
    analyzer.analyze_sensitive_data()
    analyzer.analyze_security_headers()
    analyzer.analyze_authentication()

    # Generate report
    report = analyzer.generate_report()

    with open(args.output, "w") as f:
        json.dump(report, f, indent=2)
    print(f"[+] Report saved: {args.output}")
    print(f"[*] Total findings: {report['summary']['total_findings']}")


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 1.5 KB
Keep exploring