# FindSecurityChecks.py - Ghidra script (PyGhidra / GhidraScript)
# Tự động hóa: quét strings nhóm Repackaged/Signature -> XREF -> hàm chứa -> decompile
# -> phát hiện exit/abort -> xuất báo cáo JSON + text.
# @category Security.Analysis
# @runtime PyGhidra
#
# Usage (headless):
#   analyzeHeadless <proj_dir> <proj> -import <binary> \
#     -scriptPath <dir> -postScript FindSecurityChecks.py <out.json> [extra_addr_hex ...]
# Usage (GUI): Script Manager -> FindSecurityChecks.py  (output ghidra_findings.json next to project)
import json, os
from ghidra.app.decompiler import DecompInterface, DecompileOptions
from ghidra.util.task import ConsoleTaskMonitor
from ghidra.program.model.symbol import RefType

# Nhom Repackaged/Signature (trong tam) - co the mo rong
KEYWORD_GROUPS = {
    "repack_signature": [
        "SecStaticCodeCheckValidity", "SecCodeCopySigningInformation", "SecCodeCheckValidity",
        "SecStaticCode", "SecCertificateCopyData", "SecTrustEvaluate", "SecTaskCopyValueForEntitlement",
        "_CodeSignature", "CodeResources", "embedded.mobileprovision", "mobileprovision",
        "codesign", "Code Signing", "integrity", "bundleIdentifier", "teamIdentifier",
        "application-identifier", "SignerIdentity", "Apple iPhone OS Application Signing",
        "Apple iPhone Certification Authority",
    ],
    "tamper_manifest": [
        "bshield", "build-info", "mach-headers", "tamper", "repackag", "signature",
        "Entitlements",
    ],
}

EXIT_FUNCS = ("exit", "_exit", "abort", "_abort", "kill", "__pthread_kill", "raise",
              "exit_group", "abort_with_payload", "os_crash", "trap", "__builtin_trap")

def _log(msg):
    print("[FindSecurityChecks] %s" % msg)

def scan_strings(program, monitor):
    """Iterate defined data; return list of (va, text, blockname) matching keywords."""
    allkw = {}
    for g, kws in KEYWORD_GROUPS.items():
        for kw in kws:
            allkw[kw] = g
    listing = program.getListing()
    hits = []
    it = listing.getDefinedData(True)
    n = 0
    for d in it:
        n += 1
        if monitor.isCancelled():
            break
        try:
            dt = d.getDataType().getName().lower()
        except Exception:
            continue
        if "string" not in dt and "char" not in dt:
            continue
        try:
            val = d.getValue()
            text = str(val)
        except Exception:
            continue
        if not text:
            continue
        for kw, grp in allkw.items():
            if kw.lower() in text.lower():
                hits.append({"va": d.getAddress().getOffset(), "text": text[:200],
                             "keyword": kw, "group": grp,
                             "block": str(d.getAddress())})
                break
    _log("defined data scanned=%d, string hits=%d" % (n, len(hits)))
    return hits

def containing_function(program, addr):
    fm = program.getFunctionManager()
    f = fm.getFunctionContaining(addr)
    if f is None:
        f = fm.getFunctionAt(addr)
    return f

def decompile_function(program, func, monitor, timeout=90):
    di = DecompInterface()
    opts = DecompileOptions()
    di.setOptions(opts)
    di.openProgram(program)
    try:
        res = di.decompileFunction(func, timeout, monitor)
        if res.decompileCompleted():
            return res.getDecompiledFunction().getC()
        return "// decompile failed: %s" % res.getErrorMessage()
    finally:
        di.dispose()

def called_externs(program, func, monitor):
    """Names of external functions reached by direct calls from func (incl. thunks)."""
    fm = program.getFunctionManager()
    out = set()
    body = func.getBody()
    it = program.getListing().getInstructions(body, True)
    for insn in it:
        if monitor.isCancelled():
            break
        if insn.getMnemonicString().lower().startswith("b") and "bl" in insn.getMnemonicString().lower():
            flows = insn.getFlows()
            for t in flows:
                cf = fm.getFunctionAt(t)
                if cf is None:
                    cf = fm.getReferencedFunction(t)
                if cf is None:
                    continue
                name = cf.getName()
                if cf.isExternal() or cf.isThunk():
                    out.add(name)
                # follow thunk one level
                if cf.isThunk():
                    for tht in cf.getCalledFunctions(monitor):
                        out.add(tht.getName())
    return sorted(out)

def run():
    program = currentProgram
    monitor = ConsoleTaskMonitor()
    args = getScriptArgs()
    outpath = args[0] if args else "ghidra_findings.json"
    extra_addrs = []
    for a in args[1:]:
        try:
            extra_addrs.append(int(a, 16))
        except ValueError:
            pass

    _log("program=%s" % program.getName())
    hits = scan_strings(program, monitor)

    # map va -> text for string lookup
    af = program.getAddressFactory().getDefaultAddressSpace()
    findings = []
    seen_funcs = {}

    def add_finding(fnd):
        findings.append(fnd)

    for h in hits:
        addr = af.getAddress(h["va"])
        refs = program.getReferenceManager().getReferencesTo(addr)
        ref_list = []
        funcs = {}
        for r in refs:
            ra = r.getFromAddress()
            ref_list.append({"va": ra.getOffset(), "type": str(r.getReferenceType())})
            f = containing_function(program, ra)
            if f is not None:
                funcs[f.getEntryPoint().getOffset()] = f
        for fea, f in funcs.items():
            key = (fea, h["va"])
            if key in seen_funcs:
                continue
            seen_funcs[key] = True
            _log("decompile %s (ref to '%s')" % (f.getName(), h["text"][:40]))
            c = decompile_function(program, f, monitor)
            exts = called_externs(program, f, monitor)
            exit_hits = [e for e in exts if e.lower().strip("_") in [x.strip("_") for x in EXIT_FUNCS]]
            add_finding({
                "function": f.getName(), "func_va": fea,
                "string": h["text"][:120], "string_va": h["va"],
                "keyword": h["keyword"], "group": h["group"],
                "refs": ref_list,
                "called_externs": exts,
                "exit_calls": exit_hits,
                "decompiled_c": c[:12000],
            })

    # extra addresses from CLI (e.g., results from capstone XREF phase)
    for a in extra_addrs:
        addr = af.getAddress(a)
        f = containing_function(program, addr)
        if f is None:
            _log("no function at %#x" % a)
            continue
        key = (f.getEntryPoint().getOffset(), -1)
        if key in seen_funcs:
            continue
        seen_funcs[key] = True
        _log("decompile %s @ %#x (extra)" % (f.getName(), a))
        c = decompile_function(program, f, monitor)
        exts = called_externs(program, f, monitor)
        exit_hits = [e for e in exts if e.lower().strip("_") in [x.strip("_") for x in EXIT_FUNCS]]
        add_finding({
            "function": f.getName(), "func_va": f.getEntryPoint().getOffset(),
            "string": "(extra address)", "string_va": a,
            "keyword": "", "group": "extra",
            "refs": [], "called_externs": exts, "exit_calls": exit_hits,
            "decompiled_c": c[:12000],
        })

    with open(outpath, "w", encoding="utf-8") as fp:
        json.dump({"program": program.getName(), "findings": findings}, fp, ensure_ascii=False, indent=1)
    _log("findings=%d -> %s" % (len(findings), outpath))

run()
