#!/usr/bin/env python3 """Static PE trait extractor. Never executes the binary.""" from __future__ import annotations import hashlib, json, re, struct, sys from datetime import datetime, timezone, timedelta from pathlib import Path try: import pefile except ImportError: sys.path.insert(0, str(Path("/workspace/satoshi-code/kong/.venv/lib"))) # venv site import glob for p in glob.glob("/workspace/satoshi-code/kong/.venv/lib/python*/site-packages"): sys.path.insert(0, p) import pefile # Bucharest is EET (UTC+2) on 26 Nov 2026; PE timestamps are UTC. EET = timezone(timedelta(hours=2), name="EET") # Microsoft Rich-header product IDs commonly seen in VC++ 4–7 era. # Sources: open-source tables (xorpse/rich-header, hasherezade, Microsoft). RICH_PROD = { 1: "Importer (imp.exe) / VS", 2: "Resource compiler (CVTRES) older", 4: "Visual C++ 4? linker/alias", 6: "CVTRES 5.00", 7: "link 5.10 (VC++ 5)", 9: "CVTRES 5.00", 10: "link 5.10", 11: "cvtres 5.00 / VC5", 13: "cvtres 5.00", 14: "link 5.10 / Masm 6.13?", 19: "import 5.00 / VC5", 20: "link 5.10 / VC5", 23: "Masm 6.14?", 24: "link 5.12 / VC6 early?", 25: "cvtres 5.00", 40: "utc12 (VC6 C compiler 12.00) untitled", 42: "utc12 (VC6 C/C++ compiler)", 44: "cvtres 5.00 / VC6", 45: "link 6.00 (VC++ 6)", 48: "alias obj from VC6", 79: "utc13 / VC7 compiler?", 80: "utc13", 84: "link 7.00 (VC++ 7 / VS.NET 2002)", 85: "cvtres 7.00", 95: "utc13_inv", 98: "link 7.10 (VC++ 7.1 / VS.NET 2003)", 113: "utc15 / VC8?", 120: "link 8.00 (VC++ 8 / VS 2005)", 123: "cvtres 8.00", 131: "utc16 / VC9 compiler", 137: "link 9.00 (VC++ 9 / VS 2008)", 145: "cvtres 9.00", } RTTI_RE = re.compile(rb"\.\?A[UV](?P[\w@]+)") # MSVC RTTI type descriptor: ".?AVCFoo@@" or ".?AVClassName@@" PDB_RE = re.compile(rb"(?:[A-Za-z]:[\\/][^\x00]{3,220}\.pdb)|(?:[^\x00]{3,220}\.pdb)", re.I) FILE_RE = re.compile(rb"(?:[A-Za-z]:[\\/][^\x00\r\n]{3,200}\.(?:c|cpp|cc|cxx|h|hpp|rc)|[^\x00\r\n]{3,80}\.(?:c|cpp|cc|cxx|h|hpp))", re.I) ASSERT_RE = re.compile(rb"(?:Assertion failed|assert\s*\(|_assert|__FILE__)", re.I) INTERESTING_DLLS = { "mfc", "mfc40", "mfc42", "mfc70", "mfc71", "mfc80", "mfc90", "mfco42", "mfcd42", "msvcrtd", "msvcrt", "msvcrt20", "msvcrt40", "msvcrt70", "msvcr71", "msvcr80", "msvcr90", "msvcp60", "msvcp70", "msvcp71", "msvcp80", "msvcp90", "msvcirt", "msvbvm50", "msvbvm60", "vb40032", "wxmsw", "wxmsw28", "wxbase", "wxmsw28u", "wxmsw26", "libeay32", "ssleay32", "libssl32", "libcrypto", "mingwm10", "libgcc_s_dw2-1", "libstdc++-6", "crtdll", "ole32", "oleaut32", "olepro32", "kernel32", "user32", "gdi32", "advapi32", "ws2_32", "wsock32", "comctl32", "comdlg32", } def sha256(path: Path) -> str: h = hashlib.sha256() with path.open("rb") as f: for chunk in iter(lambda: f.read(1 << 20), b""): h.update(chunk) return h.hexdigest() def ts_iso(epoch: int) -> str: if not epoch: return "0 (unset/zeroed)" try: utc = datetime.fromtimestamp(epoch, timezone.utc) eet = utc.astimezone(EET) return f"{utc.strftime('%Y-%m-%d %H:%M:%S UTC')} / {eet.strftime('%Y-%m-%d %H:%M:%S EET')}" except Exception as e: return f"{epoch} (unparsed: {e})" def ascii_strings(data: bytes, minlen=5): out = [] buf = [] for b in data: if 32 <= b < 127: buf.append(b) else: if len(buf) >= minlen: out.append(bytes(buf)) buf = [] if len(buf) >= minlen: out.append(bytes(buf)) return out def utf16le_strings(data: bytes, minlen=5): out = [] i = 0 n = len(data) while i + 2 <= n: buf = [] j = i while j + 2 <= n: c = data[j] | (data[j + 1] << 8) if 32 <= c < 127: buf.append(c) j += 2 else: break if len(buf) >= minlen: out.append(bytes(chr(c) for c in buf).decode("ascii")) i = j + 2 else: i += 2 if data[i+1:i+2] == b"\x00" or buf else 1 return out def parse_rtti_name(raw: bytes) -> str: # ".?AVCWallet@@" or ".?AVCNode@std@@" s = raw.decode("ascii", "replace") if s.startswith(".?A"): s = s[4:] # drop .?AV or .?AU — actually 4 chars: . ? A V # above is wrong if I sliced 4 leaving starting at V's following... return s def demangle_msvc_simple(raw: bytes) -> str: """Best-effort: '.?AVCWallet@@' -> 'CWallet', '.?AV?$vector@...' left as-is.""" try: s = raw.decode("ascii") except Exception: return repr(raw) if s.startswith(".?A") and len(s) >= 4: kind = "class" if s[3] == "V" else "struct" if s[3] == "U" else s[3] rest = s[4:] rest = rest.replace("@@", "") return f"{kind} {rest}" return s def analyze(path: Path) -> dict: data = path.read_bytes() rec = { "path": str(path), "name": path.name, "size": len(data), "sha256": sha256(path), "errors": [], } try: pe = pefile.PE(data=data, fast_load=False) except Exception as e: rec["errors"].append(f"pefile: {e}") rec["is_pe"] = False return rec rec["is_pe"] = True rec["machine"] = hex(pe.FILE_HEADER.Machine) rec["timedatestamp_raw"] = int(pe.FILE_HEADER.TimeDateStamp) rec["timedatestamp"] = ts_iso(pe.FILE_HEADER.TimeDateStamp) rec["linker"] = f"{pe.OPTIONAL_HEADER.MajorLinkerVersion}.{pe.OPTIONAL_HEADER.MinorLinkerVersion}" rec["os_version"] = f"{pe.OPTIONAL_HEADER.MajorOperatingSystemVersion}.{pe.OPTIONAL_HEADER.MinorOperatingSystemVersion}" _SUBSYS = {1:"NATIVE",2:"WINDOWS_GUI",3:"WINDOWS_CUI",5:"OS2_CUI",7:"POSIX_CUI",9:"WINDOWS_CE_GUI",10:"EFI_APPLICATION",14:"XBOX",16:"WINDOWS_BOOT_APPLICATION"} rec["subsystem"] = _SUBSYS.get(pe.OPTIONAL_HEADER.Subsystem, str(pe.OPTIONAL_HEADER.Subsystem)) rec["image_base"] = hex(pe.OPTIONAL_HEADER.ImageBase) rec["sections"] = [s.Name.rstrip(b"\x00").decode("latin1", "replace") for s in pe.sections] rec["characteristics"] = pe.FILE_HEADER.Characteristics # Rich header rec["rich"] = None try: rich = pe.parse_rich_header() if rich: vals = [] # pefile returns dict with 'values' list of (compid, count) or raw raw_vals = rich.get("values") or rich.get("records") or [] # pefile 2024: 'values' is flat list [prodid, build, count, prodid, build, count, ...] # actually in recent pefile: values is list of alternating? Let's inspect. rec["rich_keys"] = list(rich.keys()) if "values" in rich and isinstance(rich["values"], list): v = rich["values"] # pefile documentation: values is a list of integers, 2 per record: # xor'd already: for i in range(0,len,2): comp_id, count = values[i], values[i+1] # comp_id = (prodid << 16) | build pairs = [] if v and isinstance(v[0], int): for i in range(0, len(v) - 1, 2): compid, count = v[i], v[i + 1] prod = (compid >> 16) & 0xFFFF build = compid & 0xFFFF pairs.append({ "prod_id": prod, "build": build, "count": count, "meaning": RICH_PROD.get(prod, "unknown product id"), }) rec["rich"] = pairs else: rec["rich_raw_preview"] = str(rich)[:2000] except Exception as e: rec["errors"].append(f"rich: {e}") # Imports imports = [] dlls = [] try: if hasattr(pe, "DIRECTORY_ENTRY_IMPORT"): for entry in pe.DIRECTORY_ENTRY_IMPORT: dll = entry.dll.decode("ascii", "replace") if entry.dll else "?" dlls.append(dll) fns = [] for imp in entry.imports: if imp.name: fns.append(imp.name.decode("ascii", "replace")) elif imp.ordinal is not None: fns.append(f"ord#{imp.ordinal}") imports.append({"dll": dll, "count": len(fns), "functions": fns}) except Exception as e: rec["errors"].append(f"imports: {e}") rec["import_dlls"] = dlls rec["imports"] = imports # Exports exports = [] try: if hasattr(pe, "DIRECTORY_ENTRY_EXPORT") and pe.DIRECTORY_ENTRY_EXPORT: for exp in pe.DIRECTORY_ENTRY_EXPORT.symbols: if exp.name: exports.append(exp.name.decode("ascii", "replace")) except Exception as e: rec["errors"].append(f"exports: {e}") rec["exports"] = exports # Debug directory / PDB pdbs = [] debug_types = [] try: if hasattr(pe, "DIRECTORY_ENTRY_DEBUG"): for d in pe.DIRECTORY_ENTRY_DEBUG: typ = d.struct.Type debug_types.append(int(typ)) # CODEVIEW try: if hasattr(d, "entry") and d.entry is not None: ev = d.entry if hasattr(ev, "PdbFileName"): pdbs.append(ev.PdbFileName.decode("ascii", "replace").rstrip("\x00")) except Exception: pass except Exception as e: rec["errors"].append(f"debug: {e}") rec["debug_types"] = debug_types rec["pdb_from_debugdir"] = pdbs # Resources / version info version = {} try: if hasattr(pe, "VS_VERSIONINFO"): # FileInfo if hasattr(pe, "FileInfo"): for fi in pe.FileInfo: for item in fi: if hasattr(item, "StringTable"): for st in item.StringTable: for k, val in st.entries.items(): kk = k.decode("ascii", "replace") if isinstance(k, bytes) else str(k) vv = val.decode("ascii", "replace") if isinstance(val, bytes) else str(val) version[kk] = vv if hasattr(pe, "VS_FIXEDFILEINFO") and pe.VS_FIXEDFILEINFO: ffi = pe.VS_FIXEDFILEINFO[0] version["file_version_raw"] = f"{ffi.FileVersionMS >> 16}.{ffi.FileVersionMS & 0xFFFF}.{ffi.FileVersionLS >> 16}.{ffi.FileVersionLS & 0xFFFF}" version["product_version_raw"] = f"{ffi.ProductVersionMS >> 16}.{ffi.ProductVersionMS & 0xFFFF}.{ffi.ProductVersionLS >> 16}.{ffi.ProductVersionLS & 0xFFFF}" except Exception as e: rec["errors"].append(f"version: {e}") rec["version"] = version # Strings strs = ascii_strings(data, 5) rec["string_count"] = len(strs) # PDB / paths / RTTI from strings blob = b"\x00".join(strs) # keep simple: search raw data rtti = [] for m in re.finditer(rb"\.\?A[UV][ -~]{1,200}", data): raw = m.group(0).split(b"\x00")[0] if raw not in rtti: rtti.append(raw) rec["rtti_raw"] = [x.decode("latin1", "replace") for x in rtti[:400]] rec["rtti_demangled"] = [demangle_msvc_simple(x) for x in rtti[:400]] pdb_hits = [] for m in re.finditer(rb"[A-Za-z]:[\\/][ -~]{3,220}\.pdb", data, re.I): pdb_hits.append(m.group(0).decode("latin1", "replace")) for m in re.finditer(rb"[ -~]{3,180}\.pdb", data, re.I): s = m.group(0).decode("latin1", "replace") if s not in pdb_hits and "pdb" in s.lower(): # filter garbage if "\\" in s or "/" in s or s.lower().endswith(".pdb"): pdb_hits.append(s) rec["pdb_strings"] = pdb_hits[:50] file_hits = [] for m in re.finditer(rb"[A-Za-z]:[\\/][ -~]{3,200}\.(?:c|cpp|cc|cxx|h|hpp|rc|asm)", data, re.I): file_hits.append(m.group(0).decode("latin1", "replace")) rec["source_path_strings"] = file_hits[:80] # interesting typenames / Hungarian-like identifiers in ASCII strings names = [] hung = [] cclass = [] for s in strs: try: t = s.decode("ascii") except Exception: continue if re.fullmatch(r"C[A-Z][A-Za-z0-9_]{1,40}", t): cclass.append(t) if re.search(r"\b[nfbvpszmp][A-Z][A-Za-z0-9]{1,30}\b", t): hung.append(t) rec["c_prefixed_token_strings"] = sorted(set(cclass))[:80] # don't dump too many hung false positives; keep shorter tokens only if they look like identifiers rec["hungarianish_strings_sample"] = sorted({t for t in hung if len(t) < 60})[:40] # format / error strings fmt = [] for s in strs: try: t = s.decode("ascii") except Exception: continue if "%" in t and re.search(r"%[-+#0-9 hlL]*[diuxXsfFGgeEcpnS]", t): fmt.append(t) rec["printf_format_strings"] = fmt[:80] errorish = [] keys = ("error", "failed", "exception", "assert", "debug print", "cannot ", "can't ", "unable") for s in strs: try: t = s.decode("ascii") except Exception: continue low = t.lower() if any(k in low for k in keys) and 8 <= len(t) <= 160: errorish.append(t) rec["error_or_assert_strings"] = errorish[:80] # toolchain hints from strings hints = [] for s in strs: try: t = s.decode("ascii") except Exception: continue low = t.lower() for needle in ( "mingw", "gcc", "g++", "libstdc++", "msvbvm", "visual basic", "microsoft visual c", "visual c++", " borland", "delphi", "mfc", "wxwidgets", "wxwindows", "openssl", "crypto++", "cryptopp", "stlport", "dinkumware", "msvcrt", "mingwm10", "libeay32", "vba6", "vb5", ): if needle in low: hints.append(t) break rec["toolchain_hint_strings"] = hints[:60] # high-level flags dlls_l = [d.lower() for d in dlls] def has_dll(prefix): return any(d.startswith(prefix) or prefix in d for d in dlls_l) rec["flags"] = { "imports_msvbvm50": has_dll("msvbvm50"), "imports_msvbvm60": has_dll("msvbvm60"), "imports_mfc": any("mfc" in d for d in dlls_l), "imports_msvcrt": any(d.startswith("msvcrt") or d.startswith("msvcr") or d.startswith("msvcp") for d in dlls_l), "imports_mingwm10": has_dll("mingwm10") or has_dll("libgcc") or has_dll("libstdc"), "imports_libeay32": has_dll("libeay32") or has_dll("ssleay32") or has_dll("libssl") or has_dll("libcrypto"), "imports_wx": any(d.startswith("wx") for d in dlls_l), "has_rich_header": bool(rec.get("rich")), "has_rtti": bool(rtti), "has_pdb": bool(pdbs or pdb_hits), } return rec def main(): paths = [Path(p) for p in sys.argv[1:]] out = [analyze(p) for p in paths] json.dump(out, sys.stdout, indent=2) print() if __name__ == "__main__": main()