From b449cbd93b98fbf29f128f3945351ff21abde118 Mon Sep 17 00:00:00 2001 From: ssongliu Date: Thu, 4 Dec 2025 16:34:31 +0800 Subject: [PATCH] fix: optimize IP whitelist validation logic --- backend/init/router/router.go | 9 +++++---- backend/middleware/ip_limit.go | 7 ++++++- backend/utils/common/common.go | 16 ++++++++++++++++ 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/backend/init/router/router.go b/backend/init/router/router.go index 316e5ae0579b..a72a26191a0b 100644 --- a/backend/init/router/router.go +++ b/backend/init/router/router.go @@ -3,14 +3,15 @@ package router import ( "encoding/base64" "fmt" - "github.com/1Panel-dev/1Panel/backend/app/service" - "github.com/1Panel-dev/1Panel/backend/constant" - "github.com/1Panel-dev/1Panel/cmd/server/res" "net/http" "regexp" "strconv" "strings" + "github.com/1Panel-dev/1Panel/backend/app/service" + "github.com/1Panel-dev/1Panel/backend/constant" + "github.com/1Panel-dev/1Panel/cmd/server/res" + "github.com/1Panel-dev/1Panel/backend/global" "github.com/1Panel-dev/1Panel/backend/i18n" "github.com/1Panel-dev/1Panel/backend/middleware" @@ -160,7 +161,7 @@ func setWebStatic(rootRouter *gin.RouterGroup) { } func Routers() *gin.Engine { - Router = gin.Default() + Router = gin.New() Router.Use(middleware.OperationLog()) // Router.Use(middleware.CSRF()) // Router.Use(middleware.LoadCsrfToken()) diff --git a/backend/middleware/ip_limit.go b/backend/middleware/ip_limit.go index 00a03e2e0d30..896d5d6c9b59 100644 --- a/backend/middleware/ip_limit.go +++ b/backend/middleware/ip_limit.go @@ -8,11 +8,17 @@ import ( "github.com/1Panel-dev/1Panel/backend/app/repo" "github.com/1Panel-dev/1Panel/backend/constant" "github.com/1Panel-dev/1Panel/backend/global" + "github.com/1Panel-dev/1Panel/backend/utils/common" "github.com/gin-gonic/gin" ) func WhiteAllow() gin.HandlerFunc { return func(c *gin.Context) { + clientIP := common.GetRealClientIP(c) + if common.IsPrivateIP(clientIP) { + c.Next() + return + } settingRepo := repo.NewISettingRepo() status, err := settingRepo.Get(settingRepo.WithByKey("AllowIPs")) if err != nil { @@ -24,7 +30,6 @@ func WhiteAllow() gin.HandlerFunc { c.Next() return } - clientIP := c.ClientIP() for _, ip := range strings.Split(status.Value, ",") { if len(ip) == 0 { continue diff --git a/backend/utils/common/common.go b/backend/utils/common/common.go index 35c486316fc5..e9ed67d90870 100644 --- a/backend/utils/common/common.go +++ b/backend/utils/common/common.go @@ -426,3 +426,19 @@ func HandleIPList(content string) ([]string, error) { } return res, nil } + +func GetRealClientIP(c *gin.Context) string { + addr := c.Request.RemoteAddr + if ip, _, err := net.SplitHostPort(addr); err == nil { + return ip + } + return addr +} + +func IsPrivateIP(ipStr string) bool { + ip := net.ParseIP(ipStr) + if ip == nil { + return false + } + return ip.IsPrivate() || ip.IsLoopback() +}