github.com/in4it/ecs-deploy@v0.0.42-0.20240508120354-ed77ff16df25/ipfilter/main.go (about)

     1  package ipfilter
     2  
     3  import (
     4  	"net"
     5  	"net/http"
     6  	"strings"
     7  
     8  	"github.com/gin-gonic/gin"
     9  	"github.com/juju/loggo"
    10  )
    11  
    12  var whitelistLogger = loggo.GetLogger("whitelist")
    13  
    14  // IP filtering handlerfunc
    15  func IPWhiteList(whitelist string) gin.HandlerFunc {
    16  	return func(c *gin.Context) {
    17  		clientIP := net.ParseIP(c.ClientIP())
    18  		whitelistLogger.Tracef("Client IP: %s", clientIP)
    19  		whitelistLogger.Tracef("IP whitelist: %s", whitelist)
    20  		if clientIP == nil {
    21  			whitelistLogger.Errorf("Error: Missing or unsupported format in header")
    22  			c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
    23  				"status":  http.StatusForbidden,
    24  				"message": "Permission denied",
    25  			})
    26  			return
    27  		}
    28  		subnets := strings.Split(whitelist, ",")
    29  		for i := range subnets {
    30  			subnets[i] = strings.TrimSpace(subnets[i])
    31  		}
    32  		for _, s := range subnets {
    33  			_, ipnet, err := net.ParseCIDR(s)
    34  			if err != nil {
    35  				whitelistLogger.Errorf("Malformed whitelist argument: %s", s)
    36  			} else {
    37  				whitelistLogger.Tracef("Whitelist: %s", ipnet)
    38  				whitelistLogger.Tracef("Client: %s", clientIP)
    39  				if ipnet.Contains(clientIP) {
    40  					whitelistLogger.Tracef("Client IP match subnet: %s", ipnet)
    41  					return
    42  				}
    43  			}
    44  		}
    45  
    46  		whitelistLogger.Errorf("Blocked access from: %s", clientIP)
    47  		c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
    48  			"status":  http.StatusForbidden,
    49  			"message": "Permission denied",
    50  		})
    51  		return
    52  	}
    53  }