BlockerHelper/backends/file_reload.pm

filter: Statementstmt 63.3% 169 / 267 Branchbran 66.3% 77 / 116 Conditioncond 59.2% 16 / 27 MC/DCmcdc 27.7% 5 / 18 Subroutinesub 95.2% 20 / 21 Podpod 100% 13 / 13 totaltotal 64.9% 300 / 462 CC 69 SCAR 25.4
CC
69
Cov
64%
unban
25.0
ban_cidr
21.5
unban_cidr
21.5
CRAP 12.7
« BlockerHelper/backends/cloud_armor.pm ↑ Summary BlockerHelper/backends/shell.pm »
1 package Net::Firewall::BlockerHelper::backends::file_reload;
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::file_reload - Render banned IPs to a file and run a reload hook.
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 The rendered file has no effect on its own; whatever is meant to consume it
25 must be configured to read it and the C<reload> option set to whatever
26 makes it re-read it. So for the nginx example below, nginx needs a line
27 like the following in the relevant C<http> or C<server> context.
28  
29 include /etc/nginx/blocklist.conf;
30  
31 Also worth noting is that with C<remove_on_teardown> left at its default
32 of 1, teardown unlinks the file, so a consumer that errors on a missing
33 include, nginx included, will then fail to reload or start till the file
34 exists again. For consumers like that either set C<remove_on_teardown>
35 to 0, which leaves an empty file in place instead, or make sure the file
36 gets created before the consumer needs it.
37  
38 use Net::Firewall::BlockerHelper;
39  
40 my $fw_helper = Net::Firewall::BlockerHelper->new(
41 backend => 'file_reload',
42 name => 'blocklist',
43 options => {
44 file => '/etc/nginx/blocklist.conf',
45 format => 'deny %%%BAN%%%;',
46 reload => 'systemctl reload nginx',
47 },
48 );
49  
50 $fw_helper->init_backend;
51 $fw_helper->ban( ban => '1.2.3.4' );
52 $fw_helper->unban( ban => '1.2.3.4' );
53 $fw_helper->teardown;
54  
55 =head1 DESCRIPTION
56  
57 This is a generic backend for anything that reads a list of IPs from a file
58 and needs to be told to reload after that file changes: web servers, DNS RPZ
59 zones, hand rolled ipset restore files, and so on.
60  
61 The full set of currently banned IPs is rendered to C<file> from in-memory
62 state on every change; the file is never parsed back, so this module is the
63 sole author of its contents. After each write the optional C<reload> command
64 is run. Because the file is rewritten wholesale, ban/unban are idempotent and
65 there is never any partially applied state.
66  
67 =head1 METHODS
68  
69 =head2 new
70  
71 - options :: A hash of options. See below.
72 - Default :: {}
73  
74 - name :: Required by Net::Firewall::BlockerHelper, otherwise unused.
75 - Default :: undef
76  
77 The options hash accepts the following.
78  
79 - file :: Path of the file to render the banned IPs to. Required.
80 - Default :: undef
81  
82 - reload :: Command run after the file is written. '2>&1' is appended.
83 If undef or blank, nothing is run and only the file is updated.
84 - Default :: undef
85  
86 - blank_reload_error :: If true, the reload command producing no output
87 at all is treated as a failure, even with a zero exit. Set to 0
88 for reload commands that are silent on success, such as
89 'systemctl reload nginx'.
90 - Default :: 1
91  
92 - format :: Per-IP line template. '%%%BAN%%%' is replaced with the IP.
93 The rendered lines are newline joined.
94 - Default :: '%%%BAN%%%'
95  
96 - header :: String emitted at the top of the file, before the IP lines.
97 - Default :: ''
98  
99 - footer :: String emitted at the bottom of the file, after the IP lines.
100 - Default :: ''
101  
102 - check :: Optional command used by check(). A zero exit is healthy. If
103 not set, check() verifies the file still exists instead.
104 - Default :: undef
105  
106 - remove_on_teardown :: If true, teardown unlinks the file. If false, the
107 file is rendered empty (header/footer only) and left in place.
108 - Default :: 1
109  
110 All errors are considered fatal, meaning if new fails it will die.
111  
112 =cut
113  
114 11 ▶sub new {
Subroutine new: called CC=14 SCAR=27.2
Pod documented
115 11 my ( $blank, %opts ) = @_;
116  
117 11 my $self = {
118 perror => undef,
119 error => undef,
120 errorLine => undef,
121 errorFilename => undef,
122 errorString => "",
123 errorExtra => {
124 all_errors_fatal => 1,
125 # all_fatal is what Error::Helper 2.1.0 actually checks; all_errors_fatal
126 # is kept for the name documented in its POD
127 all_fatal => 1,
128 flags => {
129 1 => 'notInited',
130 8 => 'optionsNotHash',
131 9 => 'noBanItem',
132 10 => 'banItemNotIP',
133 12 => 'backendInitError',
134 13 => 'banFailed',
135 14 => 'unbanFailed',
136 15 => 'listFailed',
137 16 => 'reInitFailed',
138 17 => 'teardownFailed',
139 18 => 'alreadyInited',
140 24 => 'checkFailed',
141 25 => 'flushFailed',
142 30 => 'fileNotDefined',
143 31 => 'fileWriteFailed',
144 32 => 'banCidrFailed',
145 33 => 'unbanCidrFailed',
146 34 => 'cidrItemNotCidr',
147 35 => 'cidrNotSupported',
148 36 => 'listCidrFailed',
149 },
150 fatal_flags => {},
151 perror_not_fatal => 0,
152 },
153 options => {},
154 ports => [],
155 protocols => [],
156 testing => undef,
157 test_data => undef,
158 prefix => 'kur',
159 name => undef,
160 frontend_obj => undef,
161 inited => 0,
162 banned => {},
163 banned_cidr => {},
164 cidr_supported => 1,
165 };
166 11 bless $self;
167  
168 11 ▶ if ( defined( $opts{testing} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"testing"}) 4 7 11
169 4 $self->{testing} = $opts{testing};
170 }
171 11 ▶ if ( defined( $opts{frontend_obj} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"frontend_obj"}) 7 4 11
172 7 $self->{frontend_obj} = $opts{frontend_obj};
173 }
174 11 ▶ if ( defined( $opts{name} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"name"}) 11 0 11
175 11 $self->{name} = $opts{name};
176 }
177  
178 11 ▶ if ( defined( $opts{options} ) && ref( $opts{options} ) ne 'HASH' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opts{'options'} and ref $opts{'options'} ne 'HASH') { } 0 11 11
elsif (defined $opts{'options'}) { } 11 0 11
Condition33%1/3
defined $opts{"options"} and ref $opts{"options"} ne "HASH"
!ll&&!rl&&r
0110
MC/DC0%0/2
defined $opts{"options"} and ref $opts{"options"} ne "HASH"
defined $opts{"options"} ref $opts{"options"} ne "HASH"
Truth table33%1/3
A and B
A= defined $opts{"options"}B= ref $opts{"options"} ne "HASH"
ABresult
0X0
100
111
179 0 $self->{perror} = 1;
180 0 $self->{error} = 8;
181 0 $self->{errorString} = 'ref for options is "' . ref( $opts{options} ) . '" and not HASH';
182 0 $self->warn;
183 } elsif ( defined( $opts{options} ) ) {
184 11 $self->{options} = $opts{options};
185 }
186  
187 # file is the one hard requirement
188 11 ▶ if ( !defined( $self->{options}{file} ) || $self->{options}{file} eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{"options"}{"file"} or $self->{"options"}{"file"} eq "") 1 10 11
Condition66%2/3
not defined $self->{"options"}{"file"} or $self->{"options"}{"file"} eq ""
l!l&&r!l&&!r
1010
MC/DC50%1/2
not defined $self->{"options"}{"file"} or $self->{"options"}{"file"} eq ""
not defined $self->{"options"}{"file"} $self->{"options"}{"file"} eq ""
Truth table66%2/3
not(A) or B
A= not defined $self->{"options"}{"file"}B= $self->{"options"}{"file"} eq ""
ABresult
1X1
011
000
189 1 $self->{perror} = 1;
190 1 $self->{error} = 30;
191 1 $self->{errorString} = 'options{file} is undef or blank';
192 1 $self->warn;
193 }
194  
195 # fill in the templating defaults
196 10 ▶ $self->{options}{format} = '%%%BAN%%%' if ( !defined( $self->{options}{format} ) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"options"}{"format"} 7 3 10
197 10 ▶ $self->{options}{header} = '' if ( !defined( $self->{options}{header} ) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"options"}{"header"} 7 3 10
198 10 ▶ $self->{options}{footer} = '' if ( !defined( $self->{options}{footer} ) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"options"}{"footer"} 8 2 10
199 $self->{options}{remove_on_teardown} = 1
200 10 ▶ if ( !defined( $self->{options}{remove_on_teardown} ) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"options"}{"remove_on_teardown"} 9 1 10
201 $self->{options}{blank_reload_error} = 1
202 10 ▶ if ( !defined( $self->{options}{blank_reload_error} ) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"options"}{"blank_reload_error"} 9 1 10
203  
204 10 return $self;
205 } ## end sub new
206  
207 # Internal helper. Builds the entire contents of the ban list file from the
208 # current bans. Unlike the backends that own a marked region of a shared file,
209 # this one owns the whole file, so what comes back here is written out
210 # verbatim and replaces whatever was there.
211 #
212 # Single IPs and CIDR ranges are drawn from two separate internal lists but
213 # are rendered identically and interleaved into one sorted run. Nothing
214 # downstream distinguishes them, so a consumer reading the file sees a single
215 # flat list of ban targets.
216 #
217 # The entries are sorted so that the same set of bans always renders to the
218 # same bytes. That keeps the file from being rewritten with reshuffled lines
219 # on unrelated operations, which matters here because every write is followed
220 # by the reload hook. Note the sort is a plain string sort, so the order is
221 # lexical rather than numeric or address aware.
222 #
223 # The header and footer are only emitted when set to something non empty, so
224 # the default of an empty string for both produces a bare list.
225 #
226 # Takes no arguments; the bans come from the object's banned and banned_cidr
227 # hashes.
228 #
229 # Returns the complete file contents as a single string, always ending in a
230 # newline. With nothing banned and no header or footer the result is just a
231 # lone newline, not the empty string, since the join always has a newline
232 # appended.
233 #
234 # # default format, no header or footer, 10.0.0.1 and 10.0.0.0/8 banned
235 # my $content = $self->_render;
236 # # "10.0.0.0/8\n10.0.0.1\n"
237 #
238 # # with format ' deny %%%BAN%%%;', header 'block {', footer '}'
239 # # "block {\n deny 10.0.0.0/8;\n deny 10.0.0.1;\n}\n"
240 #
241 # The format option is applied per entry with every occurrence of the
242 # %%%BAN%%% placeholder replaced by the entry, so a format may mention the
243 # target more than once. It defaults to a bare %%%BAN%%%, which renders one
244 # plain address or range per line.
245 29 ▶sub _render {
Subroutine _render: called CC=4 SCAR=13.9
246 29 my ($self) = @_;
247  
248 29 my @lines;
249 29 ▶ push( @lines, $self->{options}{header} ) if ( $self->{options}{header} ne '' );
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"options"}{"header"} ne "" 12 17 29
250  
251 # single IPs and CIDR ranges are rendered into the same file the same way
252 29 my @to_render = ( keys( %{ $self->{banned} } ), keys( %{ $self->{banned_cidr} } ) );
253 29 foreach my $ip ( sort(@to_render) ) {
254 19 my $line = $self->{options}{format};
255 19 $line =~ s/\%\%\%BAN\%\%\%/$ip/g;
256 19 push( @lines, $line );
257 }
258  
259 29 ▶ push( @lines, $self->{options}{footer} ) if ( $self->{options}{footer} ne '' );
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"options"}{"footer"} ne "" 5 24 29
260  
261 29 return join( "\n", @lines ) . "\n";
262 } ## end sub _render
263  
264 # Internal helper. Writes the rendered ban list out to the configured file and
265 # then runs the reload hook. This is the only place the file is written or the
266 # hook is run, so init, ban, unban, ban_cidr, unban_cidr, re_init, teardown,
267 # and flush all funnel through it.
268 #
269 # The file is opened for truncation and rewritten in full, since this backend
270 # owns the whole file rather than a region of it. There is no locking and no
271 # atomic rename here, unlike hosts_deny: the file is assumed to belong to this
272 # instance alone, and a consumer only reads it when told to by the reload
273 # hook, which runs after the write has completed.
274 #
275 # The reload hook is skipped when the reload option is unset or empty, which
276 # is how a caller renders a file that something else is watching. Otherwise it
277 # is run through the shell with stderr folded into stdout, and a non zero exit
278 # is an error.
279 #
280 # The blank_reload_error option, on by default, additionally treats a hook
281 # that succeeds but prints nothing at all as a failure. That guards against a
282 # hook that is silently not doing anything, such as a mistyped command name
283 # swallowed by a wrapper, which would otherwise look like a working reload
284 # forever.
285 #
286 # A failure to open the file for writing always raises 31, fileWriteFailed,
287 # rather than the passed code, since that is a problem with the file itself
288 # and not with the operation that triggered it. Only reload failures use the
289 # passed code. Nothing here dies; the error is set and warned and the caller
290 # checks the error state.
291 #
292 # Args:
293 #
294 # error_flag - The numeric error code to raise if the reload hook fails,
295 # so the error reads as the operation that triggered it.
296 # Callers pass the code matching themselves: 12
297 # backendInitError from init, 13 banFailed from ban, 14
298 # unbanFailed from unban, 32 banCidrFailed from ban_cidr, 33
299 # unbanCidrFailed from unban_cidr, 16 reInitFailed from
300 # re_init, 17 teardownFailed from teardown, and 25
301 # flushFailed from flush. Not optional in practice; every
302 # caller passes one.
303 #
304 # Returns nothing, on success and on failure alike.
305 #
306 # # from ban, so a reload failure reads as banFailed
307 # $self->_apply(13);
308 #
309 # # from flush
310 # $self->_apply(25);
311 #
312 # In testing mode nothing is written and no hook is run. What would have
313 # happened is recorded on the frontend's test_data as a hashref instead:
314 #
315 # {
316 # file => '/etc/blocklist.txt', # the path that would be written
317 # content => "10.0.0.1\n", # the rendered contents
318 # reload => '/usr/local/bin/reload-blocklist', # undef if unset
319 # }
320 29 ▶sub _apply {
Subroutine _apply: called CC=9 SCAR=22.2
321 29 my ( $self, $error_flag ) = @_;
322  
323 29 my $content = $self->_render;
324 29 my $reload = $self->{options}{reload};
325  
326 29 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 9 20 29
327 $self->{frontend_obj}->{test_data} = {
328 file => $self->{options}{file},
329 9 content => $content,
330 reload => $reload,
331 };
332 9 return;
333 }
334  
335 20 my $fh;
336 20 ▶ if ( !open( $fh, '>', $self->{options}{file} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (open $fh, ">", $self->{"options"}{"file"}) 0 20 20
337 0 $self->{error} = 31;
338 0 $self->{errorString} = 'could not open "' . $self->{options}{file} . '" for writing... ' . $!;
339 0 $self->warn;
340 0 return;
341 }
342 20 print( $fh $content );
343 20 close($fh);
344  
345 20 ▶ if ( defined($reload) && $reload ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $reload and $reload ne "") 15 5 20
Condition66%2/3
defined $reload and $reload ne ""
!ll&&!rl&&r
5015
MC/DC50%1/2
defined $reload and $reload ne ""
defined $reload $reload ne ""
Truth table66%2/3
A and B
A= defined $reloadB= $reload ne ""
ABresult
0X0
100
111
346 15 my $output = `$reload 2>&1`;
347 15 ▶ $output = '' if ( !defined($output) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $output 1 14 15
348 15 ▶ if ( $? != 0 ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($? != 0) { } 5 10 15
elsif ($self->{'options'}{'blank_reload_error'} and not $output =~ /\S/) { } 1 11 12
349 5 $self->{error} = $error_flag;
350 5 $self->{errorString} = 'reload command "' . $reload . '" failed... ' . $output;
351 5 $self->warn;
352 ▶ } elsif ( $self->{options}{blank_reload_error} && $output !~ /\S/ ) {
Condition100%3/3
$self->{"options"}{"blank_reload_error"} and not $output =~ /\S/
!ll&&!rl&&r
271
MC/DC100%2/2
$self->{"options"}{"blank_reload_error"} and not $output =~ /\S/
$self->{"options"}{"blank_reload_error"} not $output =~ /\S/
Truth table100%3/3
A and not(B)
A= $self->{"options"}{"blank_reload_error"}B= not $output =~ /\S/
ABresult
0X0
100
111
353 1 $self->{error} = $error_flag;
354 $self->{errorString}
355 1 = 'reload command "' . $reload . '" produced no output and blank_reload_error is true';
356 1 $self->warn;
357 }
358 }
359  
360 14 return;
361 } ## end sub _apply
362  
363 =head2 init
364  
365 Initiates the backend, rendering an initial (empty unless bans were
366 pre-seeded) file and running the reload hook.
367  
368 Note that the consumer must be configured to read the rendered file for any
369 of this to have an effect. See L</SYNOPSIS>.
370  
371 =cut
372  
373 10 ▶sub init {
Subroutine init: called CC=2 SCAR=8.1
Pod documented
374 10 my ( $self, %opts ) = @_;
375  
376 10 $self->errorblank;
377  
378 10 ▶ if ( $self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"inited"}) 0 10 10
379 0 $self->{error} = 18;
380 0 $self->{errorString} = 'backend has already been inited';
381 0 $self->warn;
382 }
383  
384 10 $self->_apply(12);
385  
386 8 $self->{inited} = 1;
387 } ## end sub init
388  
389 =head2 ban
390  
391 Bans an IP. The value of ban is validated as being a IPv4 or IPv6 address
392 and lowercased, then added to the ban list. The file is re-rendered and the
393 reload command, if one is configured, is run. Banning an already banned IP
394 is a noop.
395  
396 $fw_helper->ban( ban => $ip );
397  
398 =cut
399  
400 11 ▶sub ban {
Subroutine ban: called CC=8 SCAR=28.4
Pod documented
401 11 my ( $self, %opts ) = @_;
402  
403 11 $self->errorblank;
404  
405 11 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 11 11
406 0 $self->{error} = 1;
407 0 $self->{errorString} = 'backend has not been inited';
408 0 $self->warn;
409 0 return;
410 }
411  
412 11 ▶ if ( !defined( $opts{ban} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opts{'ban'}) { } 0 11 11
elsif (ref $opts{'ban'} ne '') { } 0 11 11
elsif (not $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv6_re\z/) { } 0 11 11
413 0 $self->{error} = 9;
414 0 $self->{errorString} = 'Nothing specified for the value ban';
415 0 $self->warn;
416 0 return;
417 } elsif ( ref( $opts{ban} ) ne '' ) {
418 0 $self->{error} = 10;
419 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
420 0 $self->warn;
421 0 return;
422 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition66%2/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv6_re\z/
l!l&&r!l&&!r
1010
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv6_re\z/
Truth table66%2/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv6_re\z/
ABresult
1X1
011
000
423 && $opts{ban} !~ /\A$IPv6_re\z/ )
424 {
425 0 $self->{error} = 10;
426 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
427 0 $self->warn;
428 0 return;
429 }
430  
431 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
432 11 $opts{ban} = lc( $opts{ban} );
433  
434 11 ▶ if ( $self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"banned"}{$opts{"ban"}}) 1 10 11
435 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 1 0 1
436 1 $self->{frontend_obj}->{test_data} = 'already banned';
437 }
438 1 return;
439 }
440  
441 10 $self->{banned}{ $opts{ban} } = 1;
442 10 $self->_apply(13);
443 } ## end sub ban
444  
445 =head2 unban
446  
447 Unbans an IP. The value of ban is validated as being a IPv4 or IPv6 address
448 and lowercased, then removed from the ban list. The file is re-rendered
449 without it and the reload command, if one is configured, is run. Unbanning
450 an IP that is not banned is a noop.
451  
452 $fw_helper->unban( ban => $ip );
453  
454 =cut
455  
456 3 ▶sub unban {
Subroutine unban: called CC=8 SCAR=32.2
Pod documented
457 3 my ( $self, %opts ) = @_;
458  
459 3 $self->errorblank;
460  
461 3 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 3 3
462 0 $self->{error} = 1;
463 0 $self->{errorString} = 'backend has not been inited';
464 0 $self->warn;
465 0 return;
466 }
467  
468 3 ▶ if ( !defined( $opts{ban} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opts{'ban'}) { } 0 3 3
elsif (ref $opts{'ban'} ne '') { } 0 3 3
elsif (not $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv6_re\z/) { } 0 3 3
469 0 $self->{error} = 9;
470 0 $self->{errorString} = 'Nothing specified for the value ban';
471 0 $self->warn;
472 0 return;
473 } elsif ( ref( $opts{ban} ) ne '' ) {
474 0 $self->{error} = 10;
475 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
476 0 $self->warn;
477 0 return;
478 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition66%2/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv6_re\z/
l!l&&r!l&&!r
210
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv6_re\z/
Truth table66%2/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::file_reload::IPv6_re\z/
ABresult
1X1
011
000
479 && $opts{ban} !~ /\A$IPv6_re\z/ )
480 {
481 0 $self->{error} = 10;
482 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
483 0 $self->warn;
484 0 return;
485 }
486  
487 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
488 3 $opts{ban} = lc( $opts{ban} );
489  
490 3 ▶ if ( !$self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"banned"}{$opts{"ban"}}) 0 3 3
491 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
492 0 $self->{frontend_obj}->{test_data} = 'not banned';
493 }
494 0 return;
495 }
496  
497 3 delete( $self->{banned}{ $opts{ban} } );
498 3 $self->_apply(14);
499 } ## end sub unban
500  
501 =head2 ban_cidr
502  
503 Bans a CIDR range by rendering it into the file the same way a single IP is.
504  
505 $fw_helper->ban_cidr(ban => '1.2.3.0/24');
506  
507 =cut
508  
509 2 ▶sub ban_cidr {
Subroutine ban_cidr: called CC=7 SCAR=30.7
Pod documented
510 2 my ( $self, %opts ) = @_;
511  
512 2 $self->errorblank;
513  
514 2 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 2 2
515 0 $self->{error} = 1;
516 0 $self->{errorString} = 'backend has not been inited';
517 0 $self->warn;
518 0 return;
519 }
520  
521 2 ▶ if ( !defined( $opts{ban} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opts{'ban'}) { } 0 2 2
elsif (ref $opts{'ban'} ne '') { } 0 2 2
elsif (not $self->_valid_cidr($opts{'ban'})) { } 0 2 2
522 0 $self->{error} = 9;
523 0 $self->{errorString} = 'Nothing specified for the value ban';
524 0 $self->warn;
525 0 return;
526 } elsif ( ref( $opts{ban} ) ne '' ) {
527 0 $self->{error} = 34;
528 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
529 0 $self->warn;
530 0 return;
531 } elsif ( !$self->_valid_cidr( $opts{ban} ) ) {
532 0 $self->{error} = 34;
533 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 CIDR';
534 0 $self->warn;
535 0 return;
536 }
537  
538 # lowercase so the same IPv6 CIDR in differing cases can't result in duplicate entries
539 2 $opts{ban} = lc( $opts{ban} );
540  
541 2 ▶ if ( $self->{banned_cidr}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"banned_cidr"}{$opts{"ban"}}) 0 2 2
542 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
543 0 $self->{frontend_obj}->{test_data} = 'already banned';
544 }
545 0 return;
546 }
547  
548 2 $self->{banned_cidr}{ $opts{ban} } = 1;
549 2 $self->_apply(32);
550 } ## end sub ban_cidr
551  
552 =head2 unban_cidr
553  
554 Unbans a CIDR range by re-rendering the file without it.
555  
556 $fw_helper->unban_cidr(ban => '1.2.3.0/24');
557  
558 =cut
559  
560 1 ▶sub unban_cidr {
Subroutine unban_cidr: called CC=7 SCAR=30.7
Pod documented
561 1 my ( $self, %opts ) = @_;
562  
563 1 $self->errorblank;
564  
565 1 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 1 1
566 0 $self->{error} = 1;
567 0 $self->{errorString} = 'backend has not been inited';
568 0 $self->warn;
569 0 return;
570 }
571  
572 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
573 0 $self->{error} = 9;
574 0 $self->{errorString} = 'Nothing specified for the value ban';
575 0 $self->warn;
576 0 return;
577 } elsif ( ref( $opts{ban} ) ne '' ) {
578 0 $self->{error} = 34;
579 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
580 0 $self->warn;
581 0 return;
582 } elsif ( !$self->_valid_cidr( $opts{ban} ) ) {
583 0 $self->{error} = 34;
584 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 CIDR';
585 0 $self->warn;
586 0 return;
587 }
588  
589 # lowercase so the same IPv6 CIDR in differing cases can't result in duplicate entries
590 1 $opts{ban} = lc( $opts{ban} );
591  
592 1 ▶ if ( !$self->{banned_cidr}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"banned_cidr"}{$opts{"ban"}}) 0 1 1
593 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
594 0 $self->{frontend_obj}->{test_data} = 'not banned';
595 }
596 0 return;
597 }
598  
599 1 delete( $self->{banned_cidr}{ $opts{ban} } );
600 1 $self->_apply(33);
601 } ## end sub unban_cidr
602  
603 =head2 list_cidr
604  
605 List banned CIDR ranges.
606  
607 my @banned_cidrs = $fw_helper->list_cidr;
608  
609 =cut
610  
611 2 ▶sub list_cidr {
Subroutine list_cidr: called CC=2 SCAR=7.0
Pod documented
612 2 my ( $self, %opts ) = @_;
613  
614 2 $self->errorblank;
615  
616 2 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 2 0 2
617 2 $self->{frontend_obj}->{test_data} = 'list_cidr';
618 }
619  
620 2 return keys( %{ $self->{banned_cidr} } );
621 }
622  
623 =head2 list
624  
625 List banned IPs. Returns an array of the currently banned single IPs. CIDR
626 ranges are not included; for those see L</list_cidr>.
627  
628 my @banned = $fw_helper->list;
629  
630 =cut
631  
632 1 ▶sub list {
Subroutine list: called CC=2 SCAR=7.0
Pod documented
633 1 my ( $self, %opts ) = @_;
634  
635 1 $self->errorblank;
636  
637 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 1 0 1
638 1 $self->{frontend_obj}->{test_data} = 'list';
639 }
640  
641 1 return keys( %{ $self->{banned} } );
642 }
643  
644 =head2 re_init
645  
646 Re-renders the file from the retained ban list and runs the reload hook. As
647 the file is always rendered from full state, nothing needs tearing down
648 first; a single re-render restores everything.
649  
650 =cut
651  
652 1 ▶sub re_init {
Subroutine re_init: called CC=1 SCAR=0.0
Pod documented
653 1 my ( $self, %opts ) = @_;
654  
655 1 $self->errorblank;
656  
657 # render the current ban list back out; the file is authored purely from
658 # state so this restores everything in one write
659 1 $self->_apply(16);
660  
661 1 $self->{inited} = 1;
662 } ## end sub re_init
663  
664 =head2 teardown
665  
666 Removes the rendered file (or empties it when remove_on_teardown is false)
667 and runs the reload hook.
668  
669 =cut
670  
671 3 ▶sub teardown {
Subroutine teardown: called CC=9 SCAR=24.2
Pod documented
672 3 my ( $self, %opts ) = @_;
673  
674 3 $self->errorblank;
675  
676 3 $self->{inited} = 0;
677  
678 3 ▶ if ( $self->{options}{remove_on_teardown} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"options"}{"remove_on_teardown"}) 2 1 3
679 2 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 1 1 2
680 $self->{frontend_obj}->{test_data} = {
681 file => $self->{options}{file},
682 content => undef,
683 reload => $self->{options}{reload},
684 1 };
685 } else {
686 # unlink is best effort; a missing file is already the desired state
687 1 unlink( $self->{options}{file} );
688 1 my $reload = $self->{options}{reload};
689 1 ▶ if ( defined($reload) && $reload ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $reload and $reload ne "") 1 0 1
Condition33%1/3
defined $reload and $reload ne ""
!ll&&!rl&&r
001
MC/DC0%0/2
defined $reload and $reload ne ""
defined $reload $reload ne ""
Truth table33%1/3
A and B
A= defined $reloadB= $reload ne ""
ABresult
0X0
100
111
690 1 my $output = `$reload 2>&1`;
691 1 ▶ $output = '' if ( !defined($output) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $output 0 1 1
692 1 ▶ if ( $? != 0 ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($? != 0) { } 0 1 1
elsif ($self->{'options'}{'blank_reload_error'} and not $output =~ /\S/) { } 0 1 1
693 0 $self->{error} = 17;
694 0 $self->{errorString} = 'reload command "' . $reload . '" failed... ' . $output;
695 0 $self->warn;
696 ▶ } elsif ( $self->{options}{blank_reload_error} && $output !~ /\S/ ) {
Condition33%1/3
$self->{"options"}{"blank_reload_error"} and not $output =~ /\S/
!ll&&!rl&&r
010
MC/DC0%0/2
$self->{"options"}{"blank_reload_error"} and not $output =~ /\S/
$self->{"options"}{"blank_reload_error"} not $output =~ /\S/
Truth table33%1/3
A and not(B)
A= $self->{"options"}{"blank_reload_error"}B= not $output =~ /\S/
ABresult
0X0
100
111
697 0 $self->{error} = 17;
698 $self->{errorString}
699 0 = 'reload command "' . $reload . '" produced no output and blank_reload_error is true';
700 0 $self->warn;
701 }
702 }
703 }
704 2 return;
705 } ## end if ( $self->{options}{remove_on_teardown...})
706  
707 # leave an empty (header/footer only) file behind; both the single IP and
708 # CIDR state are stashed so the empty render omits them but they survive
709 1 my %saved_banned = %{ $self->{banned} };
710 1 my %saved_banned_cidr = %{ $self->{banned_cidr} };
711 1 $self->{banned} = {};
712 1 $self->{banned_cidr} = {};
713 1 $self->_apply(17);
714 1 $self->{banned} = \%saved_banned;
715 1 $self->{banned_cidr} = \%saved_banned_cidr;
716 } ## end sub teardown
717  
718 =head2 stop
719  
720 Alias for L</teardown>.
721  
722 =cut
723  
724 0 ▶sub stop {
Subroutine stop: not called CC=1 SCAR=6.9
Pod documented
725 0 my ( $self, %opts ) = @_;
726  
727 0 return $self->teardown(%opts);
728 }
729  
730 =head2 check
731  
732 If a C<check> command is configured, runs it and treats a zero exit as
733 healthy. Otherwise verifies the rendered file still exists.
734  
735 =cut
736  
737 17 ▶sub check {
Subroutine check: called CC=7 SCAR=19.7
Pod documented
738 17 my ( $self, %opts ) = @_;
739  
740 17 $self->errorblank;
741  
742 17 ▶ if ( defined( $self->{options}{check} ) && $self->{options}{check} ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"options"}{"check"} and $self->{"options"}{"check"} ne "") 3 14 17
Condition66%2/3
defined $self->{"options"}{"check"} and $self->{"options"}{"check"} ne ""
!ll&&!rl&&r
1403
MC/DC50%1/2
defined $self->{"options"}{"check"} and $self->{"options"}{"check"} ne ""
defined $self->{"options"}{"check"} $self->{"options"}{"check"} ne ""
Truth table66%2/3
A and B
A= defined $self->{"options"}{"check"}B= $self->{"options"}{"check"} ne ""
ABresult
0X0
100
111
743 3 my $command = $self->{options}{check};
744 3 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 3 3
745 0 $self->{frontend_obj}->{test_data} = $command;
746 0 return 1;
747 }
748 3 my $output = `$command 2>&1`;
749 3 ▶ return $? == 0 ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$? == 0 ? : 2 1 3
750 }
751  
752 14 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 7 7 14
753 7 $self->{frontend_obj}->{test_data} = 'check';
754 7 return 1;
755 }
756  
757 7 ▶ return ( -e $self->{options}{file} ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
-e $self->{'options'}{'file'} ? : 6 1 7
758 } ## end sub check
759  
760 =head2 flush
761  
762 Removes all currently banned IPs at once by clearing the ban list and
763 re-rendering the now empty file.
764  
765 =cut
766  
767 1 ▶sub flush {
Subroutine flush: called CC=2 SCAR=8.3
Pod documented
768 1 my ( $self, %opts ) = @_;
769  
770 1 $self->errorblank;
771  
772 1 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 1 1
773 0 $self->{error} = 1;
774 0 $self->{errorString} = 'backend has not been inited';
775 0 $self->warn;
776 0 return;
777 }
778  
779 # the file is re-rendered from full state, so clearing both hashes removes
780 # every single IP and CIDR ban at once
781 1 $self->{banned} = {};
782 1 $self->{banned_cidr} = {};
783 1 $self->_apply(25);
784 } ## end sub flush
785  
786 =head1 ERROR CODES / FLAGS
787  
788 Error handling is provided by L<Error::Helper>. All
789 errors are considered fatal.
790  
791 =head2 1, notInited
792  
793 The backend has not been inited yet.
794  
795 =head2 8, optionsNotHash
796  
797 The item passed to new for options is not a hash.
798  
799 =head2 9, noBanItem
800  
801 No IP or CIDR range specified to ban or unban.
802  
803 =head2 10, banItemNotIP
804  
805 The item to ban is not an IP. Either wrong ref type or regexp
806 test using L<Regexp::IPv4> and L<Regexp::IPv6> failed.
807  
808 =head2 12, backendInitError
809  
810 Failed to init the backend.
811  
812 =head2 13, banFailed
813  
814 Failed to ban the item.
815  
816 =head2 14, unbanFailed
817  
818 Failed to unban the item.
819  
820 =head2 15, listFailed
821  
822 Failed to get a list of bans.
823  
824 =head2 16, reInitFailed
825  
826 Failed to re_init the backend.
827  
828 =head2 17, teardownFailed
829  
830 Failed to teardown the backend.
831  
832 =head2 18, alreadyInited
833  
834 init called, but the backend has already been inited.
835  
836 =head2 24, checkFailed
837  
838 The backend check raised an error.
839  
840 =head2 25, flushFailed
841  
842 Failed to flush the bans.
843  
844 =head2 30, fileNotDefined
845  
846 The option file is undef or blank.
847  
848 =head2 31, fileWriteFailed
849  
850 Could not open the file for writing.
851  
852 =head2 32, banCidrFailed
853  
854 Failed to ban the CIDR range.
855  
856 =head2 33, unbanCidrFailed
857  
858 Failed to unban the CIDR range.
859  
860 =head2 34, cidrItemNotCidr
861  
862 The item to ban is not a CIDR range. Either wrong ref type or it is not an
863 IPv4 or IPv6 address followed by a prefix length valid for its family.
864  
865 =head2 35, cidrNotSupported
866  
867 The backend does not support CIDR bans.
868  
869 =head2 36, listCidrFailed
870  
871 Failed to get a list of CIDR bans.
872  
873 =head1 AUTHOR
874  
875 Zane C. Bowers-Hadley, C<< <vvelox at vvelox.ent> >>
876  
877 =head1 LICENSE AND COPYRIGHT
878  
879 This software is Copyright (c) 2023 by Zane C. Bowers-Hadley.
880  
881 This is free software, licensed under:
882  
883 The GNU Lesser General Public License, Version 2.1, February 1999
884  
885 =cut
886  
887 1 1; # End of Net::Firewall::BlockerHelper::backends::file_reload
« BlockerHelper/backends/cloud_armor.pm ↑ Summary BlockerHelper/backends/shell.pm »