BlockerHelper/backends/iptables.pm

filter: Statementstmt 36.1% 150 / 415 Branchbran 27.2% 43 / 158 Conditioncond 37.0% 20 / 54 MC/DCmcdc 8.8% 3 / 34 Subroutinesub 57.6% 15 / 26 Podpod 100% 13 / 13 totaltotal 34.8% 244 / 700 CC 113 SCAR 47.1
CC
113
Cov
34%
new
230.1
ban
210.0
unban
132.0
CRAP 111.4
« BlockerHelper/backends/firewalld.pm ↑ Summary BlockerHelper/Util.pm »
1 package Net::Firewall::BlockerHelper::backends::iptables;
2  
3 3 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 3 ▶use base qw( Error::Helper Net::Firewall::BlockerHelper::Util );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 3 ▶use Regexp::IPv4 qw($IPv4_re);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 3 ▶use Regexp::IPv6 qw($IPv6_re);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 =head1 NAME
11  
12 Net::Firewall::BlockerHelper::backends::iptables - iptables/ip6tables backend for Net::Firewall::BlockerHelper.
13  
14 =head1 VERSION
15  
16 Version 0.2.0
17  
18 =cut
19  
20 3 our $VERSION = '0.2.0';
21  
22 =head1 SYNOPSIS
23  
24 Everything this backend needs is wired in by init itself, the jump from
25 C<INPUT> to its chain included, so no ruleset changes are needed
26 beforehand. The jump is appended to the end of C<INPUT> though, and
27 iptables is first match wins, so any earlier rule accepting the traffic in
28 question, such as a blanket ACCEPT for a port or an established/related
29 state rule, will win out over the bans. If bans appear to have no effect,
30 check where the jump to C<< <prefix>_<name> >> sits via
31 C<iptables -L INPUT> and relocate it above such rules; the backend finds
32 it by rule spec rather than position, so moving it is safe.
33  
34 use Net::Firewall::BlockerHelper::backends::iptables;
35  
36 my $backend1;
37 my $backend2;
38 eval {
39 $backend1 = Net::Firewall::BlockerHelper::backends::iptables->new(
40 name => 'all',
41 options=>{ kill=>1 },
42 );
43 $backend2 = Net::Firewall::BlockerHelper::backends::iptables->new(
44 ports => ['143'],
45 protocols => ['tcp'],
46 name => 'imap',
47 );
48 };
49 if ($@) {
50 print 'Error: '
51 . $Error::Helper::error
52 . "\nError String: "
53 . $Error::Helper::errorString
54 . "\nError Flag: "
55 . $Error::Helper::errorFlag . "\n";
56 }
57  
58 $backend1->init;
59 $backend2->init;
60  
61 $backend1->ban(ban=>'1.2.3.4');
62 $backend1->ban(ban=>'4.3.2.1');
63 $backend2->ban(ban=>'4.3.2.1');
64  
65 use Data::Dumper;
66 print Dumper($backend1->list);
67 print Dumper($backend2->list);
68  
69 $backend1->unban(ban=>'4.3.2.1');
70  
71 $backend1->teardown;
72 $backend2->teardown;
73  
74 =head1 DESCRIPTION
75  
76 This backend blocks IPs using L<ipset(8)> in combination with
77 L<iptables(8)> and L<ip6tables(8)>.
78  
79 For each instance two ipsets are created, one for IPv4
80 (C<< <prefix>_<name>_4 >>) and one for IPv6 (C<< <prefix>_<name>_6 >>),
81 along with a dedicated chain (C<< <prefix>_<name> >>) in each of the
82 C<filter> tables. The chain is populated with the block rules and jumped
83 to from C<INPUT>. Banning an IP is then simply a matter of adding it to
84 the relevant ipset.
85  
86 When the C<tarpit> or C<delude> type is used a same-named chain is also
87 created in the C<raw> table and jumped to from C<PREROUTING>, holding
88 C<< -j CT --notrack >> rules that match the same traffic. This exempts the
89 tarpitted/deluded connections from connection tracking, which those
90 xtables-addons targets require to work. It is created and removed
91 automatically with the filter chain.
92  
93 Requires C<ipset>, C<iptables>, and C<ip6tables> to be installed and in
94 the C<PATH> of the process, which must have sufficient privileges to run
95 them. The C<tarpit>/C<delude> types additionally require the C<TARPIT>/
96 C<DELUDE> targets from xtables-addons.
97  
98 =head1 METHODS
99  
100 =head2 new
101  
102 Initiates the the object.
103  
104 - options :: Backend specific options that will be passed to the backend unchecked
105 outside of making sure it is a hash ref if defined. See below for furhter info.
106 - Default :: {}
107  
108 - ports :: A array of ports to block. Checked to make sure they are positive ints or a valid
109 service name via getservbyname. All ports will be blocked if non are specified. If
110 duplicates are removed.
111 - Default :: []
112  
113 - protocols :: A array of protocols to block. By default will block all,
114 unless ports are given, in which case it defaults to tcp and udp. This
115 is checked against /etc/protocols via the function getprotobyname. Duplicates
116 will be discarded.
117 - Default :: [], or ['tcp','udp'] when ports are given
118  
119 - prefix :: Prefix to use. Must match the regex /^[a-zA-Z0-9]+$/
120 - default :: kur
121  
122 - name :: Name of this specific instance. This must be specified.
123 - default :: undef
124  
125 The options hash accepts the following.
126  
127 - type :: The block method to use. One of 'drop', 'reject', 'tarpit',
128 or 'delude'.
129 - drop :: Silently drop the packet. See iptables(8).
130 - reject :: Send an ICMP port-unreachable back. See iptables(8).
131 - tarpit :: Hold the TCP connection open with a zero window so
132 the attacker wastes resources. Requires the TARPIT
133 target from xtables-addons. TCP only.
134 - delude :: Answer a SYN with a SYN/ACK and everything else with
135 a RST, so the port looks open but never completes a
136 session. Requires the DELUDE target from xtables-addons.
137 TCP only. The target itself is also IPv4 only, as
138 xtables-addons provides no IPv6 version, so the IPv6
139 rule falls back to DROP; banned IPv6 IPs are still
140 blocked, just silently dropped rather than deluded.
141 The tarpit and delude types only ever emit '-p tcp' rules; any
142 non-tcp protocol or port default (eg the implicit udp) is skipped
143 rather than handed to a target the kernel would reject. For these
144 types the backend also installs a matching '-j CT --notrack' rule
145 in a raw table chain jumped from PREROUTING, so conntrack does not
146 process (and fight) the crafted replies; this is set up and torn
147 down automatically alongside the filter chain.
148 - Default :: drop
149  
150 - tarpit_mode :: When type is 'tarpit', selects the TARPIT mode, one of
151 'tarpit' (default, zero-window hold), 'honeypot' (accept then hold),
152 or 'reset'. Ignored for the other types.
153 - Default :: tarpit
154  
155 - kill :: Use conntrack(8) to drop existing connection tracking entries
156 for the banned IP, for both IPv4 and IPv6. When protocols are
157 configured the kill is scoped to them via -p, so blocking only
158 udp will not drop tcp entries and vice versa; protocols conntrack
159 can not filter by are skipped. With no protocols configured
160 everything is being blocked, so entries of every protocol are
161 dropped.
162 - Default :: 0
163  
164 All errors are considered fatal, meaning if new fails it will die.
165  
166 my $backend;
167 eval {
168 $backend = Net::Firewall::BlockerHelper::backends::iptables->new(
169 ports => ['22'],
170 protocols => ['tcp'],
171 name => 'ssh',
172 );
173 };
174 if ($@) {
175 print 'Error: '
176 . $Error::Helper::error
177 . "\nError String: "
178 . $Error::Helper::errorString
179 . "\nError Flag: "
180 . $Error::Helper::errorFlag . "\n";
181 }
182  
183 =cut
184  
185 4 ▶sub new {
Subroutine new: called CC=36 SCAR=54.4
Pod documented
186 4 my ( $blank, %opts ) = @_;
187  
188 4 my $self = {
189 perror => undef,
190 error => undef,
191 errorLine => undef,
192 errorFilename => undef,
193 errorString => "",
194 errorExtra => {
195 all_errors_fatal => 1,
196 # all_fatal is what Error::Helper 2.1.0 actually checks; all_errors_fatal
197 # is kept for the name documented in its POD
198 all_fatal => 1,
199 flags => {
200 1 => 'notInited',
201 2 => 'invalidPortSpecified',
202 3 => 'portsNotArray',
203 4 => 'protocolsNotArray',
204 5 => 'invalidPortSpecified',
205 6 => 'invalidPrefixSpecified',
206 7 => 'invalidName',
207 8 => 'optionsNotHash',
208 9 => 'noBanItem',
209 10 => 'banItemNotIP',
210 11 => 'invalidBackend',
211 12 => 'backendInitError',
212 13 => 'banFailed',
213 14 => 'unbanFailed',
214 15 => 'listFailed',
215 16 => 'reInitFailed',
216 17 => 'teardownFailed',
217 18 => 'alreadyInited',
218 20 => 'typeInvalid',
219 21 => 'nameTooLong',
220 23 => 'initFailed',
221 24 => 'checkFailed',
222 25 => 'flushFailed',
223 26 => 'banCidrFailed',
224 27 => 'unbanCidrFailed',
225 28 => 'cidrItemNotCidr',
226 29 => 'cidrNotSupported',
227 30 => 'listCidrFailed',
228 },
229 fatal_flags => {},
230 perror_not_fatal => 0,
231 },
232 options => {
233 type => 'drop',
234 kill => 0,
235 },
236 ports => [],
237 protocols => [],
238 testing => undef,
239 test_data => undef,
240 prefix => 'kur',
241 frontend_obj => undef,
242 inited => 0,
243 banned => {},
244 cidr_supported => 0,
245 };
246 4 bless $self;
247  
248 4 ▶ if ( defined( $opts{ports} ) && ref( $opts{ports} ) ne 'ARRAY' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opts{'ports'} and ref $opts{'ports'} ne 'ARRAY') { } 0 4 4
elsif (defined $opts{'ports'}) { } 2 2 4
Condition66%2/3
defined $opts{"ports"} and ref $opts{"ports"} ne "ARRAY"
!ll&&!rl&&r
220
MC/DC0%0/2
defined $opts{"ports"} and ref $opts{"ports"} ne "ARRAY"
defined $opts{"ports"} ref $opts{"ports"} ne "ARRAY"
Truth table66%2/3
A and B
A= defined $opts{"ports"}B= ref $opts{"ports"} ne "ARRAY"
ABresult
0X0
100
111
249 0 $self->{perror} = 1;
250 0 $self->{error} = 3;
251 0 $self->{errorString} = 'ports is defined and type is not array but "' . ref( $opts{ports} ) . '"';
252 0 $self->warn;
253 } elsif ( defined( $opts{ports} ) ) {
254 2 my %ports;
255 2 foreach my $item ( @{ $opts{ports} } ) {
256 1 ▶ if ( $item =~ /^[0-9]+$/ && $item >= 1 && $item <= 65535 ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($item =~ /^[0-9]+$/ and $item >= 1 and $item <= 65535) { } 1 0 1
elsif ($item =~ /^[0-9]+$/) { } 0 0 0
Condition33%2/6
$item =~ /^[0-9]+$/ and $item >= 1 and $item <= 65535
!ll&&!rl&&r
001
$item =~ /^[0-9]+$/ and $item >= 1
!ll&&!rl&&r
001
MC/DC0%0/3
$item =~ /^[0-9]+$/ and $item >= 1 and $item <= 65535
$item =~ /^[0-9]+$/ $item >= 1 $item <= 65535
Truth table25%1/4
A and B and C
A= $item =~ /^[0-9]+$/B= $item >= 1C= $item <= 65535
ABCresult
0XX0
10X0
1100
1111
257 1 $ports{$item} = 1;
258 } elsif ( $item =~ /^[0-9]+$/ ) {
259 0 $self->{perror} = 1;
260 0 $self->{error} = 2;
261 $self->{errorString}
262 0 = $item . ' is not a valid value for a port as it must be a int within the range 1 to 65535';
263 0 $self->warn;
264 } else {
265 # just using tcp here as protocol must be specified
266 0 my ( $name, $aliases, $port, $proto ) = getservbyname( $item, 'tcp' );
267 0 ▶ if ( !defined($port) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $port) 0 0 0
268 0 $self->{perror} = 1;
269 0 $self->{error} = 2;
270 $self->{errorString}
271 0 = $item . ' could not be resolved to a port name via getservbyname("' . $item . '", "tcp")';
272 0 $self->warn;
273 }
274 0 $ports{$port} = 1;
275 } ## end else [ if ( $item =~ /^[0-9]+$/ && $item >= 1 ) ]
276 } ## end foreach my $item ( @{ $opts{ports} } )
277 2 my @port_keys = keys(%ports);
278 0 @port_keys = sort { $a <=> $b } @port_keys;
279 2 push( @{ $self->{ports} }, @port_keys );
280 } ## end elsif ( defined( $opts{ports} ) )
281  
282 4 ▶ if ( defined( $opts{protocols} ) && ref( $opts{protocols} ) ne 'ARRAY' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opts{'protocols'} and ref $opts{'protocols'} ne 'ARRAY') { } 0 4 4
elsif (defined $opts{'protocols'}) { } 2 2 4
Condition66%2/3
defined $opts{"protocols"} and ref $opts{"protocols"} ne "ARRAY"
!ll&&!rl&&r
220
MC/DC0%0/2
defined $opts{"protocols"} and ref $opts{"protocols"} ne "ARRAY"
defined $opts{"protocols"} ref $opts{"protocols"} ne "ARRAY"
Truth table66%2/3
A and B
A= defined $opts{"protocols"}B= ref $opts{"protocols"} ne "ARRAY"
ABresult
0X0
100
111
283 0 $self->{perror} = 1;
284 0 $self->{error} = 4;
285 0 $self->{errorString} = 'protocols is defined and type is not array but "' . ref( $opts{protocols} ) . '"';
286 0 $self->warn;
287 } elsif ( defined( $opts{protocols} ) ) {
288 2 my %protocols;
289 2 foreach my $item ( @{ $opts{protocols} } ) {
290 0 my ( $name, $aliases, $proto ) = getprotobyname($item);
291 # if this is undef, it means it is not a known protocol
292 0 ▶ if ( !defined($proto) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $proto) 0 0 0
293 0 $self->{perror} = 1;
294 0 $self->{error} = 5;
295 $self->{errorString}
296 0 = $item . ' could not be resolved to a protocol via getprotobyname("' . $item . '")';
297 0 $self->warn;
298 }
299 0 $protocols{$item} = 1;
300 } ## end foreach my $item ( @{ $opts{protocols} } )
301 2 my @protocols_keys = keys(%protocols);
302 0 @protocols_keys = sort { $a cmp $b } @protocols_keys;
303 2 push( @{ $self->{protocols} }, @protocols_keys );
304 } ## end elsif ( defined( $opts{protocols} ) )
305  
306 # make sure prefix is sane if defiend
307 4 ▶ 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 4 4
elsif (defined $opts{'prefix'}) { } 4 0 4
Condition33%1/3
defined $opts{"prefix"} and not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
!ll&&!rl&&r
040
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
308 0 $self->{perror} = 1;
309 0 $self->{error} = 6;
310 $self->{errorString}
311 0 = '"' . $opts{prefix} . '" is not a valid prefix as it does not match the regex /^[a-zA-Z0-9]+$/';
312 0 $self->warn;
313 } elsif ( defined( $opts{prefix} ) ) {
314 4 $self->{prefix} = $opts{prefix};
315 }
316  
317 # make sure we have a name and that it is valid
318 4 ▶ if ( !defined( $opts{name} ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $opts{'name'}) { } 0 4 4
elsif (not $opts{'name'} =~ /^[a-zA-Z0-9\-]+$/) { } 0 4 4
319 0 $self->{perror} = 1;
320 0 $self->{error} = 7;
321 0 $self->{errorString} = 'name is undef';
322 0 $self->warn;
323 } elsif ( $opts{name} !~ /^[a-zA-Z0-9\-]+$/ ) {
324 0 $self->{perror} = 1;
325 0 $self->{error} = 7;
326 0 $self->{errorString} = 'name set to "' . $opts{name} . '" which does not match the regexp /^[a-zA-Z0-9\-]+$/';
327 0 $self->warn;
328 }
329 4 $self->{name} = $opts{name};
330  
331 # iptables limits chain names to 28 characters and ipset set names to 31;
332 # the chain is <prefix>_<name> and the sets are <prefix>_<name>_4/_6, so
333 # catch over-long combos here rather than as a confusing error at init
334 4 ▶ if ( defined( $self->{name} ) && length( $self->{prefix} . '_' . $self->{name} ) > 28 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"name"} and length $self->{"prefix"} . '_' . $self->{"name"} > 28) 1 3 4
Condition66%2/3
defined $self->{"name"} and length $self->{"prefix"} . '_' . $self->{"name"} > 28
!ll&&!rl&&r
031
MC/DC50%1/2
defined $self->{"name"} and length $self->{"prefix"} . '_' . $self->{"name"} > 28
defined $self->{"name"} length $self->{"prefix"} . '_' . $self->{"name"} > 28
Truth table66%2/3
A and B
A= defined $self->{"name"}B= length $self->{"prefix"} . '_' . $self->{"name"} > 28
ABresult
0X0
100
111
335 1 $self->{perror} = 1;
336 1 $self->{error} = 21;
337 $self->{errorString}
338 = 'the combined prefix and name, "'
339 . $self->{prefix} . '_'
340 . $self->{name}
341 1 . '", is longer than 28 characters, the max iptables chain name length';
342 1 $self->warn;
343 }
344  
345 # used internally for testing
346 3 ▶ if ( defined( $opts{testing} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"testing"}) 2 1 3
347 2 $self->{testing} = $opts{testing};
348 }
349 3 ▶ if ( defined( $opts{frontend_obj} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"frontend_obj"}) 2 1 3
350 2 $self->{frontend_obj} = $opts{frontend_obj};
351 }
352  
353 3 ▶ if ( defined( $opts{options} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"options"}) 2 1 3
354 2 ▶ if ( ref( $opts{options} ) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $opts{"options"} ne "HASH") 0 2 2
355 0 $self->{perror} = 1;
356 0 $self->{error} = 8;
357 0 $self->{errorString} = 'ref for options is "' . ref( $opts{options} ) . '" and not HASH';
358 0 $self->warn;
359 }
360 2 $self->{options} = $opts{options};
361  
362 2 ▶ if ( !defined( $opts{options}{kill} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $opts{"options"}{"kill"}) 2 0 2
363 2 $self->{options}{kill} = 0;
364 }
365  
366 # tarpit and delude are xtables-addons targets, hence not lumped in
367 # with the base drop/reject that plain iptables always provides
368 2 my %valid_types = ( drop => 1, reject => 1, tarpit => 1, delude => 1 );
369  
370 2 ▶ if ( defined( $opts{options}{type} ) && ref( $opts{options}{type} ) ne '' ) {
Branch: 3 branches
BranchTrueFalseTotal
if (defined $opts{'options'}{'type'} and ref $opts{'options'}{'type'} ne '') { } 0 2 2
elsif (defined $opts{'options'}{'type'} and not $valid_types{$opts{'options'}{'type'}}) { } 0 2 2
elsif (not defined $opts{'options'}{'type'}) { } 0 2 2
Condition33%1/3
defined $opts{"options"}{"type"} and ref $opts{"options"}{"type"} ne ""
!ll&&!rl&&r
020
MC/DC0%0/2
defined $opts{"options"}{"type"} and ref $opts{"options"}{"type"} ne ""
defined $opts{"options"}{"type"} ref $opts{"options"}{"type"} ne ""
Truth table33%1/3
A and B
A= defined $opts{"options"}{"type"}B= ref $opts{"options"}{"type"} ne ""
ABresult
0X0
100
111
371 0 $self->{perror} = 1;
372 0 $self->{error} = 20;
373 0 $self->{errorString} = 'ref for $opts{options}{type} is "' . ref( $opts{options}{type} ) . '" and not ""';
374 0 $self->warn;
375 ▶ } elsif ( defined( $opts{options}{type} )
Condition33%1/3
defined $opts{"options"}{"type"} and not $valid_types{$opts{"options"}{"type"}}
!ll&&!rl&&r
020
MC/DC0%0/2
defined $opts{"options"}{"type"} and not $valid_types{$opts{"options"}{"type"}}
defined $opts{"options"}{"type"} not $valid_types{$opts{"options"}{"type"}}
Truth table33%1/3
A and not(B)
A= defined $opts{"options"}{"type"}B= not $valid_types{$opts{"options"}{"type"}}
ABresult
0X0
100
111
376 && !$valid_types{ $opts{options}{type} } )
377 {
378 0 $self->{perror} = 1;
379 0 $self->{error} = 20;
380 $self->{errorString}
381 = '$opts{options}{type} is "'
382 . $opts{options}{type}
383 0 . '" and not one of "drop", "reject", "tarpit", or "delude"';
384 0 $self->warn;
385 } elsif ( !defined( $opts{options}{type} ) ) {
386 0 $self->{options}{type} = 'drop';
387 }
388  
389 # tarpit has three modes; delude and the plain targets take none. Only
390 # validate it here, _rule_commands decides when it is actually emitted.
391 2 my %valid_tarpit_modes = ( tarpit => 1, honeypot => 1, reset => 1 );
392 2 ▶ if ( defined( $opts{options}{tarpit_mode} )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"options"}{"tarpit_mode"} and ref $opts{"options"}{"tarpit_mode"} ne "" || !$valid_tarpit_modes{$opts{"options"}{"tarpit_mode"}}) 0 2 2
Condition50%3/6
defined $opts{"options"}{"tarpit_mode"} and ref $opts{"options"}{"tarpit_mode"} ne "" || !$valid_tarpit_modes{$opts{"options"}{"tarpit_mode"}}
!ll&&!rl&&r
110
ref $opts{"options"}{"tarpit_mode"} ne "" or not $valid_tarpit_modes{$opts{"options"}{"tarpit_mode"}}
l!l&&r!l&&!r
001
MC/DC0%0/3
defined $opts{"options"}{"tarpit_mode"} and ref $opts{"options"}{"tarpit_mode"} ne "" || !$valid_tarpit_modes{$opts{"options"}{"tarpit_mode"}}
defined $opts{"options"}{"tarpit_mode"} ref $opts{"options"}{"tarpit_mode"} ne "" not $valid_tarpit_modes{$opts{"options"}{"tarpit_mode"}}
Truth table50%2/4
A and B or not(C)
A= defined $opts{"options"}{"tarpit_mode"}B= ref $opts{"options"}{"tarpit_mode"} ne ""C= not $valid_tarpit_modes{$opts{"options"}{"tarpit_mode"}}
ABCresult
0XX0
1000
11X1
1011
393 && ( ref( $opts{options}{tarpit_mode} ) ne ''
394 || !$valid_tarpit_modes{ $opts{options}{tarpit_mode} } ) )
395 {
396 0 $self->{perror} = 1;
397 0 $self->{error} = 20;
398 $self->{errorString}
399 = '$opts{options}{tarpit_mode} is "'
400 . ( ref( $opts{options}{tarpit_mode} ) ne '' ? ref( $opts{options}{tarpit_mode} ) : $opts{options}{tarpit_mode} )
401 0 ▶ . '" and not one of "tarpit", "honeypot", or "reset"';
Branch: 1 branch
BranchTrueFalseTotal
ref $opts{'options'}{'tarpit_mode'} ne '' ? : 0 0 0
402 0 $self->warn;
403 }
404  
405 } ## end if ( defined( $opts{options} ) )
406  
407 3 return $self;
408 } ## end sub new
409  
410 # Internal helper. Returns the three kernel object names this instance owns:
411 # its IPv4 ipset, its IPv6 ipset, and its chain.
412 #
413 # All three are derived from the prefix and the name rather than stored, so
414 # every part of the backend agrees on what to create, match against, and tear
415 # down without threading the names around. The prefix and name pair is unique
416 # per instance, so two instances can share a host without colliding.
417 #
418 # There are two ipsets because an ipset is single family: a hash:ip set is
419 # created either family inet or family inet6 and will not hold addresses of
420 # the other. The chain name has no suffix and is reused across tables, which
421 # is safe because iptables chain names are scoped per table, so the filter
422 # chain and the raw chain created for tarpit and delude do not collide.
423 #
424 # Note the length of these names is checked at new against the kernel's
425 # limits, so nothing here has to worry about truncation.
426 #
427 # Takes no arguments.
428 #
429 # Returns a three element list of the IPv4 set name, the IPv6 set name, and
430 # the chain name, in that order. Callers that only want the chain conventially
431 # discard the first two with undef.
432 #
433 # my ( $set4, $set6, $chain ) = $self->_set_names;
434 #
435 # # with prefix "kur" and name "ssh"
436 # # $set4 is 'kur_ssh_4'
437 # # $set6 is 'kur_ssh_6'
438 # # $chain is 'kur_ssh'
439 #
440 # # when only the chain is wanted
441 # my ( undef, undef, $chain ) = $self->_set_names;
442 14 ▶sub _set_names {
Subroutine _set_names: called CC=1 SCAR=0.0
443 14 my ($self) = @_;
444  
445 14 my $chain = $self->{prefix} . '_' . $self->{name};
446 14 return ( $chain . '_4', $chain . '_6', $chain );
447 }
448  
449 # Internal helper. Says whether the configured ban type is one of the
450 # xtables-addons reply crafting targets, which is what decides both whether
451 # the raw table machinery is set up at all and whether rules are restricted to
452 # TCP.
453 #
454 # The two are the same question because only tarpit and delude craft replies,
455 # and crafting replies is both what makes conntrack a problem, see
456 # _notrack_commands, and what limits them to TCP, since neither target has
457 # anything to say about UDP or ICMP.
458 #
459 # Takes no arguments; the type comes from the options.
460 #
461 # Returns 1 when the type is 'tarpit' or 'delude', 0 otherwise, which in
462 # practice means 0 for the plain 'drop' and 'reject' types. Always one of
463 # those two values, never undef.
464 #
465 # # type 'tarpit' or 'delude'
466 # $self->_needs_notrack; # 1
467 #
468 # # type 'drop' or 'reject'
469 # $self->_needs_notrack; # 0
470 #
471 # # the usual guard shape, on helpers that are a no-op for plain types
472 # return () if ( !$self->_needs_notrack );
473 10 ▶sub _needs_notrack {
Subroutine _needs_notrack: called CC=3 SCAR=12.5
474 10 my ($self) = @_;
475  
476 10 my $type = $self->{options}{type};
477 10 ▶ return ( $type eq 'tarpit' || $type eq 'delude' ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$type eq 'tarpit' || $type eq 'delude' ? : 10 0 10
Condition33%1/3
$type eq "tarpit" or $type eq "delude"
l!l&&r!l&&!r
1000
MC/DC0%0/2
$type eq "tarpit" or $type eq "delude"
$type eq "tarpit" $type eq "delude"
Truth table33%1/3
A or B
A= $type eq "tarpit"B= $type eq "delude"
ABresult
1X1
011
000
478 }
479  
480 # Internal helper. Works out the full cross product of family, protocol, and
481 # ports that this instance needs to block, and returns it as a list of specs.
482 # This is where essentially all of the backend's rule logic lives; the command
483 # building helpers downstream are near mechanical.
484 #
485 # It exists as a separate step because two different sets of rules have to
486 # match exactly the same traffic: the filter table block rules from
487 # _rule_commands and the raw table conntrack exemptions from
488 # _notrack_commands. Generating both from one spec list is what guarantees
489 # they cannot drift apart, which would leave tarpitted traffic partly tracked
490 # and the trick half broken.
491 #
492 # The target is chosen per family, not just per type, because the families do
493 # not offer the same targets. reject needs a different ICMP type for each.
494 # delude has no IPv6 implementation in xtables-addons at all, so IPv6 falls
495 # back to a plain DROP; banned IPv6 addresses are still blocked, they are just
496 # not deluded. tarpit honors the tarpit_mode option, leaving the default mode
497 # implicit rather than spelling it out so that older xtables-addons builds
498 # that predate the flag still accept the rule.
499 #
500 # Three filters are applied while walking the protocols. Protocols belonging
501 # to the wrong family are skipped, so icmp never lands in an ip6tables rule
502 # and the various spellings of IPv6 ICMP never land in an iptables one.
503 # Protocols other than TCP are skipped entirely when the type is tarpit or
504 # delude, rather than being emitted with a target the kernel would reject.
505 # Ports are only attached to protocols that actually have them, so a port list
506 # alongside gre does not produce a nonsense rule.
507 #
508 # Takes no arguments; family, protocols, ports, and type all come from the
509 # object.
510 #
511 # Returns a list of hashrefs, one per rule to be created, each of the form:
512 #
513 # {
514 # fam => {
515 # cmd => 'iptables', # or 'ip6tables'
516 # set => 'kur_ssh_4', # the ipset for this family
517 # tgt => 'DROP', # the -j target, family specific
518 # family => 4, # 4 or 6
519 # },
520 # match => ' -p tcp -m multiport --dports 22',
521 # }
522 #
523 # The match is the middle portion of the rule, everything between the source
524 # set match and the -j, already carrying its own leading space so it can be
525 # concatenated directly. It is the empty string for a match everything rule.
526 # The list is empty only if every protocol was filtered out.
527 #
528 # # no protocols and no ports, type drop: block everything from the set
529 # my @specs = $self->_rule_specs;
530 # # two specs, one per family, both with match => ''
531 #
532 # # ports 22 with no protocols: defaults to tcp and udp per family
533 # # four specs, match => ' -p tcp -m multiport --dports 22'
534 # # and ' -p udp -m multiport --dports 22'
535 #
536 # # ports 22, no protocols, type tarpit: udp is dropped from the default
537 # # two specs, both ' -p tcp -m multiport --dports 22'
538 #
539 # # protocols tcp and icmp, no ports
540 # # three specs: iptables ' -p tcp', iptables ' -p icmp',
541 # # and ip6tables ' -p tcp' -- icmp is skipped for v6
542 4 ▶sub _rule_specs {
Subroutine _rule_specs: called CC=22 SCAR=44.1
543 4 my ($self) = @_;
544  
545 4 my ( $set4, $set6 ) = $self->_set_names;
546  
547 4 my @ports = @{ $self->{ports} };
548 4 my @protos = @{ $self->{protocols} };
549 4 my $port_str = join( ',', @ports );
550  
551 4 my $type = $self->{options}{type};
552  
553 # work out the target for each family
554 4 my $t4 = 'DROP';
555 4 my $t6 = 'DROP';
556 4 ▶ if ( $type eq 'reject' ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($type eq 'reject') { } 0 4 4
elsif ($type eq 'tarpit') { } 4 0 4
elsif ($type eq 'delude') { } 0 0 0
557 0 $t4 = 'REJECT --reject-with icmp-port-unreachable';
558 0 $t6 = 'REJECT --reject-with icmp6-port-unreachable';
559 } elsif ( $type eq 'tarpit' ) {
560 # xtables-addons TARPIT; --honeypot/--reset select the alternate modes,
561 # the default --tarpit is left implicit so older builds still accept it
562 4 my $mode = $self->{options}{tarpit_mode};
563 4 ▶ $t4 = ( defined($mode) && $mode ne 'tarpit' ) ? 'TARPIT --' . $mode : 'TARPIT';
Branch: 1 branch
BranchTrueFalseTotal
defined $mode && $mode ne 'tarpit' ? : 2 2 4
Condition66%2/3
defined $mode and $mode ne "tarpit"
!ll&&!rl&&r
202
MC/DC50%1/2
defined $mode and $mode ne "tarpit"
defined $mode $mode ne "tarpit"
Truth table66%2/3
A and B
A= defined $modeB= $mode ne "tarpit"
ABresult
0X0
100
111
564 4 $t6 = $t4;
565 } elsif ( $type eq 'delude' ) {
566 0 $t4 = 'DELUDE';
567 # xtables-addons provides no IPv6 DELUDE, so v6 falls back to DROP;
568 # banned IPv6 IPs are still blocked, just not deluded
569 0 $t6 = 'DROP';
570 }
571  
572 # TARPIT and DELUDE only handle TCP, so their rules are forced to -p tcp
573 # and any non-tcp protocol/port combination is skipped rather than emitted
574 # with a target the kernel would reject.
575 4 my $tcp_only = $self->_needs_notrack;
576  
577 4 my @families = (
578 { cmd => 'iptables', set => $set4, tgt => $t4, family => 4 },
579 { cmd => 'ip6tables', set => $set6, tgt => $t6, family => 6 },
580 );
581  
582 # protocols that accept a port specification
583 4 my %port_ok = ( tcp => 1, udp => 1, sctp => 1 );
584  
585 # the various names the IPv6 ICMP protocol may go by
586 4 my %v6_icmp = ( 'ipv6-icmp' => 1, 'icmp6' => 1, 'icmpv6' => 1 );
587  
588 4 my @specs;
589 4 foreach my $fam (@families) {
590 8 ▶ if ( !@protos && !@ports ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not @protos || @ports) { } 4 4 8
elsif (not @protos and @ports) { } 4 0 4
Condition66%2/3
@protos || @ports
l!l&&r!l&&!r
044
MC/DC50%1/2
@protos || @ports
@protos @ports
Truth table66%2/3
A || B
A= @protosB= @ports
ABresult
1X1
011
000
591 4 ▶ if ($tcp_only) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tcp_only) { } 4 0 4
592 # tarpit/delude have no all-protocol form; scope to tcp
593 4 push( @specs, { fam => $fam, match => ' -p tcp' } );
594 } else {
595 # block everything sourced from the set
596 0 push( @specs, { fam => $fam, match => '' } );
597 }
598 ▶ } elsif ( !@protos && @ports ) {
Condition33%1/3
not @protos and @ports
!ll&&!rl&&r
004
MC/DC0%0/2
not @protos and @ports
not @protos @ports
Truth table33%1/3
not(A) and B
A= not @protosB= @ports
ABresult
0X0
100
111
599 # ports require a protocol, default to tcp and udp, but tarpit/delude
600 # are tcp only so udp is dropped from that default
601 4 ▶ my @default_protos = $tcp_only ? ('tcp') : ( 'tcp', 'udp' );
Branch: 1 branch
BranchTrueFalseTotal
$tcp_only ? : 4 0 4
602 4 foreach my $proto (@default_protos) {
603 4 push( @specs, { fam => $fam, match => ' -p ' . $proto . ' -m multiport --dports ' . $port_str } );
604 }
605 } else {
606 0 foreach my $proto (@protos) {
607 # skip protocols that do not belong to this family
608 0 ▶ if ( $fam->{family} == 6 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fam->{'family'} == 6) { } 0 0 0
609 0 ▶ next if ( $proto eq 'icmp' );
Branch: 1 branch
BranchTrueFalseTotal
if $proto eq "icmp" 0 0 0
610 } else {
611 0 ▶ next if ( $v6_icmp{$proto} );
Branch: 1 branch
BranchTrueFalseTotal
if $v6_icmp{$proto} 0 0 0
612 }
613  
614 # tarpit/delude can only target tcp, so leave the rest untouched
615 0 ▶ next if ( $tcp_only && $proto ne 'tcp' );
Branch: 1 branch
BranchTrueFalseTotal
if $tcp_only and $proto ne "tcp" 0 0 0
Condition0%0/3
$tcp_only and $proto ne "tcp"
!ll&&!rl&&r
000
MC/DC0%0/2
$tcp_only and $proto ne "tcp"
$tcp_only $proto ne "tcp"
Truth table0%0/3
A and B
A= $tcp_onlyB= $proto ne "tcp"
ABresult
0X0
100
111
616  
617 0 my $match = ' -p ' . $proto;
618 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
619 0 $match .= ' -m multiport --dports ' . $port_str;
620 }
621 0 push( @specs, { fam => $fam, match => $match } );
622 } ## end foreach my $proto (@protos)
623 } ## end else [ if ( !@protos && !@ports ) ]
624 } ## end foreach my $fam (@families)
625  
626 4 return @specs;
627 } ## end sub _rule_specs
628  
629 # Internal helper. Turns the specs from _rule_specs into the actual filter
630 # table commands that fill this instance's chain with its block rules. Run by
631 # init and re_init after the chain has been created.
632 #
633 # Each rule matches its family's ipset as the source and applies that family's
634 # target, so the rules are static: banning and unbanning an address only adds
635 # or removes it from the set and never touches the rules themselves. That is
636 # the whole reason the backend is built on ipset rather than one rule per
637 # address.
638 #
639 # Note the rules are appended with -A, so they land in the order the specs
640 # come back in, and the chain is expected to be empty when this runs.
641 #
642 # Takes no arguments.
643 #
644 # Returns the commands as a list of strings, one per rule, ready to hand to
645 # the runner. The list has one entry per spec, so its length depends on how
646 # many family, protocol, and port combinations apply. Never empty in practice,
647 # since a configuration with no applicable rules would have been rejected
648 # earlier.
649 #
650 # # type drop, no protocols or ports, chain kur_ssh
651 # my @commands = $self->_rule_commands;
652 # # iptables -A kur_ssh -m set --match-set kur_ssh_4 src -j DROP
653 # # ip6tables -A kur_ssh -m set --match-set kur_ssh_6 src -j DROP
654 #
655 # # type reject, protocols tcp, ports 22
656 # # iptables -A kur_ssh -m set --match-set kur_ssh_4 src -p tcp -m multiport --dports 22 -j REJECT --reject-with icmp-port-unreachable
657 # # ip6tables -A kur_ssh -m set --match-set kur_ssh_6 src -p tcp -m multiport --dports 22 -j REJECT --reject-with icmp6-port-unreachable
658 2 ▶sub _rule_commands {
Subroutine _rule_commands: called CC=2 SCAR=6.9
659 2 my ($self) = @_;
660  
661 2 my ( undef, undef, $chain ) = $self->_set_names;
662  
663 2 my @commands;
664 2 foreach my $spec ( $self->_rule_specs ) {
665 4 my $fam = $spec->{fam};
666 push( @commands,
667 $fam->{cmd}
668 . ' -A '
669 . $chain
670 . ' -m set --match-set '
671 . $fam->{set} . ' src'
672 . $spec->{match} . ' -j '
673 4 . $fam->{tgt} );
674 }
675  
676 2 return @commands;
677 } ## end sub _rule_commands
678  
679 # Internal helper. Returns the raw table rules that exempt tarpitted or
680 # deluded traffic from connection tracking.
681 #
682 # TARPIT and DELUDE craft their own TCP replies, a zero window ACK stream and
683 # a SYN/ACK-then-RST respectively, with no local socket behind them. If
684 # conntrack tracks that traffic the kernel's own stack processes it as well,
685 # which both undoes the trick and pins an INVALID conntrack entry for every
686 # attacker packet, so a busy tarpit fills the conntrack table. Matching the
687 # same traffic in raw/PREROUTING with -j CT --notrack keeps conntrack out of
688 # the way entirely.
689 #
690 # The match has to be exactly the same source set, protocol, and ports as the
691 # block rule, which is why these are generated from the same _rule_specs the
692 # filter rules are. A narrower notrack rule would leave some tarpitted traffic
693 # tracked; a wider one would exempt traffic that is not being tarpitted at
694 # all.
695 #
696 # Specs whose target is not a reply crafting one are skipped. In practice that
697 # is delude's IPv6 fallback, which is a plain DROP: dropped traffic never gets
698 # a reply, so there is nothing for conntrack to interfere with and no reason
699 # to exempt it.
700 #
701 # Takes no arguments.
702 #
703 # Returns the commands as a list of strings, one per exempted spec, ready to
704 # hand to the runner. Returns an empty list for the plain drop and reject
705 # types, which need none of this, so callers can splice the result in
706 # unconditionally.
707 #
708 # # type tarpit, ports 22, chain kur_ssh
709 # my @commands = $self->_notrack_commands;
710 # # iptables -t raw -A kur_ssh -m set --match-set kur_ssh_4 src -p tcp -m multiport --dports 22 -j CT --notrack
711 # # ip6tables -t raw -A kur_ssh -m set --match-set kur_ssh_6 src -p tcp -m multiport --dports 22 -j CT --notrack
712 #
713 # # type delude: only the v4 rule, as v6 falls back to DROP
714 # # iptables -t raw -A kur_ssh -m set --match-set kur_ssh_4 src -p tcp -j CT --notrack
715 #
716 # # type drop or reject
717 # my @commands = $self->_notrack_commands; # ()
718 #
719 # These populate a chain in the raw table that shares the filter chain's name.
720 # That is safe because iptables chain names are scoped per table.
721 2 ▶sub _notrack_commands {
Subroutine _notrack_commands: called CC=4 SCAR=14.0
722 2 my ($self) = @_;
723  
724 2 ▶ return () if ( !$self->_needs_notrack );
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_needs_notrack 0 2 2
725  
726 2 my ( undef, undef, $chain ) = $self->_set_names;
727  
728 2 my @commands;
729 2 foreach my $spec ( $self->_rule_specs ) {
730 4 my $fam = $spec->{fam};
731  
732 # only the traffic actually handled by a reply-crafting target needs
733 # exempting from conntrack; the v6 DROP fallback delude uses does not
734 4 ▶ next if ( $fam->{tgt} !~ /^(TARPIT|DELUDE)/ );
Branch: 1 branch
BranchTrueFalseTotal
unless $fam->{"tgt"} =~ /^(TARPIT|DELUDE)/ 0 4 4
735  
736 push( @commands,
737 $fam->{cmd}
738 . ' -t raw -A '
739 . $chain
740 . ' -m set --match-set '
741 . $fam->{set} . ' src'
742 . $spec->{match}
743 4 . ' -j CT --notrack' );
744 }
745  
746 2 return @commands;
747 } ## end sub _notrack_commands
748  
749 # Internal helper. Returns the complete set of commands that stand up the raw
750 # table side of a tarpit or delude instance: create the chain for both
751 # families, fill it with the conntrack exemptions, and hook it into
752 # PREROUTING.
753 #
754 # The order matters and is why this is one helper rather than three. The chain
755 # has to exist before rules can be added to it, and the jump from PREROUTING
756 # is added last so the chain is never reachable while still half filled.
757 #
758 # The jump is appended to PREROUTING with -A rather than inserted at the top.
759 #
760 # Takes no arguments.
761 #
762 # Returns the commands as a list of strings in the order they must be run,
763 # ready to hand to the runner. Returns an empty list for the plain drop and
764 # reject types, which have no raw table component at all, so init can splice
765 # the result in unconditionally.
766 #
767 # # type tarpit, no ports, chain kur_ssh
768 # my @commands = $self->_raw_setup_commands;
769 # # iptables -t raw -N kur_ssh
770 # # ip6tables -t raw -N kur_ssh
771 # # iptables -t raw -A kur_ssh -m set --match-set kur_ssh_4 src -p tcp -j CT --notrack
772 # # ip6tables -t raw -A kur_ssh -m set --match-set kur_ssh_6 src -p tcp -j CT --notrack
773 # # iptables -t raw -A PREROUTING -j kur_ssh
774 # # ip6tables -t raw -A PREROUTING -j kur_ssh
775 #
776 # # type drop
777 # my @commands = $self->_raw_setup_commands; # ()
778 #
779 # Note the chain is created for both families unconditionally, even for delude
780 # where the IPv6 chain ends up empty because the v6 fallback is a plain DROP.
781 # That keeps the teardown symmetric, since it can then remove both without
782 # having to know which were populated.
783 2 ▶sub _raw_setup_commands {
Subroutine _raw_setup_commands: called CC=2 SCAR=7.0
784 2 my ($self) = @_;
785  
786 2 ▶ return () if ( !$self->_needs_notrack );
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_needs_notrack 0 2 2
787  
788 2 my ( undef, undef, $chain ) = $self->_set_names;
789  
790 return (
791 2 'iptables -t raw -N ' . $chain,
792 'ip6tables -t raw -N ' . $chain,
793 $self->_notrack_commands,
794 'iptables -t raw -A PREROUTING -j ' . $chain,
795 'ip6tables -t raw -A PREROUTING -j ' . $chain,
796 );
797 } ## end sub _raw_setup_commands
798  
799 # Internal helper. Returns the commands that dismantle the raw table side of a
800 # tarpit or delude instance, the exact inverse of _raw_setup_commands.
801 #
802 # The order is the reverse of setup and is the reason this is one helper. The
803 # jump from PREROUTING goes first so nothing can reach the chain while it is
804 # being emptied, then the chain is flushed, then deleted. iptables refuses to
805 # delete a chain that is still referenced or still holds rules, so skipping
806 # either of the first two steps makes the last one fail.
807 #
808 # Takes no arguments.
809 #
810 # Returns the commands as a list of strings in the order they must be run,
811 # ready to hand to the runner. Returns an empty list for the plain drop and
812 # reject types, so teardown can splice the result in unconditionally.
813 #
814 # Callers run these best effort and let them fail, since a partially set up or
815 # already removed instance is the normal case during cleanup.
816 #
817 # # type tarpit, chain kur_ssh
818 # my @commands = $self->_raw_teardown_commands;
819 # # iptables -t raw -D PREROUTING -j kur_ssh
820 # # ip6tables -t raw -D PREROUTING -j kur_ssh
821 # # iptables -t raw -F kur_ssh
822 # # ip6tables -t raw -F kur_ssh
823 # # iptables -t raw -X kur_ssh
824 # # ip6tables -t raw -X kur_ssh
825 #
826 # # type drop
827 # my @commands = $self->_raw_teardown_commands; # ()
828 2 ▶sub _raw_teardown_commands {
Subroutine _raw_teardown_commands: called CC=2 SCAR=7.0
829 2 my ($self) = @_;
830  
831 2 ▶ return () if ( !$self->_needs_notrack );
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_needs_notrack 0 2 2
832  
833 2 my ( undef, undef, $chain ) = $self->_set_names;
834  
835 return (
836 2 'iptables -t raw -D PREROUTING -j ' . $chain,
837 'ip6tables -t raw -D PREROUTING -j ' . $chain,
838 'iptables -t raw -F ' . $chain,
839 'ip6tables -t raw -F ' . $chain,
840 'iptables -t raw -X ' . $chain,
841 'ip6tables -t raw -X ' . $chain,
842 );
843 } ## end sub _raw_teardown_commands
844  
845 =head2 init
846  
847 Initiates the backend. Creates the two ipsets, C<< <prefix>_<name>_4 >>
848 (hash:ip family inet) and C<< <prefix>_<name>_6 >> (hash:ip family inet6),
849 creates the C<< <prefix>_<name> >> chain via C<iptables -N> and
850 C<ip6tables -N>, populates it with the block rules built from the configured
851 type, protocols, and ports, and appends a jump to it from C<INPUT>. For the
852 tarpit and delude types a same-named chain holding the C<-j CT --notrack>
853 rules is also created in the C<raw> table and jumped to from C<PREROUTING>.
854  
855 Note that the jump is appended to the end of C<INPUT>, so earlier rules
856 accepting the traffic win out over the bans. See L</SYNOPSIS>.
857  
858 Before any of that, matching stale chains and ipsets from a previous run are
859 removed; those cleanup commands are allowed to fail.
860  
861 No arguments are taken.
862  
863 If called a second time without an intervening teardown, it will error.
864  
865 $backend->init;
866  
867 =cut
868  
869 2 ▶sub init {
Subroutine init: called CC=8 SCAR=23.4
Pod documented
870 2 my ( $self, %opts ) = @_;
871  
872 2 $self->errorblank;
873  
874 2 ▶ if ( $self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"inited"}) 0 2 2
875 0 $self->{error} = 18;
876 0 $self->{errorString} = 'backend has already been inited';
877 0 $self->warn;
878 }
879  
880 2 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 2 0 2
881 2 $self->{frontend_obj}->{test_data} = {};
882 }
883  
884 2 my ( $set4, $set6, $chain ) = $self->_set_names;
885  
886 # these are cleanup commands for any stale state and are allowed to fail
887 2 my @fail_okay_commands;
888 2 push( @fail_okay_commands, 'iptables -D INPUT -j ' . $chain );
889 2 push( @fail_okay_commands, 'ip6tables -D INPUT -j ' . $chain );
890 2 push( @fail_okay_commands, 'iptables -F ' . $chain );
891 2 push( @fail_okay_commands, 'ip6tables -F ' . $chain );
892 2 push( @fail_okay_commands, 'iptables -X ' . $chain );
893 2 push( @fail_okay_commands, 'ip6tables -X ' . $chain );
894  
895 # the stale raw table notrack chain (tarpit/delude only; empty otherwise)
896 # has to go before the ipset destroys, as its rules reference the sets
897 # and a referenced set can not be destroyed
898 2 push( @fail_okay_commands, $self->_raw_teardown_commands );
899  
900 2 push( @fail_okay_commands, 'ipset destroy ' . $set4 );
901 2 push( @fail_okay_commands, 'ipset destroy ' . $set6 );
902  
903 2 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 2 0 2
904 2 $self->{frontend_obj}->{test_data}{fail_okay_commands} = \@fail_okay_commands;
905 } else {
906 0 foreach my $item (@fail_okay_commands) {
907 0 my $output = `$item 2>&1`;
908 }
909 }
910  
911 2 my @commands;
912 # create the ipsets and the chain
913 2 push( @commands, 'ipset create ' . $set4 . ' hash:ip family inet' );
914 2 push( @commands, 'ipset create ' . $set6 . ' hash:ip family inet6' );
915 2 push( @commands, 'iptables -N ' . $chain );
916 2 push( @commands, 'ip6tables -N ' . $chain );
917  
918 # add the block rules to the chain
919 2 push( @commands, $self->_rule_commands );
920  
921 # jump to the chain from INPUT
922 2 push( @commands, 'iptables -A INPUT -j ' . $chain );
923 2 push( @commands, 'ip6tables -A INPUT -j ' . $chain );
924  
925 # for tarpit/delude, exempt the matching traffic from conntrack via a raw
926 # table chain; empty for the plain drop/reject types
927 2 push( @commands, $self->_raw_setup_commands );
928  
929 2 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 2 0 2
930 2 $self->{frontend_obj}->{test_data}{commands} = \@commands;
931 } else {
932 0 foreach my $item (@commands) {
933 0 my $output = `$item 2>&1`;
934 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
935 0 $self->{error} = 23;
936 $self->{errorString}
937 0 = 'init failed. non-zero exit code for the command... "' . $item . '"... output... ' . $output;
938 0 $self->warn;
939 }
940 }
941 } ## end else [ if ( $self->{testing} ) ]
942  
943 2 $self->{inited} = 1;
944 } ## end sub init
945  
946 =head2 ban
947  
948 Bans an IP. The value of ban is validated as being a IPv4 or IPv6 address
949 and lowercased, then added to the instance's IPv4 or IPv6 ipset, as
950 appropriate for its family, via C<ipset add>. Banning an already banned IP
951 is a noop.
952  
953 If the C<kill> option is set, L<conntrack(8)> is then used to drop existing
954 connection tracking entries for the IP; its exit code is ignored, as it is
955 non-zero when there is nothing to delete.
956  
957 $backend->ban(ban => $ip);
958  
959 =cut
960  
961 0 ▶sub ban {
Subroutine ban: not called CC=14 SCAR=53.5
Pod documented
962 0 my ( $self, %opts ) = @_;
963  
964 0 $self->errorblank;
965  
966 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
967 0 $self->{error} = 1;
968 0 $self->{errorString} = 'backend has not been inited';
969 0 $self->warn;
970 0 return;
971 }
972  
973 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::iptables::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv6_re\z/) { } 0 0 0
974 0 $self->{error} = 9;
975 0 $self->{errorString} = 'Nothing specified for the value ban';
976 0 $self->warn;
977 0 return;
978 } elsif ( ref( $opts{ban} ) ne '' ) {
979 0 $self->{error} = 10;
980 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
981 0 $self->warn;
982 0 return;
983 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition0%0/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv6_re\z/
l!l&&r!l&&!r
000
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv6_re\z/
Truth table0%0/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv6_re\z/
ABresult
1X1
011
000
984 && $opts{ban} !~ /\A$IPv6_re\z/ )
985 {
986 0 $self->{error} = 10;
987 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
988 0 $self->warn;
989 0 return;
990 }
991  
992 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
993 0 $opts{ban} = lc( $opts{ban} );
994  
995 0 ▶ if ( $self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"banned"}{$opts{"ban"}}) 0 0 0
996 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
997 0 $self->{frontend_obj}->{test_data} = 'already banned';
998 }
999 0 return;
1000 }
1001  
1002 0 my ( $set4, $set6 ) = $self->_set_names;
1003 0 ▶ my $set = ( $opts{ban} =~ /\A$IPv4_re\z/ ) ? $set4 : $set6;
Branch: 1 branch
BranchTrueFalseTotal
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv4_re\z/ ? : 0 0 0
1004  
1005 0 my $command = 'ipset add ' . $set . ' ' . $opts{ban};
1006  
1007 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
1008 0 $self->{frontend_obj}->{test_data} = [$command];
1009 } else {
1010 0 my $output = `$command 2>&1`;
1011 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
1012 0 $self->{error} = 13;
1013 $self->{errorString}
1014 0 = 'ban failed. non-zero exit code for the command... "' . $command . '"... output... ' . $output;
1015 0 $self->warn;
1016 }
1017 }
1018  
1019 0 ▶ if ( $self->{options}{kill} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"options"}{"kill"}) 0 0 0
1020 0 foreach my $kill_command ( $self->_kill_commands( $opts{ban} ) ) {
1021 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
1022 0 push( @{ $self->{frontend_obj}->{test_data} }, $kill_command );
1023 } else {
1024 # conntrack returns non-zero when there is nothing to delete,
1025 # so its exit code is intentionally ignored
1026 0 my $output = `$kill_command 2>&1`;
1027 }
1028 }
1029 } ## end if ( $self->{options}{kill} )
1030  
1031 0 $self->{banned}{ $opts{ban} } = 1;
1032 } ## end sub ban
1033  
1034 =head2 unban
1035  
1036 Unbans an IP. The value of ban is validated as being a IPv4 or IPv6 address
1037 and lowercased, then removed from the instance's IPv4 or IPv6 ipset, as
1038 appropriate for its family, via C<ipset del>. Unbanning an IP that is not
1039 banned is a noop.
1040  
1041 $backend->unban(ban => $ip);
1042  
1043 =cut
1044  
1045 0 ▶sub unban {
Subroutine unban: not called CC=11 SCAR=48.8
Pod documented
1046 0 my ( $self, %opts ) = @_;
1047  
1048 0 $self->errorblank;
1049  
1050 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
1051 0 $self->{error} = 1;
1052 0 $self->{errorString} = 'backend has not been inited';
1053 0 $self->warn;
1054 0 return;
1055 }
1056  
1057 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::iptables::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv6_re\z/) { } 0 0 0
1058 0 $self->{error} = 9;
1059 0 $self->{errorString} = 'Nothing specified for the value ban';
1060 0 $self->warn;
1061 0 return;
1062 } elsif ( ref( $opts{ban} ) ne '' ) {
1063 0 $self->{error} = 10;
1064 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
1065 0 $self->warn;
1066 0 return;
1067 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition0%0/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv6_re\z/
l!l&&r!l&&!r
000
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv6_re\z/
Truth table0%0/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv6_re\z/
ABresult
1X1
011
000
1068 && $opts{ban} !~ /\A$IPv6_re\z/ )
1069 {
1070 0 $self->{error} = 10;
1071 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
1072 0 $self->warn;
1073 0 return;
1074 }
1075  
1076 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
1077 0 $opts{ban} = lc( $opts{ban} );
1078  
1079 0 ▶ if ( !$self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"banned"}{$opts{"ban"}}) 0 0 0
1080 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1081 0 $self->{frontend_obj}->{test_data} = 'not banned';
1082 }
1083 0 return;
1084 }
1085  
1086 0 my ( $set4, $set6 ) = $self->_set_names;
1087 0 ▶ my $set = ( $opts{ban} =~ /\A$IPv4_re\z/ ) ? $set4 : $set6;
Branch: 1 branch
BranchTrueFalseTotal
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv4_re\z/ ? : 0 0 0
1088  
1089 0 my $command = 'ipset del ' . $set . ' ' . $opts{ban};
1090  
1091 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
1092 0 $self->{frontend_obj}->{test_data} = $command;
1093 } else {
1094 0 my $output = `$command 2>&1`;
1095 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
1096 0 $self->{error} = 14;
1097 $self->{errorString}
1098 0 = 'unban failed. non-zero exit code for the command... "' . $command . '"... output... ' . $output;
1099 0 $self->warn;
1100 }
1101 }
1102  
1103 0 delete( $self->{banned}{ $opts{ban} } );
1104 } ## end sub unban
1105  
1106 =head2 list
1107  
1108 List banned IPs. Returns an array of the currently banned IPs from the
1109 retained ban state; the ipsets themselves are not queried.
1110  
1111 my @banned = $backend->list;
1112  
1113 =cut
1114  
1115 0 ▶sub list {
Subroutine list: not called CC=2 SCAR=17.9
Pod documented
1116 0 my ( $self, %opts ) = @_;
1117  
1118 0 $self->errorblank;
1119  
1120 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1121 0 $self->{frontend_obj}->{test_data} = 'list';
1122 }
1123  
1124 0 return keys( %{ $self->{banned} } );
1125 }
1126  
1127 =head2 re_init
1128  
1129 Tells the backend to re-init it's self.
1130  
1131 Calls teardown, with any errors from it ignored as a partially wiped setup
1132 is exactly what re_init exists to recover from, then init, recreating the
1133 ipsets, chain, and rules. Each previously banned IP is then re-added to the
1134 relevant ipset via C<ipset add>.
1135  
1136 $backend->re_init;
1137  
1138 =cut
1139  
1140 0 ▶sub re_init {
Subroutine re_init: not called CC=6 SCAR=37.4
Pod documented
1141 0 my ( $self, %opts ) = @_;
1142  
1143 0 $self->errorblank;
1144  
1145 # teardown is best effort here as a partially or fully wiped setup is
1146 # exactly what re_init needs to recover from; init cleans up any remnants
1147 {
1148 0 local $@;
1149 0 eval { $self->teardown; };
1150 }
1151 0 $self->init;
1152  
1153 0 my ( $set4, $set6 ) = $self->_set_names;
1154  
1155 0 my @to_ban = keys( %{ $self->{banned} } );
1156  
1157 0 my @re_init_test_data;
1158 0 foreach my $item (@to_ban) {
1159 0 ▶ my $set = ( $item =~ /\A$IPv4_re\z/ ) ? $set4 : $set6;
Branch: 1 branch
BranchTrueFalseTotal
$item =~ /\A$Net::Firewall::BlockerHelper::backends::iptables::IPv4_re\z/ ? : 0 0 0
1160 0 my $command = 'ipset add ' . $set . ' ' . $item;
1161  
1162 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
1163 0 push( @re_init_test_data, $command );
1164 } else {
1165 0 my $output = `$command 2>&1`;
1166 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
1167 0 $self->{error} = 13;
1168 $self->{errorString}
1169 0 = 'ban failed. non-zero exit code for the command... "' . $command . '"... output... ' . $output;
1170 0 $self->warn;
1171 }
1172 }
1173 } ## end foreach my $item (@to_ban)
1174  
1175 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1176 0 $self->{frontend_obj}->{test_data} = \@re_init_test_data;
1177 }
1178  
1179 0 $self->{inited} = 1;
1180 } ## end sub re_init
1181  
1182 =head2 teardown
1183  
1184 Tears down the setup for the backend.
1185  
1186 Removes the jump from C<INPUT>, flushes and deletes the chain, and destroys
1187 both ipsets, via C<iptables>, C<ip6tables>, and C<ipset destroy>. For the
1188 tarpit and delude types the raw table chain and its C<PREROUTING> jump are
1189 removed as well, before the ipsets its rules reference are destroyed. The
1190 retained ban state is kept, so a later init/re_init can restore the bans.
1191  
1192 It does not check if the backend has been inited, so if called prior to
1193 init the removal commands will fail and it will error.
1194  
1195 $backend->teardown;
1196  
1197 =cut
1198  
1199 0 ▶sub teardown {
Subroutine teardown: not called CC=4 SCAR=30.0
Pod documented
1200 0 my ( $self, %opts ) = @_;
1201  
1202 0 $self->errorblank;
1203  
1204 0 $self->{inited} = 0;
1205  
1206 0 my ( $set4, $set6, $chain ) = $self->_set_names;
1207  
1208 0 my @commands;
1209 0 push( @commands, 'iptables -D INPUT -j ' . $chain );
1210 0 push( @commands, 'ip6tables -D INPUT -j ' . $chain );
1211 0 push( @commands, 'iptables -F ' . $chain );
1212 0 push( @commands, 'ip6tables -F ' . $chain );
1213 0 push( @commands, 'iptables -X ' . $chain );
1214 0 push( @commands, 'ip6tables -X ' . $chain );
1215  
1216 # remove the raw notrack chain (tarpit/delude only) before destroying the
1217 # ipsets, as its rules reference them; empty otherwise
1218 0 push( @commands, $self->_raw_teardown_commands );
1219  
1220 0 push( @commands, 'ipset destroy ' . $set4 );
1221 0 push( @commands, 'ipset destroy ' . $set6 );
1222  
1223 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
1224 0 $self->{frontend_obj}->{test_data} = \@commands;
1225 } else {
1226 0 foreach my $item (@commands) {
1227 0 my $output = `$item 2>&1`;
1228 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
1229 0 $self->{error} = 17;
1230 $self->{errorString}
1231 0 = 'teardown failed. non-zero exit code for the command... "' . $item . '"... output... ' . $output;
1232 0 $self->warn;
1233 }
1234 }
1235 } ## end else [ if ( $self->{testing} ) ]
1236 } ## end sub teardown
1237  
1238 =head2 stop
1239  
1240 Alias for L</teardown>, provided for parity with the fail2ban C<actionstop>
1241 concept.
1242  
1243 $backend->stop;
1244  
1245 =cut
1246  
1247 0 ▶sub stop {
Subroutine stop: not called CC=1 SCAR=6.9
Pod documented
1248 0 my ( $self, %opts ) = @_;
1249  
1250 0 return $self->teardown(%opts);
1251 }
1252  
1253 =head2 check
1254  
1255 Verifies that the ipsets, the chain jump, and each of the block rules in the
1256 chain are still in place. Returns a true value if the setup is intact and a
1257 false value if any part is missing. This is the equivalent of fail2ban's
1258 C<actioncheck>.
1259  
1260 if ( !$backend->check ) {
1261 $backend->re_init;
1262 }
1263  
1264 =cut
1265  
1266 0 ▶sub check {
Subroutine check: not called CC=6 SCAR=37.4
Pod documented
1267 0 my ( $self, %opts ) = @_;
1268  
1269 0 $self->errorblank;
1270  
1271 0 my ( $set4, $set6, $chain ) = $self->_set_names;
1272  
1273 # reuse the -A commands that populate the chains as -C existence checks, so
1274 # every block rule (and, for tarpit/delude, every raw notrack rule) the
1275 # setup should contain is verified
1276 0 my @rule_checks = ( $self->_rule_commands, $self->_notrack_commands );
1277 0 foreach my $item (@rule_checks) {
1278 0 $item =~ s/ -A / -C /;
1279 }
1280  
1281 0 my @commands = (
1282 'ipset list ' . $set4,
1283 'ipset list ' . $set6,
1284 'iptables -C INPUT -j ' . $chain,
1285 'ip6tables -C INPUT -j ' . $chain,
1286 @rule_checks,
1287 );
1288  
1289 # the raw table jump only exists for tarpit/delude; empty otherwise
1290 0 ▶ if ( $self->_needs_notrack ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_needs_notrack) 0 0 0
1291 0 push( @commands, 'iptables -t raw -C PREROUTING -j ' . $chain );
1292 0 push( @commands, 'ip6tables -t raw -C PREROUTING -j ' . $chain );
1293 }
1294  
1295 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1296 0 $self->{frontend_obj}->{test_data} = \@commands;
1297 0 return 1;
1298 }
1299  
1300 0 foreach my $item (@commands) {
1301 0 my $output = `$item 2>&1`;
1302 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
1303 0 return 0;
1304 }
1305 }
1306  
1307 0 return 1;
1308 } ## end sub check
1309  
1310 =head2 flush
1311  
1312 Removes all currently banned IPs at once by flushing the ipsets, leaving the
1313 chain and rules in place. This is the equivalent of fail2ban's
1314 C<actionflush>.
1315  
1316 $backend->flush;
1317  
1318 =cut
1319  
1320 0 ▶sub flush {
Subroutine flush: not called CC=5 SCAR=34.0
Pod documented
1321 0 my ( $self, %opts ) = @_;
1322  
1323 0 $self->errorblank;
1324  
1325 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
1326 0 $self->{error} = 1;
1327 0 $self->{errorString} = 'backend has not been inited';
1328 0 $self->warn;
1329 0 return;
1330 }
1331  
1332 0 my ( $set4, $set6 ) = $self->_set_names;
1333  
1334 0 my @commands = ( 'ipset flush ' . $set4, 'ipset flush ' . $set6 );
1335  
1336 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
1337 0 $self->{frontend_obj}->{test_data} = \@commands;
1338 } else {
1339 0 foreach my $item (@commands) {
1340 0 my $output = `$item 2>&1`;
1341 0 ▶ if ( $? != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? != 0) 0 0 0
1342 0 $self->{error} = 25;
1343 $self->{errorString}
1344 0 = 'flush failed. non-zero exit code for the command... "' . $item . '"... output... ' . $output;
1345 0 $self->warn;
1346 }
1347 }
1348 } ## end else [ if ( $self->{testing} ) ]
1349  
1350 0 $self->{banned} = {};
1351 } ## end sub flush
1352  
1353 =head2 ban_cidr
1354  
1355 CIDR bans are not supported by this backend; this always sets the
1356 cidrNotSupported error.
1357  
1358 $backend->ban_cidr(ban => '1.2.3.0/24');
1359  
1360 =cut
1361  
1362 0 ▶sub ban_cidr {
Subroutine ban_cidr: not called CC=1 SCAR=6.9
Pod documented
1363 0 my ( $self, %opts ) = @_;
1364  
1365 0 $self->errorblank;
1366  
1367 0 $self->{error} = 29;
1368 0 $self->{errorString} = 'the ' . __PACKAGE__ . ' backend does not support CIDR bans';
1369 0 $self->warn;
1370  
1371 0 return;
1372 } ## end sub ban_cidr
1373  
1374 =head2 unban_cidr
1375  
1376 CIDR bans are not supported by this backend; this always sets the
1377 cidrNotSupported error.
1378  
1379 $backend->unban_cidr(ban => '1.2.3.0/24');
1380  
1381 =cut
1382  
1383 0 ▶sub unban_cidr {
Subroutine unban_cidr: not called CC=1 SCAR=6.9
Pod documented
1384 0 my ( $self, %opts ) = @_;
1385  
1386 0 $self->errorblank;
1387  
1388 0 $self->{error} = 29;
1389 0 $self->{errorString} = 'the ' . __PACKAGE__ . ' backend does not support CIDR bans';
1390 0 $self->warn;
1391  
1392 0 return;
1393 } ## end sub unban_cidr
1394  
1395 =head2 list_cidr
1396  
1397 CIDR bans are not supported by this backend, so this always returns an empty
1398 list.
1399  
1400 my @banned_cidrs = $backend->list_cidr;
1401  
1402 =cut
1403  
1404 0 ▶sub list_cidr {
Subroutine list_cidr: not called CC=1 SCAR=6.9
Pod documented
1405 0 my ( $self, %opts ) = @_;
1406  
1407 0 $self->errorblank;
1408  
1409 0 return ();
1410 }
1411  
1412 =head1 ERROR CODES / FLAGS
1413  
1414 Error handling is provided by L<Error::Helper>. All
1415 errors are considered fatal.
1416  
1417 =head2 1, notInited
1418  
1419 The backend has not been inited yet.
1420  
1421 =head2 2, invalidPortSpecified
1422  
1423 Port is either not an int within the range 1 to 65535 or a name that can be resolved by getservbyname.
1424  
1425 =head2 3, portsNotArray
1426  
1427 The data passed to new for ports is not an array.
1428  
1429 =head2 4, protocolsNotArray
1430  
1431 The data passed to new for protocols is not an array.
1432  
1433 =head2 5, invalidPortSpecified
1434  
1435 Port is either not an int within the range 1 to 65535 or a name that can be resolved by getservbyname.
1436  
1437 =head2 6, invalidPrefixSpecified
1438  
1439 The specified prefix did not match /^[a-zA-Z0-9]+$/.
1440  
1441 =head2 7, invalidName
1442  
1443 The name is either undef or does not match /^[a-zA-Z0-9\-]+$/.
1444  
1445 =head2 8, optionsNotHash
1446  
1447 The item passed to new for options is not a hash.
1448  
1449 =head2 9, noBanItem
1450  
1451 No IP specified to ban or unban.
1452  
1453 =head2 10, banItemNotIP
1454  
1455 The item to ban is not an IP. Either wrong ref type or regexp
1456 test using L<Regexp::IPv4> and L<Regexp::IPv6> failed.
1457  
1458 =head2 11, invalidBackend
1459  
1460 The specified backend failed to pass a basic sanity check of making sure it
1461 matches the regexp /^[a-zA-Z0-9\_]+$/.
1462  
1463 =head2 12, backendInitError
1464  
1465 Failed to init the backend.
1466  
1467 =head2 13, banFailed
1468  
1469 Failed to ban the item.
1470  
1471 =head2 14, unbanFailed
1472  
1473 Failed to unban the item.
1474  
1475 =head2 15, listFailed
1476  
1477 Failed to get a list of bans.
1478  
1479 =head2 16, reInitFailed
1480  
1481 Failed to re_init the backend.
1482  
1483 =head2 17, teardownFailed
1484  
1485 Failed to teardown the backend.
1486  
1487 =head2 18, alreadyInited
1488  
1489 init called, but the backend has already been inited.
1490  
1491 =head2 20, typeInvalid
1492  
1493 The option type is not one of "drop", "reject", "tarpit", or "delude", or the
1494 option tarpit_mode is not one of "tarpit", "honeypot", or "reset".
1495  
1496 =head2 21, nameTooLong
1497  
1498 The combined prefix and name is longer than 28 characters, the max iptables
1499 chain name length.
1500  
1501 =head2 23, initFailed
1502  
1503 One of the required commands for init failed.
1504  
1505 =head2 24, checkFailed
1506  
1507 The backend check raised an error.
1508  
1509 =head2 25, flushFailed
1510  
1511 Failed to flush the bans.
1512  
1513 =head2 26, banCidrFailed
1514  
1515 Failed to ban the CIDR range.
1516  
1517 =head2 27, unbanCidrFailed
1518  
1519 Failed to unban the CIDR range.
1520  
1521 =head2 28, cidrItemNotCidr
1522  
1523 The item to ban is not a CIDR range. Either wrong ref type or it is not an
1524 IPv4 or IPv6 address followed by a prefix length valid for its family.
1525  
1526 =head2 29, cidrNotSupported
1527  
1528 The backend does not support CIDR bans.
1529  
1530 =head2 30, listCidrFailed
1531  
1532 Failed to get a list of CIDR bans.
1533  
1534 =head1 AUTHOR
1535  
1536 Zane C. Bowers-Hadley, C<< <vvelox at vvelox.ent> >>
1537  
1538 =head1 BUGS
1539  
1540 Please report any bugs or feature requests to C<bug-net-firewall-blockerhelper at rt.cpan.org>, or through
1541 the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Net-Firewall-BlockerHelper>. I will be notified, and then you'll
1542 automatically be notified of progress on your bug as I make changes.
1543  
1544  
1545  
1546  
1547 =head1 SUPPORT
1548  
1549 You can find documentation for this module with the perldoc command.
1550  
1551 perldoc Net::Firewall::BlockerHelper
1552  
1553  
1554 You can also look for information at:
1555  
1556 =over 4
1557  
1558 =item * RT: CPAN's request tracker (report bugs here)
1559  
1560 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Net-Firewall-BlockerHelper>
1561  
1562 =item * Search CPAN
1563  
1564 L<https://metacpan.org/release/Net-Firewall-BlockerHelper>
1565  
1566 =back
1567  
1568  
1569 =head1 ACKNOWLEDGEMENTS
1570  
1571  
1572 =head1 LICENSE AND COPYRIGHT
1573  
1574 This software is Copyright (c) 2023 by Zane C. Bowers-Hadley.
1575  
1576 This is free software, licensed under:
1577  
1578 The GNU Lesser General Public License, Version 2.1, February 1999
1579  
1580  
1581 =cut
1582  
1583 3 1; # End of Net::Firewall::BlockerHelper
« BlockerHelper/backends/firewalld.pm ↑ Summary BlockerHelper/Util.pm »