forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware_ip_whitelist.go
77 lines (63 loc) · 2.12 KB
/
middleware_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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main
import (
"errors"
"net"
"net/http"
"strings"
)
// IPWhiteListMiddleware lets you define a list of IPs to allow upstream
type IPWhiteListMiddleware struct {
*TykMiddleware
}
// New lets you do any initialisations for the object can be done here
func (i *IPWhiteListMiddleware) New() {}
// GetConfig retrieves the configuration from the API config - we user mapstructure for this for simplicity
func (i *IPWhiteListMiddleware) GetConfig() (interface{}, error) {
return nil, nil
}
// 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, configuration interface{}) (error, int) {
// Disabled, pass through
if !i.TykMiddleware.Spec.EnableIpWhiteListing {
return nil, 200
}
var remoteIP net.IP
// Enabled, check incoming IP address
for _, ip := range i.TykMiddleware.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)
}
splitIP := strings.Split(r.RemoteAddr, ":")
remoteIPString := splitIP[0]
// If X-Forwarded-For is set, override remoteIPString
forwarded := r.Header.Get("X-Forwarded-For")
if forwarded != "" {
ips := strings.Split(forwarded, ", ")
remoteIPString = ips[0]
log.Info("X-Forwarded-For set, remote IP: ", remoteIPString)
}
if len(splitIP) > 2 {
// Might be an IPv6 address, don't mess with it
remoteIPString = r.RemoteAddr
}
remoteIP = net.ParseIP(remoteIPString)
// 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.TykMiddleware, r, remoteIP.String())
// Report in health check
ReportHealthCheckValue(i.Spec.Health, KeyFailure, "-1")
// Not matched, fail
return errors.New("Access from this IP has been disallowed"), 403
}