Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check if an iptables chain exists #1186

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 39 additions & 1 deletion lib/Rex/Commands/Iptables.pm
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ use Rex::Logger;

@EXPORT = qw(iptables is_nat_gateway iptables_list iptables_clear
open_port close_port redirect_port
default_state_rule);
default_state_rule chain_exists);

sub iptables;

Expand Down Expand Up @@ -485,6 +485,44 @@ sub _iptables_list {
return $ret;
}

=head2 chain_exists

Returns true if a chain exists in a table, false otherwise.


chain_exists 'foo'; # $table defaulting to 'filter'
chain_exists 'foo', table => 'filter';
chain_exists -6, 'foo'; # IPv6


In this example we create a chain unless it already exists.

task "create_chain", sub {
iptables(t => 'filter', N => 'foo')
unless chain_exists('foo');
};


=cut

sub chain_exists {
my @params = @_;
my $ipt_version = _get_ip_version( \@params );
my ( $chain, %args ) = @params;

my $table = (delete $args{table} or 'filter');

eval {
iptables($ipt_version, list => $chain);
};

return 0 if $@ && $@ =~ /No chain/;
die $@ if $@;

return 1;

}

=head2 iptables_clear

Remove all iptables rules.
Expand Down
7 changes: 6 additions & 1 deletion t/commands/iptables.t
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use strict;
use warnings;

use Test::More tests => 32;
use Test::More tests => 36;

use Rex::Commands::Iptables;

Expand Down Expand Up @@ -55,3 +55,8 @@ is( $rules->{foo}->[0]->[13], "50", "up to 50" );
is( $rules->{foo}->[0]->[14], "j", "jump to" );
is( $rules->{foo}->[0]->[15], "RETURN", "RETURN" );

is(Rex::Commands::Iptables::chain_exists('foo'),0);
is(Rex::Commands::Iptables::chain_exists('INPUT'),1);

is(Rex::Commands::Iptables::chain_exists('foo', table => 'filter'),0);
is(Rex::Commands::Iptables::chain_exists('INPUT', table => 'filter'),1);