-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbotfilter.go
More file actions
165 lines (148 loc) · 4.02 KB
/
Copy pathbotfilter.go
File metadata and controls
165 lines (148 loc) · 4.02 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
// Package traefik_botfilter is a Traefik middleware plugin that blocks known scans
// and applies a bounded, in-memory per-IP suspicion score.
package traefik_botfilter
import (
"bufio"
"context"
"fmt"
"io"
"net"
"net/http"
"net/netip"
"strconv"
"time"
)
type botFilter struct {
next http.Handler
config *compiledConfig
cache *clientCache
logger filterLogger
}
// New constructs a Traefik middleware. Its signature is the interface used
// by Traefik's Go plugin runtime.
func New(_ context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
if next == nil {
return nil, fmt.Errorf("botfilter: next handler is nil")
}
compiled, err := compileConfig(config)
if err != nil {
return nil, err
}
return &botFilter{
next: next,
config: compiled,
cache: newClientCache(compiled),
logger: filterLogger{name: name, enabled: compiled.LogBlockedRequests},
}, nil
}
func (b *botFilter) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
now := time.Now()
addr := clientIP(r, b.config)
ip := addressString(addr)
if addressInPrefixes(addr, b.config.whitelist) {
b.next.ServeHTTP(rw, r)
return
}
if existing := b.cache.isBanned(ip, now); existing.banned {
b.reject(rw, ip, "temporary ban", existing)
return
}
match := inspectRequest(r, b.config)
paths := requestPaths(r)
decision := b.cache.observeRequest(ip, requestObservation{
at: now,
paths: paths,
points: match.points,
forceBan: match.forceBan,
})
if decision.banned {
reason := match.reason
if reason == "" {
reason = "suspicion score threshold"
}
b.reject(rw, ip, reason, decision)
return
}
recorder := &statusRecorder{ResponseWriter: rw}
b.next.ServeHTTP(recorder, r)
if result := b.cache.observeResponse(ip, recorder.statusCode(), b.config.NotFoundScore, time.Now()); result.banned {
b.logger.blocked(ip, "404 score threshold", result.score)
}
}
func (b *botFilter) reject(rw http.ResponseWriter, ip, reason string, decision cacheResult) {
b.logger.blocked(ip, reason, decision.score)
rw.Header().Set("Cache-Control", "no-store")
rw.Header().Set("Content-Type", "text/plain; charset=utf-8")
if decision.banUntil.After(time.Now()) {
seconds := int(time.Until(decision.banUntil).Seconds())
if seconds < 1 {
seconds = 1
}
rw.Header().Set("Retry-After", strconv.Itoa(seconds))
}
rw.WriteHeader(b.config.StatusCode)
_, _ = io.WriteString(rw, "request denied\n")
}
func addressString(addr netip.Addr) string {
if !addr.IsValid() {
return ""
}
return addr.String()
}
// statusRecorder keeps downstream response capabilities available while
// recording the final status used for 404 scoring.
type statusRecorder struct {
http.ResponseWriter
status int
}
func (r *statusRecorder) WriteHeader(status int) {
if r.status != 0 {
return
}
r.status = status
r.ResponseWriter.WriteHeader(status)
}
func (r *statusRecorder) Write(data []byte) (int, error) {
if r.status == 0 {
r.status = http.StatusOK
}
return r.ResponseWriter.Write(data)
}
func (r *statusRecorder) statusCode() int {
if r.status == 0 {
return http.StatusOK
}
return r.status
}
func (r *statusRecorder) Unwrap() http.ResponseWriter { return r.ResponseWriter }
func (r *statusRecorder) Flush() {
if r.status == 0 {
r.status = http.StatusOK
}
if flusher, ok := r.ResponseWriter.(http.Flusher); ok {
flusher.Flush()
}
}
func (r *statusRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hijacker, ok := r.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, http.ErrNotSupported
}
return hijacker.Hijack()
}
func (r *statusRecorder) Push(target string, options *http.PushOptions) error {
pusher, ok := r.ResponseWriter.(http.Pusher)
if !ok {
return http.ErrNotSupported
}
return pusher.Push(target, options)
}
func (r *statusRecorder) ReadFrom(source io.Reader) (int64, error) {
if r.status == 0 {
r.status = http.StatusOK
}
if readerFrom, ok := r.ResponseWriter.(io.ReaderFrom); ok {
return readerFrom.ReadFrom(source)
}
return io.Copy(struct{ io.Writer }{Writer: r.ResponseWriter}, source)
}