介紹#
一般我的站點都是採用國內線路 + 境外線路解析,默認線路為國內 CDN,境外則 cname 解析到 cloudflare 線路
CNAME 解析到 cloud flare 上可以參考我的文章 使用 CNAME 接入 CloudFlare
這樣以來可以阻擋很多來自境外的攻擊(前提是沒有暴露源站 IP)不過華歲最近剛了解到可以 “穿盾” 什麼的,貌似是把 CF 盾打穿再攻擊?,實在令人惡心啊
CLoudflare 最有效的 DDoS 防禦模式就是 “Under Attack 模式”,這個就是今天要說的 5 秒盾
開啟之後在訪問網站的時候會先跳轉的 cloudflare 的檢測頁面上,用 5 秒時間來驗證是否真實用戶訪問,可以有效緩解攻擊帶來的壓力
如果一直開啟的話會影響訪問,所以今天就分享自動開關腳本。
開源的 sh 腳本#
開源的 sh 腳本 Cloudflare-Block
可以實現在 Linux 伺服器端根據系統負載情況自動開啟 CloudFlare 的五秒盾進行被攻擊後的防禦。
API 準備#
註冊 / 登錄 cloud flare 查看
API
zoneid 區域 ID
點進接入在 CLOUDFLARE 的域名,在右側下滑即可看到
保存好上面兩個 API,腳本需要用到。
腳本使用#
只需要複製下面的代碼,保存為 Cloudflare.sh 文件再添加到 crontab 裡定時執行腳本即可。(當然也可以使用寶塔定時任務)
#!/bin/bash
# $1 = 1min, $2 = 5min, $3 = 15min,這裡選擇使用哪個負載值為閾值。
loadavg=$(awk '{printf "%f", $1}' < /proc/loadavg)
# Linux 系統負載(load average)達到 10 即開啟五秒盾,您可以根據情況來修改這個數值。
maxload=10
# 配置 Cloudflare 的 API
# 您 CloudFlare 的 Global API Key (https://dash.cloudflare.com/profile)
api_key=
# 您 CloudFlare 賬號郵箱
email=
# 您 CloudFlare 賬號的**區域 ID** (https://dash.cloudflare.com/_zone-id_/domain.com)
zone_id=
# 沒有攻擊時 CloudFlare 的默認安全級別
default_security_level=high
# 是否將調試消息寫入腳本目錄下的 debug.log 文件
debug=0
basedir=$(dirname "$0")
attacked_file=$basedir/attacked
[ "$debug" -eq 1 ] && exec > "${logfile:-$basedir/debug.log}"
# 您可以就地放置上述配置值,也可以將其放置在腳本目錄中名為“config”的文件中。
config_file=$basedir/config
[ -e "$config_file" ] && source "$config_file"
api_set_mode() {
local mode
mode=$1
curl -s -X PATCH "https://api.cloudflare.com/client/v4/zones/$zone_id/settings/security_level" \
-H "X-Auth-Email: $email" \
-H "X-Auth-Key: $api_key" \
-H "Content-Type: application/json" \
--data "{\"value\":\"$mode\"}" \
|| echo "Error: failed to set security level to $mode"
}
# 如果不存在則創建文件“attacked”
if [ ! -e "$attacked_file" ]; then
echo 0 > "$attacked_file"
fi
was_under_attack=$(cat "$attacked_file")
under_attack=$(echo "$loadavg > $maxload" | bc)
if [[ "$1" != [01] ]]; then
echo "Incorrect usage! Please pass either 0 or 1 as an argument"
exit 1
fi
if [ $debug -eq 1 ]; then
echo "Mode: $1; was under attack: $was_under_attack; now under attack: $under_attack"
echo "Load average: $loadavg"
fi
if [ "$1" -eq 0 ] && [ "$was_under_attack" -eq 0 ] && [ "$under_attack" -eq 1 ]; then
# attack just started and we want to enable under-attack mode
# Activate protection
[ "$debug" -eq 1 ] && echo "Activating under-attack mode!"
echo 1 > "$attacked_file"
api_set_mode under_attack
elif [ "$1" -eq 1 ] && [ "$was_under_attack" -eq 1 ] && [ "$under_attack" -eq 0 ]; then
# attack just finished (and up to 20 minutes passed since)
# and we want to disable under-attack mode
# Disable Protection
[ "$debug" -eq 1 ] && echo "Leaving under-attack mode!"
echo 0 > "$attacked_file"
api_set_mode "$default_security_level"
fi
exit 0
添加定時任務#
#添加定時任務
crontab -e
# 如果未啟用五秒盾保護,則每 1 分鐘檢查一次
*/1 * * * * /root/DDoS/Cloudflare.sh 0
# 每 20 分鐘檢查一次五秒盾保護是否已啟用
*/20 * * * * /root/DDoS/Cloudflare.sh 1
#重載 crontab
service crond reload
總結#
開啟自動 5s 盾後,可以在受到攻擊時自動開啟,不用自己去手動開啟,還是很方便的,懶人必備啊!