-
Notifications
You must be signed in to change notification settings - Fork 2
/
oragono-dnsbl.go
246 lines (215 loc) · 5 KB
/
oragono-dnsbl.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
// Copyright (c) 2020 Shivaram Lingamneni <[email protected]>
// Released under the MIT license
package main
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"os"
"strconv"
"strings"
"gopkg.in/yaml.v2"
)
type IPScriptInput struct {
IP string `json:"ip"`
}
type IPScriptOutput struct {
Result Action `json:"result"`
BanMessage string `json:"banMessage"`
// for caching: the network to which this result is applicable, and a TTL in seconds:
CacheNet string `json:"cacheNet"`
CacheSeconds int `json:"cacheSeconds"`
Error string `json:"error"`
}
func contains(i int, slice []int) bool {
for _, j := range slice {
if i == j {
return true
}
}
return false
}
type repliesConf struct {
Codes []int
Action Action
Reason string
}
type DNSBLConfigEntry struct {
Host string
Addresses int
Action Action
Reason string
Replies []repliesConf
}
type Config struct {
Precedence []Action
Lists []DNSBLConfigEntry
}
type Action int
const (
IPAccepted Action = 1
IPBanned Action = 2
IPRequireSASL Action = 3
)
func (a *Action) UnmarshalYAML(unmarshal func(interface{}) error) error {
var orig string
if err := unmarshal(&orig); err != nil {
return err
}
switch strings.ToLower(orig) {
case "allow", "accept":
*a = IPAccepted
case "block", "deny":
*a = IPBanned
case "require-sasl":
*a = IPRequireSASL
default:
return fmt.Errorf("invalid action: %s", orig)
}
return nil
}
func evaluateDNSBL(conf DNSBLConfigEntry, ipv4 bool, reversedIP string, debug bool) (result Action, message string) {
if (ipv4 && conf.Addresses == 6) || (!ipv4 && conf.Addresses == 4) {
return IPAccepted, ""
}
hostname := reversedIP + conf.Host
results, err := net.LookupHost(hostname)
if err != nil || len(results) == 0 {
if debug {
fmt.Fprintf(os.Stderr, "%s returned no results\n", hostname)
}
return IPAccepted, ""
}
record := results[0]
octets := strings.Split(record, ".")
if debug {
fmt.Fprintf(os.Stderr, "%s returned %s\n", hostname, record)
}
if len(octets) != 4 {
if debug {
fmt.Fprintf(os.Stderr, "corrupt response for %s: %s\n", hostname, record)
}
return IPAccepted, ""
}
code, err := strconv.Atoi(octets[3])
if err != nil {
if debug {
fmt.Fprintf(os.Stderr, "corrupt response for %s: %s\n", hostname, record)
}
return IPAccepted, ""
}
// see if this matches any of the special cased replies
for i := range conf.Replies {
if contains(code, conf.Replies[i].Codes) {
return conf.Replies[i].Action, conf.Replies[i].Reason
}
}
// ok, return the default
return conf.Action, conf.Reason
}
func ReverseIP(ipaddr net.IP) (reversed string, ipv4 bool) {
// include the trailing dot
var b strings.Builder
tofour := ipaddr.To4()
if tofour != nil {
ipv4 = true
// 1.2.3.4 -> 4.3.2.1.dnsbl.domain
for i := 3; i >= 0; i-- {
fmt.Fprintf(&b, "%d.", tofour[i])
}
} else {
for i := 15; i >= 0; i-- {
octet := ipaddr[i]
lsig_nibble := octet % 16
msig_nibble := octet >> 4
fmt.Fprintf(&b, "%s.", strconv.FormatInt(int64(lsig_nibble), 16))
fmt.Fprintf(&b, "%s.", strconv.FormatInt(int64(msig_nibble), 16))
}
}
return b.String(), ipv4
}
func LoadRawConfig(filename string) (config Config, err error) {
data, err := ioutil.ReadFile(filename)
if err != nil {
return
}
err = yaml.Unmarshal(data, &config)
if err != nil {
return
}
if len(config.Precedence) < 2 {
config.Precedence = []Action{IPRequireSASL, IPBanned}
}
return
}
func run() (output IPScriptOutput, err error) {
var ipaddr net.IP
defer func() {
output.BanMessage = strings.Replace(output.BanMessage, "{ip}", ipaddr.String(), -1)
}()
if len(os.Args) < 2 {
err = fmt.Errorf("no config file supplied")
return
}
debug := false
if len(os.Args) > 2 {
debug = true
}
config, err := LoadRawConfig(os.Args[1])
if err != nil {
return
}
reader := bufio.NewReader(os.Stdin)
line, err := reader.ReadBytes('\n')
if err != nil {
return
}
var input IPScriptInput
err = json.Unmarshal(line, &input)
if err != nil {
return
}
ipaddr = net.ParseIP(input.IP)
if ipaddr == nil {
err = fmt.Errorf("corrupt ip address %s", input.IP)
return
}
reversed, ipv4 := ReverseIP(ipaddr)
codes := make([]Action, len(config.Lists))
reasons := make([]string, len(config.Lists))
for i, list := range config.Lists {
codes[i], reasons[i] = evaluateDNSBL(list, ipv4, reversed, debug)
// fast path, if we got the highest precedence answer, no need to query any more
if codes[i] == config.Precedence[0] {
output.Result = codes[i]
output.BanMessage = reasons[i]
return
}
}
for _, action := range config.Precedence {
for i := 0; i < len(config.Lists); i++ {
if codes[i] == action {
output.Result = action
output.BanMessage = reasons[i]
return
}
}
}
output.Result = IPAccepted
return
}
func main() {
output, err := run()
if err != nil {
output.Result = 1 // allow
output.Error = err.Error()
}
out, err := json.Marshal(output)
if err != nil {
panic(err)
}
out = append(out, '\n')
os.Stdout.Write(out)
}