github.com/crowdsecurity/crowdsec@v1.6.1/pkg/apiserver/controllers/v1/utils.go (about)

     1  package v1
     2  
     3  import (
     4  	"errors"
     5  	"net"
     6  	"net/http"
     7  	"strings"
     8  
     9  	jwt "github.com/appleboy/gin-jwt/v2"
    10  	"github.com/gin-gonic/gin"
    11  
    12          middlewares "github.com/crowdsecurity/crowdsec/pkg/apiserver/middlewares/v1"
    13  	"github.com/crowdsecurity/crowdsec/pkg/database/ent"
    14  )
    15  
    16  func getBouncerFromContext(ctx *gin.Context) (*ent.Bouncer, error) {
    17  	bouncerInterface, exist := ctx.Get(middlewares.BouncerContextKey)
    18  	if !exist {
    19  		return nil, errors.New("bouncer not found")
    20  	}
    21  
    22  	bouncerInfo, ok := bouncerInterface.(*ent.Bouncer)
    23  	if !ok {
    24  		return nil, errors.New("bouncer not found")
    25  	}
    26  
    27  	return bouncerInfo, nil
    28  }
    29  
    30  func isUnixSocket(c *gin.Context) bool {
    31  	if localAddr, ok := c.Request.Context().Value(http.LocalAddrContextKey).(net.Addr); ok {
    32  		return strings.HasPrefix(localAddr.Network(), "unix")
    33  	}
    34  
    35  	return false
    36  }
    37  
    38  func getMachineIDFromContext(ctx *gin.Context) (string, error) {
    39  	claims := jwt.ExtractClaims(ctx)
    40  	if claims == nil {
    41  		return "", errors.New("failed to extract claims")
    42  	}
    43  
    44  	rawID, ok := claims[middlewares.MachineIDKey]
    45  	if !ok {
    46  		return "", errors.New("MachineID not found in claims")
    47  	}
    48  
    49  	id, ok := rawID.(string)
    50  	if !ok {
    51  		// should never happen
    52  		return "", errors.New("failed to cast machineID to string")
    53  	}
    54  
    55  	return id, nil
    56  }
    57  
    58  func (c *Controller) AbortRemoteIf(option bool) gin.HandlerFunc {
    59  	return func(gctx *gin.Context) {
    60  		if !option {
    61  			return
    62  		}
    63  
    64  		if isUnixSocket(gctx) {
    65  			return
    66  		}
    67  
    68  		incomingIP := gctx.ClientIP()
    69  		if incomingIP != "127.0.0.1" && incomingIP != "::1" {
    70  			gctx.JSON(http.StatusForbidden, gin.H{"message": "access forbidden"})
    71  			gctx.Abort()
    72  		}
    73  	}
    74  }