-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathplugin.go
163 lines (136 loc) · 3.63 KB
/
plugin.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package proxy
import (
"net"
"net/http"
"regexp"
"strings"
rrcontext "github.com/roadrunner-server/context"
"github.com/roadrunner-server/errors"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
)
const (
name string = "proxy_ip_parser"
configKey string = "http.trusted_subnets"
xff string = "X-Forwarded-For"
xrip string = "X-Real-Ip"
tcip string = "True-Client-Ip"
cfip string = "Cf-Connecting-Ip"
forwarded string = "Forwarded"
)
var (
forwardedRegex = regexp.MustCompile(`(?i)(?:for=)([^(;|,| )]+)`)
)
type Logger interface {
NamedLogger(name string) *zap.Logger
}
type Configurer interface {
// UnmarshalKey takes a single key and unmarshal it into a Struct.
UnmarshalKey(name string, out any) error
// Has checks if a config section exists.
Has(name string) bool
}
type Plugin struct {
cfg *Config
log *zap.Logger
trusted []*net.IPNet
}
func (p *Plugin) Init(cfg Configurer, l Logger) error {
const op = errors.Op("proxy_ip_parser_init")
if !cfg.Has(configKey) {
return errors.E(errors.Disabled)
}
p.cfg = &Config{}
err := cfg.UnmarshalKey(configKey, &p.cfg.TrustedSubnets)
if err != nil {
return errors.E(op, err)
}
if len(p.cfg.TrustedSubnets) == 0 {
return errors.E(errors.Disabled)
}
p.log = l.NamedLogger(name)
p.trusted = make([]*net.IPNet, len(p.cfg.TrustedSubnets))
for i := 0; i < len(p.cfg.TrustedSubnets); i++ {
_, ipNet, err := net.ParseCIDR(p.cfg.TrustedSubnets[i])
if err != nil {
return errors.E(op, err)
}
p.trusted[i] = ipNet
}
return nil
}
func (p *Plugin) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if val, ok := r.Context().Value(rrcontext.OtelTracerNameKey).(string); ok {
tp := trace.SpanFromContext(r.Context()).TracerProvider()
ctx, span := tp.Tracer(val).Start(r.Context(), name)
defer span.End()
r = r.WithContext(ctx)
}
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
ip := net.ParseIP(host)
for i := 0; i < len(p.trusted); i++ {
if p.trusted[i].Contains(ip) {
resolvedIP := p.resolveIP(r.Header)
if resolvedIP != "" {
r.RemoteAddr = resolvedIP
}
break
}
}
next.ServeHTTP(w, r)
})
}
func (p *Plugin) Name() string {
return name
}
// get real ip passing multiple proxy
func (p *Plugin) resolveIP(headers http.Header) string {
// new Forwarded header
// https://datatracker.ietf.org/doc/html/rfc7239
if fwd := headers.Get(forwarded); fwd != "" {
if get := forwardedRegex.FindStringSubmatch(fwd); len(get) > 1 {
// IPv6 -> It is important to note that an IPv6 address and any nodename with
// node-port specified MUST be quoted
// we should trim the "
return strings.Trim(get[1], `"`)
}
// XFF parse
} else if fwd := headers.Get(xff); fwd != "" {
s := strings.Index(fwd, ",")
if s == -1 {
return fwd
}
if len(fwd) < s {
return ""
}
return fwd[:s]
// next -> X-Real-Ip
} else if fwd := headers.Get(xrip); fwd != "" {
return fwd
}
// The logic here is the following:
// CloudFlare headers
// True-Client-IP is a general CF header in which copied information from X-Real-Ip in CF.
// CF-Connecting-IP is an Enterprise feature and we check it last in order.
// This operations are near O(1) because Headers struct are the map type -> type MIMEHeader map[string][]string
if fwd := headers.Get(tcip); fwd != "" {
return fwd
}
if fwd := headers.Get(cfip); fwd != "" {
return fwd
}
return ""
}
func inc(ip net.IP) {
for j := len(ip) - 1; j >= 0; j-- {
ip[j]++
if ip[j] > 0 {
break
}
}
}