"""Reproduce the GraftLoader -> Remcos unpacking from data alone. Nothing is executed or loaded. Usage: python3 decode_chain.py (writes decoded stages to ./out/)""" import base64, hashlib, io, pathlib, re, struct, sys from PIL import Image S = pathlib.Path(sys.argv[1]); OUT = pathlib.Path("out"); OUT.mkdir(exist_ok=True) sha = lambda b: hashlib.sha256(b).hexdigest() def resx_blob(name): x = (S / "src/LavenderDistillery.Properties.Resources.resx").read_text(encoding="utf-8") return base64.b64decode(re.search(rf']*>(.*?)', x, re.S).group(1)) # Stage 1 -> 2: the "Credit" bitmap, read column by column, R G B per pixel, alpha ignored blob = resx_blob("Credit") img = Image.open(io.BytesIO(blob[blob.find(b"BM"):])).convert("RGB") w, h = img.size px = img.load() stage2 = bytearray() for i in range(w * h): stage2 += bytes(px[i // h, i % h]) stage2 = bytes(stage2[:69632]) (OUT / "stage2.bin").write_bytes(stage2) print(f"[1] Credit {w}x{h} -> stage2 {len(stage2)} bytes, MZ={stage2[:2] == b'MZ'}, sha256 {sha(stage2)[:16]}") # Stage 2 -> 3: the "gvvU" bitmap, cropped by 177 x 225, ARGB ints little endian, then XOR blob = resx_blob("gvvU") img = Image.open(io.BytesIO(blob[blob.find(b"\x89PNG"):])).convert("RGBA") cw, ch = img.width - 177, img.height - 225 px = img.load() buf = bytearray() for x in range(cw): for y in range(ch): r, g, b, a = px[x, y] buf += bytes((b, g, r, a)) # Color.ToArgb() written with BitConverter n = int.from_bytes(buf[:4], "little") data = buf[4:4 + n] seed = data[-1] ^ 0x70 key = "oix".encode("utf-16-be")[:3] # 00 6f 00: the index wraps after 3 bytes stage3 = bytes(d ^ seed ^ key[i % 3] for i, d in enumerate(data)) (OUT / "stage3.bin").write_bytes(stage3) print(f"[2] gvvU crop {cw}x{ch}, length {n}, seed 0x{seed:02x} -> stage3 MZ={stage3[:2] == b'MZ'}, sha256 {sha(stage3)[:16]}") # Stage 3 -> 4: resource DRPoihQr, XOR with "wKdwZFFW" then subtract the next cipher byte c = (S / "stage2/stage4/DRPoihQr.enc").read_bytes() k = b"wKdwZFFW" p = bytearray(((c[i] ^ k[i % 8]) - c[i + 1]) & 0xFF for i in range(len(c) - 1)) print(f"[3] DRPoihQr {len(c)} bytes -> first byte 0x{p[0]:02x}, patched to 0x4d") p[0] = 0x4D (OUT / "payload.bin").write_bytes(p) print(f" payload {len(p)} bytes, sha256 {sha(bytes(p))[:16]}") # Stage 4: Remcos keeps its settings RC4 encrypted in RCDATA "SETTINGS" (first byte = key length) def rcdata(pe, want): e = struct.unpack_from(" {len(fields)} fields") for idx in (0, 1, 10, 14, 17): print(f" field {idx:>2}: {fields[idx].replace(chr(30), " ")[:120]}")