github.com/dbernstein1/tyk@v2.9.0-beta9-dl-apic+incompatible/gateway/mw_ip_whitelist.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 // IPWhiteListMiddleware lets you define a list of IPs to allow upstream 12 type IPWhiteListMiddleware struct { 13 BaseMiddleware 14 } 15 16 func (i *IPWhiteListMiddleware) Name() string { 17 return "IPWhiteListMiddleware" 18 } 19 20 func (i *IPWhiteListMiddleware) EnabledForSpec() bool { 21 return i.Spec.EnableIpWhiteListing && len(i.Spec.AllowedIPs) > 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 *IPWhiteListMiddleware) 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.AllowedIPs { 30 // Might be CIDR, try this one first then fallback to IP parsing later 31 allowedIP, allowedNet, err := net.ParseCIDR(ip) 32 if err != nil { 33 allowedIP = net.ParseIP(ip) 34 } 35 36 // Check CIDR if possible 37 if allowedNet != nil && allowedNet.Contains(remoteIP) { 38 // matched, pass through 39 return nil, http.StatusOK 40 } 41 42 // We parse the IP to manage IPv4 and IPv6 easily 43 if allowedIP.Equal(remoteIP) { 44 // matched, pass through 45 return nil, http.StatusOK 46 } 47 } 48 49 // Fire Authfailed Event 50 AuthFailed(i, r, remoteIP.String()) 51 // Report in health check 52 reportHealthValue(i.Spec, KeyFailure, "-1") 53 54 // Not matched, fail 55 return errors.New("access from this IP has been disallowed"), http.StatusForbidden 56 }