Phoebe/SpeedBump.pm untested

filter: Statementstmt 0.0% 0 / 231 Branchbran 0.0% 0 / 78 Conditioncond 0.0% 0 / 64 MC/DCmcdc 0.0% 0 / 35 Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 434 CC 39 SCAR 40.4
CC
39
Cov
0%
speed_bump
132.0
speed_bump_add
90.0
speed_bump_admin
56.0
CRAP 56.9
1 # -*- mode: perl -*-
2 # Copyright (C) 2017–2021 Alex Schroeder <alex@gnu.org>
3  
4 # This program is free software: you can redistribute it and/or modify it under
5 # the terms of the GNU Affero General Public License as published by the Free
6 # Software Foundation, either version 3 of the License, or (at your option) any
7 # later version.
8 #
9 # This program is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11 # FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
12 # details.
13 #
14 # You should have received a copy of the GNU Affero General Public License along
15 # with this program. If not, see <https://www.gnu.org/licenses/>.
16  
17 =encoding utf8
18  
19 =head1 NAME
20  
21 App::Phoebe::SpeedBump - defend Phoebe against bots and leeches
22  
23 =head1 DESCRIPTION
24  
25 We want to block crawlers that are too fast or that don’t follow the
26 instructions in robots.txt. We do this by keeping a list of recent visitors: for
27 every IP number, we remember the timestamps of their last visits. If they make
28 more than 30 requests in 60s, we block them for an ever increasing amount of
29 seconds, starting with 60s and doubling every time this happens.
30  
31 For every IP number, Phoebe also records whether the last 30 requests were
32 “suspicious” or not. A suspicious request is a request that is “disallowed” for
33 bots according to “robots.txt” (more or less). If 10 requests or more of the
34 last 30 requests in the last 60 seconds are suspicious, the IP number is
35 blocked.
36  
37 When an IP number is blocked, it is blocked for 60s, and there’s a 120s
38 probation time. When you’re blocked, Phoebe responds with a “44” response. This
39 means: slow down!
40  
41 If the IP number is unblocked but gives cause for another block in the probation
42 time, it is blocked again and the blocking time is doubled: the IP is blocked
43 for 120s and there’s 240s probation time. And if it happens again, it is doubled
44 again.
45  
46 There is no configuration required, but adding a known fingerprint is suggested.
47 The C</do/speed-bump> URL shows you more information, if you have a client
48 certificate with a known fingerprint.
49  
50 The exact number of requests and the length of the time window (in seconds) can
51 be changed in the F<config> file, too.
52  
53 Here’s one way to do all that:
54  
55 package App::Phoebe;
56 our @known_fingerprints = qw(
57 sha256$0ba6ba61da1385890f611439590f2f0758760708d1375859b2184dcd8f855a00);
58 package App::Phoebe::SpeedBump;
59 our $speed_bump_requests = 20;
60 our $speed_bump_window = 20;
61 use App::Phoebe::SpeedBump;
62  
63 Here’s how to get the fingerprint from a certificate named F<client-cert.pem>:
64  
65 openssl x509 -in client-cert.pem -noout -sha256 -fingerprint \
66 | sed -e 's/://g' -e 's/SHA256 Fingerprint=/sha256$/' \
67 | tr [:upper:] [:lower:]
68  
69 This should give you the fingerprint in the correct format to add to the list
70 above.
71  
72 =cut
73  
74 package App::Phoebe::SpeedBump;
75 use App::Phoebe qw(@extensions $log $server @known_fingerprints
76 success result port host_regex );
77 use Modern::Perl;
78 use File::Slurper qw(read_binary write_binary);
79 use List::Util qw(sum);
80 use Mojo::JSON qw(decode_json encode_json);
81 use Net::IP qw(:PROC);
82 use Net::DNS qw(rr);
83  
84 @known_fingerprints = qw(
85 sha256$54c0b95dd56aebac1432a3665107d3aec0d4e28fef905020ed6762db49e84ee1);
86  
87 our $speed_bump_requests ||= 30;
88 our $speed_bump_window ||= 60;
89  
90 # $speed_data->{$ip}->{visits} = [$last, ... , $oldest]
91 # $speed_data->{$ip}->{warnings} = [1, ... , 0]
92 # $speed_data->{$ip}->{seconds} = $sec
93 # $speed_data->{$ip}->{until} = $ts
94 # $speed_data->{$ip}->{probation} = $ts + $sec
95 my $speed_data;
96 # $speed_cidr_data->{$cidr} = $ts
97 my $speed_cidr_data;
98  
99 # order is important: we must be able to reset the stats for tests; and we need
100 # to be there before others handle our requests
101 unshift(@extensions, \&speed_bump_admin, \&speed_bump);
102  
103 sub speed_bump {
104 my ($stream, $url) = @_;
105 my $now = time;
106 # go through the data we keep and delete it if the two time limits ellapsed
107 # and the last visit is past the time window we're interested in
108 for my $ip (keys %$speed_data) {
109 if ((not $speed_data->{$ip}->{until}
110 or $speed_data->{$ip}->{until} < $now)
111 and (not $speed_data->{$ip}->{probation}
112 or $speed_data->{$ip}->{probation} < $now)
113 and (not $speed_data->{$ip}->{visits}
114 or @{$speed_data->{$ip}->{visits}} == 0
115 or $speed_data->{$ip}->{visits}->[0] < $now - $speed_bump_window)) {
116 delete($speed_data->{$ip});
117 }
118 }
119 for my $cidr (keys %$speed_cidr_data) {
120 delete($speed_cidr_data->{$cidr}) if $speed_cidr_data->{$cidr} < $now;
121 }
122 # check whether the range is blocked
123 my $ip = $stream->handle->peerhost;
124 if (not $ip) {
125 $log->info("IP number cannot be determined");
126 result($stream, "44", "10");
127 # no more processing
128 return 1;
129 }
130 my $ob = new Net::IP($ip);
131 for my $cidr (keys %$speed_cidr_data) {
132 my $range = new Net::IP($cidr);
133 if (not $range) {
134 $log->error("$cidr: " . Net::IP::Error());
135 next;
136 }
137 my $overlap = $range->overlaps($ob);
138 # $IP_PARTIAL_OVERLAP (ranges overlap) $IP_NO_OVERLAP (no overlap)
139 # $IP_A_IN_B_OVERLAP (range2 contains range1) $IP_B_IN_A_OVERLAP (range1
140 # contains range2) $IP_IDENTICAL (ranges are identical) undef (problem)
141 if (defined $overlap and $overlap != $IP_NO_OVERLAP) {
142 $log->info("Net range $cidr is blocked");
143 my $delta = $speed_cidr_data->{$cidr} - $now;
144 result($stream, "44", "$delta");
145 # no more processing
146 return 1;
147 }
148 }
149 # check if the ip is currently blocked and extend the block if so
150 if (exists $speed_data->{$ip}) {
151 my $until = $speed_data->{$ip}->{until};
152 if ($until and $until > $now) {
153 my $seconds = speed_bump_add($ip, $now);
154 $log->info("IP is blocked, extending by $seconds");
155 my $delta = $speed_data->{$ip}->{until} - $now;
156 result($stream, "44", "$delta");
157 # no more processing
158 return 1;
159 }
160 }
161 # add a timestamp to the front for the current $ip
162 unshift(@{$speed_data->{$ip}->{visits}}, $now);
163 # add a warning to the front for the current $ip if the current URL could be a bot
164 unshift(@{$speed_data->{$ip}->{warnings}},
165 scalar $url =~ m!/(raw|html|diff|history|do/(?:comment|do/(?:all/(?:latest/)?)?changes/|rss|(?:all)?atom|new|more|match|search|index|tag)|menu$|text$|html$|history$)/!);
166 # if there are enough timestamps, pop the last one and see if it falls within
167 # the time window; if so, all the requests happened within the time window
168 # we're watching
169 if (@{$speed_data->{$ip}->{visits}} > $speed_bump_requests) {
170 pop(@{$speed_data->{$ip}->{warnings}});
171 my $oldest = pop(@{$speed_data->{$ip}->{visits}});
172 if ($now < $oldest + $speed_bump_window) {
173 my $seconds = speed_bump_add($ip, $now);
174 $log->info("Blocked for $seconds because of too many requests");
175 result($stream, "44", "$seconds");
176 # no more processing
177 return 1;
178 }
179 }
180 # even if the browsing speed is ok, we want to block you if you're visiting a
181 # lot of URLs that a human would not
182 my $warnings = sum(@{$speed_data->{$ip}->{warnings}}) || 0;
183 if ($warnings > $speed_bump_requests / 3) {
184 my $seconds = speed_bump_add($ip, $now);
185 $log->info("Blocked for $seconds because of too many suspicious requests");
186 result($stream, "44", "$seconds");
187 # no more processing
188 return 1;
189 }
190 # maintenance is done and no block was required, carry on
191 return 0;
192 }
193  
194 sub speed_bump_add {
195 my $ip = shift;
196 my $now = shift;
197 # if so, we're going to block you, and if you're a repeating offender, we're
198 # going to double the block
199 my $probation = $speed_data->{$ip}->{probation};
200 # the default block time is 60s for first time offenders
201 my $seconds = $speed_data->{$ip}->{seconds} || 60;
202 # if this happened within the probation time, double the block time
203 $seconds *= 2 if $seconds and $probation and $probation > $now;
204 # protect against integer overflows, haha: 28d is 28*24*60*60 = 2419200
205 $seconds = 2419200 if $seconds > 2419200;
206 $speed_data->{$ip}->{seconds} = $seconds;
207 $speed_data->{$ip}->{until} = $now + $seconds;
208 $speed_data->{$ip}->{probation} = $now + 2 * $seconds;
209 return $seconds if $seconds < 2419200;
210 # finally, check if there are enough other IPs in the same network to warrant a net range block
211 my $cidr;
212 # only compute it if it's not cached
213 $cidr = speed_bump_cidr($ip, $now) if not $speed_data->{$ip}->{cidr};
214 # only set the cache if we computed it
215 $speed_data->{$ip}->{cidr} = $cidr if $cidr;
216 # if we have a CIDR, count the other IP numbers in our data with the same CIDR
217 if ($speed_data->{$ip}->{cidr}) {
218 my $count = 0;
219 for (keys %$speed_data) {
220 $count++ if $speed_data->{$_}->{cidr} and $speed_data->{$_}->{cidr} eq $speed_data->{$ip}->{cidr};
221 }
222 # ban the CIDR if we have three or more
223 speed_bump_add_cidr($cidr, $now + $seconds) if $count >= 3;
224 }
225 return $seconds;
226 }
227  
228 sub speed_bump_add_cidr {
229 my $cidr = shift;
230 my $until = shift;
231 $log->info("Blocking CIDR $cidr");
232 $speed_cidr_data->{$cidr} = $until;
233 }
234  
235 # load on startup
236 Mojo::IOLoop->next_tick(sub {
237 my $dir = $server->{wiki_dir};
238 return unless -f "$dir/speed-bump.json";
239 my $bytes = read_binary("$dir/speed-bump.json");
240 $speed_data = decode_json $bytes;
241 speed_bump_compute_cidr_blocks() });
242  
243 # save every half hour
244 Mojo::IOLoop->recurring(1800 => sub {
245 my $bytes = encode_json $speed_data;
246 my $dir = $server->{wiki_dir};
247 write_binary("$dir/speed-bump.json", $bytes) });
248  
249 sub speed_bump_admin {
250 my $stream = shift;
251 my $url = shift;
252 my $hosts = host_regex();
253 my $port = port($stream);
254 if ($url =~ m!^gemini://(?:$hosts)(?::$port)?/do/speed-bump$!) {
255 success($stream);
256 $stream->write("# Speed Bump\n");
257 $stream->write("Administer the block lists from this menu.\n");
258 $stream->write("=> /do/speed-bump/status status\n");
259 $stream->write("=> /do/speed-bump/debug debug\n");
260 $stream->write("=> /do/speed-bump/save save\n");
261 $stream->write("=> /do/speed-bump/load load\n");
262 $stream->write("=> /do/speed-bump/reset reset\n");
263 return 1;
264 } elsif ($url =~ m!^gemini://(?:$hosts)(?::$port)?/do/speed-bump/status$!) {
265 with_speed_bump_fingerprint($stream, sub {
266 success($stream);
267 speed_bump_status($stream) });
268 return 1;
269 } elsif ($url =~ m!^gemini://(?:$hosts)(?::$port)?/do/speed-bump/debug$!) {
270 with_speed_bump_fingerprint($stream, sub {
271 success($stream, 'text/plain; charset=UTF-8');
272 use Data::Dumper;
273 $stream->write(Dumper($speed_data)) });
274 return 1;
275 } elsif ($url =~ m!^gemini://(?:$hosts)(?::$port)?/do/speed-bump/save$!) {
276 with_speed_bump_fingerprint($stream, sub {
277 success($stream);
278 my $bytes = encode_json $speed_data;
279 my $dir = $server->{wiki_dir};
280 write_binary("$dir/speed-bump.json", $bytes);
281 $stream->write("# Speed Bump Saved\n");
282 $stream->write("=> /do/speed-bump menu\n") });
283 return 1;
284 } elsif ($url =~ m!^gemini://(?:$hosts)(?::$port)?/do/speed-bump/load$!) {
285 with_speed_bump_fingerprint($stream, sub {
286 success($stream);
287 my $dir = $server->{wiki_dir};
288 my $bytes = read_binary("$dir/speed-bump.json");
289 $speed_data = decode_json $bytes;
290 speed_bump_compute_cidr_blocks();
291 $stream->write("# Speed Bump Loaded\n");
292 $stream->write("=> /do/speed-bump menu\n") });
293 return 1;
294 } elsif ($url =~ m!^gemini://(?:$hosts)(?::$port)?/do/speed-bump/reset$!) {
295 with_speed_bump_fingerprint($stream, sub {
296 $speed_data = undef;
297 success($stream);
298 $stream->write("# Speed Bump Reset\n");
299 $stream->write("The speed bump data has been reset.\n");
300 $stream->write("=> /do/speed-bump menu\n") });
301 return 1;
302 }
303 return;
304 }
305  
306 sub speed_bump_compute_cidr_blocks {
307 my %count;
308 my %until;
309 # check which CIDR has been blocked at least three times
310 for my $ip (keys %$speed_data) {
311 my $cidr = $speed_data->{$ip}->{cidr};
312 next unless $cidr;
313 $count{$cidr}++;
314 $until{$cidr} ||= $speed_data->{$ip}->{until};
315 $until{$cidr} = $speed_data->{$ip}->{until}
316 if $speed_data->{$ip}->{until} and $speed_data->{$ip}->{until} > $until{$cidr};
317 }
318 # only copy the blocked-until timestamp for those CIDRs that were listed at least three times
319 for my $cidr (keys %count) {
320 next unless $count{$cidr} >= 3;
321 speed_bump_add_cidr($cidr, $until{$cidr});
322 }
323 }
324  
325 sub with_speed_bump_fingerprint {
326 my $stream = shift;
327 my $fun = shift;
328 my $fingerprint = $stream->handle->get_fingerprint();
329 if ($fingerprint and grep { $_ eq $fingerprint} @known_fingerprints) {
330 $fun->();
331 } elsif ($fingerprint) {
332 $log->info("Unknown client certificate $fingerprint");
333 result($stream, "61", "Your client certificate is not authorised for speed bump administration");
334 } else {
335 $log->info("Requested client certificate");
336 result($stream, "60", "You need an authorised client certificate to administer speed bumps");
337 }
338 }
339  
340 sub speed_bump_status {
341 my $stream = shift;
342 $stream->write("# Speed Bump Status\n");
343 my $now = time;
344 $stream->write("```\n");
345 # <-4s> <-4s> <2/2> <-4s> <-4s> <-4s>
346 $stream->write(" From To Warns Block Until Probation IP\n");
347 for my $ip (sort {
348 $speed_data->{$b}->{visits}->[0] <=> $speed_data->{$a}->{visits}->[0] } keys %$speed_data) {
349 $stream->write(sprintf("%s %s %2d/%2d %s %s %s %-37s %s\n",
350 speed_bump_time($speed_data->{$ip}->{visits}->[-1], $now),
351 speed_bump_time($speed_data->{$ip}->{visits}->[0], $now),
352 sum(@{$speed_data->{$ip}->{warnings}} || 0),
353 scalar(@{$speed_data->{$ip}->{warnings}}) || 0,
354 speed_bump_time($speed_data->{$ip}->{seconds}),
355 speed_bump_time($speed_data->{$ip}->{until}, $now),
356 speed_bump_time($speed_data->{$ip}->{probation}, $now),
357 $ip,
358 $speed_data->{$ip}->{cidr} || ""));
359 }
360 if (%$speed_cidr_data) {
361 $stream->write("\n");
362 $stream->write("Until CIDR\n");
363 for my $cidr (keys %$speed_cidr_data) {
364 $stream->write(sprintf("%s $cidr\n", speed_bump_time($speed_cidr_data->{$cidr}, $now)));
365 }
366 }
367 $stream->write("```\n");
368 $stream->write("=> /do/speed-bump menu\n");
369 }
370  
371 sub speed_bump_cidr {
372 my $ip = shift;
373 # Sadly, routeviews does not support IPv6 at the moment!
374 return if ip_is_ipv6($ip);
375 my $now = shift;
376 my $cidr = $speed_data->{$ip}->{cidr};
377 my $until = $speed_data->{$ip}->{until};
378 return $cidr if $cidr or not $until or $until - $now < 604800;
379 # if blocked for at least 7d and no cidr is available, get it: 7*24*60*60 = 604800
380 $ip = new Net::IP ($ip) or return;
381 my $reverse = $ip->reverse_ip();
382 $reverse =~ s/in-addr\.arpa\.$/asn.routeviews.org/;
383 $log->info("DNS TXT query for $reverse");
384 for my $rr (rr($reverse, "TXT")) {
385 next unless $rr->type eq "TXT";
386 my @data = $rr->txtdata;
387 $log->debug("DNS TXT @data");
388 $cidr = join("/", @data[1..2]);
389 $speed_data->{$ip}->{cidr} = $cidr;
390 return $cidr;
391 }
392 }
393  
394 sub speed_bump_time {
395 my $seconds = shift;
396 my $now = shift;
397 return " n/a" unless $seconds;
398 $seconds -= $now if $now;
399 return sprintf("%4dd", int($seconds/86400)) if abs($seconds) > 172800; # 2d
400 return sprintf("%4dh", int($seconds/3600)) if abs($seconds) > 7200; # 2h
401 return sprintf("%4dm", int($seconds/60)) if abs($seconds) > 120; # 2min
402 return sprintf("%4ds", $seconds);
403 }
404  
405 1;