/
proxy.go
82 lines (76 loc) · 1.96 KB
/
proxy.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
78
79
80
81
82
package azugo
import (
"net"
"strings"
)
type ProxyOptions struct {
// ForwardLimit limits the number of entries in the headers that will be processed.
// The default value is 1. Set to 0 to disable the limit.
// Trusting all entries in the headers is a security risk.
ForwardLimit int
// TrustAll option sets to trust all proxies.
TrustAll bool
// TrustedIPs represents addresses of trusted proxies.
TrustedIPs []net.IP
// TrustedNetworks represents addresses of trusted networks.
TrustedNetworks []*net.IPNet
}
var defaultProxyOptions = ProxyOptions{
ForwardLimit: 1,
TrustedIPs: []net.IP{
net.IPv4(127, 0, 0, 1),
},
}
// Clear clears trusted proxy list.
func (opts *ProxyOptions) Clear() *ProxyOptions {
opts.TrustAll = false
opts.TrustedIPs = make([]net.IP, 0)
opts.TrustedNetworks = make([]*net.IPNet, 0)
return opts
}
// Add proxy IP or network in CIDR format to trusted proxy list.
// Specify "*" to trust all proxies.
func (opts *ProxyOptions) Add(ipnet string) *ProxyOptions {
// Special option to trust all proxies if IP address is set as wildcard
if ipnet == "*" {
opts.TrustAll = true
return opts
}
// CIDR format
if strings.ContainsRune(ipnet, '/') {
_, netmask, err := net.ParseCIDR(ipnet)
if err != nil || netmask == nil {
return opts
}
opts.TrustedNetworks = append(opts.TrustedNetworks, netmask)
return opts
}
// Single IP address
ipaddr := net.ParseIP(ipnet)
if ipaddr == nil {
return opts
}
opts.TrustedIPs = append(opts.TrustedIPs, ipaddr)
return opts
}
// IsTrustedProxy checks whether the proxy that request is coming from can be trusted.
func (ctx *Context) IsTrustedProxy() bool {
if ctx.RouterOptions().Proxy.TrustAll {
return true
}
ip := ctx.IP()
if ip == nil {
return false
}
for _, tip := range ctx.RouterOptions().Proxy.TrustedIPs {
if tip.Equal(ip) {
return true
}
}
for _, tnet := range ctx.RouterOptions().Proxy.TrustedNetworks {
if tnet.Contains(ip) {
return true
}
}
return false
}