traefik/pkg/ip/strategy.go

69 lines
1.4 KiB
Go
Raw Normal View History

package ip
import (
"net"
"net/http"
"strings"
)
const (
xForwardedFor = "X-Forwarded-For"
)
2020-05-11 10:06:07 +00:00
// Strategy a strategy for IP selection.
type Strategy interface {
GetIP(req *http.Request) string
}
2020-05-11 10:06:07 +00:00
// RemoteAddrStrategy a strategy that always return the remote address.
type RemoteAddrStrategy struct{}
2020-05-11 10:06:07 +00:00
// GetIP returns the selected IP.
func (s *RemoteAddrStrategy) GetIP(req *http.Request) string {
ip, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
return req.RemoteAddr
}
return ip
}
2020-05-11 10:06:07 +00:00
// DepthStrategy a strategy based on the depth inside the X-Forwarded-For from right to left.
type DepthStrategy struct {
Depth int
}
2020-05-11 10:06:07 +00:00
// GetIP return the selected IP.
func (s *DepthStrategy) GetIP(req *http.Request) string {
xff := req.Header.Get(xForwardedFor)
xffs := strings.Split(xff, ",")
if len(xffs) < s.Depth {
return ""
}
2018-10-05 10:43:17 +00:00
return strings.TrimSpace(xffs[len(xffs)-s.Depth])
}
// CheckerStrategy a strategy based on an IP Checker
2020-05-11 10:06:07 +00:00
// allows to check that addresses are in a trusted IPs.
type CheckerStrategy struct {
Checker *Checker
}
2020-05-11 10:06:07 +00:00
// GetIP return the selected IP.
func (s *CheckerStrategy) GetIP(req *http.Request) string {
if s.Checker == nil {
return ""
}
xff := req.Header.Get(xForwardedFor)
xffs := strings.Split(xff, ",")
for i := len(xffs) - 1; i >= 0; i-- {
2018-10-05 10:43:17 +00:00
xffTrimmed := strings.TrimSpace(xffs[i])
if contain, _ := s.Checker.Contains(xffTrimmed); !contain {
return xffTrimmed
}
}
return ""
}