Exploit database

GH-cc9bda364f58e8812196c41f89e05164

ampedwastaken/php2shell-cve-2026-109618-cve-2026-109619

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-109618

413 sources

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

Repository files14

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

shell_canary.py

Python · 8,115 bytes
#!/usr/bin/env python3
"""Authorized PHP-spawned shell process canary. Not a CVE or RCE exploit.

Starts a bounded, noninteractive /bin/sh process under the PHP CLI runtime using
an existing SSH key-based session (or locally). It neither accepts an arbitrary
remote command nor opens a reverse listener. A unique marker is included in the
shell process command line for correlation with process telemetry.
"""

import argparse
from datetime import datetime, timezone
import json
from pathlib import Path
import re
import secrets
import shlex
import subprocess
import sys

MAX_REPORT_BYTES = 16384
TARGET_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_.-]{0,31}@[A-Za-z0-9][A-Za-z0-9.-]{0,252}$")
RESULT_PREFIX = "PHP2S_CANARY_RESULT:"

PHP_CANARY = r'''
$seconds = __DURATION__;
$marker = '__MARKER__';
function result(array $info) : void {
    echo 'PHP2S_CANARY_RESULT:' . json_encode($info, JSON_UNESCAPED_SLASHES) . "\n";
    flush();
}
if (!function_exists('proc_open') || !function_exists('proc_terminate') || !is_executable('/bin/sh')) {
    result(['outcome' => 'NOT_STARTED', 'reason' => 'proc_open/proc_terminate or /bin/sh unavailable']);
    exit(40);
}
$spec = [0 => ['pipe','r'], 1 => ['pipe','w'], 2 => ['pipe','w']];
// A trailing shell builtin prevents common sh implementations from replacing
// their own process with 'sleep', so process monitors can see the real shell.
$process = @proc_open(['/bin/sh', '-c', 'sleep ' . $seconds . '; : # php2shell-canary-' . $marker], $spec, $pipes);
if (!is_resource($process)) {
    result(['outcome' => 'NOT_STARTED', 'reason' => 'proc_open failed']);
    exit(41);
}
foreach ($pipes as $pipe) { fclose($pipe); }
$start = microtime(true);
$status = proc_get_status($process);
$pid = (int)$status['pid'];
$cleanup = false;
$deadline = $start + $seconds + 1.5;
while ($status['running'] && microtime(true) < $deadline) {
    usleep(100000);
    $status = proc_get_status($process);
}
if ($status['running']) {
    $cleanup = true;
    @proc_terminate($process);
    usleep(200000);
    $status = proc_get_status($process);
    if ($status['running']) { @proc_terminate($process, 9); }
}
$elapsed = round(microtime(true) - $start, 3);
$early = !$cleanup && $elapsed < $seconds - 0.65;
$outcome = $cleanup ? 'WATCHDOG_CLEANUP' : ($early ? 'EARLY_EXIT_UNATTRIBUTED' : 'COMPLETED_FULL_WINDOW');
result([
    'outcome' => $outcome,
    'marker' => $marker,
    'php_version' => PHP_VERSION,
    'sapi' => PHP_SAPI,
    'pid' => $pid,
    'seconds_requested' => $seconds,
    'elapsed_seconds' => $elapsed,
    'exit_code' => ($status['exitcode'] >= 0 ? (int)$status['exitcode'] : null),
    'cleanup_attempted' => $cleanup,
    'terminated_early' => $early,
    'interpretation' => 'Process lifetime only; correlate detector telemetry to attribute an early exit.'
]);
@proc_close($process);
'''


def parse_target(target: str) -> str:
    if not TARGET_PATTERN.fullmatch(target) or '..' in target or target.endswith('.'):
        raise ValueError('SSH target must be a single user@hostname without shell metacharacters')
    return target


def build_php_code(duration: int, marker: str) -> str:
    if not 2 <= duration <= 20:
        raise ValueError('Duration must be between 2 and 20 seconds')
    if not re.fullmatch(r'[a-f0-9]{16}', marker):
        raise ValueError('Marker must be 16 lowercase hexadecimal characters')
    return PHP_CANARY.replace('__DURATION__', str(duration)).replace('__MARKER__', marker)


def build_command(mode: str, ssh_target: str | None, port: int, code: str) -> list[str]:
    if mode == 'local':
        return ['php', '-r', code]
    if not ssh_target:
        raise ValueError('SSH target required')
    target = parse_target(ssh_target)
    if not 1 <= port <= 65535:
        raise ValueError('SSH port out of range')
    # SSH runs a fixed command through the existing authenticated session.
    # Never accept an arbitrary remote command or user-controlled PHP source.
    return ['ssh', '-T', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes',
            '-o', 'ConnectTimeout=7', '-o', 'NumberOfPasswordPrompts=0',
            '-p', str(port), '--', target, 'php -r ' + shlex.quote(code)]


def parse_result(stdout: str) -> dict | None:
    for line in stdout.splitlines():
        if line.startswith(RESULT_PREFIX):
            try:
                result = json.loads(line[len(RESULT_PREFIX):])
            except ValueError:
                return None
            return result if isinstance(result, dict) else None
    return None


def run_canary(*, local: bool, ssh_target: str | None, port: int, duration: int,
               acknowledged: bool, output: str | None) -> tuple[dict, int]:
    if local == bool(ssh_target):
        raise ValueError('Choose exactly one of --local or --ssh')
    if ssh_target and not acknowledged:
        raise ValueError('Remote execution requires --i-own-this-server and existing SSH authorization')
    marker = secrets.token_hex(8)
    code = build_php_code(duration, marker)
    command = build_command('local' if local else 'ssh', ssh_target, port, code)
    started = datetime.now(timezone.utc).isoformat()
    report = {
        'mode': 'authorized-php-shell-canary',
        'transport': 'local' if local else 'ssh',
        'server': 'localhost' if local else ssh_target,
        'created_utc': started,
        'marker': marker,
        'requested_seconds': duration,
        'rce_exploit': False,
        'reverse_shell': False,
        'web_php_fpm_context': False,
        'process_start_verified': False,
        'detector_attribution': 'NOT_VERIFIED',
        'result': None,
        'transport_error': None,
    }
    try:
        completed = subprocess.run(command, capture_output=True, text=True,
                                   timeout=duration + 9, check=False)
        parsed = parse_result(completed.stdout[:MAX_REPORT_BYTES])
        if parsed and parsed.get('marker') == marker and parsed.get('outcome') in {
            'COMPLETED_FULL_WINDOW', 'EARLY_EXIT_UNATTRIBUTED', 'WATCHDOG_CLEANUP'
        }:
            report['process_start_verified'] = True
        report['result'] = parsed
        if completed.returncode != 0 and not parsed:
            report['transport_error'] = f'PHP/SSH returned {completed.returncode}: {completed.stderr[:300]}'
        status = 0 if report['process_start_verified'] and parsed.get('outcome') == 'COMPLETED_FULL_WINDOW' else 2
    except (FileNotFoundError, OSError, subprocess.TimeoutExpired) as exc:
        report['transport_error'] = f'{type(exc).__name__}: {str(exc)[:250]}'
        status = 2
    if output:
        path = Path(output)
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(json.dumps(report, indent=2, sort_keys=True) + '\n', encoding='utf-8')
    return report, status


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description='Authorized bounded shell-process canary (NOT a PHP CVE exploit)')
    modes = parser.add_mutually_exclusive_group(required=True)
    modes.add_argument('--local', action='store_true', help='Use PHP CLI on this machine')
    modes.add_argument('--ssh', metavar='USER@HOST', help='Use existing key-authenticated SSH access')
    parser.add_argument('--port', type=int, default=22)
    parser.add_argument('--duration', type=int, default=8, help='Lifetime in seconds (2-20)')
    parser.add_argument('--i-own-this-server', action='store_true', help='Required acknowledgment for SSH execution')
    parser.add_argument('--output', default='evidence/shell-canary.json')
    args = parser.parse_args(argv)
    try:
        report, status = run_canary(local=args.local, ssh_target=args.ssh, port=args.port,
                                    duration=args.duration, acknowledged=args.i_own_this_server,
                                    output=args.output)
    except (ValueError, OSError) as exc:
        print(f'Error: {exc}', file=sys.stderr)
        return 3
    print(json.dumps(report, indent=2, sort_keys=True))
    return status


if __name__ == '__main__':
    raise SystemExit(main())