# Recherche de fichiers PHP malveillants (lecture seule). Usage : python3 malscan.py <racine>...
import os, re, sys
SIG = [
    (5, re.compile(rb'eval\s*\(\s*(base64_decode|gzinflate|gzuncompress|str_rot13|strrev|\$_(POST|GET|REQUEST|COOKIE))', re.I)),
    (5, re.compile(rb'assert\s*\(\s*\$_(POST|GET|REQUEST|COOKIE)', re.I)),
    (4, re.compile(rb'(system|shell_exec|passthru|exec|popen|proc_open)\s*\(\s*\$_(POST|GET|REQUEST|COOKIE)', re.I)),
    (4, re.compile(rb'preg_replace\s*\(\s*["\'].{1,40}/e["\']', re.I)),
    (3, re.compile(rb'gzinflate\s*\(\s*base64_decode|str_rot13\s*\(\s*base64_decode|base64_decode\s*\(\s*str_rot13', re.I)),
    (3, re.compile(rb'move_uploaded_file\s*\([^;]{0,80}\.php', re.I)),
    (3, re.compile(rb'ignore_user_abort\(true\);@?set_time_limit\(0\)', re.I)),
    (3, re.compile(rb'(FilesMan|WSO |b374k|c99shell|r57shell|IndoXploit|alfa-?shell|marijuana)', re.I)),
    (2, re.compile(rb'\$\w+\s*=\s*["\'][A-Za-z0-9+/=]{800,}["\']')),
    (2, re.compile(rb'create_function\s*\(', re.I)),
    (2, re.compile(rb'\\x[0-9a-f]{2}(\\x[0-9a-f]{2}){30,}', re.I)),
    (1, re.compile(rb'base64_decode\s*\(', re.I)),
]
SKIP = re.compile(r'/(vendor|node_modules|\.git|partial-lead-lib|storage/framework|cache)/')
for root in sys.argv[1:]:
    for dp, dn, fn in os.walk(root):
        if SKIP.search(dp + '/'):
            continue
        for f in fn:
            if not re.search(r'\.(php\d?|phtml|phar|inc)$|\.php\.', f, re.I):
                continue
            p = os.path.join(dp, f)
            try:
                if os.path.getsize(p) > 3_000_000: continue
                b = open(p, 'rb').read()
            except Exception:
                continue
            sc, hits = 0, []
            for w, rx in SIG:
                if rx.search(b):
                    sc += w; hits.append(rx.pattern[:30].decode('latin1'))
            if sc >= 4:
                print(f'{sc}\t{p}\t{" | ".join(hits)[:140]}')
