#!/usr/bin/env python3
"""Sweep all app binaries for environment-detection vocabulary."""
import os, sys, re
sys.stdout.reconfigure(encoding='utf-8')

ROOT = r'patch_src\Payload\Driver.app'

GROUPS = {
    'dev-mode': [b'DeveloperMode', b'Developer Mode', b'developer-mode', b'DVTDeveloper',
                 b'DVTFinalTarget', b'developerdisk', 'DevelopersDisk'.encode()],
    'mobilegestalt': [b'MGCopyAnswer', b'libMobileGestalt', b'MobileGestalt', b'MGSetAnswer'],
    'sysctl': [b'sysctl', b'kern.bootargs', b'kern.osversion', b'hw.machine', b'kern.osrelease'],
    'ptrace/anti-debug': [b'ptrace', b'PT_DENY_ATTACH', b'syscall', b'svc ', b'csops', b'CS_OPS'],
    'jailbreak-paths': [b'/Applications/Cydia', b'/bin/bash', b'/usr/sbin/sshd', b'/etc/apt',
                        b'/private/var/lib/apt', b'/var/jb', b'/usr/local/bin', b'Substrate',
                        b'substrate', b'TweakInject', b'/var/lib/dpkg', b'cydia://',
                        b'/Library/MobileSubstrate', b'libsubstrate', b'ellekit'],
    'hook-detect': [b'frida', b'Frida', b'gum-js', b'cynject', b'Cycript', b'cycript',
                    b'fishhook', b'rebind_symbols', b'sub_2', b'goblin'],
    'signature/provision': [b'SecStaticCode', b'SecCodeCopy', b'SecCodeCheckValidity',
                            b'embedded.mobileprovision', b'application-identifier',
                            b'SecTaskCopyValueForEntitlement', b'cmsDecoder', b'ProvisioningProfile'],
    'dyld-enum': [b'_dyld_image_count', b'_dyld_get_image_name', b'dyld_get_program_sdk',
                  b'DLAddrInfo'],
    'sim/remote': [b'isSimulated', b'SimulateLocation', b'simulateLocation', b'LLA',
                   b'isJailbroken', b'isJailBreak', b'jailbroken', b'Jailbroken'],
    'proxy/vpn': [b'CFNetworkCopySystemProxySettings', b'kCFNetworkProxiesHTTP',
                  b'utun', b'NEVPNStatus', b'NEVPNManager', b'getifaddrs'],
}

TARGETS = {}
for dp, dn, fn in os.walk(ROOT):
    for f in fn:
        p = os.path.join(dp, f)
        if not f.endswith(('.dylib',)) and 'framework' not in p and not f == 'Driver':
            # still scan binaries inside .framework dirs and the main executable
            pass
        try:
            sz = os.path.getsize(p)
            if sz > 400 * 1024 * 1024:
                continue
            # only scan likely binaries
            with open(p, 'rb') as fh:
                magic = fh.read(4)
            if magic not in (b'\xcf\xfa\xed\xfe', b'\xca\xfe\xba\xbe', b'\xfe\xed\xfa\xcf'):
                continue
        except Exception:
            continue
        TARGETS[p.replace(ROOT, '.')] = p

print('binaries to scan:', len(TARGETS))
report = {}
for label, path in sorted(TARGETS.items()):
    try:
        d = open(path, 'rb').read()
    except Exception:
        continue
    for group, needles in GROUPS.items():
        for s in needles:
            i = d.find(s)
            if i >= 0:
                report.setdefault(group, []).append((label, s.decode('latin1')[:24], hex(i)))

for group in GROUPS:
    hits = report.get(group, [])
    if not hits:
        continue
    byfile = {}
    for f, s, o in hits:
        byfile.setdefault(f, []).append(s)
    print('\n== %s ==' % group)
    for f, syms in sorted(byfile.items()):
        print('  %s: %s' % (f, sorted(set(syms))))
