Skip to content

Commit 7396315

Browse files
feat: optimize IP whitelist validation logic
1 parent 3d20238 commit 7396315

File tree

4 files changed

+27
-3
lines changed

4 files changed

+27
-3
lines changed

core/init/router/router.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ func setWebStatic(rootRouter *gin.RouterGroup) {
6666
}
6767

6868
func Routers() *gin.Engine {
69-
Router = gin.Default()
69+
Router = gin.New()
7070
Router.Use(i18n.UseI18n())
7171
Router.Use(middleware.WhiteAllow())
7272
Router.Use(middleware.BindDomain())

core/middleware/ip_limit.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,16 @@ import (
1212
func WhiteAllow() gin.HandlerFunc {
1313
return func(c *gin.Context) {
1414
tokenString := c.GetHeader("X-Panel-Local-Token")
15-
clientIP := c.ClientIP()
15+
clientIP := common.GetRealClientIP(c)
1616
if clientIP == "127.0.0.1" && tokenString != "" && c.Request.URL.Path == "/api/v2/core/xpack/sync/ssl" {
1717
c.Set("LOCAL_REQUEST", true)
1818
c.Next()
1919
return
2020
}
21+
if common.IsPrivateIP(clientIP) {
22+
c.Next()
23+
return
24+
}
2125

2226
settingRepo := repo.NewISettingRepo()
2327
status, err := settingRepo.Get(repo.WithByKey("AllowIPs"))

core/utils/common/common.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,3 +245,19 @@ func LoadParams(param string) string {
245245
}
246246
return info
247247
}
248+
249+
func GetRealClientIP(c *gin.Context) string {
250+
addr := c.Request.RemoteAddr
251+
if ip, _, err := net.SplitHostPort(addr); err == nil {
252+
return ip
253+
}
254+
return addr
255+
}
256+
257+
func IsPrivateIP(ipStr string) bool {
258+
ip := net.ParseIP(ipStr)
259+
if ip == nil {
260+
return false
261+
}
262+
return ip.IsPrivate() || ip.IsLoopback()
263+
}

core/utils/security/security.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,11 @@ func checkIPLimit(c *gin.Context) bool {
163163
if len(status.Value) == 0 {
164164
return true
165165
}
166-
clientIP := c.ClientIP()
166+
clientIP := common.GetRealClientIP(c)
167+
if common.IsPrivateIP(clientIP) {
168+
return true
169+
}
170+
167171
for _, ip := range strings.Split(status.Value, ",") {
168172
if len(ip) == 0 {
169173
continue

0 commit comments

Comments
 (0)