-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathblock.go
85 lines (78 loc) · 1.67 KB
/
block.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
package main
import (
"net"
"net/http"
"strings"
)
func agentBlock(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ua := r.Header.Get("User-Agent")
for _, bua := range []string{
"Amazonbot",
"semrush",
"Bytespider",
"AhrefsBot",
"DataForSeoBot",
"Yandex",
"meta-externalagent",
"DotBot",
"ClaudeBot",
"GPTBot",
"bingbot",
"MJ12Bot",
"PetalBot",
"Applebot",
} {
if strings.Contains(ua, bua) {
// log.Debug().Str("ua", ua).Msg("user-agent blocked")
http.Error(w, "", http.StatusForbidden)
return
}
}
next.ServeHTTP(w, r)
})
}
func ipBlock(next http.HandlerFunc) http.HandlerFunc {
ranges := make([]*net.IPNet, 0, 18)
for _, cidr := range []string{
// alicloud
"47.52.0.0/16",
"47.76.0.0/16",
// cloudflare
"173.245.48.0/20",
"103.21.244.0/22",
"103.22.200.0/22",
"103.31.4.0/22",
"141.101.64.0/18",
"108.162.192.0/18",
"190.93.240.0/20",
"188.114.96.0/20",
"197.234.240.0/22",
"198.41.128.0/17",
"162.158.0.0/15",
"104.16.0.0/13",
"104.24.0.0/14",
"172.64.0.0/13",
"131.0.72.0/22",
} {
_, ipnet, err := net.ParseCIDR(cidr)
if err != nil {
log.Error().Str("cidr", cidr).Err(err).Msg("failed to parse cloudflare ip range")
continue
}
ranges = append(ranges, ipnet)
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := net.ParseIP(actualIP(r))
if ip != nil {
for _, ipnet := range ranges {
if ipnet.Contains(ip) {
log.Debug().Stringer("ip", ip).Msg("ip blocked")
http.Error(w, "", http.StatusForbidden)
return
}
}
}
next.ServeHTTP(w, r)
})
}