fix: waf condition

This commit is contained in:
naiba
2024-11-23 10:21:01 +08:00
parent 867f840265
commit cd42b1b9d5
8 changed files with 154 additions and 131 deletions

View File

@@ -166,11 +166,13 @@ func optionalAuthMiddleware(mw *jwt.GinJWTMiddleware) func(c *gin.Context) {
identity := mw.IdentityHandler(c)
if identity != nil {
model.ClearIP(singleton.DB, c.GetString(model.CtxKeyRealIPStr))
c.Set(mw.IdentityKey, identity)
} else {
if err := model.BlockIP(singleton.DB, c.GetString(model.CtxKeyRealIPStr), model.WAFBlockReasonTypeBruteForceToken); err != nil {
waf.ShowBlockPage(c, err)
return
}
c.Set(mw.IdentityKey, identity)
}
c.Next()

View File

@@ -3,12 +3,12 @@ package waf
import (
_ "embed"
"net/http"
"net/netip"
"strings"
"github.com/gin-gonic/gin"
"github.com/naiba/nezha/model"
"github.com/naiba/nezha/pkg/utils"
"github.com/naiba/nezha/service/singleton"
)
@@ -32,26 +32,17 @@ func RealIp(c *gin.Context) {
c.AbortWithStatusJSON(http.StatusOK, model.CommonResponse[any]{Success: false, Error: "real ip header not found"})
return
}
ip, err := netip.ParseAddrPort(vals)
ip, err := utils.GetIPFromHeader(vals)
if err != nil {
c.AbortWithStatusJSON(http.StatusOK, model.CommonResponse[any]{Success: false, Error: err.Error()})
return
}
c.Set(model.CtxKeyRealIPStr, ip.Addr().String())
c.Set(model.CtxKeyRealIPStr, ip)
c.Next()
}
func Waf(c *gin.Context) {
if singleton.Conf.RealIPHeader == "" {
c.Next()
return
}
realipAddr := c.GetString(model.CtxKeyRealIPStr)
if realipAddr == "" {
c.Next()
return
}
if err := model.CheckIP(singleton.DB, realipAddr); err != nil {
if err := model.CheckIP(singleton.DB, c.GetString(model.CtxKeyRealIPStr)); err != nil {
ShowBlockPage(c, err)
return
}

View File

@@ -24,6 +24,13 @@
font-size: 12px;
color: #888;
}
@media (prefers-color-scheme: dark) {
body {
background-color: #111;
color: #007C41
}
}
</style>
</head>

View File

@@ -5,7 +5,6 @@ import (
"fmt"
"net/http"
"net/netip"
"strings"
"time"
"google.golang.org/grpc"
@@ -49,13 +48,11 @@ func getRealIp(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
if len(vals) == 0 {
return nil, fmt.Errorf("real ip header not found")
}
a := strings.Split(vals[0], ",")
h := strings.TrimSpace(a[len(a)-1])
ip, err := netip.ParseAddrPort(h)
ip, err := utils.GetIPFromHeader(vals[0])
if err != nil {
return nil, err
}
ctx = context.WithValue(ctx, model.CtxKeyRealIP{}, ip.Addr().String())
ctx = context.WithValue(ctx, model.CtxKeyRealIP{}, ip)
return handler(ctx, req)
}