며칠 전, 이 작은 블로그가 계속 그룹 내 어떤 고수의 공격을 받았습니다. CDN을 활성화해 두었기 때문에 상대방은 제 원본 IP를 알아낼 수 없었고, 대신 제 웹사이트에 대규모 CC 공격을 시작했습니다. 정말 갑작스러운 일이었습니다.
공격 출처의 IP가 너무 많아 수동으로 차단하는 것은 거의 불가능했습니다. 마침 바이두 클라우드 가속의 지능형 CC 방어 기능이 떠올랐는데, 이는 5초 방패의 원리를 기반으로 합니다. 저는 PHP로 바이두 클라우드 가속의 CC 방어 메커니즘을 모방해 간단한 방어 스크립트를 작성했고, 오늘 여러분과 공유합니다.
PHP CC 방어 코드
<?php
define('SYSTEM_ROOT', dirname(preg_replace('@\\(.*\\(.*$@', '', preg_replace('@\\(.*\\(.*$@', '', __FILE__))) . '/');
session_start();
date_default_timezone_set('Asia/Shanghai');
header('Content-Type: text/html; charset=UTF-8');
function getspider($useragent = '') {
if (defined('CC_Defender') && CC_Defender == 2) return false;
if (!$useragent) {
$useragent = $_SERVER['HTTP_USER_AGENT'];
}
$useragent = strtolower($useragent);
$spiders = [
'baiduspider', 'googlebot', 'soso', 'bing', 'yahoo', 'sohu-search',
'sogou', 'youdaobot', 'yodaobot', 'robozilla', 'msnbot', 'lycos',
'ia_archiver', 'archive.org_bot', 'sitebot', 'mj12bot', 'gosospider',
'gigabot', 'yrspider', 'jikespider', 'addsugarspiderbot', 'testspider',
'etaospider', 'wangidspider', 'foxspider', 'docomo', 'yandexbot',
'ezooms', 'sinaweibobot', 'catchbot', 'surveybot', 'dotbot', 'purebot',
'ccbot', 'mlbot', 'adsbot-google', 'ahrefsbot', 'spbot', 'augustbot'
];
foreach ($spiders as $spider) {
if (strpos($useragent, $spider) !== false) return $spider;
}
return false;
}
if ($_GET['rand'] && $_SESSION['rand_session'] != $_GET['rand']) {
header('Content-Type: text/html; charset=UTF-8');
exit('<b>浏览器不支持 COOKIE 或访问异常!</b>');
}
if (!$_SESSION['rand_session']) {
if (!getspider()) {
$rand_session = md5(uniqid() . rand(1, 1000));
$_SESSION['rand_session'] = $rand_session;
exit("<!DOCTYPE HTML>
<html>
<head>
<meta charset=\"UTF-8\"/>
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\" />
<title>安全检查中...</title>
<script>
var i = 5;
var intervalid;
intervalid = setInterval(\"fun()\", 1000);
function fun() {
if (i == 0) {
window.location.href = \"?{$_SERVER['QUERY_STRING']}&rand={$rand_session}\";
clearInterval(intervalid);
}
document.getElementById(\"mes\").innerHTML = i;
i--;
}
</script>
<style>
html, body {width: 100%; height: 100%; margin: 0; padding: 0;}
body {background-color: #ffffff; font-family: Helvetica, Arial, sans-serif; font-size: 100%;}
h1 {font-size: 1.5em; color: #404040; text-align: center;}
p {font-size: 1em; color: #404040; text-align: center; margin: 10px 0 0 0;}
#spinner {margin: 0 auto 30px auto; display: block;}
.attribution {margin-top: 20px;}
</style>
</head>
<body>
<table width=\"100%\" height=\"100%\" cellpadding=\"20\">
<tr>
<td align=\"center\" valign=\"middle\">
<noscript><h2>请开启浏览器的 JavaScript 功能并刷新页面</h2></noscript>
<h1><span>浏览器安全检查中...</span></h1>
<p>该过程自动完成</p>
<p>请稍候,还剩 <span id=\"mes\">5</span> 秒</p>
</td></tr></table>
</body></html>");
}
}
?>
위 PHP 코드를 웹사이트 상단의 PHP 파일(예: index.php 또는 기타 메인 진입 파일)에 추가하면 방어 기능을 활성화할 수 있습니다. 이렇게 하면 보안 검사를 통과하고 COOKIE를 획득한 브라우저만 웹사이트에 정상적으로 접속할 수 있습니다.
주의 사항
- 이 방법은 비교적 소규모 공격(예: 일반적인 CC 공격)에만 적합합니다.
- 대규모 분산 좀비 PC 공격(예: DDoS)을 받는 경우 이 코드로는 대응하지 못할 수 있으므로, 전문적인 DDoS 방어 서비스를 사용하는 것이 좋습니다.
- 공격을 받을 때는 신중하고 침착하게 대처하며, 도발을 피해야 합니다.