fwbuilder, несомненно, является одним из лучших среди них.
iptables и ip6tables. Разница между этими двумя командами состоит в том, что первая работает в сети IPv4, тогда как последняя предназначена для IPv6. Поскольку оба стека сетевых протоколов, вероятно, будут использоваться на протяжении многих лет, оба средства нужно будет использовать параллельно.
filter касается правил фильтрации (прием, отказ или игнорирование пакета);
NAT касается перевода источника или назначения адресов и портов пакетов;
mangle касается других изменений IP пакетов (включая ToS — Type of Service — поля и параметры);
raw позволяет производить над пакетами другие изменения вручную прежде чем они достигнут системы отслеживания соединений.
фильтров имеет три стандартных цепи:
INPUT: касается пакетов, пунктом назначения которых является брандмауэр;
OUTPUT: касается пакетов, отправляемых брандмауэром;
FORWARD: касается транзитных пакетов, проходящих через брандмауэр (который не является ни их источником, ни их пунктом назначения).
nat также имеет три стандартных цепи:
PREROUTING: для изменения пребывающих пакетов;
POSTROUTING: для изменения отправляемых пакетов, перед отправкой;
OUTPUT: для изменения пакетов, сгенерированных брандмауэром.
-j - англ. jumps - параметр в командах) на указанное действие для продолжения обработки. Наиболее распространенные варианты поведения стандартизированы и для них существует предопределённые действия. Срабатывание одного из этих стандартных действий прерывает обработку цепи, так как судьба пакета уже предрешена (за исключением исключение упомянутых ниже):
ACCEPT: разрешить пакету следовать своим путём;
REJECT: отбросить пакет с пакетом-ошибкой ICMP (параметр --reject-with тип команды iptables позволяет указать тип ошибки);
DROP: удалить (игнорировать) пакет;
LOG: записать в журнал (посредством syslogd) сообщение с описанием пакета; учтите, что данное действие не прерывает обработку и выполнение цепочки продолжится следующим правилом, поэтому журналирование отброшенных пакетов требует и правило LOG, и правило REJECT/DROP;
ULOG: записать сообщение в журнал посредством команды ulogd, которая может быть более эффективна и адаптируема чем syslogd для обработки большого количества сообщений; заметьте, что данное действие, как и LOG, также передаёт обработку следующему правилу в вызываемой цепи;
RETURN: прервать обработку текущей цепочки и вернуться к вызвавшей цепочке; если текущая цепочка является стандартной, то вызывающей цепочки нет, поэтому выполняется действие по умолчанию (определённой опцией -P команды iptables);
SNAT (только в таблице nat): применить Source NAT (дополнительные параметры описывают точные изменения для применения);
DNAT (только в таблице nat): применить Destination NAT (дополнительные параметры описывают точные изменения для применения);
MASQUERADE (только в таблице nat): применить маскарадинг (специальный вариант Source NAT);
REDIRECT (only in the nat table): redirect a packet to a given port of the firewall itself; this can be used to set up a transparent web proxy that works with no configuration on the client side, since the client thinks it connects to the recipient whereas the communications actually go through the proxy.
mangle table, are outside the scope of this text. The iptables(8) and ip6tables(8) have a comprehensive list.
iptables and ip6tables commands allow manipulating tables, chains and rules. Their -t table option indicates which table to operate on (by default, filter).
-N chain option creates a new chain. The -X chain deletes an empty and unused chain. The -A chain rule adds a rule at the end of the given chain. The -I chain rule_num rule option inserts a rule before the rule number rule_num. The -D chain rule_num (or -D chain rule) option deletes a rule in a chain; the first syntax identifies the rule to be deleted by its number, while the latter identifies it by its contents. The -F chain option flushes a chain (deletes all its rules); if no chain is mentioned, all the rules in the table are deleted. The -L chain option lists the rules in the chain. Finally, the -P chain action option defines the default action, or “policy”, for a given chain; note that only standard chains can have such a policy.
conditions -j action action_options. If several conditions are described in the same rule, then the criterion is the conjunction (logical and) of the conditions, which is at least as restrictive as each individual condition.
-p protocol condition matches the protocol field of the IP packet. The most common values are tcp, udp, icmp, and icmpv6. Prefixing the condition with an exclamation mark negates the condition, which then becomes a match for “any packets with a different protocol than the specified one”. This negation mechanism is not specific to the -p option and it can be applied to all other conditions too.
-s address or -s network/mask condition matches the source address of the packet. Correspondingly, -d address or -d network/mask matches the destination address.
-i interface condition selects packets coming from the given network interface. -o interface selects packets going out on a specific interface.
-p tcp condition can be complemented with conditions on the TCP ports, with clauses such as --source-port port and --destination-port port.
--state state condition matches the state of a packet in a connection (this requires the ipt_conntrack kernel module, for connection tracking). The NEW state describes a packet starting a new connection; ESTABLISHED matches packets belonging to an already existing connection, and RELATED matches packets initiating a new connection related to an existing one (which is useful for the ftp-data connections in the “active” mode of the FTP protocol).
LOG имеет следующие параметры:
--log-level, со значением по умолчанию warning, указывает уровень серьёзности syslog;
--log-prefix позволяет задать текстовый префикс для различия между несколькими сообщениями журнала;
--log-tcp-sequence, --log-tcp-options and --log-ip-options indicate extra data to be integrated into the message: respectively, the TCP sequence number, TCP options, and IP options.
DNAT action provides the --to-destination address:port option to indicate the new destination IP address and/or port. Similarly, SNAT provides --to-source address:port to indicate the new source IP address and/or port.
REDIRECT action (only available if NAT is available) provides the --to-ports port(s) option to indicate the port, or port range, where the packets should be redirected.
iptables/ip6tables. Typing these commands manually can be tedious, so the calls are usually stored in a script so that the same configuration is set up automatically every time the machine boots. This script can be written by hand, but it can also be interesting to prepare it with a high-level tool such as fwbuilder.
#apt install fwbuilder
fwbuilder translate the rules according to the addresses assigned to the objects.
fwbuilder can then generate a script configuring the firewall according to the rules that have been defined. Its modular architecture gives it the ability to generate scripts targeting different systems (iptables for Linux, ipf for FreeBSD and pf for OpenBSD).
up directive of the /etc/network/interfaces file. In the following example, the script is stored under /usr/local/etc/arrakis.fw.
Пример 14.1. interfaces file calling firewall script
auto eth0
iface eth0 inet static
address 192.168.0.1
network 192.168.0.0
netmask 255.255.255.0
broadcast 192.168.0.255
up /usr/local/etc/arrakis.fw