forked from jpillora/ipfilter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathipfilter.go
More file actions
418 lines (385 loc) · 10.1 KB
/
ipfilter.go
File metadata and controls
418 lines (385 loc) · 10.1 KB
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
package ipfilter
import (
"bytes"
"compress/gzip"
"errors"
"io"
"log"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
maxminddb "github.com/oschwald/maxminddb-golang"
"github.com/tomasen/realip"
)
var (
DBPublicURL = "http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.mmdb.gz"
DBTempPath = filepath.Join(os.TempDir(), "ipfilter-GeoLite2-Country.mmdb.gz")
)
//Options for IPFilter. Allowed takes precendence over Blocked.
//IPs can be IPv4 or IPv6 and can optionally contain subnet
//masks (/24). Note however, determining if a given IP is
//included in a subnet requires a linear scan so is less performant
//than looking up single IPs.
//
//This could be improved with some algorithmic magic.
type Options struct {
//explicity allowed IPs
AllowedIPs []string
//explicity blocked IPs
BlockedIPs []string
//explicity allowed country ISO codes
AllowedCountries []string
//explicity blocked country ISO codes
BlockedCountries []string
//in-memory GeoLite2-Country.mmdb file,
//if not provided falls back to IPDBPath
IPDB []byte
//path to GeoLite2-Country.mmdb[.gz] file,
//if not provided defaults to ipfilter.DBTempPath
IPDBPath string
//disable automatic fetch of GeoLite2-Country.mmdb file
//by default, when ipfilter.IPDBPath is not found,
//ipfilter.IPDBFetchURL will be retrieved and stored at
//ipfilter.IPDBPath, then loaded into memory (~19MB)
IPDBNoFetch bool
//URL of GeoLite2-Country.mmdb[.gz] file,
//if not provided defaults to ipfilter.DBPublicURL
IPDBFetchURL string
//block by default (defaults to allow)
BlockByDefault bool
// TrustProxy enable check request IP from proxy
TrustProxy bool
Logger interface {
Printf(format string, v ...interface{})
}
}
type IPFilter struct {
opts Options
//mut protects the below
//rw since writes are rare
mut sync.RWMutex
defaultAllowed bool
db *maxminddb.Reader
ips map[string]bool
codes map[string]bool
subnets []*subnet
}
type subnet struct {
str string
ipnet *net.IPNet
allowed bool
}
//NewNoDB constructs IPFilter instance without downloading DB.
func NewNoDB(opts Options) *IPFilter {
if opts.IPDBFetchURL == "" {
opts.IPDBFetchURL = DBPublicURL
}
if opts.IPDBPath == "" {
opts.IPDBPath = DBTempPath
}
if opts.Logger == nil {
flags := log.LstdFlags
opts.Logger = log.New(os.Stdout, "", flags)
}
f := &IPFilter{
opts: opts,
ips: map[string]bool{},
codes: map[string]bool{},
defaultAllowed: !opts.BlockByDefault,
}
for _, ip := range opts.BlockedIPs {
f.BlockIP(ip)
}
for _, ip := range opts.AllowedIPs {
f.AllowIP(ip)
}
for _, code := range opts.BlockedCountries {
f.BlockCountry(code)
}
for _, code := range opts.AllowedCountries {
f.AllowCountry(code)
}
return f
}
//NewLazy performs database initialization in a goroutine.
//During this initialization, any DB (country code) lookups
//will be skipped. Errors will be logged instead of returned.
func NewLazy(opts Options) *IPFilter {
f := NewNoDB(opts)
go func() {
if err := f.initDB(); err != nil {
f.opts.Logger.Printf("[ipfilter] failed to intilise db: %s", err)
}
}()
return f
}
//New blocks during database initialization and checks
//validity IP strings. returns an error on failure.
func New(opts Options) (*IPFilter, error) {
f := NewNoDB(opts)
if err := f.initDB(); err != nil {
return nil, err
}
return f, nil
}
func (f *IPFilter) initDB() error {
//in-memory
if len(f.opts.IPDB) > 0 {
return f.bytesDB(f.opts.IPDB)
}
//use local copy
if fileinfo, err := os.Stat(f.opts.IPDBPath); err == nil {
if fileinfo.Size() > 0 {
file, err := os.Open(f.opts.IPDBPath)
if err != nil {
return err
}
defer file.Close()
if err = f.readerDB(f.opts.IPDBFetchURL, file); err != nil {
f.opts.Logger.Printf("[ipfilter] error reading db file %v", err)
if errDel := os.Remove(f.opts.IPDBPath); errDel != nil {
f.opts.Logger.Printf("[ipfilter] error removing bad file %v", f.opts.IPDBPath)
}
}
return err
}
f.opts.Logger.Printf("[ipfilter] IP DB is 0 byte size")
}
//ensure fetch is allowed
if f.opts.IPDBNoFetch {
return errors.New("IP DB not found and fetch is disabled")
}
//fetch and cache missing file
file, err := os.Create(f.opts.IPDBPath)
if err != nil {
return err
}
defer file.Close()
f.opts.Logger.Printf("[ipfilter] downloading %s...", f.opts.IPDBFetchURL)
resp, err := http.Get(f.opts.IPDBFetchURL)
if err != nil {
return err
}
defer resp.Body.Close()
//store on disk as db loads
r := io.TeeReader(resp.Body, file)
err = f.readerDB(DBPublicURL, r)
f.opts.Logger.Printf("[ipfilter] cached: %s", f.opts.IPDBPath)
return err
}
func (f *IPFilter) readerDB(filename string, r io.Reader) error {
if strings.HasSuffix(filename, ".gz") {
g, err := gzip.NewReader(r)
if err != nil {
return err
}
defer g.Close()
r = g
}
buff := bytes.Buffer{}
if _, err := io.Copy(&buff, r); err != nil {
return err
}
return f.bytesDB(buff.Bytes())
}
func (f *IPFilter) bytesDB(b []byte) error {
db, err := maxminddb.FromBytes(b)
if err != nil {
return err
}
f.mut.Lock()
f.db = db
f.mut.Unlock()
return nil
}
func (f *IPFilter) AllowIP(ip string) bool {
return f.ToggleIP(ip, true)
}
func (f *IPFilter) BlockIP(ip string) bool {
return f.ToggleIP(ip, false)
}
func (f *IPFilter) ToggleIP(str string, allowed bool) bool {
//check if has subnet
if ip, net, err := net.ParseCIDR(str); err == nil {
// containing only one ip?
if n, total := net.Mask.Size(); n == total {
f.mut.Lock()
f.ips[ip.String()] = allowed
f.mut.Unlock()
return true
}
//check for existing
f.mut.Lock()
found := false
for _, subnet := range f.subnets {
if subnet.str == str {
found = true
subnet.allowed = allowed
break
}
}
if !found {
f.subnets = append(f.subnets, &subnet{
str: str,
ipnet: net,
allowed: allowed,
})
}
f.mut.Unlock()
return true
}
//check if plain ip
if ip := net.ParseIP(str); ip != nil {
f.mut.Lock()
f.ips[ip.String()] = allowed
f.mut.Unlock()
return true
}
return false
}
func (f *IPFilter) AllowCountry(code string) {
f.ToggleCountry(code, true)
}
func (f *IPFilter) BlockCountry(code string) {
f.ToggleCountry(code, false)
}
//ToggleCountry alters a specific country setting
func (f *IPFilter) ToggleCountry(code string, allowed bool) {
f.mut.Lock()
f.codes[code] = allowed
f.mut.Unlock()
}
//ToggleDefault alters the default setting
func (f *IPFilter) ToggleDefault(allowed bool) {
f.mut.Lock()
f.defaultAllowed = allowed
f.mut.Unlock()
}
//Allowed returns if a given IP can pass through the filter
func (f *IPFilter) Allowed(ipstr string) bool {
return f.NetAllowed(net.ParseIP(ipstr))
}
//NetAllowed returns if a given net.IP can pass through the filter
func (f *IPFilter) NetAllowed(ip net.IP) bool {
//invalid ip
if ip == nil {
return false
}
//read lock entire function
//except for db access
f.mut.RLock()
defer f.mut.RUnlock()
//check single ips
allowed, ok := f.ips[ip.String()]
if ok {
return allowed
}
//scan subnets for any allow/block
blocked := false
for _, subnet := range f.subnets {
if subnet.ipnet.Contains(ip) {
if subnet.allowed {
return true
}
blocked = true
}
}
if blocked {
return false
}
//check country codes
f.mut.RUnlock()
code := f.NetIPToCountry(ip)
f.mut.RLock()
if code != "" {
if allowed, ok := f.codes[code]; ok {
return allowed
}
}
//use default setting
return f.defaultAllowed
}
//Blocked returns if a given IP can NOT pass through the filter
func (f *IPFilter) Blocked(ip string) bool {
return !f.Allowed(ip)
}
//NetBlocked returns if a given net.IP can NOT pass through the filter
func (f *IPFilter) NetBlocked(ip net.IP) bool {
return !f.NetAllowed(ip)
}
//Wrap the provided handler with simple IP blocking middleware
//using this IP filter and its configuration
func (f *IPFilter) Wrap(next http.Handler) http.Handler {
return &ipFilterMiddleware{IPFilter: f, next: next}
}
//IPToCountry returns the IP's ISO country code.
//Returns an empty string when cannot determine country.
func (f *IPFilter) IPToCountry(ipstr string) string {
if ip := net.ParseIP(ipstr); ip != nil {
return f.NetIPToCountry(ip)
}
return ""
}
//NetIPToCountry returns the net.IP's ISO country code.
//Returns an empty string when cannot determine country.
func (f *IPFilter) NetIPToCountry(ip net.IP) string {
f.mut.RLock()
db := f.db
f.mut.RUnlock()
return NetIPToCountry(db, ip)
}
//Wrap is equivalent to NewLazy(opts) then Wrap(next)
func Wrap(next http.Handler, opts Options) http.Handler {
return NewLazy(opts).Wrap(next)
}
//IPToCountry is a simple IP-country code lookup.
//Returns an empty string when cannot determine country.
func IPToCountry(db *maxminddb.Reader, ipstr string) string {
if ip := net.ParseIP(ipstr); ip != nil {
return NetIPToCountry(db, ip)
}
return ""
}
//NetIPToCountry is a simple IP-country code lookup.
//Returns an empty string when cannot determine country.
func NetIPToCountry(db *maxminddb.Reader, ip net.IP) string {
r := struct {
//TODO(jpillora): lookup more fields and expose more options
// IsAnonymous bool `maxminddb:"is_anonymous"`
// IsAnonymousVPN bool `maxminddb:"is_anonymous_vpn"`
// IsHostingProvider bool `maxminddb:"is_hosting_provider"`
// IsPublicProxy bool `maxminddb:"is_public_proxy"`
// IsTorExitNode bool `maxminddb:"is_tor_exit_node"`
Country struct {
Country string `maxminddb:"iso_code"`
// Names map[string]string `maxminddb:"names"`
} `maxminddb:"country"`
}{}
if db != nil {
db.Lookup(ip, &r)
}
//DEBUG log.Printf("%s -> '%s'", ip, r.Country.Country)
return r.Country.Country
}
type ipFilterMiddleware struct {
*IPFilter
next http.Handler
}
func (m *ipFilterMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var remoteIP string
if m.opts.TrustProxy {
remoteIP = realip.FromRequest(r)
} else {
remoteIP, _, _ = net.SplitHostPort(r.RemoteAddr)
}
if !m.IPFilter.Allowed(remoteIP) {
//show simple forbidden text
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}
//success!
m.next.ServeHTTP(w, r)
}