BlockerHelper/backends/pf.pm

filter: Statementstmt 27.4% 115 / 419 Branchbran 23.1% 38 / 164 Conditioncond 26.1% 11 / 42 MC/DCmcdc 3.7% 1 / 27 Subroutinesub 50.0% 10 / 20 Podpod 100% 13 / 13 totaltotal 27.4% 188 / 685 CC 110 SCAR 44.4
CC
110
Cov
26%
ban
153.7
new
130.9
unban
110.0
CRAP 85.2
« BlockerHelper/backends/iptables.pm ↑ Summary BlockerHelper/backends/dummy.pm »
1 package Net::Firewall::BlockerHelper::backends::pf;
2  
3 3 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 3 ▶use base 'Error::Helper';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 3 ▶use Regexp::IPv4 qw($IPv4_re);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 3 ▶use Regexp::IPv6 qw($IPv6_re);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 =head1 NAME
11  
12 Net::Firewall::BlockerHelper::backends::pf - pf backend for Net::Firewall::BlockerHelper.
13  
14 =head1 VERSION
15  
16 Version 0.1.0
17  
18 =cut
19  
20 3 our $VERSION = '0.1.0';
21  
22 =head1 SYNOPSIS
23  
24 The rules and table this backend creates all live under the anchor
25 C<< <prefix>/<name> >>, which is what allows them to be managed
26 dynamically without ever touching the main ruleset. pf will only
27 evaluate the anchor if C<pf.conf> contains an anchor rule for it though,
28 so a bit of one time setup is required. With the default prefix of
29 C<kur> that means adding the like of the following and reloading
30 C<pf.conf>.
31  
32 anchor "kur/*"
33  
34 The rules loaded into the anchor are C<block drop quick> rules, so they
35 will win out over any non-C<quick> pass rules regardless of placement,
36 but the anchor line does need to come before any C<quick> pass rules
37 that would otherwise match the traffic in question.
38  
39 use Net::Firewall::BlockerHelper::backends::pf;
40  
41 my $backend1;
42 my $backend2;
43 eval {
44 $backend1 = Net::Firewall::BlockerHelper::backends::pf->new(
45 backend => 'pf',
46 name => 'all',
47 options=>{ kill=>1 },
48 );
49 $backend2 = Net::Firewall::BlockerHelper::backends::pf->new(
50 backend => 'pf',
51 ports => ['143'],
52 protocols => ['tcp'],
53 name => 'imap',
54 options=>{ kill=>0 },
55 );
56 };
57 if ($@) {
58 print 'Error: '
59 . $Error::Helper::error
60 . "\nError String: "
61 . $Error::Helper::errorString
62 . "\nError Flag: "
63 . $Error::Helper::errorFlag . "\n";
64 }
65  
66 print `pfctl -sr`
67  
68 $backend1->init;
69 $backend2->init;
70  
71 print `pfctl -sr`
72  
73 $backend1->ban(ban=>'1.2.3.4');
74 $backend1->ban(ban=>'4.3.2.1');
75 $backend2->ban(ban=>'4.3.2.1');
76  
77 use Data::Dumper;
78 print Dumper($backend1->list);
79 print Dumper($backend2->list);
80  
81 $backend1->unban(ban=>'4.3.2.1');
82  
83 use Data::Dumper;
84 print Dumper($backend1->list);
85 print Dumper($backend2->list);
86  
87 $backend1->teardown;
88  
89 print `pfctl -sr`
90  
91 $backend2->teardown;
92  
93 print `pfctl -sr`
94  
95 =head1 METHODS
96  
97 =head2 new
98  
99 Initiates the the object.
100  
101 - options :: Backend specific options that will be passed to the backend unchecked
102 outside of making sure it is a hash ref if defined. See below for furhter info.
103 - Default :: {}
104  
105 - ports :: A array of ports to block. Checked to make sure they are positive ints or a valid
106 service name via getservbyname. All ports will be blocked if non are specified. If
107 duplicates are removed.
108 - Default :: []
109  
110 - protocols :: A array of protocols to block. This is checked against
111 /etc/protocols via the function getprotobyname. Duplicates will be
112 discarded. If no protocols are given, tcp, udp, icmp, and icmp6 are
113 blocked, unless ports are given, in which case it defaults to tcp
114 and udp. Ports are only attached to port-capable protocols
115 (tcp/udp/sctp); other protocols are blocked without a port.
116 - Default :: ['tcp','udp','icmp','icmp6'], or ['tcp','udp'] when ports are given
117  
118 - prefix :: Prefix to use. Must match the regex /^[a-zA-Z0-9]+$/
119 - default :: kur
120  
121 - name :: Name of this specific instance. This must be specified.
122 - default :: undef
123  
124 The options hash accepts the following.
125  
126 - kill :: If it should kill states for the banned IP or not. Handles
127 both IPv4 and IPv6 and is scoped to what is being blocked. With
128 protocols and/or ports configured the state table is searched and
129 matching states killed by ID, filtered to the blocked protocols
130 and ports (pf keeps state for UDP as well, so blocking only udp
131 kills only udp states and leaves tcp alone); the state matching
132 follows the family of the banned IP as pf prints IPv4 states as
133 addr:port and IPv6 ones as addr[port]. With nothing configured
134 everything is being blocked and pfctl -k is used, killing all
135 states for the IP.
136 - Default :: 0
137  
138 All errors are considered fatal, meaning if new fails it will die.
139  
140 my $backend;
141 eval {
142 $backend = Net::Firewall::BlockerHelper::backends::pf->new(
143 backend => 'pf',
144 ports => ['22'],
145 protocols => ['tcp'],
146 name => 'ssh',
147 );
148 };
149 if ($@) {
150 print 'Error: '
151 . $Error::Helper::error
152 . "\nError String: "
153 . $Error::Helper::errorString
154 . "\nError Flag: "
155 . $Error::Helper::errorFlag . "\n";
156 }
157  
158 =cut
159  
160 sub new {
161 3 ▶ my ( $blank, %opts ) = @_;
Subroutine new: called CC=26 SCAR=48.7
Pod documented
162  
163 3 my $self = {
164 perror => undef,
165 error => undef,
166 errorLine => undef,
167 errorFilename => undef,
168 errorString => "",
169 errorExtra => {
170 all_errors_fatal => 1,
171 # all_fatal is what Error::Helper 2.1.0 actually checks; all_errors_fatal
172 # is kept for the name documented in its POD
173 all_fatal => 1,
174 flags => {
175 1 => 'notInited',
176 2 => 'invalidPortSpecified',
177 3 => 'portsNotArray',
178 4 => 'protocolsNotArray',
179 5 => 'invalidPortSpecified',
180 6 => 'invalidPrefixSpecified',
181 7 => 'invalidName',
182 8 => 'optionsNotHash',
183 9 => 'noBanItem',
184 10 => 'banItemNotIP',
185 11 => 'invalidBackend',
186 12 => 'backendInitError',
187 13 => 'banFailed',
188 14 => 'unbanFailed',
189 15 => 'listFailed',
190 16 => 'reInitFailed',
191 17 => 'teardownFailed',
192 18 => 'alreadyInited',
193 19 => 'nameTooLong',
194 23 => 'initFailed',
195 24 => 'checkFailed',
196 25 => 'flushFailed',
197 26 => 'banCidrFailed',
198 27 => 'unbanCidrFailed',
199 28 => 'cidrItemNotCidr',
200 29 => 'cidrNotSupported',
201 30 => 'listCidrFailed',
202 },
203 fatal_flags => {},
204 perror_not_fatal => 0,
205 },
206 options => {
207 kill => 0,
208 },
209 ports => [],
210 protocols => [],
211 testing => undef,
212 test_data => undef,
213 prefix => 'kur',
214 frontend_obj => undef,
215 inited => 0,
216 banned => {},
217 banned_cidr => {},
218 cidr_supported => 1,
219 };
220 3 bless $self;
221  
222 3 ▶ if ( defined( $opts{ports} ) && ref( $opts{ports} ) ne 'ARRAY' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opts{'ports'} and ref $opts{'ports'} ne 'ARRAY') { } 0 3 3
elsif (defined $opts{'ports'}) { } 1 2 3
Condition66%2/3
defined $opts{"ports"} and ref $opts{"ports"} ne "ARRAY"
!ll&&!rl&&r
210
MC/DC0%0/2
defined $opts{"ports"} and ref $opts{"ports"} ne "ARRAY"
defined $opts{"ports"} ref $opts{"ports"} ne "ARRAY"
Truth table66%2/3
A and B
A= defined $opts{"ports"}B= ref $opts{"ports"} ne "ARRAY"
ABresult
0X0
100
111
223 0 $self->{perror} = 1;
224 0 $self->{error} = 3;
225 0 $self->{errorString} = 'ports is defined and type is not array but "' . ref( $opts{ports} ) . '"';
226 0 $self->warn;
227 } elsif ( defined( $opts{ports} ) ) {
228 1 my %ports;
229 1 foreach my $item ( @{ $opts{ports} } ) {
230 0 ▶ if ( $item =~ /^[0-9]+$/ && $item >= 1 && $item <= 65535 ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($item =~ /^[0-9]+$/ and $item >= 1 and $item <= 65535) { } 0 0 0
elsif ($item =~ /^[0-9]+$/) { } 0 0 0
Condition0%0/6
$item =~ /^[0-9]+$/ and $item >= 1 and $item <= 65535
!ll&&!rl&&r
000
$item =~ /^[0-9]+$/ and $item >= 1
!ll&&!rl&&r
000
MC/DC0%0/3
$item =~ /^[0-9]+$/ and $item >= 1 and $item <= 65535
$item =~ /^[0-9]+$/ $item >= 1 $item <= 65535
Truth table0%0/4
A and B and C
A= $item =~ /^[0-9]+$/B= $item >= 1C= $item <= 65535
ABCresult
0XX0
10X0
1100
1111
231 0 $ports{$item} = 1;
232 } elsif ( $item =~ /^[0-9]+$/ ) {
233 0 $self->{perror} = 1;
234 0 $self->{error} = 2;
235 $self->{errorString}
236 0 = $item . ' is not a valid value for a port as it must be a int within the range 1 to 65535';
237 0 $self->warn;
238 } else {
239 # just using tcp here as protocol must be specified
240 0 my ( $name, $aliases, $port, $proto ) = getservbyname( $item, 'tcp' );
241 0 ▶ if ( !defined($port) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $port) 0 0 0
242 0 $self->{perror} = 1;
243 0 $self->{error} = 2;
244 $self->{errorString}
245 0 = $item . ' could not be resolved to a port name via getservbyname("' . $item . '", "tcp")';
246 0 $self->warn;
247 }
248 0 $ports{$port} = 1;
249 } ## end else [ if ( $item =~ /^[0-9]+$/ && $item >= 1 ) ]
250 } ## end foreach my $item ( @{ $opts{ports} } )
251 1 my @port_keys = keys(%ports);
252 1 @port_keys = sort { $a <=> $b } @port_keys;
253 1 push( @{ $self->{ports} }, @port_keys );
254 } ## end elsif ( defined( $opts{ports} ) )
255  
256 3 ▶ if ( defined( $opts{protocols} ) && ref( $opts{protocols} ) ne 'ARRAY' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opts{'protocols'} and ref $opts{'protocols'} ne 'ARRAY') { } 0 3 3
elsif (defined $opts{'protocols'}) { } 1 2 3
Condition66%2/3
defined $opts{"protocols"} and ref $opts{"protocols"} ne "ARRAY"
!ll&&!rl&&r
210
MC/DC0%0/2
defined $opts{"protocols"} and ref $opts{"protocols"} ne "ARRAY"
defined $opts{"protocols"} ref $opts{"protocols"} ne "ARRAY"
Truth table66%2/3
A and B
A= defined $opts{"protocols"}B= ref $opts{"protocols"} ne "ARRAY"
ABresult
0X0
100
111
257 0 $self->{perror} = 1;
258 0 $self->{error} = 4;
259 0 $self->{errorString} = 'protocols is defined and type is not array but "' . ref( $opts{protocols} ) . '"';
260 0 $self->warn;
261 } elsif ( defined( $opts{protocols} ) ) {
262 1 my %protocols;
263 1 foreach my $item ( @{ $opts{protocols} } ) {
264 0 my ( $name, $aliases, $proto ) = getprotobyname($item);
265 # if this is undef, it means it is not a known protocol
266 0 ▶ if ( !defined($proto) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $proto) 0 0 0
267 0 $self->{perror} = 1;
268 0 $self->{error} = 5;
269 $self->{errorString}
270 0 = $item . ' could not be resolved to a protocol via getprotobyname("' . $item . '")';
271 0 $self->warn;
272 }
273 0 $protocols{$item} = 1;
274 } ## end foreach my $item ( @{ $opts{protocols} } )
275 1 my @protocols_keys = keys(%protocols);
276 1 @protocols_keys = sort { $a cmp $b } @protocols_keys;
277 1 push( @{ $self->{protocols} }, @protocols_keys );
278 } ## end elsif ( defined( $opts{protocols} ) )
279  
280 # make sure prefix is sane if defiend
281 3 ▶ 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 3 3
elsif (defined $opts{'prefix'}) { } 3 0 3
Condition33%1/3
defined $opts{"prefix"} and not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
!ll&&!rl&&r
030
MC/DC0%0/2
defined $opts{"prefix"} and not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
defined $opts{"prefix"} not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
Truth table33%1/3
A and not(B)
A= defined $opts{"prefix"}B= not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
ABresult
0X0
100
111
282 0 $self->{perror} = 1;
283 0 $self->{error} = 6;
284 $self->{errorString}
285 0 = '"' . $opts{prefix} . '" is not a valid prefix as it does not match the regex /^[a-zA-Z0-9]+$/';
286 0 $self->warn;
287 } elsif ( defined( $opts{prefix} ) ) {
288 3 $self->{prefix} = $opts{prefix};
289 }
290  
291 # make sure we have a name and that it is valid
292 3 ▶ if ( !defined( $opts{name} ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $opts{'name'}) { } 0 3 3
elsif (not $opts{'name'} =~ /^[a-zA-Z0-9\-]+$/) { } 0 3 3
293 0 $self->{perror} = 1;
294 0 $self->{error} = 7;
295 0 $self->{errorString} = 'name is undef';
296 0 $self->warn;
297 } elsif ( $opts{name} !~ /^[a-zA-Z0-9\-]+$/ ) {
298 0 $self->{perror} = 1;
299 0 $self->{error} = 7;
300 0 $self->{errorString} = 'name set to "' . $opts{name} . '" which does not match the regexp /^[a-zA-Z0-9\-]+$/';
301 0 $self->warn;
302 }
303 3 $self->{name} = $opts{name};
304  
305 # pf limits table names to 31 characters and the table is
306 # <prefix>_<name>, so catch over-long combos here rather than as a
307 # confusing error at init
308 3 ▶ if ( defined( $self->{name} ) && length( $self->{prefix} . '_' . $self->{name} ) > 31 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"name"} and length $self->{"prefix"} . '_' . $self->{"name"} > 31) 1 2 3
Condition66%2/3
defined $self->{"name"} and length $self->{"prefix"} . '_' . $self->{"name"} > 31
!ll&&!rl&&r
021
MC/DC50%1/2
defined $self->{"name"} and length $self->{"prefix"} . '_' . $self->{"name"} > 31
defined $self->{"name"} length $self->{"prefix"} . '_' . $self->{"name"} > 31
Truth table66%2/3
A and B
A= defined $self->{"name"}B= length $self->{"prefix"} . '_' . $self->{"name"} > 31
ABresult
0X0
100
111
309 1 $self->{perror} = 1;
310 1 $self->{error} = 19;
311 $self->{errorString}
312 = 'the combined prefix and name, "'
313 . $self->{prefix} . '_'
314 . $self->{name}
315 1 . '", is longer than 31 characters, the max pf table name length';
316 1 $self->warn;
317 }
318  
319 # used internally for testing
320 2 ▶ if ( defined( $opts{testing} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"testing"}) 1 1 2
321 1 $self->{testing} = $opts{testing};
322 }
323 2 ▶ if ( defined( $opts{frontend_obj} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"frontend_obj"}) 1 1 2
324 1 $self->{frontend_obj} = $opts{frontend_obj};
325 }
326  
327 2 ▶ if ( defined( $opts{options} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"options"}) 1 1 2
328 1 ▶ if ( ref( $opts{options} ) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $opts{"options"} ne "HASH") 0 1 1
329 0 $self->{perror} = 1;
330 0 $self->{error} = 8;
331 0 $self->{errorString} = 'ref for options is "' . ref( $opts{options} ) . '" and not HASH';
332 0 $self->warn;
333 }
334 1 $self->{options} = $opts{options};
335 }
336  
337 2 return $self;
338 } ## end sub new
339  
340 =head2 init
341  
342 Initiates the backend. Best effort cleanup commands are run first, flushing
343 and killing the table and flushing the anchor rules, so remnants of a
344 previous run do not linger. Then the table C<< <prefix>_<name> >> is
345 created (persist, with counters) and C<block drop quick> rules for the
346 configured protocols and ports are loaded into the anchor
347 C<< <prefix>/<name> >> via C<pfctl -f->.
348  
349 Note that C<pf.conf> must contain a matching anchor rule for any of this
350 to have an effect. See L</SYNOPSIS>.
351  
352 No arguments are taken.
353  
354 May called a second time, it will error.
355  
356 $backend->init;
357  
358 =cut
359  
360 sub init {
361 1 ▶ my ( $self, %opts ) = @_;
Subroutine init: called CC=15 SCAR=35.0
Pod documented
362  
363 1 $self->errorblank;
364  
365 1 ▶ if ( $self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"inited"}) 0 1 1
366 0 $self->{error} = 18;
367 0 $self->{errorString} = 'backend has already been inited';
368 0 $self->warn;
369 }
370  
371 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 1 0 1
372 1 $self->{frontend_obj}->{test_data} = {};
373 }
374  
375 1 my $ports;
376 1 ▶ if ( defined( $self->{ports}[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"ports"}[0]) 0 1 1
377 0 $ports = join( ',', @{ $self->{ports} } );
378 }
379  
380 1 my @protocols;
381 1 ▶ if ( defined( $self->{protocols}[0] ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $self->{'protocols'}[0]) { } 0 1 1
elsif (defined $self->{'ports'}[0]) { } 0 1 1
382 0 push( @protocols, @{ $self->{protocols} } );
383 } elsif ( defined( $self->{ports}[0] ) ) {
384 # ports need a port-capable protocol, default to tcp and udp
385 0 push( @protocols, 'tcp', 'udp' );
386 } else {
387 1 push( @protocols, 'tcp', 'udp', 'icmp', 'icmp6' );
388 }
389  
390 # protocols that accept a port specification
391 1 my %port_ok = ( tcp => 1, udp => 1, sctp => 1 );
392  
393 1 my $pfctl = 'pfctl -a ' . $self->{prefix} . '/' . $self->{name};
394  
395 1 my $table = $self->{prefix} . '_' . $self->{name};
396  
397 1 my @fail_okay_commands;
398 1 push( @fail_okay_commands, $pfctl . ' -t ' . $table . ' -T flush' );
399 1 push( @fail_okay_commands, $pfctl . ' -t ' . $table . ' -T kill' );
400 1 push( @fail_okay_commands, $pfctl . ' -F rules' );
401  
402 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 1 0 1
403 1 $self->{frontend_obj}->{test_data}{fail_okay_commands} = \@fail_okay_commands;
404 } else {
405 0 foreach my $item (@fail_okay_commands) {
406 0 my $output = `$item 2>&1`;
407 }
408 }
409  
410 1 my $rules_init = '';
411 1 foreach my $item (@protocols) {
412 4 my $new_line = 'block drop quick proto ' . $item . ' from <' . $table . '> to any';
413 4 my $to_add = '';
414 4 ▶ if ( defined( $self->{ports}[0] ) && $port_ok{$item} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{'ports'}[0] and $port_ok{$item}) { } 0 4 4
Condition33%1/3
defined $self->{"ports"}[0] and $port_ok{$item}
!ll&&!rl&&r
400
MC/DC0%0/2
defined $self->{"ports"}[0] and $port_ok{$item}
defined $self->{"ports"}[0] $port_ok{$item}
Truth table33%1/3
A and B
A= defined $self->{"ports"}[0]B= $port_ok{$item}
ABresult
0X0
100
111
415 0 foreach my $port ( @{ $self->{ports} } ) {
416 0 $to_add = $to_add . $new_line . ' port ' . $port . "\n";
417 }
418 } else {
419 4 $to_add = $new_line . "\n";
420 }
421 4 $rules_init = $rules_init . $to_add;
422 } ## end foreach my $item (@protocols)
423  
424 1 my @commands;
425 # add the table to create the command
426 1 push( @commands, "echo 'table <" . $table . "> persist counters' | " . $pfctl . ' -f-' );
427 1 push( @commands, "echo '" . $rules_init . "' | " . $pfctl . ' -f-' );
428  
429 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 1 0 1
430 1 $self->{frontend_obj}->{test_data}{commands} = \@commands;
431 } else {
432 0 foreach my $item (@commands) {
433 0 my $output = `$item 2>&1`;
434 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
435 0 $self->{error} = 23;
436 $self->{errorString}
437 0 = 'init failed. non-zero exit code for the command... "' . $item . '"... output... ' . $output;
438 0 $self->warn;
439 }
440 }
441 } ## end else [ if ( $self->{testing} ) ]
442  
443 1 $self->{inited} = 1;
444 } ## end sub init
445  
446 =head2 ban
447  
448 Bans an IP. The value of ban is validated as being a IPv4 or IPv6 address
449 and lowercased, then added to the pf table via
450 C<< pfctl -a <prefix>/<name> -t <prefix>_<name> -T add >>. If the option
451 C<kill> is true, states for the IP are killed as well, scoped to the
452 configured protocols and ports. Banning an already banned IP is a noop.
453  
454 $backend->ban(ban => $ip);
455  
456 =cut
457  
458 sub ban {
459 2 ▶ my ( $self, %opts ) = @_;
Subroutine ban: called CC=21 SCAR=50.3
Pod documented
460  
461 2 $self->errorblank;
462  
463 2 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 2 2
464 0 $self->{error} = 1;
465 0 $self->{errorString} = 'backend has not been inited';
466 0 $self->warn;
467 0 return;
468 }
469  
470 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 $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv6_re\z/) { } 0 2 2
471 0 $self->{error} = 9;
472 0 $self->{errorString} = 'Nothing specified for the value ban';
473 0 $self->warn;
474 0 return;
475 } elsif ( ref( $opts{ban} ) ne '' ) {
476 0 $self->{error} = 10;
477 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
478 0 $self->warn;
479 0 return;
480 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition66%2/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv6_re\z/
l!l&&r!l&&!r
110
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv6_re\z/
Truth table66%2/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv6_re\z/
ABresult
1X1
011
000
481 && $opts{ban} !~ /\A$IPv6_re\z/ )
482 {
483 0 $self->{error} = 10;
484 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
485 0 $self->warn;
486 0 return;
487 }
488  
489 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
490 2 $opts{ban} = lc( $opts{ban} );
491  
492 2 ▶ if ( $self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"banned"}{$opts{"ban"}}) 0 2 2
493 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
494 0 $self->{frontend_obj}->{test_data} = 'already banned';
495 }
496 0 return;
497 }
498  
499 my $command
500 = 'pfctl -a '
501 . $self->{prefix} . '/'
502 . $self->{name} . ' -t '
503 . $self->{prefix} . '_'
504 . $self->{name} . ' -T add '
505 2 . $opts{ban};
506  
507 2 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 2 0 2
508 2 $self->{frontend_obj}->{test_data} = $command;
509 } else {
510 0 my $output = `$command 2>&1`;
511 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
512 0 $self->{error} = 13;
513 $self->{errorString}
514 0 = 'ban failed. non-zero exit code for the command... "' . $command . '"... output... ' . $output;
515 0 $self->warn;
516 }
517 }
518  
519 2 ▶ if ( $self->{options}{kill} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"options"}{"kill"}) 2 0 2
520 2 my @kill_commands;
521  
522 2 my @protos = @{ $self->{protocols} };
523 2 ▶ if ( !@protos && defined( $self->{ports}[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not @protos and defined $self->{"ports"}[0]) 0 2 2
Condition33%1/3
not @protos and defined $self->{"ports"}[0]
!ll&&!rl&&r
020
MC/DC0%0/2
not @protos and defined $self->{"ports"}[0]
not @protos defined $self->{"ports"}[0]
Truth table33%1/3
not(A) and B
A= not @protosB= defined $self->{"ports"}[0]
ABresult
0X0
100
111
524 # ports without protocols means tcp and udp are being blocked
525 0 @protos = ( 'tcp', 'udp' );
526 }
527  
528 2 ▶ if ( !@protos ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not @protos) { } 2 0 2
529 # blocking everything, so kill every state for the IP; pfctl -k
530 # handles both IPv4 and IPv6
531 2 push( @kill_commands, 'pfctl -k ' . $opts{ban} );
532 } else {
533 # kill via the state table so the kill can be scoped to the
534 # blocked protocols and ports, leaving other protocols alone;
535 # pf prints IPv4 states as addr:port but IPv6 ones as addr[port]
536 0 my $proto_grep = 'grep -wE "(' . join( '|', @protos ) . ')" | ';
537  
538 0 my $ip_grep;
539 my @port_greps;
540 0 ▶ if ( $opts{ban} =~ /\A$IPv4_re\z/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv4_re\z/) { } 0 0 0
541 # escape the dots so the IP is not treated as a regexp by grep,
542 # preventing 1.2.3.4 from also matching the likes of 1.2.314.5
543 0 my $ban_regexp = $opts{ban};
544 0 $ban_regexp =~ s/\./\\./g;
545 0 $ip_grep = 'grep -E "[[ ]' . $ban_regexp . ']*:" | ';
546 0 foreach my $port ( @{ $self->{ports} } ) {
547 0 push( @port_greps, 'grep -E ":' . $port . ' " | ' );
548 }
549 } else {
550 0 $ip_grep = 'grep -F " ' . $opts{ban} . '[" | ';
551 0 foreach my $port ( @{ $self->{ports} } ) {
552 0 push( @port_greps, 'grep -F "[' . $port . '] " | ' );
553 }
554 }
555 0 ▶ if ( !@port_greps ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@port_greps) 0 0 0
556 # no ports configured, so kill matching states on any port
557 0 @port_greps = ('');
558 }
559  
560 0 foreach my $port_grep (@port_greps) {
561 0 push( @kill_commands,
562 'pfctl -s state -vv 2> /dev/null | grep -E \'<*->*|id:\' | paste - - | '
563 . $proto_grep
564 . $port_grep
565 . $ip_grep
566 . 'sed "s/.*[\ \t]id:[\ \t]//" | cut -d " " -f 1 | paste -s - | xargs -n 1 pfctl -k id -k ' );
567 }
568 } ## end else [ if ( !@protos ) ]
569  
570 2 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 2 0 2
571 # the ban command was stored as a scalar, convert to a array so
572 # the kill commands can be seen as well
573 2 $self->{frontend_obj}->{test_data} = [ $self->{frontend_obj}->{test_data}, @kill_commands ];
574 } else {
575 # best effort; exit codes are intentionally ignored as these exit
576 # non-zero when there is nothing matching to kill
577 0 foreach my $item (@kill_commands) {
578 0 my $output = `$item 2>&1`;
579 }
580 }
581 } ## end if ( $self->{options}{kill} )
582  
583 2 $self->{banned}{ $opts{ban} } = 1;
584 } ## end sub ban
585  
586 =head2 unban
587  
588 Unbans an IP. The value of ban is validated as being a IPv4 or IPv6 address
589 and lowercased, then removed from the pf table via
590 C<< pfctl -a <prefix>/<name> -t <prefix>_<name> -T delete >>. Unbanning an
591 IP that is not banned is a noop.
592  
593 $backend->unban(ban => $ip);
594  
595 =cut
596  
597 sub unban {
598 0 ▶ my ( $self, %opts ) = @_;
Subroutine unban: not called CC=10 SCAR=47.0
Pod documented
599  
600 0 $self->errorblank;
601  
602 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
603 0 $self->{error} = 1;
604 0 $self->{errorString} = 'backend has not been inited';
605 0 $self->warn;
606 0 return;
607 }
608  
609 0 ▶ if ( !defined( $opts{ban} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opts{'ban'}) { } 0 0 0
elsif (ref $opts{'ban'} ne '') { } 0 0 0
elsif (not $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv6_re\z/) { } 0 0 0
610 0 $self->{error} = 9;
611 0 $self->{errorString} = 'Nothing specified for the value ban';
612 0 $self->warn;
613 0 return;
614 } elsif ( ref( $opts{ban} ) ne '' ) {
615 0 $self->{error} = 10;
616 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
617 0 $self->warn;
618 0 return;
619 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition0%0/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv6_re\z/
l!l&&r!l&&!r
000
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv6_re\z/
Truth table0%0/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv6_re\z/
ABresult
1X1
011
000
620 && $opts{ban} !~ /\A$IPv6_re\z/ )
621 {
622 0 $self->{error} = 10;
623 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
624 0 $self->warn;
625 0 return;
626 }
627  
628 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
629 0 $opts{ban} = lc( $opts{ban} );
630  
631 0 ▶ if ( !$self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"banned"}{$opts{"ban"}}) 0 0 0
632 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
633 0 $self->{frontend_obj}->{test_data} = 'not banned';
634 }
635 0 return;
636 }
637  
638 my $command
639 = 'pfctl -a '
640 . $self->{prefix} . '/'
641 . $self->{name} . ' -t '
642 . $self->{prefix} . '_'
643 . $self->{name}
644 . ' -T delete '
645 0 . $opts{ban};
646  
647 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
648 0 $self->{frontend_obj}->{test_data} = $command;
649 } else {
650 0 my $output = `$command 2>&1`;
651 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
652 0 $self->{error} = 14;
653 $self->{errorString}
654 0 = 'unban failed. non-zero exit code for the command... "' . $command . '"... output... ' . $output;
655 0 $self->warn;
656 }
657 }
658  
659 0 delete( $self->{banned}{ $opts{ban} } );
660 } ## end sub unban
661  
662 # Internal helper. Returns a true value if the passed scalar is a valid IPv4 or
663 # IPv6 CIDR range, that is an address followed by "/" and a prefix length that
664 # is within the range valid for its family (0 to 32 for IPv4, 0 to 128 for
665 # IPv6). Returns false otherwise.
666 sub _valid_cidr {
667 0 ▶ my ( $self, $cidr ) = @_;
Subroutine _valid_cidr: not called CC=8 SCAR=42.8
668  
669 0 ▶ return 0 if ( !defined($cidr) || ref($cidr) ne '' );
Branch: 1 branch
BranchTrueFalseTotal
if not defined $cidr or ref $cidr ne "" 0 0 0
Condition0%0/3
not defined $cidr or ref $cidr ne ""
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $cidr or ref $cidr ne ""
not defined $cidr ref $cidr ne ""
Truth table0%0/3
not(A) or B
A= not defined $cidrB= ref $cidr ne ""
ABresult
1X1
011
000
670  
671 0 ▶ if ( $cidr =~ m!\A(.+)/([0-9]{1,3})\z! ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cidr =~ m[\A(.+)/([0-9]{1,3})\z]) 0 0 0
672 0 my ( $addr, $prefix ) = ( $1, $2 );
673 0 ▶ return 1 if ( $addr =~ /\A$IPv4_re\z/ && $prefix <= 32 );
Branch: 1 branch
BranchTrueFalseTotal
if $addr =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv4_re\z/ and $prefix <= 32 0 0 0
Condition0%0/3
$addr =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv4_re\z/ and $prefix <= 32
!ll&&!rl&&r
000
MC/DC0%0/2
$addr =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv4_re\z/ and $prefix <= 32
$addr =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv4_re\z/ $prefix <= 32
Truth table0%0/3
A and B
A= $addr =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv4_re\z/B= $prefix <= 32
ABresult
0X0
100
111
674 0 ▶ return 1 if ( $addr =~ /\A$IPv6_re\z/ && $prefix <= 128 );
Branch: 1 branch
BranchTrueFalseTotal
if $addr =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv6_re\z/ and $prefix <= 128 0 0 0
Condition0%0/3
$addr =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv6_re\z/ and $prefix <= 128
!ll&&!rl&&r
000
MC/DC0%0/2
$addr =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv6_re\z/ and $prefix <= 128
$addr =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv6_re\z/ $prefix <= 128
Truth table0%0/3
A and B
A= $addr =~ /\A$Net::Firewall::BlockerHelper::backends::pf::IPv6_re\z/B= $prefix <= 128
ABresult
0X0
100
111
675 }
676  
677 0 return 0;
678 } ## end sub _valid_cidr
679  
680 =head2 ban_cidr
681  
682 Bans a CIDR range by adding it to the pf table via C<pfctl -T add>. pf
683 tables accept a network prefix in the same manner as a single address. The
684 value of ban is validated as being a IPv4 or IPv6 CIDR range and
685 lowercased. Banning an already banned range is a noop.
686  
687 $backend->ban_cidr(ban => '1.2.3.0/24');
688  
689 =cut
690  
691 sub ban_cidr {
692 0 ▶ my ( $self, %opts ) = @_;
Subroutine ban_cidr: not called CC=9 SCAR=45.0
Pod documented
693  
694 0 $self->errorblank;
695  
696 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
697 0 $self->{error} = 1;
698 0 $self->{errorString} = 'backend has not been inited';
699 0 $self->warn;
700 0 return;
701 }
702  
703 0 ▶ if ( !defined( $opts{ban} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opts{'ban'}) { } 0 0 0
elsif (ref $opts{'ban'} ne '') { } 0 0 0
elsif (not $self->_valid_cidr($opts{'ban'})) { } 0 0 0
704 0 $self->{error} = 9;
705 0 $self->{errorString} = 'Nothing specified for the value ban';
706 0 $self->warn;
707 0 return;
708 } elsif ( ref( $opts{ban} ) ne '' ) {
709 0 $self->{error} = 28;
710 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
711 0 $self->warn;
712 0 return;
713 } elsif ( !$self->_valid_cidr( $opts{ban} ) ) {
714 0 $self->{error} = 28;
715 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 CIDR';
716 0 $self->warn;
717 0 return;
718 }
719  
720 # lowercase so the same IPv6 CIDR in differing cases can't result in duplicate entries
721 0 $opts{ban} = lc( $opts{ban} );
722  
723 0 ▶ if ( $self->{banned_cidr}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"banned_cidr"}{$opts{"ban"}}) 0 0 0
724 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
725 0 $self->{frontend_obj}->{test_data} = 'already banned';
726 }
727 0 return;
728 }
729  
730 my $command
731 = 'pfctl -a '
732 . $self->{prefix} . '/'
733 . $self->{name} . ' -t '
734 . $self->{prefix} . '_'
735 . $self->{name} . ' -T add '
736 0 . $opts{ban};
737  
738 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
739 0 $self->{frontend_obj}->{test_data} = $command;
740 } else {
741 0 my $output = `$command 2>&1`;
742 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
743 0 $self->{error} = 26;
744 $self->{errorString}
745 0 = 'ban failed. non-zero exit code for the command... "' . $command . '"... output... ' . $output;
746 0 $self->warn;
747 }
748 }
749  
750 0 $self->{banned_cidr}{ $opts{ban} } = 1;
751 } ## end sub ban_cidr
752  
753 =head2 unban_cidr
754  
755 Unbans a CIDR range by deleting it from the pf table via
756 C<pfctl -T delete>. The value of ban is validated as being a IPv4 or IPv6
757 CIDR range and lowercased. Unbanning a range that is not banned is a noop.
758  
759 $backend->unban_cidr(ban => '1.2.3.0/24');
760  
761 =cut
762  
763 sub unban_cidr {
764 0 ▶ my ( $self, %opts ) = @_;
Subroutine unban_cidr: not called CC=9 SCAR=45.0
Pod documented
765  
766 0 $self->errorblank;
767  
768 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
769 0 $self->{error} = 1;
770 0 $self->{errorString} = 'backend has not been inited';
771 0 $self->warn;
772 0 return;
773 }
774  
775 0 ▶ if ( !defined( $opts{ban} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opts{'ban'}) { } 0 0 0
elsif (ref $opts{'ban'} ne '') { } 0 0 0
elsif (not $self->_valid_cidr($opts{'ban'})) { } 0 0 0
776 0 $self->{error} = 9;
777 0 $self->{errorString} = 'Nothing specified for the value ban';
778 0 $self->warn;
779 0 return;
780 } elsif ( ref( $opts{ban} ) ne '' ) {
781 0 $self->{error} = 28;
782 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
783 0 $self->warn;
784 0 return;
785 } elsif ( !$self->_valid_cidr( $opts{ban} ) ) {
786 0 $self->{error} = 28;
787 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 CIDR';
788 0 $self->warn;
789 0 return;
790 }
791  
792 # lowercase so the same IPv6 CIDR in differing cases can't result in duplicate entries
793 0 $opts{ban} = lc( $opts{ban} );
794  
795 0 ▶ if ( !$self->{banned_cidr}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"banned_cidr"}{$opts{"ban"}}) 0 0 0
796 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
797 0 $self->{frontend_obj}->{test_data} = 'not banned';
798 }
799 0 return;
800 }
801  
802 my $command
803 = 'pfctl -a '
804 . $self->{prefix} . '/'
805 . $self->{name} . ' -t '
806 . $self->{prefix} . '_'
807 . $self->{name}
808 . ' -T delete '
809 0 . $opts{ban};
810  
811 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
812 0 $self->{frontend_obj}->{test_data} = $command;
813 } else {
814 0 my $output = `$command 2>&1`;
815 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
816 0 $self->{error} = 27;
817 $self->{errorString}
818 0 = 'unban failed. non-zero exit code for the command... "' . $command . '"... output... ' . $output;
819 0 $self->warn;
820 }
821 }
822  
823 0 delete( $self->{banned_cidr}{ $opts{ban} } );
824 } ## end sub unban_cidr
825  
826 =head2 list_cidr
827  
828 List banned CIDR ranges. Returns an array of the currently banned CIDR
829 ranges. Single IPs are not included; for those see L</list>.
830  
831 my @banned_cidrs = $backend->list_cidr;
832  
833 =cut
834  
835 sub list_cidr {
836 0 ▶ my ( $self, %opts ) = @_;
Subroutine list_cidr: not called CC=2 SCAR=17.9
Pod documented
837  
838 0 $self->errorblank;
839  
840 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
841 0 $self->{frontend_obj}->{test_data} = 'list_cidr';
842 }
843  
844 0 return keys( %{ $self->{banned_cidr} } );
845 }
846  
847 =head2 list
848  
849 List banned IPs. Returns an array of the currently banned single IPs. CIDR
850 ranges are not included; for those see L</list_cidr>.
851  
852 my @banned = $backend->list;
853  
854 =cut
855  
856 sub list {
857 0 ▶ my ( $self, %opts ) = @_;
Subroutine list: not called CC=2 SCAR=17.9
Pod documented
858  
859 0 $self->errorblank;
860  
861 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
862 0 $self->{frontend_obj}->{test_data} = 'list';
863 }
864  
865 0 return keys( %{ $self->{banned} } );
866 }
867  
868 =head2 re_init
869  
870 Tells the backend to re-init it's self.
871  
872 This will call teardown and init again. After that it will
873 re-added all previously added bans.
874  
875 Will error if already inited.
876  
877 $backend->re_init;
878  
879 =cut
880  
881 sub re_init {
882 0 ▶ my ( $self, %opts ) = @_;
Subroutine re_init: not called CC=6 SCAR=37.4
Pod documented
883  
884 0 $self->errorblank;
885  
886 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
887 0 $self->{error} = 1;
888 0 $self->{errorString} = 'backend has not been inited';
889 0 $self->warn;
890 0 return;
891 }
892  
893 # teardown is best effort here as a partially or fully wiped setup is
894 # exactly what re_init needs to recover from; init cleans up any remnants
895 {
896 0 local $@;
897 0 eval { $self->teardown; };
898 }
899 0 $self->init;
900  
901 # both single IPs and CIDR ranges are re-added the same way, as pf tables
902 # hold either
903 0 my @to_ban = ( keys( %{ $self->{banned} } ), keys( %{ $self->{banned_cidr} } ) );
904  
905 0 my @re_init_test_data;
906 0 foreach my $item (@to_ban) {
907 my $command
908 = 'pfctl -a '
909 . $self->{prefix} . '/'
910 . $self->{name} . ' -t '
911 . $self->{prefix} . '_'
912 0 . $self->{name} . ' -T add '
913 . $item;
914  
915 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
916 0 push( @re_init_test_data, $command );
917 } else {
918 0 my $output = `$command 2>&1`;
919 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
920 0 $self->{error} = 13;
921 $self->{errorString}
922 0 = 'ban failed. non-zero exit code for the command... "' . $command . '"... output... ' . $output;
923 0 $self->warn;
924 }
925 }
926 } ## end foreach my $item (@to_ban)
927  
928 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
929 0 $self->{frontend_obj}->{test_data} = \@re_init_test_data;
930 }
931  
932 0 $self->{inited} = 1;
933 } ## end sub re_init
934  
935 =head2 teardown
936  
937 Tears down the setup for the backend.
938  
939 This flushes and kills the pf table and flushes the rules from the anchor,
940 removing both the table and the block rules.
941  
942 If called prior to calling init, this will error. It won't check if it has been
943 inited or not.
944  
945 $backend->teardown;
946  
947 =cut
948  
949 sub teardown {
950 0 ▶ my ( $self, %opts ) = @_;
Subroutine teardown: not called CC=4 SCAR=30.0
Pod documented
951  
952 0 $self->errorblank;
953  
954 0 $self->{inited} = 0;
955  
956 0 my $pfctl = 'pfctl -a ' . $self->{prefix} . '/' . $self->{name};
957  
958 0 my $table = $self->{prefix} . '_' . $self->{name};
959  
960 0 my @commands;
961 0 push( @commands, $pfctl . ' -t ' . $table . ' -T flush' );
962 0 push( @commands, $pfctl . ' -t ' . $table . ' -T kill' );
963 0 push( @commands, $pfctl . ' -F rules' );
964  
965 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
966 0 $self->{frontend_obj}->{test_data} = \@commands;
967 } else {
968 0 foreach my $item (@commands) {
969 0 my $output = `$item 2>&1`;
970 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
971 0 $self->{error} = 17;
972 $self->{errorString}
973 0 = 'teardown failed. non-zero exit code for the command... "' . $item . '"... output... ' . $output;
974 0 $self->warn;
975 }
976 }
977 } ## end else [ if ( $self->{testing} ) ]
978 } ## end sub teardown
979  
980 =head2 stop
981  
982 Alias for L</teardown>, provided for parity with the fail2ban C<actionstop>
983 concept.
984  
985 $backend->stop;
986  
987 =cut
988  
989 sub stop {
990 0 ▶ my ( $self, %opts ) = @_;
Subroutine stop: not called CC=1 SCAR=6.9
Pod documented
991  
992 0 return $self->teardown(%opts);
993 }
994  
995 =head2 check
996  
997 Verifies that the pf table is still present under the anchor and that the
998 anchor still contains the block rules. Returns a true value if the setup is
999 intact and a false value if any part of it appears to have been removed. This
1000 is the equivalent of fail2ban's C<actioncheck>.
1001  
1002 if ( !$backend->check ) {
1003 $backend->re_init;
1004 }
1005  
1006 =cut
1007  
1008 sub check {
1009 2 ▶ my ( $self, %opts ) = @_;
Subroutine check: called CC=5 SCAR=23.4
Pod documented
1010  
1011 2 $self->errorblank;
1012  
1013 2 my $pfctl = 'pfctl -a ' . $self->{prefix} . '/' . $self->{name};
1014 2 my $table = $self->{prefix} . '_' . $self->{name};
1015  
1016 2 my $table_command = $pfctl . ' -t ' . $table . ' -T show';
1017 2 my $rules_command = $pfctl . ' -sr';
1018  
1019 2 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 2 0 2
1020 2 $self->{frontend_obj}->{test_data} = [ $table_command, $rules_command ];
1021 2 return 1;
1022 }
1023  
1024 0 my $output = `$table_command 2>&1`;
1025 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
1026 0 return 0;
1027 }
1028  
1029 # -sr exits zero even if the anchor is empty, so the rules being flushed
1030 # externally shows up as a lack of output rather than a non-zero exit
1031 0 $output = `$rules_command 2>&1`;
1032 0 ▶ if ( $? != 0 || $output !~ /\S/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0 or not $output =~ /\S/) 0 0 0
Condition0%0/3
$? != 0 or not $output =~ /\S/
l!l&&r!l&&!r
000
MC/DC0%0/2
$? != 0 or not $output =~ /\S/
$? != 0 not $output =~ /\S/
Truth table0%0/3
A or not(B)
A= $? != 0B= not $output =~ /\S/
ABresult
1X1
011
000
1033 0 return 0;
1034 }
1035  
1036 0 return 1;
1037 } ## end sub check
1038  
1039 =head2 flush
1040  
1041 Removes all currently banned IPs at once by flushing the pf table, leaving
1042 the table and rules in place. This is the equivalent of fail2ban's
1043 C<actionflush>.
1044  
1045 $backend->flush;
1046  
1047 =cut
1048  
1049 sub flush {
1050 0 ▶ my ( $self, %opts ) = @_;
Subroutine flush: not called CC=5 SCAR=34.0
Pod documented
1051  
1052 0 $self->errorblank;
1053  
1054 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
1055 0 $self->{error} = 1;
1056 0 $self->{errorString} = 'backend has not been inited';
1057 0 $self->warn;
1058 0 return;
1059 }
1060  
1061 0 my $pfctl = 'pfctl -a ' . $self->{prefix} . '/' . $self->{name};
1062 0 my $table = $self->{prefix} . '_' . $self->{name};
1063  
1064 0 my @commands = ( $pfctl . ' -t ' . $table . ' -T flush' );
1065  
1066 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
1067 0 $self->{frontend_obj}->{test_data} = \@commands;
1068 } else {
1069 0 foreach my $item (@commands) {
1070 0 my $output = `$item 2>&1`;
1071 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
1072 0 $self->{error} = 25;
1073 $self->{errorString}
1074 0 = 'flush failed. non-zero exit code for the command... "' . $item . '"... output... ' . $output;
1075 0 $self->warn;
1076 }
1077 }
1078 } ## end else [ if ( $self->{testing} ) ]
1079  
1080 # the table flush above removes both single IP and CIDR entries at once
1081 0 $self->{banned} = {};
1082 0 $self->{banned_cidr} = {};
1083 } ## end sub flush
1084  
1085 =head1 ERROR CODES / FLAGS
1086  
1087 Error handling is provided by L<Error::Helper>. All
1088 errors are considered fatal.
1089  
1090 =head2 1, notInited
1091  
1092 The backend has not been inited yet.
1093  
1094 =head2 2, invalidPortSpecified
1095  
1096 Port is either not an int within the range 1 to 65535 or a name that can be resolved by getservbyname.
1097  
1098 =head2 3, portsNotArray
1099  
1100 The data passed to new for ports is not an array.
1101  
1102 =head2 4, protocolsNotArray
1103  
1104 The data passed to new for protocols is not an array.
1105  
1106 =head2 5, invalidPortSpecified
1107  
1108 Port is either not an int within the range 1 to 65535 or a name that can be resolved by getservbyname.
1109  
1110 =head2 6, invalidPrefixSpecified
1111  
1112 The specified prefix did not match /^[a-zA-Z0-9]+$/.
1113  
1114 =head2 7, invalidName
1115  
1116 The name is either undef or does not match /^[a-zA-Z0-9\-]+$/.
1117  
1118 =head2 8, optionsNotHash
1119  
1120 The item passed to new for options is not a hash.
1121  
1122 =head2 9, noBanItem
1123  
1124 No IP or CIDR range specified to ban or unban.
1125  
1126 =head2 10, banItemNotIP
1127  
1128 The item to ban is not an IP. Either wrong ref type or regexp
1129 test using L<Regexp::IPv4> and L<Regexp::IPv6> failed.
1130  
1131 =head2 11, invalidBackend
1132  
1133 The specified backend failed to pass a basic sanity check of making sure it
1134 matches the regexp /^[a-zA-Z0-9\_]+$/.
1135  
1136 =head2 12, backendInitError
1137  
1138 Failed to init the backend.
1139  
1140 =head2 13, banFailed
1141  
1142 Failed to ban the item.
1143  
1144 =head2 14, unbanFailed
1145  
1146 Failed to unban the item.
1147  
1148 =head2 15, listFailed
1149  
1150 Failed to get a list of bans.
1151  
1152 =head2 16, reInitFailed
1153  
1154 Failed to re_init the backend.
1155  
1156 =head2 17, teardownFailed
1157  
1158 Failed to teardown the backend.
1159  
1160 =head2 18, alreadyInited
1161  
1162 init called, but the backend has already been inited.
1163  
1164 =head2 19, nameTooLong
1165  
1166 The combined prefix and name is longer than 31 characters, the max pf table
1167 name length.
1168  
1169 =head2 23, initFailed
1170  
1171 One of the required commands for init failed.
1172  
1173 =head2 24, checkFailed
1174  
1175 The backend check raised an error.
1176  
1177 =head2 25, flushFailed
1178  
1179 Failed to flush the bans.
1180  
1181 =head2 26, banCidrFailed
1182  
1183 Failed to ban the CIDR range.
1184  
1185 =head2 27, unbanCidrFailed
1186  
1187 Failed to unban the CIDR range.
1188  
1189 =head2 28, cidrItemNotCidr
1190  
1191 The item to ban is not a CIDR range. Either wrong ref type or it is not an
1192 IPv4 or IPv6 address followed by a prefix length valid for its family.
1193  
1194 =head2 29, cidrNotSupported
1195  
1196 The backend does not support CIDR bans.
1197  
1198 =head2 30, listCidrFailed
1199  
1200 Failed to get a list of CIDR bans.
1201  
1202 =head1 AUTHOR
1203  
1204 Zane C. Bowers-Hadley, C<< <vvelox at vvelox.ent> >>
1205  
1206 =head1 BUGS
1207  
1208 Please report any bugs or feature requests to C<bug-net-firewall-blockerhelper at rt.cpan.org>, or through
1209 the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Net-Firewall-BlockerHelper>. I will be notified, and then you'll
1210 automatically be notified of progress on your bug as I make changes.
1211  
1212  
1213  
1214  
1215 =head1 SUPPORT
1216  
1217 You can find documentation for this module with the perldoc command.
1218  
1219 perldoc Net::Firewall::BlockerHelper
1220  
1221  
1222 You can also look for information at:
1223  
1224 =over 4
1225  
1226 =item * RT: CPAN's request tracker (report bugs here)
1227  
1228 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Net-Firewall-BlockerHelper>
1229  
1230 =item * Search CPAN
1231  
1232 L<https://metacpan.org/release/Net-Firewall-BlockerHelper>
1233  
1234 =back
1235  
1236  
1237 =head1 ACKNOWLEDGEMENTS
1238  
1239  
1240 =head1 LICENSE AND COPYRIGHT
1241  
1242 This software is Copyright (c) 2023 by Zane C. Bowers-Hadley.
1243  
1244 This is free software, licensed under:
1245  
1246 The GNU Lesser General Public License, Version 2.1, February 1999
1247  
1248  
1249 =cut
1250  
1251 3 1; # End of Net::Firewall::BlockerHelper
« BlockerHelper/backends/iptables.pm ↑ Summary BlockerHelper/backends/dummy.pm »