Skip to content

Commit dafb9a5

Browse files
feat: optimize IP whitelist validation logic
1 parent 0fc7153 commit dafb9a5

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
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: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,43 @@ package middleware
22

33
import (
44
"github.com/1Panel-dev/1Panel/core/utils/common"
5+
"net"
56
"strings"
67

78
"github.com/1Panel-dev/1Panel/core/app/api/v2/helper"
89
"github.com/1Panel-dev/1Panel/core/app/repo"
910
"github.com/gin-gonic/gin"
1011
)
1112

13+
func getRealClientIP(c *gin.Context) string {
14+
addr := c.Request.RemoteAddr
15+
if ip, _, err := net.SplitHostPort(addr); err == nil {
16+
return ip
17+
}
18+
return addr
19+
}
20+
21+
func IsPrivateIP(ipStr string) bool {
22+
ip := net.ParseIP(ipStr)
23+
if ip == nil {
24+
return false
25+
}
26+
return ip.IsPrivate() || ip.IsLoopback()
27+
}
28+
1229
func WhiteAllow() gin.HandlerFunc {
1330
return func(c *gin.Context) {
1431
tokenString := c.GetHeader("X-Panel-Local-Token")
15-
clientIP := c.ClientIP()
32+
clientIP := getRealClientIP(c)
1633
if clientIP == "127.0.0.1" && tokenString != "" && c.Request.URL.Path == "/api/v2/core/xpack/sync/ssl" {
1734
c.Set("LOCAL_REQUEST", true)
1835
c.Next()
1936
return
2037
}
38+
if IsPrivateIP(clientIP) {
39+
c.Next()
40+
return
41+
}
2142

2243
settingRepo := repo.NewISettingRepo()
2344
status, err := settingRepo.Get(repo.WithByKey("AllowIPs"))

0 commit comments

Comments
 (0)