将cloudflare waf日志推送到S3,同步到阿里云SLS,从日志中过滤高风险ip,将访问量大的风险ip开启5秒盾或者JS challenge选项

    1. #!/bin/bash
    2. #sync gt 400 EdgeResponseStatus
    3. log_dir=`date +%Y-%m-%d`
    4. log_time="`date "+%Y-%m-%d %H:%M:%S"`"
    5. lastweek_time="`date -d -2day "+%Y-%m-%d %H:%M:%S"`"
    6. log_status_dir="/data/drop/${log_dir}"
    7. #cf user
    8. CFEMAIL="bob.huo@orderplus.com"
    9. CFAPIKEY="f6f44711479c2***984df57959ed3060a8f3"
    10. ZONESID="4fafc4f93dd3b3***385388072a2708"
    11. #check folder
    12. check_folder(){
    13. [[ ! -e "${log_status_dir}" ]] && mkdir -p $log_status_dir
    14. }
    15. check_folder
    16. #pull log
    17. /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
    18. ere security_check_ip(ClientIP) = 1 group by ClientIP order by PV desc' --from_time="${lastweek_time}+08:00" \
    19. --to_time="${log_time}+08:00" --region-endpoint="cn-hongkong.log.aliyuncs.com" --format-output=no_escape --jmes-filter="join('\n', map(&to_string(@), @))" \
    20. --access-id="LTAI9K***OU04GlM" --access-key="R0p1TZF4oomj0kc***valOvA2Xb" >> ${log_status_dir}/drop.txt
    21. #也可以将过滤出来的结果转成csv格式,下到本地分析
    22. Json2csv(){
    23. /usr/bin/json2csv -i ${log_status_dir}/drop.txt -f EdgeResponseStatus,ClientRequestMethod,ClientRequestHost,ClientIP,ClientRequestUserAgent,ClientRequestReferer,ClientRequestURI,WAFAction,\
    24. WAFRuleMessage
    25. -o ${log_status_dir}/drop.csv
    26. }
    27. #Json2csv
    28. #jq解析json日志,获取攻击IP超过20次的
    29. #/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
    30. #use cf api block attack_ip
    31. cf_block(){
    32. IPADDR=$(<${log_status_dir}/block.txt)
    33. for IPADDR in ${IPADDR[@]};do
    34. echo $IPADDR
    35. curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONESID/firewall/access_rules/rules" \
    36. -H "X-Auth-Email: $CFEMAIL" \
    37. -H "X-Auth-Key: $CFAPIKEY" \
    38. -H "Content-Type: application/json" \
    39. --data '{"mode":"block","configuration":{"target":"ip","value":"'$IPADDR'"},"notes":"CC Attatch"}'
    40. done
    41. }
    42. #cf_block
    43. ~