将cloudflare waf日志推送到S3,同步到阿里云SLS,从日志中过滤高风险ip,将访问量大的风险ip开启5秒盾或者JS challenge选项
#!/bin/bash
#sync gt 400 EdgeResponseStatus
log_dir=`date +%Y-%m-%d`
log_time="`date "+%Y-%m-%d %H:%M:%S"`"
lastweek_time="`date -d -2day "+%Y-%m-%d %H:%M:%S"`"
log_status_dir="/data/drop/${log_dir}"
#cf user
CFEMAIL="bob.huo@orderplus.com"
CFAPIKEY="f6f44711479c2***984df57959ed3060a8f3"
ZONESID="4fafc4f93dd3b3***385388072a2708"
#check folder
check_folder(){
[[ ! -e "${log_status_dir}" ]] && mkdir -p $log_status_dir
}
check_folder
#pull log
/usr/local/bin/aliyunlog log get_log_all --project="cloudflare-logs" --logstore="log-cf" --query='*|select ClientIP,ip_to_country(ClientIP) as country, ip_to_provider(ClientIP) as provider, count(1) as PV wh
ere security_check_ip(ClientIP) = 1 group by ClientIP order by PV desc' --from_time="${lastweek_time}+08:00" \
--to_time="${log_time}+08:00" --region-endpoint="cn-hongkong.log.aliyuncs.com" --format-output=no_escape --jmes-filter="join('\n', map(&to_string(@), @))" \
--access-id="LTAI9K***OU04GlM" --access-key="R0p1TZF4oomj0kc***valOvA2Xb" >> ${log_status_dir}/drop.txt
#也可以将过滤出来的结果转成csv格式,下到本地分析
Json2csv(){
/usr/bin/json2csv -i ${log_status_dir}/drop.txt -f EdgeResponseStatus,ClientRequestMethod,ClientRequestHost,ClientIP,ClientRequestUserAgent,ClientRequestReferer,ClientRequestURI,WAFAction,\
WAFRuleMessage
-o ${log_status_dir}/drop.csv
}
#Json2csv
#jq解析json日志,获取攻击IP超过20次的
#/usr/bin/jq -r .ClientIP ${log_status_dir}/drop.txt | sort -n | uniq -c | sort -n|tail -500|awk '{if($1>10) print $2}' >> ${log_status_dir}/block.txt
#use cf api block attack_ip
cf_block(){
IPADDR=$(<${log_status_dir}/block.txt)
for IPADDR in ${IPADDR[@]};do
echo $IPADDR
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONESID/firewall/access_rules/rules" \
-H "X-Auth-Email: $CFEMAIL" \
-H "X-Auth-Key: $CFAPIKEY" \
-H "Content-Type: application/json" \
--data '{"mode":"block","configuration":{"target":"ip","value":"'$IPADDR'"},"notes":"CC Attatch"}'
done
}
#cf_block
~