BlockerHelper/backends/hosts_deny.pm

filter: Statementstmt 55.8% 139 / 249 Branchbran 56.8% 50 / 88 Conditioncond 38.8% 7 / 18 MC/DCmcdc 0.0% 0 / 12 Subroutinesub 73.0% 19 / 26 Podpod 100% 13 / 13 totaltotal 56.1% 228 / 406 CC 53 SCAR 27.7
CC
53
Cov
55%
_apply
37.5
unban
27.0
ban
25.0
CRAP 16.0
« BlockerHelper/backends/azure.pm ↑ Summary BlockerHelper.pm »
1 package Net::Firewall::BlockerHelper::backends::hosts_deny;
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 1 ▶use Fcntl qw(:flock);
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 =head1 NAME
12  
13 Net::Firewall::BlockerHelper::backends::hosts_deny - TCP wrappers hosts.deny backend.
14  
15 =head1 VERSION
16  
17 Version 0.2.0
18  
19 =cut
20  
21 1 our $VERSION = '0.2.0';
22  
23 =head1 SYNOPSIS
24  
25 use Net::Firewall::BlockerHelper;
26  
27 my $fw_helper = Net::Firewall::BlockerHelper->new(
28 backend => 'hosts_deny',
29 name => 'sshd',
30 options => { daemon => 'sshd' },
31 );
32  
33 $fw_helper->init_backend;
34 $fw_helper->ban( ban => '1.2.3.4' );
35 $fw_helper->unban( ban => '1.2.3.4' );
36 $fw_helper->teardown;
37  
38 =head1 DESCRIPTION
39  
40 Blocks IPs via TCP wrappers by maintaining a block of entries in
41 C</etc/hosts.deny>. Only libwrap aware daemons (those linked against
42 libwrap or launched via tcpd) honor this; it is not a packet filter.
43  
44 The backend owns a single marked region of the file delimited by
45  
46 # BEGIN Net::Firewall::BlockerHelper <prefix>_<name>
47 ...
48 # END Net::Firewall::BlockerHelper <prefix>_<name>
49  
50 Everything outside that region is preserved untouched, so hand maintained
51 rules and other instances (with a different prefix/name) coexist. Each ban
52 is rendered as a C<< <daemon> : <ip> >> line, with IPv6 addresses bracketed,
53 C<< <daemon> : [<ip>] >>, as that is the only IPv6 form libwrap matches. No
54 reload is needed as libwrap reads the file on each connection.
55  
56 Updates are done under an exclusive flock(2) on C<< <file>.lock >>, which is
57 created if needed and left in place, so concurrent processes updating the
58 same file serialize rather than losing each others changes. The new contents
59 are written to a temp file in the same directory and renamed into place, so
60 the update is atomic and a partial file can never be seen. The mode of the
61 file being replaced is carried over.
62  
63 =head1 METHODS
64  
65 =head2 new
66  
67 Initiates the object. Not really meant to be used directly, but instead
68 called via L<Net::Firewall::BlockerHelper>.
69  
70 - options :: A hash of options. See below.
71 - name :: Required. Used, with prefix, to tag this instance's region.
72 - prefix :: Defaults to 'kur'. Combined with name for the region tag.
73  
74 The options hash accepts the following.
75  
76 - file :: Path to the hosts.deny file.
77 - Default :: /etc/hosts.deny
78  
79 - daemon :: The daemon_list portion of each rule. 'ALL' blocks the IP for
80 every libwrap daemon; a specific name (eg 'sshd') scopes it.
81 - Default :: ALL
82  
83 All errors are considered fatal, meaning if new fails it will die.
84  
85 =cut
86  
87 2 ▶sub new {
Subroutine new: called CC=10 SCAR=26.6
Pod documented
88 2 my ( $blank, %opts ) = @_;
89  
90 2 my $self = {
91 perror => undef,
92 error => undef,
93 errorLine => undef,
94 errorFilename => undef,
95 errorString => "",
96 errorExtra => {
97 all_errors_fatal => 1,
98 # all_fatal is what Error::Helper 2.1.0 actually checks; all_errors_fatal
99 # is kept for the name documented in its POD
100 all_fatal => 1,
101 flags => {
102 1 => 'notInited',
103 7 => 'invalidName',
104 8 => 'optionsNotHash',
105 9 => 'noBanItem',
106 10 => 'banItemNotIP',
107 12 => 'backendInitError',
108 13 => 'banFailed',
109 14 => 'unbanFailed',
110 15 => 'listFailed',
111 16 => 'reInitFailed',
112 17 => 'teardownFailed',
113 18 => 'alreadyInited',
114 24 => 'checkFailed',
115 25 => 'flushFailed',
116 31 => 'fileWriteFailed',
117 32 => 'banCidrFailed',
118 33 => 'unbanCidrFailed',
119 34 => 'cidrItemNotCidr',
120 35 => 'cidrNotSupported',
121 36 => 'listCidrFailed',
122 },
123 fatal_flags => {},
124 perror_not_fatal => 0,
125 },
126 options => {},
127 ports => [],
128 protocols => [],
129 testing => undef,
130 test_data => undef,
131 test_outside => '',
132 prefix => 'kur',
133 name => undef,
134 frontend_obj => undef,
135 inited => 0,
136 banned => {},
137 cidr_supported => 0,
138 };
139 2 bless $self;
140  
141 2 ▶ if ( defined( $opts{testing} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"testing"}) 1 1 2
142 1 $self->{testing} = $opts{testing};
143 }
144 2 ▶ if ( defined( $opts{frontend_obj} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"frontend_obj"}) 2 0 2
145 2 $self->{frontend_obj} = $opts{frontend_obj};
146 }
147 2 ▶ if ( defined( $opts{prefix} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"prefix"}) 2 0 2
148 2 $self->{prefix} = $opts{prefix};
149 }
150  
151 2 ▶ if ( !defined( $opts{name} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $opts{"name"}) 0 2 2
152 0 $self->{perror} = 1;
153 0 $self->{error} = 7;
154 0 $self->{errorString} = 'name is undef';
155 0 $self->warn;
156 }
157 2 $self->{name} = $opts{name};
158  
159 2 ▶ if ( defined( $opts{options} ) && ref( $opts{options} ) ne 'HASH' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opts{'options'} and ref $opts{'options'} ne 'HASH') { } 0 2 2
elsif (defined $opts{'options'}) { } 2 0 2
Condition33%1/3
defined $opts{"options"} and ref $opts{"options"} ne "HASH"
!ll&&!rl&&r
020
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
160 0 $self->{perror} = 1;
161 0 $self->{error} = 8;
162 0 $self->{errorString} = 'ref for options is "' . ref( $opts{options} ) . '" and not HASH';
163 0 $self->warn;
164 } elsif ( defined( $opts{options} ) ) {
165 2 $self->{options} = $opts{options};
166 }
167  
168 2 ▶ $self->{options}{file} = '/etc/hosts.deny' if ( !defined( $self->{options}{file} ) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"options"}{"file"} 1 1 2
169 2 ▶ $self->{options}{daemon} = 'ALL' if ( !defined( $self->{options}{daemon} ) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"options"}{"daemon"} 1 1 2
170  
171 2 return $self;
172 } ## end sub new
173  
174 # Internal helper. Returns the pair of comment lines that fence off this
175 # instance's region of the hosts.deny file.
176 #
177 # The file is shared with whatever else the admin has put in it and possibly
178 # with other instances of this backend, so each instance only ever owns the
179 # span between its own markers. The tag embeds the prefix and the name, which
180 # together are unique per instance, so two instances writing to the same file
181 # do not see or disturb each other's entries.
182 #
183 # Takes no arguments.
184 #
185 # Returns a two element list of the begin line and the end line, in that
186 # order, neither with a trailing newline. Both are ordinary hosts.deny
187 # comments, so a region left behind by a crashed process is inert rather than
188 # something libwrap tries to parse.
189 #
190 # my ( $begin, $end ) = $self->_markers;
191 #
192 # # with prefix "kur" and name "ssh"
193 # # $begin is '# BEGIN Net::Firewall::BlockerHelper kur_ssh'
194 # # $end is '# END Net::Firewall::BlockerHelper kur_ssh'
195 16 ▶sub _markers {
Subroutine _markers: called CC=1 SCAR=0.0
196 16 my ($self) = @_;
197  
198 16 my $tag = 'Net::Firewall::BlockerHelper ' . $self->{prefix} . '_' . $self->{name};
199 16 return ( '# BEGIN ' . $tag, '# END ' . $tag );
200 }
201  
202 # Internal helper. Renders the single hosts.deny rule line that blocks the
203 # passed IP for the configured daemon.
204 #
205 # IPv6 addresses are wrapped in square brackets. libwrap only recognizes the
206 # [address] form for IPv6, and a bare IPv6 client pattern is not an error, it
207 # simply never matches anything, so an unbracketed address would look like a
208 # working ban while blocking nothing at all.
209 #
210 # Args:
211 #
212 # ip - The address to block, as a plain string. Expected to be an already
213 # validated and lowercased IPv4 or IPv6 address, such as "10.0.0.1"
214 # or "2001:db8::1". The family is decided by looking for a colon, so
215 # anything holding one is treated as IPv6.
216 #
217 # Returns the rule line as a string with no trailing newline, in the
218 # "<daemon> : <client>" form that hosts.deny expects. The daemon side comes
219 # from the daemon option and is emitted as configured, which is "ALL" by
220 # default.
221 #
222 # $self->_render_entry('10.0.0.1'); # 'ALL : 10.0.0.1'
223 # $self->_render_entry('2001:db8::1'); # 'ALL : [2001:db8::1]'
224 #
225 # # with the daemon option set to 'sshd'
226 # $self->_render_entry('10.0.0.1'); # 'sshd : 10.0.0.1'
227 12 ▶sub _render_entry {
Subroutine _render_entry: called CC=2 SCAR=6.9
228 12 my ( $self, $ip ) = @_;
229  
230 12 ▶ my $addr = ( $ip =~ /:/ ) ? '[' . $ip . ']' : $ip;
Branch: 1 branch
BranchTrueFalseTotal
$ip =~ /:/ ? : 1 11 12
231 12 return $self->{options}{daemon} . ' : ' . $addr;
232 }
233  
234 # Internal helper. Builds this instance's entire marked region, the begin
235 # marker, one rule line per banned IP, and the end marker, from the current
236 # contents of the internal ban list.
237 #
238 # The IPs are sorted so that the same set of bans always renders to the same
239 # bytes. Without that the order would follow the hash order and the file would
240 # be rewritten on unrelated operations, and the region recorded in test_data
241 # could not be compared against a fixed expected string.
242 #
243 # Takes no arguments; the bans come from the object's banned hash.
244 #
245 # Returns the region as a single string ending in a newline, ready to be
246 # concatenated onto the preserved part of the file. When nothing is banned it
247 # returns the empty string rather than an empty pair of markers, so a file
248 # that has had everything unbanned is left with no trace of this instance in
249 # it at all.
250 #
251 # # with 10.0.0.1 and 2001:db8::1 banned and the daemon option at "ALL"
252 # my $block = $self->_render_block;
253 #
254 # # # BEGIN Net::Firewall::BlockerHelper kur_ssh
255 # # ALL : 10.0.0.1
256 # # ALL : [2001:db8::1]
257 # # # END Net::Firewall::BlockerHelper kur_ssh
258 #
259 # # with nothing banned
260 # my $block = $self->_render_block; # ''
261 8 ▶sub _render_block {
Subroutine _render_block: called CC=3 SCAR=11.0
262 8 my ($self) = @_;
263  
264 8 my @ips = sort( keys( %{ $self->{banned} } ) );
265 8 ▶ return '' if ( !@ips );
Branch: 1 branch
BranchTrueFalseTotal
unless @ips 3 5 8
266  
267 5 my ( $begin, $end ) = $self->_markers;
268 5 my @lines = ($begin);
269 5 foreach my $ip (@ips) {
270 7 push( @lines, $self->_render_entry($ip) );
271 }
272 5 push( @lines, $end );
273  
274 5 return join( "\n", @lines ) . "\n";
275 } ## end sub _render_block
276  
277 # Internal helper. Given the full contents of the hosts.deny file, returns
278 # them with this instance's marked region cut out and everything else left
279 # exactly as it was.
280 #
281 # This is the half of the read-modify-write that preserves the admin's own
282 # rules and any other instance's region. Only the span from this instance's
283 # begin marker through its end marker is removed, matched non greedily so that
284 # two regions in the same file cannot be swallowed as one. The markers are
285 # escaped with \Q..\E because the tag holds :: and . characters that would
286 # otherwise be read as regex metacharacters.
287 #
288 # Args:
289 #
290 # content - The full file contents as a single string, normally straight
291 # from _read. May be the empty string, may hold no region for
292 # this instance, and may hold regions belonging to other
293 # instances; none of those are errors.
294 #
295 # Returns the contents with the region removed, as a string. When there is no
296 # region for this instance the input comes back unchanged, so this is safe to
297 # call unconditionally. The argument itself is not modified; the copy taken
298 # off @_ is what gets edited.
299 #
300 # # a file holding this instance's region plus an admin rule
301 # my $outside = $self->_strip_block($content);
302 #
303 # # in: "sshd : 192.0.2.5\n"
304 # # . "# BEGIN Net::Firewall::BlockerHelper kur_ssh\n"
305 # # . "ALL : 10.0.0.1\n"
306 # # . "# END Net::Firewall::BlockerHelper kur_ssh\n"
307 # # out: "sshd : 192.0.2.5\n"
308 #
309 # # nothing of ours in the file, so nothing changes
310 # $self->_strip_block("sshd : 192.0.2.5\n"); # "sshd : 192.0.2.5\n"
311 8 ▶sub _strip_block {
Subroutine _strip_block: called CC=1 SCAR=0.0
312 8 my ( $self, $content ) = @_;
313  
314 8 my ( $begin, $end ) = $self->_markers;
315 # \Q..\E so the :: in the tag is treated literally rather than as regex
316 8 $content =~ s/^\Q$begin\E\n.*?^\Q$end\E\n//ms;
317  
318 8 return $content;
319 } ## end sub _strip_block
320  
321 # Internal helper. Slurps the hosts.deny file and returns its contents.
322 #
323 # Every failure mode collapses to the empty string rather than an error: the
324 # file not existing, not being openable, and being empty are all treated the
325 # same. That is deliberate. A missing hosts.deny is the normal state on a host
326 # that has never had one, and the caller's next step is to write the file out
327 # in full anyway, so there is nothing an error here would let it do
328 # differently. A file that exists but cannot be read will fail loudly at the
329 # write instead, with an error code that names the operation that triggered
330 # it.
331 #
332 # In testing mode nothing is touched on disk and the test_outside attribute is
333 # returned instead, which is how a test stands in a hosts.deny that already
334 # has other content in it.
335 #
336 # Takes no arguments.
337 #
338 # Returns the file contents as a single string, or the empty string. Never
339 # returns undef, so the result can go straight into _strip_block or a string
340 # comparison without a defined check.
341 #
342 # my $current = $self->_read;
343 #
344 # # the usual read-modify-write shape
345 # my $outside = $self->_strip_block( $self->_read );
346 11 ▶sub _read {
Subroutine _read: called CC=5 SCAR=16.6
347 11 my ($self) = @_;
348  
349 11 ▶ return $self->{test_outside} if ( $self->{testing} );
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"testing"} 3 8 11
350  
351 8 ▶ return '' if ( !-e $self->{options}{file} );
Branch: 1 branch
BranchTrueFalseTotal
unless -e $self->{"options"}{"file"} 0 8 8
352  
353 8 my $fh;
354 8 ▶ if ( !open( $fh, '<', $self->{options}{file} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (open $fh, "<", $self->{"options"}{"file"}) 0 8 8
355 0 return '';
356 }
357 8 local $/ = undef;
358 8 my $content = <$fh>;
359 8 close($fh);
360  
361 8 ▶ return defined($content) ? $content : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $content ? : 8 0 8
362 } ## end sub _read
363  
364 # Internal helper. Pushes the current ban list out to the hosts.deny file,
365 # refreshing this instance's region and preserving everything else in the
366 # file byte for byte. This is the only place the file is written, so init,
367 # ban, unban, re_init, teardown, and flush all funnel through it.
368 #
369 # The whole read-modify-write runs under an exclusive flock on a sidecar
370 # <file>.lock, taken before the read so that the modify is based on what is
371 # actually current. Two processes banning at the same time therefore serialize
372 # instead of each writing back a copy based on a stale read and losing the
373 # other's entry. The lock is on a separate file rather than on hosts.deny
374 # itself because hosts.deny gets replaced by rename, which would drop a lock
375 # held on the old inode.
376 #
377 # The new contents go to a temp file in the same directory that is then
378 # renamed into place. Rename within a filesystem is atomic, so a reader never
379 # sees a half written hosts.deny and a crash mid write leaves the original
380 # intact rather than a truncated file that would silently stop blocking
381 # anything. The mode of the file being replaced is carried over to the temp
382 # file first, so an admin's tightened permissions survive the swap.
383 #
384 # If the rendered contents match what is already there the file is left alone
385 # entirely, which keeps the mtime stable and avoids pointless rewrites when a
386 # ban is re-applied.
387 #
388 # Failures do not die. They set the error to the passed code, set errorString,
389 # and warn, so the problem surfaces named after whatever the caller was doing
390 # rather than as a generic write failure.
391 #
392 # Args:
393 #
394 # error_flag - The numeric error code to raise on failure, so the error
395 # reads as the operation that triggered the write. Callers
396 # pass the code matching themselves: 12 backendInitError from
397 # init, 13 banFailed from ban, 14 unbanFailed from unban, 16
398 # reInitFailed from re_init, 17 teardownFailed from teardown,
399 # and 25 flushFailed from flush. Optional; defaults to 31,
400 # fileWriteFailed, which no current caller relies on since
401 # they all pass a code.
402 #
403 # Returns nothing, on success and on failure alike. The caller checks the
404 # error state rather than a return value.
405 #
406 # # from ban, so a write failure reads as banFailed
407 # $self->_apply(13);
408 #
409 # # from teardown
410 # $self->_apply(17);
411 #
412 # In testing mode nothing is locked, written, or renamed. The rendered result
413 # is recorded on the frontend's test_data as a hashref instead, letting a test
414 # assert on the exact file that would have been written:
415 #
416 # {
417 # file => '/etc/hosts.deny', # the path that would be written
418 # block => "# BEGIN ...\nALL : 10.0.0.1\n# END ...\n",
419 # content => "sshd : 192.0.2.5\n# BEGIN ...\n", # preserved + block
420 # }
421 8 ▶sub _apply {
Subroutine _apply: called CC=15 SCAR=36.2
422 8 my ( $self, $error_flag ) = @_;
423  
424 8 ▶ $error_flag = 31 if ( !defined($error_flag) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $error_flag 0 8 8
425  
426 8 my $file = $self->{options}{file};
427  
428 8 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 3 5 8
429 3 my $outside = $self->_strip_block( $self->_read );
430 3 my $block = $self->_render_block;
431 3 ▶ $outside .= "\n" if ( $outside ne '' && $outside !~ /\n\z/ );
Branch: 1 branch
BranchTrueFalseTotal
if $outside ne "" and not $outside =~ /\n\z/ 0 3 3
Condition33%1/3
$outside ne "" and not $outside =~ /\n\z/
!ll&&!rl&&r
300
MC/DC0%0/2
$outside ne "" and not $outside =~ /\n\z/
$outside ne "" not $outside =~ /\n\z/
Truth table33%1/3
A and not(B)
A= $outside ne ""B= not $outside =~ /\n\z/
ABresult
0X0
100
111
432 $self->{frontend_obj}->{test_data} = {
433 3 file => $file,
434 block => $block,
435 content => $outside . $block,
436 };
437 3 return;
438 }
439  
440 # hold an exclusive lock across the read-modify-write so concurrent
441 # processes updating the same file serialize rather than clobbering
442 5 my $lock_fh;
443 5 ▶ if ( !open( $lock_fh, '>>', $file . '.lock' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (open $lock_fh, ">>", $file . '.lock') 0 5 5
444 0 $self->{error} = $error_flag;
445 0 $self->{errorString} = 'could not open the lock file "' . $file . '.lock"... ' . $!;
446 0 $self->warn;
447 0 return;
448 }
449 5 ▶ if ( !flock( $lock_fh, LOCK_EX ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (flock $lock_fh, 2) 0 5 5
450 0 $self->{error} = $error_flag;
451 0 $self->{errorString} = 'could not get an exclusive lock on "' . $file . '.lock"... ' . $!;
452 0 $self->warn;
453 0 return;
454 }
455  
456 # the read happens under the lock so the modify is based on what is
457 # actually current
458 5 my $current = $self->_read;
459 5 my $outside = $self->_strip_block($current);
460 5 my $block = $self->_render_block;
461  
462 # make sure the preserved content ends with a newline so our block does
463 # not get glued onto its last line; beyond that it is left byte for byte
464 # as is
465 5 ▶ $outside .= "\n" if ( $outside ne '' && $outside !~ /\n\z/ );
Branch: 1 branch
BranchTrueFalseTotal
if $outside ne "" and not $outside =~ /\n\z/ 0 5 5
Condition33%1/3
$outside ne "" and not $outside =~ /\n\z/
!ll&&!rl&&r
050
MC/DC0%0/2
$outside ne "" and not $outside =~ /\n\z/
$outside ne "" not $outside =~ /\n\z/
Truth table33%1/3
A and not(B)
A= $outside ne ""B= not $outside =~ /\n\z/
ABresult
0X0
100
111
466 5 my $content = $outside . $block;
467  
468 # nothing would change, so leave the file untouched
469 5 ▶ if ( $content eq $current ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content eq $current) 1 4 5
470 1 close($lock_fh);
471 1 return;
472 }
473  
474 # write the new contents to a temp file in the same directory and rename
475 # it into place, making the change atomic; a reader or a crash mid write
476 # can never result in a partial file being seen or left
477 4 my $tmp = $file . '.tmp.' . $$;
478 4 my $fh;
479 4 ▶ if ( !open( $fh, '>', $tmp ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (open $fh, ">", $tmp) 0 4 4
480 0 $self->{error} = $error_flag;
481 0 $self->{errorString} = 'could not open "' . $tmp . '" for writing... ' . $!;
482 0 $self->warn;
483 0 return;
484 }
485 4 ▶ if ( !print( $fh $content ) or !close($fh) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (print $fh $content and close $fh) 0 4 4
Condition33%1/3
print $fh $content and close $fh
!ll&&!rl&&r
004
MC/DC0%0/2
print $fh $content and close $fh
print $fh $content close $fh
Truth table33%1/3
A and B
A= print $fh $contentB= close $fh
ABresult
0X0
100
111
486 0 my $save_err = $!;
487 0 unlink($tmp);
488 0 $self->{error} = $error_flag;
489 0 $self->{errorString} = 'failed writing "' . $tmp . '"... ' . $save_err;
490 0 $self->warn;
491 0 return;
492 }
493  
494 # carry the mode of the file being replaced over to the new one
495 4 ▶ if ( -e $file ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-e $file) 4 0 4
496 4 chmod( ( stat($file) )[2] & 07777, $tmp );
497 }
498  
499 4 ▶ if ( !rename( $tmp, $file ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (rename $tmp, $file) 0 4 4
500 0 my $save_err = $!;
501 0 unlink($tmp);
502 0 $self->{error} = $error_flag;
503 0 $self->{errorString} = 'could not rename "' . $tmp . '" into place as "' . $file . '"... ' . $save_err;
504 0 $self->warn;
505 0 return;
506 }
507  
508 4 close($lock_fh);
509  
510 4 return;
511 } ## end sub _apply
512  
513 =head2 init
514  
515 Initiates the backend. Removes any stale region for this instance from the
516 file. The markers are only written when there is something banned, so with
517 no bans nothing is added.
518  
519 =cut
520  
521 2 ▶sub init {
Subroutine init: called CC=2 SCAR=8.1
Pod documented
522 2 my ( $self, %opts ) = @_;
523  
524 2 $self->errorblank;
525  
526 2 ▶ if ( $self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"inited"}) 0 2 2
527 0 $self->{error} = 18;
528 0 $self->{errorString} = 'backend has already been inited';
529 0 $self->warn;
530 }
531  
532 2 $self->_apply(12);
533  
534 2 $self->{inited} = 1;
535 } ## end sub init
536  
537 =head2 ban
538  
539 Bans an IP. The value of ban is validated as being a IPv4 or IPv6 address
540 and lowercased, then added to the ban list. This instance's marked region in
541 the hosts.deny file is rewritten with a C<< <daemon> : <ip> >> line for each
542 banned IP; content outside the region is preserved. Banning an already
543 banned IP is a noop.
544  
545 $fw_helper->ban( ban => $ip );
546  
547 =cut
548  
549 4 ▶sub ban {
Subroutine ban: called CC=8 SCAR=32.2
Pod documented
550 4 my ( $self, %opts ) = @_;
551  
552 4 $self->errorblank;
553  
554 4 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 4 4
555 0 $self->{error} = 1;
556 0 $self->{errorString} = 'backend has not been inited';
557 0 $self->warn;
558 0 return;
559 }
560  
561 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::hosts_deny::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::hosts_deny::IPv6_re\z/) { } 0 4 4
562 0 $self->{error} = 9;
563 0 $self->{errorString} = 'Nothing specified for the value ban';
564 0 $self->warn;
565 0 return;
566 } elsif ( ref( $opts{ban} ) ne '' ) {
567 0 $self->{error} = 10;
568 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
569 0 $self->warn;
570 0 return;
571 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition66%2/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::hosts_deny::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::hosts_deny::IPv6_re\z/
l!l&&r!l&&!r
310
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::hosts_deny::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::hosts_deny::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::hosts_deny::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::hosts_deny::IPv6_re\z/
Truth table66%2/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::hosts_deny::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::hosts_deny::IPv6_re\z/
ABresult
1X1
011
000
572 && $opts{ban} !~ /\A$IPv6_re\z/ )
573 {
574 0 $self->{error} = 10;
575 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
576 0 $self->warn;
577 0 return;
578 }
579  
580 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
581 4 $opts{ban} = lc( $opts{ban} );
582  
583 4 ▶ if ( $self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"banned"}{$opts{"ban"}}) 0 4 4
584 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
585 0 $self->{frontend_obj}->{test_data} = 'already banned';
586 }
587 0 return;
588 }
589  
590 4 $self->{banned}{ $opts{ban} } = 1;
591 4 $self->_apply(13);
592 } ## end sub ban
593  
594 =head2 unban
595  
596 Unbans an IP. The value of ban is validated as being a IPv4 or IPv6 address
597 and lowercased, then removed from the ban list. This instance's marked
598 region in the hosts.deny file is rewritten without it; if nothing remains
599 banned the region, markers included, is removed entirely. Unbanning an IP
600 that is not banned is a noop.
601  
602 $fw_helper->unban( ban => $ip );
603  
604 =cut
605  
606 1 ▶sub unban {
Subroutine unban: called CC=8 SCAR=32.9
Pod documented
607 1 my ( $self, %opts ) = @_;
608  
609 1 $self->errorblank;
610  
611 1 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 1 1
612 0 $self->{error} = 1;
613 0 $self->{errorString} = 'backend has not been inited';
614 0 $self->warn;
615 0 return;
616 }
617  
618 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::hosts_deny::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::hosts_deny::IPv6_re\z/) { } 0 1 1
619 0 $self->{error} = 9;
620 0 $self->{errorString} = 'Nothing specified for the value ban';
621 0 $self->warn;
622 0 return;
623 } elsif ( ref( $opts{ban} ) ne '' ) {
624 0 $self->{error} = 10;
625 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
626 0 $self->warn;
627 0 return;
628 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition33%1/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::hosts_deny::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::hosts_deny::IPv6_re\z/
l!l&&r!l&&!r
100
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::hosts_deny::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::hosts_deny::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::hosts_deny::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::hosts_deny::IPv6_re\z/
Truth table33%1/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::hosts_deny::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::hosts_deny::IPv6_re\z/
ABresult
1X1
011
000
629 && $opts{ban} !~ /\A$IPv6_re\z/ )
630 {
631 0 $self->{error} = 10;
632 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
633 0 $self->warn;
634 0 return;
635 }
636  
637 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
638 1 $opts{ban} = lc( $opts{ban} );
639  
640 1 ▶ if ( !$self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"banned"}{$opts{"ban"}}) 0 1 1
641 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
642 0 $self->{frontend_obj}->{test_data} = 'not banned';
643 }
644 0 return;
645 }
646  
647 1 delete( $self->{banned}{ $opts{ban} } );
648 1 $self->_apply(14);
649 } ## end sub unban
650  
651 =head2 list
652  
653 List banned IPs. Returns an array of the currently banned IPs from the
654 in-memory ban list; the hosts.deny file is not parsed.
655  
656 my @banned = $fw_helper->list;
657  
658 =cut
659  
660 0 ▶sub list {
Subroutine list: not called CC=2 SCAR=17.9
Pod documented
661 0 my ( $self, %opts ) = @_;
662  
663 0 $self->errorblank;
664  
665 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
666 0 $self->{frontend_obj}->{test_data} = 'list';
667 }
668  
669 0 return keys( %{ $self->{banned} } );
670 }
671  
672 =head2 re_init
673  
674 Re-renders this instance's region from the retained ban list.
675  
676 =cut
677  
678 0 ▶sub re_init {
Subroutine re_init: not called CC=1 SCAR=6.9
Pod documented
679 0 my ( $self, %opts ) = @_;
680  
681 0 $self->errorblank;
682  
683 0 $self->_apply(16);
684  
685 0 $self->{inited} = 1;
686 }
687  
688 =head2 teardown
689  
690 Removes this instance's region from the file, leaving everything else intact.
691  
692 =cut
693  
694 1 ▶sub teardown {
Subroutine teardown: called CC=1 SCAR=0.0
Pod documented
695 1 my ( $self, %opts ) = @_;
696  
697 1 $self->errorblank;
698  
699 1 $self->{inited} = 0;
700  
701 # empty the ban list so _apply strips our region and writes nothing back
702 1 my %saved_banned = %{ $self->{banned} };
703 1 $self->{banned} = {};
704 1 $self->_apply(17);
705 1 $self->{banned} = \%saved_banned;
706 } ## end sub teardown
707  
708 =head2 stop
709  
710 Alias for L</teardown>.
711  
712 =cut
713  
714 0 ▶sub stop {
Subroutine stop: not called CC=1 SCAR=6.9
Pod documented
715 0 my ( $self, %opts ) = @_;
716  
717 0 return $self->teardown(%opts);
718 }
719  
720 =head2 check
721  
722 Verifies our marked region is present in the file with a
723 C<< <daemon> : <ip> >> line for every banned IP. Returns 1 if healthy and 0
724 if not. With nothing banned there is nothing to verify and it reports
725 healthy.
726  
727 =cut
728  
729 6 ▶sub check {
Subroutine check: called CC=6 SCAR=18.0
Pod documented
730 6 my ( $self, %opts ) = @_;
731  
732 6 $self->errorblank;
733  
734 6 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 2 4 6
735 2 $self->{frontend_obj}->{test_data} = 'check';
736 2 return 1;
737 }
738  
739 4 my @ips = keys( %{ $self->{banned} } );
740 4 ▶ return 1 if ( !@ips );
Branch: 1 branch
BranchTrueFalseTotal
unless @ips 1 3 4
741  
742 3 my $content = $self->_read;
743 3 my ( $begin, $end ) = $self->_markers;
744 3 ▶ return 0 if ( index( $content, $begin ) < 0 );
Branch: 1 branch
BranchTrueFalseTotal
if (index($content, $begin) == -1) 0 3 3
745  
746 3 foreach my $ip (@ips) {
747 5 ▶ return 0 if ( index( $content, $self->_render_entry($ip) ) < 0 );
Branch: 1 branch
BranchTrueFalseTotal
if (index($content, $self->_render_entry($ip)) == -1) 0 5 5
748 }
749  
750 3 return 1;
751 } ## end sub check
752  
753 =head2 flush
754  
755 Removes all bans at once by clearing the ban list and rewriting the file.
756  
757 =cut
758  
759 0 ▶sub flush {
Subroutine flush: not called CC=2 SCAR=17.9
Pod documented
760 0 my ( $self, %opts ) = @_;
761  
762 0 $self->errorblank;
763  
764 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
765 0 $self->{error} = 1;
766 0 $self->{errorString} = 'backend has not been inited';
767 0 $self->warn;
768 0 return;
769 }
770  
771 0 $self->{banned} = {};
772 0 $self->_apply(25);
773 } ## end sub flush
774  
775 =head2 ban_cidr
776  
777 CIDR bans are not supported by this backend; this always sets the
778 cidrNotSupported error.
779  
780 $backend->ban_cidr(ban => '1.2.3.0/24');
781  
782 =cut
783  
784 0 ▶sub ban_cidr {
Subroutine ban_cidr: not called CC=1 SCAR=6.9
Pod documented
785 0 my ( $self, %opts ) = @_;
786  
787 0 $self->errorblank;
788  
789 0 $self->{error} = 35;
790 0 $self->{errorString} = 'the ' . __PACKAGE__ . ' backend does not support CIDR bans';
791 0 $self->warn;
792  
793 0 return;
794 } ## end sub ban_cidr
795  
796 =head2 unban_cidr
797  
798 CIDR bans are not supported by this backend; this always sets the
799 cidrNotSupported error.
800  
801 $backend->unban_cidr(ban => '1.2.3.0/24');
802  
803 =cut
804  
805 0 ▶sub unban_cidr {
Subroutine unban_cidr: not called CC=1 SCAR=6.9
Pod documented
806 0 my ( $self, %opts ) = @_;
807  
808 0 $self->errorblank;
809  
810 0 $self->{error} = 35;
811 0 $self->{errorString} = 'the ' . __PACKAGE__ . ' backend does not support CIDR bans';
812 0 $self->warn;
813  
814 0 return;
815 } ## end sub unban_cidr
816  
817 =head2 list_cidr
818  
819 CIDR bans are not supported by this backend, so this always returns an empty
820 list.
821  
822 my @banned_cidrs = $backend->list_cidr;
823  
824 =cut
825  
826 0 ▶sub list_cidr {
Subroutine list_cidr: not called CC=1 SCAR=6.9
Pod documented
827 0 my ( $self, %opts ) = @_;
828  
829 0 $self->errorblank;
830  
831 0 return ();
832 }
833  
834 =head1 ERROR CODES / FLAGS
835  
836 Error handling is provided by L<Error::Helper>. All
837 errors are considered fatal.
838  
839 =head2 1, notInited
840  
841 The backend has not been inited yet.
842  
843 =head2 7, invalidName
844  
845 The name is undef.
846  
847 =head2 8, optionsNotHash
848  
849 The item passed to new for options is not a hash.
850  
851 =head2 9, noBanItem
852  
853 No IP specified to ban or unban.
854  
855 =head2 10, banItemNotIP
856  
857 The item to ban is not an IP. Either wrong ref type or regexp
858 test using L<Regexp::IPv4> and L<Regexp::IPv6> failed.
859  
860 =head2 12, backendInitError
861  
862 Failed to init the backend.
863  
864 =head2 13, banFailed
865  
866 Failed to ban the item.
867  
868 =head2 14, unbanFailed
869  
870 Failed to unban the item.
871  
872 =head2 15, listFailed
873  
874 Failed to get a list of bans.
875  
876 =head2 16, reInitFailed
877  
878 Failed to re_init the backend.
879  
880 =head2 17, teardownFailed
881  
882 Failed to teardown the backend.
883  
884 =head2 18, alreadyInited
885  
886 init called, but the backend has already been inited.
887  
888 =head2 24, checkFailed
889  
890 The backend check raised an error.
891  
892 =head2 25, flushFailed
893  
894 Failed to flush the bans.
895  
896 =head2 31, fileWriteFailed
897  
898 Failed to write the file. File write failures are normally raised using the
899 error code of the operation that triggered the write, such as banFailed;
900 this is the fallback if no operation code was passed internally.
901  
902 =head2 32, banCidrFailed
903  
904 Failed to ban the CIDR range.
905  
906 =head2 33, unbanCidrFailed
907  
908 Failed to unban the CIDR range.
909  
910 =head2 34, cidrItemNotCidr
911  
912 The item to ban is not a CIDR range. Either wrong ref type or it is not an
913 IPv4 or IPv6 address followed by a prefix length valid for its family.
914  
915 =head2 35, cidrNotSupported
916  
917 The backend does not support CIDR bans.
918  
919 =head2 36, listCidrFailed
920  
921 Failed to get a list of CIDR bans.
922  
923 =head1 AUTHOR
924  
925 Zane C. Bowers-Hadley, C<< <vvelox at vvelox.ent> >>
926  
927 =head1 LICENSE AND COPYRIGHT
928  
929 This software is Copyright (c) 2023 by Zane C. Bowers-Hadley.
930  
931 This is free software, licensed under:
932  
933 The GNU Lesser General Public License, Version 2.1, February 1999
934  
935 =cut
936  
937 1 1; # End of Net::Firewall::BlockerHelper::backends::hosts_deny
« BlockerHelper/backends/azure.pm ↑ Summary BlockerHelper.pm »