Skip to content

hypnguyen1209/offensive-claude / skills/mobile-pentest

mobile-pentest

Unverified

Use when pentesting an Android/iOS app — Frida 17 instrumentation, SSL-pinning & root/jailbreak bypass, Android 14/15 CA injection, exported-component/content-provider abuse, deep-link/WebView chains, biometric bypass, Flutter/React-Native RE

scripts/manifest_attack_surface.py

View on GitHub
#!/usr/bin/env python3
"""
manifest_attack_surface.py — Parse an APK's AndroidManifest into a structured attack-surface map.

Flags: exported activities/services/receivers/providers (explicit OR implicit pre-API-31),
permission protection levels, deep-link schemes/hosts, dangerous flags (debuggable, allowBackup,
usesCleartextTraffic, no networkSecurityConfig), task-hijacking exposure (taskAffinity / launchMode),
and grantUriPermissions providers. Output is JSON consumed by component_fuzz.sh.

USAGE:
    python3 manifest_attack_surface.py base.apk -o surface.json
    python3 manifest_attack_surface.py AndroidManifest.xml         # already-decoded text/binary manifest

DEPENDENCIES:
    pip install androguard        # preferred (handles binary AXML + resolves <permission> levels)
    (fallback: if androguard is missing and given a TEXT xml, uses stdlib ElementTree)

SCOPE: static analysis helper for authorized assessments.
"""
import argparse, json, sys, os

ANDROID_NS = "http://schemas.android.com/apk/res/android"


def _attr(elem_attrib, name):
    return elem_attrib.get("{%s}%s" % (ANDROID_NS, name)) or elem_attrib.get(name)


def analyze_with_androguard(apk_path):
    from androguard.core.apk import APK  # androguard >= 4.x
    a = APK(apk_path)
    axml = a.get_android_manifest_xml()
    pkg = a.get_package()
    min_sdk = int(a.get_min_sdk_version() or 0)
    target_sdk = int(a.get_target_sdk_version() or 0)

    # protection level of locally-defined custom permissions
    custom_perms = {}
    for perm in axml.findall(".//permission"):
        nm = _attr(perm.attrib, "name")
        lvl = _attr(perm.attrib, "protectionLevel") or "normal"
        if nm:
            custom_perms[nm] = lvl

    app_el = axml.find(".//application")
    app_flags = {}
    if app_el is not None:
        for f in ("debuggable", "allowBackup", "usesCleartextTraffic", "networkSecurityConfig"):
            app_flags[f] = _attr(app_el.attrib, f)

    components = {"activity": [], "service": [], "receiver": [], "provider": []}
    deep_links = []

    for tag in components:
        for el in axml.findall(".//" + tag):
            name = _attr(el.attrib, "name")
            exported_attr = _attr(el.attrib, "exported")
            perm = _attr(el.attrib, "permission")
            has_filter = el.find("intent-filter") is not None
            # API 31+: must be explicit. Pre-31: implicitly exported if it has an intent-filter.
            if exported_attr is not None:
                exported = exported_attr.lower() == "true"
            else:
                exported = has_filter and target_sdk < 31

            rec = {
                "name": name,
                "exported": exported,
                "exported_attr": exported_attr,
                "permission": perm,
                "permission_level": custom_perms.get(perm, "n/a" if not perm else "platform/unknown"),
                "has_intent_filter": has_filter,
            }
            if tag == "provider":
                rec["authorities"] = _attr(el.attrib, "authorities")
                rec["grantUriPermissions"] = _attr(el.attrib, "grantUriPermissions")
            if tag == "activity":
                rec["taskAffinity"] = _attr(el.attrib, "taskAffinity")
                rec["launchMode"] = _attr(el.attrib, "launchMode")
                # task-hijack exposure: launcher/important activity w/o empty taskAffinity
                rec["task_hijack_risk"] = (rec["taskAffinity"] != "")

            # deep links
            for f in el.findall("intent-filter"):
                actions = [_attr(a.attrib, "name") for a in f.findall("action")]
                cats = [_attr(c.attrib, "name") for c in f.findall("category")]
                for d in f.findall("data"):
                    scheme = _attr(d.attrib, "scheme")
                    host = _attr(d.attrib, "host")
                    if scheme:
                        deep_links.append({
                            "component": name, "scheme": scheme, "host": host,
                            "browsable": "android.intent.category.BROWSABLE" in cats,
                            "autoVerify": (_attr(f.attrib, "autoVerify") == "true"),
                            "actions": actions,
                        })
            components[tag].append(rec)

    return {
        "package": pkg,
        "min_sdk": min_sdk,
        "target_sdk": target_sdk,
        "application_flags": app_flags,
        "custom_permissions": custom_perms,
        "components": components,
        "deep_links": deep_links,
    }


def analyze_text_xml(path):
    # Manifests are untrusted input -> use defusedxml to block XXE / billion-laughs.
    try:
        import defusedxml.ElementTree as ET  # pip install defusedxml
    except ImportError:
        sys.exit("[!] pip install defusedxml  (stdlib XML parsers are XXE-vulnerable on untrusted input)")
    root = ET.parse(path).getroot()
    pkg = root.attrib.get("package", "?")
    target_sdk = 0
    uses = root.find("uses-sdk")
    if uses is not None:
        target_sdk = int(_attr(uses.attrib, "targetSdkVersion") or 0)
    components = {"activity": [], "service": [], "receiver": [], "provider": []}
    deep_links = []
    for tag in components:
        for el in root.iter(tag):
            name = _attr(el.attrib, "name")
            exported_attr = _attr(el.attrib, "exported")
            has_filter = el.find("intent-filter") is not None
            exported = (exported_attr.lower() == "true") if exported_attr is not None else (has_filter and target_sdk < 31)
            rec = {"name": name, "exported": exported, "permission": _attr(el.attrib, "permission"),
                   "has_intent_filter": has_filter}
            if tag == "provider":
                rec["authorities"] = _attr(el.attrib, "authorities")
            components[tag].append(rec)
            for f in el.findall("intent-filter"):
                cats = [_attr(c.attrib, "name") for c in f.findall("category")]
                for d in f.findall("data"):
                    scheme = _attr(d.attrib, "scheme")
                    if scheme:
                        deep_links.append({"component": name, "scheme": scheme,
                                           "host": _attr(d.attrib, "host"),
                                           "browsable": "android.intent.category.BROWSABLE" in cats})
    return {"package": pkg, "target_sdk": target_sdk, "components": components, "deep_links": deep_links}


def summarize(data):
    out = ["[summary]"]
    c = data["components"]
    for tag in c:
        exp = [x["name"] for x in c[tag] if x.get("exported")]
        out.append("  exported %-9s: %d  %s" % (tag, len(exp), exp[:6]))
    risky = data.get("application_flags", {})
    for f in ("debuggable", "allowBackup", "usesCleartextTraffic"):
        if str(risky.get(f)).lower() == "true":
            out.append("  [!] application android:%s=true" % f)
    if not risky.get("networkSecurityConfig"):
        out.append("  [i] no networkSecurityConfig (user CA may be trusted)")
    for a in c.get("activity", []):
        if a.get("exported") and a.get("task_hijack_risk"):
            out.append("  [!] task-hijack exposure: %s (taskAffinity=%r launchMode=%r)"
                       % (a["name"], a.get("taskAffinity"), a.get("launchMode")))
    out.append("  deep links: %d  %s" % (len(data["deep_links"]),
               sorted({d["scheme"] + "://" + (d.get("host") or "") for d in data["deep_links"]})[:8]))
    return "\n".join(out)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("target", help="APK or AndroidManifest.xml")
    ap.add_argument("-o", "--out", help="write JSON here")
    args = ap.parse_args()

    if args.target.lower().endswith(".apk"):
        try:
            data = analyze_with_androguard(args.target)
        except ImportError:
            sys.exit("[!] androguard required for APKs: pip install androguard")
    else:
        try:
            data = analyze_with_androguard(args.target)  # androguard also parses standalone AXML
        except Exception:
            data = analyze_text_xml(args.target)

    print(summarize(data))
    if args.out:
        with open(args.out, "w", encoding="utf-8") as fh:
            json.dump(data, fh, indent=2)
        print("[+] wrote " + args.out)


if __name__ == "__main__":
    main()
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall