# apply_patches.py - vaz bshield theo bang patch trong report_security_checks.md
# bshield: __TEXT vmaddr=0 => file offset == VA
# P1 0x2a3868 violation handler (entry -> ret)  : ff8302d1 fd7b09a9 -> 000080d2 c0035fd6
# P2 0x1db0ec abort helper 55 call site (-> ret): ffc300d1 fd7b02a9 -> 000080d2 c0035fd6
# P3 0x2b2f84 manifest getter (-> ret, NULL)    : ff4301d1 fd7b04a9 -> 000080d2 c0035fd6
import hashlib, shutil, sys, os

SRC = r"E:\ios\zsign-windows-x64\build_fake319\Payload\Driver.app\Frameworks\bshield.framework\bshield"
DST = r"E:\ios\zsign-windows-x64\patch_out\bshield"

PATCHES = [
    ("P1 violation handler", 0x2A3868, bytes.fromhex("ff8302d1fd7b09a9"), bytes.fromhex("000080d2c0035fd6")),
    ("P2 abort helper",      0x1DB0EC, bytes.fromhex("ffc300d1fd7b02a9"), bytes.fromhex("000080d2c0035fd6")),
    ("P3 manifest getter",   0x2B2F84, bytes.fromhex("ff4301d1fd7b04a9"), bytes.fromhex("000080d2c0035fd6")),
]

def main(layer2=True):
    os.makedirs(os.path.dirname(DST), exist_ok=True)
    shutil.copyfile(SRC, DST)
    data = bytearray(open(DST, "rb").read())
    ok = True
    for name, off, old, new in PATCHES:
        if off + len(old) > len(data):
            print(f"[!] {name}: offset 0x{off:x} vuot qua kich thuoc file!"); ok = False; continue
        cur = bytes(data[off:off+len(old)])
        if cur == old:
            data[off:off+len(old)] = new
            print(f"[+] {name} @ 0x{off:x}: da patch ({old.hex()} -> {new.hex()})")
        elif cur == new:
            print(f"[=] {name} @ 0x{off:x}: da patch tu truoc, bo qua")
        else:
            print(f"[!] {name} @ 0x{off:x}: prolog KHONG khop! thay {cur.hex()} thay vi {old.hex()}"); ok = False
    if not ok:
        print("[!] Co patch loi, KHONG ghi file."); sys.exit(1)
    open(DST, "wb").write(bytes(data))
    print("SHA-256:", hashlib.sha256(bytes(data)).hexdigest())
    print("OK ->", DST)

if __name__ == "__main__":
    main()
