-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfirewall.go
More file actions
333 lines (256 loc) · 7.27 KB
/
firewall.go
File metadata and controls
333 lines (256 loc) · 7.27 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
package main
import (
"bufio"
"errors"
"fmt"
"github.com/golang-collections/go-datastructures/bitarray"
"log"
"net"
"net/http"
"os"
"strings"
"time"
)
// ref: https://www.ip2location.com/free/robot-whitelist
// could add these results to the whitelist: select email, ip, userid from vz.request r join vz.user u on r.userid=u.id where userid >= 0 group by 1, 2, 3 order by 2, 1;
type IPs bitarray.BitArray
var (
blacklist *IPs
whitelist *IPs
dosCounter map[int]int = make(map[int]int, 0)
)
func ip_to_int(ip string) int {
val := 0
//prVal("ip_to_int ip", ip)
parts := strings.Split(ip, ".")
assert(len(parts) == 4)
for i := 0; i < 4; i++ {
val *= 256
iVal := str_to_int(parts[i])
val += iVal
}
return val
}
func int_to_ip(ip int) string {
parts := make([]string, 4)
//prVal("int_to_ip ip", ip)
pos := 3
for ip > 0 {
parts[pos] = int_to_str(ip % 256)
ip >>= 8
//prVal(" ip", ip)
pos--
}
//prVal(" parts", parts)
return strings.Join(parts, ".")
}
func registerIPSubnet(ips *IPs, ip, subnetBits int) {
//prf("registerIPSubnet %s/%d", ip, subnetBits)
assert(0 <= subnetBits && subnetBits <= 32)
rangeBits := 32 - subnetBits
numIPs := 1 << rangeBits
for i := 0; i < numIPs; i++ {
(*ips).SetBit(uint64(ip + i))
//prVal(" registering IP", int_to_ip(ip + i))
}
}
func checkIP(ips *IPs, ip int) bool {
//prVal("checkIP", ip)
bit, err := (*ips).GetBit(uint64(ip))
check(err)
return bit
}
func readIPsFile(fileName string) *IPs {
prVal("readIPsFile", fileName)
file, err := os.Open(fileName)
if err != nil {
log.Fatal(err)
}
defer file.Close()
//ips := IPs(bitarray.NewBitArray(1 << 32))
ips := IPs(bitarray.NewSparseBitArray())
//prVal("ips.Capacity()", ips.Capacity())
//prVal("size = ", ips.Capacity() / 8)
lineNum := 0
scanner := bufio.NewScanner(file)
for scanner.Scan() {
text := scanner.Text()
//prf("line %d text %s", lineNum, text)
tokens := strings.Split(text, "/")
//prVal("tokens", tokens)
ip := ip_to_int(tokens[0])
subnetBits := 32
if len(tokens) == 2 {
subnetBits = str_to_int(tokens[1])
}
//prf("tokens[0] %s ip %d subnetBits %d", tokens[0], ip, subnetBits)
// ips = append(ips, createSubnetList(ip, subnetBits))
registerIPSubnet(&ips, ip, subnetBits)
lineNum++
}
//prVal("sizeof(ips)", unsafe.Sizeof(ips))
return &ips
}
func recordBadIP(ip string) {
prVal("recordBadIP", ip)
// Write new bad ip to file.
f, err := os.OpenFile("blacklist.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
pr("error: " + err.Error())
}
defer f.Close()
if _, err := f.WriteString(fmt.Sprintf("%s\n", ip)); err != nil {
pr("error: " + err.Error())
}
}
func reportError(errorMsg string) error {
errorMsg =
"Request blocked. " + errorMsg +
" Contact the System Administrator at \"a l t e r e g o 2 0 0 @ y a h o o . c o m\" if you believe this is in error."
pr(errorMsg)
return errors.New(errorMsg)
}
func join(strList []string) string { return strings.Join(strList, "[,]") }
func logRequest(w http.ResponseWriter, r *http.Request, ip, port, path, query, errorMsg string) {
userId := GetSession(w, r)
DbExec(`INSERT INTO vz.Request(Ip, Port, Method, Path, RawQuery, Language, Referer, UserId, Error)
VALUES($1, $2, $3, $4, $5, $6, $7, $8::bigint, $9);`,
ip,
port,
r.Method,
path,
query,
join(r.Header["Accept-Language"]),
join(r.Header["Referer"]),
userId,
errorMsg)
DbExec(`INSERT INTO vz.HasVisited(UserId, PathQuery)
VALUES($1::bigint, $2)
ON CONFLICT DO NOTHING;`,
userId,
path + "?" + query)
// TODO: Inc DOS Attack counter here
}
// Returns true if this is a DOS attack - 100 requests in a minute.
func checkDOSAttack(ip int) bool {
count, _ := dosCounter[ip]
count++
if count == 100 {
return true
}
dosCounter[ip] = count
prf("Current dos count for ip %s: %d", int_to_ip(ip), count)
return false
}
func resetDOSCounters() {
for {
time.Sleep(1 * time.Minute)
dosCounter = make(map[int]int, 0)
//pr("Resetting dos counter")
}
}
// If this is an evil request, return false. Otherwise, return true and log the request.
func CheckAndLogIP(w http.ResponseWriter, r *http.Request) error {
pr("CheckAndLogIP")
var errorMsg, path, query string
ip, port, err := net.SplitHostPort(r.RemoteAddr)
path = r.URL.Path
query = r.URL.RawQuery
if flags.skipFirewall {
go logRequest(w, r, ip, port, path, query, "skipping firewall")
return nil // ok request
}
if err != nil {
errorMsg = fmt.Sprintf("RemoteAddr: %q is not IP:port. ", r.RemoteAddr)
} else if ip == "::1" {
// localhost - ok
} else {
ipVal := ip_to_int(ip)
if checkIP(whitelist, ipVal) {
// ok
} else if checkIP(blacklist, ipVal) {
errorMsg = "Blocking blacklisted ip: " + ip
} else if checkDOSAttack(ipVal) {
errorMsg = "Preventing DOS Attack"
recordBadIP(ip)
} else {
// Block method=POST and path="/"
if r.Method == "POST" && path == "/" {
errorMsg = "Blocking non-logged-in post from " + ip
//recordBadIP(ip) // This check seem legit, but it ends up blocking me somehow, so don't add to blacklist.
} else {
// Ban an IP if any request ends in .php, .cgi, .cmd. Just search for ".???".
length := len(path)
if length >= 4 {
//prVal("len(path)", length)
fourthFromLastChar := path[length-4: length-3]
prVal("fourthFromLastChar", fourthFromLastChar)
if fourthFromLastChar == "." {
extension := path[length-3:]
prVal("extension", extension)
// Block .php, .cgi, .cmd. Make sure we don't block robots.txt !!!
if extension == "php" || extension == "cgi" || extension == "cmd" {
recordBadIP(ip)
errorMsg = "Blocking script attack from " + ip + " for path " + path
}
}
}
}
}
}
// Log the request in the background.
go logRequest(w, r, ip, port, path, query, errorMsg)
if errorMsg != "" {
return reportError(errorMsg)
}
return nil // OK request
}
func InitFirewall() {
if flags.skipFirewall {
return
}
pr("reading blacklist")
blacklist = readIPsFile("blacklist.txt")
emptyList := IPs(bitarray.NewSparseBitArray())
whitelist = &emptyList
if flags.skipWhitelist {
pr("skipping whitelist")
} else {
pr("reading whitelist in background")
readWhitelist := func() {
pr(" started reading whitelist...")
whitelist = readIPsFile("whitelist.txt")
pr(" finished reading whitelist!!!")
}
go readWhitelist()
}
go resetDOSCounters()
}
/*
// // DISABLE THIS - it results in you not being able to log in!!! // Block method=POST if not logged in
// if userId < 0 && r.Method == "POST" {
// pr("blocking non-logged-in post from: " + ip)
// recordBadIP(ip)
// return false
// }
// Add the request string
pr("===========================================")
pr("logIP")
ip, port, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
prf("userip: %q is not IP:port", r.RemoteAddr)
}
prVal("IP", ip)
prVal("Port", port)
prVal("Method", r.Method) // GET
prVal("Path", r.URL.Path) // /article/?postId=17653&addOption=1
prVal("RawQuery", r.URL.RawQuery)
prVal("Host", r.Host)
prVal("Language", join(r.Header["Accept-Language"]))
prVal("Referer", join(r.Header["Referer"]))
prVal("UserAgent", join(r.Header["User-Agent"]))
//prVal("r.Form.Encode()", r.Form.Encode())
userId := GetSession(w, r)
prVal("userId", userId)
pr("<<")
*/