feat: optimize IP whitelist validation logic (#11102)

This commit is contained in:
CityFun 2025-11-27 16:29:31 +08:00 committed by GitHub
parent 3d2023858c
commit b5e56c6b65
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 27 additions and 3 deletions

View file

@ -66,7 +66,7 @@ func setWebStatic(rootRouter *gin.RouterGroup) {
} }
func Routers() *gin.Engine { func Routers() *gin.Engine {
Router = gin.Default() Router = gin.New()
Router.Use(i18n.UseI18n()) Router.Use(i18n.UseI18n())
Router.Use(middleware.WhiteAllow()) Router.Use(middleware.WhiteAllow())
Router.Use(middleware.BindDomain()) Router.Use(middleware.BindDomain())

View file

@ -12,12 +12,16 @@ import (
func WhiteAllow() gin.HandlerFunc { func WhiteAllow() gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
tokenString := c.GetHeader("X-Panel-Local-Token") tokenString := c.GetHeader("X-Panel-Local-Token")
clientIP := c.ClientIP() clientIP := common.GetRealClientIP(c)
if clientIP == "127.0.0.1" && tokenString != "" && c.Request.URL.Path == "/api/v2/core/xpack/sync/ssl" { if clientIP == "127.0.0.1" && tokenString != "" && c.Request.URL.Path == "/api/v2/core/xpack/sync/ssl" {
c.Set("LOCAL_REQUEST", true) c.Set("LOCAL_REQUEST", true)
c.Next() c.Next()
return return
} }
if common.IsPrivateIP(clientIP) {
c.Next()
return
}
settingRepo := repo.NewISettingRepo() settingRepo := repo.NewISettingRepo()
status, err := settingRepo.Get(repo.WithByKey("AllowIPs")) status, err := settingRepo.Get(repo.WithByKey("AllowIPs"))

View file

@ -245,3 +245,19 @@ func LoadParams(param string) string {
} }
return info return info
} }
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()
}

View file

@ -163,7 +163,11 @@ func checkIPLimit(c *gin.Context) bool {
if len(status.Value) == 0 { if len(status.Value) == 0 {
return true return true
} }
clientIP := c.ClientIP() clientIP := common.GetRealClientIP(c)
if common.IsPrivateIP(clientIP) {
return true
}
for _, ip := range strings.Split(status.Value, ",") { for _, ip := range strings.Split(status.Value, ",") {
if len(ip) == 0 { if len(ip) == 0 {
continue continue