BlockerHelper/backends/ufw.pm

filter: Statementstmt 4.4% 19 / 431 Branchbran 0.0% 0 / 168 Conditioncond 0.0% 0 / 54 MC/DCmcdc 0.0% 0 / 32 Subroutinesub 27.2% 6 / 22 Podpod 100% 13 / 13 totaltotal 5.2% 38 / 720 CC 131 SCAR 60.1
CC
131
Cov
3%
new
1332.0
ban
240.0
_kill_commands
210.0
CRAP 407.8
« BlockerHelper/backends/nftables.pm ↑ Summary BlockerHelper/backends/openwrt.pm »
1 package Net::Firewall::BlockerHelper::backends::ufw;
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::ufw - ufw backend for Net::Firewall::BlockerHelper.
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 use Net::Firewall::BlockerHelper;
25  
26 my $fw_helper = Net::Firewall::BlockerHelper->new(
27 backend => 'ufw',
28 ports => ['22'],
29 protocols => ['tcp'],
30 name => 'ssh',
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 using L<ufw(8)>, the uncomplicated firewall front end common on
41 Ubuntu.
42  
43 Unlike the table/set based backends there is no container to create; each
44 ban prepends one or more per-IP rules (one per protocol) and each unban
45 deletes them again. teardown removes the rules for all currently banned IPs
46 without forgetting them, so re_init can re-add them.
47  
48 ufw must already be enabled (C<ufw enable>); init and check verify this via
49 C<ufw status>. Requires C<ufw> to be in the C<PATH> of the process, which
50 must have sufficient privileges to run it.
51  
52 =head1 METHODS
53  
54 =head2 new
55  
56 Initiates the the object.
57  
58 - options :: Backend specific options that will be passed to the backend unchecked
59 outside of making sure it is a hash ref if defined. See below for furhter info.
60 - Default :: {}
61  
62 - ports :: A array of ports to block. Checked to make sure they are ints within the
63 range 1 to 65535 or a valid service name via getservbyname. All ports will be
64 blocked if non are specified. Duplicates are removed.
65 - Default :: []
66  
67 - protocols :: A array of protocols to block. This is checked against
68 /etc/protocols via the function getprotobyname and against the
69 protocols understood by ufw (tcp, udp, ah, esp, gre, igmp, and
70 ipv6). Duplicates will be discarded. If no protocols are given,
71 everything from the IP is blocked, unless ports are given, in
72 which case it defaults to tcp and udp. Ports are only attached to
73 tcp and udp; other protocols are blocked without a port.
74 - Default :: [], or ['tcp','udp'] when ports are given
75  
76 - prefix :: Prefix to use. Must match the regex /^[a-zA-Z0-9]+$/
77 - default :: kur
78  
79 - name :: Name of this specific instance. This must be specified.
80 - default :: undef
81  
82 The options hash accepts the following.
83  
84 - type :: The drop method to use. 'deny' silently drops. 'reject' sends
85 a reject back. See ufw(8).
86 - Default :: deny
87  
88 - kill :: Kill existing connections/state for the banned IP. '' does
89 nothing, 'ss' uses ss -K, and 'conntrack' uses conntrack -D. Both
90 handle IPv4 and IPv6 and both are scoped to the configured
91 protocols, so blocking only udp will not kill tcp and vice versa;
92 with no protocols configured everything applicable is killed. For
93 ss that means -t/-u/-tu as appropriate (TCP connections and
94 connected UDP sockets are what ss can kill) and for conntrack -p
95 per blocked protocol.
96 - Default :: ''
97  
98 All errors are considered fatal, meaning if new fails it will die.
99  
100 =cut
101  
102 0 ▶sub new {
Subroutine new: not called CC=36 SCAR=71.9
Pod documented
103 0 my ( $blank, %opts ) = @_;
104  
105 0 my $self = {
106 perror => undef,
107 error => undef,
108 errorLine => undef,
109 errorFilename => undef,
110 errorString => "",
111 errorExtra => {
112 all_errors_fatal => 1,
113 # all_fatal is what Error::Helper 2.1.0 actually checks; all_errors_fatal
114 # is kept for the name documented in its POD
115 all_fatal => 1,
116 flags => {
117 1 => 'notInited',
118 2 => 'invalidPortSpecified',
119 3 => 'portsNotArray',
120 4 => 'protocolsNotArray',
121 5 => 'invalidProtocolSpecified',
122 6 => 'invalidPrefixSpecified',
123 7 => 'invalidName',
124 8 => 'optionsNotHash',
125 9 => 'noBanItem',
126 10 => 'banItemNotIP',
127 12 => 'backendInitError',
128 13 => 'banFailed',
129 14 => 'unbanFailed',
130 15 => 'listFailed',
131 16 => 'reInitFailed',
132 17 => 'teardownFailed',
133 18 => 'alreadyInited',
134 19 => 'killInvalid',
135 20 => 'typeInvalid',
136 23 => 'initFailed',
137 24 => 'checkFailed',
138 25 => 'flushFailed',
139 26 => 'banCidrFailed',
140 27 => 'unbanCidrFailed',
141 28 => 'cidrItemNotCidr',
142 29 => 'cidrNotSupported',
143 30 => 'listCidrFailed',
144 },
145 fatal_flags => {},
146 perror_not_fatal => 0,
147 },
148 options => {
149 type => 'deny',
150 kill => '',
151 },
152 ports => [],
153 protocols => [],
154 testing => undef,
155 test_data => undef,
156 prefix => 'kur',
157 frontend_obj => undef,
158 inited => 0,
159 banned => {},
160 banned_cidr => {},
161 cidr_supported => 1,
162 };
163 0 bless $self;
164  
165 0 ▶ if ( defined( $opts{ports} ) && ref( $opts{ports} ) ne 'ARRAY' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opts{'ports'} and ref $opts{'ports'} ne 'ARRAY') { } 0 0 0
elsif (defined $opts{'ports'}) { } 0 0 0
Condition0%0/3
defined $opts{"ports"} and ref $opts{"ports"} ne "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $opts{"ports"} and ref $opts{"ports"} ne "ARRAY"
defined $opts{"ports"} ref $opts{"ports"} ne "ARRAY"
Truth table0%0/3
A and B
A= defined $opts{"ports"}B= ref $opts{"ports"} ne "ARRAY"
ABresult
0X0
100
111
166 0 $self->{perror} = 1;
167 0 $self->{error} = 3;
168 0 $self->{errorString} = 'ports is defined and type is not array but "' . ref( $opts{ports} ) . '"';
169 0 $self->warn;
170 } elsif ( defined( $opts{ports} ) ) {
171 0 my %ports;
172 0 foreach my $item ( @{ $opts{ports} } ) {
173 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
174 0 $ports{$item} = 1;
175 } elsif ( $item =~ /^[0-9]+$/ ) {
176 0 $self->{perror} = 1;
177 0 $self->{error} = 2;
178 $self->{errorString}
179 0 = $item . ' is not a valid value for a port as it must be a int within the range 1 to 65535';
180 0 $self->warn;
181 } else {
182 # just using tcp here as protocol must be specified
183 0 my ( $name, $aliases, $port, $proto ) = getservbyname( $item, 'tcp' );
184 0 ▶ if ( !defined($port) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $port) 0 0 0
185 0 $self->{perror} = 1;
186 0 $self->{error} = 2;
187 $self->{errorString}
188 0 = $item . ' could not be resolved to a port name via getservbyname("' . $item . '", "tcp")';
189 0 $self->warn;
190 }
191 0 $ports{$port} = 1;
192 } ## end else [ if ( $item =~ /^[0-9]+$/ && $item >= 1 &&...)]
193 } ## end foreach my $item ( @{ $opts{ports} } )
194 0 my @port_keys = keys(%ports);
195 0 @port_keys = sort { $a <=> $b } @port_keys;
196 0 push( @{ $self->{ports} }, @port_keys );
197 } ## end elsif ( defined( $opts{ports} ) )
198  
199 # the protocols ufw understands for rules
200 0 my %ufw_protocols = ( tcp => 1, udp => 1, ah => 1, esp => 1, gre => 1, igmp => 1, ipv6 => 1 );
201  
202 0 ▶ if ( defined( $opts{protocols} ) && ref( $opts{protocols} ) ne 'ARRAY' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opts{'protocols'} and ref $opts{'protocols'} ne 'ARRAY') { } 0 0 0
elsif (defined $opts{'protocols'}) { } 0 0 0
Condition0%0/3
defined $opts{"protocols"} and ref $opts{"protocols"} ne "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $opts{"protocols"} and ref $opts{"protocols"} ne "ARRAY"
defined $opts{"protocols"} ref $opts{"protocols"} ne "ARRAY"
Truth table0%0/3
A and B
A= defined $opts{"protocols"}B= ref $opts{"protocols"} ne "ARRAY"
ABresult
0X0
100
111
203 0 $self->{perror} = 1;
204 0 $self->{error} = 4;
205 0 $self->{errorString} = 'protocols is defined and type is not array but "' . ref( $opts{protocols} ) . '"';
206 0 $self->warn;
207 } elsif ( defined( $opts{protocols} ) ) {
208 0 my %protocols;
209 0 foreach my $item ( @{ $opts{protocols} } ) {
210 0 my ( $name, $aliases, $proto ) = getprotobyname($item);
211 # if this is undef, it means it is not a known protocol
212 0 ▶ if ( !defined($proto) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $proto) 0 0 0
213 0 $self->{perror} = 1;
214 0 $self->{error} = 5;
215 $self->{errorString}
216 0 = $item . ' could not be resolved to a protocol via getprotobyname("' . $item . '")';
217 0 $self->warn;
218 }
219 0 ▶ if ( !$ufw_protocols{$item} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ufw_protocols{$item}) 0 0 0
220 0 $self->{perror} = 1;
221 0 $self->{error} = 5;
222 $self->{errorString}
223 0 = $item . ' is not a protocol understood by ufw... understood protocols are tcp, udp, ah, esp, gre, igmp, and ipv6';
224 0 $self->warn;
225 }
226 0 $protocols{$item} = 1;
227 } ## end foreach my $item ( @{ $opts{protocols} } )
228 0 my @protocols_keys = keys(%protocols);
229 0 @protocols_keys = sort { $a cmp $b } @protocols_keys;
230 0 push( @{ $self->{protocols} }, @protocols_keys );
231 } ## end elsif ( defined( $opts{protocols} ) )
232  
233 # make sure prefix is sane if defiend
234 0 ▶ 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 0 0
elsif (defined $opts{'prefix'}) { } 0 0 0
Condition0%0/3
defined $opts{"prefix"} and not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
!ll&&!rl&&r
000
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 table0%0/3
A and not(B)
A= defined $opts{"prefix"}B= not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
ABresult
0X0
100
111
235 0 $self->{perror} = 1;
236 0 $self->{error} = 6;
237 $self->{errorString}
238 0 = '"' . $opts{prefix} . '" is not a valid prefix as it does not match the regex /^[a-zA-Z0-9]+$/';
239 0 $self->warn;
240 } elsif ( defined( $opts{prefix} ) ) {
241 0 $self->{prefix} = $opts{prefix};
242 }
243  
244 # make sure we have a name and that it is valid
245 0 ▶ if ( !defined( $opts{name} ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $opts{'name'}) { } 0 0 0
elsif (not $opts{'name'} =~ /^[a-zA-Z0-9\-]+$/) { } 0 0 0
246 0 $self->{perror} = 1;
247 0 $self->{error} = 7;
248 0 $self->{errorString} = 'name is undef';
249 0 $self->warn;
250 } elsif ( $opts{name} !~ /^[a-zA-Z0-9\-]+$/ ) {
251 0 $self->{perror} = 1;
252 0 $self->{error} = 7;
253 0 $self->{errorString} = 'name set to "' . $opts{name} . '" which does not match the regexp /^[a-zA-Z0-9\-]+$/';
254 0 $self->warn;
255 }
256 0 $self->{name} = $opts{name};
257  
258 # used internally for testing
259 0 ▶ if ( defined( $opts{testing} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"testing"}) 0 0 0
260 0 $self->{testing} = $opts{testing};
261 }
262 0 ▶ if ( defined( $opts{frontend_obj} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"frontend_obj"}) 0 0 0
263 0 $self->{frontend_obj} = $opts{frontend_obj};
264 }
265  
266 0 ▶ if ( defined( $opts{options} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"options"}) 0 0 0
267 0 ▶ if ( ref( $opts{options} ) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $opts{"options"} ne "HASH") 0 0 0
268 0 $self->{perror} = 1;
269 0 $self->{error} = 8;
270 0 $self->{errorString} = 'ref for options is "' . ref( $opts{options} ) . '" and not HASH';
271 0 $self->warn;
272 }
273 0 $self->{options} = $opts{options};
274  
275 0 ▶ if ( defined( $opts{options}{type} ) && ref( $opts{options}{type} ) ne '' ) {
Branch: 3 branches
BranchTrueFalseTotal
if (defined $opts{'options'}{'type'} and ref $opts{'options'}{'type'} ne '') { } 0 0 0
elsif (defined $opts{'options'}{'type'} and $opts{'options'}{'type'} ne 'deny' and $opts{'options'}{'type'} ne 'reject') { } 0 0 0
elsif (not defined $opts{'options'}{'type'}) { } 0 0 0
Condition0%0/3
defined $opts{"options"}{"type"} and ref $opts{"options"}{"type"} ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $opts{"options"}{"type"} and ref $opts{"options"}{"type"} ne ""
defined $opts{"options"}{"type"} ref $opts{"options"}{"type"} ne ""
Truth table0%0/3
A and B
A= defined $opts{"options"}{"type"}B= ref $opts{"options"}{"type"} ne ""
ABresult
0X0
100
111
276 0 $self->{perror} = 1;
277 0 $self->{error} = 20;
278 0 $self->{errorString} = 'ref for $opts{options}{type} is "' . ref( $opts{options}{type} ) . '" and not ""';
279 0 $self->warn;
280 ▶ } elsif ( defined( $opts{options}{type} )
Condition0%0/6
defined $opts{"options"}{"type"} and $opts{"options"}{"type"} ne "deny" and $opts{"options"}{"type"} ne "reject"
!ll&&!rl&&r
000
defined $opts{"options"}{"type"} and $opts{"options"}{"type"} ne "deny"
!ll&&!rl&&r
000
MC/DC0%0/3
defined $opts{"options"}{"type"} and $opts{"options"}{"type"} ne "deny" and $opts{"options"}{"type"} ne "reject"
defined $opts{"options"}{"type"} $opts{"options"}{"type"} ne "deny" $opts{"options"}{"type"} ne "reject"
Truth table0%0/4
A and B and C
A= defined $opts{"options"}{"type"}B= $opts{"options"}{"type"} ne "deny"C= $opts{"options"}{"type"} ne "reject"
ABCresult
0XX0
10X0
1100
1111
281 && $opts{options}{type} ne 'deny'
282 && $opts{options}{type} ne 'reject' )
283 {
284 0 $self->{perror} = 1;
285 0 $self->{error} = 20;
286 $self->{errorString}
287 0 = '$opts{options}{type} is "' . $opts{options}{type} . '" and not "deny" or "reject"';
288 0 $self->warn;
289 } elsif ( !defined( $opts{options}{type} ) ) {
290 0 $self->{options}{type} = 'deny';
291 }
292  
293 0 ▶ if ( defined( $opts{options}{kill} )
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opts{'options'}{'kill'} and $opts{'options'}{'kill'} ne '' and $opts{'options'}{'kill'} ne 'ss' and $opts{'options'}{'kill'} ne 'conntrack') { } 0 0 0
elsif (not defined $opts{'options'}{'kill'}) { } 0 0 0
Condition0%0/9
defined $opts{"options"}{"kill"} and $opts{"options"}{"kill"} ne "" and $opts{"options"}{"kill"} ne "ss" and $opts{"options"}{"kill"} ne "conntrack"
!ll&&!rl&&r
000
defined $opts{"options"}{"kill"} and $opts{"options"}{"kill"} ne "" and $opts{"options"}{"kill"} ne "ss"
!ll&&!rl&&r
000
defined $opts{"options"}{"kill"} and $opts{"options"}{"kill"} ne ""
!ll&&!rl&&r
000
MC/DC0%0/4
defined $opts{"options"}{"kill"} and $opts{"options"}{"kill"} ne "" and $opts{"options"}{"kill"} ne "ss" and $opts{"options"}{"kill"} ne "conntrack"
defined $opts{"options"}{"kill"} $opts{"options"}{"kill"} ne "" $opts{"options"}{"kill"} ne "ss" $opts{"options"}{"kill"} ne "conntrack"
Truth table0%0/5
A and B and C and D
A= defined $opts{"options"}{"kill"}B= $opts{"options"}{"kill"} ne ""C= $opts{"options"}{"kill"} ne "ss"D= $opts{"options"}{"kill"} ne "conntrack"
ABCDresult
0XXX0
10XX0
110X0
11100
11111
294 && $opts{options}{kill} ne ''
295 && $opts{options}{kill} ne 'ss'
296 && $opts{options}{kill} ne 'conntrack' )
297 {
298 0 $self->{perror} = 1;
299 0 $self->{error} = 19;
300 $self->{errorString}
301 0 = '$opts{options}{kill} is "' . $opts{options}{kill} . '" and not "", "ss", or "conntrack"';
302 0 $self->warn;
303 } elsif ( !defined( $opts{options}{kill} ) ) {
304 0 $self->{options}{kill} = '';
305 }
306 } ## end if ( defined( $opts{options} ) )
307  
308 0 return $self;
309 } ## end sub new
310  
311 # Internal helper. Works out the protocol and port combinations this instance
312 # needs to block for the passed IP, and returns them as ufw rule
313 # specifications.
314 #
315 # This backend differs from the ipset based ones in a way that shapes
316 # everything here: ufw has no set or group concept, so there is nothing to add
317 # an address to. Rules are per address, which is why the IP is an argument
318 # rather than the specs being static and built once at init. Banning writes
319 # these rules and unbanning deletes them, so the count of rules on the host
320 # grows with the number of bans.
321 #
322 # There is no family split either. ufw works out the family from the address
323 # in the rule, so unlike the iptables and nftables backends there is no per
324 # family loop and no filtering of protocols that belong to the other family.
325 #
326 # Ports are only attached to tcp and udp, the only protocols ufw accepts a
327 # port specification for; anything else gets a protocol only rule.
328 #
329 # Args:
330 #
331 # ip - The address to build the specifications for, as a plain string.
332 # Expected to be an already validated and lowercased IPv4 or IPv6
333 # address. It is interpolated into the rule as is.
334 #
335 # Returns the specifications as a list of strings, one per rule. Each is the
336 # portion of the rule after the deny or reject verb, so the caller prepends
337 # 'ufw deny ' or 'ufw delete deny ' to it. There is one entry per applicable
338 # protocol, so a single ban may produce several rules.
339 #
340 # # no protocols and no ports: block everything from the address
341 # $self->_rule_specs('10.0.0.1');
342 # # from 10.0.0.1 to any
343 #
344 # # ports 22 with no protocols, so tcp and udp are assumed
345 # $self->_rule_specs('10.0.0.1');
346 # # proto tcp from 10.0.0.1 to any port 22
347 # # proto udp from 10.0.0.1 to any port 22
348 #
349 # # protocols tcp, ports 22 and 143
350 # # proto tcp from 10.0.0.1 to any port 22,143
351 #
352 # # protocols gre, which takes no ports
353 # # proto gre from 10.0.0.1 to any
354 0 ▶sub _rule_specs {
Subroutine _rule_specs: not called CC=9 SCAR=45.0
355 0 my ( $self, $ip ) = @_;
356  
357 0 my @ports = @{ $self->{ports} };
358 0 my @protos = @{ $self->{protocols} };
359 0 my $port_str = join( ',', @ports );
360  
361 # protocols that accept a port specification under ufw
362 0 my %port_ok = ( tcp => 1, udp => 1 );
363  
364 0 my @specs;
365 0 ▶ if ( !@protos && !@ports ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not @protos || @ports) { } 0 0 0
elsif (not @protos and @ports) { } 0 0 0
Condition0%0/3
@protos || @ports
l!l&&r!l&&!r
000
MC/DC0%0/2
@protos || @ports
@protos @ports
Truth table0%0/3
A || B
A= @protosB= @ports
ABresult
1X1
011
000
366 # block everything from the IP
367 0 push( @specs, 'from ' . $ip . ' to any' );
368 ▶ } elsif ( !@protos && @ports ) {
Condition0%0/3
not @protos and @ports
!ll&&!rl&&r
000
MC/DC0%0/2
not @protos and @ports
not @protos @ports
Truth table0%0/3
not(A) and B
A= not @protosB= @ports
ABresult
0X0
100
111
369 # ports require a protocol, default to tcp and udp
370 0 foreach my $proto ( 'tcp', 'udp' ) {
371 0 push( @specs, 'proto ' . $proto . ' from ' . $ip . ' to any port ' . $port_str );
372 }
373 } else {
374 0 foreach my $proto (@protos) {
375 0 ▶ if ( @ports && $port_ok{$proto} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@ports and $port_ok{$proto}) { } 0 0 0
Condition0%0/3
@ports and $port_ok{$proto}
!ll&&!rl&&r
000
MC/DC0%0/2
@ports and $port_ok{$proto}
@ports $port_ok{$proto}
Truth table0%0/3
A and B
A= @portsB= $port_ok{$proto}
ABresult
0X0
100
111
376 0 push( @specs, 'proto ' . $proto . ' from ' . $ip . ' to any port ' . $port_str );
377 } else {
378 0 push( @specs, 'proto ' . $proto . ' from ' . $ip . ' to any' );
379 }
380 }
381 } ## end else [ if ( !@protos && !@ports ) ]
382  
383 0 return @specs;
384 } ## end sub _rule_specs
385  
386 # Internal helper. Returns the commands that tear down the passed IP's
387 # existing connections, used when the kill option is on.
388 #
389 # This overrides the shared _kill_commands in
390 # Net::Firewall::BlockerHelper::Util, which the iptables, nftables, and
391 # firewalld backends inherit. It differs in two ways.
392 #
393 # First, it offers an ss based mode as well as the conntrack one, selected by
394 # the kill option. ss kills sockets directly rather than dropping conntrack
395 # entries, which is useful on a host where conntrack is not in play. ss can
396 # only kill TCP connections and connected UDP sockets, so its scoping is a
397 # choice between -t, -u, and -tu rather than a per protocol command; when
398 # neither TCP nor UDP is among the blocked protocols there is nothing it can
399 # do and no command is emitted at all. Note the address is bracketed
400 # unconditionally in the ss destination, which is the form ss accepts for both
401 # families.
402 #
403 # Second, the conntrack path here recognizes a much narrower protocol set,
404 # just tcp, udp, and gre, matching what ufw itself will write rules for. The
405 # shared version additionally handles sctp, dccp, udplite, and the ICMPs, none
406 # of which apply here, which is also why this version needs no ICMP family
407 # filtering and no duplicate suppression.
408 #
409 # Args:
410 #
411 # ip - The address whose connections should be dropped, as a plain string.
412 # Expected to be an already validated and lowercased IPv4 or IPv6
413 # address. In conntrack mode the family is decided by matching
414 # against $IPv4_re and controls the -f flag; in ss mode the address
415 # is used as is.
416 #
417 # Returns the commands as a list of strings, ready to hand to the runner. The
418 # ss mode returns exactly one command, or none when neither TCP nor UDP is
419 # being blocked. The conntrack mode returns one entry per applicable protocol,
420 # or a single unscoped entry when nothing is configured, and may be empty if
421 # every configured protocol was filtered out.
422 #
423 # # kill mode 'ss', nothing configured, so both TCP and UDP
424 # $self->_kill_commands('10.0.0.1');
425 # # ss -K -tu dst "[10.0.0.1]"
426 #
427 # # kill mode 'ss' with protocols tcp only
428 # # ss -K -t dst "[10.0.0.1]"
429 #
430 # # kill mode 'ss' with protocols gre only: nothing ss can kill
431 # $self->_kill_commands('10.0.0.1'); # ()
432 #
433 # # conntrack mode, nothing configured
434 # # conntrack -D -s 10.0.0.1
435 #
436 # # conntrack mode, IPv6, protocols tcp
437 # # conntrack -f ipv6 -D -p tcp -s 2001:db8::1
438 0 ▶sub _kill_commands {
Subroutine _kill_commands: not called CC=14 SCAR=53.5
439 0 my ( $self, $ip ) = @_;
440  
441 0 my @protos = @{ $self->{protocols} };
442 0 ▶ if ( !@protos && defined( $self->{ports}[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not @protos and defined $self->{"ports"}[0]) 0 0 0
Condition0%0/3
not @protos and defined $self->{"ports"}[0]
!ll&&!rl&&r
000
MC/DC0%0/2
not @protos and defined $self->{"ports"}[0]
not @protos defined $self->{"ports"}[0]
Truth table0%0/3
not(A) and B
A= not @protosB= defined $self->{"ports"}[0]
ABresult
0X0
100
111
443 # ports without protocols means tcp and udp are being blocked
444 0 @protos = ( 'tcp', 'udp' );
445 }
446  
447 0 ▶ if ( $self->{options}{kill} eq 'ss' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"options"}{"kill"} eq "ss") 0 0 0
448 # scope to -t/-u per the blocked protocols; ss can only kill TCP
449 # connections and connected UDP sockets, so if neither is being
450 # blocked there is nothing applicable to kill
451 0 my $flags = '-tu';
452 0 ▶ if (@protos) {
Branch: 1 branch
BranchTrueFalseTotal
if (@protos) 0 0 0
453 0 my $tcp = grep { $_ eq 'tcp' } @protos;
454 0 my $udp = grep { $_ eq 'udp' } @protos;
455 0 ▶ if ( $tcp && $udp ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($tcp and $udp) { } 0 0 0
elsif ($tcp) { } 0 0 0
elsif ($udp) { } 0 0 0
Condition0%0/3
$tcp and $udp
!ll&&!rl&&r
000
MC/DC0%0/2
$tcp and $udp
$tcp $udp
Truth table0%0/3
A and B
A= $tcpB= $udp
ABresult
0X0
100
111
456 0 $flags = '-tu';
457 } elsif ($tcp) {
458 0 $flags = '-t';
459 } elsif ($udp) {
460 0 $flags = '-u';
461 } else {
462 0 return ();
463 }
464 } ## end if (@protos)
465 0 return ( 'ss -K ' . $flags . ' dst "[' . $ip . ']"' );
466 } ## end if ( $self->{options}{kill} eq 'ss' )
467  
468 # conntrack defaults to IPv4, so IPv6 IPs need the family specified
469 0 ▶ my $is_v4 = ( $ip =~ /\A$IPv4_re\z/ ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$ip =~ /\A$Net::Firewall::BlockerHelper::backends::ufw::IPv4_re\z/ ? : 0 0 0
470 0 ▶ my $family = $is_v4 ? '' : '-f ipv6 ';
Branch: 1 branch
BranchTrueFalseTotal
$is_v4 ? : 0 0 0
471  
472 # nothing configured means everything is being blocked, so drop every
473 # entry for the IP
474 0 ▶ if ( !@protos ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@protos) 0 0 0
475 0 return ( 'conntrack ' . $family . '-D -s ' . $ip );
476 }
477  
478 # scope the kill to the blocked protocols; ones conntrack can not filter
479 # by are skipped
480 0 my %conntrack_protos = ( tcp => 'tcp', udp => 'udp', gre => 'gre' );
481  
482 0 my @commands;
483 0 foreach my $proto (@protos) {
484 0 my $conntrack_proto = $conntrack_protos{$proto};
485 0 ▶ next if ( !defined($conntrack_proto) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $conntrack_proto 0 0 0
486 0 push( @commands, 'conntrack ' . $family . '-D -p ' . $conntrack_proto . ' -s ' . $ip );
487 }
488  
489 0 return @commands;
490 } ## end sub _kill_commands
491  
492 # Internal helper. Returns the command used to confirm that ufw is actually
493 # enabled, which is this backend's health check.
494 #
495 # There is no container to look for here, no chain and no set, so unlike the
496 # other packet filter backends there is nothing whose presence would prove the
497 # setup is intact. What can go wrong instead is ufw being disabled out from
498 # under a running process, at which point every rule stops applying while ufw
499 # still happily accepts new ones. Checking the status is the closest
500 # equivalent, and it is what check and the self heal path use to decide
501 # whether a rebuild is needed.
502 #
503 # The grep is what turns the check into an exit status: ufw status always
504 # succeeds, and prints "Status: active" or "Status: inactive", so the state
505 # has to be read out of the output rather than the return code. Matching is
506 # anchored, case insensitive, and tolerant of the spacing.
507 #
508 # Takes no arguments.
509 #
510 # Returns the command as a single string ready to hand to the runner, a
511 # pipeline whose exit status is 0 when ufw is enabled and non zero when it is
512 # not.
513 #
514 # $self->_status_command;
515 # # ufw status | grep -qiE "^Status:[[:space:]]*active"
516 0 ▶sub _status_command {
Subroutine _status_command: not called CC=1 SCAR=6.9
517 0 my ($self) = @_;
518  
519 0 return 'ufw status | grep -qiE "^Status:[[:space:]]*active"';
520 }
521  
522 =head2 init
523  
524 Initiates the backend. As there is no container to create, this just
525 verifies that ufw is enabled via C<ufw status>.
526  
527 $backend->init;
528  
529 =cut
530  
531 0 ▶sub init {
Subroutine init: not called CC=5 SCAR=34.0
Pod documented
532 0 my ( $self, %opts ) = @_;
533  
534 0 $self->errorblank;
535  
536 0 ▶ if ( $self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"inited"}) 0 0 0
537 0 $self->{error} = 18;
538 0 $self->{errorString} = 'backend has already been inited';
539 0 $self->warn;
540 }
541  
542 0 my @commands = ( $self->_status_command );
543  
544 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
545 0 $self->{frontend_obj}->{test_data} = { commands => \@commands };
546 } else {
547 0 foreach my $item (@commands) {
548 0 my $output = `$item 2>&1`;
549 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
550 0 $self->{error} = 23;
551 $self->{errorString}
552 0 = 'init failed. ufw does not appear to be enabled... the command "'
553 . $item
554 . '" exited non-zero... output... '
555 . $output;
556 0 $self->warn;
557 }
558 }
559 } ## end else [ if ( $self->{testing} ) ]
560  
561 0 $self->{inited} = 1;
562 } ## end sub init
563  
564 =head2 ban
565  
566 Bans an IP. The value of ban is validated as being a IPv4 or IPv6 address
567 and lowercased, then one C<< ufw prepend <type> ... >> rule per protocol is
568 added for it, based on the configured protocols and ports. If the C<kill>
569 option is set, existing connections/state for the IP are killed via C<ss -K>
570 or C<conntrack -D>. Banning an already banned IP is a noop.
571  
572 $backend->ban(ban => $ip);
573  
574 =cut
575  
576 0 ▶sub ban {
Subroutine ban: not called CC=15 SCAR=54.8
Pod documented
577 0 my ( $self, %opts ) = @_;
578  
579 0 $self->errorblank;
580  
581 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
582 0 $self->{error} = 1;
583 0 $self->{errorString} = 'backend has not been inited';
584 0 $self->warn;
585 0 return;
586 }
587  
588 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::ufw::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::ufw::IPv6_re\z/) { } 0 0 0
589 0 $self->{error} = 9;
590 0 $self->{errorString} = 'Nothing specified for the value ban';
591 0 $self->warn;
592 0 return;
593 } elsif ( ref( $opts{ban} ) ne '' ) {
594 0 $self->{error} = 10;
595 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
596 0 $self->warn;
597 0 return;
598 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition0%0/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::ufw::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::ufw::IPv6_re\z/
l!l&&r!l&&!r
000
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::ufw::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::ufw::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::ufw::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::ufw::IPv6_re\z/
Truth table0%0/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::ufw::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::ufw::IPv6_re\z/
ABresult
1X1
011
000
599 && $opts{ban} !~ /\A$IPv6_re\z/ )
600 {
601 0 $self->{error} = 10;
602 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
603 0 $self->warn;
604 0 return;
605 }
606  
607 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
608 0 $opts{ban} = lc( $opts{ban} );
609  
610 0 ▶ if ( $self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"banned"}{$opts{"ban"}}) 0 0 0
611 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
612 0 $self->{frontend_obj}->{test_data} = 'already banned';
613 }
614 0 return;
615 }
616  
617 0 my @commands;
618 0 foreach my $spec ( $self->_rule_specs( $opts{ban} ) ) {
619 0 push( @commands, 'ufw prepend ' . $self->{options}{type} . ' ' . $spec );
620 }
621  
622 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
623 0 $self->{frontend_obj}->{test_data} = \@commands;
624 } else {
625 0 foreach my $item (@commands) {
626 0 my $output = `$item 2>&1`;
627 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
628 0 $self->{error} = 13;
629 $self->{errorString}
630 0 = 'ban failed. non-zero exit code for the command... "' . $item . '"... output... ' . $output;
631 0 $self->warn;
632 }
633 }
634 } ## end else [ if ( $self->{testing} ) ]
635  
636 0 ▶ if ( $self->{options}{kill} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"options"}{"kill"}) 0 0 0
637 0 foreach my $kill_command ( $self->_kill_commands( $opts{ban} ) ) {
638 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
639 0 push( @{ $self->{frontend_obj}->{test_data} }, $kill_command );
640 } else {
641 # best effort; exit codes are intentionally ignored as both
642 # commands exit non-zero when there is nothing matching to kill
643 0 my $output = `$kill_command 2>&1`;
644 }
645 }
646 } ## end if ( $self->{options}{kill} )
647  
648 0 $self->{banned}{ $opts{ban} } = 1;
649 } ## end sub ban
650  
651 =head2 unban
652  
653 Unbans an IP. The value of ban is validated as being a IPv4 or IPv6 address
654 and lowercased, then its rules are removed via C<< ufw delete <type> ... >>,
655 one per protocol. Unbanning an IP that is not banned is a noop.
656  
657 $backend->unban(ban => $ip);
658  
659 =cut
660  
661 0 ▶sub unban {
Subroutine unban: not called CC=12 SCAR=50.5
Pod documented
662 0 my ( $self, %opts ) = @_;
663  
664 0 $self->errorblank;
665  
666 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
667 0 $self->{error} = 1;
668 0 $self->{errorString} = 'backend has not been inited';
669 0 $self->warn;
670 0 return;
671 }
672  
673 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::ufw::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::ufw::IPv6_re\z/) { } 0 0 0
674 0 $self->{error} = 9;
675 0 $self->{errorString} = 'Nothing specified for the value ban';
676 0 $self->warn;
677 0 return;
678 } elsif ( ref( $opts{ban} ) ne '' ) {
679 0 $self->{error} = 10;
680 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
681 0 $self->warn;
682 0 return;
683 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition0%0/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::ufw::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::ufw::IPv6_re\z/
l!l&&r!l&&!r
000
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::ufw::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::ufw::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::ufw::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::ufw::IPv6_re\z/
Truth table0%0/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::ufw::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::ufw::IPv6_re\z/
ABresult
1X1
011
000
684 && $opts{ban} !~ /\A$IPv6_re\z/ )
685 {
686 0 $self->{error} = 10;
687 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
688 0 $self->warn;
689 0 return;
690 }
691  
692 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
693 0 $opts{ban} = lc( $opts{ban} );
694  
695 0 ▶ if ( !$self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"banned"}{$opts{"ban"}}) 0 0 0
696 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
697 0 $self->{frontend_obj}->{test_data} = 'not banned';
698 }
699 0 return;
700 }
701  
702 0 my @commands;
703 0 foreach my $spec ( $self->_rule_specs( $opts{ban} ) ) {
704 0 push( @commands, 'ufw delete ' . $self->{options}{type} . ' ' . $spec );
705 }
706  
707 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
708 0 $self->{frontend_obj}->{test_data} = \@commands;
709 } else {
710 0 foreach my $item (@commands) {
711 0 my $output = `$item 2>&1`;
712 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
713 0 $self->{error} = 14;
714 $self->{errorString}
715 0 = 'unban failed. non-zero exit code for the command... "' . $item . '"... output... ' . $output;
716 0 $self->warn;
717 }
718 }
719 } ## end else [ if ( $self->{testing} ) ]
720  
721 0 delete( $self->{banned}{ $opts{ban} } );
722 } ## end sub unban
723  
724 =head2 ban_cidr
725  
726 Bans a CIDR range by prepending one or more per-range rules via
727 C<< ufw prepend <type> ... >>, one per protocol, in the same manner as a
728 single IP. The value of ban is validated as being a IPv4 or IPv6 CIDR range
729 and lowercased. Banning an already banned range is a noop.
730  
731 $backend->ban_cidr(ban => '1.2.3.0/24');
732  
733 =cut
734  
735 0 ▶sub ban_cidr {
Subroutine ban_cidr: not called CC=11 SCAR=48.8
Pod documented
736 0 my ( $self, %opts ) = @_;
737  
738 0 $self->errorblank;
739  
740 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
741 0 $self->{error} = 1;
742 0 $self->{errorString} = 'backend has not been inited';
743 0 $self->warn;
744 0 return;
745 }
746  
747 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
748 0 $self->{error} = 9;
749 0 $self->{errorString} = 'Nothing specified for the value ban';
750 0 $self->warn;
751 0 return;
752 } elsif ( ref( $opts{ban} ) ne '' ) {
753 0 $self->{error} = 28;
754 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
755 0 $self->warn;
756 0 return;
757 } elsif ( !$self->_valid_cidr( $opts{ban} ) ) {
758 0 $self->{error} = 28;
759 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 CIDR';
760 0 $self->warn;
761 0 return;
762 }
763  
764 # lowercase so the same IPv6 CIDR in differing cases can't result in duplicate entries
765 0 $opts{ban} = lc( $opts{ban} );
766  
767 0 ▶ if ( $self->{banned_cidr}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"banned_cidr"}{$opts{"ban"}}) 0 0 0
768 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
769 0 $self->{frontend_obj}->{test_data} = 'already banned';
770 }
771 0 return;
772 }
773  
774 0 my @commands;
775 0 foreach my $spec ( $self->_rule_specs( $opts{ban} ) ) {
776 0 push( @commands, 'ufw prepend ' . $self->{options}{type} . ' ' . $spec );
777 }
778  
779 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
780 0 $self->{frontend_obj}->{test_data} = \@commands;
781 } else {
782 0 foreach my $item (@commands) {
783 0 my $output = `$item 2>&1`;
784 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
785 0 $self->{error} = 26;
786 $self->{errorString}
787 0 = 'ban failed. non-zero exit code for the command... "' . $item . '"... output... ' . $output;
788 0 $self->warn;
789 }
790 }
791 } ## end else [ if ( $self->{testing} ) ]
792  
793 0 $self->{banned_cidr}{ $opts{ban} } = 1;
794 } ## end sub ban_cidr
795  
796 =head2 unban_cidr
797  
798 Unbans a CIDR range by deleting its per-range rules via
799 C<< ufw delete <type> ... >>. The value of ban is validated as being a IPv4
800 or IPv6 CIDR range and lowercased. Unbanning a range that is not banned is
801 a noop.
802  
803 $backend->unban_cidr(ban => '1.2.3.0/24');
804  
805 =cut
806  
807 0 ▶sub unban_cidr {
Subroutine unban_cidr: not called CC=11 SCAR=48.8
Pod documented
808 0 my ( $self, %opts ) = @_;
809  
810 0 $self->errorblank;
811  
812 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
813 0 $self->{error} = 1;
814 0 $self->{errorString} = 'backend has not been inited';
815 0 $self->warn;
816 0 return;
817 }
818  
819 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
820 0 $self->{error} = 9;
821 0 $self->{errorString} = 'Nothing specified for the value ban';
822 0 $self->warn;
823 0 return;
824 } elsif ( ref( $opts{ban} ) ne '' ) {
825 0 $self->{error} = 28;
826 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
827 0 $self->warn;
828 0 return;
829 } elsif ( !$self->_valid_cidr( $opts{ban} ) ) {
830 0 $self->{error} = 28;
831 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 CIDR';
832 0 $self->warn;
833 0 return;
834 }
835  
836 # lowercase so the same IPv6 CIDR in differing cases can't result in duplicate entries
837 0 $opts{ban} = lc( $opts{ban} );
838  
839 0 ▶ if ( !$self->{banned_cidr}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"banned_cidr"}{$opts{"ban"}}) 0 0 0
840 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
841 0 $self->{frontend_obj}->{test_data} = 'not banned';
842 }
843 0 return;
844 }
845  
846 0 my @commands;
847 0 foreach my $spec ( $self->_rule_specs( $opts{ban} ) ) {
848 0 push( @commands, 'ufw delete ' . $self->{options}{type} . ' ' . $spec );
849 }
850  
851 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
852 0 $self->{frontend_obj}->{test_data} = \@commands;
853 } else {
854 0 foreach my $item (@commands) {
855 0 my $output = `$item 2>&1`;
856 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
857 0 $self->{error} = 27;
858 $self->{errorString}
859 0 = 'unban failed. non-zero exit code for the command... "' . $item . '"... output... ' . $output;
860 0 $self->warn;
861 }
862 }
863 } ## end else [ if ( $self->{testing} ) ]
864  
865 0 delete( $self->{banned_cidr}{ $opts{ban} } );
866 } ## end sub unban_cidr
867  
868 =head2 list_cidr
869  
870 List banned CIDR ranges. Returns an array of the currently banned CIDR
871 ranges. Single IPs are not included; for those see L</list>.
872  
873 my @banned_cidrs = $backend->list_cidr;
874  
875 =cut
876  
877 0 ▶sub list_cidr {
Subroutine list_cidr: not called CC=2 SCAR=17.9
Pod documented
878 0 my ( $self, %opts ) = @_;
879  
880 0 $self->errorblank;
881  
882 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
883 0 $self->{frontend_obj}->{test_data} = 'list_cidr';
884 }
885  
886 0 return keys( %{ $self->{banned_cidr} } );
887 }
888  
889 =head2 list
890  
891 List banned IPs. Returns an array of the currently banned single IPs. CIDR
892 ranges are not included; for those see L</list_cidr>.
893  
894 my @banned = $backend->list;
895  
896 =cut
897  
898 0 ▶sub list {
Subroutine list: not called CC=2 SCAR=17.9
Pod documented
899 0 my ( $self, %opts ) = @_;
900  
901 0 $self->errorblank;
902  
903 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
904 0 $self->{frontend_obj}->{test_data} = 'list';
905 }
906  
907 0 return keys( %{ $self->{banned} } );
908 }
909  
910 =head2 re_init
911  
912 Tells the backend to re-init it's self.
913  
914 This will call teardown and init again. After that it will
915 re-added all previously added bans.
916  
917 $backend->re_init;
918  
919 =cut
920  
921 0 ▶sub re_init {
Subroutine re_init: not called CC=6 SCAR=37.4
Pod documented
922 0 my ( $self, %opts ) = @_;
923  
924 0 $self->errorblank;
925  
926 # teardown is best effort here as a partially or fully wiped setup is
927 # exactly what re_init needs to recover from; init cleans up any remnants
928 {
929 0 local $@;
930 0 eval { $self->teardown; };
931 }
932 0 $self->init;
933  
934 # both single IPs and CIDR ranges are re-added the same way
935 0 my @to_ban = ( keys( %{ $self->{banned} } ), keys( %{ $self->{banned_cidr} } ) );
936  
937 0 my @re_init_test_data;
938 0 foreach my $item (@to_ban) {
939 0 foreach my $spec ( $self->_rule_specs($item) ) {
940 0 my $command = 'ufw prepend ' . $self->{options}{type} . ' ' . $spec;
941  
942 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
943 0 push( @re_init_test_data, $command );
944 } else {
945 0 my $output = `$command 2>&1`;
946 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
947 0 $self->{error} = 13;
948 $self->{errorString}
949 0 = 'ban failed. non-zero exit code for the command... "' . $command . '"... output... ' . $output;
950 0 $self->warn;
951 }
952 }
953 } ## end foreach my $spec ( $self->_rule_specs($item) )
954 } ## end foreach my $item (@to_ban)
955  
956 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
957 0 $self->{frontend_obj}->{test_data} = \@re_init_test_data;
958 }
959  
960 0 $self->{inited} = 1;
961 } ## end sub re_init
962  
963 =head2 teardown
964  
965 Tears down the setup for the backend by deleting the rules for all currently
966 banned IPs. The internal list of bans is kept, so a following re_init will
967 re-add them.
968  
969 $backend->teardown;
970  
971 =cut
972  
973 0 ▶sub teardown {
Subroutine teardown: not called CC=8 SCAR=42.8
Pod documented
974 0 my ( $self, %opts ) = @_;
975  
976 0 $self->errorblank;
977  
978 0 $self->{inited} = 0;
979  
980 0 my @commands;
981 0 foreach my $item ( keys( %{ $self->{banned} } ) ) {
982 0 foreach my $spec ( $self->_rule_specs($item) ) {
983 0 push( @commands, 'ufw delete ' . $self->{options}{type} . ' ' . $spec );
984 }
985 }
986 0 foreach my $item ( keys( %{ $self->{banned_cidr} } ) ) {
987 0 foreach my $spec ( $self->_rule_specs($item) ) {
988 0 push( @commands, 'ufw delete ' . $self->{options}{type} . ' ' . $spec );
989 }
990 }
991  
992 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
993 0 $self->{frontend_obj}->{test_data} = \@commands;
994 } else {
995 0 foreach my $item (@commands) {
996 0 my $output = `$item 2>&1`;
997 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
998 0 $self->{error} = 17;
999 $self->{errorString}
1000 0 = 'teardown failed. non-zero exit code for the command... "' . $item . '"... output... ' . $output;
1001 0 $self->warn;
1002 }
1003 }
1004 } ## end else [ if ( $self->{testing} ) ]
1005 } ## end sub teardown
1006  
1007 =head2 stop
1008  
1009 Alias for L</teardown>, provided for parity with the fail2ban C<actionstop>
1010 concept.
1011  
1012 $backend->stop;
1013  
1014 =cut
1015  
1016 0 ▶sub stop {
Subroutine stop: not called CC=1 SCAR=6.9
Pod documented
1017 0 my ( $self, %opts ) = @_;
1018  
1019 0 return $self->teardown(%opts);
1020 }
1021  
1022 =head2 check
1023  
1024 Verifies that ufw is still enabled. Returns a true value if it is and a
1025 false value otherwise. This is the equivalent of fail2ban's C<actioncheck>.
1026  
1027 if ( !$backend->check ) {
1028 $backend->re_init;
1029 }
1030  
1031 =cut
1032  
1033 0 ▶sub check {
Subroutine check: not called CC=4 SCAR=30.0
Pod documented
1034 0 my ( $self, %opts ) = @_;
1035  
1036 0 $self->errorblank;
1037  
1038 0 my @commands = ( $self->_status_command );
1039  
1040 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1041 0 $self->{frontend_obj}->{test_data} = \@commands;
1042 0 return 1;
1043 }
1044  
1045 0 foreach my $item (@commands) {
1046 0 my $output = `$item 2>&1`;
1047 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
1048 0 return 0;
1049 }
1050 }
1051  
1052 0 return 1;
1053 } ## end sub check
1054  
1055 =head2 flush
1056  
1057 Removes all currently banned IPs at once by deleting their rules and
1058 forgetting them. This is the equivalent of fail2ban's C<actionflush>.
1059  
1060 $backend->flush;
1061  
1062 =cut
1063  
1064 0 ▶sub flush {
Subroutine flush: not called CC=9 SCAR=45.0
Pod documented
1065 0 my ( $self, %opts ) = @_;
1066  
1067 0 $self->errorblank;
1068  
1069 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
1070 0 $self->{error} = 1;
1071 0 $self->{errorString} = 'backend has not been inited';
1072 0 $self->warn;
1073 0 return;
1074 }
1075  
1076 0 my @commands;
1077 0 foreach my $item ( keys( %{ $self->{banned} } ) ) {
1078 0 foreach my $spec ( $self->_rule_specs($item) ) {
1079 0 push( @commands, 'ufw delete ' . $self->{options}{type} . ' ' . $spec );
1080 }
1081 }
1082 0 foreach my $item ( keys( %{ $self->{banned_cidr} } ) ) {
1083 0 foreach my $spec ( $self->_rule_specs($item) ) {
1084 0 push( @commands, 'ufw delete ' . $self->{options}{type} . ' ' . $spec );
1085 }
1086 }
1087  
1088 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
1089 0 $self->{frontend_obj}->{test_data} = \@commands;
1090 } else {
1091 0 foreach my $item (@commands) {
1092 0 my $output = `$item 2>&1`;
1093 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
1094 0 $self->{error} = 25;
1095 $self->{errorString}
1096 0 = 'flush failed. non-zero exit code for the command... "' . $item . '"... output... ' . $output;
1097 0 $self->warn;
1098 }
1099 }
1100 } ## end else [ if ( $self->{testing} ) ]
1101  
1102 0 $self->{banned} = {};
1103 0 $self->{banned_cidr} = {};
1104 } ## end sub flush
1105  
1106 =head1 ERROR CODES / FLAGS
1107  
1108 Error handling is provided by L<Error::Helper>. All
1109 errors are considered fatal.
1110  
1111 =head2 1, notInited
1112  
1113 The backend has not been inited yet.
1114  
1115 =head2 2, invalidPortSpecified
1116  
1117 Port is either not an int within the range 1 to 65535 or a name that can be resolved by getservbyname.
1118  
1119 =head2 3, portsNotArray
1120  
1121 The data passed to new for ports is not an array.
1122  
1123 =head2 4, protocolsNotArray
1124  
1125 The data passed to new for protocols is not an array.
1126  
1127 =head2 5, invalidProtocolSpecified
1128  
1129 The specified protocol could not be resolved via getprotobyname or is not
1130 one understood by ufw.
1131  
1132 =head2 6, invalidPrefixSpecified
1133  
1134 The specified prefix did not match /^[a-zA-Z0-9]+$/.
1135  
1136 =head2 7, invalidName
1137  
1138 The name is either undef or does not match /^[a-zA-Z0-9\-]+$/.
1139  
1140 =head2 8, optionsNotHash
1141  
1142 The item passed to new for options is not a hash.
1143  
1144 =head2 9, noBanItem
1145  
1146 No IP or CIDR range specified to ban or unban.
1147  
1148 =head2 10, banItemNotIP
1149  
1150 The item to ban is not an IP. Either wrong ref type or regexp
1151 test using L<Regexp::IPv4> and L<Regexp::IPv6> failed.
1152  
1153 =head2 12, backendInitError
1154  
1155 Failed to init the backend.
1156  
1157 =head2 13, banFailed
1158  
1159 Failed to ban the item.
1160  
1161 =head2 14, unbanFailed
1162  
1163 Failed to unban the item.
1164  
1165 =head2 15, listFailed
1166  
1167 Failed to get a list of bans.
1168  
1169 =head2 16, reInitFailed
1170  
1171 Failed to re_init the backend.
1172  
1173 =head2 17, teardownFailed
1174  
1175 Failed to teardown the backend.
1176  
1177 =head2 18, alreadyInited
1178  
1179 init called, but the backend has already been inited.
1180  
1181 =head2 19, killInvalid
1182  
1183 The option kill is not '', 'ss', or 'conntrack'.
1184  
1185 =head2 20, typeInvalid
1186  
1187 The option type is not 'deny' or 'reject'.
1188  
1189 =head2 23, initFailed
1190  
1191 init failed. ufw does not appear to be enabled.
1192  
1193 =head2 24, checkFailed
1194  
1195 The backend check raised an error.
1196  
1197 =head2 25, flushFailed
1198  
1199 Failed to flush the bans.
1200  
1201 =head2 26, banCidrFailed
1202  
1203 Failed to ban the CIDR range.
1204  
1205 =head2 27, unbanCidrFailed
1206  
1207 Failed to unban the CIDR range.
1208  
1209 =head2 28, cidrItemNotCidr
1210  
1211 The item to ban is not a CIDR range. Either wrong ref type or it is not an
1212 IPv4 or IPv6 address followed by a prefix length valid for its family.
1213  
1214 =head2 29, cidrNotSupported
1215  
1216 The backend does not support CIDR bans.
1217  
1218 =head2 30, listCidrFailed
1219  
1220 Failed to get a list of CIDR bans.
1221  
1222 =head1 AUTHOR
1223  
1224 Zane C. Bowers-Hadley, C<< <vvelox at vvelox.ent> >>
1225  
1226 =head1 BUGS
1227  
1228 Please report any bugs or feature requests to C<bug-net-firewall-blockerhelper at rt.cpan.org>, or through
1229 the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Net-Firewall-BlockerHelper>.
1230  
1231 =head1 LICENSE AND COPYRIGHT
1232  
1233 This software is Copyright (c) 2023 by Zane C. Bowers-Hadley.
1234  
1235 This is free software, licensed under:
1236  
1237 The GNU Lesser General Public License, Version 2.1, February 1999
1238  
1239  
1240 =cut
1241  
1242 1 1; # End of Net::Firewall::BlockerHelper
« BlockerHelper/backends/nftables.pm ↑ Summary BlockerHelper/backends/openwrt.pm »