github.com/anuvu/tyk@v2.9.0-beta9-dl-apic+incompatible/gateway/mw_ip_blacklist.go (about)

     1  package gateway
     2  
     3  import (
     4  	"errors"
     5  	"net"
     6  	"net/http"
     7  
     8  	"github.com/TykTechnologies/tyk/request"
     9  )
    10  
    11  // IPBlackListMiddleware lets you define a list of IPs to block from upstream
    12  type IPBlackListMiddleware struct {
    13  	BaseMiddleware
    14  }
    15  
    16  func (i *IPBlackListMiddleware) Name() string {
    17  	return "IPBlackListMiddleware"
    18  }
    19  
    20  func (i *IPBlackListMiddleware) EnabledForSpec() bool {
    21  	return i.Spec.EnableIpBlacklisting && len(i.Spec.BlacklistedIPs) > 0
    22  }
    23  
    24  // ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail
    25  func (i *IPBlackListMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) {
    26  	remoteIP := net.ParseIP(request.RealIP(r))
    27  
    28  	// Enabled, check incoming IP address
    29  	for _, ip := range i.Spec.BlacklistedIPs {
    30  		// Might be CIDR, try this one first then fallback to IP parsing later
    31  		blockedIP, blockedNet, err := net.ParseCIDR(ip)
    32  		if err != nil {
    33  			blockedIP = net.ParseIP(ip)
    34  		}
    35  
    36  		// Check CIDR if possible
    37  		if blockedNet != nil && blockedNet.Contains(remoteIP) {
    38  
    39  			return i.handleError(r, remoteIP.String())
    40  		}
    41  
    42  		// We parse the IP to manage IPv4 and IPv6 easily
    43  		if blockedIP.Equal(remoteIP) {
    44  
    45  			return i.handleError(r, remoteIP.String())
    46  		}
    47  	}
    48  
    49  	return nil, http.StatusOK
    50  }
    51  
    52  func (i *IPBlackListMiddleware) handleError(r *http.Request, blacklistedIP string) (error, int) {
    53  
    54  	// Fire Authfailed Event
    55  	AuthFailed(i, r, blacklistedIP)
    56  	// Report in health check
    57  	reportHealthValue(i.Spec, KeyFailure, "-1")
    58  	return errors.New("access from this IP has been disallowed"), http.StatusForbidden
    59  }