BlockerHelper/backends/cloudflare.pm

filter: Statementstmt 43.8% 192 / 438 Branchbran 39.4% 75 / 190 Conditioncond 45.8% 33 / 72 MC/DCmcdc 9.7% 4 / 41 Subroutinesub 88.8% 24 / 27 Podpod 100% 13 / 13 totaltotal 43.6% 341 / 781 CC 125 SCAR 38.9
CC
125
Cov
43%
_request
132.0
unban_cidr
76.6
new
74.0
CRAP 48.8
« BlockerHelper/backends/fastly.pm ↑ Summary BlockerHelper/backends/checkpoint.pm »
1 package Net::Firewall::BlockerHelper::backends::cloudflare;
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 'Error::Helper';
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::cloudflare - Cloudflare IP access rules backend for Net::Firewall::BlockerHelper.
13  
14 =head1 VERSION
15  
16 Version 0.1.0
17  
18 =cut
19  
20 1 our $VERSION = '0.1.0';
21  
22 =head1 SYNOPSIS
23  
24 use Net::Firewall::BlockerHelper;
25  
26 my $fw_helper = Net::Firewall::BlockerHelper->new(
27 backend => 'cloudflare',
28 name => 'ssh',
29 options => {
30 token => $cf_api_token,
31 zone => $cf_zone_id,
32 },
33 );
34  
35 $fw_helper->init_backend;
36 $fw_helper->ban(ban => '1.2.3.4');
37 $fw_helper->unban(ban => '1.2.3.4');
38  
39 =head1 DESCRIPTION
40  
41 Blocks IPs remotely via the Cloudflare v4 API using IP access rules,
42 equivalent to the fail2ban cloudflare and cloudflare-token actions, but
43 using L<LWP::UserAgent> rather than curl.
44  
45 Auth is via either a API token (preferred, the C<token> option) or the
46 legacy email plus global API key (the C<email> and C<key> options). If the
47 C<zone> option is set the rules are managed zone level, otherwise user
48 level.
49  
50 Blocking is per IP; ports and protocols are not supported and specifying
51 them is an error.
52  
53 L<LWP::UserAgent> is only loaded at run time, so it is only required if
54 this backend is actually used. For https, L<LWP::Protocol::https> must be
55 present as well.
56  
57 =head1 NOTES
58  
59 This backend was written going off the API docs and actual testing is
60 needed to double check a few things as the exact behavior is not clear.
61  
62 teardown currently only removes the single IP access rules, leaving CIDR
63 bans in place remotely, while flush removes both. A re_init after a
64 teardown will re-add the CIDR bans, and how the API handles creating a
65 rule that already exists needs checking.
66  
67 =head1 METHODS
68  
69 =head2 new
70  
71 Initiates the the object.
72  
73 - options :: Backend specific options. See below.
74 - Default :: {}
75  
76 - prefix :: Prefix to use. Must match the regex /^[a-zA-Z0-9]+$/
77 - default :: kur
78  
79 - name :: Name of this specific instance. This must be specified.
80 - default :: undef
81  
82 Ports and protocols are not supported by this backend and specifying either
83 is an error.
84  
85 The options hash accepts the following. Either token or both email and key
86 must be specified.
87  
88 - token :: Cloudflare API token, used as a bearer token. Ideally
89 restricted to just the needed permissions.
90 - Default :: undef
91  
92 - email :: Account email for legacy global API key auth.
93 - Default :: undef
94  
95 - key :: Legacy global API key.
96 - Default :: undef
97  
98 - zone :: Zone ID to manage the rules under. If not set, the rules are
99 managed at the user level.
100 - Default :: undef
101  
102 - mode :: What Cloudflare should do with matching requests. One of
103 'block', 'challenge', 'js_challenge', or 'managed_challenge'.
104 - Default :: block
105  
106 - notes :: Note attached to created rules, also used to find them again
107 for removal.
108 - Default :: <prefix>_<name>
109  
110 - timeout :: HTTP timeout in seconds.
111 - Default :: 30
112  
113 All errors are considered fatal, meaning if new fails it will die.
114  
115 =cut
116  
117 sub new {
118 5 ▶ my ( $blank, %opts ) = @_;
Subroutine new: called CC=31 SCAR=43.0
Pod documented
119  
120 5 my $self = {
121 perror => undef,
122 error => undef,
123 errorLine => undef,
124 errorFilename => undef,
125 errorString => "",
126 errorExtra => {
127 all_errors_fatal => 1,
128 # all_fatal is what Error::Helper 2.1.0 actually checks; all_errors_fatal
129 # is kept for the name documented in its POD
130 all_fatal => 1,
131 flags => {
132 1 => 'notInited',
133 6 => 'invalidPrefixSpecified',
134 7 => 'invalidName',
135 8 => 'optionsNotHash',
136 9 => 'noBanItem',
137 10 => 'banItemNotIP',
138 12 => 'backendInitError',
139 13 => 'banFailed',
140 14 => 'unbanFailed',
141 15 => 'listFailed',
142 16 => 'reInitFailed',
143 17 => 'teardownFailed',
144 18 => 'alreadyInited',
145 20 => 'modeInvalid',
146 23 => 'initFailed',
147 24 => 'checkFailed',
148 25 => 'flushFailed',
149 26 => 'portsNotSupported',
150 27 => 'protocolsNotSupported',
151 28 => 'optionInvalid',
152 29 => 'banCidrFailed',
153 30 => 'unbanCidrFailed',
154 31 => 'cidrItemNotCidr',
155 32 => 'cidrNotSupported',
156 33 => 'listCidrFailed',
157 },
158 fatal_flags => {},
159 perror_not_fatal => 0,
160 },
161 options => {},
162 ports => [],
163 protocols => [],
164 testing => undef,
165 test_data => undef,
166 prefix => 'kur',
167 frontend_obj => undef,
168 inited => 0,
169 banned => {},
170 banned_cidr => {},
171 cidr_supported => 1,
172 ua => undef,
173 };
174 5 bless $self;
175  
176 # blocking is per IP; the API has no concept of ports or protocols
177 5 ▶ 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 4 5
Condition83%5/6
defined $opts{"ports"} and ref $opts{"ports"} eq "ARRAY" and defined $opts{"ports"}[0]
!ll&&!rl&&r
221
defined $opts{"ports"} and ref $opts{"ports"} eq "ARRAY"
!ll&&!rl&&r
203
MC/DC66%2/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 table75%3/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
178 1 $self->{perror} = 1;
179 1 $self->{error} = 26;
180 1 $self->{errorString} = 'the cloudflare backend blocks whole IPs and does not support ports';
181 1 $self->warn;
182 }
183 4 ▶ 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 4 4
Condition66%4/6
defined $opts{"protocols"} and ref $opts{"protocols"} eq "ARRAY" and defined $opts{"protocols"}[0]
!ll&&!rl&&r
220
defined $opts{"protocols"} and ref $opts{"protocols"} eq "ARRAY"
!ll&&!rl&&r
202
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 table50%2/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
184 0 $self->{perror} = 1;
185 0 $self->{error} = 27;
186 0 $self->{errorString} = 'the cloudflare backend blocks whole IPs and does not support protocols';
187 0 $self->warn;
188 }
189  
190 # make sure prefix is sane if defiend
191 4 ▶ 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 4 4
elsif (defined $opts{'prefix'}) { } 2 2 4
Condition66%2/3
defined $opts{"prefix"} and not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
!ll&&!rl&&r
220
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 table66%2/3
A and not(B)
A= defined $opts{"prefix"}B= not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
ABresult
0X0
100
111
192 0 $self->{perror} = 1;
193 0 $self->{error} = 6;
194 $self->{errorString}
195 0 = '"' . $opts{prefix} . '" is not a valid prefix as it does not match the regex /^[a-zA-Z0-9]+$/';
196 0 $self->warn;
197 } elsif ( defined( $opts{prefix} ) ) {
198 2 $self->{prefix} = $opts{prefix};
199 }
200  
201 # make sure we have a name and that it is valid
202 4 ▶ if ( !defined( $opts{name} ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $opts{'name'}) { } 0 4 4
elsif (not $opts{'name'} =~ /^[a-zA-Z0-9\-]+$/) { } 0 4 4
203 0 $self->{perror} = 1;
204 0 $self->{error} = 7;
205 0 $self->{errorString} = 'name is undef';
206 0 $self->warn;
207 } elsif ( $opts{name} !~ /^[a-zA-Z0-9\-]+$/ ) {
208 0 $self->{perror} = 1;
209 0 $self->{error} = 7;
210 0 $self->{errorString} = 'name set to "' . $opts{name} . '" which does not match the regexp /^[a-zA-Z0-9\-]+$/';
211 0 $self->warn;
212 }
213 4 $self->{name} = $opts{name};
214  
215 # used internally for testing
216 4 ▶ if ( defined( $opts{testing} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"testing"}) 2 2 4
217 2 $self->{testing} = $opts{testing};
218 }
219 4 ▶ if ( defined( $opts{frontend_obj} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"frontend_obj"}) 2 2 4
220 2 $self->{frontend_obj} = $opts{frontend_obj};
221 }
222  
223 4 ▶ if ( defined( $opts{options} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"options"}) 3 1 4
224 3 ▶ if ( ref( $opts{options} ) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $opts{"options"} ne "HASH") 0 3 3
225 0 $self->{perror} = 1;
226 0 $self->{error} = 8;
227 0 $self->{errorString} = 'ref for options is "' . ref( $opts{options} ) . '" and not HASH';
228 0 $self->warn;
229 }
230 3 $self->{options} = $opts{options};
231 }
232  
233 # needs a token, or a email + key for legacy auth
234 4 ▶ if ( !defined( $self->{options}{token} )
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"options"}{"token"} or defined $self->{"options"}{"email"} and defined $self->{"options"}{"key"}) 1 3 4
Condition83%5/6
defined $self->{"options"}{"token"} or defined $self->{"options"}{"email"} and defined $self->{"options"}{"key"}
l!l&&r!l&&!r
211
defined $self->{"options"}{"email"} and defined $self->{"options"}{"key"}
!ll&&!rl&&r
101
MC/DC0%0/3
defined $self->{"options"}{"token"} or defined $self->{"options"}{"email"} and defined $self->{"options"}{"key"}
defined $self->{"options"}{"token"} defined $self->{"options"}{"email"} defined $self->{"options"}{"key"}
Truth table50%2/4
A or B and C
A= defined $self->{"options"}{"token"}B= defined $self->{"options"}{"email"}C= defined $self->{"options"}{"key"}
ABCresult
1XX1
0111
00X0
0100
235 && ( !defined( $self->{options}{email} ) || !defined( $self->{options}{key} ) ) )
236 {
237 1 $self->{perror} = 1;
238 1 $self->{error} = 28;
239 $self->{errorString}
240 1 = 'either the option token, or both the options email and key, must be specified for auth';
241 1 $self->warn;
242 }
243  
244 3 ▶ if ( defined( $self->{options}{zone} ) && $self->{options}{zone} !~ /^[a-fA-F0-9]+$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"options"}{"zone"} and not $self->{"options"}{"zone"} =~ /^[a-fA-F0-9]+$/) 0 3 3
Condition66%2/3
defined $self->{"options"}{"zone"} and not $self->{"options"}{"zone"} =~ /^[a-fA-F0-9]+$/
!ll&&!rl&&r
210
MC/DC0%0/2
defined $self->{"options"}{"zone"} and not $self->{"options"}{"zone"} =~ /^[a-fA-F0-9]+$/
defined $self->{"options"}{"zone"} not $self->{"options"}{"zone"} =~ /^[a-fA-F0-9]+$/
Truth table66%2/3
A and not(B)
A= defined $self->{"options"}{"zone"}B= not $self->{"options"}{"zone"} =~ /^[a-fA-F0-9]+$/
ABresult
0X0
100
111
245 0 $self->{perror} = 1;
246 0 $self->{error} = 28;
247 0 $self->{errorString} = 'the option zone, "' . $self->{options}{zone} . '", does not look like a zone ID';
248 0 $self->warn;
249 }
250  
251 3 ▶ if ( defined( $self->{options}{mode} )
Branch: 2 branches
BranchTrueFalseTotal
if (defined $self->{'options'}{'mode'} and $self->{'options'}{'mode'} ne 'block' and $self->{'options'}{'mode'} ne 'challenge' and $self->{'options'}{'mode'} ne 'js_challenge' and $self->{'options'}{'mode'} ne 'managed_challenge') { } 1 2 3
elsif (not defined $self->{'options'}{'mode'}) { } 1 1 2
Condition75%9/12
defined $self->{"options"}{"mode"} and $self->{"options"}{"mode"} ne "block" and $self->{"options"}{"mode"} ne "challenge" and $self->{"options"}{"mode"} ne "js_challenge" and $self->{"options"}{"mode"} ne "managed_challenge"
!ll&&!rl&&r
201
defined $self->{"options"}{"mode"} and $self->{"options"}{"mode"} ne "block" and $self->{"options"}{"mode"} ne "challenge" and $self->{"options"}{"mode"} ne "js_challenge"
!ll&&!rl&&r
201
defined $self->{"options"}{"mode"} and $self->{"options"}{"mode"} ne "block" and $self->{"options"}{"mode"} ne "challenge"
!ll&&!rl&&r
111
defined $self->{"options"}{"mode"} and $self->{"options"}{"mode"} ne "block"
!ll&&!rl&&r
102
MC/DC40%2/5
defined $self->{"options"}{"mode"} and $self->{"options"}{"mode"} ne "block" and $self->{"options"}{"mode"} ne "challenge" and $self->{"options"}{"mode"} ne "js_challenge" and $self->{"options"}{"mode"} ne "managed_challenge"
defined $self->{"options"}{"mode"} $self->{"options"}{"mode"} ne "block" $self->{"options"}{"mode"} ne "challenge" $self->{"options"}{"mode"} ne "js_challenge" $self->{"options"}{"mode"} ne "managed_challenge"
Truth table50%3/6
A and B and C and D and E
A= defined $self->{"options"}{"mode"}B= $self->{"options"}{"mode"} ne "block"C= $self->{"options"}{"mode"} ne "challenge"D= $self->{"options"}{"mode"} ne "js_challenge"E= $self->{"options"}{"mode"} ne "managed_challenge"
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
252 && $self->{options}{mode} ne 'block'
253 && $self->{options}{mode} ne 'challenge'
254 && $self->{options}{mode} ne 'js_challenge'
255 && $self->{options}{mode} ne 'managed_challenge' )
256 {
257 1 $self->{perror} = 1;
258 1 $self->{error} = 20;
259 $self->{errorString}
260 = '$opts{options}{mode} is "'
261 . $self->{options}{mode}
262 1 . '" and not "block", "challenge", "js_challenge", or "managed_challenge"';
263 1 $self->warn;
264 } elsif ( !defined( $self->{options}{mode} ) ) {
265 1 $self->{options}{mode} = 'block';
266 }
267  
268 2 ▶ if ( !defined( $self->{options}{notes} ) && defined( $self->{name} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{"options"}{"notes"} and defined $self->{"name"}) 2 0 2
Condition33%1/3
not defined $self->{"options"}{"notes"} and defined $self->{"name"}
!ll&&!rl&&r
002
MC/DC0%0/2
not defined $self->{"options"}{"notes"} and defined $self->{"name"}
not defined $self->{"options"}{"notes"} defined $self->{"name"}
Truth table33%1/3
not(A) and B
A= not defined $self->{"options"}{"notes"}B= defined $self->{"name"}
ABresult
0X0
100
111
269 2 $self->{options}{notes} = $self->{prefix} . '_' . $self->{name};
270 }
271  
272 2 ▶ if ( !defined( $self->{options}{timeout} ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $self->{'options'}{'timeout'}) { } 2 0 2
elsif (not $self->{'options'}{'timeout'} =~ /^[0-9]+$/) { } 0 0 0
273 2 $self->{options}{timeout} = 30;
274 } elsif ( $self->{options}{timeout} !~ /^[0-9]+$/ ) {
275 0 $self->{perror} = 1;
276 0 $self->{error} = 28;
277 0 $self->{errorString} = 'the option timeout, "' . $self->{options}{timeout} . '", is not an int';
278 0 $self->warn;
279 }
280  
281 2 return $self;
282 } ## end sub new
283  
284 # Internal helper. Returns the access rules endpoint, zone level if the zone
285 # option is set and user level otherwise.
286 sub _endpoint {
287 24 ▶ my ($self) = @_;
Subroutine _endpoint: called CC=2 SCAR=6.9
288  
289 24 ▶ if ( defined( $self->{options}{zone} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"options"}{"zone"}) 21 3 24
290 21 return 'https://api.cloudflare.com/client/v4/zones/' . $self->{options}{zone} . '/firewall/access_rules/rules';
291 }
292 3 return 'https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules';
293 }
294  
295 # Internal helper. Minimal percent encoder so URI::Escape is not needed.
296 sub _uri_escape {
297 8 ▶ my ( $self, $string ) = @_;
Subroutine _uri_escape: called CC=1 SCAR=0.0
298  
299 8 $string =~ s/([^A-Za-z0-9\-._~])/sprintf('%%%02X', ord($1))/ge;
300  
301 8 return $string;
302 }
303  
304 # Internal helper. Returns a canonical JSON::PP encoder/decoder.
305 sub _json {
306 5 ▶ my ($self) = @_;
Subroutine _json: called CC=1 SCAR=0.0
307  
308 5 require JSON::PP;
309 5 return JSON::PP->new->canonical->utf8;
310 }
311  
312 # Internal helper. Performs a HTTP request via LWP::UserAgent, returning the
313 # decoded JSON on success and dying with a explanation on any HTTP or API
314 # level failure. Never called in testing mode.
315 sub _request {
316 0 ▶ my ( $self, $method, $url, $body ) = @_;
Subroutine _request: not called CC=11 SCAR=48.8
317  
318 0 ▶ if ( !defined( $self->{ua} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"ua"}) 0 0 0
319 0 local $@;
320 0 ▶ eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require LWP::UserAgent; $self->{"ua"} = "LWP::UserAgent"->new("agent", 'Net::Firewall::BlockerHelper/' . $Net::Firewall::BlockerHelper::backends::cloudflare::VERSION, "timeout", $self->{"options"}{"timeout"}); 1 } } or die 'failed to load LWP::UserAgent, which the cloudflare backend requires... ' . $@ 0 0 0
321 0 require LWP::UserAgent;
322 $self->{ua} = LWP::UserAgent->new(
323 agent => 'Net::Firewall::BlockerHelper/' . $VERSION,
324 timeout => $self->{options}{timeout},
325 0 );
326 0 1;
327 } or die( 'failed to load LWP::UserAgent, which the cloudflare backend requires... ' . $@ );
328 }
329  
330 0 my @headers = ( 'Content-Type' => 'application/json' );
331 0 ▶ if ( defined( $self->{options}{token} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{'options'}{'token'}) { } 0 0 0
332 0 push( @headers, 'Authorization' => 'Bearer ' . $self->{options}{token} );
333 } else {
334 0 push( @headers, 'X-Auth-Email' => $self->{options}{email}, 'X-Auth-Key' => $self->{options}{key} );
335 }
336  
337 0 require HTTP::Request;
338 0 my $request = HTTP::Request->new( $method, $url, \@headers, $body );
339  
340 0 my $response = $self->{ua}->request($request);
341  
342 0 my $decoded;
343 0 local $@;
344 0 eval { $decoded = $self->_json->decode( $response->decoded_content ); };
345  
346 0 ▶ if ( !$response->is_success || !defined($decoded) || !$decoded->{success} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success and defined $decoded and $decoded->{"success"}) 0 0 0
Condition0%0/6
$response->is_success and defined $decoded and $decoded->{"success"}
!ll&&!rl&&r
000
$response->is_success and defined $decoded
!ll&&!rl&&r
000
MC/DC0%0/3
$response->is_success and defined $decoded and $decoded->{"success"}
$response->is_success defined $decoded $decoded->{"success"}
Truth table0%0/4
A and B and C
A= $response->is_successB= defined $decodedC= $decoded->{"success"}
ABCresult
0XX0
10X0
1100
1111
347 0 my $api_errors = '';
348 0 ▶ if ( defined($decoded) && ref( $decoded->{errors} ) eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $decoded and ref $decoded->{"errors"} eq "ARRAY") 0 0 0
Condition0%0/3
defined $decoded and ref $decoded->{"errors"} eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $decoded and ref $decoded->{"errors"} eq "ARRAY"
defined $decoded ref $decoded->{"errors"} eq "ARRAY"
Truth table0%0/3
A and B
A= defined $decodedB= ref $decoded->{"errors"} eq "ARRAY"
ABresult
0X0
100
111
349 $api_errors = ' API errors... ' . join(
350 ', ',
351 map {
352 ( defined( $_->{code} ) ? $_->{code} : '?' ) . ': '
353 0 ▶ . ( defined( $_->{message} ) ? $_->{message} : '?' )
Branch: 2 branches
BranchTrueFalseTotal
defined $_->{'code'} ? : 0 0 0
defined $_->{'message'} ? : 0 0 0
354 0 } @{ $decoded->{errors} }
355 );
356 }
357 0 die( $method . ' '
358 . $url
359 . ' failed... HTTP status... '
360 . $response->status_line
361 . $api_errors );
362 } ## end if ( !$response->is_success || !defined($decoded...))
363  
364 0 return $decoded;
365 } ## end sub _request
366  
367 =head2 init
368  
369 Initiates the backend. Verifies the credentials and endpoint by listing a
370 few rules.
371  
372 $backend->init;
373  
374 =cut
375  
376 sub init {
377 3 ▶ my ( $self, %opts ) = @_;
Subroutine init: called CC=4 SCAR=20.3
Pod documented
378  
379 3 $self->errorblank;
380  
381 3 ▶ if ( $self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"inited"}) 0 3 3
382 0 $self->{error} = 18;
383 0 $self->{errorString} = 'backend has already been inited';
384 0 $self->warn;
385 }
386  
387 3 my $url = $self->_endpoint . '?per_page=5';
388  
389 3 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 3 0 3
390 3 $self->{frontend_obj}->{test_data} = { requests => [ { method => 'GET', url => $url } ] };
391 } else {
392 0 local $@;
393 0 ▶ eval { $self->_request( 'GET', $url ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("GET", $url); 1 } } or do { $self->{"error"} = 23; $self->{"errorString"} = 'init failed. probing the access rules endpoint failed... ' . $@; $self->warn } 0 0 0
394 0 $self->{error} = 23;
395 0 $self->{errorString} = 'init failed. probing the access rules endpoint failed... ' . $@;
396 0 $self->warn;
397 };
398 }
399  
400 3 $self->{inited} = 1;
401 } ## end sub init
402  
403 =head2 ban
404  
405 Bans an IP. The value of ban is validated as being a IPv4 or IPv6 address
406 and lowercased, then an access rule is created for it via a POST to the
407 access rules endpoint, using the configured mode and notes. Banning an
408 already banned IP is a noop.
409  
410 $backend->ban(ban => $ip);
411  
412 =cut
413  
414 sub ban {
415 4 ▶ my ( $self, %opts ) = @_;
Subroutine ban: called CC=11 SCAR=34.7
Pod documented
416  
417 4 $self->errorblank;
418  
419 4 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 4 4
420 0 $self->{error} = 1;
421 0 $self->{errorString} = 'backend has not been inited';
422 0 $self->warn;
423 0 return;
424 }
425  
426 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::cloudflare::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv6_re\z/) { } 0 4 4
427 0 $self->{error} = 9;
428 0 $self->{errorString} = 'Nothing specified for the value ban';
429 0 $self->warn;
430 0 return;
431 } elsif ( ref( $opts{ban} ) ne '' ) {
432 0 $self->{error} = 10;
433 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
434 0 $self->warn;
435 0 return;
436 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition66%2/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv6_re\z/
l!l&&r!l&&!r
310
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv6_re\z/
Truth table66%2/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv6_re\z/
ABresult
1X1
011
000
437 && $opts{ban} !~ /\A$IPv6_re\z/ )
438 {
439 0 $self->{error} = 10;
440 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
441 0 $self->warn;
442 0 return;
443 }
444  
445 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
446 4 $opts{ban} = lc( $opts{ban} );
447  
448 4 ▶ if ( $self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"banned"}{$opts{"ban"}}) 1 3 4
449 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 1 0 1
450 1 $self->{frontend_obj}->{test_data} = 'already banned';
451 }
452 1 return;
453 }
454  
455 3 ▶ my $target = ( $opts{ban} =~ /\A$IPv4_re\z/ ) ? 'ip' : 'ip6';
Branch: 1 branch
BranchTrueFalseTotal
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv4_re\z/ ? : 2 1 3
456 my $body = $self->_json->encode(
457 {
458 mode => $self->{options}{mode},
459 configuration => { target => $target, value => $opts{ban} },
460 notes => $self->{options}{notes},
461 }
462 3 );
463  
464 3 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 3 0 3
465 3 $self->{frontend_obj}->{test_data} = [ { method => 'POST', url => $self->_endpoint, content => $body } ];
466 } else {
467 0 local $@;
468 0 ▶ eval { $self->_request( 'POST', $self->_endpoint, $body ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("POST", $self->_endpoint, $body); 1 } } or do { $self->{"error"} = 13; $self->{"errorString"} = 'banning "' . $opts{"ban"} . '" failed... ' . $@; $self->warn; return } 0 0 0
469 0 $self->{error} = 13;
470 0 $self->{errorString} = 'banning "' . $opts{ban} . '" failed... ' . $@;
471 0 $self->warn;
472 0 return;
473 };
474 }
475  
476 3 $self->{banned}{ $opts{ban} } = 1;
477 } ## end sub ban
478  
479 # Internal helper. Returns the lookup URL used to find the rule ID for the
480 # passed IP.
481 sub _unban_lookup_url {
482 3 ▶ my ( $self, $ip ) = @_;
Subroutine _unban_lookup_url: called CC=2 SCAR=6.9
483  
484 3 ▶ my $target = ( $ip =~ /\A$IPv4_re\z/ ) ? 'ip' : 'ip6';
Branch: 1 branch
BranchTrueFalseTotal
$ip =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv4_re\z/ ? : 1 2 3
485  
486 return
487 $self->_endpoint
488 . '?mode='
489 . $self->{options}{mode}
490 . '&notes='
491 . $self->_uri_escape( $self->{options}{notes} )
492 3 . '&configuration.target='
493 . $target
494 . '&configuration.value='
495 . $self->_uri_escape($ip);
496 } ## end sub _unban_lookup_url
497  
498 # Internal helper. Looks the rule for the IP up and deletes it. Dies on
499 # failure. A rule that can not be found is treated as already unbanned.
500 # Never called in testing mode.
501 sub _unban_ip {
502 0 ▶ my ( $self, $ip ) = @_;
Subroutine _unban_ip: not called CC=4 SCAR=30.0
503  
504 0 my $decoded = $self->_request( 'GET', $self->_unban_lookup_url($ip) );
505  
506 0 my $id;
507 0 ▶ if ( ref( $decoded->{result} ) eq 'ARRAY' && defined( $decoded->{result}[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $decoded->{"result"} eq "ARRAY" and defined $decoded->{"result"}[0]) 0 0 0
Condition0%0/3
ref $decoded->{"result"} eq "ARRAY" and defined $decoded->{"result"}[0]
!ll&&!rl&&r
000
MC/DC0%0/2
ref $decoded->{"result"} eq "ARRAY" and defined $decoded->{"result"}[0]
ref $decoded->{"result"} eq "ARRAY" defined $decoded->{"result"}[0]
Truth table0%0/3
A and B
A= ref $decoded->{"result"} eq "ARRAY"B= defined $decoded->{"result"}[0]
ABresult
0X0
100
111
508 0 $id = $decoded->{result}[0]{id};
509 }
510  
511 # no rule found means something else removed it already, which is fine
512 0 ▶ if ( !defined($id) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $id) 0 0 0
513 0 return;
514 }
515  
516 0 $self->_request( 'DELETE', $self->_endpoint . '/' . $id );
517  
518 0 return;
519 } ## end sub _unban_ip
520  
521 =head2 unban
522  
523 Unbans an IP. The value of ban is validated as being a IPv4 or IPv6 address
524 and lowercased. The matching access rule is then found via a GET filtering
525 on mode, notes, and the IP, and deleted by its ID. A rule that can not be
526 found is treated as already unbanned. Unbanning an IP that is not banned is
527 a noop.
528  
529 $backend->unban(ban => $ip);
530  
531 =cut
532  
533 sub unban {
534 1 ▶ my ( $self, %opts ) = @_;
Subroutine unban: called CC=10 SCAR=38.2
Pod documented
535  
536 1 $self->errorblank;
537  
538 1 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 1 1
539 0 $self->{error} = 1;
540 0 $self->{errorString} = 'backend has not been inited';
541 0 $self->warn;
542 0 return;
543 }
544  
545 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::cloudflare::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv6_re\z/) { } 0 1 1
546 0 $self->{error} = 9;
547 0 $self->{errorString} = 'Nothing specified for the value ban';
548 0 $self->warn;
549 0 return;
550 } elsif ( ref( $opts{ban} ) ne '' ) {
551 0 $self->{error} = 10;
552 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
553 0 $self->warn;
554 0 return;
555 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition33%1/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv6_re\z/
l!l&&r!l&&!r
100
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv6_re\z/
Truth table33%1/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv6_re\z/
ABresult
1X1
011
000
556 && $opts{ban} !~ /\A$IPv6_re\z/ )
557 {
558 0 $self->{error} = 10;
559 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
560 0 $self->warn;
561 0 return;
562 }
563  
564 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
565 1 $opts{ban} = lc( $opts{ban} );
566  
567 1 ▶ if ( !$self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"banned"}{$opts{"ban"}}) 0 1 1
568 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
569 0 $self->{frontend_obj}->{test_data} = 'not banned';
570 }
571 0 return;
572 }
573  
574 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 1 0 1
575 $self->{frontend_obj}->{test_data} = [
576 1 { method => 'GET', url => $self->_unban_lookup_url( $opts{ban} ) },
577 { method => 'DELETE', url => $self->_endpoint . '/<id>' },
578 ];
579 } else {
580 0 local $@;
581 0 ▶ eval { $self->_unban_ip( $opts{ban} ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_unban_ip($opts{"ban"}); 1 } } or do { $self->{"error"} = 14; $self->{"errorString"} = 'unbanning "' . $opts{"ban"} . '" failed... ' . $@; $self->warn; return } 0 0 0
582 0 $self->{error} = 14;
583 0 $self->{errorString} = 'unbanning "' . $opts{ban} . '" failed... ' . $@;
584 0 $self->warn;
585 0 return;
586 };
587 }
588  
589 1 delete( $self->{banned}{ $opts{ban} } );
590 } ## end sub unban
591  
592 # Internal helper. Returns a true value if the passed scalar is a valid IPv4 or
593 # IPv6 CIDR range, that is an address followed by "/" and a prefix length that
594 # is within the range valid for its family (0 to 32 for IPv4, 0 to 128 for
595 # IPv6). Returns false otherwise.
596 sub _valid_cidr {
597 2 ▶ my ( $self, $cidr ) = @_;
Subroutine _valid_cidr: called CC=8 SCAR=30.3
598  
599 2 ▶ return 0 if ( !defined($cidr) || ref($cidr) ne '' );
Branch: 1 branch
BranchTrueFalseTotal
if not defined $cidr or ref $cidr ne "" 0 2 2
Condition33%1/3
not defined $cidr or ref $cidr ne ""
l!l&&r!l&&!r
002
MC/DC0%0/2
not defined $cidr or ref $cidr ne ""
not defined $cidr ref $cidr ne ""
Truth table33%1/3
not(A) or B
A= not defined $cidrB= ref $cidr ne ""
ABresult
1X1
011
000
600  
601 2 ▶ if ( $cidr =~ m!\A(.+)/([0-9]{1,3})\z! ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cidr =~ m[\A(.+)/([0-9]{1,3})\z]) 2 0 2
602 2 my ( $addr, $prefix ) = ( $1, $2 );
603 2 ▶ return 1 if ( $addr =~ /\A$IPv4_re\z/ && $prefix <= 32 );
Branch: 1 branch
BranchTrueFalseTotal
if $addr =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv4_re\z/ and $prefix <= 32 2 0 2
Condition33%1/3
$addr =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv4_re\z/ and $prefix <= 32
!ll&&!rl&&r
002
MC/DC0%0/2
$addr =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv4_re\z/ and $prefix <= 32
$addr =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv4_re\z/ $prefix <= 32
Truth table33%1/3
A and B
A= $addr =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv4_re\z/B= $prefix <= 32
ABresult
0X0
100
111
604 0 ▶ return 1 if ( $addr =~ /\A$IPv6_re\z/ && $prefix <= 128 );
Branch: 1 branch
BranchTrueFalseTotal
if $addr =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv6_re\z/ and $prefix <= 128 0 0 0
Condition0%0/3
$addr =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv6_re\z/ and $prefix <= 128
!ll&&!rl&&r
000
MC/DC0%0/2
$addr =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv6_re\z/ and $prefix <= 128
$addr =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv6_re\z/ $prefix <= 128
Truth table0%0/3
A and B
A= $addr =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv6_re\z/B= $prefix <= 128
ABresult
0X0
100
111
605 }
606  
607 0 return 0;
608 } ## end sub _valid_cidr
609  
610 =head2 ban_cidr
611  
612 Bans a CIDR range by creating an access rule for it. Cloudflare access rules
613 accept a network prefix as the configuration value in the same manner as a
614 single address. The value of ban is validated as being a IPv4 or IPv6 CIDR
615 range and lowercased. Banning an already banned range is a noop.
616  
617 $backend->ban_cidr(ban => '1.2.3.0/24');
618  
619 =cut
620  
621 sub ban_cidr {
622 1 ▶ my ( $self, %opts ) = @_;
Subroutine ban_cidr: called CC=10 SCAR=37.2
Pod documented
623  
624 1 $self->errorblank;
625  
626 1 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 1 1
627 0 $self->{error} = 1;
628 0 $self->{errorString} = 'backend has not been inited';
629 0 $self->warn;
630 0 return;
631 }
632  
633 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 $self->_valid_cidr($opts{'ban'})) { } 0 1 1
634 0 $self->{error} = 9;
635 0 $self->{errorString} = 'Nothing specified for the value ban';
636 0 $self->warn;
637 0 return;
638 } elsif ( ref( $opts{ban} ) ne '' ) {
639 0 $self->{error} = 31;
640 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
641 0 $self->warn;
642 0 return;
643 } elsif ( !$self->_valid_cidr( $opts{ban} ) ) {
644 0 $self->{error} = 31;
645 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 CIDR';
646 0 $self->warn;
647 0 return;
648 }
649  
650 # lowercase so the same IPv6 CIDR in differing cases can't result in duplicate entries
651 1 $opts{ban} = lc( $opts{ban} );
652  
653 1 ▶ if ( $self->{banned_cidr}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"banned_cidr"}{$opts{"ban"}}) 0 1 1
654 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
655 0 $self->{frontend_obj}->{test_data} = 'already banned';
656 }
657 0 return;
658 }
659  
660 # the address portion of the CIDR determines the family, and thus the target
661 1 ▶ my $target = ( $opts{ban} =~ m!\A$IPv4_re/! ) ? 'ip' : 'ip6';
Branch: 1 branch
BranchTrueFalseTotal
$opts{'ban'} =~ m[\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv4_re/] ? : 1 0 1
662 my $body = $self->_json->encode(
663 {
664 mode => $self->{options}{mode},
665 configuration => { target => $target, value => $opts{ban} },
666 notes => $self->{options}{notes},
667 }
668 1 );
669  
670 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 1 0 1
671 1 $self->{frontend_obj}->{test_data} = [ { method => 'POST', url => $self->_endpoint, content => $body } ];
672 } else {
673 0 local $@;
674 0 ▶ eval { $self->_request( 'POST', $self->_endpoint, $body ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("POST", $self->_endpoint, $body); 1 } } or do { $self->{"error"} = 29; $self->{"errorString"} = 'banning "' . $opts{"ban"} . '" failed... ' . $@; $self->warn; return } 0 0 0
675 0 $self->{error} = 29;
676 0 $self->{errorString} = 'banning "' . $opts{ban} . '" failed... ' . $@;
677 0 $self->warn;
678 0 return;
679 };
680 }
681  
682 1 $self->{banned_cidr}{ $opts{ban} } = 1;
683 } ## end sub ban_cidr
684  
685 # Internal helper. Returns the lookup URL used to find the rule ID for the
686 # passed CIDR range.
687 sub _unban_cidr_lookup_url {
688 1 ▶ my ( $self, $cidr ) = @_;
Subroutine _unban_cidr_lookup_url: called CC=2 SCAR=7.1
689  
690 1 ▶ my $target = ( $cidr =~ m!\A$IPv4_re/! ) ? 'ip' : 'ip6';
Branch: 1 branch
BranchTrueFalseTotal
$cidr =~ m[\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv4_re/] ? : 1 0 1
691  
692 return
693 $self->_endpoint
694 . '?mode='
695 . $self->{options}{mode}
696 . '&notes='
697 . $self->_uri_escape( $self->{options}{notes} )
698 1 . '&configuration.target='
699 . $target
700 . '&configuration.value='
701 . $self->_uri_escape($cidr);
702 } ## end sub _unban_cidr_lookup_url
703  
704 =head2 unban_cidr
705  
706 Unbans a CIDR range by finding and deleting its access rule, the same way
707 L</unban> does for a single IP. A rule that can not be found is treated as
708 already unbanned. Unbanning a range that is not banned is a noop.
709  
710 $backend->unban_cidr(ban => '1.2.3.0/24');
711  
712 =cut
713  
714 sub unban_cidr {
715 1 ▶ my ( $self, %opts ) = @_;
Subroutine unban_cidr: called CC=12 SCAR=43.4
Pod documented
716  
717 1 $self->errorblank;
718  
719 1 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 1 1
720 0 $self->{error} = 1;
721 0 $self->{errorString} = 'backend has not been inited';
722 0 $self->warn;
723 0 return;
724 }
725  
726 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 $self->_valid_cidr($opts{'ban'})) { } 0 1 1
727 0 $self->{error} = 9;
728 0 $self->{errorString} = 'Nothing specified for the value ban';
729 0 $self->warn;
730 0 return;
731 } elsif ( ref( $opts{ban} ) ne '' ) {
732 0 $self->{error} = 31;
733 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
734 0 $self->warn;
735 0 return;
736 } elsif ( !$self->_valid_cidr( $opts{ban} ) ) {
737 0 $self->{error} = 31;
738 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 CIDR';
739 0 $self->warn;
740 0 return;
741 }
742  
743 # lowercase so the same IPv6 CIDR in differing cases can't result in duplicate entries
744 1 $opts{ban} = lc( $opts{ban} );
745  
746 1 ▶ if ( !$self->{banned_cidr}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"banned_cidr"}{$opts{"ban"}}) 0 1 1
747 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
748 0 $self->{frontend_obj}->{test_data} = 'not banned';
749 }
750 0 return;
751 }
752  
753 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 1 0 1
754 $self->{frontend_obj}->{test_data} = [
755 1 { method => 'GET', url => $self->_unban_cidr_lookup_url( $opts{ban} ) },
756 { method => 'DELETE', url => $self->_endpoint . '/<id>' },
757 ];
758 } else {
759 0 local $@;
760 eval {
761 0 my $decoded = $self->_request( 'GET', $self->_unban_cidr_lookup_url( $opts{ban} ) );
762  
763 0 my $id;
764 0 ▶ if ( ref( $decoded->{result} ) eq 'ARRAY' && defined( $decoded->{result}[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $decoded->{"result"} eq "ARRAY" and defined $decoded->{"result"}[0]) 0 0 0
Condition0%0/3
ref $decoded->{"result"} eq "ARRAY" and defined $decoded->{"result"}[0]
!ll&&!rl&&r
000
MC/DC0%0/2
ref $decoded->{"result"} eq "ARRAY" and defined $decoded->{"result"}[0]
ref $decoded->{"result"} eq "ARRAY" defined $decoded->{"result"}[0]
Truth table0%0/3
A and B
A= ref $decoded->{"result"} eq "ARRAY"B= defined $decoded->{"result"}[0]
ABresult
0X0
100
111
765 0 $id = $decoded->{result}[0]{id};
766 }
767  
768 # no rule found means something else removed it already, which is fine
769 0 ▶ if ( defined($id) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $id) 0 0 0
770 0 $self->_request( 'DELETE', $self->_endpoint . '/' . $id );
771 }
772 0 1;
773 0 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { my $decoded = $self->_request("GET", $self->_unban_cidr_lookup_url($opts{"ban"})); my $id; if (ref $decoded->{"result"} eq "ARRAY" and defined $decoded->{"result"}[0]) { $id = $decoded->{"result"}[0]{"id"}; } ; if (defined $id) { $self->_request("DELETE", $self->_endpoint . '/' . $id); } ; 1 } } or do { $self->{"error"} = 30; $self->{"errorString"} = 'unbanning "' . $opts{"ban"} . '" failed... ' . $@; $self->warn; return } 0 0 0
774 0 $self->{error} = 30;
775 0 $self->{errorString} = 'unbanning "' . $opts{ban} . '" failed... ' . $@;
776 0 $self->warn;
777 0 return;
778 };
779 } ## end else [ if ( $self->{testing} ) ]
780  
781 1 delete( $self->{banned_cidr}{ $opts{ban} } );
782 } ## end sub unban_cidr
783  
784 =head2 list_cidr
785  
786 List banned CIDR ranges. Returns an array of the currently banned CIDR
787 ranges. Single IPs are not included; for those see L</list>.
788  
789 my @banned_cidrs = $backend->list_cidr;
790  
791 =cut
792  
793 sub list_cidr {
794 2 ▶ my ( $self, %opts ) = @_;
Subroutine list_cidr: called CC=2 SCAR=7.0
Pod documented
795  
796 2 $self->errorblank;
797  
798 2 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 2 0 2
799 2 $self->{frontend_obj}->{test_data} = 'list_cidr';
800 }
801  
802 2 return keys( %{ $self->{banned_cidr} } );
803 }
804  
805 =head2 list
806  
807 List banned IPs. Returns an array of the currently banned single IPs. CIDR
808 ranges are not included; for those see L</list_cidr>.
809  
810 my @banned = $backend->list;
811  
812 =cut
813  
814 sub list {
815 1 ▶ my ( $self, %opts ) = @_;
Subroutine list: called CC=2 SCAR=7.0
Pod documented
816  
817 1 $self->errorblank;
818  
819 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 1 0 1
820 1 $self->{frontend_obj}->{test_data} = 'list';
821 }
822  
823 1 return keys( %{ $self->{banned} } );
824 }
825  
826 =head2 re_init
827  
828 Tells the backend to re-init it's self.
829  
830 This will call teardown and init again. After that it will
831 re-added all previously added bans.
832  
833 $backend->re_init;
834  
835 =cut
836  
837 sub re_init {
838 1 ▶ my ( $self, %opts ) = @_;
Subroutine re_init: called CC=11 SCAR=35.0
Pod documented
839  
840 1 $self->errorblank;
841  
842 1 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 1 1
843 0 $self->{error} = 1;
844 0 $self->{errorString} = 'backend has not been inited';
845 0 $self->warn;
846 0 return;
847 }
848  
849 # teardown is best effort here as a partially or fully wiped setup is
850 # exactly what re_init needs to recover from; init cleans up any remnants
851 {
852 1 local $@;
853 1 eval { $self->teardown; };
854 }
855 1 $self->init;
856  
857 1 my @to_ban = keys( %{ $self->{banned} } );
858  
859 1 my @re_init_test_data;
860 1 foreach my $item (@to_ban) {
861 1 ▶ my $target = ( $item =~ /\A$IPv4_re\z/ ) ? 'ip' : 'ip6';
Branch: 1 branch
BranchTrueFalseTotal
$item =~ /\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv4_re\z/ ? : 0 1 1
862 my $body = $self->_json->encode(
863 {
864 mode => $self->{options}{mode},
865 configuration => { target => $target, value => $item },
866 notes => $self->{options}{notes},
867 }
868 1 );
869  
870 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 1 0 1
871 1 push( @re_init_test_data, { method => 'POST', url => $self->_endpoint, content => $body } );
872 } else {
873 0 local $@;
874 0 ▶ eval { $self->_request( 'POST', $self->_endpoint, $body ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("POST", $self->_endpoint, $body); 1 } } or do { $self->{"error"} = 13; $self->{"errorString"} = 'banning "' . $item . '" failed... ' . $@; $self->warn } 0 0 0
875 0 $self->{error} = 13;
876 0 $self->{errorString} = 'banning "' . $item . '" failed... ' . $@;
877 0 $self->warn;
878 };
879 }
880 } ## end foreach my $item (@to_ban)
881  
882 # CIDR ranges are re-added the same way, the address portion of the CIDR
883 # determining the target
884 1 my @to_ban_cidr = keys( %{ $self->{banned_cidr} } );
885  
886 1 foreach my $item (@to_ban_cidr) {
887 0 ▶ my $target = ( $item =~ m!\A$IPv4_re/! ) ? 'ip' : 'ip6';
Branch: 1 branch
BranchTrueFalseTotal
$item =~ m[\A$Net::Firewall::BlockerHelper::backends::cloudflare::IPv4_re/] ? : 0 0 0
888 my $body = $self->_json->encode(
889 {
890 mode => $self->{options}{mode},
891 configuration => { target => $target, value => $item },
892 notes => $self->{options}{notes},
893 }
894 0 );
895  
896 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
897 0 push( @re_init_test_data, { method => 'POST', url => $self->_endpoint, content => $body } );
898 } else {
899 0 local $@;
900 0 ▶ eval { $self->_request( 'POST', $self->_endpoint, $body ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("POST", $self->_endpoint, $body); 1 } } or do { $self->{"error"} = 29; $self->{"errorString"} = 'banning "' . $item . '" failed... ' . $@; $self->warn } 0 0 0
901 0 $self->{error} = 29;
902 0 $self->{errorString} = 'banning "' . $item . '" failed... ' . $@;
903 0 $self->warn;
904 };
905 }
906 } ## end foreach my $item (@to_ban_cidr)
907  
908 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 1 0 1
909 1 $self->{frontend_obj}->{test_data} = \@re_init_test_data;
910 }
911  
912 1 $self->{inited} = 1;
913 } ## end sub re_init
914  
915 =head2 teardown
916  
917 Tears down the setup for the backend by removing the access rule for each
918 currently banned IP. The internal list of bans is kept, so a following
919 re_init will re-add them.
920  
921 $backend->teardown;
922  
923 =cut
924  
925 sub teardown {
926 1 ▶ my ( $self, %opts ) = @_;
Subroutine teardown: called CC=5 SCAR=20.5
Pod documented
927  
928 1 $self->errorblank;
929  
930 1 $self->{inited} = 0;
931  
932 1 my @requests;
933 1 foreach my $item ( sort( keys( %{ $self->{banned} } ) ) ) {
934 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 1 0 1
935 1 push(
936 @requests,
937 { method => 'GET', url => $self->_unban_lookup_url($item) },
938 { method => 'DELETE', url => $self->_endpoint . '/<id>' }
939 );
940 } else {
941 0 local $@;
942 0 ▶ eval { $self->_unban_ip($item); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_unban_ip($item); 1 } } or do { $self->{"error"} = 17; $self->{"errorString"} = 'teardown failed removing the rule for "' . $item . '"... ' . $@; $self->warn } 0 0 0
943 0 $self->{error} = 17;
944 0 $self->{errorString} = 'teardown failed removing the rule for "' . $item . '"... ' . $@;
945 0 $self->warn;
946 };
947 }
948 } ## end foreach my $item ( sort( keys( %{ $self->{banned...})))
949  
950 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 1 0 1
951 1 $self->{frontend_obj}->{test_data} = \@requests;
952 }
953 } ## end sub teardown
954  
955 =head2 stop
956  
957 Alias for L</teardown>, provided for parity with the fail2ban C<actionstop>
958 concept.
959  
960 $backend->stop;
961  
962 =cut
963  
964 sub stop {
965 0 ▶ my ( $self, %opts ) = @_;
Subroutine stop: not called CC=1 SCAR=6.9
Pod documented
966  
967 0 return $self->teardown(%opts);
968 }
969  
970 =head2 check
971  
972 Verifies the endpoint and credentials are still usable by listing a few
973 rules. Returns a true value if so and a false value otherwise. This is the
974 equivalent of fail2ban's C<actioncheck>.
975  
976 if ( !$backend->check ) {
977 $backend->re_init;
978 }
979  
980 =cut
981  
982 sub check {
983 8 ▶ my ( $self, %opts ) = @_;
Subroutine check: called CC=3 SCAR=14.7
Pod documented
984  
985 8 $self->errorblank;
986  
987 8 my $url = $self->_endpoint . '?per_page=5';
988  
989 8 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 8 0 8
990 8 $self->{frontend_obj}->{test_data} = [ { method => 'GET', url => $url } ];
991 8 return 1;
992 }
993  
994 0 local $@;
995 0 ▶ eval { $self->_request( 'GET', $url ); 1; } or return 0;
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("GET", $url); 1 } } or return 0 0 0 0
996  
997 0 return 1;
998 } ## end sub check
999  
1000 =head2 flush
1001  
1002 Removes all currently banned IPs and CIDR ranges at once by removing their
1003 access rules and forgetting them. This is the equivalent of fail2ban's
1004 C<actionflush>.
1005  
1006 $backend->flush;
1007  
1008 =cut
1009  
1010 sub flush {
1011 1 ▶ my ( $self, %opts ) = @_;
Subroutine flush: called CC=12 SCAR=41.4
Pod documented
1012  
1013 1 $self->errorblank;
1014  
1015 1 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 1 1
1016 0 $self->{error} = 1;
1017 0 $self->{errorString} = 'backend has not been inited';
1018 0 $self->warn;
1019 0 return;
1020 }
1021  
1022 1 my @requests;
1023 1 foreach my $item ( sort( keys( %{ $self->{banned} } ) ) ) {
1024 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 1 0 1
1025 1 push(
1026 @requests,
1027 { method => 'GET', url => $self->_unban_lookup_url($item) },
1028 { method => 'DELETE', url => $self->_endpoint . '/<id>' }
1029 );
1030 } else {
1031 0 local $@;
1032 0 ▶ eval { $self->_unban_ip($item); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_unban_ip($item); 1 } } or do { $self->{"error"} = 25; $self->{"errorString"} = 'flush failed removing the rule for "' . $item . '"... ' . $@; $self->warn } 0 0 0
1033 0 $self->{error} = 25;
1034 0 $self->{errorString} = 'flush failed removing the rule for "' . $item . '"... ' . $@;
1035 0 $self->warn;
1036 };
1037 }
1038 } ## end foreach my $item ( sort( keys( %{ $self->{banned...})))
1039  
1040 # CIDR ranges are removed the same way, looked up by their own lookup URL
1041 1 foreach my $item ( sort( keys( %{ $self->{banned_cidr} } ) ) ) {
1042 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
1043 0 push(
1044 @requests,
1045 { method => 'GET', url => $self->_unban_cidr_lookup_url($item) },
1046 { method => 'DELETE', url => $self->_endpoint . '/<id>' }
1047 );
1048 } else {
1049 0 local $@;
1050 eval {
1051 0 my $decoded = $self->_request( 'GET', $self->_unban_cidr_lookup_url($item) );
1052  
1053 0 my $id;
1054 0 ▶ if ( ref( $decoded->{result} ) eq 'ARRAY' && defined( $decoded->{result}[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $decoded->{"result"} eq "ARRAY" and defined $decoded->{"result"}[0]) 0 0 0
Condition0%0/3
ref $decoded->{"result"} eq "ARRAY" and defined $decoded->{"result"}[0]
!ll&&!rl&&r
000
MC/DC0%0/2
ref $decoded->{"result"} eq "ARRAY" and defined $decoded->{"result"}[0]
ref $decoded->{"result"} eq "ARRAY" defined $decoded->{"result"}[0]
Truth table0%0/3
A and B
A= ref $decoded->{"result"} eq "ARRAY"B= defined $decoded->{"result"}[0]
ABresult
0X0
100
111
1055 0 $id = $decoded->{result}[0]{id};
1056 }
1057  
1058 0 ▶ if ( defined($id) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $id) 0 0 0
1059 0 $self->_request( 'DELETE', $self->_endpoint . '/' . $id );
1060 }
1061 0 1;
1062 0 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { my $decoded = $self->_request("GET", $self->_unban_cidr_lookup_url($item)); my $id; if (ref $decoded->{"result"} eq "ARRAY" and defined $decoded->{"result"}[0]) { $id = $decoded->{"result"}[0]{"id"}; } ; if (defined $id) { $self->_request("DELETE", $self->_endpoint . '/' . $id); } ; 1 } } or do { $self->{"error"} = 25; $self->{"errorString"} = 'flush failed removing the rule for "' . $item . '"... ' . $@; $self->warn } 0 0 0
1063 0 $self->{error} = 25;
1064 0 $self->{errorString} = 'flush failed removing the rule for "' . $item . '"... ' . $@;
1065 0 $self->warn;
1066 };
1067 } ## end else [ if ( $self->{testing} ) ]
1068 } ## end foreach my $item ( sort( keys( %{ $self->{banned_cidr...})))
1069  
1070 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 1 0 1
1071 1 $self->{frontend_obj}->{test_data} = \@requests;
1072 }
1073  
1074 1 $self->{banned} = {};
1075 1 $self->{banned_cidr} = {};
1076 } ## end sub flush
1077  
1078 =head1 ERROR CODES / FLAGS
1079  
1080 Error handling is provided by L<Error::Helper>. All
1081 errors are considered fatal.
1082  
1083 =head2 1, notInited
1084  
1085 The backend has not been inited yet.
1086  
1087 =head2 6, invalidPrefixSpecified
1088  
1089 The specified prefix did not match /^[a-zA-Z0-9]+$/.
1090  
1091 =head2 7, invalidName
1092  
1093 The name is either undef or does not match /^[a-zA-Z0-9\-]+$/.
1094  
1095 =head2 8, optionsNotHash
1096  
1097 The item passed to new for options is not a hash.
1098  
1099 =head2 9, noBanItem
1100  
1101 No IP or CIDR range specified to ban or unban.
1102  
1103 =head2 10, banItemNotIP
1104  
1105 The item to ban is not an IP. Either wrong ref type or regexp
1106 test using L<Regexp::IPv4> and L<Regexp::IPv6> failed.
1107  
1108 =head2 12, backendInitError
1109  
1110 Failed to init the backend.
1111  
1112 =head2 13, banFailed
1113  
1114 Failed to ban the item.
1115  
1116 =head2 14, unbanFailed
1117  
1118 Failed to unban the item.
1119  
1120 =head2 15, listFailed
1121  
1122 Failed to get a list of bans.
1123  
1124 =head2 16, reInitFailed
1125  
1126 Failed to re_init the backend.
1127  
1128 =head2 17, teardownFailed
1129  
1130 Failed to teardown the backend.
1131  
1132 =head2 18, alreadyInited
1133  
1134 init called, but the backend has already been inited.
1135  
1136 =head2 20, modeInvalid
1137  
1138 The option mode is not 'block', 'challenge', 'js_challenge', or
1139 'managed_challenge'.
1140  
1141 =head2 23, initFailed
1142  
1143 init failed. Probing the access rules endpoint failed.
1144  
1145 =head2 24, checkFailed
1146  
1147 The backend check raised an error.
1148  
1149 =head2 25, flushFailed
1150  
1151 Failed to flush the bans.
1152  
1153 =head2 26, portsNotSupported
1154  
1155 The cloudflare backend blocks whole IPs and does not support ports.
1156  
1157 =head2 27, protocolsNotSupported
1158  
1159 The cloudflare backend blocks whole IPs and does not support protocols.
1160  
1161 =head2 28, optionInvalid
1162  
1163 An option is invalid. Auth requires either the option token or both the
1164 options email and key, zone must be a zone ID, and timeout must be an int.
1165  
1166 =head2 29, banCidrFailed
1167  
1168 Failed to ban the CIDR range.
1169  
1170 =head2 30, unbanCidrFailed
1171  
1172 Failed to unban the CIDR range.
1173  
1174 =head2 31, cidrItemNotCidr
1175  
1176 The item to ban is not a CIDR range. Either wrong ref type or it is not an
1177 IPv4 or IPv6 address followed by a prefix length valid for its family.
1178  
1179 =head2 32, cidrNotSupported
1180  
1181 The backend does not support CIDR bans.
1182  
1183 =head2 33, listCidrFailed
1184  
1185 Failed to get a list of CIDR bans.
1186  
1187 =head1 AUTHOR
1188  
1189 Zane C. Bowers-Hadley, C<< <vvelox at vvelox.ent> >>
1190  
1191 =head1 BUGS
1192  
1193 Please report any bugs or feature requests to C<bug-net-firewall-blockerhelper at rt.cpan.org>, or through
1194 the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Net-Firewall-BlockerHelper>.
1195  
1196 =head1 LICENSE AND COPYRIGHT
1197  
1198 This software is Copyright (c) 2023 by Zane C. Bowers-Hadley.
1199  
1200 This is free software, licensed under:
1201  
1202 The GNU Lesser General Public License, Version 2.1, February 1999
1203  
1204  
1205 =cut
1206  
1207 1 1; # End of Net::Firewall::BlockerHelper
« BlockerHelper/backends/fastly.pm ↑ Summary BlockerHelper/backends/checkpoint.pm »