forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmw_ip_whitelist.go
54 lines (44 loc) · 1.4 KB
/
mw_ip_whitelist.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package main
import (
"errors"
"net"
"net/http"
)
// IPWhiteListMiddleware lets you define a list of IPs to allow upstream
type IPWhiteListMiddleware struct {
BaseMiddleware
}
func (i *IPWhiteListMiddleware) Name() string {
return "IPWhiteListMiddleware"
}
func (i *IPWhiteListMiddleware) EnabledForSpec() bool {
return i.Spec.EnableIpWhiteListing && len(i.Spec.AllowedIPs) > 0
}
// ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail
func (i *IPWhiteListMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) {
remoteIP := net.ParseIP(requestIP(r))
// Enabled, check incoming IP address
for _, ip := range i.Spec.AllowedIPs {
// Might be CIDR, try this one first then fallback to IP parsing later
allowedIP, allowedNet, err := net.ParseCIDR(ip)
if err != nil {
allowedIP = net.ParseIP(ip)
}
// Check CIDR if possible
if allowedNet != nil && allowedNet.Contains(remoteIP) {
// matched, pass through
return nil, 200
}
// We parse the IP to manage IPv4 and IPv6 easily
if allowedIP.Equal(remoteIP) {
// matched, pass through
return nil, 200
}
}
// Fire Authfailed Event
AuthFailed(i, r, remoteIP.String())
// Report in health check
reportHealthValue(i.Spec, KeyFailure, "-1")
// Not matched, fail
return errors.New("Access from this IP has been disallowed"), 403
}