-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
201 lines (170 loc) · 5.27 KB
/
main.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
package scanblock
import (
"context"
"fmt"
"net"
"net/http"
"os"
"time"
)
// Default config values.
const (
DefaultMinScanRequests = 10
DefaultMinScanPercent = 25 // %
DefaultBlockSeconds = 600 // 10m
DefaultRememberSeconds = 6 * 3600 // 6h
)
// Config is the plugin configuration.
type Config struct {
// MinScanRequests defines the minimum 4xx responses to observe before
// blocking an IP.
MinScanRequests uint64
// MinTotalRequests defines the minimum requests to observe before blocking
// an IP.
MinTotalRequests uint64
// MinScanPercent defines the minimum percent of 4xx responses of total
// requests before blocking an IP.
MinScanPercent float64
// BlockPrivate defines if private IP ranges (RFC1918, RFC4193) should be
// blocked too.
BlockPrivate bool
// PlayGames defines if the the plugin should respond with random 4xx status
// codes or even kill the connection sometimes.
PlayGames bool
// BlockSeconds defines for how many seconds an IP should be blocked.
BlockSeconds int
// RememberSeconds defines for how many seconds information about an IP
// should be cached after it was last seen.
RememberSeconds int
}
// CreateConfig creates the default plugin configuration.
func CreateConfig() *Config {
return &Config{}
}
// ScanBlock is a scan blocking plugin.
type ScanBlock struct {
next http.Handler
name string
config *Config
cache *Cache
}
// New created a new plugin.
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
// Apply default values.
if config.MinScanRequests == 0 {
config.MinScanRequests = DefaultMinScanRequests
}
if config.MinScanPercent == 0 {
config.MinScanPercent = DefaultMinScanPercent
}
if config.BlockSeconds == 0 {
config.BlockSeconds = DefaultBlockSeconds
}
if config.RememberSeconds == 0 {
config.RememberSeconds = DefaultRememberSeconds
}
// Log the instantiation of the plugin, including configuration.
fmt.Fprintf(os.Stdout, "creating scanblock plugin %q with config: %+v\n", name, config)
// Return new plugin instance.
return &ScanBlock{
next: next,
name: name,
config: config,
cache: NewCache(),
}, nil
}
// ServeHTTP handles a http request.
func (sb *ScanBlock) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Check if request should be blocked and block it.
entry, ok := sb.check(r)
// If there was an issue or special bypass condition, bypass this plugin and
// continue with next handler.
if !ok {
sb.next.ServeHTTP(w, r)
return
}
// If we received no cache entry, the request should be blocked.
if entry == nil {
sb.block(w, r)
return
}
// Add this request to the counter.
entry.TotalRequests.Add(1)
// If we receive an entry, we may continue with the request, but need to wrap
// the response writer in order to record the status code.
wrappedResponseWriter := &ResponseWriter{
ResponseWriter: w,
cacheEntry: entry,
}
// Continue with next handler.
sb.next.ServeHTTP(wrappedResponseWriter, r)
}
func (sb *ScanBlock) check(r *http.Request) (entry *CacheEntry, ok bool) {
// Parse remote address.
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
fmt.Fprintf(os.Stderr, "scanblock plugin failed to parse remote address %q: %s\n", r.RemoteAddr, err)
return nil, false
}
// Parse remote IP address.
remoteIP := net.ParseIP(host)
if remoteIP == nil {
fmt.Fprintf(os.Stderr, "scanblock plugin failed to parse remote IP %q: %s\n", host, err)
return nil, false
}
// Ignore loopback IPs.
if remoteIP.IsLoopback() {
return nil, false
}
// Ignore private IPs if blocking them is not enabled.
if !sb.config.BlockPrivate && remoteIP.IsPrivate() {
return nil, false
}
// Get entry from cache.
ipString := remoteIP.String()
entry = sb.cache.GetEntry(ipString)
if entry == nil {
// If not yet in cache, create an entry.
entry = sb.cache.CreateEntry(ipString)
entry.FirstSeen.Store(time.Now().Unix())
}
// Update last seen when we're done.
defer entry.LastSeen.Store(time.Now().Unix())
// Check if we should block.
switch {
case entry.Blocking.Load():
// We are already blocking this IP.
// Unblock if time since last seen is greater than block duration.
if entry.LastSeen.Load() < time.Now().Add(-time.Duration(sb.config.BlockSeconds)*time.Second).Unix() {
entry.Blocking.Store(false)
return entry, true
}
// Otherwise, continue to block.
return nil, true
case entry.ScanRequests.Load() < sb.config.MinScanRequests:
// Not reached minimum scan requests.
return entry, true
case entry.TotalRequests.Load() < sb.config.MinTotalRequests:
// Not reached minimum total requests.
return entry, true
case (float64(entry.ScanRequests.Load())/float64(entry.TotalRequests.Load()))*100 < sb.config.MinScanPercent:
// Not reached minimum scan request percentage.
return entry, true
default:
// All conditions for a block fulfilled, start blocking.
// Log the block.
fmt.Fprintf(
os.Stdout,
"scanblock plugin %q is now blocking %s for %s (seen=%s total=%d 4xx=%d)\n",
sb.name,
ipString,
time.Duration(sb.config.BlockSeconds)*time.Second,
time.Since(time.Unix(entry.FirstSeen.Load(), 0)).Round(time.Second),
entry.TotalRequests.Load(),
entry.ScanRequests.Load(),
)
// Block this IP.
entry.Blocking.Store(true)
return nil, true
}
}