From 927199b171ef4dee6d252e843b66d0565bbf8034 Mon Sep 17 00:00:00 2001 From: samwaf Date: Tue, 2 Dec 2025 14:11:56 +0800 Subject: [PATCH] fix:linux firewall unaffected #573 --- build_docker_release_linux.bat | 2 +- firewall/firewall.go | 12 +++++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/build_docker_release_linux.bat b/build_docker_release_linux.bat index 1cca160..55e9200 100644 --- a/build_docker_release_linux.bat +++ b/build_docker_release_linux.bat @@ -1 +1 @@ -docker run --rm -v "$PWD":/media/sf_SamWaf -w /media/sf_SamWaf -e CGO_ENABLED=1 -e GOPROXY=https://goproxy.cn,direct golang:1.22.9 go build -v -ldflags="-X SamWaf/global.GWAF_RELEASE=true -X SamWaf/global.GWAF_RELEASE_VERSION_NAME=20251103 -X SamWaf/global.GWAF_RELEASE_VERSION=v1.3.17 -s -w -extldflags "-static"" -o /media/sf_SamWaf/release/SamWafLinux64 main.go && upx -9 /media/sf_SamWaf/release/SamWafLinux64 \ No newline at end of file +docker run --rm -v C:/huawei/goproject/SamWaf:/src -w /src -e CGO_ENABLED=1 -e GOOS=linux -e GOARCH=amd64 -e GOPROXY=https://goproxy.cn,direct golang:1.24.7 sh -c "go build -v -ldflags='-X SamWaf/global.GWAF_RELEASE=true -X SamWaf/global.GWAF_RELEASE_VERSION_NAME=20251103 -X SamWaf/global.GWAF_RELEASE_VERSION=v1.3.17 -s -w -extldflags \"-static\"' -o /src/release/SamWafLinux64 main.go" \ No newline at end of file diff --git a/firewall/firewall.go b/firewall/firewall.go index bcc1424..8b8b0ba 100644 --- a/firewall/firewall.go +++ b/firewall/firewall.go @@ -77,11 +77,12 @@ func (fw *FireWallEngine) executeCommand(cmd *exec.Cmd) (error error, printstr s } func (fw *FireWallEngine) AddRule(ruleName, ipToAdd, action, proc, localport string) error { - // iptables -A INPUT -s -j DROP + // iptables -I INPUT 1 -s -j DROP + // 使用 -I 插入到链的开头,确保规则优先执行 fmt.Printf("[DEBUG] 添加防火墙规则: ip=%s\n", ipToAdd) - cmd := exec.Command("iptables", "-A", "INPUT", "-s", ipToAdd, "-j", "DROP") - fmt.Printf("[DEBUG] 执行命令: iptables -A INPUT -s %s -j DROP\n", ipToAdd) + cmd := exec.Command("iptables", "-I", "INPUT", "1", "-s", ipToAdd, "-j", "DROP") + fmt.Printf("[DEBUG] 执行命令: iptables -I INPUT 1 -s %s -j DROP\n", ipToAdd) err, output := fw.executeCommand(cmd) if err != nil { @@ -180,8 +181,9 @@ func (fw *FireWallEngine) BlockIP(ip string, reason string) error { return fmt.Errorf("IP %s already blocked", ip) } - // 添加iptables规则: iptables -A INPUT -s -j DROP - cmd := exec.Command("iptables", "-A", "INPUT", "-s", ip, "-j", "DROP") + // 添加iptables规则: iptables -I INPUT 1 -s -j DROP + // 使用 -I 插入到链的开头,确保规则在 ESTABLISHED 连接规则之前执行 + cmd := exec.Command("iptables", "-I", "INPUT", "1", "-s", ip, "-j", "DROP") err, output := fw.executeCommand(cmd) if err != nil { fmt.Printf("[ERROR] 封禁IP失败: %s, error: %v, output: %s\n", ip, err, output)