BlockerHelper/backends/openwrt.pm

filter: Statementstmt 6.4% 41 / 638 Branchbran 5.8% 16 / 276 Conditioncond 3.7% 3 / 81 MC/DCmcdc 0.0% 0 / 49 Subroutinesub 19.4% 7 / 36 Podpod 100% 14 / 14 totaltotal 7.4% 81 / 1094 CC 192 SCAR 56.7
CC
192
Cov
6%
new
1003.3
check
306.0
_render_local
240.0
CRAP 289.6
« BlockerHelper/backends/ufw.pm ↑ Summary BlockerHelper/backends/firewalld.pm »
1 package Net::Firewall::BlockerHelper::backends::openwrt;
2  
3 2 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use base qw( Error::Helper Net::Firewall::BlockerHelper::Util );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use Regexp::IPv4 qw($IPv4_re);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use Regexp::IPv6 qw($IPv6_re);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 =head1 NAME
11  
12 Net::Firewall::BlockerHelper::backends::openwrt - OpenWrt fw4 backend for Net::Firewall::BlockerHelper.
13  
14 =head1 VERSION
15  
16 Version 0.2.0
17  
18 =cut
19  
20 2 our $VERSION = '0.2.0';
21  
22 =head1 SYNOPSIS
23  
24 use Net::Firewall::BlockerHelper;
25  
26 # driving the local router
27 my $fw_helper = Net::Firewall::BlockerHelper->new(
28 backend => 'openwrt',
29 ports => ['22'],
30 protocols => ['tcp'],
31 name => 'ssh',
32 options => { zone => 'wan' },
33 );
34  
35 # driving a remote router over ubus JSON-RPC
36 my $fw_helper = Net::Firewall::BlockerHelper->new(
37 backend => 'openwrt',
38 ports => ['22'],
39 protocols => ['tcp'],
40 name => 'ssh',
41 options => {
42 zone => 'wan',
43 host => '192.0.2.1',
44 user => 'blocker',
45 password => 'hunter2',
46 },
47 );
48  
49 $fw_helper->init_backend;
50 $fw_helper->ban(ban => '1.2.3.4');
51 $fw_helper->ban_cidr(ban => '1.2.3.0/24');
52  
53 # write the current ban list to flash so it survives a reboot
54 $fw_helper->commit;
55  
56 $fw_helper->teardown;
57  
58 =head1 DESCRIPTION
59  
60 Blocks IPs on OpenWrt via fw4, configured through UCI rather than by writing
61 firewall rules directly.
62  
63 Two C<config ipset> sections are added to C</etc/config/firewall>, one per
64 address family (C<< <prefix>_<name>_4 >> and C<< <prefix>_<name>_6 >>), along
65 with the C<config rule> sections that drop or reject traffic matching them.
66 fw4 renders each ipset into an nftables set inside its own C<inet fw4> table.
67 Because the sets are declared with C<< match 'src_net' >>, they are interval
68 sets and hold both single addresses and CIDR ranges, so this backend supports
69 CIDR bans.
70  
71 Banning does not touch UCI. An IP or range is added straight to the live set
72 with C<nft add element>, which takes effect immediately and needs no reload.
73 This matters on a router: an C<fw4 reload> rebuilds the whole ruleset and is
74 far too expensive to run per ban.
75  
76 Persisting the ban list is therefore a separate, explicit step. See L</commit>.
77  
78 The backend runs in one of two modes. With no C<host> option it drives the
79 local machine, running C<uci>, C<fw4>, and C<nft> directly, which is the mode
80 to use when this is running on the router itself. With C<host> set it drives a
81 remote router over ubus JSON-RPC, which is the mode to use from a management
82 host, and is usually what is wanted given OpenWrt ships no perl.
83  
84 Local mode requires C<uci>, C<fw4>, and C<nft> in the C<PATH> of a process
85 with sufficient privileges.
86  
87 Remote mode requires C<uhttpd-mod-ubus> and C<rpcd-mod-file> on the router,
88 L<LWP::UserAgent> and L<JSON> locally, and an rpcd ACL granting the
89 configured user the calls this makes. Nothing grants C<file> C<exec> by
90 default, so without an ACL every C<nft> and C<fw4> call comes back as ubus
91 permission denied. Drop the following in
92 C</usr/share/rpcd/acl.d/net-firewall-blockerhelper.json> and run
93 C<< /etc/init.d/rpcd reload >>.
94  
95 {
96 "net-firewall-blockerhelper": {
97 "description": "Net::Firewall::BlockerHelper openwrt backend",
98 "read": {
99 "ubus": { "uci": [ "get" ] },
100 "uci": [ "firewall" ]
101 },
102 "write": {
103 "ubus": {
104 "uci": [ "add", "set", "delete", "order", "commit" ],
105 "file": [ "exec" ]
106 },
107 "uci": [ "firewall" ],
108 "file": {
109 "/usr/sbin/nft": [ "exec" ],
110 "/sbin/fw4": [ "exec" ]
111 }
112 }
113 }
114 }
115  
116 C</usr/share/rpcd/acl.d/> is part of the root filesystem, which on OpenWrt is
117 an overlay whose upper layer lives in flash, so the file survives a reboot.
118 It is not carried across a sysupgrade, as it is not in the default keep list,
119 nor across a factory reset. Add its path to C</etc/sysupgrade.conf> to keep
120 it through firmware upgrades; without it, remote mode starts failing with
121 permission denied after the upgrade.
122  
123 =head2 ENABLING KILL SUPPORT
124  
125 Blocking an address only stops new connections. Anything already established
126 keeps flowing, because the block rules match the source but the existing
127 traffic has already been accepted and is tracked. The C<kill> option drops
128 those connection tracking entries too, which is what actually cuts an
129 attacker off mid session.
130  
131 It is off by default and needs a package that OpenWrt does not install on its
132 own. To turn it on:
133  
134 =over 4
135  
136 =item 1.
137  
138 Install the C<conntrack> package on the router. Note the name: the userspace
139 tool is packaged as C<conntrack>, not as C<conntrack-tools>, which is the
140 name of the upstream project rather than of anything installable here.
141  
142 apk add conntrack
143  
144 # on releases still using opkg
145 opkg update && opkg install conntrack
146  
147 The kernel side, C<kmod-nf-conntrack> and C<kmod-nf-conntrack6>, is already
148 present on any router running fw4, as fw4 depends on it.
149  
150 =item 2.
151  
152 Pass the option.
153  
154 my $fw_helper = Net::Firewall::BlockerHelper->new(
155 backend => 'openwrt',
156 ports => ['22'],
157 protocols => ['tcp'],
158 name => 'ssh',
159 options => { zone => 'wan', kill => 1 },
160 );
161  
162 =item 3.
163  
164 In remote mode only, add the binary to the C<file> section of the rpcd ACL
165 shown above and reload rpcd. Confirm the path first, as it is not the same on
166 every build:
167  
168 command -v conntrack # usually /usr/sbin/conntrack
169  
170 "file": {
171 "/usr/sbin/nft": [ "exec" ],
172 "/sbin/fw4": [ "exec" ],
173 "/usr/sbin/conntrack": [ "exec" ]
174 }
175  
176 =back
177  
178 Skipping any of that is not an error. conntrack returns a non-zero exit
179 status whenever it has nothing to delete, which is the common case, so its
180 status is ignored and a missing binary or a denying ACL is indistinguishable
181 from a ban with no established connections. The bans still work; the kill
182 just quietly does nothing. If it matters, verify it rather than assume, by
183 banning an address with a connection open and watching
184 C<< conntrack -L -s <address> >> empty out.
185  
186 The kill is scoped to what is actually being blocked. With protocols
187 configured, one conntrack call is made per protocol, so blocking only udp
188 will not drop tcp entries. With none, everything is being blocked and every
189 entry for the address goes. Protocols conntrack cannot filter by are skipped.
190  
191 =head1 NOTES
192  
193 Persistence is not automatic and this is deliberate. C<uci commit> writes to
194 the overlay filesystem, which on most OpenWrt devices is flash with a finite
195 erase budget, so committing once per ban would wear it out. Bans are applied
196 to the live nftables set only, and are lost by anything that rebuilds fw4's
197 table until L</commit> has been called. L</init> and L</teardown> commit on
198 their own because they change the UCI config and there is nothing to write
199 out otherwise.
200  
201 An C<fw4 reload> preserves the contents of the sets; an C<fw4 restart>, an
202 C<< /etc/init.d/firewall restart >>, and a reboot all empty them. Whatever
203 has been committed comes back by itself, as fw4 seeds each set from the
204 C<entry> list of its C<config ipset> section. Anything banned since the last
205 L</commit> does not, and is recovered by L</check> noticing and L</re_init>
206 putting it back, which is what the frontend's self healing does
207 automatically.
208  
209 The first L</commit> rewrites C</etc/config/firewall>. This is C<uci commit>
210 doing what it always does, canonicalising the whole file rather than editing
211 the lines it changed, and it drops every comment in the file along the way,
212 including the block of commented out examples a stock config ships with. The
213 configuration itself is unchanged. Nothing here can avoid it, so take a copy
214 of the file first if those comments are wanted.
215  
216 Overlapping CIDR bans do not round trip. fw4 gives the sets the C<auto-merge>
217 flag, so nftables folds overlapping and adjacent ranges together as they are
218 added: banning C<10.0.0.0/8> and then C<10.1.0.0/16> leaves one interval, and
219 a later C<unban_cidr> of the C</16> punches a hole in the C</8> rather than
220 being the noop it looks like. The ban list this object keeps still says the
221 C</8> is banned, because as far as it is concerned it is. Ban ranges that do
222 not overlap and this cannot arise.
223  
224 C<config rule> sections are created with C<< src '*' >> unless the C<zone>
225 option says otherwise, which is every zone. Setting C<zone> to C<wan> is
226 almost always what is actually wanted.
227  
228 fw4 defaults an unspecified C<proto> to C<< tcp udp >>, not to every protocol.
229 When neither ports nor protocols are configured this backend therefore writes
230 C<< proto 'all' >> explicitly, so that blocking everything really does block
231 everything.
232  
233 Rules are moved to the front of C</etc/config/firewall> with C<uci reorder>,
234 because fw4 emits rules in config order and a block rule appended after an
235 existing accept rule would never be reached. This puts them ahead of the zone
236 sections as well. fw4 parses the whole config before emitting anything, so
237 that is expected to be harmless, but it is worth knowing about if the config
238 is being read by hand. Set the C<reorder> option to 0 to leave the ordering
239 alone.
240  
241 Everything that touches a set at runtime, meaning every ban and unban and the
242 whole of L</check>, assumes fw4 names the nftables set after the C<name> of
243 the C<config ipset> section it came from and puts it in its own C<inet fw4>
244 table. Should that ever not hold, bans would fail with nft reporting no such
245 set.
246  
247 The C<kill> option shells out to conntrack(8), from the C<conntrack> package,
248 which is not installed by default. Without it the kill is a silent noop, as
249 conntrack's exit status is intentionally ignored. See
250 L</ENABLING KILL SUPPORT>.
251  
252 =head1 METHODS
253  
254 =head2 new
255  
256 Initiates the object.
257  
258 - options :: Backend specific options that will be passed to the backend unchecked
259 outside of making sure it is a hash ref if defined. See below for further info.
260 - Default :: {}
261  
262 - ports :: A array of ports to block. Checked to make sure they are ints within the
263 range 1 to 65535 or a valid service name via getservbyname. All ports will be
264 blocked if non are specified. Duplicates are removed.
265 - Default :: []
266  
267 - protocols :: A array of protocols to block. This is checked against
268 /etc/protocols via the function getprotobyname. Duplicates will be
269 discarded. If no protocols are given, all traffic sourced from the
270 sets is blocked, unless ports are given, in which case it defaults
271 to tcp and udp. Ports are only attached to port-capable protocols
272 (tcp/udp/sctp); other protocols are blocked without a port.
273 - Default :: [], or ['tcp','udp'] when ports are given
274  
275 - prefix :: Prefix to use. Must match the regex /^[a-zA-Z0-9]+$/
276 - default :: kur
277  
278 - name :: Name of this specific instance. This must be specified. The
279 prefix and the name joined by an underscore must come to 250
280 characters or fewer, leaving room for the suffixes appended to
281 derive the set and rule names within the nftables identifier
282 limit.
283 - default :: undef
284  
285 The options hash accepts the following.
286  
287 - type :: The drop method to use. 'drop' silently drops. 'reject' sends
288 the family-appropriate ICMP unreachable back.
289 - Default :: drop
290  
291 - zone :: The firewall zone the rules apply to, becoming the rule's src.
292 '*' is every zone. Must match /^[a-zA-Z0-9_*-]+$/.
293 - Default :: *
294  
295 - reorder :: Move the rule sections to the front of the firewall config so
296 they are evaluated before any existing accept rules.
297 - Default :: 1
298  
299 - kill :: Use conntrack(8) to drop existing connection tracking entries
300 for the banned IP, scoped to the configured protocols. Requires
301 the conntrack package, and in remote mode an ACL allowing it. See
302 L</ENABLING KILL SUPPORT>.
303 - Default :: 0
304  
305 - host :: The router to drive over ubus JSON-RPC. Leaving this undef runs
306 everything locally instead.
307 - Default :: undef
308  
309 - user :: The ubus user to authenticate as. Remote mode only.
310 - Default :: root
311  
312 - password :: The password for that user. Required in remote mode.
313 - Default :: undef
314  
315 - http_proto :: 'http' or 'https'. Remote mode only.
316 - Default :: http
317  
318 - http_port :: The port uhttpd is listening on. Remote mode only.
319 - Default :: 80, or 443 when http_proto is https
320  
321 - timeout :: HTTP timeout in seconds. Remote mode only.
322 - Default :: 30
323  
324 - insecure :: Skip TLS certificate verification, which routers with a self
325 signed certificate will need. Remote mode only.
326 - Default :: 0
327  
328 All errors are considered fatal, meaning if new fails it will die.
329  
330 =cut
331  
332 2 ▶sub new {
Subroutine new: called CC=43 SCAR=69.1
Pod documented
333 2 my ( $blank, %opts ) = @_;
334  
335 2 my $self = {
336 perror => undef,
337 error => undef,
338 errorLine => undef,
339 errorFilename => undef,
340 errorString => "",
341 errorExtra => {
342 all_errors_fatal => 1,
343 # all_fatal is what Error::Helper 2.1.0 actually checks; all_errors_fatal
344 # is kept for the name documented in its POD
345 all_fatal => 1,
346 flags => {
347 1 => 'notInited',
348 2 => 'invalidPortSpecified',
349 3 => 'portsNotArray',
350 4 => 'protocolsNotArray',
351 5 => 'invalidPortSpecified',
352 6 => 'invalidPrefixSpecified',
353 7 => 'invalidName',
354 8 => 'optionsNotHash',
355 9 => 'noBanItem',
356 10 => 'banItemNotIP',
357 12 => 'backendInitError',
358 13 => 'banFailed',
359 14 => 'unbanFailed',
360 15 => 'listFailed',
361 16 => 'reInitFailed',
362 17 => 'teardownFailed',
363 18 => 'alreadyInited',
364 20 => 'typeInvalid',
365 21 => 'nameTooLong',
366 23 => 'initFailed',
367 24 => 'checkFailed',
368 25 => 'flushFailed',
369 26 => 'banCidrFailed',
370 27 => 'unbanCidrFailed',
371 28 => 'cidrItemNotCidr',
372 29 => 'cidrNotSupported',
373 30 => 'listCidrFailed',
374 31 => 'commitFailed',
375 32 => 'invalidHost',
376 33 => 'noPassword',
377 34 => 'invalidZone',
378 35 => 'invalidHttpPort',
379 36 => 'invalidHttpProto',
380 },
381 fatal_flags => {},
382 perror_not_fatal => 0,
383 },
384 options => {
385 type => 'drop',
386 zone => '*',
387 reorder => 1,
388 kill => 0,
389 host => undef,
390 user => 'root',
391 password => undef,
392 http_proto => 'http',
393 http_port => undef,
394 timeout => 30,
395 insecure => 0,
396 },
397 ports => [],
398 protocols => [],
399 testing => undef,
400 test_data => undef,
401 prefix => 'kur',
402 frontend_obj => undef,
403 inited => 0,
404 banned => {},
405 banned_cidr => {},
406 cidr_supported => 1,
407 ua => undef,
408 session => undef,
409 };
410 2 bless $self;
411  
412 2 ▶ if ( defined( $opts{ports} ) && ref( $opts{ports} ) ne 'ARRAY' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opts{'ports'} and ref $opts{'ports'} ne 'ARRAY') { } 0 2 2
elsif (defined $opts{'ports'}) { } 0 2 2
Condition33%1/3
defined $opts{"ports"} and ref $opts{"ports"} ne "ARRAY"
!ll&&!rl&&r
200
MC/DC0%0/2
defined $opts{"ports"} and ref $opts{"ports"} ne "ARRAY"
defined $opts{"ports"} ref $opts{"ports"} ne "ARRAY"
Truth table33%1/3
A and B
A= defined $opts{"ports"}B= ref $opts{"ports"} ne "ARRAY"
ABresult
0X0
100
111
413 0 $self->{perror} = 1;
414 0 $self->{error} = 3;
415 0 $self->{errorString} = 'ports is defined and type is not array but "' . ref( $opts{ports} ) . '"';
416 0 $self->warn;
417 } elsif ( defined( $opts{ports} ) ) {
418 0 my %ports;
419 0 foreach my $item ( @{ $opts{ports} } ) {
420 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
421 0 $ports{$item} = 1;
422 } elsif ( $item =~ /^[0-9]+$/ ) {
423 0 $self->{perror} = 1;
424 0 $self->{error} = 2;
425 $self->{errorString}
426 0 = $item . ' is not a valid value for a port as it must be a int within the range 1 to 65535';
427 0 $self->warn;
428 } else {
429 # just using tcp here as protocol must be specified
430 0 my ( $name, $aliases, $port, $proto ) = getservbyname( $item, 'tcp' );
431 0 ▶ if ( !defined($port) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $port) 0 0 0
432 0 $self->{perror} = 1;
433 0 $self->{error} = 2;
434 $self->{errorString}
435 0 = $item . ' could not be resolved to a port name via getservbyname("' . $item . '", "tcp")';
436 0 $self->warn;
437 }
438 0 $ports{$port} = 1;
439 } ## end else [ if ( $item =~ /^[0-9]+$/ && $item >= 1 && ...)]
440 } ## end foreach my $item ( @{ $opts{ports} } )
441 0 my @port_keys = keys(%ports);
442 0 @port_keys = sort { $a <=> $b } @port_keys;
443 0 push( @{ $self->{ports} }, @port_keys );
444 } ## end elsif ( defined( $opts{ports} ) )
445  
446 2 ▶ if ( defined( $opts{protocols} ) && ref( $opts{protocols} ) ne 'ARRAY' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opts{'protocols'} and ref $opts{'protocols'} ne 'ARRAY') { } 0 2 2
elsif (defined $opts{'protocols'}) { } 0 2 2
Condition33%1/3
defined $opts{"protocols"} and ref $opts{"protocols"} ne "ARRAY"
!ll&&!rl&&r
200
MC/DC0%0/2
defined $opts{"protocols"} and ref $opts{"protocols"} ne "ARRAY"
defined $opts{"protocols"} ref $opts{"protocols"} ne "ARRAY"
Truth table33%1/3
A and B
A= defined $opts{"protocols"}B= ref $opts{"protocols"} ne "ARRAY"
ABresult
0X0
100
111
447 0 $self->{perror} = 1;
448 0 $self->{error} = 4;
449 0 $self->{errorString} = 'protocols is defined and type is not array but "' . ref( $opts{protocols} ) . '"';
450 0 $self->warn;
451 } elsif ( defined( $opts{protocols} ) ) {
452 0 my %protocols;
453 0 foreach my $item ( @{ $opts{protocols} } ) {
454 0 my ( $name, $aliases, $proto ) = getprotobyname($item);
455 # if this is undef, it means it is not a known protocol
456 0 ▶ if ( !defined($proto) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $proto) 0 0 0
457 0 $self->{perror} = 1;
458 0 $self->{error} = 5;
459 $self->{errorString}
460 0 = $item . ' could not be resolved to a protocol via getprotobyname("' . $item . '")';
461 0 $self->warn;
462 }
463 0 $protocols{$item} = 1;
464 } ## end foreach my $item ( @{ $opts{protocols} } )
465 0 my @protocols_keys = keys(%protocols);
466 0 @protocols_keys = sort { $a cmp $b } @protocols_keys;
467 0 push( @{ $self->{protocols} }, @protocols_keys );
468 } ## end elsif ( defined( $opts{protocols} ) )
469  
470 # make sure prefix is sane if defiend
471 2 ▶ 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 2 2
elsif (defined $opts{'prefix'}) { } 2 0 2
Condition33%1/3
defined $opts{"prefix"} and not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
!ll&&!rl&&r
020
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
472 0 $self->{perror} = 1;
473 0 $self->{error} = 6;
474 $self->{errorString}
475 0 = '"' . $opts{prefix} . '" is not a valid prefix as it does not match the regex /^[a-zA-Z0-9]+$/';
476 0 $self->warn;
477 } elsif ( defined( $opts{prefix} ) ) {
478 2 $self->{prefix} = $opts{prefix};
479 }
480  
481 # make sure we have a name and that it is valid
482 2 ▶ if ( !defined( $opts{name} ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $opts{'name'}) { } 0 2 2
elsif (not $opts{'name'} =~ /^[a-zA-Z0-9\-]+$/) { } 0 2 2
483 0 $self->{perror} = 1;
484 0 $self->{error} = 7;
485 0 $self->{errorString} = 'name is undef';
486 0 $self->warn;
487 } elsif ( $opts{name} !~ /^[a-zA-Z0-9\-]+$/ ) {
488 0 $self->{perror} = 1;
489 0 $self->{error} = 7;
490 0 $self->{errorString} = 'name set to "' . $opts{name} . '" which does not match the regexp /^[a-zA-Z0-9\-]+$/';
491 0 $self->warn;
492 }
493 2 $self->{name} = $opts{name};
494  
495 # nftables caps identifiers at 256 bytes including the terminating null, so
496 # 255 usable. The longest thing derived from the base name is a rule
497 # section, base plus "_r" plus the index, so 250 leaves ample room for that
498 # and for the "_4"/"_6" the set names take.
499 2 ▶ if ( defined( $self->{name} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"name"}) 2 0 2
500 2 my $base_length = length( $self->{prefix} ) + 1 + length( $self->{name} );
501 2 ▶ if ( $base_length > 250 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($base_length > 250) 1 1 2
502 1 $self->{perror} = 1;
503 1 $self->{error} = 21;
504 $self->{errorString}
505 1 = 'the prefix and name come to ' . $base_length . ' characters joined, which is over the 250 maximum';
506 1 $self->warn;
507 }
508 } ## end if ( defined( $self->{name} ) )
509  
510 # used internally for testing
511 1 ▶ if ( defined( $opts{testing} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"testing"}) 0 1 1
512 0 $self->{testing} = $opts{testing};
513 }
514 1 ▶ if ( defined( $opts{frontend_obj} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"frontend_obj"}) 0 1 1
515 0 $self->{frontend_obj} = $opts{frontend_obj};
516 }
517  
518 1 ▶ if ( defined( $opts{options} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"options"}) 0 1 1
519 0 ▶ if ( ref( $opts{options} ) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $opts{"options"} ne "HASH") 0 0 0
520 0 $self->{perror} = 1;
521 0 $self->{error} = 8;
522 0 $self->{errorString} = 'ref for options is "' . ref( $opts{options} ) . '" and not HASH';
523 0 $self->warn;
524 }
525  
526 # merge over the defaults rather than replacing them, so that setting
527 # one option does not silently unset the rest
528 0 foreach my $key ( keys( %{ $opts{options} } ) ) {
529 0 $self->{options}{$key} = $opts{options}{$key};
530 }
531  
532 0 ▶ if ( $self->{options}{type} ne 'drop' && $self->{options}{type} ne 'reject' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"options"}{"type"} ne "drop" and $self->{"options"}{"type"} ne "reject") 0 0 0
Condition0%0/3
$self->{"options"}{"type"} ne "drop" and $self->{"options"}{"type"} ne "reject"
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"options"}{"type"} ne "drop" and $self->{"options"}{"type"} ne "reject"
$self->{"options"}{"type"} ne "drop" $self->{"options"}{"type"} ne "reject"
Truth table0%0/3
A and B
A= $self->{"options"}{"type"} ne "drop"B= $self->{"options"}{"type"} ne "reject"
ABresult
0X0
100
111
533 0 $self->{perror} = 1;
534 0 $self->{error} = 20;
535 $self->{errorString}
536 0 = '$opts{options}{type} is "' . $self->{options}{type} . '" and not "drop" or "reject"';
537 0 $self->warn;
538 }
539  
540 0 ▶ if ( !defined( $self->{options}{zone} ) || $self->{options}{zone} !~ /^[a-zA-Z0-9_*\-]+$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"options"}{"zone"} and $self->{"options"}{"zone"} =~ /^[a-zA-Z0-9_*\-]+$/) 0 0 0
Condition0%0/3
defined $self->{"options"}{"zone"} and $self->{"options"}{"zone"} =~ /^[a-zA-Z0-9_*\-]+$/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"options"}{"zone"} and $self->{"options"}{"zone"} =~ /^[a-zA-Z0-9_*\-]+$/
defined $self->{"options"}{"zone"} $self->{"options"}{"zone"} =~ /^[a-zA-Z0-9_*\-]+$/
Truth table0%0/3
A and B
A= defined $self->{"options"}{"zone"}B= $self->{"options"}{"zone"} =~ /^[a-zA-Z0-9_*\-]+$/
ABresult
0X0
100
111
541 0 $self->{perror} = 1;
542 0 $self->{error} = 34;
543 0 $self->{errorString} = '$opts{options}{zone} does not match the regexp /^[a-zA-Z0-9_*\-]+$/';
544 0 $self->warn;
545 }
546  
547 0 ▶ if ( defined( $self->{options}{host} ) && $self->{options}{host} !~ /^[a-zA-Z0-9_.\-\[\]:]+$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"options"}{"host"} and not $self->{"options"}{"host"} =~ /^[a-zA-Z0-9_.\-\[\]:]+$/) 0 0 0
Condition0%0/3
defined $self->{"options"}{"host"} and not $self->{"options"}{"host"} =~ /^[a-zA-Z0-9_.\-\[\]:]+$/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"options"}{"host"} and not $self->{"options"}{"host"} =~ /^[a-zA-Z0-9_.\-\[\]:]+$/
defined $self->{"options"}{"host"} not $self->{"options"}{"host"} =~ /^[a-zA-Z0-9_.\-\[\]:]+$/
Truth table0%0/3
A and not(B)
A= defined $self->{"options"}{"host"}B= not $self->{"options"}{"host"} =~ /^[a-zA-Z0-9_.\-\[\]:]+$/
ABresult
0X0
100
111
548 0 $self->{perror} = 1;
549 0 $self->{error} = 32;
550 $self->{errorString}
551 = '$opts{options}{host} is "'
552 . $self->{options}{host}
553 0 . '" which does not match the regexp /^[a-zA-Z0-9_.\-\[\]:]+$/';
554 0 $self->warn;
555 }
556  
557 0 ▶ if ( defined( $self->{options}{host} ) && !defined( $self->{options}{password} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"options"}{"host"} and not defined $self->{"options"}{"password"}) 0 0 0
Condition0%0/3
defined $self->{"options"}{"host"} and not defined $self->{"options"}{"password"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"options"}{"host"} and not defined $self->{"options"}{"password"}
defined $self->{"options"}{"host"} not defined $self->{"options"}{"password"}
Truth table0%0/3
A and not(B)
A= defined $self->{"options"}{"host"}B= not defined $self->{"options"}{"password"}
ABresult
0X0
100
111
558 0 $self->{perror} = 1;
559 0 $self->{error} = 33;
560 0 $self->{errorString} = 'host is set, putting the backend in remote mode, but no password was given';
561 0 $self->warn;
562 }
563  
564 0 ▶ if ( $self->{options}{http_proto} ne 'http' && $self->{options}{http_proto} ne 'https' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"options"}{"http_proto"} ne "http" and $self->{"options"}{"http_proto"} ne "https") 0 0 0
Condition0%0/3
$self->{"options"}{"http_proto"} ne "http" and $self->{"options"}{"http_proto"} ne "https"
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"options"}{"http_proto"} ne "http" and $self->{"options"}{"http_proto"} ne "https"
$self->{"options"}{"http_proto"} ne "http" $self->{"options"}{"http_proto"} ne "https"
Truth table0%0/3
A and B
A= $self->{"options"}{"http_proto"} ne "http"B= $self->{"options"}{"http_proto"} ne "https"
ABresult
0X0
100
111
565 0 $self->{perror} = 1;
566 0 $self->{error} = 36;
567 $self->{errorString}
568 0 = '$opts{options}{http_proto} is "' . $self->{options}{http_proto} . '" and not "http" or "https"';
569 0 $self->warn;
570 }
571  
572 0 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"options"}{"http_port"} and !($self->{"options"}{"http_port"} =~ /^[0-9]+$/) || $self->{"options"}{"http_port"} < 1 || $self->{"options"}{"http_port"} > 65535) 0 0 0
Condition0%0/9
defined $self->{"options"}{"http_port"} and !($self->{"options"}{"http_port"} =~ /^[0-9]+$/) || $self->{"options"}{"http_port"} < 1 || $self->{"options"}{"http_port"} > 65535
!ll&&!rl&&r
000
not $self->{"options"}{"http_port"} =~ /^[0-9]+$/ or $self->{"options"}{"http_port"} < 1 or $self->{"options"}{"http_port"} > 65535
l!l&&r!l&&!r
000
not $self->{"options"}{"http_port"} =~ /^[0-9]+$/ or $self->{"options"}{"http_port"} < 1
l!l&&r!l&&!r
000
MC/DC0%0/4
defined $self->{"options"}{"http_port"} and !($self->{"options"}{"http_port"} =~ /^[0-9]+$/) || $self->{"options"}{"http_port"} < 1 || $self->{"options"}{"http_port"} > 65535
defined $self->{"options"}{"http_port"} not $self->{"options"}{"http_port"} =~ /^[0-9]+$/ $self->{"options"}{"http_port"} < 1 $self->{"options"}{"http_port"} > 65535
Truth table0%0/5
A and not(B) or C or D
A= defined $self->{"options"}{"http_port"}B= not $self->{"options"}{"http_port"} =~ /^[0-9]+$/C= $self->{"options"}{"http_port"} < 1D= $self->{"options"}{"http_port"} > 65535
ABCDresult
0XXX0
10000
11XX1
101X1
10011
573 defined( $self->{options}{http_port} )
574 && ( $self->{options}{http_port} !~ /^[0-9]+$/
575 || $self->{options}{http_port} < 1
576 || $self->{options}{http_port} > 65535 )
577 )
578 {
579 0 $self->{perror} = 1;
580 0 $self->{error} = 35;
581 $self->{errorString}
582 = '$opts{options}{http_port} is "'
583 . $self->{options}{http_port}
584 0 . '" and not an int within the range 1 to 65535';
585 0 $self->warn;
586 } ## end if ( defined( $self->{options}{http_port} ...))
587 } ## end if ( defined( $opts{options} ) )
588  
589 # only worked out once the proto is known to be valid
590 1 ▶ if ( !defined( $self->{options}{http_port} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"options"}{"http_port"}) 1 0 1
591 1 ▶ $self->{options}{http_port} = ( $self->{options}{http_proto} eq 'https' ) ? 443 : 80;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'options'}{'http_proto'} eq 'https' ? : 0 1 1
592 }
593  
594 1 return $self;
595 } ## end sub new
596  
597 # Internal helper. Returns the three names this instance owns: the base name,
598 # which every UCI section is derived from, and the two set names.
599 #
600 # All of them come from the prefix and the name rather than being stored, so
601 # every part of the backend agrees on what to create, reference, and tear down
602 # without threading the names around. The prefix and name pair is unique per
603 # instance, so two instances can share a router without colliding.
604 #
605 # The set names double as the names of the UCI ipset sections that declare
606 # them, which is what lets check confirm a set's config is still present from
607 # the set name alone. Rule sections are named separately, by _rule_specs.
608 #
609 # There are two sets rather than one because an nftables set is typed and fw4
610 # renders one set per ipset section per family: the _4 set is ipv4_addr and the
611 # _6 set ipv6_addr, and neither will hold the other's addresses.
612 #
613 # Takes no arguments.
614 #
615 # Returns a three element list of the base name, the IPv4 set name, and the
616 # IPv6 set name, in that order.
617 #
618 # my ( $base, $set4, $set6 ) = $self->_names;
619 #
620 # # with prefix "kur" and name "ssh"
621 # # $base is 'kur_ssh'
622 # # $set4 is 'kur_ssh_4'
623 # # $set6 is 'kur_ssh_6'
624 0 ▶sub _names {
Subroutine _names: not called CC=1 SCAR=6.9
625 0 my ($self) = @_;
626  
627 0 my $base = $self->{prefix} . '_' . $self->{name};
628 0 return ( $base, $base . '_4', $base . '_6' );
629 }
630  
631 # Internal helper. Returns the UCI ipset sections this instance needs, one per
632 # address family.
633 #
634 # fw4 turns each of these into an nftables set inside its inet fw4 table. The
635 # match is src_net rather than src_ip on purpose: src_net gives an interval
636 # set, which holds CIDR ranges as well as single addresses, and is what lets
637 # this backend support CIDR bans off the same two sets that hold the single IP
638 # bans. An interval set takes a bare address as a singleton interval, so
639 # nothing extra is needed for the single IP case.
640 #
641 # The entry list is deliberately not set here. Entries are the ban list, which
642 # is written out by commit rather than at init, so that a ban does not cause a
643 # flash write.
644 #
645 # Takes no arguments.
646 #
647 # Returns a two element list of section hashrefs, the IPv4 one first, each
648 # with:
649 #
650 # - name :: the UCI section name, which is also the set name
651 # - type :: always 'ipset'
652 # - kv :: an arrayref of [ option, value ] pairs in the order they should
653 # be written, values being either a scalar or an arrayref for a
654 # list option
655 #
656 # my @sections = $self->_ipset_sections;
657 #
658 # # with prefix "kur" and name "ssh", the first is
659 # # {
660 # # name => 'kur_ssh_4',
661 # # type => 'ipset',
662 # # kv => [ [ 'name', 'kur_ssh_4' ], [ 'family', 'ipv4' ],
663 # # [ 'match', ['src_net'] ], [ 'enabled', '1' ] ],
664 # # }
665 0 ▶sub _ipset_sections {
Subroutine _ipset_sections: not called CC=2 SCAR=17.9
666 0 my ($self) = @_;
667  
668 0 my ( $base, $set4, $set6 ) = $self->_names;
669  
670 0 my @sections;
671 0 foreach my $item ( [ $set4, 'ipv4' ], [ $set6, 'ipv6' ] ) {
672 0 push(
673 @sections,
674 {
675 name => $item->[0],
676 type => 'ipset',
677 kv =>
678 [ [ 'name', $item->[0] ], [ 'family', $item->[1] ], [ 'match', ['src_net'] ], [ 'enabled', '1' ], ],
679 }
680 );
681 } ## end foreach my $item ( [ $set4, 'ipv4' ], [ $set6, ...])
682  
683 0 return @sections;
684 } ## end sub _ipset_sections
685  
686 # Internal helper. Works out the full cross product of family, protocol, and
687 # ports this instance needs to block and returns it as UCI rule sections, along
688 # with a record of which sets those rules actually reference. Essentially all
689 # of the backend's rule logic lives here.
690 #
691 # The second return value exists for check. Verifying the setup is still intact
692 # means confirming the sets the rules depend on are present, and which sets
693 # those are is not always both of them: a configuration whose protocols are all
694 # one family, say icmp only, produces rules referencing just the IPv4 set, and
695 # demanding the IPv6 set exist would then report a healthy setup as broken.
696 # Rather than have check re-derive that, it is recorded here where the decision
697 # is actually made.
698 #
699 # Protocols belonging to the wrong family are skipped, so icmp never lands in
700 # an ipv6 rule and the various spellings of IPv6 ICMP never land in an ipv4
701 # one. Ports are only attached to protocols that have them.
702 #
703 # One rule section is emitted per protocol per family rather than collapsing
704 # the protocols into a single rule's proto list, matching how the iptables and
705 # nftables backends lay their rules out and keeping the port handling simple,
706 # as a rule mixing a port-capable protocol with one that has no ports would be
707 # rejected by fw4.
708 #
709 # The proto of a rule blocking everything is written as 'all' rather than being
710 # left out. fw4 defaults an absent proto to tcp and udp, so omitting it would
711 # quietly block far less than asked for.
712 #
713 # Takes no arguments; family, protocols, ports, type, and zone all come from
714 # the object.
715 #
716 # Returns a two element list:
717 #
718 # - an arrayref of section hashrefs, in the same shape _ipset_sections
719 # returns, with type 'rule' and names of the form <base>_r<N> where N
720 # counts up from 0 across both families
721 # - a hashref keyed by the set names those rules reference, values all 1,
722 # for check to confirm
723 #
724 # my ( $sections, $referenced ) = $self->_rule_specs;
725 #
726 # # ports 22, protocols tcp, zone wan, type drop: two sections, the first
727 # # {
728 # # name => 'kur_ssh_r0',
729 # # type => 'rule',
730 # # kv => [ [ 'name', 'kur_ssh_r0' ], [ 'family', 'ipv4' ],
731 # # [ 'src', 'wan' ], [ 'ipset', 'kur_ssh_4' ],
732 # # [ 'proto', 'tcp' ], [ 'dest_port', ['22'] ],
733 # # [ 'target', 'DROP' ] ],
734 # # }
735 # # $referenced is { kur_ssh_4 => 1, kur_ssh_6 => 1 }
736 #
737 # # no protocols and no ports: one rule per family with proto 'all' and no
738 # # dest_port
739 #
740 # # ports 22 with no protocols: two rules per family, tcp and udp
741 0 ▶sub _rule_specs {
Subroutine _rule_specs: not called CC=14 SCAR=53.5
742 0 my ($self) = @_;
743  
744 0 my ( $base, $set4, $set6 ) = $self->_names;
745  
746 0 my @ports = @{ $self->{ports} };
747 0 my @protos = @{ $self->{protocols} };
748  
749 0 ▶ my $target = ( $self->{options}{type} eq 'reject' ) ? 'REJECT' : 'DROP';
Branch: 1 branch
BranchTrueFalseTotal
$self->{'options'}{'type'} eq 'reject' ? : 0 0 0
750  
751 # protocols that accept a port specification
752 0 my %port_ok = ( tcp => 1, udp => 1, sctp => 1 );
753  
754 # the various names the IPv6 ICMP protocol may go by
755 0 my %v6_icmp = ( 'ipv6-icmp' => 1, 'icmp6' => 1, 'icmpv6' => 1 );
756  
757 my @families
758 0 = ( { set => $set4, family => 'ipv4', number => 4 }, { set => $set6, family => 'ipv6', number => 6 }, );
759  
760 0 my @sections;
761 my %referenced;
762 0 my $index = 0;
763 0 foreach my $fam (@families) {
764 0 my @fam_protos;
765 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
766 # fw4 would read a missing proto as tcp and udp, so say all
767 0 @fam_protos = ('all');
768 ▶ } 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
769 # ports require a protocol, default to tcp and udp
770 0 @fam_protos = ( 'tcp', 'udp' );
771 } else {
772 0 foreach my $proto (@protos) {
773 # skip protocols that do not belong to this family
774 0 ▶ if ( $fam->{number} == 6 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fam->{'number'} == 6) { } 0 0 0
775 0 ▶ next if ( $proto eq 'icmp' );
Branch: 1 branch
BranchTrueFalseTotal
if $proto eq "icmp" 0 0 0
776 } else {
777 0 ▶ next if ( $v6_icmp{$proto} );
Branch: 1 branch
BranchTrueFalseTotal
if $v6_icmp{$proto} 0 0 0
778 }
779 0 push( @fam_protos, $proto );
780 }
781 } ## end else [ if ( !@protos && !@ports ) ]
782  
783 0 foreach my $proto (@fam_protos) {
784 0 my $section = $base . '_r' . $index;
785 0 $index++;
786  
787 my @kv = (
788 [ 'name', $section ],
789 [ 'family', $fam->{family} ],
790 [ 'src', $self->{options}{zone} ],
791 0 [ 'ipset', $fam->{set} ],
792 [ 'proto', $proto ],
793 );
794 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
795 0 push( @kv, [ 'dest_port', [@ports] ] );
796 }
797 0 push( @kv, [ 'target', $target ] );
798  
799 0 push( @sections, { name => $section, type => 'rule', kv => \@kv } );
800 0 $referenced{ $fam->{set} } = 1;
801 } ## end foreach my $proto (@fam_protos)
802 } ## end foreach my $fam (@families)
803  
804 0 return ( \@sections, \%referenced );
805 } ## end sub _rule_specs
806  
807 # Internal helper. Returns the name of the set an address or range belongs in,
808 # picked by address family.
809 #
810 # Both the single IP and the CIDR methods need this and the CIDR ones can not
811 # match the whole value against the address regexps, as a range has a prefix
812 # length on the end, so the family test is done on the address portion only.
813 # Splitting on "/" is harmless for a bare address, which simply has no "/" to
814 # split on.
815 #
816 # Args:
817 #
818 # item - The address or range, as a plain string. Expected to be an already
819 # validated and lowercased IPv4 or IPv6 address, or such an address
820 # followed by "/" and a prefix length.
821 #
822 # Returns the set name as a string. The IPv4 set is returned for anything that
823 # matches the IPv4 regexp and the IPv6 set for everything else, so a value that
824 # is neither lands in the IPv6 set rather than erroring; callers validate
825 # before getting here.
826 #
827 # $self->_set_for('10.0.0.1'); # kur_ssh_4
828 # $self->_set_for('10.0.0.0/8'); # kur_ssh_4
829 # $self->_set_for('2001:db8::1'); # kur_ssh_6
830 # $self->_set_for('2001:db8::/32'); # kur_ssh_6
831 0 ▶sub _set_for {
Subroutine _set_for: not called CC=2 SCAR=17.9
832 0 my ( $self, $item ) = @_;
833  
834 0 my ( $base, $set4, $set6 ) = $self->_names;
835  
836 0 my ($address) = split( m!/!, $item );
837  
838 0 ▶ return ( $address =~ /\A$IPv4_re\z/ ) ? $set4 : $set6;
Branch: 1 branch
BranchTrueFalseTotal
$address =~ /\A$Net::Firewall::BlockerHelper::backends::openwrt::IPv4_re\z/ ? : 0 0 0
839 }
840  
841 # Internal helper. Splits the current ban list into the two per family entry
842 # lists that commit writes into the UCI ipset sections.
843 #
844 # Single IP bans and CIDR bans are held in separate hashes but share a set per
845 # family, as the sets are interval sets and hold both, so this merges them back
846 # together. Both hashes are sorted so that the same ban list always produces
847 # the same config, which keeps a commit that changes nothing from rewriting the
848 # file and keeps the test data comparable against a fixed expected list.
849 #
850 # Takes no arguments.
851 #
852 # Returns a two element list of arrayrefs, the IPv4 entries and then the IPv6
853 # entries. Within each, the single IPs come before the ranges, each group
854 # sorted as strings. Either or both may be empty, which is what an instance
855 # with no bans yet, or one that has just been flushed, produces.
856 #
857 # my ( $v4, $v6 ) = $self->_entry_lists;
858 #
859 # # having banned 10.0.0.1, 2001:db8::1, and 10.0.0.0/8
860 # # $v4 is [ '10.0.0.1', '10.0.0.0/8' ]
861 # # $v6 is [ '2001:db8::1' ]
862 0 ▶sub _entry_lists {
Subroutine _entry_lists: not called CC=4 SCAR=30.0
863 0 my ($self) = @_;
864  
865 0 my ( $base, $set4, $set6 ) = $self->_names;
866  
867 0 my @v4;
868 my @v6;
869 0 foreach my $hash ( $self->{banned}, $self->{banned_cidr} ) {
870 0 foreach my $item ( sort( keys( %{$hash} ) ) ) {
871 0 ▶ if ( $self->_set_for($item) eq $set4 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_set_for($item) eq $set4) { } 0 0 0
872 0 push( @v4, $item );
873 } else {
874 0 push( @v6, $item );
875 }
876 }
877 }
878  
879 0 return ( \@v4, \@v6 );
880 } ## end sub _entry_lists
881  
882 # Internal helper. Quotes a single argv token for the shell, used when
883 # rendering an operation into a local command line.
884 #
885 # The local runner uses backticks, so everything goes through /bin/sh and every
886 # token that holds anything the shell would act on has to be protected. Tokens
887 # made up entirely of characters the shell leaves alone are returned bare,
888 # which is the overwhelming majority of them and keeps the rendered commands
889 # readable. Everything else is wrapped in single quotes, with any single quote
890 # inside ended, escaped, and reopened, which is the only fully safe form as
891 # nothing is special within single quotes.
892 #
893 # Args:
894 #
895 # token - The argv token to quote, as a plain string. Expected to be
896 # defined; undef warns and is treated as the empty string, which
897 # renders as ''.
898 #
899 # Returns the token in a form safe to paste into a command line, either
900 # unchanged or single quoted.
901 #
902 # $self->_shell_quote('firewall.kur_ssh_4=ipset'); # unchanged
903 # $self->_shell_quote('{ 10.0.0.1 }'); # '{ 10.0.0.1 }'
904 # $self->_shell_quote("firewall.x.y=a b"); # 'firewall.x.y=a b'
905 # $self->_shell_quote("it's"); # 'it'\''s'
906 0 ▶sub _shell_quote {
Subroutine _shell_quote: not called CC=3 SCAR=24.8
907 0 my ( $self, $token ) = @_;
908  
909 0 ▶ $token = '' if ( !defined($token) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $token 0 0 0
910  
911 0 ▶ return $token if ( $token =~ m!\A[A-Za-z0-9_.:/=,@+\-]+\z! );
Branch: 1 branch
BranchTrueFalseTotal
if $token =~ m[\A[A-Za-z0-9_.:/=,\@+\-]+\z] 0 0 0
912  
913 0 $token =~ s/'/'\\''/g;
914  
915 0 return "'" . $token . "'";
916 } ## end sub _shell_quote
917  
918 # Internal helper. Renders the abstract operations the methods build into local
919 # shell command lines.
920 #
921 # The operations are kept abstract because the two transports need genuinely
922 # different things from them: creating a section is one ubus call but several
923 # uci invocations, and there is no uci command that sets a whole list at once.
924 # Expanding them here rather than at the point they are built is what keeps the
925 # methods identical in both modes.
926 #
927 # Operations are arrayrefs whose first element names the kind:
928 #
929 # [ 'section', $name, $type, \@kv ] create a named section and set its
930 # options, list values being arrayrefs
931 # [ 'del_section', $name ] delete a named section
932 # [ 'get_section', $name ] probe for a named section
933 # [ 'set_list', $name, $opt, \@v ] replace a list option wholesale
934 # [ 'reorder', \@names ] move sections to the front, in order
935 # [ 'commit' ] write the staged changes out
936 # [ 'exec', $command, @params ] run a command
937 #
938 # The deletes and the delete half of set_list use uci -q, as they are also used
939 # on setups that may be partly or wholly gone already and an "Entry not found"
940 # on stderr would be noise rather than information.
941 #
942 # Args:
943 #
944 # ops - An arrayref of operations in the form above. An unrecognised kind
945 # is skipped rather than erroring, as the only source of operations
946 # is this module.
947 #
948 # Returns the command lines as a list of strings, ready to hand to the runner.
949 # One operation may produce several, so the returned list is generally longer
950 # than the one passed in.
951 #
952 # $self->_render_local( [ [ 'exec', 'fw4', 'reload' ] ] );
953 # # fw4 reload
954 #
955 # $self->_render_local( [ [ 'commit' ] ] );
956 # # uci commit firewall
957 #
958 # $self->_render_local( [ [ 'section', 'kur_ssh_4', 'ipset',
959 # [ [ 'family', 'ipv4' ], [ 'match', ['src_net'] ] ] ] ] );
960 # # uci set firewall.kur_ssh_4=ipset
961 # # uci set firewall.kur_ssh_4.family=ipv4
962 # # uci add_list firewall.kur_ssh_4.match=src_net
963 0 ▶sub _render_local {
Subroutine _render_local: not called CC=15 SCAR=54.8
964 0 my ( $self, $ops ) = @_;
965  
966 0 my @commands;
967 0 foreach my $op ( @{$ops} ) {
968 0 my $kind = $op->[0];
969  
970 0 ▶ if ( $kind eq 'section' ) {
Branch: 8 branches
BranchTrueFalseTotal
if ($kind eq 'section') { } 0 0 0
elsif ($kind eq 'del_section') { } 0 0 0
elsif ($kind eq 'get_section') { } 0 0 0
elsif ($kind eq 'del_option') { } 0 0 0
elsif ($kind eq 'set_list') { } 0 0 0
elsif ($kind eq 'reorder') { } 0 0 0
elsif ($kind eq 'commit') { } 0 0 0
elsif ($kind eq 'exec') { } 0 0 0
971 0 my ( undef, $name, $type, $kv ) = @{$op};
972 0 push( @commands, 'uci set ' . $self->_shell_quote( 'firewall.' . $name . '=' . $type ) );
973 0 foreach my $pair ( @{$kv} ) {
974 0 my ( $option, $value ) = @{$pair};
975 0 ▶ if ( ref($value) eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value eq 'ARRAY') { } 0 0 0
976 0 foreach my $item ( @{$value} ) {
977 0 push( @commands,
978 'uci add_list '
979 . $self->_shell_quote( 'firewall.' . $name . '.' . $option . '=' . $item ) );
980 }
981 } else {
982 0 push( @commands,
983 'uci set ' . $self->_shell_quote( 'firewall.' . $name . '.' . $option . '=' . $value ) );
984 }
985 } ## end foreach my $pair ( @{$kv} )
986 } elsif ( $kind eq 'del_section' ) {
987 0 push( @commands, 'uci -q delete ' . $self->_shell_quote( 'firewall.' . $op->[1] ) );
988 } elsif ( $kind eq 'get_section' ) {
989 0 push( @commands, 'uci -q get ' . $self->_shell_quote( 'firewall.' . $op->[1] ) );
990 } elsif ( $kind eq 'del_option' ) {
991 0 my ( undef, $name, $option ) = @{$op};
992 0 push( @commands, 'uci -q delete ' . $self->_shell_quote( 'firewall.' . $name . '.' . $option ) );
993 } elsif ( $kind eq 'set_list' ) {
994 0 my ( undef, $name, $option, $values ) = @{$op};
995 0 foreach my $item ( @{$values} ) {
996 0 push( @commands,
997 'uci add_list ' . $self->_shell_quote( 'firewall.' . $name . '.' . $option . '=' . $item ) );
998 }
999 } elsif ( $kind eq 'reorder' ) {
1000 0 my $index = 0;
1001 0 foreach my $name ( @{ $op->[1] } ) {
1002 0 push( @commands, 'uci reorder ' . $self->_shell_quote( 'firewall.' . $name . '=' . $index ) );
1003 0 $index++;
1004 }
1005 } elsif ( $kind eq 'commit' ) {
1006 0 push( @commands, 'uci commit firewall' );
1007 } elsif ( $kind eq 'exec' ) {
1008 0 my ( undef, @parts ) = @{$op};
1009 0 push( @commands, join( ' ', map { $self->_shell_quote($_) } @parts ) );
1010 }
1011 } ## end foreach my $op ( @{$ops} )
1012  
1013 0 return @commands;
1014 } ## end sub _render_local
1015  
1016 # Internal helper. Renders the abstract operations the methods build into ubus
1017 # JSON-RPC calls.
1018 #
1019 # The operation forms are the ones documented on _render_local. Where that
1020 # expands a section into several uci invocations this produces a single call,
1021 # because the ubus uci object takes the whole set of values at once, and where
1022 # that has to delete and rebuild a list this simply sets it, because a JSON
1023 # array is a list.
1024 #
1025 # The set_list case does mean the ban list is sent in full on every commit
1026 # rather than as a delta. That is intentional. There is no ubus equivalent of
1027 # add_list, and the alternative of reading the list back, editing it, and
1028 # writing it again would race with anything else touching the config for no
1029 # gain, as commit is rare.
1030 #
1031 # Commands go through the file object's exec method, which needs rpcd-mod-file
1032 # on the router and an ACL that allows the command. There is no shell involved,
1033 # so the parameters are passed as a list rather than as a command line and
1034 # nothing needs quoting.
1035 #
1036 # Args:
1037 #
1038 # ops - An arrayref of operations, as described on _render_local. An
1039 # unrecognised kind is skipped.
1040 #
1041 # Returns the calls as a list of hashrefs, each with:
1042 #
1043 # - object :: the ubus object to call, 'uci' or 'file'
1044 # - method :: the method on it
1045 # - params :: a hashref of the arguments
1046 #
1047 # These are what the testing paths record, rather than the full JSON-RPC
1048 # envelope, as the envelope adds only a request id and the session token and
1049 # neither is worth asserting on. The session token in particular never appears,
1050 # which is what keeps the credential out of the test data.
1051 #
1052 # $self->_render_remote( [ [ 'commit' ] ] );
1053 # # { object => 'uci', method => 'commit',
1054 # # params => { config => 'firewall' } }
1055 #
1056 # $self->_render_remote( [ [ 'exec', 'fw4', 'reload' ] ] );
1057 # # { object => 'file', method => 'exec',
1058 # # params => { command => 'fw4', params => ['reload'] } }
1059 #
1060 # $self->_render_remote( [ [ 'section', 'kur_ssh_4', 'ipset',
1061 # [ [ 'family', 'ipv4' ], [ 'match', ['src_net'] ] ] ] ] );
1062 # # { object => 'uci', method => 'add',
1063 # # params => { config => 'firewall', type => 'ipset',
1064 # # name => 'kur_ssh_4',
1065 # # values => { family => 'ipv4', match => ['src_net'] } } }
1066 0 ▶sub _render_remote {
Subroutine _render_remote: not called CC=11 SCAR=48.8
1067 0 my ( $self, $ops ) = @_;
1068  
1069 0 my @calls;
1070 0 foreach my $op ( @{$ops} ) {
1071 0 my $kind = $op->[0];
1072  
1073 0 ▶ if ( $kind eq 'section' ) {
Branch: 8 branches
BranchTrueFalseTotal
if ($kind eq 'section') { } 0 0 0
elsif ($kind eq 'del_section') { } 0 0 0
elsif ($kind eq 'get_section') { } 0 0 0
elsif ($kind eq 'del_option') { } 0 0 0
elsif ($kind eq 'set_list') { } 0 0 0
elsif ($kind eq 'reorder') { } 0 0 0
elsif ($kind eq 'commit') { } 0 0 0
elsif ($kind eq 'exec') { } 0 0 0
1074 0 my ( undef, $name, $type, $kv ) = @{$op};
1075 0 my %values;
1076 0 foreach my $pair ( @{$kv} ) {
1077 0 $values{ $pair->[0] } = $pair->[1];
1078 }
1079 push(
1080 0 @calls,
1081 {
1082 object => 'uci',
1083 method => 'add',
1084 params => { config => 'firewall', type => $type, name => $name, values => \%values },
1085 }
1086 );
1087 } elsif ( $kind eq 'del_section' ) {
1088 0 push(
1089 @calls,
1090 {
1091 object => 'uci',
1092 method => 'delete',
1093 params => { config => 'firewall', section => $op->[1] },
1094 }
1095 );
1096 } elsif ( $kind eq 'get_section' ) {
1097 0 push(
1098 @calls,
1099 {
1100 object => 'uci',
1101 method => 'get',
1102 params => { config => 'firewall', section => $op->[1] },
1103 }
1104 );
1105 } elsif ( $kind eq 'del_option' ) {
1106 0 my ( undef, $name, $option ) = @{$op};
1107 0 push(
1108 @calls,
1109 {
1110 object => 'uci',
1111 method => 'delete',
1112 params => { config => 'firewall', section => $name, option => $option },
1113 }
1114 );
1115 } elsif ( $kind eq 'set_list' ) {
1116 0 my ( undef, $name, $option, $values ) = @{$op};
1117 0 push(
1118 @calls,
1119 {
1120 object => 'uci',
1121 method => 'set',
1122 params => { config => 'firewall', section => $name, values => { $option => $values } },
1123 }
1124 );
1125 } elsif ( $kind eq 'reorder' ) {
1126 0 push(
1127 @calls,
1128 {
1129 object => 'uci',
1130 method => 'order',
1131 params => { config => 'firewall', sections => $op->[1] },
1132 }
1133 );
1134 } elsif ( $kind eq 'commit' ) {
1135 0 push(
1136 @calls,
1137 {
1138 object => 'uci',
1139 method => 'commit',
1140 params => { config => 'firewall' },
1141 }
1142 );
1143 } elsif ( $kind eq 'exec' ) {
1144 0 my ( undef, $command, @params ) = @{$op};
1145 0 push(
1146 @calls,
1147 {
1148 object => 'file',
1149 method => 'exec',
1150 params => { command => $command, params => \@params },
1151 }
1152 );
1153 } ## end elsif ( $kind eq 'exec' )
1154 } ## end foreach my $op ( @{$ops} )
1155  
1156 0 return @calls;
1157 } ## end sub _render_remote
1158  
1159 # Internal helper. Posts one JSON-RPC envelope to the router's ubus endpoint
1160 # and hands back the result, doing no interpretation of what the result means.
1161 #
1162 # LWP::UserAgent is loaded with require on first use and the agent is cached on
1163 # the object, so a run that never touches remote mode never loads it and the
1164 # dist keeps it as a recommends rather than a hard prereq. HTTPS additionally
1165 # needs LWP::Protocol::https, which LWP loads itself.
1166 #
1167 # This deliberately takes the session as an argument instead of fetching it,
1168 # because it is what the login call itself goes through and there is no session
1169 # at that point. Callers other than _session pass what _session returns.
1170 #
1171 # Errors are raised by dying rather than through Error::Helper, as this sits
1172 # below the methods and they wrap their calls in eval so that a transport
1173 # failure comes out as the error for the operation the caller asked for.
1174 #
1175 # Args:
1176 #
1177 # session - The ubus session token, as a string. The all zeroes token is
1178 # what an unauthenticated call, meaning the login, uses.
1179 #
1180 # object - The ubus object to call, as a string, such as 'uci' or 'file'.
1181 #
1182 # method - The method on that object, as a string.
1183 #
1184 # params - A hashref of arguments for the method. Pass an empty hashref
1185 # rather than undef for a method that takes none.
1186 #
1187 # Returns the JSON-RPC result, which for a ubus call is a two element arrayref
1188 # of the ubus status code and, for the calls that return anything, a hashref of
1189 # the returned data. Note that a non-zero status is returned rather than raised;
1190 # deciding what to do about it is _run_rpc's job. A result of [0] with no second
1191 # element is normal for the calls that return no data.
1192 #
1193 # Dies on a transport level failure: LWP not being installed, a non-2xx HTTP
1194 # status, a body that is not JSON, or a JSON-RPC error object in the response.
1195 #
1196 # my $result = $self->_rpc_raw( $session, 'uci', 'commit',
1197 # { config => 'firewall' } );
1198 # # [ 0 ]
1199 #
1200 # my $result = $self->_rpc_raw( $session, 'file', 'exec',
1201 # { command => 'fw4', params => ['reload'] } );
1202 # # [ 0, { code => 0, stdout => '', stderr => '' } ]
1203 0 ▶sub _rpc_raw {
Subroutine _rpc_raw: not called CC=8 SCAR=42.8
1204 0 my ( $self, $session, $object, $method, $params ) = @_;
1205  
1206 0 ▶ if ( !defined( $self->{ua} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"ua"}) 0 0 0
1207 0 local $@;
1208 0 ▶ eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require LWP::UserAgent; my(%args) = ("agent", 'Net::Firewall::BlockerHelper/' . $Net::Firewall::BlockerHelper::backends::openwrt::VERSION, "timeout", $self->{"options"}{"timeout"}); if ($self->{"options"}{"insecure"}) { $args{"ssl_opts"} = {"verify_hostname", 0, "SSL_verify_mode", 0}; } ; $self->{"ua"} = "LWP::UserAgent"->new(%args); 1 } } or die 'failed to load LWP::UserAgent, which the openwrt backend requires in remote mode... ' . $@ 0 0 0
1209 0 require LWP::UserAgent;
1210 my %args = (
1211 agent => 'Net::Firewall::BlockerHelper/' . $VERSION,
1212 timeout => $self->{options}{timeout},
1213 0 );
1214 0 ▶ if ( $self->{options}{insecure} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"options"}{"insecure"}) 0 0 0
1215 0 $args{ssl_opts} = { verify_hostname => 0, SSL_verify_mode => 0 };
1216 }
1217 0 $self->{ua} = LWP::UserAgent->new(%args);
1218 0 1;
1219 } or die( 'failed to load LWP::UserAgent, which the openwrt backend requires in remote mode... ' . $@ );
1220 } ## end if ( !defined( $self->{ua} ) )
1221  
1222 my $url
1223 0 = $self->{options}{http_proto} . '://' . $self->{options}{host} . ':' . $self->{options}{http_port} . '/ubus';
1224  
1225 0 my $body = $self->_json->encode(
1226 {
1227 jsonrpc => '2.0',
1228 id => 1,
1229 method => 'call',
1230 params => [ $session, $object, $method, $params ],
1231 }
1232 );
1233  
1234 0 require HTTP::Request;
1235 0 my $request = HTTP::Request->new( 'POST', $url, [ 'Content-Type' => 'application/json' ], $body );
1236  
1237 0 my $response = $self->{ua}->request($request);
1238  
1239 0 ▶ if ( !$response->is_success ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 0 0 0
1240 0 die( 'POST ' . $url . ' failed... HTTP status... ' . $response->status_line );
1241 }
1242  
1243 0 my $decoded;
1244 {
1245 0 local $@;
1246 0 eval { $decoded = $self->_json->decode( $response->decoded_content ); };
1247 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
1248 0 die( 'POST ' . $url . ' returned a body that is not JSON... ' . $@ );
1249 }
1250 }
1251  
1252 0 ▶ if ( defined( $decoded->{error} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $decoded->{"error"}) 0 0 0
1253 die( 'ubus '
1254 . $object . '.'
1255 . $method
1256 . ' returned a JSON-RPC error... '
1257 0 . $self->_json->encode( $decoded->{error} ) );
1258 }
1259  
1260 0 ▶ if ( ref( $decoded->{result} ) ne 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $decoded->{"result"} ne "ARRAY") 0 0 0
1261 0 die( 'ubus ' . $object . '.' . $method . ' returned no result array' );
1262 }
1263  
1264 0 return $decoded->{result};
1265 } ## end sub _rpc_raw
1266  
1267 # Internal helper. Returns a ubus session token, logging in if there is not
1268 # already a usable one cached on the object.
1269 #
1270 # ubus sessions expire, five minutes after the last use by default, which a
1271 # long lived banning process will certainly outlive. Rather than track the
1272 # expiry, the token is cached and used until something rejects it, at which
1273 # point _run_rpc clears it and asks for another, so a re-login only happens
1274 # when one is actually needed.
1275 #
1276 # Takes no arguments; the credentials come from the user and password options.
1277 #
1278 # Returns the session token as a string, suitable to pass to _rpc_raw.
1279 #
1280 # Dies if the login fails, either at the transport level or by ubus refusing
1281 # the credentials, and on a login that succeeds but hands back no token.
1282 #
1283 # my $session = $self->_session;
1284 # # a 32 character hex string
1285 0 ▶sub _session {
Subroutine _session: not called CC=4 SCAR=30.0
1286 0 my ($self) = @_;
1287  
1288 0 ▶ return $self->{session} if ( defined( $self->{session} ) );
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"session"} 0 0 0
1289  
1290 my $result = $self->_rpc_raw(
1291 '00000000000000000000000000000000',
1292 'session',
1293 'login',
1294 {
1295 username => $self->{options}{user},
1296 password => $self->{options}{password},
1297 }
1298 0 );
1299  
1300 0 ▶ if ( $result->[0] != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result->[0] != 0) 0 0 0
1301 0 die( 'ubus login as "' . $self->{options}{user} . '" failed with ubus status ' . $result->[0] );
1302 }
1303  
1304 0 my $session = $result->[1]{ubus_rpc_session};
1305 0 ▶ if ( !defined($session) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $session) 0 0 0
1306 0 die('ubus login succeeded but returned no ubus_rpc_session');
1307 }
1308  
1309 0 $self->{session} = $session;
1310  
1311 0 return $session;
1312 } ## end sub _session
1313  
1314 # Internal helper. Runs one rendered remote call and reports whether it worked,
1315 # which is the remote half of what _run does per operation.
1316 #
1317 # Two layers of failure have to be unpicked. The ubus status code says whether
1318 # the call itself was accepted, and for file.exec a zero status only means the
1319 # command was started, so the exit code inside the returned data has to be
1320 # checked as well or a failing nft would look like a success.
1321 #
1322 # A permission denied is retried once with a fresh session. That status is what
1323 # an expired session comes back as, and re-logging in is cheap, so the retry
1324 # turns what would otherwise be a spurious failure every five idle minutes into
1325 # a non-event. A second permission denied is a real one and is reported.
1326 #
1327 # Args:
1328 #
1329 # call - One call hashref as produced by _render_remote, with object,
1330 # method, and params keys.
1331 #
1332 # Returns a two element list of a boolean for whether it succeeded and the
1333 # output as a string. The output is the command's stdout with its stderr
1334 # appended for a file.exec, and the JSON encoded returned data for anything
1335 # else, so that a failure has something to report and check has something to
1336 # match against. A call that dies at the transport level comes back as a
1337 # failure whose output is the exception.
1338 #
1339 # my ( $ok, $output ) = $self->_run_rpc(
1340 # { object => 'file', method => 'exec',
1341 # params => { command => 'nft', params => [ 'list', 'ruleset' ] } } );
1342 0 ▶sub _run_rpc {
Subroutine _run_rpc: not called CC=13 SCAR=52.0
1343 0 my ( $self, $call ) = @_;
1344  
1345 0 my $result;
1346 0 my $tries = 0;
1347 0 ▶ while ( $tries < 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tries < 2) 0 0 0
1348 0 $tries++;
1349  
1350 0 local $@;
1351 0 eval { $result = $self->_rpc_raw( $self->_session, $call->{object}, $call->{method}, $call->{params} ); };
1352 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
1353 0 return ( 0, $@ );
1354 }
1355  
1356 # an expired session comes back as permission denied, so drop it and
1357 # try once more with a fresh one
1358 0 ▶ if ( $result->[0] == 6 && $tries < 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result->[0] == 6 and $tries < 2) 0 0 0
Condition0%0/3
$result->[0] == 6 and $tries < 2
!ll&&!rl&&r
000
MC/DC0%0/2
$result->[0] == 6 and $tries < 2
$result->[0] == 6 $tries < 2
Truth table0%0/3
A and B
A= $result->[0] == 6B= $tries < 2
ABresult
0X0
100
111
1359 0 $self->{session} = undef;
1360 0 next;
1361 }
1362  
1363 0 last;
1364 } ## end while ( $tries < 2 )
1365  
1366 0 ▶ if ( $result->[0] != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result->[0] != 0) 0 0 0
1367 0 return ( 0, 'ubus status ' . $result->[0] );
1368 }
1369  
1370 0 my $data = $result->[1];
1371  
1372 0 ▶ if ( $call->{object} eq 'file' && $call->{method} eq 'exec' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($call->{"object"} eq "file" and $call->{"method"} eq "exec") 0 0 0
Condition0%0/3
$call->{"object"} eq "file" and $call->{"method"} eq "exec"
!ll&&!rl&&r
000
MC/DC0%0/2
$call->{"object"} eq "file" and $call->{"method"} eq "exec"
$call->{"object"} eq "file" $call->{"method"} eq "exec"
Truth table0%0/3
A and B
A= $call->{"object"} eq "file"B= $call->{"method"} eq "exec"
ABresult
0X0
100
111
1373 0 my $output = '';
1374 0 ▶ $output .= $data->{stdout} if ( defined( $data->{stdout} ) );
Branch: 1 branch
BranchTrueFalseTotal
if defined $data->{"stdout"} 0 0 0
1375 0 ▶ $output .= $data->{stderr} if ( defined( $data->{stderr} ) );
Branch: 1 branch
BranchTrueFalseTotal
if defined $data->{"stderr"} 0 0 0
1376 0 ▶ return ( ( defined( $data->{code} ) && $data->{code} == 0 ) ? 1 : 0, $output );
Branch: 1 branch
BranchTrueFalseTotal
defined $data->{'code'} && $data->{'code'} == 0 ? : 0 0 0
Condition0%0/3
defined $data->{"code"} and $data->{"code"} == 0
!ll&&!rl&&r
000
MC/DC0%0/2
defined $data->{"code"} and $data->{"code"} == 0
defined $data->{"code"} $data->{"code"} == 0
Truth table0%0/3
A and B
A= defined $data->{"code"}B= $data->{"code"} == 0
ABresult
0X0
100
111
1377 }
1378  
1379 0 ▶ return ( 1, defined($data) ? $self->_json->encode($data) : '' );
Branch: 1 branch
BranchTrueFalseTotal
defined $data ? : 0 0 0
1380 } ## end sub _run_rpc
1381  
1382 # Internal helper. Renders a list of abstract operations for whichever mode the
1383 # backend is in, runs them unless this is a test, and reports any failure
1384 # through Error::Helper.
1385 #
1386 # Every method goes through here rather than running anything itself, which is
1387 # what keeps them free of the local versus remote split: they build operations,
1388 # hand them over, and store what comes back in test_data when testing.
1389 #
1390 # Nothing is run at all in testing mode. The rendered operations are still
1391 # returned, so a test asserts on exactly what would have been done, in the form
1392 # the mode under test would have done it in: command line strings locally,
1393 # call hashrefs remotely.
1394 #
1395 # Args:
1396 #
1397 # ops - An arrayref of abstract operations, as described on _render_local.
1398 #
1399 # %args - The rest, all optional:
1400 #
1401 # error - The error number to raise if an operation fails. Leaving
1402 # this out, or passing 0, makes the whole batch best effort,
1403 # which is what the stale state cleanup at init and the
1404 # deletes at teardown want, as they are routinely run against
1405 # a setup that is already partly gone.
1406 #
1407 # action - The word naming the operation in the error string, such as
1408 # 'init' or 'ban'. Only used when error is set.
1409 #
1410 # tolerate - A regexp. A failed operation whose output matches it is
1411 # treated as having succeeded. This is for the failures that
1412 # mean the caller's goal was already met rather than that
1413 # something went wrong, specifically nft reporting "element
1414 # does not exist" when unbanning something the set has
1415 # already lost. Unlike leaving error out, this only forgives
1416 # the matching failure and still raises on everything else.
1417 #
1418 # Returns a two element list of an arrayref of the rendered operations and an
1419 # arrayref of their outputs. The outputs are in the same order and are empty in
1420 # testing mode. Note that with errors being fatal by default, a failure raised
1421 # here does not return at all.
1422 #
1423 # my ( $rendered, $outputs ) = $self->_run(
1424 # [ [ 'exec', 'fw4', 'reload' ] ], error => 23, action => 'init' );
1425 #
1426 # # best effort, failures ignored
1427 # my ($rendered) = $self->_run( [ [ 'del_section', $section ] ] );
1428 0 ▶sub _run {
Subroutine _run: not called CC=12 SCAR=50.5
1429 0 my ( $self, $ops, %args ) = @_;
1430  
1431 my @rendered
1432 = defined( $self->{options}{host} )
1433 0 ▶ ? $self->_render_remote($ops)
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'options'}{'host'} ? : 0 0 0
1434 : $self->_render_local($ops);
1435  
1436 0 my @outputs;
1437  
1438 0 ▶ if ( !$self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"testing"}) 0 0 0
1439 0 foreach my $item (@rendered) {
1440 0 my ( $ok, $output );
1441 0 ▶ if ( defined( $self->{options}{host} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{'options'}{'host'}) { } 0 0 0
1442 0 ( $ok, $output ) = $self->_run_rpc($item);
1443 } else {
1444 0 $output = `$item 2>&1`;
1445 0 ▶ $ok = ( $? == 0 ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$? == 0 ? : 0 0 0
1446 }
1447 0 push( @outputs, $output );
1448  
1449 # a failure the caller said to expect is not a failure
1450 0 ▶ if ( !$ok && $args{tolerate} && defined($output) && $output =~ $args{tolerate} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $ok and $args{"tolerate"} and defined $output and $output =~ /$args{"tolerate"}/) 0 0 0
Condition0%0/9
not $ok and $args{"tolerate"} and defined $output and $output =~ /$args{"tolerate"}/
!ll&&!rl&&r
000
not $ok and $args{"tolerate"} and defined $output
!ll&&!rl&&r
000
not $ok and $args{"tolerate"}
!ll&&!rl&&r
000
MC/DC0%0/4
not $ok and $args{"tolerate"} and defined $output and $output =~ /$args{"tolerate"}/
not $ok $args{"tolerate"} defined $output $output =~ /$args{"tolerate"}/
Truth table0%0/5
not(A) and B and C and D
A= not $okB= $args{"tolerate"}C= defined $outputD= $output =~ /$args{"tolerate"}/
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1451 0 $ok = 1;
1452 }
1453  
1454 0 ▶ if ( !$ok && $args{error} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $ok and $args{"error"}) 0 0 0
Condition0%0/3
not $ok and $args{"error"}
!ll&&!rl&&r
000
MC/DC0%0/2
not $ok and $args{"error"}
not $ok $args{"error"}
Truth table0%0/3
not(A) and B
A= not $okB= $args{"error"}
ABresult
0X0
100
111
1455 0 $self->{error} = $args{error};
1456 $self->{errorString}
1457 = $args{action}
1458 0 . ' failed. the operation... "'
1459 . $self->_describe($item)
1460 . '"... failed... output... '
1461 . $output;
1462 0 $self->warn;
1463 } ## end if ( !$ok && $args{error} )
1464 } ## end foreach my $item (@rendered)
1465 } ## end if ( !$self->{testing} )
1466  
1467 0 return ( \@rendered, \@outputs );
1468 } ## end sub _run
1469  
1470 # Internal helper. Turns a rendered operation back into something printable, so
1471 # that an error string can say which one failed regardless of the mode.
1472 #
1473 # A locally rendered operation is already a command line string and is returned
1474 # as is. A remotely rendered one is a hashref, so it is encoded as JSON, which
1475 # keeps the object, method, and arguments legible in one line.
1476 #
1477 # Args:
1478 #
1479 # item - One rendered operation, either a string from _render_local or a
1480 # hashref from _render_remote.
1481 #
1482 # Returns a single line string describing it.
1483 #
1484 # $self->_describe('uci commit firewall');
1485 # # uci commit firewall
1486 #
1487 # $self->_describe( { object => 'uci', method => 'commit',
1488 # params => { config => 'firewall' } } );
1489 # # {"method":"commit","object":"uci","params":{"config":"firewall"}}
1490 0 ▶sub _describe {
Subroutine _describe: not called CC=2 SCAR=17.9
1491 0 my ( $self, $item ) = @_;
1492  
1493 0 ▶ return $item if ( ref($item) eq '' );
Branch: 1 branch
BranchTrueFalseTotal
if ref $item eq "" 0 0 0
1494  
1495 0 return $self->_json->encode($item);
1496 }
1497  
1498 =head2 init
1499  
1500 Initiates the backend. A best effort delete of this instance's UCI sections
1501 is run first to clear any stale copy of them, then the two C<config ipset>
1502 sections and the C<config rule> sections are created, the rules are moved to
1503 the front of the config unless the C<reorder> option says otherwise, the
1504 changes are committed via L</commit>, and C<fw4 reload> is run to bring the
1505 new ruleset up.
1506  
1507 Existing bans are not re-applied here. See L</re_init> for that.
1508  
1509 $backend->init;
1510  
1511 =cut
1512  
1513 0 ▶sub init {
Subroutine init: not called CC=10 SCAR=47.0
Pod documented
1514 0 my ( $self, %opts ) = @_;
1515  
1516 0 $self->errorblank;
1517  
1518 0 ▶ if ( $self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"inited"}) 0 0 0
1519 0 $self->{error} = 18;
1520 0 $self->{errorString} = 'backend has already been inited';
1521 0 $self->warn;
1522 }
1523  
1524 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1525 0 $self->{frontend_obj}->{test_data} = {};
1526 }
1527  
1528 0 my @ipsets = $self->_ipset_sections;
1529 0 my ($rules) = $self->_rule_specs;
1530  
1531 # stale state cleanup, allowed to fail
1532 0 my @fail_okay_ops;
1533 0 foreach my $section ( @{$rules}, @ipsets ) {
1534 0 push( @fail_okay_ops, [ 'del_section', $section->{name} ] );
1535 }
1536  
1537 0 my ($fail_okay_rendered) = $self->_run( \@fail_okay_ops );
1538  
1539 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1540 0 $self->{frontend_obj}->{test_data}{fail_okay_commands} = $fail_okay_rendered;
1541 }
1542  
1543 0 my @ops;
1544 0 foreach my $section ( @ipsets, @{$rules} ) {
1545 0 push( @ops, [ 'section', $section->{name}, $section->{type}, $section->{kv} ] );
1546 }
1547  
1548 0 ▶ if ( $self->{options}{reorder} && @{$rules} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"options"}{"reorder"} and @{$rules;}) 0 0 0
Condition0%0/3
$self->{"options"}{"reorder"} and @{$rules;}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"options"}{"reorder"} and @{$rules;}
$self->{"options"}{"reorder"} @{$rules;}
Truth table0%0/3
A and B
A= $self->{"options"}{"reorder"}B= @{$rules;}
ABresult
0X0
100
111
1549 0 push( @ops, [ 'reorder', [ map { $_->{name} } @{$rules} ] ] );
1550 }
1551  
1552 0 my ($rendered) = $self->_run( \@ops, error => 23, action => 'init' );
1553  
1554 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1555 0 $self->{frontend_obj}->{test_data}{commands} = $rendered;
1556 }
1557  
1558 0 $self->commit;
1559 0 my ($reload) = $self->_run( [ [ 'exec', 'fw4', 'reload' ] ], error => 23, action => 'init' );
1560  
1561 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1562 0 $self->{frontend_obj}->{test_data}{reload} = $reload;
1563 }
1564  
1565 0 $self->{inited} = 1;
1566 } ## end sub init
1567  
1568 =head2 commit
1569  
1570 Writes the current ban list into the UCI ipset sections and commits the
1571 staged firewall config to persistent storage.
1572  
1573 Banning and unbanning only touch the live nftables sets, so a ban is in
1574 effect the moment it is made but does not survive a firewall restart or a
1575 reboot. This is what makes it survive. It is separate, and not run
1576 automatically, because C<uci commit> writes to the overlay filesystem, which
1577 on most OpenWrt devices is flash; committing per ban would wear it out. Call
1578 it as often as the durability of the ban list warrants and no more.
1579  
1580 L</init> and L</teardown> call this themselves, as both change the config and
1581 would otherwise leave it staged and unwritten.
1582  
1583 Note that L</flush> does not commit, so the emptied ban list is not persisted
1584 until this is called.
1585  
1586 This is the only backend that implements this method.
1587  
1588 $fw_helper->ban(ban => '1.2.3.4');
1589 $fw_helper->ban(ban => '5.6.7.8');
1590 $fw_helper->commit;
1591  
1592 =cut
1593  
1594 0 ▶sub commit {
Subroutine commit: not called CC=4 SCAR=30.0
Pod documented
1595 0 my ( $self, %opts ) = @_;
1596  
1597 0 $self->errorblank;
1598  
1599 0 my ( $base, $set4, $set6 ) = $self->_names;
1600  
1601 0 my ( $v4, $v6 ) = $self->_entry_lists;
1602  
1603 # clearing the old list out is best effort, as there is no entry option at
1604 # all until a commit has written one and ubus reports deleting an option
1605 # that is not there as a failure
1606 0 my @clear_ops = ( [ 'del_option', $set4, 'entry' ], [ 'del_option', $set6, 'entry' ], );
1607  
1608 0 my ($cleared) = $self->_run( \@clear_ops );
1609  
1610 # a family with no bans is left with no entry option rather than an empty
1611 # one, as ubus rejects an empty list outright
1612 0 my @ops;
1613 0 ▶ push( @ops, [ 'set_list', $set4, 'entry', $v4 ] ) if ( @{$v4} );
Branch: 1 branch
BranchTrueFalseTotal
if @{$v4;} 0 0 0
1614 0 ▶ push( @ops, [ 'set_list', $set6, 'entry', $v6 ] ) if ( @{$v6} );
Branch: 1 branch
BranchTrueFalseTotal
if @{$v6;} 0 0 0
1615 0 push( @ops, ['commit'] );
1616  
1617 0 my ($rendered) = $self->_run( \@ops, error => 31, action => 'commit' );
1618  
1619 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1620 0 $self->{frontend_obj}->{test_data}{commit} = [ @{$cleared}, @{$rendered} ];
1621 }
1622  
1623 0 return;
1624 } ## end sub commit
1625  
1626 # Internal helper. Writes the staged UCI changes out without touching the
1627 # entry lists first, which is the half of commit that teardown wants.
1628 #
1629 # teardown deletes this instance's sections and then has to make that stick,
1630 # but it can not go through commit to do it. commit's first job is to write
1631 # the ban list into the ipset sections, and by that point those sections are
1632 # gone, so it would be setting an option on something that no longer exists.
1633 # ubus reports that as a plain failure and the teardown dies having already
1634 # removed the config it was committing.
1635 #
1636 # The ban list is deliberately not cleared to make commit safe to call here
1637 # instead. teardown keeps the bans so that a following re_init can put them
1638 # back, which is the documented behaviour and what the frontend's self healing
1639 # relies on.
1640 #
1641 # Args:
1642 #
1643 # error - The error number to raise if the commit fails, passed straight
1644 # through to _run. Callers pass their own so the failure is
1645 # reported as theirs.
1646 #
1647 # action - The word naming the operation in the error string, likewise
1648 # passed through.
1649 #
1650 # Returns the rendered operations as an arrayref, the single commit, so that a
1651 # caller in testing mode can record it.
1652 #
1653 # my $committed = $self->_commit_config( 17, 'teardown' );
1654 0 ▶sub _commit_config {
Subroutine _commit_config: not called CC=1 SCAR=6.9
1655 0 my ( $self, $error, $action ) = @_;
1656  
1657 0 my ($rendered) = $self->_run( [ ['commit'] ], error => $error, action => $action );
1658  
1659 0 return $rendered;
1660 }
1661  
1662 =head2 ban
1663  
1664 Bans an IP. The value of ban is validated as being a IPv4 or IPv6 address
1665 and lowercased, then added to the family-appropriate set via
1666 C<nft add element>. If the C<kill> option is set, conntrack(8) is then used
1667 to drop existing connection tracking entries for the IP. Banning an already
1668 banned IP is a noop.
1669  
1670 The UCI config is not touched and nothing is committed, so the ban is in
1671 effect immediately but is lost by a firewall restart or a reboot until
1672 L</commit> is called.
1673  
1674 $backend->ban(ban => $ip);
1675  
1676 =cut
1677  
1678 0 ▶sub ban {
Subroutine ban: not called CC=9 SCAR=45.0
Pod documented
1679 0 my ( $self, %opts ) = @_;
1680  
1681 0 $self->errorblank;
1682  
1683 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
1684 0 $self->{error} = 1;
1685 0 $self->{errorString} = 'backend has not been inited';
1686 0 $self->warn;
1687 0 return;
1688 }
1689  
1690 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::openwrt::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::openwrt::IPv6_re\z/) { } 0 0 0
1691 0 $self->{error} = 9;
1692 0 $self->{errorString} = 'Nothing specified for the value ban';
1693 0 $self->warn;
1694 0 return;
1695 } elsif ( ref( $opts{ban} ) ne '' ) {
1696 0 $self->{error} = 10;
1697 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
1698 0 $self->warn;
1699 0 return;
1700 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition0%0/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::openwrt::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::openwrt::IPv6_re\z/
l!l&&r!l&&!r
000
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::openwrt::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::openwrt::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::openwrt::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::openwrt::IPv6_re\z/
Truth table0%0/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::openwrt::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::openwrt::IPv6_re\z/
ABresult
1X1
011
000
1701 && $opts{ban} !~ /\A$IPv6_re\z/ )
1702 {
1703 0 $self->{error} = 10;
1704 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
1705 0 $self->warn;
1706 0 return;
1707 }
1708  
1709 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
1710 0 $opts{ban} = lc( $opts{ban} );
1711  
1712 0 ▶ if ( $self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"banned"}{$opts{"ban"}}) 0 0 0
1713 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1714 0 $self->{frontend_obj}->{test_data} = 'already banned';
1715 }
1716 0 return;
1717 }
1718  
1719 0 my @ops = ( $self->_element_op( 'add', $opts{ban} ) );
1720 0 push( @ops, $self->_kill_ops( $opts{ban} ) );
1721  
1722 0 my ($rendered) = $self->_run( \@ops, error => 13, action => 'ban' );
1723  
1724 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1725 0 $self->{frontend_obj}->{test_data} = $rendered;
1726 }
1727  
1728 0 $self->{banned}{ $opts{ban} } = 1;
1729 } ## end sub ban
1730  
1731 =head2 unban
1732  
1733 Unbans an IP. The value of ban is validated as being a IPv4 or IPv6 address
1734 and lowercased, then removed from the family-appropriate set via
1735 C<nft delete element>. Unbanning an IP that is not banned is a noop.
1736  
1737 As with L</ban>, nothing is committed; call L</commit> to persist the change.
1738  
1739 $backend->unban(ban => $ip);
1740  
1741 =cut
1742  
1743 0 ▶sub unban {
Subroutine unban: not called CC=9 SCAR=45.0
Pod documented
1744 0 my ( $self, %opts ) = @_;
1745  
1746 0 $self->errorblank;
1747  
1748 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
1749 0 $self->{error} = 1;
1750 0 $self->{errorString} = 'backend has not been inited';
1751 0 $self->warn;
1752 0 return;
1753 }
1754  
1755 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::openwrt::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::openwrt::IPv6_re\z/) { } 0 0 0
1756 0 $self->{error} = 9;
1757 0 $self->{errorString} = 'Nothing specified for the value ban';
1758 0 $self->warn;
1759 0 return;
1760 } elsif ( ref( $opts{ban} ) ne '' ) {
1761 0 $self->{error} = 10;
1762 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
1763 0 $self->warn;
1764 0 return;
1765 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition0%0/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::openwrt::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::openwrt::IPv6_re\z/
l!l&&r!l&&!r
000
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::openwrt::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::openwrt::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::openwrt::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::openwrt::IPv6_re\z/
Truth table0%0/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::openwrt::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::openwrt::IPv6_re\z/
ABresult
1X1
011
000
1766 && $opts{ban} !~ /\A$IPv6_re\z/ )
1767 {
1768 0 $self->{error} = 10;
1769 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
1770 0 $self->warn;
1771 0 return;
1772 }
1773  
1774 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
1775 0 $opts{ban} = lc( $opts{ban} );
1776  
1777 0 ▶ if ( !$self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"banned"}{$opts{"ban"}}) 0 0 0
1778 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1779 0 $self->{frontend_obj}->{test_data} = 'not banned';
1780 }
1781 0 return;
1782 }
1783  
1784 my ($rendered) = $self->_run(
1785 0 [ $self->_element_op( 'delete', $opts{ban} ) ],
1786 error => 14,
1787 action => 'unban',
1788 tolerate => qr/does not exist/,
1789 );
1790  
1791 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1792 0 $self->{frontend_obj}->{test_data} = $rendered;
1793 }
1794  
1795 0 delete( $self->{banned}{ $opts{ban} } );
1796 } ## end sub unban
1797  
1798 =head2 ban_cidr
1799  
1800 Bans a CIDR range by adding it to the family-appropriate set via
1801 C<nft add element>. The value of ban is validated as being a IPv4 or IPv6
1802 CIDR range and lowercased. Banning an already banned range is a noop.
1803  
1804 The sets are interval sets, so ranges share the sets the single IP bans use
1805 and need no separate setup. Host bits do not need zeroing; nftables takes the
1806 range as given.
1807  
1808 $backend->ban_cidr(ban => '1.2.3.0/24');
1809  
1810 =cut
1811  
1812 0 ▶sub ban_cidr {
Subroutine ban_cidr: not called CC=8 SCAR=42.8
Pod documented
1813 0 my ( $self, %opts ) = @_;
1814  
1815 0 $self->errorblank;
1816  
1817 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
1818 0 $self->{error} = 1;
1819 0 $self->{errorString} = 'backend has not been inited';
1820 0 $self->warn;
1821 0 return;
1822 }
1823  
1824 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
1825 0 $self->{error} = 9;
1826 0 $self->{errorString} = 'Nothing specified for the value ban';
1827 0 $self->warn;
1828 0 return;
1829 } elsif ( ref( $opts{ban} ) ne '' ) {
1830 0 $self->{error} = 28;
1831 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
1832 0 $self->warn;
1833 0 return;
1834 } elsif ( !$self->_valid_cidr( $opts{ban} ) ) {
1835 0 $self->{error} = 28;
1836 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 CIDR';
1837 0 $self->warn;
1838 0 return;
1839 }
1840  
1841 # lowercase so the same IPv6 CIDR in differing cases can't result in duplicate entries
1842 0 $opts{ban} = lc( $opts{ban} );
1843  
1844 0 ▶ if ( $self->{banned_cidr}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"banned_cidr"}{$opts{"ban"}}) 0 0 0
1845 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1846 0 $self->{frontend_obj}->{test_data} = 'already banned';
1847 }
1848 0 return;
1849 }
1850  
1851 0 my ($rendered) = $self->_run( [ $self->_element_op( 'add', $opts{ban} ) ], error => 26, action => 'ban_cidr' );
1852  
1853 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1854 0 $self->{frontend_obj}->{test_data} = $rendered;
1855 }
1856  
1857 0 $self->{banned_cidr}{ $opts{ban} } = 1;
1858 } ## end sub ban_cidr
1859  
1860 =head2 unban_cidr
1861  
1862 Unbans a CIDR range by removing it from the family-appropriate set via
1863 C<nft delete element>. The value of ban is validated as being a IPv4 or IPv6
1864 CIDR range and lowercased. Unbanning a range that is not banned is a noop.
1865  
1866 $backend->unban_cidr(ban => '1.2.3.0/24');
1867  
1868 =cut
1869  
1870 0 ▶sub unban_cidr {
Subroutine unban_cidr: not called CC=8 SCAR=42.8
Pod documented
1871 0 my ( $self, %opts ) = @_;
1872  
1873 0 $self->errorblank;
1874  
1875 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
1876 0 $self->{error} = 1;
1877 0 $self->{errorString} = 'backend has not been inited';
1878 0 $self->warn;
1879 0 return;
1880 }
1881  
1882 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
1883 0 $self->{error} = 9;
1884 0 $self->{errorString} = 'Nothing specified for the value ban';
1885 0 $self->warn;
1886 0 return;
1887 } elsif ( ref( $opts{ban} ) ne '' ) {
1888 0 $self->{error} = 28;
1889 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
1890 0 $self->warn;
1891 0 return;
1892 } elsif ( !$self->_valid_cidr( $opts{ban} ) ) {
1893 0 $self->{error} = 28;
1894 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 CIDR';
1895 0 $self->warn;
1896 0 return;
1897 }
1898  
1899 # lowercase so the same IPv6 CIDR in differing cases can't result in duplicate entries
1900 0 $opts{ban} = lc( $opts{ban} );
1901  
1902 0 ▶ if ( !$self->{banned_cidr}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"banned_cidr"}{$opts{"ban"}}) 0 0 0
1903 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1904 0 $self->{frontend_obj}->{test_data} = 'not banned';
1905 }
1906 0 return;
1907 }
1908  
1909 my ($rendered) = $self->_run(
1910 0 [ $self->_element_op( 'delete', $opts{ban} ) ],
1911 error => 27,
1912 action => 'unban_cidr',
1913 tolerate => qr/does not exist/,
1914 );
1915  
1916 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1917 0 $self->{frontend_obj}->{test_data} = $rendered;
1918 }
1919  
1920 0 delete( $self->{banned_cidr}{ $opts{ban} } );
1921 } ## end sub unban_cidr
1922  
1923 # Internal helper. Returns the operation that adds an address or range to, or
1924 # removes it from, the live nftables set it belongs in.
1925 #
1926 # Everything that changes what is blocked goes through here, which is what
1927 # keeps ban, unban, ban_cidr, unban_cidr, and re_init all producing the same
1928 # command shape and all agreeing on which set an item belongs in.
1929 #
1930 # The set lives in fw4's own inet fw4 table rather than in a table of this
1931 # backend's own, because it was fw4 that created it from the UCI ipset section.
1932 # That is also why the element is added rather than the config being changed:
1933 # the config only comes into it at commit time.
1934 #
1935 # The braces are kept in one parameter rather than being split out as their
1936 # own. Locally that renders as a single quoted argument, which is legible and
1937 # safe, and remotely it is passed to nft as one argv entry, which nft joins
1938 # with the rest before parsing anyway.
1939 #
1940 # Args:
1941 #
1942 # action - 'add' or 'delete'. Passed to nft as is, so anything else would
1943 # be an nft syntax error rather than caught here.
1944 #
1945 # item - The address or range, as a plain string. Expected to be already
1946 # validated and lowercased. The family picks the set.
1947 #
1948 # Returns one exec operation, ready to put in a list for _run.
1949 #
1950 # $self->_element_op( 'add', '10.0.0.1' );
1951 # # local: nft add element inet fw4 kur_ssh_4 '{ 10.0.0.1 }'
1952 # # remote: file.exec nft
1953 # # [ add, element, inet, fw4, kur_ssh_4, "{ 10.0.0.1 }" ]
1954 #
1955 # $self->_element_op( 'delete', '2001:db8::/32' );
1956 # # local: nft delete element inet fw4 kur_ssh_6 '{ 2001:db8::/32 }'
1957 0 ▶sub _element_op {
Subroutine _element_op: not called CC=1 SCAR=6.9
1958 0 my ( $self, $action, $item ) = @_;
1959  
1960 0 return [ 'exec', 'nft', $action, 'element', 'inet', 'fw4', $self->_set_for($item), '{ ' . $item . ' }' ];
1961 }
1962  
1963 # Internal helper. Returns the operations that tear down an IP's existing
1964 # connections, or nothing at all when the kill option is off.
1965 #
1966 # The commands themselves come from Util's _kill_commands, which every
1967 # conntrack using backend shares and which handles scoping the kill to the
1968 # configured protocols and the address family. Those come back as command line
1969 # strings, which suits the backends that only ever run things locally, so this
1970 # splits them back into a command and its parameters for the abstract operation
1971 # form both of this backend's modes are built on.
1972 #
1973 # Splitting on whitespace is safe because everything _kill_commands emits is
1974 # option flags, protocol names, and an address, none of which can contain a
1975 # space.
1976 #
1977 # Args:
1978 #
1979 # ip - The address whose connections should be dropped, as a plain string.
1980 # Expected to be an already validated and lowercased IPv4 or IPv6
1981 # address. Only ever a single address; conntrack is not asked to drop
1982 # a whole range, so the CIDR methods do not call this.
1983 #
1984 # Returns the operations as a list, empty when the kill option is off and also
1985 # when every configured protocol was one conntrack can not filter by.
1986 #
1987 # # kill off
1988 # $self->_kill_ops('10.0.0.1'); # ()
1989 #
1990 # # kill on, protocols tcp
1991 # $self->_kill_ops('10.0.0.1');
1992 # # [ 'exec', 'conntrack', '-D', '-p', 'tcp', '-s', '10.0.0.1' ]
1993 0 ▶sub _kill_ops {
Subroutine _kill_ops: not called CC=3 SCAR=24.8
1994 0 my ( $self, $ip ) = @_;
1995  
1996 0 ▶ return () if ( !$self->{options}{kill} );
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"options"}{"kill"} 0 0 0
1997  
1998 0 my @ops;
1999 0 foreach my $command ( $self->_kill_commands($ip) ) {
2000 0 my @parts = split( /\s+/, $command );
2001 0 push( @ops, [ 'exec', @parts ] );
2002 }
2003  
2004 0 return @ops;
2005 } ## end sub _kill_ops
2006  
2007 =head2 list
2008  
2009 List banned IPs. Returns an array of the currently banned single IPs from the
2010 retained in-memory state; the sets are not queried. CIDR range bans are not
2011 included; for those see L</list_cidr>.
2012  
2013 my @banned = $backend->list;
2014  
2015 =cut
2016  
2017 0 ▶sub list {
Subroutine list: not called CC=2 SCAR=17.9
Pod documented
2018 0 my ( $self, %opts ) = @_;
2019  
2020 0 $self->errorblank;
2021  
2022 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
2023 0 $self->{frontend_obj}->{test_data} = 'list';
2024 }
2025  
2026 0 return keys( %{ $self->{banned} } );
2027 } ## end sub list
2028  
2029 =head2 list_cidr
2030  
2031 List banned CIDR ranges. Returns an array of the currently banned ranges from
2032 the retained in-memory state; the sets are not queried.
2033  
2034 my @banned_cidrs = $backend->list_cidr;
2035  
2036 =cut
2037  
2038 0 ▶sub list_cidr {
Subroutine list_cidr: not called CC=2 SCAR=17.9
Pod documented
2039 0 my ( $self, %opts ) = @_;
2040  
2041 0 $self->errorblank;
2042  
2043 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
2044 0 $self->{frontend_obj}->{test_data} = 'list_cidr';
2045 }
2046  
2047 0 return keys( %{ $self->{banned_cidr} } );
2048 } ## end sub list_cidr
2049  
2050 =head2 re_init
2051  
2052 Tears down and re-initiates the backend, recreating the UCI sections and
2053 reloading fw4, then re-adds every previously banned IP and CIDR range to the
2054 relevant set via C<nft add element>. The teardown is best effort as a
2055 partially or fully wiped setup is exactly what this needs to recover from.
2056  
2057 This is what recovers the live sets after a firewall restart or a reboot,
2058 which empty them of everything that had not been committed.
2059  
2060 $backend->re_init;
2061  
2062 =cut
2063  
2064 0 ▶sub re_init {
Subroutine re_init: not called CC=3 SCAR=24.8
Pod documented
2065 0 my ( $self, %opts ) = @_;
2066  
2067 0 $self->errorblank;
2068  
2069 # teardown is best effort here as a partially or fully wiped setup is
2070 # exactly what re_init needs to recover from; init cleans up any remnants
2071 {
2072 0 local $@;
2073 0 eval { $self->teardown; };
2074 }
2075 0 $self->init;
2076  
2077 0 my @ops;
2078 0 foreach my $item ( sort( keys( %{ $self->{banned} } ) ), sort( keys( %{ $self->{banned_cidr} } ) ) ) {
2079 0 push( @ops, $self->_element_op( 'add', $item ) );
2080 }
2081  
2082 0 my ($rendered) = $self->_run( \@ops, error => 13, action => 're_init' );
2083  
2084 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
2085 0 $self->{frontend_obj}->{test_data} = $rendered;
2086 }
2087  
2088 0 $self->{inited} = 1;
2089 } ## end sub re_init
2090  
2091 =head2 teardown
2092  
2093 Tears down the setup for the backend by deleting this instance's C<config
2094 rule> and C<config ipset> sections, committing that, running C<fw4 reload> to
2095 drop the rules, and then deleting the two sets outright.
2096  
2097 The commit here is a bare one and does not go through L</commit>, as the
2098 ipset sections the ban list would be written into have just been deleted. The
2099 ban list itself is kept, so a following L</re_init> restores it.
2100  
2101 The sets need deleting explicitly because C<fw4 reload> is incremental: it
2102 removes the rules that are no longer in the config but leaves behind a set
2103 whose C<config ipset> section has gone, so without this each teardown would
2104 strand an orphaned set in the live ruleset. C<fw4 restart> would clear them,
2105 but at the cost of emptying every other set in the table, including those of
2106 any other instance sharing the router, so the sets are removed by name
2107 instead. This is also why they are deleted after the reload rather than
2108 before: nftables will not remove a set a rule still refers to.
2109  
2110 The section deletes and the set deletes are best effort, as tearing down a
2111 setup that is already partly gone is normal, but a failure to commit or to
2112 reload is raised.
2113  
2114 $backend->teardown;
2115  
2116 =cut
2117  
2118 0 ▶sub teardown {
Subroutine teardown: not called CC=6 SCAR=37.4
Pod documented
2119 0 my ( $self, %opts ) = @_;
2120  
2121 0 $self->errorblank;
2122  
2123 0 $self->{inited} = 0;
2124  
2125 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
2126 0 $self->{frontend_obj}->{test_data} = {};
2127 }
2128  
2129 0 my @ipsets = $self->_ipset_sections;
2130 0 my ($rules) = $self->_rule_specs;
2131  
2132 0 my @ops;
2133 0 foreach my $section ( @{$rules}, @ipsets ) {
2134 0 push( @ops, [ 'del_section', $section->{name} ] );
2135 }
2136  
2137 0 my ($rendered) = $self->_run( \@ops );
2138  
2139 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
2140 0 $self->{frontend_obj}->{test_data}{fail_okay_commands} = $rendered;
2141 }
2142  
2143 0 my $committed = $self->_commit_config( 17, 'teardown' );
2144 0 my ($reload) = $self->_run( [ [ 'exec', 'fw4', 'reload' ] ], error => 17, action => 'teardown' );
2145  
2146 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
2147 0 $self->{frontend_obj}->{test_data}{commit} = $committed;
2148 0 $self->{frontend_obj}->{test_data}{reload} = $reload;
2149 }
2150  
2151 # the reload has taken the rules, so nothing refers to the sets any more
2152 # and they can be removed; best effort, as they are already gone after a
2153 # firewall restart or if init never got as far as creating them
2154 0 my ( $base, $set4, $set6 ) = $self->_names;
2155 0 my ($dropped) = $self->_run(
2156 [
2157 [ 'exec', 'nft', 'delete', 'set', 'inet', 'fw4', $set4 ],
2158 [ 'exec', 'nft', 'delete', 'set', 'inet', 'fw4', $set6 ],
2159 ]
2160 );
2161  
2162 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
2163 0 $self->{frontend_obj}->{test_data}{drop_sets} = $dropped;
2164 }
2165 } ## end sub teardown
2166  
2167 =head2 stop
2168  
2169 Alias for L</teardown>, provided for parity with the fail2ban C<actionstop>
2170 concept.
2171  
2172 $backend->stop;
2173  
2174 =cut
2175  
2176 0 ▶sub stop {
Subroutine stop: not called CC=1 SCAR=6.9
Pod documented
2177 0 my ( $self, %opts ) = @_;
2178  
2179 0 return $self->teardown(%opts);
2180 }
2181  
2182 =head2 check
2183  
2184 Verifies that the setup is still intact, at the config level, the runtime
2185 level, and the contents level. The UCI sections for each set the rules use,
2186 and for every rule, are probed; fw4's table is listed and checked for each of
2187 those sets being both defined and referenced by a rule; and any set whose
2188 family currently has bans is confirmed to actually hold something. Returns a
2189 true value if all of that holds and a false value if any of it does not. This
2190 is the equivalent of fail2ban's C<actioncheck>.
2191  
2192 Checking the contents as well is what catches the case that matters most
2193 here. An C<fw4 restart>, an C<< /etc/init.d/firewall restart >>, or a reboot
2194 empties the sets of everything that was not committed, while leaving the
2195 config and the rules perfectly intact, so nothing but the emptiness gives it
2196 away. Only emptiness is treated as broken, not a mismatch against the ban
2197 list, because nftables merges and splits the intervals in an interval set and
2198 what comes back is often not what went in.
2199  
2200 An C<fw4 reload>, as opposed to a restart, preserves set contents and so is
2201 not something this needs to catch.
2202  
2203 if ( !$backend->check ) {
2204 $backend->re_init;
2205 }
2206  
2207 =cut
2208  
2209 0 ▶sub check {
Subroutine check: not called CC=17 SCAR=57.2
Pod documented
2210 0 my ( $self, %opts ) = @_;
2211  
2212 0 $self->errorblank;
2213  
2214 0 my ( $base, $set4, $set6 ) = $self->_names;
2215  
2216 0 my ( $rules, $referenced ) = $self->_rule_specs;
2217  
2218 0 my @sets = sort( keys( %{$referenced} ) );
2219  
2220 # which families currently have something that ought to be in their set,
2221 # so that an emptied set can be told from a legitimately empty one
2222 0 my ( $v4, $v6 ) = $self->_entry_lists;
2223 0 my %expected = ( $set4 => scalar( @{$v4} ), $set6 => scalar( @{$v6} ) );
2224  
2225 0 my @ops;
2226 0 foreach my $set (@sets) {
2227 0 push( @ops, [ 'get_section', $set ] );
2228 }
2229 0 foreach my $section ( @{$rules} ) {
2230 0 push( @ops, [ 'get_section', $section->{name} ] );
2231 }
2232 0 push( @ops, [ 'exec', 'nft', 'list', 'table', 'inet', 'fw4' ] );
2233  
2234 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
2235 0 my ($rendered) = $self->_run( \@ops );
2236 0 $self->{frontend_obj}->{test_data} = $rendered;
2237 0 return 1;
2238 }
2239  
2240 my @rendered
2241 = defined( $self->{options}{host} )
2242 0 ▶ ? $self->_render_remote( \@ops )
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'options'}{'host'} ? : 0 0 0
2243 : $self->_render_local( \@ops );
2244  
2245 # everything but the table listing is a presence probe, where a failure is
2246 # the whole answer and there is nothing to read
2247 0 my $listing = pop(@rendered);
2248  
2249 0 foreach my $item (@rendered) {
2250 0 my $ok;
2251 0 ▶ if ( defined( $self->{options}{host} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{'options'}{'host'}) { } 0 0 0
2252 0 ($ok) = $self->_run_rpc($item);
2253 } else {
2254 0 my $output = `$item 2>&1`;
2255 0 ▶ $ok = ( $? == 0 ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$? == 0 ? : 0 0 0
2256 }
2257 0 ▶ return 0 if ( !$ok );
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
2258 } ## end foreach my $item (@rendered)
2259  
2260 0 my ( $ok, $output );
2261 0 ▶ if ( defined( $self->{options}{host} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{'options'}{'host'}) { } 0 0 0
2262 0 ( $ok, $output ) = $self->_run_rpc($listing);
2263 } else {
2264 0 $output = `$listing 2>&1`;
2265 0 ▶ $ok = ( $? == 0 ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$? == 0 ? : 0 0 0
2266 }
2267 0 ▶ return 0 if ( !$ok );
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
2268  
2269 0 foreach my $set (@sets) {
2270 # the set itself, then a rule matching against it
2271 0 ▶ return 0 if ( $output !~ /\bset\s+\Q$set\E\s*\{(.*?)\n\t\}/s );
Branch: 1 branch
BranchTrueFalseTotal
unless $output =~ /\bset\s+\Q$set\E\s*\{(.*?)\n\t\}/s 0 0 0
2272 0 my $body = $1;
2273 0 ▶ return 0 if ( $output !~ /\@\Q$set\E\b/ );
Branch: 1 branch
BranchTrueFalseTotal
unless $output =~ /\@\Q$set\E\b/ 0 0 0
2274  
2275 # a set that should hold bans but holds nothing was emptied out from
2276 # under us, which is what a firewall restart or a reboot does
2277 0 ▶ if ( $expected{$set} && $body !~ /\belements\s*=/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expected{$set} and not $body =~ /\belements\s*=/) 0 0 0
Condition0%0/3
$expected{$set} and not $body =~ /\belements\s*=/
!ll&&!rl&&r
000
MC/DC0%0/2
$expected{$set} and not $body =~ /\belements\s*=/
$expected{$set} not $body =~ /\belements\s*=/
Truth table0%0/3
A and not(B)
A= $expected{$set}B= not $body =~ /\belements\s*=/
ABresult
0X0
100
111
2278 0 return 0;
2279 }
2280 } ## end foreach my $set (@sets)
2281  
2282 0 return 1;
2283 } ## end sub check
2284  
2285 =head2 flush
2286  
2287 Removes all currently banned IPs and CIDR ranges at once by flushing both
2288 sets, leaving the UCI config and the rules in place. This is the equivalent
2289 of fail2ban's C<actionflush>.
2290  
2291 Nothing is committed, so the emptied list is not persisted until L</commit>
2292 is called.
2293  
2294 $backend->flush;
2295  
2296 =cut
2297  
2298 0 ▶sub flush {
Subroutine flush: not called CC=3 SCAR=24.8
Pod documented
2299 0 my ( $self, %opts ) = @_;
2300  
2301 0 $self->errorblank;
2302  
2303 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
2304 0 $self->{error} = 1;
2305 0 $self->{errorString} = 'backend has not been inited';
2306 0 $self->warn;
2307 0 return;
2308 }
2309  
2310 0 my ( $base, $set4, $set6 ) = $self->_names;
2311  
2312 0 my @ops = (
2313 [ 'exec', 'nft', 'flush', 'set', 'inet', 'fw4', $set4 ],
2314 [ 'exec', 'nft', 'flush', 'set', 'inet', 'fw4', $set6 ],
2315 );
2316  
2317 0 my ($rendered) = $self->_run( \@ops, error => 25, action => 'flush' );
2318  
2319 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
2320 0 $self->{frontend_obj}->{test_data} = $rendered;
2321 }
2322  
2323 0 $self->{banned} = {};
2324 0 $self->{banned_cidr} = {};
2325 } ## end sub flush
2326  
2327 =head1 ERROR CODES / FLAGS
2328  
2329 Error handling is provided by L<Error::Helper>. All
2330 errors are considered fatal.
2331  
2332 =head2 1, notInited
2333  
2334 The backend has not been inited yet.
2335  
2336 =head2 2, invalidPortSpecified
2337  
2338 Port is either not an int within the range 1 to 65535 or a name that can be resolved by getservbyname.
2339  
2340 =head2 3, portsNotArray
2341  
2342 The data passed to new for ports is not an array.
2343  
2344 =head2 4, protocolsNotArray
2345  
2346 The data passed to new for protocols is not an array.
2347  
2348 =head2 5, invalidPortSpecified
2349  
2350 Port is either not an int within the range 1 to 65535 or a name that can be resolved by getservbyname.
2351  
2352 =head2 6, invalidPrefixSpecified
2353  
2354 The specified prefix did not match /^[a-zA-Z0-9]+$/.
2355  
2356 =head2 7, invalidName
2357  
2358 The name is either undef or does not match /^[a-zA-Z0-9\-]+$/.
2359  
2360 =head2 8, optionsNotHash
2361  
2362 The item passed to new for options is not a hash.
2363  
2364 =head2 9, noBanItem
2365  
2366 No IP specified to ban or unban.
2367  
2368 =head2 10, banItemNotIP
2369  
2370 The item to ban is not an IP. Either wrong ref type or regexp
2371 test using L<Regexp::IPv4> and L<Regexp::IPv6> failed.
2372  
2373 =head2 12, backendInitError
2374  
2375 Failed to init the backend.
2376  
2377 =head2 13, banFailed
2378  
2379 Failed to ban the item.
2380  
2381 =head2 14, unbanFailed
2382  
2383 Failed to unban the item.
2384  
2385 =head2 15, listFailed
2386  
2387 Failed to get a list of bans.
2388  
2389 =head2 16, reInitFailed
2390  
2391 Failed to re_init the backend.
2392  
2393 =head2 17, teardownFailed
2394  
2395 Failed to teardown the backend.
2396  
2397 =head2 18, alreadyInited
2398  
2399 init called, but the backend has already been inited.
2400  
2401 =head2 20, typeInvalid
2402  
2403 The option type is not "drop" or "reject".
2404  
2405 =head2 21, nameTooLong
2406  
2407 The prefix and name joined by an underscore come to more than 250 characters,
2408 which does not leave room for the set and rule name suffixes within the
2409 nftables identifier limit.
2410  
2411 =head2 23, initFailed
2412  
2413 One of the required operations for init failed.
2414  
2415 =head2 24, checkFailed
2416  
2417 The backend check raised an error.
2418  
2419 =head2 25, flushFailed
2420  
2421 Failed to flush the bans.
2422  
2423 =head2 26, banCidrFailed
2424  
2425 Failed to ban the CIDR range.
2426  
2427 =head2 27, unbanCidrFailed
2428  
2429 Failed to unban the CIDR range.
2430  
2431 =head2 28, cidrItemNotCidr
2432  
2433 The item to ban is not a CIDR range. Either wrong ref type or it is not an
2434 IPv4 or IPv6 address followed by a prefix length valid for its family.
2435  
2436 =head2 29, cidrNotSupported
2437  
2438 The backend does not support CIDR bans. Unused here, as this backend does.
2439  
2440 =head2 30, listCidrFailed
2441  
2442 Failed to get a list of CIDR bans.
2443  
2444 =head2 31, commitFailed
2445  
2446 Failed to write the ban list out or to commit the staged UCI config.
2447  
2448 =head2 32, invalidHost
2449  
2450 The option host does not match /^[a-zA-Z0-9_.\-\[\]:]+$/.
2451  
2452 =head2 33, noPassword
2453  
2454 The option host is set, putting the backend in remote mode, but no password
2455 was given.
2456  
2457 =head2 34, invalidZone
2458  
2459 The option zone does not match /^[a-zA-Z0-9_*\-]+$/.
2460  
2461 =head2 35, invalidHttpPort
2462  
2463 The option http_port is not an int within the range 1 to 65535.
2464  
2465 =head2 36, invalidHttpProto
2466  
2467 The option http_proto is not "http" or "https".
2468  
2469 =head1 AUTHOR
2470  
2471 Zane C. Bowers-Hadley, C<< <vvelox at vvelox.ent> >>
2472  
2473 =head1 BUGS
2474  
2475 Please report any bugs or feature requests to C<bug-net-firewall-blockerhelper at rt.cpan.org>, or through
2476 the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Net-Firewall-BlockerHelper>.
2477  
2478 =head1 LICENSE AND COPYRIGHT
2479  
2480 This software is Copyright (c) 2026 by Zane C. Bowers-Hadley.
2481  
2482 This is free software, licensed under:
2483  
2484 The GNU Lesser General Public License, Version 2.1, February 1999
2485  
2486  
2487 =cut
2488  
2489 2 1; # End of Net::Firewall::BlockerHelper
« BlockerHelper/backends/ufw.pm ↑ Summary BlockerHelper/backends/firewalld.pm »