-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchecker_geoip.go
87 lines (68 loc) · 1.73 KB
/
checker_geoip.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
package main
import (
_ "embed"
"fmt"
"strings"
"github.com/oschwald/maxminddb-golang"
"github.com/vasyahuyasa/botassasin/log"
)
const countryField = "country"
//go:embed GeoLite2-Country.mmdb
var embededGeoIP []byte
var _ checker = &geoIPChecker{}
type geoIPRecord struct {
Country struct {
ISOCode string `maxminddb:"iso_code"`
} `maxminddb:"country"`
}
type geoIPConfig struct {
Path string `yaml:"path"`
AllowedCountries []string `yaml:"allowed_countries"`
}
type geoIPChecker struct {
db *maxminddb.Reader
allowedCountries []string
}
func newGeoIPChecker(cfg geoIPConfig) (*geoIPChecker, error) {
var db *maxminddb.Reader
var dbErr error
var err error
if cfg.Path == "" {
db, dbErr = maxminddb.FromBytes(embededGeoIP)
if dbErr != nil {
err = fmt.Errorf("cannot load GeoIP database from %q: %w", cfg.Path, dbErr)
}
} else {
db, dbErr = maxminddb.Open(cfg.Path)
if dbErr != nil {
err = fmt.Errorf("cannot load embeded GeoIP database: %w", dbErr)
}
}
if err != nil {
return nil, err
}
dbPath := "embeded"
if cfg.Path != "" {
dbPath = cfg.Path
}
log.Printf("geoIP loaded %q, allow countries %s", dbPath, strings.Join(cfg.AllowedCountries, ","))
return &geoIPChecker{
db: db,
allowedCountries: cfg.AllowedCountries,
}, nil
}
func (gi *geoIPChecker) Check(l *logLine) (score harmScore, decision instantDecision) {
var rec geoIPRecord
err := gi.db.Lookup(l.IP(), &rec)
if err != nil {
log.Printf("cannot check country for %v: %v", l, err)
return 0, decisionNone
}
l.Set(countryField, rec.Country.ISOCode)
for _, allowed := range gi.allowedCountries {
if rec.Country.ISOCode == allowed {
return 0, decisionWhitelist
}
}
return 0, decisionBan
}