NAME
Net::Firewall::BlockerHelper::backends::iptables - iptables/ip6tables backend for Net::Firewall::BlockerHelper.
VERSION
Version 0.2.0
SYNOPSIS
Everything this backend needs is wired in by init itself, the jump from INPUT to its chain included, so no ruleset changes are needed beforehand. The jump is appended to the end of INPUT though, and iptables is first match wins, so any earlier rule accepting the traffic in question, such as a blanket ACCEPT for a port or an established/related state rule, will win out over the bans. If bans appear to have no effect, check where the jump to <prefix>_<name> sits via iptables -L INPUT and relocate it above such rules; the backend finds it by rule spec rather than position, so moving it is safe.
use Net::Firewall::BlockerHelper::backends::iptables;
my $backend1;
my $backend2;
eval {
$backend1 = Net::Firewall::BlockerHelper::backends::iptables->new(
name => 'all',
options=>{ kill=>1 },
);
$backend2 = Net::Firewall::BlockerHelper::backends::iptables->new(
ports => ['143'],
protocols => ['tcp'],
name => 'imap',
);
};
if ($@) {
print 'Error: '
. $Error::Helper::error
. "\nError String: "
. $Error::Helper::errorString
. "\nError Flag: "
. $Error::Helper::errorFlag . "\n";
}
$backend1->init;
$backend2->init;
$backend1->ban(ban=>'1.2.3.4');
$backend1->ban(ban=>'4.3.2.1');
$backend2->ban(ban=>'4.3.2.1');
use Data::Dumper;
print Dumper($backend1->list);
print Dumper($backend2->list);
$backend1->unban(ban=>'4.3.2.1');
$backend1->teardown;
$backend2->teardown;
DESCRIPTION
This backend blocks IPs using ipset(8) in combination with iptables(8) and ip6tables(8).
For each instance two ipsets are created, one for IPv4 (<prefix>_<name>_4) and one for IPv6 (<prefix>_<name>_6), along with a dedicated chain (<prefix>_<name>) in each of the filter tables. The chain is populated with the block rules and jumped to from INPUT. Banning an IP is then simply a matter of adding it to the relevant ipset.
When the tarpit or delude type is used a same-named chain is also created in the raw table and jumped to from PREROUTING, holding -j CT --notrack rules that match the same traffic. This exempts the tarpitted/deluded connections from connection tracking, which those xtables-addons targets require to work. It is created and removed automatically with the filter chain.
Requires ipset, iptables, and ip6tables to be installed and in the PATH of the process, which must have sufficient privileges to run them. The tarpit/delude types additionally require the TARPIT/ DELUDE targets from xtables-addons.
METHODS
new
Initiates the the object.
- options :: Backend specific options that will be passed to the backend unchecked
outside of making sure it is a hash ref if defined. See below for furhter info.
- Default :: {}
- ports :: A array of ports to block. Checked to make sure they are positive ints or a valid
service name via getservbyname. All ports will be blocked if non are specified. If
duplicates are removed.
- Default :: []
- protocols :: A array of protocols to block. By default will block all,
unless ports are given, in which case it defaults to tcp and udp. This
is checked against /etc/protocols via the function getprotobyname. Duplicates
will be discarded.
- Default :: [], or ['tcp','udp'] when ports are given
- prefix :: Prefix to use. Must match the regex /^[a-zA-Z0-9]+$/
- default :: kur
- name :: Name of this specific instance. This must be specified.
- default :: undef
The options hash accepts the following.
- type :: The block method to use. One of 'drop', 'reject', 'tarpit',
or 'delude'.
- drop :: Silently drop the packet. See iptables(8).
- reject :: Send an ICMP port-unreachable back. See iptables(8).
- tarpit :: Hold the TCP connection open with a zero window so
the attacker wastes resources. Requires the TARPIT
target from xtables-addons. TCP only.
- delude :: Answer a SYN with a SYN/ACK and everything else with
a RST, so the port looks open but never completes a
session. Requires the DELUDE target from xtables-addons.
TCP only. The target itself is also IPv4 only, as
xtables-addons provides no IPv6 version, so the IPv6
rule falls back to DROP; banned IPv6 IPs are still
blocked, just silently dropped rather than deluded.
The tarpit and delude types only ever emit '-p tcp' rules; any
non-tcp protocol or port default (eg the implicit udp) is skipped
rather than handed to a target the kernel would reject. For these
types the backend also installs a matching '-j CT --notrack' rule
in a raw table chain jumped from PREROUTING, so conntrack does not
process (and fight) the crafted replies; this is set up and torn
down automatically alongside the filter chain.
- Default :: drop
- tarpit_mode :: When type is 'tarpit', selects the TARPIT mode, one of
'tarpit' (default, zero-window hold), 'honeypot' (accept then hold),
or 'reset'. Ignored for the other types.
- Default :: tarpit
- kill :: Use conntrack(8) to drop existing connection tracking entries
for the banned IP, for both IPv4 and IPv6. When protocols are
configured the kill is scoped to them via -p, so blocking only
udp will not drop tcp entries and vice versa; protocols conntrack
can not filter by are skipped. With no protocols configured
everything is being blocked, so entries of every protocol are
dropped.
- Default :: 0
All errors are considered fatal, meaning if new fails it will die.
my $backend;
eval {
$backend = Net::Firewall::BlockerHelper::backends::iptables->new(
ports => ['22'],
protocols => ['tcp'],
name => 'ssh',
);
};
if ($@) {
print 'Error: '
. $Error::Helper::error
. "\nError String: "
. $Error::Helper::errorString
. "\nError Flag: "
. $Error::Helper::errorFlag . "\n";
}
init
Initiates the backend. Creates the two ipsets, <prefix>_<name>_4 (hash:ip family inet) and <prefix>_<name>_6 (hash:ip family inet6), creates the <prefix>_<name> chain via iptables -N and ip6tables -N, populates it with the block rules built from the configured type, protocols, and ports, and appends a jump to it from INPUT. For the tarpit and delude types a same-named chain holding the -j CT --notrack rules is also created in the raw table and jumped to from PREROUTING.
Note that the jump is appended to the end of INPUT, so earlier rules accepting the traffic win out over the bans. See "SYNOPSIS".
Before any of that, matching stale chains and ipsets from a previous run are removed; those cleanup commands are allowed to fail.
No arguments are taken.
If called a second time without an intervening teardown, it will error.
$backend->init;
ban
Bans an IP. The value of ban is validated as being a IPv4 or IPv6 address and lowercased, then added to the instance's IPv4 or IPv6 ipset, as appropriate for its family, via ipset add. Banning an already banned IP is a noop.
If the kill option is set, conntrack(8) is then used to drop existing connection tracking entries for the IP; its exit code is ignored, as it is non-zero when there is nothing to delete.
$backend->ban(ban => $ip);
unban
Unbans an IP. The value of ban is validated as being a IPv4 or IPv6 address and lowercased, then removed from the instance's IPv4 or IPv6 ipset, as appropriate for its family, via ipset del. Unbanning an IP that is not banned is a noop.
$backend->unban(ban => $ip);
list
List banned IPs. Returns an array of the currently banned IPs from the retained ban state; the ipsets themselves are not queried.
my @banned = $backend->list;
re_init
Tells the backend to re-init it's self.
Calls teardown, with any errors from it ignored as a partially wiped setup is exactly what re_init exists to recover from, then init, recreating the ipsets, chain, and rules. Each previously banned IP is then re-added to the relevant ipset via ipset add.
$backend->re_init;
teardown
Tears down the setup for the backend.
Removes the jump from INPUT, flushes and deletes the chain, and destroys both ipsets, via iptables, ip6tables, and ipset destroy. For the tarpit and delude types the raw table chain and its PREROUTING jump are removed as well, before the ipsets its rules reference are destroyed. The retained ban state is kept, so a later init/re_init can restore the bans.
It does not check if the backend has been inited, so if called prior to init the removal commands will fail and it will error.
$backend->teardown;
stop
Alias for "teardown", provided for parity with the fail2ban actionstop concept.
$backend->stop;
check
Verifies that the ipsets, the chain jump, and each of the block rules in the chain are still in place. Returns a true value if the setup is intact and a false value if any part is missing. This is the equivalent of fail2ban's actioncheck.
if ( !$backend->check ) {
$backend->re_init;
}
flush
Removes all currently banned IPs at once by flushing the ipsets, leaving the chain and rules in place. This is the equivalent of fail2ban's actionflush.
$backend->flush;
ban_cidr
CIDR bans are not supported by this backend; this always sets the cidrNotSupported error.
$backend->ban_cidr(ban => '1.2.3.0/24');
unban_cidr
CIDR bans are not supported by this backend; this always sets the cidrNotSupported error.
$backend->unban_cidr(ban => '1.2.3.0/24');
list_cidr
CIDR bans are not supported by this backend, so this always returns an empty list.
my @banned_cidrs = $backend->list_cidr;
ERROR CODES / FLAGS
Error handling is provided by Error::Helper. All errors are considered fatal.
1, notInited
The backend has not been inited yet.
2, invalidPortSpecified
Port is either not an int within the range 1 to 65535 or a name that can be resolved by getservbyname.
3, portsNotArray
The data passed to new for ports is not an array.
4, protocolsNotArray
The data passed to new for protocols is not an array.
5, invalidPortSpecified
Port is either not an int within the range 1 to 65535 or a name that can be resolved by getservbyname.
6, invalidPrefixSpecified
The specified prefix did not match /^[a-zA-Z0-9]+$/.
7, invalidName
The name is either undef or does not match /^[a-zA-Z0-9\-]+$/.
8, optionsNotHash
The item passed to new for options is not a hash.
9, noBanItem
No IP specified to ban or unban.
10, banItemNotIP
The item to ban is not an IP. Either wrong ref type or regexp test using Regexp::IPv4 and Regexp::IPv6 failed.
11, invalidBackend
The specified backend failed to pass a basic sanity check of making sure it matches the regexp /^[a-zA-Z0-9\_]+$/.
12, backendInitError
Failed to init the backend.
13, banFailed
Failed to ban the item.
14, unbanFailed
Failed to unban the item.
15, listFailed
Failed to get a list of bans.
16, reInitFailed
Failed to re_init the backend.
17, teardownFailed
Failed to teardown the backend.
18, alreadyInited
init called, but the backend has already been inited.
20, typeInvalid
The option type is not one of "drop", "reject", "tarpit", or "delude", or the option tarpit_mode is not one of "tarpit", "honeypot", or "reset".
21, nameTooLong
The combined prefix and name is longer than 28 characters, the max iptables chain name length.
23, initFailed
One of the required commands for init failed.
24, checkFailed
The backend check raised an error.
25, flushFailed
Failed to flush the bans.
26, banCidrFailed
Failed to ban the CIDR range.
27, unbanCidrFailed
Failed to unban the CIDR range.
28, cidrItemNotCidr
The item to ban is not a CIDR range. Either wrong ref type or it is not an IPv4 or IPv6 address followed by a prefix length valid for its family.
29, cidrNotSupported
The backend does not support CIDR bans.
30, listCidrFailed
Failed to get a list of CIDR bans.
AUTHOR
Zane C. Bowers-Hadley, <vvelox at vvelox.ent>
BUGS
Please report any bugs or feature requests to bug-net-firewall-blockerhelper at rt.cpan.org, or through the web interface at https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Net-Firewall-BlockerHelper. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
SUPPORT
You can find documentation for this module with the perldoc command.
perldoc Net::Firewall::BlockerHelper
You can also look for information at:
RT: CPAN's request tracker (report bugs here)
https://rt.cpan.org/NoAuth/Bugs.html?Dist=Net-Firewall-BlockerHelper
Search CPAN
ACKNOWLEDGEMENTS
LICENSE AND COPYRIGHT
This software is Copyright (c) 2023 by Zane C. Bowers-Hadley.
This is free software, licensed under:
The GNU Lesser General Public License, Version 2.1, February 1999