forked from kgretzky/evilginx2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blacklist.go
120 lines (102 loc) · 2.15 KB
/
blacklist.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
package core
import (
"bufio"
"fmt"
"net"
"os"
"strings"
"github.com/kgretzky/evilginx2/log"
)
const (
BLACKLIST_MODE_FULL = 0
BLACKLIST_MODE_UNAUTH = 1
BLACKLIST_MODE_OFF = 2
)
type BlockIP struct {
ipv4 net.IP
mask *net.IPNet
}
type Blacklist struct {
ips map[string]*BlockIP
masks []*BlockIP
configPath string
mode int
}
func NewBlacklist(path string) (*Blacklist, error) {
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDONLY, 0644)
if err != nil {
return nil, err
}
defer f.Close()
bl := &Blacklist{
ips: make(map[string]*BlockIP),
configPath: path,
mode: BLACKLIST_MODE_OFF,
}
fs := bufio.NewScanner(f)
fs.Split(bufio.ScanLines)
for fs.Scan() {
l := fs.Text()
// remove comments
if n := strings.Index(l, ";"); n > -1 {
l = l[:n]
}
l = strings.Trim(l, " ")
if len(l) > 0 {
if strings.Contains(l, "/") {
ipv4, mask, err := net.ParseCIDR(l)
if err == nil {
bl.masks = append(bl.masks, &BlockIP{ipv4: ipv4, mask: mask})
} else {
log.Error("blacklist: invalid ip/mask address: %s", l)
}
} else {
ipv4 := net.ParseIP(l)
if ipv4 != nil {
bl.ips[ipv4.String()] = &BlockIP{ipv4: ipv4, mask: nil}
} else {
log.Error("blacklist: invalid ip address: %s", l)
}
}
}
}
log.Info("blacklist: loaded %d ip addresses or ip masks", len(bl.ips)+len(bl.masks))
return bl, nil
}
func (bl *Blacklist) AddIP(ip string) error {
if bl.IsBlacklisted(ip) {
return nil
}
ipv4 := net.ParseIP(ip)
if ipv4 != nil {
bl.ips[ipv4.String()] = &BlockIP{ipv4: ipv4, mask: nil}
} else {
return fmt.Errorf("blacklist: invalid ip address: %s", ip)
}
// write to file
f, err := os.OpenFile(bl.configPath, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(ipv4.String() + "\n")
if err != nil {
return err
}
return nil
}
func (bl *Blacklist) IsBlacklisted(ip string) bool {
ipv4 := net.ParseIP(ip)
if ipv4 == nil {
return false
}
if _, ok := bl.ips[ip]; ok {
return true
}
for _, m := range bl.masks {
if m.mask != nil && m.mask.Contains(ipv4) {
return true
}
}
return false
}