BlockerHelper/backends/abuseipdb.pm

filter: Statementstmt 46.4% 117 / 252 Branchbran 45.9% 45 / 98 Conditioncond 47.6% 20 / 42 MC/DCmcdc 24.0% 6 / 25 Subroutinesub 69.5% 16 / 23 Podpod 100% 13 / 13 totaltotal 47.9% 217 / 453 CC 65 SCAR 36.8
CC
65
Cov
46%
_request
72.0
new
69.9
ban
39.6
CRAP 39.6
« BlockerHelper/backends/vyos.pm ↑ Summary BlockerHelper/backends/bgp_rtbh.pm »
1 package Net::Firewall::BlockerHelper::backends::abuseipdb;
2  
3 1 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use base qw( Error::Helper Net::Firewall::BlockerHelper::Util );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Regexp::IPv4 qw($IPv4_re);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Regexp::IPv6 qw($IPv6_re);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 =head1 NAME
11  
12 Net::Firewall::BlockerHelper::backends::abuseipdb - Report banned IPs to AbuseIPDB.
13  
14 =head1 VERSION
15  
16 Version 0.2.0
17  
18 =cut
19  
20 1 our $VERSION = '0.2.0';
21  
22 =head1 SYNOPSIS
23  
24 use Net::Firewall::BlockerHelper;
25  
26 my $fw_helper = Net::Firewall::BlockerHelper->new(
27 backend => 'abuseipdb',
28 name => 'ssh',
29 options => {
30 key => $abuseipdb_api_key,
31 categories => [ '18', '22' ],
32 },
33 );
34  
35 $fw_helper->init_backend;
36 $fw_helper->ban( ban => '1.2.3.4' );
37  
38 =head1 DESCRIPTION
39  
40 Reports banned IPs to L<AbuseIPDB|https://www.abuseipdb.com/> via its v2 REST
41 API, equivalent to the fail2ban abuseipdb action. This backend blocks nothing
42 itself; it is meant to be used alongside a blocking backend so a ban both
43 blocks locally and reports upstream.
44  
45 Reports can not be withdrawn, so unban, flush, and teardown are purely
46 internal bookkeeping and touch the API not at all. re_init likewise does not
47 re-report anything, as there is no remote state to restore.
48  
49 Reporting the same IP again within AbuseIPDB's rate limit window (15 minutes
50 at the time of writing) is answered with a HTTP 429, which this backend
51 treats as already reported rather than as an error, so replaying saved ban
52 state through ban does not error out.
53  
54 Both IPv4 and IPv6 are supported. Reporting is per IP; ports and protocols are
55 not supported and specifying them is an error.
56  
57 The comment sent with each report is publicly visible on AbuseIPDB, so do not
58 put anything sensitive in the C<comment> option.
59  
60 L<LWP::UserAgent> is loaded at run time, so it is only required when this
61 backend is actually used. As the API is https only, L<LWP::Protocol::https>
62 must be present as well.
63  
64 =head1 METHODS
65  
66 =head2 new
67  
68 Initiates the backend object. No API calls are made until L</init>.
69  
70 - options :: Backend specific options. See below.
71 - prefix :: Prefix to use. Must match /^[a-zA-Z0-9]+$/. Default kur.
72 - name :: Name of this instance. Required.
73  
74 Ports and protocols are not supported and specifying either is an error.
75  
76 The options hash accepts the following.
77  
78 - key :: AbuseIPDB API key. Required.
79 - Default :: undef
80  
81 - categories :: Report categories, as either a array ref of category
82 numbers or a comma separated string of them. See
83 L<https://www.abuseipdb.com/categories> for the meanings; the
84 default, 18, is Brute-Force.
85 - Default :: 18
86  
87 - comment :: Comment attached to each report. '%%%BAN%%%' is replaced
88 with the IP being reported. Publicly visible on AbuseIPDB. If
89 blank, no comment is sent.
90 - Default :: banned by <prefix>_<name>
91  
92 - timeout :: HTTP timeout in seconds.
93 - Default :: 30
94  
95 All errors are considered fatal, meaning if new fails it will die.
96  
97 =cut
98  
99 8 ▶sub new {
Subroutine new: called CC=30 SCAR=42.5
Pod documented
100 8 my ( $blank, %opts ) = @_;
101  
102 8 my $self = {
103 perror => undef,
104 error => undef,
105 errorLine => undef,
106 errorFilename => undef,
107 errorString => "",
108 errorExtra => {
109 all_errors_fatal => 1,
110 # all_fatal is what Error::Helper 2.1.0 actually checks; all_errors_fatal
111 # is kept for the name documented in its POD
112 all_fatal => 1,
113 flags => {
114 1 => 'notInited',
115 6 => 'invalidPrefixSpecified',
116 7 => 'invalidName',
117 8 => 'optionsNotHash',
118 9 => 'noBanItem',
119 10 => 'banItemNotIP',
120 12 => 'backendInitError',
121 13 => 'banFailed',
122 14 => 'unbanFailed',
123 15 => 'listFailed',
124 16 => 'reInitFailed',
125 17 => 'teardownFailed',
126 18 => 'alreadyInited',
127 23 => 'initFailed',
128 24 => 'checkFailed',
129 25 => 'flushFailed',
130 26 => 'portsNotSupported',
131 27 => 'protocolsNotSupported',
132 30 => 'keyNotDefined',
133 31 => 'categoriesInvalid',
134 32 => 'banCidrFailed',
135 33 => 'unbanCidrFailed',
136 34 => 'cidrItemNotCidr',
137 35 => 'cidrNotSupported',
138 36 => 'listCidrFailed',
139 },
140 fatal_flags => {},
141 perror_not_fatal => 0,
142 },
143 options => {},
144 ports => [],
145 protocols => [],
146 testing => undef,
147 test_data => undef,
148 prefix => 'kur',
149 name => undef,
150 frontend_obj => undef,
151 inited => 0,
152 banned => {},
153 cidr_supported => 0,
154 ua => undef,
155 };
156 8 bless $self;
157  
158 # reporting is per IP; ports and protocols have no meaning here
159 8 ▶ if ( defined( $opts{ports} ) && ref( $opts{ports} ) eq 'ARRAY' && defined( $opts{ports}[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"ports"} and ref $opts{"ports"} eq "ARRAY" and defined $opts{"ports"}[0]) 1 7 8
Condition50%3/6
defined $opts{"ports"} and ref $opts{"ports"} eq "ARRAY" and defined $opts{"ports"}[0]
!ll&&!rl&&r
071
defined $opts{"ports"} and ref $opts{"ports"} eq "ARRAY"
!ll&&!rl&&r
008
MC/DC33%1/3
defined $opts{"ports"} and ref $opts{"ports"} eq "ARRAY" and defined $opts{"ports"}[0]
defined $opts{"ports"} ref $opts{"ports"} eq "ARRAY" defined $opts{"ports"}[0]
Truth table50%2/4
A and B and C
A= defined $opts{"ports"}B= ref $opts{"ports"} eq "ARRAY"C= defined $opts{"ports"}[0]
ABCresult
0XX0
10X0
1100
1111
160 1 $self->{perror} = 1;
161 1 $self->{error} = 26;
162 1 $self->{errorString} = 'the abuseipdb backend reports whole IPs and does not support ports';
163 1 $self->warn;
164 }
165 7 ▶ if ( defined( $opts{protocols} ) && ref( $opts{protocols} ) eq 'ARRAY' && defined( $opts{protocols}[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"protocols"} and ref $opts{"protocols"} eq "ARRAY" and defined $opts{"protocols"}[0]) 0 7 7
Condition33%2/6
defined $opts{"protocols"} and ref $opts{"protocols"} eq "ARRAY" and defined $opts{"protocols"}[0]
!ll&&!rl&&r
070
defined $opts{"protocols"} and ref $opts{"protocols"} eq "ARRAY"
!ll&&!rl&&r
007
MC/DC0%0/3
defined $opts{"protocols"} and ref $opts{"protocols"} eq "ARRAY" and defined $opts{"protocols"}[0]
defined $opts{"protocols"} ref $opts{"protocols"} eq "ARRAY" defined $opts{"protocols"}[0]
Truth table25%1/4
A and B and C
A= defined $opts{"protocols"}B= ref $opts{"protocols"} eq "ARRAY"C= defined $opts{"protocols"}[0]
ABCresult
0XX0
10X0
1100
1111
166 0 $self->{perror} = 1;
167 0 $self->{error} = 27;
168 0 $self->{errorString} = 'the abuseipdb backend reports whole IPs and does not support protocols';
169 0 $self->warn;
170 }
171  
172 # make sure prefix is sane if defined
173 7 ▶ if ( defined( $opts{prefix} ) && $opts{prefix} !~ /^[a-zA-Z0-9]+$/ ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opts{'prefix'} and not $opts{'prefix'} =~ /^[a-zA-Z0-9]+$/) { } 0 7 7
elsif (defined $opts{'prefix'}) { } 7 0 7
Condition33%1/3
defined $opts{"prefix"} and not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
!ll&&!rl&&r
070
MC/DC0%0/2
defined $opts{"prefix"} and not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
defined $opts{"prefix"} not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
Truth table33%1/3
A and not(B)
A= defined $opts{"prefix"}B= not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
ABresult
0X0
100
111
174 0 $self->{perror} = 1;
175 0 $self->{error} = 6;
176 $self->{errorString}
177 0 = '"' . $opts{prefix} . '" is not a valid prefix as it does not match the regex /^[a-zA-Z0-9]+$/';
178 0 $self->warn;
179 } elsif ( defined( $opts{prefix} ) ) {
180 7 $self->{prefix} = $opts{prefix};
181 }
182  
183 # make sure we have a name and that it is valid
184 7 ▶ if ( !defined( $opts{name} ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $opts{'name'}) { } 0 7 7
elsif (not $opts{'name'} =~ /^[a-zA-Z0-9\-]+$/) { } 0 7 7
185 0 $self->{perror} = 1;
186 0 $self->{error} = 7;
187 0 $self->{errorString} = 'name is undef';
188 0 $self->warn;
189 } elsif ( $opts{name} !~ /^[a-zA-Z0-9\-]+$/ ) {
190 0 $self->{perror} = 1;
191 0 $self->{error} = 7;
192 0 $self->{errorString} = 'name set to "' . $opts{name} . '" which does not match the regexp /^[a-zA-Z0-9\-]+$/';
193 0 $self->warn;
194 }
195 7 $self->{name} = $opts{name};
196  
197 7 ▶ if ( defined( $opts{testing} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"testing"}) 7 0 7
198 7 $self->{testing} = $opts{testing};
199 }
200 7 ▶ if ( defined( $opts{frontend_obj} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"frontend_obj"}) 7 0 7
201 7 $self->{frontend_obj} = $opts{frontend_obj};
202 }
203  
204 7 ▶ if ( defined( $opts{options} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"options"}) 7 0 7
205 7 ▶ if ( ref( $opts{options} ) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $opts{"options"} ne "HASH") 0 7 7
206 0 $self->{perror} = 1;
207 0 $self->{error} = 8;
208 0 $self->{errorString} = 'ref for options is "' . ref( $opts{options} ) . '" and not HASH';
209 0 $self->warn;
210 }
211 7 $self->{options} = $opts{options};
212 }
213  
214 # required options
215 7 ▶ if ( !defined( $self->{options}{key} ) || $self->{options}{key} eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{"options"}{"key"} or $self->{"options"}{"key"} eq "") 1 6 7
Condition66%2/3
not defined $self->{"options"}{"key"} or $self->{"options"}{"key"} eq ""
l!l&&r!l&&!r
106
MC/DC50%1/2
not defined $self->{"options"}{"key"} or $self->{"options"}{"key"} eq ""
not defined $self->{"options"}{"key"} $self->{"options"}{"key"} eq ""
Truth table66%2/3
not(A) or B
A= not defined $self->{"options"}{"key"}B= $self->{"options"}{"key"} eq ""
ABresult
1X1
011
000
216 1 $self->{perror} = 1;
217 1 $self->{error} = 30;
218 1 $self->{errorString} = 'the option key is undef or blank';
219 1 $self->warn;
220 }
221  
222 # categories may be a array ref of category numbers or a comma separated
223 # string of them... normalized to the comma separated string form
224 6 ▶ if ( !defined( $self->{options}{categories} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $self->{'options'}{'categories'}) { } 1 5 6
elsif (ref $self->{'options'}{'categories'} eq 'ARRAY') { } 2 3 5
elsif (ref $self->{'options'}{'categories'} ne '' or not $self->{'options'}{'categories'} =~ /^[0-9]+(,[0-9]+)*$/) { } 2 1 3
225 1 $self->{options}{categories} = '18';
226 } elsif ( ref( $self->{options}{categories} ) eq 'ARRAY' ) {
227 2 foreach my $item ( @{ $self->{options}{categories} } ) {
228 4 ▶ if ( !defined($item) || ref($item) ne '' || $item !~ /^[0-9]+$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $item or ref $item ne "" or not $item =~ /^[0-9]+$/) 1 3 4
Condition50%3/6
not defined $item or ref $item ne "" or not $item =~ /^[0-9]+$/
l!l&&r!l&&!r
013
not defined $item or ref $item ne ""
l!l&&r!l&&!r
004
MC/DC33%1/3
not defined $item or ref $item ne "" or not $item =~ /^[0-9]+$/
not defined $item ref $item ne "" not $item =~ /^[0-9]+$/
Truth table50%2/4
not(A) or B or not(C)
A= not defined $itemB= ref $item ne ""C= not $item =~ /^[0-9]+$/
ABCresult
1XX1
01X1
0011
0000
229 1 $self->{perror} = 1;
230 1 $self->{error} = 31;
231 $self->{errorString}
232 1 ▶ = 'categories contains "'
Branch: 1 branch
BranchTrueFalseTotal
defined $item ? : 1 0 1
233 . ( defined($item) ? $item : 'undef' )
234 . '" which is not a positive int';
235 1 $self->warn;
236 }
237 }
238 1 $self->{options}{categories} = join( ',', @{ $self->{options}{categories} } );
239 ▶ } elsif ( ref( $self->{options}{categories} ) ne '' || $self->{options}{categories} !~ /^[0-9]+(,[0-9]+)*$/ ) {
Condition66%2/3
ref $self->{"options"}{"categories"} ne "" or not $self->{"options"}{"categories"} =~ /^[0-9]+(,[0-9]+)*$/
l!l&&r!l&&!r
021
MC/DC50%1/2
ref $self->{"options"}{"categories"} ne "" or not $self->{"options"}{"categories"} =~ /^[0-9]+(,[0-9]+)*$/
ref $self->{"options"}{"categories"} ne "" not $self->{"options"}{"categories"} =~ /^[0-9]+(,[0-9]+)*$/
Truth table66%2/3
A or not(B)
A= ref $self->{"options"}{"categories"} ne ""B= not $self->{"options"}{"categories"} =~ /^[0-9]+(,[0-9]+)*$/
ABresult
1X1
011
000
240 2 $self->{perror} = 1;
241 2 $self->{error} = 31;
242 $self->{errorString}
243 = 'categories is "'
244 . $self->{options}{categories}
245 2 . '" and not a array ref or comma separated string of positive ints';
246 2 $self->warn;
247 }
248  
249 # defaults
250 3 ▶ $self->{options}{timeout} = 30 if ( !defined( $self->{options}{timeout} ) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"options"}{"timeout"} 3 0 3
251 3 ▶ if ( !defined( $self->{options}{comment} ) && defined( $self->{name} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{"options"}{"comment"} and defined $self->{"name"}) 1 2 3
Condition66%2/3
not defined $self->{"options"}{"comment"} and defined $self->{"name"}
!ll&&!rl&&r
201
MC/DC50%1/2
not defined $self->{"options"}{"comment"} and defined $self->{"name"}
not defined $self->{"options"}{"comment"} defined $self->{"name"}
Truth table66%2/3
not(A) and B
A= not defined $self->{"options"}{"comment"}B= defined $self->{"name"}
ABresult
0X0
100
111
252 1 $self->{options}{comment} = 'banned by ' . $self->{prefix} . '_' . $self->{name};
253 }
254  
255 3 return $self;
256 } ## end sub new
257  
258 # Internal helper. Returns the base URL of the AbuseIPDB v2 API, which the
259 # other URLs in this backend are built on.
260 #
261 # It is a constant rather than an option, since AbuseIPDB is a single hosted
262 # service with one endpoint; there is no self hosted or per account variant to
263 # point at.
264 #
265 # Takes no arguments.
266 #
267 # Returns the base URL as a string, with no trailing slash.
268 #
269 # $self->_api_base; # https://api.abuseipdb.com/api/v2
270 12 ▶sub _api_base {
Subroutine _api_base: called CC=1 SCAR=0.0
271 12 my ($self) = @_;
272  
273 12 return 'https://api.abuseipdb.com/api/v2';
274 }
275  
276 # Internal helper. Returns the URL of a harmless read only call, used by init
277 # and check to confirm the service is reachable and the API key works.
278 #
279 # This backend is report only: it never blocks anything and creates nothing
280 # remotely, so there is no setup whose presence could be verified. What can be
281 # checked is that the API answers and the key is accepted, which is what this
282 # is for. Nothing parses the response; only success matters.
283 #
284 # The address queried is 127.0.0.2, deliberately chosen: it is a loopback
285 # address that cannot be a real reporter or target, so the probe cannot be
286 # mistaken for interest in a genuine host. The one day window keeps the
287 # response small.
288 #
289 # Note this consumes a request against the account's daily check quota each
290 # time it runs, which matters on an instance whose self healing check fires
291 # often.
292 #
293 # Takes no arguments.
294 #
295 # Returns the URL as a string, for a GET whose result is only inspected for
296 # success.
297 #
298 # $self->_check_url;
299 # # https://api.abuseipdb.com/api/v2/check?ipAddress=127.0.0.2&maxAgeInDays=1
300 8 ▶sub _check_url {
Subroutine _check_url: called CC=1 SCAR=0.0
301 8 my ($self) = @_;
302  
303 8 return $self->_api_base . '/check?ipAddress=127.0.0.2&maxAgeInDays=1';
304 }
305  
306 # Internal helper. Builds the form encoded body that reports one address to
307 # AbuseIPDB.
308 #
309 # The categories are sent as the configured value, which is normalized to a
310 # comma separated list at new whether it was given as an arrayref or a string.
311 # They are what tell AbuseIPDB what kind of abuse is being reported.
312 #
313 # The comment is optional and is left out entirely when unset or empty, rather
314 # than being sent blank. Every occurrence of the %%%BAN%%% placeholder in it
315 # is replaced with the address, so a configured comment can name what was
316 # blocked.
317 #
318 # One thing worth keeping in mind when setting that comment: it is published
319 # on AbuseIPDB and visible to anyone, so it must not carry hostnames,
320 # usernames, log fragments, or anything else internal.
321 #
322 # Args:
323 #
324 # ip - The address to report, as a plain string. Expected to be an already
325 # validated and lowercased IPv4 or IPv6 address. Percent encoded into
326 # the body, and also substituted into the comment where the
327 # placeholder appears.
328 #
329 # Returns the body as a form urlencoded string, ready to POST to the report
330 # endpoint.
331 #
332 # # with categories 18 and 22 and a comment
333 # $self->_report_body('10.0.0.1');
334 # # ip=10.0.0.1&categories=18%2C22&comment=banned%2010.0.0.1%20by%20fail2ban
335 #
336 # # with no comment configured
337 # $self->_report_body('10.0.0.1');
338 # # ip=10.0.0.1&categories=18%2C22
339 4 ▶sub _report_body {
Subroutine _report_body: called CC=3 SCAR=11.0
340 4 my ( $self, $ip ) = @_;
341  
342 4 my $body = 'ip=' . $self->_uri_escape($ip) . '&categories=' . $self->_uri_escape( $self->{options}{categories} );
343  
344 4 ▶ if ( defined( $self->{options}{comment} ) && $self->{options}{comment} ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"options"}{"comment"} and $self->{"options"}{"comment"} ne "") 3 1 4
Condition66%2/3
defined $self->{"options"}{"comment"} and $self->{"options"}{"comment"} ne ""
!ll&&!rl&&r
013
MC/DC50%1/2
defined $self->{"options"}{"comment"} and $self->{"options"}{"comment"} ne ""
defined $self->{"options"}{"comment"} $self->{"options"}{"comment"} ne ""
Truth table66%2/3
A and B
A= defined $self->{"options"}{"comment"}B= $self->{"options"}{"comment"} ne ""
ABresult
0X0
100
111
345 3 my $comment = $self->{options}{comment};
346 3 $comment =~ s/\%\%\%BAN\%\%\%/$ip/g;
347 3 $body .= '&comment=' . $self->_uri_escape($comment);
348 }
349  
350 4 return $body;
351 } ## end sub _report_body
352  
353 # Internal helper. Performs one HTTP request against the AbuseIPDB API. Every
354 # call this backend makes goes through here.
355 #
356 # What makes this different from the other HTTP helpers in the dist is the
357 # tolerate argument. AbuseIPDB rate limits reports, and a report rejected for
358 # exceeding the daily quota is a normal operating condition rather than a
359 # failure: the ban itself has already been applied by whatever blocking
360 # backend is paired with this one, and failing the ban because the reporting
361 # service was busy would be the wrong call. So the report path tolerates 429
362 # and carries on.
363 #
364 # The user agent is built on first use and cached on the object, so a run of
365 # requests shares one agent. LWP::UserAgent is loaded with require at that
366 # point rather than at compile time, since only the HTTP backends need it;
367 # failing to load it dies with an explanation naming this backend.
368 #
369 # Authentication is the API key in a Key header.
370 #
371 # Any untolerated HTTP failure dies rather than setting an error. The callers
372 # wrap this in eval and turn the exception into the appropriate error code.
373 #
374 # Never called in testing mode; those paths record the request instead.
375 #
376 # Args:
377 #
378 # method - The HTTP method, as a plain string: 'GET' for the check
379 # probe, 'POST' for a report.
380 #
381 # url - The full URL to request, as a plain string, built on
382 # _api_base.
383 #
384 # body - Optional request body, as a form urlencoded string from
385 # _report_body. undef for the check probe.
386 #
387 # tolerate - Optional hashref of HTTP status codes to treat as
388 # non fatal, keyed by the numeric code with any true value,
389 # such as { 429 => 1 }. A response with one of those codes
390 # returns undef instead of dying. Omitted by callers that want
391 # every failure to be fatal.
392 #
393 # Returns the decoded response body on success, or undef when the status was
394 # one of the tolerated ones. Dies on any other non success status.
395 #
396 # # the check probe, where any failure is fatal
397 # $self->_request( 'GET', $self->_check_url );
398 #
399 # # a report, tolerating the rate limit
400 # $self->_request( 'POST', $url, $body, { 429 => 1 } );
401 #
402 # # the usual shape at the call sites
403 # eval { $self->_request( 'GET', $self->_check_url ); 1; } or do { ... };
404 0 ▶sub _request {
Subroutine _request: not called CC=8 SCAR=42.8
405 0 my ( $self, $method, $url, $body, $tolerate ) = @_;
406  
407 0 ▶ if ( !defined( $self->{ua} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"ua"}) 0 0 0
408 0 local $@;
409 0 ▶ eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require LWP::UserAgent; $self->{"ua"} = "LWP::UserAgent"->new("agent", 'Net::Firewall::BlockerHelper/' . $Net::Firewall::BlockerHelper::backends::abuseipdb::VERSION, "timeout", $self->{"options"}{"timeout"}); 1 } } or die 'failed to load LWP::UserAgent, which the abuseipdb backend requires... ' . $@ 0 0 0
410 0 require LWP::UserAgent;
411 $self->{ua} = LWP::UserAgent->new(
412 agent => 'Net::Firewall::BlockerHelper/' . $VERSION,
413 timeout => $self->{options}{timeout},
414 0 );
415 0 1;
416 } or die( 'failed to load LWP::UserAgent, which the abuseipdb backend requires... ' . $@ );
417 }
418  
419 0 my @headers = ( 'Key' => $self->{options}{key}, 'Accept' => 'application/json' );
420 0 ▶ if ( defined($body) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $body) 0 0 0
421 0 push( @headers, 'Content-Type' => 'application/x-www-form-urlencoded' );
422 }
423  
424 0 require HTTP::Request;
425 0 my $request = HTTP::Request->new( $method, $url, \@headers, $body );
426  
427 0 my $response = $self->{ua}->request($request);
428  
429 0 ▶ if ( !$response->is_success ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 0 0 0
430 0 ▶ if ( defined($tolerate) && $tolerate->{ $response->code } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $tolerate and $$tolerate{$response->code}) 0 0 0
Condition0%0/3
defined $tolerate and $$tolerate{$response->code}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $tolerate and $$tolerate{$response->code}
defined $tolerate $$tolerate{$response->code}
Truth table0%0/3
A and B
A= defined $tolerateB= $$tolerate{$response->code}
ABresult
0X0
100
111
431 0 return undef;
432 }
433 0 my $detail = $response->decoded_content;
434 0 ▶ $detail = defined($detail) ? ( ' body... ' . $detail ) : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $detail ? : 0 0 0
435 0 die( $method . ' ' . $url . ' failed... HTTP status... ' . $response->status_line . $detail );
436 }
437  
438 0 return $response->decoded_content;
439 } ## end sub _request
440  
441 =head2 init
442  
443 Initiates the backend. Verifies the API key and reachability via a minimal
444 GET to the v2 C</check> endpoint. Nothing is created remotely; there is no
445 remote state to set up.
446  
447 =cut
448  
449 3 ▶sub init {
Subroutine init: called CC=4 SCAR=20.9
Pod documented
450 3 my ( $self, %opts ) = @_;
451  
452 3 $self->errorblank;
453  
454 3 ▶ if ( $self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"inited"}) 0 3 3
455 0 $self->{error} = 18;
456 0 $self->{errorString} = 'backend has already been inited';
457 0 $self->warn;
458 }
459  
460 3 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 3 0 3
461 3 $self->{frontend_obj}->{test_data} = [ { method => 'GET', url => $self->_check_url } ];
462 } else {
463 0 local $@;
464 0 ▶ eval { $self->_request( 'GET', $self->_check_url ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("GET", $self->_check_url); 1 } } or do { $self->{"error"} = 23; $self->{"errorString"} = 'init failed. probing the check endpoint failed... ' . $@; $self->warn } 0 0 0
465 0 $self->{error} = 23;
466 0 $self->{errorString} = 'init failed. probing the check endpoint failed... ' . $@;
467 0 $self->warn;
468 };
469 }
470  
471 3 $self->{inited} = 1;
472 } ## end sub init
473  
474 =head2 ban
475  
476 Bans the IP by reporting it. The value of ban is validated as being a IPv4 or
477 IPv6 address and lowercased, then reported via a POST to the v2 C</report>
478 endpoint with the configured categories and comment. A HTTP 429, AbuseIPDB's
479 answer to reporting the same IP again inside its rate limit window, is
480 treated as already reported rather than as an error. Banning an already
481 banned IP is a noop.
482  
483 $backend->ban(ban => $ip);
484  
485 =cut
486  
487 4 ▶sub ban {
Subroutine ban: called CC=10 SCAR=36.8
Pod documented
488 4 my ( $self, %opts ) = @_;
489  
490 4 $self->errorblank;
491  
492 4 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 4 4
493 0 $self->{error} = 1;
494 0 $self->{errorString} = 'backend has not been inited';
495 0 $self->warn;
496 0 return;
497 }
498  
499 4 ▶ if ( !defined( $opts{ban} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opts{'ban'}) { } 0 4 4
elsif (ref $opts{'ban'} ne '') { } 0 4 4
elsif (not $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv6_re\z/) { } 0 4 4
500 0 $self->{error} = 9;
501 0 $self->{errorString} = 'Nothing specified for the value ban';
502 0 $self->warn;
503 0 return;
504 } elsif ( ref( $opts{ban} ) ne '' ) {
505 0 $self->{error} = 10;
506 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
507 0 $self->warn;
508 0 return;
509 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition66%2/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv6_re\z/
l!l&&r!l&&!r
310
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv6_re\z/
Truth table66%2/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv6_re\z/
ABresult
1X1
011
000
510 && $opts{ban} !~ /\A$IPv6_re\z/ )
511 {
512 0 $self->{error} = 10;
513 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
514 0 $self->warn;
515 0 return;
516 }
517  
518 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
519 4 $opts{ban} = lc( $opts{ban} );
520  
521 4 ▶ if ( $self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"banned"}{$opts{"ban"}}) 0 4 4
522 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
523 0 $self->{frontend_obj}->{test_data} = 'already banned';
524 }
525 0 return;
526 }
527  
528 4 my $url = $self->_api_base . '/report';
529 4 my $body = $self->_report_body( $opts{ban} );
530  
531 4 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 4 0 4
532 4 $self->{frontend_obj}->{test_data} = [ { method => 'POST', url => $url, content => $body } ];
533 } else {
534 0 local $@;
535 0 ▶ eval { $self->_request( 'POST', $url, $body, { 429 => 1 } ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("POST", $url, $body, {429, 1}); 1 } } or do { $self->{"error"} = 13; $self->{"errorString"} = 'reporting "' . $opts{"ban"} . '" failed... ' . $@; $self->warn; return } 0 0 0
536 0 $self->{error} = 13;
537 0 $self->{errorString} = 'reporting "' . $opts{ban} . '" failed... ' . $@;
538 0 $self->warn;
539 0 return;
540 };
541 }
542  
543 4 $self->{banned}{ $opts{ban} } = 1;
544 } ## end sub ban
545  
546 =head2 unban
547  
548 Unbans the IP. The value of ban is validated as being a IPv4 or IPv6 address
549 and lowercased, then removed from the internal ban list. Reports can not be
550 withdrawn, so no API call is made. Unbanning an IP that is not banned is a
551 noop.
552  
553 $backend->unban(ban => $ip);
554  
555 =cut
556  
557 1 ▶sub unban {
Subroutine unban: called CC=9 SCAR=34.2
Pod documented
558 1 my ( $self, %opts ) = @_;
559  
560 1 $self->errorblank;
561  
562 1 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 1 1
563 0 $self->{error} = 1;
564 0 $self->{errorString} = 'backend has not been inited';
565 0 $self->warn;
566 0 return;
567 }
568  
569 1 ▶ if ( !defined( $opts{ban} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opts{'ban'}) { } 0 1 1
elsif (ref $opts{'ban'} ne '') { } 0 1 1
elsif (not $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv6_re\z/) { } 0 1 1
570 0 $self->{error} = 9;
571 0 $self->{errorString} = 'Nothing specified for the value ban';
572 0 $self->warn;
573 0 return;
574 } elsif ( ref( $opts{ban} ) ne '' ) {
575 0 $self->{error} = 10;
576 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
577 0 $self->warn;
578 0 return;
579 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition33%1/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv6_re\z/
l!l&&r!l&&!r
100
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv6_re\z/
Truth table33%1/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::abuseipdb::IPv6_re\z/
ABresult
1X1
011
000
580 && $opts{ban} !~ /\A$IPv6_re\z/ )
581 {
582 0 $self->{error} = 10;
583 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
584 0 $self->warn;
585 0 return;
586 }
587  
588 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
589 1 $opts{ban} = lc( $opts{ban} );
590  
591 1 ▶ if ( !$self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"banned"}{$opts{"ban"}}) 0 1 1
592 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
593 0 $self->{frontend_obj}->{test_data} = 'not banned';
594 }
595 0 return;
596 }
597  
598 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 1 0 1
599 1 $self->{frontend_obj}->{test_data} = 'unban is internal only';
600 }
601  
602 1 delete( $self->{banned}{ $opts{ban} } );
603 } ## end sub unban
604  
605 =head2 ban_cidr
606  
607 CIDR bans are not supported by this backend; this always sets the
608 cidrNotSupported error.
609  
610 $backend->ban_cidr(ban => '1.2.3.0/24');
611  
612 =cut
613  
614 0 ▶sub ban_cidr {
Subroutine ban_cidr: not called CC=1 SCAR=6.9
Pod documented
615 0 my ( $self, %opts ) = @_;
616  
617 0 $self->errorblank;
618  
619 0 $self->{error} = 35;
620 0 $self->{errorString} = 'the ' . __PACKAGE__ . ' backend does not support CIDR bans';
621 0 $self->warn;
622  
623 0 return;
624 } ## end sub ban_cidr
625  
626 =head2 unban_cidr
627  
628 CIDR bans are not supported by this backend; this always sets the
629 cidrNotSupported error.
630  
631 $backend->unban_cidr(ban => '1.2.3.0/24');
632  
633 =cut
634  
635 0 ▶sub unban_cidr {
Subroutine unban_cidr: not called CC=1 SCAR=6.9
Pod documented
636 0 my ( $self, %opts ) = @_;
637  
638 0 $self->errorblank;
639  
640 0 $self->{error} = 35;
641 0 $self->{errorString} = 'the ' . __PACKAGE__ . ' backend does not support CIDR bans';
642 0 $self->warn;
643  
644 0 return;
645 } ## end sub unban_cidr
646  
647 =head2 list_cidr
648  
649 CIDR bans are not supported by this backend, so this always returns an empty
650 list.
651  
652 my @banned_cidrs = $backend->list_cidr;
653  
654 =cut
655  
656 0 ▶sub list_cidr {
Subroutine list_cidr: not called CC=1 SCAR=6.9
Pod documented
657 0 my ( $self, %opts ) = @_;
658  
659 0 $self->errorblank;
660  
661 0 return ();
662 }
663  
664 =head2 list
665  
666 List banned IPs. Returns an array of the IPs reported since init, from the
667 internal ban list; no API call is made.
668  
669 my @banned = $backend->list;
670  
671 =cut
672  
673 2 ▶sub list {
Subroutine list: called CC=2 SCAR=7.0
Pod documented
674 2 my ( $self, %opts ) = @_;
675  
676 2 $self->errorblank;
677  
678 2 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 2 0 2
679 2 $self->{frontend_obj}->{test_data} = 'list';
680 }
681  
682 2 return keys( %{ $self->{banned} } );
683 }
684  
685 =head2 re_init
686  
687 Tears down and re-inits. Unlike the blocking backends nothing is re-added, as
688 reports are fire and forget and there is no remote state to restore.
689  
690 =cut
691  
692 0 ▶sub re_init {
Subroutine re_init: not called CC=1 SCAR=6.9
Pod documented
693 0 my ( $self, %opts ) = @_;
694  
695 0 $self->errorblank;
696  
697 # teardown is best effort here for parity with the other backends, even
698 # though for this backend it can not fail
699 {
700 0 local $@;
701 0 eval { $self->teardown; };
702 }
703 0 $self->init;
704  
705 0 $self->{inited} = 1;
706 } ## end sub re_init
707  
708 =head2 teardown
709  
710 Tears down the backend. Reports can not be withdrawn, so no API calls are
711 made. The internal list of bans is kept.
712  
713 $backend->teardown;
714  
715 =cut
716  
717 0 ▶sub teardown {
Subroutine teardown: not called CC=2 SCAR=17.9
Pod documented
718 0 my ( $self, %opts ) = @_;
719  
720 0 $self->errorblank;
721  
722 0 $self->{inited} = 0;
723  
724 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
725 0 $self->{frontend_obj}->{test_data} = 'teardown is internal only';
726 }
727 } ## end sub teardown
728  
729 =head2 stop
730  
731 Alias for L</teardown>, provided for parity with the fail2ban C<actionstop>
732 concept.
733  
734 $backend->stop;
735  
736 =cut
737  
738 0 ▶sub stop {
Subroutine stop: not called CC=1 SCAR=6.9
Pod documented
739 0 my ( $self, %opts ) = @_;
740  
741 0 return $self->teardown(%opts);
742 }
743  
744 =head2 check
745  
746 Verifies the API key and reachability are still usable via a minimal GET to
747 the v2 C</check> endpoint. Returns a true value if so and a false value
748 otherwise. This is the
749 equivalent of fail2ban's C<actioncheck>.
750  
751 if ( !$backend->check ) {
752 $backend->re_init;
753 }
754  
755 =cut
756  
757 5 ▶sub check {
Subroutine check: called CC=3 SCAR=15.4
Pod documented
758 5 my ( $self, %opts ) = @_;
759  
760 5 $self->errorblank;
761  
762 5 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 5 0 5
763 5 $self->{frontend_obj}->{test_data} = [ { method => 'GET', url => $self->_check_url } ];
764 5 return 1;
765 }
766  
767 0 local $@;
768 0 ▶ eval { $self->_request( 'GET', $self->_check_url ); 1; } or return 0;
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("GET", $self->_check_url); 1 } } or return 0 0 0 0
769  
770 0 return 1;
771 } ## end sub check
772  
773 =head2 flush
774  
775 Removes all currently banned IPs at once by forgetting them. Reports can not
776 be withdrawn, so no API calls are made. This is the equivalent of fail2ban's
777 C<actionflush>.
778  
779 $backend->flush;
780  
781 =cut
782  
783 1 ▶sub flush {
Subroutine flush: called CC=3 SCAR=13.1
Pod documented
784 1 my ( $self, %opts ) = @_;
785  
786 1 $self->errorblank;
787  
788 1 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 1 1
789 0 $self->{error} = 1;
790 0 $self->{errorString} = 'backend has not been inited';
791 0 $self->warn;
792 0 return;
793 }
794  
795 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 1 0 1
796 1 $self->{frontend_obj}->{test_data} = 'flush is internal only';
797 }
798  
799 1 $self->{banned} = {};
800 } ## end sub flush
801  
802 =head1 ERROR CODES / FLAGS
803  
804 Error handling is provided by L<Error::Helper>. All
805 errors are considered fatal.
806  
807 =head2 1, notInited
808  
809 The backend has not been inited yet.
810  
811 =head2 6, invalidPrefixSpecified
812  
813 The specified prefix did not match /^[a-zA-Z0-9]+$/.
814  
815 =head2 7, invalidName
816  
817 The name is either undef or does not match /^[a-zA-Z0-9\-]+$/.
818  
819 =head2 8, optionsNotHash
820  
821 The item passed to new for options is not a hash.
822  
823 =head2 9, noBanItem
824  
825 No IP specified to ban or unban.
826  
827 =head2 10, banItemNotIP
828  
829 The item to ban is not an IP. Either wrong ref type or regexp
830 test using L<Regexp::IPv4> and L<Regexp::IPv6> failed.
831  
832 =head2 12, backendInitError
833  
834 Failed to init the backend.
835  
836 =head2 13, banFailed
837  
838 Failed to ban the item.
839  
840 =head2 14, unbanFailed
841  
842 Failed to unban the item.
843  
844 =head2 15, listFailed
845  
846 Failed to get a list of bans.
847  
848 =head2 16, reInitFailed
849  
850 Failed to re_init the backend.
851  
852 =head2 17, teardownFailed
853  
854 Failed to teardown the backend.
855  
856 =head2 18, alreadyInited
857  
858 init called, but the backend has already been inited.
859  
860 =head2 23, initFailed
861  
862 init failed. Probing the check endpoint failed.
863  
864 =head2 24, checkFailed
865  
866 The backend check raised an error.
867  
868 =head2 25, flushFailed
869  
870 Failed to flush the bans.
871  
872 =head2 26, portsNotSupported
873  
874 The abuseipdb backend reports whole IPs and does not support ports.
875  
876 =head2 27, protocolsNotSupported
877  
878 The abuseipdb backend reports whole IPs and does not support protocols.
879  
880 =head2 30, keyNotDefined
881  
882 The option key is undef or blank.
883  
884 =head2 31, categoriesInvalid
885  
886 The option categories is not an array ref of positive ints or a comma
887 separated string of positive ints.
888  
889 =head2 32, banCidrFailed
890  
891 Failed to ban the CIDR range.
892  
893 =head2 33, unbanCidrFailed
894  
895 Failed to unban the CIDR range.
896  
897 =head2 34, cidrItemNotCidr
898  
899 The item to ban is not a CIDR range. Either wrong ref type or it is not an
900 IPv4 or IPv6 address followed by a prefix length valid for its family.
901  
902 =head2 35, cidrNotSupported
903  
904 The backend does not support CIDR bans.
905  
906 =head2 36, listCidrFailed
907  
908 Failed to get a list of CIDR bans.
909  
910 =head1 AUTHOR
911  
912 Zane C. Bowers-Hadley, C<< <vvelox at vvelox.ent> >>
913  
914 =head1 LICENSE AND COPYRIGHT
915  
916 This software is Copyright (c) 2023 by Zane C. Bowers-Hadley.
917  
918 This is free software, licensed under:
919  
920 The GNU Lesser General Public License, Version 2.1, February 1999
921  
922 =cut
923  
924 1 1; # End of Net::Firewall::BlockerHelper::backends::abuseipdb
« BlockerHelper/backends/vyos.pm ↑ Summary BlockerHelper/backends/bgp_rtbh.pm »