hardcode cloudflare ips and also block some alicloud ips.

This commit is contained in:
fiatjaf
2024-09-26 12:40:49 -03:00
parent 567fdbb619
commit b6447bc8a3
2 changed files with 35 additions and 43 deletions

View File

@@ -1,11 +1,9 @@
package main
import (
"io"
"net"
"net/http"
"strings"
"time"
)
func agentBlock(next http.HandlerFunc) http.HandlerFunc {
@@ -31,13 +29,44 @@ func agentBlock(next http.HandlerFunc) http.HandlerFunc {
})
}
func cloudflareBlock(next http.HandlerFunc) http.HandlerFunc {
func ipBlock(next http.HandlerFunc) http.HandlerFunc {
ranges := make([]*net.IPNet, 0, 18)
for _, line := 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(strings.TrimSpace(line))
if err != nil {
log.Error().Str("line", line).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 cloudflareRanges {
for _, ipnet := range ranges {
if ipnet.Contains(ip) {
// cloudflare is not allowed
log.Debug().Stringer("ip", ip).Msg("cloudflare (attacker) ip blocked")
http.Error(w, "Forbidden", http.StatusForbidden)
return
@@ -48,37 +77,3 @@ func cloudflareBlock(next http.HandlerFunc) http.HandlerFunc {
next.ServeHTTP(w, r)
})
}
var cloudflareRanges []*net.IPNet
func updateCloudflareRangesRoutine() {
for {
newRanges := make([]*net.IPNet, 0, 30)
for _, url := range []string{
"https://www.cloudflare.com/ips-v6/",
"https://www.cloudflare.com/ips-v4/",
} {
resp, err := http.Get(url)
if err != nil {
log.Error().Err(err).Msg("failed to fetch cloudflare ips")
continue
}
data, _ := io.ReadAll(resp.Body)
resp.Body.Close()
for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") {
_, ipnet, err := net.ParseCIDR(strings.TrimSpace(line))
if err != nil {
log.Error().Str("line", line).Err(err).Msg("failed to parse cloudflare ip range")
continue
}
newRanges = append(newRanges, ipnet)
}
}
if len(newRanges) > 0 {
cloudflareRanges = newRanges
}
time.Sleep(time.Hour * 24)
}
}

View File

@@ -150,7 +150,7 @@ func main() {
}
var mainHandler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
cloudflareBlock(
ipBlock(
agentBlock(
loggingMiddleware(
queueMiddleware(
@@ -171,9 +171,6 @@ func main() {
}
}()
// download list of cloudflare ips once a day
go updateCloudflareRangesRoutine()
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
<-sc