改进SYN Flood检测

This commit is contained in:
刘祥超
2022-01-13 11:36:05 +08:00
parent 63992bb2a0
commit 14d156d42d
2 changed files with 30 additions and 7 deletions

View File

@@ -27,6 +27,7 @@ type ClientConn struct {
isTLS bool isTLS bool
hasDeadline bool hasDeadline bool
hasRead bool hasRead bool
hasResetSYNFlood bool
BaseClientConn BaseClientConn
} }
@@ -65,10 +66,13 @@ func (this *ClientConn) Read(b []byte) (n int, err error) {
var synFloodConfig = sharedNodeConfig.SYNFloodConfig() var synFloodConfig = sharedNodeConfig.SYNFloodConfig()
if synFloodConfig != nil && synFloodConfig.IsOn { if synFloodConfig != nil && synFloodConfig.IsOn {
if err != nil && os.IsTimeout(err) { if err != nil && os.IsTimeout(err) {
_ = this.SetLinger(0)
if !this.hasRead { if !this.hasRead {
this.checkSYNFlood(synFloodConfig) this.increaseSYNFlood(synFloodConfig)
} }
} else if err == nil { } else if err == nil && !this.hasResetSYNFlood {
this.hasResetSYNFlood = true
this.resetSYNFlood() this.resetSYNFlood()
} }
} }
@@ -123,10 +127,10 @@ func (this *ClientConn) SetWriteDeadline(t time.Time) error {
} }
func (this *ClientConn) resetSYNFlood() { func (this *ClientConn) resetSYNFlood() {
//ttlcache.SharedCache.Delete("SYN_FLOOD:" + this.RawIP()) ttlcache.SharedCache.Delete("SYN_FLOOD:" + this.RawIP())
} }
func (this *ClientConn) checkSYNFlood(synFloodConfig *firewallconfigs.SYNFloodConfig) { func (this *ClientConn) increaseSYNFlood(synFloodConfig *firewallconfigs.SYNFloodConfig) {
var ip = this.RawIP() var ip = this.RawIP()
if len(ip) > 0 && !iplibrary.IsInWhiteList(ip) && (!synFloodConfig.IgnoreLocal || !utils.IsLocalIP(ip)) { if len(ip) > 0 && !iplibrary.IsInWhiteList(ip) && (!synFloodConfig.IgnoreLocal || !utils.IsLocalIP(ip)) {
var timestamp = utils.NextMinuteUnixTime() var timestamp = utils.NextMinuteUnixTime()
@@ -135,6 +139,10 @@ func (this *ClientConn) checkSYNFlood(synFloodConfig *firewallconfigs.SYNFloodCo
if minAttempts < 5 { if minAttempts < 5 {
minAttempts = 5 minAttempts = 5
} }
if !this.isTLS {
// 非TLS设置为两倍防止误封
minAttempts = 2 * minAttempts
}
if result >= int64(minAttempts) { if result >= int64(minAttempts) {
var timeout = synFloodConfig.TimeoutSeconds var timeout = synFloodConfig.TimeoutSeconds
if timeout <= 0 { if timeout <= 0 {

View File

@@ -41,3 +41,18 @@ func (this *BaseClientConn) RawIP() string {
ip, _, _ := net.SplitHostPort(this.rawConn.RemoteAddr().String()) ip, _, _ := net.SplitHostPort(this.rawConn.RemoteAddr().String())
return ip return ip
} }
// TCPConn 转换为TCPConn
func (this *BaseClientConn) TCPConn() (*net.TCPConn, bool) {
conn, ok := this.rawConn.(*net.TCPConn)
return conn, ok
}
// SetLinger 设置Linger
func (this *BaseClientConn) SetLinger(seconds int) error {
tcpConn, ok := this.TCPConn()
if ok {
return tcpConn.SetLinger(seconds)
}
return nil
}