AbuseIPDB.pm

filter: Statementstmt 99.0% 101 / 102 Branchbran 97.3% 37 / 38 Conditioncond 100% 9 / 9 MC/DCmcdc 100% 5 / 5 Subroutinesub 100% 13 / 13 Podpod 100% 4 / 4 totaltotal 98.8% 169 / 171 SCAR 32.2
CC
25
Cov
99%
blacklist
8.0
_send_receive
7.0
new
7.0
CRAP 25.0
↑ Summary AbuseIPDB/Category.pm »
1 package WebService::AbuseIPDB;
2  
3 7 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 7 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 7 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 # use other modules
8 7 ▶use IO::Socket::SSL;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 7 ▶use REST::Client;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 7 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 7 ▶use JSON::XS;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 7 ▶use URI; # The GET requests need URI-escaping
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 7 our $VERSION = '0.03';
15  
16 sub new {
17 7 ▶ my ($class, %opts) = @_;
Subroutine new: called CC=7 SCAR=19.5
Pod documented
18 croak "Only version 2 is supported."
19 7 ▶ if exists $opts{ver} && 2 != $opts{ver};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"ver"} and 2 != $opts{"ver"} 1 6 7
Condition100%3/3
exists $opts{"ver"} and 2 != $opts{"ver"}
!ll&&!rl&&r
511
MC/DC100%2/2
exists $opts{"ver"} and 2 != $opts{"ver"}
exists $opts{"ver"} 2 != $opts{"ver"}
Truth table100%3/3
A and B
A= exists $opts{"ver"}B= 2 != $opts{"ver"}
ABresult
0X0
100
111
20 6 ▶ croak "No key provided." unless exists $opts{key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $opts{"key"} 1 5 6
21  
22 # This is weird. If you don't set the outer timeout it goes to 300.
23 # If you do set the outer timeout, it sets the inner one too so it's
24 # effectively doubled. Setting the inner timeout has no effect.
25 my $self = {
26 ua => REST::Client->new (
27 { host => 'https://api.abuseipdb.com',
28 timeout => $opts{timeout} // 20,
29 agent => "WebService::AbuseIPDB/$VERSION",
30  
31 # useragent => LWP::UserAgent->new (ssl_opts => {
32 # verify_hostname => 1,
33 # },
34 # #timeout => $opts{timeout} // 20,
35 # )
36 }
37 ),
38 retry => $opts{retry} // 0,
39 api_ver => $opts{ver} // 2,
40 key => $opts{key},
41 5 ▶ };
Condition100%6/6
$opts{"timeout"} // 20
l!l
14
$opts{"retry"} // 0
l!l
14
$opts{"ver"} // 2
l!l
14
MC/DC100%1/1
$opts{"timeout"} // 20
$opts{"timeout"}
MC/DC100%1/1
$opts{"retry"} // 0
$opts{"retry"}
MC/DC100%1/1
$opts{"ver"} // 2
$opts{"ver"}
Truth table100%2/2
A
A= $opts{"timeout"}
Aresult
11
00
Truth table100%2/2
A
A= $opts{"retry"}
Aresult
11
00
Truth table100%2/2
A
A= $opts{"ver"}
Aresult
11
00
42 5 bless ($self, $class);
43 5 return $self;
44 }
45  
46 sub _send_receive {
47 9 ▶ my ($self, $meth, $path, $data) = @_;
Subroutine _send_receive: called CC=7 SCAR=19.5
48  
49 9 $path = "/api/v$self->{api_ver}/$path";
50 9 my $ct = {'Content-type' => 'application/json'};
51 my $headers = {
52 Accept => 'application/json',
53 Key => $self->{key}
54 9 };
55 9 ▶ if ($meth eq 'GET') {
Branch: 1 branch
BranchTrueFalseTotal
if ($meth eq "GET") 5 4 9
56 5 my $u = URI->new ($path);
57 5 $u->query_form (%$data);
58 5 $path = $u->as_string;
59 }
60 9 my $tries_left = $self->{retry} + 1;
61 9 ▶ while ($tries_left) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tries_left) 13 2 15
62  
63 13 ▶ if ($meth eq 'GET') {
Branch: 2 branches
BranchTrueFalseTotal
if ($meth eq 'GET') { } 9 4 13
elsif ($meth eq 'POST') { } 3 1 4
64 9 $self->{ua}->GET ($path, $headers);
65 } elsif ($meth eq 'POST') {
66 3 $headers->{'Content-type'} = 'application/json';
67 3 $self->{ua}->POST ($path, encode_json ($data), $headers);
68 } else {
69 1 croak "Unrecognised method '$meth'";
70 }
71  
72 12 ▶ if ($self->{ua}->responseCode !~ /[45]00/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"ua"}->responseCode =~ /[45]00/) 6 6 12
73 return decode_json $self->{ua}->responseContent
74 6 ▶ if $self->{ua}->responseHeader ('Content-type') eq
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"ua"}->responseHeader("Content-type") eq "application/json" 6 0 6
75 'application/json';
76 0 return undef;
77 }
78 6 $tries_left--;
79 6 carp "REST error " . $self->{ua}->responseCode;
80 }
81  
82 2 carp "Problem with $meth $path";
83 2 carp "Data was " . encode_json ($data);
84 2 carp "Client warning: ", $self->{ua}->responseHeader ('Client-Warning');
85 2 return undef;
86 }
87  
88 sub check {
89 4 ▶ my ($self, %args) = @_;
Subroutine check: called CC=3 SCAR=11.0
Pod documented
90 4 ▶ unless (exists $args{ip}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $args{"ip"}) 1 3 4
91 1 carp "No IP in argument hash";
92 1 return;
93 }
94  
95 # Validate this here TODO
96 3 my $data = {ipAddress => $args{ip}};
97 3 ▶ $data->{maxAgeInDays} = $args{max_age} if exists $args{max_age};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"max_age"} 1 2 3
98 # TODO $data->{verbose} = 1 if $args{verbose};
99 3 require WebService::AbuseIPDB::CheckResponse;
100 3 return WebService::AbuseIPDB::CheckResponse->new (
101 $self->_send_receive ('GET', 'check', $data));
102  
103 }
104  
105 sub report {
106 5 ▶ my ($self, %args) = @_;
Subroutine report: called CC=4 SCAR=13.9
Pod documented
107 5 for my $mand (qw/ip categories/) {
108 9 ▶ unless (exists $args{$mand}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $args{$mand}) 2 7 9
109 2 carp "No '$mand' key in argument hash";
110 2 return;
111 }
112 }
113  
114 # More validation here
115 3 my $data = {ip => $args{ip}};
116  
117 # Form the category string
118 # More validation here too
119 3 require WebService::AbuseIPDB::Category;
120 my @categories =
121 3 map { WebService::AbuseIPDB::Category->new ($_) } @{$args{categories}};
122 3 $data->{categories} = join (',', map { $_->id } @categories);
123  
124 # Trim the comment
125 $data->{comment} = substr ($args{comment}, 0, 1024)
126 3 ▶ if defined $args{comment};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"comment"} 1 2 3
127  
128 # Run it
129 3 require WebService::AbuseIPDB::ReportResponse;
130 3 return WebService::AbuseIPDB::ReportResponse->new (
131 $self->_send_receive ('POST', 'report', $data));
132 }
133  
134 sub blacklist {
135 7 ▶ my ($self, %args) = @_;
Subroutine blacklist: called CC=8 SCAR=20.8
Pod documented
136 7 my $data = {
137 limit => 1000,
138 confidenceMinimum => 75
139 };
140  
141 7 ▶ if (exists $args{limit}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args{"limit"}) 4 3 7
142 4 ▶ unless ($args{limit} =~ /^[0-9]+$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"limit"} =~ /^[0-9]+$/) 1 3 4
143 1 carp "limit must be a whole number";
144 1 return;
145 }
146 3 ▶ if ($args{limit} < 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"limit"} < 1) 1 2 3
147 1 carp "limit must be greater than zero";
148 1 return;
149 }
150 2 $data->{limit} = $args{limit};
151 }
152  
153 5 ▶ if (exists $args{min_abuse}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args{"min_abuse"}) 4 1 5
154 4 ▶ unless ($args{min_abuse} =~ /^[0-9]+$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"min_abuse"} =~ /^[0-9]+$/) 1 3 4
155 1 carp "min_abuse must be a whole number";
156 1 return;
157 }
158 3 ▶ if ($args{min_abuse} < 25) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"min_abuse"} < 25) 1 2 3
159 1 carp "min_abuse is $args{min_abuse} but must be greater than 24";
160 1 return;
161 }
162 2 ▶ if ($args{min_abuse} > 100) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"min_abuse"} > 100) 1 1 2
163 1 carp "min_abuse is $args{min_abuse} but must be less than 100";
164 1 return;
165 }
166 1 $data->{confidenceMinimum} = $args{min_abuse};
167 }
168  
169 2 require WebService::AbuseIPDB::BlacklistResponse;
170 2 require WebService::AbuseIPDB::BlacklistMember;
171 2 return WebService::AbuseIPDB::BlacklistResponse->new (
172 $self->_send_receive ('GET', 'blacklist', $data));
173  
174 }
175  
176 7 1;
177  
178 __END__
179  
180 =pod
181  
182 =encoding utf8
183  
184  
185 =head1 NAME
186  
187 WebService::AbuseIPDB - Client for the API (version 2) of AbuseIPDB
188  
189 =head1 SYNOPSIS
190  
191 use WebService::AbuseIPDB;
192  
193 my $ipdb = WebService::AbuseIPDB->new (key => 'abc123...');
194 my $res = $ipdb->check (ip => '127.0.0.2');
195 die unless defined $res;
196 printf "There is a %i%% chance this address is up to no good.\n",
197 $res->score;
198  
199 =head1 DESCRIPTION
200  
201 L<https://www.abuseipdb.com/|AbuseIPDB> maintains a database of reports
202 of bad actors on the net. Users may interface with the database through
203 a web browser using forms on their site. An alternative is to use their
204 API. Version 1 of this API is to be retired in 2020. This module serves
205 as a client for Version 2 of the API.
206  
207 =head1 SUBROUTINES/METHODS
208  
209 =head2 new
210  
211 my $ipdb = WebService::AbuseIPDB->new (%opts);
212  
213 The constructor takes a hash of configuration details.
214  
215 =over
216  
217 =item ver
218  
219 The API version - always set this as "2" to avoid potential problems
220 with mismatched versions.
221  
222 =item key
223  
224 Your key for the API as a scalar string. You must obtain one before
225 using this module.
226  
227 =item timeout
228  
229 The timeout in seconds to wait for the server to respond. Defaults to
230 20.
231  
232 =item retry
233  
234 The number of times to retry on timeout or network error. Defaults to 0
235 (ie. no retries).
236  
237 =back
238  
239 =head2 check
240  
241 my $res = $ipdb->check (ip => '127.0.0.2', max_age => 90);
242  
243 This uses the C<check> endpoint and returns a
244 L<WebService::AbuseIPDB::CheckResponse> object to access the data held
245 in the database for the provided IP address. The argument is a hash with
246 these keys:
247  
248 =over
249  
250 =item ip
251  
252 The IP address to be checked. This item is mandatory.
253  
254 =item max_age
255  
256 The age in integral days of the oldest report(s) to include. If
257 omitted the server default is used (currently 30).
258  
259 =item verbose
260  
261 If set to any true value, the data from each report itself is also returned.
262 B<Not yet impelemented>.
263  
264 =back
265  
266 =head2 report
267  
268 my $res = $ipdb->report (
269 ip => '127.0.0.2',
270 categories => [3, 4],
271 comment => 'This address is the worst'
272 );
273  
274 This uses the C<report> endpoint to report an abusive address. It takes a
275 single hash as the only argument with these elements:
276  
277 =over 4
278  
279 =item ip
280  
281 The IP address to report. Must be a single, valid IPv4 or IPv6 address.
282 This element is mandatory.
283  
284 =item categories
285  
286 An arrayref of categories as either scalar IDs or scalar names or
287 L<WebService::AbuseIPDB::Category> objects.
288 This element is mandatory.
289  
290 =item comment
291  
292 A scalar string with details of the offence. This is optional but
293 recommended in most cases. It must be no more than 1024 characters.
294 and should be decoded.
295  
296 =back
297  
298 The method will return undef on client error and a
299 WebService::AbuseIPDB::ReportResponse object otherwise.
300  
301 =head2 blacklist
302  
303 my $res = $ipdb->blacklist (
304 min_abuse => 90,
305 limit => 1000
306 );
307 print "As at " . $res->as_at . "\n";
308 for my $bad ($res->list) {
309 printf "Address %s has score %i%%\n", $bad->ip, $bad->score;
310 }
311  
312 This uses the C<blacklist> endpoint to retrieve a list of abusive
313 addresses. It takes a single hash as the only argument with these
314 elements:
315  
316 =over 4
317  
318 =item min_abuse
319  
320 Only include addresses with an abuse confidence score of this level or
321 higher. Minimum is 25, maximum is 100 and default is 75.
322  
323 =item limit
324  
325 An integer giving the maximum quantity of addresses to return. Minimum
326 is 1, maximum is 10,000 for non-subscribers and default is 1000.
327  
328 =back
329  
330 The method will return undef on client error and a
331 WebService::AbuseIPDB::BlacklistResponse object otherwise.
332  
333  
334 =head1 STABILITY
335  
336 This is currently alpha software. Be aware that both the internals and
337 the interface are liable to change.
338  
339 =head1 TODO
340  
341 Implement the C<verbose> option on the check method.
342  
343 Add the other API endpoints: check-block and bulk-report. Allow for fast
344 blacklist-as-string response too.
345  
346 More validation/sanitation of inputs.
347  
348 Consider using objects for errors instead of AoH.
349  
350 =head1 SEE ALSO
351  
352 L<SendMail::AbuseIPDB> is a client for v1 of the API.
353  
354 Full documentation for the API is at L<https://docs.abuseipdb.com/>.
355  
356 =head1 AUTHOR
357  
358 Pete Houston, C<< <cpan at openstrike.co.uk> >>
359  
360 =head1 BUGS
361  
362 Please report any bugs or feature requests to C<bug-webservice-abuseipdb at rt.cpan.org>, or through
363 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=WebService-AbuseIPDB>. See the file CONTRIBUTING.md for further details.
364  
365 =head1 ACKNOWLEDGEMENTS
366  
367 Thanks to AbuseIPDB for making the database publicly available via this
368 API.
369  
370 =head1 LICENCE AND COPYRIGHT
371  
372 Copyright © 2020 Pete Houston.
373  
374 This program is free software; you can redistribute it and/or modify
375 it under the terms of the GNU General Public License as published by
376 the Free Software Foundation; version 2 dated June, 1991 or at your option
377 any later version.
378  
379 This program is distributed in the hope that it will be useful,
380 but WITHOUT ANY WARRANTY; without even the implied warranty of
381 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
382 GNU General Public License for more details.
383  
384 A copy of the GNU General Public License is available in the source tree;
385 if not, write to the Free Software Foundation, Inc.,
386 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
387  
388 =cut
↑ Summary AbuseIPDB/Category.pm »