Skip to content

Commit dc8c50c

Browse files
authored
fix: optimize IP whitelist validation logic (#11183)
1 parent 4ac490c commit dc8c50c

File tree

3 files changed

+27
-5
lines changed

3 files changed

+27
-5
lines changed

backend/init/router/router.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,15 @@ package router
33
import (
44
"encoding/base64"
55
"fmt"
6-
"github.com/1Panel-dev/1Panel/backend/app/service"
7-
"github.com/1Panel-dev/1Panel/backend/constant"
8-
"github.com/1Panel-dev/1Panel/cmd/server/res"
96
"net/http"
107
"regexp"
118
"strconv"
129
"strings"
1310

11+
"github.com/1Panel-dev/1Panel/backend/app/service"
12+
"github.com/1Panel-dev/1Panel/backend/constant"
13+
"github.com/1Panel-dev/1Panel/cmd/server/res"
14+
1415
"github.com/1Panel-dev/1Panel/backend/global"
1516
"github.com/1Panel-dev/1Panel/backend/i18n"
1617
"github.com/1Panel-dev/1Panel/backend/middleware"
@@ -160,7 +161,7 @@ func setWebStatic(rootRouter *gin.RouterGroup) {
160161
}
161162

162163
func Routers() *gin.Engine {
163-
Router = gin.Default()
164+
Router = gin.New()
164165
Router.Use(middleware.OperationLog())
165166
// Router.Use(middleware.CSRF())
166167
// Router.Use(middleware.LoadCsrfToken())

backend/middleware/ip_limit.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,17 @@ import (
88
"github.com/1Panel-dev/1Panel/backend/app/repo"
99
"github.com/1Panel-dev/1Panel/backend/constant"
1010
"github.com/1Panel-dev/1Panel/backend/global"
11+
"github.com/1Panel-dev/1Panel/backend/utils/common"
1112
"github.com/gin-gonic/gin"
1213
)
1314

1415
func WhiteAllow() gin.HandlerFunc {
1516
return func(c *gin.Context) {
17+
clientIP := common.GetRealClientIP(c)
18+
if common.IsPrivateIP(clientIP) {
19+
c.Next()
20+
return
21+
}
1622
settingRepo := repo.NewISettingRepo()
1723
status, err := settingRepo.Get(settingRepo.WithByKey("AllowIPs"))
1824
if err != nil {
@@ -24,7 +30,6 @@ func WhiteAllow() gin.HandlerFunc {
2430
c.Next()
2531
return
2632
}
27-
clientIP := c.ClientIP()
2833
for _, ip := range strings.Split(status.Value, ",") {
2934
if len(ip) == 0 {
3035
continue

backend/utils/common/common.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,3 +426,19 @@ func HandleIPList(content string) ([]string, error) {
426426
}
427427
return res, nil
428428
}
429+
430+
func GetRealClientIP(c *gin.Context) string {
431+
addr := c.Request.RemoteAddr
432+
if ip, _, err := net.SplitHostPort(addr); err == nil {
433+
return ip
434+
}
435+
return addr
436+
}
437+
438+
func IsPrivateIP(ipStr string) bool {
439+
ip := net.ParseIP(ipStr)
440+
if ip == nil {
441+
return false
442+
}
443+
return ip.IsPrivate() || ip.IsLoopback()
444+
}

0 commit comments

Comments
 (0)