-
Notifications
You must be signed in to change notification settings - Fork 4
/
module.go
310 lines (255 loc) · 6.69 KB
/
module.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package realip
import (
"net"
"net/http"
"strconv"
"strings"
"time"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"go.uber.org/zap"
)
var (
realPool = caddy.NewUsagePool()
)
type RealIP struct {
// Presets stores the presets that should be loaded
Presets []string `json:"presets"`
// From stores any manually included presets
From []*net.IPNet `json:"from"`
// Header to load an IP Address from typically X-Forwarded-For
Header string `json:"header"`
// MaxHops configures the maxiumum number of hops or IPs to be found in a forward header.
// It's purpose is to prevent abuse and/or DOS attacks from long forward-chains, since each one
// must be parsed and checked against a list of subnets.
// The default is 5, -1 to disable. If set to 0, any request with a forward header will be rejected
MaxHops int `json:"max_hops"`
// Will reject the request if a valid IP address can not be found
Strict bool `json:"strict"`
// How often the dynamic presets are reloaded
RefreshFrequency caddy.Duration `json:"refresh_frequency"`
// manages a global list of trusted IP ranges
state *state
// manages the complete ip set for this instance of real ip
complete []*net.IPNet
// is closed when this instance of real ip is unloaded via caddy cleanup
done chan bool
logger *zap.Logger
}
type CIDRUpdater func() ([]*net.IPNet, error)
type CIDRSet struct {
Ranges []*net.IPNet
Update CIDRUpdater
}
func init() {
caddy.RegisterModule(RealIP{})
httpcaddyfile.RegisterHandlerDirective("realip", parseCaddyfileHandler)
}
func (RealIP) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.handlers.realip",
New: func() caddy.Module {
return new(RealIP)
},
}
}
func (m *RealIP) Provision(ctx caddy.Context) error {
m.logger = ctx.Logger(m)
m.done = make(chan bool, 1)
if m.RefreshFrequency == 0 {
m.RefreshFrequency = caddy.Duration(24 * time.Hour)
}
if m.MaxHops == 0 {
m.MaxHops = 5
}
tmp, _, err := realPool.LoadOrNew("realip.state", func() (caddy.Destructor, error) {
state := state{}
state.Start(time.Duration(m.RefreshFrequency), m.logger)
return &state, nil
})
if err != nil {
m.logger.Error("unable to load previous state", zap.Error(err))
return err
}
if state, ok := tmp.(*state); ok {
m.state = state
}
// monitor for changes the presets or if this instance of the plugin has been closed
go func() {
gs := m.state
for {
select {
case <-m.done:
m.logger.Debug("cidr refresh monitor closing")
return
case _, ok := <-gs.Refreshed:
if !ok {
// this only happens if state object is being removed
return
}
m.buildCompleteSet()
}
}
}()
return m.buildCompleteSet()
}
func (m *RealIP) Cleanup() error {
if m.done != nil {
close(m.done)
}
return nil
}
func (m *RealIP) buildCompleteSet() error {
set := make([]*net.IPNet, 0)
// append any manual entries
set = append(set, m.From...)
// append current preset ranges
for _, p := range m.Presets {
set = append(set, presetRegistry[p].Ranges...)
}
m.complete = set
m.logger.Debug("ip set rebuilt")
return nil
}
func parseCaddyfileHandler(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
var m RealIP
err := m.UnmarshalCaddyfile(h.Dispenser)
if err != nil {
return nil, err
}
return m, err
}
func addIpRanges(m *RealIP, d *caddyfile.Dispenser, ranges []string) error {
for _, v := range ranges {
if _, ok := presetRegistry[v]; ok {
m.Presets = append(m.Presets, v)
continue
}
_, cidr, err := net.ParseCIDR(v)
if err != nil {
return d.Err(err.Error())
}
m.From = append(m.From, cidr)
}
return nil
}
func parseStringArg(d *caddyfile.Dispenser, out *string) error {
if !d.Args(out) {
return d.ArgErr()
}
return nil
}
func parseIntArg(d *caddyfile.Dispenser, out *int) error {
var strVal string
err := parseStringArg(d, &strVal)
if err == nil {
*out, err = strconv.Atoi(strVal)
}
return err
}
func parseBoolArg(d *caddyfile.Dispenser, out *bool) error {
var strVal string
err := parseStringArg(d, &strVal)
if err == nil {
*out, err = strconv.ParseBool(strVal)
}
return err
}
func (m *RealIP) validSource(addr string) bool {
ip := net.ParseIP(addr)
if ip == nil {
return false
}
for _, from := range m.complete {
if from.Contains(ip) {
return true
}
}
return false
}
func (m RealIP) ServeHTTP(w http.ResponseWriter, req *http.Request, handler caddyhttp.Handler) error {
m.logger.Info("checking the header",
zap.String("header", m.Header),
zap.String("remoteaddr", req.RemoteAddr),
zap.Int("maxhops", m.MaxHops),
)
// check the direct upstream server
host, port, err := net.SplitHostPort(req.RemoteAddr)
if err != nil || !m.validSource(host) {
if m.Strict {
return caddyhttp.Error(http.StatusForbidden, err)
}
return handler.ServeHTTP(w, req)
}
if !m.validSource(host) {
if m.Strict {
return caddyhttp.Error(http.StatusForbidden, err)
}
return handler.ServeHTTP(w, req)
}
// check the forwarded for header
if hVal := req.Header.Get(m.Header); hVal != "" {
parts := strings.Split(hVal, ",")
for i, part := range parts {
parts[i] = strings.TrimSpace(part)
}
if m.MaxHops != -1 && len(parts) > m.MaxHops {
return caddyhttp.Error(http.StatusForbidden, err)
}
ip := net.ParseIP(parts[len(parts)-1])
if ip == nil {
if m.Strict {
return caddyhttp.Error(http.StatusForbidden, err)
}
return handler.ServeHTTP(w, req)
}
req.RemoteAddr = net.JoinHostPort(parts[len(parts)-1], port)
for i := len(parts) - 1; i >= 0; i-- {
req.RemoteAddr = net.JoinHostPort(parts[i], port)
if i > 0 && !m.validSource(parts[i]) {
if m.Strict {
return caddyhttp.Error(http.StatusForbidden, err)
}
return handler.ServeHTTP(w, req)
}
}
}
return handler.ServeHTTP(w, req)
}
func (m *RealIP) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
d.NextArg()
for d.NextBlock(0) {
var err error
switch d.Val() {
case "header":
err = parseStringArg(d, &m.Header)
case "from":
err = addIpRanges(m, d, d.RemainingArgs())
case "strict":
err = parseBoolArg(d, &m.Strict)
case "maxhops":
err = parseIntArg(d, &m.MaxHops)
default:
return d.Errf("Unknown realip arg")
}
if err != nil {
return d.Errf("Error parsing %s: %s", d.Val(), err)
}
}
return nil
}
func MustParseCIDR(cidr string) *net.IPNet {
_, ipnet, err := net.ParseCIDR(cidr)
if err != nil {
panic(err)
}
return ipnet
}
var (
_ caddyhttp.MiddlewareHandler = (*RealIP)(nil)
_ caddy.Provisioner = (*RealIP)(nil)
_ caddy.CleanerUpper = (*RealIP)(nil)
_ caddyfile.Unmarshaler = (*RealIP)(nil)
)