\nRequire all denied\n\n\nOrder allow,deny\nDeny from all\n\n"); if (!is_file($d . '/index.html')) @file_put_contents($d . '/index.html', ''); return is_writable($d) ? $d : null; } function afwg_http_get(string $url, int $timeout): ?string { if (function_exists('curl_init')) { $ch = curl_init($url); curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 2, CURLOPT_CONNECTTIMEOUT => $timeout, CURLOPT_TIMEOUT => $timeout + 2, CURLOPT_USERAGENT => 'afw-gate/' . AFWG_VERSION . ' (+https://agentfirewall.ru/model/)']); $b = curl_exec($ch); $code = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); return ($b !== false && $code === 200) ? (string)$b : null; } $ctx = stream_context_create(['http' => ['timeout' => $timeout, 'user_agent' => 'afw-gate/' . AFWG_VERSION]]); $b = @file_get_contents($url, false, $ctx); return $b === false ? null : $b; } /** Правила: кэш в afw-data/verify.json, обновление раз в сутки, не чаще раза в час при сбоях. */ function afwg_rules(): ?array { $dir = afwg_data_dir(); if ($dir === null) return null; $f = $dir . '/verify.json'; $retry = $dir . '/verify.retry'; $age = is_file($f) ? time() - (int)filemtime($f) : PHP_INT_MAX; $canTry = !is_file($retry) || time() - (int)filemtime($retry) > 3600; if ($age > 86400 && $canTry) { $lock = @fopen($dir . '/verify.lock', 'c'); if ($lock && flock($lock, LOCK_EX | LOCK_NB)) { $body = is_file(AFWG_RULES_URL) ? (string)@file_get_contents(AFWG_RULES_URL) : afwg_http_get(AFWG_RULES_URL, 4); // путь к файлу — на самом agentfirewall.ru $j = $body !== null ? json_decode($body, true) : null; if (is_array($j) && ($j['format'] ?? 0) === 1 && is_array($j['operators'] ?? null)) { $tmp = $f . '.tmp'; if (@file_put_contents($tmp, $body, LOCK_EX)) @rename($tmp, $f); @unlink($retry); } else { @touch($retry); } flock($lock, LOCK_UN); } if ($lock) fclose($lock); } $j = is_file($f) ? json_decode((string)@file_get_contents($f), true) : null; if (!is_array($j) || ($j['format'] ?? 0) !== 1) return null; $gen = strtotime((string)($j['generated_at'] ?? '')) ?: 0; $j['_stale'] = (time() - (int)filemtime($f) > AFWG_STALE) || ($gen && time() - $gen > AFWG_STALE); return $j; } /* ---------- адрес клиента ---------- */ function afwg_public_ip(string $ip): bool { return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false; } /** Адрес клиента. За прокси (nginx перед Apache) REMOTE_ADDR бывает внутренним — тогда берётся адрес, выставленный прокси. */ function afwg_client_ip(): string { $ip = (string)($_SERVER['REMOTE_ADDR'] ?? ''); if ($ip !== '' && afwg_public_ip($ip)) return $ip; foreach (['HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR'] as $h) { if (empty($_SERVER[$h])) continue; $parts = array_map('trim', explode(',', (string)$_SERVER[$h])); $cand = (string)end($parts); // самый правый адрес дописан нашим прокси if (afwg_public_ip($cand)) return $cand; } return $ip; } function afwg_in_cidr(string $ip, string $cidr): bool { $p = strpos($cidr, '/'); if ($p === false) return false; $a = @inet_pton($ip); $b = @inet_pton(substr($cidr, 0, $p)); if ($a === false || $b === false || strlen($a) !== strlen($b)) return false; $len = (int)substr($cidr, $p + 1); $bytes = intdiv($len, 8); $bits = $len % 8; if ($bytes && substr($a, 0, $bytes) !== substr($b, 0, $bytes)) return false; if ($bits) { $m = (0xff << (8 - $bits)) & 0xff; if ((ord($a[$bytes]) & $m) !== (ord($b[$bytes]) & $m)) return false; } return true; } /* ---------- обратный DNS с прямым подтверждением ---------- */ function afwg_dns_ptr(string $ip): ?string { if (defined('AFWG_TEST_DNS')) return AFWG_TEST_DNS['ptr'][$ip] ?? null; $h = @gethostbyaddr($ip); return ($h && $h !== $ip) ? strtolower(rtrim($h, '.')) : null; } function afwg_dns_forward(string $host): array { if (defined('AFWG_TEST_DNS')) return AFWG_TEST_DNS['fwd'][$host] ?? []; $out = []; foreach ((array)@gethostbynamel($host) as $a) if ($a) $out[] = $a; foreach ((array)@dns_get_record($host, DNS_AAAA) as $r) if (!empty($r['ipv6'])) $out[] = $r['ipv6']; return $out; } function afwg_rdns_ok(string $ip, array $domains): bool { $host = afwg_dns_ptr($ip); if ($host === null) return false; $match = false; foreach ($domains as $d) { $d = strtolower($d); if ($host === $d || str_ends_with($host, '.' . $d)) { $match = true; break; } } if (!$match) return false; $want = @inet_pton($ip); foreach (afwg_dns_forward($host) as $a) if (@inet_pton($a) === $want) return true; return false; } /* ---------- решение ---------- */ /** * null — запрос не называет себя известным ботом (не наше дело). * Иначе ['op','ip','result','action']: result ∈ pass-ip | pass-rdns | fail | unverifiable | stale | no-rules | no-ip, * action ∈ allow | deny | observe (в режиме наблюдения подделка пропускается, но отмечается). */ function afwg_decide(): ?array { $ua = (string)($_SERVER['HTTP_USER_AGENT'] ?? ''); if ($ua === '') return null; $rules = afwg_rules(); if ($rules === null) { // правил нет совсем: узнать оператора не можем — проверяем только самые частые имена, чтобы было видно в журнале return preg_match('~GPTBot|ClaudeBot|Googlebot|bingbot|PerplexityBot|compatible; Yandex~i', $ua) ? ['op' => '?', 'ip' => afwg_client_ip(), 'result' => 'no-rules', 'action' => 'allow'] : null; } $claim = null; foreach ($rules['operators'] as $op) { if (@preg_match('~(?:' . $op['ua'] . ')~i', $ua)) { $claim = $op; break; } } if ($claim === null) return null; $ip = afwg_client_ip(); $d = ['op' => (string)$claim['id'], 'ip' => $ip]; if (!afwg_public_ip($ip)) return $d + ['result' => 'no-ip', 'action' => 'allow']; // настоящий адрес не виден (прокси не передаёт) — не судить if (!empty($rules['_stale'])) return $d + ['result' => 'stale', 'action' => 'allow']; $hasIp = !empty($claim['prefixes']); $hasDns = !empty($claim['rdns']); if (!$hasIp && !$hasDns) return $d + ['result' => 'unverifiable', 'action' => 'allow']; // кэш решений по адресу: подтверждённые — сутки, отказы — 6 часов $dir = afwg_data_dir(); $ck = null; if ($dir !== null) { @is_dir($dir . '/cache') || @mkdir($dir . '/cache', 0755); $ck = $dir . '/cache/' . sha1($claim['id'] . '|' . $ip) . '.txt'; if (is_file($ck)) { $c = (string)@file_get_contents($ck); $age = time() - (int)filemtime($ck); if (($c === 'pass-ip' || $c === 'pass-rdns') && $age < 86400) return $d + ['result' => $c, 'action' => 'allow']; if ($c === 'fail' && $age < 21600) return $d + ['result' => 'fail', 'action' => AFWG_MODE === 'enforce' ? 'deny' : 'observe']; } } $res = 'fail'; if ($hasIp) foreach ($claim['prefixes'] as $c) if (afwg_in_cidr($ip, (string)$c)) { $res = 'pass-ip'; break; } if ($res === 'fail' && $hasDns && afwg_rdns_ok($ip, $claim['rdns'])) $res = 'pass-rdns'; if ($ck !== null) @file_put_contents($ck, $res, LOCK_EX); return $d + ['result' => $res, 'action' => $res === 'fail' ? (AFWG_MODE === 'enforce' ? 'deny' : 'observe') : 'allow']; } function afwg_log(array $d): void { $dir = afwg_data_dir(); if ($dir === null) return; $f = $dir . '/log-' . date('Y-m') . '.csv'; if (is_file($f) && filesize($f) > 5 * 1024 * 1024) return; // не больше 5 МБ в месяц $ua = substr(str_replace(["\r", "\n", '"'], ' ', (string)($_SERVER['HTTP_USER_AGENT'] ?? '')), 0, 160); $uri = substr(str_replace(["\r", "\n", '"'], ' ', (string)($_SERVER['REQUEST_URI'] ?? '')), 0, 160); $new = !is_file($f); $line = ($new ? "time,ip,operator,result,action,uri,user_agent\n" : '') . date('c') . ',' . $d['ip'] . ',' . $d['op'] . ',' . $d['result'] . ',' . $d['action'] . ',"' . $uri . '","' . $ua . "\"\n"; @file_put_contents($f, $line, FILE_APPEND | LOCK_EX); if ($new) foreach (glob($dir . '/log-*.csv') ?: [] as $old) if (basename($old) < 'log-' . date('Y-m', strtotime('-3 months')) . '.csv') @unlink($old); } function afwg_deny(): void { http_response_code(403); header('Content-Type: text/plain; charset=utf-8'); header('X-AFW-Gate: denied'); header('Cache-Control: no-store'); echo "403: the user-agent claims a known bot, but the request did not come from that operator's published addresses.\n" . "Запрос назвался известным ботом, но пришёл не с адресов оператора.\n"; exit; } /* ---------- диагностика ---------- */ function afwg_key(): string { if (AFWG_KEY !== '') return AFWG_KEY; $cfg = __DIR__ . '/_app/config.php'; // сайты группы: ключ в config.php if (is_file($cfg)) { $c = @include $cfg; if (is_array($c) && !empty($c['gate_key'])) return (string)$c['gate_key']; } return ''; } function afwg_status(): void { $k = afwg_key(); if ($k === '' || !hash_equals($k, (string)($_GET['key'] ?? ''))) { http_response_code(404); exit; } $rules = afwg_rules(); $dir = afwg_data_dir(); $stat = []; $recent = []; if ($dir !== null) { $since = date('c', strtotime('-7 days')); foreach ([date('Y-m', strtotime('-1 month')), date('Y-m')] as $m) { $f = $dir . '/log-' . $m . '.csv'; if (!is_file($f)) continue; foreach (file($f, FILE_IGNORE_NEW_LINES) ?: [] as $i => $l) { if ($i === 0 || $l === '' || strncmp($l, 'time,', 5) === 0) continue; $c = str_getcsv($l); if (($c[0] ?? '') < $since) continue; $key = ($c[2] ?? '?') . ' ' . ($c[3] ?? '?'); $stat[$key] = ($stat[$key] ?? 0) + 1; if (in_array($c[3] ?? '', ['fail', 'no-rules', 'stale', 'no-ip'], true)) $recent[] = ['time' => $c[0], 'ip' => $c[1], 'operator' => $c[2], 'result' => $c[3], 'action' => $c[4], 'uri' => $c[5] ?? '', 'ua' => $c[6] ?? '']; } } } ksort($stat); header('Content-Type: application/json; charset=utf-8'); header('Cache-Control: no-store'); echo json_encode([ 'gate' => AFWG_VERSION, 'mode' => AFWG_MODE, 'your_ip' => afwg_client_ip(), 'remote_addr' => $_SERVER['REMOTE_ADDR'] ?? '', 'x_real_ip' => $_SERVER['HTTP_X_REAL_IP'] ?? '', 'x_forwarded_for' => $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '', 'data_dir_writable' => $dir !== null, 'rules' => $rules ? ['generated_at' => $rules['generated_at'] ?? null, 'stale' => $rules['_stale'], 'operators' => array_map(fn($o) => $o['name'] . ': ' . count($o['prefixes']) . ' диапазонов' . ($o['rdns'] ? ', DNS ' . implode('/', $o['rdns']) : ''), $rules['operators'])] : null, 'last_7_days' => $stat, 'recent_failures' => array_slice(array_reverse($recent), 0, 30), ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); exit; } /* ---------- отдача статических файлов (сайт без PHP: .htaccess направляет сюда только запросы ботов) ---------- */ const AFWG_MIME = ['html' => 'text/html; charset=utf-8', 'htm' => 'text/html; charset=utf-8', 'md' => 'text/markdown; charset=utf-8', 'txt' => 'text/plain; charset=utf-8', 'xml' => 'application/xml; charset=utf-8', 'json' => 'application/json; charset=utf-8', 'css' => 'text/css; charset=utf-8', 'js' => 'application/javascript; charset=utf-8', 'svg' => 'image/svg+xml', 'png' => 'image/png', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'webp' => 'image/webp', 'gif' => 'image/gif', 'ico' => 'image/x-icon', 'woff2' => 'font/woff2', 'pdf' => 'application/pdf']; function afwg_not_found(): void { http_response_code(404); if (is_file(__DIR__ . '/404.html')) { header('Content-Type: text/html; charset=utf-8'); readfile(__DIR__ . '/404.html'); } elseif (is_file(__DIR__ . '/404.php')) { require __DIR__ . '/404.php'; } else { header('Content-Type: text/plain; charset=utf-8'); echo "404\n"; } exit; } function afwg_serve(): void { $path = rawurldecode((string)(parse_url((string)($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH) ?: '/')); if (str_contains($path, "\0") || str_contains($path, '..') || preg_match('~/\.(?!well-known/)~', $path) || preg_match('~^/(afw-data|_app)(/|$)~', $path)) afwg_not_found(); $f = __DIR__ . $path; if (is_dir($f)) { if (!str_ends_with($path, '/')) { header('Location: ' . $path . '/', true, 301); exit; } $md = stripos((string)($_SERVER['HTTP_ACCEPT'] ?? ''), 'text/markdown') !== false; if ($md && is_file($f . 'index.md')) $f .= 'index.md'; elseif (is_file($f . 'index.html')) $f .= 'index.html'; elseif (is_file($f . 'index.php')) $f .= 'index.php'; else afwg_not_found(); } $real = realpath($f); if ($real === false || !is_file($real) || !str_starts_with($real, __DIR__ . DIRECTORY_SEPARATOR)) afwg_not_found(); $ext = strtolower(pathinfo($real, PATHINFO_EXTENSION)); if ($ext === 'php') { if ($real === __FILE__) afwg_not_found(); chdir(dirname($real)); $_SERVER['SCRIPT_FILENAME'] = $real; $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'] = substr($real, strlen(__DIR__)); require $real; exit; } if (!isset(AFWG_MIME[$ext])) afwg_not_found(); $mt = (int)filemtime($real); header('Content-Type: ' . AFWG_MIME[$ext]); header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $mt) . ' GMT'); if (in_array($ext, ['html', 'md'], true)) header('Vary: Accept', false); if (in_array($ext, ['json', 'md', 'txt', 'xml'], true)) header('Access-Control-Allow-Origin: *'); if ($ext === 'md' && AFWG_MD_NOINDEX) header('X-Robots-Tag: noindex'); $ims = strtotime((string)($_SERVER['HTTP_IF_MODIFIED_SINCE'] ?? '')); if ($ims && $ims >= $mt) { http_response_code(304); exit; } header('Content-Length: ' . filesize($real)); if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'HEAD') readfile($real); exit; } /* ---------- запуск ---------- */ (function (): void { $direct = isset($_SERVER['SCRIPT_FILENAME']) && @realpath((string)$_SERVER['SCRIPT_FILENAME']) === __FILE__ && basename((string)parse_url((string)($_SERVER['REQUEST_URI'] ?? ''), PHP_URL_PATH)) === basename(__FILE__) ? 'self' : (isset($_SERVER['SCRIPT_FILENAME']) && @realpath((string)$_SERVER['SCRIPT_FILENAME']) === __FILE__ ? 'rewrite' : 'include'); if ($direct === 'self') { // прямой вызов /afw-gate.php — только диагностика if (($_GET['afw'] ?? '') === 'status') afwg_status(); http_response_code(404); exit; } try { $d = afwg_decide(); } catch (\Throwable $e) { $d = null; } // любая ошибка — пропустить if ($d !== null) { afwg_log($d); if ($d['action'] === 'deny') afwg_deny(); } if ($direct === 'rewrite') afwg_serve(); // статический сайт: отдать запрошенный файл })();