github.com/TeaOSLab/EdgeNode@v1.3.8/internal/waf/captcha_counter.go (about) 1 // Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn . 2 3 package waf 4 5 import ( 6 "github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs" 7 "github.com/TeaOSLab/EdgeNode/internal/utils/counters" 8 "github.com/TeaOSLab/EdgeNode/internal/waf/requests" 9 "github.com/iwind/TeaGo/types" 10 "time" 11 ) 12 13 type CaptchaPageCode = string 14 15 const ( 16 CaptchaPageCodeInit CaptchaPageCode = "init" 17 CaptchaPageCodeShow CaptchaPageCode = "show" 18 CaptchaPageCodeImage CaptchaPageCode = "image" 19 CaptchaPageCodeSubmit CaptchaPageCode = "submit" 20 ) 21 22 // CaptchaIncreaseFails 增加Captcha失败次数,以便后续操作 23 func CaptchaIncreaseFails(req requests.Request, actionConfig *CaptchaAction, policyId int64, groupId int64, setId int64, pageCode CaptchaPageCode, useLocalFirewall bool) (goNext bool) { 24 var maxFails = actionConfig.MaxFails 25 var failBlockTimeout = actionConfig.FailBlockTimeout 26 if maxFails > 0 && failBlockTimeout > 0 { 27 if maxFails <= 3 { 28 maxFails = 3 // 不能小于3,防止意外刷新出现 29 } 30 var countFails = counters.SharedCounter.IncreaseKey(CaptchaCacheKey(req, pageCode), 300) 31 if int(countFails) >= maxFails { 32 SharedIPBlackList.RecordIP(IPTypeAll, firewallconfigs.FirewallScopeServer, req.WAFServerId(), req.WAFRemoteIP(), time.Now().Unix()+int64(failBlockTimeout), policyId, useLocalFirewall, groupId, setId, "CAPTCHA验证连续失败超过"+types.String(maxFails)+"次") 33 return false 34 } 35 } 36 return true 37 } 38 39 // CaptchaDeleteCacheKey 清除计数 40 func CaptchaDeleteCacheKey(req requests.Request) { 41 counters.SharedCounter.ResetKey(CaptchaCacheKey(req, CaptchaPageCodeInit)) 42 counters.SharedCounter.ResetKey(CaptchaCacheKey(req, CaptchaPageCodeShow)) 43 counters.SharedCounter.ResetKey(CaptchaCacheKey(req, CaptchaPageCodeImage)) 44 counters.SharedCounter.ResetKey(CaptchaCacheKey(req, CaptchaPageCodeSubmit)) 45 } 46 47 // CaptchaCacheKey 获取Captcha缓存Key 48 func CaptchaCacheKey(req requests.Request, pageCode CaptchaPageCode) string { 49 return "WAF:CAPTCHA:FAILS:" + pageCode + ":" + req.WAFRemoteIP() + ":" + types.String(req.WAFServerId()) 50 }