#!/usr/bin/perl
#
# Construct an iptables rules file from fragments.
#
# Given a directory full of iptables configuration fragments, this script adds
# a standard prefix and suffix to build a complete set of iptables rules and
# then loads it into the kernel.
#
# Written by Russ Allbery <eagle@eyrie.org>
# Adapted by Digant C Kasundra <digant@stanford.edu>
# Copyright 2016-2018, 2020, 2023 Russ Allbery <eagle@eyrie.org>
# Copyright 2005-2006, 2013
#     The Board of Trustees of the Leland Stanford Junior University
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

##############################################################################
# Modules and declarations
##############################################################################

use 5.020;
use autodie;
use warnings;

use File::Basename qw(basename);
use Getopt::Long::Descriptive qw(describe_options);
use IPC::System::Simple qw(systemx);
use Perl6::Slurp qw(slurp);

# Standard prefix for iptables rules.
our $PREFIX = <<'END_OF_PREFIX';
*filter
:INPUT ACCEPT
:FORWARD ACCEPT
:OUTPUT ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -p udp -m state --state ESTABLISHED -j ACCEPT
END_OF_PREFIX

# Standard suffix for iptables rules.
our $SUFFIX = <<'END_OF_SUFFIX';
# Reject all remaining connections with port-unreachable errors.
-A INPUT -p tcp --syn -j REJECT --reject-with tcp-reset
-A INPUT --ipv4 -p udp -j REJECT --reject-with icmp-port-unreachable
-A INPUT --ipv6 -p udp -j REJECT --reject-with icmp6-port-unreachable
COMMIT
END_OF_SUFFIX

##############################################################################
# iptables manipulation
##############################################################################

# Build the iptables rules for this system.  Reads fragments from that
# directory, prepends the prefix and appends the suffix, and returns the
# result as either an array of lines or a string.
#
# Returns: Text of the file as an array of lines
sub build_iptables {
    my @rules;

    # Add the prefix and a blank line.
    push(@rules, $PREFIX, "\n");

    # Build the list of fragment paths, which is every file in
    # /etc/iptables/fragments that does not begin with a period.
    opendir(my $source, '/etc/iptables/fragments');
    my @fragments = grep { !m{ \A [.] }xms } sort readdir($source);
    closedir($source);
    @fragments = map { '/etc/iptables/fragments/' . $_ } @fragments;

    # Append the fragment contents with a blank line between them.
    for my $fragment (@fragments) {
        push(@rules, split(m{ \n }xms, slurp($fragment)), q{});
    }

    # Append the suffix and return the results.
    push(@rules, split(m{ \n }xms, $SUFFIX));
    return @rules;
}

# Write lines to a file atomically, using a separate file and then atomically
# replacing the file.  Uses $file with ".new" appended as the temporary file.
#
# $file - Output file name
# @data - List of chunks of data to put into the file
#
# Returns: undef
#  Throws: Text exception on failure to write to the file
sub write_file {
    my ($file, @data) = @_;
    open(my $new, '>', "${file}.new");
    print {$new} join("\n", @data, "\n")
      or die "$0: cannot write to ${file}.new: $!\n";
    close($new);
    rename("$file.new", $file);
    return;
}

# Write IPv4 rules to /etc/iptables/rules.  Filter out all rules with --ipv6
# so that iptables-restore doesn't complain about the unknown option.
#
# @data - List of chunks of data to put into the file
#
# Returns: undef
#  Throws: Text exception on failure to write to the file
sub write_ipv4 {
    my (@data) = @_;
    @data = grep { !m{ --ipv6 }xms } @data;
    write_file('/etc/iptables/rules', @data);
    return;
}

# Write IPv6 rules to /etc/iptables/rules6.  Filter out all rules with --ipv4
# so that ip6tables-restore doesn't complain about the unknown option.
#
# @data - List of chunks of data to put into the file
#
# Returns: undef
#  Throws: Text exception on failure to write to the file
sub write_ipv6 {
    my (@data) = @_;
    @data = grep { !m{ --ipv4 }xms } @data;
    write_file('/etc/iptables/rules6', @data);
    return;
}

# Given the array of new iptables data, install a new iptables configuration
# and load it into the kernel.
#
# @rules - New iptables data
#
# Returns: undef
#  Throws: Text exception on failure to write new data or reload it
sub install_iptables {
    my @rules = @_;
    write_ipv4(@rules);
    write_ipv6(@rules);
    systemx('iptables-restore', '/etc/iptables/rules');
    systemx('ip6tables-restore', '/etc/iptables/rules6');
    return;
}

##############################################################################
# Main routine
##############################################################################

# Always flush output.
STDOUT->autoflush;

# Clean up the script name for error reporting.
my $fullpath = $0;
local $0 = basename($0);

# Parse the argument list.
my ($opt, $usage) = describe_options(
    '%c %o',
    ['help|h'       => 'Print usage message and exit'],
    ['manual|man|m' => 'Print full manual and exit'],
    ['print|p'      => 'Print out the generated rules without updating them'],
);
if ($opt->help) {
    print {*STDOUT} $usage->text
      or die "$0: cannot write to standard output: $!\n";
    exit(0);
} elsif ($opt->manual) {
    print {*STDOUT} "Feeding myself to perldoc, please wait...\n"
      or die "$0: cannot write to standard output: $!\n";
    exec('perldoc', '-t', $fullpath);
}

# Build the iptables rules for this host.
my @rules = build_iptables();

# If told to just print out the results, do so.  Otherwise, install the new
# rules.
if ($opt->print) {
    print {*STDOUT} @rules
      or die "$0: cannot write to standard output: $!\n";
} else {
    install_iptables(@rules);
}
exit(0);
__END__

##############################################################################
# Documentation
##############################################################################

=for stopwords
Digant Kasundra iptables ip6tables rebuild-iptables Allbery TCP UDP -hmp ifup
loopback startup --ipv4 --ipv6 ICMP ip6tables-nft

=head1 NAME

rebuild-iptables - Install iptables rules from fragments

=head1 SYNOPSIS

rebuild-iptables [B<-hmp>]

=head1 DESCRIPTION

B<rebuild-iptables> constructs a combined iptables and ip6tables configuration
file by concatenating fragments found in F</etc/iptables/fragments>.  The
resulting iptables configuration file is written to F</etc/iptables/rules> and
F</etc/iptables/rules6> and loaded into the kernel.

Each module is just a text file located in the directory mentioned above that
contains one or more iptables configuration lines (basically the arguments to
an B<iptables> or B<ip6tables> invocation), blank lines, or comments (lines
starting with C<#>).  Comments and blank lines will be ignored by the system.
Use B<--ipv4> and B<--ipv6> to control which lines apply to IPv4 and IPv6.
B<rebuild-iptables> will use those flags to filter out rules that don't apply.

Along with the modules in the directory specified, a standard prefix and
suffix will be added automatically.  The prefix sets up default ACCEPT
behaviors for OUTPUT and FORWARD, and automatically accepts all loopback,
ICMP, and established UDP traffic.  The suffix rejects all unaccepted traffic
to the INPUT chain with appropriate errors for TCP and UDP, and drops all
other unaccepted traffic.

=head1 OPTIONS

=over 4

=item B<-h>, B<--help>

Print a short usage message and exit.

=item B<-m>, B<--manual>, B<--man>

Display this manual and exit.

=item B<-p>, B<--print>

Rather than installing the new rules and loading them into the kernel, just
print the combined rules to standard output and exit.  This will include all
of the comments and blank lines that would be in the rule set as stored on
disk.

=back

=head1 FILES

=over 4

=item F</etc/iptables/fragments>

Every file in this directory that does not start with C<.> is assumed to be a
set of iptables rules, and its contents are added to the generated rule set.

=item F</etc/iptables/rules>

The install location of the generated iptables rule file.  This file should be
loaded with both B<iptables-restore> and B<ip6tables-restore> on boot.  This
program does not arrange for that to happen.

=back

=head1 NOTES

There is no startup script that does quite what we want (iptables-persistent
is not quite compatible).  Standard practice when using this script is to add
an B<ifup> hook in F</etc/network/if-pre-up.d> to load the rules from
F</etc/iptables/rules> before bringing up a network interface.

=head1 AUTHORS

Russ Allbery <eagle@eyrie.org> and Digant C Kasundra.

=head1 SEE ALSO

L<iptables(8)>, L<ip6tables-legacy-restore(8)>, L<ip6tables-restore(8)>,
L<iptables-legacy-restore(8)>, L<iptables-restore(8)>

=cut
