BlockerHelper/Util.pm

filter: Statementstmt 58.0% 29 / 50 Branchbran 20.8% 5 / 24 Conditioncond 22.2% 4 / 18 MC/DCmcdc 8.3% 1 / 12 Subroutinesub 88.8% 8 / 9 Podpod n/a totaltotal 41.5% 47 / 113 CC 20 SCAR 44.8
CC
20
Cov
41%
_kill_commands
182.0
_valid_cidr
11.4
BEGIN
1.0
CRAP 88.0
« BlockerHelper/backends/iptables.pm ↑ Summary BlockerHelper/backends/pf.pm »
1 package Net::Firewall::BlockerHelper::Util;
2  
3 57 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 57 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 57 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 57 ▶use Regexp::IPv4 qw($IPv4_re);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 57 ▶use Regexp::IPv6 qw($IPv6_re);
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 =head1 NAME
10  
11 Net::Firewall::BlockerHelper::Util - Shared internal helpers mixed into the frontend and backends.
12  
13 =head1 VERSION
14  
15 Version 0.0.1
16  
17 =cut
18  
19 57 our $VERSION = '0.0.1';
20  
21 =head1 SYNOPSIS
22  
23 This module is not used directly. It is a stateless mixin holding the internal
24 helpers that would otherwise be copy/pasted into every backend. Both
25 L<Net::Firewall::BlockerHelper> and each backend under
26 L<Net::Firewall::BlockerHelper>::backends inherit from it alongside
27 L<Error::Helper>.
28  
29 package Net::Firewall::BlockerHelper::backends::foo;
30  
31 use base qw( Error::Helper Net::Firewall::BlockerHelper::Util );
32  
33 # ...
34  
35 sub ban_cidr {
36 my ( $self, %opts ) = @_;
37  
38 if ( !$self->_valid_cidr( $opts{ban} ) ) {
39 # ... raise error 26 ...
40 }
41 }
42  
43 =head1 DESCRIPTION
44  
45 Everything here is an internal helper and carries a leading underscore. None of
46 it is part of the public API and none of it is expected to be called from
47 outside of the frontend or a backend. There is no constructor and no state is
48 kept; the methods only exist here so that a single definition is shared instead
49 of being duplicated per backend.
50  
51 =cut
52  
53 # Internal helper. Returns a JSON object configured the way every backend that
54 # speaks a JSON REST API wants it, used both to encode request bodies and to
55 # decode responses.
56 #
57 # JSON is used rather than JSON::PP directly because it picks JSON::XS as its
58 # backend when that is installed and only falls back to the pure perl JSON::PP
59 # when it is not, so the fast path is taken wherever it is available. The
60 # object interface used here is the same either way.
61 #
62 # Two options are set. canonical makes the encoder sort object keys, so the
63 # same data always encodes to the same string; without it the key order follows
64 # the hash order and the bodies recorded in test_data would vary run to run and
65 # could not be compared against a fixed expected string. utf8 makes the encoder
66 # emit UTF-8 encoded octets and the decoder expect them, which is what wants to
67 # be handed to and taken from an HTTP layer.
68 #
69 # JSON is pulled in with require at call time rather than use at compile time,
70 # matching how the HTTP backends load LWP::UserAgent. Only the JSON speaking
71 # backends ever need it, so it stays off the path of the many backends that do
72 # not and is a recommends rather than a hard prereq.
73 #
74 # Takes no arguments.
75 #
76 # Returns a JSON object. A new object is built on every call and nothing is
77 # cached, so the caller may reconfigure the returned object freely without
78 # affecting anything else.
79 #
80 # my $body = $self->_json->encode( { name => $name, ip => $ip } );
81 #
82 # my $decoded = $self->_json->decode($response_content);
83 # my $id = $decoded->{result}{id};
84 65 ▶sub _json {
Subroutine _json: called CC=1 SCAR=0.0
85 65 my ($self) = @_;
86  
87 65 require JSON;
88 65 return JSON->new->canonical->utf8;
89 }
90  
91 # Internal helper. Returns the conntrack commands that tear down the passed
92 # IP's existing connections, used by the backends whose kill option drops
93 # connection tracking entries.
94 #
95 # Blocking an address only stops new connections. Anything already established
96 # keeps flowing, because the block rules match the source but established
97 # traffic has already been accepted and is tracked. Dropping the conntrack
98 # entries is what actually cuts an attacker off mid session.
99 #
100 # The kill is scoped to whatever is actually being blocked rather than
101 # indiscriminately dropping every entry for the address. With protocols
102 # configured, one command is emitted per protocol. With ports but no
103 # protocols, tcp and udp are assumed, matching the default the rule builders
104 # use in the same situation. With neither, everything is being blocked, so a
105 # single unscoped command drops every entry for the address.
106 #
107 # Protocols conntrack cannot filter by are skipped rather than emitted and
108 # left to fail. The mapping also folds the several spellings of IPv6 ICMP onto
109 # one conntrack name, and duplicates are suppressed, so listing both icmp6 and
110 # ipv6-icmp produces one command rather than two identical ones. ICMP of the
111 # wrong family is skipped, since an IPv4 address can have no icmpv6 entries
112 # and vice versa.
113 #
114 # This lives here because the iptables, nftables, and firewalld backends all
115 # want exactly this. A backend whose kill works differently overrides it: see
116 # the ufw backend, which offers an ss based mode as well and supports a
117 # narrower protocol set.
118 #
119 # Args:
120 #
121 # ip - The address whose connections should be dropped, as a plain string.
122 # Expected to be an already validated and lowercased IPv4 or IPv6
123 # address. The family is decided by matching against $IPv4_re and
124 # controls both the -f flag and which ICMP protocols are relevant.
125 #
126 # Returns the commands as a list of strings, ready to hand to the runner. One
127 # entry per applicable protocol, or a single unscoped entry when nothing is
128 # configured. May be empty if every configured protocol was filtered out, for
129 # instance an IPv4 instance configured only for ipv6-icmp; callers run
130 # whatever comes back and do not depend on there being any.
131 #
132 # # nothing configured: drop every entry for the address
133 # $self->_kill_commands('10.0.0.1');
134 # # conntrack -D -s 10.0.0.1
135 #
136 # # IPv6 needs the family stated, as conntrack defaults to IPv4
137 # $self->_kill_commands('2001:db8::1');
138 # # conntrack -f ipv6 -D -s 2001:db8::1
139 #
140 # # protocols tcp and udp
141 # $self->_kill_commands('10.0.0.1');
142 # # conntrack -D -p tcp -s 10.0.0.1
143 # # conntrack -D -p udp -s 10.0.0.1
144 #
145 # # ports 22 with no protocols, so tcp and udp are assumed
146 # # conntrack -D -p tcp -s 10.0.0.1
147 # # conntrack -D -p udp -s 10.0.0.1
148 0 ▶sub _kill_commands {
Subroutine _kill_commands: not called CC=13 SCAR=52.0
149 0 my ( $self, $ip ) = @_;
150  
151 # conntrack defaults to IPv4, so IPv6 IPs need the family specified
152 0 ▶ my $is_v4 = ( $ip =~ /\A$IPv4_re\z/ ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$ip =~ /\A$Net::Firewall::BlockerHelper::Util::IPv4_re\z/ ? : 0 0 0
153 0 ▶ my $family = $is_v4 ? '' : '-f ipv6 ';
Branch: 1 branch
BranchTrueFalseTotal
$is_v4 ? : 0 0 0
154  
155 0 my @protos = @{ $self->{protocols} };
156 0 ▶ if ( !@protos && defined( $self->{ports}[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not @protos and defined $self->{"ports"}[0]) 0 0 0
Condition0%0/3
not @protos and defined $self->{"ports"}[0]
!ll&&!rl&&r
000
MC/DC0%0/2
not @protos and defined $self->{"ports"}[0]
not @protos defined $self->{"ports"}[0]
Truth table0%0/3
not(A) and B
A= not @protosB= defined $self->{"ports"}[0]
ABresult
0X0
100
111
157 # ports without protocols means tcp and udp are being blocked
158 0 @protos = ( 'tcp', 'udp' );
159 }
160  
161 # nothing configured means everything is being blocked, so drop every
162 # entry for the IP
163 0 ▶ if ( !@protos ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@protos) 0 0 0
164 0 return ( 'conntrack ' . $family . '-D -s ' . $ip );
165 }
166  
167 # scope the kill to the blocked protocols; ones conntrack can not filter
168 # by are skipped as are the icmps of the wrong family
169 0 my %conntrack_protos = (
170 tcp => 'tcp',
171 udp => 'udp',
172 udplite => 'udplite',
173 sctp => 'sctp',
174 dccp => 'dccp',
175 gre => 'gre',
176 icmp => 'icmp',
177 icmpv6 => 'icmpv6',
178 icmp6 => 'icmpv6',
179 'ipv6-icmp' => 'icmpv6',
180 );
181  
182 0 my @commands;
183 my %seen;
184 0 foreach my $proto (@protos) {
185 0 my $conntrack_proto = $conntrack_protos{$proto};
186 0 ▶ next if ( !defined($conntrack_proto) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $conntrack_proto 0 0 0
187 0 ▶ next if ( $conntrack_proto eq 'icmp' && !$is_v4 );
Branch: 1 branch
BranchTrueFalseTotal
if $conntrack_proto eq "icmp" and not $is_v4 0 0 0
Condition0%0/3
$conntrack_proto eq "icmp" and not $is_v4
!ll&&!rl&&r
000
MC/DC0%0/2
$conntrack_proto eq "icmp" and not $is_v4
$conntrack_proto eq "icmp" not $is_v4
Truth table0%0/3
A and not(B)
A= $conntrack_proto eq "icmp"B= not $is_v4
ABresult
0X0
100
111
188 0 ▶ next if ( $conntrack_proto eq 'icmpv6' && $is_v4 );
Branch: 1 branch
BranchTrueFalseTotal
if $conntrack_proto eq "icmpv6" and $is_v4 0 0 0
Condition0%0/3
$conntrack_proto eq "icmpv6" and $is_v4
!ll&&!rl&&r
000
MC/DC0%0/2
$conntrack_proto eq "icmpv6" and $is_v4
$conntrack_proto eq "icmpv6" $is_v4
Truth table0%0/3
A and B
A= $conntrack_proto eq "icmpv6"B= $is_v4
ABresult
0X0
100
111
189 0 ▶ next if ( $seen{$conntrack_proto} );
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$conntrack_proto} 0 0 0
190 0 $seen{$conntrack_proto} = 1;
191 0 push( @commands, 'conntrack ' . $family . '-D -p ' . $conntrack_proto . ' -s ' . $ip );
192 }
193  
194 0 return @commands;
195 } ## end sub _kill_commands
196  
197 # Internal helper. Percent encodes a string for use in a URL, so that the dist
198 # does not need URI::Escape as a dependency for the handful of backends that
199 # build URLs.
200 #
201 # Every character outside the RFC 3986 unreserved set (A-Z, a-z, 0-9, "-", ".",
202 # "_", and "~") is replaced with a percent sign and its two digit uppercase hex
203 # value. Note that this includes "/", which becomes %2F, so this escapes a
204 # single path segment or query value and must not be run over a whole URL or an
205 # already assembled path.
206 #
207 # The encoding is byte oriented, using ord on each character. Input is expected
208 # to be bytes, which is all the callers ever pass, being IP addresses and
209 # configured object names. A string holding wide characters would produce more
210 # than two hex digits for those characters and would need encoding to UTF-8
211 # octets first.
212 #
213 # Args:
214 #
215 # string - The scalar to encode. Expected to be a defined, non-reference
216 # string of bytes. Passing undef warns and returns undef under
217 # warnings, so callers check for a value first.
218 #
219 # Returns the percent encoded string. The argument is not modified in place;
220 # the copy taken off @_ is what gets edited and returned. A string made up
221 # entirely of unreserved characters comes back unchanged.
222 #
223 # $self->_uri_escape('10.0.0.1'); # 10.0.0.1, unreserved throughout
224 # $self->_uri_escape('2001:db8::1'); # 2001%3Adb8%3A%3A1
225 # $self->_uri_escape('10.0.0.0/8'); # 10.0.0.0%2F8
226 # $self->_uri_escape('ssh bans'); # ssh%20bans
227 #
228 # # building a URL from a name that may hold anything
229 # my $url = $self->_base_url . '/lists/' . $self->_uri_escape($name);
230 148 ▶sub _uri_escape {
Subroutine _uri_escape: called CC=1 SCAR=0.0
231 148 my ( $self, $string ) = @_;
232  
233 148 $string =~ s/([^A-Za-z0-9\-._~])/sprintf('%%%02X', ord($1))/ge;
234  
235 148 return $string;
236 }
237  
238 # Internal helper. Tests whether a scalar is a syntactically valid IPv4 or IPv6
239 # CIDR range. This is the validation used by ban_cidr, unban_cidr, and the
240 # frontend before a range is handed to a backend, so that a malformed range is
241 # rejected with an error rather than being pasted into a firewall command.
242 #
243 # A valid range is an address, a literal "/", and a decimal prefix length that
244 # is within the range allowed for the address family. The address is matched
245 # against $IPv4_re from Regexp::IPv4 and $IPv6_re from Regexp::IPv6, anchored,
246 # so a bare address with no "/" is not valid and neither is a range with any
247 # leading or trailing whitespace. The prefix length must be one to three digits
248 # and be 0 to 32 for IPv4 or 0 to 128 for IPv6. The prefix is not required to
249 # be the canonical network address for the range, so "10.0.0.1/8" is accepted
250 # as valid; masking off the host bits, if wanted, is left to the backend.
251 #
252 # Args:
253 #
254 # cidr - The scalar to test. Any value may be passed. Undef, a reference of
255 # any kind, and a string that does not match the format above are
256 # all simply not valid rather than fatal.
257 #
258 # Returns 1 if the scalar is a valid IPv4 or IPv6 CIDR range and 0 if it is
259 # not. The return is always one of those two values and is never undef, so it
260 # is safe to use directly in a boolean test or to store as a flag.
261 #
262 # $self->_valid_cidr('10.0.0.0/8'); # 1
263 # $self->_valid_cidr('2001:db8::/32'); # 1
264 # $self->_valid_cidr('10.0.0.1/8'); # 1, host bits are allowed
265 #
266 # $self->_valid_cidr('10.0.0.0/33'); # 0, prefix too large for v4
267 # $self->_valid_cidr('2001:db8::/129'); # 0, prefix too large for v6
268 # $self->_valid_cidr('10.0.0.0'); # 0, no prefix
269 # $self->_valid_cidr('not an address/8'); # 0, address does not match
270 # $self->_valid_cidr( [ '10.0.0.0/8' ] ); # 0, a reference
271 # $self->_valid_cidr(undef); # 0
272 108 ▶sub _valid_cidr {
Subroutine _valid_cidr: called CC=8 SCAR=24.3
273 108 my ( $self, $cidr ) = @_;
274  
275 108 ▶ return 0 if ( !defined($cidr) || ref($cidr) ne '' );
Branch: 1 branch
BranchTrueFalseTotal
if not defined $cidr or ref $cidr ne "" 0 108 108
Condition33%1/3
not defined $cidr or ref $cidr ne ""
l!l&&r!l&&!r
00108
MC/DC0%0/2
not defined $cidr or ref $cidr ne ""
not defined $cidr ref $cidr ne ""
Truth table33%1/3
not(A) or B
A= not defined $cidrB= ref $cidr ne ""
ABresult
1X1
011
000
276  
277 108 ▶ if ( $cidr =~ m!\A(.+)/([0-9]{1,3})\z! ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cidr =~ m[\A(.+)/([0-9]{1,3})\z]) 108 0 108
278 108 my ( $addr, $prefix ) = ( $1, $2 );
279 108 ▶ return 1 if ( $addr =~ /\A$IPv4_re\z/ && $prefix <= 32 );
Branch: 1 branch
BranchTrueFalseTotal
if $addr =~ /\A$Net::Firewall::BlockerHelper::Util::IPv4_re\z/ and $prefix <= 32 102 6 108
Condition66%2/3
$addr =~ /\A$Net::Firewall::BlockerHelper::Util::IPv4_re\z/ and $prefix <= 32
!ll&&!rl&&r
60102
MC/DC50%1/2
$addr =~ /\A$Net::Firewall::BlockerHelper::Util::IPv4_re\z/ and $prefix <= 32
$addr =~ /\A$Net::Firewall::BlockerHelper::Util::IPv4_re\z/ $prefix <= 32
Truth table66%2/3
A and B
A= $addr =~ /\A$Net::Firewall::BlockerHelper::Util::IPv4_re\z/B= $prefix <= 32
ABresult
0X0
100
111
280 6 ▶ return 1 if ( $addr =~ /\A$IPv6_re\z/ && $prefix <= 128 );
Branch: 1 branch
BranchTrueFalseTotal
if $addr =~ /\A$Net::Firewall::BlockerHelper::Util::IPv6_re\z/ and $prefix <= 128 6 0 6
Condition33%1/3
$addr =~ /\A$Net::Firewall::BlockerHelper::Util::IPv6_re\z/ and $prefix <= 128
!ll&&!rl&&r
006
MC/DC0%0/2
$addr =~ /\A$Net::Firewall::BlockerHelper::Util::IPv6_re\z/ and $prefix <= 128
$addr =~ /\A$Net::Firewall::BlockerHelper::Util::IPv6_re\z/ $prefix <= 128
Truth table33%1/3
A and B
A= $addr =~ /\A$Net::Firewall::BlockerHelper::Util::IPv6_re\z/B= $prefix <= 128
ABresult
0X0
100
111
281 }
282  
283 0 return 0;
284 } ## end sub _valid_cidr
285  
286 =head1 AUTHOR
287  
288 Zane C. Bowers-Hadley, C<< <vvelox at vvelox.ent> >>
289  
290 =head1 BUGS
291  
292 Please report any bugs or feature requests to C<bug-net-firewall-blockerhelper at rt.cpan.org>, or through
293 the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Net-Firewall-BlockerHelper>. I will be notified, and then you'll
294 automatically be notified of progress on your bug as I make changes.
295  
296  
297  
298  
299 =head1 SUPPORT
300  
301 You can find documentation for this module with the perldoc command.
302  
303 perldoc Net::Firewall::BlockerHelper
304  
305  
306 You can also look for information at:
307  
308 =over 4
309  
310 =item * RT: CPAN's request tracker (report bugs here)
311  
312 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Net-Firewall-BlockerHelper>
313  
314 =item * Search CPAN
315  
316 L<https://metacpan.org/release/Net-Firewall-BlockerHelper>
317  
318 =back
319  
320  
321 =head1 ACKNOWLEDGEMENTS
322  
323  
324 =head1 LICENSE AND COPYRIGHT
325  
326 This software is Copyright (c) 2023 by Zane C. Bowers-Hadley.
327  
328 This is free software, licensed under:
329  
330 The GNU Lesser General Public License, Version 2.1, February 1999
331  
332  
333 =cut
334  
335 57 1; # End of Net::Firewall::BlockerHelper::Util
« BlockerHelper/backends/iptables.pm ↑ Summary BlockerHelper/backends/pf.pm »